2 # Copyright 2019 Telefonica Investigacion y Desarrollo, S.A.U.
3 # This file is part of OSM
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
10 # http://www.apache.org/licenses/LICENSE-2.0
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
16 # See the License for the specific language governing permissions and
17 # limitations under the License.
19 # For those usages not covered by the Apache License, Version 2.0 please
20 # contact with: nfvlabs@tid.es
29 from uuid
import uuid4
31 from n2vc
.exceptions
import K8sException
32 from n2vc
.k8s_conn
import K8sConnector
36 class K8sHelmConnector(K8sConnector
):
39 ####################################################################################
40 ################################### P U B L I C ####################################
41 ####################################################################################
48 kubectl_command
: str = "/usr/bin/kubectl",
49 helm_command
: str = "/usr/bin/helm",
55 :param fs: file system for kubernetes and helm configuration
56 :param db: database object to write current operation status
57 :param kubectl_command: path to kubectl executable
58 :param helm_command: path to helm executable
60 :param on_update_db: callback called when k8s connector updates database
64 K8sConnector
.__init
__(self
, db
=db
, log
=log
, on_update_db
=on_update_db
)
66 self
.log
.info("Initializing K8S Helm connector")
68 # random numbers for release name generation
69 random
.seed(time
.time())
74 # exception if kubectl is not installed
75 self
.kubectl_command
= kubectl_command
76 self
._check
_file
_exists
(filename
=kubectl_command
, exception_if_not_exists
=True)
78 # exception if helm is not installed
79 self
._helm
_command
= helm_command
80 self
._check
_file
_exists
(filename
=helm_command
, exception_if_not_exists
=True)
82 # initialize helm client-only
83 self
.log
.debug("Initializing helm client-only...")
84 command
= "{} init --client-only".format(self
._helm
_command
)
86 asyncio
.ensure_future(
87 self
._local
_async
_exec
(command
=command
, raise_exception_on_error
=False)
89 # loop = asyncio.get_event_loop()
90 # loop.run_until_complete(self._local_async_exec(command=command,
91 # raise_exception_on_error=False))
92 except Exception as e
:
94 msg
="helm init failed (it was already initialized): {}".format(e
)
97 self
.log
.info("K8S Helm connector initialized")
100 self
, k8s_creds
: str, namespace
: str = "kube-system", reuse_cluster_uuid
=None
103 It prepares a given K8s cluster environment to run Charts on both sides:
107 :param k8s_creds: credentials to access a given K8s cluster, i.e. a valid
109 :param namespace: optional namespace to be used for helm. By default,
110 'kube-system' will be used
111 :param reuse_cluster_uuid: existing cluster uuid for reuse
112 :return: uuid of the K8s cluster and True if connector has installed some
113 software in the cluster
114 (on error, an exception will be raised)
117 cluster_uuid
= reuse_cluster_uuid
119 cluster_uuid
= str(uuid4())
121 self
.log
.debug("Initializing K8S environment. namespace: {}".format(namespace
))
123 # create config filename
124 _kube_dir
, helm_dir
, config_filename
, _cluster_dir
= self
._get
_paths
(
125 cluster_name
=cluster_uuid
, create_if_not_exist
=True
127 with
open(config_filename
, "w") as f
:
130 # check if tiller pod is up in cluster
131 command
= "{} --kubeconfig={} --namespace={} get deployments".format(
132 self
.kubectl_command
, config_filename
, namespace
134 output
, _rc
= await self
._local
_async
_exec
(
135 command
=command
, raise_exception_on_error
=True
138 output_table
= self
._output
_to
_table
(output
=output
)
140 # find 'tiller' pod in all pods
141 already_initialized
= False
143 for row
in output_table
:
144 if row
[0].startswith("tiller-deploy"):
145 already_initialized
= True
151 n2vc_installed_sw
= False
152 if not already_initialized
:
154 "Initializing helm in client and server: {}".format(cluster_uuid
)
156 command
= "{} --kubeconfig={} --tiller-namespace={} --home={} init".format(
157 self
._helm
_command
, config_filename
, namespace
, helm_dir
159 output
, _rc
= await self
._local
_async
_exec
(
160 command
=command
, raise_exception_on_error
=True
162 n2vc_installed_sw
= True
164 # check client helm installation
165 check_file
= helm_dir
+ "/repository/repositories.yaml"
166 if not self
._check
_file
_exists
(
167 filename
=check_file
, exception_if_not_exists
=False
169 self
.log
.info("Initializing helm in client: {}".format(cluster_uuid
))
171 "{} --kubeconfig={} --tiller-namespace={} "
172 "--home={} init --client-only"
173 ).format(self
._helm
_command
, config_filename
, namespace
, helm_dir
)
174 output
, _rc
= await self
._local
_async
_exec
(
175 command
=command
, raise_exception_on_error
=True
178 self
.log
.info("Helm client already initialized")
180 self
.log
.info("Cluster initialized {}".format(cluster_uuid
))
182 return cluster_uuid
, n2vc_installed_sw
185 self
, cluster_uuid
: str, name
: str, url
: str, repo_type
: str = "chart"
188 self
.log
.debug("adding {} repository {}. URL: {}".format(repo_type
, name
, url
))
191 _kube_dir
, helm_dir
, config_filename
, _cluster_dir
= self
._get
_paths
(
192 cluster_name
=cluster_uuid
, create_if_not_exist
=True
196 command
= "{} --kubeconfig={} --home={} repo update".format(
197 self
._helm
_command
, config_filename
, helm_dir
199 self
.log
.debug("updating repo: {}".format(command
))
200 await self
._local
_async
_exec
(command
=command
, raise_exception_on_error
=False)
202 # helm repo add name url
203 command
= "{} --kubeconfig={} --home={} repo add {} {}".format(
204 self
._helm
_command
, config_filename
, helm_dir
, name
, url
206 self
.log
.debug("adding repo: {}".format(command
))
207 await self
._local
_async
_exec
(command
=command
, raise_exception_on_error
=True)
209 async def repo_list(self
, cluster_uuid
: str) -> list:
211 Get the list of registered repositories
213 :return: list of registered repositories: [ (name, url) .... ]
216 self
.log
.debug("list repositories for cluster {}".format(cluster_uuid
))
219 _kube_dir
, helm_dir
, config_filename
, _cluster_dir
= self
._get
_paths
(
220 cluster_name
=cluster_uuid
, create_if_not_exist
=True
223 command
= "{} --kubeconfig={} --home={} repo list --output yaml".format(
224 self
._helm
_command
, config_filename
, helm_dir
227 output
, _rc
= await self
._local
_async
_exec
(
228 command
=command
, raise_exception_on_error
=True
230 if output
and len(output
) > 0:
231 return yaml
.load(output
, Loader
=yaml
.SafeLoader
)
235 async def repo_remove(self
, cluster_uuid
: str, name
: str):
237 Remove a repository from OSM
239 :param cluster_uuid: the cluster
240 :param name: repo name in OSM
241 :return: True if successful
244 self
.log
.debug("list repositories for cluster {}".format(cluster_uuid
))
247 _kube_dir
, helm_dir
, config_filename
, _cluster_dir
= self
._get
_paths
(
248 cluster_name
=cluster_uuid
, create_if_not_exist
=True
251 command
= "{} --kubeconfig={} --home={} repo remove {}".format(
252 self
._helm
_command
, config_filename
, helm_dir
, name
255 await self
._local
_async
_exec
(command
=command
, raise_exception_on_error
=True)
258 self
, cluster_uuid
: str, force
: bool = False, uninstall_sw
: bool = False
262 "Resetting K8s environment. cluster uuid: {}".format(cluster_uuid
)
265 # get kube and helm directories
266 _kube_dir
, helm_dir
, config_filename
, _cluster_dir
= self
._get
_paths
(
267 cluster_name
=cluster_uuid
, create_if_not_exist
=False
270 # uninstall releases if needed
271 releases
= await self
.instances_list(cluster_uuid
=cluster_uuid
)
272 if len(releases
) > 0:
276 kdu_instance
= r
.get("Name")
277 chart
= r
.get("Chart")
279 "Uninstalling {} -> {}".format(chart
, kdu_instance
)
281 await self
.uninstall(
282 cluster_uuid
=cluster_uuid
, kdu_instance
=kdu_instance
284 except Exception as e
:
286 "Error uninstalling release {}: {}".format(kdu_instance
, e
)
290 "Cluster has releases and not force. Cannot reset K8s "
291 "environment. Cluster uuid: {}"
292 ).format(cluster_uuid
)
294 raise K8sException(msg
)
298 self
.log
.debug("Uninstalling tiller from cluster {}".format(cluster_uuid
))
300 # find namespace for tiller pod
301 command
= "{} --kubeconfig={} get deployments --all-namespaces".format(
302 self
.kubectl_command
, config_filename
304 output
, _rc
= await self
._local
_async
_exec
(
305 command
=command
, raise_exception_on_error
=False
307 output_table
= K8sHelmConnector
._output
_to
_table
(output
=output
)
309 for r
in output_table
:
311 if "tiller-deploy" in r
[1]:
317 msg
= "Tiller deployment not found in cluster {}".format(cluster_uuid
)
320 self
.log
.debug("namespace for tiller: {}".format(namespace
))
322 force_str
= "--force"
325 # delete tiller deployment
327 "Deleting tiller deployment for cluster {}, namespace {}".format(
328 cluster_uuid
, namespace
332 "{} --namespace {} --kubeconfig={} {} delete deployment "
334 ).format(self
.kubectl_command
, namespace
, config_filename
, force_str
)
335 await self
._local
_async
_exec
(
336 command
=command
, raise_exception_on_error
=False
339 # uninstall tiller from cluster
341 "Uninstalling tiller from cluster {}".format(cluster_uuid
)
343 command
= "{} --kubeconfig={} --home={} reset".format(
344 self
._helm
_command
, config_filename
, helm_dir
346 self
.log
.debug("resetting: {}".format(command
))
347 output
, _rc
= await self
._local
_async
_exec
(
348 command
=command
, raise_exception_on_error
=True
351 self
.log
.debug("namespace not found")
353 # delete cluster directory
354 direct
= self
.fs
.path
+ "/" + cluster_uuid
355 self
.log
.debug("Removing directory {}".format(direct
))
356 shutil
.rmtree(direct
, ignore_errors
=True)
365 timeout
: float = 300,
367 db_dict
: dict = None,
368 kdu_name
: str = None,
369 namespace
: str = None,
372 self
.log
.debug("installing {} in cluster {}".format(kdu_model
, cluster_uuid
))
375 _kube_dir
, helm_dir
, config_filename
, _cluster_dir
= self
._get
_paths
(
376 cluster_name
=cluster_uuid
, create_if_not_exist
=True
380 # params_str = K8sHelmConnector._params_to_set_option(params)
381 params_str
, file_to_delete
= self
._params
_to
_file
_option
(
382 cluster_uuid
=cluster_uuid
, params
=params
387 timeout_str
= "--timeout {}".format(timeout
)
392 atomic_str
= "--atomic"
396 namespace_str
= "--namespace {}".format(namespace
)
401 parts
= kdu_model
.split(sep
=":")
403 version_str
= "--version {}".format(parts
[1])
406 # generate a name for the release. Then, check if already exists
408 while kdu_instance
is None:
409 kdu_instance
= K8sHelmConnector
._generate
_release
_name
(kdu_model
)
411 result
= await self
._status
_kdu
(
412 cluster_uuid
=cluster_uuid
,
413 kdu_instance
=kdu_instance
,
414 show_error_log
=False,
416 if result
is not None:
417 # instance already exists: generate a new one
424 "{helm} install {atomic} --output yaml --kubeconfig={config} --home={dir} "
425 "{params} {timeout} --name={name} {ns} {model} {ver}".format(
426 helm
=self
._helm
_command
,
428 config
=config_filename
,
438 self
.log
.debug("installing: {}".format(command
))
441 # exec helm in a task
442 exec_task
= asyncio
.ensure_future(
443 coro_or_future
=self
._local
_async
_exec
(
444 command
=command
, raise_exception_on_error
=False
448 # write status in another task
449 status_task
= asyncio
.ensure_future(
450 coro_or_future
=self
._store
_status
(
451 cluster_uuid
=cluster_uuid
,
452 kdu_instance
=kdu_instance
,
459 # wait for execution task
460 await asyncio
.wait([exec_task
])
465 output
, rc
= exec_task
.result()
469 output
, rc
= await self
._local
_async
_exec
(
470 command
=command
, raise_exception_on_error
=False
473 # remove temporal values yaml file
475 os
.remove(file_to_delete
)
478 await self
._store
_status
(
479 cluster_uuid
=cluster_uuid
,
480 kdu_instance
=kdu_instance
,
488 msg
= "Error executing command: {}\nOutput: {}".format(command
, output
)
490 raise K8sException(msg
)
492 self
.log
.debug("Returning kdu_instance {}".format(kdu_instance
))
495 async def instances_list(self
, cluster_uuid
: str) -> list:
497 returns a list of deployed releases in a cluster
499 :param cluster_uuid: the cluster
503 self
.log
.debug("list releases for cluster {}".format(cluster_uuid
))
506 _kube_dir
, helm_dir
, config_filename
, _cluster_dir
= self
._get
_paths
(
507 cluster_name
=cluster_uuid
, create_if_not_exist
=True
510 command
= "{} --kubeconfig={} --home={} list --output yaml".format(
511 self
._helm
_command
, config_filename
, helm_dir
514 output
, _rc
= await self
._local
_async
_exec
(
515 command
=command
, raise_exception_on_error
=True
518 if output
and len(output
) > 0:
519 return yaml
.load(output
, Loader
=yaml
.SafeLoader
).get("Releases")
527 kdu_model
: str = None,
529 timeout
: float = 300,
531 db_dict
: dict = None,
534 self
.log
.debug("upgrading {} in cluster {}".format(kdu_model
, cluster_uuid
))
537 _kube_dir
, helm_dir
, config_filename
, _cluster_dir
= self
._get
_paths
(
538 cluster_name
=cluster_uuid
, create_if_not_exist
=True
542 # params_str = K8sHelmConnector._params_to_set_option(params)
543 params_str
, file_to_delete
= self
._params
_to
_file
_option
(
544 cluster_uuid
=cluster_uuid
, params
=params
549 timeout_str
= "--timeout {}".format(timeout
)
554 atomic_str
= "--atomic"
558 if kdu_model
and ":" in kdu_model
:
559 parts
= kdu_model
.split(sep
=":")
561 version_str
= "--version {}".format(parts
[1])
566 "{} upgrade {} --output yaml --kubeconfig={} " "--home={} {} {} {} {} {}"
578 self
.log
.debug("upgrading: {}".format(command
))
582 # exec helm in a task
583 exec_task
= asyncio
.ensure_future(
584 coro_or_future
=self
._local
_async
_exec
(
585 command
=command
, raise_exception_on_error
=False
588 # write status in another task
589 status_task
= asyncio
.ensure_future(
590 coro_or_future
=self
._store
_status
(
591 cluster_uuid
=cluster_uuid
,
592 kdu_instance
=kdu_instance
,
599 # wait for execution task
600 await asyncio
.wait([exec_task
])
604 output
, rc
= exec_task
.result()
608 output
, rc
= await self
._local
_async
_exec
(
609 command
=command
, raise_exception_on_error
=False
612 # remove temporal values yaml file
614 os
.remove(file_to_delete
)
617 await self
._store
_status
(
618 cluster_uuid
=cluster_uuid
,
619 kdu_instance
=kdu_instance
,
627 msg
= "Error executing command: {}\nOutput: {}".format(command
, output
)
629 raise K8sException(msg
)
631 # return new revision number
632 instance
= await self
.get_instance_info(
633 cluster_uuid
=cluster_uuid
, kdu_instance
=kdu_instance
636 revision
= int(instance
.get("Revision"))
637 self
.log
.debug("New revision: {}".format(revision
))
643 self
, cluster_uuid
: str, kdu_instance
: str, revision
=0, db_dict
: dict = None
647 "rollback kdu_instance {} to revision {} from cluster {}".format(
648 kdu_instance
, revision
, cluster_uuid
653 _kube_dir
, helm_dir
, config_filename
, _cluster_dir
= self
._get
_paths
(
654 cluster_name
=cluster_uuid
, create_if_not_exist
=True
657 command
= "{} rollback --kubeconfig={} --home={} {} {} --wait".format(
658 self
._helm
_command
, config_filename
, helm_dir
, kdu_instance
, revision
661 # exec helm in a task
662 exec_task
= asyncio
.ensure_future(
663 coro_or_future
=self
._local
_async
_exec
(
664 command
=command
, raise_exception_on_error
=False
667 # write status in another task
668 status_task
= asyncio
.ensure_future(
669 coro_or_future
=self
._store
_status
(
670 cluster_uuid
=cluster_uuid
,
671 kdu_instance
=kdu_instance
,
673 operation
="rollback",
678 # wait for execution task
679 await asyncio
.wait([exec_task
])
684 output
, rc
= exec_task
.result()
687 await self
._store
_status
(
688 cluster_uuid
=cluster_uuid
,
689 kdu_instance
=kdu_instance
,
691 operation
="rollback",
697 msg
= "Error executing command: {}\nOutput: {}".format(command
, output
)
699 raise K8sException(msg
)
701 # return new revision number
702 instance
= await self
.get_instance_info(
703 cluster_uuid
=cluster_uuid
, kdu_instance
=kdu_instance
706 revision
= int(instance
.get("Revision"))
707 self
.log
.debug("New revision: {}".format(revision
))
712 async def uninstall(self
, cluster_uuid
: str, kdu_instance
: str):
714 Removes an existing KDU instance. It would implicitly use the `delete` call
715 (this call would happen after all _terminate-config-primitive_ of the VNF
718 :param cluster_uuid: UUID of a K8s cluster known by OSM
719 :param kdu_instance: unique name for the KDU instance to be deleted
720 :return: True if successful
724 "uninstall kdu_instance {} from cluster {}".format(
725 kdu_instance
, cluster_uuid
730 _kube_dir
, helm_dir
, config_filename
, _cluster_dir
= self
._get
_paths
(
731 cluster_name
=cluster_uuid
, create_if_not_exist
=True
734 command
= "{} --kubeconfig={} --home={} delete --purge {}".format(
735 self
._helm
_command
, config_filename
, helm_dir
, kdu_instance
738 output
, _rc
= await self
._local
_async
_exec
(
739 command
=command
, raise_exception_on_error
=True
742 return self
._output
_to
_table
(output
)
744 async def exec_primitive(
746 cluster_uuid
: str = None,
747 kdu_instance
: str = None,
748 primitive_name
: str = None,
749 timeout
: float = 300,
751 db_dict
: dict = None,
753 """Exec primitive (Juju action)
755 :param cluster_uuid str: The UUID of the cluster
756 :param kdu_instance str: The unique name of the KDU instance
757 :param primitive_name: Name of action that will be executed
758 :param timeout: Timeout for action execution
759 :param params: Dictionary of all the parameters needed for the action
760 :db_dict: Dictionary for any additional data
762 :return: Returns the output of the action
765 "KDUs deployed with Helm don't support actions "
766 "different from rollback, upgrade and status"
769 async def inspect_kdu(self
, kdu_model
: str, repo_url
: str = None) -> str:
772 "inspect kdu_model {} from (optional) repo: {}".format(kdu_model
, repo_url
)
775 return await self
._exec
_inspect
_comand
(
776 inspect_command
="", kdu_model
=kdu_model
, repo_url
=repo_url
779 async def values_kdu(self
, kdu_model
: str, repo_url
: str = None) -> str:
782 "inspect kdu_model values {} from (optional) repo: {}".format(
787 return await self
._exec
_inspect
_comand
(
788 inspect_command
="values", kdu_model
=kdu_model
, repo_url
=repo_url
791 async def help_kdu(self
, kdu_model
: str, repo_url
: str = None) -> str:
794 "inspect kdu_model {} readme.md from repo: {}".format(kdu_model
, repo_url
)
797 return await self
._exec
_inspect
_comand
(
798 inspect_command
="readme", kdu_model
=kdu_model
, repo_url
=repo_url
801 async def status_kdu(self
, cluster_uuid
: str, kdu_instance
: str) -> str:
803 # call internal function
804 return await self
._status
_kdu
(
805 cluster_uuid
=cluster_uuid
,
806 kdu_instance
=kdu_instance
,
811 async def synchronize_repos(self
, cluster_uuid
: str):
813 self
.log
.debug("syncronize repos for cluster helm-id: {}",)
815 update_repos_timeout
= (
816 300 # max timeout to sync a single repos, more than this is too much
818 db_k8scluster
= self
.db
.get_one(
819 "k8sclusters", {"_admin.helm-chart.id": cluster_uuid
}
823 db_k8scluster
.get("_admin").get("helm_chart_repos") or []
825 cluster_repo_dict
= (
826 db_k8scluster
.get("_admin").get("helm_charts_added") or {}
828 # elements that must be deleted
829 deleted_repo_list
= []
831 self
.log
.debug("helm_chart_repos: {}".format(nbi_repo_list
))
832 self
.log
.debug("helm_charts_added: {}".format(cluster_repo_dict
))
834 # obtain repos to add: registered by nbi but not added
836 repo
for repo
in nbi_repo_list
if not cluster_repo_dict
.get(repo
)
839 # obtain repos to delete: added by cluster but not in nbi list
842 for repo
in cluster_repo_dict
.keys()
843 if repo
not in nbi_repo_list
846 # delete repos: must delete first then add because there may be
847 # different repos with same name but
848 # different id and url
849 self
.log
.debug("repos to delete: {}".format(repos_to_delete
))
850 for repo_id
in repos_to_delete
:
851 # try to delete repos
853 repo_delete_task
= asyncio
.ensure_future(
855 cluster_uuid
=cluster_uuid
,
856 name
=cluster_repo_dict
[repo_id
],
859 await asyncio
.wait_for(repo_delete_task
, update_repos_timeout
)
860 except Exception as e
:
862 "Error deleting repo, id: {}, name: {}, err_msg: {}".format(
863 repo_id
, cluster_repo_dict
[repo_id
], str(e
)
866 # always add to the list of to_delete if there is an error
867 # because if is not there
868 # deleting raises error
869 deleted_repo_list
.append(repo_id
)
872 self
.log
.debug("repos to add: {}".format(repos_to_add
))
873 for repo_id
in repos_to_add
:
874 # obtain the repo data from the db
875 # if there is an error getting the repo in the database we will
876 # ignore this repo and continue
877 # because there is a possible race condition where the repo has
878 # been deleted while processing
879 db_repo
= self
.db
.get_one("k8srepos", {"_id": repo_id
})
881 "obtained repo: id, {}, name: {}, url: {}".format(
882 repo_id
, db_repo
["name"], db_repo
["url"]
886 repo_add_task
= asyncio
.ensure_future(
888 cluster_uuid
=cluster_uuid
,
889 name
=db_repo
["name"],
894 await asyncio
.wait_for(repo_add_task
, update_repos_timeout
)
895 added_repo_dict
[repo_id
] = db_repo
["name"]
897 "added repo: id, {}, name: {}".format(
898 repo_id
, db_repo
["name"]
901 except Exception as e
:
902 # deal with error adding repo, adding a repo that already
903 # exists does not raise any error
904 # will not raise error because a wrong repos added by
905 # anyone could prevent instantiating any ns
907 "Error adding repo id: {}, err_msg: {} ".format(
912 return deleted_repo_list
, added_repo_dict
914 else: # else db_k8scluster does not exist
916 "k8cluster with helm-id : {} not found".format(cluster_uuid
)
919 except Exception as e
:
920 self
.log
.error("Error synchronizing repos: {}".format(str(e
)))
921 raise K8sException("Error synchronizing repos")
924 ####################################################################################
925 ################################### P R I V A T E ##################################
926 ####################################################################################
929 async def _exec_inspect_comand(
930 self
, inspect_command
: str, kdu_model
: str, repo_url
: str = None
935 repo_str
= " --repo {}".format(repo_url
)
936 idx
= kdu_model
.find("/")
939 kdu_model
= kdu_model
[idx
:]
941 inspect_command
= "{} inspect {} {}{}".format(
942 self
._helm
_command
, inspect_command
, kdu_model
, repo_str
944 output
, _rc
= await self
._local
_async
_exec
(
945 command
=inspect_command
, encode_utf8
=True
950 async def _status_kdu(
954 show_error_log
: bool = False,
955 return_text
: bool = False,
958 self
.log
.debug("status of kdu_instance {}".format(kdu_instance
))
961 _kube_dir
, helm_dir
, config_filename
, _cluster_dir
= self
._get
_paths
(
962 cluster_name
=cluster_uuid
, create_if_not_exist
=True
965 command
= "{} --kubeconfig={} --home={} status {} --output yaml".format(
966 self
._helm
_command
, config_filename
, helm_dir
, kdu_instance
969 output
, rc
= await self
._local
_async
_exec
(
971 raise_exception_on_error
=True,
972 show_error_log
=show_error_log
,
981 data
= yaml
.load(output
, Loader
=yaml
.SafeLoader
)
983 # remove field 'notes'
985 del data
.get("info").get("status")["notes"]
989 # parse field 'resources'
991 resources
= str(data
.get("info").get("status").get("resources"))
992 resource_table
= self
._output
_to
_table
(resources
)
993 data
.get("info").get("status")["resources"] = resource_table
999 async def get_instance_info(self
, cluster_uuid
: str, kdu_instance
: str):
1000 instances
= await self
.instances_list(cluster_uuid
=cluster_uuid
)
1001 for instance
in instances
:
1002 if instance
.get("Name") == kdu_instance
:
1004 self
.log
.debug("Instance {} not found".format(kdu_instance
))
1008 def _generate_release_name(chart_name
: str):
1009 # check embeded chart (file or dir)
1010 if chart_name
.startswith("/"):
1011 # extract file or directory name
1012 chart_name
= chart_name
[chart_name
.rfind("/") + 1 :]
1014 elif "://" in chart_name
:
1015 # extract last portion of URL
1016 chart_name
= chart_name
[chart_name
.rfind("/") + 1 :]
1019 for c
in chart_name
:
1020 if c
.isalpha() or c
.isnumeric():
1027 # if does not start with alpha character, prefix 'a'
1028 if not name
[0].isalpha():
1033 def get_random_number():
1034 r
= random
.randrange(start
=1, stop
=99999999)
1036 s
= s
.rjust(10, "0")
1039 name
= name
+ get_random_number()
1042 async def _store_status(
1047 check_every
: float = 10,
1048 db_dict
: dict = None,
1049 run_once
: bool = False,
1053 await asyncio
.sleep(check_every
)
1054 detailed_status
= await self
._status
_kdu
(
1055 cluster_uuid
=cluster_uuid
, kdu_instance
=kdu_instance
,
1058 status
= detailed_status
.get("info").get("Description")
1059 self
.log
.debug('KDU {} STATUS: {}.'.format(kdu_instance
, status
))
1060 # write status to db
1061 result
= await self
.write_app_status_to_db(
1064 detailed_status
=str(detailed_status
),
1065 operation
=operation
,
1068 self
.log
.info("Error writing in database. Task exiting...")
1070 except asyncio
.CancelledError
:
1071 self
.log
.debug("Task cancelled")
1073 except Exception as e
:
1074 self
.log
.debug("_store_status exception: {}".format(str(e
)))
1080 async def _is_install_completed(self
, cluster_uuid
: str, kdu_instance
: str) -> bool:
1082 status
= await self
._status
_kdu
(
1083 cluster_uuid
=cluster_uuid
, kdu_instance
=kdu_instance
, return_text
=False
1086 # extract info.status.resources-> str
1089 # NAME READY UP-TO-DATE AVAILABLE AGE
1090 # halting-horse-mongodb 0/1 1 0 0s
1091 # halting-petit-mongodb 1/1 1 0 0s
1093 resources
= K8sHelmConnector
._get
_deep
(status
, ("info", "status", "resources"))
1096 resources
= K8sHelmConnector
._output
_to
_table
(resources
)
1098 num_lines
= len(resources
)
1100 while index
< num_lines
:
1102 line1
= resources
[index
]
1104 # find '==>' in column 0
1105 if line1
[0] == "==>":
1106 line2
= resources
[index
]
1108 # find READY in column 1
1109 if line2
[1] == "READY":
1111 line3
= resources
[index
]
1113 while len(line3
) > 1 and index
< num_lines
:
1114 ready_value
= line3
[1]
1115 parts
= ready_value
.split(sep
="/")
1116 current
= int(parts
[0])
1117 total
= int(parts
[1])
1119 self
.log
.debug("NOT READY:\n {}".format(line3
))
1121 line3
= resources
[index
]
1130 def _get_deep(dictionary
: dict, members
: tuple):
1135 value
= target
.get(m
)
1144 # find key:value in several lines
1146 def _find_in_lines(p_lines
: list, p_key
: str) -> str:
1147 for line
in p_lines
:
1149 if line
.startswith(p_key
+ ":"):
1150 parts
= line
.split(":")
1151 the_value
= parts
[1].strip()
1158 # params for use in -f file
1159 # returns values file option and filename (in order to delete it at the end)
1160 def _params_to_file_option(self
, cluster_uuid
: str, params
: dict) -> (str, str):
1162 if params
and len(params
) > 0:
1163 self
._get
_paths
(cluster_name
=cluster_uuid
, create_if_not_exist
=True)
1165 def get_random_number():
1166 r
= random
.randrange(start
=1, stop
=99999999)
1174 value
= params
.get(key
)
1175 if "!!yaml" in str(value
):
1176 value
= yaml
.load(value
[7:])
1177 params2
[key
] = value
1179 values_file
= get_random_number() + ".yaml"
1180 with
open(values_file
, "w") as stream
:
1181 yaml
.dump(params2
, stream
, indent
=4, default_flow_style
=False)
1183 return "-f {}".format(values_file
), values_file
1187 # params for use in --set option
1189 def _params_to_set_option(params
: dict) -> str:
1191 if params
and len(params
) > 0:
1194 value
= params
.get(key
, None)
1195 if value
is not None:
1197 params_str
+= "--set "
1201 params_str
+= "{}={}".format(key
, value
)
1205 def _output_to_lines(output
: str) -> list:
1206 output_lines
= list()
1207 lines
= output
.splitlines(keepends
=False)
1211 output_lines
.append(line
)
1215 def _output_to_table(output
: str) -> list:
1216 output_table
= list()
1217 lines
= output
.splitlines(keepends
=False)
1219 line
= line
.replace("\t", " ")
1221 output_table
.append(line_list
)
1222 cells
= line
.split(sep
=" ")
1226 line_list
.append(cell
)
1230 self
, cluster_name
: str, create_if_not_exist
: bool = False
1231 ) -> (str, str, str, str):
1233 Returns kube and helm directories
1235 :param cluster_name:
1236 :param create_if_not_exist:
1237 :return: kube, helm directories, config filename and cluster dir.
1238 Raises exception if not exist and cannot create
1242 if base
.endswith("/") or base
.endswith("\\"):
1245 # base dir for cluster
1246 cluster_dir
= base
+ "/" + cluster_name
1247 if create_if_not_exist
and not os
.path
.exists(cluster_dir
):
1248 self
.log
.debug("Creating dir {}".format(cluster_dir
))
1249 os
.makedirs(cluster_dir
)
1250 if not os
.path
.exists(cluster_dir
):
1251 msg
= "Base cluster dir {} does not exist".format(cluster_dir
)
1253 raise K8sException(msg
)
1256 kube_dir
= cluster_dir
+ "/" + ".kube"
1257 if create_if_not_exist
and not os
.path
.exists(kube_dir
):
1258 self
.log
.debug("Creating dir {}".format(kube_dir
))
1259 os
.makedirs(kube_dir
)
1260 if not os
.path
.exists(kube_dir
):
1261 msg
= "Kube config dir {} does not exist".format(kube_dir
)
1263 raise K8sException(msg
)
1266 helm_dir
= cluster_dir
+ "/" + ".helm"
1267 if create_if_not_exist
and not os
.path
.exists(helm_dir
):
1268 self
.log
.debug("Creating dir {}".format(helm_dir
))
1269 os
.makedirs(helm_dir
)
1270 if not os
.path
.exists(helm_dir
):
1271 msg
= "Helm config dir {} does not exist".format(helm_dir
)
1273 raise K8sException(msg
)
1275 config_filename
= kube_dir
+ "/config"
1276 return kube_dir
, helm_dir
, config_filename
, cluster_dir
1279 def _remove_multiple_spaces(strobj
):
1280 strobj
= strobj
.strip()
1281 while " " in strobj
:
1282 strobj
= strobj
.replace(" ", " ")
1285 def _local_exec(self
, command
: str) -> (str, int):
1286 command
= K8sHelmConnector
._remove
_multiple
_spaces
(command
)
1287 self
.log
.debug("Executing sync local command: {}".format(command
))
1288 # raise exception if fails
1291 output
= subprocess
.check_output(
1292 command
, shell
=True, universal_newlines
=True
1295 self
.log
.debug(output
)
1299 return output
, return_code
1301 async def _local_async_exec(
1304 raise_exception_on_error
: bool = False,
1305 show_error_log
: bool = True,
1306 encode_utf8
: bool = False,
1309 command
= K8sHelmConnector
._remove
_multiple
_spaces
(command
)
1310 self
.log
.debug("Executing async local command: {}".format(command
))
1313 command
= command
.split(sep
=" ")
1316 process
= await asyncio
.create_subprocess_exec(
1317 *command
, stdout
=asyncio
.subprocess
.PIPE
, stderr
=asyncio
.subprocess
.PIPE
1320 # wait for command terminate
1321 stdout
, stderr
= await process
.communicate()
1323 return_code
= process
.returncode
1327 output
= stdout
.decode("utf-8").strip()
1328 # output = stdout.decode()
1330 output
= stderr
.decode("utf-8").strip()
1331 # output = stderr.decode()
1333 if return_code
!= 0 and show_error_log
:
1335 "Return code (FAIL): {}\nOutput:\n{}".format(return_code
, output
)
1338 self
.log
.debug("Return code: {}".format(return_code
))
1340 if raise_exception_on_error
and return_code
!= 0:
1341 raise K8sException(output
)
1344 output
= output
.encode("utf-8").strip()
1345 output
= str(output
).replace("\\n", "\n")
1347 return output
, return_code
1349 except asyncio
.CancelledError
:
1351 except K8sException
:
1353 except Exception as e
:
1354 msg
= "Exception executing command: {} -> {}".format(command
, e
)
1356 if raise_exception_on_error
:
1357 raise K8sException(e
) from e
1361 def _check_file_exists(self
, filename
: str, exception_if_not_exists
: bool = False):
1362 # self.log.debug('Checking if file {} exists...'.format(filename))
1363 if os
.path
.exists(filename
):
1366 msg
= "File {} does not exist".format(filename
)
1367 if exception_if_not_exists
:
1368 # self.log.error(msg)
1369 raise K8sException(msg
)