blob: 22eee30b7838ba649e3ee9a8383c5749acb4a760 [file] [log] [blame]
Alex9a4ad212020-10-01 18:04:25 -05001"""
2Module to handle interaction with Kube
3"""
4import base64
5import os
6import urllib3
7import yaml
8
Alex5cace3b2021-11-10 16:40:37 -06009from kubernetes import client as kclient, config as kconfig, watch
Alex9a4ad212020-10-01 18:04:25 -050010from kubernetes.stream import stream
Alex7b0ee9a2021-09-21 17:16:17 -050011from kubernetes.client.rest import ApiException
Alex5cace3b2021-11-10 16:40:37 -060012from time import time, sleep
Alex9a4ad212020-10-01 18:04:25 -050013
14from cfg_checker.common import logger, logger_cli
Alex7b0ee9a2021-09-21 17:16:17 -050015from cfg_checker.common.decorators import retry
Alex5cace3b2021-11-10 16:40:37 -060016from cfg_checker.common.exception import CheckerException, \
17 InvalidReturnException, KubeException
Alex9a4ad212020-10-01 18:04:25 -050018from cfg_checker.common.file_utils import create_temp_file_with_content
19from cfg_checker.common.other import utils, shell
20from cfg_checker.common.ssh_utils import ssh_shell_p
Alex359e5752021-08-16 17:28:30 -050021from cfg_checker.common.const import ENV_LOCAL
Alex9a4ad212020-10-01 18:04:25 -050022
Alex7b0ee9a2021-09-21 17:16:17 -050023
Alex9a4ad212020-10-01 18:04:25 -050024urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
25
26
27def _init_kube_conf_local(config):
28 # Init kube library locally
Alex359e5752021-08-16 17:28:30 -050029 _path = "local:{}".format(config.kube_config_path)
Alex9a4ad212020-10-01 18:04:25 -050030 try:
Alexc4f59622021-08-27 13:42:00 -050031 kconfig.load_kube_config(config_file=config.kube_config_path)
Alex33747812021-04-07 10:11:39 -050032 if config.insecure:
33 kconfig.assert_hostname = False
34 kconfig.client_side_validation = False
Alex9a4ad212020-10-01 18:04:25 -050035 logger_cli.debug(
Alexc4f59622021-08-27 13:42:00 -050036 "... found Kube env: core, {}". format(
Alex9a4ad212020-10-01 18:04:25 -050037 ",".join(
38 kclient.CoreApi().get_api_versions().versions
39 )
40 )
41 )
Alexc4f59622021-08-27 13:42:00 -050042 return kconfig, kclient.ApiClient(), _path
Alex9a4ad212020-10-01 18:04:25 -050043 except Exception as e:
44 logger.warn("Failed to init local Kube client: {}".format(
45 str(e)
46 )
47 )
Alex359e5752021-08-16 17:28:30 -050048 return None, None, _path
Alex9a4ad212020-10-01 18:04:25 -050049
50
51def _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
Alex359e5752021-08-16 17:28:30 -050070 _path = ''
Alexc4f59622021-08-27 13:42:00 -050071 # 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:
Alex359e5752021-08-16 17:28:30 -050073 _path = "{}@{}:{}".format(
74 config.ssh_user,
75 config.ssh_host,
76 config.kube_config_path
77 )
Alex9d913532021-03-24 18:01:45 -050078 _c_data = ssh_shell_p(
Alexc4f59622021-08-27 13:42:00 -050079 "cat " + config.kube_config_path,
Alex9d913532021-03-24 18:01:45 -050080 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:
Alex359e5752021-08-16 17:28:30 -050087 _path = "local:{}".format(config.kube_config_path)
Alex9d913532021-03-24 18:01:45 -050088 with open(config.kube_config_path, 'r') as ff:
89 _c_data = ff.read()
Alex9a4ad212020-10-01 18:04:25 -050090
Alex359e5752021-08-16 17:28:30 -050091 if len(_c_data) < 1:
92 return None, None, _path
93
Alex9a4ad212020-10-01 18:04:25 -050094 _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(
Alexc4f59622021-08-27 13:42:00 -0500125 "... 'context' host extracted: '{}' via SSH@{}".format(
Alex9a4ad212020-10-01 18:04:25 -0500126 _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(
Alexc4f59622021-08-27 13:42:00 -0500137 "... kube remote host updated to {}".format(
Alex9a4ad212020-10-01 18:04:25 -0500138 _kube_conf.host
139 )
140 )
141 _kube_conf.verify_ssl = False
142 _kube_conf.debug = config.debug
Alex33747812021-04-07 10:11:39 -0500143 if config.insecure:
144 _kube_conf.assert_hostname = False
145 _kube_conf.client_side_validation = False
146
Alex9a4ad212020-10-01 18:04:25 -0500147 # 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
Alex359e5752021-08-16 17:28:30 -0500161 return _kube_conf, _kube_api, _path
Alex9a4ad212020-10-01 18:04:25 -0500162
163
164class KubeApi(object):
165 def __init__(self, config):
166 self.config = config
Alex359e5752021-08-16 17:28:30 -0500167 self.initialized = self._init_kclient()
Alex9a4ad212020-10-01 18:04:25 -0500168 self.last_response = None
169
170 def _init_kclient(self):
171 # if there is no password - try to get local, if this available
Alex359e5752021-08-16 17:28:30 -0500172 logger_cli.debug("... init kube config")
Alex9a4ad212020-10-01 18:04:25 -0500173 if self.config.env_name == "local":
Alex359e5752021-08-16 17:28:30 -0500174 self.kConf, self.kApi, self.kConfigPath = _init_kube_conf_local(
175 self.config
176 )
Alex9a4ad212020-10-01 18:04:25 -0500177 self.is_local = True
Alexc4f59622021-08-27 13:42:00 -0500178 # 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)
Alex9a4ad212020-10-01 18:04:25 -0500183 _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:
Alex359e5752021-08-16 17:28:30 -0500191 self.kConf, self.kApi, self.kConfigPath = _init_kube_conf_remote(
192 self.config
193 )
Alex9a4ad212020-10-01 18:04:25 -0500194 self.is_local = False
195
Alex359e5752021-08-16 17:28:30 -0500196 if self.kConf is None or self.kApi is None:
197 return False
198 else:
199 return True
200
Alex9a4ad212020-10-01 18:04:25 -0500201 def get_versions_api(self):
202 # client.CoreApi().get_api_versions().versions
203 return kclient.VersionApi(self.kApi)
204
205
206class KubeRemote(KubeApi):
207 def __init__(self, config):
208 super(KubeRemote, self).__init__(config)
209 self._coreV1 = None
Alex1f90e7b2021-09-03 15:31:28 -0500210 self._appsV1 = None
211 self._podV1 = None
Alexdcb792f2021-10-04 14:24:21 -0500212 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
Alex9a4ad212020-10-01 18:04:25 -0500219
220 @property
221 def CoreV1(self):
222 if not self._coreV1:
Alex7b0ee9a2021-09-21 17:16:17 -0500223 if self.is_local:
224 self._coreV1 = kclient.CoreV1Api(kclient.ApiClient())
225 else:
226 self._coreV1 = kclient.CoreV1Api(kclient.ApiClient(self.kConf))
Alex9a4ad212020-10-01 18:04:25 -0500227 return self._coreV1
228
Alex1f90e7b2021-09-03 15:31:28 -0500229 @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
Alex9a4ad212020-10-01 18:04:25 -0500241 @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
Alex1f90e7b2021-09-03 15:31:28 -0500259 @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
Alex2a7657c2021-11-10 20:51:34 -0600267 def wait_for_phase_on_start(self, _func, phase, *args, **kwargs):
Alex5cace3b2021-11-10 16:40:37 -0600268 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
Alex2a7657c2021-11-10 20:51:34 -0600288 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
Alex9a4ad212020-10-01 18:04:25 -0500298 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
Alexdcb792f2021-10-04 14:24:21 -0500341 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
Alex9a4ad212020-10-01 18:04:25 -0500380 def exec_on_target_pod(
381 self,
382 cmd,
383 pod_name,
384 namespace,
385 strict=False,
386 _request_timeout=120,
Alexb78191f2021-11-02 16:35:46 -0500387 arguments=None,
Alex9a4ad212020-10-01 18:04:25 -0500388 **kwargs
389 ):
Alexdcb792f2021-10-04 14:24:21 -0500390 _pname = ""
Alex9a4ad212020-10-01 18:04:25 -0500391 if not strict:
Alex1f90e7b2021-09-03 15:31:28 -0500392 logger_cli.debug(
393 "... searching for pods with the name '{}'".format(pod_name)
394 )
395 _pods = {}
Alex7b0ee9a2021-09-21 17:16:17 -0500396 _pods = self.CoreV1.list_namespaced_pod(namespace)
Alex1f90e7b2021-09-03 15:31:28 -0500397 _names = self._get_listed_attrs(_pods.items, "metadata.name")
Alex33747812021-04-07 10:11:39 -0500398 _pnames = [n for n in _names if n.startswith(pod_name)]
399 if len(_pnames) > 1:
Alex9a4ad212020-10-01 18:04:25 -0500400 logger_cli.debug(
Alexc4f59622021-08-27 13:42:00 -0500401 "... more than one pod found for '{}': {}\n"
402 "... using first one".format(
Alex9a4ad212020-10-01 18:04:25 -0500403 pod_name,
Alex33747812021-04-07 10:11:39 -0500404 ", ".join(_pnames)
Alex9a4ad212020-10-01 18:04:25 -0500405 )
406 )
Alexdcb792f2021-10-04 14:24:21 -0500407 elif len(_pnames) < 1:
Alex9a4ad212020-10-01 18:04:25 -0500408 raise KubeException("No pods found for '{}'".format(pod_name))
Alexb78191f2021-11-02 16:35:46 -0500409 # in case of >1 and =1 we are taking 1st anyway
410 _pname = _pnames[0]
Alex9a4ad212020-10-01 18:04:25 -0500411 else:
412 _pname = pod_name
Alex33747812021-04-07 10:11:39 -0500413 logger_cli.debug(
Alexb78191f2021-11-02 16:35:46 -0500414 "... cmd: [CoreV1] exec {} -n {} -- {} '{}'".format(
Alex33747812021-04-07 10:11:39 -0500415 _pname,
416 namespace,
Alexb78191f2021-11-02 16:35:46 -0500417 cmd,
418 arguments
Alex33747812021-04-07 10:11:39 -0500419 )
420 )
Alex1f90e7b2021-09-03 15:31:28 -0500421 # 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
Alex7b0ee9a2021-09-21 17:16:17 -0500425 cmd = cmd if isinstance(cmd, list) else cmd.split()
Alexb78191f2021-11-02 16:35:46 -0500426 if arguments:
427 cmd += [arguments]
Alex1f90e7b2021-09-03 15:31:28 -0500428 _pod_stream = stream(
Alex9a4ad212020-10-01 18:04:25 -0500429 self.CoreV1.connect_get_namespaced_pod_exec,
430 _pname,
431 namespace,
Alex7b0ee9a2021-09-21 17:16:17 -0500432 command=cmd,
Alex9a4ad212020-10-01 18:04:25 -0500433 stderr=True,
434 stdin=False,
435 stdout=True,
436 tty=False,
437 _request_timeout=_request_timeout,
Alex1f90e7b2021-09-03 15:31:28 -0500438 _preload_content=False,
Alex9a4ad212020-10-01 18:04:25 -0500439 **kwargs
440 )
Alex1f90e7b2021-09-03 15:31:28 -0500441 # run for timeout
442 _pod_stream.run_forever(timeout=_request_timeout)
443 # read the output
Alex7b0ee9a2021-09-21 17:16:17 -0500444 _output = _pod_stream.read_stdout()
Alexb78191f2021-11-02 16:35:46 -0500445 _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
Alex7b0ee9a2021-09-21 17:16:17 -0500456 # Force recreate of api objects
457 self._coreV1 = None
458 # Send output
459 return _output
Alex9a4ad212020-10-01 18:04:25 -0500460
Alex1f90e7b2021-09-03 15:31:28 -0500461 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))
Alexdcb792f2021-10-04 14:24:21 -0500471 _new_ns = kclient.V1Namespace()
472 _new_ns.metadata = kclient.V1ObjectMeta(name=ns)
473 _r = self.CoreV1.create_namespace(_new_ns)
Alex1f90e7b2021-09-03 15:31:28 -0500474 # 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
Alexdcb792f2021-10-04 14:24:21 -0500594 logger_cli.error("ERROR: 'exec_on_all_pods'is not implemented yet")
Alex1f90e7b2021-09-03 15:31:28 -0500595 # create result list
596
597 return []
Alex7b0ee9a2021-09-21 17:16:17 -0500598
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
Alexdcb792f2021-10-04 14:24:21 -0500666
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 )
Alex5cace3b2021-11-10 16:40:37 -0600680
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):
Alex2a7657c2021-11-10 20:51:34 -0600765 _existing = self.get_pv_by_name(pv_object.metadata.name)
Alex5cace3b2021-11-10 16:40:37 -0600766 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
Alex2a7657c2021-11-10 20:51:34 -0600774 return self.wait_for_phase(
775 "pv",
776 pv_object.metadata.name,
777 None,
778 ["Available", "Bound"]
Alex5cace3b2021-11-10 16:40:37 -0600779 )
780
781 def prepare_pvc(self, pvc_object):
Alex2a7657c2021-11-10 20:51:34 -0600782 _existing = self.get_pvc_by_name_and_ns(
783 pvc_object.metadata.name,
784 pvc_object.metadata.namespace
Alex5cace3b2021-11-10 16:40:37 -0600785 )
786 if _existing is not None:
787 _size_r = pvc_object.spec.resources.requests["storage"]
788 _size_e = _existing.spec.resources.requests["storage"]
Alex2a7657c2021-11-10 20:51:34 -0600789 logger_cli.info(
790 "-> Found PVC '{}/{}' with {}. Requested: {}'".format(
Alex5cace3b2021-11-10 16:40:37 -0600791 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
Alex2a7657c2021-11-10 20:51:34 -0600811 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)
Alex5cace3b2021-11-10 16:40:37 -0600873 else:
Alex2a7657c2021-11-10 20:51:34 -0600874 _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
Alex5cace3b2021-11-10 16:40:37 -0600882 raise CheckerException(
Alex2a7657c2021-11-10 20:51:34 -0600883 "Timed out waiting for {} '{}' in '{}'".format(
884 ttype,
885 name,
886 ", ".join(ttype)
Alex5cace3b2021-11-10 16:40:37 -0600887 )
888 )
889
890 def prepare_pod_from_yaml(self, pod_yaml):
Alex2a7657c2021-11-10 20:51:34 -0600891 _existing = self.get_pod_by_name_and_ns(
892 pod_yaml['metadata']['name'],
893 pod_yaml['metadata']['namespace']
Alex5cace3b2021-11-10 16:40:37 -0600894 )
895 if _existing is not None:
Alexbfa947c2021-11-11 18:14:28 -0600896 logger_cli.info(
897 "-> Found pod '{}/{}'. Reusing.".format(
Alex5cace3b2021-11-10 16:40:37 -0600898 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 )
Alex2a7657c2021-11-10 20:51:34 -0600908 return self.wait_for_phase(
909 "pod",
910 pod_yaml['metadata']['name'],
911 pod_yaml['metadata']['namespace'],
912 ["Running"]
Alex5cace3b2021-11-10 16:40:37 -0600913 )
914
915 def expose_pod_port(self, pod_object, port, ns="qa-space"):
Alex2a7657c2021-11-10 20:51:34 -0600916 _existing = self.get_svc_by_name_and_ns(
917 pod_object.metadata.name,
918 pod_object.metadata.namespace
Alex5cace3b2021-11-10 16:40:37 -0600919 )
920 if _existing is not None:
921 # TODO: Check port number?
Alex2a7657c2021-11-10 20:51:34 -0600922 logger_cli.info(
923 "-> Pod already exposed '{}/{}:{}'. Reusing.".format(
Alex5cace3b2021-11-10 16:40:37 -0600924 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 )