blob: 042db5d3c6743d8a5e4f9e5c32e3e685cb9c2d64 [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
9from kubernetes import client as kclient, config as kconfig
10from kubernetes.stream import stream
Alex7b0ee9a2021-09-21 17:16:17 -050011from kubernetes.client.rest import ApiException
Alex9a4ad212020-10-01 18:04:25 -050012
13from cfg_checker.common import logger, logger_cli
Alex7b0ee9a2021-09-21 17:16:17 -050014from cfg_checker.common.decorators import retry
Alex9a4ad212020-10-01 18:04:25 -050015from cfg_checker.common.exception import InvalidReturnException, KubeException
16from cfg_checker.common.file_utils import create_temp_file_with_content
17from cfg_checker.common.other import utils, shell
18from cfg_checker.common.ssh_utils import ssh_shell_p
Alex359e5752021-08-16 17:28:30 -050019from cfg_checker.common.const import ENV_LOCAL
Alex9a4ad212020-10-01 18:04:25 -050020
Alex7b0ee9a2021-09-21 17:16:17 -050021
Alex9a4ad212020-10-01 18:04:25 -050022urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
23
24
25def _init_kube_conf_local(config):
26 # Init kube library locally
Alex359e5752021-08-16 17:28:30 -050027 _path = "local:{}".format(config.kube_config_path)
Alex9a4ad212020-10-01 18:04:25 -050028 try:
Alexc4f59622021-08-27 13:42:00 -050029 kconfig.load_kube_config(config_file=config.kube_config_path)
Alex33747812021-04-07 10:11:39 -050030 if config.insecure:
31 kconfig.assert_hostname = False
32 kconfig.client_side_validation = False
Alex9a4ad212020-10-01 18:04:25 -050033 logger_cli.debug(
Alexc4f59622021-08-27 13:42:00 -050034 "... found Kube env: core, {}". format(
Alex9a4ad212020-10-01 18:04:25 -050035 ",".join(
36 kclient.CoreApi().get_api_versions().versions
37 )
38 )
39 )
Alexc4f59622021-08-27 13:42:00 -050040 return kconfig, kclient.ApiClient(), _path
Alex9a4ad212020-10-01 18:04:25 -050041 except Exception as e:
42 logger.warn("Failed to init local Kube client: {}".format(
43 str(e)
44 )
45 )
Alex359e5752021-08-16 17:28:30 -050046 return None, None, _path
Alex9a4ad212020-10-01 18:04:25 -050047
48
49def _init_kube_conf_remote(config):
50 # init remote client
51 # Preload Kube token
52 """
53 APISERVER=$(kubectl config view --minify |
54 grep server | cut -f 2- -d ":" | tr -d " ")
55 SECRET_NAME=$(kubectl get secrets |
56 grep ^default | cut -f1 -d ' ')
57 TOKEN=$(kubectl describe secret $SECRET_NAME |
58 grep -E '^token' | cut -f2 -d':' | tr -d " ")
59
60 echo "Detected API Server at: '${APISERVER}'"
61 echo "Got secret: '${SECRET_NAME}'"
62 echo "Loaded token: '${TOKEN}'"
63
64 curl $APISERVER/api
65 --header "Authorization: Bearer $TOKEN" --insecure
66 """
67 import yaml
Alex359e5752021-08-16 17:28:30 -050068 _path = ''
Alexc4f59622021-08-27 13:42:00 -050069 # Try to load remote config only if it was not detected already
70 if not config.kube_config_detected and not config.env_name == ENV_LOCAL:
Alex359e5752021-08-16 17:28:30 -050071 _path = "{}@{}:{}".format(
72 config.ssh_user,
73 config.ssh_host,
74 config.kube_config_path
75 )
Alex9d913532021-03-24 18:01:45 -050076 _c_data = ssh_shell_p(
Alexc4f59622021-08-27 13:42:00 -050077 "cat " + config.kube_config_path,
Alex9d913532021-03-24 18:01:45 -050078 config.ssh_host,
79 username=config.ssh_user,
80 keypath=config.ssh_key,
81 piped=False,
82 use_sudo=config.ssh_uses_sudo,
83 )
84 else:
Alex359e5752021-08-16 17:28:30 -050085 _path = "local:{}".format(config.kube_config_path)
Alex9d913532021-03-24 18:01:45 -050086 with open(config.kube_config_path, 'r') as ff:
87 _c_data = ff.read()
Alex9a4ad212020-10-01 18:04:25 -050088
Alex359e5752021-08-16 17:28:30 -050089 if len(_c_data) < 1:
90 return None, None, _path
91
Alex9a4ad212020-10-01 18:04:25 -050092 _conf = yaml.load(_c_data, Loader=yaml.SafeLoader)
93
94 _kube_conf = kclient.Configuration()
95 # A remote host configuration
96
97 # To work with remote cluster, we need to extract these
98 # keys = ['host', 'ssl_ca_cert', 'cert_file', 'key_file', 'verify_ssl']
99 # When v12 of the client will be release, we will use load_from_dict
100
101 _kube_conf.ssl_ca_cert = create_temp_file_with_content(
102 base64.standard_b64decode(
103 _conf['clusters'][0]['cluster']['certificate-authority-data']
104 )
105 )
106 _host = _conf['clusters'][0]['cluster']['server']
107 _kube_conf.cert_file = create_temp_file_with_content(
108 base64.standard_b64decode(
109 _conf['users'][0]['user']['client-certificate-data']
110 )
111 )
112 _kube_conf.key_file = create_temp_file_with_content(
113 base64.standard_b64decode(
114 _conf['users'][0]['user']['client-key-data']
115 )
116 )
117 if "http" not in _host or "443" not in _host:
118 logger_cli.error(
119 "Failed to extract Kube host: '{}'".format(_host)
120 )
121 else:
122 logger_cli.debug(
Alexc4f59622021-08-27 13:42:00 -0500123 "... 'context' host extracted: '{}' via SSH@{}".format(
Alex9a4ad212020-10-01 18:04:25 -0500124 _host,
125 config.ssh_host
126 )
127 )
128
129 # Substitute context host to ours
130 _tmp = _host.split(':')
131 _kube_conf.host = \
132 _tmp[0] + "://" + config.mcp_host + ":" + _tmp[2]
133 config.kube_port = _tmp[2]
134 logger_cli.debug(
Alexc4f59622021-08-27 13:42:00 -0500135 "... kube remote host updated to {}".format(
Alex9a4ad212020-10-01 18:04:25 -0500136 _kube_conf.host
137 )
138 )
139 _kube_conf.verify_ssl = False
140 _kube_conf.debug = config.debug
Alex33747812021-04-07 10:11:39 -0500141 if config.insecure:
142 _kube_conf.assert_hostname = False
143 _kube_conf.client_side_validation = False
144
Alex9a4ad212020-10-01 18:04:25 -0500145 # Nevertheless if you want to do it
146 # you can with these 2 parameters
147 # configuration.verify_ssl=True
148 # ssl_ca_cert is the filepath
149 # to the file that contains the certificate.
150 # configuration.ssl_ca_cert="certificate"
151
152 # _kube_conf.api_key = {
153 # "authorization": "Bearer " + config.kube_token
154 # }
155
156 # Create a ApiClient with our config
157 _kube_api = kclient.ApiClient(_kube_conf)
158
Alex359e5752021-08-16 17:28:30 -0500159 return _kube_conf, _kube_api, _path
Alex9a4ad212020-10-01 18:04:25 -0500160
161
162class KubeApi(object):
163 def __init__(self, config):
164 self.config = config
Alex359e5752021-08-16 17:28:30 -0500165 self.initialized = self._init_kclient()
Alex9a4ad212020-10-01 18:04:25 -0500166 self.last_response = None
167
168 def _init_kclient(self):
169 # if there is no password - try to get local, if this available
Alex359e5752021-08-16 17:28:30 -0500170 logger_cli.debug("... init kube config")
Alex9a4ad212020-10-01 18:04:25 -0500171 if self.config.env_name == "local":
Alex359e5752021-08-16 17:28:30 -0500172 self.kConf, self.kApi, self.kConfigPath = _init_kube_conf_local(
173 self.config
174 )
Alex9a4ad212020-10-01 18:04:25 -0500175 self.is_local = True
Alexc4f59622021-08-27 13:42:00 -0500176 # Try to load local config data
177 if self.config.kube_config_path and \
178 os.path.exists(self.config.kube_config_path):
179 _cmd = "cat " + self.config.kube_config_path
180 _c_data = shell(_cmd)
Alex9a4ad212020-10-01 18:04:25 -0500181 _conf = yaml.load(_c_data, Loader=yaml.SafeLoader)
182 self.user_keypath = create_temp_file_with_content(
183 base64.standard_b64decode(
184 _conf['users'][0]['user']['client-key-data']
185 )
186 )
187 self.yaml_conf = _c_data
188 else:
Alex359e5752021-08-16 17:28:30 -0500189 self.kConf, self.kApi, self.kConfigPath = _init_kube_conf_remote(
190 self.config
191 )
Alex9a4ad212020-10-01 18:04:25 -0500192 self.is_local = False
193
Alex359e5752021-08-16 17:28:30 -0500194 if self.kConf is None or self.kApi is None:
195 return False
196 else:
197 return True
198
Alex9a4ad212020-10-01 18:04:25 -0500199 def get_versions_api(self):
200 # client.CoreApi().get_api_versions().versions
201 return kclient.VersionApi(self.kApi)
202
203
204class KubeRemote(KubeApi):
205 def __init__(self, config):
206 super(KubeRemote, self).__init__(config)
207 self._coreV1 = None
Alex1f90e7b2021-09-03 15:31:28 -0500208 self._appsV1 = None
209 self._podV1 = None
Alex9a4ad212020-10-01 18:04:25 -0500210
211 @property
212 def CoreV1(self):
213 if not self._coreV1:
Alex7b0ee9a2021-09-21 17:16:17 -0500214 if self.is_local:
215 self._coreV1 = kclient.CoreV1Api(kclient.ApiClient())
216 else:
217 self._coreV1 = kclient.CoreV1Api(kclient.ApiClient(self.kConf))
Alex9a4ad212020-10-01 18:04:25 -0500218 return self._coreV1
219
Alex1f90e7b2021-09-03 15:31:28 -0500220 @property
221 def AppsV1(self):
222 if not self._appsV1:
223 self._appsV1 = kclient.AppsV1Api(self.kApi)
224 return self._appsV1
225
226 @property
227 def PodsV1(self):
228 if not self._podsV1:
229 self._podsV1 = kclient.V1Pod(self.kApi)
230 return self._podsV1
231
Alex9a4ad212020-10-01 18:04:25 -0500232 @staticmethod
233 def _typed_list_to_dict(i_list):
234 _dict = {}
235 for _item in i_list:
236 _d = _item.to_dict()
237 _type = _d.pop("type")
238 _dict[_type.lower()] = _d
239
240 return _dict
241
242 @staticmethod
243 def _get_listed_attrs(items, _path):
244 _list = []
245 for _n in items:
246 _list.append(utils.rgetattr(_n, _path))
247
248 return _list
249
Alex1f90e7b2021-09-03 15:31:28 -0500250 @staticmethod
251 def safe_get_item_by_name(api_resource, _name):
252 for item in api_resource.items:
253 if item.metadata.name == _name:
254 return item
255
256 return None
257
Alex9a4ad212020-10-01 18:04:25 -0500258 def get_node_info(self, http=False):
259 # Query API for the nodes and do some presorting
260 _nodes = {}
261 if http:
262 _raw_nodes = self.CoreV1.list_node_with_http_info()
263 else:
264 _raw_nodes = self.CoreV1.list_node()
265
266 if not isinstance(_raw_nodes, kclient.models.v1_node_list.V1NodeList):
267 raise InvalidReturnException(
268 "Invalid return type: '{}'".format(type(_raw_nodes))
269 )
270
271 for _n in _raw_nodes.items:
272 _name = _n.metadata.name
273 _d = _n.to_dict()
274 # parse inner data classes as dicts
275 _d['addresses'] = self._typed_list_to_dict(_n.status.addresses)
276 _d['conditions'] = self._typed_list_to_dict(_n.status.conditions)
277 # Update 'status' type
278 if isinstance(_d['conditions']['ready']['status'], str):
279 _d['conditions']['ready']['status'] = utils.to_bool(
280 _d['conditions']['ready']['status']
281 )
282 # Parse image names?
283 # TODO: Here is the place where we can parse each node image names
284
285 # Parse roles
286 _d['labels'] = {}
287 for _label, _data in _d["metadata"]["labels"].items():
288 if _data.lower() in ["true", "false"]:
289 _d['labels'][_label] = utils.to_bool(_data)
290 else:
291 _d['labels'][_label] = _data
292
293 # Save
294 _nodes[_name] = _d
295
296 # debug report on how many nodes detected
297 logger_cli.debug("...node items returned '{}'".format(len(_nodes)))
298
299 return _nodes
300
301 def exec_on_target_pod(
302 self,
303 cmd,
304 pod_name,
305 namespace,
306 strict=False,
307 _request_timeout=120,
308 **kwargs
309 ):
Alex9a4ad212020-10-01 18:04:25 -0500310 if not strict:
Alex1f90e7b2021-09-03 15:31:28 -0500311 logger_cli.debug(
312 "... searching for pods with the name '{}'".format(pod_name)
313 )
314 _pods = {}
Alex7b0ee9a2021-09-21 17:16:17 -0500315 _pods = self.CoreV1.list_namespaced_pod(namespace)
Alex1f90e7b2021-09-03 15:31:28 -0500316 _names = self._get_listed_attrs(_pods.items, "metadata.name")
317 _pname = ""
Alex33747812021-04-07 10:11:39 -0500318 _pnames = [n for n in _names if n.startswith(pod_name)]
319 if len(_pnames) > 1:
Alex9a4ad212020-10-01 18:04:25 -0500320 logger_cli.debug(
Alexc4f59622021-08-27 13:42:00 -0500321 "... more than one pod found for '{}': {}\n"
322 "... using first one".format(
Alex9a4ad212020-10-01 18:04:25 -0500323 pod_name,
Alex33747812021-04-07 10:11:39 -0500324 ", ".join(_pnames)
Alex9a4ad212020-10-01 18:04:25 -0500325 )
326 )
Alex33747812021-04-07 10:11:39 -0500327 _pname = _pnames[0]
Alex9a4ad212020-10-01 18:04:25 -0500328 elif len(_pname) < 1:
329 raise KubeException("No pods found for '{}'".format(pod_name))
330 else:
331 _pname = pod_name
Alex33747812021-04-07 10:11:39 -0500332 logger_cli.debug(
Alexc4f59622021-08-27 13:42:00 -0500333 "... cmd: [CoreV1] exec {} -n {} -- {}".format(
Alex33747812021-04-07 10:11:39 -0500334 _pname,
335 namespace,
336 cmd
337 )
338 )
Alex1f90e7b2021-09-03 15:31:28 -0500339 # Set preload_content to False to preserve JSON
340 # If not, output gets converted to str
341 # Which causes to change " to '
342 # After that json.loads(...) fail
Alex7b0ee9a2021-09-21 17:16:17 -0500343 cmd = cmd if isinstance(cmd, list) else cmd.split()
Alex1f90e7b2021-09-03 15:31:28 -0500344 _pod_stream = stream(
Alex9a4ad212020-10-01 18:04:25 -0500345 self.CoreV1.connect_get_namespaced_pod_exec,
346 _pname,
347 namespace,
Alex7b0ee9a2021-09-21 17:16:17 -0500348 command=cmd,
Alex9a4ad212020-10-01 18:04:25 -0500349 stderr=True,
350 stdin=False,
351 stdout=True,
352 tty=False,
353 _request_timeout=_request_timeout,
Alex1f90e7b2021-09-03 15:31:28 -0500354 _preload_content=False,
Alex9a4ad212020-10-01 18:04:25 -0500355 **kwargs
356 )
Alex1f90e7b2021-09-03 15:31:28 -0500357 # run for timeout
358 _pod_stream.run_forever(timeout=_request_timeout)
359 # read the output
Alex7b0ee9a2021-09-21 17:16:17 -0500360 _output = _pod_stream.read_stdout()
361 # Force recreate of api objects
362 self._coreV1 = None
363 # Send output
364 return _output
Alex9a4ad212020-10-01 18:04:25 -0500365
Alex1f90e7b2021-09-03 15:31:28 -0500366 def ensure_namespace(self, ns):
367 """
368 Ensure that given namespace exists
369 """
370 # list active namespaces
371 _v1NamespaceList = self.CoreV1.list_namespace()
372 _ns = self.safe_get_item_by_name(_v1NamespaceList, ns)
373
374 if _ns is None:
375 logger_cli.debug("... creating namespace '{}'".format(ns))
376 _r = self.CoreV1.create_namespace(ns)
377 # TODO: check return on fail
378 if not _r:
379 return False
380 else:
381 logger_cli.debug("... found existing namespace '{}'".format(ns))
382
383 return True
384
385 def get_daemon_set_by_name(self, ns, name):
386 return self.safe_get_item_by_name(
387 self.AppsV1.list_namespaced_daemon_set(ns),
388 name
389 )
390
391 def create_config_map(self, ns, name, source, recreate=True):
392 """
393 Creates/Overwrites ConfigMap in working namespace
394 """
395 # Prepare source
396 logger_cli.debug(
397 "... preparing config map '{}/{}' with files from '{}'".format(
398 ns,
399 name,
400 source
401 )
402 )
403 _data = {}
404 if os.path.isfile(source):
405 # populate data with one file
406 with open(source, 'rt') as fS:
407 _data[os.path.split(source)[1]] = fS.read()
408 elif os.path.isdir(source):
409 # walk dirs and populate all 'py' files
410 for path, dirs, files in os.walk(source):
411 _e = ('.py')
412 _subfiles = (_fl for _fl in files
413 if _fl.endswith(_e) and not _fl.startswith('.'))
414 for _file in _subfiles:
415 with open(os.path.join(path, _file), 'rt') as fS:
416 _data[_file] = fS.read()
417
418 _cm = kclient.V1ConfigMap()
419 _cm.metadata = kclient.V1ObjectMeta(name=name, namespace=ns)
420 _cm.data = _data
421 logger_cli.debug(
422 "... prepared config map with {} scripts".format(len(_data))
423 )
424 # Query existing configmap, delete if needed
425 _existing_cm = self.safe_get_item_by_name(
426 self.CoreV1.list_namespaced_config_map(namespace=ns),
427 name
428 )
429 if _existing_cm is not None:
430 self.CoreV1.replace_namespaced_config_map(
431 namespace=ns,
432 name=name,
433 body=_cm
434 )
435 logger_cli.debug(
436 "... replaced existing config map '{}/{}'".format(
437 ns,
438 name
439 )
440 )
441 else:
442 # Create it
443 self.CoreV1.create_namespaced_config_map(
444 namespace=ns,
445 body=_cm
446 )
447 logger_cli.debug("... created config map '{}/{}'".format(
448 ns,
449 name
450 ))
451
452 return _data.keys()
453
454 def prepare_daemonset_from_yaml(self, ns, ds_yaml):
455 _name = ds_yaml['metadata']['name']
456 _ds = self.get_daemon_set_by_name(ns, _name)
457
458 if _ds is not None:
459 logger_cli.debug(
460 "... found existing daemonset '{}'".format(_name)
461 )
462 _r = self.AppsV1.replace_namespaced_daemon_set(
463 _ds.metadata.name,
464 _ds.metadata.namespace,
465 body=ds_yaml
466 )
467 logger_cli.debug(
468 "... replacing existing daemonset '{}'".format(_name)
469 )
470 return _r
471 else:
472 logger_cli.debug(
473 "... creating daemonset '{}'".format(_name)
474 )
475 _r = self.AppsV1.create_namespaced_daemon_set(ns, body=ds_yaml)
476 return _r
477
478 def delete_daemon_set_by_name(self, ns, name):
479 return self.AppsV1.delete_namespaced_daemon_set(name, ns)
480
481 def exec_on_all_pods(self, pods):
482 """
483 Create multiple threads to execute script on all target pods
484 """
485 # Create map for threads: [[node_name, ns, pod_name]...]
486 _pod_list = []
487 for item in pods.items:
488 _pod_list.append(
489 [
490 item.spec.nodeName,
491 item.metadata.namespace,
492 item.metadata.name
493 ]
494 )
495
496 # map func and cmd
497
498 # create result list
499
500 return []
Alex7b0ee9a2021-09-21 17:16:17 -0500501
502 @retry(ApiException)
503 def get_pods_for_daemonset(self, ds):
504 # get all pod names for daemonset
505 logger_cli.debug(
506 "... extracting pod names from daemonset '{}'".format(
507 ds.metadata.name
508 )
509 )
510 _ns = ds.metadata.namespace
511 _name = ds.metadata.name
512 _pods = self.CoreV1.list_namespaced_pod(
513 namespace=_ns,
514 label_selector='name={}'.format(_name)
515 )
516 return _pods
517
518 def put_string_buffer_to_pod_as_textfile(
519 self,
520 pod_name,
521 namespace,
522 buffer,
523 filepath,
524 _request_timeout=120,
525 **kwargs
526 ):
527 _command = ['/bin/sh']
528 response = stream(
529 self.CoreV1.connect_get_namespaced_pod_exec,
530 pod_name,
531 namespace,
532 command=_command,
533 stderr=True,
534 stdin=True,
535 stdout=True,
536 tty=False,
537 _request_timeout=_request_timeout,
538 _preload_content=False,
539 **kwargs
540 )
541
542 # if json
543 # buffer = json.dumps(_dict, indent=2).encode('utf-8')
544
545 commands = [
546 bytes("cat <<'EOF' >" + filepath + "\n", 'utf-8'),
547 buffer,
548 bytes("\n" + "EOF\n", 'utf-8')
549 ]
550
551 while response.is_open():
552 response.update(timeout=1)
553 if response.peek_stdout():
554 logger_cli.debug("... STDOUT: %s" % response.read_stdout())
555 if response.peek_stderr():
556 logger_cli.debug("... STDERR: %s" % response.read_stderr())
557 if commands:
558 c = commands.pop(0)
559 logger_cli.debug("... running command... {}\n".format(c))
560 response.write_stdin(str(c, encoding='utf-8'))
561 else:
562 break
563 response.close()
564
565 # Force recreate of Api objects
566 self._coreV1 = None
567
568 return