blob: ad9d9d0bdf832576aa60ce2ee83cf29a1fb499f2 [file] [log] [blame]
quilesj26c78a42019-10-28 18:10:42 +01001##
2# Copyright 2019 Telefonica Investigacion y Desarrollo, S.A.U.
3# This file is part of OSM
4# All Rights Reserved.
5#
6# Licensed under the Apache License, Version 2.0 (the "License");
7# you may not use this file except in compliance with the License.
8# You may obtain a copy of the License at
9#
10# http://www.apache.org/licenses/LICENSE-2.0
11#
12# Unless required by applicable law or agreed to in writing, software
13# distributed under the License is distributed on an "AS IS" BASIS,
14# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
15# implied.
16# See the License for the specific language governing permissions and
17# limitations under the License.
18#
19# For those usages not covered by the Apache License, Version 2.0 please
20# contact with: nfvlabs@tid.es
21##
22
quilesj26c78a42019-10-28 18:10:42 +010023import asyncio
beierlmf52cb7c2020-04-21 16:36:35 -040024import os
quilesj26c78a42019-10-28 18:10:42 +010025import random
beierlmf52cb7c2020-04-21 16:36:35 -040026import shutil
27import subprocess
28import time
29from uuid import uuid4
30
quilesja6748412019-12-04 07:51:26 +000031from n2vc.exceptions import K8sException
beierlmf52cb7c2020-04-21 16:36:35 -040032from n2vc.k8s_conn import K8sConnector
33import yaml
quilesj26c78a42019-10-28 18:10:42 +010034
35
36class K8sHelmConnector(K8sConnector):
37
38 """
beierlmf52cb7c2020-04-21 16:36:35 -040039 ####################################################################################
40 ################################### P U B L I C ####################################
41 ####################################################################################
quilesj26c78a42019-10-28 18:10:42 +010042 """
tiernof9bdac22020-06-25 15:48:52 +000043 service_account = "osm"
quilesj26c78a42019-10-28 18:10:42 +010044
45 def __init__(
beierlmf52cb7c2020-04-21 16:36:35 -040046 self,
47 fs: object,
48 db: object,
49 kubectl_command: str = "/usr/bin/kubectl",
50 helm_command: str = "/usr/bin/helm",
51 log: object = None,
52 on_update_db=None,
quilesj26c78a42019-10-28 18:10:42 +010053 ):
54 """
55
56 :param fs: file system for kubernetes and helm configuration
57 :param db: database object to write current operation status
58 :param kubectl_command: path to kubectl executable
59 :param helm_command: path to helm executable
60 :param log: logger
61 :param on_update_db: callback called when k8s connector updates database
62 """
63
64 # parent class
beierlmf52cb7c2020-04-21 16:36:35 -040065 K8sConnector.__init__(self, db=db, log=log, on_update_db=on_update_db)
quilesj26c78a42019-10-28 18:10:42 +010066
beierlmf52cb7c2020-04-21 16:36:35 -040067 self.log.info("Initializing K8S Helm connector")
quilesj26c78a42019-10-28 18:10:42 +010068
69 # random numbers for release name generation
70 random.seed(time.time())
71
72 # the file system
73 self.fs = fs
74
75 # exception if kubectl is not installed
76 self.kubectl_command = kubectl_command
77 self._check_file_exists(filename=kubectl_command, exception_if_not_exists=True)
78
79 # exception if helm is not installed
80 self._helm_command = helm_command
81 self._check_file_exists(filename=helm_command, exception_if_not_exists=True)
82
quilesj1be06302019-11-29 11:17:11 +000083 # initialize helm client-only
beierlmf52cb7c2020-04-21 16:36:35 -040084 self.log.debug("Initializing helm client-only...")
85 command = "{} init --client-only".format(self._helm_command)
quilesj1be06302019-11-29 11:17:11 +000086 try:
beierlmf52cb7c2020-04-21 16:36:35 -040087 asyncio.ensure_future(
88 self._local_async_exec(command=command, raise_exception_on_error=False)
89 )
quilesj1be06302019-11-29 11:17:11 +000090 # loop = asyncio.get_event_loop()
beierlmf52cb7c2020-04-21 16:36:35 -040091 # loop.run_until_complete(self._local_async_exec(command=command,
92 # raise_exception_on_error=False))
quilesj1be06302019-11-29 11:17:11 +000093 except Exception as e:
beierlmf52cb7c2020-04-21 16:36:35 -040094 self.warning(
95 msg="helm init failed (it was already initialized): {}".format(e)
96 )
quilesj1be06302019-11-29 11:17:11 +000097
beierlmf52cb7c2020-04-21 16:36:35 -040098 self.log.info("K8S Helm connector initialized")
quilesj26c78a42019-10-28 18:10:42 +010099
tiernof9bdac22020-06-25 15:48:52 +0000100 @staticmethod
101 def _get_namespace_cluster_id(cluster_uuid: str) -> (str, str):
102 """
103 Parses cluster_uuid stored at database that can be either 'namespace:cluster_id' or only
104 cluster_id for backward compatibility
105 """
106 namespace, _, cluster_id = cluster_uuid.rpartition(':')
107 return namespace, cluster_id
108
quilesj26c78a42019-10-28 18:10:42 +0100109 async def init_env(
beierlmf52cb7c2020-04-21 16:36:35 -0400110 self, k8s_creds: str, namespace: str = "kube-system", reuse_cluster_uuid=None
quilesj26c78a42019-10-28 18:10:42 +0100111 ) -> (str, bool):
garciadeblas54771fa2019-12-13 13:39:03 +0100112 """
113 It prepares a given K8s cluster environment to run Charts on both sides:
114 client (OSM)
115 server (Tiller)
116
beierlmf52cb7c2020-04-21 16:36:35 -0400117 :param k8s_creds: credentials to access a given K8s cluster, i.e. a valid
118 '.kube/config'
119 :param namespace: optional namespace to be used for helm. By default,
120 'kube-system' will be used
garciadeblas54771fa2019-12-13 13:39:03 +0100121 :param reuse_cluster_uuid: existing cluster uuid for reuse
beierlmf52cb7c2020-04-21 16:36:35 -0400122 :return: uuid of the K8s cluster and True if connector has installed some
123 software in the cluster
garciadeblas54771fa2019-12-13 13:39:03 +0100124 (on error, an exception will be raised)
125 """
quilesj26c78a42019-10-28 18:10:42 +0100126
tiernof9bdac22020-06-25 15:48:52 +0000127 if reuse_cluster_uuid:
128 namespace_, cluster_id = self._get_namespace_cluster_id(reuse_cluster_uuid)
129 namespace = namespace_ or namespace
130 else:
131 cluster_id = str(uuid4())
132 cluster_uuid = "{}:{}".format(namespace, cluster_id)
quilesj26c78a42019-10-28 18:10:42 +0100133
tiernof9bdac22020-06-25 15:48:52 +0000134 self.log.debug("Initializing K8S Cluster {}. namespace: {}".format(cluster_id, namespace))
quilesj26c78a42019-10-28 18:10:42 +0100135
136 # create config filename
beierlmf52cb7c2020-04-21 16:36:35 -0400137 _kube_dir, helm_dir, config_filename, _cluster_dir = self._get_paths(
tiernof9bdac22020-06-25 15:48:52 +0000138 cluster_name=cluster_id, create_if_not_exist=True
beierlmf52cb7c2020-04-21 16:36:35 -0400139 )
tierno119f7232020-04-21 13:22:26 +0000140 with open(config_filename, "w") as f:
141 f.write(k8s_creds)
quilesj26c78a42019-10-28 18:10:42 +0100142
143 # check if tiller pod is up in cluster
beierlmf52cb7c2020-04-21 16:36:35 -0400144 command = "{} --kubeconfig={} --namespace={} get deployments".format(
145 self.kubectl_command, config_filename, namespace
146 )
147 output, _rc = await self._local_async_exec(
148 command=command, raise_exception_on_error=True
149 )
quilesj26c78a42019-10-28 18:10:42 +0100150
tierno119f7232020-04-21 13:22:26 +0000151 output_table = self._output_to_table(output=output)
quilesj26c78a42019-10-28 18:10:42 +0100152
153 # find 'tiller' pod in all pods
154 already_initialized = False
155 try:
156 for row in output_table:
beierlmf52cb7c2020-04-21 16:36:35 -0400157 if row[0].startswith("tiller-deploy"):
quilesj26c78a42019-10-28 18:10:42 +0100158 already_initialized = True
159 break
beierlmf52cb7c2020-04-21 16:36:35 -0400160 except Exception:
quilesj26c78a42019-10-28 18:10:42 +0100161 pass
162
163 # helm init
164 n2vc_installed_sw = False
165 if not already_initialized:
beierlmf52cb7c2020-04-21 16:36:35 -0400166 self.log.info(
tiernof9bdac22020-06-25 15:48:52 +0000167 "Initializing helm in client and server: {}".format(cluster_id)
beierlmf52cb7c2020-04-21 16:36:35 -0400168 )
tiernof9bdac22020-06-25 15:48:52 +0000169 command = "{} --kubeconfig={} --namespace kube-system create serviceaccount {}".format(
170 self.kubectl_command, config_filename, self.service_account)
171 _, _rc = await self._local_async_exec(command=command, raise_exception_on_error=False)
172
173 command = ("{} --kubeconfig={} create clusterrolebinding osm-tiller-cluster-rule "
174 "--clusterrole=cluster-admin --serviceaccount=kube-system:{}"
175 ).format(self.kubectl_command, config_filename, self.service_account)
176 _, _rc = await self._local_async_exec(command=command, raise_exception_on_error=False)
177
178 command = ("{} --kubeconfig={} --tiller-namespace={} --home={} --service-account {} "
179 "init").format(self._helm_command, config_filename, namespace, helm_dir,
180 self.service_account)
181 _, _rc = await self._local_async_exec(command=command, raise_exception_on_error=True)
quilesj26c78a42019-10-28 18:10:42 +0100182 n2vc_installed_sw = True
183 else:
184 # check client helm installation
beierlmf52cb7c2020-04-21 16:36:35 -0400185 check_file = helm_dir + "/repository/repositories.yaml"
tiernof9bdac22020-06-25 15:48:52 +0000186 if not self._check_file_exists(filename=check_file, exception_if_not_exists=False):
187 self.log.info("Initializing helm in client: {}".format(cluster_id))
beierlmf52cb7c2020-04-21 16:36:35 -0400188 command = (
189 "{} --kubeconfig={} --tiller-namespace={} "
190 "--home={} init --client-only"
191 ).format(self._helm_command, config_filename, namespace, helm_dir)
192 output, _rc = await self._local_async_exec(
193 command=command, raise_exception_on_error=True
194 )
quilesj26c78a42019-10-28 18:10:42 +0100195 else:
beierlmf52cb7c2020-04-21 16:36:35 -0400196 self.log.info("Helm client already initialized")
quilesj26c78a42019-10-28 18:10:42 +0100197
tiernof9bdac22020-06-25 15:48:52 +0000198 self.log.info("Cluster {} initialized".format(cluster_id))
quilesj26c78a42019-10-28 18:10:42 +0100199
200 return cluster_uuid, n2vc_installed_sw
201
202 async def repo_add(
beierlmf52cb7c2020-04-21 16:36:35 -0400203 self, cluster_uuid: str, name: str, url: str, repo_type: str = "chart"
quilesj26c78a42019-10-28 18:10:42 +0100204 ):
tiernof9bdac22020-06-25 15:48:52 +0000205 _, cluster_id = self._get_namespace_cluster_id(cluster_uuid)
206 self.log.debug("Cluster {}, adding {} repository {}. URL: {}".format(
207 cluster_id, repo_type, name, url))
quilesj26c78a42019-10-28 18:10:42 +0100208
209 # config filename
beierlmf52cb7c2020-04-21 16:36:35 -0400210 _kube_dir, helm_dir, config_filename, _cluster_dir = self._get_paths(
tiernof9bdac22020-06-25 15:48:52 +0000211 cluster_name=cluster_id, create_if_not_exist=True
beierlmf52cb7c2020-04-21 16:36:35 -0400212 )
quilesj26c78a42019-10-28 18:10:42 +0100213
214 # helm repo update
beierlmf52cb7c2020-04-21 16:36:35 -0400215 command = "{} --kubeconfig={} --home={} repo update".format(
216 self._helm_command, config_filename, helm_dir
217 )
218 self.log.debug("updating repo: {}".format(command))
quilesj26c78a42019-10-28 18:10:42 +0100219 await self._local_async_exec(command=command, raise_exception_on_error=False)
220
221 # helm repo add name url
beierlmf52cb7c2020-04-21 16:36:35 -0400222 command = "{} --kubeconfig={} --home={} repo add {} {}".format(
223 self._helm_command, config_filename, helm_dir, name, url
224 )
225 self.log.debug("adding repo: {}".format(command))
quilesj26c78a42019-10-28 18:10:42 +0100226 await self._local_async_exec(command=command, raise_exception_on_error=True)
227
beierlmf52cb7c2020-04-21 16:36:35 -0400228 async def repo_list(self, cluster_uuid: str) -> list:
quilesj26c78a42019-10-28 18:10:42 +0100229 """
230 Get the list of registered repositories
231
232 :return: list of registered repositories: [ (name, url) .... ]
233 """
234
tiernof9bdac22020-06-25 15:48:52 +0000235 _, cluster_id = self._get_namespace_cluster_id(cluster_uuid)
236 self.log.debug("list repositories for cluster {}".format(cluster_id))
quilesj26c78a42019-10-28 18:10:42 +0100237
238 # config filename
beierlmf52cb7c2020-04-21 16:36:35 -0400239 _kube_dir, helm_dir, config_filename, _cluster_dir = self._get_paths(
tiernof9bdac22020-06-25 15:48:52 +0000240 cluster_name=cluster_id, create_if_not_exist=True
beierlmf52cb7c2020-04-21 16:36:35 -0400241 )
quilesj26c78a42019-10-28 18:10:42 +0100242
beierlmf52cb7c2020-04-21 16:36:35 -0400243 command = "{} --kubeconfig={} --home={} repo list --output yaml".format(
244 self._helm_command, config_filename, helm_dir
245 )
quilesj26c78a42019-10-28 18:10:42 +0100246
beierlmf52cb7c2020-04-21 16:36:35 -0400247 output, _rc = await self._local_async_exec(
248 command=command, raise_exception_on_error=True
249 )
quilesj26c78a42019-10-28 18:10:42 +0100250 if output and len(output) > 0:
251 return yaml.load(output, Loader=yaml.SafeLoader)
252 else:
253 return []
254
beierlmf52cb7c2020-04-21 16:36:35 -0400255 async def repo_remove(self, cluster_uuid: str, name: str):
quilesj26c78a42019-10-28 18:10:42 +0100256 """
257 Remove a repository from OSM
258
tiernof9bdac22020-06-25 15:48:52 +0000259 :param cluster_uuid: the cluster or 'namespace:cluster'
quilesj26c78a42019-10-28 18:10:42 +0100260 :param name: repo name in OSM
261 :return: True if successful
262 """
263
tiernof9bdac22020-06-25 15:48:52 +0000264 _, cluster_id = self._get_namespace_cluster_id(cluster_uuid)
265 self.log.debug("list repositories for cluster {}".format(cluster_id))
quilesj26c78a42019-10-28 18:10:42 +0100266
267 # config filename
beierlmf52cb7c2020-04-21 16:36:35 -0400268 _kube_dir, helm_dir, config_filename, _cluster_dir = self._get_paths(
tiernof9bdac22020-06-25 15:48:52 +0000269 cluster_name=cluster_id, create_if_not_exist=True
beierlmf52cb7c2020-04-21 16:36:35 -0400270 )
quilesj26c78a42019-10-28 18:10:42 +0100271
beierlmf52cb7c2020-04-21 16:36:35 -0400272 command = "{} --kubeconfig={} --home={} repo remove {}".format(
273 self._helm_command, config_filename, helm_dir, name
274 )
quilesj26c78a42019-10-28 18:10:42 +0100275
276 await self._local_async_exec(command=command, raise_exception_on_error=True)
277
278 async def reset(
beierlmf52cb7c2020-04-21 16:36:35 -0400279 self, cluster_uuid: str, force: bool = False, uninstall_sw: bool = False
quilesj26c78a42019-10-28 18:10:42 +0100280 ) -> bool:
281
tiernof9bdac22020-06-25 15:48:52 +0000282 namespace, cluster_id = self._get_namespace_cluster_id(cluster_uuid)
tierno4d9facc2020-07-14 10:29:00 +0000283 self.log.debug("Resetting K8s environment. cluster uuid: {} uninstall={}"
284 .format(cluster_id, uninstall_sw))
quilesj26c78a42019-10-28 18:10:42 +0100285
286 # get kube and helm directories
beierlmf52cb7c2020-04-21 16:36:35 -0400287 _kube_dir, helm_dir, config_filename, _cluster_dir = self._get_paths(
tiernof9bdac22020-06-25 15:48:52 +0000288 cluster_name=cluster_id, create_if_not_exist=False
beierlmf52cb7c2020-04-21 16:36:35 -0400289 )
quilesj26c78a42019-10-28 18:10:42 +0100290
tierno4d9facc2020-07-14 10:29:00 +0000291 # uninstall releases if needed.
292 if uninstall_sw:
293 releases = await self.instances_list(cluster_uuid=cluster_uuid)
294 if len(releases) > 0:
295 if force:
296 for r in releases:
297 try:
298 kdu_instance = r.get("Name")
299 chart = r.get("Chart")
300 self.log.debug(
301 "Uninstalling {} -> {}".format(chart, kdu_instance)
302 )
303 await self.uninstall(
304 cluster_uuid=cluster_uuid, kdu_instance=kdu_instance
305 )
306 except Exception as e:
307 self.log.error(
308 "Error uninstalling release {}: {}".format(kdu_instance, e)
309 )
310 else:
311 msg = (
312 "Cluster uuid: {} has releases and not force. Leaving K8s helm environment"
313 ).format(cluster_id)
314 self.log.warn(msg)
315 uninstall_sw = False # Allow to remove k8s cluster without removing Tiller
quilesj26c78a42019-10-28 18:10:42 +0100316
317 if uninstall_sw:
318
tiernof9bdac22020-06-25 15:48:52 +0000319 self.log.debug("Uninstalling tiller from cluster {}".format(cluster_id))
quilesj26c78a42019-10-28 18:10:42 +0100320
tiernof9bdac22020-06-25 15:48:52 +0000321 if not namespace:
322 # find namespace for tiller pod
323 command = "{} --kubeconfig={} get deployments --all-namespaces".format(
324 self.kubectl_command, config_filename
beierlmf52cb7c2020-04-21 16:36:35 -0400325 )
tiernof9bdac22020-06-25 15:48:52 +0000326 output, _rc = await self._local_async_exec(
beierlmf52cb7c2020-04-21 16:36:35 -0400327 command=command, raise_exception_on_error=False
328 )
tiernof9bdac22020-06-25 15:48:52 +0000329 output_table = K8sHelmConnector._output_to_table(output=output)
330 namespace = None
331 for r in output_table:
332 try:
333 if "tiller-deploy" in r[1]:
334 namespace = r[0]
335 break
336 except Exception:
337 pass
338 else:
339 msg = "Tiller deployment not found in cluster {}".format(cluster_id)
340 self.log.error(msg)
quilesj26c78a42019-10-28 18:10:42 +0100341
tiernof9bdac22020-06-25 15:48:52 +0000342 self.log.debug("namespace for tiller: {}".format(namespace))
343
344 if namespace:
quilesj26c78a42019-10-28 18:10:42 +0100345 # uninstall tiller from cluster
beierlmf52cb7c2020-04-21 16:36:35 -0400346 self.log.debug(
tiernof9bdac22020-06-25 15:48:52 +0000347 "Uninstalling tiller from cluster {}".format(cluster_id)
beierlmf52cb7c2020-04-21 16:36:35 -0400348 )
349 command = "{} --kubeconfig={} --home={} reset".format(
350 self._helm_command, config_filename, helm_dir
351 )
352 self.log.debug("resetting: {}".format(command))
353 output, _rc = await self._local_async_exec(
354 command=command, raise_exception_on_error=True
355 )
tiernof9bdac22020-06-25 15:48:52 +0000356 # Delete clusterrolebinding and serviceaccount.
357 # Ignore if errors for backward compatibility
358 command = ("{} --kubeconfig={} delete clusterrolebinding.rbac.authorization.k8s."
359 "io/osm-tiller-cluster-rule").format(self.kubectl_command,
360 config_filename)
361 output, _rc = await self._local_async_exec(command=command,
362 raise_exception_on_error=False)
363 command = "{} --kubeconfig={} --namespace kube-system delete serviceaccount/{}".\
364 format(self.kubectl_command, config_filename, self.service_account)
365 output, _rc = await self._local_async_exec(command=command,
366 raise_exception_on_error=False)
367
quilesj26c78a42019-10-28 18:10:42 +0100368 else:
beierlmf52cb7c2020-04-21 16:36:35 -0400369 self.log.debug("namespace not found")
quilesj26c78a42019-10-28 18:10:42 +0100370
371 # delete cluster directory
tiernof9bdac22020-06-25 15:48:52 +0000372 direct = self.fs.path + "/" + cluster_id
beierlmf52cb7c2020-04-21 16:36:35 -0400373 self.log.debug("Removing directory {}".format(direct))
374 shutil.rmtree(direct, ignore_errors=True)
quilesj26c78a42019-10-28 18:10:42 +0100375
376 return True
377
378 async def install(
beierlmf52cb7c2020-04-21 16:36:35 -0400379 self,
380 cluster_uuid: str,
381 kdu_model: str,
382 atomic: bool = True,
383 timeout: float = 300,
384 params: dict = None,
385 db_dict: dict = None,
386 kdu_name: str = None,
387 namespace: str = None,
quilesj26c78a42019-10-28 18:10:42 +0100388 ):
389
tiernof9bdac22020-06-25 15:48:52 +0000390 _, cluster_id = self._get_namespace_cluster_id(cluster_uuid)
391 self.log.debug("installing {} in cluster {}".format(kdu_model, cluster_id))
quilesj26c78a42019-10-28 18:10:42 +0100392
quilesj26c78a42019-10-28 18:10:42 +0100393 # config filename
beierlmf52cb7c2020-04-21 16:36:35 -0400394 _kube_dir, helm_dir, config_filename, _cluster_dir = self._get_paths(
tiernof9bdac22020-06-25 15:48:52 +0000395 cluster_name=cluster_id, create_if_not_exist=True
beierlmf52cb7c2020-04-21 16:36:35 -0400396 )
quilesj26c78a42019-10-28 18:10:42 +0100397
398 # params to str
quilesjcda5f412019-11-18 11:32:12 +0100399 # params_str = K8sHelmConnector._params_to_set_option(params)
beierlmf52cb7c2020-04-21 16:36:35 -0400400 params_str, file_to_delete = self._params_to_file_option(
tiernof9bdac22020-06-25 15:48:52 +0000401 cluster_id=cluster_id, params=params
beierlmf52cb7c2020-04-21 16:36:35 -0400402 )
quilesj26c78a42019-10-28 18:10:42 +0100403
beierlmf52cb7c2020-04-21 16:36:35 -0400404 timeout_str = ""
quilesj26c78a42019-10-28 18:10:42 +0100405 if timeout:
beierlmf52cb7c2020-04-21 16:36:35 -0400406 timeout_str = "--timeout {}".format(timeout)
quilesj26c78a42019-10-28 18:10:42 +0100407
408 # atomic
beierlmf52cb7c2020-04-21 16:36:35 -0400409 atomic_str = ""
quilesj26c78a42019-10-28 18:10:42 +0100410 if atomic:
beierlmf52cb7c2020-04-21 16:36:35 -0400411 atomic_str = "--atomic"
tierno53555f62020-04-07 11:08:16 +0000412 # namespace
beierlmf52cb7c2020-04-21 16:36:35 -0400413 namespace_str = ""
tierno53555f62020-04-07 11:08:16 +0000414 if namespace:
415 namespace_str = "--namespace {}".format(namespace)
quilesj26c78a42019-10-28 18:10:42 +0100416
417 # version
beierlmf52cb7c2020-04-21 16:36:35 -0400418 version_str = ""
419 if ":" in kdu_model:
420 parts = kdu_model.split(sep=":")
quilesj26c78a42019-10-28 18:10:42 +0100421 if len(parts) == 2:
beierlmf52cb7c2020-04-21 16:36:35 -0400422 version_str = "--version {}".format(parts[1])
quilesj26c78a42019-10-28 18:10:42 +0100423 kdu_model = parts[0]
424
quilesja6748412019-12-04 07:51:26 +0000425 # generate a name for the release. Then, check if already exists
quilesj26c78a42019-10-28 18:10:42 +0100426 kdu_instance = None
427 while kdu_instance is None:
428 kdu_instance = K8sHelmConnector._generate_release_name(kdu_model)
429 try:
430 result = await self._status_kdu(
tiernof9bdac22020-06-25 15:48:52 +0000431 cluster_id=cluster_id,
quilesj26c78a42019-10-28 18:10:42 +0100432 kdu_instance=kdu_instance,
beierlmf52cb7c2020-04-21 16:36:35 -0400433 show_error_log=False,
quilesj26c78a42019-10-28 18:10:42 +0100434 )
435 if result is not None:
436 # instance already exists: generate a new one
437 kdu_instance = None
tierno601697a2020-02-04 15:26:25 +0000438 except K8sException:
439 pass
quilesj26c78a42019-10-28 18:10:42 +0100440
441 # helm repo install
beierlmf52cb7c2020-04-21 16:36:35 -0400442 command = (
443 "{helm} install {atomic} --output yaml --kubeconfig={config} --home={dir} "
444 "{params} {timeout} --name={name} {ns} {model} {ver}".format(
445 helm=self._helm_command,
446 atomic=atomic_str,
447 config=config_filename,
448 dir=helm_dir,
449 params=params_str,
450 timeout=timeout_str,
451 name=kdu_instance,
452 ns=namespace_str,
453 model=kdu_model,
454 ver=version_str,
455 )
456 )
457 self.log.debug("installing: {}".format(command))
quilesj26c78a42019-10-28 18:10:42 +0100458
459 if atomic:
460 # exec helm in a task
461 exec_task = asyncio.ensure_future(
beierlmf52cb7c2020-04-21 16:36:35 -0400462 coro_or_future=self._local_async_exec(
463 command=command, raise_exception_on_error=False
464 )
quilesj26c78a42019-10-28 18:10:42 +0100465 )
lloretgalleg65ddf852020-02-20 12:01:17 +0100466
quilesj26c78a42019-10-28 18:10:42 +0100467 # write status in another task
468 status_task = asyncio.ensure_future(
469 coro_or_future=self._store_status(
tiernof9bdac22020-06-25 15:48:52 +0000470 cluster_id=cluster_id,
quilesj26c78a42019-10-28 18:10:42 +0100471 kdu_instance=kdu_instance,
472 db_dict=db_dict,
beierlmf52cb7c2020-04-21 16:36:35 -0400473 operation="install",
474 run_once=False,
quilesj26c78a42019-10-28 18:10:42 +0100475 )
476 )
477
478 # wait for execution task
479 await asyncio.wait([exec_task])
480
481 # cancel status task
482 status_task.cancel()
483
484 output, rc = exec_task.result()
485
486 else:
487
beierlmf52cb7c2020-04-21 16:36:35 -0400488 output, rc = await self._local_async_exec(
489 command=command, raise_exception_on_error=False
490 )
quilesj26c78a42019-10-28 18:10:42 +0100491
quilesjcda5f412019-11-18 11:32:12 +0100492 # remove temporal values yaml file
493 if file_to_delete:
494 os.remove(file_to_delete)
495
quilesj26c78a42019-10-28 18:10:42 +0100496 # write final status
497 await self._store_status(
tiernof9bdac22020-06-25 15:48:52 +0000498 cluster_id=cluster_id,
quilesj26c78a42019-10-28 18:10:42 +0100499 kdu_instance=kdu_instance,
500 db_dict=db_dict,
beierlmf52cb7c2020-04-21 16:36:35 -0400501 operation="install",
quilesj26c78a42019-10-28 18:10:42 +0100502 run_once=True,
beierlmf52cb7c2020-04-21 16:36:35 -0400503 check_every=0,
quilesj26c78a42019-10-28 18:10:42 +0100504 )
505
506 if rc != 0:
beierlmf52cb7c2020-04-21 16:36:35 -0400507 msg = "Error executing command: {}\nOutput: {}".format(command, output)
Dominik Fleischmannf9bed352020-02-27 10:04:34 +0100508 self.log.error(msg)
quilesja6748412019-12-04 07:51:26 +0000509 raise K8sException(msg)
quilesj26c78a42019-10-28 18:10:42 +0100510
beierlmf52cb7c2020-04-21 16:36:35 -0400511 self.log.debug("Returning kdu_instance {}".format(kdu_instance))
quilesj26c78a42019-10-28 18:10:42 +0100512 return kdu_instance
513
beierlmf52cb7c2020-04-21 16:36:35 -0400514 async def instances_list(self, cluster_uuid: str) -> list:
quilesj26c78a42019-10-28 18:10:42 +0100515 """
516 returns a list of deployed releases in a cluster
517
tiernof9bdac22020-06-25 15:48:52 +0000518 :param cluster_uuid: the 'cluster' or 'namespace:cluster'
quilesj26c78a42019-10-28 18:10:42 +0100519 :return:
520 """
521
tiernof9bdac22020-06-25 15:48:52 +0000522 _, cluster_id = self._get_namespace_cluster_id(cluster_uuid)
523 self.log.debug("list releases for cluster {}".format(cluster_id))
quilesj26c78a42019-10-28 18:10:42 +0100524
525 # config filename
beierlmf52cb7c2020-04-21 16:36:35 -0400526 _kube_dir, helm_dir, config_filename, _cluster_dir = self._get_paths(
tiernof9bdac22020-06-25 15:48:52 +0000527 cluster_name=cluster_id, create_if_not_exist=True
beierlmf52cb7c2020-04-21 16:36:35 -0400528 )
quilesj26c78a42019-10-28 18:10:42 +0100529
beierlmf52cb7c2020-04-21 16:36:35 -0400530 command = "{} --kubeconfig={} --home={} list --output yaml".format(
531 self._helm_command, config_filename, helm_dir
532 )
quilesj26c78a42019-10-28 18:10:42 +0100533
beierlmf52cb7c2020-04-21 16:36:35 -0400534 output, _rc = await self._local_async_exec(
535 command=command, raise_exception_on_error=True
536 )
quilesj26c78a42019-10-28 18:10:42 +0100537
538 if output and len(output) > 0:
beierlmf52cb7c2020-04-21 16:36:35 -0400539 return yaml.load(output, Loader=yaml.SafeLoader).get("Releases")
quilesj26c78a42019-10-28 18:10:42 +0100540 else:
541 return []
542
543 async def upgrade(
beierlmf52cb7c2020-04-21 16:36:35 -0400544 self,
545 cluster_uuid: str,
546 kdu_instance: str,
547 kdu_model: str = None,
548 atomic: bool = True,
549 timeout: float = 300,
550 params: dict = None,
551 db_dict: dict = None,
quilesj26c78a42019-10-28 18:10:42 +0100552 ):
553
tiernof9bdac22020-06-25 15:48:52 +0000554 _, cluster_id = self._get_namespace_cluster_id(cluster_uuid)
555 self.log.debug("upgrading {} in cluster {}".format(kdu_model, cluster_id))
quilesj26c78a42019-10-28 18:10:42 +0100556
quilesj26c78a42019-10-28 18:10:42 +0100557 # config filename
beierlmf52cb7c2020-04-21 16:36:35 -0400558 _kube_dir, helm_dir, config_filename, _cluster_dir = self._get_paths(
tiernof9bdac22020-06-25 15:48:52 +0000559 cluster_name=cluster_id, create_if_not_exist=True
beierlmf52cb7c2020-04-21 16:36:35 -0400560 )
quilesj26c78a42019-10-28 18:10:42 +0100561
562 # params to str
quilesjcda5f412019-11-18 11:32:12 +0100563 # params_str = K8sHelmConnector._params_to_set_option(params)
beierlmf52cb7c2020-04-21 16:36:35 -0400564 params_str, file_to_delete = self._params_to_file_option(
tiernof9bdac22020-06-25 15:48:52 +0000565 cluster_id=cluster_id, params=params
beierlmf52cb7c2020-04-21 16:36:35 -0400566 )
quilesj26c78a42019-10-28 18:10:42 +0100567
beierlmf52cb7c2020-04-21 16:36:35 -0400568 timeout_str = ""
quilesj26c78a42019-10-28 18:10:42 +0100569 if timeout:
beierlmf52cb7c2020-04-21 16:36:35 -0400570 timeout_str = "--timeout {}".format(timeout)
quilesj26c78a42019-10-28 18:10:42 +0100571
572 # atomic
beierlmf52cb7c2020-04-21 16:36:35 -0400573 atomic_str = ""
quilesj26c78a42019-10-28 18:10:42 +0100574 if atomic:
beierlmf52cb7c2020-04-21 16:36:35 -0400575 atomic_str = "--atomic"
quilesj26c78a42019-10-28 18:10:42 +0100576
577 # version
beierlmf52cb7c2020-04-21 16:36:35 -0400578 version_str = ""
579 if kdu_model and ":" in kdu_model:
580 parts = kdu_model.split(sep=":")
quilesj26c78a42019-10-28 18:10:42 +0100581 if len(parts) == 2:
beierlmf52cb7c2020-04-21 16:36:35 -0400582 version_str = "--version {}".format(parts[1])
quilesj26c78a42019-10-28 18:10:42 +0100583 kdu_model = parts[0]
584
585 # helm repo upgrade
beierlmf52cb7c2020-04-21 16:36:35 -0400586 command = (
587 "{} upgrade {} --output yaml --kubeconfig={} " "--home={} {} {} {} {} {}"
588 ).format(
589 self._helm_command,
590 atomic_str,
591 config_filename,
592 helm_dir,
593 params_str,
594 timeout_str,
595 kdu_instance,
596 kdu_model,
597 version_str,
598 )
599 self.log.debug("upgrading: {}".format(command))
quilesj26c78a42019-10-28 18:10:42 +0100600
601 if atomic:
602
603 # exec helm in a task
604 exec_task = asyncio.ensure_future(
beierlmf52cb7c2020-04-21 16:36:35 -0400605 coro_or_future=self._local_async_exec(
606 command=command, raise_exception_on_error=False
607 )
quilesj26c78a42019-10-28 18:10:42 +0100608 )
609 # write status in another task
610 status_task = asyncio.ensure_future(
611 coro_or_future=self._store_status(
tiernof9bdac22020-06-25 15:48:52 +0000612 cluster_id=cluster_id,
quilesj26c78a42019-10-28 18:10:42 +0100613 kdu_instance=kdu_instance,
614 db_dict=db_dict,
beierlmf52cb7c2020-04-21 16:36:35 -0400615 operation="upgrade",
616 run_once=False,
quilesj26c78a42019-10-28 18:10:42 +0100617 )
618 )
619
620 # wait for execution task
quilesj1be06302019-11-29 11:17:11 +0000621 await asyncio.wait([exec_task])
quilesj26c78a42019-10-28 18:10:42 +0100622
623 # cancel status task
624 status_task.cancel()
625 output, rc = exec_task.result()
626
627 else:
628
beierlmf52cb7c2020-04-21 16:36:35 -0400629 output, rc = await self._local_async_exec(
630 command=command, raise_exception_on_error=False
631 )
quilesj26c78a42019-10-28 18:10:42 +0100632
quilesjcda5f412019-11-18 11:32:12 +0100633 # remove temporal values yaml file
634 if file_to_delete:
635 os.remove(file_to_delete)
636
quilesj26c78a42019-10-28 18:10:42 +0100637 # write final status
638 await self._store_status(
tiernof9bdac22020-06-25 15:48:52 +0000639 cluster_id=cluster_id,
quilesj26c78a42019-10-28 18:10:42 +0100640 kdu_instance=kdu_instance,
641 db_dict=db_dict,
beierlmf52cb7c2020-04-21 16:36:35 -0400642 operation="upgrade",
quilesj26c78a42019-10-28 18:10:42 +0100643 run_once=True,
beierlmf52cb7c2020-04-21 16:36:35 -0400644 check_every=0,
quilesj26c78a42019-10-28 18:10:42 +0100645 )
646
647 if rc != 0:
beierlmf52cb7c2020-04-21 16:36:35 -0400648 msg = "Error executing command: {}\nOutput: {}".format(command, output)
Dominik Fleischmannf9bed352020-02-27 10:04:34 +0100649 self.log.error(msg)
quilesja6748412019-12-04 07:51:26 +0000650 raise K8sException(msg)
quilesj26c78a42019-10-28 18:10:42 +0100651
652 # return new revision number
beierlmf52cb7c2020-04-21 16:36:35 -0400653 instance = await self.get_instance_info(
654 cluster_uuid=cluster_uuid, kdu_instance=kdu_instance
655 )
quilesj26c78a42019-10-28 18:10:42 +0100656 if instance:
beierlmf52cb7c2020-04-21 16:36:35 -0400657 revision = int(instance.get("Revision"))
658 self.log.debug("New revision: {}".format(revision))
quilesj26c78a42019-10-28 18:10:42 +0100659 return revision
660 else:
661 return 0
662
663 async def rollback(
beierlmf52cb7c2020-04-21 16:36:35 -0400664 self, cluster_uuid: str, kdu_instance: str, revision=0, db_dict: dict = None
quilesj26c78a42019-10-28 18:10:42 +0100665 ):
666
tiernof9bdac22020-06-25 15:48:52 +0000667 _, cluster_id = self._get_namespace_cluster_id(cluster_uuid)
beierlmf52cb7c2020-04-21 16:36:35 -0400668 self.log.debug(
669 "rollback kdu_instance {} to revision {} from cluster {}".format(
tiernof9bdac22020-06-25 15:48:52 +0000670 kdu_instance, revision, cluster_id
beierlmf52cb7c2020-04-21 16:36:35 -0400671 )
672 )
quilesj26c78a42019-10-28 18:10:42 +0100673
674 # config filename
beierlmf52cb7c2020-04-21 16:36:35 -0400675 _kube_dir, helm_dir, config_filename, _cluster_dir = self._get_paths(
tiernof9bdac22020-06-25 15:48:52 +0000676 cluster_name=cluster_id, create_if_not_exist=True
beierlmf52cb7c2020-04-21 16:36:35 -0400677 )
quilesj26c78a42019-10-28 18:10:42 +0100678
beierlmf52cb7c2020-04-21 16:36:35 -0400679 command = "{} rollback --kubeconfig={} --home={} {} {} --wait".format(
680 self._helm_command, config_filename, helm_dir, kdu_instance, revision
681 )
quilesj26c78a42019-10-28 18:10:42 +0100682
683 # exec helm in a task
684 exec_task = asyncio.ensure_future(
beierlmf52cb7c2020-04-21 16:36:35 -0400685 coro_or_future=self._local_async_exec(
686 command=command, raise_exception_on_error=False
687 )
quilesj26c78a42019-10-28 18:10:42 +0100688 )
689 # write status in another task
690 status_task = asyncio.ensure_future(
691 coro_or_future=self._store_status(
tiernof9bdac22020-06-25 15:48:52 +0000692 cluster_id=cluster_id,
quilesj26c78a42019-10-28 18:10:42 +0100693 kdu_instance=kdu_instance,
694 db_dict=db_dict,
beierlmf52cb7c2020-04-21 16:36:35 -0400695 operation="rollback",
696 run_once=False,
quilesj26c78a42019-10-28 18:10:42 +0100697 )
698 )
699
700 # wait for execution task
701 await asyncio.wait([exec_task])
702
703 # cancel status task
704 status_task.cancel()
705
706 output, rc = exec_task.result()
707
708 # write final status
709 await self._store_status(
tiernof9bdac22020-06-25 15:48:52 +0000710 cluster_id=cluster_id,
quilesj26c78a42019-10-28 18:10:42 +0100711 kdu_instance=kdu_instance,
712 db_dict=db_dict,
beierlmf52cb7c2020-04-21 16:36:35 -0400713 operation="rollback",
quilesj26c78a42019-10-28 18:10:42 +0100714 run_once=True,
beierlmf52cb7c2020-04-21 16:36:35 -0400715 check_every=0,
quilesj26c78a42019-10-28 18:10:42 +0100716 )
717
718 if rc != 0:
beierlmf52cb7c2020-04-21 16:36:35 -0400719 msg = "Error executing command: {}\nOutput: {}".format(command, output)
Dominik Fleischmannf9bed352020-02-27 10:04:34 +0100720 self.log.error(msg)
quilesja6748412019-12-04 07:51:26 +0000721 raise K8sException(msg)
quilesj26c78a42019-10-28 18:10:42 +0100722
723 # return new revision number
beierlmf52cb7c2020-04-21 16:36:35 -0400724 instance = await self.get_instance_info(
725 cluster_uuid=cluster_uuid, kdu_instance=kdu_instance
726 )
quilesj26c78a42019-10-28 18:10:42 +0100727 if instance:
beierlmf52cb7c2020-04-21 16:36:35 -0400728 revision = int(instance.get("Revision"))
729 self.log.debug("New revision: {}".format(revision))
quilesj26c78a42019-10-28 18:10:42 +0100730 return revision
731 else:
732 return 0
733
beierlmf52cb7c2020-04-21 16:36:35 -0400734 async def uninstall(self, cluster_uuid: str, kdu_instance: str):
quilesj26c78a42019-10-28 18:10:42 +0100735 """
beierlmf52cb7c2020-04-21 16:36:35 -0400736 Removes an existing KDU instance. It would implicitly use the `delete` call
737 (this call would happen after all _terminate-config-primitive_ of the VNF
738 are invoked).
quilesj26c78a42019-10-28 18:10:42 +0100739
tiernof9bdac22020-06-25 15:48:52 +0000740 :param cluster_uuid: UUID of a K8s cluster known by OSM, or namespace:cluster_id
quilesj26c78a42019-10-28 18:10:42 +0100741 :param kdu_instance: unique name for the KDU instance to be deleted
742 :return: True if successful
743 """
744
tiernof9bdac22020-06-25 15:48:52 +0000745 _, cluster_id = self._get_namespace_cluster_id(cluster_uuid)
beierlmf52cb7c2020-04-21 16:36:35 -0400746 self.log.debug(
747 "uninstall kdu_instance {} from cluster {}".format(
tiernof9bdac22020-06-25 15:48:52 +0000748 kdu_instance, cluster_id
beierlmf52cb7c2020-04-21 16:36:35 -0400749 )
750 )
quilesj26c78a42019-10-28 18:10:42 +0100751
752 # config filename
beierlmf52cb7c2020-04-21 16:36:35 -0400753 _kube_dir, helm_dir, config_filename, _cluster_dir = self._get_paths(
tiernof9bdac22020-06-25 15:48:52 +0000754 cluster_name=cluster_id, create_if_not_exist=True
beierlmf52cb7c2020-04-21 16:36:35 -0400755 )
quilesj26c78a42019-10-28 18:10:42 +0100756
beierlmf52cb7c2020-04-21 16:36:35 -0400757 command = "{} --kubeconfig={} --home={} delete --purge {}".format(
758 self._helm_command, config_filename, helm_dir, kdu_instance
759 )
quilesj26c78a42019-10-28 18:10:42 +0100760
beierlmf52cb7c2020-04-21 16:36:35 -0400761 output, _rc = await self._local_async_exec(
762 command=command, raise_exception_on_error=True
763 )
quilesj26c78a42019-10-28 18:10:42 +0100764
765 return self._output_to_table(output)
766
Dominik Fleischmannfc796cc2020-04-06 14:51:00 +0200767 async def exec_primitive(
768 self,
769 cluster_uuid: str = None,
770 kdu_instance: str = None,
771 primitive_name: str = None,
772 timeout: float = 300,
773 params: dict = None,
774 db_dict: dict = None,
775 ) -> str:
776 """Exec primitive (Juju action)
777
tiernof9bdac22020-06-25 15:48:52 +0000778 :param cluster_uuid str: The UUID of the cluster or namespace:cluster
Dominik Fleischmannfc796cc2020-04-06 14:51:00 +0200779 :param kdu_instance str: The unique name of the KDU instance
780 :param primitive_name: Name of action that will be executed
781 :param timeout: Timeout for action execution
782 :param params: Dictionary of all the parameters needed for the action
783 :db_dict: Dictionary for any additional data
784
785 :return: Returns the output of the action
786 """
beierlmf52cb7c2020-04-21 16:36:35 -0400787 raise K8sException(
788 "KDUs deployed with Helm don't support actions "
789 "different from rollback, upgrade and status"
790 )
Dominik Fleischmannfc796cc2020-04-06 14:51:00 +0200791
beierlmf52cb7c2020-04-21 16:36:35 -0400792 async def inspect_kdu(self, kdu_model: str, repo_url: str = None) -> str:
quilesj26c78a42019-10-28 18:10:42 +0100793
beierlmf52cb7c2020-04-21 16:36:35 -0400794 self.log.debug(
795 "inspect kdu_model {} from (optional) repo: {}".format(kdu_model, repo_url)
796 )
quilesj26c78a42019-10-28 18:10:42 +0100797
beierlmf52cb7c2020-04-21 16:36:35 -0400798 return await self._exec_inspect_comand(
799 inspect_command="", kdu_model=kdu_model, repo_url=repo_url
800 )
quilesj26c78a42019-10-28 18:10:42 +0100801
beierlmf52cb7c2020-04-21 16:36:35 -0400802 async def values_kdu(self, kdu_model: str, repo_url: str = None) -> str:
quilesj26c78a42019-10-28 18:10:42 +0100803
beierlmf52cb7c2020-04-21 16:36:35 -0400804 self.log.debug(
805 "inspect kdu_model values {} from (optional) repo: {}".format(
806 kdu_model, repo_url
807 )
808 )
quilesj1be06302019-11-29 11:17:11 +0000809
beierlmf52cb7c2020-04-21 16:36:35 -0400810 return await self._exec_inspect_comand(
811 inspect_command="values", kdu_model=kdu_model, repo_url=repo_url
812 )
quilesj26c78a42019-10-28 18:10:42 +0100813
beierlmf52cb7c2020-04-21 16:36:35 -0400814 async def help_kdu(self, kdu_model: str, repo_url: str = None) -> str:
quilesj26c78a42019-10-28 18:10:42 +0100815
beierlmf52cb7c2020-04-21 16:36:35 -0400816 self.log.debug(
817 "inspect kdu_model {} readme.md from repo: {}".format(kdu_model, repo_url)
818 )
quilesj26c78a42019-10-28 18:10:42 +0100819
beierlmf52cb7c2020-04-21 16:36:35 -0400820 return await self._exec_inspect_comand(
821 inspect_command="readme", kdu_model=kdu_model, repo_url=repo_url
822 )
quilesj26c78a42019-10-28 18:10:42 +0100823
beierlmf52cb7c2020-04-21 16:36:35 -0400824 async def status_kdu(self, cluster_uuid: str, kdu_instance: str) -> str:
quilesj26c78a42019-10-28 18:10:42 +0100825
quilesj1be06302019-11-29 11:17:11 +0000826 # call internal function
tiernof9bdac22020-06-25 15:48:52 +0000827 _, cluster_id = self._get_namespace_cluster_id(cluster_uuid)
quilesj1be06302019-11-29 11:17:11 +0000828 return await self._status_kdu(
tiernof9bdac22020-06-25 15:48:52 +0000829 cluster_id=cluster_id,
quilesj1be06302019-11-29 11:17:11 +0000830 kdu_instance=kdu_instance,
831 show_error_log=True,
beierlmf52cb7c2020-04-21 16:36:35 -0400832 return_text=True,
quilesj1be06302019-11-29 11:17:11 +0000833 )
quilesj26c78a42019-10-28 18:10:42 +0100834
lloretgallegb8ba1af2020-06-29 14:18:30 +0000835 async def get_services(self,
836 cluster_uuid: str,
837 kdu_instance: str,
838 namespace: str) -> list:
839
tierno31dd6752020-07-17 11:47:32 +0000840 _, cluster_id = self._get_namespace_cluster_id(cluster_uuid)
lloretgallegb8ba1af2020-06-29 14:18:30 +0000841 self.log.debug(
842 "get_services: cluster_uuid: {}, kdu_instance: {}".format(
843 cluster_uuid, kdu_instance
844 )
845 )
846
847 status = await self._status_kdu(
tierno31dd6752020-07-17 11:47:32 +0000848 cluster_id, kdu_instance, return_text=False
lloretgallegb8ba1af2020-06-29 14:18:30 +0000849 )
850
851 service_names = self._parse_helm_status_service_info(status)
852 service_list = []
853 for service in service_names:
854 service = await self.get_service(cluster_uuid, service, namespace)
855 service_list.append(service)
856
857 return service_list
858
859 async def get_service(self,
860 cluster_uuid: str,
861 service_name: str,
862 namespace: str) -> object:
863
864 self.log.debug(
865 "get service, service_name: {}, namespace: {}, cluster_uuid: {}".format(
866 service_name, namespace, cluster_uuid)
867 )
868
869 # get paths
tierno31dd6752020-07-17 11:47:32 +0000870 _, cluster_id = self._get_namespace_cluster_id(cluster_uuid)
lloretgallegb8ba1af2020-06-29 14:18:30 +0000871 _kube_dir, helm_dir, config_filename, _cluster_dir = self._get_paths(
tierno31dd6752020-07-17 11:47:32 +0000872 cluster_name=cluster_id, create_if_not_exist=True
lloretgallegb8ba1af2020-06-29 14:18:30 +0000873 )
874
875 command = "{} --kubeconfig={} --namespace={} get service {} -o=yaml".format(
876 self.kubectl_command, config_filename, namespace, service_name
877 )
878
879 output, _rc = await self._local_async_exec(
880 command=command, raise_exception_on_error=True
881 )
882
883 data = yaml.load(output, Loader=yaml.SafeLoader)
884
885 service = {
886 "name": service_name,
887 "type": self._get_deep(data, ("spec", "type")),
888 "ports": self._get_deep(data, ("spec", "ports")),
889 "cluster_ip": self._get_deep(data, ("spec", "clusterIP"))
890 }
891 if service["type"] == "LoadBalancer":
892 ip_map_list = self._get_deep(data, ("status", "loadBalancer", "ingress"))
893 ip_list = [elem["ip"] for elem in ip_map_list]
894 service["external_ip"] = ip_list
895
896 return service
897
lloretgalleg65ddf852020-02-20 12:01:17 +0100898 async def synchronize_repos(self, cluster_uuid: str):
899
tiernof9bdac22020-06-25 15:48:52 +0000900 _, cluster_id = self._get_namespace_cluster_id(cluster_uuid)
Dominik Fleischmannf9bed352020-02-27 10:04:34 +0100901 self.log.debug("syncronize repos for cluster helm-id: {}",)
lloretgalleg65ddf852020-02-20 12:01:17 +0100902 try:
beierlmf52cb7c2020-04-21 16:36:35 -0400903 update_repos_timeout = (
904 300 # max timeout to sync a single repos, more than this is too much
905 )
906 db_k8scluster = self.db.get_one(
907 "k8sclusters", {"_admin.helm-chart.id": cluster_uuid}
908 )
lloretgalleg65ddf852020-02-20 12:01:17 +0100909 if db_k8scluster:
beierlmf52cb7c2020-04-21 16:36:35 -0400910 nbi_repo_list = (
911 db_k8scluster.get("_admin").get("helm_chart_repos") or []
912 )
913 cluster_repo_dict = (
914 db_k8scluster.get("_admin").get("helm_charts_added") or {}
915 )
lloretgalleg65ddf852020-02-20 12:01:17 +0100916 # elements that must be deleted
917 deleted_repo_list = []
918 added_repo_dict = {}
Dominik Fleischmannf9bed352020-02-27 10:04:34 +0100919 self.log.debug("helm_chart_repos: {}".format(nbi_repo_list))
920 self.log.debug("helm_charts_added: {}".format(cluster_repo_dict))
lloretgalleg65ddf852020-02-20 12:01:17 +0100921
922 # obtain repos to add: registered by nbi but not added
beierlmf52cb7c2020-04-21 16:36:35 -0400923 repos_to_add = [
924 repo for repo in nbi_repo_list if not cluster_repo_dict.get(repo)
925 ]
lloretgalleg65ddf852020-02-20 12:01:17 +0100926
927 # obtain repos to delete: added by cluster but not in nbi list
beierlmf52cb7c2020-04-21 16:36:35 -0400928 repos_to_delete = [
929 repo
930 for repo in cluster_repo_dict.keys()
931 if repo not in nbi_repo_list
932 ]
lloretgalleg65ddf852020-02-20 12:01:17 +0100933
beierlmf52cb7c2020-04-21 16:36:35 -0400934 # delete repos: must delete first then add because there may be
935 # different repos with same name but
lloretgalleg65ddf852020-02-20 12:01:17 +0100936 # different id and url
Dominik Fleischmannf9bed352020-02-27 10:04:34 +0100937 self.log.debug("repos to delete: {}".format(repos_to_delete))
lloretgalleg65ddf852020-02-20 12:01:17 +0100938 for repo_id in repos_to_delete:
939 # try to delete repos
940 try:
beierlmf52cb7c2020-04-21 16:36:35 -0400941 repo_delete_task = asyncio.ensure_future(
942 self.repo_remove(
943 cluster_uuid=cluster_uuid,
944 name=cluster_repo_dict[repo_id],
945 )
946 )
lloretgalleg65ddf852020-02-20 12:01:17 +0100947 await asyncio.wait_for(repo_delete_task, update_repos_timeout)
948 except Exception as e:
beierlmf52cb7c2020-04-21 16:36:35 -0400949 self.warning(
950 "Error deleting repo, id: {}, name: {}, err_msg: {}".format(
951 repo_id, cluster_repo_dict[repo_id], str(e)
952 )
953 )
954 # always add to the list of to_delete if there is an error
955 # because if is not there
956 # deleting raises error
lloretgalleg65ddf852020-02-20 12:01:17 +0100957 deleted_repo_list.append(repo_id)
958
959 # add repos
Dominik Fleischmannf9bed352020-02-27 10:04:34 +0100960 self.log.debug("repos to add: {}".format(repos_to_add))
lloretgalleg65ddf852020-02-20 12:01:17 +0100961 for repo_id in repos_to_add:
962 # obtain the repo data from the db
beierlmf52cb7c2020-04-21 16:36:35 -0400963 # if there is an error getting the repo in the database we will
964 # ignore this repo and continue
965 # because there is a possible race condition where the repo has
966 # been deleted while processing
lloretgalleg65ddf852020-02-20 12:01:17 +0100967 db_repo = self.db.get_one("k8srepos", {"_id": repo_id})
beierlmf52cb7c2020-04-21 16:36:35 -0400968 self.log.debug(
969 "obtained repo: id, {}, name: {}, url: {}".format(
970 repo_id, db_repo["name"], db_repo["url"]
971 )
972 )
lloretgalleg65ddf852020-02-20 12:01:17 +0100973 try:
beierlmf52cb7c2020-04-21 16:36:35 -0400974 repo_add_task = asyncio.ensure_future(
975 self.repo_add(
976 cluster_uuid=cluster_uuid,
977 name=db_repo["name"],
978 url=db_repo["url"],
979 repo_type="chart",
980 )
981 )
lloretgalleg65ddf852020-02-20 12:01:17 +0100982 await asyncio.wait_for(repo_add_task, update_repos_timeout)
983 added_repo_dict[repo_id] = db_repo["name"]
beierlmf52cb7c2020-04-21 16:36:35 -0400984 self.log.debug(
985 "added repo: id, {}, name: {}".format(
986 repo_id, db_repo["name"]
987 )
988 )
lloretgalleg65ddf852020-02-20 12:01:17 +0100989 except Exception as e:
beierlmf52cb7c2020-04-21 16:36:35 -0400990 # deal with error adding repo, adding a repo that already
991 # exists does not raise any error
992 # will not raise error because a wrong repos added by
993 # anyone could prevent instantiating any ns
994 self.log.error(
995 "Error adding repo id: {}, err_msg: {} ".format(
996 repo_id, repr(e)
997 )
998 )
lloretgalleg65ddf852020-02-20 12:01:17 +0100999
1000 return deleted_repo_list, added_repo_dict
1001
beierlmf52cb7c2020-04-21 16:36:35 -04001002 else: # else db_k8scluster does not exist
1003 raise K8sException(
1004 "k8cluster with helm-id : {} not found".format(cluster_uuid)
1005 )
lloretgalleg65ddf852020-02-20 12:01:17 +01001006
1007 except Exception as e:
Dominik Fleischmannf9bed352020-02-27 10:04:34 +01001008 self.log.error("Error synchronizing repos: {}".format(str(e)))
lloretgalleg65ddf852020-02-20 12:01:17 +01001009 raise K8sException("Error synchronizing repos")
1010
quilesj26c78a42019-10-28 18:10:42 +01001011 """
beierlmf52cb7c2020-04-21 16:36:35 -04001012 ####################################################################################
1013 ################################### P R I V A T E ##################################
1014 ####################################################################################
quilesj26c78a42019-10-28 18:10:42 +01001015 """
1016
quilesj1be06302019-11-29 11:17:11 +00001017 async def _exec_inspect_comand(
beierlmf52cb7c2020-04-21 16:36:35 -04001018 self, inspect_command: str, kdu_model: str, repo_url: str = None
quilesj1be06302019-11-29 11:17:11 +00001019 ):
1020
beierlmf52cb7c2020-04-21 16:36:35 -04001021 repo_str = ""
quilesj1be06302019-11-29 11:17:11 +00001022 if repo_url:
beierlmf52cb7c2020-04-21 16:36:35 -04001023 repo_str = " --repo {}".format(repo_url)
1024 idx = kdu_model.find("/")
quilesj1be06302019-11-29 11:17:11 +00001025 if idx >= 0:
1026 idx += 1
1027 kdu_model = kdu_model[idx:]
1028
beierlmf52cb7c2020-04-21 16:36:35 -04001029 inspect_command = "{} inspect {} {}{}".format(
1030 self._helm_command, inspect_command, kdu_model, repo_str
1031 )
1032 output, _rc = await self._local_async_exec(
1033 command=inspect_command, encode_utf8=True
1034 )
quilesj1be06302019-11-29 11:17:11 +00001035
1036 return output
1037
quilesj26c78a42019-10-28 18:10:42 +01001038 async def _status_kdu(
beierlmf52cb7c2020-04-21 16:36:35 -04001039 self,
tiernof9bdac22020-06-25 15:48:52 +00001040 cluster_id: str,
beierlmf52cb7c2020-04-21 16:36:35 -04001041 kdu_instance: str,
1042 show_error_log: bool = False,
1043 return_text: bool = False,
quilesj26c78a42019-10-28 18:10:42 +01001044 ):
1045
beierlmf52cb7c2020-04-21 16:36:35 -04001046 self.log.debug("status of kdu_instance {}".format(kdu_instance))
quilesj26c78a42019-10-28 18:10:42 +01001047
1048 # config filename
beierlmf52cb7c2020-04-21 16:36:35 -04001049 _kube_dir, helm_dir, config_filename, _cluster_dir = self._get_paths(
tiernof9bdac22020-06-25 15:48:52 +00001050 cluster_name=cluster_id, create_if_not_exist=True
beierlmf52cb7c2020-04-21 16:36:35 -04001051 )
quilesj26c78a42019-10-28 18:10:42 +01001052
beierlmf52cb7c2020-04-21 16:36:35 -04001053 command = "{} --kubeconfig={} --home={} status {} --output yaml".format(
1054 self._helm_command, config_filename, helm_dir, kdu_instance
1055 )
quilesj26c78a42019-10-28 18:10:42 +01001056
1057 output, rc = await self._local_async_exec(
1058 command=command,
1059 raise_exception_on_error=True,
beierlmf52cb7c2020-04-21 16:36:35 -04001060 show_error_log=show_error_log,
quilesj26c78a42019-10-28 18:10:42 +01001061 )
1062
quilesj1be06302019-11-29 11:17:11 +00001063 if return_text:
1064 return str(output)
1065
quilesj26c78a42019-10-28 18:10:42 +01001066 if rc != 0:
1067 return None
1068
1069 data = yaml.load(output, Loader=yaml.SafeLoader)
1070
1071 # remove field 'notes'
1072 try:
beierlmf52cb7c2020-04-21 16:36:35 -04001073 del data.get("info").get("status")["notes"]
quilesj26c78a42019-10-28 18:10:42 +01001074 except KeyError:
1075 pass
1076
1077 # parse field 'resources'
1078 try:
beierlmf52cb7c2020-04-21 16:36:35 -04001079 resources = str(data.get("info").get("status").get("resources"))
quilesj26c78a42019-10-28 18:10:42 +01001080 resource_table = self._output_to_table(resources)
beierlmf52cb7c2020-04-21 16:36:35 -04001081 data.get("info").get("status")["resources"] = resource_table
1082 except Exception:
quilesj26c78a42019-10-28 18:10:42 +01001083 pass
1084
1085 return data
1086
beierlmf52cb7c2020-04-21 16:36:35 -04001087 async def get_instance_info(self, cluster_uuid: str, kdu_instance: str):
quilesj26c78a42019-10-28 18:10:42 +01001088 instances = await self.instances_list(cluster_uuid=cluster_uuid)
1089 for instance in instances:
beierlmf52cb7c2020-04-21 16:36:35 -04001090 if instance.get("Name") == kdu_instance:
quilesj26c78a42019-10-28 18:10:42 +01001091 return instance
beierlmf52cb7c2020-04-21 16:36:35 -04001092 self.log.debug("Instance {} not found".format(kdu_instance))
quilesj26c78a42019-10-28 18:10:42 +01001093 return None
1094
1095 @staticmethod
beierlmf52cb7c2020-04-21 16:36:35 -04001096 def _generate_release_name(chart_name: str):
quilesjbc355a12020-01-23 09:28:26 +00001097 # check embeded chart (file or dir)
beierlmf52cb7c2020-04-21 16:36:35 -04001098 if chart_name.startswith("/"):
quilesjbc355a12020-01-23 09:28:26 +00001099 # extract file or directory name
beierlmf52cb7c2020-04-21 16:36:35 -04001100 chart_name = chart_name[chart_name.rfind("/") + 1 :]
quilesjbc355a12020-01-23 09:28:26 +00001101 # check URL
beierlmf52cb7c2020-04-21 16:36:35 -04001102 elif "://" in chart_name:
quilesjbc355a12020-01-23 09:28:26 +00001103 # extract last portion of URL
beierlmf52cb7c2020-04-21 16:36:35 -04001104 chart_name = chart_name[chart_name.rfind("/") + 1 :]
quilesjbc355a12020-01-23 09:28:26 +00001105
beierlmf52cb7c2020-04-21 16:36:35 -04001106 name = ""
quilesj26c78a42019-10-28 18:10:42 +01001107 for c in chart_name:
1108 if c.isalpha() or c.isnumeric():
1109 name += c
1110 else:
beierlmf52cb7c2020-04-21 16:36:35 -04001111 name += "-"
quilesj26c78a42019-10-28 18:10:42 +01001112 if len(name) > 35:
1113 name = name[0:35]
1114
1115 # if does not start with alpha character, prefix 'a'
1116 if not name[0].isalpha():
beierlmf52cb7c2020-04-21 16:36:35 -04001117 name = "a" + name
quilesj26c78a42019-10-28 18:10:42 +01001118
beierlmf52cb7c2020-04-21 16:36:35 -04001119 name += "-"
quilesj26c78a42019-10-28 18:10:42 +01001120
1121 def get_random_number():
1122 r = random.randrange(start=1, stop=99999999)
1123 s = str(r)
beierlmf52cb7c2020-04-21 16:36:35 -04001124 s = s.rjust(10, "0")
quilesj26c78a42019-10-28 18:10:42 +01001125 return s
1126
1127 name = name + get_random_number()
1128 return name.lower()
1129
1130 async def _store_status(
beierlmf52cb7c2020-04-21 16:36:35 -04001131 self,
tiernof9bdac22020-06-25 15:48:52 +00001132 cluster_id: str,
beierlmf52cb7c2020-04-21 16:36:35 -04001133 operation: str,
1134 kdu_instance: str,
1135 check_every: float = 10,
1136 db_dict: dict = None,
1137 run_once: bool = False,
quilesj26c78a42019-10-28 18:10:42 +01001138 ):
1139 while True:
1140 try:
1141 await asyncio.sleep(check_every)
tierno119f7232020-04-21 13:22:26 +00001142 detailed_status = await self._status_kdu(
tiernof9bdac22020-06-25 15:48:52 +00001143 cluster_id=cluster_id, kdu_instance=kdu_instance,
tierno119f7232020-04-21 13:22:26 +00001144 return_text=False
beierlmf52cb7c2020-04-21 16:36:35 -04001145 )
1146 status = detailed_status.get("info").get("Description")
tierno119f7232020-04-21 13:22:26 +00001147 self.log.debug('KDU {} STATUS: {}.'.format(kdu_instance, status))
quilesj26c78a42019-10-28 18:10:42 +01001148 # write status to db
1149 result = await self.write_app_status_to_db(
1150 db_dict=db_dict,
1151 status=str(status),
1152 detailed_status=str(detailed_status),
beierlmf52cb7c2020-04-21 16:36:35 -04001153 operation=operation,
1154 )
quilesj26c78a42019-10-28 18:10:42 +01001155 if not result:
beierlmf52cb7c2020-04-21 16:36:35 -04001156 self.log.info("Error writing in database. Task exiting...")
quilesj26c78a42019-10-28 18:10:42 +01001157 return
1158 except asyncio.CancelledError:
beierlmf52cb7c2020-04-21 16:36:35 -04001159 self.log.debug("Task cancelled")
quilesj26c78a42019-10-28 18:10:42 +01001160 return
1161 except Exception as e:
lloretgallegb8ba1af2020-06-29 14:18:30 +00001162 self.log.debug("_store_status exception: {}".format(str(e)), exc_info=True)
quilesj26c78a42019-10-28 18:10:42 +01001163 pass
1164 finally:
1165 if run_once:
1166 return
1167
tiernof9bdac22020-06-25 15:48:52 +00001168 async def _is_install_completed(self, cluster_id: str, kdu_instance: str) -> bool:
quilesj26c78a42019-10-28 18:10:42 +01001169
beierlmf52cb7c2020-04-21 16:36:35 -04001170 status = await self._status_kdu(
tiernof9bdac22020-06-25 15:48:52 +00001171 cluster_id=cluster_id, kdu_instance=kdu_instance, return_text=False
beierlmf52cb7c2020-04-21 16:36:35 -04001172 )
quilesj26c78a42019-10-28 18:10:42 +01001173
1174 # extract info.status.resources-> str
1175 # format:
1176 # ==> v1/Deployment
1177 # NAME READY UP-TO-DATE AVAILABLE AGE
1178 # halting-horse-mongodb 0/1 1 0 0s
1179 # halting-petit-mongodb 1/1 1 0 0s
1180 # blank line
beierlmf52cb7c2020-04-21 16:36:35 -04001181 resources = K8sHelmConnector._get_deep(status, ("info", "status", "resources"))
quilesj26c78a42019-10-28 18:10:42 +01001182
1183 # convert to table
1184 resources = K8sHelmConnector._output_to_table(resources)
1185
1186 num_lines = len(resources)
1187 index = 0
1188 while index < num_lines:
1189 try:
1190 line1 = resources[index]
1191 index += 1
1192 # find '==>' in column 0
beierlmf52cb7c2020-04-21 16:36:35 -04001193 if line1[0] == "==>":
quilesj26c78a42019-10-28 18:10:42 +01001194 line2 = resources[index]
1195 index += 1
1196 # find READY in column 1
beierlmf52cb7c2020-04-21 16:36:35 -04001197 if line2[1] == "READY":
quilesj26c78a42019-10-28 18:10:42 +01001198 # read next lines
1199 line3 = resources[index]
1200 index += 1
1201 while len(line3) > 1 and index < num_lines:
1202 ready_value = line3[1]
beierlmf52cb7c2020-04-21 16:36:35 -04001203 parts = ready_value.split(sep="/")
quilesj26c78a42019-10-28 18:10:42 +01001204 current = int(parts[0])
1205 total = int(parts[1])
1206 if current < total:
beierlmf52cb7c2020-04-21 16:36:35 -04001207 self.log.debug("NOT READY:\n {}".format(line3))
quilesj26c78a42019-10-28 18:10:42 +01001208 ready = False
1209 line3 = resources[index]
1210 index += 1
1211
beierlmf52cb7c2020-04-21 16:36:35 -04001212 except Exception:
quilesj26c78a42019-10-28 18:10:42 +01001213 pass
1214
1215 return ready
1216
lloretgallegb8ba1af2020-06-29 14:18:30 +00001217 def _parse_helm_status_service_info(self, status):
1218
1219 # extract info.status.resources-> str
1220 # format:
1221 # ==> v1/Deployment
1222 # NAME READY UP-TO-DATE AVAILABLE AGE
1223 # halting-horse-mongodb 0/1 1 0 0s
1224 # halting-petit-mongodb 1/1 1 0 0s
1225 # blank line
1226 resources = K8sHelmConnector._get_deep(status, ("info", "status", "resources"))
1227
1228 service_list = []
1229 first_line_skipped = service_found = False
1230 for line in resources:
1231 if not service_found:
1232 if len(line) >= 2 and line[0] == "==>" and line[1] == "v1/Service":
1233 service_found = True
1234 continue
1235 else:
1236 if len(line) >= 2 and line[0] == "==>":
1237 service_found = first_line_skipped = False
1238 continue
1239 if not line:
1240 continue
1241 if not first_line_skipped:
1242 first_line_skipped = True
1243 continue
1244 service_list.append(line[0])
1245
1246 return service_list
1247
quilesj26c78a42019-10-28 18:10:42 +01001248 @staticmethod
1249 def _get_deep(dictionary: dict, members: tuple):
1250 target = dictionary
1251 value = None
1252 try:
1253 for m in members:
1254 value = target.get(m)
1255 if not value:
1256 return None
1257 else:
1258 target = value
beierlmf52cb7c2020-04-21 16:36:35 -04001259 except Exception:
quilesj26c78a42019-10-28 18:10:42 +01001260 pass
1261 return value
1262
1263 # find key:value in several lines
1264 @staticmethod
1265 def _find_in_lines(p_lines: list, p_key: str) -> str:
1266 for line in p_lines:
1267 try:
beierlmf52cb7c2020-04-21 16:36:35 -04001268 if line.startswith(p_key + ":"):
1269 parts = line.split(":")
quilesj26c78a42019-10-28 18:10:42 +01001270 the_value = parts[1].strip()
1271 return the_value
beierlmf52cb7c2020-04-21 16:36:35 -04001272 except Exception:
quilesj26c78a42019-10-28 18:10:42 +01001273 # ignore it
1274 pass
1275 return None
1276
quilesjcda5f412019-11-18 11:32:12 +01001277 # params for use in -f file
1278 # returns values file option and filename (in order to delete it at the end)
tiernof9bdac22020-06-25 15:48:52 +00001279 def _params_to_file_option(self, cluster_id: str, params: dict) -> (str, str):
quilesjcda5f412019-11-18 11:32:12 +01001280
1281 if params and len(params) > 0:
tiernof9bdac22020-06-25 15:48:52 +00001282 self._get_paths(cluster_name=cluster_id, create_if_not_exist=True)
quilesjcda5f412019-11-18 11:32:12 +01001283
1284 def get_random_number():
1285 r = random.randrange(start=1, stop=99999999)
1286 s = str(r)
1287 while len(s) < 10:
beierlmf52cb7c2020-04-21 16:36:35 -04001288 s = "0" + s
quilesjcda5f412019-11-18 11:32:12 +01001289 return s
1290
1291 params2 = dict()
1292 for key in params:
1293 value = params.get(key)
beierlmf52cb7c2020-04-21 16:36:35 -04001294 if "!!yaml" in str(value):
quilesj1be06302019-11-29 11:17:11 +00001295 value = yaml.load(value[7:])
quilesjcda5f412019-11-18 11:32:12 +01001296 params2[key] = value
1297
beierlmf52cb7c2020-04-21 16:36:35 -04001298 values_file = get_random_number() + ".yaml"
1299 with open(values_file, "w") as stream:
quilesjcda5f412019-11-18 11:32:12 +01001300 yaml.dump(params2, stream, indent=4, default_flow_style=False)
1301
beierlmf52cb7c2020-04-21 16:36:35 -04001302 return "-f {}".format(values_file), values_file
quilesjcda5f412019-11-18 11:32:12 +01001303
beierlmf52cb7c2020-04-21 16:36:35 -04001304 return "", None
quilesjcda5f412019-11-18 11:32:12 +01001305
quilesj26c78a42019-10-28 18:10:42 +01001306 # params for use in --set option
1307 @staticmethod
1308 def _params_to_set_option(params: dict) -> str:
beierlmf52cb7c2020-04-21 16:36:35 -04001309 params_str = ""
quilesj26c78a42019-10-28 18:10:42 +01001310 if params and len(params) > 0:
1311 start = True
1312 for key in params:
1313 value = params.get(key, None)
1314 if value is not None:
1315 if start:
beierlmf52cb7c2020-04-21 16:36:35 -04001316 params_str += "--set "
quilesj26c78a42019-10-28 18:10:42 +01001317 start = False
1318 else:
beierlmf52cb7c2020-04-21 16:36:35 -04001319 params_str += ","
1320 params_str += "{}={}".format(key, value)
quilesj26c78a42019-10-28 18:10:42 +01001321 return params_str
1322
1323 @staticmethod
1324 def _output_to_lines(output: str) -> list:
1325 output_lines = list()
1326 lines = output.splitlines(keepends=False)
1327 for line in lines:
1328 line = line.strip()
1329 if len(line) > 0:
1330 output_lines.append(line)
1331 return output_lines
1332
1333 @staticmethod
1334 def _output_to_table(output: str) -> list:
1335 output_table = list()
1336 lines = output.splitlines(keepends=False)
1337 for line in lines:
beierlmf52cb7c2020-04-21 16:36:35 -04001338 line = line.replace("\t", " ")
quilesj26c78a42019-10-28 18:10:42 +01001339 line_list = list()
1340 output_table.append(line_list)
beierlmf52cb7c2020-04-21 16:36:35 -04001341 cells = line.split(sep=" ")
quilesj26c78a42019-10-28 18:10:42 +01001342 for cell in cells:
1343 cell = cell.strip()
1344 if len(cell) > 0:
1345 line_list.append(cell)
1346 return output_table
1347
beierlmf52cb7c2020-04-21 16:36:35 -04001348 def _get_paths(
1349 self, cluster_name: str, create_if_not_exist: bool = False
1350 ) -> (str, str, str, str):
quilesj26c78a42019-10-28 18:10:42 +01001351 """
1352 Returns kube and helm directories
1353
1354 :param cluster_name:
1355 :param create_if_not_exist:
quilesjcda5f412019-11-18 11:32:12 +01001356 :return: kube, helm directories, config filename and cluster dir.
1357 Raises exception if not exist and cannot create
quilesj26c78a42019-10-28 18:10:42 +01001358 """
1359
1360 base = self.fs.path
1361 if base.endswith("/") or base.endswith("\\"):
1362 base = base[:-1]
1363
1364 # base dir for cluster
beierlmf52cb7c2020-04-21 16:36:35 -04001365 cluster_dir = base + "/" + cluster_name
quilesj26c78a42019-10-28 18:10:42 +01001366 if create_if_not_exist and not os.path.exists(cluster_dir):
beierlmf52cb7c2020-04-21 16:36:35 -04001367 self.log.debug("Creating dir {}".format(cluster_dir))
quilesj26c78a42019-10-28 18:10:42 +01001368 os.makedirs(cluster_dir)
1369 if not os.path.exists(cluster_dir):
beierlmf52cb7c2020-04-21 16:36:35 -04001370 msg = "Base cluster dir {} does not exist".format(cluster_dir)
Dominik Fleischmannf9bed352020-02-27 10:04:34 +01001371 self.log.error(msg)
quilesja6748412019-12-04 07:51:26 +00001372 raise K8sException(msg)
quilesj26c78a42019-10-28 18:10:42 +01001373
1374 # kube dir
beierlmf52cb7c2020-04-21 16:36:35 -04001375 kube_dir = cluster_dir + "/" + ".kube"
quilesj26c78a42019-10-28 18:10:42 +01001376 if create_if_not_exist and not os.path.exists(kube_dir):
beierlmf52cb7c2020-04-21 16:36:35 -04001377 self.log.debug("Creating dir {}".format(kube_dir))
quilesj26c78a42019-10-28 18:10:42 +01001378 os.makedirs(kube_dir)
1379 if not os.path.exists(kube_dir):
beierlmf52cb7c2020-04-21 16:36:35 -04001380 msg = "Kube config dir {} does not exist".format(kube_dir)
Dominik Fleischmannf9bed352020-02-27 10:04:34 +01001381 self.log.error(msg)
quilesja6748412019-12-04 07:51:26 +00001382 raise K8sException(msg)
quilesj26c78a42019-10-28 18:10:42 +01001383
1384 # helm home dir
beierlmf52cb7c2020-04-21 16:36:35 -04001385 helm_dir = cluster_dir + "/" + ".helm"
quilesj26c78a42019-10-28 18:10:42 +01001386 if create_if_not_exist and not os.path.exists(helm_dir):
beierlmf52cb7c2020-04-21 16:36:35 -04001387 self.log.debug("Creating dir {}".format(helm_dir))
quilesj26c78a42019-10-28 18:10:42 +01001388 os.makedirs(helm_dir)
1389 if not os.path.exists(helm_dir):
beierlmf52cb7c2020-04-21 16:36:35 -04001390 msg = "Helm config dir {} does not exist".format(helm_dir)
Dominik Fleischmannf9bed352020-02-27 10:04:34 +01001391 self.log.error(msg)
quilesja6748412019-12-04 07:51:26 +00001392 raise K8sException(msg)
quilesj26c78a42019-10-28 18:10:42 +01001393
beierlmf52cb7c2020-04-21 16:36:35 -04001394 config_filename = kube_dir + "/config"
quilesjcda5f412019-11-18 11:32:12 +01001395 return kube_dir, helm_dir, config_filename, cluster_dir
quilesj26c78a42019-10-28 18:10:42 +01001396
1397 @staticmethod
beierlmf52cb7c2020-04-21 16:36:35 -04001398 def _remove_multiple_spaces(strobj):
1399 strobj = strobj.strip()
1400 while " " in strobj:
1401 strobj = strobj.replace(" ", " ")
1402 return strobj
quilesj26c78a42019-10-28 18:10:42 +01001403
beierlmf52cb7c2020-04-21 16:36:35 -04001404 def _local_exec(self, command: str) -> (str, int):
quilesj26c78a42019-10-28 18:10:42 +01001405 command = K8sHelmConnector._remove_multiple_spaces(command)
beierlmf52cb7c2020-04-21 16:36:35 -04001406 self.log.debug("Executing sync local command: {}".format(command))
quilesj26c78a42019-10-28 18:10:42 +01001407 # raise exception if fails
beierlmf52cb7c2020-04-21 16:36:35 -04001408 output = ""
quilesj26c78a42019-10-28 18:10:42 +01001409 try:
beierlmf52cb7c2020-04-21 16:36:35 -04001410 output = subprocess.check_output(
1411 command, shell=True, universal_newlines=True
1412 )
quilesj26c78a42019-10-28 18:10:42 +01001413 return_code = 0
Dominik Fleischmannf9bed352020-02-27 10:04:34 +01001414 self.log.debug(output)
beierlmf52cb7c2020-04-21 16:36:35 -04001415 except Exception:
quilesj26c78a42019-10-28 18:10:42 +01001416 return_code = 1
1417
1418 return output, return_code
1419
1420 async def _local_async_exec(
beierlmf52cb7c2020-04-21 16:36:35 -04001421 self,
1422 command: str,
1423 raise_exception_on_error: bool = False,
1424 show_error_log: bool = True,
1425 encode_utf8: bool = False,
quilesj26c78a42019-10-28 18:10:42 +01001426 ) -> (str, int):
1427
1428 command = K8sHelmConnector._remove_multiple_spaces(command)
beierlmf52cb7c2020-04-21 16:36:35 -04001429 self.log.debug("Executing async local command: {}".format(command))
quilesj26c78a42019-10-28 18:10:42 +01001430
1431 # split command
beierlmf52cb7c2020-04-21 16:36:35 -04001432 command = command.split(sep=" ")
quilesj26c78a42019-10-28 18:10:42 +01001433
1434 try:
1435 process = await asyncio.create_subprocess_exec(
beierlmf52cb7c2020-04-21 16:36:35 -04001436 *command, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE
quilesj26c78a42019-10-28 18:10:42 +01001437 )
1438
1439 # wait for command terminate
1440 stdout, stderr = await process.communicate()
1441
1442 return_code = process.returncode
1443
beierlmf52cb7c2020-04-21 16:36:35 -04001444 output = ""
quilesj26c78a42019-10-28 18:10:42 +01001445 if stdout:
beierlmf52cb7c2020-04-21 16:36:35 -04001446 output = stdout.decode("utf-8").strip()
quilesj1be06302019-11-29 11:17:11 +00001447 # output = stdout.decode()
quilesj26c78a42019-10-28 18:10:42 +01001448 if stderr:
beierlmf52cb7c2020-04-21 16:36:35 -04001449 output = stderr.decode("utf-8").strip()
quilesj1be06302019-11-29 11:17:11 +00001450 # output = stderr.decode()
quilesj26c78a42019-10-28 18:10:42 +01001451
1452 if return_code != 0 and show_error_log:
beierlmf52cb7c2020-04-21 16:36:35 -04001453 self.log.debug(
1454 "Return code (FAIL): {}\nOutput:\n{}".format(return_code, output)
1455 )
quilesj26c78a42019-10-28 18:10:42 +01001456 else:
beierlmf52cb7c2020-04-21 16:36:35 -04001457 self.log.debug("Return code: {}".format(return_code))
quilesj26c78a42019-10-28 18:10:42 +01001458
1459 if raise_exception_on_error and return_code != 0:
tierno601697a2020-02-04 15:26:25 +00001460 raise K8sException(output)
quilesj26c78a42019-10-28 18:10:42 +01001461
quilesj1be06302019-11-29 11:17:11 +00001462 if encode_utf8:
beierlmf52cb7c2020-04-21 16:36:35 -04001463 output = output.encode("utf-8").strip()
1464 output = str(output).replace("\\n", "\n")
quilesj1be06302019-11-29 11:17:11 +00001465
quilesj26c78a42019-10-28 18:10:42 +01001466 return output, return_code
1467
lloretgallegdd0cdee2020-02-26 10:00:16 +01001468 except asyncio.CancelledError:
1469 raise
tierno601697a2020-02-04 15:26:25 +00001470 except K8sException:
1471 raise
quilesj26c78a42019-10-28 18:10:42 +01001472 except Exception as e:
beierlmf52cb7c2020-04-21 16:36:35 -04001473 msg = "Exception executing command: {} -> {}".format(command, e)
Dominik Fleischmannf9bed352020-02-27 10:04:34 +01001474 self.log.error(msg)
quilesj32dc3c62020-01-23 16:30:04 +00001475 if raise_exception_on_error:
tierno601697a2020-02-04 15:26:25 +00001476 raise K8sException(e) from e
quilesj32dc3c62020-01-23 16:30:04 +00001477 else:
beierlmf52cb7c2020-04-21 16:36:35 -04001478 return "", -1
quilesj26c78a42019-10-28 18:10:42 +01001479
quilesj26c78a42019-10-28 18:10:42 +01001480 def _check_file_exists(self, filename: str, exception_if_not_exists: bool = False):
tierno8ff11992020-03-26 09:51:11 +00001481 # self.log.debug('Checking if file {} exists...'.format(filename))
quilesj26c78a42019-10-28 18:10:42 +01001482 if os.path.exists(filename):
1483 return True
1484 else:
beierlmf52cb7c2020-04-21 16:36:35 -04001485 msg = "File {} does not exist".format(filename)
quilesj26c78a42019-10-28 18:10:42 +01001486 if exception_if_not_exists:
tierno8ff11992020-03-26 09:51:11 +00001487 # self.log.error(msg)
quilesja6748412019-12-04 07:51:26 +00001488 raise K8sException(msg)