269f316c1b3c1fe19691d14ff3c522dd6410996c
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
24 from typing
import Union
32 from uuid
import uuid4
34 from n2vc
.config
import EnvironConfig
35 from n2vc
.exceptions
import K8sException
36 from n2vc
.k8s_conn
import K8sConnector
39 class K8sHelmBaseConnector(K8sConnector
):
42 ####################################################################################
43 ################################### P U B L I C ####################################
44 ####################################################################################
47 service_account
= "osm"
53 kubectl_command
: str = "/usr/bin/kubectl",
54 helm_command
: str = "/usr/bin/helm",
60 :param fs: file system for kubernetes and helm configuration
61 :param db: database object to write current operation status
62 :param kubectl_command: path to kubectl executable
63 :param helm_command: path to helm executable
65 :param on_update_db: callback called when k8s connector updates database
69 K8sConnector
.__init
__(self
, db
=db
, log
=log
, on_update_db
=on_update_db
)
71 self
.log
.info("Initializing K8S Helm connector")
73 self
.config
= EnvironConfig()
74 # random numbers for release name generation
75 random
.seed(time
.time())
80 # exception if kubectl is not installed
81 self
.kubectl_command
= kubectl_command
82 self
._check
_file
_exists
(filename
=kubectl_command
, exception_if_not_exists
=True)
84 # exception if helm is not installed
85 self
._helm
_command
= helm_command
86 self
._check
_file
_exists
(filename
=helm_command
, exception_if_not_exists
=True)
88 # obtain stable repo url from config or apply default
89 self
._stable
_repo
_url
= self
.config
.get("stablerepourl")
90 if self
._stable
_repo
_url
== "None":
91 self
._stable
_repo
_url
= None
93 def _get_namespace(self
, cluster_uuid
: str) -> str:
95 Obtains the namespace used by the cluster with the uuid passed by argument
97 param: cluster_uuid: cluster's uuid
100 # first, obtain the cluster corresponding to the uuid passed by argument
101 k8scluster
= self
.db
.get_one(
102 "k8sclusters", q_filter
={"_id": cluster_uuid
}, fail_on_empty
=False
104 return k8scluster
.get("namespace")
109 namespace
: str = "kube-system",
110 reuse_cluster_uuid
=None,
114 It prepares a given K8s cluster environment to run Charts
116 :param k8s_creds: credentials to access a given K8s cluster, i.e. a valid
118 :param namespace: optional namespace to be used for helm. By default,
119 'kube-system' will be used
120 :param reuse_cluster_uuid: existing cluster uuid for reuse
121 :param kwargs: Additional parameters (None yet)
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 cluster_id
= reuse_cluster_uuid
130 cluster_id
= str(uuid4())
133 "Initializing K8S Cluster {}. namespace: {}".format(cluster_id
, namespace
)
136 paths
, env
= self
._init
_paths
_env
(
137 cluster_name
=cluster_id
, create_if_not_exist
=True
139 mode
= stat
.S_IRUSR | stat
.S_IWUSR
140 with
open(paths
["kube_config"], "w", mode
) as f
:
142 os
.chmod(paths
["kube_config"], 0o600)
144 # Code with initialization specific of helm version
145 n2vc_installed_sw
= await self
._cluster
_init
(cluster_id
, namespace
, paths
, env
)
147 # sync fs with local data
148 self
.fs
.reverse_sync(from_path
=cluster_id
)
150 self
.log
.info("Cluster {} initialized".format(cluster_id
))
152 return cluster_id
, n2vc_installed_sw
155 self
, cluster_uuid
: str, name
: str, url
: str, repo_type
: str = "chart"
158 "Cluster {}, adding {} repository {}. URL: {}".format(
159 cluster_uuid
, repo_type
, name
, url
164 paths
, env
= self
._init
_paths
_env
(
165 cluster_name
=cluster_uuid
, create_if_not_exist
=True
169 self
.fs
.sync(from_path
=cluster_uuid
)
171 # helm repo add name url
172 command
= "env KUBECONFIG={} {} repo add {} {}".format(
173 paths
["kube_config"], self
._helm
_command
, name
, url
175 self
.log
.debug("adding repo: {}".format(command
))
176 await self
._local
_async
_exec
(
177 command
=command
, raise_exception_on_error
=True, env
=env
181 command
= "env KUBECONFIG={} {} repo update {}".format(
182 paths
["kube_config"], self
._helm
_command
, name
184 self
.log
.debug("updating repo: {}".format(command
))
185 await self
._local
_async
_exec
(
186 command
=command
, raise_exception_on_error
=False, env
=env
190 self
.fs
.reverse_sync(from_path
=cluster_uuid
)
192 async def repo_update(self
, cluster_uuid
: str, name
: str, repo_type
: str = "chart"):
194 "Cluster {}, updating {} repository {}".format(
195 cluster_uuid
, repo_type
, name
200 paths
, env
= self
._init
_paths
_env
(
201 cluster_name
=cluster_uuid
, create_if_not_exist
=True
205 self
.fs
.sync(from_path
=cluster_uuid
)
208 command
= "{} repo update {}".format(self
._helm
_command
, name
)
209 self
.log
.debug("updating repo: {}".format(command
))
210 await self
._local
_async
_exec
(
211 command
=command
, raise_exception_on_error
=False, env
=env
215 self
.fs
.reverse_sync(from_path
=cluster_uuid
)
217 async def repo_list(self
, cluster_uuid
: str) -> list:
219 Get the list of registered repositories
221 :return: list of registered repositories: [ (name, url) .... ]
224 self
.log
.debug("list repositories for cluster {}".format(cluster_uuid
))
227 paths
, env
= self
._init
_paths
_env
(
228 cluster_name
=cluster_uuid
, create_if_not_exist
=True
232 self
.fs
.sync(from_path
=cluster_uuid
)
234 command
= "env KUBECONFIG={} {} repo list --output yaml".format(
235 paths
["kube_config"], self
._helm
_command
238 # Set exception to false because if there are no repos just want an empty list
239 output
, _rc
= await self
._local
_async
_exec
(
240 command
=command
, raise_exception_on_error
=False, env
=env
244 self
.fs
.reverse_sync(from_path
=cluster_uuid
)
247 if output
and len(output
) > 0:
248 repos
= yaml
.load(output
, Loader
=yaml
.SafeLoader
)
249 # unify format between helm2 and helm3 setting all keys lowercase
250 return self
._lower
_keys
_list
(repos
)
256 async def repo_remove(self
, cluster_uuid
: str, name
: str):
258 "remove {} repositories for cluster {}".format(name
, cluster_uuid
)
262 paths
, env
= self
._init
_paths
_env
(
263 cluster_name
=cluster_uuid
, create_if_not_exist
=True
267 self
.fs
.sync(from_path
=cluster_uuid
)
269 command
= "env KUBECONFIG={} {} repo remove {}".format(
270 paths
["kube_config"], self
._helm
_command
, name
272 await self
._local
_async
_exec
(
273 command
=command
, raise_exception_on_error
=True, env
=env
277 self
.fs
.reverse_sync(from_path
=cluster_uuid
)
283 uninstall_sw
: bool = False,
288 Resets the Kubernetes cluster by removing the helm deployment that represents it.
290 :param cluster_uuid: The UUID of the cluster to reset
291 :param force: Boolean to force the reset
292 :param uninstall_sw: Boolean to force the reset
293 :param kwargs: Additional parameters (None yet)
294 :return: Returns True if successful or raises an exception.
296 namespace
= self
._get
_namespace
(cluster_uuid
=cluster_uuid
)
298 "Resetting K8s environment. cluster uuid: {} uninstall={}".format(
299 cluster_uuid
, uninstall_sw
304 self
.fs
.sync(from_path
=cluster_uuid
)
306 # uninstall releases if needed.
308 releases
= await self
.instances_list(cluster_uuid
=cluster_uuid
)
309 if len(releases
) > 0:
313 kdu_instance
= r
.get("name")
314 chart
= r
.get("chart")
316 "Uninstalling {} -> {}".format(chart
, kdu_instance
)
318 await self
.uninstall(
319 cluster_uuid
=cluster_uuid
, kdu_instance
=kdu_instance
321 except Exception as e
:
322 # will not raise exception as it was found
323 # that in some cases of previously installed helm releases it
326 "Error uninstalling release {}: {}".format(
332 "Cluster uuid: {} has releases and not force. Leaving K8s helm environment"
333 ).format(cluster_uuid
)
336 False # Allow to remove k8s cluster without removing Tiller
340 await self
._uninstall
_sw
(cluster_id
=cluster_uuid
, namespace
=namespace
)
342 # delete cluster directory
343 self
.log
.debug("Removing directory {}".format(cluster_uuid
))
344 self
.fs
.file_delete(cluster_uuid
, ignore_non_exist
=True)
345 # Remove also local directorio if still exist
346 direct
= self
.fs
.path
+ "/" + cluster_uuid
347 shutil
.rmtree(direct
, ignore_errors
=True)
351 async def _install_impl(
359 timeout
: float = 300,
361 db_dict
: dict = None,
362 kdu_name
: str = None,
363 namespace
: str = None,
366 paths
, env
= self
._init
_paths
_env
(
367 cluster_name
=cluster_id
, create_if_not_exist
=True
371 params_str
, file_to_delete
= self
._params
_to
_file
_option
(
372 cluster_id
=cluster_id
, params
=params
378 parts
= kdu_model
.split(sep
=":")
380 version
= str(parts
[1])
383 repo
= self
._split
_repo
(kdu_model
)
385 self
.repo_update(cluster_id
, repo
)
387 command
= self
._get
_install
_command
(
395 paths
["kube_config"],
398 self
.log
.debug("installing: {}".format(command
))
401 # exec helm in a task
402 exec_task
= asyncio
.ensure_future(
403 coro_or_future
=self
._local
_async
_exec
(
404 command
=command
, raise_exception_on_error
=False, env
=env
408 # write status in another task
409 status_task
= asyncio
.ensure_future(
410 coro_or_future
=self
._store
_status
(
411 cluster_id
=cluster_id
,
412 kdu_instance
=kdu_instance
,
420 # wait for execution task
421 await asyncio
.wait([exec_task
])
426 output
, rc
= exec_task
.result()
430 output
, rc
= await self
._local
_async
_exec
(
431 command
=command
, raise_exception_on_error
=False, env
=env
434 # remove temporal values yaml file
436 os
.remove(file_to_delete
)
439 await self
._store
_status
(
440 cluster_id
=cluster_id
,
441 kdu_instance
=kdu_instance
,
450 msg
= "Error executing command: {}\nOutput: {}".format(command
, output
)
452 raise K8sException(msg
)
458 kdu_model
: str = None,
460 timeout
: float = 300,
462 db_dict
: dict = None,
464 self
.log
.debug("upgrading {} in cluster {}".format(kdu_model
, cluster_uuid
))
467 self
.fs
.sync(from_path
=cluster_uuid
)
469 # look for instance to obtain namespace
470 instance_info
= await self
.get_instance_info(cluster_uuid
, kdu_instance
)
471 if not instance_info
:
472 raise K8sException("kdu_instance {} not found".format(kdu_instance
))
475 paths
, env
= self
._init
_paths
_env
(
476 cluster_name
=cluster_uuid
, create_if_not_exist
=True
480 self
.fs
.sync(from_path
=cluster_uuid
)
483 params_str
, file_to_delete
= self
._params
_to
_file
_option
(
484 cluster_id
=cluster_uuid
, params
=params
490 parts
= kdu_model
.split(sep
=":")
492 version
= str(parts
[1])
495 repo
= self
._split
_repo
(kdu_model
)
497 self
.repo_update(cluster_uuid
, repo
)
499 command
= self
._get
_upgrade
_command
(
502 instance_info
["namespace"],
507 paths
["kube_config"],
510 self
.log
.debug("upgrading: {}".format(command
))
514 # exec helm in a task
515 exec_task
= asyncio
.ensure_future(
516 coro_or_future
=self
._local
_async
_exec
(
517 command
=command
, raise_exception_on_error
=False, env
=env
520 # write status in another task
521 status_task
= asyncio
.ensure_future(
522 coro_or_future
=self
._store
_status
(
523 cluster_id
=cluster_uuid
,
524 kdu_instance
=kdu_instance
,
525 namespace
=instance_info
["namespace"],
532 # wait for execution task
533 await asyncio
.wait([exec_task
])
537 output
, rc
= exec_task
.result()
541 output
, rc
= await self
._local
_async
_exec
(
542 command
=command
, raise_exception_on_error
=False, env
=env
545 # remove temporal values yaml file
547 os
.remove(file_to_delete
)
550 await self
._store
_status
(
551 cluster_id
=cluster_uuid
,
552 kdu_instance
=kdu_instance
,
553 namespace
=instance_info
["namespace"],
561 msg
= "Error executing command: {}\nOutput: {}".format(command
, output
)
563 raise K8sException(msg
)
566 self
.fs
.reverse_sync(from_path
=cluster_uuid
)
568 # return new revision number
569 instance
= await self
.get_instance_info(
570 cluster_uuid
=cluster_uuid
, kdu_instance
=kdu_instance
573 revision
= int(instance
.get("revision"))
574 self
.log
.debug("New revision: {}".format(revision
))
584 total_timeout
: float = 1800,
587 raise NotImplementedError("Method not implemented")
589 async def get_scale_count(
595 raise NotImplementedError("Method not implemented")
598 self
, cluster_uuid
: str, kdu_instance
: str, revision
=0, db_dict
: dict = None
601 "rollback kdu_instance {} to revision {} from cluster {}".format(
602 kdu_instance
, revision
, cluster_uuid
607 self
.fs
.sync(from_path
=cluster_uuid
)
609 # look for instance to obtain namespace
610 instance_info
= await self
.get_instance_info(cluster_uuid
, kdu_instance
)
611 if not instance_info
:
612 raise K8sException("kdu_instance {} not found".format(kdu_instance
))
615 paths
, env
= self
._init
_paths
_env
(
616 cluster_name
=cluster_uuid
, create_if_not_exist
=True
620 self
.fs
.sync(from_path
=cluster_uuid
)
622 command
= self
._get
_rollback
_command
(
623 kdu_instance
, instance_info
["namespace"], revision
, paths
["kube_config"]
626 self
.log
.debug("rolling_back: {}".format(command
))
628 # exec helm in a task
629 exec_task
= asyncio
.ensure_future(
630 coro_or_future
=self
._local
_async
_exec
(
631 command
=command
, raise_exception_on_error
=False, env
=env
634 # write status in another task
635 status_task
= asyncio
.ensure_future(
636 coro_or_future
=self
._store
_status
(
637 cluster_id
=cluster_uuid
,
638 kdu_instance
=kdu_instance
,
639 namespace
=instance_info
["namespace"],
641 operation
="rollback",
646 # wait for execution task
647 await asyncio
.wait([exec_task
])
652 output
, rc
= exec_task
.result()
655 await self
._store
_status
(
656 cluster_id
=cluster_uuid
,
657 kdu_instance
=kdu_instance
,
658 namespace
=instance_info
["namespace"],
660 operation
="rollback",
666 msg
= "Error executing command: {}\nOutput: {}".format(command
, output
)
668 raise K8sException(msg
)
671 self
.fs
.reverse_sync(from_path
=cluster_uuid
)
673 # return new revision number
674 instance
= await self
.get_instance_info(
675 cluster_uuid
=cluster_uuid
, kdu_instance
=kdu_instance
678 revision
= int(instance
.get("revision"))
679 self
.log
.debug("New revision: {}".format(revision
))
684 async def uninstall(self
, cluster_uuid
: str, kdu_instance
: str, **kwargs
):
686 Removes an existing KDU instance. It would implicitly use the `delete` or 'uninstall' call
687 (this call should happen after all _terminate-config-primitive_ of the VNF
690 :param cluster_uuid: UUID of a K8s cluster known by OSM, or namespace:cluster_id
691 :param kdu_instance: unique name for the KDU instance to be deleted
692 :param kwargs: Additional parameters (None yet)
693 :return: True if successful
697 "uninstall kdu_instance {} from cluster {}".format(
698 kdu_instance
, cluster_uuid
703 self
.fs
.sync(from_path
=cluster_uuid
)
705 # look for instance to obtain namespace
706 instance_info
= await self
.get_instance_info(cluster_uuid
, kdu_instance
)
707 if not instance_info
:
708 self
.log
.warning(("kdu_instance {} not found".format(kdu_instance
)))
711 paths
, env
= self
._init
_paths
_env
(
712 cluster_name
=cluster_uuid
, create_if_not_exist
=True
716 self
.fs
.sync(from_path
=cluster_uuid
)
718 command
= self
._get
_uninstall
_command
(
719 kdu_instance
, instance_info
["namespace"], paths
["kube_config"]
721 output
, _rc
= await self
._local
_async
_exec
(
722 command
=command
, raise_exception_on_error
=True, env
=env
726 self
.fs
.reverse_sync(from_path
=cluster_uuid
)
728 return self
._output
_to
_table
(output
)
730 async def instances_list(self
, cluster_uuid
: str) -> list:
732 returns a list of deployed releases in a cluster
734 :param cluster_uuid: the 'cluster' or 'namespace:cluster'
738 self
.log
.debug("list releases for cluster {}".format(cluster_uuid
))
741 self
.fs
.sync(from_path
=cluster_uuid
)
743 # execute internal command
744 result
= await self
._instances
_list
(cluster_uuid
)
747 self
.fs
.reverse_sync(from_path
=cluster_uuid
)
751 async def get_instance_info(self
, cluster_uuid
: str, kdu_instance
: str):
752 instances
= await self
.instances_list(cluster_uuid
=cluster_uuid
)
753 for instance
in instances
:
754 if instance
.get("name") == kdu_instance
:
756 self
.log
.debug("Instance {} not found".format(kdu_instance
))
759 async def exec_primitive(
761 cluster_uuid
: str = None,
762 kdu_instance
: str = None,
763 primitive_name
: str = None,
764 timeout
: float = 300,
766 db_dict
: dict = None,
769 """Exec primitive (Juju action)
771 :param cluster_uuid: The UUID of the cluster or namespace:cluster
772 :param kdu_instance: The unique name of the KDU instance
773 :param primitive_name: Name of action that will be executed
774 :param timeout: Timeout for action execution
775 :param params: Dictionary of all the parameters needed for the action
776 :db_dict: Dictionary for any additional data
777 :param kwargs: Additional parameters (None yet)
779 :return: Returns the output of the action
782 "KDUs deployed with Helm don't support actions "
783 "different from rollback, upgrade and status"
786 async def get_services(
787 self
, cluster_uuid
: str, kdu_instance
: str, namespace
: str
790 Returns a list of services defined for the specified kdu instance.
792 :param cluster_uuid: UUID of a K8s cluster known by OSM
793 :param kdu_instance: unique name for the KDU instance
794 :param namespace: K8s namespace used by the KDU instance
795 :return: If successful, it will return a list of services, Each service
796 can have the following data:
797 - `name` of the service
798 - `type` type of service in the k8 cluster
799 - `ports` List of ports offered by the service, for each port includes at least
801 - `cluster_ip` Internal ip to be used inside k8s cluster
802 - `external_ip` List of external ips (in case they are available)
806 "get_services: cluster_uuid: {}, kdu_instance: {}".format(
807 cluster_uuid
, kdu_instance
812 paths
, env
= self
._init
_paths
_env
(
813 cluster_name
=cluster_uuid
, create_if_not_exist
=True
817 self
.fs
.sync(from_path
=cluster_uuid
)
819 # get list of services names for kdu
820 service_names
= await self
._get
_services
(
821 cluster_uuid
, kdu_instance
, namespace
, paths
["kube_config"]
825 for service
in service_names
:
826 service
= await self
._get
_service
(cluster_uuid
, service
, namespace
)
827 service_list
.append(service
)
830 self
.fs
.reverse_sync(from_path
=cluster_uuid
)
834 async def get_service(
835 self
, cluster_uuid
: str, service_name
: str, namespace
: str
839 "get service, service_name: {}, namespace: {}, cluster_uuid: {}".format(
840 service_name
, namespace
, cluster_uuid
845 self
.fs
.sync(from_path
=cluster_uuid
)
847 service
= await self
._get
_service
(cluster_uuid
, service_name
, namespace
)
850 self
.fs
.reverse_sync(from_path
=cluster_uuid
)
854 async def status_kdu(
855 self
, cluster_uuid
: str, kdu_instance
: str, yaml_format
: str = False, **kwargs
856 ) -> Union
[str, dict]:
858 This call would retrieve tha current state of a given KDU instance. It would be
859 would allow to retrieve the _composition_ (i.e. K8s objects) and _specific
860 values_ of the configuration parameters applied to a given instance. This call
861 would be based on the `status` call.
863 :param cluster_uuid: UUID of a K8s cluster known by OSM
864 :param kdu_instance: unique name for the KDU instance
865 :param kwargs: Additional parameters (None yet)
866 :param yaml_format: if the return shall be returned as an YAML string or as a
868 :return: If successful, it will return the following vector of arguments:
869 - K8s `namespace` in the cluster where the KDU lives
870 - `state` of the KDU instance. It can be:
877 - List of `resources` (objects) that this release consists of, sorted by kind,
878 and the status of those resources
879 - Last `deployment_time`.
883 "status_kdu: cluster_uuid: {}, kdu_instance: {}".format(
884 cluster_uuid
, kdu_instance
889 self
.fs
.sync(from_path
=cluster_uuid
)
891 # get instance: needed to obtain namespace
892 instances
= await self
._instances
_list
(cluster_id
=cluster_uuid
)
893 for instance
in instances
:
894 if instance
.get("name") == kdu_instance
:
897 # instance does not exist
899 "Instance name: {} not found in cluster: {}".format(
900 kdu_instance
, cluster_uuid
904 status
= await self
._status
_kdu
(
905 cluster_id
=cluster_uuid
,
906 kdu_instance
=kdu_instance
,
907 namespace
=instance
["namespace"],
908 yaml_format
=yaml_format
,
913 self
.fs
.reverse_sync(from_path
=cluster_uuid
)
917 async def values_kdu(self
, kdu_model
: str, repo_url
: str = None) -> str:
920 "inspect kdu_model values {} from (optional) repo: {}".format(
925 return await self
._exec
_inspect
_comand
(
926 inspect_command
="values", kdu_model
=kdu_model
, repo_url
=repo_url
929 async def help_kdu(self
, kdu_model
: str, repo_url
: str = None) -> str:
932 "inspect kdu_model {} readme.md from repo: {}".format(kdu_model
, repo_url
)
935 return await self
._exec
_inspect
_comand
(
936 inspect_command
="readme", kdu_model
=kdu_model
, repo_url
=repo_url
939 async def synchronize_repos(self
, cluster_uuid
: str):
941 self
.log
.debug("synchronize repos for cluster helm-id: {}".format(cluster_uuid
))
943 db_repo_ids
= self
._get
_helm
_chart
_repos
_ids
(cluster_uuid
)
944 db_repo_dict
= self
._get
_db
_repos
_dict
(db_repo_ids
)
946 local_repo_list
= await self
.repo_list(cluster_uuid
)
947 local_repo_dict
= {repo
["name"]: repo
["url"] for repo
in local_repo_list
}
949 deleted_repo_list
= []
952 # iterate over the list of repos in the database that should be
953 # added if not present
954 for repo_name
, db_repo
in db_repo_dict
.items():
956 # check if it is already present
957 curr_repo_url
= local_repo_dict
.get(db_repo
["name"])
958 repo_id
= db_repo
.get("_id")
959 if curr_repo_url
!= db_repo
["url"]:
962 "repo {} url changed, delete and and again".format(
966 await self
.repo_remove(cluster_uuid
, db_repo
["name"])
967 deleted_repo_list
.append(repo_id
)
970 self
.log
.debug("add repo {}".format(db_repo
["name"]))
972 cluster_uuid
, db_repo
["name"], db_repo
["url"]
974 added_repo_dict
[repo_id
] = db_repo
["name"]
975 except Exception as e
:
977 "Error adding repo id: {}, err_msg: {} ".format(
982 # Delete repos that are present but not in nbi_list
983 for repo_name
in local_repo_dict
:
984 if not db_repo_dict
.get(repo_name
) and repo_name
!= "stable":
985 self
.log
.debug("delete repo {}".format(repo_name
))
987 await self
.repo_remove(cluster_uuid
, repo_name
)
988 deleted_repo_list
.append(repo_name
)
989 except Exception as e
:
991 "Error deleting repo, name: {}, err_msg: {}".format(
996 return deleted_repo_list
, added_repo_dict
1000 except Exception as e
:
1001 # Do not raise errors synchronizing repos
1002 self
.log
.error("Error synchronizing repos: {}".format(e
))
1003 raise Exception("Error synchronizing repos: {}".format(e
))
1005 def _get_db_repos_dict(self
, repo_ids
: list):
1007 for repo_id
in repo_ids
:
1008 db_repo
= self
.db
.get_one("k8srepos", {"_id": repo_id
})
1009 db_repos_dict
[db_repo
["name"]] = db_repo
1010 return db_repos_dict
1013 ####################################################################################
1014 ################################### TO BE IMPLEMENTED SUBCLASSES ###################
1015 ####################################################################################
1019 def _init_paths_env(self
, cluster_name
: str, create_if_not_exist
: bool = True):
1021 Creates and returns base cluster and kube dirs and returns them.
1022 Also created helm3 dirs according to new directory specification, paths are
1023 not returned but assigned to helm environment variables
1025 :param cluster_name: cluster_name
1026 :return: Dictionary with config_paths and dictionary with helm environment variables
1030 async def _cluster_init(self
, cluster_id
, namespace
, paths
, env
):
1032 Implements the helm version dependent cluster initialization
1036 async def _instances_list(self
, cluster_id
):
1038 Implements the helm version dependent helm instances list
1042 async def _get_services(self
, cluster_id
, kdu_instance
, namespace
, kubeconfig
):
1044 Implements the helm version dependent method to obtain services from a helm instance
1048 async def _status_kdu(
1052 namespace
: str = None,
1053 yaml_format
: bool = False,
1054 show_error_log
: bool = False,
1055 ) -> Union
[str, dict]:
1057 Implements the helm version dependent method to obtain status of a helm instance
1061 def _get_install_command(
1073 Obtain command to be executed to delete the indicated instance
1077 def _get_upgrade_command(
1089 Obtain command to be executed to upgrade the indicated instance
1093 def _get_rollback_command(
1094 self
, kdu_instance
, namespace
, revision
, kubeconfig
1097 Obtain command to be executed to rollback the indicated instance
1101 def _get_uninstall_command(
1102 self
, kdu_instance
: str, namespace
: str, kubeconfig
: str
1105 Obtain command to be executed to delete the indicated instance
1109 def _get_inspect_command(
1110 self
, show_command
: str, kdu_model
: str, repo_str
: str, version
: str
1113 Obtain command to be executed to obtain information about the kdu
1117 async def _uninstall_sw(self
, cluster_id
: str, namespace
: str):
1119 Method call to uninstall cluster software for helm. This method is dependent
1121 For Helm v2 it will be called when Tiller must be uninstalled
1122 For Helm v3 it does nothing and does not need to be callled
1126 def _get_helm_chart_repos_ids(self
, cluster_uuid
) -> list:
1128 Obtains the cluster repos identifiers
1132 ####################################################################################
1133 ################################### P R I V A T E ##################################
1134 ####################################################################################
1138 def _check_file_exists(filename
: str, exception_if_not_exists
: bool = False):
1139 if os
.path
.exists(filename
):
1142 msg
= "File {} does not exist".format(filename
)
1143 if exception_if_not_exists
:
1144 raise K8sException(msg
)
1147 def _remove_multiple_spaces(strobj
):
1148 strobj
= strobj
.strip()
1149 while " " in strobj
:
1150 strobj
= strobj
.replace(" ", " ")
1154 def _output_to_lines(output
: str) -> list:
1155 output_lines
= list()
1156 lines
= output
.splitlines(keepends
=False)
1160 output_lines
.append(line
)
1164 def _output_to_table(output
: str) -> list:
1165 output_table
= list()
1166 lines
= output
.splitlines(keepends
=False)
1168 line
= line
.replace("\t", " ")
1170 output_table
.append(line_list
)
1171 cells
= line
.split(sep
=" ")
1175 line_list
.append(cell
)
1179 def _parse_services(output
: str) -> list:
1180 lines
= output
.splitlines(keepends
=False)
1183 line
= line
.replace("\t", " ")
1184 cells
= line
.split(sep
=" ")
1185 if len(cells
) > 0 and cells
[0].startswith("service/"):
1186 elems
= cells
[0].split(sep
="/")
1188 services
.append(elems
[1])
1192 def _get_deep(dictionary
: dict, members
: tuple):
1197 value
= target
.get(m
)
1206 # find key:value in several lines
1208 def _find_in_lines(p_lines
: list, p_key
: str) -> str:
1209 for line
in p_lines
:
1211 if line
.startswith(p_key
+ ":"):
1212 parts
= line
.split(":")
1213 the_value
= parts
[1].strip()
1221 def _lower_keys_list(input_list
: list):
1223 Transform the keys in a list of dictionaries to lower case and returns a new list
1228 for dictionary
in input_list
:
1229 new_dict
= dict((k
.lower(), v
) for k
, v
in dictionary
.items())
1230 new_list
.append(new_dict
)
1233 async def _local_async_exec(
1236 raise_exception_on_error
: bool = False,
1237 show_error_log
: bool = True,
1238 encode_utf8
: bool = False,
1242 command
= K8sHelmBaseConnector
._remove
_multiple
_spaces
(command
)
1244 "Executing async local command: {}, env: {}".format(command
, env
)
1248 command
= shlex
.split(command
)
1250 environ
= os
.environ
.copy()
1255 process
= await asyncio
.create_subprocess_exec(
1257 stdout
=asyncio
.subprocess
.PIPE
,
1258 stderr
=asyncio
.subprocess
.PIPE
,
1262 # wait for command terminate
1263 stdout
, stderr
= await process
.communicate()
1265 return_code
= process
.returncode
1269 output
= stdout
.decode("utf-8").strip()
1270 # output = stdout.decode()
1272 output
= stderr
.decode("utf-8").strip()
1273 # output = stderr.decode()
1275 if return_code
!= 0 and show_error_log
:
1277 "Return code (FAIL): {}\nOutput:\n{}".format(return_code
, output
)
1280 self
.log
.debug("Return code: {}".format(return_code
))
1282 if raise_exception_on_error
and return_code
!= 0:
1283 raise K8sException(output
)
1286 output
= output
.encode("utf-8").strip()
1287 output
= str(output
).replace("\\n", "\n")
1289 return output
, return_code
1291 except asyncio
.CancelledError
:
1293 except K8sException
:
1295 except Exception as e
:
1296 msg
= "Exception executing command: {} -> {}".format(command
, e
)
1298 if raise_exception_on_error
:
1299 raise K8sException(e
) from e
1303 async def _local_async_exec_pipe(
1307 raise_exception_on_error
: bool = True,
1308 show_error_log
: bool = True,
1309 encode_utf8
: bool = False,
1313 command1
= K8sHelmBaseConnector
._remove
_multiple
_spaces
(command1
)
1314 command2
= K8sHelmBaseConnector
._remove
_multiple
_spaces
(command2
)
1315 command
= "{} | {}".format(command1
, command2
)
1317 "Executing async local command: {}, env: {}".format(command
, env
)
1321 command1
= shlex
.split(command1
)
1322 command2
= shlex
.split(command2
)
1324 environ
= os
.environ
.copy()
1329 read
, write
= os
.pipe()
1330 await asyncio
.create_subprocess_exec(*command1
, stdout
=write
, env
=environ
)
1332 process_2
= await asyncio
.create_subprocess_exec(
1333 *command2
, stdin
=read
, stdout
=asyncio
.subprocess
.PIPE
, env
=environ
1336 stdout
, stderr
= await process_2
.communicate()
1338 return_code
= process_2
.returncode
1342 output
= stdout
.decode("utf-8").strip()
1343 # output = stdout.decode()
1345 output
= stderr
.decode("utf-8").strip()
1346 # output = stderr.decode()
1348 if return_code
!= 0 and show_error_log
:
1350 "Return code (FAIL): {}\nOutput:\n{}".format(return_code
, output
)
1353 self
.log
.debug("Return code: {}".format(return_code
))
1355 if raise_exception_on_error
and return_code
!= 0:
1356 raise K8sException(output
)
1359 output
= output
.encode("utf-8").strip()
1360 output
= str(output
).replace("\\n", "\n")
1362 return output
, return_code
1363 except asyncio
.CancelledError
:
1365 except K8sException
:
1367 except Exception as e
:
1368 msg
= "Exception executing command: {} -> {}".format(command
, e
)
1370 if raise_exception_on_error
:
1371 raise K8sException(e
) from e
1375 async def _get_service(self
, cluster_id
, service_name
, namespace
):
1377 Obtains the data of the specified service in the k8cluster.
1379 :param cluster_id: id of a K8s cluster known by OSM
1380 :param service_name: name of the K8s service in the specified namespace
1381 :param namespace: K8s namespace used by the KDU instance
1382 :return: If successful, it will return a service with the following data:
1383 - `name` of the service
1384 - `type` type of service in the k8 cluster
1385 - `ports` List of ports offered by the service, for each port includes at least
1386 name, port, protocol
1387 - `cluster_ip` Internal ip to be used inside k8s cluster
1388 - `external_ip` List of external ips (in case they are available)
1392 paths
, env
= self
._init
_paths
_env
(
1393 cluster_name
=cluster_id
, create_if_not_exist
=True
1396 command
= "{} --kubeconfig={} --namespace={} get service {} -o=yaml".format(
1397 self
.kubectl_command
, paths
["kube_config"], namespace
, service_name
1400 output
, _rc
= await self
._local
_async
_exec
(
1401 command
=command
, raise_exception_on_error
=True, env
=env
1404 data
= yaml
.load(output
, Loader
=yaml
.SafeLoader
)
1407 "name": service_name
,
1408 "type": self
._get
_deep
(data
, ("spec", "type")),
1409 "ports": self
._get
_deep
(data
, ("spec", "ports")),
1410 "cluster_ip": self
._get
_deep
(data
, ("spec", "clusterIP")),
1412 if service
["type"] == "LoadBalancer":
1413 ip_map_list
= self
._get
_deep
(data
, ("status", "loadBalancer", "ingress"))
1414 ip_list
= [elem
["ip"] for elem
in ip_map_list
]
1415 service
["external_ip"] = ip_list
1419 async def _exec_inspect_comand(
1420 self
, inspect_command
: str, kdu_model
: str, repo_url
: str = None
1423 Obtains information about a kdu, no cluster (no env)
1428 repo_str
= " --repo {}".format(repo_url
)
1430 idx
= kdu_model
.find("/")
1433 kdu_model
= kdu_model
[idx
:]
1436 if ":" in kdu_model
:
1437 parts
= kdu_model
.split(sep
=":")
1439 version
= "--version {}".format(str(parts
[1]))
1440 kdu_model
= parts
[0]
1442 full_command
= self
._get
_inspect
_command
(
1443 inspect_command
, kdu_model
, repo_str
, version
1445 output
, _rc
= await self
._local
_async
_exec
(
1446 command
=full_command
, encode_utf8
=True
1451 async def _store_status(
1456 namespace
: str = None,
1457 check_every
: float = 10,
1458 db_dict
: dict = None,
1459 run_once
: bool = False,
1463 await asyncio
.sleep(check_every
)
1464 detailed_status
= await self
._status
_kdu
(
1465 cluster_id
=cluster_id
,
1466 kdu_instance
=kdu_instance
,
1468 namespace
=namespace
,
1470 status
= detailed_status
.get("info").get("description")
1471 self
.log
.debug("KDU {} STATUS: {}.".format(kdu_instance
, status
))
1472 # write status to db
1473 result
= await self
.write_app_status_to_db(
1476 detailed_status
=str(detailed_status
),
1477 operation
=operation
,
1480 self
.log
.info("Error writing in database. Task exiting...")
1482 except asyncio
.CancelledError
:
1483 self
.log
.debug("Task cancelled")
1485 except Exception as e
:
1487 "_store_status exception: {}".format(str(e
)), exc_info
=True
1494 # params for use in -f file
1495 # returns values file option and filename (in order to delete it at the end)
1496 def _params_to_file_option(self
, cluster_id
: str, params
: dict) -> (str, str):
1498 if params
and len(params
) > 0:
1499 self
._init
_paths
_env
(cluster_name
=cluster_id
, create_if_not_exist
=True)
1501 def get_random_number():
1502 r
= random
.randrange(start
=1, stop
=99999999)
1510 value
= params
.get(key
)
1511 if "!!yaml" in str(value
):
1512 value
= yaml
.load(value
[7:])
1513 params2
[key
] = value
1515 values_file
= get_random_number() + ".yaml"
1516 with
open(values_file
, "w") as stream
:
1517 yaml
.dump(params2
, stream
, indent
=4, default_flow_style
=False)
1519 return "-f {}".format(values_file
), values_file
1523 # params for use in --set option
1525 def _params_to_set_option(params
: dict) -> str:
1527 if params
and len(params
) > 0:
1530 value
= params
.get(key
, None)
1531 if value
is not None:
1533 params_str
+= "--set "
1537 params_str
+= "{}={}".format(key
, value
)
1541 def generate_kdu_instance_name(**kwargs
):
1542 chart_name
= kwargs
["kdu_model"]
1543 # check embeded chart (file or dir)
1544 if chart_name
.startswith("/"):
1545 # extract file or directory name
1546 chart_name
= chart_name
[chart_name
.rfind("/") + 1 :]
1548 elif "://" in chart_name
:
1549 # extract last portion of URL
1550 chart_name
= chart_name
[chart_name
.rfind("/") + 1 :]
1553 for c
in chart_name
:
1554 if c
.isalpha() or c
.isnumeric():
1561 # if does not start with alpha character, prefix 'a'
1562 if not name
[0].isalpha():
1567 def get_random_number():
1568 r
= random
.randrange(start
=1, stop
=99999999)
1570 s
= s
.rjust(10, "0")
1573 name
= name
+ get_random_number()
1576 def _split_version(self
, kdu_model
: str) -> (str, str):
1578 if ":" in kdu_model
:
1579 parts
= kdu_model
.split(sep
=":")
1581 version
= str(parts
[1])
1582 kdu_model
= parts
[0]
1583 return kdu_model
, version
1585 async def _split_repo(self
, kdu_model
: str) -> str:
1587 idx
= kdu_model
.find("/")
1589 repo_name
= kdu_model
[:idx
]
1592 async def _find_repo(self
, kdu_model
: str, cluster_uuid
: str) -> str:
1594 idx
= kdu_model
.find("/")
1596 repo_name
= kdu_model
[:idx
]
1597 # Find repository link
1598 local_repo_list
= await self
.repo_list(cluster_uuid
)
1599 for repo
in local_repo_list
:
1600 repo_url
= repo
["url"] if repo
["name"] == repo_name
else None