|
| 1 | +import base64 |
| 2 | +import logging |
| 3 | +import os |
| 4 | +import os.path |
| 5 | +import time |
| 6 | +from typing import Any, cast |
| 7 | + |
| 8 | +from jinja2 import Environment, Template |
| 9 | +from kubernetes.client import ApiClient, ApiException, Configuration, CoreV1Api, CustomObjectsApi, V1Secret |
| 10 | +import yaml |
| 11 | + |
| 12 | +from interface import KubernetesClusterPlugin |
| 13 | +import k8s_helper |
| 14 | + |
| 15 | +logger = logging.getLogger(__name__) |
| 16 | +logging.getLogger("kubernetes").setLevel(logging.INFO) |
| 17 | + |
| 18 | + |
| 19 | +TIMEOUTS = [30] * 60 + [0] # wait at most 30 minutes; sentinel value at the end |
| 20 | + |
| 21 | +HR_GROUP = "helm.toolkit.fluxcd.io" |
| 22 | +HR_VERSION = "v2" |
| 23 | +HR_PLURAL = "helmreleases" |
| 24 | + |
| 25 | +# All of these are mandated by the ValidatingAdmissionPolicy on the management cluster |
| 26 | +# and cannot be changed without updating both the VAP and the RBAC. |
| 27 | +HR_NAME = "scs-kaas-certification" |
| 28 | +HR_NAMESPACE = "scs-kaas-certification" |
| 29 | +HR_KUBECONFIG_SECRET = "scs-kaas-certification-kubeconfig" |
| 30 | +HR_CHART_REF = { |
| 31 | + "kind": "HelmChart", |
| 32 | + "name": "scs-kaas-certification", |
| 33 | + "namespace": "flux-system", |
| 34 | +} |
| 35 | +HR_VALUES_FIXED = { |
| 36 | + "cloud": "bfe2-prod", |
| 37 | + "controlPlane": {"hosted": True}, |
| 38 | + "metadata": { |
| 39 | + "customerID": 1111, |
| 40 | + "customerName": "teuto.net Netzdienste GmbH", |
| 41 | + "friendlyName": "scs-kaas-certification", |
| 42 | + "serviceLevelAgreement": "None", |
| 43 | + }, |
| 44 | + "nodePools": { |
| 45 | + "pool-0": {"flavor": "standard.2.1905", "replicas": 2}, |
| 46 | + }, |
| 47 | +} |
| 48 | + |
| 49 | + |
| 50 | +class PluginT8s(KubernetesClusterPlugin): |
| 51 | + """ |
| 52 | + Plugin to provision Kubernetes clusters on the t8s (teuto k8s) management cluster |
| 53 | + via a Flux HelmRelease. |
| 54 | +
|
| 55 | + Creates a HelmRelease on mgmt-bfe2-prod and waits for the resulting cluster's |
| 56 | + kubeconfig to appear in the secret scs-kaas-certification-kubeconfig. |
| 57 | +
|
| 58 | + Expected config keys: |
| 59 | + kubernetesVersion: '1.35' (major.minor) |
| 60 | + version_patch: 2 (patch component of the k8s version) |
| 61 | + templates: |
| 62 | + kubeconfig: t8s-kubeconfig.yaml (management cluster kubeconfig template) |
| 63 | + secrets: |
| 64 | + token: '{{ clouds_conf.teuto_mgmt_token }}' |
| 65 | + """ |
| 66 | + |
| 67 | + def __init__(self, config: dict[str, Any], basepath: str = ".", cwd: str = ".") -> None: |
| 68 | + self.basepath = basepath |
| 69 | + self.cwd = cwd |
| 70 | + self.env = Environment() |
| 71 | + |
| 72 | + fn: str = config["templates"]["kubeconfig"] |
| 73 | + with open(os.path.join(basepath, fn), "r") as f: |
| 74 | + self.kubeconfig_template: Template = self.env.from_string(f.read()) |
| 75 | + self.secrets: dict[str, Any] = config.get("secrets", {}) |
| 76 | + |
| 77 | + major, minor = (int(x) for x in config["kubernetesVersion"].split(".")) |
| 78 | + self.k8s_version: dict[str, int] = { |
| 79 | + "major": major, |
| 80 | + "minor": minor, |
| 81 | + "patch": int(config.get("version_patch", 0)), |
| 82 | + } |
| 83 | + |
| 84 | + kubeconfig = cast(dict[str, Any], yaml.load( |
| 85 | + self.kubeconfig_template.render(**self.secrets), Loader=yaml.SafeLoader |
| 86 | + )) |
| 87 | + self.client_config: Configuration = Configuration() |
| 88 | + k8s_helper.setup_client_config(self.client_config, kubeconfig, cwd=self.cwd) |
| 89 | + |
| 90 | + def _build_helmrelease(self) -> dict[str, Any]: |
| 91 | + return { |
| 92 | + "apiVersion": f"{HR_GROUP}/{HR_VERSION}", |
| 93 | + "kind": "HelmRelease", |
| 94 | + "metadata": {"name": HR_NAME, "namespace": HR_NAMESPACE}, |
| 95 | + "spec": { |
| 96 | + "chartRef": HR_CHART_REF, |
| 97 | + "driftDetection": {"mode": "enabled"}, |
| 98 | + "interval": "1m", |
| 99 | + "values": {**HR_VALUES_FIXED, "version": self.k8s_version}, |
| 100 | + }, |
| 101 | + } |
| 102 | + |
| 103 | + def _delete_helmrelease(self, co_api: CustomObjectsApi) -> None: |
| 104 | + try: |
| 105 | + co_api.delete_namespaced_custom_object( |
| 106 | + HR_GROUP, |
| 107 | + HR_VERSION, |
| 108 | + HR_NAMESPACE, |
| 109 | + HR_PLURAL, |
| 110 | + HR_NAME, |
| 111 | + ) |
| 112 | + except ApiException as e: |
| 113 | + if e.status == 404: |
| 114 | + logger.debug(f"HelmRelease {HR_NAME} not present, nothing to delete") |
| 115 | + return |
| 116 | + raise |
| 117 | + # Give Flux time to begin deletion before we try to recreate |
| 118 | + logger.debug(f"HelmRelease {HR_NAME} deletion requested; waiting 30s") |
| 119 | + time.sleep(30) |
| 120 | + |
| 121 | + def _apply_helmrelease(self, api_client: ApiClient) -> None: |
| 122 | + """Server-side apply the HelmRelease (creates or updates). |
| 123 | +
|
| 124 | + Uses PATCH with application/apply-patch+yaml so the resource name is |
| 125 | + part of the URL — meaning resourceNames RBAC constraints are evaluated |
| 126 | + correctly, unlike POST (create) where the name is only in the body. |
| 127 | + """ |
| 128 | + hr = self._build_helmrelease() |
| 129 | + api_client.call_api( |
| 130 | + '/apis/{group}/{version}/namespaces/{namespace}/{plural}/{name}', |
| 131 | + 'PATCH', |
| 132 | + path_params={ |
| 133 | + 'group': HR_GROUP, |
| 134 | + 'version': HR_VERSION, |
| 135 | + 'namespace': HR_NAMESPACE, |
| 136 | + 'plural': HR_PLURAL, |
| 137 | + 'name': HR_NAME, |
| 138 | + }, |
| 139 | + query_params=[('fieldManager', 'plugin_t8s'), ('force', 'true')], |
| 140 | + header_params={ |
| 141 | + 'Accept': 'application/json', |
| 142 | + 'Content-Type': 'application/apply-patch+yaml', |
| 143 | + }, |
| 144 | + body=hr, |
| 145 | + post_params=[], |
| 146 | + files={}, |
| 147 | + response_type='object', |
| 148 | + auth_settings=['BearerToken'], |
| 149 | + _return_http_data_only=True, |
| 150 | + ) |
| 151 | + logger.debug(f"HelmRelease {HR_NAME} applied") |
| 152 | + |
| 153 | + def _get_kubeconfig_from_secret(self, core_api: CoreV1Api) -> bytes: |
| 154 | + secret = cast(V1Secret, core_api.read_namespaced_secret(HR_KUBECONFIG_SECRET, HR_NAMESPACE)) |
| 155 | + data: dict[str, str] = secret.data or {} |
| 156 | + if "value" in data: |
| 157 | + return base64.standard_b64decode(data["value"].encode()) |
| 158 | + raise RuntimeError( |
| 159 | + f"kubeconfig secret {HR_KUBECONFIG_SECRET} is missing key 'value'; has keys: {list(data)}" |
| 160 | + ) |
| 161 | + |
| 162 | + def _wait_for_kubeconfig_secret(self, core_api: CoreV1Api) -> bytes: |
| 163 | + timeouts = iter(TIMEOUTS) |
| 164 | + while True: |
| 165 | + try: |
| 166 | + return self._get_kubeconfig_from_secret(core_api) |
| 167 | + except ApiException as e: |
| 168 | + if e.status != 404: |
| 169 | + raise |
| 170 | + timeout = next(timeouts) |
| 171 | + if not timeout: |
| 172 | + raise RuntimeError( |
| 173 | + f"Timeout waiting for kubeconfig secret {HR_KUBECONFIG_SECRET}" |
| 174 | + ) |
| 175 | + logger.debug( |
| 176 | + f"waiting {timeout}s for kubeconfig secret {HR_KUBECONFIG_SECRET}" |
| 177 | + ) |
| 178 | + time.sleep(timeout) |
| 179 | + |
| 180 | + def _write_kubeconfig(self, data: bytes) -> None: |
| 181 | + path = os.path.join(self.cwd, "kubeconfig.yaml") |
| 182 | + logger.debug(f"writing {path}") |
| 183 | + with open(path, "wb") as f: |
| 184 | + f.write(data) |
| 185 | + |
| 186 | + def create_cluster(self) -> None: |
| 187 | + with ApiClient(self.client_config) as api_client: |
| 188 | + core_api = CoreV1Api(api_client) |
| 189 | + self._apply_helmrelease(api_client) |
| 190 | + kubeconfig = self._wait_for_kubeconfig_secret(core_api) |
| 191 | + self._write_kubeconfig(kubeconfig) |
| 192 | + |
| 193 | + def delete_cluster(self) -> None: |
| 194 | + with ApiClient(self.client_config) as api_client: |
| 195 | + co_api = CustomObjectsApi(api_client) |
| 196 | + self._delete_helmrelease(co_api) |
0 commit comments