diff --git a/README.md b/README.md index 063a4bb..1882615 100644 --- a/README.md +++ b/README.md @@ -116,6 +116,65 @@ 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 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. Components left out +of the file are uninstalled, and an empty entry such as `istio:` is rejected: + +```bash +cat > components.yaml < components.yaml +``` + +**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 +``` + +`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 diff --git a/centml/cli/cluster.py b/centml/cli/cluster.py index 52145f0..4c146c1 100644 --- a/centml/cli/cluster.py +++ b/centml/cli/cluster.py @@ -2,6 +2,7 @@ from functools import wraps from typing import Dict import click +import yaml from tabulate import tabulate from centml.sdk import ( DeploymentType, @@ -10,6 +11,9 @@ RolloutStatus, ApiException, HardwareInstanceResponse, + CloudProvider, + ClusterCredential, + ClusterRegistrationRequest, ) from centml.sdk.api import get_centml_client @@ -326,3 +330,83 @@ 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], case_sensitive=False), + default=None, + help="Cloud provider the cluster runs on", +) +@handle_exception +# pylint: disable=R0917 +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, + region=region, + 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: + response = cclient.register_cluster(request) + click.echo(f"Registered cluster {response.id}") + + +@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.""") +@click.argument("cluster_id", type=int) +@click.argument("request_file", type=click.File("r")) +@handle_exception +def update_cluster(cluster_id, 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 click.BadParameter(f"not valid YAML or JSON: {e}", param_hint="REQUEST_FILE") from e + with get_centml_client() as cclient: + 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(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(help="Delete a registered cluster") +@click.argument("cluster_id", type=int) +@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: + 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 504ea4f..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 +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) @@ -46,6 +57,10 @@ def ccluster(): ccluster.add_command(pause) ccluster.add_command(resume) 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 b4a4af2..c48924b 100644 --- a/centml/sdk/api.py +++ b/centml/sdk/api.py @@ -15,11 +15,15 @@ CreateDynamoDeploymentRequest, CreateJobDeploymentRequest, CreateHardwareInstanceRequest, + ClusterRegistrationRequest, + UpdateClusterRequest, + ClusterBaseComponents, UpdateClusterMetadataRequest, ApiException, InviteUserRequest, Metric, ) +from pydantic import ValidationError from typing_extensions import deprecated from centml.sdk import auth @@ -46,6 +50,28 @@ LOG_RETRY_JITTER = 0.25 +def _build_update_cluster_request(body) -> UpdateClusterRequest: + """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"] + 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, 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") + 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 @@ -177,6 +203,21 @@ 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(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) + 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/examples/sdk/register_cluster.py b/examples/sdk/register_cluster.py new file mode 100644 index 0000000..e3e250c --- /dev/null +++ b/examples/sdk/register_cluster.py @@ -0,0 +1,49 @@ +#!/usr/bin/env python3 +"""Register your own Kubernetes cluster. + +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`: + + export CLUSTER_SERVER="https://" + export CLUSTER_BEARER_TOKEN="" + export CLUSTER_CA_CERT="" + export CLUSTER_STORAGE_CLASS="" + python examples/sdk/register_cluster.py + +Then install the cluster's components with examples/sdk/update_cluster.py. +""" + +import os + +from centml.sdk import ClusterCredential, ClusterRegistrationRequest +from centml.sdk.api import get_centml_client + + +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 main() -> None: + 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"), + ), + ) + with get_centml_client() as client: + cluster_id = client.register_cluster(request).id + print(f"Registered cluster {cluster_id}") + + +if __name__ == "__main__": + main() diff --git a/examples/sdk/update_cluster.py b/examples/sdk/update_cluster.py new file mode 100644 index 0000000..d055fe6 --- /dev/null +++ b/examples/sdk/update_cluster.py @@ -0,0 +1,49 @@ +#!/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). + + export CLUSTER_ID="" + python examples/sdk/update_cluster.py + +Register the cluster first with examples/sdk/register_cluster.py. +""" + +import os + +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.") + + with get_centml_client() as client: + 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}") + + +if __name__ == "__main__": + main() 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 998fbe3..3e9dd03 100644 --- a/tests/test_cli_cluster.py +++ b/tests/test_cli_cluster.py @@ -226,3 +226,182 @@ 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_cluster + from centml.sdk import CloudProvider + + with _patch_cluster_client() as client: + client.register_cluster.return_value = SimpleNamespace(id=7) + + result = CliRunner().invoke( + register_cluster, + [ + "--name", + "my-cluster", + "--storage-class", + "standard", + "--server", + "https://k8s.example.com", + "--ca-cert", + "LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSUIKLS0tLS1FTkQgQ0VSVElGSUNBVEUtLS0tLQo=", + "--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 == "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", + [ + "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 + + request_file = tmp_path / "request" + request_file.write_text(contents) + + 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 = api.update_cluster_clusters_cluster_id_put.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 + + +@pytest.mark.parametrize( + "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", "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"), + ], + ids=[ + "unknown-component", + "non-string-name", + "empty-component", + "no-wrapper", + "misspelled-wrapper", + "not-mapping", + "empty-file", + "no-final-stack", + "bad-yaml", + ], +) +def test_update_cluster_rejects_invalid_request_file(tmp_path, contents, error): + from centml.cli.cluster import update_cluster + + request_file = tmp_path / "request.yaml" + request_file.write_text(contents) + + with _patch_platform_api() as api: + result = CliRunner().invoke(update_cluster, ["7", str(request_file)]) + + assert result.exit_code == 2, result.output + assert "Invalid value for REQUEST_FILE" in result.output + assert error in result.output + api.update_cluster_clusters_cluster_id_put.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 11d8ae1..deb18da 100644 --- a/tests/test_sdk_api.py +++ b/tests/test_sdk_api.py @@ -6,6 +6,9 @@ import platform_api_python_client from platform_api_python_client import ( + ClusterCredential, + ClusterRegistrationRequest, + UpdateClusterRequest, CreateDynamoDeploymentRequest, CreateHardwareInstanceRequest, CreateJobDeploymentRequest, @@ -193,6 +196,68 @@ 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="LS0tLS1CRUdJTiBDRVJUSUZJQ0FURS0tLS0tCk1JSUIKLS0tLS1FTkQgQ0VSVElGSUNBVEUtLS0tLQo=", + ), + ) + 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_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() + client = CentMLClient(api) + + with pytest.raises(ValueError): + client.update_cluster(42, body) + + api.update_cluster_clusters_cluster_id_put.assert_not_called() + + +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)]