Alex | 9a4ad21 | 2020-10-01 18:04:25 -0500 | [diff] [blame] | 1 | """ |
| 2 | Module to handle interaction with Kube |
| 3 | """ |
| 4 | import base64 |
| 5 | import os |
| 6 | import urllib3 |
| 7 | import yaml |
| 8 | |
Alex | 5cace3b | 2021-11-10 16:40:37 -0600 | [diff] [blame] | 9 | from kubernetes import client as kclient, config as kconfig, watch |
Alex | 9a4ad21 | 2020-10-01 18:04:25 -0500 | [diff] [blame] | 10 | from kubernetes.stream import stream |
Alex | 7b0ee9a | 2021-09-21 17:16:17 -0500 | [diff] [blame] | 11 | from kubernetes.client.rest import ApiException |
Alex | 5cace3b | 2021-11-10 16:40:37 -0600 | [diff] [blame] | 12 | from time import time, sleep |
Alex | 9a4ad21 | 2020-10-01 18:04:25 -0500 | [diff] [blame] | 13 | |
| 14 | from cfg_checker.common import logger, logger_cli |
Alex | 7b0ee9a | 2021-09-21 17:16:17 -0500 | [diff] [blame] | 15 | from cfg_checker.common.decorators import retry |
Alex | 5cace3b | 2021-11-10 16:40:37 -0600 | [diff] [blame] | 16 | from cfg_checker.common.exception import CheckerException, \ |
| 17 | InvalidReturnException, KubeException |
Alex | 9a4ad21 | 2020-10-01 18:04:25 -0500 | [diff] [blame] | 18 | from cfg_checker.common.file_utils import create_temp_file_with_content |
| 19 | from cfg_checker.common.other import utils, shell |
| 20 | from cfg_checker.common.ssh_utils import ssh_shell_p |
Alex | 359e575 | 2021-08-16 17:28:30 -0500 | [diff] [blame] | 21 | from cfg_checker.common.const import ENV_LOCAL |
Alex | 9a4ad21 | 2020-10-01 18:04:25 -0500 | [diff] [blame] | 22 | |
Alex | 7b0ee9a | 2021-09-21 17:16:17 -0500 | [diff] [blame] | 23 | |
Alex | 9a4ad21 | 2020-10-01 18:04:25 -0500 | [diff] [blame] | 24 | urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning) |
| 25 | |
| 26 | |
| 27 | def _init_kube_conf_local(config): |
| 28 | # Init kube library locally |
Alex | 359e575 | 2021-08-16 17:28:30 -0500 | [diff] [blame] | 29 | _path = "local:{}".format(config.kube_config_path) |
Alex | 9a4ad21 | 2020-10-01 18:04:25 -0500 | [diff] [blame] | 30 | try: |
Alex | c4f5962 | 2021-08-27 13:42:00 -0500 | [diff] [blame] | 31 | kconfig.load_kube_config(config_file=config.kube_config_path) |
Alex | 3374781 | 2021-04-07 10:11:39 -0500 | [diff] [blame] | 32 | if config.insecure: |
| 33 | kconfig.assert_hostname = False |
| 34 | kconfig.client_side_validation = False |
Alex | 9a4ad21 | 2020-10-01 18:04:25 -0500 | [diff] [blame] | 35 | logger_cli.debug( |
Alex | c4f5962 | 2021-08-27 13:42:00 -0500 | [diff] [blame] | 36 | "... found Kube env: core, {}". format( |
Alex | 9a4ad21 | 2020-10-01 18:04:25 -0500 | [diff] [blame] | 37 | ",".join( |
| 38 | kclient.CoreApi().get_api_versions().versions |
| 39 | ) |
| 40 | ) |
| 41 | ) |
Alex | c4f5962 | 2021-08-27 13:42:00 -0500 | [diff] [blame] | 42 | return kconfig, kclient.ApiClient(), _path |
Alex | 9a4ad21 | 2020-10-01 18:04:25 -0500 | [diff] [blame] | 43 | except Exception as e: |
| 44 | logger.warn("Failed to init local Kube client: {}".format( |
| 45 | str(e) |
| 46 | ) |
| 47 | ) |
Alex | 359e575 | 2021-08-16 17:28:30 -0500 | [diff] [blame] | 48 | return None, None, _path |
Alex | 9a4ad21 | 2020-10-01 18:04:25 -0500 | [diff] [blame] | 49 | |
| 50 | |
| 51 | def _init_kube_conf_remote(config): |
| 52 | # init remote client |
| 53 | # Preload Kube token |
| 54 | """ |
| 55 | APISERVER=$(kubectl config view --minify | |
| 56 | grep server | cut -f 2- -d ":" | tr -d " ") |
| 57 | SECRET_NAME=$(kubectl get secrets | |
| 58 | grep ^default | cut -f1 -d ' ') |
| 59 | TOKEN=$(kubectl describe secret $SECRET_NAME | |
| 60 | grep -E '^token' | cut -f2 -d':' | tr -d " ") |
| 61 | |
| 62 | echo "Detected API Server at: '${APISERVER}'" |
| 63 | echo "Got secret: '${SECRET_NAME}'" |
| 64 | echo "Loaded token: '${TOKEN}'" |
| 65 | |
| 66 | curl $APISERVER/api |
| 67 | --header "Authorization: Bearer $TOKEN" --insecure |
| 68 | """ |
| 69 | import yaml |
Alex | 359e575 | 2021-08-16 17:28:30 -0500 | [diff] [blame] | 70 | _path = '' |
Alex | c4f5962 | 2021-08-27 13:42:00 -0500 | [diff] [blame] | 71 | # Try to load remote config only if it was not detected already |
| 72 | if not config.kube_config_detected and not config.env_name == ENV_LOCAL: |
Alex | 359e575 | 2021-08-16 17:28:30 -0500 | [diff] [blame] | 73 | _path = "{}@{}:{}".format( |
| 74 | config.ssh_user, |
| 75 | config.ssh_host, |
| 76 | config.kube_config_path |
| 77 | ) |
Alex | 9d91353 | 2021-03-24 18:01:45 -0500 | [diff] [blame] | 78 | _c_data = ssh_shell_p( |
Alex | c4f5962 | 2021-08-27 13:42:00 -0500 | [diff] [blame] | 79 | "cat " + config.kube_config_path, |
Alex | 9d91353 | 2021-03-24 18:01:45 -0500 | [diff] [blame] | 80 | config.ssh_host, |
| 81 | username=config.ssh_user, |
| 82 | keypath=config.ssh_key, |
| 83 | piped=False, |
| 84 | use_sudo=config.ssh_uses_sudo, |
| 85 | ) |
| 86 | else: |
Alex | 359e575 | 2021-08-16 17:28:30 -0500 | [diff] [blame] | 87 | _path = "local:{}".format(config.kube_config_path) |
Alex | 9d91353 | 2021-03-24 18:01:45 -0500 | [diff] [blame] | 88 | with open(config.kube_config_path, 'r') as ff: |
| 89 | _c_data = ff.read() |
Alex | 9a4ad21 | 2020-10-01 18:04:25 -0500 | [diff] [blame] | 90 | |
Alex | 359e575 | 2021-08-16 17:28:30 -0500 | [diff] [blame] | 91 | if len(_c_data) < 1: |
| 92 | return None, None, _path |
| 93 | |
Alex | 9a4ad21 | 2020-10-01 18:04:25 -0500 | [diff] [blame] | 94 | _conf = yaml.load(_c_data, Loader=yaml.SafeLoader) |
| 95 | |
| 96 | _kube_conf = kclient.Configuration() |
| 97 | # A remote host configuration |
| 98 | |
| 99 | # To work with remote cluster, we need to extract these |
| 100 | # keys = ['host', 'ssl_ca_cert', 'cert_file', 'key_file', 'verify_ssl'] |
| 101 | # When v12 of the client will be release, we will use load_from_dict |
| 102 | |
| 103 | _kube_conf.ssl_ca_cert = create_temp_file_with_content( |
| 104 | base64.standard_b64decode( |
| 105 | _conf['clusters'][0]['cluster']['certificate-authority-data'] |
| 106 | ) |
| 107 | ) |
| 108 | _host = _conf['clusters'][0]['cluster']['server'] |
| 109 | _kube_conf.cert_file = create_temp_file_with_content( |
| 110 | base64.standard_b64decode( |
| 111 | _conf['users'][0]['user']['client-certificate-data'] |
| 112 | ) |
| 113 | ) |
| 114 | _kube_conf.key_file = create_temp_file_with_content( |
| 115 | base64.standard_b64decode( |
| 116 | _conf['users'][0]['user']['client-key-data'] |
| 117 | ) |
| 118 | ) |
| 119 | if "http" not in _host or "443" not in _host: |
| 120 | logger_cli.error( |
| 121 | "Failed to extract Kube host: '{}'".format(_host) |
| 122 | ) |
| 123 | else: |
| 124 | logger_cli.debug( |
Alex | c4f5962 | 2021-08-27 13:42:00 -0500 | [diff] [blame] | 125 | "... 'context' host extracted: '{}' via SSH@{}".format( |
Alex | 9a4ad21 | 2020-10-01 18:04:25 -0500 | [diff] [blame] | 126 | _host, |
| 127 | config.ssh_host |
| 128 | ) |
| 129 | ) |
| 130 | |
| 131 | # Substitute context host to ours |
| 132 | _tmp = _host.split(':') |
| 133 | _kube_conf.host = \ |
| 134 | _tmp[0] + "://" + config.mcp_host + ":" + _tmp[2] |
| 135 | config.kube_port = _tmp[2] |
| 136 | logger_cli.debug( |
Alex | c4f5962 | 2021-08-27 13:42:00 -0500 | [diff] [blame] | 137 | "... kube remote host updated to {}".format( |
Alex | 9a4ad21 | 2020-10-01 18:04:25 -0500 | [diff] [blame] | 138 | _kube_conf.host |
| 139 | ) |
| 140 | ) |
| 141 | _kube_conf.verify_ssl = False |
| 142 | _kube_conf.debug = config.debug |
Alex | 3374781 | 2021-04-07 10:11:39 -0500 | [diff] [blame] | 143 | if config.insecure: |
| 144 | _kube_conf.assert_hostname = False |
| 145 | _kube_conf.client_side_validation = False |
| 146 | |
Alex | 9a4ad21 | 2020-10-01 18:04:25 -0500 | [diff] [blame] | 147 | # Nevertheless if you want to do it |
| 148 | # you can with these 2 parameters |
| 149 | # configuration.verify_ssl=True |
| 150 | # ssl_ca_cert is the filepath |
| 151 | # to the file that contains the certificate. |
| 152 | # configuration.ssl_ca_cert="certificate" |
| 153 | |
| 154 | # _kube_conf.api_key = { |
| 155 | # "authorization": "Bearer " + config.kube_token |
| 156 | # } |
| 157 | |
| 158 | # Create a ApiClient with our config |
| 159 | _kube_api = kclient.ApiClient(_kube_conf) |
| 160 | |
Alex | 359e575 | 2021-08-16 17:28:30 -0500 | [diff] [blame] | 161 | return _kube_conf, _kube_api, _path |
Alex | 9a4ad21 | 2020-10-01 18:04:25 -0500 | [diff] [blame] | 162 | |
| 163 | |
| 164 | class KubeApi(object): |
| 165 | def __init__(self, config): |
| 166 | self.config = config |
Alex | 359e575 | 2021-08-16 17:28:30 -0500 | [diff] [blame] | 167 | self.initialized = self._init_kclient() |
Alex | 9a4ad21 | 2020-10-01 18:04:25 -0500 | [diff] [blame] | 168 | self.last_response = None |
| 169 | |
| 170 | def _init_kclient(self): |
| 171 | # if there is no password - try to get local, if this available |
Alex | 359e575 | 2021-08-16 17:28:30 -0500 | [diff] [blame] | 172 | logger_cli.debug("... init kube config") |
Alex | 9a4ad21 | 2020-10-01 18:04:25 -0500 | [diff] [blame] | 173 | if self.config.env_name == "local": |
Alex | 359e575 | 2021-08-16 17:28:30 -0500 | [diff] [blame] | 174 | self.kConf, self.kApi, self.kConfigPath = _init_kube_conf_local( |
| 175 | self.config |
| 176 | ) |
Alex | 9a4ad21 | 2020-10-01 18:04:25 -0500 | [diff] [blame] | 177 | self.is_local = True |
Alex | c4f5962 | 2021-08-27 13:42:00 -0500 | [diff] [blame] | 178 | # Try to load local config data |
| 179 | if self.config.kube_config_path and \ |
| 180 | os.path.exists(self.config.kube_config_path): |
| 181 | _cmd = "cat " + self.config.kube_config_path |
| 182 | _c_data = shell(_cmd) |
Alex | 9a4ad21 | 2020-10-01 18:04:25 -0500 | [diff] [blame] | 183 | _conf = yaml.load(_c_data, Loader=yaml.SafeLoader) |
| 184 | self.user_keypath = create_temp_file_with_content( |
| 185 | base64.standard_b64decode( |
| 186 | _conf['users'][0]['user']['client-key-data'] |
| 187 | ) |
| 188 | ) |
| 189 | self.yaml_conf = _c_data |
| 190 | else: |
Alex | 359e575 | 2021-08-16 17:28:30 -0500 | [diff] [blame] | 191 | self.kConf, self.kApi, self.kConfigPath = _init_kube_conf_remote( |
| 192 | self.config |
| 193 | ) |
Alex | 9a4ad21 | 2020-10-01 18:04:25 -0500 | [diff] [blame] | 194 | self.is_local = False |
| 195 | |
Alex | 359e575 | 2021-08-16 17:28:30 -0500 | [diff] [blame] | 196 | if self.kConf is None or self.kApi is None: |
| 197 | return False |
| 198 | else: |
| 199 | return True |
| 200 | |
Alex | 9a4ad21 | 2020-10-01 18:04:25 -0500 | [diff] [blame] | 201 | def get_versions_api(self): |
| 202 | # client.CoreApi().get_api_versions().versions |
| 203 | return kclient.VersionApi(self.kApi) |
| 204 | |
| 205 | |
| 206 | class KubeRemote(KubeApi): |
| 207 | def __init__(self, config): |
| 208 | super(KubeRemote, self).__init__(config) |
| 209 | self._coreV1 = None |
Alex | 1f90e7b | 2021-09-03 15:31:28 -0500 | [diff] [blame] | 210 | self._appsV1 = None |
| 211 | self._podV1 = None |
Alex | dcb792f | 2021-10-04 14:24:21 -0500 | [diff] [blame] | 212 | self._custom = None |
| 213 | |
| 214 | @property |
| 215 | def CustomObjects(self): |
| 216 | if not self._custom: |
| 217 | self._custom = kclient.CustomObjectsApi(self.kApi) |
| 218 | return self._custom |
Alex | 9a4ad21 | 2020-10-01 18:04:25 -0500 | [diff] [blame] | 219 | |
| 220 | @property |
| 221 | def CoreV1(self): |
| 222 | if not self._coreV1: |
Alex | 7b0ee9a | 2021-09-21 17:16:17 -0500 | [diff] [blame] | 223 | if self.is_local: |
| 224 | self._coreV1 = kclient.CoreV1Api(kclient.ApiClient()) |
| 225 | else: |
| 226 | self._coreV1 = kclient.CoreV1Api(kclient.ApiClient(self.kConf)) |
Alex | 9a4ad21 | 2020-10-01 18:04:25 -0500 | [diff] [blame] | 227 | return self._coreV1 |
| 228 | |
Alex | 1f90e7b | 2021-09-03 15:31:28 -0500 | [diff] [blame] | 229 | @property |
| 230 | def AppsV1(self): |
| 231 | if not self._appsV1: |
| 232 | self._appsV1 = kclient.AppsV1Api(self.kApi) |
| 233 | return self._appsV1 |
| 234 | |
| 235 | @property |
| 236 | def PodsV1(self): |
| 237 | if not self._podsV1: |
| 238 | self._podsV1 = kclient.V1Pod(self.kApi) |
| 239 | return self._podsV1 |
| 240 | |
Alex | 9a4ad21 | 2020-10-01 18:04:25 -0500 | [diff] [blame] | 241 | @staticmethod |
| 242 | def _typed_list_to_dict(i_list): |
| 243 | _dict = {} |
| 244 | for _item in i_list: |
| 245 | _d = _item.to_dict() |
| 246 | _type = _d.pop("type") |
| 247 | _dict[_type.lower()] = _d |
| 248 | |
| 249 | return _dict |
| 250 | |
| 251 | @staticmethod |
| 252 | def _get_listed_attrs(items, _path): |
| 253 | _list = [] |
| 254 | for _n in items: |
| 255 | _list.append(utils.rgetattr(_n, _path)) |
| 256 | |
| 257 | return _list |
| 258 | |
Alex | 1f90e7b | 2021-09-03 15:31:28 -0500 | [diff] [blame] | 259 | @staticmethod |
| 260 | def safe_get_item_by_name(api_resource, _name): |
| 261 | for item in api_resource.items: |
| 262 | if item.metadata.name == _name: |
| 263 | return item |
| 264 | |
| 265 | return None |
| 266 | |
Alex | 2a7657c | 2021-11-10 20:51:34 -0600 | [diff] [blame] | 267 | def wait_for_phase_on_start(self, _func, phase, *args, **kwargs): |
Alex | 5cace3b | 2021-11-10 16:40:37 -0600 | [diff] [blame] | 268 | w = watch.Watch() |
| 269 | start_time = time() |
| 270 | for event in w.stream(_func, *args, **kwargs): |
| 271 | if event["object"].status.phase == phase: |
| 272 | w.stop() |
| 273 | end_time = time() |
| 274 | logger_cli.debug( |
| 275 | "... bacame '{}' in {:0.2f} sec".format( |
| 276 | phase, |
| 277 | end_time-start_time |
| 278 | ) |
| 279 | ) |
| 280 | return |
| 281 | # event.type: ADDED, MODIFIED, DELETED |
| 282 | if event["type"] == "DELETED": |
| 283 | # Pod was deleted while we were waiting for it to start. |
| 284 | logger_cli.debug("... deleted before started") |
| 285 | w.stop() |
| 286 | return |
| 287 | |
Alex | 2a7657c | 2021-11-10 20:51:34 -0600 | [diff] [blame] | 288 | def wait_for_event(self, _func, event, *args, **kwargs): |
| 289 | w = watch.Watch() |
| 290 | for event in w.stream(_func, *args, **kwargs): |
| 291 | # event.type: ADDED, MODIFIED, DELETED |
| 292 | if event["type"] == event: |
| 293 | # Pod was deleted while we were waiting for it to start. |
| 294 | logger_cli.debug("... got {} event".format(event["type"])) |
| 295 | w.stop() |
| 296 | return |
| 297 | |
Alex | 9a4ad21 | 2020-10-01 18:04:25 -0500 | [diff] [blame] | 298 | def get_node_info(self, http=False): |
| 299 | # Query API for the nodes and do some presorting |
| 300 | _nodes = {} |
| 301 | if http: |
| 302 | _raw_nodes = self.CoreV1.list_node_with_http_info() |
| 303 | else: |
| 304 | _raw_nodes = self.CoreV1.list_node() |
| 305 | |
| 306 | if not isinstance(_raw_nodes, kclient.models.v1_node_list.V1NodeList): |
| 307 | raise InvalidReturnException( |
| 308 | "Invalid return type: '{}'".format(type(_raw_nodes)) |
| 309 | ) |
| 310 | |
| 311 | for _n in _raw_nodes.items: |
| 312 | _name = _n.metadata.name |
| 313 | _d = _n.to_dict() |
| 314 | # parse inner data classes as dicts |
| 315 | _d['addresses'] = self._typed_list_to_dict(_n.status.addresses) |
| 316 | _d['conditions'] = self._typed_list_to_dict(_n.status.conditions) |
| 317 | # Update 'status' type |
| 318 | if isinstance(_d['conditions']['ready']['status'], str): |
| 319 | _d['conditions']['ready']['status'] = utils.to_bool( |
| 320 | _d['conditions']['ready']['status'] |
| 321 | ) |
| 322 | # Parse image names? |
| 323 | # TODO: Here is the place where we can parse each node image names |
| 324 | |
| 325 | # Parse roles |
| 326 | _d['labels'] = {} |
| 327 | for _label, _data in _d["metadata"]["labels"].items(): |
| 328 | if _data.lower() in ["true", "false"]: |
| 329 | _d['labels'][_label] = utils.to_bool(_data) |
| 330 | else: |
| 331 | _d['labels'][_label] = _data |
| 332 | |
| 333 | # Save |
| 334 | _nodes[_name] = _d |
| 335 | |
| 336 | # debug report on how many nodes detected |
| 337 | logger_cli.debug("...node items returned '{}'".format(len(_nodes))) |
| 338 | |
| 339 | return _nodes |
| 340 | |
Alex | dcb792f | 2021-10-04 14:24:21 -0500 | [diff] [blame] | 341 | def get_pod_names_by_partial_name(self, partial_name, ns): |
| 342 | logger_cli.debug('... searching for pods with {}'.format(partial_name)) |
| 343 | _pods = self.CoreV1.list_namespaced_pod(ns) |
| 344 | _names = self._get_listed_attrs(_pods.items, "metadata.name") |
| 345 | _pnames = [n for n in _names if partial_name in n] |
| 346 | if len(_pnames) > 1: |
| 347 | logger_cli.debug( |
| 348 | "... more than one pod found for '{}': {}\n".format( |
| 349 | partial_name, |
| 350 | ", ".join(_pnames) |
| 351 | ) |
| 352 | ) |
| 353 | elif len(_pnames) < 1: |
| 354 | logger_cli.warning( |
| 355 | "WARNING: No pods found for '{}'".format(partial_name) |
| 356 | ) |
| 357 | |
| 358 | return _pnames |
| 359 | |
| 360 | def get_pods_by_partial_name(self, partial_name, ns): |
| 361 | logger_cli.debug('... searching for pods with {}'.format(partial_name)) |
| 362 | _all_pods = self.CoreV1.list_namespaced_pod(ns) |
| 363 | # _names = self._get_listed_attrs(_pods.items, "metadata.name") |
| 364 | _pods = [_pod for _pod in _all_pods.items |
| 365 | if partial_name in _pod.metadata.name] |
| 366 | if len(_pods) > 1: |
| 367 | logger_cli.debug( |
| 368 | "... more than one pod found for '{}': {}\n".format( |
| 369 | partial_name, |
| 370 | ", ".join(partial_name) |
| 371 | ) |
| 372 | ) |
| 373 | elif len(_pods) < 1: |
| 374 | logger_cli.warning( |
| 375 | "WARNING: No pods found for '{}'".format(partial_name) |
| 376 | ) |
| 377 | |
| 378 | return _pods |
| 379 | |
Alex | 9a4ad21 | 2020-10-01 18:04:25 -0500 | [diff] [blame] | 380 | def exec_on_target_pod( |
| 381 | self, |
| 382 | cmd, |
| 383 | pod_name, |
| 384 | namespace, |
| 385 | strict=False, |
| 386 | _request_timeout=120, |
Alex | b78191f | 2021-11-02 16:35:46 -0500 | [diff] [blame] | 387 | arguments=None, |
Alex | 9a4ad21 | 2020-10-01 18:04:25 -0500 | [diff] [blame] | 388 | **kwargs |
| 389 | ): |
Alex | dcb792f | 2021-10-04 14:24:21 -0500 | [diff] [blame] | 390 | _pname = "" |
Alex | 9a4ad21 | 2020-10-01 18:04:25 -0500 | [diff] [blame] | 391 | if not strict: |
Alex | 1f90e7b | 2021-09-03 15:31:28 -0500 | [diff] [blame] | 392 | logger_cli.debug( |
| 393 | "... searching for pods with the name '{}'".format(pod_name) |
| 394 | ) |
| 395 | _pods = {} |
Alex | 7b0ee9a | 2021-09-21 17:16:17 -0500 | [diff] [blame] | 396 | _pods = self.CoreV1.list_namespaced_pod(namespace) |
Alex | 1f90e7b | 2021-09-03 15:31:28 -0500 | [diff] [blame] | 397 | _names = self._get_listed_attrs(_pods.items, "metadata.name") |
Alex | 3374781 | 2021-04-07 10:11:39 -0500 | [diff] [blame] | 398 | _pnames = [n for n in _names if n.startswith(pod_name)] |
| 399 | if len(_pnames) > 1: |
Alex | 9a4ad21 | 2020-10-01 18:04:25 -0500 | [diff] [blame] | 400 | logger_cli.debug( |
Alex | c4f5962 | 2021-08-27 13:42:00 -0500 | [diff] [blame] | 401 | "... more than one pod found for '{}': {}\n" |
| 402 | "... using first one".format( |
Alex | 9a4ad21 | 2020-10-01 18:04:25 -0500 | [diff] [blame] | 403 | pod_name, |
Alex | 3374781 | 2021-04-07 10:11:39 -0500 | [diff] [blame] | 404 | ", ".join(_pnames) |
Alex | 9a4ad21 | 2020-10-01 18:04:25 -0500 | [diff] [blame] | 405 | ) |
| 406 | ) |
Alex | dcb792f | 2021-10-04 14:24:21 -0500 | [diff] [blame] | 407 | elif len(_pnames) < 1: |
Alex | 9a4ad21 | 2020-10-01 18:04:25 -0500 | [diff] [blame] | 408 | raise KubeException("No pods found for '{}'".format(pod_name)) |
Alex | b78191f | 2021-11-02 16:35:46 -0500 | [diff] [blame] | 409 | # in case of >1 and =1 we are taking 1st anyway |
| 410 | _pname = _pnames[0] |
Alex | 9a4ad21 | 2020-10-01 18:04:25 -0500 | [diff] [blame] | 411 | else: |
| 412 | _pname = pod_name |
Alex | 3374781 | 2021-04-07 10:11:39 -0500 | [diff] [blame] | 413 | logger_cli.debug( |
Alex | b78191f | 2021-11-02 16:35:46 -0500 | [diff] [blame] | 414 | "... cmd: [CoreV1] exec {} -n {} -- {} '{}'".format( |
Alex | 3374781 | 2021-04-07 10:11:39 -0500 | [diff] [blame] | 415 | _pname, |
| 416 | namespace, |
Alex | b78191f | 2021-11-02 16:35:46 -0500 | [diff] [blame] | 417 | cmd, |
| 418 | arguments |
Alex | 3374781 | 2021-04-07 10:11:39 -0500 | [diff] [blame] | 419 | ) |
| 420 | ) |
Alex | 1f90e7b | 2021-09-03 15:31:28 -0500 | [diff] [blame] | 421 | # Set preload_content to False to preserve JSON |
| 422 | # If not, output gets converted to str |
| 423 | # Which causes to change " to ' |
| 424 | # After that json.loads(...) fail |
Alex | 7b0ee9a | 2021-09-21 17:16:17 -0500 | [diff] [blame] | 425 | cmd = cmd if isinstance(cmd, list) else cmd.split() |
Alex | b78191f | 2021-11-02 16:35:46 -0500 | [diff] [blame] | 426 | if arguments: |
| 427 | cmd += [arguments] |
Alex | 1f90e7b | 2021-09-03 15:31:28 -0500 | [diff] [blame] | 428 | _pod_stream = stream( |
Alex | 9a4ad21 | 2020-10-01 18:04:25 -0500 | [diff] [blame] | 429 | self.CoreV1.connect_get_namespaced_pod_exec, |
| 430 | _pname, |
| 431 | namespace, |
Alex | 7b0ee9a | 2021-09-21 17:16:17 -0500 | [diff] [blame] | 432 | command=cmd, |
Alex | 9a4ad21 | 2020-10-01 18:04:25 -0500 | [diff] [blame] | 433 | stderr=True, |
| 434 | stdin=False, |
| 435 | stdout=True, |
| 436 | tty=False, |
| 437 | _request_timeout=_request_timeout, |
Alex | 1f90e7b | 2021-09-03 15:31:28 -0500 | [diff] [blame] | 438 | _preload_content=False, |
Alex | 9a4ad21 | 2020-10-01 18:04:25 -0500 | [diff] [blame] | 439 | **kwargs |
| 440 | ) |
Alex | 1f90e7b | 2021-09-03 15:31:28 -0500 | [diff] [blame] | 441 | # run for timeout |
| 442 | _pod_stream.run_forever(timeout=_request_timeout) |
| 443 | # read the output |
Alex | 7b0ee9a | 2021-09-21 17:16:17 -0500 | [diff] [blame] | 444 | _output = _pod_stream.read_stdout() |
Alex | b78191f | 2021-11-02 16:35:46 -0500 | [diff] [blame] | 445 | _error = _pod_stream.read_stderr() |
| 446 | if _error: |
| 447 | # copy error to output |
| 448 | logger_cli.warning( |
| 449 | "WARNING: cmd of '{}' returned error:\n{}\n".format( |
| 450 | " ".join(cmd), |
| 451 | _error |
| 452 | ) |
| 453 | ) |
| 454 | if not _output: |
| 455 | _output = _error |
Alex | 7b0ee9a | 2021-09-21 17:16:17 -0500 | [diff] [blame] | 456 | # Force recreate of api objects |
| 457 | self._coreV1 = None |
| 458 | # Send output |
| 459 | return _output |
Alex | 9a4ad21 | 2020-10-01 18:04:25 -0500 | [diff] [blame] | 460 | |
Alex | 1f90e7b | 2021-09-03 15:31:28 -0500 | [diff] [blame] | 461 | def ensure_namespace(self, ns): |
| 462 | """ |
| 463 | Ensure that given namespace exists |
| 464 | """ |
| 465 | # list active namespaces |
| 466 | _v1NamespaceList = self.CoreV1.list_namespace() |
| 467 | _ns = self.safe_get_item_by_name(_v1NamespaceList, ns) |
| 468 | |
| 469 | if _ns is None: |
| 470 | logger_cli.debug("... creating namespace '{}'".format(ns)) |
Alex | dcb792f | 2021-10-04 14:24:21 -0500 | [diff] [blame] | 471 | _new_ns = kclient.V1Namespace() |
| 472 | _new_ns.metadata = kclient.V1ObjectMeta(name=ns) |
| 473 | _r = self.CoreV1.create_namespace(_new_ns) |
Alex | 1f90e7b | 2021-09-03 15:31:28 -0500 | [diff] [blame] | 474 | # TODO: check return on fail |
| 475 | if not _r: |
| 476 | return False |
| 477 | else: |
| 478 | logger_cli.debug("... found existing namespace '{}'".format(ns)) |
| 479 | |
| 480 | return True |
| 481 | |
| 482 | def get_daemon_set_by_name(self, ns, name): |
| 483 | return self.safe_get_item_by_name( |
| 484 | self.AppsV1.list_namespaced_daemon_set(ns), |
| 485 | name |
| 486 | ) |
| 487 | |
| 488 | def create_config_map(self, ns, name, source, recreate=True): |
| 489 | """ |
| 490 | Creates/Overwrites ConfigMap in working namespace |
| 491 | """ |
| 492 | # Prepare source |
| 493 | logger_cli.debug( |
| 494 | "... preparing config map '{}/{}' with files from '{}'".format( |
| 495 | ns, |
| 496 | name, |
| 497 | source |
| 498 | ) |
| 499 | ) |
| 500 | _data = {} |
| 501 | if os.path.isfile(source): |
| 502 | # populate data with one file |
| 503 | with open(source, 'rt') as fS: |
| 504 | _data[os.path.split(source)[1]] = fS.read() |
| 505 | elif os.path.isdir(source): |
| 506 | # walk dirs and populate all 'py' files |
| 507 | for path, dirs, files in os.walk(source): |
| 508 | _e = ('.py') |
| 509 | _subfiles = (_fl for _fl in files |
| 510 | if _fl.endswith(_e) and not _fl.startswith('.')) |
| 511 | for _file in _subfiles: |
| 512 | with open(os.path.join(path, _file), 'rt') as fS: |
| 513 | _data[_file] = fS.read() |
| 514 | |
| 515 | _cm = kclient.V1ConfigMap() |
| 516 | _cm.metadata = kclient.V1ObjectMeta(name=name, namespace=ns) |
| 517 | _cm.data = _data |
| 518 | logger_cli.debug( |
| 519 | "... prepared config map with {} scripts".format(len(_data)) |
| 520 | ) |
| 521 | # Query existing configmap, delete if needed |
| 522 | _existing_cm = self.safe_get_item_by_name( |
| 523 | self.CoreV1.list_namespaced_config_map(namespace=ns), |
| 524 | name |
| 525 | ) |
| 526 | if _existing_cm is not None: |
| 527 | self.CoreV1.replace_namespaced_config_map( |
| 528 | namespace=ns, |
| 529 | name=name, |
| 530 | body=_cm |
| 531 | ) |
| 532 | logger_cli.debug( |
| 533 | "... replaced existing config map '{}/{}'".format( |
| 534 | ns, |
| 535 | name |
| 536 | ) |
| 537 | ) |
| 538 | else: |
| 539 | # Create it |
| 540 | self.CoreV1.create_namespaced_config_map( |
| 541 | namespace=ns, |
| 542 | body=_cm |
| 543 | ) |
| 544 | logger_cli.debug("... created config map '{}/{}'".format( |
| 545 | ns, |
| 546 | name |
| 547 | )) |
| 548 | |
| 549 | return _data.keys() |
| 550 | |
| 551 | def prepare_daemonset_from_yaml(self, ns, ds_yaml): |
| 552 | _name = ds_yaml['metadata']['name'] |
| 553 | _ds = self.get_daemon_set_by_name(ns, _name) |
| 554 | |
| 555 | if _ds is not None: |
| 556 | logger_cli.debug( |
| 557 | "... found existing daemonset '{}'".format(_name) |
| 558 | ) |
| 559 | _r = self.AppsV1.replace_namespaced_daemon_set( |
| 560 | _ds.metadata.name, |
| 561 | _ds.metadata.namespace, |
| 562 | body=ds_yaml |
| 563 | ) |
| 564 | logger_cli.debug( |
| 565 | "... replacing existing daemonset '{}'".format(_name) |
| 566 | ) |
| 567 | return _r |
| 568 | else: |
| 569 | logger_cli.debug( |
| 570 | "... creating daemonset '{}'".format(_name) |
| 571 | ) |
| 572 | _r = self.AppsV1.create_namespaced_daemon_set(ns, body=ds_yaml) |
| 573 | return _r |
| 574 | |
| 575 | def delete_daemon_set_by_name(self, ns, name): |
| 576 | return self.AppsV1.delete_namespaced_daemon_set(name, ns) |
| 577 | |
| 578 | def exec_on_all_pods(self, pods): |
| 579 | """ |
| 580 | Create multiple threads to execute script on all target pods |
| 581 | """ |
| 582 | # Create map for threads: [[node_name, ns, pod_name]...] |
| 583 | _pod_list = [] |
| 584 | for item in pods.items: |
| 585 | _pod_list.append( |
| 586 | [ |
| 587 | item.spec.nodeName, |
| 588 | item.metadata.namespace, |
| 589 | item.metadata.name |
| 590 | ] |
| 591 | ) |
| 592 | |
| 593 | # map func and cmd |
Alex | dcb792f | 2021-10-04 14:24:21 -0500 | [diff] [blame] | 594 | logger_cli.error("ERROR: 'exec_on_all_pods'is not implemented yet") |
Alex | 1f90e7b | 2021-09-03 15:31:28 -0500 | [diff] [blame] | 595 | # create result list |
| 596 | |
| 597 | return [] |
Alex | 7b0ee9a | 2021-09-21 17:16:17 -0500 | [diff] [blame] | 598 | |
| 599 | @retry(ApiException) |
| 600 | def get_pods_for_daemonset(self, ds): |
| 601 | # get all pod names for daemonset |
| 602 | logger_cli.debug( |
| 603 | "... extracting pod names from daemonset '{}'".format( |
| 604 | ds.metadata.name |
| 605 | ) |
| 606 | ) |
| 607 | _ns = ds.metadata.namespace |
| 608 | _name = ds.metadata.name |
| 609 | _pods = self.CoreV1.list_namespaced_pod( |
| 610 | namespace=_ns, |
| 611 | label_selector='name={}'.format(_name) |
| 612 | ) |
| 613 | return _pods |
| 614 | |
| 615 | def put_string_buffer_to_pod_as_textfile( |
| 616 | self, |
| 617 | pod_name, |
| 618 | namespace, |
| 619 | buffer, |
| 620 | filepath, |
| 621 | _request_timeout=120, |
| 622 | **kwargs |
| 623 | ): |
| 624 | _command = ['/bin/sh'] |
| 625 | response = stream( |
| 626 | self.CoreV1.connect_get_namespaced_pod_exec, |
| 627 | pod_name, |
| 628 | namespace, |
| 629 | command=_command, |
| 630 | stderr=True, |
| 631 | stdin=True, |
| 632 | stdout=True, |
| 633 | tty=False, |
| 634 | _request_timeout=_request_timeout, |
| 635 | _preload_content=False, |
| 636 | **kwargs |
| 637 | ) |
| 638 | |
| 639 | # if json |
| 640 | # buffer = json.dumps(_dict, indent=2).encode('utf-8') |
| 641 | |
| 642 | commands = [ |
| 643 | bytes("cat <<'EOF' >" + filepath + "\n", 'utf-8'), |
| 644 | buffer, |
| 645 | bytes("\n" + "EOF\n", 'utf-8') |
| 646 | ] |
| 647 | |
| 648 | while response.is_open(): |
| 649 | response.update(timeout=1) |
| 650 | if response.peek_stdout(): |
| 651 | logger_cli.debug("... STDOUT: %s" % response.read_stdout()) |
| 652 | if response.peek_stderr(): |
| 653 | logger_cli.debug("... STDERR: %s" % response.read_stderr()) |
| 654 | if commands: |
| 655 | c = commands.pop(0) |
| 656 | logger_cli.debug("... running command... {}\n".format(c)) |
| 657 | response.write_stdin(str(c, encoding='utf-8')) |
| 658 | else: |
| 659 | break |
| 660 | response.close() |
| 661 | |
| 662 | # Force recreate of Api objects |
| 663 | self._coreV1 = None |
| 664 | |
| 665 | return |
Alex | dcb792f | 2021-10-04 14:24:21 -0500 | [diff] [blame] | 666 | |
| 667 | def get_custom_resource(self, group, version, plural): |
| 668 | # Get it |
| 669 | # Example: |
| 670 | # kubernetes.client.CustomObjectsApi().list_cluster_custom_object( |
| 671 | # group="networking.istio.io", |
| 672 | # version="v1alpha3", |
| 673 | # plural="serviceentries" |
| 674 | # ) |
| 675 | return self.CustomObjects.list_cluster_custom_object( |
| 676 | group=group, |
| 677 | version=version, |
| 678 | plural=plural |
| 679 | ) |
Alex | 5cace3b | 2021-11-10 16:40:37 -0600 | [diff] [blame] | 680 | |
| 681 | def init_pvc_resource( |
| 682 | self, |
| 683 | name, |
| 684 | storage_class, |
| 685 | size, |
| 686 | ns="qa-space", |
| 687 | mode="ReadWriteOnce" |
| 688 | ): |
| 689 | """Return the Kubernetes PVC resource""" |
| 690 | return kclient.V1PersistentVolumeClaim( |
| 691 | api_version='v1', |
| 692 | kind='PersistentVolumeClaim', |
| 693 | metadata=kclient.V1ObjectMeta( |
| 694 | name=name, |
| 695 | namespace=ns, |
| 696 | labels={"name": name} |
| 697 | ), |
| 698 | spec=kclient.V1PersistentVolumeClaimSpec( |
| 699 | storage_class_name=storage_class, |
| 700 | access_modes=[mode], |
| 701 | resources=kclient.V1ResourceRequirements( |
| 702 | requests={'storage': size} |
| 703 | ) |
| 704 | ) |
| 705 | ) |
| 706 | |
| 707 | def init_pv_resource( |
| 708 | self, |
| 709 | name, |
| 710 | storage_class, |
| 711 | size, |
| 712 | path, |
| 713 | ns="qa-space", |
| 714 | mode="ReadWriteOnce" |
| 715 | ): |
| 716 | """Return the Kubernetes PVC resource""" |
| 717 | return kclient.V1PersistentVolume( |
| 718 | api_version='v1', |
| 719 | kind='PersistentVolume', |
| 720 | metadata=kclient.V1ObjectMeta( |
| 721 | name=name, |
| 722 | namespace=ns, |
| 723 | labels={"name": name} |
| 724 | ), |
| 725 | spec=kclient.V1PersistentVolumeSpec( |
| 726 | storage_class_name=storage_class, |
| 727 | access_modes=[mode], |
| 728 | capacity={'storage': size}, |
| 729 | host_path=kclient.V1HostPathVolumeSource(path=path) |
| 730 | ) |
| 731 | ) |
| 732 | |
| 733 | def init_service( |
| 734 | self, |
| 735 | name, |
| 736 | port, |
| 737 | clusterip=None, |
| 738 | ns="qa-space" |
| 739 | ): |
| 740 | """ Inits a V1Service object with data for benchmark agent""" |
| 741 | _meta = kclient.V1ObjectMeta( |
| 742 | name=name, |
| 743 | namespace=ns, |
| 744 | labels={"name": name} |
| 745 | ) |
| 746 | _port = kclient.V1ServicePort( |
| 747 | port=port, |
| 748 | protocol="TCP", |
| 749 | target_port=port |
| 750 | ) |
| 751 | _spec = kclient.V1ServiceSpec( |
| 752 | # cluster_ip=clusterip, |
| 753 | selector={"name": name}, |
| 754 | # type="ClusterIP", |
| 755 | ports=[_port] |
| 756 | ) |
| 757 | return kclient.V1Service( |
| 758 | api_version="v1", |
| 759 | kind="Service", |
| 760 | metadata=_meta, |
| 761 | spec=_spec |
| 762 | ) |
| 763 | |
| 764 | def prepare_pv(self, pv_object): |
Alex | 2a7657c | 2021-11-10 20:51:34 -0600 | [diff] [blame] | 765 | _existing = self.get_pv_by_name(pv_object.metadata.name) |
Alex | 5cace3b | 2021-11-10 16:40:37 -0600 | [diff] [blame] | 766 | if _existing is not None: |
| 767 | self.CoreV1.replace_persistent_volume( |
| 768 | pv_object.metadata.name, |
| 769 | pv_object |
| 770 | ) |
| 771 | else: |
| 772 | self.CoreV1.create_persistent_volume(pv_object) |
| 773 | |
Alex | 2a7657c | 2021-11-10 20:51:34 -0600 | [diff] [blame] | 774 | return self.wait_for_phase( |
| 775 | "pv", |
| 776 | pv_object.metadata.name, |
| 777 | None, |
| 778 | ["Available", "Bound"] |
Alex | 5cace3b | 2021-11-10 16:40:37 -0600 | [diff] [blame] | 779 | ) |
| 780 | |
| 781 | def prepare_pvc(self, pvc_object): |
Alex | 2a7657c | 2021-11-10 20:51:34 -0600 | [diff] [blame] | 782 | _existing = self.get_pvc_by_name_and_ns( |
| 783 | pvc_object.metadata.name, |
| 784 | pvc_object.metadata.namespace |
Alex | 5cace3b | 2021-11-10 16:40:37 -0600 | [diff] [blame] | 785 | ) |
| 786 | if _existing is not None: |
| 787 | _size_r = pvc_object.spec.resources.requests["storage"] |
| 788 | _size_e = _existing.spec.resources.requests["storage"] |
Alex | 2a7657c | 2021-11-10 20:51:34 -0600 | [diff] [blame] | 789 | logger_cli.info( |
| 790 | "-> Found PVC '{}/{}' with {}. Requested: {}'".format( |
Alex | 5cace3b | 2021-11-10 16:40:37 -0600 | [diff] [blame] | 791 | pvc_object.metadata.namespace, |
| 792 | pvc_object.metadata.name, |
| 793 | _size_e, |
| 794 | _size_r |
| 795 | ) |
| 796 | ) |
| 797 | if _size_r != _size_e: |
| 798 | raise CheckerException( |
| 799 | "ERROR: PVC exists on the cloud with different size " |
| 800 | "than needed. Please cleanup!" |
| 801 | ) |
| 802 | else: |
| 803 | logger_cli.debug( |
| 804 | "... creating pvc '{}'".format(pvc_object.metadata.name) |
| 805 | ) |
| 806 | self.CoreV1.create_namespaced_persistent_volume_claim( |
| 807 | pvc_object.metadata.namespace, |
| 808 | pvc_object |
| 809 | ) |
| 810 | |
Alex | 2a7657c | 2021-11-10 20:51:34 -0600 | [diff] [blame] | 811 | return self.wait_for_phase( |
| 812 | "pvc", |
| 813 | pvc_object.metadata.name, |
| 814 | pvc_object.metadata.namespace, |
| 815 | ["Available", "Bound"] |
| 816 | ) |
| 817 | |
| 818 | def get_pod_by_name_and_ns(self, name, ns): |
| 819 | return self.safe_get_item_by_name( |
| 820 | self.CoreV1.list_namespaced_pod( |
| 821 | ns, |
| 822 | label_selector='name={}'.format(name) |
| 823 | ), |
| 824 | name |
| 825 | ) |
| 826 | |
| 827 | def get_svc_by_name_and_ns(self, name, ns): |
| 828 | return self.safe_get_item_by_name( |
| 829 | self.CoreV1.list_namespaced_service( |
| 830 | ns, |
| 831 | label_selector='name={}'.format(name) |
| 832 | ), |
| 833 | name |
| 834 | ) |
| 835 | |
| 836 | def get_pvc_by_name_and_ns(self, name, ns): |
| 837 | return self.safe_get_item_by_name( |
| 838 | self.CoreV1.list_namespaced_persistent_volume_claim( |
| 839 | ns, |
| 840 | label_selector='name={}'.format(name) |
| 841 | ), |
| 842 | name |
| 843 | ) |
| 844 | |
| 845 | def get_pv_by_name(self, name): |
| 846 | return self.safe_get_item_by_name( |
| 847 | self.CoreV1.list_persistent_volume( |
| 848 | label_selector='name={}'.format(name) |
| 849 | ), |
| 850 | name |
| 851 | ) |
| 852 | |
| 853 | def wait_for_phase(self, ttype, name, ns, phase_list, timeout=120): |
| 854 | logger_cli.debug( |
| 855 | "... waiting '{}'s until {} is '{}'".format( |
| 856 | timeout, |
| 857 | ttype, |
| 858 | ", ".join(phase_list) |
| 859 | ) |
| 860 | ) |
| 861 | while timeout > 0: |
| 862 | if ttype == "pod": |
| 863 | _t = self.get_pod_by_name_and_ns(name, ns) |
| 864 | elif ttype == "svc": |
| 865 | _t = self.get_svc_by_name_and_ns(name, ns) |
| 866 | elif ttype == "pvc": |
| 867 | _t = self.get_pvc_by_name_and_ns(name, ns) |
| 868 | elif ttype == "pv": |
| 869 | _t = self.get_pv_by_name(name) |
| 870 | if "Terminated" in phase_list and not _t: |
| 871 | if ns: |
| 872 | _s = "... {} {}/{} not found".format(ttype, ns, name) |
Alex | 5cace3b | 2021-11-10 16:40:37 -0600 | [diff] [blame] | 873 | else: |
Alex | 2a7657c | 2021-11-10 20:51:34 -0600 | [diff] [blame] | 874 | _s = "... {} '{}' not found".format(ttype, name) |
| 875 | logger_cli.debug(_s) |
| 876 | return None |
| 877 | logger_cli.debug("... {} is '{}'".format(ttype, _t.status.phase)) |
| 878 | if _t.status.phase in phase_list: |
| 879 | return _t |
| 880 | sleep(2) |
| 881 | timeout -= 2 |
Alex | 5cace3b | 2021-11-10 16:40:37 -0600 | [diff] [blame] | 882 | raise CheckerException( |
Alex | 2a7657c | 2021-11-10 20:51:34 -0600 | [diff] [blame] | 883 | "Timed out waiting for {} '{}' in '{}'".format( |
| 884 | ttype, |
| 885 | name, |
| 886 | ", ".join(ttype) |
Alex | 5cace3b | 2021-11-10 16:40:37 -0600 | [diff] [blame] | 887 | ) |
| 888 | ) |
| 889 | |
| 890 | def prepare_pod_from_yaml(self, pod_yaml): |
Alex | 2a7657c | 2021-11-10 20:51:34 -0600 | [diff] [blame] | 891 | _existing = self.get_pod_by_name_and_ns( |
| 892 | pod_yaml['metadata']['name'], |
| 893 | pod_yaml['metadata']['namespace'] |
Alex | 5cace3b | 2021-11-10 16:40:37 -0600 | [diff] [blame] | 894 | ) |
| 895 | if _existing is not None: |
Alex | bfa947c | 2021-11-11 18:14:28 -0600 | [diff] [blame^] | 896 | logger_cli.info( |
| 897 | "-> Found pod '{}/{}'. Reusing.".format( |
Alex | 5cace3b | 2021-11-10 16:40:37 -0600 | [diff] [blame] | 898 | pod_yaml['metadata']['namespace'], |
| 899 | pod_yaml['metadata']['name'] |
| 900 | ) |
| 901 | ) |
| 902 | return _existing |
| 903 | else: |
| 904 | self.CoreV1.create_namespaced_pod( |
| 905 | pod_yaml['metadata']['namespace'], |
| 906 | pod_yaml |
| 907 | ) |
Alex | 2a7657c | 2021-11-10 20:51:34 -0600 | [diff] [blame] | 908 | return self.wait_for_phase( |
| 909 | "pod", |
| 910 | pod_yaml['metadata']['name'], |
| 911 | pod_yaml['metadata']['namespace'], |
| 912 | ["Running"] |
Alex | 5cace3b | 2021-11-10 16:40:37 -0600 | [diff] [blame] | 913 | ) |
| 914 | |
| 915 | def expose_pod_port(self, pod_object, port, ns="qa-space"): |
Alex | 2a7657c | 2021-11-10 20:51:34 -0600 | [diff] [blame] | 916 | _existing = self.get_svc_by_name_and_ns( |
| 917 | pod_object.metadata.name, |
| 918 | pod_object.metadata.namespace |
Alex | 5cace3b | 2021-11-10 16:40:37 -0600 | [diff] [blame] | 919 | ) |
| 920 | if _existing is not None: |
| 921 | # TODO: Check port number? |
Alex | 2a7657c | 2021-11-10 20:51:34 -0600 | [diff] [blame] | 922 | logger_cli.info( |
| 923 | "-> Pod already exposed '{}/{}:{}'. Reusing.".format( |
Alex | 5cace3b | 2021-11-10 16:40:37 -0600 | [diff] [blame] | 924 | pod_object.metadata.namespace, |
| 925 | pod_object.metadata.name, |
| 926 | port |
| 927 | ) |
| 928 | ) |
| 929 | return _existing |
| 930 | else: |
| 931 | logger_cli.debug( |
| 932 | "... creating service for pod {}/{}: {}:{}".format( |
| 933 | pod_object.metadata.namespace, |
| 934 | pod_object.metadata.name, |
| 935 | pod_object.status.pod_ip, |
| 936 | port |
| 937 | ) |
| 938 | ) |
| 939 | _svc = self.init_service( |
| 940 | pod_object.metadata.name, |
| 941 | port |
| 942 | ) |
| 943 | return self.CoreV1.create_namespaced_service( |
| 944 | pod_object.metadata.namespace, |
| 945 | _svc |
| 946 | ) |