1 # Copyright (C) 2021 Wind River Systems, Inc.
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
7 # http://www.apache.org/licenses/LICENSE-2.0
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
19 from datetime import datetime
22 from o2common.service import unit_of_work
23 from o2common.config import config
24 from o2common.views.pagination_view import Pagination
25 from o2ims.domain import ocloud
26 from o2ims.views.ocloud_dto import SubscriptionDTO
27 from o2ims.domain.subscription_obj import Subscription
29 from o2common.helper import o2logging
30 logger = o2logging.get_logger(__name__)
33 def oclouds(uow: unit_of_work.AbstractUnitOfWork):
35 li = uow.oclouds.list()
36 return [r.serialize() for r in li]
39 def ocloud_one(ocloudid: str, uow: unit_of_work.AbstractUnitOfWork):
41 first = uow.oclouds.get(ocloudid)
42 return first.serialize() if first is not None else None
45 def resource_types(uow: unit_of_work.AbstractUnitOfWork, **kwargs):
46 pagination = Pagination(**kwargs)
47 filter_kwargs = pagination.get_filter()
49 li = uow.resource_types.list_with_count(**filter_kwargs)
50 return pagination.get_result(li)
53 def resource_type_one(resourceTypeId: str,
54 uow: unit_of_work.AbstractUnitOfWork):
56 first = uow.resource_types.get(resourceTypeId)
57 return first.serialize() if first is not None else None
60 def resource_pools(uow: unit_of_work.AbstractUnitOfWork, **kwargs):
61 pagination = Pagination(**kwargs)
62 filter_kwargs = pagination.get_filter()
64 li = uow.resource_pools.list_with_count(**filter_kwargs)
65 return pagination.get_result(li)
68 def resource_pool_one(resourcePoolId: str,
69 uow: unit_of_work.AbstractUnitOfWork):
71 first = uow.resource_pools.get(resourcePoolId)
72 return first.serialize() if first is not None else None
75 def resources(resourcePoolId: str, uow: unit_of_work.AbstractUnitOfWork,
77 pagination = Pagination(**kwargs)
78 # filter key should be the same with database name
79 filter_kwargs = pagination.get_filter()
80 if 'resourceTypeName' in kwargs:
81 resource_type_name = kwargs['resourceTypeName']
83 # res_types = uow.resource_types.list()
85 # restype.resourceTypeId for restype in res_types
86 # if resourceTypeName == restype.name]
87 # restype_id = '' if len(restype_ids) == 0 else restype_ids[0]
88 res_type = uow.resource_types.get_by_name(resource_type_name)
89 restype_id = '' if res_type is None else res_type.resourceTypeId
90 filter_kwargs['resourceTypeId'] = restype_id
92 if 'parentId' in kwargs:
93 filter_kwargs['parentId'] = kwargs['parentId']
95 filter_kwargs['sort'] = kwargs['sort']
98 ret = uow.resources.list_with_count(resourcePoolId, **filter_kwargs)
100 return pagination.get_result(ret)
103 def resource_one(resourceId: str, uow: unit_of_work.AbstractUnitOfWork):
105 first = uow.resources.get(resourceId)
106 return first.serialize() if first is not None else None
109 def deployment_managers(uow: unit_of_work.AbstractUnitOfWork, **kwargs):
110 pagination = Pagination(**kwargs)
111 filter_kwargs = pagination.get_filter()
113 li = uow.deployment_managers.list_with_count(**filter_kwargs)
114 return pagination.get_result(li)
117 def deployment_manager_one(deploymentManagerId: str,
118 uow: unit_of_work.AbstractUnitOfWork,
119 profile: str = 'default'):
120 profile = profile.lower()
122 first = uow.deployment_managers.get(deploymentManagerId)
125 result = first.serialize()
129 profile_data = result.pop("profile", None)
130 result['profileName'] = profile
132 if ocloud.DeploymentManagerProfileDefault == profile:
134 elif ocloud.DeploymentManagerProfileSOL018 == profile:
135 result['deploymentManagementServiceEndpoint'] = \
136 profile_data['cluster_api_endpoint']
137 result['profileData'] = profile_data
138 elif ocloud.DeploymentManagerProfileSOL018HelmCLI == profile:
139 result['deploymentManagementServiceEndpoint'] = \
140 profile_data['cluster_api_endpoint']
142 helmcli_profile = dict()
143 helmcli_profile["helmcli_host_with_port"], helmcli_profile[
144 "helmcli_username"], helmcli_profile["helmcli_password"] = \
145 config.get_helmcli_access()
146 helmcli_profile["helmcli_kubeconfig"] = _gen_kube_config(
147 deploymentManagerId, profile_data)
148 result['profileData'] = helmcli_profile
155 def _gen_kube_config(dmId: str, kubeconfig: dict) -> dict:
157 data = config.gen_k8s_config_dict(
158 kubeconfig.pop('cluster_api_endpoint', None),
159 kubeconfig.pop('cluster_ca_cert', None),
160 kubeconfig.pop('admin_user', None),
161 kubeconfig.pop('admin_client_cert', None),
162 kubeconfig.pop('admin_client_key', None),
165 # Generate a random key for tmp kube config file
166 # letters = string.ascii_uppercase
167 # random_key = ''.join(random.choice(letters) for i in range(10))
170 # Get datetime of now as tag of the tmp file
171 current_time = datetime.now().strftime("%Y%m%d%H%M%S")
172 tmp_file_name = 'kubeconfig_' + name_key + "_" + current_time
173 kube_config_name = 'kubeconfig_' + name_key + '.config'
175 # write down the yaml file of kubectl into tmp folder
176 with open('/tmp/' + tmp_file_name, 'w') as file:
177 yaml.dump(data, file)
179 # generate the kube config file if not exist or update the file if it
181 if not os.path.exists('/configs/' + kube_config_name) or not \
182 filecmp.cmp('/tmp/'+tmp_file_name, '/configs/'+kube_config_name):
183 shutil.move(os.path.join('/tmp', tmp_file_name),
184 os.path.join('/configs', kube_config_name))
186 return '/configs/'+kube_config_name
189 def subscriptions(uow: unit_of_work.AbstractUnitOfWork, **kwargs):
190 pagination = Pagination(**kwargs)
191 filter_kwargs = pagination.get_filter()
193 li = uow.subscriptions.list_with_count(**filter_kwargs)
194 return pagination.get_result(li)
197 def subscription_one(subscriptionId: str,
198 uow: unit_of_work.AbstractUnitOfWork):
200 first = uow.subscriptions.get(subscriptionId)
201 return first.serialize() if first is not None else None
204 def subscription_create(subscriptionDto: SubscriptionDTO.subscription,
205 uow: unit_of_work.AbstractUnitOfWork):
207 sub_uuid = str(uuid.uuid4())
208 subscription = Subscription(
209 sub_uuid, subscriptionDto['callback'],
210 subscriptionDto['consumerSubscriptionId'],
211 subscriptionDto['filter'])
213 uow.subscriptions.add(subscription)
215 return {"subscriptionId": sub_uuid}
218 def subscription_delete(subscriptionId: str,
219 uow: unit_of_work.AbstractUnitOfWork):
221 uow.subscriptions.delete(subscriptionId)