-
Notifications
You must be signed in to change notification settings - Fork 0
Add Registry Ping Command #45
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
Merged
Changes from all commits
Commits
Show all changes
9 commits
Select commit
Hold shift + click to select a range
51fbeea
Add design spec for registry ping command (issue #32)
toddysm 310dcd2
Implement registry ping command (issue #32)
toddysm 28b48b4
Potential fix for pull request finding
toddysm ae823fc
Potential fix for pull request finding
toddysm 8f436e6
Potential fix for pull request finding
toddysm 4fc39aa
Potential fix for pull request finding
toddysm 8ac6ba7
Potential fix for pull request finding
toddysm b930df9
Potential fix for pull request finding
toddysm 6571502
Potential fix for pull request finding
toddysm File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,230 @@ | ||
| # CLI: `ping` | ||
|
|
||
| ## Overview | ||
|
|
||
| Implements a top-level `regshape ping` command that performs `GET /v2/` against a target registry to verify connectivity, authentication, and OCI Distribution API support. This is a connectivity check command — it does not operate on repositories or images. | ||
|
|
||
| ## Usage | ||
|
|
||
| ``` | ||
| regshape ping --registry <registry> [--json] | ||
| ``` | ||
|
|
||
| ## Arguments | ||
|
|
||
| None. | ||
|
|
||
| ## Options | ||
|
|
||
| | Option | Short | Type | Default | Description | | ||
| |--------|-------|------|---------|-------------| | ||
| | `--registry` | `-r` | string | required | Registry hostname (e.g. `ghcr.io`, `localhost:5000`) | | ||
| | `--json` | | flag | false | Output as JSON | | ||
|
|
||
| ## Library Layer | ||
|
|
||
| ### Module: `src/regshape/libs/ping/` | ||
|
|
||
| #### `ping(client: RegistryClient) -> PingResult` | ||
|
|
||
| Issues `GET /v2/` via the provided `RegistryClient` and returns a `PingResult` describing the outcome. | ||
|
|
||
| **Parameters:** | ||
| - `client` — A configured `RegistryClient` instance targeting the registry. | ||
|
|
||
| **Returns:** `PingResult` dataclass. | ||
|
|
||
| **Raises:** | ||
| - `AuthError` — When the registry returns `401 Unauthorized`. | ||
| - `PingError` — When the registry is unreachable (DNS failure, connection refused, timeout). | ||
|
|
||
| #### `PingResult` dataclass | ||
|
|
||
| ```python | ||
| @dataclasses.dataclass | ||
| class PingResult: | ||
| reachable: bool # True if HTTP 200 | ||
| status_code: int # HTTP status code returned | ||
| api_version: str | None # Docker-Distribution-API-Version header value | ||
| latency_ms: float # Round-trip time in milliseconds | ||
|
|
||
| def to_dict(self) -> dict: ... | ||
| ``` | ||
|
|
||
| ### Error Class: `PingError` | ||
|
|
||
| Added to `src/regshape/libs/errors.py`: | ||
|
|
||
| ```python | ||
| class PingError(RegShapeError): | ||
| """Error caused by a failed registry ping (connection, DNS, timeout).""" | ||
| pass | ||
| ``` | ||
|
|
||
| ## Protocol Flow | ||
|
|
||
| ``` | ||
| Client Registry | ||
| | | | ||
| |--- GET /v2/ ----------------->| | ||
| |<-- 200 OK + headers ----------| | ||
| ``` | ||
|
|
||
| The `GET /v2/` endpoint is the OCI Distribution Spec API version check. A `200 OK` response confirms the registry is reachable and speaks the Distribution API. The response may include a `Docker-Distribution-API-Version` header (typically `registry/2.0`). | ||
|
|
||
| ### Behavior by HTTP Status | ||
|
|
||
| | Status | Interpretation | Result | | ||
| |--------|---------------|--------| | ||
| | `200` | Registry reachable and authenticated | `PingResult(reachable=True, ...)` | | ||
| | `401` | Authentication required or failed | Raises `AuthError` | | ||
| | Other 4xx/5xx | Registry responded but endpoint unsupported | `PingResult(reachable=False, ...)` | | ||
| | Connection error / timeout | Registry unreachable | Raises `PingError` | | ||
|
|
||
| ### Latency Measurement | ||
|
|
||
| Round-trip latency is measured using `time.monotonic()` around the `client.get()` call and reported in milliseconds. | ||
|
|
||
| ## CLI Layer | ||
|
|
||
| ### File: `src/regshape/cli/ping.py` | ||
|
|
||
| A **top-level command** (not a command group), registered directly on the `regshape` group in `main.py`. | ||
|
|
||
| **Implementation pattern** (follows `tag.py`): | ||
| - Creates `RegistryClient(TransportConfig(registry=registry, insecure=insecure))` | ||
| - Calls `ping(client)` from the operations module | ||
| - Catches `(AuthError, PingError, requests.exceptions.RequestException)` | ||
| - Uses `@telemetry_options` and `@track_scenario("ping")` decorators | ||
|
|
||
| ### Registration in `main.py` | ||
|
|
||
| ```python | ||
| from regshape.cli.ping import ping | ||
| regshape.add_command(ping) | ||
| ``` | ||
|
|
||
| ## Examples | ||
|
|
||
| ```bash | ||
| # Basic ping | ||
| regshape ping --registry ghcr.io | ||
|
|
||
| # Ping with JSON output | ||
| regshape ping --registry ghcr.io --json | ||
|
|
||
| # Ping an insecure (HTTP) registry | ||
| regshape --insecure ping --registry localhost:5000 | ||
| ``` | ||
|
|
||
| ## Output Format | ||
|
|
||
| ### Plain text (default) | ||
|
|
||
| Success: | ||
|
|
||
| ``` | ||
| Registry ghcr.io is reachable | ||
| API Version: registry/2.0 | ||
| Latency: 42ms | ||
| ``` | ||
|
|
||
| Failure (non-200 response): | ||
|
|
||
| ``` | ||
| Error: Registry ghcr.io is not reachable (HTTP 503) | ||
| ``` | ||
|
|
||
| Failure (connection error): | ||
|
|
||
| ``` | ||
| Error: Registry ghcr.io is not reachable: Connection refused | ||
| ``` | ||
|
|
||
| Failure (auth error): | ||
|
|
||
| ``` | ||
| Error: Registry ghcr.io requires authentication: 401 Unauthorized | ||
| ``` | ||
|
|
||
| ### JSON (`--json`) | ||
|
|
||
| Success: | ||
|
|
||
| ```json | ||
| { | ||
| "registry": "ghcr.io", | ||
| "reachable": true, | ||
| "status_code": 200, | ||
| "api_version": "registry/2.0", | ||
| "latency_ms": 42.3 | ||
| } | ||
| ``` | ||
|
|
||
| Failure: | ||
|
|
||
| ```json | ||
| { | ||
| "registry": "ghcr.io", | ||
| "reachable": false, | ||
| "error": "503 Service Unavailable" | ||
| } | ||
| ``` | ||
|
|
||
| ## Exit Codes | ||
|
|
||
| | Code | Meaning | | ||
| |------|---------| | ||
| | 0 | Registry is reachable (HTTP 200 or authentication required, e.g. HTTP 401/403) | | ||
| | 1 | Registry is not reachable or error occurred | | ||
|
|
||
| ## Error Messages | ||
|
|
||
| | Scenario | Message | | ||
| |----------|---------| | ||
| | Connection refused | `Error: Registry <host> is not reachable: Connection refused` | | ||
| | DNS resolution failed | `Error: Registry <host> is not reachable: Name resolution failed` | | ||
| | Timeout | `Error: Registry <host> is not reachable: Connection timed out` | | ||
| | 401 Unauthorized | `Error: Registry <host> requires authentication: 401 Unauthorized` | | ||
| | Non-200 HTTP status | `Error: Registry <host> is not reachable (HTTP <code>)` | | ||
|
|
||
| ## Files to Create/Modify | ||
|
|
||
| | File | Action | | ||
| |------|--------| | ||
| | `src/regshape/libs/ping/__init__.py` | Create — re-exports `ping` and `PingResult` | | ||
| | `src/regshape/libs/ping/operations.py` | Create — `ping()` function and `PingResult` dataclass | | ||
| | `src/regshape/libs/errors.py` | Modify — add `PingError` | | ||
| | `src/regshape/cli/ping.py` | Create — Click command | | ||
| | `src/regshape/cli/main.py` | Modify — import and register `ping` command | | ||
| | `src/regshape/tests/test_ping_operations.py` | Create — operations layer tests | | ||
| | `src/regshape/tests/test_ping_cli.py` | Create — CLI layer tests | | ||
|
|
||
| ## Test Plan | ||
|
|
||
| ### Operations tests (`test_ping_operations.py`) | ||
|
|
||
| - Mock `RegistryClient.get()` returning 200 with `Docker-Distribution-API-Version` header → `PingResult(reachable=True, api_version="registry/2.0")` | ||
| - Mock returning 200 without `Docker-Distribution-API-Version` header → `PingResult(reachable=True, api_version=None)` | ||
| - Mock returning non-200 status (e.g. 503) → `PingResult(reachable=False, status_code=503)` | ||
| - Mock raising `AuthError` (401) → propagated to caller | ||
| - Mock raising `ConnectionError` → `PingError` | ||
| - Mock raising `Timeout` → `PingError` | ||
| - Verify latency is measured (non-negative value) | ||
|
|
||
| ### CLI tests (`test_ping_cli.py`) | ||
|
|
||
| - Successful ping → exit code 0, plain text contains "is reachable" | ||
| - Successful ping with `--json` → exit code 0, valid JSON with expected keys | ||
| - Unreachable registry → exit code 1, error message | ||
| - Auth failure → exit code 0, message indicates registry is reachable but authentication failed | ||
| - `--registry` option is required → exit code 2 (Click usage error) | ||
|
|
||
| ## Dependencies | ||
|
|
||
| - Internal: `regshape.libs.transport` (`RegistryClient`, `TransportConfig`), `regshape.libs.errors`, `regshape.libs.decorators` | ||
| - External: `requests`, `click` | ||
|
|
||
| ## Open Questions | ||
|
|
||
| - [ ] Should `--registry` also accept a full image reference (and extract the registry), or strictly a hostname? Current design uses hostname-only since this is a connectivity check, not a repository operation. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,129 @@ | ||
| #!/usr/bin/env python3 | ||
|
|
||
| """ | ||
| :mod:`regshape.cli.ping` - CLI command for OCI registry ping | ||
| ============================================================== | ||
|
|
||
| .. module:: regshape.cli.ping | ||
| :platform: Unix, Windows | ||
| :synopsis: Top-level Click command that pings an OCI registry via | ||
| ``GET /v2/`` to verify connectivity and API support. | ||
|
|
||
| .. moduleauthor:: ToddySM <toddysm@gmail.com> | ||
| """ | ||
|
|
||
| import json | ||
| import sys | ||
|
|
||
| import click | ||
| import requests | ||
|
|
||
| from regshape.libs.decorators import telemetry_options | ||
| from regshape.libs.decorators.scenario import track_scenario | ||
| from regshape.libs.errors import AuthError, PingError | ||
| from regshape.libs.ping import ping as ping_registry | ||
| from regshape.libs.transport import RegistryClient, TransportConfig | ||
|
|
||
|
|
||
| # =========================================================================== | ||
| # ping command (top-level, not a group) | ||
| # =========================================================================== | ||
|
|
||
| @click.command() | ||
| @telemetry_options | ||
| @click.option( | ||
| "--registry", | ||
| "-r", | ||
| required=True, | ||
| metavar="REGISTRY", | ||
| help="Registry hostname (e.g. ghcr.io, localhost:5000).", | ||
| ) | ||
| @click.option( | ||
| "--json", | ||
| "as_json", | ||
| is_flag=True, | ||
| default=False, | ||
| help="Output as JSON.", | ||
| ) | ||
| @click.pass_context | ||
| @track_scenario("ping") | ||
| def ping(ctx, registry, as_json): | ||
| """Ping an OCI registry to verify connectivity and API support. | ||
|
|
||
| Issues ``GET /v2/`` against the target REGISTRY and reports whether | ||
| the registry is reachable, the API version it advertises, and the | ||
| round-trip latency. Credentials are resolved automatically from | ||
| the credential store populated by ``auth login``. | ||
| """ | ||
| insecure = ctx.obj.get("insecure", False) if ctx.obj else False | ||
|
|
||
| client = RegistryClient(TransportConfig(registry=registry, insecure=insecure)) | ||
|
|
||
| try: | ||
| result = ping_registry(client) | ||
| except AuthError as exc: | ||
| # A 401/403 during token negotiation means the registry *is* | ||
| # reachable but requires credentials. Report success with a hint. | ||
| if as_json: | ||
| click.echo(json.dumps({ | ||
| "registry": registry, | ||
| "reachable": True, | ||
| "api_version": None, | ||
| "latency_ms": None, | ||
| "note": "Registry requires authentication", | ||
| "error": str(exc), | ||
| }, indent=2)) | ||
| else: | ||
| click.echo(f"Registry {registry} is reachable") | ||
| click.echo(" Note: Registry requires authentication. " | ||
| "Run 'regshape auth login' to configure credentials.") | ||
| return | ||
| except PingError as exc: | ||
| detail = str(exc.__cause__) if getattr(exc, "__cause__", None) is not None else str(exc) | ||
| _error(registry, detail, as_json) | ||
| sys.exit(1) | ||
| except requests.exceptions.RequestException as exc: | ||
| _error(registry, str(exc), as_json) | ||
| sys.exit(1) | ||
|
|
||
| if as_json: | ||
| output = { | ||
| "registry": registry, | ||
| "reachable": False, | ||
| "status_code": result.status_code, | ||
| "api_version": result.api_version, | ||
| "latency_ms": result.latency_ms, | ||
| "error": f"HTTP {result.status_code}", | ||
| } | ||
| click.echo(json.dumps(output, indent=2), err=True) | ||
| else: | ||
| _error(registry, f"HTTP {result.status_code}", as_json) | ||
| _error(registry, f"HTTP {result.status_code}", as_json) | ||
|
toddysm marked this conversation as resolved.
|
||
| sys.exit(1) | ||
|
|
||
| if as_json: | ||
| output = result.to_dict() | ||
| output["registry"] = registry | ||
| click.echo(json.dumps(output, indent=2)) | ||
| else: | ||
| click.echo(f"Registry {registry} is reachable") | ||
| if result.api_version: | ||
| click.echo(f" API Version: {result.api_version}") | ||
| click.echo(f" Latency: {result.latency_ms:.0f}ms") | ||
|
|
||
|
|
||
| # =========================================================================== | ||
| # Helpers | ||
| # =========================================================================== | ||
|
|
||
|
|
||
| def _error(registry: str, detail: str, as_json: bool = False) -> None: | ||
| """Print an error message to stderr.""" | ||
| if as_json: | ||
| click.echo(json.dumps({ | ||
| "registry": registry, | ||
| "reachable": False, | ||
| "error": detail, | ||
| }, indent=2), err=True) | ||
| else: | ||
| click.echo(f"Error: Registry {registry} is not reachable: {detail}", err=True) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.