Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
59 changes: 59 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -116,6 +116,65 @@ source scripts/completions/completion.<shell language>
Shell language can be: bash, zsh, fish
(Hint: add `source /path/to/completions/completion.<shell language>` 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 <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://<api-server> --ca-cert <base64-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 <<EOF
components:
kube_prometheus_stack: {}
istio: {}
cert_manager: {}
ingress_nginx: {}
keda: {}
argo_rollouts: {}
gpu_operator: {}
kai_scheduler: {}
metrics_server: {}
final_stack: {}
EOF
ccluster update-cluster <cluster-id> 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 <cluster-id>
```

`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
Expand Down
84 changes: 84 additions & 0 deletions centml/cli/cluster.py
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand All @@ -10,6 +11,9 @@
RolloutStatus,
ApiException,
HardwareInstanceResponse,
CloudProvider,
ClusterCredential,
ClusterRegistrationRequest,
)
from centml.sdk.api import get_centml_client

Expand Down Expand Up @@ -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}")
17 changes: 16 additions & 1 deletion centml/cli/main.py
Original file line number Diff line number Diff line change
@@ -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)
Expand Down Expand Up @@ -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")

Expand Down
41 changes: 41 additions & 0 deletions centml/sdk/api.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand All @@ -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
Expand Down Expand Up @@ -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)

Expand Down
30 changes: 30 additions & 0 deletions examples/sdk/delete_cluster.py
Original file line number Diff line number Diff line change
@@ -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="<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()
49 changes: 49 additions & 0 deletions examples/sdk/register_cluster.py
Original file line number Diff line number Diff line change
@@ -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://<api-server>"
export CLUSTER_BEARER_TOKEN="<service-account-token>"
export CLUSTER_CA_CERT="<base64 PEM CA certificate>"
export CLUSTER_STORAGE_CLASS="<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()
49 changes: 49 additions & 0 deletions examples/sdk/update_cluster.py
Original file line number Diff line number Diff line change
@@ -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="<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()
Loading
Loading