From 75c77171354d8afba07b2bd7be4b76afab43edc9 Mon Sep 17 00:00:00 2001 From: Anand Jayarajan Date: Mon, 23 Nov 2026 13:08:08 -0500 Subject: [PATCH 01/11] [SDK/CLI] Add cluster registration Expose POST /clusters as CentMLClient.register_cluster and a `register` CLI command so users can register their own cluster. Co-Authored-By: Claude Opus 5.5 --- centml/cli/cluster.py | 41 +++++++++++++++++++++++++++++++++++++++ centml/cli/main.py | 3 ++- centml/sdk/api.py | 4 ++++ tests/test_cli_cluster.py | 39 +++++++++++++++++++++++++++++++++++++ tests/test_sdk_api.py | 19 ++++++++++++++++++ 5 files changed, 105 insertions(+), 1 deletion(-) diff --git a/centml/cli/cluster.py b/centml/cli/cluster.py index 52145f0..da5efed 100644 --- a/centml/cli/cluster.py +++ b/centml/cli/cluster.py @@ -10,6 +10,9 @@ RolloutStatus, ApiException, HardwareInstanceResponse, + CloudProvider, + ClusterCredential, + ClusterRegistrationRequest, ) from centml.sdk.api import get_centml_client @@ -326,3 +329,41 @@ def capacity(cluster_id): disable_numparse=True, ) ) + + +@click.command(help="Register your own Kubernetes cluster") +@click.option("--name", "display_name", required=True, help="Display name for the cluster") +@click.option("--storage-class", required=True, help="Storage class to use for deployments on the cluster") +@click.option("--server", required=True, help="URL of the cluster's Kubernetes API server") +@click.option( + "--ca-cert", + required=True, + help="Base64-encoded PEM CA certificate of the API server (a kubeconfig's certificate-authority-data)", +) +@click.option( + "--bearer-token", + required=True, + prompt=True, + hide_input=True, + help="Bearer token for the API server; prompted for when omitted", +) +@click.option("--region", default=None, help="Region the cluster runs in") +@click.option( + "--cloud-provider", + type=click.Choice([p.value for p in CloudProvider if p != CloudProvider.UNKNOWN]), + default=None, + help="Cloud provider the cluster runs on", +) +@handle_exception +# pylint: disable=R0917 +def register(display_name, storage_class, server, ca_cert, bearer_token, region, cloud_provider): + request = ClusterRegistrationRequest( + display_name=display_name, + storage_class=storage_class, + region=region, + cloud_provider=CloudProvider(cloud_provider) if cloud_provider else None, + credential=ClusterCredential(server=server, bearer_token=bearer_token, ca_cert=ca_cert), + ) + with get_centml_client() as cclient: + response = cclient.register_cluster(request) + click.echo(f"Registered cluster {response.id}") diff --git a/centml/cli/main.py b/centml/cli/main.py index 504ea4f..d610b93 100644 --- a/centml/cli/main.py +++ b/centml/cli/main.py @@ -1,7 +1,7 @@ import click from centml.cli.login import login, logout -from centml.cli.cluster import ls, get, delete, pause, resume, capacity +from centml.cli.cluster import ls, get, delete, pause, resume, capacity, register from centml.cli.shell import shell, exec_cmd # NVIDIA green (#76B900) @@ -46,6 +46,7 @@ def ccluster(): ccluster.add_command(pause) ccluster.add_command(resume) ccluster.add_command(capacity) +ccluster.add_command(register) ccluster.add_command(shell) ccluster.add_command(exec_cmd, name="exec") diff --git a/centml/sdk/api.py b/centml/sdk/api.py index b4a4af2..3f5af84 100644 --- a/centml/sdk/api.py +++ b/centml/sdk/api.py @@ -15,6 +15,7 @@ CreateDynamoDeploymentRequest, CreateJobDeploymentRequest, CreateHardwareInstanceRequest, + ClusterRegistrationRequest, UpdateClusterMetadataRequest, ApiException, InviteUserRequest, @@ -177,6 +178,9 @@ def resume(self, id): def get_clusters(self): return self._api.get_clusters_clusters_get() + def register_cluster(self, request: ClusterRegistrationRequest): + return self._api.create_cluster_clusters_post(request) + def update_cluster_metadata(self, cluster_id: int, request: UpdateClusterMetadataRequest): return self._api.update_cluster_metadata_clusters_cluster_id_metadata_put(cluster_id, request) diff --git a/tests/test_cli_cluster.py b/tests/test_cli_cluster.py index 998fbe3..4be03ad 100644 --- a/tests/test_cli_cluster.py +++ b/tests/test_cli_cluster.py @@ -226,3 +226,42 @@ def test_get_job_routes_to_job_api_and_displays_job_config(): assert "Parallelism" in result.output assert "h100 (8x H100)" in result.output assert "credits/hr" not in result.output + + +def test_register_sends_registration_request_and_prints_cluster_id(): + from centml.cli.cluster import register + from centml.sdk import CloudProvider + + with _patch_cluster_client() as client: + client.register_cluster.return_value = SimpleNamespace(id=7) + + result = CliRunner().invoke( + register, + [ + "--name", + "my-cluster", + "--storage-class", + "standard", + "--server", + "https://k8s.example.com", + "--ca-cert", + "Y2E=", + "--region", + "us-east-1", + "--cloud-provider", + "aws", + ], + input="secret-token\n", + ) + + assert result.exit_code == 0, result.output + assert "Registered cluster 7" in result.output + assert "secret-token" not in result.output + request = client.register_cluster.call_args.args[0] + assert request.display_name == "my-cluster" + assert request.storage_class == "standard" + assert request.region == "us-east-1" + assert request.cloud_provider == CloudProvider.AWS + assert request.credential.server == "https://k8s.example.com" + assert request.credential.ca_cert == "Y2E=" + assert request.credential.bearer_token == "secret-token" diff --git a/tests/test_sdk_api.py b/tests/test_sdk_api.py index 11d8ae1..2c5f6ed 100644 --- a/tests/test_sdk_api.py +++ b/tests/test_sdk_api.py @@ -6,6 +6,8 @@ import platform_api_python_client from platform_api_python_client import ( + ClusterCredential, + ClusterRegistrationRequest, CreateDynamoDeploymentRequest, CreateHardwareInstanceRequest, CreateJobDeploymentRequest, @@ -193,6 +195,23 @@ def test_update_cluster_metadata_delegates_to_platform_client(): api.update_cluster_metadata_clusters_cluster_id_metadata_put.assert_called_once_with(42, request) +def test_register_cluster_delegates_to_platform_client(): + api = MagicMock() + expected_response = MagicMock() + api.create_cluster_clusters_post.return_value = expected_response + request = ClusterRegistrationRequest( + display_name="my-cluster", + storage_class="standard", + credential=ClusterCredential(server="https://k8s.example.com", bearer_token="token", ca_cert="Y2E="), + ) + client = CentMLClient(api) + + response = client.register_cluster(request) + + assert response is expected_response + api.create_cluster_clusters_post.assert_called_once_with(request) + + def test_get_hardware_instances_returns_results(): api = MagicMock() expected_results = [SimpleNamespace(id=1), SimpleNamespace(id=2)] From 5d5300b47a26c0ad3a04def99d90a1a98e09b640 Mon Sep 17 00:00:00 2001 From: Anand Jayarajan Date: Mon, 23 Nov 2026 13:12:10 -0500 Subject: [PATCH 02/11] [SDK/CLI] Add cluster component updates Expose PUT /clusters/{id} as CentMLClient.update_cluster and an `update` CLI command that reads the components from a YAML or JSON file. Co-Authored-By: Claude Opus 5.5 --- centml/cli/cluster.py | 37 ++++++++++++++++++++++++++ centml/cli/main.py | 3 ++- centml/sdk/api.py | 4 +++ requirements-dev.txt | 1 + requirements.txt | 1 + tests/test_cli_cluster.py | 56 +++++++++++++++++++++++++++++++++++++++ tests/test_sdk_api.py | 11 ++++++++ 7 files changed, 112 insertions(+), 1 deletion(-) diff --git a/centml/cli/cluster.py b/centml/cli/cluster.py index da5efed..e79a42a 100644 --- a/centml/cli/cluster.py +++ b/centml/cli/cluster.py @@ -2,6 +2,8 @@ from functools import wraps from typing import Dict import click +import yaml +from pydantic import ValidationError from tabulate import tabulate from centml.sdk import ( DeploymentType, @@ -13,6 +15,8 @@ CloudProvider, ClusterCredential, ClusterRegistrationRequest, + ClusterBaseComponents, + UpdateClusterRequest, ) from centml.sdk.api import get_centml_client @@ -367,3 +371,36 @@ def register(display_name, storage_class, server, ca_cert, bearer_token, region, with get_centml_client() as cclient: response = cclient.register_cluster(request) click.echo(f"Registered cluster {response.id}") + + +@click.command(help="""Set the components installed on a registered cluster. + +COMPONENTS_FILE is a YAML or JSON mapping of component name to its Helm chart values +({} for the defaults). final_stack is required. Components left out of the file are +uninstalled from the cluster.""") +@click.argument("cluster_id", type=int) +@click.argument("components_file", type=click.File("r")) +@handle_exception +def update(cluster_id, components_file): + try: + components = yaml.safe_load(components_file) + except yaml.YAMLError as e: + raise click.BadParameter(f"not valid YAML: {e}", param_hint="COMPONENTS_FILE") from e + if not isinstance(components, dict): + raise click.BadParameter("must be a mapping of component name to chart values", param_hint="COMPONENTS_FILE") + # The generated model silently drops unknown names, which would uninstall a misspelled component. + unknown = sorted(set(components) - set(ClusterBaseComponents.model_fields)) + if unknown: + raise click.BadParameter( + f"unknown component(s) {', '.join(unknown)}; expected any of " + f"{', '.join(ClusterBaseComponents.model_fields)}", + param_hint="COMPONENTS_FILE", + ) + # from_dict, not the constructors: they drop chart keys the typed models don't list. + try: + request = UpdateClusterRequest.from_dict({"components": components}) + except ValidationError as e: + raise click.BadParameter(str(e), param_hint="COMPONENTS_FILE") from e + with get_centml_client() as cclient: + cclient.update_cluster(cluster_id, request) + click.echo(f"Updating components on cluster {cluster_id}") diff --git a/centml/cli/main.py b/centml/cli/main.py index d610b93..98a4832 100644 --- a/centml/cli/main.py +++ b/centml/cli/main.py @@ -1,7 +1,7 @@ import click from centml.cli.login import login, logout -from centml.cli.cluster import ls, get, delete, pause, resume, capacity, register +from centml.cli.cluster import ls, get, delete, pause, resume, capacity, register, update from centml.cli.shell import shell, exec_cmd # NVIDIA green (#76B900) @@ -47,6 +47,7 @@ def ccluster(): ccluster.add_command(resume) ccluster.add_command(capacity) ccluster.add_command(register) +ccluster.add_command(update) ccluster.add_command(shell) ccluster.add_command(exec_cmd, name="exec") diff --git a/centml/sdk/api.py b/centml/sdk/api.py index 3f5af84..dcec8fd 100644 --- a/centml/sdk/api.py +++ b/centml/sdk/api.py @@ -16,6 +16,7 @@ CreateJobDeploymentRequest, CreateHardwareInstanceRequest, ClusterRegistrationRequest, + UpdateClusterRequest, UpdateClusterMetadataRequest, ApiException, InviteUserRequest, @@ -181,6 +182,9 @@ def get_clusters(self): def register_cluster(self, request: ClusterRegistrationRequest): return self._api.create_cluster_clusters_post(request) + def update_cluster(self, cluster_id: int, request: UpdateClusterRequest): + return self._api.update_cluster_clusters_cluster_id_put(cluster_id, request) + def update_cluster_metadata(self, cluster_id: int, request: UpdateClusterMetadataRequest): return self._api.update_cluster_metadata_clusters_cluster_id_metadata_put(cluster_id, request) diff --git a/requirements-dev.txt b/requirements-dev.txt index 01b0850..79a7c95 100644 --- a/requirements-dev.txt +++ b/requirements-dev.txt @@ -7,3 +7,4 @@ pytest-env>=1.1.3 mypy==1.15.0 types-requests==2.31.0.2 types-tabulate>=0.9.0 +types-PyYAML>=6.0 diff --git a/requirements.txt b/requirements.txt index 20f20f7..2f5b80a 100644 --- a/requirements.txt +++ b/requirements.txt @@ -8,3 +8,4 @@ pyte>=0.8.0 platform-api-python-client==4.41.0 click>=8.4.1 typing-extensions>=4.5 +PyYAML>=6.0 diff --git a/tests/test_cli_cluster.py b/tests/test_cli_cluster.py index 4be03ad..372572d 100644 --- a/tests/test_cli_cluster.py +++ b/tests/test_cli_cluster.py @@ -265,3 +265,59 @@ def test_register_sends_registration_request_and_prints_cluster_id(): assert request.credential.server == "https://k8s.example.com" assert request.credential.ca_cert == "Y2E=" assert request.credential.bearer_token == "secret-token" + + +def test_update_sends_components_from_file_keeping_untyped_chart_keys(tmp_path): + from centml.cli.cluster import update + + components_file = tmp_path / "components.yaml" + components_file.write_text( + "final_stack: {}\n" + "ingress_nginx:\n" + " ingress-nginx:\n" + " controller:\n" + " podLabels:\n" + " sidecar.istio.io/inject: 'true'\n" + " untypedKey: 1\n" + ) + + with _patch_cluster_client() as client: + result = CliRunner().invoke(update, ["7", str(components_file)]) + + assert result.exit_code == 0, result.output + cluster_id, request = client.update_cluster.call_args.args + assert cluster_id == 7 + components = request.to_dict()["components"] + assert components["final_stack"] == {} + controller = components["ingress_nginx"]["ingress-nginx"]["controller"] + assert controller["podLabels"] == {"sidecar.istio.io/inject": "true"} + assert controller["untypedKey"] == 1 + + +def test_update_rejects_unknown_component_names(tmp_path): + from centml.cli.cluster import update + + components_file = tmp_path / "components.yaml" + components_file.write_text("final_stack: {}\ningress-nginx: {}\n") + + with _patch_cluster_client() as client: + result = CliRunner().invoke(update, ["7", str(components_file)]) + + assert result.exit_code != 0 + assert "unknown component(s) ingress-nginx" in result.output + client.update_cluster.assert_not_called() + + +@pytest.mark.parametrize("contents", ["istio: {}\n", "final_stack: [\n"]) +def test_update_reports_invalid_components_file_without_traceback(tmp_path, contents): + from centml.cli.cluster import update + + components_file = tmp_path / "components.yaml" + components_file.write_text(contents) + + with _patch_cluster_client() as client: + result = CliRunner().invoke(update, ["7", str(components_file)]) + + assert result.exit_code == 2 + assert "Invalid value for COMPONENTS_FILE" in result.output + client.update_cluster.assert_not_called() diff --git a/tests/test_sdk_api.py b/tests/test_sdk_api.py index 2c5f6ed..1029c34 100644 --- a/tests/test_sdk_api.py +++ b/tests/test_sdk_api.py @@ -8,6 +8,7 @@ from platform_api_python_client import ( ClusterCredential, ClusterRegistrationRequest, + UpdateClusterRequest, CreateDynamoDeploymentRequest, CreateHardwareInstanceRequest, CreateJobDeploymentRequest, @@ -212,6 +213,16 @@ def test_register_cluster_delegates_to_platform_client(): api.create_cluster_clusters_post.assert_called_once_with(request) +def test_update_cluster_delegates_to_platform_client(): + api = MagicMock() + request = UpdateClusterRequest.from_dict({"components": {"final_stack": {}}}) + client = CentMLClient(api) + + client.update_cluster(42, request) + + api.update_cluster_clusters_cluster_id_put.assert_called_once_with(42, request) + + def test_get_hardware_instances_returns_results(): api = MagicMock() expected_results = [SimpleNamespace(id=1), SimpleNamespace(id=2)] From 1296bee68d9463cbac46641cb1324037b4b41bdf Mon Sep 17 00:00:00 2001 From: Anand Jayarajan Date: Mon, 23 Nov 2026 13:15:16 -0500 Subject: [PATCH 03/11] [CLI] Rename cluster update command to update_cluster Co-Authored-By: Claude Opus 5.5 --- centml/cli/cluster.py | 9 ++++++--- centml/cli/main.py | 4 ++-- tests/test_cli_cluster.py | 12 ++++++------ 3 files changed, 14 insertions(+), 11 deletions(-) diff --git a/centml/cli/cluster.py b/centml/cli/cluster.py index e79a42a..7bbf3d7 100644 --- a/centml/cli/cluster.py +++ b/centml/cli/cluster.py @@ -373,15 +373,18 @@ def register(display_name, storage_class, server, ca_cert, bearer_token, region, click.echo(f"Registered cluster {response.id}") -@click.command(help="""Set the components installed on a registered cluster. +@click.command( + name="update_cluster", + help="""Set the components installed on a registered cluster. COMPONENTS_FILE is a YAML or JSON mapping of component name to its Helm chart values ({} for the defaults). final_stack is required. Components left out of the file are -uninstalled from the cluster.""") +uninstalled from the cluster.""", +) @click.argument("cluster_id", type=int) @click.argument("components_file", type=click.File("r")) @handle_exception -def update(cluster_id, components_file): +def update_cluster(cluster_id, components_file): try: components = yaml.safe_load(components_file) except yaml.YAMLError as e: diff --git a/centml/cli/main.py b/centml/cli/main.py index 98a4832..7ae3fd9 100644 --- a/centml/cli/main.py +++ b/centml/cli/main.py @@ -1,7 +1,7 @@ import click from centml.cli.login import login, logout -from centml.cli.cluster import ls, get, delete, pause, resume, capacity, register, update +from centml.cli.cluster import ls, get, delete, pause, resume, capacity, register, update_cluster from centml.cli.shell import shell, exec_cmd # NVIDIA green (#76B900) @@ -47,7 +47,7 @@ def ccluster(): ccluster.add_command(resume) ccluster.add_command(capacity) ccluster.add_command(register) -ccluster.add_command(update) +ccluster.add_command(update_cluster) ccluster.add_command(shell) ccluster.add_command(exec_cmd, name="exec") diff --git a/tests/test_cli_cluster.py b/tests/test_cli_cluster.py index 372572d..efc2c38 100644 --- a/tests/test_cli_cluster.py +++ b/tests/test_cli_cluster.py @@ -268,7 +268,7 @@ def test_register_sends_registration_request_and_prints_cluster_id(): def test_update_sends_components_from_file_keeping_untyped_chart_keys(tmp_path): - from centml.cli.cluster import update + from centml.cli.cluster import update_cluster components_file = tmp_path / "components.yaml" components_file.write_text( @@ -282,7 +282,7 @@ def test_update_sends_components_from_file_keeping_untyped_chart_keys(tmp_path): ) with _patch_cluster_client() as client: - result = CliRunner().invoke(update, ["7", str(components_file)]) + result = CliRunner().invoke(update_cluster, ["7", str(components_file)]) assert result.exit_code == 0, result.output cluster_id, request = client.update_cluster.call_args.args @@ -295,13 +295,13 @@ def test_update_sends_components_from_file_keeping_untyped_chart_keys(tmp_path): def test_update_rejects_unknown_component_names(tmp_path): - from centml.cli.cluster import update + from centml.cli.cluster import update_cluster components_file = tmp_path / "components.yaml" components_file.write_text("final_stack: {}\ningress-nginx: {}\n") with _patch_cluster_client() as client: - result = CliRunner().invoke(update, ["7", str(components_file)]) + result = CliRunner().invoke(update_cluster, ["7", str(components_file)]) assert result.exit_code != 0 assert "unknown component(s) ingress-nginx" in result.output @@ -310,13 +310,13 @@ def test_update_rejects_unknown_component_names(tmp_path): @pytest.mark.parametrize("contents", ["istio: {}\n", "final_stack: [\n"]) def test_update_reports_invalid_components_file_without_traceback(tmp_path, contents): - from centml.cli.cluster import update + from centml.cli.cluster import update_cluster components_file = tmp_path / "components.yaml" components_file.write_text(contents) with _patch_cluster_client() as client: - result = CliRunner().invoke(update, ["7", str(components_file)]) + result = CliRunner().invoke(update_cluster, ["7", str(components_file)]) assert result.exit_code == 2 assert "Invalid value for COMPONENTS_FILE" in result.output From 6f2c906130a4640a82259062b1bef031df235e83 Mon Sep 17 00:00:00 2001 From: Anand Jayarajan Date: Mon, 23 Nov 2026 13:16:37 -0500 Subject: [PATCH 04/11] [CLI] Rename cluster register command to register_cluster Co-Authored-By: Claude Opus 5.5 --- centml/cli/cluster.py | 4 ++-- centml/cli/main.py | 4 ++-- tests/test_cli_cluster.py | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/centml/cli/cluster.py b/centml/cli/cluster.py index 7bbf3d7..8ff534d 100644 --- a/centml/cli/cluster.py +++ b/centml/cli/cluster.py @@ -335,7 +335,7 @@ def capacity(cluster_id): ) -@click.command(help="Register your own Kubernetes cluster") +@click.command(name="register_cluster", help="Register your own Kubernetes cluster") @click.option("--name", "display_name", required=True, help="Display name for the cluster") @click.option("--storage-class", required=True, help="Storage class to use for deployments on the cluster") @click.option("--server", required=True, help="URL of the cluster's Kubernetes API server") @@ -360,7 +360,7 @@ def capacity(cluster_id): ) @handle_exception # pylint: disable=R0917 -def register(display_name, storage_class, server, ca_cert, bearer_token, region, cloud_provider): +def register_cluster(display_name, storage_class, server, ca_cert, bearer_token, region, cloud_provider): request = ClusterRegistrationRequest( display_name=display_name, storage_class=storage_class, diff --git a/centml/cli/main.py b/centml/cli/main.py index 7ae3fd9..4e46baf 100644 --- a/centml/cli/main.py +++ b/centml/cli/main.py @@ -1,7 +1,7 @@ import click from centml.cli.login import login, logout -from centml.cli.cluster import ls, get, delete, pause, resume, capacity, register, update_cluster +from centml.cli.cluster import ls, get, delete, pause, resume, capacity, register_cluster, update_cluster from centml.cli.shell import shell, exec_cmd # NVIDIA green (#76B900) @@ -46,7 +46,7 @@ def ccluster(): ccluster.add_command(pause) ccluster.add_command(resume) ccluster.add_command(capacity) -ccluster.add_command(register) +ccluster.add_command(register_cluster) ccluster.add_command(update_cluster) ccluster.add_command(shell) ccluster.add_command(exec_cmd, name="exec") diff --git a/tests/test_cli_cluster.py b/tests/test_cli_cluster.py index efc2c38..d49bb4f 100644 --- a/tests/test_cli_cluster.py +++ b/tests/test_cli_cluster.py @@ -229,14 +229,14 @@ def test_get_job_routes_to_job_api_and_displays_job_config(): def test_register_sends_registration_request_and_prints_cluster_id(): - from centml.cli.cluster import register + from centml.cli.cluster import register_cluster from centml.sdk import CloudProvider with _patch_cluster_client() as client: client.register_cluster.return_value = SimpleNamespace(id=7) result = CliRunner().invoke( - register, + register_cluster, [ "--name", "my-cluster", From b30f581a4cff08a0df45a9c48c4f8095a61106c7 Mon Sep 17 00:00:00 2001 From: Anand Jayarajan Date: Mon, 23 Nov 2026 13:17:26 -0500 Subject: [PATCH 05/11] [Examples] Add SDK example for registering and updating a cluster Co-Authored-By: Claude Opus 5.5 --- examples/sdk/register_cluster.py | 80 ++++++++++++++++++++++++++++++++ 1 file changed, 80 insertions(+) create mode 100644 examples/sdk/register_cluster.py diff --git a/examples/sdk/register_cluster.py b/examples/sdk/register_cluster.py new file mode 100644 index 0000000..11c6450 --- /dev/null +++ b/examples/sdk/register_cluster.py @@ -0,0 +1,80 @@ +#!/usr/bin/env python3 +"""Register your own Kubernetes cluster and install its platform components. + +Run `centml login` or configure service-account credentials first. Registering and +updating clusters requires admin privileges (PERM_ADMIN_MANAGE_HARDWARE). + +The cluster's API server is reached with a bearer token and its CA certificate, +base64-encoded as in a kubeconfig's `certificate-authority-data`: + + export CLUSTER_SERVER="https://" + export CLUSTER_BEARER_TOKEN="" + export CLUSTER_CA_CERT="" + export CLUSTER_STORAGE_CLASS="" + python examples/sdk/register_cluster.py + +Set CLUSTER_ID instead to skip registration and only update an existing cluster. +""" + +import os + +from centml.sdk import ClusterCredential, ClusterRegistrationRequest, UpdateClusterRequest +from centml.sdk.api import get_centml_client + +# Each component maps to its Helm chart values; {} installs it with the catalog defaults. +# final_stack is required. A component left out is uninstalled, so every update must list +# all the components the cluster should keep. +COMPONENTS = { + "kube_prometheus_stack": {}, + "istio": {}, + "cert_manager": {}, + "ingress_nginx": {}, + "keda": {}, + "argo_rollouts": {}, + "gpu_operator": {}, + "kai_scheduler": {}, + "metrics_server": {}, + "final_stack": {}, +} + + +def required_env(name: str) -> str: + value = os.getenv(name) + if not value: + raise SystemExit(f"Set {name} before running this example.") + return value + + +def register_cluster(client) -> int: + request = ClusterRegistrationRequest( + display_name=os.getenv("CLUSTER_NAME", "my-cluster"), + storage_class=required_env("CLUSTER_STORAGE_CLASS"), + region=os.getenv("CLUSTER_REGION"), + credential=ClusterCredential( + server=required_env("CLUSTER_SERVER"), + bearer_token=required_env("CLUSTER_BEARER_TOKEN"), + ca_cert=required_env("CLUSTER_CA_CERT"), + ), + ) + cluster_id = client.register_cluster(request).id + print(f"Registered cluster {cluster_id}") + return cluster_id + + +def update_cluster(client, cluster_id: int) -> None: + # Build the request with from_dict: the model constructors drop chart values + # their typed models don't list. + request = UpdateClusterRequest.from_dict({"components": COMPONENTS}) + client.update_cluster(cluster_id, request) + # The update returns without waiting for the components to roll out. + print(f"Installing {len(COMPONENTS)} components on cluster {cluster_id}") + + +def main() -> None: + with get_centml_client() as client: + cluster_id = int(os.environ["CLUSTER_ID"]) if os.getenv("CLUSTER_ID") else register_cluster(client) + update_cluster(client, cluster_id) + + +if __name__ == "__main__": + main() From 56a7e5e14feca2eb1632e87d8828ea113a896aad Mon Sep 17 00:00:00 2001 From: Anand Jayarajan Date: Mon, 23 Nov 2026 13:22:14 -0500 Subject: [PATCH 06/11] [Examples] Split cluster example into register and update scripts Co-Authored-By: Claude Opus 5.5 --- examples/sdk/register_cluster.py | 47 +++++------------------------- examples/sdk/update_cluster.py | 50 ++++++++++++++++++++++++++++++++ 2 files changed, 58 insertions(+), 39 deletions(-) create mode 100644 examples/sdk/update_cluster.py diff --git a/examples/sdk/register_cluster.py b/examples/sdk/register_cluster.py index 11c6450..e3e250c 100644 --- a/examples/sdk/register_cluster.py +++ b/examples/sdk/register_cluster.py @@ -1,8 +1,8 @@ #!/usr/bin/env python3 -"""Register your own Kubernetes cluster and install its platform components. +"""Register your own Kubernetes cluster. -Run `centml login` or configure service-account credentials first. Registering and -updating clusters requires admin privileges (PERM_ADMIN_MANAGE_HARDWARE). +Run `centml login` or configure service-account credentials first. Registering a +cluster requires admin privileges (PERM_ADMIN_MANAGE_HARDWARE). The cluster's API server is reached with a bearer token and its CA certificate, base64-encoded as in a kubeconfig's `certificate-authority-data`: @@ -13,30 +13,14 @@ export CLUSTER_STORAGE_CLASS="" python examples/sdk/register_cluster.py -Set CLUSTER_ID instead to skip registration and only update an existing cluster. +Then install the cluster's components with examples/sdk/update_cluster.py. """ import os -from centml.sdk import ClusterCredential, ClusterRegistrationRequest, UpdateClusterRequest +from centml.sdk import ClusterCredential, ClusterRegistrationRequest from centml.sdk.api import get_centml_client -# Each component maps to its Helm chart values; {} installs it with the catalog defaults. -# final_stack is required. A component left out is uninstalled, so every update must list -# all the components the cluster should keep. -COMPONENTS = { - "kube_prometheus_stack": {}, - "istio": {}, - "cert_manager": {}, - "ingress_nginx": {}, - "keda": {}, - "argo_rollouts": {}, - "gpu_operator": {}, - "kai_scheduler": {}, - "metrics_server": {}, - "final_stack": {}, -} - def required_env(name: str) -> str: value = os.getenv(name) @@ -45,7 +29,7 @@ def required_env(name: str) -> str: return value -def register_cluster(client) -> int: +def main() -> None: request = ClusterRegistrationRequest( display_name=os.getenv("CLUSTER_NAME", "my-cluster"), storage_class=required_env("CLUSTER_STORAGE_CLASS"), @@ -56,24 +40,9 @@ def register_cluster(client) -> int: ca_cert=required_env("CLUSTER_CA_CERT"), ), ) - cluster_id = client.register_cluster(request).id - print(f"Registered cluster {cluster_id}") - return cluster_id - - -def update_cluster(client, cluster_id: int) -> None: - # Build the request with from_dict: the model constructors drop chart values - # their typed models don't list. - request = UpdateClusterRequest.from_dict({"components": COMPONENTS}) - client.update_cluster(cluster_id, request) - # The update returns without waiting for the components to roll out. - print(f"Installing {len(COMPONENTS)} components on cluster {cluster_id}") - - -def main() -> None: with get_centml_client() as client: - cluster_id = int(os.environ["CLUSTER_ID"]) if os.getenv("CLUSTER_ID") else register_cluster(client) - update_cluster(client, cluster_id) + cluster_id = client.register_cluster(request).id + print(f"Registered cluster {cluster_id}") if __name__ == "__main__": diff --git a/examples/sdk/update_cluster.py b/examples/sdk/update_cluster.py new file mode 100644 index 0000000..90e74f6 --- /dev/null +++ b/examples/sdk/update_cluster.py @@ -0,0 +1,50 @@ +#!/usr/bin/env python3 +"""Install the platform components on a registered cluster. + +Run `centml login` or configure service-account credentials first. Updating a +cluster requires admin privileges (PERM_ADMIN_MANAGE_HARDWARE). + + export CLUSTER_ID="" + python examples/sdk/update_cluster.py + +Register the cluster first with examples/sdk/register_cluster.py. +""" + +import os + +from centml.sdk import UpdateClusterRequest +from centml.sdk.api import get_centml_client + +# Each component maps to its Helm chart values; {} installs it with the catalog defaults. +# final_stack is required. A component left out is uninstalled, so every update must list +# all the components the cluster should keep. +COMPONENTS = { + "kube_prometheus_stack": {}, + "istio": {}, + "cert_manager": {}, + "ingress_nginx": {}, + "keda": {}, + "argo_rollouts": {}, + "gpu_operator": {}, + "kai_scheduler": {}, + "metrics_server": {}, + "final_stack": {}, +} + + +def main() -> None: + cluster_id = os.getenv("CLUSTER_ID") + if not cluster_id: + raise SystemExit("Set CLUSTER_ID before running this example.") + + # Build the request with from_dict: the model constructors drop chart values + # their typed models don't list. + request = UpdateClusterRequest.from_dict({"components": COMPONENTS}) + with get_centml_client() as client: + client.update_cluster(int(cluster_id), request) + # The update returns without waiting for the components to roll out. + print(f"Installing {len(COMPONENTS)} components on cluster {cluster_id}") + + +if __name__ == "__main__": + main() From d760e2253939752e1e37d2690876a50c726be134 Mon Sep 17 00:00:00 2001 From: Anand Jayarajan Date: Mon, 23 Nov 2026 13:49:38 -0500 Subject: [PATCH 07/11] [SDK/CLI] Add cluster listing and deletion Add CentMLClient.delete_cluster, list_clusters and delete_cluster CLI commands, and a delete_cluster example. Co-Authored-By: Claude Opus 5.5 --- centml/cli/cluster.py | 20 ++++++++++++++ centml/cli/main.py | 15 ++++++++++- centml/sdk/api.py | 3 +++ examples/sdk/delete_cluster.py | 30 +++++++++++++++++++++ tests/test_cli_cluster.py | 49 ++++++++++++++++++++++++++++++++++ tests/test_sdk_api.py | 9 +++++++ 6 files changed, 125 insertions(+), 1 deletion(-) create mode 100644 examples/sdk/delete_cluster.py diff --git a/centml/cli/cluster.py b/centml/cli/cluster.py index 8ff534d..4f69b1f 100644 --- a/centml/cli/cluster.py +++ b/centml/cli/cluster.py @@ -407,3 +407,23 @@ def update_cluster(cluster_id, components_file): with get_centml_client() as cclient: cclient.update_cluster(cluster_id, request) click.echo(f"Updating components on cluster {cluster_id}") + + +@click.command(name="list_clusters", help="List the clusters you can deploy to") +@handle_exception +def list_clusters(): + with get_centml_client() as cclient: + clusters = cclient.get_clusters().results + + rows = [[c.id, c.display_name, c.region or ""] for c in sorted(clusters, key=lambda c: c.id)] + click.echo(tabulate(rows, headers=["ID", "Name", "Region"], tablefmt="rounded_outline", disable_numparse=True)) + + +@click.command(name="delete_cluster", help="Delete a registered cluster and uninstall its components") +@click.argument("cluster_id", type=int) +@click.confirmation_option(prompt="Delete this cluster and uninstall its components?") +@handle_exception +def delete_cluster(cluster_id): + with get_centml_client() as cclient: + cclient.delete_cluster(cluster_id) + click.echo(f"Deleted cluster {cluster_id}") diff --git a/centml/cli/main.py b/centml/cli/main.py index 4e46baf..28e836d 100644 --- a/centml/cli/main.py +++ b/centml/cli/main.py @@ -1,7 +1,18 @@ import click from centml.cli.login import login, logout -from centml.cli.cluster import ls, get, delete, pause, resume, capacity, register_cluster, update_cluster +from centml.cli.cluster import ( + ls, + get, + delete, + pause, + resume, + capacity, + register_cluster, + update_cluster, + list_clusters, + delete_cluster, +) from centml.cli.shell import shell, exec_cmd # NVIDIA green (#76B900) @@ -48,6 +59,8 @@ def ccluster(): ccluster.add_command(capacity) ccluster.add_command(register_cluster) ccluster.add_command(update_cluster) +ccluster.add_command(list_clusters) +ccluster.add_command(delete_cluster) ccluster.add_command(shell) ccluster.add_command(exec_cmd, name="exec") diff --git a/centml/sdk/api.py b/centml/sdk/api.py index dcec8fd..8585ad5 100644 --- a/centml/sdk/api.py +++ b/centml/sdk/api.py @@ -185,6 +185,9 @@ def register_cluster(self, request: ClusterRegistrationRequest): def update_cluster(self, cluster_id: int, request: UpdateClusterRequest): return self._api.update_cluster_clusters_cluster_id_put(cluster_id, request) + def delete_cluster(self, cluster_id: int): + return self._api.delete_cluster_clusters_cluster_id_delete(cluster_id) + def update_cluster_metadata(self, cluster_id: int, request: UpdateClusterMetadataRequest): return self._api.update_cluster_metadata_clusters_cluster_id_metadata_put(cluster_id, request) diff --git a/examples/sdk/delete_cluster.py b/examples/sdk/delete_cluster.py new file mode 100644 index 0000000..e726db7 --- /dev/null +++ b/examples/sdk/delete_cluster.py @@ -0,0 +1,30 @@ +#!/usr/bin/env python3 +"""Delete a registered cluster. + +Run `centml login` or configure service-account credentials first. Deleting a +cluster requires admin privileges (PERM_ADMIN_MANAGE_HARDWARE). It uninstalls the +cluster's components and cannot be undone. + + export CLUSTER_ID="" + python examples/sdk/delete_cluster.py + +List your clusters and their IDs with examples/sdk/get_clusters.py. +""" + +import os + +from centml.sdk.api import get_centml_client + + +def main() -> None: + cluster_id = os.getenv("CLUSTER_ID") + if not cluster_id: + raise SystemExit("Set CLUSTER_ID before running this example.") + + with get_centml_client() as client: + client.delete_cluster(int(cluster_id)) + print(f"Deleted cluster {cluster_id}") + + +if __name__ == "__main__": + main() diff --git a/tests/test_cli_cluster.py b/tests/test_cli_cluster.py index d49bb4f..dba95d9 100644 --- a/tests/test_cli_cluster.py +++ b/tests/test_cli_cluster.py @@ -321,3 +321,52 @@ def test_update_reports_invalid_components_file_without_traceback(tmp_path, cont assert result.exit_code == 2 assert "Invalid value for COMPONENTS_FILE" in result.output client.update_cluster.assert_not_called() + + +def test_list_clusters_shows_clusters_sorted_by_id(): + from centml.cli.cluster import list_clusters + + with _patch_cluster_client() as client: + client.get_clusters.return_value = SimpleNamespace( + results=[ + SimpleNamespace(id=9, display_name="second", region=None), + SimpleNamespace(id=3, display_name="first", region="us-east-1"), + ] + ) + + result = CliRunner().invoke(list_clusters) + + assert result.exit_code == 0, result.output + assert "us-east-1" in result.output + assert result.output.index("first") < result.output.index("second") + + +def test_delete_cluster_deletes_after_confirmation(): + from centml.cli.cluster import delete_cluster + + with _patch_cluster_client() as client: + result = CliRunner().invoke(delete_cluster, ["7"], input="y\n") + + assert result.exit_code == 0, result.output + assert "Deleted cluster 7" in result.output + client.delete_cluster.assert_called_once_with(7) + + +def test_delete_cluster_skips_prompt_with_yes(): + from centml.cli.cluster import delete_cluster + + with _patch_cluster_client() as client: + result = CliRunner().invoke(delete_cluster, ["7", "--yes"]) + + assert result.exit_code == 0, result.output + client.delete_cluster.assert_called_once_with(7) + + +def test_delete_cluster_does_nothing_when_declined(): + from centml.cli.cluster import delete_cluster + + with _patch_cluster_client() as client: + result = CliRunner().invoke(delete_cluster, ["7"], input="n\n") + + assert result.exit_code == 1 + client.delete_cluster.assert_not_called() diff --git a/tests/test_sdk_api.py b/tests/test_sdk_api.py index 1029c34..81d8357 100644 --- a/tests/test_sdk_api.py +++ b/tests/test_sdk_api.py @@ -223,6 +223,15 @@ def test_update_cluster_delegates_to_platform_client(): api.update_cluster_clusters_cluster_id_put.assert_called_once_with(42, request) +def test_delete_cluster_delegates_to_platform_client(): + api = MagicMock() + client = CentMLClient(api) + + client.delete_cluster(42) + + api.delete_cluster_clusters_cluster_id_delete.assert_called_once_with(42) + + def test_get_hardware_instances_returns_results(): api = MagicMock() expected_results = [SimpleNamespace(id=1), SimpleNamespace(id=2)] From dd93190097977e3f409242e7042fb61d5f4c89d8 Mon Sep 17 00:00:00 2001 From: Anand Jayarajan Date: Mon, 23 Nov 2026 15:45:28 -0500 Subject: [PATCH 08/11] [Docs] Document cluster management CLI commands in README Co-Authored-By: Claude Opus 5.5 --- README.md | 57 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/README.md b/README.md index 063a4bb..6587914 100644 --- a/README.md +++ b/README.md @@ -116,6 +116,63 @@ source scripts/completions/completion. Shell language can be: bash, zsh, fish (Hint: add `source /path/to/completions/completion.` to your `~/.bashrc`, `~/.zshrc` or `~/.config/fish/completions/centml.fish`) +### Managing your own clusters + +Registering, updating and deleting clusters requires admin privileges +(PERM_ADMIN_MANAGE_HARDWARE). Before registering, install the infra-plane operator in +the cluster and create a ServiceAccount token with cluster-admin access: + +```bash +helm install ccluster-ip oci://ghcr.io/nvidia/charts/ccluster-ip --version \ + -n ccluster-ip-system --create-namespace +``` + +**Register** a cluster. `--ca-cert` is the base64-encoded PEM CA certificate of the +API server, as in a kubeconfig's `certificate-authority-data`. The bearer token is +prompted for, with hidden input, when `--bearer-token` is omitted: + +```bash +ccluster register_cluster --name my-cluster --storage-class standard-rwo \ + --server https:// --ca-cert \ + --cloud-provider gcp --region us-east1 +``` + +**List** the clusters you have access to, with their IDs: + +```bash +ccluster list_clusters +``` + +**Update** the components installed on a registered cluster. The file maps each +component to its Helm chart values (`{}` for the defaults); `final_stack` is required, +and components left out of the file are uninstalled: + +```bash +cat > components.yaml < components.yaml +``` + +**Delete** a cluster. This uninstalls its components; pass `--yes` to skip the +confirmation prompt: + +```bash +ccluster delete_cluster +``` + +`examples/sdk/register_cluster.py`, `update_cluster.py`, `get_clusters.py` and +`delete_cluster.py` do the same with the SDK. + ### Tests To run tests, first install required packages: ```bash From a1e42f43eed6bf88ee9b41884dd314658394788b Mon Sep 17 00:00:00 2001 From: Anand Jayarajan Date: Mon, 23 Nov 2026 15:49:59 -0500 Subject: [PATCH 09/11] [CLI] Take the PUT /clusters/{id} request body in update_cluster The file now has the API's {"components": {...}} shape, in YAML or JSON, so the same file works with the API and the CLI. Co-Authored-By: Claude Opus 5.5 --- README.md | 28 +++++++------- centml/cli/cluster.py | 35 ++++++++++------- tests/test_cli_cluster.py | 79 +++++++++++++++++++++++---------------- 3 files changed, 83 insertions(+), 59 deletions(-) diff --git a/README.md b/README.md index 6587914..f74e930 100644 --- a/README.md +++ b/README.md @@ -143,22 +143,24 @@ ccluster register_cluster --name my-cluster --storage-class standard-rwo \ ccluster list_clusters ``` -**Update** the components installed on a registered cluster. The file maps each -component to its Helm chart values (`{}` for the defaults); `final_stack` is required, -and components left out of the file are uninstalled: +**Update** the components installed on a registered cluster. The file is the +`PUT /clusters/{id}` request body, in YAML or JSON: `components` maps each component to +its Helm chart values (`{}` for the defaults). `final_stack` is required, and components +left out of the file are uninstalled: ```bash cat > components.yaml < components.yaml ``` diff --git a/centml/cli/cluster.py b/centml/cli/cluster.py index 4f69b1f..93bf852 100644 --- a/centml/cli/cluster.py +++ b/centml/cli/cluster.py @@ -377,33 +377,40 @@ def register_cluster(display_name, storage_class, server, ca_cert, bearer_token, name="update_cluster", help="""Set the components installed on a registered cluster. -COMPONENTS_FILE is a YAML or JSON mapping of component name to its Helm chart values -({} for the defaults). final_stack is required. Components left out of the file are -uninstalled from the cluster.""", +REQUEST_FILE is the PUT /clusters/{id} request body, in YAML or JSON: a "components" +mapping of component name to its Helm chart values ({} for the defaults). +final_stack is required. Components left out of the file are uninstalled from the cluster.""", ) @click.argument("cluster_id", type=int) -@click.argument("components_file", type=click.File("r")) +@click.argument("request_file", type=click.File("r")) @handle_exception -def update_cluster(cluster_id, components_file): +def update_cluster(cluster_id, request_file): + def invalid(message): + return click.BadParameter(message, param_hint="REQUEST_FILE") + try: - components = yaml.safe_load(components_file) + # YAML is a superset of JSON, so this reads both. + body = yaml.safe_load(request_file) except yaml.YAMLError as e: - raise click.BadParameter(f"not valid YAML: {e}", param_hint="COMPONENTS_FILE") from e + raise invalid(f"not valid YAML or JSON: {e}") from e + # The generated models silently drop unknown keys, so a misspelled key would go + # unnoticed, and a misspelled component would be uninstalled. + if not isinstance(body, dict) or set(body) != {"components"}: + raise invalid('must be a mapping with a single "components" key') + components = body["components"] if not isinstance(components, dict): - raise click.BadParameter("must be a mapping of component name to chart values", param_hint="COMPONENTS_FILE") - # The generated model silently drops unknown names, which would uninstall a misspelled component. + raise invalid('"components" must be a mapping of component name to chart values') unknown = sorted(set(components) - set(ClusterBaseComponents.model_fields)) if unknown: - raise click.BadParameter( + raise invalid( f"unknown component(s) {', '.join(unknown)}; expected any of " - f"{', '.join(ClusterBaseComponents.model_fields)}", - param_hint="COMPONENTS_FILE", + f"{', '.join(ClusterBaseComponents.model_fields)}" ) # from_dict, not the constructors: they drop chart keys the typed models don't list. try: - request = UpdateClusterRequest.from_dict({"components": components}) + request = UpdateClusterRequest.from_dict(body) except ValidationError as e: - raise click.BadParameter(str(e), param_hint="COMPONENTS_FILE") from e + raise invalid(str(e)) from e with get_centml_client() as cclient: cclient.update_cluster(cluster_id, request) click.echo(f"Updating components on cluster {cluster_id}") diff --git a/tests/test_cli_cluster.py b/tests/test_cli_cluster.py index dba95d9..0631ef9 100644 --- a/tests/test_cli_cluster.py +++ b/tests/test_cli_cluster.py @@ -267,22 +267,30 @@ def test_register_sends_registration_request_and_prints_cluster_id(): assert request.credential.bearer_token == "secret-token" -def test_update_sends_components_from_file_keeping_untyped_chart_keys(tmp_path): +@pytest.mark.parametrize( + "contents", + [ + "components:\n" + " final_stack: {}\n" + " ingress_nginx:\n" + " ingress-nginx:\n" + " controller:\n" + " podLabels:\n" + " sidecar.istio.io/inject: 'true'\n" + " untypedKey: 1\n", + '{"components": {"final_stack": {}, "ingress_nginx": {"ingress-nginx": {"controller": ' + '{"podLabels": {"sidecar.istio.io/inject": "true"}, "untypedKey": 1}}}}}', + ], + ids=["yaml", "json"], +) +def test_update_cluster_sends_request_from_file_keeping_untyped_chart_keys(tmp_path, contents): from centml.cli.cluster import update_cluster - components_file = tmp_path / "components.yaml" - components_file.write_text( - "final_stack: {}\n" - "ingress_nginx:\n" - " ingress-nginx:\n" - " controller:\n" - " podLabels:\n" - " sidecar.istio.io/inject: 'true'\n" - " untypedKey: 1\n" - ) + request_file = tmp_path / "request" + request_file.write_text(contents) with _patch_cluster_client() as client: - result = CliRunner().invoke(update_cluster, ["7", str(components_file)]) + result = CliRunner().invoke(update_cluster, ["7", str(request_file)]) assert result.exit_code == 0, result.output cluster_id, request = client.update_cluster.call_args.args @@ -294,32 +302,39 @@ def test_update_sends_components_from_file_keeping_untyped_chart_keys(tmp_path): assert controller["untypedKey"] == 1 -def test_update_rejects_unknown_component_names(tmp_path): - from centml.cli.cluster import update_cluster - - components_file = tmp_path / "components.yaml" - components_file.write_text("final_stack: {}\ningress-nginx: {}\n") - - with _patch_cluster_client() as client: - result = CliRunner().invoke(update_cluster, ["7", str(components_file)]) - - assert result.exit_code != 0 - assert "unknown component(s) ingress-nginx" in result.output - client.update_cluster.assert_not_called() - - -@pytest.mark.parametrize("contents", ["istio: {}\n", "final_stack: [\n"]) -def test_update_reports_invalid_components_file_without_traceback(tmp_path, contents): +@pytest.mark.parametrize( + "contents, error", + [ + ("components:\n final_stack: {}\n ingress-nginx: {}\n", "unknown component(s) ingress-nginx"), + ("final_stack: {}\n", 'single "components" key'), + ("component:\n final_stack: {}\n", 'single "components" key'), + ("components:\n final_stack: {}\nextra: 1\n", 'single "components" key'), + ("components: []\n", '"components" must be a mapping'), + ("components:\n istio: {}\n", "final_stack"), + ("components: [\n", "not valid YAML or JSON"), + ], + ids=[ + "unknown-component", + "no-wrapper", + "misspelled-wrapper", + "extra-key", + "not-mapping", + "no-final-stack", + "bad-yaml", + ], +) +def test_update_cluster_rejects_invalid_request_file(tmp_path, contents, error): from centml.cli.cluster import update_cluster - components_file = tmp_path / "components.yaml" - components_file.write_text(contents) + request_file = tmp_path / "request.yaml" + request_file.write_text(contents) with _patch_cluster_client() as client: - result = CliRunner().invoke(update_cluster, ["7", str(components_file)]) + result = CliRunner().invoke(update_cluster, ["7", str(request_file)]) assert result.exit_code == 2 - assert "Invalid value for COMPONENTS_FILE" in result.output + assert "Invalid value for REQUEST_FILE" in result.output + assert error in result.output client.update_cluster.assert_not_called() From d29b9b63ab9b019e8e521e5e9a6a4b5954338fc4 Mon Sep 17 00:00:00 2001 From: Anand Jayarajan Date: Mon, 23 Nov 2026 16:01:29 -0500 Subject: [PATCH 10/11] [SDK/CLI] Address review: validate update requests in the SDK, dashed command names - CentMLClient.update_cluster takes the request body as a dict and rejects empty components (which would be uninstalled), unknown or non-string component names, and a missing or misspelled components key, before building the request with from_dict. The CLI and the example use it. - Rename the cluster commands to register-cluster, update-cluster, list-clusters and delete-cluster. - Accept --cloud-provider in any case; reword the delete prompt for clusters not managed by ccluster; use a PEM-shaped ca_cert in tests; note in the update example that it resets every component to its defaults. Co-Authored-By: Claude Opus 5.5 --- README.md | 16 +++++------ centml/cli/cluster.py | 50 +++++++++------------------------- centml/sdk/api.py | 41 ++++++++++++++++++++++++++-- examples/sdk/update_cluster.py | 9 +++--- tests/test_cli_cluster.py | 36 ++++++++++++++++++------ tests/test_sdk_api.py | 36 ++++++++++++++++++++---- 6 files changed, 123 insertions(+), 65 deletions(-) diff --git a/README.md b/README.md index f74e930..1882615 100644 --- a/README.md +++ b/README.md @@ -132,7 +132,7 @@ API server, as in a kubeconfig's `certificate-authority-data`. The bearer token prompted for, with hidden input, when `--bearer-token` is omitted: ```bash -ccluster register_cluster --name my-cluster --storage-class standard-rwo \ +ccluster register-cluster --name my-cluster --storage-class standard-rwo \ --server https:// --ca-cert \ --cloud-provider gcp --region us-east1 ``` @@ -140,13 +140,13 @@ ccluster register_cluster --name my-cluster --storage-class standard-rwo \ **List** the clusters you have access to, with their IDs: ```bash -ccluster list_clusters +ccluster list-clusters ``` **Update** the components installed on a registered cluster. The file is the `PUT /clusters/{id}` request body, in YAML or JSON: `components` maps each component to -its Helm chart values (`{}` for the defaults). `final_stack` is required, and components -left out of the file are uninstalled: +its Helm chart values (`{}` for the defaults). `final_stack` is required. Components left out +of the file are uninstalled, and an empty entry such as `istio:` is rejected: ```bash cat > components.yaml < components.yaml +ccluster update-cluster components.yaml ``` -**Delete** a cluster. This uninstalls its components; pass `--yes` to skip the -confirmation prompt: +**Delete** a cluster. For a cluster managed by ccluster, this also uninstalls the +components installed through it. Pass `--yes` to skip the confirmation prompt: ```bash -ccluster delete_cluster +ccluster delete-cluster ``` `examples/sdk/register_cluster.py`, `update_cluster.py`, `get_clusters.py` and diff --git a/centml/cli/cluster.py b/centml/cli/cluster.py index 93bf852..4c146c1 100644 --- a/centml/cli/cluster.py +++ b/centml/cli/cluster.py @@ -3,7 +3,6 @@ from typing import Dict import click import yaml -from pydantic import ValidationError from tabulate import tabulate from centml.sdk import ( DeploymentType, @@ -15,8 +14,6 @@ CloudProvider, ClusterCredential, ClusterRegistrationRequest, - ClusterBaseComponents, - UpdateClusterRequest, ) from centml.sdk.api import get_centml_client @@ -335,7 +332,7 @@ def capacity(cluster_id): ) -@click.command(name="register_cluster", help="Register your own Kubernetes cluster") +@click.command(help="Register your own Kubernetes cluster") @click.option("--name", "display_name", required=True, help="Display name for the cluster") @click.option("--storage-class", required=True, help="Storage class to use for deployments on the cluster") @click.option("--server", required=True, help="URL of the cluster's Kubernetes API server") @@ -354,7 +351,7 @@ def capacity(cluster_id): @click.option("--region", default=None, help="Region the cluster runs in") @click.option( "--cloud-provider", - type=click.Choice([p.value for p in CloudProvider if p != CloudProvider.UNKNOWN]), + type=click.Choice([p.value for p in CloudProvider if p != CloudProvider.UNKNOWN], case_sensitive=False), default=None, help="Cloud provider the cluster runs on", ) @@ -365,7 +362,7 @@ def register_cluster(display_name, storage_class, server, ca_cert, bearer_token, display_name=display_name, storage_class=storage_class, region=region, - cloud_provider=CloudProvider(cloud_provider) if cloud_provider else None, + cloud_provider=CloudProvider(cloud_provider.lower()) if cloud_provider else None, credential=ClusterCredential(server=server, bearer_token=bearer_token, ca_cert=ca_cert), ) with get_centml_client() as cclient: @@ -373,50 +370,29 @@ def register_cluster(display_name, storage_class, server, ca_cert, bearer_token, click.echo(f"Registered cluster {response.id}") -@click.command( - name="update_cluster", - help="""Set the components installed on a registered cluster. +@click.command(help="""Set the components installed on a registered cluster. REQUEST_FILE is the PUT /clusters/{id} request body, in YAML or JSON: a "components" mapping of component name to its Helm chart values ({} for the defaults). -final_stack is required. Components left out of the file are uninstalled from the cluster.""", -) +final_stack is required. Components left out of the file are uninstalled from the cluster.""") @click.argument("cluster_id", type=int) @click.argument("request_file", type=click.File("r")) @handle_exception def update_cluster(cluster_id, request_file): - def invalid(message): - return click.BadParameter(message, param_hint="REQUEST_FILE") - try: # YAML is a superset of JSON, so this reads both. body = yaml.safe_load(request_file) except yaml.YAMLError as e: - raise invalid(f"not valid YAML or JSON: {e}") from e - # The generated models silently drop unknown keys, so a misspelled key would go - # unnoticed, and a misspelled component would be uninstalled. - if not isinstance(body, dict) or set(body) != {"components"}: - raise invalid('must be a mapping with a single "components" key') - components = body["components"] - if not isinstance(components, dict): - raise invalid('"components" must be a mapping of component name to chart values') - unknown = sorted(set(components) - set(ClusterBaseComponents.model_fields)) - if unknown: - raise invalid( - f"unknown component(s) {', '.join(unknown)}; expected any of " - f"{', '.join(ClusterBaseComponents.model_fields)}" - ) - # from_dict, not the constructors: they drop chart keys the typed models don't list. - try: - request = UpdateClusterRequest.from_dict(body) - except ValidationError as e: - raise invalid(str(e)) from e + raise click.BadParameter(f"not valid YAML or JSON: {e}", param_hint="REQUEST_FILE") from e with get_centml_client() as cclient: - cclient.update_cluster(cluster_id, request) + try: + cclient.update_cluster(cluster_id, body) + except ValueError as e: + raise click.BadParameter(str(e), param_hint="REQUEST_FILE") from e click.echo(f"Updating components on cluster {cluster_id}") -@click.command(name="list_clusters", help="List the clusters you can deploy to") +@click.command(help="List the clusters you can deploy to") @handle_exception def list_clusters(): with get_centml_client() as cclient: @@ -426,9 +402,9 @@ def list_clusters(): click.echo(tabulate(rows, headers=["ID", "Name", "Region"], tablefmt="rounded_outline", disable_numparse=True)) -@click.command(name="delete_cluster", help="Delete a registered cluster and uninstall its components") +@click.command(help="Delete a registered cluster") @click.argument("cluster_id", type=int) -@click.confirmation_option(prompt="Delete this cluster and uninstall its components?") +@click.confirmation_option(prompt="Delete this cluster? Components installed through ccluster are uninstalled from it.") @handle_exception def delete_cluster(cluster_id): with get_centml_client() as cclient: diff --git a/centml/sdk/api.py b/centml/sdk/api.py index 8585ad5..330101c 100644 --- a/centml/sdk/api.py +++ b/centml/sdk/api.py @@ -17,11 +17,13 @@ CreateHardwareInstanceRequest, ClusterRegistrationRequest, UpdateClusterRequest, + ClusterBaseComponents, UpdateClusterMetadataRequest, ApiException, InviteUserRequest, Metric, ) +from pydantic import ValidationError from typing_extensions import deprecated from centml.sdk import auth @@ -48,6 +50,35 @@ LOG_RETRY_JITTER = 0.25 +def _build_update_cluster_request(body) -> UpdateClusterRequest: + """Validate a PUT /clusters/{id} body and build the request from it. + + The generated models silently drop keys they don't know and send None as null, which the + server reads as "not requested". A misspelled or empty component would be uninstalled + rather than rejected, so both are refused here. + """ + if not isinstance(body, dict) or set(body) != {"components"}: + raise ValueError('request must be a mapping with a single "components" key') + components = body["components"] + if not isinstance(components, dict): + raise ValueError('"components" must be a mapping of component name to chart values') + known = list(ClusterBaseComponents.model_fields) + unknown = sorted(str(name) for name in components if name not in known) + if unknown: + raise ValueError(f"unknown component(s) {', '.join(unknown)}; expected any of {', '.join(known)}") + empty = [name for name in known if name in components and components[name] is None] + if empty: + raise ValueError(f"component(s) {', '.join(empty)} have no values; use {{}} for the chart defaults") + # from_dict, not the constructors: they drop chart keys the typed models don't list. + try: + request = UpdateClusterRequest.from_dict(body) + except ValidationError as e: + raise ValueError(str(e)) from e + # from_dict returns None only for a None body, which the checks above rule out. + assert request is not None + return request + + def _with_busy_retry(fetch_page: Callable[[], list]) -> list: """Call fetch_page, retrying while the store reports itself busy. There is no server-issued cursor, so a page request is a pure function of its anchor and @@ -182,8 +213,14 @@ def get_clusters(self): def register_cluster(self, request: ClusterRegistrationRequest): return self._api.create_cluster_clusters_post(request) - def update_cluster(self, cluster_id: int, request: UpdateClusterRequest): - return self._api.update_cluster_clusters_cluster_id_put(cluster_id, request) + def update_cluster(self, cluster_id: int, request: dict): + """Set the components installed on a registered cluster. + + ``request`` is the PUT /clusters/{id} body: ``{"components": {name: chart values}}``, + with ``{}`` for a chart's defaults. final_stack is required, and a component left out + is uninstalled from the cluster. Raises ValueError for a malformed request. + """ + return self._api.update_cluster_clusters_cluster_id_put(cluster_id, _build_update_cluster_request(request)) def delete_cluster(self, cluster_id: int): return self._api.delete_cluster_clusters_cluster_id_delete(cluster_id) diff --git a/examples/sdk/update_cluster.py b/examples/sdk/update_cluster.py index 90e74f6..d055fe6 100644 --- a/examples/sdk/update_cluster.py +++ b/examples/sdk/update_cluster.py @@ -1,6 +1,9 @@ #!/usr/bin/env python3 """Install the platform components on a registered cluster. +This sets every component to its chart defaults, replacing any values set by an +earlier update, and uninstalls any component not listed in COMPONENTS. + Run `centml login` or configure service-account credentials first. Updating a cluster requires admin privileges (PERM_ADMIN_MANAGE_HARDWARE). @@ -12,7 +15,6 @@ import os -from centml.sdk import UpdateClusterRequest from centml.sdk.api import get_centml_client # Each component maps to its Helm chart values; {} installs it with the catalog defaults. @@ -37,11 +39,8 @@ def main() -> None: if not cluster_id: raise SystemExit("Set CLUSTER_ID before running this example.") - # Build the request with from_dict: the model constructors drop chart values - # their typed models don't list. - request = UpdateClusterRequest.from_dict({"components": COMPONENTS}) with get_centml_client() as client: - client.update_cluster(int(cluster_id), request) + client.update_cluster(int(cluster_id), {"components": COMPONENTS}) # The update returns without waiting for the components to roll out. print(f"Installing {len(COMPONENTS)} components on cluster {cluster_id}") diff --git a/tests/test_cli_cluster.py b/tests/test_cli_cluster.py index 0631ef9..203a510 100644 --- a/tests/test_cli_cluster.py +++ b/tests/test_cli_cluster.py @@ -245,11 +245,11 @@ def test_register_sends_registration_request_and_prints_cluster_id(): "--server", "https://k8s.example.com", "--ca-cert", - "Y2E=", + "LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSUIKLS0tLS1FTkQgQ0VSVElGSUNBVEUtLS0tLQo=", "--region", "us-east-1", "--cloud-provider", - "aws", + "AWS", ], input="secret-token\n", ) @@ -263,10 +263,26 @@ def test_register_sends_registration_request_and_prints_cluster_id(): assert request.region == "us-east-1" assert request.cloud_provider == CloudProvider.AWS assert request.credential.server == "https://k8s.example.com" - assert request.credential.ca_cert == "Y2E=" + assert ( + request.credential.ca_cert == "LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSUIKLS0tLS1FTkQgQ0VSVElGSUNBVEUtLS0tLQo=" + ) assert request.credential.bearer_token == "secret-token" +@contextmanager +def _patch_platform_api(): + """Patch the generated API under a real CentMLClient, so the SDK's validation runs.""" + from centml.sdk.api import CentMLClient + + api = MagicMock() + context = MagicMock() + context.__enter__.return_value = CentMLClient(api) + context.__exit__.return_value = False + + with patch("centml.cli.cluster.get_centml_client", return_value=context): + yield api + + @pytest.mark.parametrize( "contents", [ @@ -289,11 +305,11 @@ def test_update_cluster_sends_request_from_file_keeping_untyped_chart_keys(tmp_p request_file = tmp_path / "request" request_file.write_text(contents) - with _patch_cluster_client() as client: + with _patch_platform_api() as api: result = CliRunner().invoke(update_cluster, ["7", str(request_file)]) assert result.exit_code == 0, result.output - cluster_id, request = client.update_cluster.call_args.args + cluster_id, request = api.update_cluster_clusters_cluster_id_put.call_args.args assert cluster_id == 7 components = request.to_dict()["components"] assert components["final_stack"] == {} @@ -306,6 +322,8 @@ def test_update_cluster_sends_request_from_file_keeping_untyped_chart_keys(tmp_p "contents, error", [ ("components:\n final_stack: {}\n ingress-nginx: {}\n", "unknown component(s) ingress-nginx"), + ("components:\n final_stack: {}\n 1: x\n", "unknown component(s) 1"), + ("components:\n final_stack: {}\n istio:\n", "component(s) istio have no values; use {}"), ("final_stack: {}\n", 'single "components" key'), ("component:\n final_stack: {}\n", 'single "components" key'), ("components:\n final_stack: {}\nextra: 1\n", 'single "components" key'), @@ -315,6 +333,8 @@ def test_update_cluster_sends_request_from_file_keeping_untyped_chart_keys(tmp_p ], ids=[ "unknown-component", + "non-string-name", + "empty-component", "no-wrapper", "misspelled-wrapper", "extra-key", @@ -329,13 +349,13 @@ def test_update_cluster_rejects_invalid_request_file(tmp_path, contents, error): request_file = tmp_path / "request.yaml" request_file.write_text(contents) - with _patch_cluster_client() as client: + with _patch_platform_api() as api: result = CliRunner().invoke(update_cluster, ["7", str(request_file)]) - assert result.exit_code == 2 + assert result.exit_code == 2, result.output assert "Invalid value for REQUEST_FILE" in result.output assert error in result.output - client.update_cluster.assert_not_called() + api.update_cluster_clusters_cluster_id_put.assert_not_called() def test_list_clusters_shows_clusters_sorted_by_id(): diff --git a/tests/test_sdk_api.py b/tests/test_sdk_api.py index 81d8357..deb18da 100644 --- a/tests/test_sdk_api.py +++ b/tests/test_sdk_api.py @@ -203,7 +203,11 @@ def test_register_cluster_delegates_to_platform_client(): request = ClusterRegistrationRequest( display_name="my-cluster", storage_class="standard", - credential=ClusterCredential(server="https://k8s.example.com", bearer_token="token", ca_cert="Y2E="), + credential=ClusterCredential( + server="https://k8s.example.com", + bearer_token="token", + ca_cert="LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSUIKLS0tLS1FTkQgQ0VSVElGSUNBVEUtLS0tLQo=", + ), ) client = CentMLClient(api) @@ -213,14 +217,36 @@ def test_register_cluster_delegates_to_platform_client(): api.create_cluster_clusters_post.assert_called_once_with(request) -def test_update_cluster_delegates_to_platform_client(): +def test_update_cluster_builds_request_keeping_untyped_chart_keys(): + api = MagicMock() + client = CentMLClient(api) + + client.update_cluster(42, {"components": {"final_stack": {}, "keda": {"keda": {"untypedKey": 1}}}}) + + cluster_id, request = api.update_cluster_clusters_cluster_id_put.call_args.args + assert cluster_id == 42 + assert isinstance(request, UpdateClusterRequest) + assert request.to_dict()["components"]["keda"]["keda"]["untypedKey"] == 1 + + +@pytest.mark.parametrize( + "body", + [ + {"components": {"final_stack": {}, "istio": None}}, + {"components": {"final_stack": {}, "ingress-nginx": {}}}, + {"final_stack": {}}, + {"components": {"istio": {}}}, + ], + ids=["empty-component", "unknown-component", "no-wrapper", "no-final-stack"], +) +def test_update_cluster_rejects_malformed_request_without_calling_api(body): api = MagicMock() - request = UpdateClusterRequest.from_dict({"components": {"final_stack": {}}}) client = CentMLClient(api) - client.update_cluster(42, request) + with pytest.raises(ValueError): + client.update_cluster(42, body) - api.update_cluster_clusters_cluster_id_put.assert_called_once_with(42, request) + api.update_cluster_clusters_cluster_id_put.assert_not_called() def test_delete_cluster_delegates_to_platform_client(): From aeac105efc8e8e7e7a35bcf0e8a96c16c39c16b3 Mon Sep 17 00:00:00 2001 From: Anand Jayarajan Date: Mon, 23 Nov 2026 16:08:43 -0500 Subject: [PATCH 11/11] [SDK] Validate update requests with from_dict, keeping only the checks it can't do from_dict already rejects a missing or misspelled components key, a non-mapping body and a missing final_stack. Keep only the two mistakes it accepts and the server would read as an uninstall: an unknown component name and a component with no values. Co-Authored-By: Claude Opus 5.5 --- centml/sdk/api.py | 29 +++++++++++------------------ tests/test_cli_cluster.py | 10 +++++----- 2 files changed, 16 insertions(+), 23 deletions(-) diff --git a/centml/sdk/api.py b/centml/sdk/api.py index 330101c..c48924b 100644 --- a/centml/sdk/api.py +++ b/centml/sdk/api.py @@ -51,31 +51,24 @@ def _build_update_cluster_request(body) -> UpdateClusterRequest: - """Validate a PUT /clusters/{id} body and build the request from it. - - The generated models silently drop keys they don't know and send None as null, which the - server reads as "not requested". A misspelled or empty component would be uninstalled - rather than rejected, so both are refused here. - """ - if not isinstance(body, dict) or set(body) != {"components"}: - raise ValueError('request must be a mapping with a single "components" key') + """Build the request from a PUT /clusters/{id} body, raising ValueError if it is invalid.""" + # from_dict, not the constructors: they drop chart keys the typed models don't list. + try: + request = UpdateClusterRequest.from_dict(body) + except ValidationError as e: + raise ValueError(str(e)) from e + if request is None: + raise ValueError("request is empty") + # from_dict accepts two mistakes that the server reads as "not requested", uninstalling + # the component: a misspelled name, which it drops, and a name with no values, sent as null. components = body["components"] - if not isinstance(components, dict): - raise ValueError('"components" must be a mapping of component name to chart values') known = list(ClusterBaseComponents.model_fields) unknown = sorted(str(name) for name in components if name not in known) if unknown: raise ValueError(f"unknown component(s) {', '.join(unknown)}; expected any of {', '.join(known)}") - empty = [name for name in known if name in components and components[name] is None] + empty = [name for name, values in components.items() if values is None] if empty: raise ValueError(f"component(s) {', '.join(empty)} have no values; use {{}} for the chart defaults") - # from_dict, not the constructors: they drop chart keys the typed models don't list. - try: - request = UpdateClusterRequest.from_dict(body) - except ValidationError as e: - raise ValueError(str(e)) from e - # from_dict returns None only for a None body, which the checks above rule out. - assert request is not None return request diff --git a/tests/test_cli_cluster.py b/tests/test_cli_cluster.py index 203a510..3e9dd03 100644 --- a/tests/test_cli_cluster.py +++ b/tests/test_cli_cluster.py @@ -324,10 +324,10 @@ def test_update_cluster_sends_request_from_file_keeping_untyped_chart_keys(tmp_p ("components:\n final_stack: {}\n ingress-nginx: {}\n", "unknown component(s) ingress-nginx"), ("components:\n final_stack: {}\n 1: x\n", "unknown component(s) 1"), ("components:\n final_stack: {}\n istio:\n", "component(s) istio have no values; use {}"), - ("final_stack: {}\n", 'single "components" key'), - ("component:\n final_stack: {}\n", 'single "components" key'), - ("components:\n final_stack: {}\nextra: 1\n", 'single "components" key'), - ("components: []\n", '"components" must be a mapping'), + ("final_stack: {}\n", "components\n Input should be a valid dictionary"), + ("component:\n final_stack: {}\n", "components\n Input should be a valid dictionary"), + ("components: []\n", "Input should be a valid dictionary"), + ("", "request is empty"), ("components:\n istio: {}\n", "final_stack"), ("components: [\n", "not valid YAML or JSON"), ], @@ -337,8 +337,8 @@ def test_update_cluster_sends_request_from_file_keeping_untyped_chart_keys(tmp_p "empty-component", "no-wrapper", "misspelled-wrapper", - "extra-key", "not-mapping", + "empty-file", "no-final-stack", "bad-yaml", ],