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 ####################################################################################
43 service_account
= "osm"
49 kubectl_command
: str = "/usr/bin/kubectl",
50 helm_command
: str = "/usr/bin/helm",
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
61 :param on_update_db: callback called when k8s connector updates database
65 K8sConnector
.__init
__(self
, db
=db
, log
=log
, on_update_db
=on_update_db
)
67 self
.log
.info("Initializing K8S Helm connector")
69 # random numbers for release name generation
70 random
.seed(time
.time())
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)
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)
83 # initialize helm client-only
84 self
.log
.debug("Initializing helm client-only...")
85 command
= "{} init --client-only".format(self
._helm
_command
)
87 asyncio
.ensure_future(
88 self
._local
_async
_exec
(command
=command
, raise_exception_on_error
=False)
90 # loop = asyncio.get_event_loop()
91 # loop.run_until_complete(self._local_async_exec(command=command,
92 # raise_exception_on_error=False))
93 except Exception as e
:
95 msg
="helm init failed (it was already initialized): {}".format(e
)
98 self
.log
.info("K8S Helm connector initialized")
101 def _get_namespace_cluster_id(cluster_uuid
: str) -> (str, str):
103 Parses cluster_uuid stored at database that can be either 'namespace:cluster_id' or only
104 cluster_id for backward compatibility
106 namespace
, _
, cluster_id
= cluster_uuid
.rpartition(':')
107 return namespace
, cluster_id
110 self
, k8s_creds
: str, namespace
: str = "kube-system", reuse_cluster_uuid
=None
113 It prepares a given K8s cluster environment to run Charts on both sides:
117 :param k8s_creds: credentials to access a given K8s cluster, i.e. a valid
119 :param namespace: optional namespace to be used for helm. By default,
120 'kube-system' will be used
121 :param reuse_cluster_uuid: existing cluster uuid for reuse
122 :return: uuid of the K8s cluster and True if connector has installed some
123 software in the cluster
124 (on error, an exception will be raised)
127 if reuse_cluster_uuid
:
128 namespace_
, cluster_id
= self
._get
_namespace
_cluster
_id
(reuse_cluster_uuid
)
129 namespace
= namespace_
or namespace
131 cluster_id
= str(uuid4())
132 cluster_uuid
= "{}:{}".format(namespace
, cluster_id
)
134 self
.log
.debug("Initializing K8S Cluster {}. namespace: {}".format(cluster_id
, namespace
))
136 # create config filename
137 _kube_dir
, helm_dir
, config_filename
, _cluster_dir
= self
._get
_paths
(
138 cluster_name
=cluster_id
, create_if_not_exist
=True
140 with
open(config_filename
, "w") as f
:
143 # check if tiller pod is up in cluster
144 command
= "{} --kubeconfig={} --namespace={} get deployments".format(
145 self
.kubectl_command
, config_filename
, namespace
147 output
, _rc
= await self
._local
_async
_exec
(
148 command
=command
, raise_exception_on_error
=True
151 output_table
= self
._output
_to
_table
(output
=output
)
153 # find 'tiller' pod in all pods
154 already_initialized
= False
156 for row
in output_table
:
157 if row
[0].startswith("tiller-deploy"):
158 already_initialized
= True
164 n2vc_installed_sw
= False
165 if not already_initialized
:
167 "Initializing helm in client and server: {}".format(cluster_id
)
169 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)
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)
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)
182 n2vc_installed_sw
= True
184 # check client helm installation
185 check_file
= helm_dir
+ "/repository/repositories.yaml"
186 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
))
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
196 self
.log
.info("Helm client already initialized")
198 # sync fs with local data
199 self
.fs
.reverse_sync(from_path
=cluster_id
)
201 self
.log
.info("Cluster {} initialized".format(cluster_id
))
203 return cluster_uuid
, n2vc_installed_sw
206 self
, cluster_uuid
: str, name
: str, url
: str, repo_type
: str = "chart"
208 _
, cluster_id
= self
._get
_namespace
_cluster
_id
(cluster_uuid
)
209 self
.log
.debug("Cluster {}, adding {} repository {}. URL: {}".format(
210 cluster_id
, repo_type
, name
, url
))
213 _kube_dir
, helm_dir
, config_filename
, _cluster_dir
= self
._get
_paths
(
214 cluster_name
=cluster_id
, create_if_not_exist
=True
218 self
.fs
.sync(from_path
=cluster_id
)
221 command
= "{} --kubeconfig={} --home={} repo update".format(
222 self
._helm
_command
, config_filename
, helm_dir
224 self
.log
.debug("updating repo: {}".format(command
))
225 await self
._local
_async
_exec
(command
=command
, raise_exception_on_error
=False)
227 # helm repo add name url
228 command
= "{} --kubeconfig={} --home={} repo add {} {}".format(
229 self
._helm
_command
, config_filename
, helm_dir
, name
, url
231 self
.log
.debug("adding repo: {}".format(command
))
232 await self
._local
_async
_exec
(command
=command
, raise_exception_on_error
=True)
235 self
.fs
.reverse_sync(from_path
=cluster_id
)
237 async def repo_list(self
, cluster_uuid
: str) -> list:
239 Get the list of registered repositories
241 :return: list of registered repositories: [ (name, url) .... ]
244 _
, cluster_id
= self
._get
_namespace
_cluster
_id
(cluster_uuid
)
245 self
.log
.debug("list repositories for cluster {}".format(cluster_id
))
248 _kube_dir
, helm_dir
, config_filename
, _cluster_dir
= self
._get
_paths
(
249 cluster_name
=cluster_id
, create_if_not_exist
=True
253 self
.fs
.sync(from_path
=cluster_id
)
255 command
= "{} --kubeconfig={} --home={} repo list --output yaml".format(
256 self
._helm
_command
, config_filename
, helm_dir
259 output
, _rc
= await self
._local
_async
_exec
(
260 command
=command
, raise_exception_on_error
=True
262 if output
and len(output
) > 0:
263 return yaml
.load(output
, Loader
=yaml
.SafeLoader
)
268 self
.fs
.reverse_sync(from_path
=cluster_id
)
270 async def repo_remove(self
, cluster_uuid
: str, name
: str):
272 Remove a repository from OSM
274 :param cluster_uuid: the cluster or 'namespace:cluster'
275 :param name: repo name in OSM
276 :return: True if successful
279 _
, cluster_id
= self
._get
_namespace
_cluster
_id
(cluster_uuid
)
280 self
.log
.debug("list repositories for cluster {}".format(cluster_id
))
283 _kube_dir
, helm_dir
, config_filename
, _cluster_dir
= self
._get
_paths
(
284 cluster_name
=cluster_id
, create_if_not_exist
=True
288 self
.fs
.sync(from_path
=cluster_id
)
290 command
= "{} --kubeconfig={} --home={} repo remove {}".format(
291 self
._helm
_command
, config_filename
, helm_dir
, name
294 await self
._local
_async
_exec
(command
=command
, raise_exception_on_error
=True)
297 self
.fs
.reverse_sync(from_path
=cluster_id
)
300 self
, cluster_uuid
: str, force
: bool = False, uninstall_sw
: bool = False
303 namespace
, cluster_id
= self
._get
_namespace
_cluster
_id
(cluster_uuid
)
304 self
.log
.debug("Resetting K8s environment. cluster uuid: {} uninstall={}"
305 .format(cluster_id
, uninstall_sw
))
307 # get kube and helm directories
308 _kube_dir
, helm_dir
, config_filename
, _cluster_dir
= self
._get
_paths
(
309 cluster_name
=cluster_id
, create_if_not_exist
=False
313 self
.fs
.sync(from_path
=cluster_id
)
315 # uninstall releases if needed.
317 releases
= await self
.instances_list(cluster_uuid
=cluster_uuid
)
318 if len(releases
) > 0:
322 kdu_instance
= r
.get("Name")
323 chart
= r
.get("Chart")
325 "Uninstalling {} -> {}".format(chart
, kdu_instance
)
327 await self
.uninstall(
328 cluster_uuid
=cluster_uuid
, kdu_instance
=kdu_instance
330 except Exception as e
:
332 "Error uninstalling release {}: {}".format(kdu_instance
, e
)
336 "Cluster uuid: {} has releases and not force. Leaving K8s helm environment"
339 uninstall_sw
= False # Allow to remove k8s cluster without removing Tiller
343 self
.log
.debug("Uninstalling tiller from cluster {}".format(cluster_id
))
346 # find namespace for tiller pod
347 command
= "{} --kubeconfig={} get deployments --all-namespaces".format(
348 self
.kubectl_command
, config_filename
350 output
, _rc
= await self
._local
_async
_exec
(
351 command
=command
, raise_exception_on_error
=False
353 output_table
= K8sHelmConnector
._output
_to
_table
(output
=output
)
355 for r
in output_table
:
357 if "tiller-deploy" in r
[1]:
363 msg
= "Tiller deployment not found in cluster {}".format(cluster_id
)
366 self
.log
.debug("namespace for tiller: {}".format(namespace
))
369 # uninstall tiller from cluster
371 "Uninstalling tiller from cluster {}".format(cluster_id
)
373 command
= "{} --kubeconfig={} --home={} reset".format(
374 self
._helm
_command
, config_filename
, helm_dir
376 self
.log
.debug("resetting: {}".format(command
))
377 output
, _rc
= await self
._local
_async
_exec
(
378 command
=command
, raise_exception_on_error
=True
380 # Delete clusterrolebinding and serviceaccount.
381 # Ignore if errors for backward compatibility
382 command
= ("{} --kubeconfig={} delete clusterrolebinding.rbac.authorization.k8s."
383 "io/osm-tiller-cluster-rule").format(self
.kubectl_command
,
385 output
, _rc
= await self
._local
_async
_exec
(command
=command
,
386 raise_exception_on_error
=False)
387 command
= "{} --kubeconfig={} --namespace kube-system delete serviceaccount/{}".\
388 format(self
.kubectl_command
, config_filename
, self
.service_account
)
389 output
, _rc
= await self
._local
_async
_exec
(command
=command
,
390 raise_exception_on_error
=False)
393 self
.log
.debug("namespace not found")
395 # delete cluster directory
396 self
.log
.debug("Removing directory {}".format(cluster_id
))
397 self
.fs
.file_delete(cluster_id
, ignore_non_exist
=True)
398 # Remove also local directorio if still exist
399 direct
= self
.fs
.path
+ "/" + cluster_id
400 shutil
.rmtree(direct
, ignore_errors
=True)
409 timeout
: float = 300,
411 db_dict
: dict = None,
412 kdu_name
: str = None,
413 namespace
: str = None,
416 _
, cluster_id
= self
._get
_namespace
_cluster
_id
(cluster_uuid
)
417 self
.log
.debug("installing {} in cluster {}".format(kdu_model
, cluster_id
))
420 _kube_dir
, helm_dir
, config_filename
, _cluster_dir
= self
._get
_paths
(
421 cluster_name
=cluster_id
, create_if_not_exist
=True
425 self
.log
.debug("sync cluster_id: {}".format(_cluster_dir
))
426 self
.fs
.sync(from_path
=cluster_id
)
429 # params_str = K8sHelmConnector._params_to_set_option(params)
430 params_str
, file_to_delete
= self
._params
_to
_file
_option
(
431 cluster_id
=cluster_id
, params
=params
436 timeout_str
= "--timeout {}".format(timeout
)
441 atomic_str
= "--atomic"
445 namespace_str
= "--namespace {}".format(namespace
)
450 parts
= kdu_model
.split(sep
=":")
452 version_str
= "--version {}".format(parts
[1])
455 # generate a name for the release. Then, check if already exists
457 while kdu_instance
is None:
458 kdu_instance
= K8sHelmConnector
._generate
_release
_name
(kdu_model
)
460 result
= await self
._status
_kdu
(
461 cluster_id
=cluster_id
,
462 kdu_instance
=kdu_instance
,
463 show_error_log
=False,
465 if result
is not None:
466 # instance already exists: generate a new one
473 "{helm} install {atomic} --output yaml --kubeconfig={config} --home={dir} "
474 "{params} {timeout} --name={name} {ns} {model} {ver}".format(
475 helm
=self
._helm
_command
,
477 config
=config_filename
,
487 self
.log
.debug("installing: {}".format(command
))
490 # exec helm in a task
491 exec_task
= asyncio
.ensure_future(
492 coro_or_future
=self
._local
_async
_exec
(
493 command
=command
, raise_exception_on_error
=False
497 # write status in another task
498 status_task
= asyncio
.ensure_future(
499 coro_or_future
=self
._store
_status
(
500 cluster_id
=cluster_id
,
501 kdu_instance
=kdu_instance
,
508 # wait for execution task
509 await asyncio
.wait([exec_task
])
514 output
, rc
= exec_task
.result()
518 output
, rc
= await self
._local
_async
_exec
(
519 command
=command
, raise_exception_on_error
=False
522 # remove temporal values yaml file
524 os
.remove(file_to_delete
)
527 await self
._store
_status
(
528 cluster_id
=cluster_id
,
529 kdu_instance
=kdu_instance
,
537 msg
= "Error executing command: {}\nOutput: {}".format(command
, output
)
539 raise K8sException(msg
)
542 self
.fs
.reverse_sync(from_path
=cluster_id
)
544 self
.log
.debug("Returning kdu_instance {}".format(kdu_instance
))
547 async def instances_list(self
, cluster_uuid
: str) -> list:
549 returns a list of deployed releases in a cluster
551 :param cluster_uuid: the 'cluster' or 'namespace:cluster'
555 _
, cluster_id
= self
._get
_namespace
_cluster
_id
(cluster_uuid
)
556 self
.log
.debug("list releases for cluster {}".format(cluster_id
))
559 _kube_dir
, helm_dir
, config_filename
, _cluster_dir
= self
._get
_paths
(
560 cluster_name
=cluster_id
, create_if_not_exist
=True
564 self
.fs
.sync(from_path
=cluster_id
)
566 command
= "{} --kubeconfig={} --home={} list --output yaml".format(
567 self
._helm
_command
, config_filename
, helm_dir
570 output
, _rc
= await self
._local
_async
_exec
(
571 command
=command
, raise_exception_on_error
=True
574 if output
and len(output
) > 0:
575 return yaml
.load(output
, Loader
=yaml
.SafeLoader
).get("Releases")
583 kdu_model
: str = None,
585 timeout
: float = 300,
587 db_dict
: dict = None,
590 _
, cluster_id
= self
._get
_namespace
_cluster
_id
(cluster_uuid
)
591 self
.log
.debug("upgrading {} in cluster {}".format(kdu_model
, cluster_id
))
594 _kube_dir
, helm_dir
, config_filename
, _cluster_dir
= self
._get
_paths
(
595 cluster_name
=cluster_id
, create_if_not_exist
=True
599 self
.fs
.sync(from_path
=cluster_id
)
602 # params_str = K8sHelmConnector._params_to_set_option(params)
603 params_str
, file_to_delete
= self
._params
_to
_file
_option
(
604 cluster_id
=cluster_id
, params
=params
609 timeout_str
= "--timeout {}".format(timeout
)
614 atomic_str
= "--atomic"
618 if kdu_model
and ":" in kdu_model
:
619 parts
= kdu_model
.split(sep
=":")
621 version_str
= "--version {}".format(parts
[1])
626 "{} upgrade {} --output yaml --kubeconfig={} " "--home={} {} {} {} {} {}"
638 self
.log
.debug("upgrading: {}".format(command
))
642 # exec helm in a task
643 exec_task
= asyncio
.ensure_future(
644 coro_or_future
=self
._local
_async
_exec
(
645 command
=command
, raise_exception_on_error
=False
648 # write status in another task
649 status_task
= asyncio
.ensure_future(
650 coro_or_future
=self
._store
_status
(
651 cluster_id
=cluster_id
,
652 kdu_instance
=kdu_instance
,
659 # wait for execution task
660 await asyncio
.wait([exec_task
])
664 output
, rc
= exec_task
.result()
668 output
, rc
= await self
._local
_async
_exec
(
669 command
=command
, raise_exception_on_error
=False
672 # remove temporal values yaml file
674 os
.remove(file_to_delete
)
677 await self
._store
_status
(
678 cluster_id
=cluster_id
,
679 kdu_instance
=kdu_instance
,
687 msg
= "Error executing command: {}\nOutput: {}".format(command
, output
)
689 raise K8sException(msg
)
692 self
.fs
.reverse_sync(from_path
=cluster_id
)
694 # return new revision number
695 instance
= await self
.get_instance_info(
696 cluster_uuid
=cluster_uuid
, kdu_instance
=kdu_instance
699 revision
= int(instance
.get("Revision"))
700 self
.log
.debug("New revision: {}".format(revision
))
706 self
, cluster_uuid
: str, kdu_instance
: str, revision
=0, db_dict
: dict = None
709 _
, cluster_id
= self
._get
_namespace
_cluster
_id
(cluster_uuid
)
711 "rollback kdu_instance {} to revision {} from cluster {}".format(
712 kdu_instance
, revision
, cluster_id
717 _kube_dir
, helm_dir
, config_filename
, _cluster_dir
= self
._get
_paths
(
718 cluster_name
=cluster_id
, create_if_not_exist
=True
722 self
.fs
.sync(from_path
=cluster_id
)
724 command
= "{} rollback --kubeconfig={} --home={} {} {} --wait".format(
725 self
._helm
_command
, config_filename
, helm_dir
, kdu_instance
, revision
728 # exec helm in a task
729 exec_task
= asyncio
.ensure_future(
730 coro_or_future
=self
._local
_async
_exec
(
731 command
=command
, raise_exception_on_error
=False
734 # write status in another task
735 status_task
= asyncio
.ensure_future(
736 coro_or_future
=self
._store
_status
(
737 cluster_id
=cluster_id
,
738 kdu_instance
=kdu_instance
,
740 operation
="rollback",
745 # wait for execution task
746 await asyncio
.wait([exec_task
])
751 output
, rc
= exec_task
.result()
754 await self
._store
_status
(
755 cluster_id
=cluster_id
,
756 kdu_instance
=kdu_instance
,
758 operation
="rollback",
764 msg
= "Error executing command: {}\nOutput: {}".format(command
, output
)
766 raise K8sException(msg
)
769 self
.fs
.reverse_sync(from_path
=cluster_id
)
771 # return new revision number
772 instance
= await self
.get_instance_info(
773 cluster_uuid
=cluster_uuid
, kdu_instance
=kdu_instance
776 revision
= int(instance
.get("Revision"))
777 self
.log
.debug("New revision: {}".format(revision
))
782 async def uninstall(self
, cluster_uuid
: str, kdu_instance
: str):
784 Removes an existing KDU instance. It would implicitly use the `delete` call
785 (this call would happen after all _terminate-config-primitive_ of the VNF
788 :param cluster_uuid: UUID of a K8s cluster known by OSM, or namespace:cluster_id
789 :param kdu_instance: unique name for the KDU instance to be deleted
790 :return: True if successful
793 _
, cluster_id
= self
._get
_namespace
_cluster
_id
(cluster_uuid
)
795 "uninstall kdu_instance {} from cluster {}".format(
796 kdu_instance
, cluster_id
801 _kube_dir
, helm_dir
, config_filename
, _cluster_dir
= self
._get
_paths
(
802 cluster_name
=cluster_id
, create_if_not_exist
=True
806 self
.fs
.sync(from_path
=cluster_id
)
808 command
= "{} --kubeconfig={} --home={} delete --purge {}".format(
809 self
._helm
_command
, config_filename
, helm_dir
, kdu_instance
812 output
, _rc
= await self
._local
_async
_exec
(
813 command
=command
, raise_exception_on_error
=True
817 self
.fs
.reverse_sync(from_path
=cluster_id
)
819 return self
._output
_to
_table
(output
)
821 async def exec_primitive(
823 cluster_uuid
: str = None,
824 kdu_instance
: str = None,
825 primitive_name
: str = None,
826 timeout
: float = 300,
828 db_dict
: dict = None,
830 """Exec primitive (Juju action)
832 :param cluster_uuid str: The UUID of the cluster or namespace:cluster
833 :param kdu_instance str: The unique name of the KDU instance
834 :param primitive_name: Name of action that will be executed
835 :param timeout: Timeout for action execution
836 :param params: Dictionary of all the parameters needed for the action
837 :db_dict: Dictionary for any additional data
839 :return: Returns the output of the action
842 "KDUs deployed with Helm don't support actions "
843 "different from rollback, upgrade and status"
846 async def inspect_kdu(self
, kdu_model
: str, repo_url
: str = None) -> str:
849 "inspect kdu_model {} from (optional) repo: {}".format(kdu_model
, repo_url
)
852 return await self
._exec
_inspect
_comand
(
853 inspect_command
="", kdu_model
=kdu_model
, repo_url
=repo_url
856 async def values_kdu(self
, kdu_model
: str, repo_url
: str = None) -> str:
859 "inspect kdu_model values {} from (optional) repo: {}".format(
864 return await self
._exec
_inspect
_comand
(
865 inspect_command
="values", kdu_model
=kdu_model
, repo_url
=repo_url
868 async def help_kdu(self
, kdu_model
: str, repo_url
: str = None) -> str:
871 "inspect kdu_model {} readme.md from repo: {}".format(kdu_model
, repo_url
)
874 return await self
._exec
_inspect
_comand
(
875 inspect_command
="readme", kdu_model
=kdu_model
, repo_url
=repo_url
878 async def status_kdu(self
, cluster_uuid
: str, kdu_instance
: str) -> str:
880 # call internal function
881 _
, cluster_id
= self
._get
_namespace
_cluster
_id
(cluster_uuid
)
882 return await self
._status
_kdu
(
883 cluster_id
=cluster_id
,
884 kdu_instance
=kdu_instance
,
889 async def get_services(self
,
892 namespace
: str) -> list:
894 _
, cluster_id
= self
._get
_namespace
_cluster
_id
(cluster_uuid
)
896 "get_services: cluster_uuid: {}, kdu_instance: {}".format(
897 cluster_uuid
, kdu_instance
902 self
.fs
.sync(from_path
=cluster_id
)
904 status
= await self
._status
_kdu
(
905 cluster_id
, kdu_instance
, return_text
=False
908 service_names
= self
._parse
_helm
_status
_service
_info
(status
)
910 for service
in service_names
:
911 service
= await self
.get_service(cluster_uuid
, service
, namespace
)
912 service_list
.append(service
)
915 self
.fs
.reverse_sync(from_path
=cluster_id
)
919 async def get_service(self
,
922 namespace
: str) -> object:
925 "get service, service_name: {}, namespace: {}, cluster_uuid: {}".format(
926 service_name
, namespace
, cluster_uuid
)
930 _
, cluster_id
= self
._get
_namespace
_cluster
_id
(cluster_uuid
)
931 _kube_dir
, helm_dir
, config_filename
, _cluster_dir
= self
._get
_paths
(
932 cluster_name
=cluster_id
, create_if_not_exist
=True
936 self
.fs
.sync(from_path
=cluster_id
)
938 command
= "{} --kubeconfig={} --namespace={} get service {} -o=yaml".format(
939 self
.kubectl_command
, config_filename
, namespace
, service_name
942 output
, _rc
= await self
._local
_async
_exec
(
943 command
=command
, raise_exception_on_error
=True
946 data
= yaml
.load(output
, Loader
=yaml
.SafeLoader
)
949 "name": service_name
,
950 "type": self
._get
_deep
(data
, ("spec", "type")),
951 "ports": self
._get
_deep
(data
, ("spec", "ports")),
952 "cluster_ip": self
._get
_deep
(data
, ("spec", "clusterIP"))
954 if service
["type"] == "LoadBalancer":
955 ip_map_list
= self
._get
_deep
(data
, ("status", "loadBalancer", "ingress"))
956 ip_list
= [elem
["ip"] for elem
in ip_map_list
]
957 service
["external_ip"] = ip_list
960 self
.fs
.reverse_sync(from_path
=cluster_id
)
964 async def synchronize_repos(self
, cluster_uuid
: str):
966 _
, cluster_id
= self
._get
_namespace
_cluster
_id
(cluster_uuid
)
967 self
.log
.debug("syncronize repos for cluster helm-id: {}",)
969 update_repos_timeout
= (
970 300 # max timeout to sync a single repos, more than this is too much
972 db_k8scluster
= self
.db
.get_one(
973 "k8sclusters", {"_admin.helm-chart.id": cluster_uuid
}
977 db_k8scluster
.get("_admin").get("helm_chart_repos") or []
979 cluster_repo_dict
= (
980 db_k8scluster
.get("_admin").get("helm_charts_added") or {}
982 # elements that must be deleted
983 deleted_repo_list
= []
985 self
.log
.debug("helm_chart_repos: {}".format(nbi_repo_list
))
986 self
.log
.debug("helm_charts_added: {}".format(cluster_repo_dict
))
988 # obtain repos to add: registered by nbi but not added
990 repo
for repo
in nbi_repo_list
if not cluster_repo_dict
.get(repo
)
993 # obtain repos to delete: added by cluster but not in nbi list
996 for repo
in cluster_repo_dict
.keys()
997 if repo
not in nbi_repo_list
1000 # delete repos: must delete first then add because there may be
1001 # different repos with same name but
1002 # different id and url
1003 self
.log
.debug("repos to delete: {}".format(repos_to_delete
))
1004 for repo_id
in repos_to_delete
:
1005 # try to delete repos
1007 repo_delete_task
= asyncio
.ensure_future(
1009 cluster_uuid
=cluster_uuid
,
1010 name
=cluster_repo_dict
[repo_id
],
1013 await asyncio
.wait_for(repo_delete_task
, update_repos_timeout
)
1014 except Exception as e
:
1016 "Error deleting repo, id: {}, name: {}, err_msg: {}".format(
1017 repo_id
, cluster_repo_dict
[repo_id
], str(e
)
1020 # always add to the list of to_delete if there is an error
1021 # because if is not there
1022 # deleting raises error
1023 deleted_repo_list
.append(repo_id
)
1026 self
.log
.debug("repos to add: {}".format(repos_to_add
))
1027 for repo_id
in repos_to_add
:
1028 # obtain the repo data from the db
1029 # if there is an error getting the repo in the database we will
1030 # ignore this repo and continue
1031 # because there is a possible race condition where the repo has
1032 # been deleted while processing
1033 db_repo
= self
.db
.get_one("k8srepos", {"_id": repo_id
})
1035 "obtained repo: id, {}, name: {}, url: {}".format(
1036 repo_id
, db_repo
["name"], db_repo
["url"]
1040 repo_add_task
= asyncio
.ensure_future(
1042 cluster_uuid
=cluster_uuid
,
1043 name
=db_repo
["name"],
1048 await asyncio
.wait_for(repo_add_task
, update_repos_timeout
)
1049 added_repo_dict
[repo_id
] = db_repo
["name"]
1051 "added repo: id, {}, name: {}".format(
1052 repo_id
, db_repo
["name"]
1055 except Exception as e
:
1056 # deal with error adding repo, adding a repo that already
1057 # exists does not raise any error
1058 # will not raise error because a wrong repos added by
1059 # anyone could prevent instantiating any ns
1061 "Error adding repo id: {}, err_msg: {} ".format(
1066 return deleted_repo_list
, added_repo_dict
1068 else: # else db_k8scluster does not exist
1070 "k8cluster with helm-id : {} not found".format(cluster_uuid
)
1073 except Exception as e
:
1074 self
.log
.error("Error synchronizing repos: {}".format(str(e
)))
1075 raise K8sException("Error synchronizing repos")
1078 ####################################################################################
1079 ################################### P R I V A T E ##################################
1080 ####################################################################################
1083 async def _exec_inspect_comand(
1084 self
, inspect_command
: str, kdu_model
: str, repo_url
: str = None
1089 repo_str
= " --repo {}".format(repo_url
)
1090 idx
= kdu_model
.find("/")
1093 kdu_model
= kdu_model
[idx
:]
1095 inspect_command
= "{} inspect {} {}{}".format(
1096 self
._helm
_command
, inspect_command
, kdu_model
, repo_str
1098 output
, _rc
= await self
._local
_async
_exec
(
1099 command
=inspect_command
, encode_utf8
=True
1104 async def _status_kdu(
1108 show_error_log
: bool = False,
1109 return_text
: bool = False,
1112 self
.log
.debug("status of kdu_instance {}".format(kdu_instance
))
1115 _kube_dir
, helm_dir
, config_filename
, _cluster_dir
= self
._get
_paths
(
1116 cluster_name
=cluster_id
, create_if_not_exist
=True
1119 command
= "{} --kubeconfig={} --home={} status {} --output yaml".format(
1120 self
._helm
_command
, config_filename
, helm_dir
, kdu_instance
1123 output
, rc
= await self
._local
_async
_exec
(
1125 raise_exception_on_error
=True,
1126 show_error_log
=show_error_log
,
1135 data
= yaml
.load(output
, Loader
=yaml
.SafeLoader
)
1137 # remove field 'notes'
1139 del data
.get("info").get("status")["notes"]
1143 # parse field 'resources'
1145 resources
= str(data
.get("info").get("status").get("resources"))
1146 resource_table
= self
._output
_to
_table
(resources
)
1147 data
.get("info").get("status")["resources"] = resource_table
1153 async def get_instance_info(self
, cluster_uuid
: str, kdu_instance
: str):
1154 instances
= await self
.instances_list(cluster_uuid
=cluster_uuid
)
1155 for instance
in instances
:
1156 if instance
.get("Name") == kdu_instance
:
1158 self
.log
.debug("Instance {} not found".format(kdu_instance
))
1162 def _generate_release_name(chart_name
: str):
1163 # check embeded chart (file or dir)
1164 if chart_name
.startswith("/"):
1165 # extract file or directory name
1166 chart_name
= chart_name
[chart_name
.rfind("/") + 1 :]
1168 elif "://" in chart_name
:
1169 # extract last portion of URL
1170 chart_name
= chart_name
[chart_name
.rfind("/") + 1 :]
1173 for c
in chart_name
:
1174 if c
.isalpha() or c
.isnumeric():
1181 # if does not start with alpha character, prefix 'a'
1182 if not name
[0].isalpha():
1187 def get_random_number():
1188 r
= random
.randrange(start
=1, stop
=99999999)
1190 s
= s
.rjust(10, "0")
1193 name
= name
+ get_random_number()
1196 async def _store_status(
1201 check_every
: float = 10,
1202 db_dict
: dict = None,
1203 run_once
: bool = False,
1207 await asyncio
.sleep(check_every
)
1208 detailed_status
= await self
._status
_kdu
(
1209 cluster_id
=cluster_id
, kdu_instance
=kdu_instance
,
1212 status
= detailed_status
.get("info").get("Description")
1213 self
.log
.debug('KDU {} STATUS: {}.'.format(kdu_instance
, status
))
1214 # write status to db
1215 result
= await self
.write_app_status_to_db(
1218 detailed_status
=str(detailed_status
),
1219 operation
=operation
,
1222 self
.log
.info("Error writing in database. Task exiting...")
1224 except asyncio
.CancelledError
:
1225 self
.log
.debug("Task cancelled")
1227 except Exception as e
:
1228 self
.log
.debug("_store_status exception: {}".format(str(e
)), exc_info
=True)
1234 async def _is_install_completed(self
, cluster_id
: str, kdu_instance
: str) -> bool:
1236 status
= await self
._status
_kdu
(
1237 cluster_id
=cluster_id
, kdu_instance
=kdu_instance
, return_text
=False
1240 # extract info.status.resources-> str
1243 # NAME READY UP-TO-DATE AVAILABLE AGE
1244 # halting-horse-mongodb 0/1 1 0 0s
1245 # halting-petit-mongodb 1/1 1 0 0s
1247 resources
= K8sHelmConnector
._get
_deep
(status
, ("info", "status", "resources"))
1250 resources
= K8sHelmConnector
._output
_to
_table
(resources
)
1252 num_lines
= len(resources
)
1254 while index
< num_lines
:
1256 line1
= resources
[index
]
1258 # find '==>' in column 0
1259 if line1
[0] == "==>":
1260 line2
= resources
[index
]
1262 # find READY in column 1
1263 if line2
[1] == "READY":
1265 line3
= resources
[index
]
1267 while len(line3
) > 1 and index
< num_lines
:
1268 ready_value
= line3
[1]
1269 parts
= ready_value
.split(sep
="/")
1270 current
= int(parts
[0])
1271 total
= int(parts
[1])
1273 self
.log
.debug("NOT READY:\n {}".format(line3
))
1275 line3
= resources
[index
]
1283 def _parse_helm_status_service_info(self
, status
):
1285 # extract info.status.resources-> str
1288 # NAME READY UP-TO-DATE AVAILABLE AGE
1289 # halting-horse-mongodb 0/1 1 0 0s
1290 # halting-petit-mongodb 1/1 1 0 0s
1292 resources
= K8sHelmConnector
._get
_deep
(status
, ("info", "status", "resources"))
1295 first_line_skipped
= service_found
= False
1296 for line
in resources
:
1297 if not service_found
:
1298 if len(line
) >= 2 and line
[0] == "==>" and line
[1] == "v1/Service":
1299 service_found
= True
1302 if len(line
) >= 2 and line
[0] == "==>":
1303 service_found
= first_line_skipped
= False
1307 if not first_line_skipped
:
1308 first_line_skipped
= True
1310 service_list
.append(line
[0])
1315 def _get_deep(dictionary
: dict, members
: tuple):
1320 value
= target
.get(m
)
1329 # find key:value in several lines
1331 def _find_in_lines(p_lines
: list, p_key
: str) -> str:
1332 for line
in p_lines
:
1334 if line
.startswith(p_key
+ ":"):
1335 parts
= line
.split(":")
1336 the_value
= parts
[1].strip()
1343 # params for use in -f file
1344 # returns values file option and filename (in order to delete it at the end)
1345 def _params_to_file_option(self
, cluster_id
: str, params
: dict) -> (str, str):
1347 if params
and len(params
) > 0:
1348 self
._get
_paths
(cluster_name
=cluster_id
, create_if_not_exist
=True)
1350 def get_random_number():
1351 r
= random
.randrange(start
=1, stop
=99999999)
1359 value
= params
.get(key
)
1360 if "!!yaml" in str(value
):
1361 value
= yaml
.load(value
[7:])
1362 params2
[key
] = value
1364 values_file
= get_random_number() + ".yaml"
1365 with
open(values_file
, "w") as stream
:
1366 yaml
.dump(params2
, stream
, indent
=4, default_flow_style
=False)
1368 return "-f {}".format(values_file
), values_file
1372 # params for use in --set option
1374 def _params_to_set_option(params
: dict) -> str:
1376 if params
and len(params
) > 0:
1379 value
= params
.get(key
, None)
1380 if value
is not None:
1382 params_str
+= "--set "
1386 params_str
+= "{}={}".format(key
, value
)
1390 def _output_to_lines(output
: str) -> list:
1391 output_lines
= list()
1392 lines
= output
.splitlines(keepends
=False)
1396 output_lines
.append(line
)
1400 def _output_to_table(output
: str) -> list:
1401 output_table
= list()
1402 lines
= output
.splitlines(keepends
=False)
1404 line
= line
.replace("\t", " ")
1406 output_table
.append(line_list
)
1407 cells
= line
.split(sep
=" ")
1411 line_list
.append(cell
)
1415 self
, cluster_name
: str, create_if_not_exist
: bool = False
1416 ) -> (str, str, str, str):
1418 Returns kube and helm directories
1420 :param cluster_name:
1421 :param create_if_not_exist:
1422 :return: kube, helm directories, config filename and cluster dir.
1423 Raises exception if not exist and cannot create
1427 if base
.endswith("/") or base
.endswith("\\"):
1430 # base dir for cluster
1431 cluster_dir
= base
+ "/" + cluster_name
1432 if create_if_not_exist
and not os
.path
.exists(cluster_dir
):
1433 self
.log
.debug("Creating dir {}".format(cluster_dir
))
1434 os
.makedirs(cluster_dir
)
1435 if not os
.path
.exists(cluster_dir
):
1436 msg
= "Base cluster dir {} does not exist".format(cluster_dir
)
1438 raise K8sException(msg
)
1441 kube_dir
= cluster_dir
+ "/" + ".kube"
1442 if create_if_not_exist
and not os
.path
.exists(kube_dir
):
1443 self
.log
.debug("Creating dir {}".format(kube_dir
))
1444 os
.makedirs(kube_dir
)
1445 if not os
.path
.exists(kube_dir
):
1446 msg
= "Kube config dir {} does not exist".format(kube_dir
)
1448 raise K8sException(msg
)
1451 helm_dir
= cluster_dir
+ "/" + ".helm"
1452 if create_if_not_exist
and not os
.path
.exists(helm_dir
):
1453 self
.log
.debug("Creating dir {}".format(helm_dir
))
1454 os
.makedirs(helm_dir
)
1455 if not os
.path
.exists(helm_dir
):
1456 msg
= "Helm config dir {} does not exist".format(helm_dir
)
1458 raise K8sException(msg
)
1460 config_filename
= kube_dir
+ "/config"
1461 return kube_dir
, helm_dir
, config_filename
, cluster_dir
1464 def _remove_multiple_spaces(strobj
):
1465 strobj
= strobj
.strip()
1466 while " " in strobj
:
1467 strobj
= strobj
.replace(" ", " ")
1470 def _local_exec(self
, command
: str) -> (str, int):
1471 command
= K8sHelmConnector
._remove
_multiple
_spaces
(command
)
1472 self
.log
.debug("Executing sync local command: {}".format(command
))
1473 # raise exception if fails
1476 output
= subprocess
.check_output(
1477 command
, shell
=True, universal_newlines
=True
1480 self
.log
.debug(output
)
1484 return output
, return_code
1486 async def _local_async_exec(
1489 raise_exception_on_error
: bool = False,
1490 show_error_log
: bool = True,
1491 encode_utf8
: bool = False,
1494 command
= K8sHelmConnector
._remove
_multiple
_spaces
(command
)
1495 self
.log
.debug("Executing async local command: {}".format(command
))
1498 command
= command
.split(sep
=" ")
1501 process
= await asyncio
.create_subprocess_exec(
1502 *command
, stdout
=asyncio
.subprocess
.PIPE
, stderr
=asyncio
.subprocess
.PIPE
1505 # wait for command terminate
1506 stdout
, stderr
= await process
.communicate()
1508 return_code
= process
.returncode
1512 output
= stdout
.decode("utf-8").strip()
1513 # output = stdout.decode()
1515 output
= stderr
.decode("utf-8").strip()
1516 # output = stderr.decode()
1518 if return_code
!= 0 and show_error_log
:
1520 "Return code (FAIL): {}\nOutput:\n{}".format(return_code
, output
)
1523 self
.log
.debug("Return code: {}".format(return_code
))
1525 if raise_exception_on_error
and return_code
!= 0:
1526 raise K8sException(output
)
1529 output
= output
.encode("utf-8").strip()
1530 output
= str(output
).replace("\\n", "\n")
1532 return output
, return_code
1534 except asyncio
.CancelledError
:
1536 except K8sException
:
1538 except Exception as e
:
1539 msg
= "Exception executing command: {} -> {}".format(command
, e
)
1541 if raise_exception_on_error
:
1542 raise K8sException(e
) from e
1546 def _check_file_exists(self
, filename
: str, exception_if_not_exists
: bool = False):
1547 # self.log.debug('Checking if file {} exists...'.format(filename))
1548 if os
.path
.exists(filename
):
1551 msg
= "File {} does not exist".format(filename
)
1552 if exception_if_not_exists
:
1553 # self.log.error(msg)
1554 raise K8sException(msg
)