diff --git a/CHANGELOG.md b/CHANGELOG.md index 56125be51..73eeff322 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -16,6 +16,9 @@ ### Bug Fixes +* SDK and CLI requests reject unfollowed redirects. Apps errors sanitize credentials in redirect diagnostics, including artifact upload failures. +* Account login is available through `runpod.auth.login` and `runpod.apps.auth`. `LoginError` is catchable as either `AuthenticationError` or `AppError`. CLI helpers are available under both `runpod.cli` and `runpod.rp_cli`. +* Assigning a custom `runpod.endpoint_url_base` takes precedence over the endpoint environment variable. * [BREAKING] `rp login` asks you to paste the API key shown in the console after approval. It no longer collects the key by polling the auth request, and it fails fast without an interactive terminal. * Task calls support indefinite execution with bounded interruption cleanup. Failed deletion retains the pod ID for recovery. * Network volume creation intersects catalog storage support with every sharing resource's hardware stock and datacenter constraints. Unsupported explicit pins fail before creation; existing volumes retain their authoritative IDs and datacenters. diff --git a/CONTRIBUTING.md b/CONTRIBUTING.md index af0be9cd0..3f525eda7 100644 --- a/CONTRIBUTING.md +++ b/CONTRIBUTING.md @@ -68,6 +68,22 @@ This project adheres to the [PEP 8](https://www.python.org/dev/peps/pep-0008/) c Before submitting a pull request, please make sure your changes pass all tests. New features should include additional unit tests validating the changes. +### HTTP Requests + +Use `Route` templates for paths and the shared clients in `runpod.api` for HTTP requests. Route parameters are escaped, and service bases are configured in `runpod.api.routes`. Keep a client context open across related requests to reuse its connection pool. + +```python +from runpod.api.rest import AsyncRESTClient +from runpod.api.routes import Route + +async with AsyncRESTClient() as client: + pod = await client.request(Route("GET", "/v2/pods/{pod_id}", pod_id=pod_id)) +``` + +`RESTClient` provides the synchronous equivalent. Both clients apply account authentication and bounded rate-limit waits. `HTTPClient` and `SyncHTTPClient` in `runpod.api.http` handle raw transport for GraphQL, streams, worker requests, and uploads. These raw clients require explicit authentication headers. Their `stream()` contexts expose responses for protocol-specific handling and release them on exit. A supplied session remains owned by its caller. + +Account login and credential storage belong in `runpod.auth`. CLI commands belong in `runpod.cli`. + ## Getting Help If you have any questions or need help with contributing, feel free to reach out on the [issue tracker](https://github.com/runpod/runpod-python/issues) or open a new issue. We're here to help! diff --git a/README.md b/README.md index 91c3740ad..329d234c1 100644 --- a/README.md +++ b/README.md @@ -88,9 +88,6 @@ rp flash dev main.py # live dev session: edit, re-run, logs stream back rp flash deploy # deploy production endpoints ``` -Recurring schedules are not supported by `runpod.apps`. For periodic jobs, use -an external scheduler to invoke a deployed queue function with `.spawn()`. - ## Contributing Pull requests and issues are welcome — see the [contributing guide](CONTRIBUTING.md) to get started. diff --git a/pyproject.toml b/pyproject.toml index 67b6e0aef..8cd06a61b 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -52,6 +52,7 @@ runpod = [ "serverless/binaries/gpu_test", "serverless/binaries/README.md", "py.typed", + "*.pyi", ] [tool.setuptools_scm] @@ -60,8 +61,8 @@ local_scheme = "no-local-version" [project.scripts] -runpod = "runpod.rp_cli.main:run" -rp = "runpod.rp_cli.main:run" +runpod = "runpod.cli.main:run" +rp = "runpod.cli.main:run" [dependency-groups] @@ -106,6 +107,9 @@ select = ["E4", "E7", "E9", "F", "B", "I", "UP"] # UP042 (str+Enum -> StrEnum) changes str()/format() output of public enums. ignore = ["UP042"] +[tool.ruff.lint.isort] +combine-as-imports = true + [tool.mypy] python_version = "3.11" files = ["runpod"] @@ -116,60 +120,3 @@ ignore_missing_imports = true check_untyped_defs = false warn_unused_configs = true disable_error_code = ["annotation-unchecked"] - -# Backlog: modules that do not pass yet. Remove an entry once the module is -# clean; new modules are checked from day one. -[[tool.mypy.overrides]] -module = [ - "runpod._health.fitness", - "runpod._health.gpu", - "runpod.api.ctl_commands", - "runpod.api.rest", - "runpod.apps.api", - "runpod.apps.app", - "runpod.apps.auth", - "runpod.apps.build", - "runpod.apps.context", - "runpod.apps.deploy", - "runpod.apps.dev", - "runpod.apps.discovery", - "runpod.apps.gpu", - "runpod.apps.handles", - "runpod.apps.invoker", - "runpod.apps.spec", - "runpod.apps.targets", - "runpod.apps.tasks", - "runpod.apps.utils.http", - "runpod.apps.utils.network", - "runpod.apps.volume", - "runpod.endpoint.runner", - "runpod.network_volume_transfer", - "runpod.rp_cli.api", - "runpod.rp_cli.catalog", - "runpod.rp_cli.compute", - "runpod.rp_cli.console", - "runpod.rp_cli.endpoint", - "runpod.rp_cli.endpoint_config", - "runpod.rp_cli.main", - "runpod.rp_cli.pod", - "runpod.serverless", - "runpod.serverless.modules.rp_fastapi", - "runpod.serverless.modules.rp_http", - "runpod.serverless.modules.rp_job", - "runpod.serverless.modules.rp_local", - "runpod.serverless.modules.rp_ping", - "runpod.serverless.modules.rp_prestart", - "runpod.serverless.modules.rp_progress", - "runpod.serverless.modules.rp_scale", - "runpod.serverless.modules.rp_tips", - "runpod.serverless.modules.worker_state", - "runpod.serverless.utils.rp_cleanup", - "runpod.serverless.utils.rp_debugger", - "runpod.serverless.utils.rp_download", - "runpod.serverless.utils.rp_model_cache", - "runpod.serverless.utils.rp_ssrf", - "runpod.serverless.utils.rp_validator", - "runpod.serverless.utils.rp_volume_cache", - "runpod.serverless.worker", -] -ignore_errors = true diff --git a/requirements.txt b/requirements.txt index 021f1cd68..8eec3513f 100644 --- a/requirements.txt +++ b/requirements.txt @@ -8,6 +8,7 @@ click >= 8.5.1 colorama >= 0.4.6, < 0.4.7 cryptography >= 50.0.2 fastapi[all] >= 0.162.5 +opentelemetry-api < 1.46 packaging >= 26.3 paramiko >= 5.1.0 pathspec >= 1.1.1 diff --git a/runpod/__init__.py b/runpod/__init__.py index cab68de3f..1de8cea38 100644 --- a/runpod/__init__.py +++ b/runpod/__init__.py @@ -3,7 +3,6 @@ import importlib import logging import os -from typing import TYPE_CHECKING # early serverless-worker startup gate (fitness/hardware checks). safe to # call at import time: it no-ops outside eligible worker processes and @@ -38,9 +37,9 @@ "update_endpoint_template": "runpod.api.ctl_commands", "update_user_settings": "runpod.api.ctl_commands", # config helpers - "check_credentials": "runpod.cli.groups.config.functions", - "get_credentials": "runpod.cli.groups.config.functions", - "set_credentials": "runpod.cli.groups.config.functions", + "check_credentials": "runpod.auth.credentials", + "get_credentials": "runpod.auth.credentials", + "set_credentials": "runpod.auth.credentials", # endpoint clients "AsyncioEndpoint": "runpod.endpoint", "AsyncioJob": "runpod.endpoint", @@ -75,153 +74,6 @@ "serverless": "runpod.serverless", } -# type checkers cannot see through __getattr__; mirror the lazy table so -# consumers get real definitions (tests/test_init_typing.py keeps it in sync) -if TYPE_CHECKING: - from runpod import ( - serverless as serverless, - ) - from runpod._logger import ( - RunPodLogger as RunPodLogger, - ) - from runpod.api.ctl_commands import ( - create_container_registry_auth as create_container_registry_auth, - ) - from runpod.api.ctl_commands import ( - create_endpoint as create_endpoint, - ) - from runpod.api.ctl_commands import ( - create_pod as create_pod, - ) - from runpod.api.ctl_commands import ( - create_template as create_template, - ) - from runpod.api.ctl_commands import ( - delete_container_registry_auth as delete_container_registry_auth, - ) - from runpod.api.ctl_commands import ( - get_endpoints as get_endpoints, - ) - from runpod.api.ctl_commands import ( - get_gpu as get_gpu, - ) - from runpod.api.ctl_commands import ( - get_gpus as get_gpus, - ) - from runpod.api.ctl_commands import ( - get_pod as get_pod, - ) - from runpod.api.ctl_commands import ( - get_pods as get_pods, - ) - from runpod.api.ctl_commands import ( - get_user as get_user, - ) - from runpod.api.ctl_commands import ( - resume_pod as resume_pod, - ) - from runpod.api.ctl_commands import ( - stop_pod as stop_pod, - ) - from runpod.api.ctl_commands import ( - terminate_pod as terminate_pod, - ) - from runpod.api.ctl_commands import ( - update_container_registry_auth as update_container_registry_auth, - ) - from runpod.api.ctl_commands import ( - update_endpoint_template as update_endpoint_template, - ) - from runpod.api.ctl_commands import ( - update_user_settings as update_user_settings, - ) - from runpod.apps import ( - Api as Api, - ) - from runpod.apps import ( - App as App, - ) - from runpod.apps import ( - DataCenter as DataCenter, - ) - from runpod.apps import ( - EndpointNotFound as EndpointNotFound, - ) - from runpod.apps import ( - GlobalVolume as GlobalVolume, - ) - from runpod.apps import ( - Job as Job, - ) - from runpod.apps import ( - Model as Model, - ) - from runpod.apps import ( - NetworkVolume as NetworkVolume, - ) - from runpod.apps import ( - Queue as Queue, - ) - from runpod.apps import ( - Secret as Secret, - ) - from runpod.apps import ( - Task as Task, - ) - from runpod.apps import ( - Volume as Volume, - ) - from runpod.apps import ( - is_local as is_local, - ) - from runpod.apps import ( - local_entrypoint as local_entrypoint, - ) - from runpod.apps.gpu import ( - CpuInstanceType as CpuInstanceType, - ) - from runpod.apps.gpu import ( - GpuGroup as GpuGroup, - ) - from runpod.apps.gpu import ( - GpuType as GpuType, - ) - from runpod.apps.markers import ( - delete as delete, - ) - from runpod.apps.markers import ( - get as get, - ) - from runpod.apps.markers import ( - init as init, - ) - from runpod.apps.markers import ( - patch as patch, - ) - from runpod.apps.markers import ( - post as post, - ) - from runpod.apps.markers import ( - put as put, - ) - from runpod.cli.groups.config.functions import ( - check_credentials as check_credentials, - ) - from runpod.cli.groups.config.functions import ( - get_credentials as get_credentials, - ) - from runpod.cli.groups.config.functions import ( - set_credentials as set_credentials, - ) - from runpod.endpoint import ( - AsyncioEndpoint as AsyncioEndpoint, - ) - from runpod.endpoint import ( - AsyncioJob as AsyncioJob, - ) - from runpod.endpoint import ( - Endpoint as Endpoint, - ) # lazy names resolve through __getattr__, so __all__ derives from the # lazy table plus the eagerly-defined module attributes @@ -248,22 +100,10 @@ def _selected_profile() -> str: def _load_api_key(): - """resolve the api key from the environment, then stored credentials. + """resolve the api key from the environment or selected profile.""" + from .auth import load_api_key - the credential lookup is deferred (and tolerant of a missing cli - dependency closure) so a bare `import runpod` never drags in the - config/cli modules; the deployed worker gets its key from the env. - """ - key = os.environ.get("RUNPOD_API_KEY") - if key: - return key - try: - creds = importlib.import_module( - "runpod.cli.groups.config.functions" - ).get_credentials(profile) - except Exception: # noqa: BLE001 - no stored key is a valid state - return None - return creds.get("api_key") if creds else None + return load_api_key(profile) def __getattr__(name): @@ -291,6 +131,7 @@ def __getattr__(name): endpoint_url_base = os.environ.get( "RUNPOD_ENDPOINT_BASE_URL", "https://api.runpod.ai/v2" ) # pylint: disable=invalid-name +_initial_endpoint_url_base = endpoint_url_base # --------------------------- Force Logging Levels --------------------------- # diff --git a/runpod/__init__.pyi b/runpod/__init__.pyi new file mode 100644 index 000000000..b7387e7fd --- /dev/null +++ b/runpod/__init__.pyi @@ -0,0 +1,77 @@ +from runpod import ( + serverless as serverless, +) +from runpod._logger import ( + RunPodLogger as RunPodLogger, +) +from runpod.api.ctl_commands import ( + create_container_registry_auth as create_container_registry_auth, + create_endpoint as create_endpoint, + create_pod as create_pod, + create_template as create_template, + delete_container_registry_auth as delete_container_registry_auth, + get_endpoints as get_endpoints, + get_gpu as get_gpu, + get_gpus as get_gpus, + get_pod as get_pod, + get_pods as get_pods, + get_user as get_user, + resume_pod as resume_pod, + stop_pod as stop_pod, + terminate_pod as terminate_pod, + update_container_registry_auth as update_container_registry_auth, + update_endpoint_template as update_endpoint_template, + update_user_settings as update_user_settings, +) +from runpod.apps import ( + Api as Api, + App as App, + DataCenter as DataCenter, + EndpointNotFound as EndpointNotFound, + GlobalVolume as GlobalVolume, + Job as Job, + Model as Model, + NetworkVolume as NetworkVolume, + Queue as Queue, + Secret as Secret, + Task as Task, + Volume as Volume, + is_local as is_local, + local_entrypoint as local_entrypoint, +) +from runpod.apps.gpu import ( + CpuInstanceType as CpuInstanceType, + GpuGroup as GpuGroup, + GpuType as GpuType, +) +from runpod.apps.markers import ( + delete as delete, + get as get, + init as init, + patch as patch, + post as post, + put as put, +) +from runpod.auth.credentials import ( + check_credentials as check_credentials, + get_credentials as get_credentials, + set_credentials as set_credentials, +) +from runpod.endpoint import ( + AsyncioEndpoint as AsyncioEndpoint, + AsyncioJob as AsyncioJob, + Endpoint as Endpoint, +) +from runpod.version import __version__ as __version__ + +_LAZY_ATTRS: dict[str, str] +__all__: list[str] +DEFAULT_PROFILE: str +SSH_KEY_PATH: str +profile: str +api_key: str | None +endpoint_url_base: str +_initial_endpoint_url_base: str + +def _selected_profile() -> str: ... +def _load_api_key() -> str | None: ... diff --git a/runpod/_health/fitness.py b/runpod/_health/fitness.py index 44291d1b6..053c9a90f 100644 --- a/runpod/_health/fitness.py +++ b/runpod/_health/fitness.py @@ -18,6 +18,7 @@ import time import traceback from collections.abc import Callable +from typing import Literal, TypedDict from runpod._logger import RunPodLogger @@ -110,6 +111,17 @@ def _env_flag(name: str) -> bool: return os.environ.get(name, "").strip().lower() in ("1", "true", "yes", "on") +class _FitnessCheckMetadata(TypedDict, total=False): + _runpod_defer_to_worker_start: bool + _runpod_recheck_at_worker_start: bool + _runpod_builtin: Literal["gpu_check", "system_checks"] + + +def _mark_check(func: Callable, metadata: _FitnessCheckMetadata) -> None: + for name, value in metadata.items(): + setattr(func, name, value) + + def defer_to_worker_start(func: Callable) -> Callable: """ Mark a check as unsafe to run at import. @@ -119,7 +131,7 @@ def defer_to_worker_start(func: Callable) -> Callable: handler module runs would leave a CUDA context in a process the handler may later fork (vLLM, DeepSpeed), which CUDA does not support. """ - func._runpod_defer_to_worker_start = True + _mark_check(func, {"_runpod_defer_to_worker_start": True}) return func @@ -129,7 +141,7 @@ def _is_deferred(func: Callable) -> bool: def recheck_at_worker_start(func: Callable) -> Callable: """Run a built-in check again after handler initialization.""" - func._runpod_recheck_at_worker_start = True + _mark_check(func, {"_runpod_recheck_at_worker_start": True}) return func @@ -260,7 +272,7 @@ def _ensure_gpu_check_registered() -> None: before = len(_fitness_checks) auto_register_gpu_check() for check in _fitness_checks[before:]: - check._runpod_builtin = "gpu_check" + _mark_check(check, {"_runpod_builtin": "gpu_check"}) _registration_state["gpu_check"] = True @@ -288,7 +300,7 @@ def _ensure_system_checks_registered() -> None: before = len(_fitness_checks) auto_register_system_checks() for check in _fitness_checks[before:]: - check._runpod_builtin = "system_checks" + _mark_check(check, {"_runpod_builtin": "system_checks"}) _registration_state["system_checks"] = True diff --git a/runpod/_health/gpu.py b/runpod/_health/gpu.py index 5ea9d7060..e079c89a9 100644 --- a/runpod/_health/gpu.py +++ b/runpod/_health/gpu.py @@ -14,7 +14,7 @@ import os import subprocess from pathlib import Path -from typing import Any +from typing import TypedDict from runpod._binary_helpers import get_binary_path from runpod._logger import RunPodLogger @@ -53,7 +53,15 @@ def _get_gpu_test_binary_path() -> Path | None: return get_binary_path("gpu_test") -def _parse_gpu_test_output(output: str) -> dict[str, Any]: +class _GpuTestResult(TypedDict): + success: bool + gpu_count: int + found_gpus: int + errors: list[str] + details: dict[str, str] + + +def _parse_gpu_test_output(output: str) -> _GpuTestResult: """ Parse gpu_test binary output and detect success/failure. @@ -75,7 +83,7 @@ def _parse_gpu_test_output(output: str) -> dict[str, Any]: """ lines = output.strip().split("\n") - result = { + result: _GpuTestResult = { "success": False, "gpu_count": 0, "found_gpus": 0, @@ -121,7 +129,7 @@ def _parse_gpu_test_output(output: str) -> dict[str, Any]: return result -async def _run_gpu_test_binary() -> dict[str, Any]: +async def _run_gpu_test_binary() -> _GpuTestResult: """ Execute gpu_test binary and parse output. @@ -256,7 +264,7 @@ async def _check_gpu_health() -> None: RuntimeError: If GPU health check fails """ binary_attempted = False - binary_error = None + binary_error: Exception | None = None # Try binary first try: diff --git a/runpod/_hosts.py b/runpod/_hosts.py index f5e792b81..38d993cca 100644 --- a/runpod/_hosts.py +++ b/runpod/_hosts.py @@ -7,10 +7,12 @@ RUNPOD_CONSOLE_URL web console base URL (default https://console.runpod.io) RUNPOD_PROXY_DOMAIN pod HTTP proxy domain (default proxy.runpod.net) RUNPOD_ENDPOINT_BASE_URL serverless base URL (default https://api.runpod.ai/v2) + RUNPOD_API_BASE_URL control-plane base URL (default https://api.runpod.io) + RUNPOD_HAPI_URL host API base URL (default https://hapi.runpod.net) -The endpoint domain is the host of ``RUNPOD_ENDPOINT_BASE_URL``. When that is -unset or blank, a non-blank ``runpod.endpoint_url_base`` set programmatically -is used instead. +The endpoint domain is the host of the serverless base URL. A non-blank +``runpod.endpoint_url_base`` assigned a value different from its import-time +value takes precedence over ``RUNPOD_ENDPOINT_BASE_URL``. Example: >>> proxy_url("abc123", 8080) @@ -22,6 +24,8 @@ DEFAULT_CONSOLE_URL = "https://console.runpod.io" DEFAULT_PROXY_DOMAIN = "proxy.runpod.net" DEFAULT_ENDPOINT_BASE_URL = "https://api.runpod.ai/v2" +DEFAULT_API_BASE_URL = "https://api.runpod.io" +DEFAULT_HOST_API_URL = "https://hapi.runpod.net" def _env(name: str, default: str) -> str: @@ -34,6 +38,28 @@ def console_url() -> str: return _env("RUNPOD_CONSOLE_URL", DEFAULT_CONSOLE_URL).rstrip("/") +def api_base_url() -> str: + """control-plane API base URL.""" + return _env("RUNPOD_API_BASE_URL", DEFAULT_API_BASE_URL).rstrip("/") + + +def host_api_base_url() -> str: + """host API base URL for pod log snapshots.""" + return _env("RUNPOD_HAPI_URL", DEFAULT_HOST_API_URL).rstrip("/") + + +def endpoint_base_url() -> str: + """serverless API base URL with environment and module overrides.""" + import runpod + + module_base = (runpod.endpoint_url_base or "").strip() + if module_base and runpod.endpoint_url_base != runpod._initial_endpoint_url_base: + return module_base.rstrip("/") + return _env( + "RUNPOD_ENDPOINT_BASE_URL", module_base or DEFAULT_ENDPOINT_BASE_URL + ).rstrip("/") + + def proxy_url(pod_id: str, port: int | str) -> str: """Public HTTP proxy URL for ``port`` on ``pod_id``.""" domain = _env("RUNPOD_PROXY_DOMAIN", DEFAULT_PROXY_DOMAIN).strip("/") @@ -45,9 +71,6 @@ def endpoint_domain() -> str: Load-balanced endpoints are served on ``.``. """ - import runpod - - module_base = (runpod.endpoint_url_base or "").strip() - base = _env("RUNPOD_ENDPOINT_BASE_URL", module_base or DEFAULT_ENDPOINT_BASE_URL) + base = endpoint_base_url() host = base.split("://", 1)[-1] return host.split("/", 1)[0] diff --git a/runpod/api/ctl_commands.py b/runpod/api/ctl_commands.py index c093b36bf..86f15a117 100644 --- a/runpod/api/ctl_commands.py +++ b/runpod/api/ctl_commands.py @@ -23,6 +23,7 @@ def _path_segment(value: str) -> str: def _split_values(value: Iterable[Any] | str | None) -> list[str]: if value is None: return [] + values: Iterable[object] if isinstance(value, str): values = value.split(",") else: @@ -34,6 +35,12 @@ def _environment(env: dict | None) -> dict[str, str]: return {str(key): str(value) for key, value in (env or {}).items()} +def _require_record(response: dict[str, Any] | None) -> dict[str, Any]: + if not isinstance(response, dict): + raise error.QueryError("expected a JSON object response") + return response + + def _cpu_config(instance_id: str | None) -> dict[str, Any]: if not instance_id: raise ValueError("instance_id must be provided for CPU pods") @@ -72,21 +79,23 @@ def get_gpus( response = run_rest_request( "GET", "/v2/catalog/gpus", api_key=api_key, user_agent=user_agent ) - return response["gpus"] + return _require_record(response)["gpus"] def get_gpu(gpu_id: str, gpu_quantity: int = 1, api_key: str | None = None) -> dict: """Get a GPU type and its pod availability.""" try: - return run_rest_request( - "GET", - f"/v2/catalog/gpus/{_path_segment(gpu_id)}", - api_key=api_key, - params={ - "include": "AVAILABILITY", - "product": "POD", - "count": gpu_quantity, - }, + return _require_record( + run_rest_request( + "GET", + f"/v2/catalog/gpus/{_path_segment(gpu_id)}", + api_key=api_key, + params={ + "include": "AVAILABILITY", + "product": "POD", + "count": gpu_quantity, + }, + ) ) except error.QueryError as exc: if exc.status_code == HTTP_STATUS_NOT_FOUND: @@ -100,7 +109,7 @@ def get_gpu(gpu_id: str, gpu_quantity: int = 1, api_key: str | None = None) -> d def get_pods(api_key: str | None = None) -> list[dict]: """Get all standalone pods.""" response = run_rest_request("GET", "/v2/pods", api_key=api_key) - return response["pods"] + return _require_record(response)["pods"] def get_pod(pod_id: str, api_key: str | None = None) -> dict | None: @@ -199,7 +208,7 @@ def create_pod( template = run_rest_request( "GET", f"/v2/templates/{_path_segment(template_id)}" ) - persistent = template.get("mounts", {}).get("persistent") + persistent = _require_record(template).get("mounts", {}).get("persistent") if persistent is not None: body["mounts"] = { "persistent": {"size": persistent["size"], "path": volume_mount_path} @@ -217,15 +226,17 @@ def create_pod( else: body["cpu"] = _cpu_config(instance_id) - return run_rest_request("POST", "/v2/pods", json=body) + return _require_record(run_rest_request("POST", "/v2/pods", json=body)) def stop_pod(pod_id: str) -> dict: """Stop a pod.""" - return run_rest_request( - "POST", - f"/v2/pods/{_path_segment(pod_id)}/action", - json={"action": "stop"}, + return _require_record( + run_rest_request( + "POST", + f"/v2/pods/{_path_segment(pod_id)}/action", + json={"action": "stop"}, + ) ) @@ -233,10 +244,12 @@ def resume_pod(pod_id: str, gpu_count: int | None = None) -> dict: """Start a stopped pod without changing its GPU allocation.""" if gpu_count is not None: raise ValueError("REST API v2 does not support gpu_count when resuming a pod") - return run_rest_request( - "POST", - f"/v2/pods/{_path_segment(pod_id)}/action", - json={"action": "start"}, + return _require_record( + run_rest_request( + "POST", + f"/v2/pods/{_path_segment(pod_id)}/action", + json={"action": "start"}, + ) ) @@ -248,14 +261,14 @@ def terminate_pod(pod_id: str) -> None: def create_template( name: str, image_name: str, - docker_start_cmd: str = None, + docker_start_cmd: str | None = None, container_disk_in_gb: int = 10, - volume_in_gb: int = None, - volume_mount_path: str = None, - ports: str = None, - env: dict = None, + volume_in_gb: int | None = None, + volume_mount_path: str | None = None, + ports: str | None = None, + env: dict | None = None, is_serverless: bool = False, - registry_auth_id: str = None, + registry_auth_id: str | None = None, ) -> dict: """Create a pod or serverless template.""" body: dict[str, Any] = { @@ -280,28 +293,28 @@ def create_template( if registry_auth_id is not None: body["registry"] = registry_auth_id - return run_rest_request("POST", "/v2/templates", json=body) + return _require_record(run_rest_request("POST", "/v2/templates", json=body)) def get_endpoints() -> list[dict]: """Get all serverless endpoints.""" response = run_rest_request("GET", "/v2/serverless") - return response["endpoints"] + return _require_record(response)["endpoints"] def create_endpoint( name: str, template_id: str, gpu_ids: str = "AMPERE_16", - network_volume_id: str = None, - locations: str = None, + network_volume_id: str | None = None, + locations: str | None = None, idle_timeout: int | None = None, scaler_type: str = "QUEUE_DELAY", scaler_value: int = 4, workers_min: int = 0, workers_max: int = 3, flashboot=False, - allowed_cuda_versions: str = None, + allowed_cuda_versions: str | None = None, gpu_count: int = 1, ) -> dict: """Create a queue-based serverless endpoint; locations are datacenter IDs.""" @@ -351,24 +364,28 @@ def create_endpoint( if locations: body["dataCenterIds"] = _split_values(locations) - return run_rest_request("POST", "/v2/serverless", json=body) + return _require_record(run_rest_request("POST", "/v2/serverless", json=body)) def update_endpoint_template(endpoint_id: str, template_id: str) -> dict: """Apply a serverless template to an endpoint.""" - return run_rest_request( - "PATCH", - f"/v2/serverless/{_path_segment(endpoint_id)}", - json={"templateId": template_id}, + return _require_record( + run_rest_request( + "PATCH", + f"/v2/serverless/{_path_segment(endpoint_id)}", + json={"templateId": template_id}, + ) ) def create_container_registry_auth(name: str, username: str, password: str) -> dict: """Create a container registry credential.""" - return run_rest_request( - "POST", - "/v2/registries", - json={"name": name, "username": username, "password": password}, + return _require_record( + run_rest_request( + "POST", + "/v2/registries", + json={"name": name, "username": username, "password": password}, + ) ) diff --git a/runpod/api/graphql.py b/runpod/api/graphql.py index 7119b09e0..c385c0850 100644 --- a/runpod/api/graphql.py +++ b/runpod/api/graphql.py @@ -3,29 +3,16 @@ """ import json -import os from typing import Any -import requests - from runpod import error +from runpod.auth import resolve_api_key as _resolve_api_key from runpod.user_agent import USER_AGENT -HTTP_STATUS_UNAUTHORIZED = 401 - - -def _graphql_url() -> str: - api_url_base = os.environ.get("RUNPOD_API_BASE_URL", "https://api.runpod.io") - return f"{api_url_base}/graphql" - +from .http import HTTPClient, SyncHTTPClient +from .routes import Route -def _resolve_api_key(api_key: str | None) -> str: - from runpod import api_key as global_api_key # pylint: disable=import-outside-toplevel, cyclic-import - - effective_api_key = api_key or global_api_key - if not effective_api_key: - raise error.AuthenticationError("No API key provided") - return effective_api_key +HTTP_STATUS_UNAUTHORIZED = 401 def _build_headers(api_key: str | None) -> dict[str, str]: @@ -66,19 +53,21 @@ def run_graphql_query( """ effective_api_key = _resolve_api_key(api_key) - response = requests.post( - _graphql_url(), + with SyncHTTPClient().stream( + Route("POST", "/graphql"), headers=_build_headers(effective_api_key), data=json.dumps(_build_payload(query, variables)), timeout=30, - ) - - if response.status_code == HTTP_STATUS_UNAUTHORIZED: - raise error.AuthenticationError( - "Unauthorized request, please check your API key." - ) - - return _check_response(response.json(), query) + ) as response: + if 300 <= response.status_code < 400: + raise error.QueryError( + "unexpected redirect", status_code=response.status_code + ) + if response.status_code == HTTP_STATUS_UNAUTHORIZED: + raise error.AuthenticationError( + "Unauthorized request, please check your API key." + ) + return _check_response(response.json(), query) async def run_graphql_query_async( @@ -102,21 +91,20 @@ async def run_graphql_query_async( is available. Login creates its auth request this way so a stale stored key cannot fail the request. """ - import aiohttp # pylint: disable=import-outside-toplevel - effective_api_key = None if anonymous else _resolve_api_key(api_key) - client_timeout = aiohttp.ClientTimeout(total=timeout) - async with aiohttp.ClientSession(timeout=client_timeout) as session: - async with session.post( - _graphql_url(), - headers={**_build_headers(effective_api_key), **(headers or {})}, - json=_build_payload(query, variables), - ) as response: - if response.status == HTTP_STATUS_UNAUTHORIZED: - raise error.AuthenticationError( - "Unauthorized request, please check your API key." - ) - response_json = await response.json() + async with HTTPClient().stream( + Route("POST", "/graphql"), + headers={**_build_headers(effective_api_key), **(headers or {})}, + json=_build_payload(query, variables), + timeout=timeout, + ) as response: + if 300 <= response.status < 400: + raise error.QueryError("unexpected redirect", status_code=response.status) + if response.status == HTTP_STATUS_UNAUTHORIZED: + raise error.AuthenticationError( + "Unauthorized request, please check your API key." + ) + response_json = await response.json() return _check_response(response_json, query) diff --git a/runpod/api/http.py b/runpod/api/http.py new file mode 100644 index 000000000..ba78c02c9 --- /dev/null +++ b/runpod/api/http.py @@ -0,0 +1,156 @@ +"""shared HTTP sessions, request lifetimes, and response decoding.""" + +from collections.abc import Mapping +from contextlib import asynccontextmanager, contextmanager + +import aiohttp +import requests +from yarl import URL + +from runpod.user_agent import USER_AGENT + +from .routes import Route, api_base_url + + +async def _without_disconnect_replay(request, handler): + try: + return await handler(request) + except aiohttp.ClientConnectorError: + raise + except (aiohttp.ClientOSError, aiohttp.ServerDisconnectedError) as exc: + raise aiohttp.ClientConnectionError(str(exc)) from exc + + +class _AsyncHTTPTransport: + """an async transport with an explicitly scoped connection pool.""" + + def __init__( + self, + base_url: str | None = None, + *, + headers: Mapping[str, str] | None = None, + session: aiohttp.ClientSession | None = None, + ): + self.base_url = api_base_url() if base_url is None else base_url + self.headers = {"User-Agent": USER_AGENT} if session is None else {} + self.headers.update(headers or {}) + self.session = session + self._owns_session = session is None + + async def __aenter__(self): + if self.session is None: + self.session = aiohttp.ClientSession(cookie_jar=aiohttp.DummyCookieJar()) + elif self.session.closed: + raise RuntimeError("the supplied HTTP session is closed") + return self + + async def __aexit__(self, *args): + await self.close() + + async def close(self): + if self._owns_session and self.session is not None: + session, self.session = self.session, None + await session.close() + + @asynccontextmanager + async def stream(self, route: Route, *, timeout=30, headers=None, **kwargs): + if self.session is None: + async with _AsyncHTTPTransport( + self.base_url, headers=self.headers + ) as client: + async with client.stream( + route, timeout=timeout, headers=headers, **kwargs + ) as response: + yield response + return + if route.method in {"PUT", "DELETE"}: + middlewares = kwargs.get("middlewares") + if middlewares is None: + middlewares = self.session._middlewares + kwargs["middlewares"] = (*middlewares, _without_disconnect_replay) + if not isinstance(timeout, aiohttp.ClientTimeout): + timeout = aiohttp.ClientTimeout(total=timeout) + kwargs.setdefault("allow_redirects", False) + async with self.session.request( + route.method, + URL(route.url(self.base_url), encoded=True), + headers={**self.headers, **(headers or {})}, + timeout=timeout, + **kwargs, + ) as response: + yield response + + +class HTTPClient(_AsyncHTTPTransport): + """an async transport with JSON and text response decoding.""" + + async def request(self, route: Route, *, response_type="json", **kwargs): + if response_type not in {"json", "text"}: + raise ValueError("response_type must be json or text") + async with self.stream(route, **kwargs) as response: + response.raise_for_status() + if 300 <= response.status < 400: + raise aiohttp.ClientResponseError( + response.request_info, + response.history, + status=response.status, + message="unexpected redirect", + headers=response.headers, + ) + if response_type == "text": + return await response.text() + if response.status == 204 or not await response.read(): + return None + return await response.json(content_type=None) + + +class SyncHTTPClient: + """a synchronous transport with the same routes and ownership rules.""" + + def __init__( + self, + base_url: str | None = None, + *, + headers: Mapping[str, str] | None = None, + session: requests.Session | None = None, + ): + self.base_url = api_base_url() if base_url is None else base_url + self.headers = {"User-Agent": USER_AGENT} if session is None else {} + self.headers.update(headers or {}) + self.session = session + self._owns_session = session is None + + def __enter__(self): + if self.session is None: + self.session = requests.Session() + return self + + def __exit__(self, *args): + self.close() + + def close(self): + if self._owns_session and self.session is not None: + session, self.session = self.session, None + session.close() + + @contextmanager + def stream(self, route: Route, *, timeout=30, headers=None, **kwargs): + if self.session is None: + with SyncHTTPClient(self.base_url, headers=self.headers) as client: + with client.stream( + route, timeout=timeout, headers=headers, **kwargs + ) as response: + yield response + return + kwargs.setdefault("allow_redirects", False) + response = self.session.request( + route.method, + route.url(self.base_url), + headers={**self.headers, **(headers or {})}, + timeout=timeout, + **kwargs, + ) + try: + yield response + finally: + response.close() diff --git a/runpod/api/mutations/apps.py b/runpod/api/mutations/apps.py index 1b549580e..5f1a3da5e 100644 --- a/runpod/api/mutations/apps.py +++ b/runpod/api/mutations/apps.py @@ -66,16 +66,6 @@ } """ -MUTATION_CREATE_FLASH_AUTH_REQUEST = """ -mutation createFlashAuthRequest { - createFlashAuthRequest { - id - status - expiresAt - } -} -""" - MUTATION_PREPARE_ARTIFACT_UPLOAD = """ mutation PrepareArtifactUpload($input: PrepareFlashArtifactUploadInput!) { prepareFlashArtifactUpload(input: $input) { diff --git a/runpod/api/queries/apps.py b/runpod/api/queries/apps.py index 0d8b63cbc..257674fa7 100644 --- a/runpod/api/queries/apps.py +++ b/runpod/api/queries/apps.py @@ -86,13 +86,3 @@ } } """ - -# no apiKey: the console shows the key only to the approver. -QUERY_FLASH_AUTH_REQUEST_STATUS = """ -query flashAuthRequestStatus($flashAuthRequestId: String!) { - flashAuthRequestStatus(flashAuthRequestId: $flashAuthRequestId) { - id - status - } -} -""" diff --git a/runpod/api/rest.py b/runpod/api/rest.py index d6f0e3b3c..8698a6228 100644 --- a/runpod/api/rest.py +++ b/runpod/api/rest.py @@ -2,20 +2,20 @@ import asyncio import json as json_module -import os import time from collections.abc import Mapping from concurrent.futures import Future -from contextlib import nullcontext from typing import Any import aiohttp -import requests from runpod import error +from runpod.auth import resolve_api_key as _resolve_api_key from runpod.user_agent import USER_AGENT from ._rate_limit import _RetryBudget, _validate_retry_options, rate_limits +from .http import HTTPClient, SyncHTTPClient, _AsyncHTTPTransport +from .routes import Route HTTP_STATUS_NO_CONTENT = 204 HTTP_STATUS_BAD_REQUEST = 400 @@ -23,20 +23,8 @@ HTTP_STATUS_NOT_FOUND = 404 -def _resolve_api_key(api_key: str | None) -> str: - from runpod import ( # pylint: disable=import-outside-toplevel,cyclic-import - api_key as global_api_key, - ) - - effective_api_key = api_key or global_api_key - if not effective_api_key: - raise error.AuthenticationError("No API key provided") - return effective_api_key - - def _build_url(path: str) -> str: - api_url_base = os.environ.get("RUNPOD_API_BASE_URL", "https://api.runpod.io") - return f"{api_url_base.rstrip('/')}/{path.lstrip('/')}" + return Route("GET", path).url() def _build_headers(api_key: str) -> dict[str, str]: @@ -55,6 +43,8 @@ def _raise_for_error( text: str = "", retry_after: float | None = None, ) -> None: + if 300 <= status_code < 400: + raise error.QueryError("unexpected redirect", status_code=status_code) if status_code == HTTP_STATUS_UNAUTHORIZED: raise error.AuthenticationError( "Unauthorized request, please check your API key." @@ -89,108 +79,121 @@ def _raise_for_error( ) -def run_rest_request( - method: str, - path: str, - *, - api_key: str | None = None, - params: Mapping[str, Any] | None = None, - json: Mapping[str, Any] | None = None, - timeout: float = 30, - max_retries: int = 3, - max_rate_limit_wait: float = 60, - user_agent: str = USER_AGENT, -) -> dict[str, Any] | None: - """Send a REST request with bounded 429 retries and shared quota waits. - - ``timeout`` applies to each HTTP attempt. ``max_rate_limit_wait`` bounds - cumulative quota sleeps in seconds; ``max_retries`` counts 429 retries. - Network failures and other HTTP errors are not retried. - """ - _validate_retry_options(max_retries, max_rate_limit_wait) - key = _resolve_api_key(api_key) - url = _build_url(path) - headers = _build_headers(key) - headers["User-Agent"] = user_agent - budget = _RetryBudget(max_retries, max_rate_limit_wait, f"{method.upper()} {path}") - with rate_limits.bucket(url, key) as bucket: - for attempt in range(max_retries + 1): - while wait := bucket.acquire(budget): - if isinstance(wait, Future): - wait.result() - else: - time.sleep(wait) - try: - started_at = time.monotonic() - response = requests.request( - method, - url, - headers=headers, - params=params, - json=json, - timeout=timeout, - ) +class RESTClient(SyncHTTPClient): + """reusable synchronous REST requests with shared quota handling.""" + + def __init__(self, api_key=None, *, base_url=None, session=None): + super().__init__(base_url, session=session) + self.api_key = api_key + + def request( + self, + route: Route, + *, + api_key: str | None = None, + params: Mapping[str, Any] | None = None, + json: Mapping[str, Any] | None = None, + timeout: float = 30, + max_retries: int = 3, + max_rate_limit_wait: float = 60, + user_agent: str = USER_AGENT, + ) -> dict[str, Any] | None: + """Send a REST request with bounded 429 retries and shared quota waits. + + ``timeout`` applies to each HTTP attempt. ``max_rate_limit_wait`` bounds + cumulative quota sleeps in seconds; ``max_retries`` counts 429 retries. + Network failures and other HTTP errors are not retried. + """ + method, path = route.method, route.resolved_path + _validate_retry_options(max_retries, max_rate_limit_wait) + key = _resolve_api_key(api_key or self.api_key) + url = route.url(self.base_url) + headers = _build_headers(key) + headers["User-Agent"] = user_agent + budget = _RetryBudget( + max_retries, max_rate_limit_wait, f"{method.upper()} {path}" + ) + with rate_limits.bucket(url, key) as bucket: + attempt = 0 + while True: + while wait := bucket.acquire(budget): + if isinstance(wait, Future): + wait.result() + else: + time.sleep(wait) try: - retry_after = bucket.update( - response.status_code, - response.headers, - attempt, - started_at=started_at, - ) - if budget.can_retry(attempt, retry_after): - continue - if response.status_code >= HTTP_STATUS_BAD_REQUEST: - _raise_for_error( + started_at = time.monotonic() + with self.stream( + route, + headers=headers, + params=params, + json=json, + timeout=timeout, + ) as response: + retry_after = bucket.update( response.status_code, - method, - path, - response.text, - retry_after, + response.headers, + attempt, + started_at=started_at, ) - if ( - response.status_code == HTTP_STATUS_NO_CONTENT - or not response.content - ): - return None - return response.json() + if budget.can_retry(attempt, retry_after): + attempt += 1 + continue + if response.status_code >= 300: + _raise_for_error( + response.status_code, + method, + path, + response.text, + retry_after, + ) + if ( + response.status_code == HTTP_STATUS_NO_CONTENT + or not response.content + ): + return None + return response.json() finally: - response.close() - finally: - bucket.release() + bucket.release() -async def run_rest_request_async( - method: str, - path: str, - *, - api_key: str | None = None, - params: Mapping[str, Any] | None = None, - json: Mapping[str, Any] | None = None, - timeout: float = 30, - max_retries: int = 3, - max_rate_limit_wait: float = 60, - session: aiohttp.ClientSession | None = None, - user_agent: str = USER_AGENT, -) -> dict[str, Any] | None: - """Send a REST request with cancellable quota waits and bounded 429 retries. - - ``timeout`` applies to each HTTP attempt. ``max_rate_limit_wait`` bounds - cumulative quota sleeps in seconds; ``max_retries`` counts 429 retries. - Network failures and other HTTP errors are not retried. - """ - _validate_retry_options(max_retries, max_rate_limit_wait) - key = _resolve_api_key(api_key) - url = _build_url(path) - headers = _build_headers(key) - headers["User-Agent"] = user_agent - budget = _RetryBudget(max_retries, max_rate_limit_wait, f"{method.upper()} {path}") - client_timeout = aiohttp.ClientTimeout(total=timeout) - context = nullcontext(session) if session is not None else aiohttp.ClientSession() - async with context as session: - # aiohttp otherwise replays put/delete requests after an ambiguous disconnect. - session._retry_connection = False # pylint: disable=protected-access +class AsyncRESTClient(_AsyncHTTPTransport): + """reusable async REST requests with cancellable quota handling.""" + + def __init__(self, api_key=None, *, base_url=None, session=None): + super().__init__(base_url, session=session) + self.api_key = api_key + + async def request( + self, + route: Route, + *, + api_key: str | None = None, + params: Mapping[str, Any] | None = None, + json: Mapping[str, Any] | None = None, + timeout: float = 30, + max_retries: int = 3, + max_rate_limit_wait: float = 60, + user_agent: str = USER_AGENT, + ) -> dict[str, Any] | None: + """Send a REST request with cancellable quota waits and bounded 429 retries. + + ``timeout`` applies to each HTTP attempt. ``max_rate_limit_wait`` bounds + cumulative quota sleeps in seconds; ``max_retries`` counts 429 retries. + Network failures and other HTTP errors are not retried. + """ + method, path = route.method, route.resolved_path + _validate_retry_options(max_retries, max_rate_limit_wait) + key = _resolve_api_key(api_key or self.api_key) + url = route.url(self.base_url) + headers = _build_headers(key) + headers["User-Agent"] = user_agent + budget = _RetryBudget( + max_retries, max_rate_limit_wait, f"{method.upper()} {path}" + ) with rate_limits.bucket(url, key) as bucket: - for attempt in range(max_retries + 1): + attempt = 0 + while True: while wait := bucket.acquire(budget): if isinstance(wait, Future): await asyncio.wrap_future(wait) @@ -198,13 +201,12 @@ async def run_rest_request_async( await asyncio.sleep(wait) try: started_at = time.monotonic() - async with session.request( - method, - url, + async with self.stream( + route, headers=headers, params=params, json=json, - timeout=client_timeout, + timeout=timeout, ) as response: retry_after = bucket.update( response.status, @@ -213,8 +215,9 @@ async def run_rest_request_async( started_at=started_at, ) if budget.can_retry(attempt, retry_after): + attempt += 1 continue - if response.status >= HTTP_STATUS_BAD_REQUEST: + if response.status >= 300: text = ( "" if response.status == HTTP_STATUS_UNAUTHORIZED @@ -233,6 +236,59 @@ async def run_rest_request_async( bucket.release() +def run_rest_request( + method: str, + path: str, + *, + api_key: str | None = None, + params: Mapping[str, Any] | None = None, + json: Mapping[str, Any] | None = None, + timeout: float = 30, + max_retries: int = 3, + max_rate_limit_wait: float = 60, + user_agent: str = USER_AGENT, +) -> dict[str, Any] | None: + """send one REST request and close its connection pool.""" + api_key = _resolve_api_key(api_key) + with RESTClient(api_key) as client: + return client.request( + Route(method, path), + params=params, + json=json, + timeout=timeout, + max_retries=max_retries, + max_rate_limit_wait=max_rate_limit_wait, + user_agent=user_agent, + ) + + +async def run_rest_request_async( + method: str, + path: str, + *, + api_key: str | None = None, + params: Mapping[str, Any] | None = None, + json: Mapping[str, Any] | None = None, + timeout: float = 30, + max_retries: int = 3, + max_rate_limit_wait: float = 60, + user_agent: str = USER_AGENT, + session: aiohttp.ClientSession | None = None, +) -> dict[str, Any] | None: + """send one REST request using an owned or borrowed connection pool.""" + api_key = _resolve_api_key(api_key) + async with AsyncRESTClient(api_key, session=session) as client: + return await client.request( + Route(method, path), + params=params, + json=json, + timeout=timeout, + max_retries=max_retries, + max_rate_limit_wait=max_rate_limit_wait, + user_agent=user_agent, + ) + + class _CursorPagination: def __init__( self, @@ -309,8 +365,9 @@ async def run_rest_paginated_request_async( user_agent: str = USER_AGENT, ) -> list[dict[str, Any]]: """read all cursor pages with one session and four transport attempts per page.""" + api_key = _resolve_api_key(api_key) pagination = _CursorPagination(path, collection) - async with aiohttp.ClientSession() as session: + async with HTTPClient() as client: while True: for attempt in range(4): try: @@ -319,7 +376,7 @@ async def run_rest_paginated_request_async( path, api_key=api_key, params=pagination.params, - session=session, + session=client.session, user_agent=user_agent, ) break diff --git a/runpod/api/routes.py b/runpod/api/routes.py new file mode 100644 index 000000000..6b07cdb3a --- /dev/null +++ b/runpod/api/routes.py @@ -0,0 +1,84 @@ +"""route templates and service origins.""" + +import re +from urllib.parse import quote, urlsplit, urlunsplit + +from runpod._hosts import ( + api_base_url as api_base_url, + endpoint_base_url as _endpoint_base_url, + host_api_base_url as host_api_base_url, + proxy_url, +) + + +def endpoint_base_url(endpoint_id: str | None = None) -> str: + base = _endpoint_base_url() + if endpoint_id is None: + return base + return Route("GET", "/{endpoint_id}", endpoint_id=endpoint_id).url(base) + + +def _host_label(value: str) -> str: + if not re.fullmatch(r"[A-Za-z0-9_-]+", value): + raise ValueError("invalid resource id for a service hostname") + return value + + +def load_balancer_base_url(endpoint_id: str) -> str: + base = urlsplit(endpoint_base_url()) + if base.scheme not in {"http", "https"} or not base.netloc or base.username: + raise ValueError("invalid endpoint base URL") + return urlunsplit( + (base.scheme, f"{_host_label(endpoint_id)}.{base.netloc}", "", "", "") + ) + + +def pod_proxy_base_url(pod_id: str, port: int) -> str: + if isinstance(port, bool) or not isinstance(port, int) or not 1 <= port <= 65535: + raise ValueError("invalid pod proxy port") + return proxy_url(_host_label(pod_id), port) + + +class Route: + """an HTTP method and a path template with escaped parameters.""" + + def __init__(self, method: str, path: str, **parameters): + self.method = method.upper() + self.path = path + self.parameters = parameters + + @property + def resolved_path(self) -> str: + if not self.parameters: + return self.path + parameters = {} + for name, value in self.parameters.items(): + encoded = quote(str(value), safe="") + parameters[name] = ( + encoded.replace(".", "%2E") if encoded in {".", ".."} else encoded + ) + return self.path.format_map(parameters) + + def url(self, base_url: str | None = None) -> str: + base_url = api_base_url() if base_url is None else base_url + base = urlsplit(base_url) + if base.scheme not in {"http", "https"} or not base.netloc or base.username: + raise ValueError( + "base URL must be an HTTP origin without embedded credentials" + ) + path = self.resolved_path + if not path: + return base_url + parsed = urlsplit(path) + if parsed.scheme or parsed.netloc or parsed.fragment or path.startswith("//"): + raise ValueError("route paths must be relative to their service") + if any(part in {".", ".."} for part in parsed.path.split("/")): + raise ValueError("route paths must not traverse parent directories") + if base.query or base.fragment: + raise ValueError("a service base URL cannot contain a query or fragment") + resolved = quote( + f"{base.path.rstrip('/')}/{parsed.path.lstrip('/')}", + safe="/%:@!$&'()*+,;=-._~", + ) + query = quote(parsed.query, safe="/%?:@!$&'()*+,;=-._~") + return urlunsplit((base.scheme, base.netloc, resolved, query, "")) diff --git a/runpod/apps/_stock.py b/runpod/apps/_stock.py new file mode 100644 index 000000000..949dc033e --- /dev/null +++ b/runpod/apps/_stock.py @@ -0,0 +1,16 @@ +"""stock lookup contract shared by placement and volume resolution.""" + +from collections.abc import Iterable +from typing import Protocol + +StockKey = tuple[str, str, int] + + +class StockSource(Protocol): + async def fetch( + self, keys: Iterable[StockKey], *, datacenters: Iterable[str] | None = None + ) -> None: + raise NotImplementedError + + def score(self, key: StockKey, dc: str) -> int: + raise NotImplementedError diff --git a/runpod/apps/api.py b/runpod/apps/api.py index 811f08dfa..2f9547526 100644 --- a/runpod/apps/api.py +++ b/runpod/apps/api.py @@ -1,7 +1,7 @@ """control-plane calls for app provisioning. rest handles equivalent resource operations; graphql handles flash lifecycle, -auth, secrets, task provisioning, and endpoint capabilities +secrets, task provisioning, and endpoint capabilities absent from rest. management verbs for the wider sdk stay in runpod.api.ctl_commands. """ @@ -12,11 +12,12 @@ from ..api.ctl_commands import _cpu_config, _path_segment, _split_values from ..api.graphql import run_graphql_query_async +from ..api.http import HTTPClient from ..api.mutations import apps as app_mutations from ..api.queries import apps as app_queries -from ..api.queries import user as user_queries from ..api.rest import run_rest_paginated_request_async, run_rest_request_async -from ..error import AuthenticationError, QueryError +from ..api.routes import Route +from ..error import QueryError from ..user_agent import APPS_USER_AGENT from .errors import AppHTTPError from .utils.http import raise_for_status @@ -24,6 +25,14 @@ _TRANSPORT_RETRIES = 4 +def _require_rest_response( + data: dict[str, Any] | None, operation: str +) -> dict[str, Any]: + if data is None: + raise QueryError(f"{operation} returned an empty response") + return data + + class FlashTaskApiClient: """named task lifecycle operations with runtime-scoped authentication.""" @@ -318,12 +327,15 @@ async def save_endpoint(self, endpoint_input: dict[str, Any]) -> dict[str, Any]: path = "/v2/serverless" if endpoint_id: path += f"/{_path_segment(endpoint_id)}" - return await run_rest_request_async( - "PATCH" if endpoint_id else "POST", - path, - user_agent=APPS_USER_AGENT, - api_key=self._api_key, - json=body, + return _require_rest_response( + await run_rest_request_async( + "PATCH" if endpoint_id else "POST", + path, + user_agent=APPS_USER_AGENT, + api_key=self._api_key, + json=body, + ), + "saving endpoint", ) template = endpoint_input.get("template") if template is not None and "name" not in template and "name" in endpoint_input: @@ -346,19 +358,28 @@ async def delete_endpoint(self, endpoint_id: str) -> bool: return True async def list_my_endpoints(self) -> list[dict[str, Any]]: - data = await run_rest_request_async( - "GET", "/v2/serverless", user_agent=APPS_USER_AGENT, api_key=self._api_key + data = _require_rest_response( + await run_rest_request_async( + "GET", + "/v2/serverless", + user_agent=APPS_USER_AGENT, + api_key=self._api_key, + ), + "listing endpoints", ) return data["endpoints"] async def endpoint_workers(self, endpoint_id: str) -> dict[str, Any]: """worker state uses the user key.""" - return await run_rest_request_async( - "GET", - f"/v2/serverless/{_path_segment(endpoint_id)}/workers", - user_agent=APPS_USER_AGENT, - api_key=self._api_key, - timeout=10, + return _require_rest_response( + await run_rest_request_async( + "GET", + f"/v2/serverless/{_path_segment(endpoint_id)}/workers", + user_agent=APPS_USER_AGENT, + api_key=self._api_key, + timeout=10, + ), + "reading endpoint workers", ) async def deploy_task_pod( @@ -431,17 +452,20 @@ async def gpu_stock_status( pods: bool = False, ) -> str | None: """secure-cloud stock scoped to GPU count and pod/serverless product.""" - data = await run_rest_request_async( - "GET", - f"/v2/catalog/gpus/{_path_segment(gpu_id)}", - user_agent=APPS_USER_AGENT, - api_key=self._api_key, - params={ - "include": "AVAILABILITY", - "product": "POD" if pods else "SERVERLESS", - "count": gpu_count, - "cloud": "SECURE", - }, + data = _require_rest_response( + await run_rest_request_async( + "GET", + f"/v2/catalog/gpus/{_path_segment(gpu_id)}", + user_agent=APPS_USER_AGENT, + api_key=self._api_key, + params={ + "include": "AVAILABILITY", + "product": "POD" if pods else "SERVERLESS", + "count": gpu_count, + "cloud": "SECURE", + }, + ), + "reading GPU stock", ) return _stock_in_datacenter(data, data_center_id) @@ -468,16 +492,19 @@ async def cpu_stock_status( flavors = data.get("cpuFlavors") or [] specifics = (flavors[0].get("specifics") or {}) if flavors else {} return specifics.get("stockStatus") - data = await run_rest_request_async( - "GET", - f"/v2/catalog/cpus/{_path_segment(cpu['id'])}", - user_agent=APPS_USER_AGENT, - api_key=self._api_key, - params={ - "include": "AVAILABILITY", - "product": "POD" if pods else "SERVERLESS", - "vcpuCount": cpu["vcpuCount"], - }, + data = _require_rest_response( + await run_rest_request_async( + "GET", + f"/v2/catalog/cpus/{_path_segment(cpu['id'])}", + user_agent=APPS_USER_AGENT, + api_key=self._api_key, + params={ + "include": "AVAILABILITY", + "product": "POD" if pods else "SERVERLESS", + "vcpuCount": cpu["vcpuCount"], + }, + ), + "reading CPU stock", ) return _stock_in_datacenter(data, data_center_id) @@ -561,12 +588,15 @@ async def list_network_volumes(self) -> list[dict[str, Any]]: async def create_network_volume( self, name: str, size: int, data_center_id: str ) -> dict[str, Any]: - return await run_rest_request_async( - "POST", - "/v2/network-volumes", - user_agent=APPS_USER_AGENT, - api_key=self._api_key, - json={"name": name, "size": size, "dataCenter": data_center_id}, + return _require_rest_response( + await run_rest_request_async( + "POST", + "/v2/network-volumes", + user_agent=APPS_USER_AGENT, + api_key=self._api_key, + json={"name": name, "size": size, "dataCenter": data_center_id}, + ), + "creating network volume", ) async def delete_network_volume(self, volume_id: str) -> bool: @@ -580,20 +610,29 @@ async def delete_network_volume(self, volume_id: str) -> bool: return True async def list_registry_auths(self) -> list[dict[str, Any]]: - data = await run_rest_request_async( - "GET", "/v2/registries", user_agent=APPS_USER_AGENT, api_key=self._api_key + data = _require_rest_response( + await run_rest_request_async( + "GET", + "/v2/registries", + user_agent=APPS_USER_AGENT, + api_key=self._api_key, + ), + "listing registry credentials", ) return data["registries"] async def create_registry_auth( self, name: str, username: str, password: str ) -> dict[str, Any]: - return await run_rest_request_async( - "POST", - "/v2/registries", - user_agent=APPS_USER_AGENT, - api_key=self._api_key, - json={"name": name, "username": username, "password": password}, + return _require_rest_response( + await run_rest_request_async( + "POST", + "/v2/registries", + user_agent=APPS_USER_AGENT, + api_key=self._api_key, + json={"name": name, "username": username, "password": password}, + ), + "creating registry credentials", ) async def delete_registry_auth(self, auth_id: str) -> bool: @@ -667,32 +706,6 @@ async def delete_environment(self, environment_id: str) -> bool: data = await self._execute(mutation, {"flashEnvironmentId": environment_id}) return bool(data.get("deleteFlashEnvironment")) - async def create_auth_request(self) -> dict[str, Any]: - """open a browser-approval auth request; no credentials needed.""" - mutation = app_mutations.MUTATION_CREATE_FLASH_AUTH_REQUEST - data = await self._execute(mutation, anonymous=True) - return data.get("createFlashAuthRequest") or {} - - async def get_auth_request_status(self, request_id: str) -> dict[str, Any]: - query = app_queries.QUERY_FLASH_AUTH_REQUEST_STATUS - data = await self._execute( - query, {"flashAuthRequestId": request_id}, anonymous=True - ) - return data.get("flashAuthRequestStatus") or {} - - async def verify_api_key(self, api_key: str) -> bool: - """true when api_key authenticates; transport failures still raise.""" - try: - response = await run_graphql_query_async( - user_queries.QUERY_USER, - api_key=api_key, - headers={"User-Agent": APPS_USER_AGENT}, - ) - except (AuthenticationError, QueryError): - return False - myself = (response.get("data") or {}).get("myself") or {} - return bool(myself.get("id")) - async def prepare_artifact_upload( self, app_id: str, tarball_size: int ) -> dict[str, Any]: @@ -765,24 +778,25 @@ async def _reader(): yield chunk attempts = 4 - for attempt in range(attempts): - try: - await self._put_tarball(upload_url, _reader(), total, timeout) - return - except (AppHTTPError, aiohttp.ClientError, OSError): - if attempt == attempts - 1: - raise - await asyncio.sleep(2**attempt) - - async def _put_tarball(self, upload_url, reader, total, timeout) -> None: - async with aiohttp.ClientSession(timeout=timeout) as session: - async with session.put( - upload_url, - data=reader, - headers={ - "User-Agent": APPS_USER_AGENT, - "Content-Type": "application/gzip", - "Content-Length": str(total), - }, - ) as resp: - await raise_for_status(resp) + async with HTTPClient(base_url=upload_url) as client: + for attempt in range(attempts): + try: + await self._put_tarball(client, _reader(), total, timeout) + return + except (AppHTTPError, aiohttp.ClientError, OSError): + if attempt == attempts - 1: + raise + await asyncio.sleep(2**attempt) + + async def _put_tarball(self, client, reader, total, timeout) -> None: + async with client.stream( + Route("PUT", ""), + timeout=timeout, + data=reader, + headers={ + "User-Agent": APPS_USER_AGENT, + "Content-Type": "application/gzip", + "Content-Length": str(total), + }, + ) as resp: + await raise_for_status(resp) diff --git a/runpod/apps/auth.py b/runpod/apps/auth.py index 853d453ee..1db9c903a 100644 --- a/runpod/apps/auth.py +++ b/runpod/apps/auth.py @@ -1,259 +1,7 @@ -"""browser-approval and email-verification login flows.""" +"""shared account login flows.""" -import base64 -import datetime as dt -import hashlib -import json -import os -import secrets -import tempfile -from collections.abc import Callable -from pathlib import Path -from typing import Any -from urllib.parse import quote -from uuid import uuid4 +import sys -import aiohttp +from runpod.auth import login -from runpod._hosts import console_url -from runpod.api.rest import _build_url -from runpod.user_agent import APPS_USER_AGENT - -from ..error import QueryError -from .api import AppsApiClient -from .errors import AppError - -MAX_KEY_ATTEMPTS = 3 - -_CLOSED_REASONS = { - "DENIED": "login was denied in the browser", - "EXPIRED": "login request expired", -} - - -class LoginError(AppError): - pass - - -class _VerificationCodeRejected(LoginError): - pass - - -async def _post_authentication_attempt( - session: aiohttp.ClientSession, - path: str, - body: dict, - *, - creating: bool = False, -) -> dict: - try: - async with session.post( - _build_url(path), - json=body, - headers={"Idempotency-Key": str(uuid4())} if creating else {}, - allow_redirects=False, - ) as response: - if response.status != (201 if creating else 200): - if response.status == 403: - raise LoginError( - "email sign-in is not allowed for this account; sign in " - "through the console and use runpod login --api-key" - ) - if response.status == 404: - if creating: - raise LoginError("email sign-in is unavailable on this API") - raise LoginError( - "login attempt expired, was already used, or is locked; " - "start login again" - ) - if response.status == 422: - if creating: - raise LoginError( - "email sign-in request rejected; check --email" - ) - raise _VerificationCodeRejected("verification code rejected") - if response.status == 429: - raise LoginError( - "too many login attempts; wait before trying again" - ) - raise LoginError(f"email sign-in failed (HTTP {response.status})") - payload = await response.json() - except (TimeoutError, aiohttp.ClientError): - raise LoginError( - "could not complete email sign-in; check your connection" - ) from None - except ValueError: - raise LoginError("invalid response from the email sign-in API") from None - - if not isinstance(payload, dict): - raise LoginError("invalid response from the email sign-in API") - return payload - - -def pending_agent_login_path(profile: str) -> Path: - from runpod.cli.groups.config.functions import CREDENTIAL_FILE - - profile_id = hashlib.sha256(profile.encode("utf-8")).hexdigest() - return Path(CREDENTIAL_FILE).parent / f"login-{profile_id}.json" - - -def save_agent_login(attempt: dict, profile: str) -> None: - path = pending_agent_login_path(profile) - path.parent.mkdir(mode=0o700, parents=True, exist_ok=True) - fd, temporary = tempfile.mkstemp(dir=path.parent, suffix=".json") - try: - with os.fdopen(fd, "w", encoding="utf-8") as pending: - json.dump(attempt, pending) - os.replace(temporary, path) - except BaseException: - os.unlink(temporary) - raise - - -def load_agent_login(profile: str) -> dict: - try: - attempt = json.loads( - pending_agent_login_path(profile).read_text(encoding="utf-8") - ) - except FileNotFoundError: - raise LoginError( - "no pending login for this profile. Run runpod login --agent --email ADDRESS" - ) from None - except ValueError: - raise LoginError( - "invalid pending login. Run runpod login --agent --email ADDRESS to request a new code" - ) from None - if not isinstance(attempt, dict) or any( - not isinstance(attempt.get(field), str) or not attempt[field] - for field in ("attempt_id", "verifier", "api_url") - ): - raise LoginError( - "invalid pending login. Run runpod login --agent --email ADDRESS to request a new code" - ) - return attempt - - -def _agent_session() -> aiohttp.ClientSession: - return aiohttp.ClientSession( - timeout=aiohttp.ClientTimeout(total=30), - headers={"Accept": "application/json", "User-Agent": APPS_USER_AGENT}, - cookie_jar=aiohttp.DummyCookieJar(), - ) - - -async def start_agent_login(email: str) -> dict: - """request an emailed code and return its proof-of-possession state.""" - verifier = secrets.token_urlsafe(32) - challenge = ( - base64.urlsafe_b64encode(hashlib.sha256(verifier.encode("ascii")).digest()) - .decode("ascii") - .rstrip("=") - ) - path = "/v2/signup/authentication-attempts" - - async with _agent_session() as session: - attempt = await _post_authentication_attempt( - session, - path, - {"email": email, "keyName": "runpod-cli-agent", "codeChallenge": challenge}, - creating=True, - ) - attempt_id = attempt.get("attemptId") - if not isinstance(attempt_id, str) or not attempt_id: - raise LoginError("auth attempt failed to initialize") - - return {"attempt_id": attempt_id, "verifier": verifier, "api_url": _build_url(path)} - - -async def verify_agent_login(attempt: dict, code: str) -> str: - """exchange a code and its saved verifier for an api key.""" - path = "/v2/signup/authentication-attempts" - if attempt["api_url"] != _build_url(path): - raise LoginError("pending login belongs to a different API. Request a new code") - async with _agent_session() as session: - result = await _post_authentication_attempt( - session, - f"{path}/{quote(attempt['attempt_id'], safe='')}/verify", - {"code": code, "codeVerifier": attempt["verifier"]}, - ) - credential = result.get("credential") - api_key = credential.get("apiKey") if isinstance(credential, dict) else None - if not isinstance(api_key, str) or not api_key.strip(): - raise LoginError("email sign-in response did not contain an API key") - return api_key - - -async def agent_login(email: str, *, read_code: Callable[[], str]) -> str: - """exchange an emailed code for an api key bound to this login's verifier.""" - attempt = await start_agent_login(email) - while True: - code = read_code() - try: - return await verify_agent_login(attempt, code) - except _VerificationCodeRejected: - continue - - -def _parse_expires_at(value: str | None) -> dt.datetime | None: - if not value: - return None - try: - return dt.datetime.fromisoformat(value.replace("Z", "+00:00")) - except ValueError: - return None - - -def auth_url(request_id: str) -> str: - return f"{console_url()}/flash/login?request={request_id}" - - -async def _closed_reason(client: AppsApiClient, request_id: str) -> str | None: - """why the request can no longer produce a key, or None to keep prompting.""" - try: - request = await client.get_auth_request_status(request_id) - except (TimeoutError, QueryError, aiohttp.ClientError, OSError): - return None - return _CLOSED_REASONS.get(request.get("status")) - - -async def browser_login( - *, - prompt_key: Callable[[], str], - on_url: Callable[[str], None] | None = None, - on_rejected: Callable[[str], None] | None = None, - api: AppsApiClient | None = None, - max_attempts: int = MAX_KEY_ATTEMPTS, -) -> str: - """run the browser-approval flow and return the pasted api key. - - on_url is called with the approval url as soon as the request is - created (the caller renders/opens it). the console shows the new key - only to the signed-in approver, so the user pastes it via prompt_key. - on_rejected is called with a reason before each re-prompt. - """ - client = api or AppsApiClient() - request: dict[str, Any] = await client.create_auth_request() - request_id = request.get("id") - - if not request_id: - raise LoginError("auth request failed to initialize") - - if on_url is not None: - on_url(auth_url(request_id)) - - reason = "no api key entered" - for attempt in range(max_attempts): - api_key = (prompt_key() or "").strip() - if not api_key: - reason = "no api key entered" - elif await client.verify_api_key(api_key): - return api_key - else: - reason = "api key was rejected" - closed = await _closed_reason(client, request_id) - if closed: - raise LoginError(f"{closed}; run login again") - if on_rejected is not None and attempt < max_attempts - 1: - on_rejected(reason) - - raise LoginError(f"{reason}; run login again") +sys.modules[__name__] = login diff --git a/runpod/apps/build.py b/runpod/apps/build.py index b8e6a46d7..8a4a5b898 100644 --- a/runpod/apps/build.py +++ b/runpod/apps/build.py @@ -472,7 +472,9 @@ def _requires_dist(dist_info: Path) -> list[Requirement] | None: requirements = [ _parse_requirement(line) for line in headers.get_all("Requires-Dist") or [] ] - return None if None in requirements else requirements + if any(requirement is None for requirement in requirements): + return None + return [requirement for requirement in requirements if requirement is not None] def _extra_marker_applies(markers: list, extra: str) -> bool: @@ -534,7 +536,7 @@ def installed_closure(env_dir: Path, roots: list[str]) -> set: if known is not None and extras <= known: continue active = activated[node] = (known or set()) | extras - stack.extend(_active_requirements(requires.get(node) or (), active)) + stack.extend(_active_requirements(requires.get(node) or [], active)) return set(activated) @@ -630,7 +632,7 @@ def _distributions_to_drop( parsed_roots = [_parse_requirement(r) for r in roots] if None in records.values() or None in parsed_roots: return targets - root_names = {canonicalize_name(r.name) for r in parsed_roots} + root_names = {canonicalize_name(r.name) for r in parsed_roots if r is not None} requires = {} for name, dist_info in dist_infos.items(): dependencies = _requires_dist(dist_info) @@ -657,8 +659,8 @@ def _delete_distributions( ) -> None: """delete the dropped distributions' files, keeping any file a kept distribution also installed.""" - dropped_files = set() - kept_files = set() + dropped_files: set[str] = set() + kept_files: set[str] = set() for name, paths in records.items(): (dropped_files if name in dropped else kept_files).update(paths or ()) touched = _remove_files(env_dir, dropped_files - kept_files) @@ -785,7 +787,7 @@ def vendor( python_version: str, *, no_deps: bool = False, - progress: Callable | None = None, + progress: Callable[[int, str], None] | None = None, ) -> None: """resolve requirements into env_dir for the worker platform. @@ -824,7 +826,8 @@ def vendor( text=True, ) count = 0 - output = deque(maxlen=30) + output: deque[str] = deque(maxlen=30) + assert proc.stdout is not None for line in proc.stdout: output.append(line) line = line.strip() diff --git a/runpod/apps/context.py b/runpod/apps/context.py index 9aa41cc7d..534299f42 100644 --- a/runpod/apps/context.py +++ b/runpod/apps/context.py @@ -46,16 +46,17 @@ def deployed_identity() -> tuple[str, str, str] | None: or os.getenv("FLASH_RESOURCE_NAME") ): return None - fields = tuple( - os.getenv(key) - for key in ("FLASH_APP_NAME", "FLASH_ENVIRONMENT", "FLASH_RESOURCE_NAME") - ) + app = os.getenv("FLASH_APP_NAME") + environment = os.getenv("FLASH_ENVIRONMENT") + resource = os.getenv("FLASH_RESOURCE_NAME") + fields = (app, environment, resource) build = os.getenv("RUNPOD_BUILD_ID") if any(not value or value != value.strip() for value in (*fields, build)): raise RuntimeError( "deployed flash requires app, environment, resource and build identity" ) - return fields + assert app is not None and environment is not None and resource is not None + return app, environment, resource def is_local() -> bool: diff --git a/runpod/apps/deploy.py b/runpod/apps/deploy.py index beaf6cf67..18813305f 100644 --- a/runpod/apps/deploy.py +++ b/runpod/apps/deploy.py @@ -32,8 +32,9 @@ ) from .shim import runtime_launcher from .source import iter_source_files -from .spec import ResourceKind +from .spec import ResourceKind, normalize_gpu from .utils.events import emit +from .volume import GlobalVolume, NetworkVolume log = logging.getLogger(__name__) @@ -171,7 +172,7 @@ def build_manifest( raise InvalidResourceError( f"task '{spec.name}' env contains reserved runtime field {key!r}" ) - for path in spec.mounts: + for path in spec.mounts or {}: mount_path = PurePosixPath(path) for reserved in ( "/root/.runpod", @@ -193,10 +194,11 @@ def build_manifest( entry["imageName"] = image_for_spec(spec, python_version=python_version) entry["customImage"] = bool(spec.image) for mount, volume in zip( - entry.get("mounts", []), spec.mounts.values(), strict=True + entry.get("mounts", []), (spec.mounts or {}).values(), strict=True ): + assert isinstance(volume, (GlobalVolume, NetworkVolume)) mount["create"] = volume.create - if volume.kind == "network": + if isinstance(volume, NetworkVolume): mount["size"] = volume.size if volume.datacenter is not None: mount["datacenter"] = volume.datacenter @@ -294,8 +296,8 @@ def package_project( or path == output_resolved ): continue - rel = path.relative_to(env_resolved).as_posix() - tar.add(path, arcname=f"{ENV_DIR_NAME}/{rel}", recursive=False) + env_rel = path.relative_to(env_resolved).as_posix() + tar.add(path, arcname=f"{ENV_DIR_NAME}/{env_rel}", recursive=False) manifest_bytes = json.dumps(_without_env(manifest), indent=2).encode() info = tarfile.TarInfo(name="runpod_manifest.json") @@ -479,7 +481,7 @@ async def reconcile_endpoints( endpoints: dict[str, str] = {} snapshots = {} - undo = [] + undo: list[tuple[str, str, dict[str, Any] | None]] = [] activation_attempted = False creating = False action = "prepare deployment" @@ -500,7 +502,7 @@ async def reconcile_endpoints( action = f"prepare '{name}'" creating = False members = None - if needs_gpu_catalog(handle.spec.gpu): + if needs_gpu_catalog(normalize_gpu(handle.spec.gpu)): members = await client.gpu_pool_members() if name in existing: template_name = existing_templates.get(name) @@ -854,8 +856,10 @@ async def deploy_app( await client.upload_tarball( upload["uploadUrl"], str(tar_path), progress=upload_progress ) - build = await client.finalize_artifact_upload(app_id, upload["objectKey"], manifest) - definitions = build.get("resourceSpec") + remote_build = await client.finalize_artifact_upload( + app_id, upload["objectKey"], manifest + ) + definitions = remote_build.get("resourceSpec") tasks = {r["name"] for r in manifest["resources"] if r["kind"] == "task"} if tasks and ( not isinstance(definitions, dict) @@ -869,7 +873,7 @@ async def deploy_app( raise RuntimeError( "backend did not acknowledge the registered task definitions" ) - log.info("uploaded build %s", build["id"]) + log.info("uploaded build %s", remote_build["id"]) current = await client.get_environment_by_name(app.name, env_name) if ( @@ -894,7 +898,7 @@ async def deploy_app( client, app, environment, - build["id"], + remote_build["id"], python_version, resolver=resolver, activate_build=True, @@ -908,7 +912,7 @@ async def deploy_app( return DeployResult( app_name=app.name, - build_id=build["id"], + build_id=remote_build["id"], environment_id=environment["id"], resources=[r["name"] for r in manifest["resources"]], endpoints=endpoints, diff --git a/runpod/apps/dev.py b/runpod/apps/dev.py index 5177b6c45..fb1ea7f9f 100644 --- a/runpod/apps/dev.py +++ b/runpod/apps/dev.py @@ -17,10 +17,17 @@ from .gpu import needs_gpu_catalog from .handles import ApiHandle, FunctionHandle from .shim import runtime_launcher -from .spec import ResourceKind, ResourceSpec +from .spec import ( + ResourceKind, + ResourceSpec, + normalize_cpu, + normalize_gpu, + normalize_workers, +) from .targets import LiveTarget from .utils.events import emit from .utils.names import dev_endpoint_name +from .volume import VolumeResolver log = logging.getLogger(__name__) @@ -124,6 +131,7 @@ def _endpoint_input( """ spec.validate() + workers = normalize_workers(spec.workers) resource_env = _render_env(spec.env) resource_env["RUNPOD_DEV_RESOURCE"] = spec.name if spec.kind is ResourceKind.API: @@ -132,8 +140,8 @@ def _endpoint_input( payload: dict = { "name": dev_endpoint_name(app.name, spec.name), - "workersMin": spec.workers[0], - "workersMax": spec.workers[1], + "workersMin": workers[0], + "workersMax": workers[1], "idleTimeout": spec.idle_timeout, "scalerType": spec.effective_scaler_type, "scalerValue": spec.scaler_value, @@ -190,11 +198,13 @@ def _endpoint_input( if spec.is_cpu: payload["instanceIds"] = spec.cpu if not spec.datacenter: - payload["locations"] = _cpu_locations(spec.cpu or []) + payload["locations"] = _cpu_locations(normalize_cpu(spec.cpu) or []) else: from .gpu import gpu_ids_value - payload["gpuIds"] = gpu_ids_value(spec.gpu, pool_members=pool_members) + payload["gpuIds"] = gpu_ids_value( + normalize_gpu(spec.gpu), pool_members=pool_members + ) payload["gpuCount"] = spec.gpu_count payload["minCudaVersion"] = spec.effective_min_cuda_version return payload @@ -228,7 +238,7 @@ def __init__( # endpoint name -> comparable payload, for refresh diffing self._payloads: dict[str, dict] = {} # volumes resolve once per session (placement is stable) - self._volume_resolver = None + self._volume_resolver: VolumeResolver | None = None # template names are unique per owner, and a deleted endpoint keeps # its template for a while, so a fixed name collides when the same # app starts again soon after. endpoint names stay fixed for adoption. @@ -245,7 +255,7 @@ async def _attach_volumes(self, payload: dict, spec, app) -> None: """resolve the resource's volumes and registry auth onto a dev endpoint payload.""" from .registry import resolve_registry_auth - from .volume import VolumeResolver, attach_endpoint_volumes + from .volume import attach_endpoint_volumes if spec.registry_auth: auth_id = await resolve_registry_auth(spec.registry_auth, api=self.api) @@ -283,8 +293,6 @@ async def start(self) -> None: for name in secret_names(handle.spec.env) ] await validate_secrets(referenced, api=self.api) - from .volume import VolumeResolver - self._volume_resolver = VolumeResolver(self.api, events=self.events) await self._volume_resolver.preflight( [handle.spec for app in self.apps for handle in app.resources.values()] @@ -304,7 +312,7 @@ async def start(self) -> None: self._resource_names[name] = spec.name spec.validate() members = None - if needs_gpu_catalog(spec.gpu): + if needs_gpu_catalog(normalize_gpu(spec.gpu)): members = await self.api.gpu_pool_members() payload = _endpoint_input( app, @@ -315,7 +323,9 @@ async def start(self) -> None: ) await self._attach_volumes(payload, spec, app) - hardware = ",".join(spec.cpu or spec.gpu or ["any"]) + hardware = ",".join( + normalize_cpu(spec.cpu) or normalize_gpu(spec.gpu) or ["any"] + ) if found: # adopt: reconcile the leftover endpoint to the # current spec instead of creating a duplicate @@ -352,8 +362,6 @@ async def refresh(self, apps: list[App]) -> None: requests execute in fresh processes. added resources are provisioned, removed ones deleted.""" - from .volume import VolumeResolver - if self._volume_resolver is None: self._volume_resolver = VolumeResolver(self.api, events=self.events) await self._volume_resolver.preflight( @@ -431,7 +439,9 @@ async def refresh(self, apps: list[App]) -> None: ) spec = handle.spec - hardware = ",".join(spec.cpu or spec.gpu or ["any"]) + hardware = ",".join( + normalize_cpu(spec.cpu) or normalize_gpu(spec.gpu) or ["any"] + ) if previous is None: self._emit("resource_added", spec.name, spec.kind.value, hardware) diff --git a/runpod/apps/discovery.py b/runpod/apps/discovery.py index 79c47d03c..8b50452be 100644 --- a/runpod/apps/discovery.py +++ b/runpod/apps/discovery.py @@ -216,7 +216,7 @@ def discover_apps(target: Path, *, strict: bool = False) -> list[App]: log.warning("%s", exc) found = [app for app in get_registered_apps() if id(app) not in before] - by_name = {} + by_name: dict[str, App] = {} for app in found: if app.name in by_name and by_name[app.name] is not app: other = by_name[app.name] diff --git a/runpod/apps/errors.py b/runpod/apps/errors.py index 58ce1621b..a359cdbf3 100644 --- a/runpod/apps/errors.py +++ b/runpod/apps/errors.py @@ -2,9 +2,7 @@ from yarl import URL - -class AppError(Exception): - """base error for the apps sdk.""" +from runpod.error import AppError as AppError class AppHTTPError(AppError): diff --git a/runpod/apps/gpu.py b/runpod/apps/gpu.py index 62124da7e..80781b540 100644 --- a/runpod/apps/gpu.py +++ b/runpod/apps/gpu.py @@ -388,7 +388,9 @@ def gpu_ids_value( value = pool if value not in pools: pools.append(value) - device_pools = {_device_pool(d) for d in devices} - named_pools + device_pools = { + pool for d in devices if (pool := _device_pool(d)) is not None + } - named_pools if pool_members is None and device_pools: pool_members = live_pool_members() exclusions = sorted( diff --git a/runpod/apps/invoker.py b/runpod/apps/invoker.py index 143784113..c84732931 100644 --- a/runpod/apps/invoker.py +++ b/runpod/apps/invoker.py @@ -62,13 +62,17 @@ def __init__(self, factory: AsyncGenFactory): def __call__(self, *args: Any, **kwargs: Any) -> Iterator[Any]: agen = self._factory(*args, **kwargs) + + async def advance() -> Any: + return await agen.__anext__() + # true only while agen is suspended at a yield, the one state in which # it is safe and necessary to close it. parked_at_yield = False try: while True: try: - item = block(agen.__anext__()) + item = block(advance()) except StopAsyncIteration: return parked_at_yield = True diff --git a/runpod/apps/logs.py b/runpod/apps/logs.py index 36caec32e..faaf7fa09 100644 --- a/runpod/apps/logs.py +++ b/runpod/apps/logs.py @@ -6,19 +6,16 @@ import asyncio import json -import os from collections.abc import AsyncIterator, Callable from typing import Any import aiohttp -from ..api.ctl_commands import _path_segment -from ..api.rest import _build_url +from ..api.http import HTTPClient +from ..api.routes import Route, host_api_base_url from ..user_agent import APPS_USER_AGENT from .utils.http import raise_for_status -HAPI_BASE = os.environ.get("RUNPOD_HAPI_URL", "https://hapi.runpod.net") - STREAM_TIMEOUT_SECONDS = 3600.0 @@ -35,14 +32,14 @@ async def pod_logs( timeout: float = 30.0, ) -> dict[str, list[str]]: """snapshot of a pod's logs: {"container": [...], "system": [...]}.""" - url = f"{HAPI_BASE}/v1/pod/{pod_id}/logs" - client_timeout = aiohttp.ClientTimeout(total=timeout) - async with aiohttp.ClientSession(timeout=client_timeout) as session: - async with session.get( - url, params={"type": log_type}, headers=_headers() - ) as resp: - await raise_for_status(resp) - data = await resp.json() + async with HTTPClient(base_url=host_api_base_url()).stream( + Route("GET", "/v1/pod/{pod_id}/logs", pod_id=pod_id), + params={"type": log_type}, + headers=_headers(), + timeout=timeout, + ) as resp: + await raise_for_status(resp) + data = await resp.json() return {k: v or [] for k, v in data.items()} @@ -67,18 +64,21 @@ async def stream_pod_logs( measured only after the response headers have been received. """ params: dict[str, Any] = {"tail": str(tail)} + base_url = None if log_type == "all": - url = f"{HAPI_BASE}/v1/pod/{_path_segment(pod_id)}/logs" + base_url = host_api_base_url() + route = Route("GET", "/v1/pod/{pod_id}/logs", pod_id=pod_id) params.update(stream="true", type=log_type) else: if endpoint_id is None: - path = f"/v2/pods/{_path_segment(pod_id)}/logs" + route = Route("GET", "/v2/pods/{pod_id}/logs", pod_id=pod_id) else: - path = ( - f"/v2/serverless/{_path_segment(endpoint_id)}" - f"/workers/{_path_segment(pod_id)}/logs" + route = Route( + "GET", + "/v2/serverless/{endpoint_id}/workers/{pod_id}/logs", + endpoint_id=endpoint_id, + pod_id=pod_id, ) - url = _build_url(path) if log_type: params["source"] = log_type if since: @@ -88,8 +88,10 @@ async def stream_pod_logs( headers["Last-Event-ID"] = last_event_id client_timeout = aiohttp.ClientTimeout(total=STREAM_TIMEOUT_SECONDS, sock_read=60) - async with aiohttp.ClientSession(timeout=client_timeout) as session: - async with session.get(url, params=params, headers=headers) as resp: + async with HTTPClient(base_url=base_url) as client: + async with client.stream( + route, params=params, headers=headers, timeout=client_timeout + ) as resp: await raise_for_status(resp) event_id = None data = [] diff --git a/runpod/apps/placement.py b/runpod/apps/placement.py index 100717ef8..d8a464311 100644 --- a/runpod/apps/placement.py +++ b/runpod/apps/placement.py @@ -11,6 +11,7 @@ import logging from collections.abc import Iterable +from ._stock import StockKey as StockKey, StockSource from .datacenter import DEFAULT_DATACENTERS, DataCenter, datacenter_id from .errors import AppError from .gpu import GpuGroup @@ -20,7 +21,6 @@ # stock signal ranking; unknown/none scores zero _STOCK_SCORE = {"HIGH": 3, "MEDIUM": 2, "LOW": 1} -StockKey = tuple[str, str, int] class PlacementError(AppError): @@ -143,7 +143,9 @@ def score(self, key: StockKey, dc: str) -> int: return self._cpu.get((hw, dc, kind == "cpu-pod"), 0) -def candidates(spec, stock: StockMap, *, volume_dc: str | None = None) -> set[str]: +def candidates( + spec, stock: StockSource, *, volume_dc: str | None = None +) -> set[str]: """datacenters where a resource is schedulable. hardware needs stock in the DC (any of the resource's acceptable @@ -170,7 +172,7 @@ def candidates(spec, stock: StockMap, *, volume_dc: str | None = None) -> set[st return viable | unlisted -def _resource_best_score(spec, stock: StockMap, dc: str) -> int: +def _resource_best_score(spec, stock: StockSource, dc: str) -> int: keys = _hardware_keys(spec) if not keys: return 1 @@ -179,7 +181,7 @@ def _resource_best_score(spec, stock: StockMap, dc: str) -> int: def solve_placement( specs: list, - stock: StockMap, + stock: StockSource, *, volume_name: str, volume_datacenters: set[str], diff --git a/runpod/apps/spec.py b/runpod/apps/spec.py index 97de2d7ed..33eb25764 100644 --- a/runpod/apps/spec.py +++ b/runpod/apps/spec.py @@ -88,7 +88,7 @@ def normalize_workers(workers: int | tuple[int, int] | None) -> tuple[int, int]: def normalize_gpu( - gpu: GpuGroup | GpuType | str | list[GpuGroup | GpuType | str] | None, + gpu: GpuGroup | GpuType | str | list[GpuGroup | GpuType | str] | list[str] | None, ) -> list[str] | None: """normalize gpu input to a list of api-facing string values.""" if gpu is None: @@ -202,7 +202,7 @@ class ResourceSpec: kind: ResourceKind name: str - gpu: GpuLike | list[GpuLike] | None = None + gpu: GpuLike | list[GpuLike] | list[str] | None = None cpu: str | list[str] | None = None gpu_count: int = 1 workers: int | tuple[int, int] | None = DEFAULT_WORKERS @@ -350,12 +350,13 @@ def to_manifest(self, *, include_env: bool = True) -> dict[str, Any]: never written into the packaged artifact. """ self.validate() + workers = normalize_workers(self.workers) data: dict[str, Any] = { "kind": self.kind.value, "name": self.name, "gpuCount": self.gpu_count, - "workersMin": self.workers[0], - "workersMax": self.workers[1], + "workersMin": workers[0], + "workersMax": workers[1], "idleTimeout": self.idle_timeout, } if self.gpu is not None: diff --git a/runpod/apps/targets.py b/runpod/apps/targets.py index bed30ad61..ff5d092d2 100644 --- a/runpod/apps/targets.py +++ b/runpod/apps/targets.py @@ -15,7 +15,8 @@ import aiohttp -from .._hosts import endpoint_domain +from ..api.http import HTTPClient +from ..api.routes import Route, endpoint_base_url, load_balancer_base_url from ..user_agent import APPS_USER_AGENT from .errors import ( AppHTTPError, @@ -26,11 +27,10 @@ from .invoker import close_iterator from .protocol import FORMAT_JSON, FunctionRequest from .serialization import require_json_value -from .spec import ResourceSpec +from .spec import ResourceSpec, normalize_cpu, normalize_gpu from .utils.events import emit from .utils.http import raise_for_status from .utils.network import api_key as _api_key -from .utils.network import endpoint_url_base as _endpoint_url_base # the sentinel pseudo-endpoint id; ai-api resolves the real endpoint from # the X-Flash-App / X-Flash-Environment / X-Flash-Endpoint headers. @@ -43,11 +43,6 @@ FINAL_STATUSES = frozenset({"COMPLETED", "FAILED", "CANCELLED", "TIMED_OUT"}) -def _lb_domain() -> str: - """host portion of the data-plane base url, for lb subdomain urls.""" - return endpoint_domain() - - def _headers(extra: dict[str, str] | None = None) -> dict[str, str]: from .utils.network import runtime_headers @@ -173,7 +168,9 @@ def unwrap(self, data: dict[str, Any]) -> Any: return unwrap_job_output(data) @abstractmethod - async def invoke(self, payload: dict[str, Any], *, timeout: float) -> Any: + async def invoke( + self, payload: dict[str, Any], *, timeout: float = DEFAULT_TIMEOUT_SECONDS + ) -> Any: """submit and wait for the result.""" @abstractmethod @@ -194,7 +191,9 @@ async def retry_job(self, job_id: str) -> dict[str, Any]: """retry a failed or timed-out job.""" raise NotImplementedError(f"{type(self).__name__} does not support job retries") - def stream_job(self, job_id: str, *, timeout: float) -> AsyncIterator[Any]: + def stream_job( + self, job_id: str, *, timeout: float = DEFAULT_TIMEOUT_SECONDS + ) -> AsyncIterator[Any]: """yield partial outputs of a generator job as they arrive.""" raise NotImplementedError( f"{type(self).__name__} does not support job streaming" @@ -255,7 +254,6 @@ async def _request_json( require_json_value(payload, "remote request body must be JSON-serializable") retry_transient = method.upper() in {"GET", "HEAD", "OPTIONS"} - client_timeout = aiohttp.ClientTimeout(total=timeout) last_exc: Exception | None = None attempts = ( JOB_PROPAGATION_ATTEMPTS @@ -264,13 +262,13 @@ async def _request_json( if retry_transient else 1 ) - for attempt in range(attempts): - if attempt: - await asyncio.sleep(RETRY_BASE_DELAY * (2 ** (attempt - 1))) - try: - async with aiohttp.ClientSession(timeout=client_timeout) as session: - async with session.request( - method, url, json=payload, headers=headers + async with HTTPClient(base_url=url) as client: + for attempt in range(attempts): + if attempt: + await asyncio.sleep(RETRY_BASE_DELAY * (2 ** (attempt - 1))) + try: + async with client.stream( + Route(method, ""), json=payload, headers=headers, timeout=timeout ) as resp: if ( resp.status == 404 @@ -298,18 +296,18 @@ async def _request_json( raise last_exc await raise_for_status(resp, job_id=job_id) return await resp.json() - except AppHTTPError as exc: - if (exc.status == 404 and retry_not_found) or ( - exc.status in RETRYABLE_STATUSES and retry_transient - ): + except AppHTTPError as exc: + if (exc.status == 404 and retry_not_found) or ( + exc.status in RETRYABLE_STATUSES and retry_transient + ): + last_exc = exc + continue + raise + except (TimeoutError, aiohttp.ClientConnectionError) as exc: + if not retry_transient: + raise last_exc = exc continue - raise - except (TimeoutError, aiohttp.ClientConnectionError) as exc: - if not retry_transient: - raise - last_exc = exc - continue if last_exc is None: # pragma: no cover - loop always runs once raise RuntimeError("request retry loop exited cleanly") raise last_exc @@ -407,7 +405,7 @@ async def _wait_terminal( await asyncio.sleep(interval) interval = min(interval * 1.5, max_interval) data = await _get_json( - f"{base_url}/status/{job_id}", + Route("GET", "/status/{job_id}", job_id=job_id).url(base_url), headers, 30.0, app_name=app_name, @@ -444,7 +442,7 @@ def __init__( @property def base_url(self) -> str: - return f"{_endpoint_url_base()}/{self.endpoint_id}" + return endpoint_base_url(self.endpoint_id) async def _call( self, @@ -452,17 +450,19 @@ async def _call( path: str, payload: Any = None, timeout: float = DEFAULT_TIMEOUT_SECONDS, + *, + job_id: str | None = None, ) -> dict[str, Any]: return await _request_json( method, - f"{self.base_url}/{path}", + Route(method, path).url(self.base_url), self._headers(), timeout, payload=payload, app_name=self._app_name, resource_name=self._resource_name, retry_not_found=path.startswith("status/"), - job_id=_job_id_from_path(path), + job_id=job_id if job_id is not None else _job_id_from_path(path), ) async def run( @@ -510,13 +510,24 @@ async def invoke( ) async def status(self, job_id: str) -> dict[str, Any]: - return await self._call("GET", f"status/{job_id}") + return await self._call( + "GET", Route("GET", "status/{job_id}", job_id=job_id).resolved_path, + job_id=job_id, + ) async def cancel(self, job_id: str) -> dict[str, Any]: - return await self._call("POST", f"cancel/{job_id}") + return await self._call( + "POST", + Route("POST", "cancel/{job_id}", job_id=job_id).resolved_path, + job_id=job_id, + ) async def retry(self, job_id: str) -> dict[str, Any]: - return await self._call("POST", f"retry/{job_id}") + return await self._call( + "POST", + Route("POST", "retry/{job_id}", job_id=job_id).resolved_path, + job_id=job_id, + ) async def stream(self, job_id: str, *, timeout: float) -> AsyncIterator[Any]: """yield partial outputs from /stream until the job is terminal. @@ -532,7 +543,11 @@ async def stream(self, job_id: str, *, timeout: float) -> AsyncIterator[Any]: raise TimeoutError( f"job {job_id} stream did not complete within {timeout}s" ) - data = await self._call("GET", f"stream/{job_id}") + data = await self._call( + "GET", + Route("GET", "stream/{job_id}", job_id=job_id).resolved_path, + job_id=job_id, + ) if data.get("status") == "FAILED" or data.get("error"): unwrap_job_output(data) for chunk in data.get("stream") or []: @@ -570,11 +585,14 @@ async def http( ) -> Any: """plain http call through the endpoint's lb subdomain.""" require_json_value(body, "api request body must be JSON-serializable") - url = f"https://{self.endpoint_id}.{_lb_domain()}{path}" - client_timeout = aiohttp.ClientTimeout(total=timeout) - async with aiohttp.ClientSession(timeout=client_timeout) as session: - async with session.request( - method, url, json=body, headers=self._headers() + async with HTTPClient( + base_url=load_balancer_base_url(self.endpoint_id) + ) as client: + async with client.stream( + Route(method, path), + json=body, + headers=self._headers(), + timeout=timeout, ) as resp: if resp.status == 404 and self._app_name: raise EndpointNotFound(self._app_name, self._resource_name) @@ -719,7 +737,9 @@ async def _sync_source(self, timeout: float) -> None: digest = hashlib.sha256(source.encode()).hexdigest() if digest == self._synced_hash: return - url = f"https://{self.endpoint_id}.{_lb_domain()}/_runpod/sync" + url = Route("POST", "/_runpod/sync").url( + load_balancer_base_url(self.endpoint_id) + ) payload: dict[str, Any] = { "source": source, "resource": self._source_resource, @@ -905,6 +925,10 @@ def _validate_task_payload(payload: dict[str, Any]) -> None: class _TaskTarget(InvocationTarget): """shared execution, result collection, and cleanup for task targets.""" + resource_name: str + hardware: str + events: object | None + @abstractmethod def _execution(self, payload, timeout=None): raise NotImplementedError @@ -994,7 +1018,7 @@ class PodTarget(_TaskTarget): def __init__( self, spec: ResourceSpec, - fn: Callable, + fn: Callable | None, events: object | None = None, *, specs: list[ResourceSpec] | None = None, @@ -1004,7 +1028,9 @@ def __init__( self.events = events self.specs = specs self.resource_name = spec.name - self.hardware = ",".join(spec.cpu or spec.gpu or ["any"]) + self.hardware = ",".join( + normalize_cpu(spec.cpu) or normalize_gpu(spec.gpu) or ["any"] + ) def _execution(self, payload, timeout=None): from .tasks import TaskExecution diff --git a/runpod/apps/tasks.py b/runpod/apps/tasks.py index f762bdb65..90c04eb4e 100644 --- a/runpod/apps/tasks.py +++ b/runpod/apps/tasks.py @@ -19,12 +19,13 @@ import aiohttp -from .._hosts import proxy_url +from ..api.http import HTTPClient +from ..api.routes import Route, pod_proxy_base_url from ..user_agent import APPS_USER_AGENT from .api import AppsApiClient, is_capacity_error from .context import CLEANUP_TIMEOUT from .invoker import Invoker -from .spec import ResourceSpec +from .spec import ResourceSpec, normalize_gpu from .utils.http import raise_for_status log = logging.getLogger(__name__) @@ -36,7 +37,7 @@ RESULT_POLL_INTERVAL = 2.0 DELETE_ATTEMPTS = 3 DELETE_TIMEOUT = 5.0 -_pending_cleanups = set() +_pending_cleanups: set[asyncio.Task[None]] = set() def _validate_timeout(timeout): @@ -117,8 +118,9 @@ def _device_names(gpu: list[str] | None) -> list[str]: return names -def _proxy_url(pod_id: str) -> str: - return proxy_url(pod_id, TASK_PORT) +def _proxy_url(pod_id: str | None) -> str: + assert pod_id is not None + return pod_proxy_base_url(pod_id, TASK_PORT) def _pod_input(spec: ResourceSpec, token: str, task_name: str) -> dict[str, Any]: @@ -162,13 +164,15 @@ def _pod_input(spec: ResourceSpec, token: str, task_name: str) -> dict[str, Any] from .datacenter import CPU3_DATACENTERS, CPU5_DATACENTERS, DEFAULT_DATACENTERS if spec.is_cpu: - pool = dict.fromkeys( - dc - for instance in spec.cpu or [] - for dc in ( - CPU5_DATACENTERS - if instance.startswith("cpu5") - else CPU3_DATACENTERS + pool = list( + dict.fromkeys( + dc + for instance in spec.cpu or [] + for dc in ( + CPU5_DATACENTERS + if instance.startswith("cpu5") + else CPU3_DATACENTERS + ) ) ) else: @@ -177,7 +181,7 @@ def _pod_input(spec: ResourceSpec, token: str, task_name: str) -> dict[str, Any] if spec.is_cpu: pod["instanceIds"] = spec.cpu else: - pod["gpuTypeIdList"] = _device_names(spec.gpu) + pod["gpuTypeIdList"] = _device_names(normalize_gpu(spec.gpu)) pod["gpuCount"] = spec.gpu_count if min_cuda_version := spec.effective_min_cuda_version: pod["minCudaVersion"] = min_cuda_version @@ -200,14 +204,12 @@ def _headers(self) -> dict[str, str]: async def wait_ready(self, timeout: float = READY_TIMEOUT) -> None: """poll the runner's /ping through the pod proxy until it answers.""" - url = f"{_proxy_url(self.pod_id)}/ping" deadline = time.monotonic() + timeout - async with aiohttp.ClientSession() as session: + async with HTTPClient(base_url=_proxy_url(self.pod_id)) as client: while time.monotonic() < deadline: try: - async with session.get( - url, - timeout=aiohttp.ClientTimeout(total=5), + async with client.stream( + Route("GET", "/ping"), timeout=5, headers={"User-Agent": APPS_USER_AGENT}, ) as resp: if resp.status == 200: @@ -261,15 +263,14 @@ async def _post(self, path: str, request: dict[str, Any]) -> None: timeout = request.get("timeout") _validate_timeout(timeout) require_json_value(request, "task request body must be JSON-serializable") - url = f"{_proxy_url(self.pod_id)}{path}" attempts = 6 - async with aiohttp.ClientSession() as session: + async with HTTPClient(base_url=_proxy_url(self.pod_id)) as client: for attempt in range(attempts): - async with session.post( - url, + async with client.stream( + Route("POST", path), json=request, headers=self._headers, - timeout=aiohttp.ClientTimeout(total=30), + timeout=30, ) as resp: if resp.status == 404 and attempt < attempts - 1: await asyncio.sleep(2 * (attempt + 1)) @@ -295,15 +296,14 @@ async def poll_result(self) -> dict[str, Any] | None: retried briefly; a persistent 404 means the pod is gone and surfaces as an error. """ - url = f"{_proxy_url(self.pod_id)}/result" attempts = 6 data: dict[str, Any] = {} - async with aiohttp.ClientSession() as session: + async with HTTPClient(base_url=_proxy_url(self.pod_id)) as client: for attempt in range(attempts): - async with session.get( - url, + async with client.stream( + Route("GET", "/result"), headers=self._headers, - timeout=aiohttp.ClientTimeout(total=30), + timeout=30, ) as resp: if resp.status == 404 and attempt < attempts - 1: await asyncio.sleep(2 * (attempt + 1)) diff --git a/runpod/apps/utils/http.py b/runpod/apps/utils/http.py index 19768fbd3..925c86331 100644 --- a/runpod/apps/utils/http.py +++ b/runpod/apps/utils/http.py @@ -17,13 +17,13 @@ async def raise_for_status( response: aiohttp.ClientResponse, *, job_id: str | None = None ) -> None: - if response.status < 400: + if response.status < 300: return secrets = set() for item in (*response.history, response): - url = item.request_info.real_url - for name, value in url.query.items(): + request_url = item.request_info.real_url + for name, value in request_url.query.items(): if name.lower() == "sig" or any( word in name.lower() for word in ( @@ -37,7 +37,9 @@ async def raise_for_status( ) ): secrets.add(value) - secrets.update(value for value in (url.user, url.password) if value) + secrets.update( + value for value in (request_url.user, request_url.password) if value + ) for name, value in item.request_info.headers.items(): if any( word in name.lower() @@ -51,7 +53,7 @@ async def raise_for_status( part.partition("=")[2].strip() for part in value.split(";") ) - sensitive = set() + sensitive: set[str] = set() for value in secrets: if value: sensitive.update( diff --git a/runpod/apps/utils/network.py b/runpod/apps/utils/network.py index 88f2ff029..f117b1c3e 100644 --- a/runpod/apps/utils/network.py +++ b/runpod/apps/utils/network.py @@ -3,8 +3,8 @@ import os from typing import Any -import aiohttp - +from ...api.http import HTTPClient +from ...api.routes import Route, endpoint_base_url from ...error import NOT_LOGGED_IN from ...user_agent import APPS_USER_AGENT from .http import raise_for_status @@ -19,20 +19,21 @@ def runtime_headers() -> dict[str, str] | None: pod = os.getenv("RUNPOD_POD_ID") if os.getenv("RUNPOD_RUNTIME_KIND") == "task": endpoint = None - if not endpoint and not pod: + source = endpoint or pod + if not source: raise RuntimeError("production flash runtime source identity is missing") key = os.getenv("RUNPOD_AI_API_KEY" if endpoint else "RUNPOD_API_KEY") if not key or key != key.strip(): raise RuntimeError("production flash runtime credential is missing") - if (endpoint or pod) != (endpoint or pod).strip(): + if source != source.strip(): raise RuntimeError("production flash runtime source identity is malformed") return { "Authorization": f"Bearer {key}", - "X-RunPod-Endpoint-Id" if endpoint else "X-RunPod-Pod-Id": endpoint or pod, + "X-RunPod-Endpoint-Id" if endpoint else "X-RunPod-Pod-Id": source, } -def validate_runtime_target(app_name: str, env_name: str) -> None: +def validate_runtime_target(app_name: object, env_name: object) -> None: from ..context import deployed_identity identity = deployed_identity() @@ -54,16 +55,14 @@ def api_key() -> str: def endpoint_url_base() -> str: - import runpod - - return runpod.endpoint_url_base.rstrip("/") + return endpoint_base_url() async def get_json(url: str, headers: dict[str, str], timeout: float) -> dict[str, Any]: - client_timeout = aiohttp.ClientTimeout(total=timeout) - async with aiohttp.ClientSession(timeout=client_timeout) as session: - async with session.get( - url, headers={**headers, "User-Agent": APPS_USER_AGENT} - ) as response: - await raise_for_status(response) - return await response.json() + async with HTTPClient(base_url=url).stream( + Route("GET", ""), + headers={**headers, "User-Agent": APPS_USER_AGENT}, + timeout=timeout, + ) as response: + await raise_for_status(response) + return await response.json() diff --git a/runpod/apps/volume.py b/runpod/apps/volume.py index 442da5c60..3ff8b1a61 100644 --- a/runpod/apps/volume.py +++ b/runpod/apps/volume.py @@ -10,6 +10,7 @@ from typing import Any from ..user_agent import APPS_USER_AGENT +from ._stock import StockSource from .errors import AppError from .utils.client import default_client from .utils.events import emit @@ -202,7 +203,7 @@ def __repr__(self) -> str: return f"" -def _mount_path(path: str) -> str: +def _mount_path(path: object) -> str: if ( not isinstance(path, str) or not path.startswith("/") @@ -259,16 +260,20 @@ def _configure_mounts(bindings: list[dict[str, str]]) -> None: """install resolved mounts for this worker before importing user code.""" if not isinstance(bindings, list): raise VolumeError("worker mount bindings must be a list") - resolved = {} + resolved: dict[tuple[str, str], list[Path]] = {} for binding in bindings: if not isinstance(binding, Mapping): raise VolumeError("worker mount bindings must be objects") kind = binding.get("kind") reference = binding.get("reference") volume_id = binding.get("id") - if kind not in ("network", "global") or any( - not isinstance(value, str) or not value.strip() - for value in (reference, volume_id) + if ( + not isinstance(kind, str) + or kind not in ("network", "global") + or not isinstance(reference, str) + or not reference.strip() + or not isinstance(volume_id, str) + or not volume_id.strip() ): raise VolumeError("worker mount bindings require kind, reference, and id") path = Path(_mount_path(binding.get("path"))) @@ -294,7 +299,7 @@ def __init__(self, api=None, events: object | None = None): self._resolved: dict[tuple[str, str], dict[str, Any]] = {} self.created_volumes: list[dict[str, str]] = [] self._planned: dict[tuple[str, str], tuple[dict[str, Any], list]] = {} - self._stock = None + self._stock: StockSource | None = None self._volume_datacenters: set[str] | None = None async def _client(self): @@ -328,6 +333,7 @@ async def resolve( ) log.info("created global volume %s (%s)", volume.name, record["id"]) else: + assert isinstance(volume, NetworkVolume) dc = planned["dataCenterId"] record = await client.create_network_volume( name=volume.name, size=volume.size, data_center_id=dc @@ -351,7 +357,7 @@ async def preflight( self, specs: list, *, keys: set[tuple[str, str]] | None = None ) -> None: """plan selected volumes and their sharing constraints before provisioning.""" - volumes = {} + volumes: dict[tuple[str, str], tuple[Volume, list[object]]] = {} for spec in specs: if keys is not None and not any( (volume.kind, volume.reference) in keys diff --git a/runpod/auth/__init__.py b/runpod/auth/__init__.py new file mode 100644 index 000000000..d6238d14d --- /dev/null +++ b/runpod/auth/__init__.py @@ -0,0 +1,28 @@ +"""shared api key selection for the sdk and cli.""" + +import os + + +def load_api_key(profile: str = "default"): + """load the environment key or the selected credential profile.""" + key = os.environ.get("RUNPOD_API_KEY") + if key: + return key + try: + from .credentials import get_credentials + + credentials = get_credentials(profile) + except Exception: + return None + return credentials.get("api_key") if credentials else None + + +def resolve_api_key(api_key=None) -> str: + """select an explicit key or the sdk's configured key.""" + import runpod + from runpod.error import AuthenticationError + + key = api_key or runpod.api_key + if not key: + raise AuthenticationError("No API key provided") + return key diff --git a/runpod/auth/api.py b/runpod/auth/api.py new file mode 100644 index 000000000..3b3fac5be --- /dev/null +++ b/runpod/auth/api.py @@ -0,0 +1,43 @@ +"""account authentication requests and api key verification.""" + +from runpod.api.graphql import run_graphql_query_async +from runpod.api.queries.user import QUERY_USER +from runpod.error import AuthenticationError, QueryError +from runpod.user_agent import APPS_USER_AGENT + + +class AuthApiClient: + """browser approval and credential verification transport.""" + + async def create_auth_request(self) -> dict: + response = await run_graphql_query_async( + """mutation createFlashAuthRequest { + createFlashAuthRequest { id status expiresAt } + }""", + anonymous=True, + headers={"User-Agent": APPS_USER_AGENT}, + ) + return response["data"].get("createFlashAuthRequest") or {} + + async def get_auth_request_status(self, request_id: str) -> dict: + response = await run_graphql_query_async( + """query flashAuthRequestStatus($flashAuthRequestId: String!) { + flashAuthRequestStatus(flashAuthRequestId: $flashAuthRequestId) { + id status + } + }""", + variables={"flashAuthRequestId": request_id}, + anonymous=True, + headers={"User-Agent": APPS_USER_AGENT}, + ) + return response["data"].get("flashAuthRequestStatus") or {} + + async def verify_api_key(self, api_key: str) -> bool: + try: + response = await run_graphql_query_async( + QUERY_USER, api_key=api_key, headers={"User-Agent": APPS_USER_AGENT} + ) + except (AuthenticationError, QueryError): + return False + myself = (response.get("data") or {}).get("myself") or {} + return bool(myself.get("id")) diff --git a/runpod/cli/groups/config/functions.py b/runpod/auth/credentials.py similarity index 96% rename from runpod/cli/groups/config/functions.py rename to runpod/auth/credentials.py index d12974363..559acdcbe 100644 --- a/runpod/cli/groups/config/functions.py +++ b/runpod/auth/credentials.py @@ -1,9 +1,4 @@ -""" -runpod | cli | config.py - -A collection of functions to set and validate configurations. -Configurations are TOML files located under ~/.runpod/ -""" +"""credential profiles stored in ~/.runpod/config.toml.""" import os import tempfile diff --git a/runpod/auth/login.py b/runpod/auth/login.py new file mode 100644 index 000000000..c3b326c91 --- /dev/null +++ b/runpod/auth/login.py @@ -0,0 +1,260 @@ +"""browser-approval and email-verification login flows.""" + +import base64 +import datetime as dt +import hashlib +import json +import os +import secrets +import tempfile +from collections.abc import Callable +from pathlib import Path +from typing import Any +from uuid import uuid4 + +import aiohttp + +from runpod._hosts import console_url +from runpod.api.http import HTTPClient +from runpod.api.routes import Route +from runpod.user_agent import APPS_USER_AGENT + +from ..error import AppError, AuthenticationError, QueryError +from .api import AuthApiClient + +MAX_KEY_ATTEMPTS = 3 + +_CLOSED_REASONS = { + "DENIED": "login was denied in the browser", + "EXPIRED": "login request expired", +} + + +class LoginError(AuthenticationError, AppError): + pass + + +class _VerificationCodeRejected(LoginError): + pass + + +async def _post_authentication_attempt( + session: HTTPClient, + route: Route, + body: dict, + *, + creating: bool = False, +) -> dict: + try: + async with session.stream( + route, + json=body, + headers={"Idempotency-Key": str(uuid4())} if creating else {}, + allow_redirects=False, + ) as response: + if response.status != (201 if creating else 200): + if response.status == 403: + raise LoginError( + "email sign-in is not allowed for this account; sign in " + "through the console and use runpod login --api-key" + ) + if response.status == 404: + if creating: + raise LoginError("email sign-in is unavailable on this API") + raise LoginError( + "login attempt expired, was already used, or is locked; " + "start login again" + ) + if response.status == 422: + if creating: + raise LoginError( + "email sign-in request rejected; check --email" + ) + raise _VerificationCodeRejected("verification code rejected") + if response.status == 429: + raise LoginError( + "too many login attempts; wait before trying again" + ) + raise LoginError(f"email sign-in failed (HTTP {response.status})") + payload = await response.json() + except (TimeoutError, aiohttp.ClientError): + raise LoginError( + "could not complete email sign-in; check your connection" + ) from None + except ValueError: + raise LoginError("invalid response from the email sign-in API") from None + + if not isinstance(payload, dict): + raise LoginError("invalid response from the email sign-in API") + return payload + + +def pending_agent_login_path(profile: str) -> Path: + from runpod.auth.credentials import CREDENTIAL_FILE + + profile_id = hashlib.sha256(profile.encode("utf-8")).hexdigest() + return Path(CREDENTIAL_FILE).parent / f"login-{profile_id}.json" + + +def save_agent_login(attempt: dict, profile: str) -> None: + path = pending_agent_login_path(profile) + path.parent.mkdir(mode=0o700, parents=True, exist_ok=True) + fd, temporary = tempfile.mkstemp(dir=path.parent, suffix=".json") + try: + with os.fdopen(fd, "w", encoding="utf-8") as pending: + json.dump(attempt, pending) + os.replace(temporary, path) + except BaseException: + os.unlink(temporary) + raise + + +def load_agent_login(profile: str) -> dict: + try: + attempt = json.loads( + pending_agent_login_path(profile).read_text(encoding="utf-8") + ) + except FileNotFoundError: + raise LoginError( + "no pending login for this profile. Run runpod login --agent --email ADDRESS" + ) from None + except ValueError: + raise LoginError( + "invalid pending login. Run runpod login --agent --email ADDRESS to request a new code" + ) from None + if not isinstance(attempt, dict) or any( + not isinstance(attempt.get(field), str) or not attempt[field] + for field in ("attempt_id", "verifier", "api_url") + ): + raise LoginError( + "invalid pending login. Run runpod login --agent --email ADDRESS to request a new code" + ) + return attempt + + +def _agent_session() -> HTTPClient: + return HTTPClient( + headers={"Accept": "application/json", "User-Agent": APPS_USER_AGENT}, + ) + + +async def start_agent_login(email: str) -> dict: + """request an emailed code and return its proof-of-possession state.""" + verifier = secrets.token_urlsafe(32) + challenge = ( + base64.urlsafe_b64encode(hashlib.sha256(verifier.encode("ascii")).digest()) + .decode("ascii") + .rstrip("=") + ) + route = Route("POST", "/v2/signup/authentication-attempts") + + async with _agent_session() as session: + attempt = await _post_authentication_attempt( + session, + route, + {"email": email, "keyName": "runpod-cli-agent", "codeChallenge": challenge}, + creating=True, + ) + attempt_id = attempt.get("attemptId") + if not isinstance(attempt_id, str) or not attempt_id: + raise LoginError("auth attempt failed to initialize") + + return {"attempt_id": attempt_id, "verifier": verifier, "api_url": route.url()} + + +async def verify_agent_login(attempt: dict, code: str) -> str: + """exchange a code and its saved verifier for an api key.""" + if attempt["api_url"] != Route("POST", "/v2/signup/authentication-attempts").url(): + raise LoginError("pending login belongs to a different API. Request a new code") + async with _agent_session() as session: + result = await _post_authentication_attempt( + session, + Route( + "POST", + "/v2/signup/authentication-attempts/{attempt_id}/verify", + attempt_id=attempt["attempt_id"], + ), + {"code": code, "codeVerifier": attempt["verifier"]}, + ) + credential = result.get("credential") + api_key = credential.get("apiKey") if isinstance(credential, dict) else None + if not isinstance(api_key, str) or not api_key.strip(): + raise LoginError("email sign-in response did not contain an API key") + return api_key + + +async def agent_login(email: str, *, read_code: Callable[[], str]) -> str: + """exchange an emailed code for an api key bound to this login's verifier.""" + attempt = await start_agent_login(email) + while True: + code = read_code() + try: + return await verify_agent_login(attempt, code) + except _VerificationCodeRejected: + continue + + +def _parse_expires_at(value: str | None) -> dt.datetime | None: + if not value: + return None + try: + return dt.datetime.fromisoformat(value.replace("Z", "+00:00")) + except ValueError: + return None + + +def auth_url(request_id: str) -> str: + return f"{console_url()}/flash/login?request={request_id}" + + +async def _closed_reason(client: AuthApiClient, request_id: str) -> str | None: + """why the request can no longer produce a key, or None to keep prompting.""" + try: + request = await client.get_auth_request_status(request_id) + except (TimeoutError, QueryError, aiohttp.ClientError, OSError): + return None + status = request.get("status") + return _CLOSED_REASONS.get(status) if status is not None else None + + +async def browser_login( + *, + prompt_key: Callable[[], str], + on_url: Callable[[str], None] | None = None, + on_rejected: Callable[[str], None] | None = None, + api: AuthApiClient | None = None, + max_attempts: int = MAX_KEY_ATTEMPTS, +) -> str: + """run the browser-approval flow and return the pasted api key. + + on_url is called with the approval url as soon as the request is + created (the caller renders/opens it). the console shows the new key + only to the signed-in approver, so the user pastes it via prompt_key. + on_rejected is called with a reason before each re-prompt. + """ + client = api or AuthApiClient() + request: dict[str, Any] = await client.create_auth_request() + request_id = request.get("id") + + if not request_id: + raise LoginError("auth request failed to initialize") + + if on_url is not None: + on_url(auth_url(request_id)) + + reason = "no api key entered" + for attempt in range(max_attempts): + api_key = (prompt_key() or "").strip() + if not api_key: + reason = "no api key entered" + elif await client.verify_api_key(api_key): + return api_key + else: + reason = "api key was rejected" + closed = await _closed_reason(client, request_id) + if closed: + raise LoginError(f"{closed}; run login again") + if on_rejected is not None and attempt < max_attempts - 1: + on_rejected(reason) + + raise LoginError(f"{reason}; run login again") diff --git a/runpod/cli/api.py b/runpod/cli/api.py new file mode 100644 index 000000000..bccc37497 --- /dev/null +++ b/runpod/cli/api.py @@ -0,0 +1,22 @@ +"""pagination and error reporting for rest-backed cli commands.""" + +from contextlib import contextmanager + +import click +from requests import RequestException + +from runpod import error +from runpod.api.rest import run_rest_paginated_request +from runpod.cli.compute import ResolutionError + + +def list_all(path: str, collection: str, params: dict | None = None) -> list[dict]: + return run_rest_paginated_request(path, collection, params=params) + + +@contextmanager +def api_errors(): + try: + yield + except (error.RunPodError, ResolutionError, RequestException, ValueError) as exc: + raise click.ClickException(str(exc)) from exc diff --git a/runpod/cli/catalog.py b/runpod/cli/catalog.py new file mode 100644 index 000000000..4a941942e --- /dev/null +++ b/runpod/cli/catalog.py @@ -0,0 +1,311 @@ +"""`rp catalog`: gpu and cpu pricing and stock search.""" + + +import click +from click.core import ParameterSource + +from runpod.cli import compute +from runpod.cli.api import api_errors +from runpod.cli.output import json_option, print_json, print_table + + +def _money(value: float | None, format_spec: str = ".2f") -> str: + return f"${value:{format_spec}}" if value else "-" + + +def _stock(entries: list[dict]) -> str: + ranked = sorted( + entries, key=lambda dc: -compute.availability_rank(dc["availability"]) + ) + return ", ".join(f"{dc['id']} {dc['availability'].lower()}" for dc in ranked) + + +def _filter_stock(records: list[dict], regions: tuple[str, ...], available: bool): + allowed = ( + set(compute.resolve_regions(regions, compute.list_datacenters())) + if regions + else None + ) + for record in records: + row = dict(record) + if allowed is not None: + row["dataCenters"] = [ + dc for dc in record.get("dataCenters", []) if dc["id"] in allowed + ] + row["availability"] = compute.best_availability( + dc["availability"] for dc in row["dataCenters"] + ) + if not available or compute.availability_rank(row.get("availability")) > 0: + yield row + + +def _unit_price(gpu: dict, product: str, cloud: str | None) -> float | None: + price = gpu["price"] + if product == "SERVERLESS": + return price.get("serverless") or None + if cloud: + return price.get(cloud) or None + offered = [ + value for value in (price.get("secure"), price.get("community")) if value + ] + return min(offered, default=None) + + +def _gpu_rows( + query, product, count, regions, cloud, cuda, min_vram, max_price, available +) -> list[dict]: + min_cuda, exact_cuda = compute.parse_cuda(cuda) + gpus = compute.list_gpus( + product=product, + count=count, + cloud=cloud.upper() if cloud else None, + cuda_versions=exact_cuda, + min_cuda_version=min_cuda, + ) + if query: + gpus = compute.resolve_gpus(query, gpus) + if product == "SERVERLESS": + gpus = [gpu for gpu in gpus if gpu.get("pool")] + rows = [] + for row in _filter_stock(gpus, regions, available): + unit = _unit_price(row, product, cloud) + if min_vram and row["memory"] < min_vram: + continue + if max_price is not None and (unit is None or unit > max_price): + continue + row["count"] = count + row["totalPrice"] = { + tier: round(value * count, 4) if value else None + for tier, value in row["price"].items() + } + rows.append(row) + rows.sort( + key=lambda row: ( + -compute.availability_rank(row.get("availability")), + _unit_price(row, product, cloud) or float("inf"), + row["name"], + ) + ) + return rows + + +def _gpu_columns(product: str, count: int, cloud: str | None): + suffix = f" x{count}" if count > 1 else "" + columns = [ + ("GPU", lambda row: row["name"]), + ("VRAM", lambda row: f"{row['memory']}GB"), + ] + if product == "SERVERLESS": + columns += [ + ("POOL", lambda row: row["pool"]), + (f"$/HR{suffix}", lambda row: _money(row["totalPrice"].get("serverless"))), + ] + else: + tiers = [cloud] if cloud else ["secure", "community"] + for tier in tiers: + + def price(row: dict, tier: str = tier) -> str: + return _money(row["totalPrice"].get(tier)) + + columns.append( + ( + f"{tier.upper()} $/HR{suffix}", + price, + ) + ) + columns.append( + ( + "MAX", + lambda row: ( + row["maxCount"].get(cloud) + if cloud + else max(row["maxCount"].values(), default=None) + ), + ) + ) + columns += [ + ("STOCK", lambda row: (row.get("availability") or "NONE").lower()), + ("DATA CENTERS", lambda row: _stock(row.get("dataCenters") or [])), + ] + return columns + + +def _cpu_rows(query, product, vcpu, regions, available) -> list[dict]: + cpus = compute.list_cpus(product=product, vcpu_count=vcpu) + if query: + cpus = compute.match_cpus(query, cpus) + if not cpus: + raise compute.ResolutionError(f"unknown cpu '{query}'") + return sorted( + _filter_stock(cpus, regions, available), + key=lambda row: -compute.availability_rank(row.get("availability")), + ) + + +def _cpu_columns(product: str): + tier = "serverlessPerVcpu" if product == "SERVERLESS" else "securePerVcpu" + return [ + ("CPU", lambda row: row["id"]), + ("NAME", lambda row: row["name"]), + ("GROUP", lambda row: row["group"]), + ("VCPU", lambda row: "{min}-{max}".format(**row["vcpu"])), + ("RAM/VCPU", lambda row: f"{row['ramGbPerVcpu']:g}GB"), + ("$/VCPU-HR", lambda row: _money(row["price"].get(tier), ".4g")), + ("STOCK", lambda row: (row.get("availability") or "NONE").lower()), + ("DATA CENTERS", lambda row: _stock(row.get("dataCenters") or [])), + ] + + +_DATACENTER_COLUMNS = [ + ("DATA CENTER", lambda row: row["id"]), + ("REGION", lambda row: row["region"].lower().replace("_", " ")), + ( + "VOLUME TYPES", + lambda row: [kind.lower() for kind in row["networkVolumeTypes"]], + ), + ("GLOBAL NETWORK", lambda row: row["globalNetwork"]), + ("COMPLIANCE", lambda row: row["compliance"]), +] + + +@click.command() +@click.argument("query", required=False) +@click.option( + "--pod", + "product", + flag_value="POD", + default=True, + help="Pod pricing and stock (default).", +) +@click.option( + "--serverless", + "product", + flag_value="SERVERLESS", + help="Serverless pricing, pools, and stock.", +) +@click.option( + "--cpu", "cpu_mode", is_flag=True, help="Search CPU flavors instead of GPUs." +) +@click.option( + "--datacenters", is_flag=True, help="List data centers and their regions." +) +@click.option( + "--count", + type=click.IntRange(min=1), + default=1, + show_default=True, + help="GPUs per pod or worker; prices and stock account for it.", +) +@click.option( + "--vcpu", + type=click.IntRange(min=2), + default=None, + help="vCPUs per pod or worker (with --cpu).", +) +@click.option( + "--region", + "regions", + multiple=True, + help="Region (eu, na, asia), id prefix (us, eu-ro), or data center id. Repeatable.", +) +@click.option( + "--cloud", + type=click.Choice(["secure", "community"], case_sensitive=False), + default=None, + help="Pod cloud tier.", +) +@click.option( + "--cuda", + multiple=True, + help="CUDA filter: '>=12.4' for a floor, 12.4 or 12.4,12.8 for exact versions.", +) +@click.option("--min-vram", type=int, default=None, help="Minimum VRAM per GPU in GB.") +@click.option("--max-price", type=float, default=None, help="Maximum USD per GPU-hour.") +@click.option("--available", is_flag=True, help="Only show hardware that is in stock.") +@json_option +def catalog( + query, + product, + cpu_mode, + datacenters, + count, + vcpu, + regions, + cloud, + cuda, + min_vram, + max_price, + available, + as_json, +): # pylint: disable=too-many-arguments + """Search GPU and CPU pricing and stock by data center. + + QUERY is a human-readable GPU (4090, h100, a100-sxm4), a serverless + pool id, or with --cpu a CPU flavor. + + \b + rp catalog h100 --count 2 --region eu --cuda '>=12.4' + rp catalog 4090 --serverless + rp catalog --cpu --vcpu 8 --available + rp catalog --datacenters --region us + """ + if cpu_mode and datacenters: + raise click.UsageError("use either --cpu or --datacenters") + if datacenters: + mode = "--datacenters" + unsupported = ( + "product", + "count", + "vcpu", + "cloud", + "cuda", + "min_vram", + "max_price", + "available", + ) + elif cpu_mode: + mode = "--cpu" + unsupported = ("count", "cuda", "min_vram", "max_price") + else: + mode = "GPU" + unsupported = ("vcpu",) + ctx = click.get_current_context() + for name in unsupported: + if ctx.get_parameter_source(name) not in (None, ParameterSource.DEFAULT): + option = product.lower() if name == "product" else name.replace("_", "-") + raise click.UsageError(f"--{option} cannot be used in {mode} mode") + if cloud and product == "SERVERLESS": + raise click.UsageError("--cloud applies to pods only") + cloud = cloud.lower() if cloud else None + if cpu_mode and cloud == "community": + raise click.UsageError("--cpu is only available in the secure cloud") + + with api_errors(): + if datacenters: + values = regions + ((query,) if query else ()) + rows = compute.list_datacenters() + if values: + allowed = set(compute.resolve_regions(values, rows)) + rows = [row for row in rows if row["id"] in allowed] + columns, empty = _DATACENTER_COLUMNS, "no data centers match" + elif cpu_mode: + rows = _cpu_rows(query, product, vcpu, regions, available) + columns, empty = _cpu_columns(product), "no cpu flavors match" + else: + rows = _gpu_rows( + query, + product, + count, + regions, + cloud, + cuda, + min_vram, + max_price, + available, + ) + columns, empty = _gpu_columns(product, count, cloud), "no gpus match" + + if as_json: + print_json(rows) + return + print_table(rows, columns, empty) diff --git a/runpod/cli/compute.py b/runpod/cli/compute.py new file mode 100644 index 000000000..f7de4cd5f --- /dev/null +++ b/runpod/cli/compute.py @@ -0,0 +1,268 @@ +"""gpu, cpu, and region resolution against the rest v2 catalog.""" + +import re +from collections.abc import Iterable +from typing import Any + +from runpod.api.rest import run_rest_request +from runpod.error import QueryError + +AVAILABILITY_RANK = {"NONE": 0, "LOW": 1, "MEDIUM": 2, "HIGH": 3} + +REGION_ALIASES = { + "na": "NORTH_AMERICA", + "northamerica": "NORTH_AMERICA", + "sa": "SOUTH_AMERICA", + "southamerica": "SOUTH_AMERICA", + "eu": "EUROPE", + "europe": "EUROPE", + "asia": "ASIA", + "apac": "ASIA", + "me": "MIDDLE_EAST", + "middleeast": "MIDDLE_EAST", + "africa": "AFRICA", + "oceania": "OCEANIA", +} + +_NOISE_TOKENS = {"nvidia", "geforce", "amd", "instinct"} + + +class ResolutionError(ValueError): + """a user-supplied gpu, cpu, or region that does not resolve.""" + + +def _query_params(**values: Any) -> dict[str, Any]: + return { + key: ",".join(value) if isinstance(value, (list, tuple)) else value + for key, value in values.items() + if value is not None and value != [] + } + + +def list_gpus( + product: str | None = None, + count: int | None = None, + cloud: str | None = None, + cuda_versions: list[str] | None = None, + min_cuda_version: str | None = None, +) -> list[dict]: + """gpu types, with availability when a product context is given.""" + params = _query_params( + include="AVAILABILITY" if product else None, + product=product, + count=count if product else None, + cloud=cloud if product else None, + cudaVersions=cuda_versions if product else None, + minCudaVersion=min_cuda_version if product else None, + ) + response = run_rest_request("GET", "/v2/catalog/gpus", params=params) + if response is None: + raise QueryError("empty GPU catalog response") + return response["gpus"] + + +def list_cpus( + product: str | None = None, vcpu_count: int | None = None +) -> list[dict]: + """cpu flavors, with availability when a product context is given.""" + params = _query_params( + include="AVAILABILITY" if product else None, + product=product, + vcpuCount=vcpu_count if product else None, + ) + response = run_rest_request("GET", "/v2/catalog/cpus", params=params) + if response is None: + raise QueryError("empty CPU catalog response") + return response["cpus"] + + +def list_datacenters(include: list[str] | None = None) -> list[dict]: + """every data center in the catalog.""" + response = run_rest_request( + "GET", "/v2/catalog/datacenters", params=_query_params(include=include) + ) + if response is None: + raise QueryError("empty data center catalog response") + return response["dataCenters"] + + +def _tokens(text: str) -> list[str]: + return [token for token in re.split(r"[\s_\-]+", text.lower()) if token] + + +def _compact(text: str) -> str: + return re.sub(r"[\s_\-]+", "", text.lower()) + + +def match_gpus(query: str, gpus: Iterable[dict]) -> list[dict]: + """prefer exact ids, names, and pools, then match hardware-name tokens.""" + gpus = list(gpus) + text = query.strip().lower() + exact = [ + gpu + for gpu in gpus + if text in (gpu["id"].lower(), (gpu.get("name") or "").lower()) + ] + if exact: + return exact + pool = [gpu for gpu in gpus if (gpu.get("pool") or "").lower() == text] + if pool: + return pool + wanted = [token for token in _tokens(text) if token not in _NOISE_TOKENS] + if not wanted: + return [] + hits = [ + gpu + for gpu in gpus + if set(wanted) <= set(_tokens(gpu["id"])) | set(_tokens(gpu.get("name") or "")) + ] + if hits: + return hits + compact = "".join(wanted) + return [gpu for gpu in gpus if compact in _compact(gpu["id"])] + + +def resolve_gpus(query: str, gpus: Iterable[dict]) -> list[dict]: + """like match_gpus, but raise when nothing matches.""" + gpus = list(gpus) + matches = match_gpus(query, gpus) + if not matches: + known = ", ".join(sorted(gpu.get("name") or gpu["id"] for gpu in gpus)) + raise ResolutionError(f"unknown gpu '{query}'. known gpus: {known}") + return matches + + +def parse_gpu_spec(value: str) -> tuple[str, int | None]: + """split "h100:2" into ("h100", 2); a bare name has no count.""" + name, sep, count = value.strip().rpartition(":") + if not sep: + return value.strip(), None + if not name or not count.isdigit() or int(count) < 1: + raise ResolutionError( + f"invalid gpu '{value}'. use a name with an optional count, like h100:2" + ) + return name, int(count) + + +def parse_cuda(values: Iterable[str]) -> tuple[str | None, list[str]]: + """split cuda filters into (minimum, exact versions). + + ">=12.4" sets a floor; "12.4" or "12.4,12.8" lists exact versions. + """ + minimum = None + exact: list[str] = [] + for value in values: + for part in value.split(","): + part = part.strip() + if not part: + continue + floor = part.startswith(">=") + version = part[2:].strip() if floor else part + if not re.fullmatch(r"\d+\.\d+", version): + raise ResolutionError( + f"invalid cuda version '{part}'. use 12.4, 12.4,12.8, or '>=12.4'" + ) + if floor: + if minimum is None or tuple(map(int, version.split("."))) > tuple( + map(int, minimum.split(".")) + ): + minimum = version + else: + exact.append(version) + if minimum and exact: + raise ResolutionError( + "use either a cuda floor (>=) or exact versions, not both" + ) + return minimum, exact + + +def endpoint_gpu_selection( + matches: Iterable[dict], gpus: Iterable[dict] +) -> tuple[list[str], list[str]]: + """serverless (pools, excludedTypes) that select exactly the matched types.""" + matches = list(matches) + pools = list(dict.fromkeys(gpu["pool"] for gpu in matches if gpu.get("pool"))) + if not pools: + names = ", ".join(gpu.get("name") or gpu["id"] for gpu in matches) + raise ResolutionError(f"{names} is not offered on serverless") + chosen = {gpu["id"] for gpu in matches} + excluded = [ + gpu["id"] + for gpu in gpus + if gpu.get("pool") in pools and gpu["id"] not in chosen + ] + return pools, excluded + + +def resolve_regions(values: Iterable[str], datacenters: Iterable[dict]) -> list[str]: + """data center ids named by ids, id prefixes, or region names. + + "EU-RO-1" is one data center, "us" and "eu-ro" match every id with + that prefix, and "eu" or "europe" match every data center in the + region. + """ + datacenters = list(datacenters) + resolved: list[str] = [] + for value in values: + text = value.strip().upper().replace("_", "-") + region = REGION_ALIASES.get(_compact(value)) + matches = [ + dc["id"] + for dc in datacenters + if dc["id"].upper() == text + or dc["id"].upper().startswith(text + "-") + or (region and dc.get("region") == region) + ] + if not matches: + ids = ", ".join(sorted(dc["id"] for dc in datacenters)) + names = ", ".join( + sorted( + { + dc["region"].lower().replace("_", "-") + for dc in datacenters + if dc.get("region") + } + ) + ) + raise ResolutionError( + f"unknown region '{value}'. use a region (eu, na, {names}), " + f"an id prefix like us or eu-ro, or a data center ({ids})" + ) + resolved.extend(match for match in matches if match not in resolved) + return resolved + + +def match_cpus(query: str, cpus: Iterable[dict]) -> list[dict]: + """cpu flavors named by id ("cpu3c"), group ("cpu3"), or name.""" + text = query.strip().lower() + return [ + cpu + for cpu in cpus + if text + in ( + cpu["id"].lower(), + (cpu.get("group") or "").lower(), + (cpu.get("name") or "").lower(), + ) + or _compact(text) == _compact(cpu.get("name") or "") + ] + + +def resolve_cpu(query: str, cpus: Iterable[dict]) -> dict: + """the single cpu flavor a query names.""" + cpus = list(cpus) + matches = match_cpus(query, cpus) + if len(matches) != 1: + known = ", ".join(sorted(cpu["id"] for cpu in cpus)) + problem = "ambiguous" if matches else "unknown" + raise ResolutionError(f"{problem} cpu '{query}'. cpu flavors: {known}") + return matches[0] + + +def availability_rank(level: str | None) -> int: + return AVAILABILITY_RANK.get(level or "NONE", 0) + + +def best_availability(levels: Iterable[str | None]) -> str: + """the highest stock level among levels, NONE when empty.""" + return max(levels, key=availability_rank, default="NONE") or "NONE" diff --git a/runpod/cli/console.py b/runpod/cli/console.py new file mode 100644 index 000000000..5c5bdc449 --- /dev/null +++ b/runpod/cli/console.py @@ -0,0 +1,616 @@ +"""console rendering for the rp cli. + +live, animated lifecycle output: spinner-driven phase tracking for +deploys (with byte-level upload progress), per-resource provisioning +animation for dev sessions, and color-coded resource badges. engine +modules stay renderer-free; they emit duck-typed events and this +module turns them into pixels. +""" + +import time +from collections.abc import Iterable + +from rich.console import Console, RenderableType +from rich.progress import ( + Progress, + SpinnerColumn, + Task, + TaskID, + TextColumn, +) +from rich.spinner import SPINNERS +from rich.text import Text +from rich.theme import Theme + +from runpod._hosts import console_url + +# -- brand ---------------------------------------------------------------- + +ACCENT = "#673de6" # runpod purple +ACCENT_LIGHT = "#a78bfa" +OK = "#34d399" +ERR = "#f87171" +WARN = "#fbbf24" +DIM = "grey58" + +RUNPOD_SAND_SPINNER = "runpod_sand" +RUNPOD_SAND_SPINNER_FRAMES = [ + "⠁", + "⠂", + "⠄", + "⡀", + "⡈", + "⡐", + "⡠", + "⣀", + "⣁", + "⣂", + "⣄", + "⣌", + "⣔", + "⣤", + "⣥", + "⣦", + "⣮", + "⣶", + "⣷", + "⣿", + "⡿", + "⠿", + "⢟", + "⠟", + "⡛", + "⠛", + "⠫", + "⢋", + "⠋", + "⠍", + "⡉", + "⠉", + "⠑", + "⠡", + "⢁", +] +SPINNERS[RUNPOD_SAND_SPINNER] = { + "interval": 1000 / 16, + "frames": RUNPOD_SAND_SPINNER_FRAMES, +} + +KIND_STYLES: dict[str, str] = { + "queue": "bold cyan", + "api": "bold magenta", + "task": "bold yellow", +} + +theme = Theme( + { + "accent": ACCENT, + "accent.light": ACCENT_LIGHT, + "ok": OK, + "err": ERR, + "warn": WARN, + "dim": DIM, + "progress.elapsed": DIM, + } +) + +console = Console(highlight=False, theme=theme) + + +def _spinner_column(finished_text: str = "[ok]✓[/ok]") -> SpinnerColumn: + return SpinnerColumn( + RUNPOD_SAND_SPINNER, + style=ACCENT, + finished_text=finished_text, + ) + + +def endpoint_url(endpoint_id: str) -> str: + return f"{console_url()}/serverless/user/endpoint/{endpoint_id}?tab=overview" + + +def endpoint_link(endpoint_id: str) -> str: + """short clickable endpoint reference (osc8 hyperlink).""" + return ( + f"[link={endpoint_url(endpoint_id)}]" + f"[accent.light]{endpoint_id} ↗[/accent.light][/link]" + ) + + + + +_name_width: int = 0 + + +def set_name_width(names: Iterable[str]) -> None: + global _name_width + _name_width = max((len(n) for n in names), default=0) + + +def _padded(name: str) -> str: + return f"{name:<{_name_width}}" if _name_width else name + + +def _pipe(name: str) -> str: + return f"[accent.light]{_padded(name)}[/accent.light] [dim]│[/dim]" + + +def kind_badge(kind: str) -> str: + style = KIND_STYLES.get(kind, "bold white") + return f"[{style}]{kind:<5}[/{style}]" + + +# -- generic lines --------------------------------------------------------- + + +def info(message: str) -> None: + console.print(f"{message}") + + +def success(message: str) -> None: + console.print(f"[ok]✓[/ok] {message}") + + +def error(message: str) -> None: + console.print(f"[err]✗[/err] {message}") + + +def warn(message: str) -> None: + console.print(f"[warn]![/warn] {message}") + + +def rule(title: str = "") -> None: + console.rule(f"[accent]{title}[/accent]" if title else "", style="dim") + + +# -- request lifecycle ----------------------------------------------------- + + +def request_started(name: str, label: str = "") -> None: + console.print( + f"[bold white]CALL[/bold white] [accent.light]/{name}[/accent.light]" + f" [dim]{label}[/dim]" + ) + + +def request_completed(name: str, elapsed_s: float) -> None: + console.print( + f"[ok]✓[/ok] {_padded(name)} [dim]{elapsed_s:.1f}s[/dim]" + ) + + +def request_failed(name: str, elapsed_s: float, err: str | None = None) -> None: + console.print( + f"[err]✗[/err] {_padded(name)} [dim]{elapsed_s:.1f}s[/dim]" + ) + if err: + console.print(f" [err dim]{err}[/err dim]") + + +# -- banners --------------------------------------------------------------- + + +def dev_banner(app_names: Iterable[str], module: str) -> None: + console.print( + f"[bold white]dev[/bold white] [dim]{', '.join(app_names)} in {module}[/dim]" + ) + + +def deploy_plan(apps: Iterable[tuple[str, str, int]]) -> None: + """upfront summary for multi-app deploys: (name, source, n_resources).""" + apps = list(apps) + console.print( + f"[bold white]deploy[/bold white] [dim]{len(apps)} apps[/dim]" + ) + width = max(len(name) for name, _, _ in apps) + for name, source, count in apps: + detail = f"{source}, " if source else "" + console.print( + f" [white]{name:<{width}}[/white] " + f"[dim]{detail}{count} resource{'s' if count != 1 else ''}[/dim]" + ) + + +def deploy_banner( + app_name: str, + env: str, + resources: Iterable[tuple[str, str]], + source: str = "", +) -> None: + """resources: (name, kind) pairs.""" + names = ", ".join(name for name, _ in resources) or "(no resources)" + origin = f" from {source}" if source else "" + console.print( + f"[bold white]deploy[/bold white] [white]{app_name}[/white] " + f"[dim]→ {env}{origin}, {names}[/dim]" + ) + + +def resources_table(rows: Iterable[tuple]) -> None: + """rows of (name, kind, hardware, endpoint_id).""" + rows = list(rows) + if not rows: + return + w_name = max(len(r[0]) for r in rows) + w_hw = max(len(r[2]) for r in rows) + for name, kind, hardware, endpoint_id in rows: + if endpoint_id == "registered": + tail = "[dim]registered / per-call[/dim]" + elif not endpoint_id or endpoint_id == "per-call": + tail = "[dim]per-call[/dim]" + else: + tail = endpoint_link(endpoint_id) + console.print( + f" [white]{name:<{w_name}}[/white]" + f" {kind_badge(kind)}" + f" [dim]{hardware:<{w_hw}}[/dim]" + f" {tail}" + ) + + +def reload_banner(module: str = "") -> None: + console.print() + detail = f" [dim]{module} changed[/dim]" if module else "" + console.print(f" [accent]↻[/accent] [white]reloading[/white]{detail}") + + +# -- live deploy phases ------------------------------------------------------ + +_PHASE_LABELS = { + "vendor": "resolving dependencies", + "package": "packaging artifact", + "upload": "uploading build", + "endpoints": "deploying endpoints", + "snapshot": "saving current settings", + "activate": "activating build", + "cleanup": "removing unused endpoints", +} + + +_BAR_WIDTH = 22 + + +def _bar(fraction: float) -> str: + """slim one-line progress bar.""" + fraction = min(max(fraction, 0.0), 1.0) + filled = int(fraction * _BAR_WIDTH) + return ( + f"[accent]{'━' * filled}[/accent]" + f"[grey30]{'━' * (_BAR_WIDTH - filled)}[/grey30]" + ) + + +class _DeploySpinnerColumn(SpinnerColumn): + + def render(self, task: Task) -> RenderableType: + if task.fields.get("failed"): + return Text("✗", style="err") + return super().render(task) + + +class DeployEvents: + """deploy_app event sink: animated phase list with live progress. + + each phase renders a spinner while active and collapses to a ✓ with + a short summary when the next begins. vendoring streams package + names as pip resolves them; upload renders a slim in-line bar. + """ + + def __init__(self) -> None: + self._progress = Progress( + _DeploySpinnerColumn( + RUNPOD_SAND_SPINNER, style=ACCENT, finished_text="[ok]✓[/ok]" + ), + TextColumn("[white]{task.description}[/white]"), + TextColumn("{task.fields[detail]}"), + console=console, + transient=False, + ) + self._current: TaskID | None = None + self._current_name = "" + self._started = False + self._package_count = 0 + self._upload_total = 0 + + def _ensure_started(self) -> None: + if not self._started: + self._progress.start() + self._started = True + + def _finish_current(self) -> None: + if self._current is None: + return + # collapse the live detail into a short summary + if self._current_name == "vendor" and self._package_count: + summary = f"{self._package_count} packages" + elif self._current_name == "upload" and self._upload_total: + summary = f"{self._upload_total / 1048576:.1f} MB" + else: + summary = "" + self._progress.update( + self._current, + detail=f"[dim]{summary}[/dim]", + total=1, + completed=1, + ) + self._current = None + + def phase(self, name: str, detail: str = "") -> None: + self._ensure_started() + self._finish_current() + self._current_name = name + self._current = self._progress.add_task( + _PHASE_LABELS.get(name, name), + detail=f"[dim]{detail}[/dim]" if detail else "", + total=None, + ) + + def vendor_progress(self, count: int, package: str) -> None: + if self._current is None: + return + self._package_count = count + self._progress.update( + self._current, + detail=f"[accent.light]{package}[/accent.light] [dim]({count})[/dim]", + ) + + def upload_progress(self, sent: int, total: int) -> None: + if self._current is None: + return + self._upload_total = total + mb = 1048576 + self._progress.update( + self._current, + detail=( + f"{_bar(sent / total)} " + f"[dim]{sent / mb:.1f} / {total / mb:.1f} MB[/dim]" + ), + ) + + def endpoint_ready(self, name: str, endpoint_id: str) -> None: + # collected, not printed: endpoint urls render in the final + # summary after the progress display stops + self.endpoints: dict[str, str] = getattr(self, "endpoints", {}) + self.endpoints[name] = endpoint_id + + def close(self, *, failed: bool = False) -> None: + if failed and self._current is not None: + self._progress.update(self._current, failed=True, detail="") + self._progress.stop_task(self._current) + self._current = None + else: + self._finish_current() + if self._started: + self._progress.stop() + self._started = False + + +# -- live dev provisioning ---------------------------------------------------- + + +class DevEvents: + """DevSession event sink. + + provisioning renders transient spinner rows that vanish once the + session is up (the resource table is the durable record). request + lifecycle renders as a block: an accent dispatch line, a dim + indented worker feed, and a check/cross verdict. + """ + + def __init__(self) -> None: + self._progress: Progress | None = None + self._tasks: dict[str, TaskID] = {} + + def session_starting(self) -> None: + self._progress = Progress( + _spinner_column(), + TextColumn("[white]{task.description}[/white]"), + TextColumn("[dim]{task.fields[detail]}[/dim]"), + console=console, + transient=True, + ) + self._progress.start() + + def session_started(self) -> None: + if self._progress is not None: + self._progress.stop() + self._progress = None + self._tasks.clear() + + def _row(self, name: str, detail: str) -> None: + if self._progress is None: + info(f"{_pipe(name)} {detail}") + return + if name not in self._tasks: + self._tasks[name] = self._progress.add_task( + _padded(name), detail=detail, total=None + ) + else: + self._progress.update(self._tasks[name], detail=detail) + + def provisioning(self, name: str, kind: str, hardware: str) -> None: + self._row(name, f"provisioning {kind} on {hardware}") + + def adopted(self, name: str, endpoint_id: str) -> None: + self._row(name, "adopting") + + def ready(self, name: str, endpoint_id: str) -> None: + if self._progress is not None and name in self._tasks: + self._progress.update( + self._tasks[name], detail="ready", total=1, completed=1 + ) + + def deleted(self, name: str) -> None: + console.print(f" [dim]− {name}[/dim]") + + # -- refresh diff -- + + def resource_added(self, name: str, kind: str, hardware: str) -> None: + console.print( + f" [ok]+[/ok] [white]{name}[/white] " + f"[dim]{kind} on {hardware}[/dim]" + ) + + def resource_changed(self, name: str, fields: list[str]) -> None: + what = ", ".join(fields) if fields else "config" + console.print( + f" [warn]~[/warn] [white]{name}[/white] [dim]{what}[/dim]" + ) + + def resource_removed(self, name: str) -> None: + console.print(f" [err]−[/err] [white]{name}[/white]") + + # -- request lifecycle (LiveTarget events) -- + # next.js/wrangler-style event lines: leading status glyph, the + # function call in normal weight, everything else dim, timing at + # the end. function stdout renders as `name │ line` so concurrent + # calls interleave without losing attribution. + + def dispatch(self, name: str, label: str = "") -> None: + detail = f" [dim]{label}[/dim]" if label else "" + console.print(f" [accent]→[/accent] [white]{name}()[/white]{detail}") + + def worker_status(self, name: str, counts: dict[str, int]) -> None: + from runpod.apps.monitor import format_worker_counts + + console.print( + f" [dim]↳ {name}() waiting: {format_worker_counts(counts)}[/dim]" + ) + + def task_status(self, name: str, detail: str) -> None: + console.print(f" [dim]↳ {name}() {detail}[/dim]") + + def volume_created(self, name: str, size: int, dc: str) -> None: + console.print( + f" [ok]+[/ok] [white]volume {name}[/white] [dim]{size}GB in {dc}[/dim]" + ) + + def worker_ready(self, name: str, worker_id: str) -> None: + worker = worker_id[:12] if worker_id else "pod" + console.print( + f" [accent]↳[/accent] [white]{name}()[/white] [dim]worker " + f"{worker} ready[/dim]" + ) + + def worker_log(self, name: str, line: str) -> None: + from rich.markup import escape + + console.print(f" {_pipe(name)} {escape(line)}") + + def request_completed(self, name: str, elapsed_s: float) -> None: + console.print( + f" [ok]✓[/ok] [white]{name}()[/white] " + f"[dim]in {_fmt_elapsed(elapsed_s)}[/dim]" + ) + + def request_failed(self, name: str, elapsed_s: float) -> None: + console.print( + f" [err]✗[/err] [white]{name}()[/white] " + f"[dim]failed in {_fmt_elapsed(elapsed_s)}[/dim]" + ) + + +class CleanupEvents: + """session teardown sink: one spinner line with delete progress.""" + + def __init__(self) -> None: + self._progress: Progress | None = None + self._task: TaskID | None = None + self._total = 0 + self._done = 0 + + def cleanup_started(self, total: int) -> None: + self._total = total + if total == 0: + return + console.print() + self._progress = Progress( + _spinner_column(), + TextColumn("[white]{task.description}[/white]"), + TextColumn("[dim]{task.fields[detail]}[/dim]"), + console=console, + ) + self._progress.start() + self._task = self._progress.add_task( + "cleaning up", detail="", total=total + ) + + def deleting(self, name: str) -> None: + if self._progress is not None and self._task is not None: + self._progress.update( + self._task, detail=f"{name} ({self._done}/{self._total})" + ) + + def deleted(self, name: str) -> None: + self._done += 1 + if self._progress is not None and self._task is not None: + self._progress.update( + self._task, + completed=self._done, + detail=f"{name} ({self._done}/{self._total})", + ) + + def delete_failed(self, name: str) -> None: + self._done += 1 + if self._progress is not None and self._task is not None: + self._progress.update(self._task, completed=self._done) + console.print(f" [warn]![/warn] [dim]could not delete {name}[/dim]") + + def close(self) -> None: + if self._progress is not None and self._task is not None: + self._progress.update( + self._task, + completed=self._total, + detail=f"{self._done} deleted", + ) + self._progress.stop() + self._progress = None + + +class Timer: + """context timer for elapsed reporting.""" + + def __enter__(self) -> "Timer": + self._start = time.monotonic() + return self + + def __exit__(self, *exc) -> None: + self.elapsed = time.monotonic() - self._start + + @property + def so_far(self) -> float: + return time.monotonic() - self._start + + +def _fmt_elapsed(elapsed: float) -> str: + if elapsed < 1: + return f"{elapsed * 1000:.0f}ms" + if elapsed < 120: + return f"{elapsed:.1f}s" + return f"{int(elapsed // 60)}m{int(elapsed % 60):02d}s" + + +def entrypoint_header(fn_name: str = "") -> None: + console.print() + if fn_name: + console.print( + f" [accent]◆[/accent] [white]{fn_name}()[/white] " + f"[dim]local entrypoint[/dim]" + ) + + +def entrypoint_success(elapsed: float) -> None: + console.print() + console.print( + f" [ok]✓[/ok] [white]done[/white] [dim]in {_fmt_elapsed(elapsed)}, " + f"enter re-run, edit reload, ^C quit[/dim]" + ) + + +def entrypoint_failure(elapsed: float, err: str) -> None: + console.print() + console.print(f" [err]✗ {err}[/err]") + console.print( + f" [err]✗[/err] [white]failed[/white] [dim]in {_fmt_elapsed(elapsed)}, " + f"enter re-run, edit reload, ^C quit[/dim]" + ) diff --git a/runpod/cli/datacenter.py b/runpod/cli/datacenter.py new file mode 100644 index 000000000..e74841076 --- /dev/null +++ b/runpod/cli/datacenter.py @@ -0,0 +1,58 @@ +"""data center locations and GPU availability.""" + +import click + +from runpod.api.graphql import run_graphql_query +from runpod.cli.api import api_errors +from runpod.cli.output import json_option, print_json, print_table + +_DATACENTERS_QUERY = """ +query { + dataCenters { + id + name + location + gpuAvailability { + gpuTypeId + displayName + stockStatus + } + } +} +""" + + +def _availability(row): + return ", ".join( + f"{gpu.get('displayName') or gpu.get('gpuTypeId') or '-'} " + f"({gpu.get('stockStatus') or '-'})" + for gpu in row.get("gpuAvailability") or [] + ) + + +_COLUMNS = [ + ("ID", lambda row: row.get("id")), + ("NAME", lambda row: row.get("name")), + ("LOCATION", lambda row: row.get("location")), + ("GPU AVAILABILITY", _availability), +] + + +@click.group() +def datacenter(): + """Browse data center locations and GPU availability.""" + + +@datacenter.command("list") +@json_option +def list_datacenters(as_json): + """List data centers and their GPU stock.""" + with api_errors(): + data = run_graphql_query(_DATACENTERS_QUERY).get("data") or {} + if "dataCenters" not in data: + raise click.ClickException("data center information is unavailable") + rows = data["dataCenters"] or [] + if as_json: + print_json(rows) + return + print_table(rows, _COLUMNS, "no data centers found") diff --git a/runpod/cli/endpoint.py b/runpod/cli/endpoint.py new file mode 100644 index 000000000..8761c17fb --- /dev/null +++ b/runpod/cli/endpoint.py @@ -0,0 +1,1225 @@ +import contextlib +import fnmatch +import json +import sys +import time +from collections.abc import Iterator +from typing import Any +from urllib.parse import quote + +import click +import requests +from rich.markup import escape + +from runpod._hosts import endpoint_domain +from runpod.api.rest import run_rest_request +from runpod.apps.utils.network import api_key +from runpod.cli import compute, console as ui, endpoint_config as config +from runpod.cli.api import api_errors, list_all +from runpod.cli.output import ( + completer, + confirm, + interactive, + json_option, + pick, + print_fields, + print_json, + print_table, + table, +) +from runpod.cli.volume import _choices as volume_choices +from runpod.endpoint import runner +from runpod.endpoint.helpers import is_completed +from runpod.error import QueryError + +TYPES = {"queue": "QUEUE", "load-balancer": "LOAD_BALANCER"} + + +def _path(endpoint_id: str, *parts: str) -> str: + segments = [quote(value, safe="") for value in (endpoint_id, *parts)] + return "/v2/serverless/" + "/".join(segments) + + +def _choices(path: str, collection: str): + def fetch(): + return [ + (record["id"], record.get("name") or "") + for record in list_all(path, collection) + ] + + return completer(fetch) + + +complete_endpoint = _choices("/v2/serverless", "endpoints") +complete_volume = completer(volume_choices) +complete_registry = _choices("/v2/registries", "registries") +complete_template = _choices("/v2/templates", "templates") +complete_datacenter = completer( + lambda: [ + (dc["id"], (dc.get("region") or "").lower()) + for dc in compute.list_datacenters() + ] +) + + +def complete_worker(ctx, param, incomplete): + endpoint_id = ctx.params.get("endpoint_id") + if not endpoint_id: + return [] + return completer( + lambda: [ + (worker["id"], (worker.get("status") or "").lower()) + for worker in run_rest_request("GET", _path(endpoint_id, "workers"))[ + "workers" + ] + ] + )(ctx, param, incomplete) + + +def endpoint_argument(required: bool = True): + return click.argument( + "endpoint_id", required=required, shell_complete=complete_endpoint + ) + + +def _pick_endpoint(endpoint_id: str | None) -> str: + if endpoint_id: + return endpoint_id + if not interactive(): + raise click.UsageError("pass an ENDPOINT_ID") + with api_errors(): + endpoints = list_all("/v2/serverless", "endpoints") + return pick( + "endpoint", + [ + (e["id"], f"{e['id']} {e.get('name') or ''} {_type(e) or ''}") + for e in endpoints + ], + "pass an ENDPOINT_ID", + ) + + +def _type(endpoint: dict) -> str | None: + names = {value: key for key, value in TYPES.items()} + kind = endpoint.get("type") + return names.get(kind, kind) if kind is not None else None + + +def _flashboot(endpoint: dict) -> str | None: + names = {value: key for key, value in config.FLASHBOOT.items()} + mode = endpoint.get("flashboot") + return names.get(mode, mode) if mode is not None else None + + +def _compute(endpoint: dict, compact: bool = False) -> str | None: + gpu = endpoint.get("gpu") + if gpu: + text = f"{', '.join(gpu.get('pools') or [])} x{gpu.get('count') or 1}" + excluded = gpu.get("excludedTypes") or [] + if compact or not excluded: + return text + return f"{text} (excluding {', '.join(excluded)})" + cpus = endpoint.get("cpu") or [] + return ", ".join(f"{cpu['id']} {cpu.get('vcpuCount')} vcpu" for cpu in cpus) or None + + +def _cuda(endpoint: dict) -> str | None: + gpu = endpoint.get("gpu") + if not gpu: + return None + if gpu.get("minCudaVersion"): + return f">={gpu['minCudaVersion']}" + return ", ".join(gpu.get("allowedCudaVersions") or []) or "any" + + +def _scaling(endpoint: dict, compact: bool = False) -> str | None: + scaling = endpoint.get("scaling") or {} + if scaling.get("type") == "QUEUE_DELAY": + delay = f"{scaling.get('queueDelay'):g}s" + return f"{delay} delay" if compact else f"queue delay {delay}" + if scaling.get("type") == "REQUEST_COUNT": + count = scaling.get("requestCount") + return f"{count}/worker" if compact else f"{count} requests per worker" + return None + + +def _workers(endpoint: dict) -> str | None: + workers = endpoint.get("workers") or {} + if "min" not in workers and "max" not in workers: + return None + return f"{workers.get('min', 0)}-{workers.get('max', 0)}" + + +def _seconds(value: float | None) -> str | None: + return f"{value:g}s" if value else None + + +def _volumes(endpoint: dict) -> list[str]: + mounts = endpoint.get("mounts") or {} + return [ + f"{mount['volumeId']} ({kind})" + for kind in ("network", "global") + for mount in mounts.get(kind) or [] + ] + + +def _url(endpoint: dict) -> str | None: + urls = endpoint.get("requestUrls") or {} + return urls.get("base") or urls.get("run") + + +_LIST_COLUMNS = [ + ("ID", lambda e: e["id"]), + ("NAME", lambda e: e.get("name")), + ("TYPE", _type), + ("COMPUTE", lambda e: _compute(e, compact=True)), + ("WORKERS", _workers), + ("SCALING", lambda e: _scaling(e, compact=True)), + ("CREATED", lambda e: (e.get("createdAt") or "")[:10]), +] + +_FIELDS = [ + ("id", lambda e: e.get("id")), + ("name", lambda e: e.get("name")), + ("type", _type), + ("image", lambda e: e.get("image")), + ("compute", _compute), + ("cuda", _cuda), + ("workers", _workers), + ("idle timeout", lambda e: _seconds((e.get("workers") or {}).get("idleTimeout"))), + ("scaling", _scaling), + ("request timeout", lambda e: _seconds((e.get("timeout") or 0) / 1000)), + ("flashboot", _flashboot), + ("data centers", lambda e: e.get("dataCenterIds")), + ("volumes", _volumes), + ("env", lambda e: sorted(e.get("env") or {})), + ("ports", lambda e: e.get("ports")), + ("disk", lambda e: f"{e['disk']}GB" if e.get("disk") else None), + ("args", lambda e: e.get("args")), + ("registry", lambda e: e.get("registry")), + ("url", _url), + ("created", lambda e: e.get("createdAt")), +] + + +def _scale_options(func): + for option in reversed( + [ + click.option( + "--min-workers", type=click.IntRange(min=0), help="Minimum workers." + ), + click.option( + "--max-workers", type=click.IntRange(min=0), help="Maximum workers." + ), + click.option( + "--idle-timeout-seconds", + type=click.IntRange(1, 3600), + help="Seconds before idle workers scale down.", + ), + click.option( + "--queue-delay-seconds", + type=click.FloatRange(min=0.5), + help="Scale on queue wait time (queue endpoints).", + ), + click.option( + "--requests-per-worker", + type=click.IntRange(min=1), + help="Scale on in-flight requests per worker.", + ), + ] + ): + func = option(func) + return func + + +def _config_options(creating: bool): + head = [click.option("--name", required=creating, help="Endpoint name.")] + if creating: + head.append( + click.option( + "--type", + "endpoint_type", + required=True, + type=click.Choice(list(TYPES), case_sensitive=False), + callback=lambda ctx, param, value: ( + TYPES[value.lower()] if value else value + ), + help="Request routing: queued jobs or load-balanced HTTP.", + ) + ) + options = head + [ + click.option("--image", help="Container image."), + click.option( + "--template", + help="Serverless template ID to base the container on.", + shell_complete=complete_template, + ), + click.option( + "--gpu", + multiple=True, + help="GPU type (4090, h100, a100-sxm4) or pool id, optionally with a " + "count (h100:2). Repeatable.", + ), + click.option( + "--gpu-count", type=click.IntRange(min=1), help="GPUs per worker." + ), + click.option( + "--cuda", + multiple=True, + help="CUDA constraint: '>=12.4' for a floor, 12.4 or 12.4,12.8 for exact " + "versions, any for no constraint.", + ), + click.option( + "--cpu", + multiple=True, + help="CPU flavor (cpu3c, cpu5g), optionally with vCPUs (cpu3c:8). Repeatable.", + ), + click.option( + "--vcpu-count", type=click.IntRange(min=2), help="vCPUs per worker." + ), + _scale_options, + click.option( + "--request-timeout-seconds", + type=click.IntRange(min=0), + help="Per-request execution timeout.", + ), + click.option( + "--data-center", + multiple=True, + help="Data center id (EU-RO-1). Repeatable.", + shell_complete=complete_datacenter, + ), + click.option( + "--region", + multiple=True, + help="Region (eu, na, asia) or id prefix (us, eu-ro). Repeatable.", + ), + click.option( + "--volume", + multiple=True, + help="Network or global volume ID. Repeatable. Updates replace mounts " + "of each supplied storage type.", + shell_complete=complete_volume, + ), + click.option( + "--env", multiple=True, help="Environment variable KEY=VALUE. Repeatable." + ), + click.option( + "--flashboot", + type=click.Choice(list(config.FLASHBOOT), case_sensitive=False), + help="FlashBoot mode.", + ), + click.option( + "--disk", type=click.IntRange(min=1), help="Container disk in GB." + ), + click.option( + "--port", multiple=True, help="Exposed port as port/protocol. Repeatable." + ), + click.option("--args", help="Container start command as one raw string."), + click.option("--entrypoint", help="Container ENTRYPOINT, shell-quoted."), + click.option("--cmd", help="Container CMD, shell-quoted."), + click.option( + "--registry", + help="Registry credential name or ID for private images; empty clears it.", + shell_complete=complete_registry, + ), + ] + if not creating: + options.append( + click.option( + "--unset-env", + multiple=True, + help="Remove an environment variable. Repeatable.", + ) + ) + + def decorate(func): + for option in reversed(options): + func = option(func) + return func + + return decorate + + +def _rollout_line(state: dict) -> str: + rollout = state.get("rollout") or {} + on_latest = f"{rollout.get('workersOnLatest', 0)}/{rollout.get('workersTotal', 0)}" + phase = "rolling out" if rollout.get("inProgress") else "live" + return f"v{state.get('endpointVersion')} {phase}, {on_latest} workers on latest" + + +def _follow_rollout( + endpoint_id: str, + previous_version: int | None, + timeout: float, + interval: float = 2.0, +) -> None: + started = time.monotonic() + last = None + try: + while True: + with api_errors(): + state = run_rest_request( + "GET", _path(endpoint_id, "releases"), params={"limit": 1} + ) + if state is None: + raise QueryError( + f"empty release response for endpoint {endpoint_id}" + ) + version = state.get("endpointVersion") + elapsed = time.monotonic() - started + waiting_for_release = ( + previous_version is not None and version == previous_version + ) + if not waiting_for_release: + line = _rollout_line(state) + if line != last: + ui.console.print(f"[dim]{line}[/dim]") + last = line + if not (state.get("rollout") or {}).get("inProgress"): + ui.success(f"release v{version} is live") + return + if elapsed >= timeout: + phase = ( + "no new release observed" + if waiting_for_release + else "rollout still in progress" + ) + ui.warn( + f"{phase} after {timeout:g}s. " + f"follow with: rp endpoint releases {endpoint_id}" + ) + return + time.sleep(interval) + except KeyboardInterrupt: + ui.console.print( + "\n[dim]detached; the rollout continues. " + f"follow with: rp endpoint releases {endpoint_id}[/dim]" + ) + + +def _apply( + endpoint_id: str, patch: dict, follow: bool, timeout: float, as_json: bool +) -> None: + if patch.keys() <= {"name", "workers", "scaling", "timeout", "flashboot"}: + follow = False + before = None + if follow: + try: + with api_errors(): + state = run_rest_request( + "GET", _path(endpoint_id, "releases"), params={"limit": 1} + ) + if state is None: + raise QueryError( + f"empty release response for endpoint {endpoint_id}" + ) + before = state.get("endpointVersion") + except click.ClickException as exc: + click.echo(f"warning: cannot follow rollout: {exc.message}", err=True) + follow = False + with api_errors(): + updated = run_rest_request("PATCH", _path(endpoint_id), json=patch) + if updated is None: + raise QueryError(f"empty response for endpoint {endpoint_id}") + if as_json: + print_json(updated) + else: + ui.success( + f"updated [white]{escape(updated['name'])}[/white] " + f"[dim]{endpoint_id}[/dim]" + ) + if follow: + with ( + contextlib.redirect_stdout(sys.stderr) + if as_json + else contextlib.nullcontext() + ): + _follow_rollout(endpoint_id, before, timeout) + + +def _edit_document(before: dict) -> dict | None: + text = json.dumps(before, indent=2) + "\n" + while True: + edited = click.edit(text, extension=".json") + if edited is None: + return None + try: + return config.validate(edited, before) + except click.ClickException as exc: + ui.error(escape(exc.message)) + if not click.confirm("re-open the editor?", default=True): + raise + text = edited + + +def _uptime(seconds: int | None) -> str | None: + if not seconds: + return None + hours, rest = divmod(int(seconds), 3600) + minutes, secs = divmod(rest, 60) + if hours: + return f"{hours}h{minutes:02d}m" + return f"{minutes}m{secs:02d}s" if minutes else f"{secs}s" + + +def _worker_version(worker: dict) -> str | None: + stale = " (stale)" if worker.get("isStale") else "" + if worker.get("version") is None: + return stale.strip(" ()") or None + return f"v{worker['version']}{stale}" + + +_WORKER_COLUMNS = [ + ("WORKER", lambda w: w["id"]), + ("STATUS", lambda w: (w.get("status") or "").lower()), + ( + "GPU", + lambda w: ( + f"{w.get('gpuTypeId')} x{w['gpuCount']}" if w.get("gpuCount") else None + ), + ), + ("DATA CENTER", lambda w: w.get("dataCenterId")), + ("VERSION", _worker_version), + ("UPTIME", lambda w: _uptime(w.get("uptimeSeconds"))), +] + + +def _workers_view(data: dict): + from rich.console import Group + from rich.text import Text + + summary = data["summary"] + counts = ", ".join( + f"{summary[status]} {status}" + for status in ("running", "idle", "initializing", "throttled", "unhealthy") + ) + version = data.get("endpointVersion") + suffix = f", endpoint v{version}" if version is not None else "" + header = Text(f"{summary['total']} workers: {counts}{suffix}", style="dim") + return ( + Group(header, table(data["workers"], _WORKER_COLUMNS)) + if data["workers"] + else header + ) + + +@contextlib.contextmanager +def _data_plane_errors() -> Iterator[None]: + try: + yield + except requests.HTTPError as exc: + response = exc.response + if response is None: + raise click.ClickException(str(exc)) from exc + detail = response.text.strip() or response.reason or "" + raise click.ClickException(f"{response.status_code} {detail}".strip()) from exc + except (requests.RequestException, RuntimeError, QueryError) as exc: + raise click.ClickException(str(exc)) from exc + + +def _job_path(endpoint_id: str, action: str, job_id: str | None = None) -> str: + parts = [quote(endpoint_id, safe=""), action] + if job_id: + parts.append(quote(job_id, safe="")) + return "/".join(parts) + + +def _print_job(job: dict, as_json: bool) -> None: + if as_json: + print_json(job) + elif job["status"] == "COMPLETED": + output = job.get("output") + click.echo(output if isinstance(output, str) else json.dumps(output, indent=2)) + if job["status"] != "COMPLETED": + detail = f": {job['error']}" if job.get("error") else "" + raise click.ClickException(f"job {job['id']} {job['status'].lower()}{detail}") + + +def _follow_job(client, endpoint_id, job_id, as_json, *, stream=False, timeout=None): + """wait for completion, draining streamed chunks before reading the final result.""" + action = "stream" if stream else "status" + resume = "stream" if stream else "wait" + deadline = time.monotonic() + timeout if timeout is not None else None + status = "pending" + + def remaining_time(limit): + if deadline is None or is_completed(status): + return limit + remaining = deadline - time.monotonic() + if remaining <= 0: + raise click.ClickException( + f"job {job_id} is still {status} after {timeout:g}s. " + f"resume with: rp endpoint job {resume} {endpoint_id} {job_id}" + ) + return min(limit, remaining) + + streamed = open_line = False + progress = ( + contextlib.nullcontext() + if stream + else ui.console.status(f"[dim]waiting for job {job_id} ...[/dim]") + ) + try: + with progress: + while True: + try: + if stream: + job = client.get( + _job_path(endpoint_id, action, job_id), + timeout=remaining_time(60), + ) + elif deadline is not None: + job = client.get( + _job_path(endpoint_id, action, job_id), + timeout=remaining_time(10), + ) + else: + job = client.get(_job_path(endpoint_id, action, job_id)) + except requests.Timeout as exc: + remaining_time(0) + if ( + stream + and isinstance(exc, requests.ReadTimeout) + and not is_completed(status) + ): + continue + raise + status = job["status"] + chunks = (job.get("stream") or []) if stream else [] + streamed = streamed or bool(chunks) + for chunk in chunks: + output = chunk["output"] + if isinstance(output, str) and not as_json: + click.echo(output, nl=False) + open_line = not output.endswith("\n") + else: + if open_line: + click.echo() + open_line = False + click.echo(json.dumps(output)) + if is_completed(job["status"]) and not chunks: + break + if not chunks: + time.sleep(remaining_time(0.5 if stream else 1)) + except KeyboardInterrupt: + click.echo( + f"\njob {job_id} keeps running. resume with: " + f"rp endpoint job {resume} {endpoint_id} {job_id}", + err=True, + ) + raise click.Abort() from None + if open_line: + click.echo() + if streamed and job["status"] == "COMPLETED": + return + if stream: + kwargs = {"timeout": remaining_time(10)} if deadline is not None else {} + job = client.get(_job_path(endpoint_id, "status", job_id), **kwargs) + _print_job(job, as_json) + + +def _request_body(input_file, data: str | None) -> Any | None: + if input_file and data: + raise click.UsageError("use either --input or --data") + text = input_file.read() if input_file else data + if text is None: + return None + try: + return json.loads(text) + except json.JSONDecodeError as exc: + raise click.UsageError(f"request body is not valid JSON: {exc}") from exc + + +def _call_load_balancer( + endpoint: dict, path: str, method, body, timeout, as_json +) -> None: + base = (endpoint.get("requestUrls") or {}).get("base") or ( + f"https://{endpoint['id']}.{endpoint_domain()}" + ) + method = (method or ("POST" if body is not None else "GET")).upper() + url = f"{base.rstrip('/')}/{path.lstrip('/')}" + response = requests.request( + method, + url, + headers={ + "Authorization": f"Bearer {api_key()}", + "Accept": "application/json", + }, + json=body, + timeout=timeout or 600, + ) + if response.status_code >= 400: + raise click.ClickException( + f"{method} {url} returned {response.status_code}: {response.text.strip()}" + ) + try: + payload = response.json() + except ValueError: + if as_json: + print_json(response.text) + else: + click.echo(response.text) + return + if isinstance(payload, str) and not as_json: + click.echo(payload) + return + print_json(payload) + + +@click.group() +def endpoint(): + """Create, inspect, scale, observe, and call serverless endpoints. + + \b + rp endpoint list --type queue + rp endpoint create --name llama --type queue --image IMAGE --gpu h100 + rp endpoint edit ENDPOINT_ID + rp endpoint logs ENDPOINT_ID --follow + rp endpoint run ENDPOINT_ID --data '{"prompt":"hello"}' + """ + + +@endpoint.command(name="list") +@click.option( + "--name", help="Only endpoints with this name (globs like 'llama*' work)." +) +@click.option( + "--type", + "endpoint_type", + type=click.Choice(list(TYPES), case_sensitive=False), + help="Only endpoints of this type.", +) +@json_option +def list_endpoints(name, endpoint_type, as_json): + """List endpoints with their IDs.""" + with api_errors(): + endpoints = list_all("/v2/serverless", "endpoints") + if name: + endpoints = [ + e + for e in endpoints + if fnmatch.fnmatch((e.get("name") or "").lower(), name.lower()) + ] + if endpoint_type: + endpoints = [ + e for e in endpoints if e.get("type") == TYPES[endpoint_type.lower()] + ] + if as_json: + print_json(endpoints) + return + print_table(endpoints, _LIST_COLUMNS, "no endpoints match") + + +@endpoint.command(name="get") +@endpoint_argument(required=False) +@json_option +def get_endpoint(endpoint_id, as_json): + """Show an endpoint's configuration (picker when ENDPOINT_ID is omitted).""" + endpoint_id = _pick_endpoint(endpoint_id) + with api_errors(): + record = run_rest_request("GET", _path(endpoint_id)) + if as_json: + print_json(record) + return + print_fields(record, _FIELDS) + + +@endpoint.command(name="create") +@_config_options(creating=True) +@json_option +def create_endpoint(as_json, **options): + """Create an endpoint. + + GPU types are human-readable and resolve against the serverless + catalog, and regions expand to their data centers. + + \b + rp endpoint create --name llama-prod --type queue \\ + --image ghcr.io/acme/llama:latest --gpu h100 --max-workers 4 \\ + --region eu --env MODEL_ID=meta-llama/Llama-3.1-8B --flashboot standard + rp endpoint create --name api --type load-balancer --image IMAGE \\ + --gpu 4090 --requests-per-worker 4 --env PORT=8000 + rp endpoint create --name embeddings --type queue --image IMAGE \\ + --cpu cpu3c --vcpu-count 8 + """ + if not options.get("image") and not options.get("template"): + raise click.UsageError("pass --image or --template") + with api_errors(): + body = config.config_body(options) + created = run_rest_request("POST", "/v2/serverless", json=body) + if as_json: + print_json(created) + return + ui.success( + f"created [white]{escape(created['name'])}[/white] [dim]{created['id']}[/dim]" + ) + print_fields(created, _FIELDS) + + +@endpoint.command(name="update") +@endpoint_argument() +@_config_options(creating=False) +@click.option( + "--wait", is_flag=True, help="Follow the rollout until the new release is live." +) +@click.option( + "--timeout", default=600.0, show_default=True, help="Seconds to follow the rollout." +) +@json_option +def update_endpoint(endpoint_id, wait, timeout, as_json, **options): + """Change an endpoint's configuration with flags. + + Only the given fields change. --env merges into the existing variables, + while --data-center replaces its list. --volume replaces mounts of each + supplied storage type and preserves mounts of the other type. + """ + with api_errors(): + current = run_rest_request("GET", _path(endpoint_id)) + patch = config.config_body(options, current) + if not patch: + raise click.UsageError( + "nothing to update. pass an option (see --help) or use rp endpoint edit" + ) + _apply(endpoint_id, patch, wait, timeout, as_json) + + +@endpoint.command(name="edit") +@endpoint_argument(required=False) +@click.option( + "--file", + "document", + type=click.File("r"), + help="Apply a JSON document (- for stdin) instead of opening $EDITOR.", +) +@click.option("--yes", "-y", is_flag=True, help="Apply without confirming.") +@click.option("--no-follow", is_flag=True, help="Return without following the rollout.") +@click.option( + "--timeout", default=600.0, show_default=True, help="Seconds to follow the rollout." +) +@json_option +def edit_endpoint(endpoint_id, document, yes, no_follow, timeout, as_json): + """Edit an endpoint's configuration in $EDITOR. + + Opens the mutable configuration as JSON, validates it, shows the + patch, and after confirmation applies it and follows any worker rollout. + runtime-only changes return without polling for a release. + Ctrl-C while following detaches without undoing anything. Fields + removed from the document stay unchanged. + """ + endpoint_id = _pick_endpoint(endpoint_id) + with api_errors(): + current = run_rest_request("GET", _path(endpoint_id)) + before = config.mutable(current) + if document: + after = config.validate(document.read(), before) + elif not interactive(): + raise click.UsageError( + "edit opens $EDITOR and needs an interactive terminal. " + "pass --file or use rp endpoint update" + ) + else: + after = _edit_document(before) + patch = config.patch(before, after) if after is not None else {} + if not patch: + if as_json: + print_json({}) + else: + ui.console.print("[dim]no changes[/dim]") + return + if not as_json: + ui.console.print("[dim]patch:[/dim]") + print_json(patch) + confirm(f"apply to endpoint {endpoint_id}?", yes) + _apply(endpoint_id, patch, not (no_follow or as_json), timeout, as_json) + + +@endpoint.command(name="scale") +@endpoint_argument() +@_scale_options +@json_option +def scale_endpoint(endpoint_id, as_json, **options): + """Change worker limits and the autoscaler.""" + with api_errors(): + current = run_rest_request("GET", _path(endpoint_id)) + patch = config.scale_patch(options, current) + if not patch: + raise click.UsageError("pass --min-workers, --max-workers, or a scaler option") + with api_errors(): + updated = run_rest_request("PATCH", _path(endpoint_id), json=patch) + if as_json: + print_json(updated) + return + ui.success(f"scaled [white]{escape(updated['name'])}[/white]") + print_fields( + updated, + [ + ("id", lambda e: e.get("id") or endpoint_id), + ("workers", _workers), + ( + "idle timeout", + lambda e: _seconds((e.get("workers") or {}).get("idleTimeout")), + ), + ("scaling", _scaling), + ], + ) + + +@endpoint.command(name="delete") +@endpoint_argument() +@click.option("--yes", "-y", is_flag=True, help="Skip the confirmation prompt.") +def delete_endpoint(endpoint_id, yes): + """Delete an endpoint and its workers.""" + with api_errors(): + name = run_rest_request("GET", _path(endpoint_id))["name"] + confirm(f"delete endpoint '{name}' ({endpoint_id})?", yes) + with api_errors(): + run_rest_request("DELETE", _path(endpoint_id)) + ui.success(f"deleted [white]{escape(name)}[/white] [dim]{endpoint_id}[/dim]") + + +@endpoint.command(name="workers") +@endpoint_argument() +@click.option("--watch", "-w", is_flag=True, help="Refresh in place until Ctrl-C.") +@click.option( + "--interval", + type=click.FloatRange(min=1), + default=2.0, + show_default=True, + help="Seconds between refreshes.", +) +@json_option +def list_workers(endpoint_id, watch, interval, as_json): + """Show an endpoint's workers. With --watch, --json prints one line per refresh.""" + try: + with api_errors(): + data = run_rest_request("GET", _path(endpoint_id, "workers")) + if not watch: + if as_json: + print_json(data) + else: + ui.console.print(_workers_view(data)) + return + if as_json: + while True: + click.echo(json.dumps(data, default=str)) + time.sleep(interval) + with api_errors(): + data = run_rest_request("GET", _path(endpoint_id, "workers")) + from rich.live import Live + + with Live(_workers_view(data), console=ui.console, auto_refresh=False) as live: + while True: + time.sleep(interval) + with api_errors(): + data = run_rest_request("GET", _path(endpoint_id, "workers")) + live.update(_workers_view(data), refresh=True) + except KeyboardInterrupt: + pass + + +def _release_changes(release: dict) -> list[str]: + return [ + entry["field"].removeprefix("template.") + for entry in release.get("diff") or [] + if entry.get("field") and (entry.get("old") or entry.get("new")) + ] + + +@endpoint.command(name="releases") +@endpoint_argument() +@json_option +def list_releases(endpoint_id, as_json): + """Show release history and rollout progress.""" + with api_errors(): + state = run_rest_request( + "GET", _path(endpoint_id, "releases"), params={"limit": 1} + ) + releases = list_all(_path(endpoint_id, "releases"), "releases") + if as_json: + print_json( + { + "endpointVersion": state.get("endpointVersion"), + "rollout": state.get("rollout"), + "releases": releases, + } + ) + return + if state.get("endpointVersion") is not None: + ui.console.print(f"[dim]{_rollout_line(state)}[/dim]") + print_table( + releases, + [ + ("RELEASE", lambda r: r["id"]), + ( + "VERSION", + lambda r: f"v{r['version']}" if r.get("version") is not None else None, + ), + ("SOURCE", lambda r: (r.get("source") or "").lower().replace("_", " ")), + ("BUILD", lambda r: r.get("buildId")), + ("WORKERS", lambda r: r.get("workerCount")), + ("CREATED", lambda r: (r.get("createdAt") or "")[:16].replace("T", " ")), + ("CHANGES", _release_changes), + ], + "no releases", + ) + + +@endpoint.command(name="logs") +@endpoint_argument() +@click.option( + "--worker", + "worker_ids", + multiple=True, + shell_complete=complete_worker, + help="Only this worker. Repeatable. Omit for every worker.", +) +@click.option( + "--follow", "-f", is_flag=True, help="Keep streaming and attach to new workers." +) +@click.option( + "--source", + type=click.Choice(["container", "system"]), + help="Log source. Omit for both.", +) +@click.option( + "--tail", + type=click.IntRange(0, 5000), + default=100, + show_default=True, + help="Lines of backfill per worker.", +) +@click.option("--since", help="RFC3339 timestamp to start from (overrides --tail).") +@json_option +def logs(endpoint_id, worker_ids, follow, source, tail, since, as_json): + """Show worker logs, each line prefixed with its worker id. + + Without --worker, every worker's logs are multiplexed, and with + --follow newly created workers are attached automatically. + """ + from runpod.cli.logs import show_logs + + show_logs( + endpoint_id=endpoint_id, + worker_ids=worker_ids, + follow=follow, + source=source, + tail=tail, + since=since, + as_json=as_json, + ) + + +@endpoint.command(name="run") +@endpoint_argument() +@click.option( + "--input", + "input_file", + type=click.File("r"), + help="JSON request file, or - for stdin. A body without an 'input' key is wrapped in one.", +) +@click.option("--data", help="Inline JSON request.") +@click.option("--async", "run_async", is_flag=True, help="Submit and print the job id.") +@click.option("--stream", is_flag=True, help="Print streamed output as it arrives.") +@click.option("--webhook", help="URL notified when the job finishes.") +@click.option( + "--execution-timeout", + type=click.IntRange(min=1), + help="Job execution limit in seconds.", +) +@click.option("--ttl", type=click.IntRange(min=1), help="Job time to live in seconds.") +@click.option( + "--low-priority", is_flag=True, help="Do not scale up workers for this job." +) +@click.option( + "--timeout", + type=click.FloatRange(min=0, min_open=True), + help="Seconds to wait for the result.", +) +@click.option("--path", "lb_path", help="Load-balancer endpoints: request path.") +@click.option( + "--method", + help="Load-balancer endpoints: HTTP method (POST with a body, else GET).", +) +@json_option +@_data_plane_errors() +def run_endpoint( + endpoint_id, + input_file, + data, + run_async, + stream, + webhook, + execution_timeout, + ttl, + low_priority, + timeout, + lb_path, + method, + as_json, +): # pylint: disable=too-many-arguments + """Send a request to an endpoint. + + Queue endpoints run a job on the serverless data plane and print its + output. Load-balancer endpoints receive the body as an HTTP request + to --path on the endpoint URL. + + \b + rp endpoint run ENDPOINT_ID --input request.json + rp endpoint run ENDPOINT_ID --data '{"prompt":"hello"}' + rp endpoint run ENDPOINT_ID --input - --stream + rp endpoint run ENDPOINT_ID --input request.json --async + rp endpoint run LB_ENDPOINT_ID --path /v1/models + """ + if run_async and stream: + raise click.UsageError("use either --async or --stream") + body = _request_body(input_file, data) + with api_errors(): + record = run_rest_request("GET", _path(endpoint_id)) + + if record.get("type") == "LOAD_BALANCER": + if run_async or stream or webhook or execution_timeout or ttl or low_priority: + raise click.UsageError( + "load-balancer endpoints take --path, --method, and a body; " + "job options apply to queue endpoints" + ) + _call_load_balancer(record, lb_path or "/", method, body, timeout, as_json) + return + + if lb_path or method: + raise click.UsageError("--path and --method apply to load-balancer endpoints") + if body is None: + raise click.UsageError("pass --input FILE or --data JSON") + request = body if isinstance(body, dict) and "input" in body else {"input": body} + if webhook: + request["webhook"] = webhook + policy = dict(request.get("policy") or {}) + if execution_timeout: + policy["executionTimeout"] = execution_timeout * 1000 + if ttl: + policy["ttl"] = ttl * 1000 + if low_priority: + policy["lowPriority"] = True + if policy: + request["policy"] = policy + + client = runner.RunPodClient() + submitted = client.post(_job_path(endpoint_id, "run"), request) + job_id = submitted["id"] + if run_async: + if as_json: + print_json(submitted) + return + ui.success( + f"submitted job [white]{job_id}[/white] [dim]{submitted.get('status')}[/dim]" + ) + ui.console.print(f"[dim]rp endpoint job wait {endpoint_id} {job_id}[/dim]") + return + if stream: + if not as_json: + click.echo(f"job {job_id}", err=True) + _follow_job(client, endpoint_id, job_id, as_json, stream=True, timeout=timeout) + return + _follow_job(client, endpoint_id, job_id, as_json, timeout=timeout) + + +@endpoint.group(name="job") +def job(): + """Inspect and control queue jobs.""" + + +def _job_command(name: str): + def decorate(func): + func = json_option(func) + func = click.argument("job_id")(func) + func = endpoint_argument()(func) + return job.command(name=name)(func) + + return decorate + + +def _job_output(record: dict) -> str | None: + output = record.get("output") + if output is None or isinstance(output, str): + return output + return json.dumps(output) + + +_JOB_FIELDS = [ + ("id", lambda j: j.get("id")), + ("status", lambda j: (j.get("status") or "").lower()), + ("delay", lambda j: _seconds((j.get("delayTime") or 0) / 1000)), + ("execution", lambda j: _seconds((j.get("executionTime") or 0) / 1000)), + ("worker", lambda j: j.get("workerId")), + ("error", lambda j: j.get("error")), + ("output", _job_output), +] + + +@_job_command("get") +@_data_plane_errors() +def job_get(endpoint_id, job_id, as_json): + """Show a job's status and output.""" + record = runner.RunPodClient().get(_job_path(endpoint_id, "status", job_id)) + if as_json: + print_json(record) + return + print_fields(record, _JOB_FIELDS) + + +@_job_command("wait") +@click.option( + "--timeout", type=click.FloatRange(min=0, min_open=True), help="Seconds to wait." +) +@_data_plane_errors() +def job_wait(endpoint_id, job_id, timeout, as_json): + """Wait for a job to finish and print its output.""" + _follow_job(runner.RunPodClient(), endpoint_id, job_id, as_json, timeout=timeout) + + +@_job_command("stream") +@_data_plane_errors() +def job_stream(endpoint_id, job_id, as_json): + """Print a job's streamed output as it arrives.""" + _follow_job(runner.RunPodClient(), endpoint_id, job_id, as_json, stream=True) + + +@_job_command("cancel") +@_data_plane_errors() +def job_cancel(endpoint_id, job_id, as_json): + """Cancel a queued or running job.""" + record = runner.RunPodClient().post(_job_path(endpoint_id, "cancel", job_id), None) + if as_json: + print_json(record) + return + ui.success(f"job [white]{job_id}[/white] [dim]{record.get('status')}[/dim]") + + +@_job_command("retry") +@_data_plane_errors() +def job_retry(endpoint_id, job_id, as_json): + """Requeue a failed or timed-out job.""" + record = runner.RunPodClient().post(_job_path(endpoint_id, "retry", job_id), None) + if as_json: + print_json(record) + return + ui.success( + f"job [white]{record.get('id') or job_id}[/white] [dim]{record.get('status')}[/dim]" + ) + + +@endpoint.command(name="purge") +@endpoint_argument() +@click.option("--yes", "-y", is_flag=True, help="Skip the confirmation prompt.") +@json_option +@_data_plane_errors() +def purge_queue(endpoint_id, yes, as_json): + """Remove every queued job. Running jobs are not affected.""" + confirm(f"remove every queued job from {endpoint_id}?", yes) + record = runner.RunPodClient().post(_job_path(endpoint_id, "purge-queue"), None) + if as_json: + print_json(record) + return + ui.success( + f"purged {record.get('removed', 0)} queued jobs from [white]{endpoint_id}[/white]" + ) diff --git a/runpod/cli/endpoint_config.py b/runpod/cli/endpoint_config.py new file mode 100644 index 000000000..ae766e879 --- /dev/null +++ b/runpod/cli/endpoint_config.py @@ -0,0 +1,301 @@ +import json +from typing import Any + +import click + +from runpod.cli import compute +from runpod.cli.options import container_fields +from runpod.cli.volume import _get_volume + +FLASHBOOT = {"off": "OFF", "standard": "FLASHBOOT", "priority": "PRIORITY_FLASHBOOT"} + + +MUTABLE_FIELDS = { + "name": (str,), + "image": (str,), + "args": (str,), + "env": (dict,), + "disk": (int,), + "ports": (list,), + "registry": (str, type(None)), + "gpu": (dict,), + "cpu": (list,), + "workers": (dict,), + "scaling": (dict,), + "timeout": (int,), + "flashboot": (str,), + "dataCenterIds": (list,), + "mounts": (dict,), +} + + +NESTED_FIELDS = { + "gpu": {"pools", "excludedTypes", "count", "allowedCudaVersions", "minCudaVersion"}, + "workers": {"min", "max", "idleTimeout"}, + "scaling": {"type", "queueDelay", "requestCount"}, + "mounts": {"network", "global"}, +} + + +def _gpu(specs, count, cuda, updating: bool) -> dict: + gpu: dict[str, Any] = {} + if specs: + catalog = [ + entry + for entry in compute.list_gpus(product="SERVERLESS") + if entry.get("pool") + ] + matches: list[dict] = [] + counts = {count} if count else set() + for spec in specs: + name, spec_count = compute.parse_gpu_spec(spec) + if spec_count: + counts.add(spec_count) + for match in compute.resolve_gpus(name, catalog): + if match not in matches: + matches.append(match) + if len(counts) > 1: + raise click.UsageError("conflicting gpu counts; use one count per worker") + pools, excluded = compute.endpoint_gpu_selection(matches, catalog) + gpu["pools"] = pools + if excluded or updating: + gpu["excludedTypes"] = excluded + count = counts.pop() if counts else None + if count: + gpu["count"] = count + if cuda: + if [value.lower() for value in cuda] == ["any"]: + gpu["allowedCudaVersions"] = [] + if updating: + gpu["minCudaVersion"] = "" + return gpu + minimum, exact = compute.parse_cuda(cuda) + if minimum: + gpu["minCudaVersion"] = minimum + if updating: + gpu["allowedCudaVersions"] = [] + else: + gpu["allowedCudaVersions"] = exact + if updating: + gpu["minCudaVersion"] = "" + return gpu + + +def _cpu(specs, vcpu_count, current: dict | None) -> list | None: + if not specs: + if vcpu_count and current and current.get("cpu"): + return [ + {"id": cpu["id"], "vcpuCount": vcpu_count} for cpu in current["cpu"] + ] + if vcpu_count: + raise click.UsageError("--vcpu-count applies to CPU endpoints (pass --cpu)") + return None + flavors = compute.list_cpus(product="SERVERLESS") + entries = [] + for spec in specs: + name, sep, count = spec.rpartition(":") + if not sep: + name, count = spec, "" + if count and not count.isdigit(): + raise click.UsageError( + f"invalid --cpu '{spec}'. use a flavor like cpu3c or cpu3c:8" + ) + vcpus = int(count) if count else vcpu_count + if not vcpus: + raise click.UsageError(f"pass --vcpu-count or --cpu {name}:VCPUS") + entries.append( + {"id": compute.resolve_cpu(name, flavors)["id"], "vcpuCount": vcpus} + ) + return entries + + +def scale_patch(options: dict, current: dict) -> dict: + patch = {} + changes = { + key: options[flag] + for key, flag in ( + ("min", "min_workers"), + ("max", "max_workers"), + ("idleTimeout", "idle_timeout_seconds"), + ) + if options.get(flag) is not None + } + if changes: + patch["workers"] = {**(current.get("workers") or {}), **changes} + delay = options.get("queue_delay_seconds") + count = options.get("requests_per_worker") + if delay is not None and count is not None: + raise click.UsageError( + "use either --queue-delay-seconds or --requests-per-worker" + ) + if delay is not None: + if current.get("type") == "LOAD_BALANCER": + raise click.UsageError( + "load-balancer endpoints scale on --requests-per-worker" + ) + patch["scaling"] = {"type": "QUEUE_DELAY", "queueDelay": delay} + elif count is not None: + patch["scaling"] = {"type": "REQUEST_COUNT", "requestCount": count} + return patch + + +def config_body(options: dict, current: dict | None = None) -> dict: + updating = current is not None + if current is None: + current = {"type": options["endpoint_type"]} + body = container_fields( + {**options, "ports": options.get("port")}, + current, + options.get("unset_env", ()), + ) + if not updating: + body["type"] = current["type"] + if options.get("name") is not None: + body["name"] = options["name"] + if options.get("flashboot"): + body["flashboot"] = FLASHBOOT[options["flashboot"].lower()] + if options.get("request_timeout_seconds") is not None: + body["timeout"] = options["request_timeout_seconds"] * 1000 + + if options.get("gpu") and options.get("cpu"): + raise click.UsageError("use either --gpu or --cpu") + if current.get("cpu") and options.get("gpu"): + raise click.UsageError("a CPU endpoint cannot switch to GPUs") + if current.get("gpu") and options.get("cpu"): + raise click.UsageError("a GPU endpoint cannot switch to CPUs") + if (options.get("cpu") or current.get("cpu")) and ( + options.get("cuda") or options.get("gpu_count") + ): + raise click.UsageError("--cuda and --gpu-count apply to GPU endpoints") + gpu = _gpu( + options.get("gpu"), options.get("gpu_count"), options.get("cuda"), updating + ) + if gpu: + body["gpu"] = gpu + cpu = _cpu(options.get("cpu"), options.get("vcpu_count"), current) + if cpu: + body["cpu"] = cpu + + body.update(scale_patch(options, current)) + if not updating and "scaling" not in body: + if current["type"] == "LOAD_BALANCER": + raise click.UsageError("load-balancer endpoints need --requests-per-worker") + body["scaling"] = {"type": "QUEUE_DELAY", "queueDelay": 4} + places = (*options.get("data_center", ()), *options.get("region", ())) + if places: + body["dataCenterIds"] = compute.resolve_regions( + places, compute.list_datacenters() + ) + if options.get("volume"): + mounts = dict(current.get("mounts") or {}) + resolved: dict[str, list[dict[str, str]]] = {} + for volume_id in options["volume"]: + kind, _ = _get_volume(volume_id) + if any(mount["volumeId"] == volume_id for mount in resolved.get(kind, [])): + raise click.BadParameter( + f"volume {volume_id!r} is specified more than once", + param_hint="--volume", + ) + resolved.setdefault(kind, []).append({"volumeId": volume_id}) + mounts.update(resolved) + body["mounts"] = mounts + return body + + +def mutable(endpoint: dict) -> dict: + doc: dict[str, Any] = {} + for key in ("name", "image", "args", "env", "disk", "ports"): + if endpoint.get(key) is not None: + doc[key] = endpoint[key] + doc["registry"] = endpoint.get("registry") + gpu = endpoint.get("gpu") + if gpu: + doc["gpu"] = { + "pools": gpu.get("pools") or [], + "excludedTypes": gpu.get("excludedTypes") or [], + "count": gpu.get("count") or 1, + "allowedCudaVersions": gpu.get("allowedCudaVersions") or [], + "minCudaVersion": gpu.get("minCudaVersion"), + } + if endpoint.get("cpu"): + doc["cpu"] = [ + {"id": cpu["id"], "vcpuCount": cpu["vcpuCount"]} for cpu in endpoint["cpu"] + ] + for key in ("workers", "scaling", "timeout", "flashboot", "dataCenterIds"): + if endpoint.get(key) is not None: + doc[key] = endpoint[key] + mounts = endpoint.get("mounts") or {} + doc["mounts"] = { + kind: [{"volumeId": m["volumeId"]} for m in mounts.get(kind) or []] + for kind in ("network", "global") + } + return doc + + +def _kind(kind: type) -> str: + return { + str: "a string", + int: "an integer", + dict: "an object", + list: "a list", + type(None): "null", + }[kind] + + +def validate(text: str, before: dict) -> dict: + try: + doc = json.loads(text) + except json.JSONDecodeError as exc: + raise click.ClickException(f"invalid JSON: {exc}") from exc + if not isinstance(doc, dict): + raise click.ClickException("the document must be a JSON object") + problems = [] + for key, value in doc.items(): + kinds = MUTABLE_FIELDS.get(key) + if kinds is None: + problems.append(f"unknown field '{key}'") + continue + if isinstance(value, bool) or not isinstance(value, kinds): + problems.append(f"'{key}' must be {' or '.join(_kind(k) for k in kinds)}") + continue + allowed = NESTED_FIELDS.get(key) + if allowed and isinstance(value, dict): + problems.extend( + f"unknown field '{key}.{nested}'" + for nested in value + if nested not in allowed + ) + env = doc.get("env") + if isinstance(env, dict) and not all(isinstance(v, str) for v in env.values()): + problems.append("env values must be strings") + flashboot = doc.get("flashboot") + if isinstance(flashboot, str) and flashboot not in FLASHBOOT.values(): + problems.append(f"'flashboot' must be one of {', '.join(FLASHBOOT.values())}") + if "gpu" in doc and "gpu" not in before: + problems.append("a CPU endpoint cannot switch to GPUs") + if "cpu" in doc and "cpu" not in before: + problems.append("a GPU endpoint cannot switch to CPUs") + if problems: + raise click.ClickException("; ".join(problems)) + return doc + + +def patch(before: dict, after: dict) -> dict: + patch = {} + for key, value in after.items(): + if before.get(key) == value: + continue + if key != "gpu": + patch[key] = value + continue + old = before.get("gpu") or {} + gpu = {k: v for k, v in value.items() if old.get(k) != v} + if "pools" in gpu or "excludedTypes" in gpu: + gpu["pools"] = value.get("pools", old.get("pools")) + gpu["excludedTypes"] = ( + value.get("excludedTypes", old.get("excludedTypes")) or [] + ) + if "minCudaVersion" in gpu and gpu["minCudaVersion"] is None: + gpu["minCudaVersion"] = "" + patch["gpu"] = gpu + return patch diff --git a/runpod/cli/groups/config/__init__.py b/runpod/cli/groups/config/__init__.py index d9af37604..9de3d7a4c 100644 --- a/runpod/cli/groups/config/__init__.py +++ b/runpod/cli/groups/config/__init__.py @@ -1 +1,7 @@ -""" Config related CLI functions. """ +"""credential imports for runpod-flash.""" + +import sys + +from runpod.auth import credentials as functions + +sys.modules[f"{__name__}.functions"] = functions diff --git a/runpod/cli/logs.py b/runpod/cli/logs.py new file mode 100644 index 000000000..0f1bd00d8 --- /dev/null +++ b/runpod/cli/logs.py @@ -0,0 +1,158 @@ +"""shared pod and serverless log views backed by the sdk stream reader.""" + +import asyncio +import json +from datetime import UTC, datetime + +import aiohttp +import click + +from runpod.api.ctl_commands import _path_segment +from runpod.api.rest import run_rest_request +from runpod.apps.errors import AppHTTPError +from runpod.apps.logs import stream_pod_logs +from runpod.cli import console as ui +from runpod.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(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 (AppHTTPError, aiohttp.ClientResponseError) as exc: + if endpoint_id and exc.status == 404: + return + if not follow or not (exc.status == 429 or 500 <= exc.status < 600): + raise + except (TimeoutError, aiohttp.ClientConnectionError): + 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 (TimeoutError, AppHTTPError, aiohttp.ClientError) as exc: + raise click.ClickException(str(exc)) from exc diff --git a/runpod/cli/main.py b/runpod/cli/main.py new file mode 100644 index 000000000..7b468a941 --- /dev/null +++ b/runpod/cli/main.py @@ -0,0 +1,1267 @@ +"""the `rp` / `runpod` cli. + +flash app commands share one namespace while account, registry, secret, +logs, pod, and ssh commands remain on the root. help, errors, and exit +codes behave identically at every level. rich is used only for runtime +output, never for help rendering. +""" + +import asyncio +import os +import shlex +import signal +import sys +from pathlib import Path +from typing import NoReturn + +import click + +# commands whose output would be polluted by (or that manage) the +# update notice +_UPDATE_CHECK_EXCLUDED = frozenset({"completion", "flash", "update"}) +_FLASH_UPDATE_CHECK_EXCLUDED = frozenset({"dev"}) + + +def _default_profile() -> str: + from runpod import _selected_profile + + return _selected_profile() + + +@click.group() +@click.pass_context +def cli(ctx): + """Runpod CLI: manage Flash apps, endpoints, and pods. + + Using an AI agent? Point it to https://docs.runpod.io/agent-setup.md + """ + if ctx.invoked_subcommand not in _UPDATE_CHECK_EXCLUDED: + from runpod.cli.update import start_background_check + + start_background_check() + + +@cli.group() +@click.pass_context +def flash(ctx): + """Build, develop, and manage Flash apps.""" + if ctx.invoked_subcommand not in _FLASH_UPDATE_CHECK_EXCLUDED: + from runpod.cli.update import start_background_check + + start_background_check() + + +def _fail(message: str) -> NoReturn: + raise click.ClickException(message) + + +def _stdin_is_tty() -> bool: + return sys.stdin.isatty() + + +def _app_source(found, project_root: Path) -> str: + """the file an app was discovered in, relative to the project.""" + source = getattr(found, "_source_file", None) + if source is None: + return "" + try: + return str(Path(source).resolve().relative_to(project_root)) + except ValueError: + return str(source) + + +# ------------------------------------------------------------------ init + + +@flash.command() +@click.argument("project_name", required=False) +@click.option("--force", "-f", is_flag=True, help="Overwrite existing files.") +def init(project_name, force): + """Create a new app project (PROJECT_NAME, or '.' for the cwd).""" + from runpod.apps.init import create_project, detect_conflicts + from runpod.cli import console as ui + + if project_name is None or project_name == ".": + project_dir = Path.cwd() + name = project_dir.name + else: + project_dir = Path(project_name) + name = project_name + + conflicts = detect_conflicts(project_dir) + if conflicts and not force: + listing = ", ".join(conflicts) + _fail( + f"{listing} already exist{'s' if len(conflicts) == 1 else ''} " + f"in {project_dir}. pass --force to overwrite." + ) + + written = create_project(project_dir, name, overwrite=force) + ui.success( + f"initialized [white]{name}[/white] " + f"[dim]{len(written)} files[/dim]" + ) + ui.console.print() + if project_dir != Path.cwd(): + ui.console.print(f" [dim]cd {project_name}[/dim]") + ui.console.print(" [dim]rp login[/dim]") + ui.console.print(" [dim]rp flash dev main.py[/dim]") + ui.console.print() + + +# ---------------------------------------------------------------- update + + +@cli.command() +@click.option( + "--version", "-V", "version_opt", default=None, help="Target version." +) +def update(version_opt): + """Update the runpod package to the latest (or a given) version.""" + from runpod.cli import console as ui + from runpod.cli.update import ( + compare_versions, + current_version, + fetch_pypi_metadata, + parse_version, + run_install, + ) + + current = current_version() + ui.console.print(f"current version: [white]{current}[/white]") + + with ui.console.status("[dim]checking pypi ...[/dim]"): + try: + latest, releases = fetch_pypi_metadata() + except (ConnectionError, RuntimeError) as exc: + _fail(str(exc)) + + target = version_opt or latest + if target not in releases: + _fail(f"version '{target}' not found on pypi") + if current == target: + ui.console.print(f"already on [white]{target}[/white], nothing to do") + return + if ( + current != "unknown" + and compare_versions(parse_version(target), parse_version(current)) < 0 + ): + ui.warn(f"downgrading from {current} to {target}") + + with ui.console.status(f"[dim]installing runpod {target} ...[/dim]"): + try: + run_install(target) + except Exception as exc: # noqa: BLE001 - surface installer errors cleanly + _fail(str(exc)) + ui.success(f"updated to [white]{target}[/white]") + + +# ---------------------------------------------------------------- deploy + + +@flash.command() +@click.argument("target", required=False, type=click.Path(path_type=Path)) +@click.option("--env", "-e", "env", default=None, help="Target environment name.") +@click.option( + "--python-version", + default=None, + help="Worker python version for dependency wheels (3.11-3.14). " + "Defaults to the python running the cli.", +) +@click.option( + "--exclude", + default=None, + help="Comma-separated packages to exclude from the artifact " + "(they must then come from the worker image). Torch packages are " + "excluded automatically on builtin gpu images.", +) +@click.option( + "--build-only", + is_flag=True, + help="Build the artifact without deploying; writes " + "-artifact.tar.gz to the current directory.", +) +def deploy(target, env, python_version, exclude, build_only): + """Package and deploy all apps found in TARGET (default: cwd).""" + import logging + + from runpod.apps.deploy import build_artifact, deploy_app + from runpod.apps.discovery import discover_apps, resolve_project + from runpod.cli import console as ui + + logging.getLogger("runpod.apps").setLevel(logging.WARNING) + + if python_version is None: + from runpod.apps.images import ( + DEFAULT_PYTHON_VERSION, + local_python_version, + ) + + try: + python_version = local_python_version() + except RuntimeError: + # deployed calls are plain json (no pickle compat needed), + # so an unsupported local interpreter falls back instead of + # failing like dev does + ui.warn( + f"local python has no runtime image; building for " + f"{DEFAULT_PYTHON_VERSION} (override with --python-version)" + ) + python_version = DEFAULT_PYTHON_VERSION + + target = (target or Path.cwd()).resolve() + if not target.exists(): + _fail(f"{target} does not exist") + + try: + project = resolve_project(target) + apps = discover_apps(project.target, strict=True) + except Exception as exc: + _fail(str(exc)) + + project_root = project.source_root + + if build_only: + for found in apps: + ui.set_name_width(list(found.resources)) + events = ui.DeployEvents() + succeeded = False + try: + artifact = build_artifact( + found, + project_root, + python_version=python_version, + exclude=exclude.split(",") if exclude else None, + events=events, + output=Path.cwd() / f"{found.name}-artifact.tar.gz", + ) + succeeded = True + except Exception as exc: # noqa: BLE001 - surface engine errors cleanly + raise click.ClickException(str(exc)) from exc + finally: + events.close(failed=not succeeded) + size_mb = artifact.stat().st_size / (1024 * 1024) + ui.success( + f"built [white]{found.name}[/white] " + f"[dim]{artifact.name} ({size_mb:.1f} MB)[/dim]" + ) + return + + if len(apps) > 1: + ui.deploy_plan( + [ + ( + found.name, + _app_source(found, project_root), + len(found.resources), + ) + for found in apps + ] + ) + + for index, found in enumerate(apps): + if index or len(apps) > 1: + ui.console.print() + ui.set_name_width(list(found.resources)) + ui.deploy_banner( + found.name, + env or found.env, + [(h.spec.name, h.spec.kind.value) for h in found.resources.values()], + source=_app_source(found, project_root), + ) + events = ui.DeployEvents() + succeeded = False + with ui.Timer() as t: + try: + result = asyncio.run( + deploy_app( + found, + project_root, + env_name=env, + python_version=python_version, + exclude=exclude.split(",") if exclude else None, + events=events, + ) + ) + succeeded = True + except Exception as exc: # noqa: BLE001 - surface engine errors cleanly + raise click.ClickException(str(exc)) from exc + finally: + events.close(failed=not succeeded) + ui.success( + f"[bold white]{result.app_name}/{env or found.env}[/bold white] " + f"is live [dim]{t.elapsed:.1f}s[/dim]" + ) + if result.resources: + ui.console.print() + ui.resources_table( + ( + name, + handle.spec.kind.value, + ",".join(handle.spec.cpu or handle.spec.gpu or ["any"]), + result.endpoints.get(name, "registered"), + ) + for name, handle in sorted(found.resources.items()) + ) + ui.console.print() + + +# ------------------------------------------------------------------- dev + + +@flash.command() +@click.argument("target", default=".", type=click.Path(exists=True, path_type=Path)) +@click.option( + "--entrypoint", + "entrypoint_selector", + default=None, + help="Select a registered entry hook as module:function.", +) +@click.option( + "--once", + is_flag=True, + help="Provision, run an optional entry hook, tear down, and exit.", +) +def dev(target, once, entrypoint_selector): + """Start an interactive dev session for TARGET (default: cwd). + + Provisions temporary live endpoints, runs an optional + @runpod.local_entrypoint, watches the project for file changes, + and deletes the endpoints on exit. + """ + import logging + + from runpod.apps.dev import DevSession + from runpod.apps.discovery import discover_apps, resolve_project + from runpod.apps.entrypoint import ( + _clear_entrypoints, + _restore_entrypoints, + get_entrypoints, + run_entrypoint, + select_entrypoint, + ) + from runpod.apps.utils.names import dev_endpoint_name + from runpod.apps.watch import FileWatcher + from runpod.cli import console as ui + from runpod.error import AuthenticationError, auth_hint + + logging.getLogger("runpod.apps").setLevel(logging.WARNING) + + try: + project = resolve_project(target) + except Exception as exc: + _fail(str(exc)) + + os.environ["RUNPOD_DEV_SESSION"] = "1" + + def _scan(): + previous_entrypoints = get_entrypoints() + _clear_entrypoints() + try: + apps = discover_apps(project.target, strict=True) + entrypoint = select_entrypoint(entrypoint_selector) + except BaseException: + _restore_entrypoints(previous_entrypoints) + raise + return apps, entrypoint + + try: + apps, entrypoint = _scan() + except Exception as exc: + _fail(str(exc)) + + def _all_resource_names(app_list) -> list: + return [ + handle.spec.name + for a in app_list + for handle in a.resources.values() + ] + + def _table_rows(session: "DevSession") -> list: + rows = [] + for a in session.apps: + for handle in a.resources.values(): + spec = handle.spec + devices = spec.cpu or spec.gpu or ["any"] + hardware = ",".join( + device if isinstance(device, str) else device.value + for device in (devices if isinstance(devices, list) else [devices]) + ) + endpoint_id = session._endpoints.get( + dev_endpoint_name(a.name, spec.name), "" + ) or ("per-call" if spec.kind.value == "task" else "") + rows.append((spec.name, spec.kind.value, hardware, endpoint_id)) + return rows + + # daemon stdin reader: a blocked readline must never keep the + # process alive after ctrl-c (executor threads are joined at + # loop shutdown; a daemon thread is not) + import queue as _queue + import threading + + stdin_lines: _queue.Queue[str] = _queue.Queue() + + def _stdin_reader() -> None: + for line in sys.stdin: + stdin_lines.put(line) + stdin_lines.put("") # eof marker + + threading.Thread(target=_stdin_reader, daemon=True).start() + + async def _wait_for_rerun(watcher: "FileWatcher") -> str: + """race the enter key against a file change.""" + eof = False + while True: + if watcher.changed(): + return "changed" + if not eof: + try: + line = stdin_lines.get_nowait() + if line == "": + # piped stdin / ci: no interactive re-runs, + # keep watching files only + eof = True + else: + return "enter" + except _queue.Empty: + # no keypress this tick; fall through to the sleep + pass + await asyncio.sleep(0.5) + + # set by a second stop signal: teardown stops waiting for a running + # entrypoint + force_stop = asyncio.Event() + # once teardown starts, signals leave it to finish + tearing_down = False + + async def _run_entrypoint_cancellable(fn) -> None: + """run user code without blocking the event loop. + + cancellation waits for the entrypoint to finish so its remote + calls cannot race with session teardown, unless a second stop + signal forces teardown first. + """ + loop = asyncio.get_running_loop() + done: asyncio.Future[None] = loop.create_future() + + def _finish(exc: "BaseException | None") -> None: + if done.done(): + return + if exc is None: + done.set_result(None) + else: + done.set_exception(exc) + + def _report(exc: "BaseException | None") -> None: + try: + loop.call_soon_threadsafe(_finish, exc) + except RuntimeError: + # a forced stop closed the loop while this entrypoint ran + pass + + def _runner() -> None: + try: + run_entrypoint(fn) + # entrypoint control-flow exceptions must reach the loop, + # not die on this thread + except (Exception, KeyboardInterrupt, SystemExit) as exc: + # bind the exception now: `as exc` is unbound once the + # except block exits, before the loop callback runs + _report(exc) + else: + _report(None) + + # daemon: a forced stop must not leave process exit waiting on + # a long remote call + threading.Thread(target=_runner, daemon=True).start() + try: + return await asyncio.shield(done) + except asyncio.CancelledError: + await _settle_after_stop(done) + raise + + async def _settle_after_stop(done: "asyncio.Future[None]") -> None: + """after a stop, wait for the still-running entrypoint so its remote + calls cannot race teardown, unless a second signal forces the stop.""" + if done.done(): + _discard_result(done) + return + forced = asyncio.ensure_future(force_stop.wait()) + await asyncio.wait({done, forced}, return_when=asyncio.FIRST_COMPLETED) + forced.cancel() + done.add_done_callback(_discard_result) + + def _install_stop_signals() -> None: + """stop cleanly on sigint and sigterm. + + python only turns sigint into KeyboardInterrupt when it was not + ignored at startup, and shells start background jobs with sigint + ignored; sigterm has no handler at all. without these a stopped + session would leave its endpoints running. the first signal + cancels the session (teardown deletes the endpoints), the second + stops waiting for a running entrypoint. signals during teardown + are ignored so every endpoint still gets deleted. + """ + loop = asyncio.get_running_loop() + task = asyncio.current_task() + stopping = False + + def _on_signal() -> None: + nonlocal stopping + if tearing_down: + # cancelling teardown would skip the remaining deletes + return + if stopping: + force_stop.set() + else: + stopping = True + if task is not None: + task.cancel() + + for sig in (signal.SIGINT, signal.SIGTERM): + try: + loop.add_signal_handler(sig, _on_signal) + except (NotImplementedError, RuntimeError, ValueError): + # windows event loops have no signal handlers; ctrl-c + # still raises KeyboardInterrupt there + pass + + async def _session() -> int: + nonlocal apps, entrypoint, tearing_down + ui.set_name_width(_all_resource_names(apps)) + session = DevSession(apps, events=ui.DevEvents()) + watcher = FileWatcher([project.source_root]) + + ui.dev_banner([a.name for a in apps], str(project.target.name)) + _install_stop_signals() + try: + await session.start() + ui.resources_table(_table_rows(session)) + while True: + if entrypoint is not None: + ui.entrypoint_header(getattr(entrypoint, "__name__", "")) + with ui.Timer() as t: + try: + await _run_entrypoint_cancellable(entrypoint) + ui.entrypoint_success(t.so_far) + except asyncio.CancelledError: + raise + except Exception as exc: + ui.entrypoint_failure(t.so_far, str(exc)) + if once: + return 1 + if once: + return 0 + reload_failed = False + while True: + reason = await _wait_for_rerun(watcher) + if reason == "changed": + ui.reload_banner(str(project.target.name)) + try: + apps, entrypoint = _scan() + except Exception as exc: + ui.error(f"reload failed: {exc}; keeping current endpoints") + reload_failed = True + continue + ui.set_name_width(_all_resource_names(apps)) + await session.refresh(apps) + reload_failed = False + if not reload_failed: + break + finally: + tearing_down = True + events = ui.CleanupEvents() + try: + await session.stop(events=events) + finally: + events.close() + + try: + sys.exit(asyncio.run(_session())) + except (KeyboardInterrupt, EOFError, asyncio.CancelledError): + ui.console.print() + except AuthenticationError as exc: + raise click.ClickException(auth_hint()) from exc + except Exception as exc: # noqa: BLE001 - surface engine errors cleanly + raise click.ClickException(str(exc)) from exc + + +@cli.command() +@click.argument("shell", type=click.Choice(["bash", "zsh", "fish"])) +def completion(shell): + """Print the shell completion script for SHELL. + + Completes commands, flags, and resource IDs. Add this to your shell + profile: eval "$(rp completion zsh)" + """ + from click.shell_completion import get_completion_class + + complete = get_completion_class(shell)(cli, {}, "rp", "_RP_COMPLETE") + click.echo(complete.source()) + + +def _discard_result(future: "asyncio.Future[None]") -> None: + """mark an abandoned entrypoint's error as retrieved, so asyncio does + not log it as never retrieved.""" + if not future.cancelled(): + future.exception() + + +# ------------------------------------------------------------------ logs + + +@cli.command() +@click.argument("pod_id") +@click.option("--follow", "-f", is_flag=True, help="Stream logs as they arrive.") +@click.option( + "--type", + "log_type", + default="all", + show_default=True, + type=click.Choice(["all", "container", "system"]), + help="Log source.", +) +@click.option("--tail", default=100, show_default=True, help="Lines of backfill.") +def logs(pod_id, follow, log_type, tail): + """Show a pod's container and system logs.""" + from runpod.apps.logs import pod_logs, stream_pod_logs + + async def _run(): + if follow: + async for entry in stream_pod_logs( + pod_id, log_type=log_type, tail=tail + ): + source = entry.get("source", "?") + click.echo(f"[{source}] {entry.get('line', '')}") + else: + logs_data = await pod_logs(pod_id, log_type=log_type) + for source in ("system", "container"): + for line in logs_data.get(source) or []: + click.echo(f"[{source}] {line}") + + try: + asyncio.run(_run()) + except KeyboardInterrupt: + # ctrl-c ends the log follow; not an error + pass + + +# ----------------------------------------------------------------- login + + +@cli.command() +@click.option( + "--no-open", is_flag=True, help="Print the url instead of opening a browser." +) +@click.option( + "--api-key", + "api_key_opt", + default=None, + help="Store this API key directly (skips the browser flow).", +) +@click.option( + "--profile", + default=_default_profile, + show_default="RUNPOD_PROFILE, else default", + help="Credential profile.", +) +@click.option( + "--agent", + is_flag=True, + help="Sign in without prompting: use --email to request a code, then --code to complete login.", +) +@click.option("--email", default=None, help="Email address for --agent sign-in.") +@click.option( + "--code", + default=None, + help="Complete a pending --agent login with a six-digit code without prompting.", +) +def login(no_open, api_key_opt, profile, agent, email, code): + """Authenticate with Runpod and store the API key. + + Opens the Runpod console for browser approval by default, then asks + you to paste the API key the console shows. Pass --api-key to store a + key directly. Run --agent --email ADDRESS to email a verification code + and exit, then --agent --code CODE to complete login without prompting. + Use the same --profile for both commands. Pending + login state is stored in ~/.runpod with owner-only permissions and + deleted after credentials are saved. Treat the code as a secret. + Command arguments can appear in shell history and process listings. + """ + from runpod.auth.credentials import set_credentials + from runpod.auth.login import ( + LoginError, + browser_login, + load_agent_login, + pending_agent_login_path, + save_agent_login, + start_agent_login, + verify_agent_login, + ) + from runpod.cli import console as ui + + if agent and api_key_opt is not None: + raise click.UsageError("--agent cannot be combined with --api-key") + if code is not None and not agent: + raise click.UsageError("--code requires --agent") + if code is not None and email is not None: + raise click.UsageError( + "--code uses the pending login. Do not combine it with --email" + ) + if code is not None: + code = code.strip() + if len(code) != 6 or not code.isascii() or not code.isdigit(): + raise click.UsageError("--code must contain six ASCII digits") + if agent and code is None and (email is None or not email.strip()): + raise click.UsageError("--agent requires --email") + if email is not None and not agent: + raise click.UsageError("--email requires --agent") + + if api_key_opt: + try: + set_credentials(api_key_opt, profile=profile, overwrite=True) + except ValueError as exc: + _fail(str(exc)) + ui.success("credentials saved to [dim]~/.runpod/config.toml[/dim]") + return + + if not agent and not _stdin_is_tty(): + _fail( + "rp login needs an interactive terminal to paste the API key. " + "Set RUNPOD_API_KEY, run rp login --api-key YOUR_KEY, or add the " + "key to ~/.runpod/config.toml." + ) + + def _show_url(url: str) -> None: + ui.console.print() + ui.console.print(" [white]authorize in your browser:[/white]") + ui.console.print(f" [accent.light][link={url}]{url}[/link][/accent.light]") + ui.console.print( + " [dim]after approving, copy the API key the console shows[/dim]" + ) + ui.console.print() + if not no_open: + click.launch(url) + + def _prompt_key() -> str: + return click.prompt( + "paste API key", hide_input=True, default="", show_default=False + ) + + def _rejected(reason: str) -> None: + ui.console.print(f" [dim]{reason}, try again[/dim]") + + try: + if agent and code is None: + attempt = asyncio.run(start_agent_login(email.strip())) + save_agent_login(attempt, profile) + command = ["runpod", "login", "--agent", "--code", "CODE"] + if profile != "default": + command.extend(["--profile", profile]) + click.echo("A verification code was sent to your email.") + click.echo("Check your inbox, then run:") + click.echo(f"\n {shlex.join(command)}\n") + click.echo("Replace CODE with the six-digit code from your email.") + return + if code is not None: + api_key = asyncio.run(verify_agent_login(load_agent_login(profile), code)) + else: + api_key = asyncio.run( + browser_login( + prompt_key=_prompt_key, on_url=_show_url, on_rejected=_rejected + ) + ) + set_credentials(api_key, profile=profile, overwrite=True) + if code is not None: + pending_agent_login_path(profile).unlink(missing_ok=True) + except (LoginError, ValueError, OSError) as exc: + _fail(str(exc)) + ui.success("logged in, credentials saved to [dim]~/.runpod/config.toml[/dim]") + + +# ---------------------------------------------------------- app / env + + +def _fmt_ts(value) -> str: + if not value: + return "-" + text = str(value) + return text[:10] if len(text) >= 10 else text + + +@flash.group() +def app(): + """Manage deployed apps.""" + + +@app.command(name="list") +def app_list(): + """List all apps and their environments.""" + from runpod.apps.manage import list_apps + from runpod.cli import console as ui + + try: + apps = asyncio.run(list_apps()) + except Exception as exc: # noqa: BLE001 - surface engine errors cleanly + raise click.ClickException(str(exc)) from exc + + if not apps: + ui.console.print( + "\n no apps deployed. run [white]rp flash deploy[/white]\n" + ) + return + + width = max(len(a["name"]) for a in apps) + ui.console.print() + for entry in apps: + envs = entry.get("flashEnvironments") or [] + names = ", ".join(e["name"] for e in envs) or "-" + ui.console.print( + f" [white]{entry['name']:<{width}}[/white] [dim]{names}[/dim]" + ) + ui.console.print() + + +@app.command(name="get") +@click.argument("app_name") +def app_get(app_name): + """Show one app with its environments.""" + from runpod.apps.manage import get_app + from runpod.cli import console as ui + + try: + entry = asyncio.run(get_app(app_name)) + except Exception as exc: # noqa: BLE001 - surface engine errors cleanly + raise click.ClickException(str(exc)) from exc + + envs = entry.get("flashEnvironments") or [] + ui.console.print() + ui.console.print(f" [white]{entry['name']}[/white]") + if envs: + width = max(len(e["name"]) for e in envs) + for env_entry in envs: + build = (env_entry.get("activeBuildId") or "no build")[:12] + ui.console.print( + f" [white]{env_entry['name']:<{width}}[/white] [dim]{build}[/dim]" + ) + ui.console.print() + + +@app.command(name="delete") +@click.argument("app_name") +@click.option("--yes", "-y", is_flag=True, help="Skip the confirmation prompt.") +def app_delete(app_name, yes): + """Delete an app and its environments. Volumes are retained and keep billing.""" + from runpod.apps.manage import delete_app + from runpod.cli import console as ui + + ui.warn( + "app deletion retains network and global volumes, which continue billing. " + "Review them with `rp volume list`. " + "Delete unneeded volumes and their data with `rp volume delete VOLUME_ID`." + ) + if not yes: + click.confirm(f"delete app '{app_name}' and all its environments?", abort=True) + + events = ui.CleanupEvents() + try: + result = asyncio.run(delete_app(app_name, events=events)) + except Exception as exc: # noqa: BLE001 - surface engine errors cleanly + raise click.ClickException(str(exc)) from exc + finally: + events.close() + + if result.failures: + for failure in result.failures: + ui.error(failure) + raise click.ClickException("undeploy incomplete; app kept") + ui.success( + f"deleted [white]{app_name}[/white] " + f"[dim]{result.endpoints_deleted} endpoints removed[/dim]" + ) + + +@cli.group() +def registry(): + """Manage container registry credentials (private images).""" + + +@registry.command(name="add") +@click.argument("name", required=False) +@click.option("--username", default=None, help="Registry username (prompted if omitted).") +@click.option("--password", default=None, help="Registry password/token (prompted if omitted).") +def registry_add(name, username, password): + """Create a registry credential. Reference it with registry_auth=NAME.""" + from runpod.apps.api import AppsApiClient + from runpod.cli import console as ui + + if name is None: + name = click.prompt("name") + if username is None: + username = click.prompt("username") + if password is None: + password = click.prompt("password", hide_input=True) + + try: + asyncio.run( + AppsApiClient().create_registry_auth(name, username, password) + ) + except Exception as exc: # noqa: BLE001 - surface engine errors cleanly + raise click.ClickException(str(exc)) from exc + ui.success( + f"registry credential [white]{name}[/white] created, " + f'[dim]use registry_auth="{name}"[/dim]' + ) + + +@registry.command(name="list") +def registry_list(): + """List registry credential names.""" + from runpod.apps.api import AppsApiClient + from runpod.cli import console as ui + + try: + creds = asyncio.run(AppsApiClient().list_registry_auths()) + except Exception as exc: # noqa: BLE001 - surface engine errors cleanly + raise click.ClickException(str(exc)) from exc + + if not creds: + ui.console.print( + "\n no registry credentials. run [white]rp registry add [/white]\n" + ) + return + ui.console.print() + for entry in sorted(creds, key=lambda c: c["name"]): + ui.console.print(f" [white]{entry['name']}[/white] [dim]{entry['id']}[/dim]") + ui.console.print() + + +@registry.command(name="delete") +@click.argument("name") +@click.option("--yes", "-y", is_flag=True, help="Skip the confirmation prompt.") +def registry_delete(name, yes): + """Delete a registry credential by name.""" + from runpod.apps.api import AppsApiClient + from runpod.cli import console as ui + + async def _delete(): + client = AppsApiClient() + creds = await client.list_registry_auths() + match = next((c for c in creds if c["name"] == name), None) + if match is None: + _fail(f"no registry credential named '{name}'") + await client.delete_registry_auth(match["id"]) + + if not yes: + click.confirm(f"delete registry credential '{name}'?", abort=True) + try: + asyncio.run(_delete()) + except click.ClickException: + raise + except Exception as exc: # noqa: BLE001 - surface engine errors cleanly + raise click.ClickException(str(exc)) from exc + ui.success(f"deleted registry credential [white]{name}[/white]") + + +@cli.group() +def secret(): + """Manage platform secrets (encrypted env values).""" + + +@secret.command(name="add") +@click.argument("name", required=False) +@click.option("--value", default=None, help="Secret value (prompted if omitted).") +@click.option("--description", default="", help="Optional description.") +def secret_add(name, value, description): + """Create a secret. Reference it with runpod.Secret(NAME). + + Prompts for anything not provided: bare `rp secret add` asks for + name and value, `rp secret add NAME` asks for just the value. + """ + from runpod.apps.api import AppsApiClient + from runpod.cli import console as ui + + if name is None: + name = click.prompt("name") + if value is None: + value = click.prompt("value", hide_input=True) + + try: + asyncio.run(AppsApiClient().create_secret(name, value, description)) + except Exception as exc: # noqa: BLE001 - surface engine errors cleanly + raise click.ClickException(str(exc)) from exc + ui.success( + f"secret [white]{name}[/white] created, " + f"[dim]use runpod.Secret(\"{name}\")[/dim]" + ) + + +@secret.command(name="list") +def secret_list(): + """List secret names (values are never shown).""" + from runpod.apps.api import AppsApiClient + from runpod.cli import console as ui + + try: + secrets = asyncio.run(AppsApiClient().list_secrets()) + except Exception as exc: # noqa: BLE001 - surface engine errors cleanly + raise click.ClickException(str(exc)) from exc + + if not secrets: + ui.console.print("\n no secrets. run [white]rp secret add [/white]\n") + return + ui.console.print() + width = max(len(s["name"]) for s in secrets) + for entry in sorted(secrets, key=lambda s: s["name"]): + description = entry.get("description") or "" + ui.console.print( + f" [white]{entry['name']:<{width}}[/white] [dim]{description}[/dim]" + ) + ui.console.print() + + +@secret.command(name="delete") +@click.argument("name") +@click.option("--yes", "-y", is_flag=True, help="Skip the confirmation prompt.") +def secret_delete(name, yes): + """Delete a secret by name.""" + from runpod.apps.api import AppsApiClient + from runpod.cli import console as ui + + async def _delete(): + client = AppsApiClient() + secrets = await client.list_secrets() + match = next((s for s in secrets if s["name"] == name), None) + if match is None: + _fail(f"no secret named '{name}'") + await client.delete_secret(match["id"]) + + if not yes: + click.confirm(f"delete secret '{name}'?", abort=True) + try: + asyncio.run(_delete()) + except click.ClickException: + raise + except Exception as exc: # noqa: BLE001 - surface engine errors cleanly + raise click.ClickException(str(exc)) from exc + ui.success(f"deleted secret [white]{name}[/white]") + + +@flash.group() +def env(): + """Manage app environments.""" + + +def _resolve_app_name(app_name) -> str: + """--app flag or the single app discovered in cwd.""" + if app_name: + return app_name + from runpod.apps.discovery import DiscoveryError, discover_apps + + try: + apps = discover_apps(Path.cwd()) + except DiscoveryError: + apps = [] + if len(apps) == 1: + return apps[0].name + _fail("pass --app (no unique app found in the current directory)") + + +@env.command(name="list") +@click.option("--app", "-a", "app_name", default=None, help="App name.") +def env_list(app_name): + """List environments for an app.""" + from runpod.apps.manage import get_app + from runpod.cli import console as ui + + name = _resolve_app_name(app_name) + try: + entry = asyncio.run(get_app(name)) + except Exception as exc: # noqa: BLE001 - surface engine errors cleanly + raise click.ClickException(str(exc)) from exc + + envs = entry.get("flashEnvironments") or [] + if not envs: + ui.console.print( + f"\n no environments in [white]{name}[/white]. " + f"run [white]rp flash deploy[/white]\n" + ) + return + ui.console.print() + width = max(len(e["name"]) for e in envs) + for env_entry in envs: + build = (env_entry.get("activeBuildId") or "-")[:12] + ui.console.print( + f" [white]{env_entry['name']:<{width}}[/white] " + f"[dim]{build}, {_fmt_ts(env_entry.get('createdAt'))}[/dim]" + ) + ui.console.print() + + +@env.command(name="get") +@click.argument("env_name") +@click.option("--app", "-a", "app_name", default=None, help="App name.") +def env_get(env_name, app_name): + """Show an environment with its endpoints.""" + from runpod.apps.manage import get_environment + from runpod.cli import console as ui + + name = _resolve_app_name(app_name) + try: + entry = asyncio.run(get_environment(name, env_name)) + except Exception as exc: # noqa: BLE001 - surface engine errors cleanly + raise click.ClickException(str(exc)) from exc + + ui.console.print() + ui.console.print( + f" [white]{name}/{entry['name']}[/white] " + f"[dim]build {(entry.get('activeBuildId') or '-')[:12]}[/dim]" + ) + endpoints = entry.get("endpoints") or [] + if endpoints: + width = max(len(e["name"]) for e in endpoints) + for endpoint in endpoints: + ui.console.print( + f" [white]{endpoint['name']:<{width}}[/white] " + f"{ui.endpoint_link(endpoint['id'])}" + ) + ui.console.print() + + +@env.command(name="add") +@click.argument("env_name") +@click.option("--app", "-a", "app_name", default=None, help="App name.") +def env_add(env_name, app_name): + """Create a new environment in an app.""" + from runpod.apps.api import AppsApiClient + from runpod.apps.manage import get_app + from runpod.cli import console as ui + + name = _resolve_app_name(app_name) + + async def _create(): + client = AppsApiClient() + entry = await get_app(name, api=client) + return await client.create_environment(entry["id"], env_name) + + try: + asyncio.run(_create()) + except Exception as exc: # noqa: BLE001 - surface engine errors cleanly + raise click.ClickException(str(exc)) from exc + ui.success(f"created [white]{name}/{env_name}[/white]") + + +@env.command(name="delete") +@click.argument("env_name") +@click.option("--app", "-a", "app_name", default=None, help="App name.") +@click.option("--yes", "-y", is_flag=True, help="Skip the confirmation prompt.") +def env_delete(env_name, app_name, yes): + """Undeploy and delete an environment.""" + from runpod.apps.manage import undeploy_environment + from runpod.cli import console as ui + + name = _resolve_app_name(app_name) + if not yes: + click.confirm( + f"undeploy and delete '{name}/{env_name}'?", abort=True + ) + + events = ui.CleanupEvents() + try: + result = asyncio.run( + undeploy_environment(name, env_name, events=events) + ) + except Exception as exc: # noqa: BLE001 - surface engine errors cleanly + raise click.ClickException(str(exc)) from exc + finally: + events.close() + + if result.failures: + for failure in result.failures: + ui.error(failure) + raise click.ClickException("undeploy incomplete; environment kept") + ui.success( + f"deleted [white]{name}/{env_name}[/white] " + f"[dim]{result.endpoints_deleted} endpoints removed[/dim]" + ) + + +@flash.command() +@click.option("--app", "-a", "app_name", default=None, help="App name.") +@click.option("--env", "-e", "env_name", default="default", show_default=True) +@click.option("--yes", "-y", is_flag=True, help="Skip the confirmation prompt.") +def undeploy(app_name, env_name, yes): + """Tear down a deployed environment's endpoints. + + Deletes the environment's endpoints and the environment itself; + the app and its build history remain. + """ + from runpod.apps.manage import undeploy_environment + from runpod.cli import console as ui + + name = _resolve_app_name(app_name) + if not yes: + click.confirm(f"undeploy '{name}/{env_name}'?", abort=True) + + events = ui.CleanupEvents() + try: + result = asyncio.run( + undeploy_environment(name, env_name, events=events) + ) + except Exception as exc: # noqa: BLE001 - surface engine errors cleanly + raise click.ClickException(str(exc)) from exc + finally: + events.close() + + if result.failures: + for failure in result.failures: + ui.error(failure) + raise click.ClickException("undeploy incomplete") + ui.success( + f"undeployed [white]{name}/{env_name}[/white] " + f"[dim]{result.endpoints_deleted} endpoints removed[/dim]" + ) + + +# -------------------------------------------------------- legacy groups + + +def _mount_groups() -> None: + from runpod.cli.catalog import catalog + from runpod.cli.datacenter import datacenter + from runpod.cli.endpoint import endpoint + from runpod.cli.groups.ssh.commands import ssh_cli + from runpod.cli.pod import pod + from runpod.cli.template import template + from runpod.cli.user import user + from runpod.cli.volume import volume + + for command in ( + ssh_cli, + pod, + catalog, + volume, + endpoint, + template, + user, + datacenter, + ): + cli.add_command(command) + cli.add_command(user, name="account") + cli.add_command(user, name="me") + + +_mount_groups() + + +def run() -> None: + """console-script entry point.""" + for stream in (sys.stdout, sys.stderr): + reconfigure = getattr(stream, "reconfigure", None) + if callable(reconfigure): + reconfigure(errors="replace") + cli() + + +if __name__ == "__main__": + run() diff --git a/runpod/cli/options.py b/runpod/cli/options.py new file mode 100644 index 000000000..7caffd3dc --- /dev/null +++ b/runpod/cli/options.py @@ -0,0 +1,66 @@ +"""value parsing shared by resource command options.""" + +import shlex +from collections.abc import Iterable + +import click + +from runpod.cli.api import list_all +from runpod.cli.compute import ResolutionError + +DEFAULT_MOUNT_PATH = "/workspace" + + +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 diff --git a/runpod/cli/output.py b/runpod/cli/output.py new file mode 100644 index 000000000..4bb14444f --- /dev/null +++ b/runpod/cli/output.py @@ -0,0 +1,115 @@ +"""output, picker, prompt, and completion helpers shared by resource commands.""" + +import json +import shutil +import sys +from collections.abc import Callable, Iterable, Sequence +from typing import Any + +import click +from click.shell_completion import CompletionItem + +Column = tuple[str, Callable[[dict], Any]] + +json_option = click.option( + "--json", "as_json", is_flag=True, help="Print JSON for scripts and agents." +) + + +def print_json(data: Any) -> None: + click.echo(json.dumps(data, indent=2, default=str)) + + +def cell(value: Any) -> str: + if value is None or value == "" or value == [] or value == {}: + return "-" + if isinstance(value, bool): + return "yes" if value else "no" + if isinstance(value, (list, tuple)): + return ", ".join(str(item) for item in value) + return str(value) + + +def table(rows: Sequence[dict], columns: Sequence[Column]): + from rich.markup import escape + from rich.table import Table + + result = Table(box=None, header_style="dim", pad_edge=False) + for index, (header, _) in enumerate(columns): + result.add_column(header, no_wrap=index == 0, overflow="fold") + for row in rows: + result.add_row(*(escape(cell(value(row))) for _, value in columns)) + return result + + +def print_table(rows: Sequence[dict], columns: Sequence[Column], empty: str) -> None: + from runpod.cli import console as ui + + ui.console.print(table(rows, columns) if rows else f"[dim]{empty}[/dim]") + + +def print_fields(record: dict, fields: Sequence[Column]) -> None: + from rich.markup import escape + from rich.table import Table + + from runpod.cli import console as ui + + result = Table.grid(padding=(0, 2)) + result.add_column(style="dim", no_wrap=True) + result.add_column(overflow="fold") + for label, value in fields: + result.add_row(label, escape(cell(value(record)))) + ui.console.print(result) + + +def interactive() -> bool: + return sys.stdin.isatty() and sys.stdout.isatty() + + +def pick(message: str, choices: Sequence[tuple[str, str]], missing: str) -> str: + if not interactive(): + raise click.UsageError(missing) + if not choices: + raise click.UsageError(f"{missing} (none found)") + from InquirerPy import inquirer + from InquirerPy.base.control import Choice + from rich.text import Text + + width = max(1, shutil.get_terminal_size().columns - Text(message).cell_len - 3) + items = [] + for value, label in choices: + name = Text(label) + name.truncate(width, overflow="ellipsis") + items.append(Choice(value, name=name.plain)) + return inquirer.fuzzy( + message=message, + choices=items, + wrap_lines=False, + ).execute() + + +def confirm(message: str, yes: bool) -> None: + if yes: + return + if not interactive(): + raise click.UsageError("pass --yes to confirm in a non-interactive shell") + click.confirm(message, abort=True) + + +def completer( + fetch: Callable[[], Iterable[tuple[str, str]]], +) -> Callable[[click.Context, click.Parameter, str], list[CompletionItem]]: + """shell completion offering (value, help) pairs from fetch.""" + + def complete(ctx, param, incomplete): + try: + entries = list(fetch()) + except Exception: + return [] + return [ + CompletionItem(value, help=label) + for value, label in entries + if value.startswith(incomplete) + ] + + return complete diff --git a/runpod/cli/pod.py b/runpod/cli/pod.py new file mode 100644 index 000000000..72b96574f --- /dev/null +++ b/runpod/cli/pod.py @@ -0,0 +1,846 @@ +import posixpath +import time +from operator import itemgetter +from typing import NotRequired, TypedDict + +import click + +from runpod._hosts import proxy_url +from runpod.api.rest import run_rest_request +from runpod.cli import compute +from runpod.cli.api import api_errors, list_all +from runpod.cli.groups.pod.commands import sync_pods +from runpod.cli.options import DEFAULT_MOUNT_PATH, container_fields +from runpod.cli.output import ( + completer, + confirm, + interactive, + json_option, + pick, + print_fields, + print_json, + print_table, +) +from runpod.cli.volume import _choices as volume_choices, _get_volume +from runpod.error import QueryError + +STATUSES = ["PROVISIONING", "STARTING", "RUNNING", "EXITED", "ERROR", "TERMINATED"] +WAIT_TIMEOUT = 600 +WAIT_INTERVAL = 5 + + +class _PersistentMount(TypedDict): + size: int + path: str + + +class _VolumeMount(TypedDict): + volumeId: str + path: NotRequired[str] + + +def _pod_choices(action: str | None = None) -> list[tuple[str, str]]: + return [ + (pod["id"], f"{pod['name']} {pod['status'].lower()}") + for pod in list_all("/v2/pods", "pods") + if action is None or action in pod["actions"] + ] + + +def _resolve_pod_id(pod_id: str | None, action: str | None = None) -> str: + if pod_id: + return pod_id + choices = [] + if interactive(): + with api_errors(): + choices = _pod_choices(action) + return pick("pod", choices, "pass a POD_ID") + + +_complete_pods = completer(_pod_choices) +_complete_datacenters = completer( + lambda: [ + (dc["id"], (dc.get("region") or "").lower()) + for dc in compute.list_datacenters() + ] +) +_complete_volumes = completer(volume_choices) +_complete_registries = completer( + lambda: [ + (registry["name"], registry["id"]) + for registry in list_all("/v2/registries", "registries") + ] +) + + +def _say(message: str, as_json: bool, warning: bool = False) -> None: + if as_json: + click.echo(message, err=True) + return + from rich.markup import escape + + from runpod.cli import console as ui + + (ui.warn if warning else ui.info)(escape(message)) + + +def _status(pod: dict) -> str: + status = pod["status"].lower() + if status == "running" and not (pod.get("runtime") or {}).get("uptime"): + return "starting" + return status + + +def _summary(pod: dict) -> dict: + hardware = pod.get("gpu") or pod.get("cpu") or {} + description = None + if pod.get("gpu"): + description = f"{hardware['count']}x {hardware['id']}" + elif pod.get("cpu"): + description = f"{hardware['id']} {hardware['vcpuCount']} vcpu" + return { + "id": pod["id"], + "name": pod["name"], + "status": _status(pod), + "hardware": description, + "data center": pod.get("dataCenterId"), + "cost": f"${pod['cost']:.2f}/hr" if pod.get("cost") else None, + "image": pod["image"], + } + + +def _show(pod: dict, as_json: bool) -> None: + if as_json: + print_json(pod) + return + runtime = pod.get("runtime") or {} + mounts = pod.get("mounts") or {} + networking = pod.get("globalNetworking") or {} + ssh = pod.get("ssh") or {} + hardware = pod.get("gpu") or pod.get("cpu") or {} + volumes = [] + if mounts.get("persistent"): + volume = mounts["persistent"] + volumes.append(f"persistent {volume['size']}GB at {volume['path']}") + for kind in ("network", "global"): + for volume in mounts.get(kind, []): + volumes.append( + f"{kind} {volume['volumeId']} at {volume.get('path') or '-'}" + ) + uptime = None + if runtime.get("uptime"): + minutes, seconds = divmod(runtime["uptime"], 60) + hours, minutes = divmod(minutes, 60) + uptime = f"{hours}h {minutes}m" if hours else f"{minutes}m {seconds}s" + if not hours and not minutes: + uptime = f"{seconds}s" + fields = { + **_summary(pod), + "resources": [ + f"{hardware[key]:g}{unit}" + for key, unit in (("vcpuCount", " vcpu"), ("memory", "GB ram")) + if hardware.get(key) + ], + "cloud": (pod.get("cloud") or "").lower(), + "cuda": pod.get("cudaVersion"), + "disk": f"{pod['disk']}GB" if pod.get("disk") else None, + "volumes": volumes, + "ports": pod.get("ports"), + "env": sorted(pod.get("env") or {}), + "command": pod.get("args"), + "locked": pod.get("locked"), + "global network": bool(networking.get("enabled")) + and (networking.get("internalDns") or networking.get("ip") or True), + "cluster": (pod.get("cluster") or {}).get("id"), + "created": pod.get("createdAt"), + "started": pod.get("startedAt"), + "uptime": uptime, + "actions": pod["actions"], + "ssh": (ssh.get("proxy") or {}).get("command"), + "ssh direct": (ssh.get("direct") or {}).get("command"), + "urls": [ + proxy_url(pod["id"], port.split("/")[0]) + for port in pod.get("ports", []) + if port.endswith("/http") + ], + "tcp": [ + f"{port['ip']}:{port['public']} -> {port['private']}" + for port in runtime.get("ports", []) + if port["type"] == "tcp" and port.get("ip") and port.get("public") + ], + } + print_fields(fields, [(label, itemgetter(label)) for label in fields]) + + +def _wait_running(pod_id: str, since: float, previous: dict | None = None) -> dict: + from runpod.cli import console as ui + + deadline = time.monotonic() + WAIT_TIMEOUT + previous_uptime = ((previous or {}).get("runtime") or {}).get("uptime") or 0 + runtime_restarted = previous is None + with ui.console.status(f"[dim]waiting for {pod_id} to start ...[/dim]"): + while True: + pod = run_rest_request("GET", f"/v2/pods/{pod_id}") + if pod is None: + raise QueryError(f"empty response for pod {pod_id}") + status = _status(pod) + uptime = pod["runtime"]["uptime"] if status == "running" else 0 + if status != "running" or uptime < previous_uptime: + runtime_restarted = True + new_start = previous is None or ( + pod.get("startedAt") and pod["startedAt"] != previous.get("startedAt") + ) + if ( + status == "running" + and new_start + and runtime_restarted + and uptime <= time.monotonic() - since + 1 + ): + return pod + if status in ("error", "terminated"): + raise click.ClickException(f"pod {pod_id} is {status}") + if time.monotonic() >= deadline: + raise click.ClickException( + f"pod {pod_id} is still {status or 'unknown'} after {WAIT_TIMEOUT}s" + ) + time.sleep(WAIT_INTERVAL) + + +def _container_body( + options: dict, current: dict | None = None, unset_env=(), network_centers=None +) -> dict: + """build container settings, preserving existing environment and mount paths.""" + current = current or {} + body = container_fields(options, current, unset_env) + mounts: dict[str, _PersistentMount | list[_VolumeMount]] = {} + values: list[tuple[str | None, str]] = ( + [("persistent", options["persistent_volume"])] + if options["persistent_volume"] is not None + else [] + ) + values.extend((None, value) for value in options["volume"]) + for kind, value in values: + head, sep, path = value.partition(":") + flag = "--persistent-volume" if kind == "persistent" else "--volume" + if not head or (sep and not path): + raise click.BadParameter( + f"'{value}' should look like VALUE[:PATH]", param_hint=flag + ) + if kind is None: + kind, record = _get_volume(head) + if kind == "network" and network_centers is not None: + network_centers.add(record["dataCenter"]) + existing = (current.get("mounts") or {}).get(kind) + if kind != "persistent": + existing = next( + (mount for mount in existing or [] if mount["volumeId"] == head), None + ) + path = path or (existing or {}).get("path") or "" + if kind != "global": + path = path or DEFAULT_MOUNT_PATH + if kind == "persistent": + if not head.isdigit(): + raise click.BadParameter( + "size is in GB, like 50 or 50:/workspace", param_hint=flag + ) + mounts[kind] = {"size": int(head), "path": path} + else: + entries = mounts.setdefault(kind, []) + assert isinstance(entries, list) + if any(mount["volumeId"] == head for mount in entries): + raise click.BadParameter( + f"volume {head!r} is specified more than once", param_hint=flag + ) + volume_mount: _VolumeMount = {"volumeId": head} + if path: + volume_mount["path"] = path + entries.append(volume_mount) + if mounts: + effective_mounts = dict(current.get("mounts") or {}) + for kind, mount_entries in mounts.items(): + if isinstance(mount_entries, dict): + effective_mounts[kind] = mount_entries + continue + replaced_ids = {mount["volumeId"] for mount in mount_entries} + effective_mounts[kind] = [ + mount + for mount in effective_mounts.get(kind) or [] + if mount["volumeId"] not in replaced_ids + ] + mount_entries + paths = set() + for kind, entries in effective_mounts.items(): + if not entries: + continue + for mount in ([entries] if kind == "persistent" else entries): + if not mount.get("path"): + continue + path = posixpath.normpath(mount["path"]) + if path.startswith("//"): + path = path[1:] + if path in paths: + raise click.UsageError( + f"multiple volumes target {path!r}. use a distinct :PATH for each volume" + ) + paths.add(path) + body["mounts"] = mounts + return body + + +_CONTAINER_OPTIONS = [ + click.option( + "--image", default=None, help="Container image, like runpod/pytorch:latest." + ), + click.option( + "--template", + default=None, + help="Template id whose container settings to apply.", + ), + click.option( + "--env", + "-e", + multiple=True, + metavar="KEY=VALUE", + help="Environment variable. Repeatable.", + ), + click.option( + "--port", + "-p", + "ports", + multiple=True, + metavar="PORT/PROTO", + help="Exposed port like 8888/http or 22/tcp. Repeatable.", + ), + click.option( + "--disk", type=click.IntRange(min=1), default=None, help="Container disk in GB." + ), + click.option( + "--persistent-volume", + metavar="GB[:PATH]", + default=None, + help=f"Host-local persistent volume (path defaults to {DEFAULT_MOUNT_PATH}).", + ), + click.option( + "--volume", + metavar="ID[:PATH]", + multiple=True, + shell_complete=_complete_volumes, + help="Network or global volume to mount, resolved by ID. Repeatable. " + f"Network paths default to {DEFAULT_MOUNT_PATH}.", + ), + click.option( + "--args", + default=None, + help="Container start command as one raw string ('' clears).", + ), + click.option( + "--cmd", + default=None, + help="Container CMD as a shell string, split into exec form.", + ), + click.option( + "--entrypoint", + default=None, + help="Container ENTRYPOINT as a shell string, split into exec form.", + ), + click.option( + "--registry", + default=None, + shell_complete=_complete_registries, + help="Registry credential name or id for private images ('' clears).", + ), + click.option( + "--global-networking/--no-global-networking", + default=None, + help="Private networking across data centers (NVIDIA GPUs only).", + ), +] + + +def _container_options(command): + for option in reversed(_CONTAINER_OPTIONS): + command = option(command) + return command + + +def _gpu_body( + spec: str, + count: int | None, + cloud: str, + cuda: tuple[str, ...], + datacenter_ids: list[str], + min_ram: int | None, + min_vcpu: int | None, + as_json: bool, +) -> dict: + """resolve a GPU specification by stock and price, then build its request.""" + query, spec_count = compute.parse_gpu_spec(spec) + if spec_count and count and spec_count != count: + raise click.UsageError(f"--gpu {spec} conflicts with --gpu-count {count}") + count = spec_count or count or 1 + min_cuda, exact_cuda = compute.parse_cuda(cuda) + gpus = compute.list_gpus( + product="POD", + count=count, + cloud=cloud.upper(), + cuda_versions=exact_cuda, + min_cuda_version=min_cuda, + ) + matches = compute.resolve_gpus(query, gpus) + allowed = set(datacenter_ids) + + def stock(gpu: dict) -> str: + if not allowed: + return gpu.get("availability") or "NONE" + return compute.best_availability( + dc.get("availability") + for dc in gpu.get("dataCenters") or [] + if dc["id"] in allowed + ) + + offered = [ + gpu + for gpu in matches + if len(matches) == 1 + or ( + gpu.get(cloud, True) + and (gpu.get("maxCount") or {}).get(cloud, count) >= count + ) + ] + if not offered: + names = ", ".join(gpu.get("name") or gpu["id"] for gpu in matches) + raise compute.ResolutionError( + f"no '{query}' gpu ({names}) offers {count} per pod on {cloud} cloud" + ) + best = min( + offered, + key=lambda gpu: ( + -compute.availability_rank(stock(gpu)), + (gpu.get("price") or {}).get(cloud) or float("inf"), + gpu.get("name") or gpu["id"], + ), + ) + availability = stock(best) + label = best.get("name") or best["id"] + price = (best.get("price") or {}).get(cloud) + if len(matches) > 1: + cost = f", ${price * count:.2f}/hr" if price else "" + _say( + f"'{query}' matches {len(matches)} gpu types; using {label} " + f"({best['id']}): {'no' if availability == 'NONE' else availability.lower()} stock{cost}", + as_json, + ) + if availability == "NONE": + _say( + f"the catalog reports no {cloud} stock for {count}x {label} " + "in the requested data centers; creation may fail", + as_json, + warning=True, + ) + body = {"id": best["id"], "count": count} + for field, value in ( + ("minCudaVersion", min_cuda), + ("allowedCudaVersions", exact_cuda), + ("minRamPerGpu", min_ram), + ("minVcpuCountPerGpu", min_vcpu), + ): + if value: + body[field] = value + return body + + +def _datacenter_ids(regions, data_centers, network_centers) -> list[str]: + ids = ( + compute.resolve_regions(regions, compute.list_datacenters()) if regions else [] + ) + ids += [dc for dc in data_centers if dc not in ids] + if len(network_centers) > 1: + raise click.UsageError("a pod's network volumes must share a data center") + if network_centers: + center = next(iter(network_centers)) + if ids and center not in ids: + raise click.UsageError( + f"network volumes are in {center}, outside the requested placement" + ) + ids = ids or [center] + return ids + + +def _create_body( + name, + gpu, + gpu_count, + cpu, + vcpu, + cloud, + regions, + data_centers, + cuda, + min_ram_per_gpu, + min_vcpu_per_gpu, + ssh, + jupyter, + as_json, + **container, +): + if gpu and cpu: + raise click.UsageError("use either --gpu or --cpu") + if not gpu and not cpu: + raise click.UsageError("pass --gpu (like 4090 or h100:2) or --cpu (like cpu3c)") + if cpu and (gpu_count or cuda or min_ram_per_gpu or min_vcpu_per_gpu): + raise click.UsageError( + "--gpu-count, --cuda, --min-ram-per-gpu, and --min-vcpu-per-gpu apply to gpu pods" + ) + if vcpu and not cpu: + raise click.UsageError("--vcpu applies to cpu pods") + if not container["image"] and not container["template"]: + raise click.UsageError("pass --image or --template") + if not name: + if not interactive(): + raise click.UsageError("pass a NAME") + name = click.prompt("pod name") + + network_centers = set() + body = { + "name": name, + **_container_body(container, network_centers=network_centers), + } + datacenter_ids = _datacenter_ids(regions, data_centers, network_centers) + if datacenter_ids: + body["dataCenterIds"] = datacenter_ids + if cloud: + body["cloud"] = cloud.upper() + + if gpu: + body["gpu"] = _gpu_body( + gpu, + gpu_count, + (cloud or "secure").lower(), + cuda, + datacenter_ids, + min_ram_per_gpu, + min_vcpu_per_gpu, + as_json, + ) + else: + flavor = compute.resolve_cpu( + cpu, compute.list_cpus(product="POD", vcpu_count=vcpu) + ) + body["cpu"] = { + "id": flavor["id"], + "vcpuCount": vcpu or (flavor.get("vcpu") or {}).get("min") or 2, + } + + if ssh: + body["startSsh"] = True + keys = run_rest_request("GET", "/v2/account/ssh-keys")["keys"] + if not keys: + _say( + "your account has no ssh keys, so --ssh has no effect. " + "add one with rp ssh add", + as_json, + warning=True, + ) + if jupyter: + body["startJupyter"] = True + + return body + + +@click.group("pod") +def pod(): + """Create and manage pods.""" + + +@pod.command(name="list") +@click.option("--name", default=None, help="Only pods whose name contains this text.") +@click.option( + "--status", + "statuses", + multiple=True, + type=click.Choice(STATUSES, case_sensitive=False), + help="Only pods in this status. Repeatable.", +) +@click.option( + "--include-cluster-pods", is_flag=True, help="Include cluster member pods." +) +@json_option +def list_pods(name, statuses, include_cluster_pods, as_json): + """List your pods.""" + with api_errors(): + params = {"includeClusterPods": "true"} if include_cluster_pods else None + pods = list_all("/v2/pods", "pods", params) + if name: + pods = [p for p in pods if name.lower() in (p.get("name") or "").lower()] + if statuses: + wanted = {status.lower() for status in statuses} + pods = [p for p in pods if _status(p) in wanted] + if as_json: + print_json(pods) + return + columns = ["id", "name", "status", "hardware", "data center", "cost", "image"] + print_table( + [_summary(p) for p in pods], + [(label.upper(), itemgetter(label)) for label in columns], + "no pods. create one with rp pod create", + ) + + +@pod.command() +@click.argument("pod_id", required=False, shell_complete=_complete_pods) +@json_option +def get(pod_id, as_json): + """Show a pod with its connection details.""" + pod_id = _resolve_pod_id(pod_id) + with api_errors(): + _show(run_rest_request("GET", f"/v2/pods/{pod_id}"), as_json) + + +@pod.command() +@click.argument("name", required=False) +@click.option( + "--gpu", default=None, metavar="TYPE[:COUNT]", help="GPU type like 4090 or h100:2." +) +@click.option( + "--gpu-count", type=click.IntRange(min=1), default=None, help="GPUs per pod." +) +@click.option( + "--cpu", default=None, help="CPU flavor like cpu3c or cpu5g, for a CPU pod." +) +@click.option( + "--vcpu", + type=click.IntRange(min=2), + default=None, + help="vCPUs for a CPU pod (defaults to the flavor's minimum).", +) +@click.option( + "--cloud", + type=click.Choice(["secure", "community"], case_sensitive=False), + default=None, + help="Cloud tier (the api defaults to secure).", +) +@click.option( + "--region", + "regions", + multiple=True, + help="Region (eu, na, asia), id prefix (us, eu-ro), or data center id. Repeatable.", +) +@click.option( + "--data-center", + "data_centers", + multiple=True, + shell_complete=_complete_datacenters, + help="Exact data center id like US-TX-3. Repeatable.", +) +@click.option( + "--cuda", + multiple=True, + help="Host CUDA: '>=12.4' for a floor, 12.4 or 12.4,12.8 for exact versions.", +) +@click.option( + "--min-ram-per-gpu", + type=click.IntRange(min=1), + default=None, + help="Minimum host RAM in GB per GPU.", +) +@click.option( + "--min-vcpu-per-gpu", + type=click.IntRange(min=1), + default=None, + help="Minimum host vCPUs per GPU.", +) +@_container_options +@click.option("--ssh", is_flag=True, help="Start sshd with your account's SSH keys.") +@click.option( + "--jupyter", is_flag=True, help="Start JupyterLab (expose 8888/http to reach it)." +) +@click.option("--wait", is_flag=True, help="Wait until the pod is running.") +@json_option +def create(name, wait, as_json, **options): + """Create a pod named NAME. + + GPU types are human-readable (4090, h100, a100-sxm). When a name + matches several types, the one with the most stock in the requested + regions wins, then the cheapest. + + \b + rp pod create trainer --gpu h100:2 --image runpod/pytorch:latest --region eu --ssh + rp pod create box --cpu cpu3c --vcpu 4 --image ubuntu:24.04 + rp pod create nb --gpu 4090 --image runpod/pytorch:latest --jupyter -p 8888/http + """ + with api_errors(): + body = _create_body(name, as_json=as_json, **options) + since = time.monotonic() + created = run_rest_request("POST", "/v2/pods", json=body) + _say(f"created pod {created['name']} ({created['id']})", as_json) + if wait: + created = _wait_running(created["id"], since) + _show(created, as_json) + + +@pod.command() +@click.argument("pod_id", required=False, shell_complete=_complete_pods) +@click.option("--name", default=None, help="New pod name.") +@_container_options +@click.option( + "--unset-env", + multiple=True, + metavar="KEY", + help="Remove an environment variable. Repeatable.", +) +@click.option( + "--lock/--unlock", + "locked", + default=None, + help="Lock the pod against stop and reset.", +) +@json_option +def update(pod_id, name, unset_env, locked, as_json, **container): + """Change a pod's settings. + + --env and --unset-env edit the existing environment, --port replaces + the exposed ports, and volume flags restate the full mount (the + volume id cannot change; the path defaults to the current one). + Most changes apply on the pod's next start. + """ + requested = [name, locked, *unset_env, *container.values()] + if all(value in (None, ()) for value in requested): + raise click.UsageError("nothing to update. see rp pod update --help") + pod_id = _resolve_pod_id(pod_id) + + with api_errors(): + needs_current = ( + container["env"] + or unset_env + or any(container[key] for key in ("persistent_volume", "volume")) + ) + current = ( + run_rest_request("GET", f"/v2/pods/{pod_id}") if needs_current else None + ) + network_centers = set() + body = _container_body( + container, current, unset_env, network_centers=network_centers + ) + if network_centers: + pod_center = current.get("dataCenterId") + _datacenter_ids((), [pod_center] if pod_center else (), network_centers) + if name: + body["name"] = name + if locked is not None: + body["locked"] = locked + updated = run_rest_request("PATCH", f"/v2/pods/{pod_id}", json=body) + _say(f"updated pod {pod_id}", as_json) + _show(updated, as_json) + + +def _act( + pod_id: str | None, action: str, done: str, as_json: bool, wait: bool = False +): + pod_id = _resolve_pod_id(pod_id, action) + with api_errors(): + previous = ( + run_rest_request("GET", f"/v2/pods/{pod_id}") + if wait and action == "restart" + else None + ) + since = time.monotonic() + result = run_rest_request( + "POST", f"/v2/pods/{pod_id}/action", json={"action": action} + ) + _say(f"{done} pod {pod_id}", as_json) + if wait: + result = _wait_running(pod_id, since, previous) + if result is None: + raise QueryError(f"empty response for pod {pod_id}") + _show(result, as_json) + + +@pod.command() +@click.argument("pod_id", required=False, shell_complete=_complete_pods) +@click.option("--wait", is_flag=True, help="Wait until the pod is running.") +@json_option +def start(pod_id, wait, as_json): + """Start a stopped pod.""" + _act(pod_id, "start", "started", as_json, wait) + + +@pod.command() +@click.argument("pod_id", required=False, shell_complete=_complete_pods) +@json_option +def stop(pod_id, as_json): + """Stop a running pod, keeping its volume.""" + _act(pod_id, "stop", "stopped", as_json) + + +@pod.command() +@click.argument("pod_id", required=False, shell_complete=_complete_pods) +@click.option("--wait", is_flag=True, help="Wait until the pod is running.") +@json_option +def restart(pod_id, wait, as_json): + """Restart a running pod.""" + _act(pod_id, "restart", "restarted", as_json, wait) + + +@pod.command() +@click.argument("pod_id", required=False, shell_complete=_complete_pods) +@click.option("--yes", "-y", is_flag=True, help="Skip the confirmation prompt.") +def terminate(pod_id, yes): + """Terminate a pod permanently.""" + from runpod.cli import console as ui + + pod_id = _resolve_pod_id(pod_id, "terminate") + with api_errors(): + if not yes: + record = run_rest_request("GET", f"/v2/pods/{pod_id}") + confirm( + f"terminate pod {pod_id} ({record['name']})? " + "its disk and persistent volume are deleted", + yes, + ) + run_rest_request("DELETE", f"/v2/pods/{pod_id}") + ui.success(f"terminated pod {pod_id}") + + +pod.add_command(terminate, "delete") + + +@pod.command() +@click.argument("pod_id", required=False, shell_complete=_complete_pods) +@click.option("--follow", "-f", is_flag=True, help="Follow new log lines.") +@click.option("--tail", type=click.IntRange(0, 5000), default=100, show_default=True) +@click.option("--source", type=click.Choice(["container", "system"])) +@click.option("--since", help="Only logs after this timestamp.") +@json_option +def logs(pod_id, follow, tail, source, since, as_json): + """Read a pod's container or system logs.""" + from runpod.cli.logs import show_logs + + pod_id = _resolve_pod_id(pod_id) + show_logs( + pod_id, + follow=follow, + tail=tail, + source=source, + since=since, + as_json=as_json, + ) + + +@pod.command() +@click.argument("pod_id", required=False, shell_complete=_complete_pods) +def connect(pod_id): + """Open an interactive terminal on a pod over SSH. + + Needs an SSH key on your account (rp ssh add) and 22/tcp exposed. + """ + from runpod.cli.utils import ssh_cmd + + pod_id = _resolve_pod_id(pod_id) + click.echo(f"connecting to pod {pod_id}...") + try: + ssh = ssh_cmd.SSHConnection(pod_id) + except (ValueError, TimeoutError) as exc: + raise click.ClickException(str(exc)) from exc + ssh.launch_terminal() + + +pod.add_command(sync_pods, "sync") diff --git a/runpod/cli/template.py b/runpod/cli/template.py new file mode 100644 index 000000000..322956d53 --- /dev/null +++ b/runpod/cli/template.py @@ -0,0 +1,265 @@ +"""manage reusable pod and serverless container templates.""" + +import click +from rich.markup import escape + +from runpod.api.ctl_commands import _path_segment +from runpod.api.rest import run_rest_request +from runpod.cli import console as ui +from runpod.cli.api import api_errors, list_all +from runpod.cli.options import DEFAULT_MOUNT_PATH, container_fields +from runpod.cli.output import ( + completer, + confirm, + json_option, + pick, + print_fields, + print_json, + print_table, +) + + +def _validate_record(record, required_fields): + if not isinstance(record, dict) or not record: + raise click.ClickException("template information is unavailable") + if any(key not in record for key in required_fields): + raise click.ClickException("template response is missing required fields") + + +def _choices(): + rows = list_all("/v2/templates", "templates") + for row in rows: + _validate_record(row, ("id",)) + return [(row["id"], row.get("name") or row["id"]) for row in rows] + + +complete_template = completer(_choices) + + +def _show(record, as_json): + _validate_record(record, ("id", "name", "image", "disk")) + if as_json: + print_json(record) + return + print_fields( + record, + [ + ("id", lambda row: row["id"]), + ("name", lambda row: row["name"]), + ("image", lambda row: row["image"]), + ("serverless", lambda row: row.get("serverless")), + ("public", lambda row: row.get("public")), + ("disk", lambda row: f"{row['disk']} GB"), + ("ports", lambda row: row.get("ports")), + ("entrypoint", lambda row: row.get("entrypoint")), + ("cmd", lambda row: row.get("cmd")), + ("mounts", lambda row: row.get("mounts")), + ("env", lambda row: sorted(row.get("env") or {})), + ("registry", lambda row: row.get("registry")), + ], + ) + + +@click.group() +def template(): + """Manage pod and serverless templates.""" + + +@template.command(name="list") +@click.option( + "--type", + "source", + type=click.Choice(["user", "official", "verified", "community", "all"]), + default="user", + show_default=True, + help="List your templates or a public catalog.", +) +@click.option("--search", help="Match an id, name, or image (case-insensitive).") +@json_option +def template_list(source, search, as_json): + """List your templates, or browse public templates with --type.""" + with api_errors(): + rows = [] + sources = ( + ["user", "official", "verified", "community"] + if source == "all" + else [source] + ) + for selected in sources: + if selected == "user": + rows.extend(list_all("/v2/templates", "templates")) + else: + rows.extend( + list_all("/v2/catalog/templates", "templates", {"source": selected}) + ) + for row in rows: + _validate_record(row, ("id",)) + rows = list({row["id"]: row for row in rows}.values()) + if search: + term = search.casefold() + rows = [ + row + for row in rows + if any( + term in (row.get(key) or "").casefold() + for key in ("id", "name", "image") + ) + ] + if as_json: + print_json(rows) + return + print_table( + rows, + [ + ("ID", lambda row: row["id"]), + ("NAME", lambda row: row.get("name")), + ("IMAGE", lambda row: row.get("image")), + ("SERVERLESS", lambda row: row.get("serverless")), + ("PUBLIC", lambda row: row.get("public")), + ], + "no templates match", + ) + + +@template.command(name="get") +@click.argument("template_id", required=False, shell_complete=complete_template) +@json_option +def template_get(template_id, as_json): + """Show a template by id, or pick one of your templates.""" + with api_errors(): + if template_id is None: + template_id = pick("template", _choices(), "pass TEMPLATE_ID") + record = run_rest_request("GET", f"/v2/templates/{_path_segment(template_id)}") + _show(record, as_json) + + +def _options(function): + options = [ + click.option("--name", help="Template name."), + click.option("--image", help="Container image."), + click.option( + "--disk", type=click.IntRange(min=1), help="Container disk in GB." + ), + click.option( + "--serverless/--pod", default=None, help="Template workload type." + ), + click.option( + "--public/--private", default=None, help="Public catalog visibility." + ), + click.option( + "--port", + "ports", + multiple=True, + help="Exposed port, such as 8888/http. Repeatable.", + ), + click.option( + "--env", multiple=True, help="Environment variable KEY=VALUE. Repeatable." + ), + click.option("--cmd", help="Container command, parsed as shell words."), + click.option( + "--entrypoint", help="Container entrypoint, parsed as shell words." + ), + click.option( + "--registry", + help="Registry credential id or name. An empty value clears it.", + ), + click.option( + "--volume-size", + type=click.IntRange(min=10), + help="Persistent volume in GB (Pods only).", + ), + click.option( + "--volume-path", + help=f"Persistent volume mount path. Defaults to {DEFAULT_MOUNT_PATH} on create.", + ), + ] + for option in reversed(options): + function = option(function) + return function + + +def _body(options, current=None, unset_env=()): + body = container_fields(options, current, unset_env) + for key in ("name", "serverless", "public"): + if options[key] is not None: + body[key] = options[key] + for key in ("name", "image"): + if key in body and not body[key].strip(): + raise click.UsageError(f"--{key} cannot be empty") + size, path = options["volume_size"], options["volume_path"] + if size is not None or path is not None: + if body.get("serverless", (current or {}).get("serverless", False)): + raise click.UsageError("persistent volumes apply to pod templates only") + mount = ((current or {}).get("mounts") or {}).get("persistent") or {} + size = size if size is not None else mount.get("size") + if size is None: + raise click.UsageError("pass --volume-size when adding a persistent volume") + path = path if path is not None else mount.get("path", DEFAULT_MOUNT_PATH) + if not path.startswith("/"): + raise click.UsageError("--volume-path must be an absolute container path") + body["mounts"] = {"persistent": {"size": size, "path": path}} + return body + + +@template.command(name="create") +@_options +@json_option +def template_create(as_json, **options): + """Create a template with --name and --image. + + Environment values are stored in the template. Use platform secret + references for sensitive values. + """ + if not options["name"] or not options["image"]: + raise click.UsageError("pass --name and --image") + with api_errors(): + body = _body(options) + record = run_rest_request("POST", "/v2/templates", json=body) + _show(record, as_json) + + +@template.command(name="update") +@click.argument("template_id", shell_complete=complete_template) +@_options +@click.option( + "--unset-env", multiple=True, help="Remove an environment variable. Repeatable." +) +@click.option("--clear-ports", is_flag=True, help="Remove all exposed ports.") +@json_option +def template_update(template_id, unset_env, clear_ports, as_json, **options): + """Update a template. Unspecified settings are retained. + + --env edits individual keys. --port replaces the exposed ports. + """ + if clear_ports and options["ports"]: + raise click.UsageError("use either --port or --clear-ports") + with api_errors(): + current = None + path = f"/v2/templates/{_path_segment(template_id)}" + if ( + options["env"] + or unset_env + or options["volume_size"] is not None + or options["volume_path"] is not None + ): + current = run_rest_request("GET", path) + if not current: + raise click.ClickException("template information is unavailable") + body = _body(options, current, unset_env) + if clear_ports: + body["ports"] = [] + if not body: + raise click.UsageError("pass at least one setting to update") + record = run_rest_request("PATCH", path, json=body) + _show(record, as_json) + + +@template.command(name="delete") +@click.argument("template_id", shell_complete=complete_template) +@click.option("--yes", "-y", is_flag=True, help="Skip the confirmation prompt.") +def template_delete(template_id, yes): + """Delete a template.""" + confirm(f"delete template {template_id}?", yes) + with api_errors(): + run_rest_request("DELETE", f"/v2/templates/{_path_segment(template_id)}") + ui.success(f"deleted template [white]{escape(template_id)}[/white]") diff --git a/runpod/cli/update.py b/runpod/cli/update.py new file mode 100644 index 000000000..b7c369f66 --- /dev/null +++ b/runpod/cli/update.py @@ -0,0 +1,221 @@ +"""self-update for the rp cli and a passive new-version notice. + +`rp update` installs the latest (or a pinned) runpod release from pypi +using uv when available, pip otherwise. every other command starts a +daemon thread that checks pypi at most once per day (cached under +~/.runpod) and prints a one-line notice at exit when a newer version +exists. the check never blocks or crashes a command. +""" + +from __future__ import annotations + +import atexit +import json +import shutil +import subprocess +import sys +import threading +import urllib.error +import urllib.request +from datetime import UTC, datetime +from pathlib import Path + +PYPI_URL = "https://pypi.org/pypi/runpod/json" +INSTALL_TIMEOUT_SECONDS = 120 +CACHE_PATH = Path.home() / ".runpod" / "update_check.json" +CHECK_INTERVAL_HOURS = 24 + +_newer_version: str | None = None +_check_done = threading.Event() +_started = threading.Event() +_start_lock = threading.Lock() + + +def current_version() -> str: + try: + from runpod import __version__ + + return __version__ + except Exception: # noqa: BLE001 - version must never break the cli + return "unknown" + + +def parse_version(version: str) -> tuple[int, ...]: + """leading numeric release segments of a version string. + + dev/local suffixes (e.g. 1.8.0.dev3) are ignored so a dev build of + the next release does not count as older than the current one. + """ + parts = [] + for part in version.split("."): + if not part.isdigit(): + break + parts.append(int(part)) + return tuple(parts) + + +def compare_versions(a: tuple[int, ...], b: tuple[int, ...]) -> int: + """negative when a < b, zero when equal, positive when a > b.""" + width = max(len(a), len(b)) + a_padded = a + (0,) * (width - len(a)) + b_padded = b + (0,) * (width - len(b)) + return (a_padded > b_padded) - (a_padded < b_padded) + + +def fetch_pypi_metadata() -> tuple[str, set[str]]: + """(latest version, all release versions) from pypi.""" + try: + with urllib.request.urlopen(PYPI_URL, timeout=15) as resp: # noqa: S310 + data = json.loads(resp.read().decode()) + except urllib.error.URLError as exc: + if isinstance(exc, urllib.error.HTTPError): + raise RuntimeError( + f"pypi returned HTTP {exc.code}; try again later" + ) from exc + raise ConnectionError( + "could not reach pypi; check your network connection" + ) from exc + except (json.JSONDecodeError, UnicodeDecodeError) as exc: + raise RuntimeError("pypi returned an unexpected response") from exc + + try: + latest = data["info"]["version"] + except (KeyError, TypeError) as exc: + raise RuntimeError("pypi response missing version info") from exc + return latest, set(data.get("releases", {}).keys()) + + +def install_command(version: str) -> list: + """the installer invocation targeting the running interpreter. + + `uv pip install` is used only with an explicit --python pointing at + this interpreter: bare uv resolves against an activated venv, which + is not necessarily where this cli runs from. + """ + package_spec = f"runpod=={version}" + if shutil.which("uv"): + return [ + "uv", + "pip", + "install", + "--python", + sys.executable, + package_spec, + "--quiet", + ] + return [sys.executable, "-m", "pip", "install", package_spec, "--quiet"] + + +def run_install(version: str) -> None: + cmd = install_command(version) + result = subprocess.run( + cmd, + capture_output=True, + text=True, + timeout=INSTALL_TIMEOUT_SECONDS, + ) + if result.returncode != 0: + installer = "uv" if cmd[0] == "uv" else "pip" + raise RuntimeError( + f"{installer} install failed (exit {result.returncode}): " + f"{result.stderr.strip()}" + ) + + +# -- passive background check ------------------------------------------- + + +def _read_cache() -> dict | None: + try: + return json.loads(CACHE_PATH.read_text(encoding="utf-8")) + except (OSError, json.JSONDecodeError, ValueError): + return None + + +def _write_cache(latest_version: str) -> None: + try: + CACHE_PATH.parent.mkdir(parents=True, exist_ok=True) + CACHE_PATH.write_text( + json.dumps( + { + "last_checked_utc": datetime.now( + UTC + ).isoformat(), + "latest_version": latest_version, + } + ), + encoding="utf-8", + ) + except OSError: + # cache write is best-effort; the check reruns next invocation + pass + + +def _cache_fresh(cache: dict) -> bool: + try: + last_checked = datetime.fromisoformat(cache["last_checked_utc"]) + elapsed = ( + datetime.now(UTC) - last_checked + ).total_seconds() / 3600 + return elapsed < CHECK_INTERVAL_HOURS + except (KeyError, ValueError, TypeError): + return False + + +def _run_check() -> None: + global _newer_version # noqa: PLW0603 + try: + current = current_version() + if current == "unknown": + return + + cache = _read_cache() + latest = None + if cache and _cache_fresh(cache): + latest = cache.get("latest_version") or None + if not latest: + latest, _ = fetch_pypi_metadata() + _write_cache(latest) + if not latest: + return + + if compare_versions(parse_version(latest), parse_version(current)) > 0: + _newer_version = latest + except Exception: # noqa: BLE001 - the check must never crash the cli + pass + finally: + _check_done.set() + + +def _print_update_notice() -> None: + # plain text: atexit runs after rich teardown + if not _check_done.is_set(): + return + if _newer_version: + print( + f"\na new version of runpod is available: {_newer_version}\n" + " run 'rp update' to upgrade.", + file=sys.stderr, + ) + + +def _is_interactive() -> bool: + for stream in (sys.stderr, sys.stdout): + try: + if stream is not None and stream.isatty(): + return True + except Exception: # noqa: BLE001 + pass + return False + + +def start_background_check() -> None: + """spawn the daemon check thread once per process (ttys only).""" + with _start_lock: + if _started.is_set(): + return + _started.set() + if not _is_interactive(): + return + atexit.register(_print_update_notice) + threading.Thread(target=_run_check, daemon=True).start() diff --git a/runpod/cli/user.py b/runpod/cli/user.py new file mode 100644 index 000000000..130a5e7a4 --- /dev/null +++ b/runpod/cli/user.py @@ -0,0 +1,94 @@ +"""account details and balance for the authenticated user.""" + +import click + +from runpod.api.graphql import run_graphql_query +from runpod.cli.api import api_errors +from runpod.cli.output import json_option, print_fields, print_json + +_USER_QUERY = """ +query { + myself { + id + email + clientBalance + currentSpendPerHr + spendLimit + notifyPodsStale + notifyPodsGeneral + notifyLowBalance + } +} +""" +_BALANCE_KEYS = ("clientBalance", "currentSpendPerHr", "spendLimit") +_USER_KEYS = ( + "id", + "email", + *_BALANCE_KEYS, + "notifyPodsStale", + "notifyPodsGeneral", + "notifyLowBalance", +) + + +def _money(value): + if isinstance(value, bool) or ( + value is not None and not isinstance(value, (int, float)) + ): + raise click.ClickException( + "account balance response contains a non-numeric value" + ) + return f"${value:.2f}" if value is not None else None + + +_BALANCE_FIELDS = [ + ("balance", lambda row: _money(row.get("clientBalance"))), + ("spend per hour", lambda row: _money(row.get("currentSpendPerHr"))), + ("spend limit", lambda row: _money(row.get("spendLimit"))), +] +_USER_FIELDS = [ + ("id", lambda row: row.get("id")), + ("email", lambda row: row.get("email")), + *_BALANCE_FIELDS, + ("notify stale pods", lambda row: row.get("notifyPodsStale")), + ("notify general pod events", lambda row: row.get("notifyPodsGeneral")), + ("notify low balance", lambda row: row.get("notifyLowBalance")), +] + + +def _show_user(as_json, balance_only=False): + with api_errors(): + record = (run_graphql_query(_USER_QUERY).get("data") or {}).get("myself") + if not record: + raise click.ClickException("account information is unavailable") + keys = _BALANCE_KEYS if balance_only else _USER_KEYS + record = {key: record.get(key) for key in keys} + if as_json: + print_json(record) + return + print_fields(record, _BALANCE_FIELDS if balance_only else _USER_FIELDS) + + +@click.group(invoke_without_command=True) +@json_option +@click.pass_context +def user(ctx, as_json): + """Show account information and balance.""" + if ctx.invoked_subcommand is None: + _show_user(as_json) + + +@user.command() +@json_option +@click.pass_context +def info(ctx, as_json): + """Show account details, spending, and notification settings.""" + _show_user(as_json or ctx.parent.params.get("as_json", False)) + + +@user.command() +@json_option +@click.pass_context +def balance(ctx, as_json): + """Show the account balance, hourly spending, and spending limit.""" + _show_user(as_json or ctx.parent.params.get("as_json", False), balance_only=True) diff --git a/runpod/cli/volume.py b/runpod/cli/volume.py new file mode 100644 index 000000000..0ec576142 --- /dev/null +++ b/runpod/cli/volume.py @@ -0,0 +1,674 @@ +import os +import re +import sys +from pathlib import Path + +import click +from requests import RequestException + +from runpod.api.ctl_commands import _path_segment +from runpod.api.rest import run_rest_request +from runpod.cli import compute, console as ui +from runpod.cli.api import api_errors, list_all +from runpod.cli.output import ( + completer, + confirm, + json_option, + pick, + print_fields, + print_json, + print_table, +) +from runpod.error import QueryError + +NETWORK_FIELDS = [ + ("id", lambda row: row["id"]), + ("name", lambda row: row["name"]), + ("size", lambda row: f"{row['size']} GB"), + ("data center", lambda row: row["dataCenter"]), + ("type", lambda row: row["type"].lower()), +] +GLOBAL_FIELDS = [ + ("id", lambda row: row["id"]), + ("name", lambda row: row["name"]), + ("created", lambda row: row["createdAt"]), + ("created by", lambda row: row["createdByUserId"]), +] +global_option = click.option( + "--global", + "kind", + flag_value="global", + default=None, + help="Select global volumes only.", +) + + +def _label(record): + if "size" not in record: + return record["name"] + return ( + f"{record['name']} {record['size']} GB " + f"{record['dataCenter']} {record['type'].lower()}" + ) + + +def _list_volumes(kind=None, failures=None): + rows = [] + for volume_kind in ([kind] if kind else ["network", "global"]): + try: + records = list_all(f"/v2/{volume_kind}-volumes", f"{volume_kind}Volumes") + except (QueryError, RequestException) as exc: + if failures is None: + raise + failures.append(f"could not list {volume_kind} volumes: {exc}") + continue + rows.extend({**row, "kind": volume_kind} for row in records) + return rows + + +def _choices(kind=None): + failures = [] + rows = _list_volumes(kind, failures) + for failure in failures: + click.echo(f"Warning: {failure}", err=True) + return [(row["id"], f"{row['kind']} {_label(row)}") for row in rows] + + +def _complete_ids(ctx, param, incomplete): + kind = "network" if ctx.command.name == "expand" else ctx.params.get("kind") + return completer(lambda: _choices(kind))(ctx, param, incomplete) + + +def _get_volume(volume_id, kind=None): + path_id = _path_segment(volume_id) + if kind: + return kind, run_rest_request("GET", f"/v2/{kind}-volumes/{path_id}") + try: + return "network", run_rest_request("GET", f"/v2/network-volumes/{path_id}") + except QueryError as exc: + if exc.status_code != 404: + raise + return "global", run_rest_request("GET", f"/v2/global-volumes/{path_id}") + + +def _show(record, kind, as_json, action=None): + if as_json: + print_json(record) + return + if action: + ui.success(f"{action} {kind} volume [white]{record['id']}[/white]") + print_fields(record, GLOBAL_FIELDS if kind == "global" else NETWORK_FIELDS) + + +def _data_center(regions, volume_type): + datacenters = compute.list_datacenters() + if regions: + allowed = compute.resolve_regions(regions, datacenters) + datacenters = [dc for dc in datacenters if dc["id"] in allowed] + candidates = [ + dc + for dc in datacenters + if dc["networkVolumeTypes"] + and (not volume_type or volume_type in dc["networkVolumeTypes"]) + ] + scope = f"region {', '.join(regions)}" if regions else "the catalog" + offered = ( + f"{volume_type.lower()} network volumes" if volume_type else "network volumes" + ) + if not candidates: + raise compute.ResolutionError(f"no data center in {scope} offers {offered}") + if len(candidates) == 1: + return candidates[0]["id"] + return pick( + "data center", + [ + ( + dc["id"], + f"{dc['id']} {dc['region'].lower().replace('_', ' ')} " + + ", ".join(t.lower() for t in dc["networkVolumeTypes"]), + ) + for dc in candidates + ], + f"several data centers in {scope} offer {offered} " + f"({', '.join(dc['id'] for dc in candidates)}). pass one with --data-center", + ) + + +def _growth(volume_id, size, expand=False): + text = str(size).strip() + if not re.fullmatch(r"\+?\d+", text): + raise click.BadParameter( + f"'{size}' is not a size. use N for a total or +N to add N GB", + param_hint="--size", + ) + kind, record = _get_volume(volume_id) + if kind == "global": + raise click.UsageError("global volumes have no size to change") + current = record["size"] + target = current + int(text) if text.startswith("+") else int(text) + if target < current or (expand and target == current): + raise click.UsageError( + f"network volumes can only grow: {volume_id} is {current} GB, " + f"requested {target} GB" + ) + if target > 4096: + raise click.UsageError( + f"network volumes hold at most 4096 GB, requested {target} GB" + ) + return current, target + + +@click.group() +def volume(): + """Create, list, resize, and delete volumes, and transfer files to them. + + upload and download use the S3-compatible API, which needs S3 API keys + (separate from your API key): set RUNPOD_S3_ACCESS_KEY and + RUNPOD_S3_SECRET_KEY, pass the --s3-* flags, use saved config, or enter + them when asked. Re-run an interrupted transfer to resume it. + Parts of an upload that is + never re-run stay in the volume's hidden .s3compat_uploads folder and + count toward its size. + """ + + +@volume.command(name="list") +@global_option +@json_option +def volume_list(kind, as_json): + """List network and global volumes together with their type.""" + failures = [] + with api_errors(): + rows = _list_volumes(kind, None if as_json else failures) + if as_json: + print_json(rows) + return + fields = [ + ("id", lambda row: row["id"]), + ("name", lambda row: row["name"]), + ("type", lambda row: row["kind"]), + ("size", lambda row: f"{row['size']} GB" if "size" in row else None), + ("data center", lambda row: row.get("dataCenter")), + ("tier", lambda row: (row.get("type") or "").lower()), + ] + print_table( + rows, + [(label.upper(), value) for label, value in fields], + ( + "volume inventory unavailable" + if failures + else "no volumes. create one with rp volume create" + ), + ) + if failures: + raise click.ClickException( + "incomplete volume inventory. " + ". ".join(failures) + ) + + +@volume.command(name="get") +@click.argument("volume_id", required=False, shell_complete=_complete_ids) +@global_option +@json_option +def volume_get(volume_id, kind, as_json): + """Show one volume (pick one when VOLUME_ID is omitted).""" + with api_errors(): + if volume_id is None: + volume_id = pick("volume", _choices(kind), "pass VOLUME_ID") + kind, record = _get_volume(volume_id, kind) + _show(record, kind, as_json) + + +@volume.command(name="create") +@click.option("--name", required=True, help="Human-readable name.") +@click.option( + "--size", + type=click.IntRange(10, 4096), + help="Storage in GB (10-4096). Required for network volumes.", +) +@click.option( + "--region", + "regions", + multiple=True, + help="Region (eu, na), id prefix (us, eu-ro), or data center id. Repeatable.", +) +@click.option("--data-center", help="Exact data center id, like EU-RO-1.") +@click.option( + "--type", + "kind", + type=click.Choice(["network", "global"], case_sensitive=False), + default="network", + show_default=True, + help="Storage type. Global volumes mount in any data center.", +) +@click.option( + "--tier", + "volume_type", + type=click.Choice(["standard", "high_performance"], case_sensitive=False), + help="Storage tier, immutable after creation. Defaults to the data center's " + "primary tier.", +) +@json_option +def volume_create(name, size, regions, data_center, volume_type, kind, as_json): + """Create a network volume in one data center, or a global volume. + + A region matching several data centers narrows to those offering + the requested --tier, then prompts for one. + + \b + rp volume create --name models --size 100 --region eu + rp volume create --name scratch --size 50 --data-center EU-RO-1 + rp volume create --name shared --type global + """ + kind = kind.lower() + body = {"name": name} + with api_errors(): + if kind == "global": + given = [ + flag + for flag, value in ( + ("--size", size), + ("--region", regions), + ("--data-center", data_center), + ("--tier", volume_type), + ) + if value + ] + if given: + raise click.UsageError( + f"{', '.join(given)} do not apply to global volumes" + ) + else: + if size is None: + raise click.UsageError("pass --size in GB for a network volume") + if regions and data_center: + raise click.UsageError("use either --region or --data-center") + volume_type = volume_type.upper() if volume_type else None + body.update( + size=size, + dataCenter=data_center or _data_center(regions, volume_type), + ) + if volume_type: + body["type"] = volume_type + record = run_rest_request("POST", f"/v2/{kind}-volumes", json=body) + _show(record, kind, as_json, "created") + + +@volume.command(name="update") +@click.argument("volume_id", shell_complete=_complete_ids) +@click.option("--name", help="New name.") +@click.option( + "--size", + type=click.IntRange(10, 4096), + help="New size in GB; network volumes can only grow.", +) +@global_option +@json_option +def volume_update(volume_id, name, size, kind, as_json): + """Rename and/or resize a volume.""" + if kind == "global" and size is not None: + raise click.UsageError("global volumes have no size to change") + body = { + key: value + for key, value in (("name", name), ("size", size)) + if value is not None + } + if not body: + raise click.UsageError("pass --name and/or --size") + with api_errors(): + if size is not None: + _growth(volume_id, size) + kind = "network" + elif kind is None: + kind, _ = _get_volume(volume_id) + record = run_rest_request( + "PATCH", f"/v2/{kind}-volumes/{_path_segment(volume_id)}", json=body + ) + _show(record, kind, as_json, "updated") + + +@volume.command(name="expand") +@click.argument("volume_id", shell_complete=_complete_ids) +@click.option( + "--size", + required=True, + metavar="N|+N", + help="New total size in GB, or +N to add N GB.", +) +@json_option +def volume_expand(volume_id, size, as_json): + """Grow a network volume; storage can never shrink.""" + with api_errors(): + current, target = _growth(volume_id, size, expand=True) + record = run_rest_request( + "PATCH", + f"/v2/network-volumes/{_path_segment(volume_id)}", + json={"size": target}, + ) + if as_json: + print_json(record) + else: + ui.success( + f"expanded [white]{volume_id}[/white] from {current} GB to {record['size']} GB" + ) + + +@volume.command(name="delete") +@click.argument("volume_id", shell_complete=_complete_ids) +@click.option("--yes", "-y", is_flag=True, help="Skip the confirmation prompt.") +@global_option +def volume_delete(volume_id, yes, kind): + """Delete a volume and everything stored on it.""" + with api_errors(): + if kind is None or not yes: + kind, record = _get_volume(volume_id, kind) + if not yes: + confirm( + f"delete {kind} volume {volume_id} ({_label(record)}) and all its data?", + yes, + ) + path = f"/v2/{kind}-volumes/{_path_segment(volume_id)}" + run_rest_request("DELETE", path) + ui.success(f"deleted {kind} volume [white]{volume_id}[/white]") + + +def _transfer_options(func): + options = [ + click.option("--s3-access-key", default=None, help="S3 API access key."), + click.option("--s3-secret-key", default=None, help="S3 API secret key."), + click.option("--endpoint-url", default=None, hidden=True), + click.option( + "--concurrency", + default=4, + show_default=True, + type=click.IntRange(1, 64), + help="Parallel requests.", + ), + click.option( + "--force", + is_flag=True, + help="Transfer every file, even ones the size and time check calls unchanged.", + ), + ] + for option in reversed(options): + func = option(func) + return func + + +class _ProgressRenderer: + """draws one bar per file in flight and prints each finished file.""" + + def __init__(self, bar, action_label): + self._bar = bar + self._action_label = action_label + self._tasks = {} + + def __call__(self, event, path, nbytes): + if event == "start": + self._tasks[path] = self._bar.add_task(Path(path).name, total=nbytes) + return + task = self._tasks.get(path) + if task is None: + return + if event in ("advance", "reuse"): + self._bar.advance(task, nbytes) + elif event == "done": + self._bar.remove_task(self._tasks.pop(path)) + self._bar.console.print(f" {self._action_label} {path}") + + +def _progress_bar(): + from rich.console import Console + from rich.progress import ( + BarColumn, + DownloadColumn, + Progress, + TextColumn, + TransferSpeedColumn, + ) + + return Progress( + TextColumn("{task.description}"), + BarColumn(), + DownloadColumn(), + TransferSpeedColumn(), + console=Console(stderr=True), + transient=True, + ) + + +def _cli_error(exc: Exception) -> click.ClickException: + """a transfer failure as a cli error, with a resume hint when re-running + would resume.""" + from botocore.exceptions import EndpointConnectionError + + import runpod.network_volume_transfer as nvt + + hint = "\nre-run the same command to resume" if nvt.is_resumable(exc) else "" + if isinstance(exc, EndpointConnectionError): + hint = ( + "\nif the volume's datacenter does not support the s3 api yet, " + f"see {nvt.S3_DOCS_URL}; otherwise re-run the same command to resume" + ) + return click.ClickException(f"{exc}{hint}") + + +def _invoke_transfer(transfer_method, source, target, opts, progress, retry_keys): + """run the transfer, turning failures into cli errors. a rejection of + saved keys propagates when `retry_keys`, so the caller can prompt.""" + import runpod.network_volume_transfer as nvt + + try: + return transfer_method( + source, + target, + access_key=opts["s3_access_key"], + secret_key=opts["s3_secret_key"], + endpoint_url=opts["endpoint_url"], + concurrency=opts["concurrency"], + progress=progress, + force=opts["force"], + ) + except KeyboardInterrupt: + click.echo("interrupted; re-run the same command to resume", err=True) + raise SystemExit(130) from None + except Exception as exc: # noqa: BLE001 - surface transfer errors cleanly + if retry_keys and isinstance(exc, nvt.RejectedS3Keys): + raise + raise _cli_error(exc) from exc + + +def _run_transfer(action_label, transfer_method, source, target, opts) -> None: + import runpod.network_volume_transfer as nvt + + retry_keys = bool(opts.get("_saved_keys")) and _interactive() + while True: + try: + with _progress_bar() as bar: + summary = _invoke_transfer( + transfer_method, + source, + target, + opts, + _ProgressRenderer(bar, action_label), + retry_keys, + ) + break + except nvt.RejectedS3Keys as exc: + # the bar is closed here, so the prompts draw cleanly + retry_keys = False + if not click.confirm( + "saved s3 keys were rejected. enter a new pair?", default=True + ): + raise _cli_error(exc) from exc + try: + opts["s3_access_key"], opts["s3_secret_key"] = _prompt_s3_keys() + except (click.ClickException, click.Abort): + raise + except Exception as save_exc: # noqa: BLE001 - saving can fail + raise _cli_error(save_exc) from save_exc + click.echo( + f"{action_label} {summary['files_transferred']} file(s), " + f"{summary['bytes_transferred']} bytes; " + f"skipped {summary['files_skipped']} unchanged" + ) + + +def _interactive() -> bool: + return sys.stdin.isatty() and sys.stdout.isatty() + + +def _ensure_logged_in(ctx) -> None: + """offer the browser login when no api key is set; the volume lookup + needs one.""" + import runpod + import runpod.network_volume_transfer as nvt + from runpod.auth.credentials import get_credentials + from runpod.cli.main import login + + if runpod.api_key: + return + if not _interactive() or not click.confirm( + "you are not logged in to runpod. log in now?", default=True + ): + raise click.ClickException(nvt.NOT_LOGGED_IN) + ctx.invoke(login, no_open=False, api_key_opt=None, profile=runpod.profile) + runpod.api_key = (get_credentials(runpod.profile) or {}).get("api_key") + if not runpod.api_key: + raise click.ClickException(nvt.NOT_LOGGED_IN) + + +def _pick_volume() -> str: + """let the user choose one of their network volumes by number.""" + import runpod.network_volume_transfer as nvt + + if not _interactive(): + raise click.UsageError("pass VOLUME first (a network volume id or name)") + try: + volumes = nvt._list_volumes() + except nvt.NetworkVolumeTransferError as exc: + raise click.ClickException(str(exc)) from exc + if not volumes: + raise click.ClickException( + "no network volumes yet: create one at https://console.runpod.io/user/storage" + ) + for number, vol in enumerate(volumes, 1): + datacenter = vol.get("dataCenterId") or vol.get("dataCenter") + click.echo( + f" {number}. {vol['name']} {vol['id']} {vol.get('size')} GB {datacenter}" + ) + choice = click.prompt("volume", type=click.IntRange(1, len(volumes))) + return volumes[choice - 1]["id"] + + +def _missing_keys_message() -> str: + import runpod.network_volume_transfer as nvt + + return ( + "s3 api keys required (separate from your api key): set " + f"{nvt.ACCESS_KEY_ENV} and {nvt.SECRET_KEY_ENV} or pass --s3-access-key " + f"and --s3-secret-key (create keys at {nvt.S3_KEYS_URL})" + ) + + +def _prompt_s3_keys(): + """ask for the s3 keys, offering to save them for next time.""" + import runpod + import runpod.network_volume_transfer as nvt + from runpod.auth.credentials import set_s3_keys + + if not _interactive(): + raise click.ClickException(_missing_keys_message()) + click.echo( + "network volume transfers use s3 api keys, separate from your api key.\n" + f"create a pair at {nvt.S3_KEYS_URL} (s3 api keys)." + ) + access = click.prompt("s3 access key") + secret = click.prompt("s3 secret key", hide_input=True) + if click.confirm("save them to ~/.runpod/config.toml?", default=True): + set_s3_keys(access, secret, profile=runpod.profile) + return access, secret + + +def _ensure_s3_keys(opts) -> None: + """fill in the s3 keys from the flags, the environment, or the saved + config, prompting for them when none are set.""" + import runpod.network_volume_transfer as nvt + + explicit = bool(opts["s3_access_key"] and opts["s3_secret_key"]) + env = bool( + os.environ.get(nvt.ACCESS_KEY_ENV) and os.environ.get(nvt.SECRET_KEY_ENV) + ) + keys = nvt.find_s3_keys(opts["s3_access_key"], opts["s3_secret_key"]) + opts["_saved_keys"] = bool(keys and not explicit and not env) + opts["s3_access_key"], opts["s3_secret_key"] = keys or _prompt_s3_keys() + + +def _split_args(args, second: str, third: str): + """[VOLUME] SECOND [THIRD]: a lone argument is SECOND, and the volume is + picked interactively.""" + if not 1 <= len(args) <= 3: + raise click.UsageError(f"expected [VOLUME] {second} [{third}]") + if len(args) == 1: + return None, args[0], None + return args[0], args[1], args[2] if len(args) == 3 else None + + +def _transfer(ctx, action_label, method_name, reference, source, target, opts) -> None: + """the checks every transfer needs, in order: login, volume, s3 keys.""" + import runpod.network_volume_transfer as nvt + from runpod.apps import NetworkVolume + from runpod.apps.volume import VolumeError + from runpod.user_agent import USER_AGENT + + _ensure_logged_in(ctx) + reference = reference or _pick_volume() + try: + target_volume = NetworkVolume(reference, create=False) + target_volume._user_agent = USER_AGENT + # the volume caches this lookup, so the transfer does not repeat it + target_volume._s3_location(opts["endpoint_url"]) + except (nvt.NetworkVolumeTransferError, VolumeError) as exc: + raise click.ClickException(str(exc)) from exc + _ensure_s3_keys(opts) + method = getattr(target_volume, method_name) + _run_transfer(action_label, method, source, target, opts) + + +@volume.command(name="upload") +@click.argument( + "args", nargs=-1, required=True, metavar="[VOLUME] LOCAL_PATH [REMOTE_PATH]" +) +@_transfer_options +@click.pass_context +def volume_upload(ctx, args, **opts): + """Upload a file or folder to a network volume. + + VOLUME is the volume's id or name. Give only LOCAL_PATH to pick the + volume from a list. REMOTE_PATH defaults to the local name. A folder's + contents go under REMOTE_PATH/. + Files whose remote copy has the same size and is not older are skipped; + --force sends them anyway. + """ + reference, local_path, remote_path = _split_args(args, "LOCAL_PATH", "REMOTE_PATH") + if not Path(local_path).exists(): + raise click.UsageError(f"local path {local_path} does not exist") + _transfer(ctx, "uploaded", "upload", reference, local_path, remote_path, opts) + + +@volume.command(name="download") +@click.argument( + "args", nargs=-1, required=True, metavar="[VOLUME] REMOTE_PATH [LOCAL_PATH]" +) +@_transfer_options +@click.pass_context +def volume_download(ctx, args, **opts): + """Download a file or folder from a network volume. + + VOLUME is the volume's id or name. Give only REMOTE_PATH to pick the + volume from a list. A REMOTE_PATH ending in / is a folder. LOCAL_PATH defaults to the remote + name. Local files of the same size and not older than the remote copy + are skipped; --force fetches them anyway. + """ + reference, remote_path, local_path = _split_args(args, "REMOTE_PATH", "LOCAL_PATH") + _transfer(ctx, "downloaded", "download", reference, remote_path, local_path, opts) diff --git a/runpod/endpoint/__init__.py b/runpod/endpoint/__init__.py index 0b2df68cf..a4a08063b 100644 --- a/runpod/endpoint/__init__.py +++ b/runpod/endpoint/__init__.py @@ -1,7 +1,6 @@ """ Allows endpoints to be imported as a module. """ -from .asyncio.asyncio_runner import Endpoint as AsyncioEndpoint -from .asyncio.asyncio_runner import Job as AsyncioJob +from .asyncio.asyncio_runner import Endpoint as AsyncioEndpoint, Job as AsyncioJob from .runner import Endpoint, Job __all__ = [ diff --git a/runpod/endpoint/asyncio/asyncio_runner.py b/runpod/endpoint/asyncio/asyncio_runner.py index ad8896008..34c85578f 100644 --- a/runpod/endpoint/asyncio/asyncio_runner.py +++ b/runpod/endpoint/asyncio/asyncio_runner.py @@ -5,7 +5,14 @@ import asyncio from typing import Any -from runpod.endpoint.helpers import FINAL_STATES, is_completed, raise_for_job_state +from runpod.api.http import HTTPClient +from runpod.api.routes import Route, endpoint_base_url +from runpod.endpoint.helpers import ( + FINAL_STATES, + is_completed, + raise_for_job_state, + raise_for_redirect, +) from runpod.http_client import ClientSession @@ -22,14 +29,10 @@ def __init__(self, endpoint_id: str, job_id: str, session: ClientSession, header session: The aiohttp ClientSession. headers: Headers to use for requests. """ - from runpod import ( # pylint: disable=import-outside-toplevel,cyclic-import - endpoint_url_base, - ) - self.endpoint_id = endpoint_id self.job_id = job_id self.session = session - self.endpoint_url_base = endpoint_url_base + self.endpoint_url_base = endpoint_base_url() self.headers = headers self.job_status = None @@ -42,11 +45,19 @@ async def _fetch_job(self, source: str = "status") -> dict[str, Any]: Args: source: The URL source path of the job status. """ - status_url = ( - f"{self.endpoint_url_base}/{self.endpoint_id}/{source}/{self.job_id}" + route = Route( + "GET", + "{endpoint_id}/{source}/{job_id}", + endpoint_id=self.endpoint_id, + source=source, + job_id=self.job_id, ) - job_state = await self.session.get(status_url, headers=self.headers) - job_state = await job_state.json() + client = HTTPClient(self.endpoint_url_base, session=self.session) + async with client.stream( + route, headers=self.headers, timeout=self.session.timeout + ) as response: + raise_for_redirect(response.status) + job_state = await response.json() if is_completed(job_state["status"]): self.job_status = job_state["status"] @@ -123,8 +134,17 @@ async def cancel(self) -> dict: Returns: Output of cancel operation """ - cancel_url = f"{self.endpoint_url_base}/{self.endpoint_id}/cancel/{self.job_id}" - async with self.session.post(cancel_url, headers=self.headers) as resp: + route = Route( + "POST", + "{endpoint_id}/cancel/{job_id}", + endpoint_id=self.endpoint_id, + job_id=self.job_id, + ) + client = HTTPClient(self.endpoint_url_base, session=self.session) + async with client.stream( + route, headers=self.headers, timeout=self.session.timeout + ) as resp: + raise_for_redirect(resp.status) return await resp.json() @@ -144,14 +164,13 @@ def __init__(self, endpoint_id: str, session: ClientSession, from runpod import ( # pylint: disable=import-outside-toplevel api_key as global_api_key, ) - from runpod import ( - endpoint_url_base, - ) self.endpoint_id = endpoint_id self.session = session - self.endpoint_url_base = endpoint_url_base - self.endpoint_url = f"{endpoint_url_base}/{self.endpoint_id}/run" + self.endpoint_url_base = endpoint_base_url() + self.endpoint_url = Route( + "POST", "{endpoint_id}/run", endpoint_id=self.endpoint_id + ).url(self.endpoint_url_base) # Store instance API key for future requests self.api_key = api_key or global_api_key @@ -174,13 +193,17 @@ async def run(self, endpoint_input: dict) -> Job: Returns: Newly created job """ - # Same rule as the sync client: only wrap input not already wrapped. if "input" not in endpoint_input: endpoint_input = {"input": endpoint_input} - async with self.session.post( - self.endpoint_url, headers=self.headers, json=endpoint_input + client = HTTPClient(self.endpoint_url_base, session=self.session) + async with client.stream( + Route("POST", "{endpoint_id}/run", endpoint_id=self.endpoint_id), + headers=self.headers, + json=endpoint_input, + timeout=self.session.timeout, ) as resp: + raise_for_redirect(resp.status) json_resp = await resp.json() # Create job with endpoint's headers @@ -195,9 +218,13 @@ async def health(self) -> dict: Returns: Health of endpoint """ - health_url = f"{self.endpoint_url_base}/{self.endpoint_id}/health" - - async with self.session.get(health_url, headers=self.headers) as resp: + client = HTTPClient(self.endpoint_url_base, session=self.session) + async with client.stream( + Route("GET", "{endpoint_id}/health", endpoint_id=self.endpoint_id), + headers=self.headers, + timeout=self.session.timeout, + ) as resp: + raise_for_redirect(resp.status) return await resp.json() async def purge_queue(self) -> dict: @@ -207,7 +234,11 @@ async def purge_queue(self) -> dict: Returns: Purge status """ - purge_url = f"{self.endpoint_url_base}/{self.endpoint_id}/purge-queue" - - async with self.session.post(purge_url, headers=self.headers) as resp: + client = HTTPClient(self.endpoint_url_base, session=self.session) + async with client.stream( + Route("POST", "{endpoint_id}/purge-queue", endpoint_id=self.endpoint_id), + headers=self.headers, + timeout=self.session.timeout, + ) as resp: + raise_for_redirect(resp.status) return await resp.json() diff --git a/runpod/endpoint/helpers.py b/runpod/endpoint/helpers.py index de41430fb..d0a6dc118 100644 --- a/runpod/endpoint/helpers.py +++ b/runpod/endpoint/helpers.py @@ -1,7 +1,7 @@ -""" Helper functions for the Runpod Endpoint API. """ +"""Helper functions for the Runpod Endpoint API.""" -from runpod.error import JobError +from runpod.error import JobError, QueryError # Terminal job statuses; a job in any of these never changes again. FINAL_STATES = ["COMPLETED", "FAILED", "TIMED_OUT", "CANCELLED"] @@ -16,6 +16,11 @@ ) +def raise_for_redirect(status: int) -> None: + if status in range(300, 400): + raise QueryError("unexpected redirect", status_code=status) + + def is_completed(status: str) -> bool: """Returns true if status is one of the possible final states for a serverless request.""" return status in FINAL_STATES diff --git a/runpod/endpoint/runner.py b/runpod/endpoint/runner.py index 5d40b19ff..6192bc26b 100644 --- a/runpod/endpoint/runner.py +++ b/runpod/endpoint/runner.py @@ -8,12 +8,15 @@ import requests from requests.adapters import HTTPAdapter, Retry +from runpod.api.http import SyncHTTPClient +from runpod.api.routes import Route, endpoint_base_url from runpod.endpoint.helpers import ( API_KEY_NOT_SET_MSG, FINAL_STATES, UNAUTHORIZED_MSG, is_completed, raise_for_job_state, + raise_for_redirect, ) POLL_INTERVAL_SECONDS = 1 @@ -40,13 +43,10 @@ def __init__(self, api_key: str | None = None): from runpod import ( # pylint: disable=import-outside-toplevel, cyclic-import api_key as global_api_key, ) - from runpod import ( - endpoint_url_base, - ) - + # Use provided api_key or fall back to global self.api_key = api_key or global_api_key - + if self.api_key is None: raise RuntimeError(API_KEY_NOT_SET_MSG) @@ -62,11 +62,24 @@ def __init__(self, api_key: str | None = None): "Authorization": f"Bearer {self.api_key}", } - self.endpoint_url_base = endpoint_url_base + self.endpoint_url_base = endpoint_base_url() + + def __enter__(self): + return self + + def __exit__(self, *args): + self.close() + + def close(self): + """Close the client's connection pool.""" + self.rp_session.close() def _request( - self, method: str, endpoint: str, data: dict | None = None, - timeout: int = 10 + self, + method: str, + endpoint: str, + data: dict | None = None, + timeout: float = 10, ): """ Make a request to the specified endpoint using the given HTTP method. @@ -84,22 +97,22 @@ def _request( RuntimeError: If the response returns a 401 Unauthorized status. requests.HTTPError: If the response contains an unsuccessful status code. """ - url = f"{self.endpoint_url_base}/{endpoint}" - response = self.rp_session.request( - method, url, headers=self.headers, json=data, timeout=timeout - ) - - if response.status_code == 401: - raise RuntimeError(UNAUTHORIZED_MSG) - - response.raise_for_status() - return response.json() - - def post(self, endpoint: str, data: dict, timeout: int = 10): + client = SyncHTTPClient(self.endpoint_url_base, session=self.rp_session) + with client.stream( + Route(method, endpoint), headers=self.headers, json=data, timeout=timeout + ) as response: + raise_for_redirect(response.status_code) + if response.status_code == 401: + raise RuntimeError(UNAUTHORIZED_MSG) + + response.raise_for_status() + return response.json() + + def post(self, endpoint: str, data: dict | None, timeout: float = 10): """Post to the endpoint.""" return self._request("POST", endpoint, data, timeout) - def get(self, endpoint: str, timeout: int = 10): + def get(self, endpoint: str, timeout: float = 10): """Get from the endpoint.""" return self._request("GET", endpoint, timeout=timeout) @@ -123,15 +136,21 @@ def __init__(self, endpoint_id: str, job_id: str, client: RunPodClient): self.job_id = job_id self.rp_client = client - self.job_status = None - self.job_output = None - self.job_error = None + self.job_status: str | None = None + self.job_output: object = None + self.job_error: str | None = None def _fetch_job( self, source: str = "status", timeout: float = STATUS_REQUEST_TIMEOUT_SECONDS ) -> dict[str, Any]: """Returns the raw json of the status, raises an exception if invalid""" - status_url = f"{self.endpoint_id}/{source}/{self.job_id}" + status_url = Route( + "GET", + "{endpoint_id}/{source}/{job_id}", + endpoint_id=self.endpoint_id, + source=source, + job_id=self.job_id, + ).resolved_path job_state = self.rp_client.get(endpoint=status_url, timeout=timeout) if is_completed(job_state["status"]): @@ -148,7 +167,7 @@ def status(self): return self._fetch_job()["status"] - def output(self, timeout: int = 0) -> Any: + def output(self, timeout: float = 0) -> Any: """ Returns the output of the job request. @@ -183,6 +202,7 @@ def output(self, timeout: int = 0) -> Any: # output; fetch it from /status before returning the result self._fetch_job() + assert self.job_status is not None raise_for_job_state(self.job_id, self.job_status, self.job_error) return self.job_output @@ -220,7 +240,12 @@ def cancel(self, timeout: int = 3) -> Any: timeout: The number of seconds to wait for the server to respond before giving up. """ return self.rp_client.post( - f"{self.endpoint_id}/cancel/{self.job_id}", + Route( + "POST", + "{endpoint_id}/cancel/{job_id}", + endpoint_id=self.endpoint_id, + job_id=self.job_id, + ).resolved_path, data=None, timeout=timeout ) @@ -249,6 +274,16 @@ def __init__(self, endpoint_id: str, api_key: str | None = None): self.endpoint_id = endpoint_id self.rp_client = RunPodClient(api_key=api_key) + def __enter__(self): + return self + + def __exit__(self, *args): + self.close() + + def close(self): + """Close the endpoint's connection pool after its jobs finish.""" + self.rp_client.close() + def run(self, request_input: dict[str, Any]) -> Job: """ Run the endpoint with the given input. @@ -263,7 +298,7 @@ def run(self, request_input: dict[str, Any]) -> Job: request_input = {"input": request_input} job_request = self.rp_client.post( - f"{self.endpoint_id}/run", + Route("POST", "{endpoint_id}/run", endpoint_id=self.endpoint_id).resolved_path, request_input ) return Job(self.endpoint_id, job_request["id"], self.rp_client) @@ -288,7 +323,9 @@ def run_sync( request_input = {"input": request_input} job_request = self.rp_client.post( - f"{self.endpoint_id}/runsync", + Route( + "POST", "{endpoint_id}/runsync", endpoint_id=self.endpoint_id + ).resolved_path, request_input, timeout=timeout ) @@ -317,7 +354,7 @@ def health(self, timeout: int = 3) -> dict[str, Any]: timeout: The number of seconds to wait for the server to respond before giving up. """ return self.rp_client.get( - f"{self.endpoint_id}/health", + Route("GET", "{endpoint_id}/health", endpoint_id=self.endpoint_id).resolved_path, timeout=timeout ) @@ -329,7 +366,9 @@ def purge_queue(self, timeout: int = 3) -> dict[str, Any]: timeout: The number of seconds to wait for the server to respond before giving up. """ return self.rp_client.post( - f"{self.endpoint_id}/purge-queue", + Route( + "POST", "{endpoint_id}/purge-queue", endpoint_id=self.endpoint_id + ).resolved_path, data=None, timeout=timeout ) diff --git a/runpod/error.py b/runpod/error.py index 6ff80f4b0..3b1ad3156 100644 --- a/runpod/error.py +++ b/runpod/error.py @@ -19,6 +19,10 @@ def auth_hint() -> str: return API_KEY_REJECTED if api_key else NOT_LOGGED_IN +class AppError(Exception): + """base error for the apps sdk.""" + + class RunPodError(Exception): """ Base class for all runpod errors diff --git a/runpod/http_client.py b/runpod/http_client.py index d3d4160b7..56a376f74 100644 --- a/runpod/http_client.py +++ b/runpod/http_client.py @@ -7,7 +7,7 @@ import requests from aiohttp import ClientResponseError, ClientSession, ClientTimeout, TCPConnector -from .cli.groups.config.functions import get_credentials +from .auth.credentials import get_credentials from .user_agent import USER_AGENT diff --git a/runpod/network_volume_transfer.py b/runpod/network_volume_transfer.py index 8043b2549..79acf8431 100644 --- a/runpod/network_volume_transfer.py +++ b/runpod/network_volume_transfer.py @@ -25,9 +25,10 @@ import os import threading import time -from collections.abc import Callable +from collections.abc import Callable, Iterable from concurrent.futures import ThreadPoolExecutor, as_completed from contextlib import closing +from functools import partial from pathlib import Path, PurePosixPath from typing import Any, TypeVar @@ -146,8 +147,6 @@ def is_resumable(exc: BaseException) -> bool: same way on every run.""" from botocore.exceptions import ( # pylint: disable=import-outside-toplevel ConnectionError as BotoConnectionError, - ) - from botocore.exceptions import ( HTTPClientError, IncompleteReadError, ResponseStreamingError, @@ -266,7 +265,7 @@ def _stop_before_send(self, event_name: str = "", **_kwargs: Any) -> None: if self._stop.is_set() and not event_name.endswith(_CLEANUP_OPERATIONS): raise NetworkVolumeTransferError("interrupted", resumable=True) - def _run(self, tasks: list[Callable[[], Any]]) -> list[Any]: + def _run(self, tasks: Iterable[Callable[[], T]]) -> list[T]: """run tasks in parallel; the first failure cancels the ones not started.""" pool = ThreadPoolExecutor(max_workers=self.concurrency) try: @@ -289,7 +288,7 @@ def _emit(self, event: str, path: str, nbytes: int = 0) -> None: if self._progress is not None: self._progress(event, path, nbytes) - def _run_files(self, jobs: list[tuple[Any, Callable[[], Any]]]) -> None: + def _run_files(self, jobs: Iterable[tuple[Any, Callable[[], Any]]]) -> None: """run every file; failures are reported together, resumable only when every one of them is.""" failures: list[tuple[str, bool]] = [] @@ -304,7 +303,7 @@ def guarded(label: Any, task: Callable[[], Any]) -> None: with self._lock: failures.append((f"{label}: {exc}", is_resumable(exc))) - self._run([lambda lbl=label, t=task: guarded(lbl, t) for label, task in jobs]) + self._run([partial(guarded, label, task) for label, task in jobs]) if failures: raise NetworkVolumeTransferError( f"{len(failures)} file(s) failed:\n " @@ -404,7 +403,7 @@ def _upload_folder(self, local: Path, remote_path: str | None) -> None: ): self._emit("skip", str(path), path.stat().st_size) else: - jobs.append((path, lambda p=path, k=key: self.upload_file(p, k))) + jobs.append((path, partial(self.upload_file, path, key))) self._run_files(jobs) def _upload_one(self, local: Path, remote_path: str | None) -> None: @@ -528,17 +527,11 @@ def _download_folder(self, prefix: str, remote_path: str, local_path: Any) -> No ) jobs = [(_safe_target(root, obj["Key"][len(listed) :]), obj) for obj in objects] _check_local_names([dest for dest, _ in jobs], root) - self._run_files( - [ - ( - dest, - lambda d=dest, o=obj: _Download( - self, o["Key"], o["Size"], o, d - ).run(), - ) - for dest, obj in jobs - ] - ) + + def download(dest: Path, obj: dict[str, Any]) -> None: + _Download(self, obj["Key"], obj["Size"], obj, dest).run() + + self._run_files([(dest, partial(download, dest, obj)) for dest, obj in jobs]) class _Upload: @@ -567,7 +560,7 @@ def run(self) -> None: if reused: self.t._emit("reuse", str(self.local), reused) todo = [n for n in range(1, self.count + 1) if n not in self.parts] - self.parts.update(self.t._run([lambda n=n: self._send(n) for n in todo])) + self.parts.update(self.t._run([partial(self._send, n) for n in todo])) # the parts were read over the whole upload; if the file moved under # them, they may mix two versions of it if not _same_version(self.stat, self.local.stat()): @@ -735,11 +728,7 @@ def run(self) -> None: if reused: self.t._emit("reuse", label, reused) self.t._run( - [ - lambda i=i: self._fetch(i) - for i in range(self.count) - if i not in self.done - ] + [partial(self._fetch, i) for i in range(self.count) if i not in self.done] ) if self.partial.stat().st_size != self.size: raise NetworkVolumeTransferError( @@ -889,7 +878,7 @@ def _resolve_volume(reference: str, *, user_agent: str = USER_AGENT) -> tuple[st def saved_s3_keys() -> tuple[str | None, str | None]: """the s3 keys saved in ~/.runpod/config.toml for the current profile.""" from runpod import profile # pylint: disable=import-outside-toplevel - from runpod.cli.groups.config.functions import ( # pylint: disable=import-outside-toplevel + from runpod.auth.credentials import ( # pylint: disable=import-outside-toplevel get_credentials, ) @@ -905,11 +894,15 @@ def find_s3_keys( mixes sources.""" if access_key and secret_key: return access_key, secret_key - from_env = (os.environ.get(ACCESS_KEY_ENV), os.environ.get(SECRET_KEY_ENV)) - if all(from_env): - return from_env - saved = saved_s3_keys() - return saved if all(saved) else None + env_access, env_secret = os.environ.get(ACCESS_KEY_ENV), os.environ.get( + SECRET_KEY_ENV + ) + if env_access and env_secret: + return env_access, env_secret + saved_access, saved_secret = saved_s3_keys() + if saved_access and saved_secret: + return saved_access, saved_secret + return None def _s3_keys(access_key: str | None, secret_key: str | None) -> tuple[str, str]: diff --git a/runpod/rp_cli/__init__.py b/runpod/rp_cli/__init__.py index de9fc580d..ce5a4f9b8 100644 --- a/runpod/rp_cli/__init__.py +++ b/runpod/rp_cli/__init__.py @@ -1 +1 @@ -"""the `rp` command line interface.""" +"""command-line entry points and helpers.""" diff --git a/runpod/rp_cli/api.py b/runpod/rp_cli/api.py index de558287a..5a900a8ba 100644 --- a/runpod/rp_cli/api.py +++ b/runpod/rp_cli/api.py @@ -1,22 +1,7 @@ -"""pagination and error reporting for rest-backed cli commands.""" +"""shared command-line helpers.""" -from contextlib import contextmanager +import sys -import click -from requests import RequestException +from runpod.cli import api -from runpod import error -from runpod.api.rest import run_rest_paginated_request -from runpod.rp_cli.compute import ResolutionError - - -def list_all(path: str, collection: str, params: dict | None = None) -> list[dict]: - return run_rest_paginated_request(path, collection, params=params) - - -@contextmanager -def api_errors(): - try: - yield - except (error.RunPodError, ResolutionError, RequestException) as exc: - raise click.ClickException(str(exc)) from exc +sys.modules[__name__] = api diff --git a/runpod/rp_cli/catalog.py b/runpod/rp_cli/catalog.py index 3af6403a6..877fa12d5 100644 --- a/runpod/rp_cli/catalog.py +++ b/runpod/rp_cli/catalog.py @@ -1,307 +1,7 @@ -"""`rp catalog`: gpu and cpu pricing and stock search.""" +"""shared command-line helpers.""" +import sys -import click -from click.core import ParameterSource +from runpod.cli import catalog -from runpod.rp_cli import compute -from runpod.rp_cli.api import api_errors -from runpod.rp_cli.output import json_option, print_json, print_table - - -def _money(value: float | None, format_spec: str = ".2f") -> str: - return f"${value:{format_spec}}" if value else "-" - - -def _stock(entries: list[dict]) -> str: - ranked = sorted( - entries, key=lambda dc: -compute.availability_rank(dc["availability"]) - ) - return ", ".join(f"{dc['id']} {dc['availability'].lower()}" for dc in ranked) - - -def _filter_stock(records: list[dict], regions: tuple[str, ...], available: bool): - allowed = ( - set(compute.resolve_regions(regions, compute.list_datacenters())) - if regions - else None - ) - for record in records: - row = dict(record) - if allowed is not None: - row["dataCenters"] = [ - dc for dc in record.get("dataCenters", []) if dc["id"] in allowed - ] - row["availability"] = compute.best_availability( - dc["availability"] for dc in row["dataCenters"] - ) - if not available or compute.availability_rank(row.get("availability")) > 0: - yield row - - -def _unit_price(gpu: dict, product: str, cloud: str | None) -> float | None: - price = gpu["price"] - if product == "SERVERLESS": - return price.get("serverless") or None - if cloud: - return price.get(cloud) or None - offered = [ - value for value in (price.get("secure"), price.get("community")) if value - ] - return min(offered, default=None) - - -def _gpu_rows( - query, product, count, regions, cloud, cuda, min_vram, max_price, available -) -> list[dict]: - min_cuda, exact_cuda = compute.parse_cuda(cuda) - gpus = compute.list_gpus( - product=product, - count=count, - cloud=cloud.upper() if cloud else None, - cuda_versions=exact_cuda, - min_cuda_version=min_cuda, - ) - if query: - gpus = compute.resolve_gpus(query, gpus) - if product == "SERVERLESS": - gpus = [gpu for gpu in gpus if gpu.get("pool")] - rows = [] - for row in _filter_stock(gpus, regions, available): - unit = _unit_price(row, product, cloud) - if min_vram and row["memory"] < min_vram: - continue - if max_price is not None and (unit is None or unit > max_price): - continue - row["count"] = count - row["totalPrice"] = { - tier: round(value * count, 4) if value else None - for tier, value in row["price"].items() - } - rows.append(row) - rows.sort( - key=lambda row: ( - -compute.availability_rank(row.get("availability")), - _unit_price(row, product, cloud) or float("inf"), - row["name"], - ) - ) - return rows - - -def _gpu_columns(product: str, count: int, cloud: str | None): - suffix = f" x{count}" if count > 1 else "" - columns = [ - ("GPU", lambda row: row["name"]), - ("VRAM", lambda row: f"{row['memory']}GB"), - ] - if product == "SERVERLESS": - columns += [ - ("POOL", lambda row: row["pool"]), - (f"$/HR{suffix}", lambda row: _money(row["totalPrice"].get("serverless"))), - ] - else: - tiers = [cloud] if cloud else ["secure", "community"] - for tier in tiers: - columns.append( - ( - f"{tier.upper()} $/HR{suffix}", - lambda row, tier=tier: _money(row["totalPrice"].get(tier)), - ) - ) - columns.append( - ( - "MAX", - lambda row: ( - row["maxCount"].get(cloud) - if cloud - else max(row["maxCount"].values(), default=None) - ), - ) - ) - columns += [ - ("STOCK", lambda row: (row.get("availability") or "NONE").lower()), - ("DATA CENTERS", lambda row: _stock(row.get("dataCenters") or [])), - ] - return columns - - -def _cpu_rows(query, product, vcpu, regions, available) -> list[dict]: - cpus = compute.list_cpus(product=product, vcpu_count=vcpu) - if query: - cpus = compute.match_cpus(query, cpus) - if not cpus: - raise compute.ResolutionError(f"unknown cpu '{query}'") - return sorted( - _filter_stock(cpus, regions, available), - key=lambda row: -compute.availability_rank(row.get("availability")), - ) - - -def _cpu_columns(product: str): - tier = "serverlessPerVcpu" if product == "SERVERLESS" else "securePerVcpu" - return [ - ("CPU", lambda row: row["id"]), - ("NAME", lambda row: row["name"]), - ("GROUP", lambda row: row["group"]), - ("VCPU", lambda row: "{min}-{max}".format(**row["vcpu"])), - ("RAM/VCPU", lambda row: f"{row['ramGbPerVcpu']:g}GB"), - ("$/VCPU-HR", lambda row: _money(row["price"].get(tier), ".4g")), - ("STOCK", lambda row: (row.get("availability") or "NONE").lower()), - ("DATA CENTERS", lambda row: _stock(row.get("dataCenters") or [])), - ] - - -_DATACENTER_COLUMNS = [ - ("DATA CENTER", lambda row: row["id"]), - ("REGION", lambda row: row["region"].lower().replace("_", " ")), - ( - "VOLUME TYPES", - lambda row: [kind.lower() for kind in row["networkVolumeTypes"]], - ), - ("GLOBAL NETWORK", lambda row: row["globalNetwork"]), - ("COMPLIANCE", lambda row: row["compliance"]), -] - - -@click.command() -@click.argument("query", required=False) -@click.option( - "--pod", - "product", - flag_value="POD", - default=True, - help="Pod pricing and stock (default).", -) -@click.option( - "--serverless", - "product", - flag_value="SERVERLESS", - help="Serverless pricing, pools, and stock.", -) -@click.option( - "--cpu", "cpu_mode", is_flag=True, help="Search CPU flavors instead of GPUs." -) -@click.option( - "--datacenters", is_flag=True, help="List data centers and their regions." -) -@click.option( - "--count", - type=click.IntRange(min=1), - default=1, - show_default=True, - help="GPUs per pod or worker; prices and stock account for it.", -) -@click.option( - "--vcpu", - type=click.IntRange(min=2), - default=None, - help="vCPUs per pod or worker (with --cpu).", -) -@click.option( - "--region", - "regions", - multiple=True, - help="Region (eu, na, asia), id prefix (us, eu-ro), or data center id. Repeatable.", -) -@click.option( - "--cloud", - type=click.Choice(["secure", "community"], case_sensitive=False), - default=None, - help="Pod cloud tier.", -) -@click.option( - "--cuda", - multiple=True, - help="CUDA filter: '>=12.4' for a floor, 12.4 or 12.4,12.8 for exact versions.", -) -@click.option("--min-vram", type=int, default=None, help="Minimum VRAM per GPU in GB.") -@click.option("--max-price", type=float, default=None, help="Maximum USD per GPU-hour.") -@click.option("--available", is_flag=True, help="Only show hardware that is in stock.") -@json_option -def catalog( - query, - product, - cpu_mode, - datacenters, - count, - vcpu, - regions, - cloud, - cuda, - min_vram, - max_price, - available, - as_json, -): # pylint: disable=too-many-arguments - """Search GPU and CPU pricing and stock by data center. - - QUERY is a human-readable GPU (4090, h100, a100-sxm4), a serverless - pool id, or with --cpu a CPU flavor. - - \b - rp catalog h100 --count 2 --region eu --cuda '>=12.4' - rp catalog 4090 --serverless - rp catalog --cpu --vcpu 8 --available - rp catalog --datacenters --region us - """ - if cpu_mode and datacenters: - raise click.UsageError("use either --cpu or --datacenters") - if datacenters: - mode = "--datacenters" - unsupported = ( - "product", - "count", - "vcpu", - "cloud", - "cuda", - "min_vram", - "max_price", - "available", - ) - elif cpu_mode: - mode = "--cpu" - unsupported = ("count", "cuda", "min_vram", "max_price") - else: - mode = "GPU" - unsupported = ("vcpu",) - ctx = click.get_current_context() - for name in unsupported: - if ctx.get_parameter_source(name) not in (None, ParameterSource.DEFAULT): - option = product.lower() if name == "product" else name.replace("_", "-") - raise click.UsageError(f"--{option} cannot be used in {mode} mode") - if cloud and product == "SERVERLESS": - raise click.UsageError("--cloud applies to pods only") - cloud = cloud.lower() if cloud else None - if cpu_mode and cloud == "community": - raise click.UsageError("--cpu is only available in the secure cloud") - - with api_errors(): - if datacenters: - values = regions + ((query,) if query else ()) - rows = compute.list_datacenters() - if values: - allowed = set(compute.resolve_regions(values, rows)) - rows = [row for row in rows if row["id"] in allowed] - columns, empty = _DATACENTER_COLUMNS, "no data centers match" - elif cpu_mode: - rows = _cpu_rows(query, product, vcpu, regions, available) - columns, empty = _cpu_columns(product), "no cpu flavors match" - else: - rows = _gpu_rows( - query, - product, - count, - regions, - cloud, - cuda, - min_vram, - max_price, - available, - ) - columns, empty = _gpu_columns(product, count, cloud), "no gpus match" - - if as_json: - print_json(rows) - return - print_table(rows, columns, empty) +sys.modules[__name__] = catalog diff --git a/runpod/rp_cli/compute.py b/runpod/rp_cli/compute.py index ef8f67c79..8400c3740 100644 --- a/runpod/rp_cli/compute.py +++ b/runpod/rp_cli/compute.py @@ -1,258 +1,7 @@ -"""gpu, cpu, and region resolution against the rest v2 catalog.""" +"""shared command-line helpers.""" -import re -from collections.abc import Iterable -from typing import Any +import sys -from runpod.api.rest import run_rest_request +from runpod.cli import compute -AVAILABILITY_RANK = {"NONE": 0, "LOW": 1, "MEDIUM": 2, "HIGH": 3} - -REGION_ALIASES = { - "na": "NORTH_AMERICA", - "northamerica": "NORTH_AMERICA", - "sa": "SOUTH_AMERICA", - "southamerica": "SOUTH_AMERICA", - "eu": "EUROPE", - "europe": "EUROPE", - "asia": "ASIA", - "apac": "ASIA", - "me": "MIDDLE_EAST", - "middleeast": "MIDDLE_EAST", - "africa": "AFRICA", - "oceania": "OCEANIA", -} - -_NOISE_TOKENS = {"nvidia", "geforce", "amd", "instinct"} - - -class ResolutionError(ValueError): - """a user-supplied gpu, cpu, or region that does not resolve.""" - - -def _query_params(**values: Any) -> dict[str, Any]: - return { - key: ",".join(value) if isinstance(value, (list, tuple)) else value - for key, value in values.items() - if value is not None and value != [] - } - - -def list_gpus( - product: str | None = None, - count: int | None = None, - cloud: str | None = None, - cuda_versions: list[str] | None = None, - min_cuda_version: str | None = None, -) -> list[dict]: - """gpu types, with availability when a product context is given.""" - params = _query_params( - include="AVAILABILITY" if product else None, - product=product, - count=count if product else None, - cloud=cloud if product else None, - cudaVersions=cuda_versions if product else None, - minCudaVersion=min_cuda_version if product else None, - ) - return run_rest_request("GET", "/v2/catalog/gpus", params=params)["gpus"] - - -def list_cpus( - product: str | None = None, vcpu_count: int | None = None -) -> list[dict]: - """cpu flavors, with availability when a product context is given.""" - params = _query_params( - include="AVAILABILITY" if product else None, - product=product, - vcpuCount=vcpu_count if product else None, - ) - return run_rest_request("GET", "/v2/catalog/cpus", params=params)["cpus"] - - -def list_datacenters(include: list[str] | None = None) -> list[dict]: - """every data center in the catalog.""" - return run_rest_request( - "GET", "/v2/catalog/datacenters", params=_query_params(include=include) - )["dataCenters"] - - -def _tokens(text: str) -> list[str]: - return [token for token in re.split(r"[\s_\-]+", text.lower()) if token] - - -def _compact(text: str) -> str: - return re.sub(r"[\s_\-]+", "", text.lower()) - - -def match_gpus(query: str, gpus: Iterable[dict]) -> list[dict]: - """prefer exact ids, names, and pools, then match hardware-name tokens.""" - gpus = list(gpus) - text = query.strip().lower() - exact = [ - gpu - for gpu in gpus - if text in (gpu["id"].lower(), (gpu.get("name") or "").lower()) - ] - if exact: - return exact - pool = [gpu for gpu in gpus if (gpu.get("pool") or "").lower() == text] - if pool: - return pool - wanted = [token for token in _tokens(text) if token not in _NOISE_TOKENS] - if not wanted: - return [] - hits = [ - gpu - for gpu in gpus - if set(wanted) <= set(_tokens(gpu["id"])) | set(_tokens(gpu.get("name") or "")) - ] - if hits: - return hits - compact = "".join(wanted) - return [gpu for gpu in gpus if compact in _compact(gpu["id"])] - - -def resolve_gpus(query: str, gpus: Iterable[dict]) -> list[dict]: - """like match_gpus, but raise when nothing matches.""" - gpus = list(gpus) - matches = match_gpus(query, gpus) - if not matches: - known = ", ".join(sorted(gpu.get("name") or gpu["id"] for gpu in gpus)) - raise ResolutionError(f"unknown gpu '{query}'. known gpus: {known}") - return matches - - -def parse_gpu_spec(value: str) -> tuple[str, int | None]: - """split "h100:2" into ("h100", 2); a bare name has no count.""" - name, sep, count = value.strip().rpartition(":") - if not sep: - return value.strip(), None - if not name or not count.isdigit() or int(count) < 1: - raise ResolutionError( - f"invalid gpu '{value}'. use a name with an optional count, like h100:2" - ) - return name, int(count) - - -def parse_cuda(values: Iterable[str]) -> tuple[str | None, list[str]]: - """split cuda filters into (minimum, exact versions). - - ">=12.4" sets a floor; "12.4" or "12.4,12.8" lists exact versions. - """ - minimum = None - exact: list[str] = [] - for value in values: - for part in value.split(","): - part = part.strip() - if not part: - continue - floor = part.startswith(">=") - version = part[2:].strip() if floor else part - if not re.fullmatch(r"\d+\.\d+", version): - raise ResolutionError( - f"invalid cuda version '{part}'. use 12.4, 12.4,12.8, or '>=12.4'" - ) - if floor: - if minimum is None or tuple(map(int, version.split("."))) > tuple( - map(int, minimum.split(".")) - ): - minimum = version - else: - exact.append(version) - if minimum and exact: - raise ResolutionError( - "use either a cuda floor (>=) or exact versions, not both" - ) - return minimum, exact - - -def endpoint_gpu_selection( - matches: Iterable[dict], gpus: Iterable[dict] -) -> tuple[list[str], list[str]]: - """serverless (pools, excludedTypes) that select exactly the matched types.""" - matches = list(matches) - pools = list(dict.fromkeys(gpu["pool"] for gpu in matches if gpu.get("pool"))) - if not pools: - names = ", ".join(gpu.get("name") or gpu["id"] for gpu in matches) - raise ResolutionError(f"{names} is not offered on serverless") - chosen = {gpu["id"] for gpu in matches} - excluded = [ - gpu["id"] - for gpu in gpus - if gpu.get("pool") in pools and gpu["id"] not in chosen - ] - return pools, excluded - - -def resolve_regions(values: Iterable[str], datacenters: Iterable[dict]) -> list[str]: - """data center ids named by ids, id prefixes, or region names. - - "EU-RO-1" is one data center, "us" and "eu-ro" match every id with - that prefix, and "eu" or "europe" match every data center in the - region. - """ - datacenters = list(datacenters) - resolved: list[str] = [] - for value in values: - text = value.strip().upper().replace("_", "-") - region = REGION_ALIASES.get(_compact(value)) - matches = [ - dc["id"] - for dc in datacenters - if dc["id"].upper() == text - or dc["id"].upper().startswith(text + "-") - or (region and dc.get("region") == region) - ] - if not matches: - ids = ", ".join(sorted(dc["id"] for dc in datacenters)) - names = ", ".join( - sorted( - { - dc["region"].lower().replace("_", "-") - for dc in datacenters - if dc.get("region") - } - ) - ) - raise ResolutionError( - f"unknown region '{value}'. use a region (eu, na, {names}), " - f"an id prefix like us or eu-ro, or a data center ({ids})" - ) - resolved.extend(match for match in matches if match not in resolved) - return resolved - - -def match_cpus(query: str, cpus: Iterable[dict]) -> list[dict]: - """cpu flavors named by id ("cpu3c"), group ("cpu3"), or name.""" - text = query.strip().lower() - return [ - cpu - for cpu in cpus - if text - in ( - cpu["id"].lower(), - (cpu.get("group") or "").lower(), - (cpu.get("name") or "").lower(), - ) - or _compact(text) == _compact(cpu.get("name") or "") - ] - - -def resolve_cpu(query: str, cpus: Iterable[dict]) -> dict: - """the single cpu flavor a query names.""" - cpus = list(cpus) - matches = match_cpus(query, cpus) - if len(matches) != 1: - known = ", ".join(sorted(cpu["id"] for cpu in cpus)) - problem = "ambiguous" if matches else "unknown" - raise ResolutionError(f"{problem} cpu '{query}'. cpu flavors: {known}") - return matches[0] - - -def availability_rank(level: str | None) -> int: - return AVAILABILITY_RANK.get(level or "NONE", 0) - - -def best_availability(levels: Iterable[str | None]) -> str: - """the highest stock level among levels, NONE when empty.""" - return max(levels, key=availability_rank, default="NONE") or "NONE" +sys.modules[__name__] = compute diff --git a/runpod/rp_cli/console.py b/runpod/rp_cli/console.py index 8139a2ed8..d74157611 100644 --- a/runpod/rp_cli/console.py +++ b/runpod/rp_cli/console.py @@ -1,615 +1,7 @@ -"""console rendering for the rp cli. +"""shared command-line helpers.""" -live, animated lifecycle output: spinner-driven phase tracking for -deploys (with byte-level upload progress), per-resource provisioning -animation for dev sessions, and color-coded resource badges. engine -modules stay renderer-free; they emit duck-typed events and this -module turns them into pixels. -""" +import sys -import time -from collections.abc import Iterable +from runpod.cli import console -from rich.console import Console -from rich.progress import ( - Progress, - SpinnerColumn, - Task, - TaskID, - TextColumn, -) -from rich.spinner import SPINNERS -from rich.text import Text -from rich.theme import Theme - -from runpod._hosts import console_url - -# -- brand ---------------------------------------------------------------- - -ACCENT = "#673de6" # runpod purple -ACCENT_LIGHT = "#a78bfa" -OK = "#34d399" -ERR = "#f87171" -WARN = "#fbbf24" -DIM = "grey58" - -RUNPOD_SAND_SPINNER = "runpod_sand" -RUNPOD_SAND_SPINNER_FRAMES = [ - "⠁", - "⠂", - "⠄", - "⡀", - "⡈", - "⡐", - "⡠", - "⣀", - "⣁", - "⣂", - "⣄", - "⣌", - "⣔", - "⣤", - "⣥", - "⣦", - "⣮", - "⣶", - "⣷", - "⣿", - "⡿", - "⠿", - "⢟", - "⠟", - "⡛", - "⠛", - "⠫", - "⢋", - "⠋", - "⠍", - "⡉", - "⠉", - "⠑", - "⠡", - "⢁", -] -SPINNERS[RUNPOD_SAND_SPINNER] = { - "interval": 1000 / 16, - "frames": RUNPOD_SAND_SPINNER_FRAMES, -} - -KIND_STYLES: dict[str, str] = { - "queue": "bold cyan", - "api": "bold magenta", - "task": "bold yellow", -} - -theme = Theme( - { - "accent": ACCENT, - "accent.light": ACCENT_LIGHT, - "ok": OK, - "err": ERR, - "warn": WARN, - "dim": DIM, - "progress.elapsed": DIM, - } -) - -console = Console(highlight=False, theme=theme) - - -def _spinner_column(finished_text: str = "[ok]✓[/ok]") -> SpinnerColumn: - return SpinnerColumn( - RUNPOD_SAND_SPINNER, - style=ACCENT, - finished_text=finished_text, - ) - - -def endpoint_url(endpoint_id: str) -> str: - return f"{console_url()}/serverless/user/endpoint/{endpoint_id}?tab=overview" - - -def endpoint_link(endpoint_id: str) -> str: - """short clickable endpoint reference (osc8 hyperlink).""" - return ( - f"[link={endpoint_url(endpoint_id)}]" - f"[accent.light]{endpoint_id} ↗[/accent.light][/link]" - ) - - - - -_name_width: int = 0 - - -def set_name_width(names: Iterable[str]) -> None: - global _name_width - _name_width = max((len(n) for n in names), default=0) - - -def _padded(name: str) -> str: - return f"{name:<{_name_width}}" if _name_width else name - - -def _pipe(name: str) -> str: - return f"[accent.light]{_padded(name)}[/accent.light] [dim]│[/dim]" - - -def kind_badge(kind: str) -> str: - style = KIND_STYLES.get(kind, "bold white") - return f"[{style}]{kind:<5}[/{style}]" - - -# -- generic lines --------------------------------------------------------- - - -def info(message: str) -> None: - console.print(f"{message}") - - -def success(message: str) -> None: - console.print(f"[ok]✓[/ok] {message}") - - -def error(message: str) -> None: - console.print(f"[err]✗[/err] {message}") - - -def warn(message: str) -> None: - console.print(f"[warn]![/warn] {message}") - - -def rule(title: str = "") -> None: - console.rule(f"[accent]{title}[/accent]" if title else None, style="dim") - - -# -- request lifecycle ----------------------------------------------------- - - -def request_started(name: str, label: str = "") -> None: - console.print( - f"[bold white]CALL[/bold white] [accent.light]/{name}[/accent.light]" - f" [dim]{label}[/dim]" - ) - - -def request_completed(name: str, elapsed_s: float) -> None: - console.print( - f"[ok]✓[/ok] {_padded(name)} [dim]{elapsed_s:.1f}s[/dim]" - ) - - -def request_failed(name: str, elapsed_s: float, err: str | None = None) -> None: - console.print( - f"[err]✗[/err] {_padded(name)} [dim]{elapsed_s:.1f}s[/dim]" - ) - if err: - console.print(f" [err dim]{err}[/err dim]") - - -# -- banners --------------------------------------------------------------- - - -def dev_banner(app_names: Iterable[str], module: str) -> None: - console.print( - f"[bold white]dev[/bold white] [dim]{', '.join(app_names)} in {module}[/dim]" - ) - - -def deploy_plan(apps: Iterable[tuple[str, str, int]]) -> None: - """upfront summary for multi-app deploys: (name, source, n_resources).""" - apps = list(apps) - console.print( - f"[bold white]deploy[/bold white] [dim]{len(apps)} apps[/dim]" - ) - width = max(len(name) for name, _, _ in apps) - for name, source, count in apps: - detail = f"{source}, " if source else "" - console.print( - f" [white]{name:<{width}}[/white] " - f"[dim]{detail}{count} resource{'s' if count != 1 else ''}[/dim]" - ) - - -def deploy_banner( - app_name: str, - env: str, - resources: Iterable[tuple[str, str]], - source: str = "", -) -> None: - """resources: (name, kind) pairs.""" - names = ", ".join(name for name, _ in resources) or "(no resources)" - origin = f" from {source}" if source else "" - console.print( - f"[bold white]deploy[/bold white] [white]{app_name}[/white] " - f"[dim]→ {env}{origin}, {names}[/dim]" - ) - - -def resources_table(rows: Iterable[tuple]) -> None: - """rows of (name, kind, hardware, endpoint_id).""" - rows = list(rows) - if not rows: - return - w_name = max(len(r[0]) for r in rows) - w_hw = max(len(r[2]) for r in rows) - for name, kind, hardware, endpoint_id in rows: - if endpoint_id == "registered": - tail = "[dim]registered / per-call[/dim]" - elif not endpoint_id or endpoint_id == "per-call": - tail = "[dim]per-call[/dim]" - else: - tail = endpoint_link(endpoint_id) - console.print( - f" [white]{name:<{w_name}}[/white]" - f" {kind_badge(kind)}" - f" [dim]{hardware:<{w_hw}}[/dim]" - f" {tail}" - ) - - -def reload_banner(module: str = "") -> None: - console.print() - detail = f" [dim]{module} changed[/dim]" if module else "" - console.print(f" [accent]↻[/accent] [white]reloading[/white]{detail}") - - -# -- live deploy phases ------------------------------------------------------ - -_PHASE_LABELS = { - "vendor": "resolving dependencies", - "package": "packaging artifact", - "upload": "uploading build", - "endpoints": "deploying endpoints", - "snapshot": "saving current settings", - "activate": "activating build", - "cleanup": "removing unused endpoints", -} - - -_BAR_WIDTH = 22 - - -def _bar(fraction: float) -> str: - """slim one-line progress bar.""" - fraction = min(max(fraction, 0.0), 1.0) - filled = int(fraction * _BAR_WIDTH) - return ( - f"[accent]{'━' * filled}[/accent]" - f"[grey30]{'━' * (_BAR_WIDTH - filled)}[/grey30]" - ) - - -class _DeploySpinnerColumn(SpinnerColumn): - def render(self, task: Task) -> Text: - if task.fields.get("failed"): - return Text("✗", style="err") - return super().render(task) - - -class DeployEvents: - """deploy_app event sink: animated phase list with live progress. - - each phase renders a spinner while active and collapses to a ✓ with - a short summary when the next begins. vendoring streams package - names as pip resolves them; upload renders a slim in-line bar. - """ - - def __init__(self) -> None: - self._progress = Progress( - _DeploySpinnerColumn( - RUNPOD_SAND_SPINNER, style=ACCENT, finished_text="[ok]✓[/ok]" - ), - TextColumn("[white]{task.description}[/white]"), - TextColumn("{task.fields[detail]}"), - console=console, - transient=False, - ) - self._current: TaskID | None = None - self._current_name = "" - self._started = False - self._package_count = 0 - self._upload_total = 0 - - def _ensure_started(self) -> None: - if not self._started: - self._progress.start() - self._started = True - - def _finish_current(self) -> None: - if self._current is None: - return - # collapse the live detail into a short summary - if self._current_name == "vendor" and self._package_count: - summary = f"{self._package_count} packages" - elif self._current_name == "upload" and self._upload_total: - summary = f"{self._upload_total / 1048576:.1f} MB" - else: - summary = "" - self._progress.update( - self._current, - detail=f"[dim]{summary}[/dim]", - total=1, - completed=1, - ) - self._current = None - - def phase(self, name: str, detail: str = "") -> None: - self._ensure_started() - self._finish_current() - self._current_name = name - self._current = self._progress.add_task( - _PHASE_LABELS.get(name, name), - detail=f"[dim]{detail}[/dim]" if detail else "", - total=None, - ) - - def vendor_progress(self, count: int, package: str) -> None: - if self._current is None: - return - self._package_count = count - self._progress.update( - self._current, - detail=f"[accent.light]{package}[/accent.light] [dim]({count})[/dim]", - ) - - def upload_progress(self, sent: int, total: int) -> None: - if self._current is None: - return - self._upload_total = total - mb = 1048576 - self._progress.update( - self._current, - detail=( - f"{_bar(sent / total)} " - f"[dim]{sent / mb:.1f} / {total / mb:.1f} MB[/dim]" - ), - ) - - def endpoint_ready(self, name: str, endpoint_id: str) -> None: - # collected, not printed: endpoint urls render in the final - # summary after the progress display stops - self.endpoints: dict[str, str] = getattr(self, "endpoints", {}) - self.endpoints[name] = endpoint_id - - def close(self, *, failed: bool = False) -> None: - if failed and self._current is not None: - self._progress.update(self._current, failed=True, detail="") - self._progress.stop_task(self._current) - self._current = None - else: - self._finish_current() - if self._started: - self._progress.stop() - self._started = False - - -# -- live dev provisioning ---------------------------------------------------- - - -class DevEvents: - """DevSession event sink. - - provisioning renders transient spinner rows that vanish once the - session is up (the resource table is the durable record). request - lifecycle renders as a block: an accent dispatch line, a dim - indented worker feed, and a check/cross verdict. - """ - - def __init__(self) -> None: - self._progress: Progress | None = None - self._tasks: dict[str, TaskID] = {} - - def session_starting(self) -> None: - self._progress = Progress( - _spinner_column(), - TextColumn("[white]{task.description}[/white]"), - TextColumn("[dim]{task.fields[detail]}[/dim]"), - console=console, - transient=True, - ) - self._progress.start() - - def session_started(self) -> None: - if self._progress is not None: - self._progress.stop() - self._progress = None - self._tasks.clear() - - def _row(self, name: str, detail: str) -> None: - if self._progress is None: - info(f"{_pipe(name)} {detail}") - return - if name not in self._tasks: - self._tasks[name] = self._progress.add_task( - _padded(name), detail=detail, total=None - ) - else: - self._progress.update(self._tasks[name], detail=detail) - - def provisioning(self, name: str, kind: str, hardware: str) -> None: - self._row(name, f"provisioning {kind} on {hardware}") - - def adopted(self, name: str, endpoint_id: str) -> None: - self._row(name, "adopting") - - def ready(self, name: str, endpoint_id: str) -> None: - if self._progress is not None and name in self._tasks: - self._progress.update( - self._tasks[name], detail="ready", total=1, completed=1 - ) - - def deleted(self, name: str) -> None: - console.print(f" [dim]− {name}[/dim]") - - # -- refresh diff -- - - def resource_added(self, name: str, kind: str, hardware: str) -> None: - console.print( - f" [ok]+[/ok] [white]{name}[/white] " - f"[dim]{kind} on {hardware}[/dim]" - ) - - def resource_changed(self, name: str, fields: list[str]) -> None: - what = ", ".join(fields) if fields else "config" - console.print( - f" [warn]~[/warn] [white]{name}[/white] [dim]{what}[/dim]" - ) - - def resource_removed(self, name: str) -> None: - console.print(f" [err]−[/err] [white]{name}[/white]") - - # -- request lifecycle (LiveTarget events) -- - # next.js/wrangler-style event lines: leading status glyph, the - # function call in normal weight, everything else dim, timing at - # the end. function stdout renders as `name │ line` so concurrent - # calls interleave without losing attribution. - - def dispatch(self, name: str, label: str = "") -> None: - detail = f" [dim]{label}[/dim]" if label else "" - console.print(f" [accent]→[/accent] [white]{name}()[/white]{detail}") - - def worker_status(self, name: str, counts: dict[str, int]) -> None: - from runpod.apps.monitor import format_worker_counts - - console.print( - f" [dim]↳ {name}() waiting: {format_worker_counts(counts)}[/dim]" - ) - - def task_status(self, name: str, detail: str) -> None: - console.print(f" [dim]↳ {name}() {detail}[/dim]") - - def volume_created(self, name: str, size: int, dc: str) -> None: - console.print( - f" [ok]+[/ok] [white]volume {name}[/white] [dim]{size}GB in {dc}[/dim]" - ) - - def worker_ready(self, name: str, worker_id: str) -> None: - worker = worker_id[:12] if worker_id else "pod" - console.print( - f" [accent]↳[/accent] [white]{name}()[/white] [dim]worker " - f"{worker} ready[/dim]" - ) - - def worker_log(self, name: str, line: str) -> None: - from rich.markup import escape - - console.print(f" {_pipe(name)} {escape(line)}") - - def request_completed(self, name: str, elapsed_s: float) -> None: - console.print( - f" [ok]✓[/ok] [white]{name}()[/white] " - f"[dim]in {_fmt_elapsed(elapsed_s)}[/dim]" - ) - - def request_failed(self, name: str, elapsed_s: float) -> None: - console.print( - f" [err]✗[/err] [white]{name}()[/white] " - f"[dim]failed in {_fmt_elapsed(elapsed_s)}[/dim]" - ) - - -class CleanupEvents: - """session teardown sink: one spinner line with delete progress.""" - - def __init__(self) -> None: - self._progress: Progress | None = None - self._task: TaskID | None = None - self._total = 0 - self._done = 0 - - def cleanup_started(self, total: int) -> None: - self._total = total - if total == 0: - return - console.print() - self._progress = Progress( - _spinner_column(), - TextColumn("[white]{task.description}[/white]"), - TextColumn("[dim]{task.fields[detail]}[/dim]"), - console=console, - ) - self._progress.start() - self._task = self._progress.add_task( - "cleaning up", detail="", total=total - ) - - def deleting(self, name: str) -> None: - if self._progress is not None and self._task is not None: - self._progress.update( - self._task, detail=f"{name} ({self._done}/{self._total})" - ) - - def deleted(self, name: str) -> None: - self._done += 1 - if self._progress is not None and self._task is not None: - self._progress.update( - self._task, - completed=self._done, - detail=f"{name} ({self._done}/{self._total})", - ) - - def delete_failed(self, name: str) -> None: - self._done += 1 - if self._progress is not None and self._task is not None: - self._progress.update(self._task, completed=self._done) - console.print(f" [warn]![/warn] [dim]could not delete {name}[/dim]") - - def close(self) -> None: - if self._progress is not None and self._task is not None: - self._progress.update( - self._task, - completed=self._total, - detail=f"{self._done} deleted", - ) - self._progress.stop() - self._progress = None - - -class Timer: - """context timer for elapsed reporting.""" - - def __enter__(self) -> "Timer": - self._start = time.monotonic() - return self - - def __exit__(self, *exc) -> None: - self.elapsed = time.monotonic() - self._start - - @property - def so_far(self) -> float: - return time.monotonic() - self._start - - -def _fmt_elapsed(elapsed: float) -> str: - if elapsed < 1: - return f"{elapsed * 1000:.0f}ms" - if elapsed < 120: - return f"{elapsed:.1f}s" - return f"{int(elapsed // 60)}m{int(elapsed % 60):02d}s" - - -def entrypoint_header(fn_name: str = "") -> None: - console.print() - if fn_name: - console.print( - f" [accent]◆[/accent] [white]{fn_name}()[/white] " - f"[dim]local entrypoint[/dim]" - ) - - -def entrypoint_success(elapsed: float) -> None: - console.print() - console.print( - f" [ok]✓[/ok] [white]done[/white] [dim]in {_fmt_elapsed(elapsed)}, " - f"enter re-run, edit reload, ^C quit[/dim]" - ) - - -def entrypoint_failure(elapsed: float, err: str) -> None: - console.print() - console.print(f" [err]✗ {err}[/err]") - console.print( - f" [err]✗[/err] [white]failed[/white] [dim]in {_fmt_elapsed(elapsed)}, " - f"enter re-run, edit reload, ^C quit[/dim]" - ) +sys.modules[__name__] = console diff --git a/runpod/rp_cli/datacenter.py b/runpod/rp_cli/datacenter.py index 7fdcd80cf..0ea88929f 100644 --- a/runpod/rp_cli/datacenter.py +++ b/runpod/rp_cli/datacenter.py @@ -1,58 +1,7 @@ -"""data center locations and GPU availability.""" +"""shared command-line helpers.""" -import click +import sys -from runpod.api.graphql import run_graphql_query -from runpod.rp_cli.api import api_errors -from runpod.rp_cli.output import json_option, print_json, print_table +from runpod.cli import datacenter -_DATACENTERS_QUERY = """ -query { - dataCenters { - id - name - location - gpuAvailability { - gpuTypeId - displayName - stockStatus - } - } -} -""" - - -def _availability(row): - return ", ".join( - f"{gpu.get('displayName') or gpu.get('gpuTypeId') or '-'} " - f"({gpu.get('stockStatus') or '-'})" - for gpu in row.get("gpuAvailability") or [] - ) - - -_COLUMNS = [ - ("ID", lambda row: row.get("id")), - ("NAME", lambda row: row.get("name")), - ("LOCATION", lambda row: row.get("location")), - ("GPU AVAILABILITY", _availability), -] - - -@click.group() -def datacenter(): - """Browse data center locations and GPU availability.""" - - -@datacenter.command("list") -@json_option -def list_datacenters(as_json): - """List data centers and their GPU stock.""" - with api_errors(): - data = run_graphql_query(_DATACENTERS_QUERY).get("data") or {} - if "dataCenters" not in data: - raise click.ClickException("data center information is unavailable") - rows = data["dataCenters"] or [] - if as_json: - print_json(rows) - return - print_table(rows, _COLUMNS, "no data centers found") +sys.modules[__name__] = datacenter diff --git a/runpod/rp_cli/endpoint.py b/runpod/rp_cli/endpoint.py index d7f18c642..0460ff72d 100644 --- a/runpod/rp_cli/endpoint.py +++ b/runpod/rp_cli/endpoint.py @@ -1,1213 +1,7 @@ -import contextlib -import fnmatch -import json -import sys -import time -from collections.abc import Iterator -from typing import Any -from urllib.parse import quote - -import click -import requests -from rich.markup import escape - -from runpod._hosts import endpoint_domain -from runpod.api.rest import run_rest_request -from runpod.apps.utils.network import api_key -from runpod.endpoint import runner -from runpod.endpoint.helpers import is_completed -from runpod.rp_cli import compute -from runpod.rp_cli import console as ui -from runpod.rp_cli import endpoint_config as config -from runpod.rp_cli.api import api_errors, list_all -from runpod.rp_cli.output import ( - completer, - confirm, - interactive, - json_option, - pick, - print_fields, - print_json, - print_table, - table, -) -from runpod.rp_cli.volume import _choices as volume_choices - -TYPES = {"queue": "QUEUE", "load-balancer": "LOAD_BALANCER"} - - -def _path(endpoint_id: str, *parts: str) -> str: - segments = [quote(value, safe="") for value in (endpoint_id, *parts)] - return "/v2/serverless/" + "/".join(segments) - - -def _choices(path: str, collection: str): - def fetch(): - return [ - (record["id"], record.get("name") or "") - for record in list_all(path, collection) - ] - - return completer(fetch) - - -complete_endpoint = _choices("/v2/serverless", "endpoints") -complete_volume = completer(volume_choices) -complete_registry = _choices("/v2/registries", "registries") -complete_template = _choices("/v2/templates", "templates") -complete_datacenter = completer( - lambda: [ - (dc["id"], (dc.get("region") or "").lower()) - for dc in compute.list_datacenters() - ] -) - - -def complete_worker(ctx, param, incomplete): - endpoint_id = ctx.params.get("endpoint_id") - if not endpoint_id: - return [] - return completer( - lambda: [ - (worker["id"], (worker.get("status") or "").lower()) - for worker in run_rest_request("GET", _path(endpoint_id, "workers"))[ - "workers" - ] - ] - )(ctx, param, incomplete) - - -def endpoint_argument(required: bool = True): - return click.argument( - "endpoint_id", required=required, shell_complete=complete_endpoint - ) - - -def _pick_endpoint(endpoint_id: str | None) -> str: - if endpoint_id: - return endpoint_id - if not interactive(): - raise click.UsageError("pass an ENDPOINT_ID") - with api_errors(): - endpoints = list_all("/v2/serverless", "endpoints") - return pick( - "endpoint", - [ - (e["id"], f"{e['id']} {e.get('name') or ''} {_type(e) or ''}") - for e in endpoints - ], - "pass an ENDPOINT_ID", - ) - - -def _type(endpoint: dict) -> str | None: - names = {value: key for key, value in TYPES.items()} - return names.get(endpoint.get("type"), endpoint.get("type")) - - -def _flashboot(endpoint: dict) -> str | None: - names = {value: key for key, value in config.FLASHBOOT.items()} - return names.get(endpoint.get("flashboot"), endpoint.get("flashboot")) - - -def _compute(endpoint: dict, compact: bool = False) -> str | None: - gpu = endpoint.get("gpu") - if gpu: - text = f"{', '.join(gpu.get('pools') or [])} x{gpu.get('count') or 1}" - excluded = gpu.get("excludedTypes") or [] - if compact or not excluded: - return text - return f"{text} (excluding {', '.join(excluded)})" - cpus = endpoint.get("cpu") or [] - return ", ".join(f"{cpu['id']} {cpu.get('vcpuCount')} vcpu" for cpu in cpus) or None - - -def _cuda(endpoint: dict) -> str | None: - gpu = endpoint.get("gpu") - if not gpu: - return None - if gpu.get("minCudaVersion"): - return f">={gpu['minCudaVersion']}" - return ", ".join(gpu.get("allowedCudaVersions") or []) or "any" - - -def _scaling(endpoint: dict, compact: bool = False) -> str | None: - scaling = endpoint.get("scaling") or {} - if scaling.get("type") == "QUEUE_DELAY": - delay = f"{scaling.get('queueDelay'):g}s" - return f"{delay} delay" if compact else f"queue delay {delay}" - if scaling.get("type") == "REQUEST_COUNT": - count = scaling.get("requestCount") - return f"{count}/worker" if compact else f"{count} requests per worker" - return None - - -def _workers(endpoint: dict) -> str | None: - workers = endpoint.get("workers") or {} - if "min" not in workers and "max" not in workers: - return None - return f"{workers.get('min', 0)}-{workers.get('max', 0)}" - - -def _seconds(value: float | None) -> str | None: - return f"{value:g}s" if value else None - - -def _volumes(endpoint: dict) -> list[str]: - mounts = endpoint.get("mounts") or {} - return [ - f"{mount['volumeId']} ({kind})" - for kind in ("network", "global") - for mount in mounts.get(kind) or [] - ] - - -def _url(endpoint: dict) -> str | None: - urls = endpoint.get("requestUrls") or {} - return urls.get("base") or urls.get("run") - - -_LIST_COLUMNS = [ - ("ID", lambda e: e["id"]), - ("NAME", lambda e: e.get("name")), - ("TYPE", _type), - ("COMPUTE", lambda e: _compute(e, compact=True)), - ("WORKERS", _workers), - ("SCALING", lambda e: _scaling(e, compact=True)), - ("CREATED", lambda e: (e.get("createdAt") or "")[:10]), -] - -_FIELDS = [ - ("id", lambda e: e.get("id")), - ("name", lambda e: e.get("name")), - ("type", _type), - ("image", lambda e: e.get("image")), - ("compute", _compute), - ("cuda", _cuda), - ("workers", _workers), - ("idle timeout", lambda e: _seconds((e.get("workers") or {}).get("idleTimeout"))), - ("scaling", _scaling), - ("request timeout", lambda e: _seconds((e.get("timeout") or 0) / 1000)), - ("flashboot", _flashboot), - ("data centers", lambda e: e.get("dataCenterIds")), - ("volumes", _volumes), - ("env", lambda e: sorted(e.get("env") or {})), - ("ports", lambda e: e.get("ports")), - ("disk", lambda e: f"{e['disk']}GB" if e.get("disk") else None), - ("args", lambda e: e.get("args")), - ("registry", lambda e: e.get("registry")), - ("url", _url), - ("created", lambda e: e.get("createdAt")), -] - - -def _scale_options(func): - for option in reversed( - [ - click.option( - "--min-workers", type=click.IntRange(min=0), help="Minimum workers." - ), - click.option( - "--max-workers", type=click.IntRange(min=0), help="Maximum workers." - ), - click.option( - "--idle-timeout-seconds", - type=click.IntRange(1, 3600), - help="Seconds before idle workers scale down.", - ), - click.option( - "--queue-delay-seconds", - type=click.FloatRange(min=0.5), - help="Scale on queue wait time (queue endpoints).", - ), - click.option( - "--requests-per-worker", - type=click.IntRange(min=1), - help="Scale on in-flight requests per worker.", - ), - ] - ): - func = option(func) - return func - - -def _config_options(creating: bool): - head = [click.option("--name", required=creating, help="Endpoint name.")] - if creating: - head.append( - click.option( - "--type", - "endpoint_type", - required=True, - type=click.Choice(list(TYPES), case_sensitive=False), - callback=lambda ctx, param, value: ( - TYPES[value.lower()] if value else value - ), - help="Request routing: queued jobs or load-balanced HTTP.", - ) - ) - options = head + [ - click.option("--image", help="Container image."), - click.option( - "--template", - help="Serverless template ID to base the container on.", - shell_complete=complete_template, - ), - click.option( - "--gpu", - multiple=True, - help="GPU type (4090, h100, a100-sxm4) or pool id, optionally with a " - "count (h100:2). Repeatable.", - ), - click.option( - "--gpu-count", type=click.IntRange(min=1), help="GPUs per worker." - ), - click.option( - "--cuda", - multiple=True, - help="CUDA constraint: '>=12.4' for a floor, 12.4 or 12.4,12.8 for exact " - "versions, any for no constraint.", - ), - click.option( - "--cpu", - multiple=True, - help="CPU flavor (cpu3c, cpu5g), optionally with vCPUs (cpu3c:8). Repeatable.", - ), - click.option( - "--vcpu-count", type=click.IntRange(min=2), help="vCPUs per worker." - ), - _scale_options, - click.option( - "--request-timeout-seconds", - type=click.IntRange(min=0), - help="Per-request execution timeout.", - ), - click.option( - "--data-center", - multiple=True, - help="Data center id (EU-RO-1). Repeatable.", - shell_complete=complete_datacenter, - ), - click.option( - "--region", - multiple=True, - help="Region (eu, na, asia) or id prefix (us, eu-ro). Repeatable.", - ), - click.option( - "--volume", - multiple=True, - help="Network or global volume ID. Repeatable. Updates replace mounts " - "of each supplied storage type.", - shell_complete=complete_volume, - ), - click.option( - "--env", multiple=True, help="Environment variable KEY=VALUE. Repeatable." - ), - click.option( - "--flashboot", - type=click.Choice(list(config.FLASHBOOT), case_sensitive=False), - help="FlashBoot mode.", - ), - click.option( - "--disk", type=click.IntRange(min=1), help="Container disk in GB." - ), - click.option( - "--port", multiple=True, help="Exposed port as port/protocol. Repeatable." - ), - click.option("--args", help="Container start command as one raw string."), - click.option("--entrypoint", help="Container ENTRYPOINT, shell-quoted."), - click.option("--cmd", help="Container CMD, shell-quoted."), - click.option( - "--registry", - help="Registry credential name or ID for private images; empty clears it.", - shell_complete=complete_registry, - ), - ] - if not creating: - options.append( - click.option( - "--unset-env", - multiple=True, - help="Remove an environment variable. Repeatable.", - ) - ) - - def decorate(func): - for option in reversed(options): - func = option(func) - return func - - return decorate - - -def _rollout_line(state: dict) -> str: - rollout = state.get("rollout") or {} - on_latest = f"{rollout.get('workersOnLatest', 0)}/{rollout.get('workersTotal', 0)}" - phase = "rolling out" if rollout.get("inProgress") else "live" - return f"v{state.get('endpointVersion')} {phase}, {on_latest} workers on latest" - - -def _follow_rollout( - endpoint_id: str, - previous_version: int | None, - timeout: float, - interval: float = 2.0, -) -> None: - started = time.monotonic() - last = None - try: - while True: - with api_errors(): - state = run_rest_request( - "GET", _path(endpoint_id, "releases"), params={"limit": 1} - ) - version = state.get("endpointVersion") - elapsed = time.monotonic() - started - waiting_for_release = ( - previous_version is not None and version == previous_version - ) - if not waiting_for_release: - line = _rollout_line(state) - if line != last: - ui.console.print(f"[dim]{line}[/dim]") - last = line - if not (state.get("rollout") or {}).get("inProgress"): - ui.success(f"release v{version} is live") - return - if elapsed >= timeout: - phase = ( - "no new release observed" - if waiting_for_release - else "rollout still in progress" - ) - ui.warn( - f"{phase} after {timeout:g}s. " - f"follow with: rp endpoint releases {endpoint_id}" - ) - return - time.sleep(interval) - except KeyboardInterrupt: - ui.console.print( - "\n[dim]detached; the rollout continues. " - f"follow with: rp endpoint releases {endpoint_id}[/dim]" - ) - - -def _apply( - endpoint_id: str, patch: dict, follow: bool, timeout: float, as_json: bool -) -> None: - if patch.keys() <= {"name", "workers", "scaling", "timeout", "flashboot"}: - follow = False - before = None - if follow: - try: - with api_errors(): - before = run_rest_request( - "GET", _path(endpoint_id, "releases"), params={"limit": 1} - ).get("endpointVersion") - except click.ClickException as exc: - click.echo(f"warning: cannot follow rollout: {exc.message}", err=True) - follow = False - with api_errors(): - updated = run_rest_request("PATCH", _path(endpoint_id), json=patch) - if as_json: - print_json(updated) - else: - ui.success( - f"updated [white]{escape(updated['name'])}[/white] " - f"[dim]{endpoint_id}[/dim]" - ) - if follow: - with ( - contextlib.redirect_stdout(sys.stderr) - if as_json - else contextlib.nullcontext() - ): - _follow_rollout(endpoint_id, before, timeout) - - -def _edit_document(before: dict) -> dict | None: - text = json.dumps(before, indent=2) + "\n" - while True: - edited = click.edit(text, extension=".json") - if edited is None: - return None - try: - return config.validate(edited, before) - except click.ClickException as exc: - ui.error(escape(exc.message)) - if not click.confirm("re-open the editor?", default=True): - raise - text = edited - - -def _uptime(seconds: int | None) -> str | None: - if not seconds: - return None - hours, rest = divmod(int(seconds), 3600) - minutes, secs = divmod(rest, 60) - if hours: - return f"{hours}h{minutes:02d}m" - return f"{minutes}m{secs:02d}s" if minutes else f"{secs}s" - - -def _worker_version(worker: dict) -> str | None: - stale = " (stale)" if worker.get("isStale") else "" - if worker.get("version") is None: - return stale.strip(" ()") or None - return f"v{worker['version']}{stale}" - - -_WORKER_COLUMNS = [ - ("WORKER", lambda w: w["id"]), - ("STATUS", lambda w: (w.get("status") or "").lower()), - ( - "GPU", - lambda w: ( - f"{w.get('gpuTypeId')} x{w['gpuCount']}" if w.get("gpuCount") else None - ), - ), - ("DATA CENTER", lambda w: w.get("dataCenterId")), - ("VERSION", _worker_version), - ("UPTIME", lambda w: _uptime(w.get("uptimeSeconds"))), -] - - -def _workers_view(data: dict): - from rich.console import Group - from rich.text import Text - - summary = data["summary"] - counts = ", ".join( - f"{summary[status]} {status}" - for status in ("running", "idle", "initializing", "throttled", "unhealthy") - ) - version = data.get("endpointVersion") - suffix = f", endpoint v{version}" if version is not None else "" - header = Text(f"{summary['total']} workers: {counts}{suffix}", style="dim") - return ( - Group(header, table(data["workers"], _WORKER_COLUMNS)) - if data["workers"] - else header - ) - - -@contextlib.contextmanager -def _data_plane_errors() -> Iterator[None]: - try: - yield - except requests.HTTPError as exc: - response = exc.response - if response is None: - raise click.ClickException(str(exc)) from exc - detail = response.text.strip() or response.reason or "" - raise click.ClickException(f"{response.status_code} {detail}".strip()) from exc - except (requests.RequestException, RuntimeError) as exc: - raise click.ClickException(str(exc)) from exc - - -def _job_path(endpoint_id: str, action: str, job_id: str | None = None) -> str: - parts = [quote(endpoint_id, safe=""), action] - if job_id: - parts.append(quote(job_id, safe="")) - return "/".join(parts) - - -def _print_job(job: dict, as_json: bool) -> None: - if as_json: - print_json(job) - elif job["status"] == "COMPLETED": - output = job.get("output") - click.echo(output if isinstance(output, str) else json.dumps(output, indent=2)) - if job["status"] != "COMPLETED": - detail = f": {job['error']}" if job.get("error") else "" - raise click.ClickException(f"job {job['id']} {job['status'].lower()}{detail}") +"""shared command-line helpers.""" +import sys -def _follow_job(client, endpoint_id, job_id, as_json, *, stream=False, timeout=None): - """wait for completion, draining streamed chunks before reading the final result.""" - action = "stream" if stream else "status" - resume = "stream" if stream else "wait" - deadline = time.monotonic() + timeout if timeout is not None else None - status = "pending" - - def remaining_time(limit): - if deadline is None or is_completed(status): - return limit - remaining = deadline - time.monotonic() - if remaining <= 0: - raise click.ClickException( - f"job {job_id} is still {status} after {timeout:g}s. " - f"resume with: rp endpoint job {resume} {endpoint_id} {job_id}" - ) - return min(limit, remaining) - - streamed = open_line = False - progress = ( - contextlib.nullcontext() - if stream - else ui.console.status(f"[dim]waiting for job {job_id} ...[/dim]") - ) - try: - with progress: - while True: - try: - if stream: - job = client.get( - _job_path(endpoint_id, action, job_id), - timeout=remaining_time(60), - ) - elif deadline is not None: - job = client.get( - _job_path(endpoint_id, action, job_id), - timeout=remaining_time(10), - ) - else: - job = client.get(_job_path(endpoint_id, action, job_id)) - except requests.Timeout as exc: - remaining_time(0) - if ( - stream - and isinstance(exc, requests.ReadTimeout) - and not is_completed(status) - ): - continue - raise - status = job["status"] - chunks = (job.get("stream") or []) if stream else [] - streamed = streamed or bool(chunks) - for chunk in chunks: - output = chunk["output"] - if isinstance(output, str) and not as_json: - click.echo(output, nl=False) - open_line = not output.endswith("\n") - else: - if open_line: - click.echo() - open_line = False - click.echo(json.dumps(output)) - if is_completed(job["status"]) and not chunks: - break - if not chunks: - time.sleep(remaining_time(0.5 if stream else 1)) - except KeyboardInterrupt: - click.echo( - f"\njob {job_id} keeps running. resume with: " - f"rp endpoint job {resume} {endpoint_id} {job_id}", - err=True, - ) - raise click.Abort() from None - if open_line: - click.echo() - if streamed and job["status"] == "COMPLETED": - return - if stream: - kwargs = {"timeout": remaining_time(10)} if deadline is not None else {} - job = client.get(_job_path(endpoint_id, "status", job_id), **kwargs) - _print_job(job, as_json) - - -def _request_body(input_file, data: str | None) -> Any | None: - if input_file and data: - raise click.UsageError("use either --input or --data") - text = input_file.read() if input_file else data - if text is None: - return None - try: - return json.loads(text) - except json.JSONDecodeError as exc: - raise click.UsageError(f"request body is not valid JSON: {exc}") from exc - - -def _call_load_balancer( - endpoint: dict, path: str, method, body, timeout, as_json -) -> None: - base = (endpoint.get("requestUrls") or {}).get("base") or ( - f"https://{endpoint['id']}.{endpoint_domain()}" - ) - method = (method or ("POST" if body is not None else "GET")).upper() - url = f"{base.rstrip('/')}/{path.lstrip('/')}" - response = requests.request( - method, - url, - headers={ - "Authorization": f"Bearer {api_key()}", - "Accept": "application/json", - }, - json=body, - timeout=timeout or 600, - ) - if response.status_code >= 400: - raise click.ClickException( - f"{method} {url} returned {response.status_code}: {response.text.strip()}" - ) - try: - payload = response.json() - except ValueError: - if as_json: - print_json(response.text) - else: - click.echo(response.text) - return - if isinstance(payload, str) and not as_json: - click.echo(payload) - return - print_json(payload) - - -@click.group() -def endpoint(): - """Create, inspect, scale, observe, and call serverless endpoints. - - \b - rp endpoint list --type queue - rp endpoint create --name llama --type queue --image IMAGE --gpu h100 - rp endpoint edit ENDPOINT_ID - rp endpoint logs ENDPOINT_ID --follow - rp endpoint run ENDPOINT_ID --data '{"prompt":"hello"}' - """ - - -@endpoint.command(name="list") -@click.option( - "--name", help="Only endpoints with this name (globs like 'llama*' work)." -) -@click.option( - "--type", - "endpoint_type", - type=click.Choice(list(TYPES), case_sensitive=False), - help="Only endpoints of this type.", -) -@json_option -def list_endpoints(name, endpoint_type, as_json): - """List endpoints with their IDs.""" - with api_errors(): - endpoints = list_all("/v2/serverless", "endpoints") - if name: - endpoints = [ - e - for e in endpoints - if fnmatch.fnmatch((e.get("name") or "").lower(), name.lower()) - ] - if endpoint_type: - endpoints = [ - e for e in endpoints if e.get("type") == TYPES[endpoint_type.lower()] - ] - if as_json: - print_json(endpoints) - return - print_table(endpoints, _LIST_COLUMNS, "no endpoints match") - - -@endpoint.command(name="get") -@endpoint_argument(required=False) -@json_option -def get_endpoint(endpoint_id, as_json): - """Show an endpoint's configuration (picker when ENDPOINT_ID is omitted).""" - endpoint_id = _pick_endpoint(endpoint_id) - with api_errors(): - record = run_rest_request("GET", _path(endpoint_id)) - if as_json: - print_json(record) - return - print_fields(record, _FIELDS) - - -@endpoint.command(name="create") -@_config_options(creating=True) -@json_option -def create_endpoint(as_json, **options): - """Create an endpoint. - - GPU types are human-readable and resolve against the serverless - catalog, and regions expand to their data centers. - - \b - rp endpoint create --name llama-prod --type queue \\ - --image ghcr.io/acme/llama:latest --gpu h100 --max-workers 4 \\ - --region eu --env MODEL_ID=meta-llama/Llama-3.1-8B --flashboot standard - rp endpoint create --name api --type load-balancer --image IMAGE \\ - --gpu 4090 --requests-per-worker 4 --env PORT=8000 - rp endpoint create --name embeddings --type queue --image IMAGE \\ - --cpu cpu3c --vcpu-count 8 - """ - if not options.get("image") and not options.get("template"): - raise click.UsageError("pass --image or --template") - with api_errors(): - body = config.config_body(options) - created = run_rest_request("POST", "/v2/serverless", json=body) - if as_json: - print_json(created) - return - ui.success( - f"created [white]{escape(created['name'])}[/white] [dim]{created['id']}[/dim]" - ) - print_fields(created, _FIELDS) - - -@endpoint.command(name="update") -@endpoint_argument() -@_config_options(creating=False) -@click.option( - "--wait", is_flag=True, help="Follow the rollout until the new release is live." -) -@click.option( - "--timeout", default=600.0, show_default=True, help="Seconds to follow the rollout." -) -@json_option -def update_endpoint(endpoint_id, wait, timeout, as_json, **options): - """Change an endpoint's configuration with flags. - - Only the given fields change. --env merges into the existing variables, - while --data-center replaces its list. --volume replaces mounts of each - supplied storage type and preserves mounts of the other type. - """ - with api_errors(): - current = run_rest_request("GET", _path(endpoint_id)) - patch = config.config_body(options, current) - if not patch: - raise click.UsageError( - "nothing to update. pass an option (see --help) or use rp endpoint edit" - ) - _apply(endpoint_id, patch, wait, timeout, as_json) - - -@endpoint.command(name="edit") -@endpoint_argument(required=False) -@click.option( - "--file", - "document", - type=click.File("r"), - help="Apply a JSON document (- for stdin) instead of opening $EDITOR.", -) -@click.option("--yes", "-y", is_flag=True, help="Apply without confirming.") -@click.option("--no-follow", is_flag=True, help="Return without following the rollout.") -@click.option( - "--timeout", default=600.0, show_default=True, help="Seconds to follow the rollout." -) -@json_option -def edit_endpoint(endpoint_id, document, yes, no_follow, timeout, as_json): - """Edit an endpoint's configuration in $EDITOR. - - Opens the mutable configuration as JSON, validates it, shows the - patch, and after confirmation applies it and follows any worker rollout. - runtime-only changes return without polling for a release. - Ctrl-C while following detaches without undoing anything. Fields - removed from the document stay unchanged. - """ - endpoint_id = _pick_endpoint(endpoint_id) - with api_errors(): - current = run_rest_request("GET", _path(endpoint_id)) - before = config.mutable(current) - if document: - after = config.validate(document.read(), before) - elif not interactive(): - raise click.UsageError( - "edit opens $EDITOR and needs an interactive terminal. " - "pass --file or use rp endpoint update" - ) - else: - after = _edit_document(before) - patch = config.patch(before, after) if after is not None else {} - if not patch: - if as_json: - print_json({}) - else: - ui.console.print("[dim]no changes[/dim]") - return - if not as_json: - ui.console.print("[dim]patch:[/dim]") - print_json(patch) - confirm(f"apply to endpoint {endpoint_id}?", yes) - _apply(endpoint_id, patch, not (no_follow or as_json), timeout, as_json) - - -@endpoint.command(name="scale") -@endpoint_argument() -@_scale_options -@json_option -def scale_endpoint(endpoint_id, as_json, **options): - """Change worker limits and the autoscaler.""" - with api_errors(): - current = run_rest_request("GET", _path(endpoint_id)) - patch = config.scale_patch(options, current) - if not patch: - raise click.UsageError("pass --min-workers, --max-workers, or a scaler option") - with api_errors(): - updated = run_rest_request("PATCH", _path(endpoint_id), json=patch) - if as_json: - print_json(updated) - return - ui.success(f"scaled [white]{escape(updated['name'])}[/white]") - print_fields( - updated, - [ - ("id", lambda e: e.get("id") or endpoint_id), - ("workers", _workers), - ( - "idle timeout", - lambda e: _seconds((e.get("workers") or {}).get("idleTimeout")), - ), - ("scaling", _scaling), - ], - ) - - -@endpoint.command(name="delete") -@endpoint_argument() -@click.option("--yes", "-y", is_flag=True, help="Skip the confirmation prompt.") -def delete_endpoint(endpoint_id, yes): - """Delete an endpoint and its workers.""" - with api_errors(): - name = run_rest_request("GET", _path(endpoint_id))["name"] - confirm(f"delete endpoint '{name}' ({endpoint_id})?", yes) - with api_errors(): - run_rest_request("DELETE", _path(endpoint_id)) - ui.success(f"deleted [white]{escape(name)}[/white] [dim]{endpoint_id}[/dim]") - - -@endpoint.command(name="workers") -@endpoint_argument() -@click.option("--watch", "-w", is_flag=True, help="Refresh in place until Ctrl-C.") -@click.option( - "--interval", - type=click.FloatRange(min=1), - default=2.0, - show_default=True, - help="Seconds between refreshes.", -) -@json_option -def list_workers(endpoint_id, watch, interval, as_json): - """Show an endpoint's workers. With --watch, --json prints one line per refresh.""" - try: - with api_errors(): - data = run_rest_request("GET", _path(endpoint_id, "workers")) - if not watch: - if as_json: - print_json(data) - else: - ui.console.print(_workers_view(data)) - return - if as_json: - while True: - click.echo(json.dumps(data, default=str)) - time.sleep(interval) - with api_errors(): - data = run_rest_request("GET", _path(endpoint_id, "workers")) - from rich.live import Live - - with Live(_workers_view(data), console=ui.console, auto_refresh=False) as live: - while True: - time.sleep(interval) - with api_errors(): - data = run_rest_request("GET", _path(endpoint_id, "workers")) - live.update(_workers_view(data), refresh=True) - except KeyboardInterrupt: - pass - - -def _release_changes(release: dict) -> list[str]: - return [ - entry["field"].removeprefix("template.") - for entry in release.get("diff") or [] - if entry.get("field") and (entry.get("old") or entry.get("new")) - ] - - -@endpoint.command(name="releases") -@endpoint_argument() -@json_option -def list_releases(endpoint_id, as_json): - """Show release history and rollout progress.""" - with api_errors(): - state = run_rest_request( - "GET", _path(endpoint_id, "releases"), params={"limit": 1} - ) - releases = list_all(_path(endpoint_id, "releases"), "releases") - if as_json: - print_json( - { - "endpointVersion": state.get("endpointVersion"), - "rollout": state.get("rollout"), - "releases": releases, - } - ) - return - if state.get("endpointVersion") is not None: - ui.console.print(f"[dim]{_rollout_line(state)}[/dim]") - print_table( - releases, - [ - ("RELEASE", lambda r: r["id"]), - ( - "VERSION", - lambda r: f"v{r['version']}" if r.get("version") is not None else None, - ), - ("SOURCE", lambda r: (r.get("source") or "").lower().replace("_", " ")), - ("BUILD", lambda r: r.get("buildId")), - ("WORKERS", lambda r: r.get("workerCount")), - ("CREATED", lambda r: (r.get("createdAt") or "")[:16].replace("T", " ")), - ("CHANGES", _release_changes), - ], - "no releases", - ) - - -@endpoint.command(name="logs") -@endpoint_argument() -@click.option( - "--worker", - "worker_ids", - multiple=True, - shell_complete=complete_worker, - help="Only this worker. Repeatable. Omit for every worker.", -) -@click.option( - "--follow", "-f", is_flag=True, help="Keep streaming and attach to new workers." -) -@click.option( - "--source", - type=click.Choice(["container", "system"]), - help="Log source. Omit for both.", -) -@click.option( - "--tail", - type=click.IntRange(0, 5000), - default=100, - show_default=True, - help="Lines of backfill per worker.", -) -@click.option("--since", help="RFC3339 timestamp to start from (overrides --tail).") -@json_option -def logs(endpoint_id, worker_ids, follow, source, tail, since, as_json): - """Show worker logs, each line prefixed with its worker id. - - Without --worker, every worker's logs are multiplexed, and with - --follow newly created workers are attached automatically. - """ - from runpod.rp_cli.logs import show_logs - - show_logs( - endpoint_id=endpoint_id, - worker_ids=worker_ids, - follow=follow, - source=source, - tail=tail, - since=since, - as_json=as_json, - ) - - -@endpoint.command(name="run") -@endpoint_argument() -@click.option( - "--input", - "input_file", - type=click.File("r"), - help="JSON request file, or - for stdin. A body without an 'input' key is wrapped in one.", -) -@click.option("--data", help="Inline JSON request.") -@click.option("--async", "run_async", is_flag=True, help="Submit and print the job id.") -@click.option("--stream", is_flag=True, help="Print streamed output as it arrives.") -@click.option("--webhook", help="URL notified when the job finishes.") -@click.option( - "--execution-timeout", - type=click.IntRange(min=1), - help="Job execution limit in seconds.", -) -@click.option("--ttl", type=click.IntRange(min=1), help="Job time to live in seconds.") -@click.option( - "--low-priority", is_flag=True, help="Do not scale up workers for this job." -) -@click.option( - "--timeout", - type=click.FloatRange(min=0, min_open=True), - help="Seconds to wait for the result.", -) -@click.option("--path", "lb_path", help="Load-balancer endpoints: request path.") -@click.option( - "--method", - help="Load-balancer endpoints: HTTP method (POST with a body, else GET).", -) -@json_option -@_data_plane_errors() -def run_endpoint( - endpoint_id, - input_file, - data, - run_async, - stream, - webhook, - execution_timeout, - ttl, - low_priority, - timeout, - lb_path, - method, - as_json, -): # pylint: disable=too-many-arguments - """Send a request to an endpoint. - - Queue endpoints run a job on the serverless data plane and print its - output. Load-balancer endpoints receive the body as an HTTP request - to --path on the endpoint URL. - - \b - rp endpoint run ENDPOINT_ID --input request.json - rp endpoint run ENDPOINT_ID --data '{"prompt":"hello"}' - rp endpoint run ENDPOINT_ID --input - --stream - rp endpoint run ENDPOINT_ID --input request.json --async - rp endpoint run LB_ENDPOINT_ID --path /v1/models - """ - if run_async and stream: - raise click.UsageError("use either --async or --stream") - body = _request_body(input_file, data) - with api_errors(): - record = run_rest_request("GET", _path(endpoint_id)) - - if record.get("type") == "LOAD_BALANCER": - if run_async or stream or webhook or execution_timeout or ttl or low_priority: - raise click.UsageError( - "load-balancer endpoints take --path, --method, and a body; " - "job options apply to queue endpoints" - ) - _call_load_balancer(record, lb_path or "/", method, body, timeout, as_json) - return - - if lb_path or method: - raise click.UsageError("--path and --method apply to load-balancer endpoints") - if body is None: - raise click.UsageError("pass --input FILE or --data JSON") - request = body if isinstance(body, dict) and "input" in body else {"input": body} - if webhook: - request["webhook"] = webhook - policy = dict(request.get("policy") or {}) - if execution_timeout: - policy["executionTimeout"] = execution_timeout * 1000 - if ttl: - policy["ttl"] = ttl * 1000 - if low_priority: - policy["lowPriority"] = True - if policy: - request["policy"] = policy - - client = runner.RunPodClient() - submitted = client.post(_job_path(endpoint_id, "run"), request) - job_id = submitted["id"] - if run_async: - if as_json: - print_json(submitted) - return - ui.success( - f"submitted job [white]{job_id}[/white] [dim]{submitted.get('status')}[/dim]" - ) - ui.console.print(f"[dim]rp endpoint job wait {endpoint_id} {job_id}[/dim]") - return - if stream: - if not as_json: - click.echo(f"job {job_id}", err=True) - _follow_job(client, endpoint_id, job_id, as_json, stream=True, timeout=timeout) - return - _follow_job(client, endpoint_id, job_id, as_json, timeout=timeout) - - -@endpoint.group(name="job") -def job(): - """Inspect and control queue jobs.""" - - -def _job_command(name: str): - def decorate(func): - func = json_option(func) - func = click.argument("job_id")(func) - func = endpoint_argument()(func) - return job.command(name=name)(func) - - return decorate - - -def _job_output(record: dict) -> str | None: - output = record.get("output") - if output is None or isinstance(output, str): - return output - return json.dumps(output) - - -_JOB_FIELDS = [ - ("id", lambda j: j.get("id")), - ("status", lambda j: (j.get("status") or "").lower()), - ("delay", lambda j: _seconds((j.get("delayTime") or 0) / 1000)), - ("execution", lambda j: _seconds((j.get("executionTime") or 0) / 1000)), - ("worker", lambda j: j.get("workerId")), - ("error", lambda j: j.get("error")), - ("output", _job_output), -] - - -@_job_command("get") -@_data_plane_errors() -def job_get(endpoint_id, job_id, as_json): - """Show a job's status and output.""" - record = runner.RunPodClient().get(_job_path(endpoint_id, "status", job_id)) - if as_json: - print_json(record) - return - print_fields(record, _JOB_FIELDS) - - -@_job_command("wait") -@click.option( - "--timeout", type=click.FloatRange(min=0, min_open=True), help="Seconds to wait." -) -@_data_plane_errors() -def job_wait(endpoint_id, job_id, timeout, as_json): - """Wait for a job to finish and print its output.""" - _follow_job(runner.RunPodClient(), endpoint_id, job_id, as_json, timeout=timeout) - - -@_job_command("stream") -@_data_plane_errors() -def job_stream(endpoint_id, job_id, as_json): - """Print a job's streamed output as it arrives.""" - _follow_job(runner.RunPodClient(), endpoint_id, job_id, as_json, stream=True) - - -@_job_command("cancel") -@_data_plane_errors() -def job_cancel(endpoint_id, job_id, as_json): - """Cancel a queued or running job.""" - record = runner.RunPodClient().post(_job_path(endpoint_id, "cancel", job_id), None) - if as_json: - print_json(record) - return - ui.success(f"job [white]{job_id}[/white] [dim]{record.get('status')}[/dim]") - - -@_job_command("retry") -@_data_plane_errors() -def job_retry(endpoint_id, job_id, as_json): - """Requeue a failed or timed-out job.""" - record = runner.RunPodClient().post(_job_path(endpoint_id, "retry", job_id), None) - if as_json: - print_json(record) - return - ui.success( - f"job [white]{record.get('id') or job_id}[/white] [dim]{record.get('status')}[/dim]" - ) - +from runpod.cli import endpoint -@endpoint.command(name="purge") -@endpoint_argument() -@click.option("--yes", "-y", is_flag=True, help="Skip the confirmation prompt.") -@json_option -@_data_plane_errors() -def purge_queue(endpoint_id, yes, as_json): - """Remove every queued job. Running jobs are not affected.""" - confirm(f"remove every queued job from {endpoint_id}?", yes) - record = runner.RunPodClient().post(_job_path(endpoint_id, "purge-queue"), None) - if as_json: - print_json(record) - return - ui.success( - f"purged {record.get('removed', 0)} queued jobs from [white]{endpoint_id}[/white]" - ) +sys.modules[__name__] = endpoint diff --git a/runpod/rp_cli/endpoint_config.py b/runpod/rp_cli/endpoint_config.py index 89ddce146..f2487c70c 100644 --- a/runpod/rp_cli/endpoint_config.py +++ b/runpod/rp_cli/endpoint_config.py @@ -1,300 +1,7 @@ -import json -from typing import Any +"""shared command-line helpers.""" -import click +import sys -from runpod.rp_cli import compute -from runpod.rp_cli.options import container_fields -from runpod.rp_cli.volume import _get_volume +from runpod.cli import endpoint_config -FLASHBOOT = {"off": "OFF", "standard": "FLASHBOOT", "priority": "PRIORITY_FLASHBOOT"} - - -MUTABLE_FIELDS = { - "name": (str,), - "image": (str,), - "args": (str,), - "env": (dict,), - "disk": (int,), - "ports": (list,), - "registry": (str, type(None)), - "gpu": (dict,), - "cpu": (list,), - "workers": (dict,), - "scaling": (dict,), - "timeout": (int,), - "flashboot": (str,), - "dataCenterIds": (list,), - "mounts": (dict,), -} - - -NESTED_FIELDS = { - "gpu": {"pools", "excludedTypes", "count", "allowedCudaVersions", "minCudaVersion"}, - "workers": {"min", "max", "idleTimeout"}, - "scaling": {"type", "queueDelay", "requestCount"}, - "mounts": {"network", "global"}, -} - - -def _gpu(specs, count, cuda, updating: bool) -> dict: - gpu: dict[str, Any] = {} - if specs: - catalog = [ - entry - for entry in compute.list_gpus(product="SERVERLESS") - if entry.get("pool") - ] - matches: list[dict] = [] - counts = {count} if count else set() - for spec in specs: - name, spec_count = compute.parse_gpu_spec(spec) - if spec_count: - counts.add(spec_count) - for match in compute.resolve_gpus(name, catalog): - if match not in matches: - matches.append(match) - if len(counts) > 1: - raise click.UsageError("conflicting gpu counts; use one count per worker") - pools, excluded = compute.endpoint_gpu_selection(matches, catalog) - gpu["pools"] = pools - if excluded or updating: - gpu["excludedTypes"] = excluded - count = counts.pop() if counts else None - if count: - gpu["count"] = count - if cuda: - if [value.lower() for value in cuda] == ["any"]: - gpu["allowedCudaVersions"] = [] - if updating: - gpu["minCudaVersion"] = "" - return gpu - minimum, exact = compute.parse_cuda(cuda) - if minimum: - gpu["minCudaVersion"] = minimum - if updating: - gpu["allowedCudaVersions"] = [] - else: - gpu["allowedCudaVersions"] = exact - if updating: - gpu["minCudaVersion"] = "" - return gpu - - -def _cpu(specs, vcpu_count, current: dict | None) -> list | None: - if not specs: - if vcpu_count and current and current.get("cpu"): - return [ - {"id": cpu["id"], "vcpuCount": vcpu_count} for cpu in current["cpu"] - ] - if vcpu_count: - raise click.UsageError("--vcpu-count applies to CPU endpoints (pass --cpu)") - return None - flavors = compute.list_cpus(product="SERVERLESS") - entries = [] - for spec in specs: - name, sep, count = spec.rpartition(":") - if not sep: - name, count = spec, "" - if count and not count.isdigit(): - raise click.UsageError( - f"invalid --cpu '{spec}'. use a flavor like cpu3c or cpu3c:8" - ) - vcpus = int(count) if count else vcpu_count - if not vcpus: - raise click.UsageError(f"pass --vcpu-count or --cpu {name}:VCPUS") - entries.append( - {"id": compute.resolve_cpu(name, flavors)["id"], "vcpuCount": vcpus} - ) - return entries - - -def scale_patch(options: dict, current: dict) -> dict: - patch = {} - changes = { - key: options[flag] - for key, flag in ( - ("min", "min_workers"), - ("max", "max_workers"), - ("idleTimeout", "idle_timeout_seconds"), - ) - if options.get(flag) is not None - } - if changes: - patch["workers"] = {**(current.get("workers") or {}), **changes} - delay = options.get("queue_delay_seconds") - count = options.get("requests_per_worker") - if delay is not None and count is not None: - raise click.UsageError( - "use either --queue-delay-seconds or --requests-per-worker" - ) - if delay is not None: - if current.get("type") == "LOAD_BALANCER": - raise click.UsageError( - "load-balancer endpoints scale on --requests-per-worker" - ) - patch["scaling"] = {"type": "QUEUE_DELAY", "queueDelay": delay} - elif count is not None: - patch["scaling"] = {"type": "REQUEST_COUNT", "requestCount": count} - return patch - - -def config_body(options: dict, current: dict | None = None) -> dict: - updating = current is not None - current = current if updating else {"type": options["endpoint_type"]} - body = container_fields( - {**options, "ports": options.get("port")}, - current, - options.get("unset_env", ()), - ) - if not updating: - body["type"] = current["type"] - if options.get("name") is not None: - body["name"] = options["name"] - if options.get("flashboot"): - body["flashboot"] = FLASHBOOT[options["flashboot"].lower()] - if options.get("request_timeout_seconds") is not None: - body["timeout"] = options["request_timeout_seconds"] * 1000 - - if options.get("gpu") and options.get("cpu"): - raise click.UsageError("use either --gpu or --cpu") - if current.get("cpu") and options.get("gpu"): - raise click.UsageError("a CPU endpoint cannot switch to GPUs") - if current.get("gpu") and options.get("cpu"): - raise click.UsageError("a GPU endpoint cannot switch to CPUs") - if (options.get("cpu") or current.get("cpu")) and ( - options.get("cuda") or options.get("gpu_count") - ): - raise click.UsageError("--cuda and --gpu-count apply to GPU endpoints") - gpu = _gpu( - options.get("gpu"), options.get("gpu_count"), options.get("cuda"), updating - ) - if gpu: - body["gpu"] = gpu - cpu = _cpu(options.get("cpu"), options.get("vcpu_count"), current) - if cpu: - body["cpu"] = cpu - - body.update(scale_patch(options, current)) - if not updating and "scaling" not in body: - if current["type"] == "LOAD_BALANCER": - raise click.UsageError("load-balancer endpoints need --requests-per-worker") - body["scaling"] = {"type": "QUEUE_DELAY", "queueDelay": 4} - places = (*options.get("data_center", ()), *options.get("region", ())) - if places: - body["dataCenterIds"] = compute.resolve_regions( - places, compute.list_datacenters() - ) - if options.get("volume"): - mounts = dict(current.get("mounts") or {}) - resolved = {} - for volume_id in options["volume"]: - kind, _ = _get_volume(volume_id) - if any(mount["volumeId"] == volume_id for mount in resolved.get(kind, [])): - raise click.BadParameter( - f"volume {volume_id!r} is specified more than once", - param_hint="--volume", - ) - resolved.setdefault(kind, []).append({"volumeId": volume_id}) - mounts.update(resolved) - body["mounts"] = mounts - return body - - -def mutable(endpoint: dict) -> dict: - doc: dict[str, Any] = {} - for key in ("name", "image", "args", "env", "disk", "ports"): - if endpoint.get(key) is not None: - doc[key] = endpoint[key] - doc["registry"] = endpoint.get("registry") - gpu = endpoint.get("gpu") - if gpu: - doc["gpu"] = { - "pools": gpu.get("pools") or [], - "excludedTypes": gpu.get("excludedTypes") or [], - "count": gpu.get("count") or 1, - "allowedCudaVersions": gpu.get("allowedCudaVersions") or [], - "minCudaVersion": gpu.get("minCudaVersion"), - } - if endpoint.get("cpu"): - doc["cpu"] = [ - {"id": cpu["id"], "vcpuCount": cpu["vcpuCount"]} for cpu in endpoint["cpu"] - ] - for key in ("workers", "scaling", "timeout", "flashboot", "dataCenterIds"): - if endpoint.get(key) is not None: - doc[key] = endpoint[key] - mounts = endpoint.get("mounts") or {} - doc["mounts"] = { - kind: [{"volumeId": m["volumeId"]} for m in mounts.get(kind) or []] - for kind in ("network", "global") - } - return doc - - -def _kind(kind: type) -> str: - return { - str: "a string", - int: "an integer", - dict: "an object", - list: "a list", - type(None): "null", - }[kind] - - -def validate(text: str, before: dict) -> dict: - try: - doc = json.loads(text) - except json.JSONDecodeError as exc: - raise click.ClickException(f"invalid JSON: {exc}") from exc - if not isinstance(doc, dict): - raise click.ClickException("the document must be a JSON object") - problems = [] - for key, value in doc.items(): - kinds = MUTABLE_FIELDS.get(key) - if kinds is None: - problems.append(f"unknown field '{key}'") - continue - if isinstance(value, bool) or not isinstance(value, kinds): - problems.append(f"'{key}' must be {' or '.join(_kind(k) for k in kinds)}") - continue - allowed = NESTED_FIELDS.get(key) - if allowed: - problems.extend( - f"unknown field '{key}.{nested}'" - for nested in value - if nested not in allowed - ) - env = doc.get("env") - if isinstance(env, dict) and not all(isinstance(v, str) for v in env.values()): - problems.append("env values must be strings") - flashboot = doc.get("flashboot") - if isinstance(flashboot, str) and flashboot not in FLASHBOOT.values(): - problems.append(f"'flashboot' must be one of {', '.join(FLASHBOOT.values())}") - if "gpu" in doc and "gpu" not in before: - problems.append("a CPU endpoint cannot switch to GPUs") - if "cpu" in doc and "cpu" not in before: - problems.append("a GPU endpoint cannot switch to CPUs") - if problems: - raise click.ClickException("; ".join(problems)) - return doc - - -def patch(before: dict, after: dict) -> dict: - patch = {} - for key, value in after.items(): - if before.get(key) == value: - continue - if key != "gpu": - patch[key] = value - continue - old = before.get("gpu") or {} - gpu = {k: v for k, v in value.items() if old.get(k) != v} - if "pools" in gpu or "excludedTypes" in gpu: - gpu["pools"] = value.get("pools", old.get("pools")) - gpu["excludedTypes"] = ( - value.get("excludedTypes", old.get("excludedTypes")) or [] - ) - if "minCudaVersion" in gpu and gpu["minCudaVersion"] is None: - gpu["minCudaVersion"] = "" - patch["gpu"] = gpu - return patch +sys.modules[__name__] = endpoint_config diff --git a/runpod/rp_cli/logs.py b/runpod/rp_cli/logs.py index e9a5720ea..7258f39bf 100644 --- a/runpod/rp_cli/logs.py +++ b/runpod/rp_cli/logs.py @@ -1,158 +1,7 @@ -"""shared pod and serverless log views backed by the sdk stream reader.""" +"""shared command-line helpers.""" -import asyncio -import json -from datetime import UTC, datetime +import sys -import aiohttp -import click +from runpod.cli import logs -from runpod.api.ctl_commands import _path_segment -from runpod.api.rest import run_rest_request -from runpod.apps.errors import AppHTTPError -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(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 (AppHTTPError, aiohttp.ClientResponseError) as exc: - if endpoint_id and exc.status == 404: - return - if not follow or not (exc.status == 429 or 500 <= exc.status < 600): - raise - except (TimeoutError, aiohttp.ClientConnectionError): - 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 (TimeoutError, AppHTTPError, aiohttp.ClientError) as exc: - raise click.ClickException(str(exc)) from exc +sys.modules[__name__] = logs diff --git a/runpod/rp_cli/main.py b/runpod/rp_cli/main.py index 4729d799a..e5562ec60 100644 --- a/runpod/rp_cli/main.py +++ b/runpod/rp_cli/main.py @@ -1,1252 +1,10 @@ -"""the `rp` / `runpod` cli. +"""shared command-line helpers.""" -flash app commands share one namespace while account, registry, secret, -logs, pod, and ssh commands remain on the root. help, errors, and exit -codes behave identically at every level. rich is used only for runtime -output, never for help rendering. -""" - -import asyncio -import os -import shlex -import signal import sys -from pathlib import Path - -import click - -# commands whose output would be polluted by (or that manage) the -# update notice -_UPDATE_CHECK_EXCLUDED = frozenset({"completion", "flash", "update"}) -_FLASH_UPDATE_CHECK_EXCLUDED = frozenset({"dev"}) - - -def _default_profile() -> str: - from runpod import _selected_profile - - return _selected_profile() - - -@click.group() -@click.pass_context -def cli(ctx): - """Runpod CLI: manage Flash apps, endpoints, and pods. - - Using an AI agent? Point it to https://docs.runpod.io/agent-setup.md - """ - if ctx.invoked_subcommand not in _UPDATE_CHECK_EXCLUDED: - from runpod.rp_cli.update import start_background_check - - start_background_check() - - -@cli.group() -@click.pass_context -def flash(ctx): - """Build, develop, and manage Flash apps.""" - if ctx.invoked_subcommand not in _FLASH_UPDATE_CHECK_EXCLUDED: - from runpod.rp_cli.update import start_background_check - - start_background_check() - - -def _fail(message: str) -> None: - raise click.ClickException(message) - - -def _stdin_is_tty() -> bool: - return sys.stdin.isatty() - - -def _app_source(found, project_root: Path) -> str: - """the file an app was discovered in, relative to the project.""" - source = getattr(found, "_source_file", None) - if source is None: - return "" - try: - return str(Path(source).resolve().relative_to(project_root)) - except ValueError: - return str(source) - - -# ------------------------------------------------------------------ init - - -@flash.command() -@click.argument("project_name", required=False) -@click.option("--force", "-f", is_flag=True, help="Overwrite existing files.") -def init(project_name, force): - """Create a new app project (PROJECT_NAME, or '.' for the cwd).""" - from runpod.apps.init import create_project, detect_conflicts - from runpod.rp_cli import console as ui - - if project_name is None or project_name == ".": - project_dir = Path.cwd() - name = project_dir.name - else: - project_dir = Path(project_name) - name = project_name - - conflicts = detect_conflicts(project_dir) - if conflicts and not force: - listing = ", ".join(conflicts) - _fail( - f"{listing} already exist{'s' if len(conflicts) == 1 else ''} " - f"in {project_dir}. pass --force to overwrite." - ) - - written = create_project(project_dir, name, overwrite=force) - ui.success( - f"initialized [white]{name}[/white] " - f"[dim]{len(written)} files[/dim]" - ) - ui.console.print() - if project_dir != Path.cwd(): - ui.console.print(f" [dim]cd {project_name}[/dim]") - ui.console.print(" [dim]rp login[/dim]") - ui.console.print(" [dim]rp flash dev main.py[/dim]") - ui.console.print() - - -# ---------------------------------------------------------------- update - - -@cli.command() -@click.option( - "--version", "-V", "version_opt", default=None, help="Target version." -) -def update(version_opt): - """Update the runpod package to the latest (or a given) version.""" - from runpod.rp_cli import console as ui - from runpod.rp_cli.update import ( - compare_versions, - current_version, - fetch_pypi_metadata, - parse_version, - run_install, - ) - - current = current_version() - ui.console.print(f"current version: [white]{current}[/white]") - - with ui.console.status("[dim]checking pypi ...[/dim]"): - try: - latest, releases = fetch_pypi_metadata() - except (ConnectionError, RuntimeError) as exc: - _fail(str(exc)) - - target = version_opt or latest - if target not in releases: - _fail(f"version '{target}' not found on pypi") - if current == target: - ui.console.print(f"already on [white]{target}[/white], nothing to do") - return - if ( - current != "unknown" - and compare_versions(parse_version(target), parse_version(current)) < 0 - ): - ui.warn(f"downgrading from {current} to {target}") - - with ui.console.status(f"[dim]installing runpod {target} ...[/dim]"): - try: - run_install(target) - except Exception as exc: # noqa: BLE001 - surface installer errors cleanly - _fail(str(exc)) - ui.success(f"updated to [white]{target}[/white]") - - -# ---------------------------------------------------------------- deploy - - -@flash.command() -@click.argument("target", required=False, type=click.Path(path_type=Path)) -@click.option("--env", "-e", "env", default=None, help="Target environment name.") -@click.option( - "--python-version", - default=None, - help="Worker python version for dependency wheels (3.11-3.14). " - "Defaults to the python running the cli.", -) -@click.option( - "--exclude", - default=None, - help="Comma-separated packages to exclude from the artifact " - "(they must then come from the worker image). Torch packages are " - "excluded automatically on builtin gpu images.", -) -@click.option( - "--build-only", - is_flag=True, - help="Build the artifact without deploying; writes " - "-artifact.tar.gz to the current directory.", -) -def deploy(target, env, python_version, exclude, build_only): - """Package and deploy all apps found in TARGET (default: cwd).""" - import logging - - from runpod.apps.deploy import build_artifact, deploy_app - from runpod.apps.discovery import discover_apps, resolve_project - from runpod.rp_cli import console as ui - - logging.getLogger("runpod.apps").setLevel(logging.WARNING) - - if python_version is None: - from runpod.apps.images import ( - DEFAULT_PYTHON_VERSION, - local_python_version, - ) - - try: - python_version = local_python_version() - except RuntimeError: - # deployed calls are plain json (no pickle compat needed), - # so an unsupported local interpreter falls back instead of - # failing like dev does - ui.warn( - f"local python has no runtime image; building for " - f"{DEFAULT_PYTHON_VERSION} (override with --python-version)" - ) - python_version = DEFAULT_PYTHON_VERSION - - target = (target or Path.cwd()).resolve() - if not target.exists(): - _fail(f"{target} does not exist") - - try: - project = resolve_project(target) - apps = discover_apps(project.target, strict=True) - except Exception as exc: - _fail(str(exc)) - - project_root = project.source_root - - if build_only: - for found in apps: - ui.set_name_width(list(found.resources)) - events = ui.DeployEvents() - succeeded = False - try: - artifact = build_artifact( - found, - project_root, - python_version=python_version, - exclude=exclude.split(",") if exclude else None, - events=events, - output=Path.cwd() / f"{found.name}-artifact.tar.gz", - ) - succeeded = True - except Exception as exc: # noqa: BLE001 - surface engine errors cleanly - raise click.ClickException(str(exc)) from exc - finally: - events.close(failed=not succeeded) - size_mb = artifact.stat().st_size / (1024 * 1024) - ui.success( - f"built [white]{found.name}[/white] " - f"[dim]{artifact.name} ({size_mb:.1f} MB)[/dim]" - ) - return - - if len(apps) > 1: - ui.deploy_plan( - [ - ( - found.name, - _app_source(found, project_root), - len(found.resources), - ) - for found in apps - ] - ) - - for index, found in enumerate(apps): - if index or len(apps) > 1: - ui.console.print() - ui.set_name_width(list(found.resources)) - ui.deploy_banner( - found.name, - env or found.env, - [(h.spec.name, h.spec.kind.value) for h in found.resources.values()], - source=_app_source(found, project_root), - ) - events = ui.DeployEvents() - succeeded = False - with ui.Timer() as t: - try: - result = asyncio.run( - deploy_app( - found, - project_root, - env_name=env, - python_version=python_version, - exclude=exclude.split(",") if exclude else None, - events=events, - ) - ) - succeeded = True - except Exception as exc: # noqa: BLE001 - surface engine errors cleanly - raise click.ClickException(str(exc)) from exc - finally: - events.close(failed=not succeeded) - ui.success( - f"[bold white]{result.app_name}/{env or found.env}[/bold white] " - f"is live [dim]{t.elapsed:.1f}s[/dim]" - ) - if result.resources: - ui.console.print() - ui.resources_table( - ( - name, - handle.spec.kind.value, - ",".join(handle.spec.cpu or handle.spec.gpu or ["any"]), - result.endpoints.get(name, "registered"), - ) - for name, handle in sorted(found.resources.items()) - ) - ui.console.print() - - -# ------------------------------------------------------------------- dev - - -@flash.command() -@click.argument("target", default=".", type=click.Path(exists=True, path_type=Path)) -@click.option( - "--entrypoint", - "entrypoint_selector", - default=None, - help="Select a registered entry hook as module:function.", -) -@click.option( - "--once", - is_flag=True, - help="Provision, run an optional entry hook, tear down, and exit.", -) -def dev(target, once, entrypoint_selector): - """Start an interactive dev session for TARGET (default: cwd). - - Provisions temporary live endpoints, runs an optional - @runpod.local_entrypoint, watches the project for file changes, - and deletes the endpoints on exit. - """ - import logging - - from runpod.apps.dev import DevSession - from runpod.apps.discovery import discover_apps, resolve_project - from runpod.apps.entrypoint import ( - _clear_entrypoints, - _restore_entrypoints, - get_entrypoints, - run_entrypoint, - select_entrypoint, - ) - from runpod.apps.utils.names import dev_endpoint_name - from runpod.apps.watch import FileWatcher - from runpod.error import AuthenticationError, auth_hint - from runpod.rp_cli import console as ui - - logging.getLogger("runpod.apps").setLevel(logging.WARNING) - - try: - project = resolve_project(target) - except Exception as exc: - _fail(str(exc)) - - os.environ["RUNPOD_DEV_SESSION"] = "1" - - def _scan(): - previous_entrypoints = get_entrypoints() - _clear_entrypoints() - try: - apps = discover_apps(project.target, strict=True) - entrypoint = select_entrypoint(entrypoint_selector) - except BaseException: - _restore_entrypoints(previous_entrypoints) - raise - return apps, entrypoint - - try: - apps, entrypoint = _scan() - except Exception as exc: - _fail(str(exc)) - - def _all_resource_names(app_list) -> list: - return [ - handle.spec.name - for a in app_list - for handle in a.resources.values() - ] - - def _table_rows(session: "DevSession") -> list: - rows = [] - for a in session.apps: - for handle in a.resources.values(): - spec = handle.spec - hardware = ",".join(spec.cpu or spec.gpu or ["any"]) - endpoint_id = session._endpoints.get( - dev_endpoint_name(a.name, spec.name), "" - ) or ("per-call" if spec.kind.value == "task" else "") - rows.append((spec.name, spec.kind.value, hardware, endpoint_id)) - return rows - - # daemon stdin reader: a blocked readline must never keep the - # process alive after ctrl-c (executor threads are joined at - # loop shutdown; a daemon thread is not) - import queue as _queue - import threading - - stdin_lines: _queue.Queue[str] = _queue.Queue() - - def _stdin_reader() -> None: - for line in sys.stdin: - stdin_lines.put(line) - stdin_lines.put("") # eof marker - - threading.Thread(target=_stdin_reader, daemon=True).start() - - async def _wait_for_rerun(watcher: "FileWatcher") -> str: - """race the enter key against a file change.""" - eof = False - while True: - if watcher.changed(): - return "changed" - if not eof: - try: - line = stdin_lines.get_nowait() - if line == "": - # piped stdin / ci: no interactive re-runs, - # keep watching files only - eof = True - else: - return "enter" - except _queue.Empty: - # no keypress this tick; fall through to the sleep - pass - await asyncio.sleep(0.5) - - # set by a second stop signal: teardown stops waiting for a running - # entrypoint - force_stop = asyncio.Event() - # once teardown starts, signals leave it to finish - tearing_down = False - - async def _run_entrypoint_cancellable(fn) -> None: - """run user code without blocking the event loop. - - cancellation waits for the entrypoint to finish so its remote - calls cannot race with session teardown, unless a second stop - signal forces teardown first. - """ - loop = asyncio.get_running_loop() - done: asyncio.Future[None] = loop.create_future() - - def _finish(exc: "BaseException | None") -> None: - if done.done(): - return - if exc is None: - done.set_result(None) - else: - done.set_exception(exc) - - def _report(exc: "BaseException | None") -> None: - try: - loop.call_soon_threadsafe(_finish, exc) - except RuntimeError: - # a forced stop closed the loop while this entrypoint ran - pass - - def _runner() -> None: - try: - run_entrypoint(fn) - # entrypoint control-flow exceptions must reach the loop, - # not die on this thread - except (Exception, KeyboardInterrupt, SystemExit) as exc: - # bind the exception now: `as exc` is unbound once the - # except block exits, before the loop callback runs - _report(exc) - else: - _report(None) - - # daemon: a forced stop must not leave process exit waiting on - # a long remote call - threading.Thread(target=_runner, daemon=True).start() - try: - return await asyncio.shield(done) - except asyncio.CancelledError: - await _settle_after_stop(done) - raise - - async def _settle_after_stop(done: "asyncio.Future[None]") -> None: - """after a stop, wait for the still-running entrypoint so its remote - calls cannot race teardown, unless a second signal forces the stop.""" - if done.done(): - _discard_result(done) - return - forced = asyncio.ensure_future(force_stop.wait()) - await asyncio.wait({done, forced}, return_when=asyncio.FIRST_COMPLETED) - forced.cancel() - done.add_done_callback(_discard_result) - - def _install_stop_signals() -> None: - """stop cleanly on sigint and sigterm. - - python only turns sigint into KeyboardInterrupt when it was not - ignored at startup, and shells start background jobs with sigint - ignored; sigterm has no handler at all. without these a stopped - session would leave its endpoints running. the first signal - cancels the session (teardown deletes the endpoints), the second - stops waiting for a running entrypoint. signals during teardown - are ignored so every endpoint still gets deleted. - """ - loop = asyncio.get_running_loop() - task = asyncio.current_task() - stopping = False - - def _on_signal() -> None: - nonlocal stopping - if tearing_down: - # cancelling teardown would skip the remaining deletes - return - if stopping: - force_stop.set() - else: - stopping = True - task.cancel() - - for sig in (signal.SIGINT, signal.SIGTERM): - try: - loop.add_signal_handler(sig, _on_signal) - except (NotImplementedError, RuntimeError, ValueError): - # windows event loops have no signal handlers; ctrl-c - # still raises KeyboardInterrupt there - pass - - async def _session() -> int: - nonlocal apps, entrypoint, tearing_down - ui.set_name_width(_all_resource_names(apps)) - session = DevSession(apps, events=ui.DevEvents()) - watcher = FileWatcher([project.source_root]) - - ui.dev_banner([a.name for a in apps], str(project.target.name)) - _install_stop_signals() - try: - await session.start() - ui.resources_table(_table_rows(session)) - while True: - if entrypoint is not None: - ui.entrypoint_header(getattr(entrypoint, "__name__", "")) - with ui.Timer() as t: - try: - await _run_entrypoint_cancellable(entrypoint) - ui.entrypoint_success(t.so_far) - except asyncio.CancelledError: - raise - except Exception as exc: - ui.entrypoint_failure(t.so_far, str(exc)) - if once: - return 1 - if once: - return 0 - reload_failed = False - while True: - reason = await _wait_for_rerun(watcher) - if reason == "changed": - ui.reload_banner(str(project.target.name)) - try: - apps, entrypoint = _scan() - except Exception as exc: - ui.error(f"reload failed: {exc}; keeping current endpoints") - reload_failed = True - continue - ui.set_name_width(_all_resource_names(apps)) - await session.refresh(apps) - reload_failed = False - if not reload_failed: - break - finally: - tearing_down = True - events = ui.CleanupEvents() - try: - await session.stop(events=events) - finally: - events.close() - - try: - sys.exit(asyncio.run(_session())) - except (KeyboardInterrupt, EOFError, asyncio.CancelledError): - ui.console.print() - except AuthenticationError as exc: - raise click.ClickException(auth_hint()) from exc - except Exception as exc: # noqa: BLE001 - surface engine errors cleanly - raise click.ClickException(str(exc)) from exc - - -@cli.command() -@click.argument("shell", type=click.Choice(["bash", "zsh", "fish"])) -def completion(shell): - """Print the shell completion script for SHELL. - - Completes commands, flags, and resource IDs. Add this to your shell - profile: eval "$(rp completion zsh)" - """ - from click.shell_completion import get_completion_class - - complete = get_completion_class(shell)(cli, {}, "rp", "_RP_COMPLETE") - click.echo(complete.source()) - - -def _discard_result(future: "asyncio.Future[None]") -> None: - """mark an abandoned entrypoint's error as retrieved, so asyncio does - not log it as never retrieved.""" - if not future.cancelled(): - future.exception() - - -# ------------------------------------------------------------------ logs - - -@cli.command() -@click.argument("pod_id") -@click.option("--follow", "-f", is_flag=True, help="Stream logs as they arrive.") -@click.option( - "--type", - "log_type", - default="all", - show_default=True, - type=click.Choice(["all", "container", "system"]), - help="Log source.", -) -@click.option("--tail", default=100, show_default=True, help="Lines of backfill.") -def logs(pod_id, follow, log_type, tail): - """Show a pod's container and system logs.""" - from runpod.apps.logs import pod_logs, stream_pod_logs - - async def _run(): - if follow: - async for entry in stream_pod_logs( - pod_id, log_type=log_type, tail=tail - ): - source = entry.get("source", "?") - click.echo(f"[{source}] {entry.get('line', '')}") - else: - logs_data = await pod_logs(pod_id, log_type=log_type) - for source in ("system", "container"): - for line in logs_data.get(source) or []: - click.echo(f"[{source}] {line}") - - try: - asyncio.run(_run()) - except KeyboardInterrupt: - # ctrl-c ends the log follow; not an error - pass - - -# ----------------------------------------------------------------- login - - -@cli.command() -@click.option( - "--no-open", is_flag=True, help="Print the url instead of opening a browser." -) -@click.option( - "--api-key", - "api_key_opt", - default=None, - help="Store this API key directly (skips the browser flow).", -) -@click.option( - "--profile", - default=_default_profile, - show_default="RUNPOD_PROFILE, else default", - help="Credential profile.", -) -@click.option( - "--agent", - is_flag=True, - help="Sign in without prompting: use --email to request a code, then --code to complete login.", -) -@click.option("--email", default=None, help="Email address for --agent sign-in.") -@click.option( - "--code", - default=None, - help="Complete a pending --agent login with a six-digit code without prompting.", -) -def login(no_open, api_key_opt, profile, agent, email, code): - """Authenticate with Runpod and store the API key. - - Opens the Runpod console for browser approval by default, then asks - you to paste the API key the console shows. Pass --api-key to store a - key directly. Run --agent --email ADDRESS to email a verification code - and exit, then --agent --code CODE to complete login without prompting. - Use the same --profile for both commands. Pending - login state is stored in ~/.runpod with owner-only permissions and - deleted after credentials are saved. Treat the code as a secret. - Command arguments can appear in shell history and process listings. - """ - from runpod.apps.auth import ( - LoginError, - browser_login, - load_agent_login, - pending_agent_login_path, - save_agent_login, - start_agent_login, - verify_agent_login, - ) - from runpod.cli.groups.config.functions import set_credentials - from runpod.rp_cli import console as ui - - if agent and api_key_opt is not None: - raise click.UsageError("--agent cannot be combined with --api-key") - if code is not None and not agent: - raise click.UsageError("--code requires --agent") - if code is not None and email is not None: - raise click.UsageError( - "--code uses the pending login. Do not combine it with --email" - ) - if code is not None: - code = code.strip() - if len(code) != 6 or not code.isascii() or not code.isdigit(): - raise click.UsageError("--code must contain six ASCII digits") - if agent and code is None and (email is None or not email.strip()): - raise click.UsageError("--agent requires --email") - if email is not None and not agent: - raise click.UsageError("--email requires --agent") - - if api_key_opt: - try: - set_credentials(api_key_opt, profile=profile, overwrite=True) - except ValueError as exc: - _fail(str(exc)) - ui.success("credentials saved to [dim]~/.runpod/config.toml[/dim]") - return - - if not agent and not _stdin_is_tty(): - _fail( - "rp login needs an interactive terminal to paste the API key. " - "Set RUNPOD_API_KEY, run rp login --api-key YOUR_KEY, or add the " - "key to ~/.runpod/config.toml." - ) - - def _show_url(url: str) -> None: - ui.console.print() - ui.console.print(" [white]authorize in your browser:[/white]") - ui.console.print(f" [accent.light][link={url}]{url}[/link][/accent.light]") - ui.console.print( - " [dim]after approving, copy the API key the console shows[/dim]" - ) - ui.console.print() - if not no_open: - click.launch(url) - - def _prompt_key() -> str: - return click.prompt( - "paste API key", hide_input=True, default="", show_default=False - ) - - def _rejected(reason: str) -> None: - ui.console.print(f" [dim]{reason}, try again[/dim]") - - try: - if agent and code is None: - attempt = asyncio.run(start_agent_login(email.strip())) - save_agent_login(attempt, profile) - command = ["runpod", "login", "--agent", "--code", "CODE"] - if profile != "default": - command.extend(["--profile", profile]) - click.echo("A verification code was sent to your email.") - click.echo("Check your inbox, then run:") - click.echo(f"\n {shlex.join(command)}\n") - click.echo("Replace CODE with the six-digit code from your email.") - return - if code is not None: - api_key = asyncio.run(verify_agent_login(load_agent_login(profile), code)) - else: - api_key = asyncio.run( - browser_login( - prompt_key=_prompt_key, on_url=_show_url, on_rejected=_rejected - ) - ) - set_credentials(api_key, profile=profile, overwrite=True) - if code is not None: - pending_agent_login_path(profile).unlink(missing_ok=True) - except (LoginError, ValueError, OSError) as exc: - _fail(str(exc)) - ui.success("logged in, credentials saved to [dim]~/.runpod/config.toml[/dim]") - - -# ---------------------------------------------------------- app / env - - -def _fmt_ts(value) -> str: - if not value: - return "-" - text = str(value) - return text[:10] if len(text) >= 10 else text - - -@flash.group() -def app(): - """Manage deployed apps.""" - - -@app.command(name="list") -def app_list(): - """List all apps and their environments.""" - from runpod.apps.manage import list_apps - from runpod.rp_cli import console as ui - - try: - apps = asyncio.run(list_apps()) - except Exception as exc: # noqa: BLE001 - surface engine errors cleanly - raise click.ClickException(str(exc)) from exc - - if not apps: - ui.console.print( - "\n no apps deployed. run [white]rp flash deploy[/white]\n" - ) - return - - width = max(len(a["name"]) for a in apps) - ui.console.print() - for entry in apps: - envs = entry.get("flashEnvironments") or [] - names = ", ".join(e["name"] for e in envs) or "-" - ui.console.print( - f" [white]{entry['name']:<{width}}[/white] [dim]{names}[/dim]" - ) - ui.console.print() - - -@app.command(name="get") -@click.argument("app_name") -def app_get(app_name): - """Show one app with its environments.""" - from runpod.apps.manage import get_app - from runpod.rp_cli import console as ui - - try: - entry = asyncio.run(get_app(app_name)) - except Exception as exc: # noqa: BLE001 - surface engine errors cleanly - raise click.ClickException(str(exc)) from exc - - envs = entry.get("flashEnvironments") or [] - ui.console.print() - ui.console.print(f" [white]{entry['name']}[/white]") - if envs: - width = max(len(e["name"]) for e in envs) - for env_entry in envs: - build = (env_entry.get("activeBuildId") or "no build")[:12] - ui.console.print( - f" [white]{env_entry['name']:<{width}}[/white] [dim]{build}[/dim]" - ) - ui.console.print() - - -@app.command(name="delete") -@click.argument("app_name") -@click.option("--yes", "-y", is_flag=True, help="Skip the confirmation prompt.") -def app_delete(app_name, yes): - """Delete an app and its environments. Volumes are retained and keep billing.""" - from runpod.apps.manage import delete_app - from runpod.rp_cli import console as ui - - ui.warn( - "app deletion retains network and global volumes, which continue billing. " - "Review them with `rp volume list`. " - "Delete unneeded volumes and their data with `rp volume delete VOLUME_ID`." - ) - if not yes: - click.confirm(f"delete app '{app_name}' and all its environments?", abort=True) - - events = ui.CleanupEvents() - try: - result = asyncio.run(delete_app(app_name, events=events)) - except Exception as exc: # noqa: BLE001 - surface engine errors cleanly - raise click.ClickException(str(exc)) from exc - finally: - events.close() - - if result.failures: - for failure in result.failures: - ui.error(failure) - raise click.ClickException("undeploy incomplete; app kept") - ui.success( - f"deleted [white]{app_name}[/white] " - f"[dim]{result.endpoints_deleted} endpoints removed[/dim]" - ) - - -@cli.group() -def registry(): - """Manage container registry credentials (private images).""" - - -@registry.command(name="add") -@click.argument("name", required=False) -@click.option("--username", default=None, help="Registry username (prompted if omitted).") -@click.option("--password", default=None, help="Registry password/token (prompted if omitted).") -def registry_add(name, username, password): - """Create a registry credential. Reference it with registry_auth=NAME.""" - from runpod.apps.api import AppsApiClient - from runpod.rp_cli import console as ui - - if name is None: - name = click.prompt("name") - if username is None: - username = click.prompt("username") - if password is None: - password = click.prompt("password", hide_input=True) - - try: - asyncio.run( - AppsApiClient().create_registry_auth(name, username, password) - ) - except Exception as exc: # noqa: BLE001 - surface engine errors cleanly - raise click.ClickException(str(exc)) from exc - ui.success( - f"registry credential [white]{name}[/white] created, " - f'[dim]use registry_auth="{name}"[/dim]' - ) - - -@registry.command(name="list") -def registry_list(): - """List registry credential names.""" - from runpod.apps.api import AppsApiClient - from runpod.rp_cli import console as ui - - try: - creds = asyncio.run(AppsApiClient().list_registry_auths()) - except Exception as exc: # noqa: BLE001 - surface engine errors cleanly - raise click.ClickException(str(exc)) from exc - - if not creds: - ui.console.print( - "\n no registry credentials. run [white]rp registry add [/white]\n" - ) - return - ui.console.print() - for entry in sorted(creds, key=lambda c: c["name"]): - ui.console.print(f" [white]{entry['name']}[/white] [dim]{entry['id']}[/dim]") - ui.console.print() - - -@registry.command(name="delete") -@click.argument("name") -@click.option("--yes", "-y", is_flag=True, help="Skip the confirmation prompt.") -def registry_delete(name, yes): - """Delete a registry credential by name.""" - from runpod.apps.api import AppsApiClient - from runpod.rp_cli import console as ui - - async def _delete(): - client = AppsApiClient() - creds = await client.list_registry_auths() - match = next((c for c in creds if c["name"] == name), None) - if match is None: - _fail(f"no registry credential named '{name}'") - await client.delete_registry_auth(match["id"]) - - if not yes: - click.confirm(f"delete registry credential '{name}'?", abort=True) - try: - asyncio.run(_delete()) - except click.ClickException: - raise - except Exception as exc: # noqa: BLE001 - surface engine errors cleanly - raise click.ClickException(str(exc)) from exc - ui.success(f"deleted registry credential [white]{name}[/white]") - - -@cli.group() -def secret(): - """Manage platform secrets (encrypted env values).""" - - -@secret.command(name="add") -@click.argument("name", required=False) -@click.option("--value", default=None, help="Secret value (prompted if omitted).") -@click.option("--description", default="", help="Optional description.") -def secret_add(name, value, description): - """Create a secret. Reference it with runpod.Secret(NAME). - - Prompts for anything not provided: bare `rp secret add` asks for - name and value, `rp secret add NAME` asks for just the value. - """ - from runpod.apps.api import AppsApiClient - from runpod.rp_cli import console as ui - - if name is None: - name = click.prompt("name") - if value is None: - value = click.prompt("value", hide_input=True) - - try: - asyncio.run(AppsApiClient().create_secret(name, value, description)) - except Exception as exc: # noqa: BLE001 - surface engine errors cleanly - raise click.ClickException(str(exc)) from exc - ui.success( - f"secret [white]{name}[/white] created, " - f"[dim]use runpod.Secret(\"{name}\")[/dim]" - ) - - -@secret.command(name="list") -def secret_list(): - """List secret names (values are never shown).""" - from runpod.apps.api import AppsApiClient - from runpod.rp_cli import console as ui - - try: - secrets = asyncio.run(AppsApiClient().list_secrets()) - except Exception as exc: # noqa: BLE001 - surface engine errors cleanly - raise click.ClickException(str(exc)) from exc - - if not secrets: - ui.console.print("\n no secrets. run [white]rp secret add [/white]\n") - return - ui.console.print() - width = max(len(s["name"]) for s in secrets) - for entry in sorted(secrets, key=lambda s: s["name"]): - description = entry.get("description") or "" - ui.console.print( - f" [white]{entry['name']:<{width}}[/white] [dim]{description}[/dim]" - ) - ui.console.print() - - -@secret.command(name="delete") -@click.argument("name") -@click.option("--yes", "-y", is_flag=True, help="Skip the confirmation prompt.") -def secret_delete(name, yes): - """Delete a secret by name.""" - from runpod.apps.api import AppsApiClient - from runpod.rp_cli import console as ui - - async def _delete(): - client = AppsApiClient() - secrets = await client.list_secrets() - match = next((s for s in secrets if s["name"] == name), None) - if match is None: - _fail(f"no secret named '{name}'") - await client.delete_secret(match["id"]) - - if not yes: - click.confirm(f"delete secret '{name}'?", abort=True) - try: - asyncio.run(_delete()) - except click.ClickException: - raise - except Exception as exc: # noqa: BLE001 - surface engine errors cleanly - raise click.ClickException(str(exc)) from exc - ui.success(f"deleted secret [white]{name}[/white]") - - -@flash.group() -def env(): - """Manage app environments.""" - - -def _resolve_app_name(app_name) -> str: - """--app flag or the single app discovered in cwd.""" - if app_name: - return app_name - from runpod.apps.discovery import DiscoveryError, discover_apps - - try: - apps = discover_apps(Path.cwd()) - except DiscoveryError: - apps = [] - if len(apps) == 1: - return apps[0].name - _fail("pass --app (no unique app found in the current directory)") - - -@env.command(name="list") -@click.option("--app", "-a", "app_name", default=None, help="App name.") -def env_list(app_name): - """List environments for an app.""" - from runpod.apps.manage import get_app - from runpod.rp_cli import console as ui - - name = _resolve_app_name(app_name) - try: - entry = asyncio.run(get_app(name)) - except Exception as exc: # noqa: BLE001 - surface engine errors cleanly - raise click.ClickException(str(exc)) from exc - - envs = entry.get("flashEnvironments") or [] - if not envs: - ui.console.print( - f"\n no environments in [white]{name}[/white]. " - f"run [white]rp flash deploy[/white]\n" - ) - return - ui.console.print() - width = max(len(e["name"]) for e in envs) - for env_entry in envs: - build = (env_entry.get("activeBuildId") or "-")[:12] - ui.console.print( - f" [white]{env_entry['name']:<{width}}[/white] " - f"[dim]{build}, {_fmt_ts(env_entry.get('createdAt'))}[/dim]" - ) - ui.console.print() - - -@env.command(name="get") -@click.argument("env_name") -@click.option("--app", "-a", "app_name", default=None, help="App name.") -def env_get(env_name, app_name): - """Show an environment with its endpoints.""" - from runpod.apps.manage import get_environment - from runpod.rp_cli import console as ui - - name = _resolve_app_name(app_name) - try: - entry = asyncio.run(get_environment(name, env_name)) - except Exception as exc: # noqa: BLE001 - surface engine errors cleanly - raise click.ClickException(str(exc)) from exc - - ui.console.print() - ui.console.print( - f" [white]{name}/{entry['name']}[/white] " - f"[dim]build {(entry.get('activeBuildId') or '-')[:12]}[/dim]" - ) - endpoints = entry.get("endpoints") or [] - if endpoints: - width = max(len(e["name"]) for e in endpoints) - for endpoint in endpoints: - ui.console.print( - f" [white]{endpoint['name']:<{width}}[/white] " - f"{ui.endpoint_link(endpoint['id'])}" - ) - ui.console.print() - - -@env.command(name="add") -@click.argument("env_name") -@click.option("--app", "-a", "app_name", default=None, help="App name.") -def env_add(env_name, app_name): - """Create a new environment in an app.""" - from runpod.apps.api import AppsApiClient - from runpod.apps.manage import get_app - from runpod.rp_cli import console as ui - - name = _resolve_app_name(app_name) - - async def _create(): - client = AppsApiClient() - entry = await get_app(name, api=client) - return await client.create_environment(entry["id"], env_name) - - try: - asyncio.run(_create()) - except Exception as exc: # noqa: BLE001 - surface engine errors cleanly - raise click.ClickException(str(exc)) from exc - ui.success(f"created [white]{name}/{env_name}[/white]") - - -@env.command(name="delete") -@click.argument("env_name") -@click.option("--app", "-a", "app_name", default=None, help="App name.") -@click.option("--yes", "-y", is_flag=True, help="Skip the confirmation prompt.") -def env_delete(env_name, app_name, yes): - """Undeploy and delete an environment.""" - from runpod.apps.manage import undeploy_environment - from runpod.rp_cli import console as ui - - name = _resolve_app_name(app_name) - if not yes: - click.confirm( - f"undeploy and delete '{name}/{env_name}'?", abort=True - ) - - events = ui.CleanupEvents() - try: - result = asyncio.run( - undeploy_environment(name, env_name, events=events) - ) - except Exception as exc: # noqa: BLE001 - surface engine errors cleanly - raise click.ClickException(str(exc)) from exc - finally: - events.close() - - if result.failures: - for failure in result.failures: - ui.error(failure) - raise click.ClickException("undeploy incomplete; environment kept") - ui.success( - f"deleted [white]{name}/{env_name}[/white] " - f"[dim]{result.endpoints_deleted} endpoints removed[/dim]" - ) - - -@flash.command() -@click.option("--app", "-a", "app_name", default=None, help="App name.") -@click.option("--env", "-e", "env_name", default="default", show_default=True) -@click.option("--yes", "-y", is_flag=True, help="Skip the confirmation prompt.") -def undeploy(app_name, env_name, yes): - """Tear down a deployed environment's endpoints. - - Deletes the environment's endpoints and the environment itself; - the app and its build history remain. - """ - from runpod.apps.manage import undeploy_environment - from runpod.rp_cli import console as ui - - name = _resolve_app_name(app_name) - if not yes: - click.confirm(f"undeploy '{name}/{env_name}'?", abort=True) - - events = ui.CleanupEvents() - try: - result = asyncio.run( - undeploy_environment(name, env_name, events=events) - ) - except Exception as exc: # noqa: BLE001 - surface engine errors cleanly - raise click.ClickException(str(exc)) from exc - finally: - events.close() - - if result.failures: - for failure in result.failures: - ui.error(failure) - raise click.ClickException("undeploy incomplete") - ui.success( - f"undeployed [white]{name}/{env_name}[/white] " - f"[dim]{result.endpoints_deleted} endpoints removed[/dim]" - ) - - -# -------------------------------------------------------- legacy groups - - -def _mount_groups() -> None: - from runpod.cli.groups.ssh.commands import ssh_cli - from runpod.rp_cli.catalog import catalog - from runpod.rp_cli.datacenter import datacenter - from runpod.rp_cli.endpoint import endpoint - from runpod.rp_cli.pod import pod - from runpod.rp_cli.template import template - from runpod.rp_cli.user import user - from runpod.rp_cli.volume import volume - - for command in (ssh_cli, pod, catalog, volume, endpoint, template, user, datacenter): - cli.add_command(command) - cli.add_command(user, name="account") - cli.add_command(user, name="me") - - -_mount_groups() - - -def run() -> None: - """console-script entry point.""" - for stream in (sys.stdout, sys.stderr): - reconfigure = getattr(stream, "reconfigure", None) - if callable(reconfigure): - reconfigure(errors="replace") - cli() +from runpod.cli import main if __name__ == "__main__": - run() + main.run() +else: + sys.modules[__name__] = main diff --git a/runpod/rp_cli/options.py b/runpod/rp_cli/options.py index e7b27491f..e5e6c2310 100644 --- a/runpod/rp_cli/options.py +++ b/runpod/rp_cli/options.py @@ -1,66 +1,7 @@ -"""value parsing shared by resource command options.""" +"""shared command-line helpers.""" -import shlex -from collections.abc import Iterable +import sys -import click +from runpod.cli import options -from runpod.rp_cli.api import list_all -from runpod.rp_cli.compute import ResolutionError - -DEFAULT_MOUNT_PATH = "/workspace" - - -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 +sys.modules[__name__] = options diff --git a/runpod/rp_cli/output.py b/runpod/rp_cli/output.py index c715d9904..57f560779 100644 --- a/runpod/rp_cli/output.py +++ b/runpod/rp_cli/output.py @@ -1,115 +1,7 @@ -"""output, picker, prompt, and completion helpers shared by resource commands.""" +"""shared command-line helpers.""" -import json -import shutil import sys -from collections.abc import Callable, Iterable, Sequence -from typing import Any -import click -from click.shell_completion import CompletionItem +from runpod.cli import output -Column = tuple[str, Callable[[dict], Any]] - -json_option = click.option( - "--json", "as_json", is_flag=True, help="Print JSON for scripts and agents." -) - - -def print_json(data: Any) -> None: - click.echo(json.dumps(data, indent=2, default=str)) - - -def cell(value: Any) -> str: - if value is None or value == "" or value == [] or value == {}: - return "-" - if isinstance(value, bool): - return "yes" if value else "no" - if isinstance(value, (list, tuple)): - return ", ".join(str(item) for item in value) - return str(value) - - -def table(rows: Sequence[dict], columns: Sequence[Column]): - from rich.markup import escape - from rich.table import Table - - result = Table(box=None, header_style="dim", pad_edge=False) - for index, (header, _) in enumerate(columns): - result.add_column(header, no_wrap=index == 0, overflow="fold") - for row in rows: - result.add_row(*(escape(cell(value(row))) for _, value in columns)) - return result - - -def print_table(rows: Sequence[dict], columns: Sequence[Column], empty: str) -> None: - from runpod.rp_cli import console as ui - - ui.console.print(table(rows, columns) if rows else f"[dim]{empty}[/dim]") - - -def print_fields(record: dict, fields: Sequence[Column]) -> None: - from rich.markup import escape - from rich.table import Table - - from runpod.rp_cli import console as ui - - result = Table.grid(padding=(0, 2)) - result.add_column(style="dim", no_wrap=True) - result.add_column(overflow="fold") - for label, value in fields: - result.add_row(label, escape(cell(value(record)))) - ui.console.print(result) - - -def interactive() -> bool: - return sys.stdin.isatty() and sys.stdout.isatty() - - -def pick(message: str, choices: Sequence[tuple[str, str]], missing: str) -> str: - if not interactive(): - raise click.UsageError(missing) - if not choices: - raise click.UsageError(f"{missing} (none found)") - from InquirerPy import inquirer - from InquirerPy.base.control import Choice - from rich.text import Text - - width = max(1, shutil.get_terminal_size().columns - Text(message).cell_len - 3) - items = [] - for value, label in choices: - name = Text(label) - name.truncate(width, overflow="ellipsis") - items.append(Choice(value, name=name.plain)) - return inquirer.fuzzy( - message=message, - choices=items, - wrap_lines=False, - ).execute() - - -def confirm(message: str, yes: bool) -> None: - if yes: - return - if not interactive(): - raise click.UsageError("pass --yes to confirm in a non-interactive shell") - click.confirm(message, abort=True) - - -def completer( - fetch: Callable[[], Iterable[tuple[str, str]]], -) -> Callable[[click.Context, click.Parameter, str], list[CompletionItem]]: - """shell completion offering (value, help) pairs from fetch.""" - - def complete(ctx, param, incomplete): - try: - entries = list(fetch()) - except Exception: - return [] - return [ - CompletionItem(value, help=label) - for value, label in entries - if value.startswith(incomplete) - ] - - return complete +sys.modules[__name__] = output diff --git a/runpod/rp_cli/pod.py b/runpod/rp_cli/pod.py index 7b96c256f..6421dfea0 100644 --- a/runpod/rp_cli/pod.py +++ b/runpod/rp_cli/pod.py @@ -1,828 +1,7 @@ -import posixpath -import time -from operator import itemgetter +"""shared command-line helpers.""" -import click +import sys -from runpod._hosts import proxy_url -from runpod.api.rest import run_rest_request -from runpod.cli.groups.pod.commands import sync_pods -from runpod.rp_cli import compute -from runpod.rp_cli.api import api_errors, list_all -from runpod.rp_cli.options import DEFAULT_MOUNT_PATH, container_fields -from runpod.rp_cli.output import ( - completer, - confirm, - interactive, - json_option, - pick, - print_fields, - print_json, - print_table, -) -from runpod.rp_cli.volume import _choices as volume_choices -from runpod.rp_cli.volume import _get_volume +from runpod.cli import pod -STATUSES = ["PROVISIONING", "STARTING", "RUNNING", "EXITED", "ERROR", "TERMINATED"] -WAIT_TIMEOUT = 600 -WAIT_INTERVAL = 5 - - -def _pod_choices(action: str | None = None) -> list[tuple[str, str]]: - return [ - (pod["id"], f"{pod['name']} {pod['status'].lower()}") - for pod in list_all("/v2/pods", "pods") - if action is None or action in pod["actions"] - ] - - -def _resolve_pod_id(pod_id: str | None, action: str | None = None) -> str: - if pod_id: - return pod_id - choices = [] - if interactive(): - with api_errors(): - choices = _pod_choices(action) - return pick("pod", choices, "pass a POD_ID") - - -_complete_pods = completer(_pod_choices) -_complete_datacenters = completer( - lambda: [ - (dc["id"], (dc.get("region") or "").lower()) - for dc in compute.list_datacenters() - ] -) -_complete_volumes = completer(volume_choices) -_complete_registries = completer( - lambda: [ - (registry["name"], registry["id"]) - for registry in list_all("/v2/registries", "registries") - ] -) - - -def _say(message: str, as_json: bool, warning: bool = False) -> None: - if as_json: - click.echo(message, err=True) - return - from rich.markup import escape - - from runpod.rp_cli import console as ui - - (ui.warn if warning else ui.info)(escape(message)) - - -def _status(pod: dict) -> str: - status = pod["status"].lower() - if status == "running" and not (pod.get("runtime") or {}).get("uptime"): - return "starting" - return status - - -def _summary(pod: dict) -> dict: - hardware = pod.get("gpu") or pod.get("cpu") or {} - description = None - if pod.get("gpu"): - description = f"{hardware['count']}x {hardware['id']}" - elif pod.get("cpu"): - description = f"{hardware['id']} {hardware['vcpuCount']} vcpu" - return { - "id": pod["id"], - "name": pod["name"], - "status": _status(pod), - "hardware": description, - "data center": pod.get("dataCenterId"), - "cost": f"${pod['cost']:.2f}/hr" if pod.get("cost") else None, - "image": pod["image"], - } - - -def _show(pod: dict, as_json: bool) -> None: - if as_json: - print_json(pod) - return - runtime = pod.get("runtime") or {} - mounts = pod.get("mounts") or {} - networking = pod.get("globalNetworking") or {} - ssh = pod.get("ssh") or {} - hardware = pod.get("gpu") or pod.get("cpu") or {} - volumes = [] - if mounts.get("persistent"): - volume = mounts["persistent"] - volumes.append(f"persistent {volume['size']}GB at {volume['path']}") - for kind in ("network", "global"): - for volume in mounts.get(kind, []): - volumes.append( - f"{kind} {volume['volumeId']} at {volume.get('path') or '-'}" - ) - uptime = None - if runtime.get("uptime"): - minutes, seconds = divmod(runtime["uptime"], 60) - hours, minutes = divmod(minutes, 60) - uptime = f"{hours}h {minutes}m" if hours else f"{minutes}m {seconds}s" - if not hours and not minutes: - uptime = f"{seconds}s" - fields = { - **_summary(pod), - "resources": [ - f"{hardware[key]:g}{unit}" - for key, unit in (("vcpuCount", " vcpu"), ("memory", "GB ram")) - if hardware.get(key) - ], - "cloud": (pod.get("cloud") or "").lower(), - "cuda": pod.get("cudaVersion"), - "disk": f"{pod['disk']}GB" if pod.get("disk") else None, - "volumes": volumes, - "ports": pod.get("ports"), - "env": sorted(pod.get("env") or {}), - "command": pod.get("args"), - "locked": pod.get("locked"), - "global network": bool(networking.get("enabled")) - and (networking.get("internalDns") or networking.get("ip") or True), - "cluster": (pod.get("cluster") or {}).get("id"), - "created": pod.get("createdAt"), - "started": pod.get("startedAt"), - "uptime": uptime, - "actions": pod["actions"], - "ssh": (ssh.get("proxy") or {}).get("command"), - "ssh direct": (ssh.get("direct") or {}).get("command"), - "urls": [ - proxy_url(pod["id"], port.split("/")[0]) - for port in pod.get("ports", []) - if port.endswith("/http") - ], - "tcp": [ - f"{port['ip']}:{port['public']} -> {port['private']}" - for port in runtime.get("ports", []) - if port["type"] == "tcp" and port.get("ip") and port.get("public") - ], - } - print_fields(fields, [(label, itemgetter(label)) for label in fields]) - - -def _wait_running(pod_id: str, since: float, previous: dict | None = None) -> dict: - from runpod.rp_cli import console as ui - - deadline = time.monotonic() + WAIT_TIMEOUT - previous_uptime = ((previous or {}).get("runtime") or {}).get("uptime") or 0 - runtime_restarted = previous is None - with ui.console.status(f"[dim]waiting for {pod_id} to start ...[/dim]"): - while True: - pod = run_rest_request("GET", f"/v2/pods/{pod_id}") - status = _status(pod) - uptime = pod["runtime"]["uptime"] if status == "running" else 0 - if status != "running" or uptime < previous_uptime: - runtime_restarted = True - new_start = previous is None or ( - pod.get("startedAt") and pod["startedAt"] != previous.get("startedAt") - ) - if ( - status == "running" - and new_start - and runtime_restarted - and uptime <= time.monotonic() - since + 1 - ): - return pod - if status in ("error", "terminated"): - raise click.ClickException(f"pod {pod_id} is {status}") - if time.monotonic() >= deadline: - raise click.ClickException( - f"pod {pod_id} is still {status or 'unknown'} after {WAIT_TIMEOUT}s" - ) - time.sleep(WAIT_INTERVAL) - - -def _container_body( - options: dict, current: dict | None = None, unset_env=(), network_centers=None -) -> dict: - """build container settings, preserving existing environment and mount paths.""" - current = current or {} - body = container_fields(options, current, unset_env) - mounts = {} - values = ( - [("persistent", options["persistent_volume"])] - if options["persistent_volume"] is not None - else [] - ) - values.extend((None, value) for value in options["volume"]) - for kind, value in values: - head, sep, path = value.partition(":") - flag = "--persistent-volume" if kind == "persistent" else "--volume" - if not head or (sep and not path): - raise click.BadParameter( - f"'{value}' should look like VALUE[:PATH]", param_hint=flag - ) - if kind is None: - kind, record = _get_volume(head) - if kind == "network" and network_centers is not None: - network_centers.add(record["dataCenter"]) - existing = (current.get("mounts") or {}).get(kind) - if kind != "persistent": - existing = next( - (mount for mount in existing or [] if mount["volumeId"] == head), None - ) - path = path or (existing or {}).get("path") - if kind != "global": - path = path or DEFAULT_MOUNT_PATH - if kind == "persistent": - if not head.isdigit(): - raise click.BadParameter( - "size is in GB, like 50 or 50:/workspace", param_hint=flag - ) - mounts[kind] = {"size": int(head), "path": path} - else: - if any(mount["volumeId"] == head for mount in mounts.get(kind, [])): - raise click.BadParameter( - f"volume {head!r} is specified more than once", param_hint=flag - ) - mounts.setdefault(kind, []).append( - {"volumeId": head, **({"path": path} if path else {})} - ) - if mounts: - effective_mounts = dict(current.get("mounts") or {}) - for kind, entries in mounts.items(): - if kind == "persistent": - effective_mounts[kind] = entries - continue - replaced_ids = {mount["volumeId"] for mount in entries} - effective_mounts[kind] = [ - mount - for mount in effective_mounts.get(kind) or [] - if mount["volumeId"] not in replaced_ids - ] + entries - paths = set() - for kind, entries in effective_mounts.items(): - if not entries: - continue - for mount in ([entries] if kind == "persistent" else entries): - if not mount.get("path"): - continue - path = posixpath.normpath(mount["path"]) - if path.startswith("//"): - path = path[1:] - if path in paths: - raise click.UsageError( - f"multiple volumes target {path!r}. use a distinct :PATH for each volume" - ) - paths.add(path) - body["mounts"] = mounts - return body - - -_CONTAINER_OPTIONS = [ - click.option( - "--image", default=None, help="Container image, like runpod/pytorch:latest." - ), - click.option( - "--template", - default=None, - help="Template id whose container settings to apply.", - ), - click.option( - "--env", - "-e", - multiple=True, - metavar="KEY=VALUE", - help="Environment variable. Repeatable.", - ), - click.option( - "--port", - "-p", - "ports", - multiple=True, - metavar="PORT/PROTO", - help="Exposed port like 8888/http or 22/tcp. Repeatable.", - ), - click.option( - "--disk", type=click.IntRange(min=1), default=None, help="Container disk in GB." - ), - click.option( - "--persistent-volume", - metavar="GB[:PATH]", - default=None, - help=f"Host-local persistent volume (path defaults to {DEFAULT_MOUNT_PATH}).", - ), - click.option( - "--volume", - metavar="ID[:PATH]", - multiple=True, - shell_complete=_complete_volumes, - help="Network or global volume to mount, resolved by ID. Repeatable. " - f"Network paths default to {DEFAULT_MOUNT_PATH}.", - ), - click.option( - "--args", - default=None, - help="Container start command as one raw string ('' clears).", - ), - click.option( - "--cmd", - default=None, - help="Container CMD as a shell string, split into exec form.", - ), - click.option( - "--entrypoint", - default=None, - help="Container ENTRYPOINT as a shell string, split into exec form.", - ), - click.option( - "--registry", - default=None, - shell_complete=_complete_registries, - help="Registry credential name or id for private images ('' clears).", - ), - click.option( - "--global-networking/--no-global-networking", - default=None, - help="Private networking across data centers (NVIDIA GPUs only).", - ), -] - - -def _container_options(command): - for option in reversed(_CONTAINER_OPTIONS): - command = option(command) - return command - - -def _gpu_body( - spec: str, - count: int | None, - cloud: str, - cuda: tuple[str, ...], - datacenter_ids: list[str], - min_ram: int | None, - min_vcpu: int | None, - as_json: bool, -) -> dict: - """resolve a GPU specification by stock and price, then build its request.""" - query, spec_count = compute.parse_gpu_spec(spec) - if spec_count and count and spec_count != count: - raise click.UsageError(f"--gpu {spec} conflicts with --gpu-count {count}") - count = spec_count or count or 1 - min_cuda, exact_cuda = compute.parse_cuda(cuda) - gpus = compute.list_gpus( - product="POD", - count=count, - cloud=cloud.upper(), - cuda_versions=exact_cuda, - min_cuda_version=min_cuda, - ) - matches = compute.resolve_gpus(query, gpus) - allowed = set(datacenter_ids) - - def stock(gpu: dict) -> str: - if not allowed: - return gpu.get("availability") or "NONE" - return compute.best_availability( - dc.get("availability") - for dc in gpu.get("dataCenters") or [] - if dc["id"] in allowed - ) - - offered = [ - gpu - for gpu in matches - if len(matches) == 1 - or ( - gpu.get(cloud, True) - and (gpu.get("maxCount") or {}).get(cloud, count) >= count - ) - ] - if not offered: - names = ", ".join(gpu.get("name") or gpu["id"] for gpu in matches) - raise compute.ResolutionError( - f"no '{query}' gpu ({names}) offers {count} per pod on {cloud} cloud" - ) - best = min( - offered, - key=lambda gpu: ( - -compute.availability_rank(stock(gpu)), - (gpu.get("price") or {}).get(cloud) or float("inf"), - gpu.get("name") or gpu["id"], - ), - ) - availability = stock(best) - label = best.get("name") or best["id"] - price = (best.get("price") or {}).get(cloud) - if len(matches) > 1: - cost = f", ${price * count:.2f}/hr" if price else "" - _say( - f"'{query}' matches {len(matches)} gpu types; using {label} " - f"({best['id']}): {'no' if availability == 'NONE' else availability.lower()} stock{cost}", - as_json, - ) - if availability == "NONE": - _say( - f"the catalog reports no {cloud} stock for {count}x {label} " - "in the requested data centers; creation may fail", - as_json, - warning=True, - ) - body = {"id": best["id"], "count": count} - for field, value in ( - ("minCudaVersion", min_cuda), - ("allowedCudaVersions", exact_cuda), - ("minRamPerGpu", min_ram), - ("minVcpuCountPerGpu", min_vcpu), - ): - if value: - body[field] = value - return body - - -def _datacenter_ids(regions, data_centers, network_centers) -> list[str]: - ids = ( - compute.resolve_regions(regions, compute.list_datacenters()) if regions else [] - ) - ids += [dc for dc in data_centers if dc not in ids] - if len(network_centers) > 1: - raise click.UsageError("a pod's network volumes must share a data center") - if network_centers: - center = next(iter(network_centers)) - if ids and center not in ids: - raise click.UsageError( - f"network volumes are in {center}, outside the requested placement" - ) - ids = ids or [center] - return ids - - -def _create_body( - name, - gpu, - gpu_count, - cpu, - vcpu, - cloud, - regions, - data_centers, - cuda, - min_ram_per_gpu, - min_vcpu_per_gpu, - ssh, - jupyter, - as_json, - **container, -): - if gpu and cpu: - raise click.UsageError("use either --gpu or --cpu") - if not gpu and not cpu: - raise click.UsageError("pass --gpu (like 4090 or h100:2) or --cpu (like cpu3c)") - if cpu and (gpu_count or cuda or min_ram_per_gpu or min_vcpu_per_gpu): - raise click.UsageError( - "--gpu-count, --cuda, --min-ram-per-gpu, and --min-vcpu-per-gpu apply to gpu pods" - ) - if vcpu and not cpu: - raise click.UsageError("--vcpu applies to cpu pods") - if not container["image"] and not container["template"]: - raise click.UsageError("pass --image or --template") - if not name: - if not interactive(): - raise click.UsageError("pass a NAME") - name = click.prompt("pod name") - - network_centers = set() - body = { - "name": name, - **_container_body(container, network_centers=network_centers), - } - datacenter_ids = _datacenter_ids(regions, data_centers, network_centers) - if datacenter_ids: - body["dataCenterIds"] = datacenter_ids - if cloud: - body["cloud"] = cloud.upper() - - if gpu: - body["gpu"] = _gpu_body( - gpu, - gpu_count, - (cloud or "secure").lower(), - cuda, - datacenter_ids, - min_ram_per_gpu, - min_vcpu_per_gpu, - as_json, - ) - else: - flavor = compute.resolve_cpu( - cpu, compute.list_cpus(product="POD", vcpu_count=vcpu) - ) - body["cpu"] = { - "id": flavor["id"], - "vcpuCount": vcpu or (flavor.get("vcpu") or {}).get("min") or 2, - } - - if ssh: - body["startSsh"] = True - keys = run_rest_request("GET", "/v2/account/ssh-keys")["keys"] - if not keys: - _say( - "your account has no ssh keys, so --ssh has no effect. " - "add one with rp ssh add", - as_json, - warning=True, - ) - if jupyter: - body["startJupyter"] = True - - return body - - -@click.group("pod") -def pod(): - """Create and manage pods.""" - - -@pod.command(name="list") -@click.option("--name", default=None, help="Only pods whose name contains this text.") -@click.option( - "--status", - "statuses", - multiple=True, - type=click.Choice(STATUSES, case_sensitive=False), - help="Only pods in this status. Repeatable.", -) -@click.option( - "--include-cluster-pods", is_flag=True, help="Include cluster member pods." -) -@json_option -def list_pods(name, statuses, include_cluster_pods, as_json): - """List your pods.""" - with api_errors(): - params = {"includeClusterPods": "true"} if include_cluster_pods else None - pods = list_all("/v2/pods", "pods", params) - if name: - pods = [p for p in pods if name.lower() in (p.get("name") or "").lower()] - if statuses: - wanted = {status.lower() for status in statuses} - pods = [p for p in pods if _status(p) in wanted] - if as_json: - print_json(pods) - return - columns = ["id", "name", "status", "hardware", "data center", "cost", "image"] - print_table( - [_summary(p) for p in pods], - [(label.upper(), itemgetter(label)) for label in columns], - "no pods. create one with rp pod create", - ) - - -@pod.command() -@click.argument("pod_id", required=False, shell_complete=_complete_pods) -@json_option -def get(pod_id, as_json): - """Show a pod with its connection details.""" - pod_id = _resolve_pod_id(pod_id) - with api_errors(): - _show(run_rest_request("GET", f"/v2/pods/{pod_id}"), as_json) - - -@pod.command() -@click.argument("name", required=False) -@click.option( - "--gpu", default=None, metavar="TYPE[:COUNT]", help="GPU type like 4090 or h100:2." -) -@click.option( - "--gpu-count", type=click.IntRange(min=1), default=None, help="GPUs per pod." -) -@click.option( - "--cpu", default=None, help="CPU flavor like cpu3c or cpu5g, for a CPU pod." -) -@click.option( - "--vcpu", - type=click.IntRange(min=2), - default=None, - help="vCPUs for a CPU pod (defaults to the flavor's minimum).", -) -@click.option( - "--cloud", - type=click.Choice(["secure", "community"], case_sensitive=False), - default=None, - help="Cloud tier (the api defaults to secure).", -) -@click.option( - "--region", - "regions", - multiple=True, - help="Region (eu, na, asia), id prefix (us, eu-ro), or data center id. Repeatable.", -) -@click.option( - "--data-center", - "data_centers", - multiple=True, - shell_complete=_complete_datacenters, - help="Exact data center id like US-TX-3. Repeatable.", -) -@click.option( - "--cuda", - multiple=True, - help="Host CUDA: '>=12.4' for a floor, 12.4 or 12.4,12.8 for exact versions.", -) -@click.option( - "--min-ram-per-gpu", - type=click.IntRange(min=1), - default=None, - help="Minimum host RAM in GB per GPU.", -) -@click.option( - "--min-vcpu-per-gpu", - type=click.IntRange(min=1), - default=None, - help="Minimum host vCPUs per GPU.", -) -@_container_options -@click.option("--ssh", is_flag=True, help="Start sshd with your account's SSH keys.") -@click.option( - "--jupyter", is_flag=True, help="Start JupyterLab (expose 8888/http to reach it)." -) -@click.option("--wait", is_flag=True, help="Wait until the pod is running.") -@json_option -def create(name, wait, as_json, **options): - """Create a pod named NAME. - - GPU types are human-readable (4090, h100, a100-sxm). When a name - matches several types, the one with the most stock in the requested - regions wins, then the cheapest. - - \b - rp pod create trainer --gpu h100:2 --image runpod/pytorch:latest --region eu --ssh - rp pod create box --cpu cpu3c --vcpu 4 --image ubuntu:24.04 - rp pod create nb --gpu 4090 --image runpod/pytorch:latest --jupyter -p 8888/http - """ - with api_errors(): - body = _create_body(name, as_json=as_json, **options) - since = time.monotonic() - created = run_rest_request("POST", "/v2/pods", json=body) - _say(f"created pod {created['name']} ({created['id']})", as_json) - if wait: - created = _wait_running(created["id"], since) - _show(created, as_json) - - -@pod.command() -@click.argument("pod_id", required=False, shell_complete=_complete_pods) -@click.option("--name", default=None, help="New pod name.") -@_container_options -@click.option( - "--unset-env", - multiple=True, - metavar="KEY", - help="Remove an environment variable. Repeatable.", -) -@click.option( - "--lock/--unlock", - "locked", - default=None, - help="Lock the pod against stop and reset.", -) -@json_option -def update(pod_id, name, unset_env, locked, as_json, **container): - """Change a pod's settings. - - --env and --unset-env edit the existing environment, --port replaces - the exposed ports, and volume flags restate the full mount (the - volume id cannot change; the path defaults to the current one). - Most changes apply on the pod's next start. - """ - requested = [name, locked, *unset_env, *container.values()] - if all(value in (None, ()) for value in requested): - raise click.UsageError("nothing to update. see rp pod update --help") - pod_id = _resolve_pod_id(pod_id) - - with api_errors(): - needs_current = ( - container["env"] - or unset_env - or any(container[key] for key in ("persistent_volume", "volume")) - ) - current = ( - run_rest_request("GET", f"/v2/pods/{pod_id}") if needs_current else None - ) - network_centers = set() - body = _container_body( - container, current, unset_env, network_centers=network_centers - ) - if network_centers: - pod_center = current.get("dataCenterId") - _datacenter_ids((), [pod_center] if pod_center else (), network_centers) - if name: - body["name"] = name - if locked is not None: - body["locked"] = locked - updated = run_rest_request("PATCH", f"/v2/pods/{pod_id}", json=body) - _say(f"updated pod {pod_id}", as_json) - _show(updated, as_json) - - -def _act( - pod_id: str | None, action: str, done: str, as_json: bool, wait: bool = False -): - pod_id = _resolve_pod_id(pod_id, action) - with api_errors(): - previous = ( - run_rest_request("GET", f"/v2/pods/{pod_id}") - if wait and action == "restart" - else None - ) - since = time.monotonic() - result = run_rest_request( - "POST", f"/v2/pods/{pod_id}/action", json={"action": action} - ) - _say(f"{done} pod {pod_id}", as_json) - if wait: - result = _wait_running(pod_id, since, previous) - _show(result, as_json) - - -@pod.command() -@click.argument("pod_id", required=False, shell_complete=_complete_pods) -@click.option("--wait", is_flag=True, help="Wait until the pod is running.") -@json_option -def start(pod_id, wait, as_json): - """Start a stopped pod.""" - _act(pod_id, "start", "started", as_json, wait) - - -@pod.command() -@click.argument("pod_id", required=False, shell_complete=_complete_pods) -@json_option -def stop(pod_id, as_json): - """Stop a running pod, keeping its volume.""" - _act(pod_id, "stop", "stopped", as_json) - - -@pod.command() -@click.argument("pod_id", required=False, shell_complete=_complete_pods) -@click.option("--wait", is_flag=True, help="Wait until the pod is running.") -@json_option -def restart(pod_id, wait, as_json): - """Restart a running pod.""" - _act(pod_id, "restart", "restarted", as_json, wait) - - -@pod.command() -@click.argument("pod_id", required=False, shell_complete=_complete_pods) -@click.option("--yes", "-y", is_flag=True, help="Skip the confirmation prompt.") -def terminate(pod_id, yes): - """Terminate a pod permanently.""" - from runpod.rp_cli import console as ui - - pod_id = _resolve_pod_id(pod_id, "terminate") - with api_errors(): - if not yes: - record = run_rest_request("GET", f"/v2/pods/{pod_id}") - confirm( - f"terminate pod {pod_id} ({record['name']})? " - "its disk and persistent volume are deleted", - yes, - ) - run_rest_request("DELETE", f"/v2/pods/{pod_id}") - ui.success(f"terminated pod {pod_id}") - - -pod.add_command(terminate, "delete") - - -@pod.command() -@click.argument("pod_id", required=False, shell_complete=_complete_pods) -@click.option("--follow", "-f", is_flag=True, help="Follow new log lines.") -@click.option("--tail", type=click.IntRange(0, 5000), default=100, show_default=True) -@click.option("--source", type=click.Choice(["container", "system"])) -@click.option("--since", help="Only logs after this timestamp.") -@json_option -def logs(pod_id, follow, tail, source, since, as_json): - """Read a pod's container or system logs.""" - from runpod.rp_cli.logs import show_logs - - pod_id = _resolve_pod_id(pod_id) - show_logs( - pod_id, - follow=follow, - tail=tail, - source=source, - since=since, - as_json=as_json, - ) - - -@pod.command() -@click.argument("pod_id", required=False, shell_complete=_complete_pods) -def connect(pod_id): - """Open an interactive terminal on a pod over SSH. - - Needs an SSH key on your account (rp ssh add) and 22/tcp exposed. - """ - from runpod.cli.utils import ssh_cmd - - pod_id = _resolve_pod_id(pod_id) - click.echo(f"connecting to pod {pod_id}...") - try: - ssh = ssh_cmd.SSHConnection(pod_id) - except (ValueError, TimeoutError) as exc: - raise click.ClickException(str(exc)) from exc - ssh.launch_terminal() - - -pod.add_command(sync_pods, "sync") +sys.modules[__name__] = pod diff --git a/runpod/rp_cli/template.py b/runpod/rp_cli/template.py index 0a4591636..db124b475 100644 --- a/runpod/rp_cli/template.py +++ b/runpod/rp_cli/template.py @@ -1,265 +1,7 @@ -"""manage reusable pod and serverless container templates.""" +"""shared command-line helpers.""" -import click -from rich.markup import escape +import sys -from runpod.api.ctl_commands import _path_segment -from runpod.api.rest import run_rest_request -from runpod.rp_cli import console as ui -from runpod.rp_cli.api import api_errors, list_all -from runpod.rp_cli.options import DEFAULT_MOUNT_PATH, container_fields -from runpod.rp_cli.output import ( - completer, - confirm, - json_option, - pick, - print_fields, - print_json, - print_table, -) +from runpod.cli import template - -def _validate_record(record, required_fields): - if not isinstance(record, dict) or not record: - raise click.ClickException("template information is unavailable") - if any(key not in record for key in required_fields): - raise click.ClickException("template response is missing required fields") - - -def _choices(): - rows = list_all("/v2/templates", "templates") - for row in rows: - _validate_record(row, ("id",)) - return [(row["id"], row.get("name") or row["id"]) for row in rows] - - -complete_template = completer(_choices) - - -def _show(record, as_json): - _validate_record(record, ("id", "name", "image", "disk")) - if as_json: - print_json(record) - return - print_fields( - record, - [ - ("id", lambda row: row["id"]), - ("name", lambda row: row["name"]), - ("image", lambda row: row["image"]), - ("serverless", lambda row: row.get("serverless")), - ("public", lambda row: row.get("public")), - ("disk", lambda row: f"{row['disk']} GB"), - ("ports", lambda row: row.get("ports")), - ("entrypoint", lambda row: row.get("entrypoint")), - ("cmd", lambda row: row.get("cmd")), - ("mounts", lambda row: row.get("mounts")), - ("env", lambda row: sorted(row.get("env") or {})), - ("registry", lambda row: row.get("registry")), - ], - ) - - -@click.group() -def template(): - """Manage pod and serverless templates.""" - - -@template.command(name="list") -@click.option( - "--type", - "source", - type=click.Choice(["user", "official", "verified", "community", "all"]), - default="user", - show_default=True, - help="List your templates or a public catalog.", -) -@click.option("--search", help="Match an id, name, or image (case-insensitive).") -@json_option -def template_list(source, search, as_json): - """List your templates, or browse public templates with --type.""" - with api_errors(): - rows = [] - sources = ( - ["user", "official", "verified", "community"] - if source == "all" - else [source] - ) - for selected in sources: - if selected == "user": - rows.extend(list_all("/v2/templates", "templates")) - else: - rows.extend( - list_all("/v2/catalog/templates", "templates", {"source": selected}) - ) - for row in rows: - _validate_record(row, ("id",)) - rows = list({row["id"]: row for row in rows}.values()) - if search: - term = search.casefold() - rows = [ - row - for row in rows - if any( - term in (row.get(key) or "").casefold() - for key in ("id", "name", "image") - ) - ] - if as_json: - print_json(rows) - return - print_table( - rows, - [ - ("ID", lambda row: row["id"]), - ("NAME", lambda row: row.get("name")), - ("IMAGE", lambda row: row.get("image")), - ("SERVERLESS", lambda row: row.get("serverless")), - ("PUBLIC", lambda row: row.get("public")), - ], - "no templates match", - ) - - -@template.command(name="get") -@click.argument("template_id", required=False, shell_complete=complete_template) -@json_option -def template_get(template_id, as_json): - """Show a template by id, or pick one of your templates.""" - with api_errors(): - if template_id is None: - template_id = pick("template", _choices(), "pass TEMPLATE_ID") - record = run_rest_request("GET", f"/v2/templates/{_path_segment(template_id)}") - _show(record, as_json) - - -def _options(function): - options = [ - click.option("--name", help="Template name."), - click.option("--image", help="Container image."), - click.option( - "--disk", type=click.IntRange(min=1), help="Container disk in GB." - ), - click.option( - "--serverless/--pod", default=None, help="Template workload type." - ), - click.option( - "--public/--private", default=None, help="Public catalog visibility." - ), - click.option( - "--port", - "ports", - multiple=True, - help="Exposed port, such as 8888/http. Repeatable.", - ), - click.option( - "--env", multiple=True, help="Environment variable KEY=VALUE. Repeatable." - ), - click.option("--cmd", help="Container command, parsed as shell words."), - click.option( - "--entrypoint", help="Container entrypoint, parsed as shell words." - ), - click.option( - "--registry", - help="Registry credential id or name. An empty value clears it.", - ), - click.option( - "--volume-size", - type=click.IntRange(min=10), - help="Persistent volume in GB (Pods only).", - ), - click.option( - "--volume-path", - help=f"Persistent volume mount path. Defaults to {DEFAULT_MOUNT_PATH} on create.", - ), - ] - for option in reversed(options): - function = option(function) - return function - - -def _body(options, current=None, unset_env=()): - body = container_fields(options, current, unset_env) - for key in ("name", "serverless", "public"): - if options[key] is not None: - body[key] = options[key] - for key in ("name", "image"): - if key in body and not body[key].strip(): - raise click.UsageError(f"--{key} cannot be empty") - size, path = options["volume_size"], options["volume_path"] - if size is not None or path is not None: - if body.get("serverless", (current or {}).get("serverless", False)): - raise click.UsageError("persistent volumes apply to pod templates only") - mount = ((current or {}).get("mounts") or {}).get("persistent") or {} - size = size if size is not None else mount.get("size") - if size is None: - raise click.UsageError("pass --volume-size when adding a persistent volume") - path = path if path is not None else mount.get("path", DEFAULT_MOUNT_PATH) - if not path.startswith("/"): - raise click.UsageError("--volume-path must be an absolute container path") - body["mounts"] = {"persistent": {"size": size, "path": path}} - return body - - -@template.command(name="create") -@_options -@json_option -def template_create(as_json, **options): - """Create a template with --name and --image. - - Environment values are stored in the template. Use platform secret - references for sensitive values. - """ - if not options["name"] or not options["image"]: - raise click.UsageError("pass --name and --image") - with api_errors(): - body = _body(options) - record = run_rest_request("POST", "/v2/templates", json=body) - _show(record, as_json) - - -@template.command(name="update") -@click.argument("template_id", shell_complete=complete_template) -@_options -@click.option( - "--unset-env", multiple=True, help="Remove an environment variable. Repeatable." -) -@click.option("--clear-ports", is_flag=True, help="Remove all exposed ports.") -@json_option -def template_update(template_id, unset_env, clear_ports, as_json, **options): - """Update a template. Unspecified settings are retained. - - --env edits individual keys. --port replaces the exposed ports. - """ - if clear_ports and options["ports"]: - raise click.UsageError("use either --port or --clear-ports") - with api_errors(): - current = None - path = f"/v2/templates/{_path_segment(template_id)}" - if ( - options["env"] - or unset_env - or options["volume_size"] is not None - or options["volume_path"] is not None - ): - current = run_rest_request("GET", path) - if not current: - raise click.ClickException("template information is unavailable") - body = _body(options, current, unset_env) - if clear_ports: - body["ports"] = [] - if not body: - raise click.UsageError("pass at least one setting to update") - record = run_rest_request("PATCH", path, json=body) - _show(record, as_json) - - -@template.command(name="delete") -@click.argument("template_id", shell_complete=complete_template) -@click.option("--yes", "-y", is_flag=True, help="Skip the confirmation prompt.") -def template_delete(template_id, yes): - """Delete a template.""" - confirm(f"delete template {template_id}?", yes) - with api_errors(): - run_rest_request("DELETE", f"/v2/templates/{_path_segment(template_id)}") - ui.success(f"deleted template [white]{escape(template_id)}[/white]") +sys.modules[__name__] = template diff --git a/runpod/rp_cli/update.py b/runpod/rp_cli/update.py index b7c369f66..5b5b89abf 100644 --- a/runpod/rp_cli/update.py +++ b/runpod/rp_cli/update.py @@ -1,221 +1,7 @@ -"""self-update for the rp cli and a passive new-version notice. +"""shared command-line helpers.""" -`rp update` installs the latest (or a pinned) runpod release from pypi -using uv when available, pip otherwise. every other command starts a -daemon thread that checks pypi at most once per day (cached under -~/.runpod) and prints a one-line notice at exit when a newer version -exists. the check never blocks or crashes a command. -""" - -from __future__ import annotations - -import atexit -import json -import shutil -import subprocess import sys -import threading -import urllib.error -import urllib.request -from datetime import UTC, datetime -from pathlib import Path - -PYPI_URL = "https://pypi.org/pypi/runpod/json" -INSTALL_TIMEOUT_SECONDS = 120 -CACHE_PATH = Path.home() / ".runpod" / "update_check.json" -CHECK_INTERVAL_HOURS = 24 - -_newer_version: str | None = None -_check_done = threading.Event() -_started = threading.Event() -_start_lock = threading.Lock() - - -def current_version() -> str: - try: - from runpod import __version__ - - return __version__ - except Exception: # noqa: BLE001 - version must never break the cli - return "unknown" - - -def parse_version(version: str) -> tuple[int, ...]: - """leading numeric release segments of a version string. - - dev/local suffixes (e.g. 1.8.0.dev3) are ignored so a dev build of - the next release does not count as older than the current one. - """ - parts = [] - for part in version.split("."): - if not part.isdigit(): - break - parts.append(int(part)) - return tuple(parts) - - -def compare_versions(a: tuple[int, ...], b: tuple[int, ...]) -> int: - """negative when a < b, zero when equal, positive when a > b.""" - width = max(len(a), len(b)) - a_padded = a + (0,) * (width - len(a)) - b_padded = b + (0,) * (width - len(b)) - return (a_padded > b_padded) - (a_padded < b_padded) - - -def fetch_pypi_metadata() -> tuple[str, set[str]]: - """(latest version, all release versions) from pypi.""" - try: - with urllib.request.urlopen(PYPI_URL, timeout=15) as resp: # noqa: S310 - data = json.loads(resp.read().decode()) - except urllib.error.URLError as exc: - if isinstance(exc, urllib.error.HTTPError): - raise RuntimeError( - f"pypi returned HTTP {exc.code}; try again later" - ) from exc - raise ConnectionError( - "could not reach pypi; check your network connection" - ) from exc - except (json.JSONDecodeError, UnicodeDecodeError) as exc: - raise RuntimeError("pypi returned an unexpected response") from exc - - try: - latest = data["info"]["version"] - except (KeyError, TypeError) as exc: - raise RuntimeError("pypi response missing version info") from exc - return latest, set(data.get("releases", {}).keys()) - - -def install_command(version: str) -> list: - """the installer invocation targeting the running interpreter. - - `uv pip install` is used only with an explicit --python pointing at - this interpreter: bare uv resolves against an activated venv, which - is not necessarily where this cli runs from. - """ - package_spec = f"runpod=={version}" - if shutil.which("uv"): - return [ - "uv", - "pip", - "install", - "--python", - sys.executable, - package_spec, - "--quiet", - ] - return [sys.executable, "-m", "pip", "install", package_spec, "--quiet"] - - -def run_install(version: str) -> None: - cmd = install_command(version) - result = subprocess.run( - cmd, - capture_output=True, - text=True, - timeout=INSTALL_TIMEOUT_SECONDS, - ) - if result.returncode != 0: - installer = "uv" if cmd[0] == "uv" else "pip" - raise RuntimeError( - f"{installer} install failed (exit {result.returncode}): " - f"{result.stderr.strip()}" - ) - - -# -- passive background check ------------------------------------------- - - -def _read_cache() -> dict | None: - try: - return json.loads(CACHE_PATH.read_text(encoding="utf-8")) - except (OSError, json.JSONDecodeError, ValueError): - return None - - -def _write_cache(latest_version: str) -> None: - try: - CACHE_PATH.parent.mkdir(parents=True, exist_ok=True) - CACHE_PATH.write_text( - json.dumps( - { - "last_checked_utc": datetime.now( - UTC - ).isoformat(), - "latest_version": latest_version, - } - ), - encoding="utf-8", - ) - except OSError: - # cache write is best-effort; the check reruns next invocation - pass - - -def _cache_fresh(cache: dict) -> bool: - try: - last_checked = datetime.fromisoformat(cache["last_checked_utc"]) - elapsed = ( - datetime.now(UTC) - last_checked - ).total_seconds() / 3600 - return elapsed < CHECK_INTERVAL_HOURS - except (KeyError, ValueError, TypeError): - return False - - -def _run_check() -> None: - global _newer_version # noqa: PLW0603 - try: - current = current_version() - if current == "unknown": - return - - cache = _read_cache() - latest = None - if cache and _cache_fresh(cache): - latest = cache.get("latest_version") or None - if not latest: - latest, _ = fetch_pypi_metadata() - _write_cache(latest) - if not latest: - return - - if compare_versions(parse_version(latest), parse_version(current)) > 0: - _newer_version = latest - except Exception: # noqa: BLE001 - the check must never crash the cli - pass - finally: - _check_done.set() - - -def _print_update_notice() -> None: - # plain text: atexit runs after rich teardown - if not _check_done.is_set(): - return - if _newer_version: - print( - f"\na new version of runpod is available: {_newer_version}\n" - " run 'rp update' to upgrade.", - file=sys.stderr, - ) - - -def _is_interactive() -> bool: - for stream in (sys.stderr, sys.stdout): - try: - if stream is not None and stream.isatty(): - return True - except Exception: # noqa: BLE001 - pass - return False +from runpod.cli import update -def start_background_check() -> None: - """spawn the daemon check thread once per process (ttys only).""" - with _start_lock: - if _started.is_set(): - return - _started.set() - if not _is_interactive(): - return - atexit.register(_print_update_notice) - threading.Thread(target=_run_check, daemon=True).start() +sys.modules[__name__] = update diff --git a/runpod/rp_cli/user.py b/runpod/rp_cli/user.py index 1462d04a1..768096b7d 100644 --- a/runpod/rp_cli/user.py +++ b/runpod/rp_cli/user.py @@ -1,94 +1,7 @@ -"""account details and balance for the authenticated user.""" +"""shared command-line helpers.""" -import click +import sys -from runpod.api.graphql import run_graphql_query -from runpod.rp_cli.api import api_errors -from runpod.rp_cli.output import json_option, print_fields, print_json +from runpod.cli import user -_USER_QUERY = """ -query { - myself { - id - email - clientBalance - currentSpendPerHr - spendLimit - notifyPodsStale - notifyPodsGeneral - notifyLowBalance - } -} -""" -_BALANCE_KEYS = ("clientBalance", "currentSpendPerHr", "spendLimit") -_USER_KEYS = ( - "id", - "email", - *_BALANCE_KEYS, - "notifyPodsStale", - "notifyPodsGeneral", - "notifyLowBalance", -) - - -def _money(value): - if isinstance(value, bool) or ( - value is not None and not isinstance(value, (int, float)) - ): - raise click.ClickException( - "account balance response contains a non-numeric value" - ) - return f"${value:.2f}" if value is not None else None - - -_BALANCE_FIELDS = [ - ("balance", lambda row: _money(row.get("clientBalance"))), - ("spend per hour", lambda row: _money(row.get("currentSpendPerHr"))), - ("spend limit", lambda row: _money(row.get("spendLimit"))), -] -_USER_FIELDS = [ - ("id", lambda row: row.get("id")), - ("email", lambda row: row.get("email")), - *_BALANCE_FIELDS, - ("notify stale pods", lambda row: row.get("notifyPodsStale")), - ("notify general pod events", lambda row: row.get("notifyPodsGeneral")), - ("notify low balance", lambda row: row.get("notifyLowBalance")), -] - - -def _show_user(as_json, balance_only=False): - with api_errors(): - record = (run_graphql_query(_USER_QUERY).get("data") or {}).get("myself") - if not record: - raise click.ClickException("account information is unavailable") - keys = _BALANCE_KEYS if balance_only else _USER_KEYS - record = {key: record.get(key) for key in keys} - if as_json: - print_json(record) - return - print_fields(record, _BALANCE_FIELDS if balance_only else _USER_FIELDS) - - -@click.group(invoke_without_command=True) -@json_option -@click.pass_context -def user(ctx, as_json): - """Show account information and balance.""" - if ctx.invoked_subcommand is None: - _show_user(as_json) - - -@user.command() -@json_option -@click.pass_context -def info(ctx, as_json): - """Show account details, spending, and notification settings.""" - _show_user(as_json or ctx.parent.params.get("as_json", False)) - - -@user.command() -@json_option -@click.pass_context -def balance(ctx, as_json): - """Show the account balance, hourly spending, and spending limit.""" - _show_user(as_json or ctx.parent.params.get("as_json", False), balance_only=True) +sys.modules[__name__] = user diff --git a/runpod/rp_cli/volume.py b/runpod/rp_cli/volume.py index 36623be3a..108d3e604 100644 --- a/runpod/rp_cli/volume.py +++ b/runpod/rp_cli/volume.py @@ -1,675 +1,7 @@ -import os -import re -import sys -from pathlib import Path - -import click -from requests import RequestException - -from runpod.api.ctl_commands import _path_segment -from runpod.api.rest import run_rest_request -from runpod.error import QueryError -from runpod.rp_cli import compute -from runpod.rp_cli import console as ui -from runpod.rp_cli.api import api_errors, list_all -from runpod.rp_cli.output import ( - completer, - confirm, - json_option, - pick, - print_fields, - print_json, - print_table, -) - -NETWORK_FIELDS = [ - ("id", lambda row: row["id"]), - ("name", lambda row: row["name"]), - ("size", lambda row: f"{row['size']} GB"), - ("data center", lambda row: row["dataCenter"]), - ("type", lambda row: row["type"].lower()), -] -GLOBAL_FIELDS = [ - ("id", lambda row: row["id"]), - ("name", lambda row: row["name"]), - ("created", lambda row: row["createdAt"]), - ("created by", lambda row: row["createdByUserId"]), -] -global_option = click.option( - "--global", - "kind", - flag_value="global", - default=None, - help="Select global volumes only.", -) - - -def _label(record): - if "size" not in record: - return record["name"] - return ( - f"{record['name']} {record['size']} GB " - f"{record['dataCenter']} {record['type'].lower()}" - ) - - -def _list_volumes(kind=None, failures=None): - rows = [] - for volume_kind in ([kind] if kind else ["network", "global"]): - try: - records = list_all(f"/v2/{volume_kind}-volumes", f"{volume_kind}Volumes") - except (QueryError, RequestException) as exc: - if failures is None: - raise - failures.append(f"could not list {volume_kind} volumes: {exc}") - continue - rows.extend({**row, "kind": volume_kind} for row in records) - return rows - - -def _choices(kind=None): - failures = [] - rows = _list_volumes(kind, failures) - for failure in failures: - click.echo(f"Warning: {failure}", err=True) - return [(row["id"], f"{row['kind']} {_label(row)}") for row in rows] - - -def _complete_ids(ctx, param, incomplete): - kind = "network" if ctx.command.name == "expand" else ctx.params.get("kind") - return completer(lambda: _choices(kind))(ctx, param, incomplete) - - -def _get_volume(volume_id, kind=None): - path_id = _path_segment(volume_id) - if kind: - return kind, run_rest_request("GET", f"/v2/{kind}-volumes/{path_id}") - try: - return "network", run_rest_request("GET", f"/v2/network-volumes/{path_id}") - except QueryError as exc: - if exc.status_code != 404: - raise - return "global", run_rest_request("GET", f"/v2/global-volumes/{path_id}") - - -def _show(record, kind, as_json, action=None): - if as_json: - print_json(record) - return - if action: - ui.success(f"{action} {kind} volume [white]{record['id']}[/white]") - print_fields(record, GLOBAL_FIELDS if kind == "global" else NETWORK_FIELDS) - - -def _data_center(regions, volume_type): - datacenters = compute.list_datacenters() - if regions: - allowed = compute.resolve_regions(regions, datacenters) - datacenters = [dc for dc in datacenters if dc["id"] in allowed] - candidates = [ - dc - for dc in datacenters - if dc["networkVolumeTypes"] - and (not volume_type or volume_type in dc["networkVolumeTypes"]) - ] - scope = f"region {', '.join(regions)}" if regions else "the catalog" - offered = ( - f"{volume_type.lower()} network volumes" if volume_type else "network volumes" - ) - if not candidates: - raise compute.ResolutionError(f"no data center in {scope} offers {offered}") - if len(candidates) == 1: - return candidates[0]["id"] - return pick( - "data center", - [ - ( - dc["id"], - f"{dc['id']} {dc['region'].lower().replace('_', ' ')} " - + ", ".join(t.lower() for t in dc["networkVolumeTypes"]), - ) - for dc in candidates - ], - f"several data centers in {scope} offer {offered} " - f"({', '.join(dc['id'] for dc in candidates)}). pass one with --data-center", - ) - - -def _growth(volume_id, size, expand=False): - text = str(size).strip() - if not re.fullmatch(r"\+?\d+", text): - raise click.BadParameter( - f"'{size}' is not a size. use N for a total or +N to add N GB", - param_hint="--size", - ) - kind, record = _get_volume(volume_id) - if kind == "global": - raise click.UsageError("global volumes have no size to change") - current = record["size"] - target = current + int(text) if text.startswith("+") else int(text) - if target < current or (expand and target == current): - raise click.UsageError( - f"network volumes can only grow: {volume_id} is {current} GB, " - f"requested {target} GB" - ) - if target > 4096: - raise click.UsageError( - f"network volumes hold at most 4096 GB, requested {target} GB" - ) - return current, target - - -@click.group() -def volume(): - """Create, list, resize, and delete volumes, and transfer files to them. - - upload and download use the S3-compatible API, which needs S3 API keys - (separate from your API key): set RUNPOD_S3_ACCESS_KEY and - RUNPOD_S3_SECRET_KEY, pass the --s3-* flags, use saved config, or enter - them when asked. Re-run an interrupted transfer to resume it. - Parts of an upload that is - never re-run stay in the volume's hidden .s3compat_uploads folder and - count toward its size. - """ - - -@volume.command(name="list") -@global_option -@json_option -def volume_list(kind, as_json): - """List network and global volumes together with their type.""" - failures = [] - with api_errors(): - rows = _list_volumes(kind, None if as_json else failures) - if as_json: - print_json(rows) - return - fields = [ - ("id", lambda row: row["id"]), - ("name", lambda row: row["name"]), - ("type", lambda row: row["kind"]), - ("size", lambda row: f"{row['size']} GB" if "size" in row else None), - ("data center", lambda row: row.get("dataCenter")), - ("tier", lambda row: (row.get("type") or "").lower()), - ] - print_table( - rows, - [(label.upper(), value) for label, value in fields], - ( - "volume inventory unavailable" - if failures - else "no volumes. create one with rp volume create" - ), - ) - if failures: - raise click.ClickException( - "incomplete volume inventory. " + ". ".join(failures) - ) - - -@volume.command(name="get") -@click.argument("volume_id", required=False, shell_complete=_complete_ids) -@global_option -@json_option -def volume_get(volume_id, kind, as_json): - """Show one volume (pick one when VOLUME_ID is omitted).""" - with api_errors(): - if volume_id is None: - volume_id = pick("volume", _choices(kind), "pass VOLUME_ID") - kind, record = _get_volume(volume_id, kind) - _show(record, kind, as_json) - - -@volume.command(name="create") -@click.option("--name", required=True, help="Human-readable name.") -@click.option( - "--size", - type=click.IntRange(10, 4096), - help="Storage in GB (10-4096). Required for network volumes.", -) -@click.option( - "--region", - "regions", - multiple=True, - help="Region (eu, na), id prefix (us, eu-ro), or data center id. Repeatable.", -) -@click.option("--data-center", help="Exact data center id, like EU-RO-1.") -@click.option( - "--type", - "kind", - type=click.Choice(["network", "global"], case_sensitive=False), - default="network", - show_default=True, - help="Storage type. Global volumes mount in any data center.", -) -@click.option( - "--tier", - "volume_type", - type=click.Choice(["standard", "high_performance"], case_sensitive=False), - help="Storage tier, immutable after creation. Defaults to the data center's " - "primary tier.", -) -@json_option -def volume_create(name, size, regions, data_center, volume_type, kind, as_json): - """Create a network volume in one data center, or a global volume. - - A region matching several data centers narrows to those offering - the requested --tier, then prompts for one. - - \b - rp volume create --name models --size 100 --region eu - rp volume create --name scratch --size 50 --data-center EU-RO-1 - rp volume create --name shared --type global - """ - kind = kind.lower() - body = {"name": name} - with api_errors(): - if kind == "global": - given = [ - flag - for flag, value in ( - ("--size", size), - ("--region", regions), - ("--data-center", data_center), - ("--tier", volume_type), - ) - if value - ] - if given: - raise click.UsageError( - f"{', '.join(given)} do not apply to global volumes" - ) - else: - if size is None: - raise click.UsageError("pass --size in GB for a network volume") - if regions and data_center: - raise click.UsageError("use either --region or --data-center") - volume_type = volume_type.upper() if volume_type else None - body.update( - size=size, - dataCenter=data_center or _data_center(regions, volume_type), - ) - if volume_type: - body["type"] = volume_type - record = run_rest_request("POST", f"/v2/{kind}-volumes", json=body) - _show(record, kind, as_json, "created") - - -@volume.command(name="update") -@click.argument("volume_id", shell_complete=_complete_ids) -@click.option("--name", help="New name.") -@click.option( - "--size", - type=click.IntRange(10, 4096), - help="New size in GB; network volumes can only grow.", -) -@global_option -@json_option -def volume_update(volume_id, name, size, kind, as_json): - """Rename and/or resize a volume.""" - if kind == "global" and size is not None: - raise click.UsageError("global volumes have no size to change") - body = { - key: value - for key, value in (("name", name), ("size", size)) - if value is not None - } - if not body: - raise click.UsageError("pass --name and/or --size") - with api_errors(): - if size is not None: - _growth(volume_id, size) - kind = "network" - elif kind is None: - kind, _ = _get_volume(volume_id) - record = run_rest_request( - "PATCH", f"/v2/{kind}-volumes/{_path_segment(volume_id)}", json=body - ) - _show(record, kind, as_json, "updated") - - -@volume.command(name="expand") -@click.argument("volume_id", shell_complete=_complete_ids) -@click.option( - "--size", - required=True, - metavar="N|+N", - help="New total size in GB, or +N to add N GB.", -) -@json_option -def volume_expand(volume_id, size, as_json): - """Grow a network volume; storage can never shrink.""" - with api_errors(): - current, target = _growth(volume_id, size, expand=True) - record = run_rest_request( - "PATCH", - f"/v2/network-volumes/{_path_segment(volume_id)}", - json={"size": target}, - ) - if as_json: - print_json(record) - else: - ui.success( - f"expanded [white]{volume_id}[/white] from {current} GB to {record['size']} GB" - ) - - -@volume.command(name="delete") -@click.argument("volume_id", shell_complete=_complete_ids) -@click.option("--yes", "-y", is_flag=True, help="Skip the confirmation prompt.") -@global_option -def volume_delete(volume_id, yes, kind): - """Delete a volume and everything stored on it.""" - with api_errors(): - if kind is None or not yes: - kind, record = _get_volume(volume_id, kind) - path = f"/v2/{kind}-volumes/{_path_segment(volume_id)}" - if not yes: - confirm( - f"delete {kind} volume {volume_id} ({_label(record)}) and all its data?", - yes, - ) - run_rest_request("DELETE", path) - ui.success(f"deleted {kind} volume [white]{volume_id}[/white]") - - -def _transfer_options(func): - options = [ - click.option("--s3-access-key", default=None, help="S3 API access key."), - click.option("--s3-secret-key", default=None, help="S3 API secret key."), - click.option("--endpoint-url", default=None, hidden=True), - click.option( - "--concurrency", - default=4, - show_default=True, - type=click.IntRange(1, 64), - help="Parallel requests.", - ), - click.option( - "--force", - is_flag=True, - help="Transfer every file, even ones the size and time check calls unchanged.", - ), - ] - for option in reversed(options): - func = option(func) - return func - - -class _ProgressRenderer: - """draws one bar per file in flight and prints each finished file.""" - - def __init__(self, bar, action_label): - self._bar = bar - self._action_label = action_label - self._tasks = {} - - def __call__(self, event, path, nbytes): - if event == "start": - self._tasks[path] = self._bar.add_task(Path(path).name, total=nbytes) - return - task = self._tasks.get(path) - if task is None: - return - if event in ("advance", "reuse"): - self._bar.advance(task, nbytes) - elif event == "done": - self._bar.remove_task(self._tasks.pop(path)) - self._bar.console.print(f" {self._action_label} {path}") - - -def _progress_bar(): - from rich.console import Console - from rich.progress import ( - BarColumn, - DownloadColumn, - Progress, - TextColumn, - TransferSpeedColumn, - ) - - return Progress( - TextColumn("{task.description}"), - BarColumn(), - DownloadColumn(), - TransferSpeedColumn(), - console=Console(stderr=True), - transient=True, - ) - - -def _cli_error(exc: Exception) -> click.ClickException: - """a transfer failure as a cli error, with a resume hint when re-running - would resume.""" - from botocore.exceptions import EndpointConnectionError - - import runpod.network_volume_transfer as nvt - - hint = "\nre-run the same command to resume" if nvt.is_resumable(exc) else "" - if isinstance(exc, EndpointConnectionError): - hint = ( - "\nif the volume's datacenter does not support the s3 api yet, " - f"see {nvt.S3_DOCS_URL}; otherwise re-run the same command to resume" - ) - return click.ClickException(f"{exc}{hint}") - - -def _invoke_transfer(transfer_method, source, target, opts, progress, retry_keys): - """run the transfer, turning failures into cli errors. a rejection of - saved keys propagates when `retry_keys`, so the caller can prompt.""" - import runpod.network_volume_transfer as nvt - - try: - return transfer_method( - source, - target, - access_key=opts["s3_access_key"], - secret_key=opts["s3_secret_key"], - endpoint_url=opts["endpoint_url"], - concurrency=opts["concurrency"], - progress=progress, - force=opts["force"], - ) - except KeyboardInterrupt: - click.echo("interrupted; re-run the same command to resume", err=True) - raise SystemExit(130) from None - except Exception as exc: # noqa: BLE001 - surface transfer errors cleanly - if retry_keys and isinstance(exc, nvt.RejectedS3Keys): - raise - raise _cli_error(exc) from exc - - -def _run_transfer(action_label, transfer_method, source, target, opts) -> None: - import runpod.network_volume_transfer as nvt - - retry_keys = bool(opts.get("_saved_keys")) and _interactive() - while True: - try: - with _progress_bar() as bar: - summary = _invoke_transfer( - transfer_method, - source, - target, - opts, - _ProgressRenderer(bar, action_label), - retry_keys, - ) - break - except nvt.RejectedS3Keys as exc: - # the bar is closed here, so the prompts draw cleanly - retry_keys = False - if not click.confirm( - "saved s3 keys were rejected. enter a new pair?", default=True - ): - raise _cli_error(exc) from exc - try: - opts["s3_access_key"], opts["s3_secret_key"] = _prompt_s3_keys() - except (click.ClickException, click.Abort): - raise - except Exception as save_exc: # noqa: BLE001 - saving can fail - raise _cli_error(save_exc) from save_exc - click.echo( - f"{action_label} {summary['files_transferred']} file(s), " - f"{summary['bytes_transferred']} bytes; " - f"skipped {summary['files_skipped']} unchanged" - ) - - -def _interactive() -> bool: - return sys.stdin.isatty() and sys.stdout.isatty() - - -def _ensure_logged_in(ctx) -> None: - """offer the browser login when no api key is set; the volume lookup - needs one.""" - import runpod - import runpod.network_volume_transfer as nvt - from runpod.cli.groups.config.functions import get_credentials - from runpod.rp_cli.main import login - - if runpod.api_key: - return - if not _interactive() or not click.confirm( - "you are not logged in to runpod. log in now?", default=True - ): - raise click.ClickException(nvt.NOT_LOGGED_IN) - ctx.invoke(login, no_open=False, api_key_opt=None, profile=runpod.profile) - runpod.api_key = (get_credentials(runpod.profile) or {}).get("api_key") - if not runpod.api_key: - raise click.ClickException(nvt.NOT_LOGGED_IN) - - -def _pick_volume() -> str: - """let the user choose one of their network volumes by number.""" - import runpod.network_volume_transfer as nvt - - if not _interactive(): - raise click.UsageError("pass VOLUME first (a network volume id or name)") - try: - volumes = nvt._list_volumes() - except nvt.NetworkVolumeTransferError as exc: - raise click.ClickException(str(exc)) from exc - if not volumes: - raise click.ClickException( - "no network volumes yet: create one at https://console.runpod.io/user/storage" - ) - for number, vol in enumerate(volumes, 1): - datacenter = vol.get("dataCenterId") or vol.get("dataCenter") - click.echo( - f" {number}. {vol['name']} {vol['id']} {vol.get('size')} GB {datacenter}" - ) - choice = click.prompt("volume", type=click.IntRange(1, len(volumes))) - return volumes[choice - 1]["id"] - - -def _missing_keys_message() -> str: - import runpod.network_volume_transfer as nvt - - return ( - "s3 api keys required (separate from your api key): set " - f"{nvt.ACCESS_KEY_ENV} and {nvt.SECRET_KEY_ENV} or pass --s3-access-key " - f"and --s3-secret-key (create keys at {nvt.S3_KEYS_URL})" - ) - - -def _prompt_s3_keys(): - """ask for the s3 keys, offering to save them for next time.""" - import runpod - import runpod.network_volume_transfer as nvt - from runpod.cli.groups.config.functions import set_s3_keys - - if not _interactive(): - raise click.ClickException(_missing_keys_message()) - click.echo( - "network volume transfers use s3 api keys, separate from your api key.\n" - f"create a pair at {nvt.S3_KEYS_URL} (s3 api keys)." - ) - access = click.prompt("s3 access key") - secret = click.prompt("s3 secret key", hide_input=True) - if click.confirm("save them to ~/.runpod/config.toml?", default=True): - set_s3_keys(access, secret, profile=runpod.profile) - return access, secret - - -def _ensure_s3_keys(opts) -> None: - """fill in the s3 keys from the flags, the environment, or the saved - config, prompting for them when none are set.""" - import runpod.network_volume_transfer as nvt - - explicit = bool(opts["s3_access_key"] and opts["s3_secret_key"]) - env = bool( - os.environ.get(nvt.ACCESS_KEY_ENV) and os.environ.get(nvt.SECRET_KEY_ENV) - ) - keys = nvt.find_s3_keys(opts["s3_access_key"], opts["s3_secret_key"]) - opts["_saved_keys"] = bool(keys and not explicit and not env) - opts["s3_access_key"], opts["s3_secret_key"] = keys or _prompt_s3_keys() - - -def _split_args(args, second: str, third: str): - """[VOLUME] SECOND [THIRD]: a lone argument is SECOND, and the volume is - picked interactively.""" - if not 1 <= len(args) <= 3: - raise click.UsageError(f"expected [VOLUME] {second} [{third}]") - if len(args) == 1: - return None, args[0], None - return args[0], args[1], args[2] if len(args) == 3 else None - - -def _transfer(ctx, action_label, method_name, reference, source, target, opts) -> None: - """the checks every transfer needs, in order: login, volume, s3 keys.""" - import runpod.network_volume_transfer as nvt - from runpod.apps import NetworkVolume - from runpod.apps.volume import VolumeError - from runpod.user_agent import USER_AGENT - - _ensure_logged_in(ctx) - reference = reference or _pick_volume() - try: - target_volume = NetworkVolume(reference, create=False) - target_volume._user_agent = USER_AGENT - # the volume caches this lookup, so the transfer does not repeat it - target_volume._s3_location(opts["endpoint_url"]) - except (nvt.NetworkVolumeTransferError, VolumeError) as exc: - raise click.ClickException(str(exc)) from exc - _ensure_s3_keys(opts) - method = getattr(target_volume, method_name) - _run_transfer(action_label, method, source, target, opts) - - -@volume.command(name="upload") -@click.argument( - "args", nargs=-1, required=True, metavar="[VOLUME] LOCAL_PATH [REMOTE_PATH]" -) -@_transfer_options -@click.pass_context -def volume_upload(ctx, args, **opts): - """Upload a file or folder to a network volume. - - VOLUME is the volume's id or name. Give only LOCAL_PATH to pick the - volume from a list. REMOTE_PATH defaults to the local name. A folder's - contents go under REMOTE_PATH/. - Files whose remote copy has the same size and is not older are skipped; - --force sends them anyway. - """ - reference, local_path, remote_path = _split_args(args, "LOCAL_PATH", "REMOTE_PATH") - if not Path(local_path).exists(): - raise click.UsageError(f"local path {local_path} does not exist") - _transfer(ctx, "uploaded", "upload", reference, local_path, remote_path, opts) +"""shared command-line helpers.""" +import sys -@volume.command(name="download") -@click.argument( - "args", nargs=-1, required=True, metavar="[VOLUME] REMOTE_PATH [LOCAL_PATH]" -) -@_transfer_options -@click.pass_context -def volume_download(ctx, args, **opts): - """Download a file or folder from a network volume. +from runpod.cli import volume - VOLUME is the volume's id or name. Give only REMOTE_PATH to pick the - volume from a list. A REMOTE_PATH ending in / is a folder. LOCAL_PATH defaults to the remote - name. Local files of the same size and not older than the remote copy - are skipped; --force fetches them anyway. - """ - reference, remote_path, local_path = _split_args(args, "REMOTE_PATH", "LOCAL_PATH") - _transfer(ctx, "downloaded", "download", reference, remote_path, local_path, opts) +sys.modules[__name__] = volume diff --git a/runpod/serverless/__init__.py b/runpod/serverless/__init__.py index d5132eb31..3603d0144 100644 --- a/runpod/serverless/__init__.py +++ b/runpod/serverless/__init__.py @@ -16,8 +16,10 @@ from . import worker from .modules.rp_fitness import register_fitness_check from .modules.rp_logger import RunPodLogger -from .modules.rp_prestart import has_prestart_hooks as _has_prestart_hooks -from .modules.rp_prestart import register_prestart_hook +from .modules.rp_prestart import ( + has_prestart_hooks as _has_prestart_hooks, + register_prestart_hook, +) from .modules.rp_progress import progress_update from .utils.rp_volume_cache import VolumeCache diff --git a/runpod/serverless/modules/rp_fastapi.py b/runpod/serverless/modules/rp_fastapi.py index 56c6c6d84..e63ea7311 100644 --- a/runpod/serverless/modules/rp_fastapi.py +++ b/runpod/serverless/modules/rp_fastapi.py @@ -359,12 +359,13 @@ async def _sim_runsync(self, job_request: DefaultRequest) -> JobOutput: if is_generator(self.config["handler"]): generator_output = run_job_generator(self.config["handler"], job.__dict__) - job_output = {"output": []} + aggregate: list[object] = [] + job_output: dict[str, object] = {"output": aggregate} async for stream_output in generator_output: if stream_output.get("error"): job_output = stream_output break - job_output["output"].append(stream_output["output"]) + aggregate.append(stream_output["output"]) else: job_output = await run_job(self.config["handler"], job.__dict__) @@ -442,12 +443,13 @@ async def _sim_status(self, job_id: str) -> JobOutput: if is_generator(self.config["handler"]): generator_output = run_job_generator(self.config["handler"], job.__dict__) - job_output = {"output": []} + aggregate: list[object] = [] + job_output: dict[str, object] = {"output": aggregate} async for stream_output in generator_output: if stream_output.get("error"): job_output = stream_output break - job_output["output"].append(stream_output["output"]) + aggregate.append(stream_output["output"]) else: job_output = await run_job(self.config["handler"], job.__dict__) diff --git a/runpod/serverless/modules/rp_fitness.pyi b/runpod/serverless/modules/rp_fitness.pyi new file mode 100644 index 000000000..e6a66f4fc --- /dev/null +++ b/runpod/serverless/modules/rp_fitness.pyi @@ -0,0 +1,33 @@ +from runpod._health.fitness import ( + _CHECK_CONFIG_DEPENDENCIES as _CHECK_CONFIG_DEPENDENCIES, + _CONFIG_ENV_VARS as _CONFIG_ENV_VARS, + _REPORT_TIMEOUT_SECONDS as _REPORT_TIMEOUT_SECONDS, + DEFER_FITNESS_CHECKS_ENV as DEFER_FITNESS_CHECKS_ENV, + EARLY_CHECKS_DONE_ENV as EARLY_CHECKS_DONE_ENV, + SKIP_FITNESS_CHECKS_ENV as SKIP_FITNESS_CHECKS_ENV, + _completed_checks as _completed_checks, + _config_snapshot as _config_snapshot, + _ensure_gpu_check_registered as _ensure_gpu_check_registered, + _ensure_system_checks_registered as _ensure_system_checks_registered, + _env_flag as _env_flag, + _event_loop_running as _event_loop_running, + _fail_worker as _fail_worker, + _fitness_checks as _fitness_checks, + _invoke_check as _invoke_check, + _is_deferred as _is_deferred, + _is_shared_check as _is_shared_check, + _refresh_late_config as _refresh_late_config, + _register_builtins as _register_builtins, + _registration_state as _registration_state, + _report_unhealthy as _report_unhealthy, + _reset_registration_state as _reset_registration_state, + _terminate_unhealthy as _terminate_unhealthy, + _worker_start_completed_checks as _worker_start_completed_checks, + clear_fitness_checks as clear_fitness_checks, + defer_to_worker_start as defer_to_worker_start, + log as log, + recheck_at_worker_start as recheck_at_worker_start, + register_fitness_check as register_fitness_check, + run_fitness_checks as run_fitness_checks, + run_startup_fitness_checks as run_startup_fitness_checks, +) diff --git a/runpod/serverless/modules/rp_job.py b/runpod/serverless/modules/rp_job.py index 9cc18a012..ec9ab922b 100644 --- a/runpod/serverless/modules/rp_job.py +++ b/runpod/serverless/modules/rp_job.py @@ -66,7 +66,7 @@ async def get_stop_signals(session: ClientSession) -> list[str]: response.request_info, response.history, status=response.status, - message=response.reason, + message=response.reason or "", ) response.raise_for_status() @@ -147,18 +147,18 @@ async def get_job( if response.status == 204: log.debug("rp_job | Received 204 status, no jobs.") - return + return None if response.status == 400: log.debug("rp_job | Received 400 status, expected when FlashBoot is enabled.") - return + return None if response.status == 429: raise TooManyRequests( response.request_info, response.history, status=response.status, - message=response.reason + message=response.reason or "", ) # All other errors should raise an exception @@ -167,22 +167,22 @@ async def get_job( # Verify if the content type is JSON if response.content_type != "application/json": log.debug(f"rp_job | Unexpected content type: {response.content_type}") - return + return None # Check if there is a non-empty content to parse if response.content_length == 0: log.debug("rp_job | No content to parse.") - return + return None try: jobs = await response.json() log.debug("rp_job | Received Job(s)") except aiohttp.ContentTypeError: log.debug(f"rp_job | Response content is not valid JSON. {response.content}") - return + return None except ValueError as json_error: log.debug(f"rp_job | Failed to parse JSON response: {json_error}") - return + return None # legacy job-take API if isinstance(jobs, dict): @@ -194,6 +194,8 @@ async def get_job( if isinstance(jobs, list): return [_with_default_input(job) for job in jobs] + return None + def _with_default_input(job: Any) -> Any: """Give a job that arrived without an input an empty one. @@ -226,13 +228,14 @@ async def handle_job( generator_output = run_job_generator(config["handler"], job) log.debug("Handler is a generator, streaming results.", job["id"]) - job_result = {"output": []} + job_result: dict[str, Any] = {"output": []} async for stream_output in generator_output: log.debug(f"Stream output: {stream_output}", job["id"]) - if isinstance(stream_output.get("output"), dict): - if stream_output["output"].get("error"): - stream_output = {"error": str(stream_output["output"]["error"])} + output = stream_output.get("output") + if isinstance(output, dict): + if output.get("error"): + stream_output = {"error": str(output["error"])} if stream_output.get("error"): job_result = stream_output @@ -268,7 +271,7 @@ async def handle_job( if inspect.isawaitable(callback_result): # Await the callback's coroutine for its side effects (freeing the # slot, draining earlier uploads); it resolves to None. - callback_result = await callback_result + await callback_result # Send the job result back to JOB_DONE_URL await send_result(session, job_result, job, is_stream=is_stream) @@ -287,7 +290,7 @@ async def run_job(handler: Callable, job: dict[str, Any]) -> dict[str, Any]: Dict[str, Any]: The result of running the job. """ log.info("Started.", job["id"]) - run_result = {} + run_result: dict[str, object] = {} with capture(enabled=handler_capture_enabled()) as cap: try: diff --git a/runpod/serverless/modules/rp_logger.pyi b/runpod/serverless/modules/rp_logger.pyi new file mode 100644 index 000000000..17d520b69 --- /dev/null +++ b/runpod/serverless/modules/rp_logger.pyi @@ -0,0 +1,10 @@ +from runpod._logger import ( + LOG_LEVELS as LOG_LEVELS, + MAX_MESSAGE_LENGTH as MAX_MESSAGE_LENGTH, + TIP_LEVEL as TIP_LEVEL, + RunPodLogger as RunPodLogger, + _batch_id as _batch_id, + _reset_batch_id as _reset_batch_id, + _set_batch_id as _set_batch_id, + _validate_log_level as _validate_log_level, +) diff --git a/runpod/serverless/modules/rp_prestart.py b/runpod/serverless/modules/rp_prestart.py index 2f5520664..c406ce209 100644 --- a/runpod/serverless/modules/rp_prestart.py +++ b/runpod/serverless/modules/rp_prestart.py @@ -16,7 +16,7 @@ import threading import traceback from collections.abc import Callable, Sequence -from typing import Any +from typing import Any, Protocol from runpod.serverless.modules.rp_capture import ( MAX_CAPTURED_CHARS, @@ -157,7 +157,13 @@ def worker(): return results[0] if results else None -async def _invoke_hook(hook: Callable[[], Any]) -> None: +class _PrestartHook(Protocol): + + def __call__(self) -> object: + raise NotImplementedError + + +async def _invoke_hook(hook: _PrestartHook) -> None: if inspect.iscoroutinefunction(hook) or inspect.iscoroutinefunction(hook.__call__): result = hook() else: diff --git a/runpod/serverless/modules/rp_scale.py b/runpod/serverless/modules/rp_scale.py index 2041b0915..e82680998 100644 --- a/runpod/serverless/modules/rp_scale.py +++ b/runpod/serverless/modules/rp_scale.py @@ -102,7 +102,9 @@ def __init__(self, config: dict[str, Any]): self.stop_signals_fetcher = get_stop_signals self.stop_signals_fetcher_timeout = 90 - self.jobs_queue = asyncio.Queue(maxsize=self.current_concurrency) + self.jobs_queue: asyncio.Queue[dict[str, Any]] = asyncio.Queue( + maxsize=self.current_concurrency + ) self.concurrency_modifier = _default_concurrency_modifier self.jobs_fetcher = get_job @@ -571,7 +573,11 @@ async def stop_job(self, job_id: str) -> bool: log.info("Stopping job.", job_id) self._stopped_jobs.add(job_id) - if inspect.getcoroutinestate(task.get_coro()) == inspect.CORO_CREATED: + coro = task.get_coro() + if ( + inspect.iscoroutine(coro) + and inspect.getcoroutinestate(coro) == inspect.CORO_CREATED + ): # Cancelling a task before its first step skips handle_job's # try/finally entirely; handle_job checks _stopped_jobs on entry. return True diff --git a/runpod/serverless/utils/rp_debugger.py b/runpod/serverless/utils/rp_debugger.py index a35c7092d..f2101db91 100644 --- a/runpod/serverless/utils/rp_debugger.py +++ b/runpod/serverless/utils/rp_debugger.py @@ -8,6 +8,7 @@ import functools import platform import time +from typing import NotRequired, TypedDict # ---------------------------------------------------------------------------- # # System Info # @@ -33,6 +34,15 @@ def get_processor_info(): PYTHON_VERSION = platform.python_version() +class _Checkpoint(TypedDict): + name: str + start: NotRequired[float] + start_utc: NotRequired[str] + end: NotRequired[float] + stop_utc: NotRequired[str] + duration_ms: NotRequired[float] + + class Checkpoints: """ A singleton class to store checkpoint times. @@ -63,8 +73,8 @@ class Checkpoints: """ __instance = None - checkpoints = [] - name_lookup = {} + checkpoints: list[_Checkpoint] = [] + name_lookup: dict[str, int] = {} def __new__(cls): if Checkpoints.__instance is None: diff --git a/runpod/serverless/utils/rp_download.py b/runpod/serverless/utils/rp_download.py index 79adfe2e8..46bdf875f 100644 --- a/runpod/serverless/utils/rp_download.py +++ b/runpod/serverless/utils/rp_download.py @@ -11,6 +11,7 @@ import shutil import uuid import zipfile +from collections.abc import Sequence from concurrent.futures import ThreadPoolExecutor from urllib.parse import urlparse @@ -132,7 +133,9 @@ def extract_disposition_params(content_disposition: str) -> dict[str, str]: return params -def download_files_from_urls(job_id: str, urls: str | list[str]) -> list[str]: +def download_files_from_urls( + job_id: str, urls: str | Sequence[str | None] +) -> list[str | None]: """ Accepts a single URL or a list of URLs and downloads the files. Returns the list of downloaded file absolute paths. @@ -168,7 +171,7 @@ def download_file(url: str, path_to_save: str) -> str: return file_extension - def download_file_to_path(url: str) -> str: + def download_file_to_path(url: str | None) -> str | None: if url is None: return None diff --git a/runpod/serverless/utils/rp_ssrf.py b/runpod/serverless/utils/rp_ssrf.py index 96335f769..0fcfeff80 100644 --- a/runpod/serverless/utils/rp_ssrf.py +++ b/runpod/serverless/utils/rp_ssrf.py @@ -116,6 +116,8 @@ def resolve_and_validate(host: str, port: int) -> list[str]: ips: list[str] = [] for info in infos: ip = info[4][0] + if not isinstance(ip, str): + raise SSRFError(f"unexpected address resolved for host {host!r}") if ip not in ips: ips.append(ip) diff --git a/runpod/serverless/utils/rp_validator.py b/runpod/serverless/utils/rp_validator.py index 5a66e18e5..a7fb6b05d 100644 --- a/runpod/serverless/utils/rp_validator.py +++ b/runpod/serverless/utils/rp_validator.py @@ -102,7 +102,7 @@ def validate( or {"validated_input": {"input1": "value1", "input2": "value2"} """ - error_list = [] + error_list: list[str] = [] validated_input = raw_input.copy() # Separate the process into functions for better readability @@ -113,7 +113,9 @@ def validate( ) _validate_input_against_schema(schema, validated_input, error_list) - validation_return = {"validated_input": validated_input} + validation_return: dict[str, dict[str, Any] | list[str]] = { + "validated_input": validated_input + } if error_list: validation_return = {"errors": error_list} diff --git a/runpod/serverless/utils/rp_volume_cache.py b/runpod/serverless/utils/rp_volume_cache.py index 7584bfc4b..5d620dfbe 100644 --- a/runpod/serverless/utils/rp_volume_cache.py +++ b/runpod/serverless/utils/rp_volume_cache.py @@ -1088,7 +1088,7 @@ def _fsync_dir(path): # background sync completion # ----------------------------------------------------------------------- # -_pending_syncs = [] +_pending_syncs: list[threading.Thread] = [] def _register_pending(thread): diff --git a/setup.py b/setup.py index dfbb6c74b..35b567aec 100644 --- a/setup.py +++ b/setup.py @@ -66,8 +66,8 @@ }, entry_points={ "console_scripts": [ - "runpod = runpod.rp_cli.main:run", - "rp = runpod.rp_cli.main:run", + "runpod = runpod.cli.main:run", + "rp = runpod.cli.main:run", ] }, keywords=[ diff --git a/tests/test_api/test_connection_replay.py b/tests/test_api/test_connection_replay.py new file mode 100644 index 000000000..01aa6a421 --- /dev/null +++ b/tests/test_api/test_connection_replay.py @@ -0,0 +1,111 @@ +"""connection failure types and replay boundaries.""" + +import socket +import ssl +from unittest.mock import AsyncMock + +import aiohttp +import pytest +from aiohttp import web +from aiohttp.client_reqrep import ConnectionKey + +from runpod.api.http import HTTPClient +from runpod.api.rest import AsyncRESTClient +from runpod.api.routes import Route + + +@pytest.mark.parametrize("method", ["PUT", "DELETE"]) +@pytest.mark.parametrize( + "error_type,cause", + [ + (aiohttp.ClientConnectorError, OSError("connection failed")), + (aiohttp.ClientConnectorDNSError, socket.gaierror("name lookup failed")), + (aiohttp.ClientSSLError, ssl.SSLError("TLS negotiation failed")), + ( + aiohttp.ClientConnectorCertificateError, + ssl.CertificateError("invalid certificate"), + ), + ], +) +async def test_connector_failures_preserve_type_and_details( + monkeypatch, method, error_type, cause +): + key = ConnectionKey("synthetic.invalid", 443, True, True, None, None, None) + failure = error_type(key, cause) + async with aiohttp.ClientSession() as session: + connect = AsyncMock(side_effect=failure) + monkeypatch.setattr(session.connector, "connect", connect) + async with AsyncRESTClient( + "synthetic-key", base_url="https://synthetic.invalid", session=session + ) as client: + with pytest.raises(error_type) as caught: + await client.request(Route(method, "/work")) + assert caught.value is failure + assert isinstance(caught.value, OSError) + assert caught.value.host == "synthetic.invalid" + assert caught.value.port == 443 + if error_type is aiohttp.ClientConnectorCertificateError: + assert caught.value.certificate_error is cause + else: + assert caught.value.os_error is cause + connect.assert_awaited_once() + assert not session.closed + + +@pytest.fixture +async def disconnect_server(): + requests = [] + + async def handler(request): + await request.read() + requests.append((request.method, request.transport)) + if len(requests) == 2: + request.transport.close() + return web.json_response({"ok": True}) + + app = web.Application() + app.router.add_route("*", "/{path:.*}", handler) + runner = web.AppRunner(app) + await runner.setup() + site = web.TCPSite(runner, "127.0.0.1", 0) + await site.start() + port = site._server.sockets[0].getsockname()[1] + try: + yield f"http://127.0.0.1:{port}", requests + finally: + await runner.cleanup() + + +@pytest.mark.parametrize("method", ["GET", "POST", "PUT", "DELETE"]) +@pytest.mark.parametrize("rest", [True, False]) +async def test_only_reads_replay_after_keep_alive_disconnect( + disconnect_server, method, rest +): + base, requests = disconnect_server + calls = [] + + async def middleware(request, handler): + calls.append(request.method) + return await handler(request) + + async with aiohttp.ClientSession(middlewares=(middleware,)) as session: + retry_policy = session._retry_connection + client = ( + AsyncRESTClient("synthetic-key", base_url=base, session=session) + if rest + else HTTPClient(base, session=session) + ) + async with client: + assert await client.request(Route("GET", "/warm")) == {"ok": True} + if method == "GET": + assert await client.request(Route(method, "/work")) == {"ok": True} + else: + with pytest.raises(aiohttp.ClientConnectionError): + await client.request(Route(method, "/work")) + assert not session.closed + assert session._retry_connection is retry_policy + assert calls == (["GET", "GET", "GET"] if method == "GET" else ["GET", method]) + assert [request[0] for request in requests] == calls + assert requests[0][1] is requests[1][1] + if method == "GET": + assert requests[2][1] is not requests[1][1] diff --git a/tests/test_api/test_http.py b/tests/test_api/test_http.py new file mode 100644 index 000000000..00f13130c --- /dev/null +++ b/tests/test_api/test_http.py @@ -0,0 +1,295 @@ +"""shared transport ownership, route resolution, and credential boundaries.""" + +import asyncio +import json +import threading +from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer + +import aiohttp +import pytest +import requests + +import runpod +from runpod.api.http import HTTPClient, SyncHTTPClient +from runpod.api.rest import AsyncRESTClient, RESTClient +from runpod.api.routes import ( + Route, + endpoint_base_url, + host_api_base_url, + load_balancer_base_url, + pod_proxy_base_url, +) + + +@pytest.fixture +def http_server(): + state = {"requests": [], "status": 200, "body": b'{"ok":true}'} + + class Handler(BaseHTTPRequestHandler): + protocol_version = "HTTP/1.1" + + def do_GET(self): + body = self.rfile.read(int(self.headers.get("Content-Length", 0))) + state["requests"].append( + (self.command, self.path, dict(self.headers), body, self.client_address) + ) + payload = state["body"] + self.send_response(state["status"]) + self.send_header("Content-Type", "application/json") + self.send_header("Content-Length", str(len(payload))) + self.send_header("Set-Cookie", "session=should-not-be-replayed") + self.send_header("Location", "/redirect-target") + self.end_headers() + self.wfile.write(payload) + + do_POST = do_PUT = do_GET + + def log_message(self, *args): + pass + + server = ThreadingHTTPServer(("127.0.0.1", 0), Handler) + worker = threading.Thread(target=server.serve_forever, daemon=True) + worker.start() + try: + yield f"http://127.0.0.1:{server.server_port}/prefix/", state + finally: + server.shutdown() + server.server_close() + worker.join() + + +def test_route_encodes_parameters_and_preserves_service_prefix(): + route = Route("get", "/v2/pods/{pod_id}", pod_id="id/with ?#%") + assert route.method == "GET" + assert route.url("https://api.example/base/") == ( + "https://api.example/base/v2/pods/id%2Fwith%20%3F%23%25" + ) + + +@pytest.mark.parametrize( + "path", ["https://other.example/x", "//other.example/x", "../x", "/x#secret"] +) +def test_route_cannot_override_service_origin(path): + with pytest.raises(ValueError): + Route("GET", path).url("https://api.example/prefix") + + +@pytest.mark.parametrize( + "base", ["file:///tmp/data", "https://user:password@example.com", "relative"] +) +def test_route_requires_http_origin_without_credentials(base): + with pytest.raises(ValueError): + Route("GET", "/v2/pods").url(base) + + +def test_signed_upload_url_is_preserved_exactly(): + url = "https://storage.example/artifact?signature=a%2Fb&expires=123" + assert Route("PUT", "").url(url) == url + with pytest.raises(ValueError): + Route("PUT", "/another").url(url) + + +def test_route_encodes_literal_spaces_without_requoting_parameters(): + assert ( + Route("GET", "/hello world/{value}?q=a b", value="a/b").url( + "https://api.example/base path/" + ) + == "https://api.example/base%20path/hello%20world/a%2Fb?q=a%20b" + ) + + +def test_service_bases_respect_configuration(monkeypatch): + monkeypatch.delenv("RUNPOD_ENDPOINT_BASE_URL", raising=False) + monkeypatch.delenv("RUNPOD_PROXY_DOMAIN", raising=False) + monkeypatch.setenv("RUNPOD_API_BASE_URL", "http://control.example/prefix/") + monkeypatch.setenv("RUNPOD_HAPI_URL", "http://logs.example/prefix/") + monkeypatch.setattr(runpod, "endpoint_url_base", "http://worker.example:8080/v2/") + assert Route("POST", "/graphql").url() == "http://control.example/prefix/graphql" + assert host_api_base_url() == "http://logs.example/prefix" + assert ( + endpoint_base_url("endpoint/id") + == "http://worker.example:8080/v2/endpoint%2Fid" + ) + assert ( + load_balancer_base_url("endpoint-id") + == "http://endpoint-id.worker.example:8080" + ) + assert pod_proxy_base_url("pod-id", 8080) == "https://pod-id-8080.proxy.runpod.net" + + +@pytest.mark.parametrize( + "resource_id", ["other.example/", "id@evil.example", "id:123", ""] +) +def test_resource_hostnames_reject_url_components(resource_id): + with pytest.raises(ValueError): + load_balancer_base_url(resource_id) + with pytest.raises(ValueError): + pod_proxy_base_url(resource_id, 8080) + + +async def test_async_client_reuses_and_closes_owned_session(http_server): + base, state = http_server + client = HTTPClient(base) + async with client: + session = client.session + assert await client.request(Route("GET", "/first")) == {"ok": True} + assert await client.request(Route("GET", "/second")) == {"ok": True} + assert client.session is session + assert not session.closed + assert session.closed + assert client.session is None + assert state["requests"][0][4] == state["requests"][1][4] + assert all("Cookie" not in request[2] for request in state["requests"]) + + +async def test_borrowed_async_session_is_not_closed(http_server): + base, state = http_server + async with aiohttp.ClientSession(headers={"User-Agent": "caller-agent"}) as session: + async with HTTPClient(base, session=session) as client: + assert await client.request(Route("GET", "/pods")) == {"ok": True} + assert not session.closed + assert state["requests"][0][2]["User-Agent"] == "caller-agent" + + +async def test_concurrent_one_shot_calls_have_independent_lifetimes(http_server): + base, state = http_server + client = HTTPClient(base) + results = await asyncio.gather( + *(client.request(Route("GET", "/{index}", index=index)) for index in range(4)) + ) + assert results == [{"ok": True}] * 4 + assert len(state["requests"]) == 4 + assert client.session is None + + +async def test_raw_transport_never_reads_account_credentials(http_server, monkeypatch): + base, state = http_server + monkeypatch.setattr(runpod, "api_key", "account-secret") + monkeypatch.setenv("RUNPOD_API_KEY", "environment-secret") + client = HTTPClient(base) + await client.request(Route("GET", "/anonymous")) + await client.request( + Route("GET", "/worker"), headers={"Authorization": "Bearer task-token"} + ) + assert "Authorization" not in state["requests"][0][2] + assert state["requests"][1][2]["Authorization"] == "Bearer task-token" + + +async def test_redirect_is_not_followed_with_credentials(http_server): + base, state = http_server + state["status"] = 302 + with pytest.raises(aiohttp.ClientResponseError) as caught: + await HTTPClient(base).request( + Route("GET", "/start"), headers={"Authorization": "Bearer private-key"} + ) + assert caught.value.status == 302 + assert len(state["requests"]) == 1 + + +async def test_response_decoding_and_streaming_errors(http_server): + base, state = http_server + async with HTTPClient(base) as client: + state.update(status=204, body=b"") + assert await client.request(Route("GET", "/empty")) is None + state.update(status=200, body=b"plain text") + assert ( + await client.request(Route("GET", "/text"), response_type="text") + == "plain text" + ) + state.update(status=403, body=b'{"detail":"denied"}') + async with client.stream(Route("GET", "/error")) as response: + assert response.status == 403 + assert await response.json() == {"detail": "denied"} + with pytest.raises(aiohttp.ClientResponseError): + await client.request(Route("GET", "/error")) + + +async def test_async_rest_client_reuses_pool_and_explicit_key(http_server, monkeypatch): + base, state = http_server + monkeypatch.setattr(runpod, "api_key", "wrong-key") + async with AsyncRESTClient("right-key", base_url=base) as client: + session = client.session + await client.request(Route("GET", "/v2/pods")) + await client.request(Route("POST", "/v2/pods"), json={"name": "pod"}) + assert client.session is session + assert session.closed + assert all( + request[2]["Authorization"] == "Bearer right-key" + for request in state["requests"] + ) + assert json.loads(state["requests"][1][3]) == {"name": "pod"} + + +def test_sync_client_reuses_pool_and_borrows_sessions(http_server): + base, state = http_server + with requests.Session() as session: + session.headers["User-Agent"] = "caller-agent" + with SyncHTTPClient(base, session=session) as client: + for path in ("/first", "/second"): + with client.stream(Route("GET", path)) as response: + assert response.json() == {"ok": True} + assert session.get(f"{base}third").status_code == 200 + assert state["requests"][0][4] == state["requests"][1][4] + assert state["requests"][0][2]["User-Agent"] == "caller-agent" + + +def test_sync_rest_client_reuses_pool_and_closes_responses(http_server): + base, state = http_server + with RESTClient("key", base_url=base) as client: + session = client.session + assert client.request(Route("GET", "/v2/pods")) == {"ok": True} + assert client.request(Route("GET", "/v2/pods")) == {"ok": True} + assert client.session is session + assert client.session is None + assert state["requests"][0][4] == state["requests"][1][4] + + +async def test_mutation_preserves_borrowed_session_middleware(http_server): + base, state = http_server + calls = [] + + async def middleware(request, handler): + calls.append(request.method) + request.headers["X-Caller"] = "preserved" + return await handler(request) + + async with aiohttp.ClientSession(middlewares=(middleware,)) as session: + async with HTTPClient(base, session=session) as client: + await client.request(Route("PUT", "/first")) + async with session.get(f"{base}second") as response: + await response.read() + assert session._retry_connection is True + assert calls == ["PUT", "GET"] + assert all(request[2]["X-Caller"] == "preserved" for request in state["requests"]) + + +@pytest.mark.parametrize("status", [302, 307, 308]) +def test_graphql_rejects_redirect_before_decoding(http_server, monkeypatch, status): + from runpod.api.graphql import run_graphql_query + from runpod.error import QueryError + + base, state = http_server + state.update(status=status, body=b"") + monkeypatch.setenv("RUNPOD_API_BASE_URL", base) + with pytest.raises(QueryError, match="unexpected redirect") as caught: + run_graphql_query("query { myself { id } }", api_key="synthetic-key") + assert caught.value.status_code == status + assert len(state["requests"]) == 1 + + +@pytest.mark.parametrize("status", [302, 307, 308]) +async def test_async_graphql_rejects_redirect_before_decoding( + http_server, monkeypatch, status +): + from runpod.api.graphql import run_graphql_query_async + from runpod.error import QueryError + + base, state = http_server + state.update(status=status, body=b"") + monkeypatch.setenv("RUNPOD_API_BASE_URL", base) + with pytest.raises(QueryError, match="unexpected redirect") as caught: + await run_graphql_query_async( + "query { myself { id } }", api_key="synthetic-key" + ) + assert caught.value.status_code == status + assert len(state["requests"]) == 1 diff --git a/tests/test_api/test_http_review_feedback.py b/tests/test_api/test_http_review_feedback.py new file mode 100644 index 000000000..9fc43816a --- /dev/null +++ b/tests/test_api/test_http_review_feedback.py @@ -0,0 +1,133 @@ +"""request compatibility and unfollowed redirect handling.""" + +import importlib +from unittest.mock import AsyncMock, MagicMock + +import aiohttp +import click +import pytest + +import runpod +from runpod.api.http import HTTPClient +from runpod.api.rest import AsyncRESTClient, RESTClient +from runpod.api.routes import Route, endpoint_base_url +from runpod.cli.api import api_errors +from runpod.error import AppError, AuthenticationError, QueryError + + +@pytest.mark.parametrize( + "path,expected", + [ + ("/v2/pods/a{b}", "/v2/pods/a%7Bb%7D"), + ('/search?q={"a":1}', "/search?q=%7B%22a%22:1%7D"), + ], +) +def test_raw_paths_preserve_literal_braces(path, expected): + assert Route("GET", path).url("https://example.test") == ( + "https://example.test" + expected + ) + + +@pytest.mark.parametrize("status", [301, 302, 303, 307, 308]) +def test_sync_rest_rejects_redirect_without_exposing_body(status): + response = MagicMock(status_code=status, text="synthetic-secret", headers={}) + session = MagicMock() + session.request.return_value = response + with RESTClient("synthetic-key", session=session) as client: + with pytest.raises(QueryError, match="unexpected redirect") as caught: + client.request(Route("DELETE", "/v2/pods/pod")) + assert caught.value.status_code == status + assert "synthetic-secret" not in str(caught.value) + response.json.assert_not_called() + response.close.assert_called_once() + assert session.request.call_args.kwargs["allow_redirects"] is False + + +@pytest.mark.parametrize("status", [301, 302, 303, 307, 308]) +async def test_async_rest_rejects_redirect_without_exposing_body(status): + response = MagicMock(status=status, headers={}) + response.text = AsyncMock(return_value="synthetic-secret") + response.json = AsyncMock() + session = MagicMock(closed=False) + session.request.return_value.__aenter__.return_value = response + async with AsyncRESTClient("synthetic-key", session=session) as client: + with pytest.raises(QueryError, match="unexpected redirect") as caught: + await client.request(Route("DELETE", "/v2/pods/pod")) + assert caught.value.status_code == status + assert "synthetic-secret" not in str(caught.value) + response.json.assert_not_awaited() + session.request.return_value.__aexit__.assert_awaited_once() + assert session.request.call_args.kwargs["allow_redirects"] is False + + +async def test_borrowed_session_retry_policy_is_unchanged(): + async with aiohttp.ClientSession() as session: + retry = session._retry_connection + response = MagicMock(status=200) + session.request = MagicMock() + session.request.return_value.__aenter__.return_value = response + async with HTTPClient(session=session) as client: + for method in ("GET", "POST", "PUT", "DELETE"): + async with client.stream(Route(method, "/work")): + assert session._retry_connection is retry + assert session._retry_connection is retry + assert not session.closed + + +async def test_closed_borrowed_session_fails_in_context_and_stream(): + session = aiohttp.ClientSession() + await session.close() + client = HTTPClient(session=session) + with pytest.raises(RuntimeError, match="supplied HTTP session is closed"): + async with client: + pass + with pytest.raises(RuntimeError, match="Session is closed"): + async with client.stream(Route("GET", "/work")): + pass + + +def test_programmatic_endpoint_base_takes_precedence(monkeypatch): + monkeypatch.setenv("RUNPOD_ENDPOINT_BASE_URL", "https://environment.test/v2") + monkeypatch.setattr(runpod, "endpoint_url_base", "https://explicit.test/v2") + assert endpoint_base_url() == "https://explicit.test/v2" + + +@pytest.mark.parametrize( + "base", ["relative", "file:///tmp", "https://user:secret@host"] +) +def test_invalid_api_base_has_clean_cli_error(monkeypatch, base): + monkeypatch.setenv("RUNPOD_API_BASE_URL", base) + with pytest.raises(click.ClickException, match="base URL must be an HTTP origin"): + with api_errors(): + Route("GET", "/v2/pods").url() + + +@pytest.mark.parametrize( + "module", + [ + "api", + "catalog", + "compute", + "console", + "endpoint", + "endpoint_config", + "logs", + "main", + "options", + "output", + "pod", + "update", + "volume", + ], +) +def test_cli_import_aliases_share_module_identity(module): + assert importlib.import_module(f"runpod.rp_cli.{module}") is ( + importlib.import_module(f"runpod.cli.{module}") + ) + + +def test_login_import_and_exception_compatibility(): + login = importlib.import_module("runpod.auth.login") + assert importlib.import_module("runpod.apps.auth") is login + assert isinstance(login.LoginError("denied"), AuthenticationError) + assert isinstance(login.LoginError("denied"), AppError) diff --git a/tests/test_api/test_rate_limit.py b/tests/test_api/test_rate_limit.py index 92b1940b1..e36ebd96e 100644 --- a/tests/test_api/test_rate_limit.py +++ b/tests/test_api/test_rate_limit.py @@ -508,7 +508,7 @@ def test_sync_response_is_closed_before_sleep(monkeypatch, clock): second._content_consumed = True second.close = Mock() monkeypatch.setattr(rest, "rate_limits", _rate_limit._RateLimits()) - monkeypatch.setattr(rest.requests, "request", Mock(side_effect=[first, second])) + monkeypatch.setattr(requests.Session, "request", Mock(side_effect=[first, second])) def sleep(seconds): first.close.assert_called_once() diff --git a/tests/test_api/test_response_contracts.py b/tests/test_api/test_response_contracts.py new file mode 100644 index 000000000..191f14614 --- /dev/null +++ b/tests/test_api/test_response_contracts.py @@ -0,0 +1,136 @@ +"""required records and empty REST response contracts.""" + +from unittest.mock import AsyncMock, MagicMock, patch + +import pytest + +from runpod.api import ctl_commands +from runpod.api.rest import AsyncRESTClient, RESTClient +from runpod.api.routes import Route +from runpod.error import QueryError + + +@pytest.mark.parametrize( + "response", [None, [], "invalid"], ids=["empty", "list", "text"] +) +@pytest.mark.parametrize( + "command,args,kwargs", + [ + pytest.param(ctl_commands.get_gpus, (), {}, id="get-gpus"), + pytest.param(ctl_commands.get_gpu, ("gpu",), {}, id="get-gpu"), + pytest.param(ctl_commands.get_pods, (), {}, id="get-pods"), + pytest.param( + ctl_commands.create_pod, + ("pod", "image"), + {"gpu_type_id": "gpu"}, + id="create-pod", + ), + pytest.param(ctl_commands.stop_pod, ("pod",), {}, id="stop-pod"), + pytest.param(ctl_commands.resume_pod, ("pod",), {}, id="resume-pod"), + pytest.param( + ctl_commands.create_template, + ("template", "image"), + {}, + id="create-template", + ), + pytest.param(ctl_commands.get_endpoints, (), {}, id="get-endpoints"), + pytest.param( + ctl_commands.create_endpoint, + ("endpoint", "template"), + {}, + id="create-endpoint", + ), + pytest.param( + ctl_commands.update_endpoint_template, + ("endpoint", "template"), + {}, + id="update-endpoint-template", + ), + pytest.param( + ctl_commands.create_container_registry_auth, + ("registry", "user", "synthetic-password"), + {}, + id="create-registry-auth", + ), + pytest.param( + ctl_commands.create_pod, + ("pod",), + { + "gpu_type_id": "gpu", + "template_id": "template", + "volume_mount_path": "/workspace", + }, + id="read-template-mounts", + ), + ], +) +def test_required_record_commands_reject_empty_or_non_object_responses( + command, args, kwargs, response +): + with patch("runpod.api.ctl_commands.run_rest_request", return_value=response): + with pytest.raises(QueryError, match="expected a JSON object response"): + command(*args, **kwargs) + + +@pytest.mark.parametrize( + "command,args,expected", + [ + pytest.param(ctl_commands.get_pod, ("pod",), None, id="get-pod"), + pytest.param(ctl_commands.terminate_pod, ("pod",), None, id="terminate-pod"), + pytest.param( + ctl_commands.delete_container_registry_auth, + ("registry",), + True, + id="delete-registry-auth", + ), + ], +) +def test_optional_and_void_commands_accept_empty_responses(command, args, expected): + with patch("runpod.api.ctl_commands.run_rest_request", return_value=None): + assert command(*args) is expected + + +def test_update_user_settings_accepts_empty_write_response(): + user = {"id": "user"} + with ( + patch("runpod.api.ctl_commands.run_rest_request", return_value=None), + patch("runpod.api.ctl_commands.get_user", return_value=user) as get_user, + ): + assert ( + ctl_commands.update_user_settings("ssh-ed25519 key", api_key="key") is user + ) + get_user.assert_called_once_with(api_key="key") + + +@pytest.mark.parametrize("status", [200, 204]) +def test_sync_rest_empty_get_returns_none(status): + response = MagicMock(status_code=status, headers={}, content=b"") + session = MagicMock() + session.request.return_value = response + + with RESTClient( + "synthetic-key", base_url="https://example.test", session=session + ) as client: + assert client.request(Route("GET", "/v2/pods/pod")) is None + + response.json.assert_not_called() + response.close.assert_called_once() + session.close.assert_not_called() + + +@pytest.mark.parametrize("status", [200, 204]) +async def test_async_rest_empty_get_returns_none(status): + response = MagicMock(status=status, headers={}) + response.read = AsyncMock(return_value=b"") + response.json = AsyncMock() + session = MagicMock(closed=False) + session.request.return_value.__aenter__.return_value = response + + async with AsyncRESTClient( + "synthetic-key", base_url="https://example.test", session=session + ) as client: + assert await client.request(Route("GET", "/v2/pods/pod")) is None + + response.json.assert_not_awaited() + session.request.return_value.__aexit__.assert_awaited_once() + session.close.assert_not_called() diff --git a/tests/test_api/test_rest.py b/tests/test_api/test_rest.py index 23f4a96e5..31db1d116 100644 --- a/tests/test_api/test_rest.py +++ b/tests/test_api/test_rest.py @@ -242,6 +242,14 @@ async def test_supplied_session_does_not_replay_mutations(rest_server, method): class TestCursorPagination: + @pytest.mark.parametrize("key", [None, ""]) + async def test_missing_key_fails_before_session_creation(self, monkeypatch, key): + monkeypatch.setattr(runpod, "api_key", key) + with patch("aiohttp.ClientSession") as session: + with pytest.raises(AuthenticationError, match="No API key provided"): + await run_rest_paginated_request_async("/v2/items", "items") + session.assert_not_called() + async def test_retries_current_page_with_backoff_and_one_session(self): first = {"id": "one"} second = {"id": "two"} @@ -280,7 +288,9 @@ async def test_exhausted_retries_close_session(self): patch("runpod.api.rest.asyncio.sleep", new_callable=AsyncMock) as sleep, ): with pytest.raises(aiohttp.ClientError, match="down"): - await run_rest_paginated_request_async("/v2/items", "items") + await run_rest_paginated_request_async( + "/v2/items", "items", api_key="key" + ) assert rest.await_count == 4 assert sleep.await_args_list == [call(1), call(2), call(4)] assert rest.await_args.kwargs["session"].closed @@ -297,7 +307,9 @@ async def test_non_transport_errors_are_not_retried(self, failure): rest = AsyncMock(side_effect=failure) with patch("runpod.api.rest.run_rest_request_async", rest): with pytest.raises(type(failure)): - await run_rest_paginated_request_async("/v2/items", "items") + await run_rest_paginated_request_async( + "/v2/items", "items", api_key="key" + ) rest.assert_awaited_once() assert rest.await_args.kwargs["session"].closed @@ -322,7 +334,9 @@ async def test_invalid_envelopes_raise_query_error(self, data): rest = AsyncMock(return_value=data) with patch("runpod.api.rest.run_rest_request_async", rest): with pytest.raises(QueryError, match="invalid items") as raised: - await run_rest_paginated_request_async("/v2/items", "items") + await run_rest_paginated_request_async( + "/v2/items", "items", api_key="key" + ) assert raised.value.query == "GET /v2/items" rest.assert_awaited_once() assert rest.await_args.kwargs["session"].closed @@ -341,7 +355,9 @@ async def test_missing_or_invalid_cursor_raises(self, pagination): rest = AsyncMock(return_value={"items": [], "pagination": pagination}) with patch("runpod.api.rest.run_rest_request_async", rest): with pytest.raises(QueryError, match="nextCursor"): - await run_rest_paginated_request_async("/v2/items", "items") + await run_rest_paginated_request_async( + "/v2/items", "items", api_key="key" + ) rest.assert_awaited_once() @pytest.mark.parametrize("cursors", [["a", "a"], ["a", "b", "a"]]) @@ -357,6 +373,8 @@ async def test_cursor_cycles_raise(self, cursors): ) with patch("runpod.api.rest.run_rest_request_async", rest): with pytest.raises(QueryError, match="repeated a cursor"): - await run_rest_paginated_request_async("/v2/items", "items") + await run_rest_paginated_request_async( + "/v2/items", "items", api_key="key" + ) assert rest.await_count == len(cursors) assert rest.await_args.kwargs["session"].closed diff --git a/tests/test_apps/test_api_client.py b/tests/test_apps/test_api_client.py index 3bbbfbce0..6637ee56d 100644 --- a/tests/test_apps/test_api_client.py +++ b/tests/test_apps/test_api_client.py @@ -6,7 +6,7 @@ import pytest from runpod.apps.api import AppsApiClient -from runpod.error import AuthenticationError, QueryError +from runpod.error import QueryError from runpod.user_agent import APPS_USER_AGENT @@ -730,61 +730,6 @@ async def test_secret_crud(self): assert await client.delete_secret("s1") is True -class TestAuthRequests: - async def test_create_auth_request_is_anonymous(self): - client = AppsApiClient(api_key="test-key") - transport = _respond( - {"createFlashAuthRequest": {"id": "req1", "status": "PENDING"}} - ) - with patch("runpod.apps.api.run_graphql_query_async", transport): - result = await client.create_auth_request() - assert result["id"] == "req1" - assert transport.call_args[1]["anonymous"] is True - - async def test_verify_api_key_sends_the_pasted_key(self): - client = AppsApiClient(api_key="stored-key") - transport = _respond({"myself": {"id": "user1"}}) - with patch("runpod.apps.api.run_graphql_query_async", transport): - assert await client.verify_api_key("rpa_new") is True - assert transport.call_args[1]["api_key"] == "rpa_new" - assert transport.call_args[1].get("anonymous", False) is False - - @pytest.mark.parametrize( - "outcome", - [ - AuthenticationError("Unauthorized request"), - QueryError("invalid api key", "query"), - {"data": {"myself": None}}, - {"data": None}, - ], - ) - async def test_verify_api_key_rejects(self, outcome): - transport = AsyncMock() - if isinstance(outcome, Exception): - transport.side_effect = outcome - else: - transport.return_value = outcome - with patch("runpod.apps.api.run_graphql_query_async", transport): - assert await AppsApiClient().verify_api_key("rpa_bad") is False - - async def test_verify_api_key_raises_on_transport_error(self): - transport = AsyncMock(side_effect=aiohttp.ClientConnectionError("down")) - with patch("runpod.apps.api.run_graphql_query_async", transport): - with pytest.raises(aiohttp.ClientConnectionError): - await AppsApiClient().verify_api_key("rpa_new") - - async def test_status_check_is_anonymous_and_never_asks_for_the_key(self): - client = AppsApiClient(api_key="test-key") - transport = _respond( - {"flashAuthRequestStatus": {"id": "req1", "status": "DENIED"}} - ) - with patch("runpod.apps.api.run_graphql_query_async", transport): - result = await client.get_auth_request_status("req1") - assert result["status"] == "DENIED" - assert transport.call_args[1]["anonymous"] is True - assert "apiKey" not in transport.call_args[0][0] - - class TestArtifacts: async def test_prepare_artifact_upload(self): client, patcher = _client_with( diff --git a/tests/test_apps/test_app.py b/tests/test_apps/test_app.py index 5e416ab89..6fb09b166 100644 --- a/tests/test_apps/test_app.py +++ b/tests/test_apps/test_app.py @@ -595,11 +595,11 @@ def test_live_pool_members_parses_catalog_and_fails_soft(self, monkeypatch): } fetch = _real_live_pool_members gpu_mod._clear_catalog_cache() - with patch("requests.request", return_value=resp) as get: + with patch("requests.Session.request", return_value=resp) as get: assert fetch() == {"AMPERE_24": {"NVIDIA L4"}} assert get.call_args.kwargs["headers"]["Authorization"] == "Bearer k" gpu_mod._clear_catalog_cache() - with patch("requests.request", side_effect=OSError("offline")) as get: + with patch("requests.Session.request", side_effect=OSError("offline")) as get: assert fetch() is None # a failure is not retried on every lookup assert fetch() is None @@ -607,7 +607,7 @@ def test_live_pool_members_parses_catalog_and_fails_soft(self, monkeypatch): # it is retried once the window passes cache = next(iter(gpu_mod._catalog_caches.values())) cache.failed_at -= gpu_mod.CATALOG_RETRY_SECONDS - with patch("requests.request", return_value=resp): + with patch("requests.Session.request", return_value=resp): assert fetch() == {"AMPERE_24": {"NVIDIA L4"}} gpu_mod._clear_catalog_cache() diff --git a/tests/test_apps/test_entrypoint_execution.py b/tests/test_apps/test_entrypoint_execution.py index 68d0c0b89..c14688c56 100644 --- a/tests/test_apps/test_entrypoint_execution.py +++ b/tests/test_apps/test_entrypoint_execution.py @@ -92,7 +92,7 @@ async def main(): from click.testing import CliRunner from runpod.apps.entrypoint import run_entrypoint from runpod.apps.targets import SentinelTarget -from runpod.rp_cli.main import cli +from runpod.cli.main import cli async def start(session): for app in session.apps: diff --git a/tests/test_apps/test_gpu_catalog.py b/tests/test_apps/test_gpu_catalog.py index ecfc72698..4af46a01f 100644 --- a/tests/test_apps/test_gpu_catalog.py +++ b/tests/test_apps/test_gpu_catalog.py @@ -13,8 +13,10 @@ from runpod.apps.app import _clear_registry from runpod.apps.deploy import reconcile_endpoints from runpod.apps.dev import DevSession -from runpod.apps.gpu import live_pool_members as _real_live_pool_members -from runpod.apps.gpu import live_pool_members_async as _real_live_pool_members_async +from runpod.apps.gpu import ( + live_pool_members as _real_live_pool_members, + live_pool_members_async as _real_live_pool_members_async, +) from runpod.user_agent import APPS_USER_AGENT MIG = "NVIDIA RTX PRO 6000 Blackwell Server Edition MIG 1g.24gb" diff --git a/tests/test_apps/test_http_errors.py b/tests/test_apps/test_http_errors.py index 668076292..227837de9 100644 --- a/tests/test_apps/test_http_errors.py +++ b/tests/test_apps/test_http_errors.py @@ -75,11 +75,15 @@ async def local_request(self, method, url, **kwargs): ("json", "GET", "/data", 1), ], ) +@pytest.mark.parametrize("status", [302, 307, 308, 500]) async def test_transports_report_body_without_credentials( - error_server, monkeypatch, tmp_path, operation, method, path, attempts + error_server, monkeypatch, tmp_path, operation, method, path, attempts, status ): + error_server["status"] = status + if operation == "queue_status" and status < 400: + attempts = 1 monkeypatch.setattr("runpod.endpoint_url_base", "https://api.runpod.ai/v2") - monkeypatch.setattr("runpod.apps.logs.HAPI_BASE", "https://logs.example") + monkeypatch.setenv("RUNPOD_HAPI_URL", "https://logs.example") client = QueueClient( "ep", lambda: {"Authorization": "Bearer synthetic-account-key"} ) @@ -117,7 +121,7 @@ async def test_transports_report_body_without_credentials( error = raised.value assert isinstance(error, AppError) - assert error.status == 500 + assert error.status == status assert error.method == method assert error.url.endswith(path) assert "GPU capacity exhausted." in error.body_excerpt @@ -183,8 +187,14 @@ async def test_body_excerpt_is_bounded_and_tolerates_non_json(body, excerpt): @pytest.mark.parametrize("status", [200, 204, 302]) async def test_success_does_not_consume_body(status): response = response_for(b"success", status=status) - await raise_for_status(response) - response.content.readexactly.assert_not_awaited() + if status < 300: + await raise_for_status(response) + response.content.readexactly.assert_not_awaited() + else: + with pytest.raises(AppHTTPError) as raised: + await raise_for_status(response) + assert raised.value.status == status + response.content.readexactly.assert_awaited_once() @pytest.mark.parametrize( diff --git a/tests/test_apps/test_http_transport.py b/tests/test_apps/test_http_transport.py new file mode 100644 index 000000000..581038f2a --- /dev/null +++ b/tests/test_apps/test_http_transport.py @@ -0,0 +1,224 @@ +"""HTTP transport routing, ownership, and credentials for Apps operations.""" + +from contextlib import asynccontextmanager +from unittest.mock import AsyncMock, MagicMock, patch + +import pytest +from aiohttp import web + +import runpod +from runpod.api.http import HTTPClient +from runpod.apps.api import AppsApiClient +from runpod.apps.logs import pod_logs, stream_pod_logs +from runpod.apps.spec import ResourceKind, ResourceSpec +from runpod.apps.targets import QueueClient, _wait_terminal +from runpod.apps.tasks import TaskExecution +from runpod.apps.utils.network import get_json +from runpod.user_agent import APPS_USER_AGENT + + +@pytest.mark.parametrize("operation", ["status", "cancel", "retry", "stream"]) +async def test_queue_routes_escape_ids_and_preserve_base_path(monkeypatch, operation): + monkeypatch.setattr(runpod, "endpoint_url_base", "http://custom.test:8080/api/v2/") + client = QueueClient("endpoint/id ?#%", lambda: {"Authorization": "Bearer worker"}) + with patch( + "runpod.apps.targets._request_json", + AsyncMock(return_value={"status": "COMPLETED"}), + ) as request: + if operation == "stream": + assert [ + chunk async for chunk in client.stream("job/id ?#%", timeout=5) + ] == [] + else: + await getattr(client, operation)("job/id ?#%") + assert request.call_args.args[:3] == ( + "GET" if operation in {"status", "stream"} else "POST", + f"http://custom.test:8080/api/v2/endpoint%2Fid%20%3F%23%25/{operation}/job%2Fid%20%3F%23%25", + {"Authorization": "Bearer worker"}, + ) + assert request.call_args.kwargs["job_id"] == "job/id ?#%" + assert request.call_args.kwargs["retry_not_found"] is (operation == "status") + + +async def test_poll_route_escapes_job_id(): + with ( + patch("runpod.apps.targets.asyncio.sleep", AsyncMock()), + patch( + "runpod.apps.targets._get_json", + AsyncMock(return_value={"status": "COMPLETED"}), + ) as request, + ): + await _wait_terminal( + "http://custom.test/prefix/endpoint", + {"id": "job/id?", "status": "IN_QUEUE"}, + {}, + 5, + ) + assert ( + request.call_args.args[0] + == "http://custom.test/prefix/endpoint/status/job%2Fid%3F" + ) + + +async def test_lb_transport_preserves_custom_scheme_and_port(monkeypatch): + monkeypatch.setattr(runpod, "endpoint_url_base", "http://custom.test:8080/api/v2") + response = MagicMock(status=200) + response.text = AsyncMock(return_value='{"ok": true}') + with patch("runpod.apps.targets.HTTPClient") as factory: + client = factory.return_value.__aenter__.return_value + client.stream = MagicMock() + client.stream.return_value.__aenter__.return_value = response + result = await QueueClient("endpoint", lambda: {}).http( + "POST", "/work", timeout=5 + ) + assert result == {"ok": True} + factory.assert_called_once_with(base_url="http://endpoint.custom.test:8080") + assert client.stream.call_args.args[0].resolved_path == "/work" + assert client.stream.call_args.args[0].method == "POST" + + +async def test_host_log_base_is_read_per_operation(monkeypatch): + monkeypatch.setenv("RUNPOD_API_KEY", "account-key") + with patch("runpod.apps.logs.HTTPClient") as factory: + response = MagicMock(status=200) + response.json = AsyncMock(return_value={"container": []}) + factory.return_value.stream.return_value.__aenter__.return_value = response + for base in ("http://one.test/prefix", "http://two.test/other"): + monkeypatch.setenv("RUNPOD_HAPI_URL", base) + await pod_logs("pod/id?#") + factory.assert_called_with(base_url=base) + route = factory.return_value.stream.call_args.args[0] + assert route.url(base) == f"{base}/v1/pod/pod%2Fid%3F%23/logs" + + +async def test_worker_log_route_escapes_both_ids(monkeypatch): + monkeypatch.setenv("RUNPOD_API_KEY", "account-key") + monkeypatch.setenv("RUNPOD_API_BASE_URL", "http://custom.test/prefix") + + async def content(): + yield b'data: {"line": "ready"}\n' + yield b"\n" + + response = MagicMock(status=200) + response.content = content() + with patch("runpod.apps.logs.HTTPClient") as factory: + client = factory.return_value.__aenter__.return_value + client.stream = MagicMock() + client.stream.return_value.__aenter__.return_value = response + assert [ + event + async for event in stream_pod_logs( + "pod/id", endpoint_id="endpoint?", log_type="system" + ) + ] == [{"line": "ready"}] + route = client.stream.call_args.args[0] + assert ( + route.url() + == "http://custom.test/prefix/v2/serverless/endpoint%3F/workers/pod%2Fid/logs" + ) + + +@pytest.mark.parametrize("operation", ["submit", "poll_result", "wait_ready"]) +async def test_task_retries_share_client_and_use_only_task_credentials( + monkeypatch, operation +): + monkeypatch.setenv("RUNPOD_API_KEY", "account-key") + execution = TaskExecution( + ResourceSpec(kind=ResourceKind.TASK, name="task"), api=MagicMock() + ) + execution.pod_id = "pod1" + responses = [MagicMock(status=404), MagicMock(status=200)] + responses[-1].json = AsyncMock( + return_value={"status": "DONE", "response": {"ok": True}} + ) + with ( + patch("runpod.apps.tasks.HTTPClient") as factory, + patch("runpod.apps.tasks.asyncio.sleep", AsyncMock()), + ): + client = factory.return_value.__aenter__.return_value + client.stream = MagicMock() + client.stream.return_value.__aenter__.side_effect = responses + if operation == "submit": + await execution.submit({"input": {}}) + elif operation == "poll_result": + assert await execution.poll_result() == {"ok": True} + else: + await execution.wait_ready(timeout=5) + factory.assert_called_once_with(base_url="https://pod1-8080.proxy.runpod.net") + assert client.stream.call_count == 2 + for call in client.stream.call_args_list: + assert call.kwargs.get("headers", {}) == ( + {"User-Agent": APPS_USER_AGENT} + if operation == "wait_ready" + else { + "Authorization": f"Bearer {execution.token}", + "User-Agent": APPS_USER_AGENT, + } + ) + factory.return_value.__aexit__.assert_awaited_once() + + +async def test_upload_reuses_session_and_preserves_presigned_query( + tmp_path, monkeypatch +): + monkeypatch.setenv("RUNPOD_API_KEY", "account-key") + tar = tmp_path / "app.tar.gz" + tar.write_bytes(b"payload") + requests = [] + sessions = [] + original_stream = HTTPClient.stream + + @asynccontextmanager + async def stream(client, *args, **kwargs): + sessions.append(client.session) + async with original_stream(client, *args, **kwargs) as response: + yield response + + async def upload(request): + requests.append((request.raw_path, dict(request.headers), await request.read())) + return web.Response(status=503 if len(requests) == 1 else 200) + + app = web.Application() + app.router.add_put("/upload", upload) + runner = web.AppRunner(app) + await runner.setup() + site = web.TCPSite(runner, "127.0.0.1", 0) + await site.start() + port = site._server.sockets[0].getsockname()[1] + try: + with ( + patch.object(HTTPClient, "stream", stream), + patch("asyncio.sleep", AsyncMock()), + ): + await AppsApiClient(api_key="explicit-account-key").upload_tarball( + f"http://127.0.0.1:{port}/upload?signature=a%2Fb%2Bz", str(tar) + ) + finally: + await runner.cleanup() + assert len(requests) == 2 + for path, headers, payload in requests: + assert path == "/upload?signature=a%2Fb%2Bz" + assert "Authorization" not in headers + assert payload == b"payload" + assert headers["Content-Type"] == "application/gzip" + assert len(sessions) == 2 + assert sessions[0] is sessions[1] + assert sessions[0].closed + + +async def test_network_get_uses_explicit_credentials(): + with patch("runpod.apps.utils.network.HTTPClient") as factory: + response = MagicMock(status=200) + response.json = AsyncMock(return_value={"ok": True}) + factory.return_value.stream.return_value.__aenter__.return_value = response + assert await get_json( + "http://custom.test/api?q=x", {"Authorization": "Bearer worker"}, 9 + ) == {"ok": True} + factory.assert_called_once_with(base_url="http://custom.test/api?q=x") + route = factory.return_value.stream.call_args.args[0] + assert route.method == "GET" + assert route.path == "" + assert factory.return_value.stream.call_args.kwargs == { + "headers": {"Authorization": "Bearer worker", "User-Agent": APPS_USER_AGENT}, + "timeout": 9, + } diff --git a/tests/test_apps/test_logs.py b/tests/test_apps/test_logs.py index 578988010..bf3a4748e 100644 --- a/tests/test_apps/test_logs.py +++ b/tests/test_apps/test_logs.py @@ -37,17 +37,17 @@ def test_system_before_container(self): def _mock_session(response): - """a ClientSession whose get() context manager yields `response`.""" + """an HTTPClient whose stream yields the response.""" response.status = 200 get_cm = MagicMock() get_cm.__aenter__ = AsyncMock(return_value=response) get_cm.__aexit__ = AsyncMock(return_value=False) session = MagicMock() - session.get = MagicMock(return_value=get_cm) - session_cm = MagicMock() - session_cm.__aenter__ = AsyncMock(return_value=session) - session_cm.__aexit__ = AsyncMock(return_value=False) - return session_cm, session + session.stream = MagicMock(return_value=get_cm) + session.request = response.json + session.__aenter__ = AsyncMock(return_value=session) + session.__aexit__ = AsyncMock(return_value=False) + return session, session class TestPodLogs: @@ -58,13 +58,13 @@ async def test_snapshot_normalizes_nulls(self, monkeypatch): response.json = AsyncMock(return_value={"container": ["hello"], "system": None}) session_cm, session = _mock_session(response) - with patch("aiohttp.ClientSession", return_value=session_cm): + with patch("runpod.apps.logs.HTTPClient", return_value=session_cm): result = await pod_logs("pod123") assert result == {"container": ["hello"], "system": []} - url = session.get.call_args[0][0] - assert "pod123" in url - headers = session.get.call_args[1]["headers"] + route = session.stream.call_args[0][0] + assert "pod123" in route.resolved_path + headers = session.stream.call_args[1]["headers"] assert headers["Authorization"] == "Bearer test-key" @@ -97,7 +97,7 @@ async def test_combined_rest_stream_resumes_delivered_events( ) session_cm, session = _mock_session(response) cursors = [] - with patch("aiohttp.ClientSession", return_value=session_cm): + with patch("runpod.apps.logs.HTTPClient", return_value=session_cm): entries = [ entry async for entry in stream_pod_logs( @@ -108,15 +108,15 @@ async def test_combined_rest_stream_resumes_delivered_events( on_event_id=cursors.append, ) ] - url = session.get.call_args.args[0] + url = session.stream.call_args.args[0].resolved_path suffix = ( "/v2/serverless/ep1/workers/pod1/logs" if endpoint_id else "/v2/pods/pod1/logs" ) assert url.endswith(suffix) - assert session.get.call_args.kwargs["params"] == {"tail": "100"} - assert session.get.call_args.kwargs["headers"]["Last-Event-ID"] == "cursor1" + assert session.stream.call_args.kwargs["params"] == {"tail": "100"} + assert session.stream.call_args.kwargs["headers"]["Last-Event-ID"] == "cursor1" assert cursors == ["cursor2"] assert entries == [{"source": "system", "line": "ready", "ts": "t2"}] @@ -141,14 +141,14 @@ async def test_parses_sse_frames(self, monkeypatch): response.content = _FakeContent(frames) session_cm, session = _mock_session(response) - with patch("aiohttp.ClientSession", return_value=session_cm): + with patch("runpod.apps.logs.HTTPClient", return_value=session_cm): events = [e async for e in stream_pod_logs("pod123")] assert events == [ {"source": "container", "line": "hi", "ts": "t1"}, {"source": "system", "line": "boot", "ts": "t2"}, ] - params = session.get.call_args[1]["params"] + params = session.stream.call_args[1]["params"] assert params["stream"] == "true" assert params["tail"] == "100" @@ -167,7 +167,7 @@ async def test_cursor_matches_each_complete_frame(self, monkeypatch, id_first): response.content = _FakeContent(frames) session_cm, _ = _mock_session(response) cursors = [] - with patch("aiohttp.ClientSession", return_value=session_cm): + with patch("runpod.apps.logs.HTTPClient", return_value=session_cm): stream = stream_pod_logs("pod1", on_event_id=cursors.append) assert await anext(stream) == {"line": 0} assert cursors == ["cursor0"] @@ -190,7 +190,7 @@ async def test_multiline_data_and_incomplete_frames(self, monkeypatch): ) session_cm, _ = _mock_session(response) cursors = [] - with patch("aiohttp.ClientSession", return_value=session_cm): + with patch("runpod.apps.logs.HTTPClient", return_value=session_cm): events = [ e async for e in stream_pod_logs("pod1", on_event_id=cursors.append) ] @@ -220,8 +220,8 @@ async def connect(): await asyncio.sleep(0.03) return response - session.get.return_value.__aenter__.side_effect = connect - with patch("aiohttp.ClientSession", return_value=session_cm): + session.stream.return_value.__aenter__.side_effect = connect + with patch("runpod.apps.logs.HTTPClient", return_value=session_cm): stream = stream_pod_logs("pod1", idle_timeout=0.001) if status == 403: with pytest.raises(AppHTTPError) as raised: @@ -230,7 +230,7 @@ async def connect(): assert raised.value.body_excerpt == "forbidden" else: assert [e async for e in stream] == [{"line": "ready"}] - session.get.return_value.__aexit__.assert_awaited_once() + session.stream.return_value.__aexit__.assert_awaited_once() async def test_idle_timeout_closes_established_stream(self, monkeypatch): monkeypatch.setenv("RUNPOD_API_KEY", "test-key") @@ -247,19 +247,19 @@ async def content(): response = MagicMock() response.content = content() session_cm, session = _mock_session(response) - with patch("aiohttp.ClientSession", return_value=session_cm): + with patch("runpod.apps.logs.HTTPClient", return_value=session_cm): events = [e async for e in stream_pod_logs("pod1", idle_timeout=0.001)] assert events == [{"line": "ready"}] assert closed == [True] - session.get.return_value.__aexit__.assert_awaited_once() + session.stream.return_value.__aexit__.assert_awaited_once() async def test_connection_timeout_propagates(self, monkeypatch): monkeypatch.setenv("RUNPOD_API_KEY", "test-key") session_cm, session = _mock_session(MagicMock()) - session.get.return_value.__aenter__.side_effect = TimeoutError( + session.stream.return_value.__aenter__.side_effect = TimeoutError( "connection timed out" ) - with patch("aiohttp.ClientSession", return_value=session_cm): + with patch("runpod.apps.logs.HTTPClient", return_value=session_cm): with pytest.raises(asyncio.TimeoutError, match="connection timed out"): await anext(stream_pod_logs("pod1", idle_timeout=0.001)) diff --git a/tests/test_apps/test_retry.py b/tests/test_apps/test_retry.py index 95aa5dd80..94a020bb2 100644 --- a/tests/test_apps/test_retry.py +++ b/tests/test_apps/test_retry.py @@ -5,12 +5,14 @@ import socket import threading import time +from contextlib import asynccontextmanager from http.server import BaseHTTPRequestHandler, ThreadingHTTPServer from unittest.mock import patch import aiohttp import pytest +from runpod.api.http import HTTPClient from runpod.apps.errors import AppHTTPError, EndpointNotFound, JobNotFound from runpod.apps.targets import ( JOB_PROPAGATION_ATTEMPTS, @@ -75,6 +77,27 @@ async def test_retries_transient_5xx_then_succeeds(flaky_server): assert data["hits"] == 3 +async def test_read_retries_share_one_session_and_close_it(flaky_server): + flaky_server.state["script"] = [520, 502] + sessions = [] + original_stream = HTTPClient.stream + + @asynccontextmanager + async def stream(client, *args, **kwargs): + sessions.append(client.session) + async with original_stream(client, *args, **kwargs) as response: + yield response + + with ( + patch("runpod.apps.targets.RETRY_BASE_DELAY", 0.01), + patch.object(HTTPClient, "stream", stream), + ): + assert (await _request_json("GET", flaky_server.url, {}, timeout=10))["ok"] + assert len(sessions) == 3 + assert all(session is sessions[0] for session in sessions) + assert sessions[0].closed + + async def test_exhausted_retries_raise_last_error(flaky_server): flaky_server.state["script"] = [503] * (RETRY_ATTEMPTS + 2) with patch("runpod.apps.targets.RETRY_BASE_DELAY", 0.01): diff --git a/tests/test_apps/test_targets.py b/tests/test_apps/test_targets.py index 84e46c461..803ca632b 100644 --- a/tests/test_apps/test_targets.py +++ b/tests/test_apps/test_targets.py @@ -8,6 +8,7 @@ import pytest +from runpod.api.routes import load_balancer_base_url from runpod.apps.errors import RemoteExecutionError from runpod.apps.spec import ResourceKind, ResourceSpec from runpod.apps.targets import ( @@ -16,7 +17,6 @@ SentinelTarget, _api_key, _headers, - _lb_domain, _wait_terminal, args_to_input, unwrap_job_output, @@ -49,7 +49,7 @@ def test_lb_domain(self, monkeypatch): import runpod monkeypatch.setattr(runpod, "endpoint_url_base", "https://api.runpod.ai/v2") - assert _lb_domain() == "api.runpod.ai" + assert load_balancer_base_url("endpoint") == "https://endpoint.api.runpod.ai" def test_headers(self, monkeypatch): monkeypatch.setenv("RUNPOD_API_KEY", "sk-test") diff --git a/tests/test_apps/test_tasks.py b/tests/test_apps/test_tasks.py index 438b6210f..8d69d73b9 100644 --- a/tests/test_apps/test_tasks.py +++ b/tests/test_apps/test_tasks.py @@ -510,16 +510,16 @@ async def test_runtime_must_acknowledge_timeout(self, method, acknowledged): ) session = MagicMock() session.__aenter__.return_value = session - session.post.return_value.__aenter__.return_value = response - with patch("runpod.apps.tasks.aiohttp.ClientSession", return_value=session): + session.stream.return_value.__aenter__.return_value = response + with patch("runpod.apps.tasks.HTTPClient", return_value=session): argument = {"timeout": 60} if method == "submit" else 60 if acknowledged: await getattr(execution, method)(argument) else: with pytest.raises(RuntimeError, match="did not acknowledge"): await getattr(execution, method)(argument) - assert session.post.call_args.kwargs["json"] == {"timeout": 60} - assert session.post.call_args.kwargs["headers"] == execution._headers + assert session.stream.call_args.kwargs["json"] == {"timeout": 60} + assert session.stream.call_args.kwargs["headers"] == execution._headers @pytest.mark.parametrize("timeout", [-1, True, "60", float("nan"), float("inf")]) async def test_invalid_timeouts_fail_before_http(self, timeout): @@ -528,7 +528,7 @@ async def test_invalid_timeouts_fail_before_http(self, timeout): execution = TaskExecution( ResourceSpec(kind=ResourceKind.TASK, name="t"), api=MagicMock() ) - with patch("runpod.apps.tasks.aiohttp.ClientSession") as session: + with patch("runpod.apps.tasks.HTTPClient") as session: with pytest.raises(ValueError, match="finite non-negative"): await execution.set_timeout(timeout) session.assert_not_called() diff --git a/tests/test_apps/test_transport_parity.py b/tests/test_apps/test_transport_parity.py index 55fb99b24..787d3d2b4 100644 --- a/tests/test_apps/test_transport_parity.py +++ b/tests/test_apps/test_transport_parity.py @@ -76,7 +76,7 @@ def work(value, flag): @pytest.mark.parametrize("value", [b"bytes", float("nan"), float("inf")]) async def test_api_body_validation_precedes_requests_and_source_sync(target, value): with ( - patch("runpod.apps.targets.aiohttp.ClientSession") as session, + patch("runpod.apps.targets.HTTPClient") as session, patch.object(LiveTarget, "_sync_source", AsyncMock()) as sync, ): with pytest.raises( @@ -88,7 +88,7 @@ async def test_api_body_validation_precedes_requests_and_source_sync(target, val async def test_raw_queue_requests_reject_non_json_options_before_network(): - with patch("runpod.apps.targets.aiohttp.ClientSession") as session: + with patch("runpod.apps.targets.HTTPClient") as session: with pytest.raises(ValueError, match="remote request body"): await _request_json( "POST", @@ -120,16 +120,16 @@ def test_queue_and_task_results_reject_non_finite_json(value): async def test_api_json_and_text_responses_share_transport(target, text, expected): with ( patch.object(target._client, "_headers", return_value={}), - patch("runpod.apps.targets.aiohttp.ClientSession") as factory, + patch("runpod.apps.targets.HTTPClient") as factory, ): session = factory.return_value.__aenter__.return_value - session.request = MagicMock() - response = session.request.return_value.__aenter__.return_value + session.stream = MagicMock() + response = session.stream.return_value.__aenter__.return_value response.status = 200 response.text = AsyncMock(return_value=text) response.raise_for_status = lambda: None assert await target.request("POST", "/work", {"value": 1}) == expected - assert session.request.call_args.kwargs["json"] == {"value": 1} + assert session.stream.call_args.kwargs["json"] == {"value": 1} @pytest.mark.parametrize("async_call", [False, True]) diff --git a/tests/test_apps/test_user_agent.py b/tests/test_apps/test_user_agent.py index 4b1103c04..7b16f6db6 100644 --- a/tests/test_apps/test_user_agent.py +++ b/tests/test_apps/test_user_agent.py @@ -15,10 +15,11 @@ from runpod.api.rest import run_rest_request, run_rest_request_async from runpod.apps import gpu, logs, tasks from runpod.apps.api import AppsApiClient, FlashTaskApiClient -from runpod.apps.auth import agent_login from runpod.apps.gpu import live_pool_members, live_pool_members_async from runpod.apps.targets import LiveTarget, SentinelTarget from runpod.apps.utils.network import get_json +from runpod.auth.api import AuthApiClient +from runpod.auth.login import agent_login from runpod.user_agent import APPS_USER_AGENT, USER_AGENT @@ -55,7 +56,7 @@ def log_message(self, *args): monkeypatch.setenv("RUNPOD_API_KEY", "test-key") monkeypatch.setattr(runpod, "api_key", "test-key") monkeypatch.setattr(runpod, "endpoint_url_base", state.url) - monkeypatch.setattr(logs, "HAPI_BASE", state.url) + monkeypatch.setenv("RUNPOD_HAPI_URL", state.url) monkeypatch.setattr(tasks, "_proxy_url", lambda pod_id: state.url) monkeypatch.setattr("runpod.apps.context.deployed_identity", lambda: None) gpu._clear_catalog_cache() @@ -104,7 +105,7 @@ async def query(*args, **kwargs): async def test_verify_api_key(server): server.responses = [{"data": {"myself": {"id": "user"}}}] - assert await AppsApiClient().verify_api_key("test-key") + assert await AuthApiClient().verify_api_key("test-key") @pytest.mark.parametrize("runtime", [None, "endpoint", "pod"]) @@ -219,7 +220,7 @@ async def test_queue_and_load_balancer(server, target, operation, monkeypatch): original = aiohttp.ClientSession._request async def request(session, method, url, **kwargs): - assert url.startswith("https://") + assert str(url).startswith(f"http://{client.endpoint_id}.127.0.0.1:") return await original(session, method, server.url + "/route", **kwargs) monkeypatch.setattr(aiohttp.ClientSession, "_request", request) @@ -333,7 +334,7 @@ def test_volume_transfer_caller_attribution( from click.testing import CliRunner from runpod.apps import NetworkVolume - from runpod.rp_cli.main import cli + from runpod.cli.main import cli server.user_agent = APPS_USER_AGENT if caller == "apps" else USER_AGENT server.responses = [ @@ -342,7 +343,7 @@ def test_volume_transfer_caller_attribution( "pagination": {"hasNextPage": False}, } ] - monkeypatch.setattr("runpod.rp_cli.update.start_background_check", lambda: None) + monkeypatch.setattr("runpod.cli.update.start_background_check", lambda: None) local = tmp_path / "model.bin" local.write_bytes(b"model") source, target = ( diff --git a/tests/test_auth/__init__.py b/tests/test_auth/__init__.py new file mode 100644 index 000000000..87798a67b --- /dev/null +++ b/tests/test_auth/__init__.py @@ -0,0 +1 @@ +"""account authentication tests.""" diff --git a/tests/test_apps/test_agent_auth.py b/tests/test_auth/test_agent_login.py similarity index 94% rename from tests/test_apps/test_agent_auth.py rename to tests/test_auth/test_agent_login.py index 69c2230da..fd2dabdca 100644 --- a/tests/test_apps/test_agent_auth.py +++ b/tests/test_auth/test_agent_login.py @@ -14,7 +14,8 @@ import pytest import runpod -from runpod.apps.auth import LoginError, _post_authentication_attempt, agent_login +from runpod.api.routes import Route +from runpod.auth.login import LoginError, _post_authentication_attempt, agent_login from runpod.user_agent import APPS_USER_AGENT @@ -235,11 +236,11 @@ def test_aborted_code_prompt_does_not_verify(signup_server): @pytest.mark.parametrize("error", [asyncio.TimeoutError, aiohttp.ClientConnectionError]) def test_transport_failures_are_sanitized(error): session = MagicMock() - session.post.return_value.__aenter__ = AsyncMock(side_effect=error("secret")) + session.stream.return_value.__aenter__ = AsyncMock(side_effect=error("secret")) with pytest.raises(LoginError, match="check your connection") as exc: - asyncio.run(_post_authentication_attempt(session, "/path", {})) + asyncio.run(_post_authentication_attempt(session, Route("POST", "/path"), {})) assert "secret" not in str(exc.value) - session.post.assert_called_once() + session.stream.assert_called_once() def test_two_step_login_across_processes(signup_server, tmp_path): @@ -257,9 +258,9 @@ def test_two_step_login_across_processes(signup_server, tmp_path): command = [ sys.executable, "-c", - "from runpod.rp_cli import update; " + "from runpod.cli import update; " "update.start_background_check = lambda: None; " - "from runpod.rp_cli.main import run; run()", + "from runpod.cli.main import run; run()", "login", "--agent", "--profile", @@ -313,12 +314,12 @@ def test_two_step_login_across_processes(signup_server, tmp_path): def test_two_step_rejected_code_can_be_retried(signup_server, monkeypatch, tmp_path): from click.testing import CliRunner - from runpod.apps.auth import load_agent_login, pending_agent_login_path - from runpod.cli.groups.config import functions - from runpod.rp_cli.main import cli + from runpod.auth import credentials as functions + from runpod.auth.login import load_agent_login, pending_agent_login_path + from runpod.cli.main import cli monkeypatch.setattr(functions, "CREDENTIAL_FILE", str(tmp_path / "config.toml")) - monkeypatch.setattr("runpod.rp_cli.update.start_background_check", lambda: None) + monkeypatch.setattr("runpod.cli.update.start_background_check", lambda: None) monkeypatch.setattr( "click.prompt", MagicMock(side_effect=AssertionError("unexpected prompt")) ) diff --git a/tests/test_auth/test_api.py b/tests/test_auth/test_api.py new file mode 100644 index 000000000..4ebea7455 --- /dev/null +++ b/tests/test_auth/test_api.py @@ -0,0 +1,74 @@ +"""account authentication transport.""" + +from unittest.mock import AsyncMock, patch + +import aiohttp +import pytest + +import runpod +from runpod.auth.api import AuthApiClient +from runpod.error import AuthenticationError, QueryError + + +@pytest.fixture(autouse=True) +def stored_key(monkeypatch): + monkeypatch.setattr(runpod, "api_key", "stored-key") + + +def _respond(data): + return AsyncMock(return_value={"data": data}) + + +class TestAuthRequests: + async def test_create_auth_request_is_anonymous(self): + client = AuthApiClient() + transport = _respond( + {"createFlashAuthRequest": {"id": "req1", "status": "PENDING"}} + ) + with patch("runpod.auth.api.run_graphql_query_async", transport): + result = await client.create_auth_request() + assert result["id"] == "req1" + assert transport.call_args[1]["anonymous"] is True + + async def test_verify_api_key_sends_the_pasted_key(self): + client = AuthApiClient() + transport = _respond({"myself": {"id": "user1"}}) + with patch("runpod.auth.api.run_graphql_query_async", transport): + assert await client.verify_api_key("rpa_new") is True + assert transport.call_args[1]["api_key"] == "rpa_new" + assert transport.call_args[1].get("anonymous", False) is False + + @pytest.mark.parametrize( + "outcome", + [ + AuthenticationError("Unauthorized request"), + QueryError("invalid api key", "query"), + {"data": {"myself": None}}, + {"data": None}, + ], + ) + async def test_verify_api_key_rejects(self, outcome): + transport = AsyncMock() + if isinstance(outcome, Exception): + transport.side_effect = outcome + else: + transport.return_value = outcome + with patch("runpod.auth.api.run_graphql_query_async", transport): + assert await AuthApiClient().verify_api_key("rpa_bad") is False + + async def test_verify_api_key_raises_on_transport_error(self): + transport = AsyncMock(side_effect=aiohttp.ClientConnectionError("down")) + with patch("runpod.auth.api.run_graphql_query_async", transport): + with pytest.raises(aiohttp.ClientConnectionError): + await AuthApiClient().verify_api_key("rpa_new") + + async def test_status_check_is_anonymous_and_never_asks_for_the_key(self): + client = AuthApiClient() + transport = _respond( + {"flashAuthRequestStatus": {"id": "req1", "status": "DENIED"}} + ) + with patch("runpod.auth.api.run_graphql_query_async", transport): + result = await client.get_auth_request_status("req1") + assert result["status"] == "DENIED" + assert transport.call_args[1]["anonymous"] is True + assert "apiKey" not in transport.call_args[0][0] diff --git a/tests/test_cli/test_cli_groups/test_config_functions.py b/tests/test_auth/test_credentials.py similarity index 70% rename from tests/test_cli/test_cli_groups/test_config_functions.py rename to tests/test_auth/test_credentials.py index 75c34522e..f1ad2a353 100644 --- a/tests/test_cli/test_cli_groups/test_config_functions.py +++ b/tests/test_auth/test_credentials.py @@ -5,7 +5,7 @@ import unittest from unittest.mock import mock_open, patch -from runpod.cli.groups.config import functions +from runpod.auth import credentials as functions class TestConfig(unittest.TestCase): @@ -14,14 +14,14 @@ class TestConfig(unittest.TestCase): def setUp(self) -> None: self.sample_credentials = "[default]\n" 'api_key = "RUNPOD_API_KEY"\n' - @patch("runpod.cli.groups.config.functions.os.replace") - @patch("runpod.cli.groups.config.functions.os.unlink") - @patch("runpod.cli.groups.config.functions.os.fdopen", new_callable=mock_open) - @patch("runpod.cli.groups.config.functions.tempfile.mkstemp") - @patch("runpod.cli.groups.config.functions.tomlkit.dump") - @patch("runpod.cli.groups.config.functions.tomlkit.document") - @patch("runpod.cli.groups.config.functions.Path.touch") - @patch("runpod.cli.groups.config.functions.os.makedirs") + @patch("runpod.auth.credentials.os.replace") + @patch("runpod.auth.credentials.os.unlink") + @patch("runpod.auth.credentials.os.fdopen", new_callable=mock_open) + @patch("runpod.auth.credentials.tempfile.mkstemp") + @patch("runpod.auth.credentials.tomlkit.dump") + @patch("runpod.auth.credentials.tomlkit.document") + @patch("runpod.auth.credentials.Path.touch") + @patch("runpod.auth.credentials.os.makedirs") @patch("builtins.open", new_callable=mock_open, read_data="") def test_set_credentials( self, mock_file, _mock_makedirs, _mock_touch, mock_document, @@ -36,7 +36,7 @@ def test_set_credentials( assert any( call.args[0] == functions.CREDENTIAL_FILE - and len(call.args) == 1 # default read mode + and len(call.args) == 1 and call.kwargs.get("encoding") == "UTF-8" for call in mock_file.call_args_list ) @@ -50,13 +50,13 @@ def test_set_credentials( "Profile already exists. Use set_credentials(overwrite=True) to update.", ) - @patch("runpod.cli.groups.config.functions.os.replace") - @patch("runpod.cli.groups.config.functions.os.unlink") - @patch("runpod.cli.groups.config.functions.os.fdopen", new_callable=mock_open) - @patch("runpod.cli.groups.config.functions.tempfile.mkstemp") - @patch("runpod.cli.groups.config.functions.tomlkit.dump") - @patch("runpod.cli.groups.config.functions.Path.touch") - @patch("runpod.cli.groups.config.functions.os.makedirs") + @patch("runpod.auth.credentials.os.replace") + @patch("runpod.auth.credentials.os.unlink") + @patch("runpod.auth.credentials.os.fdopen", new_callable=mock_open) + @patch("runpod.auth.credentials.tempfile.mkstemp") + @patch("runpod.auth.credentials.tomlkit.dump") + @patch("runpod.auth.credentials.Path.touch") + @patch("runpod.auth.credentials.os.makedirs") @patch( "builtins.open", new_callable=mock_open, @@ -79,8 +79,8 @@ def test_set_credentials_preserves_existing_profiles( assert dumped_config["profile2"]["api_key"] == "NEW_KEY" @patch("builtins.open", new_callable=mock_open()) - @patch("runpod.cli.groups.config.functions.toml.load") - @patch("runpod.cli.groups.config.functions.os.path.exists") + @patch("runpod.auth.credentials.toml.load") + @patch("runpod.auth.credentials.os.path.exists") def test_check_credentials(self, mock_exists, mock_toml_load, mock_file): """mock_open_call Tests the check_credentials function. @@ -109,7 +109,7 @@ def test_check_credentials(self, mock_exists, mock_toml_load, mock_file): assert passed is True @patch("os.path.exists", return_value=True) - @patch("runpod.cli.groups.config.functions.toml.load") + @patch("runpod.auth.credentials.toml.load") @patch( "builtins.open", new_callable=mock_open, read_data='[default]\nkey = "value"' ) @@ -126,7 +126,7 @@ def test_get_credentials_existing_profile( assert mock_exists.called @patch("os.path.exists", return_value=True) - @patch("runpod.cli.groups.config.functions.toml.load") + @patch("runpod.auth.credentials.toml.load") @patch( "builtins.open", new_callable=mock_open, read_data='[default]\nkey = "value"' ) @@ -142,9 +142,9 @@ def test_get_credentials_non_existent_profile( assert mock_open_call.called assert mock_exists.called - @patch("runpod.cli.groups.config.functions.os.path.exists", return_value=True) + @patch("runpod.auth.credentials.os.path.exists", return_value=True) @patch( - "runpod.cli.groups.config.functions.toml.load", + "runpod.auth.credentials.toml.load", side_effect=ValueError("Invalid value"), ) @patch("builtins.open", new_callable=mock_open) @@ -155,9 +155,9 @@ def test_get_credentials_corrupted_toml( result = functions.get_credentials("default") assert result is None - @patch("runpod.cli.groups.config.functions.os.path.exists", return_value=True) + @patch("runpod.auth.credentials.os.path.exists", return_value=True) @patch( - "runpod.cli.groups.config.functions.toml.load", + "runpod.auth.credentials.toml.load", side_effect=TypeError("bad type"), ) @patch("builtins.open", new_callable=mock_open) @@ -168,13 +168,13 @@ def test_get_credentials_type_error( result = functions.get_credentials("default") assert result is None - @patch("runpod.cli.groups.config.functions.os.replace") - @patch("runpod.cli.groups.config.functions.os.unlink") - @patch("runpod.cli.groups.config.functions.os.fdopen", new_callable=mock_open) - @patch("runpod.cli.groups.config.functions.tempfile.mkstemp") - @patch("runpod.cli.groups.config.functions.tomlkit.dump") - @patch("runpod.cli.groups.config.functions.Path.touch") - @patch("runpod.cli.groups.config.functions.os.makedirs") + @patch("runpod.auth.credentials.os.replace") + @patch("runpod.auth.credentials.os.unlink") + @patch("runpod.auth.credentials.os.fdopen", new_callable=mock_open) + @patch("runpod.auth.credentials.tempfile.mkstemp") + @patch("runpod.auth.credentials.tomlkit.dump") + @patch("runpod.auth.credentials.Path.touch") + @patch("runpod.auth.credentials.os.makedirs") @patch( "builtins.open", new_callable=mock_open, @@ -191,13 +191,13 @@ def test_set_credentials_overwrite_replaces_existing_profile( dumped_config = mock_dump.call_args[0][0] assert dumped_config["default"]["api_key"] == "NEW_KEY" - @patch("runpod.cli.groups.config.functions.os.replace") - @patch("runpod.cli.groups.config.functions.os.unlink") - @patch("runpod.cli.groups.config.functions.os.fdopen", new_callable=mock_open) - @patch("runpod.cli.groups.config.functions.tempfile.mkstemp") - @patch("runpod.cli.groups.config.functions.tomlkit.dump", side_effect=OSError("disk full")) - @patch("runpod.cli.groups.config.functions.Path.touch") - @patch("runpod.cli.groups.config.functions.os.makedirs") + @patch("runpod.auth.credentials.os.replace") + @patch("runpod.auth.credentials.os.unlink") + @patch("runpod.auth.credentials.os.fdopen", new_callable=mock_open) + @patch("runpod.auth.credentials.tempfile.mkstemp") + @patch("runpod.auth.credentials.tomlkit.dump", side_effect=OSError("disk full")) + @patch("runpod.auth.credentials.Path.touch") + @patch("runpod.auth.credentials.os.makedirs") @patch("builtins.open", new_callable=mock_open, read_data="") def test_set_credentials_cleans_up_temp_on_dump_failure( self, _mock_file, _mock_makedirs, _mock_touch, _mock_dump, @@ -211,12 +211,12 @@ def test_set_credentials_cleans_up_temp_on_dump_failure( mock_unlink.assert_called_once_with("/tmp/cred.toml") mock_replace.assert_not_called() - @patch("runpod.cli.groups.config.functions.os.replace") - @patch("runpod.cli.groups.config.functions.os.unlink") - @patch("runpod.cli.groups.config.functions.tempfile.mkstemp") - @patch("runpod.cli.groups.config.functions.tomlkit.dump") - @patch("runpod.cli.groups.config.functions.Path.touch") - @patch("runpod.cli.groups.config.functions.os.makedirs") + @patch("runpod.auth.credentials.os.replace") + @patch("runpod.auth.credentials.os.unlink") + @patch("runpod.auth.credentials.tempfile.mkstemp") + @patch("runpod.auth.credentials.tomlkit.dump") + @patch("runpod.auth.credentials.Path.touch") + @patch("runpod.auth.credentials.os.makedirs") @patch("builtins.open", new_callable=mock_open, read_data="not valid toml {{{") def test_set_credentials_corrupted_toml_raises( self, _mock_file, _mock_makedirs, _mock_touch, _mock_dump, diff --git a/tests/test_apps/test_auth.py b/tests/test_auth/test_login.py similarity index 98% rename from tests/test_apps/test_auth.py rename to tests/test_auth/test_login.py index 14ca01349..39bfa0aea 100644 --- a/tests/test_apps/test_auth.py +++ b/tests/test_auth/test_login.py @@ -6,7 +6,7 @@ import aiohttp import pytest -from runpod.apps.auth import LoginError, auth_url, browser_login +from runpod.auth.login import LoginError, auth_url, browser_login def _api(valid_keys=("rpa_new",), status="PENDING"): diff --git a/tests/test_auth/test_package.py b/tests/test_auth/test_package.py new file mode 100644 index 000000000..8fb602711 --- /dev/null +++ b/tests/test_auth/test_package.py @@ -0,0 +1,113 @@ +"""shared authentication and package boundaries.""" + +import importlib +import os +import subprocess +import sys + +import pytest + +import runpod +from runpod.auth import credentials, load_api_key, resolve_api_key +from runpod.error import AuthenticationError + + +def test_environment_key_precedes_stored_profile(monkeypatch): + monkeypatch.setenv("RUNPOD_API_KEY", "environment-key") + + def unexpected_read(*args): + raise AssertionError("credentials should not be read") + + monkeypatch.setattr(credentials, "get_credentials", unexpected_read) + assert load_api_key("agent") == "environment-key" + + +def test_load_selected_profile(monkeypatch, tmp_path): + monkeypatch.delenv("RUNPOD_API_KEY", raising=False) + monkeypatch.setattr(credentials, "CREDENTIAL_FILE", str(tmp_path / "config.toml")) + credentials.set_credentials("default-key") + credentials.set_credentials("agent-key", profile="agent") + assert load_api_key() == "default-key" + assert load_api_key("agent") == "agent-key" + assert load_api_key("missing") is None + + +def test_missing_credentials_are_optional(monkeypatch, tmp_path): + monkeypatch.delenv("RUNPOD_API_KEY", raising=False) + monkeypatch.setattr(credentials, "CREDENTIAL_FILE", str(tmp_path / "missing.toml")) + assert load_api_key() is None + + +def test_resolve_explicit_and_configured_keys(monkeypatch): + monkeypatch.setattr(runpod, "api_key", "configured-key") + assert resolve_api_key("explicit-key") == "explicit-key" + assert resolve_api_key() == "configured-key" + monkeypatch.setattr(runpod, "api_key", None) + with pytest.raises(AuthenticationError, match="No API key provided"): + resolve_api_key() + + +def test_transports_share_key_resolution(): + from runpod.api import graphql, rest + + assert graphql._resolve_api_key is resolve_api_key + assert rest._resolve_api_key is resolve_api_key + + +def test_public_credential_functions_use_auth_package(): + assert runpod.get_credentials is credentials.get_credentials + assert runpod.set_credentials is credentials.set_credentials + assert runpod.check_credentials is credentials.check_credentials + + +def test_flash_credential_import_uses_shared_module(monkeypatch, tmp_path): + import runpod.cli.groups.config.functions as flash_credentials + + assert flash_credentials is credentials + assert importlib.import_module("runpod.cli.groups.config.functions") is credentials + monkeypatch.setattr( + flash_credentials, "CREDENTIAL_FILE", str(tmp_path / "config.toml") + ) + flash_credentials.set_credentials("profile-key") + assert credentials.get_credentials() == {"api_key": "profile-key"} + + +def test_login_import_does_not_load_apps_or_cli(): + result = subprocess.run( + [ + sys.executable, + "-c", + "import sys, runpod.auth.login; " + "assert 'runpod.apps' not in sys.modules; " + "assert 'runpod.cli' not in sys.modules", + ], + capture_output=True, + text=True, + check=False, + ) + assert result.returncode == 0, result.stderr + + +@pytest.mark.parametrize("environment_key", [None, "environment-key"]) +def test_sdk_import_does_not_load_cli_or_login(monkeypatch, tmp_path, environment_key): + monkeypatch.setenv("HOME", str(tmp_path)) + monkeypatch.delenv("RUNPOD_API_KEY", raising=False) + if environment_key is not None: + monkeypatch.setenv("RUNPOD_API_KEY", environment_key) + result = subprocess.run( + [ + sys.executable, + "-c", + "import sys, runpod; " + "assert 'runpod.cli' not in sys.modules; " + "assert 'runpod.auth.login' not in sys.modules; " + "assert 'runpod.apps' not in sys.modules; " + "assert 'click' not in sys.modules; " + "assert 'paramiko' not in sys.modules", + ], + env=os.environ.copy(), + capture_output=True, + text=True, + check=False, + ) + assert result.returncode == 0, result.stderr diff --git a/tests/test_cli/test_agent_login.py b/tests/test_cli/test_agent_login.py index 7473f7113..da73386e1 100644 --- a/tests/test_cli/test_agent_login.py +++ b/tests/test_cli/test_agent_login.py @@ -7,9 +7,9 @@ import pytest from click.testing import CliRunner -from runpod.apps.auth import LoginError -from runpod.cli.groups.config import functions -from runpod.rp_cli.main import cli +from runpod.auth import credentials as functions +from runpod.auth.login import LoginError +from runpod.cli.main import cli @pytest.fixture @@ -19,16 +19,16 @@ def login_env(monkeypatch, tmp_path): '[default]\napi_key = "keep-default"\n' '[agent]\napi_key = "old-agent"\n' ) monkeypatch.setattr(functions, "CREDENTIAL_FILE", str(credentials)) - monkeypatch.setattr("runpod.rp_cli.update.start_background_check", lambda: None) + monkeypatch.setattr("runpod.cli.update.start_background_check", lambda: None) browser = AsyncMock(side_effect=AssertionError("unexpected browser login")) launch = MagicMock(side_effect=AssertionError("unexpected browser launch")) - monkeypatch.setattr("runpod.apps.auth.browser_login", browser) + monkeypatch.setattr("runpod.auth.login.browser_login", browser) monkeypatch.setattr("click.launch", launch) monkeypatch.setattr( "click.prompt", MagicMock(side_effect=AssertionError("unexpected prompt")) ) monkeypatch.setattr( - "runpod.apps.auth.start_agent_login", + "runpod.auth.login.start_agent_login", AsyncMock( return_value={ "attempt_id": "att_test", @@ -41,7 +41,7 @@ def login_env(monkeypatch, tmp_path): def test_agent_saves_named_profile_and_hides_code_and_key(login_env, monkeypatch): - from runpod.apps.auth import load_agent_login + from runpod.auth.login import load_agent_login async def authenticate(email): assert email == "owner@example.com" @@ -51,9 +51,9 @@ async def authenticate(email): "api_url": "https://api.runpod.io/v2/signup/authentication-attempts", } - monkeypatch.setattr("runpod.apps.auth.start_agent_login", authenticate) + monkeypatch.setattr("runpod.auth.login.start_agent_login", authenticate) verify = AsyncMock(return_value="rpa_new-agent-key") - monkeypatch.setattr("runpod.apps.auth.verify_agent_login", verify) + monkeypatch.setattr("runpod.auth.login.verify_agent_login", verify) result = CliRunner().invoke( cli, ["login", "--agent", "--email", " owner@example.com ", "--profile", "agent"], @@ -96,7 +96,7 @@ def test_invalid_options_have_no_auth_or_storage_side_effects( ): before = login_env.read_bytes() authenticate = AsyncMock() - monkeypatch.setattr("runpod.apps.auth.start_agent_login", authenticate) + monkeypatch.setattr("runpod.auth.login.start_agent_login", authenticate) result = CliRunner().invoke(cli, ["login", *args]) assert result.exit_code == 2 assert message in result.output @@ -107,7 +107,7 @@ def test_invalid_options_have_no_auth_or_storage_side_effects( def test_code_format_is_validated_without_echoing_input(login_env, monkeypatch): verify = AsyncMock(return_value="rpa_test") - monkeypatch.setattr("runpod.apps.auth.verify_agent_login", verify) + monkeypatch.setattr("runpod.auth.login.verify_agent_login", verify) runner = CliRunner() sent = runner.invoke( cli, ["login", "--agent", "--email", "owner@example.com", "--no-open"] @@ -139,7 +139,7 @@ def test_email_request_exits_without_stdin_and_preserves_credentials(login_env): def test_auth_error_preserves_credentials(login_env, monkeypatch): before = login_env.read_bytes() monkeypatch.setattr( - "runpod.apps.auth.start_agent_login", + "runpod.auth.login.start_agent_login", AsyncMock(side_effect=LoginError("code rejected")), ) result = CliRunner().invoke( @@ -155,7 +155,7 @@ def test_credential_write_failure_is_reported(login_env, monkeypatch): sent = CliRunner().invoke(cli, ["login", "--agent", "--email", "owner@example.com"]) assert sent.exit_code == 0, sent.output monkeypatch.setattr( - "runpod.apps.auth.verify_agent_login", AsyncMock(return_value="rpa_test") + "runpod.auth.login.verify_agent_login", AsyncMock(return_value="rpa_test") ) monkeypatch.setattr( functions, "set_credentials", MagicMock(side_effect=OSError("disk full")) @@ -169,7 +169,7 @@ def test_credential_write_failure_is_reported(login_env, monkeypatch): def test_direct_key_login_does_not_start_email_flow(login_env, monkeypatch): authenticate = AsyncMock() - monkeypatch.setattr("runpod.apps.auth.start_agent_login", authenticate) + monkeypatch.setattr("runpod.auth.login.start_agent_login", authenticate) result = CliRunner().invoke(cli, ["login", "--api-key", "rpa_direct"]) assert result.exit_code == 0 authenticate.assert_not_called() @@ -183,7 +183,7 @@ def test_agent_retry_explains_rejection_without_resending_notice( verify = AsyncMock( side_effect=[LoginError("verification code rejected"), "rpa_test"] ) - monkeypatch.setattr("runpod.apps.auth.verify_agent_login", verify) + monkeypatch.setattr("runpod.auth.login.verify_agent_login", verify) runner = CliRunner() sent = runner.invoke(cli, ["login", "--agent", "--email", "owner@example.com"]) assert sent.exit_code == 0, sent.output @@ -237,8 +237,8 @@ def test_two_step_invalid_options_do_not_authenticate( ): start = AsyncMock() verify = AsyncMock() - monkeypatch.setattr("runpod.apps.auth.start_agent_login", start) - monkeypatch.setattr("runpod.apps.auth.verify_agent_login", verify) + monkeypatch.setattr("runpod.auth.login.start_agent_login", start) + monkeypatch.setattr("runpod.auth.login.verify_agent_login", verify) before = login_env.read_bytes() result = CliRunner().invoke(cli, ["login", *args]) assert result.exit_code == 2 @@ -251,7 +251,7 @@ def test_two_step_invalid_options_do_not_authenticate( def test_two_step_missing_state_does_not_authenticate(login_env, monkeypatch): verify = AsyncMock() - monkeypatch.setattr("runpod.apps.auth.verify_agent_login", verify) + monkeypatch.setattr("runpod.auth.login.verify_agent_login", verify) result = CliRunner().invoke(cli, ["login", "--agent", "--code", "012345"]) assert result.exit_code == 1 assert "no pending login" in result.output @@ -262,11 +262,11 @@ def test_two_step_missing_state_does_not_authenticate(login_env, monkeypatch): "content", ["not json", "[]", "{}", '{"verifier": "sensitive"}'] ) def test_two_step_invalid_state_is_sanitized(login_env, monkeypatch, content): - from runpod.apps.auth import pending_agent_login_path + from runpod.auth.login import pending_agent_login_path pending_agent_login_path("default").write_text(content) verify = AsyncMock() - monkeypatch.setattr("runpod.apps.auth.verify_agent_login", verify) + monkeypatch.setattr("runpod.auth.login.verify_agent_login", verify) result = CliRunner().invoke(cli, ["login", "--agent", "--code", "012345"]) assert result.exit_code == 1 assert "invalid pending login" in result.output @@ -275,7 +275,7 @@ def test_two_step_invalid_state_is_sanitized(login_env, monkeypatch, content): def test_pending_logins_are_private_and_profile_scoped(login_env): - from runpod.apps.auth import ( + from runpod.auth.login import ( load_agent_login, pending_agent_login_path, save_agent_login, @@ -296,7 +296,7 @@ def test_pending_logins_are_private_and_profile_scoped(login_env): def test_two_step_api_change_does_not_send_verifier(login_env, monkeypatch): - from runpod.apps.auth import save_agent_login + from runpod.auth.login import save_agent_login save_agent_login( { @@ -308,7 +308,7 @@ def test_two_step_api_change_does_not_send_verifier(login_env, monkeypatch): ) monkeypatch.setenv("RUNPOD_API_BASE_URL", "https://api.runpod.io") post = AsyncMock() - monkeypatch.setattr("runpod.apps.auth._post_authentication_attempt", post) + monkeypatch.setattr("runpod.auth.login._post_authentication_attempt", post) result = CliRunner().invoke(cli, ["login", "--agent", "--code", "012345"]) assert result.exit_code == 1 assert "different API" in result.output @@ -349,7 +349,7 @@ def test_email_request_prints_shell_safe_completion_command(login_env, profile): def test_pending_login_atomic_write_preserves_previous_attempt(login_env, monkeypatch): - from runpod.apps.auth import ( + from runpod.auth.login import ( load_agent_login, pending_agent_login_path, save_agent_login, @@ -362,7 +362,7 @@ def test_pending_login_atomic_write_preserves_previous_attempt(login_env, monkey } save_agent_login(attempt, "default") monkeypatch.setattr( - "runpod.apps.auth.os.replace", MagicMock(side_effect=OSError("disk full")) + "runpod.auth.login.os.replace", MagicMock(side_effect=OSError("disk full")) ) with pytest.raises(OSError, match="disk full"): save_agent_login({**attempt, "attempt_id": "att_new"}, "default") @@ -373,7 +373,7 @@ def test_pending_login_atomic_write_preserves_previous_attempt(login_env, monkey def test_two_step_credential_write_failure_keeps_pending_state(login_env, monkeypatch): - from runpod.apps.auth import load_agent_login, save_agent_login + from runpod.auth.login import load_agent_login, save_agent_login attempt = { "attempt_id": "att_test", @@ -382,7 +382,7 @@ def test_two_step_credential_write_failure_keeps_pending_state(login_env, monkey } save_agent_login(attempt, "default") monkeypatch.setattr( - "runpod.apps.auth.verify_agent_login", AsyncMock(return_value="rpa_test") + "runpod.auth.login.verify_agent_login", AsyncMock(return_value="rpa_test") ) monkeypatch.setattr( functions, "set_credentials", MagicMock(side_effect=OSError("disk full")) diff --git a/tests/test_cli/test_catalog_command.py b/tests/test_cli/test_catalog_command.py index 70ede1d45..38a805d62 100644 --- a/tests/test_cli/test_catalog_command.py +++ b/tests/test_cli/test_catalog_command.py @@ -7,7 +7,7 @@ from click.testing import CliRunner from runpod import error -from runpod.rp_cli.main import cli +from runpod.cli.main import cli GPUS = [ { @@ -88,16 +88,16 @@ @pytest.fixture(autouse=True) def wide_console(monkeypatch): - from runpod.rp_cli import console as ui + from runpod.cli import console as ui monkeypatch.setattr(ui.console, "_width", 200) def _invoke(args, gpus=GPUS, cpus=CPUS, datacenters=DATACENTERS): with ( - patch("runpod.rp_cli.compute.list_gpus", return_value=gpus) as list_gpus, - patch("runpod.rp_cli.compute.list_cpus", return_value=cpus) as list_cpus, - patch("runpod.rp_cli.compute.list_datacenters", return_value=datacenters), + patch("runpod.cli.compute.list_gpus", return_value=gpus) as list_gpus, + patch("runpod.cli.compute.list_cpus", return_value=cpus) as list_cpus, + patch("runpod.cli.compute.list_datacenters", return_value=datacenters), ): result = CliRunner().invoke(cli, ["catalog", *args]) return result, list_gpus, list_cpus @@ -108,7 +108,7 @@ class TestGpuCatalog: "cloud, expected", [(None, 10), ("secure", 1), ("community", 10)] ) def test_max_count_matches_cloud(self, cloud, expected): - from runpod.rp_cli.catalog import _gpu_columns + from runpod.cli.catalog import _gpu_columns columns = dict(_gpu_columns("POD", 1, cloud)) assert columns["MAX"](GPUS[1]) == expected @@ -209,7 +209,7 @@ def test_conflicting_flags(self): def test_api_error_is_clean(self): with patch( - "runpod.rp_cli.compute.list_gpus", + "runpod.cli.compute.list_gpus", side_effect=error.AuthenticationError("Unauthorized request"), ): result = CliRunner().invoke(cli, ["catalog"]) @@ -249,7 +249,7 @@ def test_unknown(self): ], ) def test_per_vcpu_price_precision(self, product, price, expected): - from runpod.rp_cli.catalog import _cpu_columns + from runpod.cli.catalog import _cpu_columns tier = "serverlessPerVcpu" if product == "SERVERLESS" else "securePerVcpu" row = dict(CPUS[0], price={tier: price}) @@ -285,9 +285,9 @@ def test_per_vcpu_price_precision(self, product, price, expected): ) def test_inapplicable_flags_fail_before_fetch(mode, options, offending_flag, as_json): with ( - patch("runpod.rp_cli.compute.list_datacenters") as list_datacenters, - patch("runpod.rp_cli.compute.list_gpus") as list_gpus, - patch("runpod.rp_cli.compute.list_cpus") as list_cpus, + patch("runpod.cli.compute.list_datacenters") as list_datacenters, + patch("runpod.cli.compute.list_gpus") as list_gpus, + patch("runpod.cli.compute.list_cpus") as list_cpus, ): result = CliRunner().invoke( cli, ["catalog", *mode, *options, *(["--json"] if as_json else [])] diff --git a/tests/test_cli/test_cli_api.py b/tests/test_cli/test_cli_api.py index a7c6785d9..c9c55b313 100644 --- a/tests/test_cli/test_cli_api.py +++ b/tests/test_cli/test_cli_api.py @@ -7,7 +7,7 @@ import requests from runpod import error -from runpod.rp_cli import api +from runpod.cli import api class TestApi: diff --git a/tests/test_cli/test_cli_groups/test_ssh_dispatch.py b/tests/test_cli/test_cli_groups/test_ssh_dispatch.py index fa74cc130..57e2648ba 100644 --- a/tests/test_cli/test_cli_groups/test_ssh_dispatch.py +++ b/tests/test_cli/test_cli_groups/test_ssh_dispatch.py @@ -4,7 +4,7 @@ from click.testing import CliRunner -from runpod.rp_cli.main import cli +from runpod.cli.main import cli class TestSSHDispatch: diff --git a/tests/test_cli/test_cli_logs.py b/tests/test_cli/test_cli_logs.py index f7044f38c..dc3792453 100644 --- a/tests/test_cli/test_cli_logs.py +++ b/tests/test_cli/test_cli_logs.py @@ -5,7 +5,7 @@ import pytest from runpod.apps.errors import AppHTTPError -from runpod.rp_cli import logs +from runpod.cli import logs def event(line="hello", ts="2026-01-01T00:00:00Z"): diff --git a/tests/test_cli/test_cli_options.py b/tests/test_cli/test_cli_options.py index 6587bc953..e9c55f389 100644 --- a/tests/test_cli/test_cli_options.py +++ b/tests/test_cli/test_cli_options.py @@ -3,8 +3,8 @@ import click import pytest -from runpod.rp_cli.compute import ResolutionError -from runpod.rp_cli.options import container_fields, parse_env +from runpod.cli.compute import ResolutionError +from runpod.cli.options import container_fields, parse_env def test_env_values_preserve_equals_and_allow_empty_values(): @@ -64,7 +64,7 @@ def list_registries(path, collection): assert (path, collection) == ("/v2/registries", "registries") return [{"id": "reg1", "name": "private"}] - monkeypatch.setattr("runpod.rp_cli.options.list_all", list_registries) + monkeypatch.setattr("runpod.cli.options.list_all", list_registries) assert container_fields({"registry": registry}) == {"registry": "reg1"} @@ -72,12 +72,12 @@ def test_container_fields_clear_registry_without_lookup(monkeypatch): def unexpected_lookup(*args): pytest.fail("clearing a registry must not fetch credentials") - monkeypatch.setattr("runpod.rp_cli.options.list_all", unexpected_lookup) + monkeypatch.setattr("runpod.cli.options.list_all", unexpected_lookup) assert container_fields({"registry": ""}) == {"registry": None} def test_container_fields_reject_unknown_registry(monkeypatch): - monkeypatch.setattr("runpod.rp_cli.options.list_all", lambda *args: []) + monkeypatch.setattr("runpod.cli.options.list_all", lambda *args: []) with pytest.raises(ResolutionError, match="unknown registry credential"): container_fields({"registry": "missing"}) diff --git a/tests/test_cli/test_cli_output.py b/tests/test_cli/test_cli_output.py index 1c08e3dce..fa8a4b8d9 100644 --- a/tests/test_cli/test_cli_output.py +++ b/tests/test_cli/test_cli_output.py @@ -6,7 +6,7 @@ import pytest from runpod import error -from runpod.rp_cli import output +from runpod.cli import output class TestOutputHelpers: @@ -17,7 +17,7 @@ def test_cell(self): assert output.cell(3) == "3" def test_print_table_keeps_ids_and_values_whole(self, monkeypatch, capsys): - from runpod.rp_cli import console as ui + from runpod.cli import console as ui monkeypatch.setattr(ui.console, "_width", 40) rows = [{"id": "cmvfsn771000007jp15tn8esm", "type": "high_performance"}] diff --git a/tests/test_cli/test_compatibility.py b/tests/test_cli/test_compatibility.py new file mode 100644 index 000000000..05d6a4c53 --- /dev/null +++ b/tests/test_cli/test_compatibility.py @@ -0,0 +1,21 @@ +"""compatibility imports for resource commands.""" + +from importlib import import_module + +import pytest +from click.testing import CliRunner + + +@pytest.mark.parametrize("name", ["template", "user", "datacenter"]) +def test_compatibility_modules_share_canonical_commands(name): + canonical = import_module(f"runpod.cli.{name}") + compatibility = import_module(f"runpod.rp_cli.{name}") + main = import_module("runpod.cli.main") + + assert compatibility is canonical + assert import_module("runpod.rp_cli.main") is main + assert main.cli.commands[name] is getattr(compatibility, name) + + result = CliRunner().invoke(getattr(compatibility, name), ["--help"]) + assert result.exit_code == 0, result.output + assert "Usage:" in result.output diff --git a/tests/test_cli/test_compute.py b/tests/test_cli/test_compute.py index d7124b4c8..2376e493b 100644 --- a/tests/test_cli/test_compute.py +++ b/tests/test_cli/test_compute.py @@ -4,7 +4,7 @@ import pytest -from runpod.rp_cli import compute +from runpod.cli import compute GPUS = [ {"id": "NVIDIA GeForce RTX 4090", "name": "RTX 4090", "pool": "ADA_24"}, diff --git a/tests/test_cli/test_console.py b/tests/test_cli/test_console.py index 6a1027030..307870e37 100644 --- a/tests/test_cli/test_console.py +++ b/tests/test_cli/test_console.py @@ -5,7 +5,7 @@ import pytest from rich.console import Console -from runpod.rp_cli import console as ui +from runpod.cli import console as ui @pytest.fixture(autouse=True) diff --git a/tests/test_cli/test_datacenter_command.py b/tests/test_cli/test_datacenter_command.py index e128d679b..862cec1f6 100644 --- a/tests/test_cli/test_datacenter_command.py +++ b/tests/test_cli/test_datacenter_command.py @@ -8,7 +8,7 @@ from requests import Timeout from runpod import error -from runpod.rp_cli.datacenter import datacenter +from runpod.cli.datacenter import datacenter DATA_CENTERS = [ { @@ -39,7 +39,7 @@ @pytest.fixture(autouse=True) def isolated_requests(monkeypatch): - from runpod.rp_cli import console as ui + from runpod.cli import console as ui monkeypatch.setattr(ui.console, "_width", 200) with patch( @@ -52,7 +52,7 @@ def isolated_requests(monkeypatch): @pytest.fixture def query(): with patch( - "runpod.rp_cli.datacenter.run_graphql_query", + "runpod.cli.datacenter.run_graphql_query", return_value={"data": {"dataCenters": DATA_CENTERS}}, ) as mocked: yield mocked @@ -170,9 +170,9 @@ def test_unknown_option_does_not_query(query): def test_root_datacenter_command(query): - from runpod.rp_cli.main import cli + from runpod.cli.main import cli - with patch("runpod.rp_cli.update.start_background_check"): + with patch("runpod.cli.update.start_background_check"): result = CliRunner().invoke(cli, ["datacenter", "list", "--json"]) assert result.exit_code == 0, result.output assert json.loads(result.output) == DATA_CENTERS diff --git a/tests/test_cli/test_deploy_command.py b/tests/test_cli/test_deploy_command.py index 6f26e154b..70a14520f 100644 --- a/tests/test_cli/test_deploy_command.py +++ b/tests/test_cli/test_deploy_command.py @@ -8,7 +8,7 @@ from runpod.apps.deploy import DeployResult from runpod.apps.utils.names import dev_endpoint_name -from runpod.rp_cli.main import cli +from runpod.cli.main import cli @pytest.fixture(autouse=True) diff --git a/tests/test_cli/test_endpoint_command.py b/tests/test_cli/test_endpoint_command.py index 64fd02290..8440f9a8b 100644 --- a/tests/test_cli/test_endpoint_command.py +++ b/tests/test_cli/test_endpoint_command.py @@ -8,11 +8,9 @@ from click.testing import CliRunner from runpod import error +from runpod.cli import compute, endpoint as ep, endpoint_config as config, output +from runpod.cli.main import cli from runpod.endpoint import runner -from runpod.rp_cli import compute, output -from runpod.rp_cli import endpoint as ep -from runpod.rp_cli import endpoint_config as config -from runpod.rp_cli.main import cli PAGE = {"hasNextPage": False, "nextCursor": None} @@ -193,7 +191,7 @@ def no_network(*args, **kwargs): pytest.fail("endpoint tests must not make real network requests") monkeypatch.setattr(requests.sessions.Session, "request", no_network) - from runpod.rp_cli import console as ui + from runpod.cli import console as ui monkeypatch.setattr(ui.console, "_width", 200) @@ -1028,7 +1026,7 @@ def test_releases(api): def test_logs_routes_options_to_shared_streamer(api, monkeypatch): - from runpod.rp_cli import logs + from runpod.cli import logs show = MagicMock() monkeypatch.setattr(logs, "show_logs", show) @@ -1396,6 +1394,31 @@ def test_purge(api, client): assert json.loads(ok("purge", "ep1", "--yes", "--json"))["removed"] == 3 +@pytest.mark.parametrize("status", [301, 302, 303, 307, 308]) +@pytest.mark.parametrize("action", ["get", "cancel"]) +def test_data_plane_redirect_is_a_sanitized_cli_error(monkeypatch, status, action): + monkeypatch.setattr("runpod.api_key", "synthetic-key") + monkeypatch.setattr("runpod.cli.update.start_background_check", lambda: None) + response = requests.Response() + response.status_code = status + response._content = b"synthetic-secret" + response._content_consumed = True + response.headers["Location"] = "https://redirect.invalid/?token=synthetic-secret" + response.close = MagicMock(wraps=response.close) + send = MagicMock(return_value=response) + monkeypatch.setattr(requests.Session, "request", send) + + result = invoke("job", action, "ep1", "job1") + + assert result.exit_code == 1 + assert isinstance(result.exception, SystemExit) + assert result.output == "Error: unexpected redirect\n" + assert "synthetic-secret" not in result.output + send.assert_called_once() + assert send.call_args.kwargs["allow_redirects"] is False + response.close.assert_called_once() + + def test_data_plane_errors(api, client, monkeypatch): response = requests.Response() response.status_code = 404 diff --git a/tests/test_cli/test_init_command.py b/tests/test_cli/test_init_command.py index 42be0898c..fe1af3146 100644 --- a/tests/test_cli/test_init_command.py +++ b/tests/test_cli/test_init_command.py @@ -3,7 +3,7 @@ from click.testing import CliRunner from runpod.apps.init import create_project, detect_conflicts -from runpod.rp_cli.main import cli +from runpod.cli.main import cli class TestCreateProject: diff --git a/tests/test_cli/test_management_commands.py b/tests/test_cli/test_management_commands.py index 7fe385ab5..490b26452 100644 --- a/tests/test_cli/test_management_commands.py +++ b/tests/test_cli/test_management_commands.py @@ -6,7 +6,7 @@ from click.testing import CliRunner from runpod.apps.manage import UndeployResult -from runpod.rp_cli.main import cli +from runpod.cli.main import cli def _runner(): @@ -351,7 +351,7 @@ class TestLoginCommand: def test_login_updates_only_selected_profile( self, tmp_path, monkeypatch, browser, profile ): - from runpod.cli.groups.config import functions + from runpod.auth import credentials as functions credentials = tmp_path / "config.toml" credentials.write_text( @@ -360,13 +360,13 @@ def test_login_updates_only_selected_profile( '[production]\napi_key = "keep-production"\n' ) monkeypatch.setattr(functions, "CREDENTIAL_FILE", str(credentials)) - monkeypatch.setattr("runpod.rp_cli.main._stdin_is_tty", lambda: True) + monkeypatch.setattr("runpod.cli.main._stdin_is_tty", lambda: True) args = ["login"] if profile != "default": args.extend(["--profile", profile]) args.extend(["--no-open"] if browser else ["--api-key", "new-key"]) with patch( - "runpod.apps.auth.browser_login", AsyncMock(return_value="new-key") + "runpod.auth.login.browser_login", AsyncMock(return_value="new-key") ): result = _runner().invoke(cli, args) @@ -377,7 +377,7 @@ def test_login_updates_only_selected_profile( assert functions.get_credentials("production")["api_key"] == "keep-production" def test_login_saves_to_profile_from_env(self, tmp_path, monkeypatch): - from runpod.cli.groups.config import functions + from runpod.auth import credentials as functions credentials = tmp_path / "config.toml" credentials.write_text('[default]\napi_key = "keep-default"\n') @@ -391,7 +391,7 @@ def test_login_saves_to_profile_from_env(self, tmp_path, monkeypatch): assert functions.get_credentials("default")["api_key"] == "keep-default" def test_login_profile_flag_overrides_env(self, tmp_path, monkeypatch): - from runpod.cli.groups.config import functions + from runpod.auth import credentials as functions credentials = tmp_path / "config.toml" monkeypatch.setattr(functions, "CREDENTIAL_FILE", str(credentials)) @@ -406,12 +406,12 @@ def test_login_profile_flag_overrides_env(self, tmp_path, monkeypatch): assert functions.get_credentials("team") is None def test_browser_flow_error(self): - from runpod.apps.auth import LoginError + from runpod.auth.login import LoginError with ( - patch("runpod.rp_cli.main._stdin_is_tty", return_value=True), + patch("runpod.cli.main._stdin_is_tty", return_value=True), patch( - "runpod.apps.auth.browser_login", + "runpod.auth.login.browser_login", AsyncMock(side_effect=LoginError("api key was rejected")), ), ): @@ -421,24 +421,24 @@ def test_browser_flow_error(self): def test_browser_flow_fails_fast_without_tty(self): login = AsyncMock() - with patch("runpod.apps.auth.browser_login", login): + with patch("runpod.auth.login.browser_login", login): result = _runner().invoke(cli, ["login", "--no-open"]) assert result.exit_code == 1 assert "RUNPOD_API_KEY" in result.output login.assert_not_called() def test_browser_flow_prompts_with_hidden_input(self, tmp_path, monkeypatch): - from runpod.cli.groups.config import functions + from runpod.auth import credentials as functions monkeypatch.setattr(functions, "CREDENTIAL_FILE", str(tmp_path / "c.toml")) api = MagicMock() api.create_auth_request = AsyncMock(return_value={"id": "req-1"}) api.verify_api_key = AsyncMock(return_value=True) with ( - patch("runpod.rp_cli.main._stdin_is_tty", return_value=True), - patch("runpod.apps.auth.AppsApiClient", return_value=api), + patch("runpod.cli.main._stdin_is_tty", return_value=True), + patch("runpod.auth.login.AuthApiClient", return_value=api), patch( - "runpod.rp_cli.main.click.prompt", return_value=" rpa_new " + "runpod.cli.main.click.prompt", return_value=" rpa_new " ) as prompt, ): result = _runner().invoke(cli, ["login", "--no-open"]) diff --git a/tests/test_cli/test_module_entrypoint.py b/tests/test_cli/test_module_entrypoint.py new file mode 100644 index 000000000..8a010a712 --- /dev/null +++ b/tests/test_cli/test_module_entrypoint.py @@ -0,0 +1,33 @@ +"""module entry points dispatch command-line arguments.""" + +import os +import subprocess +import sys +from pathlib import Path + +import pytest + + +@pytest.mark.parametrize("module", ["runpod.cli.main", "runpod.rp_cli.main"]) +@pytest.mark.parametrize( + "arguments, expected", + [(["--help"], "Usage:"), (["completion", "bash"], "_rp_completion")], +) +def test_module_entrypoint(module, arguments, expected, tmp_path): + root = Path(__file__).resolve().parents[2] + result = subprocess.run( + [sys.executable, "-m", module, *arguments], + cwd=root, + env={ + **os.environ, + "HOME": str(tmp_path), + "PYTHONPATH": str(root), + "PYTHONDONTWRITEBYTECODE": "1", + }, + capture_output=True, + text=True, + timeout=30, + ) + assert result.returncode == 0, result.stderr + assert expected in result.stdout + assert "Traceback" not in result.stderr diff --git a/tests/test_cli/test_pod_command.py b/tests/test_cli/test_pod_command.py index 1a93da6d1..80e9baed6 100644 --- a/tests/test_cli/test_pod_command.py +++ b/tests/test_cli/test_pod_command.py @@ -7,8 +7,8 @@ from click.testing import CliRunner from runpod import error -from runpod.rp_cli import pod as pod_module -from runpod.rp_cli.main import cli +from runpod.cli import pod as pod_module +from runpod.cli.main import cli from runpod.user_agent import USER_AGENT GPUS = [ @@ -183,12 +183,12 @@ def made(self, method, path): @pytest.fixture(autouse=True) def cli_environment(monkeypatch): - from runpod.rp_cli import console as ui + from runpod.cli import console as ui monkeypatch.setattr(ui.console, "_width", 200) monkeypatch.setattr(pod_module.time, "sleep", lambda seconds: None) monkeypatch.setattr( - "requests.request", + "requests.Session.request", MagicMock(side_effect=AssertionError("unexpected HTTP request")), ) @@ -196,14 +196,14 @@ def cli_environment(monkeypatch): def _invoke(args, api=None, gpus=GPUS, interactive=False, input=None): api = api or FakeApi() with ( - patch("runpod.rp_cli.pod.run_rest_request", api), - patch("runpod.rp_cli.volume.run_rest_request", api), + patch("runpod.cli.pod.run_rest_request", api), + patch("runpod.cli.volume.run_rest_request", api), patch("runpod.api.rest.run_rest_request", api), - patch("runpod.rp_cli.compute.list_gpus", return_value=gpus) as list_gpus, - patch("runpod.rp_cli.compute.list_cpus", return_value=CPUS) as list_cpus, - patch("runpod.rp_cli.compute.list_datacenters", return_value=DATACENTERS), - patch("runpod.rp_cli.pod.interactive", return_value=interactive), - patch("runpod.rp_cli.output.interactive", return_value=interactive), + patch("runpod.cli.compute.list_gpus", return_value=gpus) as list_gpus, + patch("runpod.cli.compute.list_cpus", return_value=CPUS) as list_cpus, + patch("runpod.cli.compute.list_datacenters", return_value=DATACENTERS), + patch("runpod.cli.pod.interactive", return_value=interactive), + patch("runpod.cli.output.interactive", return_value=interactive), ): result = CliRunner().invoke(cli, ["pod", *args], input=input) result.api, result.list_gpus, result.list_cpus = api, list_gpus, list_cpus @@ -1358,14 +1358,14 @@ def test_sync_is_mounted(self): ], ) def test_logs_forward_options(args, expected): - with patch("runpod.rp_cli.logs.show_logs") as show_logs: + with patch("runpod.cli.logs.show_logs") as show_logs: result = _invoke(["logs", "pod123", *args]) assert result.exit_code == 0, result.output show_logs.assert_called_once_with("pod123", **expected) def test_logs_reject_tail_above_api_limit(): - with patch("runpod.rp_cli.logs.show_logs") as show_logs: + with patch("runpod.cli.logs.show_logs") as show_logs: result = _invoke(["logs", "pod123", "--tail", "5001"]) assert result.exit_code == 2 assert "5000" in result.output @@ -1376,9 +1376,9 @@ class TestCompletion: def test_completers(self): api = FakeApi() with ( - patch("runpod.rp_cli.pod.run_rest_request", api), + patch("runpod.cli.pod.run_rest_request", api), patch("runpod.api.rest.run_rest_request", api), - patch("runpod.rp_cli.compute.list_datacenters", return_value=DATACENTERS), + patch("runpod.cli.compute.list_datacenters", return_value=DATACENTERS), ): pods = pod_module._complete_pods(None, None, "pod1") datacenters = pod_module._complete_datacenters(None, None, "EU") diff --git a/tests/test_cli/test_project_commands.py b/tests/test_cli/test_project_commands.py index 8221f344a..eebed2f13 100644 --- a/tests/test_cli/test_project_commands.py +++ b/tests/test_cli/test_project_commands.py @@ -9,7 +9,7 @@ from runpod.apps.app import _clear_registry, get_registered_apps from runpod.apps.entrypoint import _clear_entrypoints, get_entrypoints -from runpod.rp_cli.main import cli +from runpod.cli.main import cli APP_SOURCE = """ import runpod @@ -31,7 +31,7 @@ def clean_project_state(tmp_path, monkeypatch): _clear_registry() _clear_entrypoints() monkeypatch.delenv("RUNPOD_DEV_SESSION", raising=False) - monkeypatch.setattr("runpod.rp_cli.update.start_background_check", lambda: None) + monkeypatch.setattr("runpod.cli.update.start_background_check", lambda: None) yield _clear_registry() _clear_entrypoints() diff --git a/tests/test_cli/test_response_guards.py b/tests/test_cli/test_response_guards.py index a3cf76959..09a375841 100644 --- a/tests/test_cli/test_response_guards.py +++ b/tests/test_cli/test_response_guards.py @@ -6,9 +6,9 @@ import pytest from click.testing import CliRunner -from runpod.rp_cli.datacenter import datacenter -from runpod.rp_cli.template import template -from runpod.rp_cli.user import user +from runpod.cli.datacenter import datacenter +from runpod.cli.template import template +from runpod.cli.user import user from runpod.user_agent import USER_AGENT @@ -145,7 +145,7 @@ def test_catalog_pagination_keeps_source_and_page_specific_cursor(): @pytest.mark.parametrize("term, matches", [("tpl", True), ("missing", False)]) def test_template_search_handles_nullable_fields(fields, term, matches): record = {"id": "tpl1", **fields} - with patch("runpod.rp_cli.template.list_all", return_value=[record]): + with patch("runpod.cli.template.list_all", return_value=[record]): result = CliRunner().invoke(template, ["list", "--search", term, "--json"]) assert result.exit_code == 0, result.output assert json.loads(result.output) == ([record] if matches else []) @@ -162,7 +162,7 @@ def test_template_search_handles_nullable_fields(fields, term, matches): ], ) def test_template_requires_response_record(record, as_json, args): - with patch("runpod.rp_cli.template.run_rest_request", return_value=record): + with patch("runpod.cli.template.run_rest_request", return_value=record): result = CliRunner().invoke(template, args + (["--json"] if as_json else [])) assert result.exit_code == 1 assert "Error: template information is unavailable" in result.output @@ -173,7 +173,7 @@ def test_template_requires_response_record(record, as_json, args): def test_template_rejects_partial_response(missing, as_json): record = {"id": "tpl1", "name": "worker", "image": "image", "disk": 20} del record[missing] - with patch("runpod.rp_cli.template.run_rest_request", return_value=record): + with patch("runpod.cli.template.run_rest_request", return_value=record): result = CliRunner().invoke( template, ["get", "tpl1"] + (["--json"] if as_json else []) ) @@ -183,7 +183,7 @@ def test_template_rejects_partial_response(missing, as_json): @pytest.mark.parametrize("record", ["invalid", ["invalid"]]) def test_template_rejects_nonobject_response(record): - with patch("runpod.rp_cli.template.run_rest_request", return_value=record): + with patch("runpod.cli.template.run_rest_request", return_value=record): result = CliRunner().invoke(template, ["get", "tpl1"]) assert result.exit_code == 1 assert "Error: template information is unavailable" in result.output @@ -195,10 +195,10 @@ def test_template_rejects_nonobject_response(record): def test_template_list_and_picker_require_ids(args): with ( patch( - "runpod.rp_cli.template.list_all", + "runpod.cli.template.list_all", return_value=[{"name": "worker", "image": "image"}], ), - patch("runpod.rp_cli.template.pick") as pick, + patch("runpod.cli.template.pick") as pick, ): result = CliRunner().invoke(template, args) assert result.exit_code == 1 @@ -208,9 +208,7 @@ def test_template_list_and_picker_require_ids(args): @pytest.mark.parametrize("fields", [{}, {"name": None, "image": None}]) def test_template_list_renders_missing_labels(fields): - with patch( - "runpod.rp_cli.template.list_all", return_value=[{"id": "tpl1", **fields}] - ): + with patch("runpod.cli.template.list_all", return_value=[{"id": "tpl1", **fields}]): result = CliRunner().invoke(template, ["list"]) assert result.exit_code == 0, result.output assert "tpl1" in result.output @@ -220,12 +218,10 @@ def test_template_list_renders_missing_labels(fields): @pytest.mark.parametrize("fields", [{}, {"name": None}]) def test_template_picker_uses_id_for_missing_name(fields): with ( + patch("runpod.cli.template.list_all", return_value=[{"id": "tpl1", **fields}]), + patch("runpod.cli.template.pick", return_value="tpl1") as pick, patch( - "runpod.rp_cli.template.list_all", return_value=[{"id": "tpl1", **fields}] - ), - patch("runpod.rp_cli.template.pick", return_value="tpl1") as pick, - patch( - "runpod.rp_cli.template.run_rest_request", + "runpod.cli.template.run_rest_request", return_value={"id": "tpl1", "name": "worker", "image": "image", "disk": 20}, ), ): @@ -235,7 +231,7 @@ def test_template_picker_uses_id_for_missing_name(fields): def test_template_update_requires_current_record_before_merging(): - with patch("runpod.rp_cli.template.run_rest_request", return_value=None) as request: + with patch("runpod.cli.template.run_rest_request", return_value=None) as request: result = CliRunner().invoke( template, ["update", "tpl1", "--env", "MODEL=large"] ) @@ -249,7 +245,7 @@ def test_template_update_requires_current_record_before_merging(): ) @pytest.mark.parametrize("args", [[], ["info", "--json"], ["balance"]]) def test_user_requires_account_envelope(response, args): - with patch("runpod.rp_cli.user.run_graphql_query", return_value=response): + with patch("runpod.cli.user.run_graphql_query", return_value=response): result = CliRunner().invoke(user, args) assert result.exit_code == 1 assert "Error: account information is unavailable" in result.output @@ -259,7 +255,7 @@ def test_user_requires_account_envelope(response, args): @pytest.mark.parametrize("key", ["clientBalance", "currentSpendPerHr", "spendLimit"]) def test_user_rejects_nonnumeric_money(value, key): with patch( - "runpod.rp_cli.user.run_graphql_query", + "runpod.cli.user.run_graphql_query", return_value={"data": {"myself": {"id": "user", key: value}}}, ): result = CliRunner().invoke(user, ["balance"]) @@ -274,7 +270,7 @@ def test_user_rejects_nonnumeric_money(value, key): ) @pytest.mark.parametrize("as_json", [False, True]) def test_datacenter_requires_response_envelope(response, as_json): - with patch("runpod.rp_cli.datacenter.run_graphql_query", return_value=response): + with patch("runpod.cli.datacenter.run_graphql_query", return_value=response): result = CliRunner().invoke( datacenter, ["list"] + (["--json"] if as_json else []) ) diff --git a/tests/test_cli/test_stream_encoding.py b/tests/test_cli/test_stream_encoding.py index 2779f7863..48edbd93b 100644 --- a/tests/test_cli/test_stream_encoding.py +++ b/tests/test_cli/test_stream_encoding.py @@ -8,7 +8,7 @@ import pytest -from runpod.rp_cli import main +from runpod.cli import main @pytest.mark.parametrize("encoding", ["cp1252", "ascii", "utf-8"]) @@ -25,7 +25,7 @@ def test_redirected_deploy_output(tmp_path, encoding, destination, build_only): from unittest.mock import patch from runpod.apps.deploy import DeployResult - from runpod.rp_cli.main import run + from runpod.cli.main import run def build(app, root, *, events, output, **kwargs): events.phase("package") @@ -46,7 +46,7 @@ async def deploy(app, root, *, events, **kwargs): with ( patch("runpod.apps.deploy.build_artifact", side_effect=build), patch("runpod.apps.deploy.deploy_app", side_effect=deploy), - patch("runpod.rp_cli.update.start_background_check"), + patch("runpod.cli.update.start_background_check"), ): run() """) diff --git a/tests/test_cli/test_template_command.py b/tests/test_cli/test_template_command.py index 535511e52..baa5ac93e 100644 --- a/tests/test_cli/test_template_command.py +++ b/tests/test_cli/test_template_command.py @@ -9,7 +9,7 @@ from requests import ConnectionError from runpod import error -from runpod.rp_cli.main import cli +from runpod.cli.main import cli from runpod.user_agent import USER_AGENT TEMPLATE = { @@ -34,15 +34,13 @@ def invoke(*args, **kwargs): @pytest.fixture def rest(): - with patch( - "runpod.rp_cli.template.run_rest_request", return_value=TEMPLATE - ) as mock: + with patch("runpod.cli.template.run_rest_request", return_value=TEMPLATE) as mock: yield mock @pytest.fixture def listing(): - with patch("runpod.rp_cli.template.list_all", return_value=[TEMPLATE]) as mock: + with patch("runpod.cli.template.list_all", return_value=[TEMPLATE]) as mock: yield mock @@ -145,7 +143,7 @@ def test_get_json_and_human_output(rest): def test_get_picker(rest, listing): - with patch("runpod.rp_cli.template.pick", return_value="tpl1") as pick: + with patch("runpod.cli.template.pick", return_value="tpl1") as pick: result = invoke("get") assert result.exit_code == 0, result.output pick.assert_called_once_with("template", [("tpl1", "Worker")], "pass TEMPLATE_ID") @@ -326,7 +324,7 @@ def test_clear_ports_and_commands(rest): def test_registry_resolves_name(rest): with patch( - "runpod.rp_cli.options.list_all", + "runpod.cli.options.list_all", return_value=[{"id": "reg1", "name": "private"}], ): result = invoke("update", "tpl1", "--registry", "private") @@ -335,7 +333,7 @@ def test_registry_resolves_name(rest): def test_unknown_registry_does_not_mutate(rest): - with patch("runpod.rp_cli.options.list_all", return_value=[]): + with patch("runpod.cli.options.list_all", return_value=[]): result = invoke("update", "tpl1", "--registry", "missing") assert result.exit_code == 1 assert "Error: unknown registry credential 'missing'" in result.output @@ -371,7 +369,7 @@ def test_delete_yes(rest): def test_delete_declined(rest): - with patch("runpod.rp_cli.output.interactive", return_value=True): + with patch("runpod.cli.output.interactive", return_value=True): result = invoke("delete", "tpl1", input="n\n") assert result.exit_code == 1 rest.assert_not_called() diff --git a/tests/test_cli/test_update_command.py b/tests/test_cli/test_update_command.py index 674d434c5..27d221bf5 100644 --- a/tests/test_cli/test_update_command.py +++ b/tests/test_cli/test_update_command.py @@ -8,8 +8,8 @@ import pytest from click.testing import CliRunner -from runpod.rp_cli import update as upd -from runpod.rp_cli.main import cli +from runpod.cli import update as upd +from runpod.cli.main import cli class TestParseVersion: @@ -51,7 +51,7 @@ def test_already_current(self): with patch.object( upd, "fetch_pypi_metadata", return_value=("9.9.9", {"9.9.9"}) ), patch.object(upd, "current_version", return_value="9.9.9"), patch( - "runpod.rp_cli.main.cli.callback" + "runpod.cli.main.cli.callback" ): result = runner.invoke(cli, ["update"]) assert result.exit_code == 0, result.output diff --git a/tests/test_cli/test_user_command.py b/tests/test_cli/test_user_command.py index 1c8549bee..4830bdf17 100644 --- a/tests/test_cli/test_user_command.py +++ b/tests/test_cli/test_user_command.py @@ -8,7 +8,7 @@ from requests import Timeout from runpod import error -from runpod.rp_cli.user import user +from runpod.cli.user import user ACCOUNT = { "id": "user-123", @@ -34,7 +34,7 @@ def isolated_requests(): @pytest.fixture def query(): with patch( - "runpod.rp_cli.user.run_graphql_query", + "runpod.cli.user.run_graphql_query", return_value={"data": {"myself": ACCOUNT}}, ) as mocked: yield mocked @@ -168,9 +168,9 @@ def test_unknown_subcommand_does_not_query(query): "args", [[], ["--json"], ["info", "--json"], ["balance", "--json"]] ) def test_root_account_aliases(alias, args, query): - from runpod.rp_cli.main import cli + from runpod.cli.main import cli - with patch("runpod.rp_cli.update.start_background_check"): + with patch("runpod.cli.update.start_background_check"): result = CliRunner().invoke(cli, [alias, *args]) assert result.exit_code == 0, result.output query.assert_called_once() diff --git a/tests/test_cli/test_volume_command.py b/tests/test_cli/test_volume_command.py index 67a93a2bd..ba5532396 100644 --- a/tests/test_cli/test_volume_command.py +++ b/tests/test_cli/test_volume_command.py @@ -6,7 +6,7 @@ from click.testing import CliRunner from runpod import error -from runpod.rp_cli.main import cli +from runpod.cli.main import cli VOLUME = { "id": "vol1", @@ -40,14 +40,14 @@ def invoke(command, **kwargs): @pytest.fixture def rest(): - with patch("runpod.rp_cli.volume.run_rest_request", return_value=VOLUME) as mock: + with patch("runpod.cli.volume.run_rest_request", return_value=VOLUME) as mock: yield mock @pytest.fixture def listing(): with patch( - "runpod.rp_cli.volume.list_all", + "runpod.cli.volume.list_all", side_effect=lambda path, collection: ( [GLOBAL_VOLUME] if collection == "globalVolumes" else [VOLUME] ), @@ -57,9 +57,7 @@ def listing(): @pytest.fixture def datacenters(): - with patch( - "runpod.rp_cli.compute.list_datacenters", return_value=DATACENTERS - ) as mock: + with patch("runpod.cli.compute.list_datacenters", return_value=DATACENTERS) as mock: yield mock @@ -123,7 +121,7 @@ def test_get_fields_and_json(resource, rest): def test_get_picker(rest, listing): - with patch("runpod.rp_cli.volume.pick", return_value="vol1") as pick: + with patch("runpod.cli.volume.pick", return_value="vol1") as pick: result = invoke("get") assert result.exit_code == 0, result.output assert pick.call_args.args[1] == [ @@ -186,7 +184,7 @@ def test_create_exact_data_center(rest, datacenters): ], ) def test_create_filters_picker_candidates(rest, datacenters, options, candidates): - with patch("runpod.rp_cli.volume.pick", return_value=candidates[0]) as pick: + with patch("runpod.cli.volume.pick", return_value=candidates[0]) as pick: result = invoke(f"create --name m --size 10 {options} --json") assert result.exit_code == 0, result.output assert [value for value, _ in pick.call_args.args[1]] == candidates @@ -371,7 +369,7 @@ def test_delete_yes(resource, rest): @pytest.mark.parametrize("answer,code", [("y", 0), ("n", 1)]) def test_delete_confirmation(rest, answer, code): - with patch("runpod.rp_cli.output.interactive", return_value=True): + with patch("runpod.cli.output.interactive", return_value=True): result = invoke("delete vol1", input=f"{answer}\n") assert result.exit_code == code assert "models 100 GB EU-RO-1 standard" in result.output diff --git a/tests/test_endpoint/test_asyncio_runner.py b/tests/test_endpoint/test_asyncio_runner.py index bf3e593ee..5114d8da3 100644 --- a/tests/test_endpoint/test_asyncio_runner.py +++ b/tests/test_endpoint/test_asyncio_runner.py @@ -26,14 +26,14 @@ async def test_status(self): Tests Job.status """ with patch( - "aiohttp.ClientSession", new_callable=AsyncMock + "aiohttp.ClientSession", new_callable=MagicMock ) as mock_session_class: mock_session = mock_session_class.return_value - mock_get = mock_session.get + mock_get = mock_session.request mock_resp = AsyncMock() mock_resp.json.return_value = {"status": "COMPLETED"} - mock_get.return_value = mock_resp + mock_get.return_value.__aenter__.return_value = mock_resp headers = { "Content-Type": "application/json", @@ -52,10 +52,10 @@ async def test_output(self): with patch( "runpod.endpoint.asyncio.asyncio_runner.asyncio.sleep" ) as mock_sleep, patch( - "aiohttp.ClientSession", new_callable=AsyncMock + "aiohttp.ClientSession", new_callable=MagicMock ) as mock_session_class: mock_session = mock_session_class.return_value - mock_get = mock_session.get + mock_get = mock_session.request mock_resp = AsyncMock() async def json_side_effect(): @@ -64,7 +64,7 @@ async def json_side_effect(): return {"output": "OUTPUT", "status": "COMPLETED"} mock_resp.json.side_effect = json_side_effect - mock_get.return_value = mock_resp + mock_get.return_value.__aenter__.return_value = mock_resp headers = { "Content-Type": "application/json", @@ -83,14 +83,14 @@ async def test_output_timeout(self): Tests Job.output with a timeout """ with patch( - "aiohttp.ClientSession", new_callable=AsyncMock + "aiohttp.ClientSession", new_callable=MagicMock ) as mock_session_class: mock_session = mock_session_class.return_value - mock_get = mock_session.get + mock_get = mock_session.request mock_resp = AsyncMock() mock_resp.json.return_value = {"status": "IN_PROGRESS"} - mock_get.return_value = mock_resp + mock_get.return_value.__aenter__.return_value = mock_resp headers = { "Content-Type": "application/json", @@ -108,10 +108,10 @@ async def test_stream(self): Tests Job.stream """ with patch( - "aiohttp.ClientSession", new_callable=AsyncMock + "aiohttp.ClientSession", new_callable=MagicMock ) as mock_session_class: mock_session = mock_session_class.return_value - mock_get = mock_session.get + mock_get = mock_session.request mock_resp = AsyncMock() responses = [ @@ -127,7 +127,7 @@ async def json_side_effect(): ) mock_resp.json.side_effect = json_side_effect - mock_get.return_value = mock_resp + mock_get.return_value.__aenter__.return_value = mock_resp headers = { "Content-Type": "application/json", @@ -146,10 +146,10 @@ async def test_output_after_stream_fetches_aggregate_result(self): """output() after a completed stream fetches the aggregate result from /status instead of returning the stream's empty output.""" with patch( - "aiohttp.ClientSession", new_callable=AsyncMock + "aiohttp.ClientSession", new_callable=MagicMock ) as mock_session_class: mock_session = mock_session_class.return_value - mock_get = mock_session.get + mock_get = mock_session.request mock_resp = AsyncMock() responses = [ @@ -165,7 +165,7 @@ async def json_side_effect(): } mock_resp.json.side_effect = json_side_effect - mock_get.return_value = mock_resp + mock_get.return_value.__aenter__.return_value = mock_resp headers = { "Content-Type": "application/json", @@ -186,7 +186,7 @@ async def test_cancel(self): mock_resp = MagicMock() mock_resp.json = MagicMock(return_value=asyncio.Future()) mock_resp.json.return_value.set_result({"result": "CANCELLED"}) - mock_session.post.return_value.__aenter__.return_value = mock_resp + mock_session.request.return_value.__aenter__.return_value = mock_resp headers = { "Content-Type": "application/json", @@ -200,10 +200,10 @@ async def test_cancel(self): async def test_output_in_progress_then_completed(self): """Tests Job.output when status is initially IN_PROGRESS and then changes to COMPLETED""" with patch( - "aiohttp.ClientSession", new_callable=AsyncMock + "aiohttp.ClientSession", new_callable=MagicMock ) as mock_session_class: mock_session = mock_session_class.return_value - mock_get = mock_session.get + mock_get = mock_session.request mock_resp = AsyncMock() responses = [ @@ -219,7 +219,7 @@ async def json_side_effect(): ) # pylint: disable=line-too-long mock_resp.json.side_effect = json_side_effect - mock_get.return_value = mock_resp + mock_get.return_value.__aenter__.return_value = mock_resp headers = { "Content-Type": "application/json", @@ -247,7 +247,7 @@ async def test_run(self): mock_resp = MagicMock() mock_resp.json = MagicMock(return_value=asyncio.Future()) mock_resp.json.return_value.set_result({"id": "job_id"}) - mock_session.post.return_value.__aenter__.return_value = mock_resp + mock_session.request.return_value.__aenter__.return_value = mock_resp endpoint = Endpoint("endpoint_id", mock_session) job = await endpoint.run({"input": "INPUT"}) @@ -261,7 +261,7 @@ async def test_health(self): mock_resp = MagicMock() mock_resp.json = MagicMock(return_value=asyncio.Future()) mock_resp.json.return_value.set_result({"status": "HEALTHY"}) - mock_session.get.return_value.__aenter__.return_value = mock_resp + mock_session.request.return_value.__aenter__.return_value = mock_resp endpoint = Endpoint("endpoint_id", mock_session) health = await endpoint.health() @@ -275,7 +275,7 @@ async def test_purge_queue(self): mock_resp = MagicMock() mock_resp.json = MagicMock(return_value=asyncio.Future()) mock_resp.json.return_value.set_result({"result": "PURGED"}) - mock_session.post.return_value.__aenter__.return_value = mock_resp + mock_session.request.return_value.__aenter__.return_value = mock_resp endpoint = Endpoint("endpoint_id", mock_session) purge_result = await endpoint.purge_queue() @@ -317,10 +317,10 @@ class TestJobOutputDefaultTimeout(IsolatedAsyncioTestCase): async def test_output_without_timeout_does_not_raise_for_unfinished_job(self): """An unfinished job returns its current (empty) output, like sync.""" - session = AsyncMock() + session = MagicMock() response = AsyncMock() response.json.return_value = {"status": "IN_PROGRESS"} - session.get.return_value = response + session.request.return_value.__aenter__.return_value = response job = Job("endpoint_id", "job_id", session, {}) @@ -339,11 +339,11 @@ async def _posted_json(self, endpoint_input): response = MagicMock() response.json = AsyncMock(return_value={"id": "job_id"}) session = MagicMock() - session.post.return_value.__aenter__.return_value = response + session.request.return_value.__aenter__.return_value = response await Endpoint("endpoint_id", session).run(endpoint_input) - return session.post.call_args.kwargs["json"] + return session.request.call_args.kwargs["json"] async def test_already_wrapped_input_is_not_wrapped_again(self): assert await self._posted_json({"input": {"prompt": "hi"}}) == { diff --git a/tests/test_endpoint/test_failed_jobs.py b/tests/test_endpoint/test_failed_jobs.py index aa1be2ad4..48fd57a21 100644 --- a/tests/test_endpoint/test_failed_jobs.py +++ b/tests/test_endpoint/test_failed_jobs.py @@ -1,6 +1,6 @@ """a job that ends in a non-COMPLETED final state raises JobError.""" -from unittest.mock import AsyncMock, Mock, patch +from unittest.mock import AsyncMock, MagicMock, Mock, patch import pytest @@ -79,8 +79,8 @@ def test_job_error_without_error_field_still_names_the_status(): async def test_async_job_output_raises_on_failure(): response = AsyncMock() response.json.return_value = {"status": "FAILED", "error": "bad input"} - session = AsyncMock() - session.get.return_value = response + session = MagicMock() + session.request.return_value.__aenter__.return_value = response job = AsyncJob("ENDPOINT_ID", "job-1", session, headers={}) with pytest.raises(JobError, match="bad input") as caught: @@ -113,8 +113,8 @@ async def test_async_stream_stops_after_job_is_cancelled(): responses = _cancelled_stream_responses() response = AsyncMock() response.json.side_effect = lambda: next(responses) - session = AsyncMock() - session.get.return_value = response + session = MagicMock() + session.request.return_value.__aenter__.return_value = response job = AsyncJob("ENDPOINT_ID", "job-1", session, headers={}) with patch("runpod.endpoint.asyncio.asyncio_runner.asyncio.sleep"): diff --git a/tests/test_endpoint/test_redirects.py b/tests/test_endpoint/test_redirects.py new file mode 100644 index 000000000..ee279f4f5 --- /dev/null +++ b/tests/test_endpoint/test_redirects.py @@ -0,0 +1,103 @@ +"""endpoint redirects fail before job response decoding.""" + +import asyncio + +import aiohttp +import pytest +from aiohttp import web + +from runpod.endpoint.asyncio import asyncio_runner +from runpod.endpoint.runner import Endpoint, Job +from runpod.error import QueryError + + +@pytest.fixture +async def redirect_server(monkeypatch): + state = {"status": 307, "body": b"", "content_type": "text/html", "requests": []} + + async def handler(request): + await request.read() + state["requests"].append(request.path) + return web.Response( + status=state["status"], + body=state["body"], + content_type=state["content_type"], + headers={"Location": "/destination?signature=synthetic-secret"}, + ) + + app = web.Application() + app.router.add_route("*", "/{path:.*}", handler) + runner = web.AppRunner(app) + await runner.setup() + site = web.TCPSite(runner, "127.0.0.1", 0) + await site.start() + port = site._server.sockets[0].getsockname()[1] + base = f"http://127.0.0.1:{port}/v2" + monkeypatch.setenv("RUNPOD_ENDPOINT_BASE_URL", base) + monkeypatch.setattr("runpod.endpoint_url_base", base) + try: + yield state + finally: + await runner.cleanup() + + +@pytest.mark.parametrize("status", [301, 307, 308]) +@pytest.mark.parametrize( + "body,content_type", + [ + (b"", "text/html"), + (b"synthetic-secret", "text/html"), + ( + b'{"id":"job","status":"COMPLETED","output":"synthetic-secret"}', + "application/json", + ), + ], +) +@pytest.mark.parametrize( + "operation", + ["run", "health", "purge_queue", "status", "output", "stream", "cancel"], +) +@pytest.mark.parametrize("async_runner", [True, False]) +async def test_endpoint_rejects_redirect_before_decoding( + redirect_server, status, body, content_type, operation, async_runner +): + redirect_server.update(status=status, body=body, content_type=content_type) + with pytest.raises(QueryError, match="unexpected redirect") as caught: + if async_runner: + async with aiohttp.ClientSession() as session: + endpoint = asyncio_runner.Endpoint( + "endpoint", session, api_key="synthetic-key" + ) + job = asyncio_runner.Job("endpoint", "job", session, endpoint.headers) + try: + if operation == "run": + await endpoint.run({}) + elif operation in {"health", "purge_queue"}: + await getattr(endpoint, operation)() + elif operation == "stream": + await job._fetch_job("stream") + elif operation == "output": + await job.output(timeout=3) + else: + await getattr(job, operation)() + finally: + assert not session.closed + else: + + def invoke(): + with Endpoint("endpoint", api_key="synthetic-key") as endpoint: + job = Job("endpoint", "job", endpoint.rp_client) + if operation == "run": + endpoint.run({}) + elif operation in {"health", "purge_queue"}: + getattr(endpoint, operation)() + elif operation == "stream": + job._fetch_job("stream") + else: + getattr(job, operation)() + + await asyncio.to_thread(invoke) + assert caught.value.status_code == status + assert "synthetic" not in str(caught.value) + repr(vars(caught.value)) + assert len(redirect_server["requests"]) == 1 + assert redirect_server["requests"][0].startswith("/v2/endpoint/") diff --git a/tests/test_endpoint/test_transport.py b/tests/test_endpoint/test_transport.py new file mode 100644 index 000000000..f9bfa81dd --- /dev/null +++ b/tests/test_endpoint/test_transport.py @@ -0,0 +1,221 @@ +"""Endpoint route, response lifetime, and session ownership tests.""" + +import asyncio +from unittest.mock import AsyncMock, MagicMock, Mock, patch + +import aiohttp +import pytest +import requests + +import runpod +from runpod.endpoint.asyncio import asyncio_runner +from runpod.endpoint.helpers import UNAUTHORIZED_MSG +from runpod.endpoint.runner import Endpoint, Job, RunPodClient + + +@pytest.mark.parametrize( + ("operation", "method", "path", "timeout"), + [ + ("run", "POST", "run", 10), + ("run_sync", "POST", "runsync", 86400), + ("health", "GET", "health", 3), + ("purge_queue", "POST", "purge-queue", 3), + ("status", "GET", "status/job%2F%3F%23%25", 10), + ("stream", "GET", "stream/job%2F%3F%23%25", 10), + ("cancel", "POST", "cancel/job%2F%3F%23%25", 3), + ], +) +def test_sync_routes_and_response_release(operation, method, path, timeout): + response = Mock(status_code=200) + response.json.return_value = {"id": "job/?#%", "status": "COMPLETED"} + with ( + patch.object(runpod, "endpoint_url_base", "https://example.com/v2/"), + patch("requests.Session.request", return_value=response) as request, + ): + with Endpoint("endpoint/?#%", api_key="endpoint-key") as endpoint: + if operation in {"run", "run_sync"}: + getattr(endpoint, operation)({"message": "hello"}) + elif operation in {"health", "purge_queue"}: + getattr(endpoint, operation)() + else: + job = Job(endpoint.endpoint_id, "job/?#%", endpoint.rp_client) + if operation == "stream": + job._fetch_job("stream") + else: + getattr(job, operation)() + + assert request.call_args.args == ( + method, + f"https://example.com/v2/endpoint%2F%3F%23%25/{path}", + ) + assert request.call_args.kwargs["headers"]["Authorization"] == "Bearer endpoint-key" + assert request.call_args.kwargs["timeout"] == timeout + assert request.call_args.kwargs["allow_redirects"] is False + response.close.assert_called_once_with() + + +def test_sync_endpoint_reuses_and_closes_its_pool(): + session = Mock() + session.request.return_value.status_code = 200 + session.request.return_value.json.return_value = { + "id": "job", + "status": "COMPLETED", + } + with patch("runpod.endpoint.runner.requests.Session", return_value=session): + with Endpoint("endpoint", api_key="key") as endpoint: + job = endpoint.run({"message": "hello"}) + assert job.status() == "COMPLETED" + assert job.rp_client is endpoint.rp_client + assert endpoint.rp_client.rp_session is session + assert session.request.call_count == 2 + assert session.request.return_value.close.call_count == 2 + session.close.assert_not_called() + session.close.assert_called_once_with() + + +@pytest.mark.parametrize("failure", ["unauthorized", "http", "json"]) +def test_sync_releases_response_and_pool_on_errors(failure): + response = Mock(status_code=401 if failure == "unauthorized" else 500) + if failure == "http": + response.raise_for_status.side_effect = requests.HTTPError("server error") + expected = requests.HTTPError + message = "server error" + elif failure == "json": + response.status_code = 200 + response.json.side_effect = ValueError("invalid json") + expected = ValueError + message = "invalid json" + else: + expected = RuntimeError + message = UNAUTHORIZED_MSG + + with ( + patch("requests.Session.request", return_value=response), + patch("requests.Session.close") as close, + ): + with pytest.raises(expected) as error: + with RunPodClient(api_key="key") as client: + client.get("endpoint/status/job") + assert str(error.value) == message + close.assert_called_once_with() + response.close.assert_called_once_with() + + +@pytest.mark.asyncio +async def test_async_routes_reuse_the_borrowed_session(): + response = MagicMock() + response.json = AsyncMock( + return_value={"id": "job/?#%", "status": "COMPLETED", "output": "done"} + ) + context = MagicMock() + context.__aenter__.return_value = response + with patch.object(runpod, "endpoint_url_base", "https://example.com/v2/"): + timeout = aiohttp.ClientTimeout(total=900, connect=45, sock_read=120) + async with aiohttp.ClientSession(timeout=timeout) as session: + with patch.object(session, "request", return_value=context) as request: + endpoint = asyncio_runner.Endpoint( + "endpoint/?#%", session, api_key="key" + ) + job = await endpoint.run({"message": "hello"}) + await endpoint.health() + await endpoint.purge_queue() + assert await job.status() == "COMPLETED" + await job._fetch_job("stream") + await job.cancel() + assert job.session is session + assert not session.closed + + assert [ + (call.args[0], str(call.args[1])) for call in request.call_args_list + ] == [ + ("POST", "https://example.com/v2/endpoint%2F%3F%23%25/run"), + ("GET", "https://example.com/v2/endpoint%2F%3F%23%25/health"), + ("POST", "https://example.com/v2/endpoint%2F%3F%23%25/purge-queue"), + ( + "GET", + "https://example.com/v2/endpoint%2F%3F%23%25/status/job%2F%3F%23%25", + ), + ( + "GET", + "https://example.com/v2/endpoint%2F%3F%23%25/stream/job%2F%3F%23%25", + ), + ( + "POST", + "https://example.com/v2/endpoint%2F%3F%23%25/cancel/job%2F%3F%23%25", + ), + ] + for call in request.call_args_list: + assert call.kwargs["headers"]["Authorization"] == "Bearer key" + assert call.kwargs["timeout"] is timeout + assert call.kwargs["allow_redirects"] is False + assert request.call_args_list[0].kwargs["json"] == { + "input": {"message": "hello"} + } + assert request.call_args.kwargs["headers"]["X-Request-ID"] == "job/?#%" + assert context.__aexit__.await_count == 6 + response.raise_for_status.assert_not_called() + assert session.closed + + +@pytest.mark.asyncio +@pytest.mark.parametrize( + "operation", ["run", "health", "purge_queue", "status", "cancel"] +) +async def test_async_json_errors_release_response_without_closing_session(operation): + response = MagicMock() + response.json = AsyncMock(side_effect=ValueError("invalid json")) + context = MagicMock() + context.__aenter__.return_value = response + async with aiohttp.ClientSession() as session: + with patch.object(session, "request", return_value=context): + endpoint = asyncio_runner.Endpoint("endpoint", session, api_key="key") + job = asyncio_runner.Job("endpoint", "job", session, endpoint.headers) + with pytest.raises(ValueError, match="invalid json"): + if operation == "run": + await endpoint.run({}) + elif operation in {"status", "cancel"}: + await getattr(job, operation)() + else: + await getattr(endpoint, operation)() + context.__aexit__.assert_awaited_once() + assert not session.closed + + +@pytest.mark.asyncio +@pytest.mark.parametrize("status", [401, 500]) +async def test_async_preserves_error_response_json(status): + response = MagicMock(status=status) + response.json = AsyncMock(return_value={"error": "request failed"}) + context = MagicMock() + context.__aenter__.return_value = response + async with aiohttp.ClientSession() as session: + with patch.object(session, "request", return_value=context): + endpoint = asyncio_runner.Endpoint("endpoint", session, api_key="key") + assert await endpoint.health() == {"error": "request failed"} + response.raise_for_status.assert_not_called() + context.__aexit__.assert_awaited_once() + assert not session.closed + + +@pytest.mark.asyncio +async def test_async_cancellation_releases_response_without_closing_session(): + decoding = asyncio.Event() + + async def read_json(): + decoding.set() + await asyncio.Future() + + response = MagicMock() + response.json = AsyncMock(side_effect=read_json) + context = MagicMock() + context.__aenter__.return_value = response + async with aiohttp.ClientSession() as session: + with patch.object(session, "request", return_value=context): + endpoint = asyncio_runner.Endpoint("endpoint", session, api_key="key") + task = asyncio.create_task(endpoint.run({})) + await decoding.wait() + task.cancel() + with pytest.raises(asyncio.CancelledError): + await task + context.__aexit__.assert_awaited_once() + assert not session.closed diff --git a/tests/test_init_typing.py b/tests/test_init_typing.py index 8df82f8aa..4c2b08dac 100644 --- a/tests/test_init_typing.py +++ b/tests/test_init_typing.py @@ -1,9 +1,8 @@ -"""Type checkers must see the real definitions behind runpod's lazy root names. +"""type checkers see the real definitions behind runpod's lazy root names. runpod resolves its public names through a PEP 562 __getattr__, which a type checker reads as untyped. The package ships py.typed, so consumers annotating -with root names (runpod.Endpoint, runpod.AsyncioJob) need explicit imports -under TYPE_CHECKING that mirror the lazy table. +with root names (runpod.Endpoint, runpod.AsyncioJob) use the package stub. """ import ast @@ -15,9 +14,9 @@ import runpod INIT_PATH = Path(runpod.__file__) +STUB_PATH = INIT_PATH.with_suffix(".pyi") -CONSUMER = textwrap.dedent( - """ +CONSUMER = textwrap.dedent(""" import runpod async def poll(job: runpod.AsyncioJob) -> str: @@ -28,31 +27,25 @@ def build(endpoint_id: str) -> runpod.Endpoint: reveal_type(runpod.Endpoint) reveal_type(runpod.create_pod) - """ -) + """) -def _type_checking_imports() -> dict[str, str]: - """Map each name imported under `if TYPE_CHECKING:` to its module.""" - tree = ast.parse(INIT_PATH.read_text()) +def _stub_imports() -> dict[str, str]: + """map lazy names to their declared modules in the package stub.""" + tree = ast.parse(STUB_PATH.read_text()) imports: dict[str, str] = {} for node in tree.body: - is_type_checking = ( - isinstance(node, ast.If) - and isinstance(node.test, ast.Name) - and node.test.id == "TYPE_CHECKING" - ) - if not is_type_checking: + if not isinstance(node, ast.ImportFrom): continue - for stmt in node.body: - assert isinstance(stmt, ast.ImportFrom), ast.dump(stmt) - for alias in stmt.names: - imports[alias.asname or alias.name] = stmt.module or "" + for alias in node.names: + name = alias.asname or alias.name + if name in runpod._LAZY_ATTRS: + imports[name] = node.module or "" return imports def _lazy_imports() -> dict[str, str]: - """The lazy table as TYPE_CHECKING imports: submodules import from the parent.""" + """the lazy table as stub imports, with submodules imported from the parent.""" imports = {} for name, module in runpod._LAZY_ATTRS.items(): if module == f"runpod.{name}": @@ -62,7 +55,7 @@ def _lazy_imports() -> dict[str, str]: def test_every_lazy_name_has_a_typed_import(): - assert _type_checking_imports() == _lazy_imports() + assert _stub_imports() == _lazy_imports() def test_consumer_sees_root_definitions(): diff --git a/tests/test_network_volume_transfer.py b/tests/test_network_volume_transfer.py index a393787e8..55379ddb8 100644 --- a/tests/test_network_volume_transfer.py +++ b/tests/test_network_volume_transfer.py @@ -824,7 +824,7 @@ def test_no_module_level_transfer_exports(): @pytest.mark.usefixtures("cli_preflight") def test_cli_upload_prints_summary(tmp_path): - from runpod.rp_cli.main import cli + from runpod.cli.main import cli src = tmp_path / "f.txt" src.write_text("x") @@ -851,7 +851,7 @@ def fake_upload(volume, source, target, **kwargs): @pytest.mark.usefixtures("cli_preflight") def test_cli_download_failure_says_resume(): - from runpod.rp_cli.main import cli + from runpod.cli.main import cli with patch.object( runpod.NetworkVolume, "download", side_effect=ConnectionResetError("boom") @@ -864,7 +864,7 @@ def test_cli_download_failure_says_resume(): @pytest.mark.usefixtures("cli_preflight") def test_cli_ctrl_c_exits_130_with_resume_hint(): - from runpod.rp_cli.main import cli + from runpod.cli.main import cli with patch.object(runpod.NetworkVolume, "upload", side_effect=KeyboardInterrupt): result = CliRunner().invoke(cli, ["volume", "upload", "vol", "."]) @@ -874,7 +874,7 @@ def test_cli_ctrl_c_exits_130_with_resume_hint(): @pytest.mark.usefixtures("cli_preflight") def test_cli_final_error_has_no_resume_hint(): - from runpod.rp_cli.main import cli + from runpod.cli.main import cli err = nvt.NetworkVolumeTransferError("s3 api keys required") with patch.object(runpod.NetworkVolume, "download", side_effect=err): @@ -886,7 +886,7 @@ def test_cli_final_error_has_no_resume_hint(): @pytest.mark.usefixtures("cli_preflight") def test_cli_missing_path_has_no_resume_hint(): - from runpod.rp_cli.main import cli + from runpod.cli.main import cli with patch.object( runpod.NetworkVolume, "download", side_effect=FileNotFoundError("no such file") @@ -1338,14 +1338,14 @@ def test_download_refuses_symlinked_work_files(tmp_path, suffix): def _cli(): - from runpod.rp_cli.main import cli + from runpod.cli.main import cli return cli @pytest.fixture def interactive(monkeypatch): - monkeypatch.setattr("runpod.rp_cli.volume._interactive", lambda: True) + monkeypatch.setattr("runpod.cli.volume._interactive", lambda: True) @pytest.fixture @@ -1380,11 +1380,11 @@ def test_cli_offers_login_and_continues(monkeypatch, tmp_path, interactive): logins = [] monkeypatch.setattr(runpod, "api_key", None) monkeypatch.setattr( - "runpod.rp_cli.main.login", + "runpod.cli.main.login", _click.Command("login", callback=lambda **kw: logins.append(kw)), ) monkeypatch.setattr( - "runpod.cli.groups.config.functions.get_credentials", + "runpod.auth.credentials.get_credentials", lambda profile="default": {"api_key": "rpa_new"}, ) calls = [] @@ -1455,7 +1455,7 @@ def test_cli_prompts_for_keys_and_offers_to_save( monkeypatch.delenv(nvt.ACCESS_KEY_ENV) saved = [] monkeypatch.setattr( - "runpod.cli.groups.config.functions.set_s3_keys", + "runpod.auth.credentials.set_s3_keys", lambda access, secret, profile="default": saved.append((access, secret)), ) calls = [] @@ -1482,7 +1482,7 @@ def missing_volume(reference, **kwargs): monkeypatch.setattr(nvt, "_resolve_volume", missing_volume) monkeypatch.setattr( - "runpod.rp_cli.volume._prompt_s3_keys", lambda: pytest.fail("prompted for keys") + "runpod.cli.volume._prompt_s3_keys", lambda: pytest.fail("prompted for keys") ) result = CliRunner().invoke(_cli(), ["volume", "upload", "missing", str(tmp_path)]) assert result.exit_code == 1 @@ -1503,7 +1503,7 @@ def transfer(volume, source, target, **kwargs): monkeypatch.delenv(nvt.SECRET_KEY_ENV, raising=False) monkeypatch.setattr(nvt, "saved_s3_keys", lambda: ("saved", "old")) monkeypatch.setattr( - "runpod.rp_cli.volume._prompt_s3_keys", lambda: ("new", "secret") + "runpod.cli.volume._prompt_s3_keys", lambda: ("new", "secret") ) with patch.object( runpod.NetworkVolume, "upload", autospec=True, side_effect=transfer @@ -1547,8 +1547,8 @@ def transfer(volume, source, target, **kwargs): monkeypatch.delenv(nvt.ACCESS_KEY_ENV, raising=False) monkeypatch.delenv(nvt.SECRET_KEY_ENV, raising=False) monkeypatch.setattr(nvt, "saved_s3_keys", lambda: ("saved", "old")) - monkeypatch.setattr("runpod.rp_cli.volume._progress_bar", fake_bar) - monkeypatch.setattr("runpod.rp_cli.volume._prompt_s3_keys", prompt) + monkeypatch.setattr("runpod.cli.volume._progress_bar", fake_bar) + monkeypatch.setattr("runpod.cli.volume._prompt_s3_keys", prompt) with patch.object( runpod.NetworkVolume, "upload", autospec=True, side_effect=transfer ): @@ -1571,7 +1571,7 @@ def unsaved(): monkeypatch.delenv(nvt.ACCESS_KEY_ENV, raising=False) monkeypatch.delenv(nvt.SECRET_KEY_ENV, raising=False) monkeypatch.setattr(nvt, "saved_s3_keys", lambda: ("saved", "old")) - monkeypatch.setattr("runpod.rp_cli.volume._prompt_s3_keys", unsaved) + monkeypatch.setattr("runpod.cli.volume._prompt_s3_keys", unsaved) with patch.object( runpod.NetworkVolume, "upload", autospec=True, side_effect=transfer ): @@ -1664,7 +1664,7 @@ def make(volume, *args, location=None, **kwargs): def test_set_s3_keys_keeps_the_api_key_and_login_keeps_the_s3_keys( monkeypatch, tmp_path ): - from runpod.cli.groups.config import functions + from runpod.auth import credentials as functions monkeypatch.setattr(functions, "CREDENTIAL_FILE", str(tmp_path / "config.toml")) functions.set_credentials("rpa_one", overwrite=True) diff --git a/tests/test_profile.py b/tests/test_profile.py index 7751de035..282f4be5a 100644 --- a/tests/test_profile.py +++ b/tests/test_profile.py @@ -28,7 +28,7 @@ def test_blank_env_falls_back_to_default(self, monkeypatch, value): class TestApiKeyFromSelectedProfile: def test_loads_key_from_selected_profile(self, tmp_path, monkeypatch): - from runpod.cli.groups.config import functions + from runpod.auth import credentials as functions credentials = tmp_path / "config.toml" credentials.write_text( @@ -41,7 +41,7 @@ def test_loads_key_from_selected_profile(self, tmp_path, monkeypatch): assert runpod._load_api_key() == "team-key" def test_api_key_env_wins_over_profile(self, tmp_path, monkeypatch): - from runpod.cli.groups.config import functions + from runpod.auth import credentials as functions credentials = tmp_path / "config.toml" credentials.write_text('[team]\napi_key = "team-key"\n') @@ -63,7 +63,7 @@ def reload_runpod(self, monkeypatch): def test_s3_only_profile_imports_without_api_key( self, tmp_path, monkeypatch, reload_runpod ): - from runpod.cli.groups.config import functions + from runpod.auth import credentials as functions credentials = tmp_path / "config.toml" credentials.write_text( diff --git a/tests/test_serverless/test_modules/test_job_rate_limit.py b/tests/test_serverless/test_modules/test_job_rate_limit.py new file mode 100644 index 000000000..c3ed3cea4 --- /dev/null +++ b/tests/test_serverless/test_modules/test_job_rate_limit.py @@ -0,0 +1,29 @@ +"""rate-limit responses with optional reason phrases.""" + +from unittest.mock import MagicMock, Mock, patch + +import pytest +from aiohttp import ClientResponse + +from runpod.http_client import TooManyRequests +from runpod.serverless.modules import rp_job + + +@pytest.mark.parametrize("handler", [rp_job.get_job, rp_job.get_stop_signals]) +@pytest.mark.parametrize("reason", [None, "", "Too Many Requests"]) +async def test_429_preserves_retry_exception(handler, reason): + response = Mock(ClientResponse) + response.status = 429 + response.reason = reason + response.history = () + session = MagicMock() + session.get.return_value.__aenter__.return_value = response + + with patch.object(rp_job, "JOB_GET_URL", "https://example.test/job-take/worker"): + with pytest.raises(TooManyRequests) as raised: + await handler(session) + + assert raised.value.status == 429 + assert raised.value.message == (reason or "") + response.raise_for_status.assert_not_called() + session.get.return_value.__aexit__.assert_awaited_once() diff --git a/tests/test_serverless/test_utils/test_ssrf.py b/tests/test_serverless/test_utils/test_ssrf.py index 6e9e2edf8..c2c97210c 100644 --- a/tests/test_serverless/test_utils/test_ssrf.py +++ b/tests/test_serverless/test_utils/test_ssrf.py @@ -7,8 +7,7 @@ import unittest from unittest.mock import MagicMock, patch -from requests import ConnectionError as RequestsConnectionError -from requests import RequestException +from requests import ConnectionError as RequestsConnectionError, RequestException from runpod.serverless.utils.rp_ssrf import ( SSRFError, diff --git a/tests/test_shared/test_auth.py b/tests/test_shared/test_auth.py index 2cb93defb..b96b37118 100644 --- a/tests/test_shared/test_auth.py +++ b/tests/test_shared/test_auth.py @@ -18,7 +18,7 @@ class TestAPIKey(unittest.TestCase): """ @patch("builtins.open", new_callable=mock_open, read_data=CREDENTIALS) - @patch("runpod.cli.groups.config.functions.os.path.exists", return_value=True) + @patch("runpod.auth.credentials.os.path.exists", return_value=True) def test_use_file_credentials(self, _mock_exists, mock_file): """ Test that the API key is read from the credentials file diff --git a/tests/test_user_agent.py b/tests/test_user_agent.py index 6589a7eb6..26b210eae 100644 --- a/tests/test_user_agent.py +++ b/tests/test_user_agent.py @@ -6,8 +6,7 @@ import pytest -from runpod import __version__ as runpod_version -from runpod import agent +from runpod import __version__ as runpod_version, agent from runpod.user_agent import construct_user_agent