blob: 315f5ee5c9ecaf2e9ace3e58b71af196e0476f64 [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
11
12from cfg_checker.common import logger, logger_cli
13from cfg_checker.common.exception import InvalidReturnException, KubeException
14from cfg_checker.common.file_utils import create_temp_file_with_content
15from cfg_checker.common.other import utils, shell
16from cfg_checker.common.ssh_utils import ssh_shell_p
Alex359e5752021-08-16 17:28:30 -050017from cfg_checker.common.const import ENV_LOCAL
Alex9a4ad212020-10-01 18:04:25 -050018
19urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)
20
21
22def _init_kube_conf_local(config):
23 # Init kube library locally
Alex359e5752021-08-16 17:28:30 -050024 _path = "local:{}".format(config.kube_config_path)
Alex9a4ad212020-10-01 18:04:25 -050025 try:
Alexc4f59622021-08-27 13:42:00 -050026 kconfig.load_kube_config(config_file=config.kube_config_path)
Alex33747812021-04-07 10:11:39 -050027 if config.insecure:
28 kconfig.assert_hostname = False
29 kconfig.client_side_validation = False
Alex9a4ad212020-10-01 18:04:25 -050030 logger_cli.debug(
Alexc4f59622021-08-27 13:42:00 -050031 "... found Kube env: core, {}". format(
Alex9a4ad212020-10-01 18:04:25 -050032 ",".join(
33 kclient.CoreApi().get_api_versions().versions
34 )
35 )
36 )
Alexc4f59622021-08-27 13:42:00 -050037 return kconfig, kclient.ApiClient(), _path
Alex9a4ad212020-10-01 18:04:25 -050038 except Exception as e:
39 logger.warn("Failed to init local Kube client: {}".format(
40 str(e)
41 )
42 )
Alex359e5752021-08-16 17:28:30 -050043 return None, None, _path
Alex9a4ad212020-10-01 18:04:25 -050044
45
46def _init_kube_conf_remote(config):
47 # init remote client
48 # Preload Kube token
49 """
50 APISERVER=$(kubectl config view --minify |
51 grep server | cut -f 2- -d ":" | tr -d " ")
52 SECRET_NAME=$(kubectl get secrets |
53 grep ^default | cut -f1 -d ' ')
54 TOKEN=$(kubectl describe secret $SECRET_NAME |
55 grep -E '^token' | cut -f2 -d':' | tr -d " ")
56
57 echo "Detected API Server at: '${APISERVER}'"
58 echo "Got secret: '${SECRET_NAME}'"
59 echo "Loaded token: '${TOKEN}'"
60
61 curl $APISERVER/api
62 --header "Authorization: Bearer $TOKEN" --insecure
63 """
64 import yaml
Alex359e5752021-08-16 17:28:30 -050065 _path = ''
Alexc4f59622021-08-27 13:42:00 -050066 # Try to load remote config only if it was not detected already
67 if not config.kube_config_detected and not config.env_name == ENV_LOCAL:
Alex359e5752021-08-16 17:28:30 -050068 _path = "{}@{}:{}".format(
69 config.ssh_user,
70 config.ssh_host,
71 config.kube_config_path
72 )
Alex9d913532021-03-24 18:01:45 -050073 _c_data = ssh_shell_p(
Alexc4f59622021-08-27 13:42:00 -050074 "cat " + config.kube_config_path,
Alex9d913532021-03-24 18:01:45 -050075 config.ssh_host,
76 username=config.ssh_user,
77 keypath=config.ssh_key,
78 piped=False,
79 use_sudo=config.ssh_uses_sudo,
80 )
81 else:
Alex359e5752021-08-16 17:28:30 -050082 _path = "local:{}".format(config.kube_config_path)
Alex9d913532021-03-24 18:01:45 -050083 with open(config.kube_config_path, 'r') as ff:
84 _c_data = ff.read()
Alex9a4ad212020-10-01 18:04:25 -050085
Alex359e5752021-08-16 17:28:30 -050086 if len(_c_data) < 1:
87 return None, None, _path
88
Alex9a4ad212020-10-01 18:04:25 -050089 _conf = yaml.load(_c_data, Loader=yaml.SafeLoader)
90
91 _kube_conf = kclient.Configuration()
92 # A remote host configuration
93
94 # To work with remote cluster, we need to extract these
95 # keys = ['host', 'ssl_ca_cert', 'cert_file', 'key_file', 'verify_ssl']
96 # When v12 of the client will be release, we will use load_from_dict
97
98 _kube_conf.ssl_ca_cert = create_temp_file_with_content(
99 base64.standard_b64decode(
100 _conf['clusters'][0]['cluster']['certificate-authority-data']
101 )
102 )
103 _host = _conf['clusters'][0]['cluster']['server']
104 _kube_conf.cert_file = create_temp_file_with_content(
105 base64.standard_b64decode(
106 _conf['users'][0]['user']['client-certificate-data']
107 )
108 )
109 _kube_conf.key_file = create_temp_file_with_content(
110 base64.standard_b64decode(
111 _conf['users'][0]['user']['client-key-data']
112 )
113 )
114 if "http" not in _host or "443" not in _host:
115 logger_cli.error(
116 "Failed to extract Kube host: '{}'".format(_host)
117 )
118 else:
119 logger_cli.debug(
Alexc4f59622021-08-27 13:42:00 -0500120 "... 'context' host extracted: '{}' via SSH@{}".format(
Alex9a4ad212020-10-01 18:04:25 -0500121 _host,
122 config.ssh_host
123 )
124 )
125
126 # Substitute context host to ours
127 _tmp = _host.split(':')
128 _kube_conf.host = \
129 _tmp[0] + "://" + config.mcp_host + ":" + _tmp[2]
130 config.kube_port = _tmp[2]
131 logger_cli.debug(
Alexc4f59622021-08-27 13:42:00 -0500132 "... kube remote host updated to {}".format(
Alex9a4ad212020-10-01 18:04:25 -0500133 _kube_conf.host
134 )
135 )
136 _kube_conf.verify_ssl = False
137 _kube_conf.debug = config.debug
Alex33747812021-04-07 10:11:39 -0500138 if config.insecure:
139 _kube_conf.assert_hostname = False
140 _kube_conf.client_side_validation = False
141
Alex9a4ad212020-10-01 18:04:25 -0500142 # Nevertheless if you want to do it
143 # you can with these 2 parameters
144 # configuration.verify_ssl=True
145 # ssl_ca_cert is the filepath
146 # to the file that contains the certificate.
147 # configuration.ssl_ca_cert="certificate"
148
149 # _kube_conf.api_key = {
150 # "authorization": "Bearer " + config.kube_token
151 # }
152
153 # Create a ApiClient with our config
154 _kube_api = kclient.ApiClient(_kube_conf)
155
Alex359e5752021-08-16 17:28:30 -0500156 return _kube_conf, _kube_api, _path
Alex9a4ad212020-10-01 18:04:25 -0500157
158
159class KubeApi(object):
160 def __init__(self, config):
161 self.config = config
Alex359e5752021-08-16 17:28:30 -0500162 self.initialized = self._init_kclient()
Alex9a4ad212020-10-01 18:04:25 -0500163 self.last_response = None
164
165 def _init_kclient(self):
166 # if there is no password - try to get local, if this available
Alex359e5752021-08-16 17:28:30 -0500167 logger_cli.debug("... init kube config")
Alex9a4ad212020-10-01 18:04:25 -0500168 if self.config.env_name == "local":
Alex359e5752021-08-16 17:28:30 -0500169 self.kConf, self.kApi, self.kConfigPath = _init_kube_conf_local(
170 self.config
171 )
Alex9a4ad212020-10-01 18:04:25 -0500172 self.is_local = True
Alexc4f59622021-08-27 13:42:00 -0500173 # Try to load local config data
174 if self.config.kube_config_path and \
175 os.path.exists(self.config.kube_config_path):
176 _cmd = "cat " + self.config.kube_config_path
177 _c_data = shell(_cmd)
Alex9a4ad212020-10-01 18:04:25 -0500178 _conf = yaml.load(_c_data, Loader=yaml.SafeLoader)
179 self.user_keypath = create_temp_file_with_content(
180 base64.standard_b64decode(
181 _conf['users'][0]['user']['client-key-data']
182 )
183 )
184 self.yaml_conf = _c_data
185 else:
Alex359e5752021-08-16 17:28:30 -0500186 self.kConf, self.kApi, self.kConfigPath = _init_kube_conf_remote(
187 self.config
188 )
Alex9a4ad212020-10-01 18:04:25 -0500189 self.is_local = False
190
Alex359e5752021-08-16 17:28:30 -0500191 if self.kConf is None or self.kApi is None:
192 return False
193 else:
194 return True
195
Alex9a4ad212020-10-01 18:04:25 -0500196 def get_versions_api(self):
197 # client.CoreApi().get_api_versions().versions
198 return kclient.VersionApi(self.kApi)
199
200
201class KubeRemote(KubeApi):
202 def __init__(self, config):
203 super(KubeRemote, self).__init__(config)
204 self._coreV1 = None
205
206 @property
207 def CoreV1(self):
208 if not self._coreV1:
209 self._coreV1 = kclient.CoreV1Api(self.kApi)
210 return self._coreV1
211
212 @staticmethod
213 def _typed_list_to_dict(i_list):
214 _dict = {}
215 for _item in i_list:
216 _d = _item.to_dict()
217 _type = _d.pop("type")
218 _dict[_type.lower()] = _d
219
220 return _dict
221
222 @staticmethod
223 def _get_listed_attrs(items, _path):
224 _list = []
225 for _n in items:
226 _list.append(utils.rgetattr(_n, _path))
227
228 return _list
229
230 def get_node_info(self, http=False):
231 # Query API for the nodes and do some presorting
232 _nodes = {}
233 if http:
234 _raw_nodes = self.CoreV1.list_node_with_http_info()
235 else:
236 _raw_nodes = self.CoreV1.list_node()
237
238 if not isinstance(_raw_nodes, kclient.models.v1_node_list.V1NodeList):
239 raise InvalidReturnException(
240 "Invalid return type: '{}'".format(type(_raw_nodes))
241 )
242
243 for _n in _raw_nodes.items:
244 _name = _n.metadata.name
245 _d = _n.to_dict()
246 # parse inner data classes as dicts
247 _d['addresses'] = self._typed_list_to_dict(_n.status.addresses)
248 _d['conditions'] = self._typed_list_to_dict(_n.status.conditions)
249 # Update 'status' type
250 if isinstance(_d['conditions']['ready']['status'], str):
251 _d['conditions']['ready']['status'] = utils.to_bool(
252 _d['conditions']['ready']['status']
253 )
254 # Parse image names?
255 # TODO: Here is the place where we can parse each node image names
256
257 # Parse roles
258 _d['labels'] = {}
259 for _label, _data in _d["metadata"]["labels"].items():
260 if _data.lower() in ["true", "false"]:
261 _d['labels'][_label] = utils.to_bool(_data)
262 else:
263 _d['labels'][_label] = _data
264
265 # Save
266 _nodes[_name] = _d
267
268 # debug report on how many nodes detected
269 logger_cli.debug("...node items returned '{}'".format(len(_nodes)))
270
271 return _nodes
272
273 def exec_on_target_pod(
274 self,
275 cmd,
276 pod_name,
277 namespace,
278 strict=False,
279 _request_timeout=120,
280 **kwargs
281 ):
Alex33747812021-04-07 10:11:39 -0500282 logger_cli.debug(
Alexc4f59622021-08-27 13:42:00 -0500283 "... searching for pods with the name '{}'".format(pod_name)
Alex33747812021-04-07 10:11:39 -0500284 )
Alex9a4ad212020-10-01 18:04:25 -0500285 _pods = {}
286 _pods = self._coreV1.list_namespaced_pod(namespace)
287 _names = self._get_listed_attrs(_pods.items, "metadata.name")
288
289 _pname = ""
290 if not strict:
Alex33747812021-04-07 10:11:39 -0500291 _pnames = [n for n in _names if n.startswith(pod_name)]
292 if len(_pnames) > 1:
Alex9a4ad212020-10-01 18:04:25 -0500293 logger_cli.debug(
Alexc4f59622021-08-27 13:42:00 -0500294 "... more than one pod found for '{}': {}\n"
295 "... using first one".format(
Alex9a4ad212020-10-01 18:04:25 -0500296 pod_name,
Alex33747812021-04-07 10:11:39 -0500297 ", ".join(_pnames)
Alex9a4ad212020-10-01 18:04:25 -0500298 )
299 )
Alex33747812021-04-07 10:11:39 -0500300 _pname = _pnames[0]
Alex9a4ad212020-10-01 18:04:25 -0500301 elif len(_pname) < 1:
302 raise KubeException("No pods found for '{}'".format(pod_name))
303 else:
304 _pname = pod_name
Alex33747812021-04-07 10:11:39 -0500305 logger_cli.debug(
Alexc4f59622021-08-27 13:42:00 -0500306 "... cmd: [CoreV1] exec {} -n {} -- {}".format(
Alex33747812021-04-07 10:11:39 -0500307 _pname,
308 namespace,
309 cmd
310 )
311 )
Alex9a4ad212020-10-01 18:04:25 -0500312 _r = stream(
313 self.CoreV1.connect_get_namespaced_pod_exec,
314 _pname,
315 namespace,
316 command=cmd.split(),
317 stderr=True,
318 stdin=False,
319 stdout=True,
320 tty=False,
321 _request_timeout=_request_timeout,
322 **kwargs
323 )
324
325 return _r