|
| 1 | +import logging |
| 2 | +import os |
| 3 | +import os.path |
| 4 | +import time |
| 5 | + |
| 6 | +from jinja2 import Environment, StrictUndefined |
| 7 | +from kubernetes.client import ApiClient, ApiException |
| 8 | +import yaml |
| 9 | + |
| 10 | +from interface import KubernetesClusterPlugin |
| 11 | +import gardener_helper as _gh |
| 12 | + |
| 13 | +logger = logging.getLogger(__name__) |
| 14 | +logging.getLogger("kubernetes").setLevel(logging.INFO) |
| 15 | + |
| 16 | + |
| 17 | +TEMPLATE_KEYS = ('shoot', 'kubeconfig') |
| 18 | + |
| 19 | + |
| 20 | +class _ShootOps: |
| 21 | + def __init__(self, namespace: str, name: str): |
| 22 | + self.namespace = namespace |
| 23 | + self.name = name |
| 24 | + self.secret_name = f'{name}.kubeconfig' |
| 25 | + |
| 26 | + def _get_last_operation(self, co_api: _gh.CustomObjectsApi): |
| 27 | + try: |
| 28 | + status = _gh.get_shoot_status(co_api, self.namespace, self.name).get('status', {}) |
| 29 | + return status.get('lastOperation', {}) |
| 30 | + except ApiException as e: |
| 31 | + if e.status != 404: |
| 32 | + raise |
| 33 | + return None |
| 34 | + |
| 35 | + def create(self, co_api: _gh.CustomObjectsApi, shoot_dict): |
| 36 | + # Gardener shoot reconciliation is idempotent, so we can just try to create. |
| 37 | + # If it exists, we check its state. |
| 38 | + # repeat this because it's possible that a cluster object exists that is in state Delete |
| 39 | + while True: |
| 40 | + logger.debug(f"creating shoot object for {self.name}") |
| 41 | + try: |
| 42 | + _gh.create_shoot(co_api, self.namespace, shoot_dict) |
| 43 | + except ApiException as e: |
| 44 | + # 409 means that the object already exists |
| 45 | + if e.status != 409: |
| 46 | + raise |
| 47 | + # check state: if it's Processing or Succeeded, we are good |
| 48 | + last_op = self._get_last_operation(co_api) |
| 49 | + if last_op is None: |
| 50 | + logger.debug(f'cluster object for {self.name} was present, has disappeared, retry') |
| 51 | + continue |
| 52 | + state = last_op.get('state', 'Unknown') |
| 53 | + logger.debug(f"Shoot object for {self.name} already present in state {state}") |
| 54 | + if state in ('Succeeded', 'Processing'): |
| 55 | + break |
| 56 | + if state == 'Failed': |
| 57 | + raise RuntimeError(f"Shoot {self.name} is in Failed state. Please check the Gardener dashboard.") |
| 58 | + |
| 59 | + logger.debug(f'waiting 30 s for shoot {self.name} to proceed') |
| 60 | + time.sleep(30) |
| 61 | + else: |
| 62 | + break |
| 63 | + |
| 64 | + def delete(self, co_api: _gh.CustomObjectsApi): |
| 65 | + # Add deletion confirmation annotation to the shoot before deleting. |
| 66 | + # This is required by Gardener. |
| 67 | + try: |
| 68 | + _gh.annotate_shoot_confirm_deletion(co_api, self.namespace, self.name) |
| 69 | + _gh.delete_shoot(co_api, self.namespace, self.name) |
| 70 | + except ApiException as e: |
| 71 | + if e.status == 404: |
| 72 | + logger.debug(f"Shoot {self.name} not present") |
| 73 | + return |
| 74 | + raise |
| 75 | + |
| 76 | + logger.debug(f"Shoot {self.name} deletion requested; waiting 8 s for it to start deleting") |
| 77 | + time.sleep(8) |
| 78 | + while True: |
| 79 | + last_op = self._get_last_operation(co_api) |
| 80 | + if last_op is None: |
| 81 | + logger.info(f"Shoot {self.name} has been deleted.") |
| 82 | + break |
| 83 | + |
| 84 | + if last_op.get('type') != 'Delete': |
| 85 | + raise RuntimeError(f"Shoot {self.name} in unexpected state during deletion: {last_op!r}") |
| 86 | + state = last_op.get('state', 'Unknown') |
| 87 | + if state not in ('Processing', 'Succeeded'): |
| 88 | + raise RuntimeError(f"Shoot {self.name} in unexpected state during deletion: state={state}") |
| 89 | + |
| 90 | + if state == 'Processing': |
| 91 | + progress = last_op.get('progress', 0) |
| 92 | + logger.debug(f"Shoot {self.name} is being deleted (progress: {progress} %); waiting 30 s") |
| 93 | + elif state == 'Succeeded': |
| 94 | + logger.info(f"Shoot {self.name} deletion succeeded, but object still exists. Waiting 30 s for it to vanish.") |
| 95 | + time.sleep(30) |
| 96 | + |
| 97 | + def get_kubeconfig(self, core_api: _gh.CoreV1Api): |
| 98 | + return _gh.get_secret_data(core_api, self.namespace, self.secret_name) |
| 99 | + |
| 100 | + def wait_for_shoot_ready(self, co_api: _gh.CustomObjectsApi): |
| 101 | + last_op = self._get_last_operation(co_api) |
| 102 | + while last_op is not None and last_op.get('state') != 'Succeeded': |
| 103 | + state = last_op.get('state', 'Unknown') |
| 104 | + progress = last_op.get('progress', 0) |
| 105 | + logger.debug(f'waiting 30 s for shoot {self.name} to become ready (current state: {state}, progress: {progress}%)') |
| 106 | + time.sleep(30) |
| 107 | + last_op = self._get_last_operation(co_api) |
| 108 | + if last_op is None: |
| 109 | + raise RuntimeError(f"Shoot {self.name} object disappeared") |
| 110 | + logger.debug(f'shoot {self.name} appears to be ready') |
| 111 | + |
| 112 | + |
| 113 | +def load_templates(env, basepath, fn_map, keys=TEMPLATE_KEYS): |
| 114 | + new_map = {} |
| 115 | + for key in keys: |
| 116 | + fn = fn_map.get(key) |
| 117 | + if fn is None: |
| 118 | + new_map[key] = None |
| 119 | + continue |
| 120 | + with open(os.path.join(basepath, fn), "r") as fileobj: |
| 121 | + new_map[key] = env.from_string(fileobj.read()) |
| 122 | + missing = [key for k, v in new_map.items() if v is None] |
| 123 | + if missing: |
| 124 | + raise RuntimeError(f'missing templates: {", ".join(missing)}') |
| 125 | + return new_map |
| 126 | + |
| 127 | + |
| 128 | +class PluginGardener(KubernetesClusterPlugin): |
| 129 | + """ |
| 130 | + Plugin to handle the provisioning of Kubernetes clusters via Gardener |
| 131 | + to be used for conformance testing. |
| 132 | + """ |
| 133 | + def __init__(self, plugin_config, basepath='.', cwd='.', name=None): |
| 134 | + self.basepath = basepath |
| 135 | + self.cwd = cwd |
| 136 | + self.config = plugin_config |
| 137 | + self.env = Environment(undefined=StrictUndefined) |
| 138 | + self.template_map = load_templates(self.env, self.basepath, self.config['templates']) |
| 139 | + self.vars = self.config['vars'] |
| 140 | + self.vars['name'] = self.config['name'] |
| 141 | + self.secrets = self.config['secrets'] |
| 142 | + self.kubeconfig = yaml.load(self._render_template('kubeconfig'), Loader=yaml.SafeLoader) |
| 143 | + self.client_config = _gh.Configuration() |
| 144 | + _gh.setup_client_config(self.client_config, self.kubeconfig, cwd=self.cwd) |
| 145 | + self.namespace = self.kubeconfig['contexts'][0]['context']['namespace'] |
| 146 | + |
| 147 | + def _render_template(self, key): |
| 148 | + return self.template_map[key].render(**self.vars, **self.secrets) |
| 149 | + |
| 150 | + def _write_shoot_yaml(self, shoot_yaml): |
| 151 | + # write out shoot.yaml for purposes of documentation |
| 152 | + # we will however use the dict instead of calling the shell with `kubectl apply -f` |
| 153 | + shoot_yaml_path = os.path.join(self.cwd, 'shoot.yaml') |
| 154 | + logger.debug(f'writing out {shoot_yaml_path}') |
| 155 | + with open(shoot_yaml_path, "w") as fileobj: |
| 156 | + fileobj.write(shoot_yaml) |
| 157 | + |
| 158 | + def _write_kubeconfig(self, kubeconfig): |
| 159 | + # write out kubeconfig.yaml |
| 160 | + kubeconfig_path = os.path.join(self.cwd, 'kubeconfig.yaml') |
| 161 | + logger.debug(f'writing out {kubeconfig_path}') |
| 162 | + with open(kubeconfig_path, 'wb') as fileobj: |
| 163 | + fileobj.write(kubeconfig) |
| 164 | + |
| 165 | + def create_cluster(self): |
| 166 | + with ApiClient(self.client_config) as api_client: |
| 167 | + core_api = _gh.CoreV1Api(api_client) |
| 168 | + co_api = _gh.CustomObjectsApi(api_client) |
| 169 | + shoot_yaml = self._render_template('shoot') |
| 170 | + shoot_dict = yaml.load(shoot_yaml, Loader=yaml.SafeLoader) |
| 171 | + self._write_shoot_yaml(shoot_yaml) |
| 172 | + sops = _ShootOps(self.namespace, self.config['name']) |
| 173 | + sops.create(co_api=co_api, shoot_dict=shoot_dict) |
| 174 | + sops.wait_for_shoot_ready(co_api) |
| 175 | + self._write_kubeconfig(cops.get_kubeconfig(core_api)) |
| 176 | + |
| 177 | + def delete_cluster(self): |
| 178 | + with ApiClient(self.client_config) as api_client: |
| 179 | + co_api = _gh.CustomObjectsApi(api_client) |
| 180 | + _ShootOps(self.namespace, self.config['name']).delete(co_api) |
0 commit comments