blob: 2e7442372aeb62c1d723c8940d7b5fddbbffce02 [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)
beierlmf52cb7c2020-04-21 16:36:35 -0400283 self.log.debug(
tiernof9bdac22020-06-25 15:48:52 +0000284 "Resetting K8s environment. cluster uuid: {}".format(cluster_id)
beierlmf52cb7c2020-04-21 16:36:35 -0400285 )
quilesj26c78a42019-10-28 18:10:42 +0100286
287 # get kube and helm directories
beierlmf52cb7c2020-04-21 16:36:35 -0400288 _kube_dir, helm_dir, config_filename, _cluster_dir = self._get_paths(
tiernof9bdac22020-06-25 15:48:52 +0000289 cluster_name=cluster_id, create_if_not_exist=False
beierlmf52cb7c2020-04-21 16:36:35 -0400290 )
quilesj26c78a42019-10-28 18:10:42 +0100291
292 # uninstall releases if needed
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:
beierlmf52cb7c2020-04-21 16:36:35 -0400298 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 )
quilesj26c78a42019-10-28 18:10:42 +0100306 except Exception as e:
beierlmf52cb7c2020-04-21 16:36:35 -0400307 self.log.error(
308 "Error uninstalling release {}: {}".format(kdu_instance, e)
309 )
quilesj26c78a42019-10-28 18:10:42 +0100310 else:
beierlmf52cb7c2020-04-21 16:36:35 -0400311 msg = (
312 "Cluster has releases and not force. Cannot reset K8s "
313 "environment. Cluster uuid: {}"
tiernof9bdac22020-06-25 15:48:52 +0000314 ).format(cluster_id)
Dominik Fleischmannf9bed352020-02-27 10:04:34 +0100315 self.log.error(msg)
quilesja6748412019-12-04 07:51:26 +0000316 raise K8sException(msg)
quilesj26c78a42019-10-28 18:10:42 +0100317
318 if uninstall_sw:
319
tiernof9bdac22020-06-25 15:48:52 +0000320 self.log.debug("Uninstalling tiller from cluster {}".format(cluster_id))
quilesj26c78a42019-10-28 18:10:42 +0100321
tiernof9bdac22020-06-25 15:48:52 +0000322 if not namespace:
323 # find namespace for tiller pod
324 command = "{} --kubeconfig={} get deployments --all-namespaces".format(
325 self.kubectl_command, config_filename
beierlmf52cb7c2020-04-21 16:36:35 -0400326 )
tiernof9bdac22020-06-25 15:48:52 +0000327 output, _rc = await self._local_async_exec(
beierlmf52cb7c2020-04-21 16:36:35 -0400328 command=command, raise_exception_on_error=False
329 )
tiernof9bdac22020-06-25 15:48:52 +0000330 output_table = K8sHelmConnector._output_to_table(output=output)
331 namespace = None
332 for r in output_table:
333 try:
334 if "tiller-deploy" in r[1]:
335 namespace = r[0]
336 break
337 except Exception:
338 pass
339 else:
340 msg = "Tiller deployment not found in cluster {}".format(cluster_id)
341 self.log.error(msg)
quilesj26c78a42019-10-28 18:10:42 +0100342
tiernof9bdac22020-06-25 15:48:52 +0000343 self.log.debug("namespace for tiller: {}".format(namespace))
344
345 if namespace:
quilesj26c78a42019-10-28 18:10:42 +0100346 # uninstall tiller from cluster
beierlmf52cb7c2020-04-21 16:36:35 -0400347 self.log.debug(
tiernof9bdac22020-06-25 15:48:52 +0000348 "Uninstalling tiller from cluster {}".format(cluster_id)
beierlmf52cb7c2020-04-21 16:36:35 -0400349 )
350 command = "{} --kubeconfig={} --home={} reset".format(
351 self._helm_command, config_filename, helm_dir
352 )
353 self.log.debug("resetting: {}".format(command))
354 output, _rc = await self._local_async_exec(
355 command=command, raise_exception_on_error=True
356 )
tiernof9bdac22020-06-25 15:48:52 +0000357 # Delete clusterrolebinding and serviceaccount.
358 # Ignore if errors for backward compatibility
359 command = ("{} --kubeconfig={} delete clusterrolebinding.rbac.authorization.k8s."
360 "io/osm-tiller-cluster-rule").format(self.kubectl_command,
361 config_filename)
362 output, _rc = await self._local_async_exec(command=command,
363 raise_exception_on_error=False)
364 command = "{} --kubeconfig={} --namespace kube-system delete serviceaccount/{}".\
365 format(self.kubectl_command, config_filename, self.service_account)
366 output, _rc = await self._local_async_exec(command=command,
367 raise_exception_on_error=False)
368
quilesj26c78a42019-10-28 18:10:42 +0100369 else:
beierlmf52cb7c2020-04-21 16:36:35 -0400370 self.log.debug("namespace not found")
quilesj26c78a42019-10-28 18:10:42 +0100371
372 # delete cluster directory
tiernof9bdac22020-06-25 15:48:52 +0000373 direct = self.fs.path + "/" + cluster_id
beierlmf52cb7c2020-04-21 16:36:35 -0400374 self.log.debug("Removing directory {}".format(direct))
375 shutil.rmtree(direct, ignore_errors=True)
quilesj26c78a42019-10-28 18:10:42 +0100376
377 return True
378
379 async def install(
beierlmf52cb7c2020-04-21 16:36:35 -0400380 self,
381 cluster_uuid: str,
382 kdu_model: str,
383 atomic: bool = True,
384 timeout: float = 300,
385 params: dict = None,
386 db_dict: dict = None,
387 kdu_name: str = None,
388 namespace: str = None,
quilesj26c78a42019-10-28 18:10:42 +0100389 ):
390
tiernof9bdac22020-06-25 15:48:52 +0000391 _, cluster_id = self._get_namespace_cluster_id(cluster_uuid)
392 self.log.debug("installing {} in cluster {}".format(kdu_model, cluster_id))
quilesj26c78a42019-10-28 18:10:42 +0100393
quilesj26c78a42019-10-28 18:10:42 +0100394 # config filename
beierlmf52cb7c2020-04-21 16:36:35 -0400395 _kube_dir, helm_dir, config_filename, _cluster_dir = self._get_paths(
tiernof9bdac22020-06-25 15:48:52 +0000396 cluster_name=cluster_id, create_if_not_exist=True
beierlmf52cb7c2020-04-21 16:36:35 -0400397 )
quilesj26c78a42019-10-28 18:10:42 +0100398
399 # params to str
quilesjcda5f412019-11-18 11:32:12 +0100400 # params_str = K8sHelmConnector._params_to_set_option(params)
beierlmf52cb7c2020-04-21 16:36:35 -0400401 params_str, file_to_delete = self._params_to_file_option(
tiernof9bdac22020-06-25 15:48:52 +0000402 cluster_id=cluster_id, params=params
beierlmf52cb7c2020-04-21 16:36:35 -0400403 )
quilesj26c78a42019-10-28 18:10:42 +0100404
beierlmf52cb7c2020-04-21 16:36:35 -0400405 timeout_str = ""
quilesj26c78a42019-10-28 18:10:42 +0100406 if timeout:
beierlmf52cb7c2020-04-21 16:36:35 -0400407 timeout_str = "--timeout {}".format(timeout)
quilesj26c78a42019-10-28 18:10:42 +0100408
409 # atomic
beierlmf52cb7c2020-04-21 16:36:35 -0400410 atomic_str = ""
quilesj26c78a42019-10-28 18:10:42 +0100411 if atomic:
beierlmf52cb7c2020-04-21 16:36:35 -0400412 atomic_str = "--atomic"
tierno53555f62020-04-07 11:08:16 +0000413 # namespace
beierlmf52cb7c2020-04-21 16:36:35 -0400414 namespace_str = ""
tierno53555f62020-04-07 11:08:16 +0000415 if namespace:
416 namespace_str = "--namespace {}".format(namespace)
quilesj26c78a42019-10-28 18:10:42 +0100417
418 # version
beierlmf52cb7c2020-04-21 16:36:35 -0400419 version_str = ""
420 if ":" in kdu_model:
421 parts = kdu_model.split(sep=":")
quilesj26c78a42019-10-28 18:10:42 +0100422 if len(parts) == 2:
beierlmf52cb7c2020-04-21 16:36:35 -0400423 version_str = "--version {}".format(parts[1])
quilesj26c78a42019-10-28 18:10:42 +0100424 kdu_model = parts[0]
425
quilesja6748412019-12-04 07:51:26 +0000426 # generate a name for the release. Then, check if already exists
quilesj26c78a42019-10-28 18:10:42 +0100427 kdu_instance = None
428 while kdu_instance is None:
429 kdu_instance = K8sHelmConnector._generate_release_name(kdu_model)
430 try:
431 result = await self._status_kdu(
tiernof9bdac22020-06-25 15:48:52 +0000432 cluster_id=cluster_id,
quilesj26c78a42019-10-28 18:10:42 +0100433 kdu_instance=kdu_instance,
beierlmf52cb7c2020-04-21 16:36:35 -0400434 show_error_log=False,
quilesj26c78a42019-10-28 18:10:42 +0100435 )
436 if result is not None:
437 # instance already exists: generate a new one
438 kdu_instance = None
tierno601697a2020-02-04 15:26:25 +0000439 except K8sException:
440 pass
quilesj26c78a42019-10-28 18:10:42 +0100441
442 # helm repo install
beierlmf52cb7c2020-04-21 16:36:35 -0400443 command = (
444 "{helm} install {atomic} --output yaml --kubeconfig={config} --home={dir} "
445 "{params} {timeout} --name={name} {ns} {model} {ver}".format(
446 helm=self._helm_command,
447 atomic=atomic_str,
448 config=config_filename,
449 dir=helm_dir,
450 params=params_str,
451 timeout=timeout_str,
452 name=kdu_instance,
453 ns=namespace_str,
454 model=kdu_model,
455 ver=version_str,
456 )
457 )
458 self.log.debug("installing: {}".format(command))
quilesj26c78a42019-10-28 18:10:42 +0100459
460 if atomic:
461 # exec helm in a task
462 exec_task = asyncio.ensure_future(
beierlmf52cb7c2020-04-21 16:36:35 -0400463 coro_or_future=self._local_async_exec(
464 command=command, raise_exception_on_error=False
465 )
quilesj26c78a42019-10-28 18:10:42 +0100466 )
lloretgalleg65ddf852020-02-20 12:01:17 +0100467
quilesj26c78a42019-10-28 18:10:42 +0100468 # write status in another task
469 status_task = asyncio.ensure_future(
470 coro_or_future=self._store_status(
tiernof9bdac22020-06-25 15:48:52 +0000471 cluster_id=cluster_id,
quilesj26c78a42019-10-28 18:10:42 +0100472 kdu_instance=kdu_instance,
473 db_dict=db_dict,
beierlmf52cb7c2020-04-21 16:36:35 -0400474 operation="install",
475 run_once=False,
quilesj26c78a42019-10-28 18:10:42 +0100476 )
477 )
478
479 # wait for execution task
480 await asyncio.wait([exec_task])
481
482 # cancel status task
483 status_task.cancel()
484
485 output, rc = exec_task.result()
486
487 else:
488
beierlmf52cb7c2020-04-21 16:36:35 -0400489 output, rc = await self._local_async_exec(
490 command=command, raise_exception_on_error=False
491 )
quilesj26c78a42019-10-28 18:10:42 +0100492
quilesjcda5f412019-11-18 11:32:12 +0100493 # remove temporal values yaml file
494 if file_to_delete:
495 os.remove(file_to_delete)
496
quilesj26c78a42019-10-28 18:10:42 +0100497 # write final status
498 await self._store_status(
tiernof9bdac22020-06-25 15:48:52 +0000499 cluster_id=cluster_id,
quilesj26c78a42019-10-28 18:10:42 +0100500 kdu_instance=kdu_instance,
501 db_dict=db_dict,
beierlmf52cb7c2020-04-21 16:36:35 -0400502 operation="install",
quilesj26c78a42019-10-28 18:10:42 +0100503 run_once=True,
beierlmf52cb7c2020-04-21 16:36:35 -0400504 check_every=0,
quilesj26c78a42019-10-28 18:10:42 +0100505 )
506
507 if rc != 0:
beierlmf52cb7c2020-04-21 16:36:35 -0400508 msg = "Error executing command: {}\nOutput: {}".format(command, output)
Dominik Fleischmannf9bed352020-02-27 10:04:34 +0100509 self.log.error(msg)
quilesja6748412019-12-04 07:51:26 +0000510 raise K8sException(msg)
quilesj26c78a42019-10-28 18:10:42 +0100511
beierlmf52cb7c2020-04-21 16:36:35 -0400512 self.log.debug("Returning kdu_instance {}".format(kdu_instance))
quilesj26c78a42019-10-28 18:10:42 +0100513 return kdu_instance
514
beierlmf52cb7c2020-04-21 16:36:35 -0400515 async def instances_list(self, cluster_uuid: str) -> list:
quilesj26c78a42019-10-28 18:10:42 +0100516 """
517 returns a list of deployed releases in a cluster
518
tiernof9bdac22020-06-25 15:48:52 +0000519 :param cluster_uuid: the 'cluster' or 'namespace:cluster'
quilesj26c78a42019-10-28 18:10:42 +0100520 :return:
521 """
522
tiernof9bdac22020-06-25 15:48:52 +0000523 _, cluster_id = self._get_namespace_cluster_id(cluster_uuid)
524 self.log.debug("list releases for cluster {}".format(cluster_id))
quilesj26c78a42019-10-28 18:10:42 +0100525
526 # config filename
beierlmf52cb7c2020-04-21 16:36:35 -0400527 _kube_dir, helm_dir, config_filename, _cluster_dir = self._get_paths(
tiernof9bdac22020-06-25 15:48:52 +0000528 cluster_name=cluster_id, create_if_not_exist=True
beierlmf52cb7c2020-04-21 16:36:35 -0400529 )
quilesj26c78a42019-10-28 18:10:42 +0100530
beierlmf52cb7c2020-04-21 16:36:35 -0400531 command = "{} --kubeconfig={} --home={} list --output yaml".format(
532 self._helm_command, config_filename, helm_dir
533 )
quilesj26c78a42019-10-28 18:10:42 +0100534
beierlmf52cb7c2020-04-21 16:36:35 -0400535 output, _rc = await self._local_async_exec(
536 command=command, raise_exception_on_error=True
537 )
quilesj26c78a42019-10-28 18:10:42 +0100538
539 if output and len(output) > 0:
beierlmf52cb7c2020-04-21 16:36:35 -0400540 return yaml.load(output, Loader=yaml.SafeLoader).get("Releases")
quilesj26c78a42019-10-28 18:10:42 +0100541 else:
542 return []
543
544 async def upgrade(
beierlmf52cb7c2020-04-21 16:36:35 -0400545 self,
546 cluster_uuid: str,
547 kdu_instance: str,
548 kdu_model: str = None,
549 atomic: bool = True,
550 timeout: float = 300,
551 params: dict = None,
552 db_dict: dict = None,
quilesj26c78a42019-10-28 18:10:42 +0100553 ):
554
tiernof9bdac22020-06-25 15:48:52 +0000555 _, cluster_id = self._get_namespace_cluster_id(cluster_uuid)
556 self.log.debug("upgrading {} in cluster {}".format(kdu_model, cluster_id))
quilesj26c78a42019-10-28 18:10:42 +0100557
quilesj26c78a42019-10-28 18:10:42 +0100558 # config filename
beierlmf52cb7c2020-04-21 16:36:35 -0400559 _kube_dir, helm_dir, config_filename, _cluster_dir = self._get_paths(
tiernof9bdac22020-06-25 15:48:52 +0000560 cluster_name=cluster_id, create_if_not_exist=True
beierlmf52cb7c2020-04-21 16:36:35 -0400561 )
quilesj26c78a42019-10-28 18:10:42 +0100562
563 # params to str
quilesjcda5f412019-11-18 11:32:12 +0100564 # params_str = K8sHelmConnector._params_to_set_option(params)
beierlmf52cb7c2020-04-21 16:36:35 -0400565 params_str, file_to_delete = self._params_to_file_option(
tiernof9bdac22020-06-25 15:48:52 +0000566 cluster_id=cluster_id, params=params
beierlmf52cb7c2020-04-21 16:36:35 -0400567 )
quilesj26c78a42019-10-28 18:10:42 +0100568
beierlmf52cb7c2020-04-21 16:36:35 -0400569 timeout_str = ""
quilesj26c78a42019-10-28 18:10:42 +0100570 if timeout:
beierlmf52cb7c2020-04-21 16:36:35 -0400571 timeout_str = "--timeout {}".format(timeout)
quilesj26c78a42019-10-28 18:10:42 +0100572
573 # atomic
beierlmf52cb7c2020-04-21 16:36:35 -0400574 atomic_str = ""
quilesj26c78a42019-10-28 18:10:42 +0100575 if atomic:
beierlmf52cb7c2020-04-21 16:36:35 -0400576 atomic_str = "--atomic"
quilesj26c78a42019-10-28 18:10:42 +0100577
578 # version
beierlmf52cb7c2020-04-21 16:36:35 -0400579 version_str = ""
580 if kdu_model and ":" in kdu_model:
581 parts = kdu_model.split(sep=":")
quilesj26c78a42019-10-28 18:10:42 +0100582 if len(parts) == 2:
beierlmf52cb7c2020-04-21 16:36:35 -0400583 version_str = "--version {}".format(parts[1])
quilesj26c78a42019-10-28 18:10:42 +0100584 kdu_model = parts[0]
585
586 # helm repo upgrade
beierlmf52cb7c2020-04-21 16:36:35 -0400587 command = (
588 "{} upgrade {} --output yaml --kubeconfig={} " "--home={} {} {} {} {} {}"
589 ).format(
590 self._helm_command,
591 atomic_str,
592 config_filename,
593 helm_dir,
594 params_str,
595 timeout_str,
596 kdu_instance,
597 kdu_model,
598 version_str,
599 )
600 self.log.debug("upgrading: {}".format(command))
quilesj26c78a42019-10-28 18:10:42 +0100601
602 if atomic:
603
604 # exec helm in a task
605 exec_task = asyncio.ensure_future(
beierlmf52cb7c2020-04-21 16:36:35 -0400606 coro_or_future=self._local_async_exec(
607 command=command, raise_exception_on_error=False
608 )
quilesj26c78a42019-10-28 18:10:42 +0100609 )
610 # write status in another task
611 status_task = asyncio.ensure_future(
612 coro_or_future=self._store_status(
tiernof9bdac22020-06-25 15:48:52 +0000613 cluster_id=cluster_id,
quilesj26c78a42019-10-28 18:10:42 +0100614 kdu_instance=kdu_instance,
615 db_dict=db_dict,
beierlmf52cb7c2020-04-21 16:36:35 -0400616 operation="upgrade",
617 run_once=False,
quilesj26c78a42019-10-28 18:10:42 +0100618 )
619 )
620
621 # wait for execution task
quilesj1be06302019-11-29 11:17:11 +0000622 await asyncio.wait([exec_task])
quilesj26c78a42019-10-28 18:10:42 +0100623
624 # cancel status task
625 status_task.cancel()
626 output, rc = exec_task.result()
627
628 else:
629
beierlmf52cb7c2020-04-21 16:36:35 -0400630 output, rc = await self._local_async_exec(
631 command=command, raise_exception_on_error=False
632 )
quilesj26c78a42019-10-28 18:10:42 +0100633
quilesjcda5f412019-11-18 11:32:12 +0100634 # remove temporal values yaml file
635 if file_to_delete:
636 os.remove(file_to_delete)
637
quilesj26c78a42019-10-28 18:10:42 +0100638 # write final status
639 await self._store_status(
tiernof9bdac22020-06-25 15:48:52 +0000640 cluster_id=cluster_id,
quilesj26c78a42019-10-28 18:10:42 +0100641 kdu_instance=kdu_instance,
642 db_dict=db_dict,
beierlmf52cb7c2020-04-21 16:36:35 -0400643 operation="upgrade",
quilesj26c78a42019-10-28 18:10:42 +0100644 run_once=True,
beierlmf52cb7c2020-04-21 16:36:35 -0400645 check_every=0,
quilesj26c78a42019-10-28 18:10:42 +0100646 )
647
648 if rc != 0:
beierlmf52cb7c2020-04-21 16:36:35 -0400649 msg = "Error executing command: {}\nOutput: {}".format(command, output)
Dominik Fleischmannf9bed352020-02-27 10:04:34 +0100650 self.log.error(msg)
quilesja6748412019-12-04 07:51:26 +0000651 raise K8sException(msg)
quilesj26c78a42019-10-28 18:10:42 +0100652
653 # return new revision number
beierlmf52cb7c2020-04-21 16:36:35 -0400654 instance = await self.get_instance_info(
655 cluster_uuid=cluster_uuid, kdu_instance=kdu_instance
656 )
quilesj26c78a42019-10-28 18:10:42 +0100657 if instance:
beierlmf52cb7c2020-04-21 16:36:35 -0400658 revision = int(instance.get("Revision"))
659 self.log.debug("New revision: {}".format(revision))
quilesj26c78a42019-10-28 18:10:42 +0100660 return revision
661 else:
662 return 0
663
664 async def rollback(
beierlmf52cb7c2020-04-21 16:36:35 -0400665 self, cluster_uuid: str, kdu_instance: str, revision=0, db_dict: dict = None
quilesj26c78a42019-10-28 18:10:42 +0100666 ):
667
tiernof9bdac22020-06-25 15:48:52 +0000668 _, cluster_id = self._get_namespace_cluster_id(cluster_uuid)
beierlmf52cb7c2020-04-21 16:36:35 -0400669 self.log.debug(
670 "rollback kdu_instance {} to revision {} from cluster {}".format(
tiernof9bdac22020-06-25 15:48:52 +0000671 kdu_instance, revision, cluster_id
beierlmf52cb7c2020-04-21 16:36:35 -0400672 )
673 )
quilesj26c78a42019-10-28 18:10:42 +0100674
675 # config filename
beierlmf52cb7c2020-04-21 16:36:35 -0400676 _kube_dir, helm_dir, config_filename, _cluster_dir = self._get_paths(
tiernof9bdac22020-06-25 15:48:52 +0000677 cluster_name=cluster_id, create_if_not_exist=True
beierlmf52cb7c2020-04-21 16:36:35 -0400678 )
quilesj26c78a42019-10-28 18:10:42 +0100679
beierlmf52cb7c2020-04-21 16:36:35 -0400680 command = "{} rollback --kubeconfig={} --home={} {} {} --wait".format(
681 self._helm_command, config_filename, helm_dir, kdu_instance, revision
682 )
quilesj26c78a42019-10-28 18:10:42 +0100683
684 # exec helm in a task
685 exec_task = asyncio.ensure_future(
beierlmf52cb7c2020-04-21 16:36:35 -0400686 coro_or_future=self._local_async_exec(
687 command=command, raise_exception_on_error=False
688 )
quilesj26c78a42019-10-28 18:10:42 +0100689 )
690 # write status in another task
691 status_task = asyncio.ensure_future(
692 coro_or_future=self._store_status(
tiernof9bdac22020-06-25 15:48:52 +0000693 cluster_id=cluster_id,
quilesj26c78a42019-10-28 18:10:42 +0100694 kdu_instance=kdu_instance,
695 db_dict=db_dict,
beierlmf52cb7c2020-04-21 16:36:35 -0400696 operation="rollback",
697 run_once=False,
quilesj26c78a42019-10-28 18:10:42 +0100698 )
699 )
700
701 # wait for execution task
702 await asyncio.wait([exec_task])
703
704 # cancel status task
705 status_task.cancel()
706
707 output, rc = exec_task.result()
708
709 # write final status
710 await self._store_status(
tiernof9bdac22020-06-25 15:48:52 +0000711 cluster_id=cluster_id,
quilesj26c78a42019-10-28 18:10:42 +0100712 kdu_instance=kdu_instance,
713 db_dict=db_dict,
beierlmf52cb7c2020-04-21 16:36:35 -0400714 operation="rollback",
quilesj26c78a42019-10-28 18:10:42 +0100715 run_once=True,
beierlmf52cb7c2020-04-21 16:36:35 -0400716 check_every=0,
quilesj26c78a42019-10-28 18:10:42 +0100717 )
718
719 if rc != 0:
beierlmf52cb7c2020-04-21 16:36:35 -0400720 msg = "Error executing command: {}\nOutput: {}".format(command, output)
Dominik Fleischmannf9bed352020-02-27 10:04:34 +0100721 self.log.error(msg)
quilesja6748412019-12-04 07:51:26 +0000722 raise K8sException(msg)
quilesj26c78a42019-10-28 18:10:42 +0100723
724 # return new revision number
beierlmf52cb7c2020-04-21 16:36:35 -0400725 instance = await self.get_instance_info(
726 cluster_uuid=cluster_uuid, kdu_instance=kdu_instance
727 )
quilesj26c78a42019-10-28 18:10:42 +0100728 if instance:
beierlmf52cb7c2020-04-21 16:36:35 -0400729 revision = int(instance.get("Revision"))
730 self.log.debug("New revision: {}".format(revision))
quilesj26c78a42019-10-28 18:10:42 +0100731 return revision
732 else:
733 return 0
734
beierlmf52cb7c2020-04-21 16:36:35 -0400735 async def uninstall(self, cluster_uuid: str, kdu_instance: str):
quilesj26c78a42019-10-28 18:10:42 +0100736 """
beierlmf52cb7c2020-04-21 16:36:35 -0400737 Removes an existing KDU instance. It would implicitly use the `delete` call
738 (this call would happen after all _terminate-config-primitive_ of the VNF
739 are invoked).
quilesj26c78a42019-10-28 18:10:42 +0100740
tiernof9bdac22020-06-25 15:48:52 +0000741 :param cluster_uuid: UUID of a K8s cluster known by OSM, or namespace:cluster_id
quilesj26c78a42019-10-28 18:10:42 +0100742 :param kdu_instance: unique name for the KDU instance to be deleted
743 :return: True if successful
744 """
745
tiernof9bdac22020-06-25 15:48:52 +0000746 _, cluster_id = self._get_namespace_cluster_id(cluster_uuid)
beierlmf52cb7c2020-04-21 16:36:35 -0400747 self.log.debug(
748 "uninstall kdu_instance {} from cluster {}".format(
tiernof9bdac22020-06-25 15:48:52 +0000749 kdu_instance, cluster_id
beierlmf52cb7c2020-04-21 16:36:35 -0400750 )
751 )
quilesj26c78a42019-10-28 18:10:42 +0100752
753 # config filename
beierlmf52cb7c2020-04-21 16:36:35 -0400754 _kube_dir, helm_dir, config_filename, _cluster_dir = self._get_paths(
tiernof9bdac22020-06-25 15:48:52 +0000755 cluster_name=cluster_id, create_if_not_exist=True
beierlmf52cb7c2020-04-21 16:36:35 -0400756 )
quilesj26c78a42019-10-28 18:10:42 +0100757
beierlmf52cb7c2020-04-21 16:36:35 -0400758 command = "{} --kubeconfig={} --home={} delete --purge {}".format(
759 self._helm_command, config_filename, helm_dir, kdu_instance
760 )
quilesj26c78a42019-10-28 18:10:42 +0100761
beierlmf52cb7c2020-04-21 16:36:35 -0400762 output, _rc = await self._local_async_exec(
763 command=command, raise_exception_on_error=True
764 )
quilesj26c78a42019-10-28 18:10:42 +0100765
766 return self._output_to_table(output)
767
Dominik Fleischmannfc796cc2020-04-06 14:51:00 +0200768 async def exec_primitive(
769 self,
770 cluster_uuid: str = None,
771 kdu_instance: str = None,
772 primitive_name: str = None,
773 timeout: float = 300,
774 params: dict = None,
775 db_dict: dict = None,
776 ) -> str:
777 """Exec primitive (Juju action)
778
tiernof9bdac22020-06-25 15:48:52 +0000779 :param cluster_uuid str: The UUID of the cluster or namespace:cluster
Dominik Fleischmannfc796cc2020-04-06 14:51:00 +0200780 :param kdu_instance str: The unique name of the KDU instance
781 :param primitive_name: Name of action that will be executed
782 :param timeout: Timeout for action execution
783 :param params: Dictionary of all the parameters needed for the action
784 :db_dict: Dictionary for any additional data
785
786 :return: Returns the output of the action
787 """
beierlmf52cb7c2020-04-21 16:36:35 -0400788 raise K8sException(
789 "KDUs deployed with Helm don't support actions "
790 "different from rollback, upgrade and status"
791 )
Dominik Fleischmannfc796cc2020-04-06 14:51:00 +0200792
beierlmf52cb7c2020-04-21 16:36:35 -0400793 async def inspect_kdu(self, kdu_model: str, repo_url: str = None) -> str:
quilesj26c78a42019-10-28 18:10:42 +0100794
beierlmf52cb7c2020-04-21 16:36:35 -0400795 self.log.debug(
796 "inspect kdu_model {} from (optional) repo: {}".format(kdu_model, repo_url)
797 )
quilesj26c78a42019-10-28 18:10:42 +0100798
beierlmf52cb7c2020-04-21 16:36:35 -0400799 return await self._exec_inspect_comand(
800 inspect_command="", kdu_model=kdu_model, repo_url=repo_url
801 )
quilesj26c78a42019-10-28 18:10:42 +0100802
beierlmf52cb7c2020-04-21 16:36:35 -0400803 async def values_kdu(self, kdu_model: str, repo_url: str = None) -> str:
quilesj26c78a42019-10-28 18:10:42 +0100804
beierlmf52cb7c2020-04-21 16:36:35 -0400805 self.log.debug(
806 "inspect kdu_model values {} from (optional) repo: {}".format(
807 kdu_model, repo_url
808 )
809 )
quilesj1be06302019-11-29 11:17:11 +0000810
beierlmf52cb7c2020-04-21 16:36:35 -0400811 return await self._exec_inspect_comand(
812 inspect_command="values", kdu_model=kdu_model, repo_url=repo_url
813 )
quilesj26c78a42019-10-28 18:10:42 +0100814
beierlmf52cb7c2020-04-21 16:36:35 -0400815 async def help_kdu(self, kdu_model: str, repo_url: str = None) -> str:
quilesj26c78a42019-10-28 18:10:42 +0100816
beierlmf52cb7c2020-04-21 16:36:35 -0400817 self.log.debug(
818 "inspect kdu_model {} readme.md from repo: {}".format(kdu_model, repo_url)
819 )
quilesj26c78a42019-10-28 18:10:42 +0100820
beierlmf52cb7c2020-04-21 16:36:35 -0400821 return await self._exec_inspect_comand(
822 inspect_command="readme", kdu_model=kdu_model, repo_url=repo_url
823 )
quilesj26c78a42019-10-28 18:10:42 +0100824
beierlmf52cb7c2020-04-21 16:36:35 -0400825 async def status_kdu(self, cluster_uuid: str, kdu_instance: str) -> str:
quilesj26c78a42019-10-28 18:10:42 +0100826
quilesj1be06302019-11-29 11:17:11 +0000827 # call internal function
tiernof9bdac22020-06-25 15:48:52 +0000828 _, cluster_id = self._get_namespace_cluster_id(cluster_uuid)
quilesj1be06302019-11-29 11:17:11 +0000829 return await self._status_kdu(
tiernof9bdac22020-06-25 15:48:52 +0000830 cluster_id=cluster_id,
quilesj1be06302019-11-29 11:17:11 +0000831 kdu_instance=kdu_instance,
832 show_error_log=True,
beierlmf52cb7c2020-04-21 16:36:35 -0400833 return_text=True,
quilesj1be06302019-11-29 11:17:11 +0000834 )
quilesj26c78a42019-10-28 18:10:42 +0100835
lloretgalleg65ddf852020-02-20 12:01:17 +0100836 async def synchronize_repos(self, cluster_uuid: str):
837
tiernof9bdac22020-06-25 15:48:52 +0000838 _, cluster_id = self._get_namespace_cluster_id(cluster_uuid)
Dominik Fleischmannf9bed352020-02-27 10:04:34 +0100839 self.log.debug("syncronize repos for cluster helm-id: {}",)
lloretgalleg65ddf852020-02-20 12:01:17 +0100840 try:
beierlmf52cb7c2020-04-21 16:36:35 -0400841 update_repos_timeout = (
842 300 # max timeout to sync a single repos, more than this is too much
843 )
844 db_k8scluster = self.db.get_one(
845 "k8sclusters", {"_admin.helm-chart.id": cluster_uuid}
846 )
lloretgalleg65ddf852020-02-20 12:01:17 +0100847 if db_k8scluster:
beierlmf52cb7c2020-04-21 16:36:35 -0400848 nbi_repo_list = (
849 db_k8scluster.get("_admin").get("helm_chart_repos") or []
850 )
851 cluster_repo_dict = (
852 db_k8scluster.get("_admin").get("helm_charts_added") or {}
853 )
lloretgalleg65ddf852020-02-20 12:01:17 +0100854 # elements that must be deleted
855 deleted_repo_list = []
856 added_repo_dict = {}
Dominik Fleischmannf9bed352020-02-27 10:04:34 +0100857 self.log.debug("helm_chart_repos: {}".format(nbi_repo_list))
858 self.log.debug("helm_charts_added: {}".format(cluster_repo_dict))
lloretgalleg65ddf852020-02-20 12:01:17 +0100859
860 # obtain repos to add: registered by nbi but not added
beierlmf52cb7c2020-04-21 16:36:35 -0400861 repos_to_add = [
862 repo for repo in nbi_repo_list if not cluster_repo_dict.get(repo)
863 ]
lloretgalleg65ddf852020-02-20 12:01:17 +0100864
865 # obtain repos to delete: added by cluster but not in nbi list
beierlmf52cb7c2020-04-21 16:36:35 -0400866 repos_to_delete = [
867 repo
868 for repo in cluster_repo_dict.keys()
869 if repo not in nbi_repo_list
870 ]
lloretgalleg65ddf852020-02-20 12:01:17 +0100871
beierlmf52cb7c2020-04-21 16:36:35 -0400872 # delete repos: must delete first then add because there may be
873 # different repos with same name but
lloretgalleg65ddf852020-02-20 12:01:17 +0100874 # different id and url
Dominik Fleischmannf9bed352020-02-27 10:04:34 +0100875 self.log.debug("repos to delete: {}".format(repos_to_delete))
lloretgalleg65ddf852020-02-20 12:01:17 +0100876 for repo_id in repos_to_delete:
877 # try to delete repos
878 try:
beierlmf52cb7c2020-04-21 16:36:35 -0400879 repo_delete_task = asyncio.ensure_future(
880 self.repo_remove(
881 cluster_uuid=cluster_uuid,
882 name=cluster_repo_dict[repo_id],
883 )
884 )
lloretgalleg65ddf852020-02-20 12:01:17 +0100885 await asyncio.wait_for(repo_delete_task, update_repos_timeout)
886 except Exception as e:
beierlmf52cb7c2020-04-21 16:36:35 -0400887 self.warning(
888 "Error deleting repo, id: {}, name: {}, err_msg: {}".format(
889 repo_id, cluster_repo_dict[repo_id], str(e)
890 )
891 )
892 # always add to the list of to_delete if there is an error
893 # because if is not there
894 # deleting raises error
lloretgalleg65ddf852020-02-20 12:01:17 +0100895 deleted_repo_list.append(repo_id)
896
897 # add repos
Dominik Fleischmannf9bed352020-02-27 10:04:34 +0100898 self.log.debug("repos to add: {}".format(repos_to_add))
lloretgalleg65ddf852020-02-20 12:01:17 +0100899 for repo_id in repos_to_add:
900 # obtain the repo data from the db
beierlmf52cb7c2020-04-21 16:36:35 -0400901 # if there is an error getting the repo in the database we will
902 # ignore this repo and continue
903 # because there is a possible race condition where the repo has
904 # been deleted while processing
lloretgalleg65ddf852020-02-20 12:01:17 +0100905 db_repo = self.db.get_one("k8srepos", {"_id": repo_id})
beierlmf52cb7c2020-04-21 16:36:35 -0400906 self.log.debug(
907 "obtained repo: id, {}, name: {}, url: {}".format(
908 repo_id, db_repo["name"], db_repo["url"]
909 )
910 )
lloretgalleg65ddf852020-02-20 12:01:17 +0100911 try:
beierlmf52cb7c2020-04-21 16:36:35 -0400912 repo_add_task = asyncio.ensure_future(
913 self.repo_add(
914 cluster_uuid=cluster_uuid,
915 name=db_repo["name"],
916 url=db_repo["url"],
917 repo_type="chart",
918 )
919 )
lloretgalleg65ddf852020-02-20 12:01:17 +0100920 await asyncio.wait_for(repo_add_task, update_repos_timeout)
921 added_repo_dict[repo_id] = db_repo["name"]
beierlmf52cb7c2020-04-21 16:36:35 -0400922 self.log.debug(
923 "added repo: id, {}, name: {}".format(
924 repo_id, db_repo["name"]
925 )
926 )
lloretgalleg65ddf852020-02-20 12:01:17 +0100927 except Exception as e:
beierlmf52cb7c2020-04-21 16:36:35 -0400928 # deal with error adding repo, adding a repo that already
929 # exists does not raise any error
930 # will not raise error because a wrong repos added by
931 # anyone could prevent instantiating any ns
932 self.log.error(
933 "Error adding repo id: {}, err_msg: {} ".format(
934 repo_id, repr(e)
935 )
936 )
lloretgalleg65ddf852020-02-20 12:01:17 +0100937
938 return deleted_repo_list, added_repo_dict
939
beierlmf52cb7c2020-04-21 16:36:35 -0400940 else: # else db_k8scluster does not exist
941 raise K8sException(
942 "k8cluster with helm-id : {} not found".format(cluster_uuid)
943 )
lloretgalleg65ddf852020-02-20 12:01:17 +0100944
945 except Exception as e:
Dominik Fleischmannf9bed352020-02-27 10:04:34 +0100946 self.log.error("Error synchronizing repos: {}".format(str(e)))
lloretgalleg65ddf852020-02-20 12:01:17 +0100947 raise K8sException("Error synchronizing repos")
948
quilesj26c78a42019-10-28 18:10:42 +0100949 """
beierlmf52cb7c2020-04-21 16:36:35 -0400950 ####################################################################################
951 ################################### P R I V A T E ##################################
952 ####################################################################################
quilesj26c78a42019-10-28 18:10:42 +0100953 """
954
quilesj1be06302019-11-29 11:17:11 +0000955 async def _exec_inspect_comand(
beierlmf52cb7c2020-04-21 16:36:35 -0400956 self, inspect_command: str, kdu_model: str, repo_url: str = None
quilesj1be06302019-11-29 11:17:11 +0000957 ):
958
beierlmf52cb7c2020-04-21 16:36:35 -0400959 repo_str = ""
quilesj1be06302019-11-29 11:17:11 +0000960 if repo_url:
beierlmf52cb7c2020-04-21 16:36:35 -0400961 repo_str = " --repo {}".format(repo_url)
962 idx = kdu_model.find("/")
quilesj1be06302019-11-29 11:17:11 +0000963 if idx >= 0:
964 idx += 1
965 kdu_model = kdu_model[idx:]
966
beierlmf52cb7c2020-04-21 16:36:35 -0400967 inspect_command = "{} inspect {} {}{}".format(
968 self._helm_command, inspect_command, kdu_model, repo_str
969 )
970 output, _rc = await self._local_async_exec(
971 command=inspect_command, encode_utf8=True
972 )
quilesj1be06302019-11-29 11:17:11 +0000973
974 return output
975
quilesj26c78a42019-10-28 18:10:42 +0100976 async def _status_kdu(
beierlmf52cb7c2020-04-21 16:36:35 -0400977 self,
tiernof9bdac22020-06-25 15:48:52 +0000978 cluster_id: str,
beierlmf52cb7c2020-04-21 16:36:35 -0400979 kdu_instance: str,
980 show_error_log: bool = False,
981 return_text: bool = False,
quilesj26c78a42019-10-28 18:10:42 +0100982 ):
983
beierlmf52cb7c2020-04-21 16:36:35 -0400984 self.log.debug("status of kdu_instance {}".format(kdu_instance))
quilesj26c78a42019-10-28 18:10:42 +0100985
986 # config filename
beierlmf52cb7c2020-04-21 16:36:35 -0400987 _kube_dir, helm_dir, config_filename, _cluster_dir = self._get_paths(
tiernof9bdac22020-06-25 15:48:52 +0000988 cluster_name=cluster_id, create_if_not_exist=True
beierlmf52cb7c2020-04-21 16:36:35 -0400989 )
quilesj26c78a42019-10-28 18:10:42 +0100990
beierlmf52cb7c2020-04-21 16:36:35 -0400991 command = "{} --kubeconfig={} --home={} status {} --output yaml".format(
992 self._helm_command, config_filename, helm_dir, kdu_instance
993 )
quilesj26c78a42019-10-28 18:10:42 +0100994
995 output, rc = await self._local_async_exec(
996 command=command,
997 raise_exception_on_error=True,
beierlmf52cb7c2020-04-21 16:36:35 -0400998 show_error_log=show_error_log,
quilesj26c78a42019-10-28 18:10:42 +0100999 )
1000
quilesj1be06302019-11-29 11:17:11 +00001001 if return_text:
1002 return str(output)
1003
quilesj26c78a42019-10-28 18:10:42 +01001004 if rc != 0:
1005 return None
1006
1007 data = yaml.load(output, Loader=yaml.SafeLoader)
1008
1009 # remove field 'notes'
1010 try:
beierlmf52cb7c2020-04-21 16:36:35 -04001011 del data.get("info").get("status")["notes"]
quilesj26c78a42019-10-28 18:10:42 +01001012 except KeyError:
1013 pass
1014
1015 # parse field 'resources'
1016 try:
beierlmf52cb7c2020-04-21 16:36:35 -04001017 resources = str(data.get("info").get("status").get("resources"))
quilesj26c78a42019-10-28 18:10:42 +01001018 resource_table = self._output_to_table(resources)
beierlmf52cb7c2020-04-21 16:36:35 -04001019 data.get("info").get("status")["resources"] = resource_table
1020 except Exception:
quilesj26c78a42019-10-28 18:10:42 +01001021 pass
1022
1023 return data
1024
beierlmf52cb7c2020-04-21 16:36:35 -04001025 async def get_instance_info(self, cluster_uuid: str, kdu_instance: str):
quilesj26c78a42019-10-28 18:10:42 +01001026 instances = await self.instances_list(cluster_uuid=cluster_uuid)
1027 for instance in instances:
beierlmf52cb7c2020-04-21 16:36:35 -04001028 if instance.get("Name") == kdu_instance:
quilesj26c78a42019-10-28 18:10:42 +01001029 return instance
beierlmf52cb7c2020-04-21 16:36:35 -04001030 self.log.debug("Instance {} not found".format(kdu_instance))
quilesj26c78a42019-10-28 18:10:42 +01001031 return None
1032
1033 @staticmethod
beierlmf52cb7c2020-04-21 16:36:35 -04001034 def _generate_release_name(chart_name: str):
quilesjbc355a12020-01-23 09:28:26 +00001035 # check embeded chart (file or dir)
beierlmf52cb7c2020-04-21 16:36:35 -04001036 if chart_name.startswith("/"):
quilesjbc355a12020-01-23 09:28:26 +00001037 # extract file or directory name
beierlmf52cb7c2020-04-21 16:36:35 -04001038 chart_name = chart_name[chart_name.rfind("/") + 1 :]
quilesjbc355a12020-01-23 09:28:26 +00001039 # check URL
beierlmf52cb7c2020-04-21 16:36:35 -04001040 elif "://" in chart_name:
quilesjbc355a12020-01-23 09:28:26 +00001041 # extract last portion of URL
beierlmf52cb7c2020-04-21 16:36:35 -04001042 chart_name = chart_name[chart_name.rfind("/") + 1 :]
quilesjbc355a12020-01-23 09:28:26 +00001043
beierlmf52cb7c2020-04-21 16:36:35 -04001044 name = ""
quilesj26c78a42019-10-28 18:10:42 +01001045 for c in chart_name:
1046 if c.isalpha() or c.isnumeric():
1047 name += c
1048 else:
beierlmf52cb7c2020-04-21 16:36:35 -04001049 name += "-"
quilesj26c78a42019-10-28 18:10:42 +01001050 if len(name) > 35:
1051 name = name[0:35]
1052
1053 # if does not start with alpha character, prefix 'a'
1054 if not name[0].isalpha():
beierlmf52cb7c2020-04-21 16:36:35 -04001055 name = "a" + name
quilesj26c78a42019-10-28 18:10:42 +01001056
beierlmf52cb7c2020-04-21 16:36:35 -04001057 name += "-"
quilesj26c78a42019-10-28 18:10:42 +01001058
1059 def get_random_number():
1060 r = random.randrange(start=1, stop=99999999)
1061 s = str(r)
beierlmf52cb7c2020-04-21 16:36:35 -04001062 s = s.rjust(10, "0")
quilesj26c78a42019-10-28 18:10:42 +01001063 return s
1064
1065 name = name + get_random_number()
1066 return name.lower()
1067
1068 async def _store_status(
beierlmf52cb7c2020-04-21 16:36:35 -04001069 self,
tiernof9bdac22020-06-25 15:48:52 +00001070 cluster_id: str,
beierlmf52cb7c2020-04-21 16:36:35 -04001071 operation: str,
1072 kdu_instance: str,
1073 check_every: float = 10,
1074 db_dict: dict = None,
1075 run_once: bool = False,
quilesj26c78a42019-10-28 18:10:42 +01001076 ):
1077 while True:
1078 try:
1079 await asyncio.sleep(check_every)
tierno119f7232020-04-21 13:22:26 +00001080 detailed_status = await self._status_kdu(
tiernof9bdac22020-06-25 15:48:52 +00001081 cluster_id=cluster_id, kdu_instance=kdu_instance,
tierno119f7232020-04-21 13:22:26 +00001082 return_text=False
beierlmf52cb7c2020-04-21 16:36:35 -04001083 )
1084 status = detailed_status.get("info").get("Description")
tierno119f7232020-04-21 13:22:26 +00001085 self.log.debug('KDU {} STATUS: {}.'.format(kdu_instance, status))
quilesj26c78a42019-10-28 18:10:42 +01001086 # write status to db
1087 result = await self.write_app_status_to_db(
1088 db_dict=db_dict,
1089 status=str(status),
1090 detailed_status=str(detailed_status),
beierlmf52cb7c2020-04-21 16:36:35 -04001091 operation=operation,
1092 )
quilesj26c78a42019-10-28 18:10:42 +01001093 if not result:
beierlmf52cb7c2020-04-21 16:36:35 -04001094 self.log.info("Error writing in database. Task exiting...")
quilesj26c78a42019-10-28 18:10:42 +01001095 return
1096 except asyncio.CancelledError:
beierlmf52cb7c2020-04-21 16:36:35 -04001097 self.log.debug("Task cancelled")
quilesj26c78a42019-10-28 18:10:42 +01001098 return
1099 except Exception as e:
beierlmf52cb7c2020-04-21 16:36:35 -04001100 self.log.debug("_store_status exception: {}".format(str(e)))
quilesj26c78a42019-10-28 18:10:42 +01001101 pass
1102 finally:
1103 if run_once:
1104 return
1105
tiernof9bdac22020-06-25 15:48:52 +00001106 async def _is_install_completed(self, cluster_id: str, kdu_instance: str) -> bool:
quilesj26c78a42019-10-28 18:10:42 +01001107
beierlmf52cb7c2020-04-21 16:36:35 -04001108 status = await self._status_kdu(
tiernof9bdac22020-06-25 15:48:52 +00001109 cluster_id=cluster_id, kdu_instance=kdu_instance, return_text=False
beierlmf52cb7c2020-04-21 16:36:35 -04001110 )
quilesj26c78a42019-10-28 18:10:42 +01001111
1112 # extract info.status.resources-> str
1113 # format:
1114 # ==> v1/Deployment
1115 # NAME READY UP-TO-DATE AVAILABLE AGE
1116 # halting-horse-mongodb 0/1 1 0 0s
1117 # halting-petit-mongodb 1/1 1 0 0s
1118 # blank line
beierlmf52cb7c2020-04-21 16:36:35 -04001119 resources = K8sHelmConnector._get_deep(status, ("info", "status", "resources"))
quilesj26c78a42019-10-28 18:10:42 +01001120
1121 # convert to table
1122 resources = K8sHelmConnector._output_to_table(resources)
1123
1124 num_lines = len(resources)
1125 index = 0
1126 while index < num_lines:
1127 try:
1128 line1 = resources[index]
1129 index += 1
1130 # find '==>' in column 0
beierlmf52cb7c2020-04-21 16:36:35 -04001131 if line1[0] == "==>":
quilesj26c78a42019-10-28 18:10:42 +01001132 line2 = resources[index]
1133 index += 1
1134 # find READY in column 1
beierlmf52cb7c2020-04-21 16:36:35 -04001135 if line2[1] == "READY":
quilesj26c78a42019-10-28 18:10:42 +01001136 # read next lines
1137 line3 = resources[index]
1138 index += 1
1139 while len(line3) > 1 and index < num_lines:
1140 ready_value = line3[1]
beierlmf52cb7c2020-04-21 16:36:35 -04001141 parts = ready_value.split(sep="/")
quilesj26c78a42019-10-28 18:10:42 +01001142 current = int(parts[0])
1143 total = int(parts[1])
1144 if current < total:
beierlmf52cb7c2020-04-21 16:36:35 -04001145 self.log.debug("NOT READY:\n {}".format(line3))
quilesj26c78a42019-10-28 18:10:42 +01001146 ready = False
1147 line3 = resources[index]
1148 index += 1
1149
beierlmf52cb7c2020-04-21 16:36:35 -04001150 except Exception:
quilesj26c78a42019-10-28 18:10:42 +01001151 pass
1152
1153 return ready
1154
1155 @staticmethod
1156 def _get_deep(dictionary: dict, members: tuple):
1157 target = dictionary
1158 value = None
1159 try:
1160 for m in members:
1161 value = target.get(m)
1162 if not value:
1163 return None
1164 else:
1165 target = value
beierlmf52cb7c2020-04-21 16:36:35 -04001166 except Exception:
quilesj26c78a42019-10-28 18:10:42 +01001167 pass
1168 return value
1169
1170 # find key:value in several lines
1171 @staticmethod
1172 def _find_in_lines(p_lines: list, p_key: str) -> str:
1173 for line in p_lines:
1174 try:
beierlmf52cb7c2020-04-21 16:36:35 -04001175 if line.startswith(p_key + ":"):
1176 parts = line.split(":")
quilesj26c78a42019-10-28 18:10:42 +01001177 the_value = parts[1].strip()
1178 return the_value
beierlmf52cb7c2020-04-21 16:36:35 -04001179 except Exception:
quilesj26c78a42019-10-28 18:10:42 +01001180 # ignore it
1181 pass
1182 return None
1183
quilesjcda5f412019-11-18 11:32:12 +01001184 # params for use in -f file
1185 # returns values file option and filename (in order to delete it at the end)
tiernof9bdac22020-06-25 15:48:52 +00001186 def _params_to_file_option(self, cluster_id: str, params: dict) -> (str, str):
quilesjcda5f412019-11-18 11:32:12 +01001187
1188 if params and len(params) > 0:
tiernof9bdac22020-06-25 15:48:52 +00001189 self._get_paths(cluster_name=cluster_id, create_if_not_exist=True)
quilesjcda5f412019-11-18 11:32:12 +01001190
1191 def get_random_number():
1192 r = random.randrange(start=1, stop=99999999)
1193 s = str(r)
1194 while len(s) < 10:
beierlmf52cb7c2020-04-21 16:36:35 -04001195 s = "0" + s
quilesjcda5f412019-11-18 11:32:12 +01001196 return s
1197
1198 params2 = dict()
1199 for key in params:
1200 value = params.get(key)
beierlmf52cb7c2020-04-21 16:36:35 -04001201 if "!!yaml" in str(value):
quilesj1be06302019-11-29 11:17:11 +00001202 value = yaml.load(value[7:])
quilesjcda5f412019-11-18 11:32:12 +01001203 params2[key] = value
1204
beierlmf52cb7c2020-04-21 16:36:35 -04001205 values_file = get_random_number() + ".yaml"
1206 with open(values_file, "w") as stream:
quilesjcda5f412019-11-18 11:32:12 +01001207 yaml.dump(params2, stream, indent=4, default_flow_style=False)
1208
beierlmf52cb7c2020-04-21 16:36:35 -04001209 return "-f {}".format(values_file), values_file
quilesjcda5f412019-11-18 11:32:12 +01001210
beierlmf52cb7c2020-04-21 16:36:35 -04001211 return "", None
quilesjcda5f412019-11-18 11:32:12 +01001212
quilesj26c78a42019-10-28 18:10:42 +01001213 # params for use in --set option
1214 @staticmethod
1215 def _params_to_set_option(params: dict) -> str:
beierlmf52cb7c2020-04-21 16:36:35 -04001216 params_str = ""
quilesj26c78a42019-10-28 18:10:42 +01001217 if params and len(params) > 0:
1218 start = True
1219 for key in params:
1220 value = params.get(key, None)
1221 if value is not None:
1222 if start:
beierlmf52cb7c2020-04-21 16:36:35 -04001223 params_str += "--set "
quilesj26c78a42019-10-28 18:10:42 +01001224 start = False
1225 else:
beierlmf52cb7c2020-04-21 16:36:35 -04001226 params_str += ","
1227 params_str += "{}={}".format(key, value)
quilesj26c78a42019-10-28 18:10:42 +01001228 return params_str
1229
1230 @staticmethod
1231 def _output_to_lines(output: str) -> list:
1232 output_lines = list()
1233 lines = output.splitlines(keepends=False)
1234 for line in lines:
1235 line = line.strip()
1236 if len(line) > 0:
1237 output_lines.append(line)
1238 return output_lines
1239
1240 @staticmethod
1241 def _output_to_table(output: str) -> list:
1242 output_table = list()
1243 lines = output.splitlines(keepends=False)
1244 for line in lines:
beierlmf52cb7c2020-04-21 16:36:35 -04001245 line = line.replace("\t", " ")
quilesj26c78a42019-10-28 18:10:42 +01001246 line_list = list()
1247 output_table.append(line_list)
beierlmf52cb7c2020-04-21 16:36:35 -04001248 cells = line.split(sep=" ")
quilesj26c78a42019-10-28 18:10:42 +01001249 for cell in cells:
1250 cell = cell.strip()
1251 if len(cell) > 0:
1252 line_list.append(cell)
1253 return output_table
1254
beierlmf52cb7c2020-04-21 16:36:35 -04001255 def _get_paths(
1256 self, cluster_name: str, create_if_not_exist: bool = False
1257 ) -> (str, str, str, str):
quilesj26c78a42019-10-28 18:10:42 +01001258 """
1259 Returns kube and helm directories
1260
1261 :param cluster_name:
1262 :param create_if_not_exist:
quilesjcda5f412019-11-18 11:32:12 +01001263 :return: kube, helm directories, config filename and cluster dir.
1264 Raises exception if not exist and cannot create
quilesj26c78a42019-10-28 18:10:42 +01001265 """
1266
1267 base = self.fs.path
1268 if base.endswith("/") or base.endswith("\\"):
1269 base = base[:-1]
1270
1271 # base dir for cluster
beierlmf52cb7c2020-04-21 16:36:35 -04001272 cluster_dir = base + "/" + cluster_name
quilesj26c78a42019-10-28 18:10:42 +01001273 if create_if_not_exist and not os.path.exists(cluster_dir):
beierlmf52cb7c2020-04-21 16:36:35 -04001274 self.log.debug("Creating dir {}".format(cluster_dir))
quilesj26c78a42019-10-28 18:10:42 +01001275 os.makedirs(cluster_dir)
1276 if not os.path.exists(cluster_dir):
beierlmf52cb7c2020-04-21 16:36:35 -04001277 msg = "Base cluster dir {} does not exist".format(cluster_dir)
Dominik Fleischmannf9bed352020-02-27 10:04:34 +01001278 self.log.error(msg)
quilesja6748412019-12-04 07:51:26 +00001279 raise K8sException(msg)
quilesj26c78a42019-10-28 18:10:42 +01001280
1281 # kube dir
beierlmf52cb7c2020-04-21 16:36:35 -04001282 kube_dir = cluster_dir + "/" + ".kube"
quilesj26c78a42019-10-28 18:10:42 +01001283 if create_if_not_exist and not os.path.exists(kube_dir):
beierlmf52cb7c2020-04-21 16:36:35 -04001284 self.log.debug("Creating dir {}".format(kube_dir))
quilesj26c78a42019-10-28 18:10:42 +01001285 os.makedirs(kube_dir)
1286 if not os.path.exists(kube_dir):
beierlmf52cb7c2020-04-21 16:36:35 -04001287 msg = "Kube config dir {} does not exist".format(kube_dir)
Dominik Fleischmannf9bed352020-02-27 10:04:34 +01001288 self.log.error(msg)
quilesja6748412019-12-04 07:51:26 +00001289 raise K8sException(msg)
quilesj26c78a42019-10-28 18:10:42 +01001290
1291 # helm home dir
beierlmf52cb7c2020-04-21 16:36:35 -04001292 helm_dir = cluster_dir + "/" + ".helm"
quilesj26c78a42019-10-28 18:10:42 +01001293 if create_if_not_exist and not os.path.exists(helm_dir):
beierlmf52cb7c2020-04-21 16:36:35 -04001294 self.log.debug("Creating dir {}".format(helm_dir))
quilesj26c78a42019-10-28 18:10:42 +01001295 os.makedirs(helm_dir)
1296 if not os.path.exists(helm_dir):
beierlmf52cb7c2020-04-21 16:36:35 -04001297 msg = "Helm config dir {} does not exist".format(helm_dir)
Dominik Fleischmannf9bed352020-02-27 10:04:34 +01001298 self.log.error(msg)
quilesja6748412019-12-04 07:51:26 +00001299 raise K8sException(msg)
quilesj26c78a42019-10-28 18:10:42 +01001300
beierlmf52cb7c2020-04-21 16:36:35 -04001301 config_filename = kube_dir + "/config"
quilesjcda5f412019-11-18 11:32:12 +01001302 return kube_dir, helm_dir, config_filename, cluster_dir
quilesj26c78a42019-10-28 18:10:42 +01001303
1304 @staticmethod
beierlmf52cb7c2020-04-21 16:36:35 -04001305 def _remove_multiple_spaces(strobj):
1306 strobj = strobj.strip()
1307 while " " in strobj:
1308 strobj = strobj.replace(" ", " ")
1309 return strobj
quilesj26c78a42019-10-28 18:10:42 +01001310
beierlmf52cb7c2020-04-21 16:36:35 -04001311 def _local_exec(self, command: str) -> (str, int):
quilesj26c78a42019-10-28 18:10:42 +01001312 command = K8sHelmConnector._remove_multiple_spaces(command)
beierlmf52cb7c2020-04-21 16:36:35 -04001313 self.log.debug("Executing sync local command: {}".format(command))
quilesj26c78a42019-10-28 18:10:42 +01001314 # raise exception if fails
beierlmf52cb7c2020-04-21 16:36:35 -04001315 output = ""
quilesj26c78a42019-10-28 18:10:42 +01001316 try:
beierlmf52cb7c2020-04-21 16:36:35 -04001317 output = subprocess.check_output(
1318 command, shell=True, universal_newlines=True
1319 )
quilesj26c78a42019-10-28 18:10:42 +01001320 return_code = 0
Dominik Fleischmannf9bed352020-02-27 10:04:34 +01001321 self.log.debug(output)
beierlmf52cb7c2020-04-21 16:36:35 -04001322 except Exception:
quilesj26c78a42019-10-28 18:10:42 +01001323 return_code = 1
1324
1325 return output, return_code
1326
1327 async def _local_async_exec(
beierlmf52cb7c2020-04-21 16:36:35 -04001328 self,
1329 command: str,
1330 raise_exception_on_error: bool = False,
1331 show_error_log: bool = True,
1332 encode_utf8: bool = False,
quilesj26c78a42019-10-28 18:10:42 +01001333 ) -> (str, int):
1334
1335 command = K8sHelmConnector._remove_multiple_spaces(command)
beierlmf52cb7c2020-04-21 16:36:35 -04001336 self.log.debug("Executing async local command: {}".format(command))
quilesj26c78a42019-10-28 18:10:42 +01001337
1338 # split command
beierlmf52cb7c2020-04-21 16:36:35 -04001339 command = command.split(sep=" ")
quilesj26c78a42019-10-28 18:10:42 +01001340
1341 try:
1342 process = await asyncio.create_subprocess_exec(
beierlmf52cb7c2020-04-21 16:36:35 -04001343 *command, stdout=asyncio.subprocess.PIPE, stderr=asyncio.subprocess.PIPE
quilesj26c78a42019-10-28 18:10:42 +01001344 )
1345
1346 # wait for command terminate
1347 stdout, stderr = await process.communicate()
1348
1349 return_code = process.returncode
1350
beierlmf52cb7c2020-04-21 16:36:35 -04001351 output = ""
quilesj26c78a42019-10-28 18:10:42 +01001352 if stdout:
beierlmf52cb7c2020-04-21 16:36:35 -04001353 output = stdout.decode("utf-8").strip()
quilesj1be06302019-11-29 11:17:11 +00001354 # output = stdout.decode()
quilesj26c78a42019-10-28 18:10:42 +01001355 if stderr:
beierlmf52cb7c2020-04-21 16:36:35 -04001356 output = stderr.decode("utf-8").strip()
quilesj1be06302019-11-29 11:17:11 +00001357 # output = stderr.decode()
quilesj26c78a42019-10-28 18:10:42 +01001358
1359 if return_code != 0 and show_error_log:
beierlmf52cb7c2020-04-21 16:36:35 -04001360 self.log.debug(
1361 "Return code (FAIL): {}\nOutput:\n{}".format(return_code, output)
1362 )
quilesj26c78a42019-10-28 18:10:42 +01001363 else:
beierlmf52cb7c2020-04-21 16:36:35 -04001364 self.log.debug("Return code: {}".format(return_code))
quilesj26c78a42019-10-28 18:10:42 +01001365
1366 if raise_exception_on_error and return_code != 0:
tierno601697a2020-02-04 15:26:25 +00001367 raise K8sException(output)
quilesj26c78a42019-10-28 18:10:42 +01001368
quilesj1be06302019-11-29 11:17:11 +00001369 if encode_utf8:
beierlmf52cb7c2020-04-21 16:36:35 -04001370 output = output.encode("utf-8").strip()
1371 output = str(output).replace("\\n", "\n")
quilesj1be06302019-11-29 11:17:11 +00001372
quilesj26c78a42019-10-28 18:10:42 +01001373 return output, return_code
1374
lloretgallegdd0cdee2020-02-26 10:00:16 +01001375 except asyncio.CancelledError:
1376 raise
tierno601697a2020-02-04 15:26:25 +00001377 except K8sException:
1378 raise
quilesj26c78a42019-10-28 18:10:42 +01001379 except Exception as e:
beierlmf52cb7c2020-04-21 16:36:35 -04001380 msg = "Exception executing command: {} -> {}".format(command, e)
Dominik Fleischmannf9bed352020-02-27 10:04:34 +01001381 self.log.error(msg)
quilesj32dc3c62020-01-23 16:30:04 +00001382 if raise_exception_on_error:
tierno601697a2020-02-04 15:26:25 +00001383 raise K8sException(e) from e
quilesj32dc3c62020-01-23 16:30:04 +00001384 else:
beierlmf52cb7c2020-04-21 16:36:35 -04001385 return "", -1
quilesj26c78a42019-10-28 18:10:42 +01001386
quilesj26c78a42019-10-28 18:10:42 +01001387 def _check_file_exists(self, filename: str, exception_if_not_exists: bool = False):
tierno8ff11992020-03-26 09:51:11 +00001388 # self.log.debug('Checking if file {} exists...'.format(filename))
quilesj26c78a42019-10-28 18:10:42 +01001389 if os.path.exists(filename):
1390 return True
1391 else:
beierlmf52cb7c2020-04-21 16:36:35 -04001392 msg = "File {} does not exist".format(filename)
quilesj26c78a42019-10-28 18:10:42 +01001393 if exception_if_not_exists:
tierno8ff11992020-03-26 09:51:11 +00001394 # self.log.error(msg)
quilesja6748412019-12-04 07:51:26 +00001395 raise K8sException(msg)