Fix INF-342 refactor deploymentManager profile data
[pti/o2.git] / o2ims / views / ocloud_view.py
1 # Copyright (C) 2021 Wind River Systems, Inc.
2 #
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
6 #
7 #      http://www.apache.org/licenses/LICENSE-2.0
8 #
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.
14
15 import filecmp
16 import os.path
17 import uuid
18 import yaml
19 from datetime import datetime
20 import shutil
21
22 from o2common.service import unit_of_work
23 from o2common.config import config
24 from o2common.views.pagination_view import Pagination
25 from o2common.views.view import gen_filter, check_filter
26 from o2ims.domain import ocloud
27 from o2ims.views.ocloud_dto import SubscriptionDTO
28 from o2ims.domain.subscription_obj import Subscription
29
30 from o2common.helper import o2logging
31 logger = o2logging.get_logger(__name__)
32
33
34 def oclouds(uow: unit_of_work.AbstractUnitOfWork):
35     with uow:
36         li = uow.oclouds.list()
37     return [r.serialize() for r in li]
38
39
40 def ocloud_one(ocloudid: str, uow: unit_of_work.AbstractUnitOfWork):
41     with uow:
42         first = uow.oclouds.get(ocloudid)
43         return first.serialize() if first is not None else None
44
45
46 def resource_types(uow: unit_of_work.AbstractUnitOfWork, **kwargs):
47     pagination = Pagination(**kwargs)
48     query_kwargs = pagination.get_pagination()
49     args = gen_filter(ocloud.ResourceType,
50                       kwargs['filter']) if 'filter' in kwargs else []
51     with uow:
52         li = uow.resource_types.list_with_count(*args, **query_kwargs)
53     return pagination.get_result(li)
54
55
56 def resource_type_one(resourceTypeId: str,
57                       uow: unit_of_work.AbstractUnitOfWork):
58     with uow:
59         first = uow.resource_types.get(resourceTypeId)
60         return first.serialize() if first is not None else None
61
62
63 def resource_pools(uow: unit_of_work.AbstractUnitOfWork, **kwargs):
64     pagination = Pagination(**kwargs)
65     query_kwargs = pagination.get_pagination()
66     args = gen_filter(ocloud.ResourcePool,
67                       kwargs['filter']) if 'filter' in kwargs else []
68     with uow:
69         li = uow.resource_pools.list_with_count(*args, **query_kwargs)
70     return pagination.get_result(li)
71
72
73 def resource_pool_one(resourcePoolId: str,
74                       uow: unit_of_work.AbstractUnitOfWork):
75     with uow:
76         first = uow.resource_pools.get(resourcePoolId)
77         return first.serialize() if first is not None else None
78
79
80 def resources(resourcePoolId: str, uow: unit_of_work.AbstractUnitOfWork,
81               **kwargs):
82     pagination = Pagination(**kwargs)
83     # filter key should be the same with database name
84     query_kwargs = pagination.get_pagination()
85     if 'resourceTypeName' in kwargs:
86         resource_type_name = kwargs['resourceTypeName']
87         with uow:
88             # res_types = uow.resource_types.list()
89             # restype_ids = [
90             #     restype.resourceTypeId for restype in res_types
91             #     if resourceTypeName == restype.name]
92             # restype_id = '' if len(restype_ids) == 0 else restype_ids[0]
93             res_type = uow.resource_types.get_by_name(resource_type_name)
94             restype_id = '' if res_type is None else res_type.resourceTypeId
95         query_kwargs['resourceTypeId'] = restype_id
96     args = gen_filter(
97         ocloud.Resource, kwargs['filter']) if 'filter' in kwargs else []
98     args.append(ocloud.Resource.resourcePoolId == resourcePoolId)
99     # args.append(ocloud.Resource.parentId == None)
100
101     if 'parentId' in kwargs:
102         query_kwargs['parentId'] = kwargs['parentId']
103     if 'sort' in kwargs:
104         query_kwargs['sort'] = kwargs['sort']
105
106     with uow:
107         ret = uow.resources.list_with_count(
108             resourcePoolId, *args, **query_kwargs)
109
110     return pagination.get_result(ret)
111
112
113 def resource_one(resourceId: str, uow: unit_of_work.AbstractUnitOfWork):
114     with uow:
115         first = uow.resources.get(resourceId)
116         return first.serialize() if first is not None else None
117
118
119 def deployment_managers(uow: unit_of_work.AbstractUnitOfWork, **kwargs):
120     pagination = Pagination(**kwargs)
121     query_kwargs = pagination.get_pagination()
122     args = gen_filter(ocloud.DeploymentManager,
123                       kwargs['filter']) if 'filter' in kwargs else []
124     with uow:
125         li = uow.deployment_managers.list_with_count(*args, **query_kwargs)
126     return pagination.get_result(li)
127
128
129 def deployment_manager_one(deploymentManagerId: str,
130                            uow: unit_of_work.AbstractUnitOfWork,
131                            profile: str =
132                            ocloud.DeploymentManagerProfileDefault):
133     profile = profile.lower()
134     with uow:
135         first = uow.deployment_managers.get(deploymentManagerId)
136         if first is None:
137             return first
138         result = first.serialize()
139         if result is None:
140             return None
141
142     profile_data = result.pop("profile", None)
143     profiles = config.get_dms_support_profiles()
144     if profile not in profiles:
145         return ""
146
147     extensions = {
148         'profileName': profile
149     }
150     if ocloud.DeploymentManagerProfileDefault == profile \
151             or ocloud.DeploymentManagerProfileSOL018 == profile:
152         result['serviceUri'] = \
153             profile_data['cluster_api_endpoint']
154         extensions['profileData'] = profile_data
155     elif ocloud.DeploymentManagerProfileSOL018HelmCLI == profile:
156         result['serviceUri'] = \
157             profile_data['cluster_api_endpoint']
158
159         helmcli_profile = dict()
160         helmcli_profile["helmcli_host_with_port"], helmcli_profile[
161             "helmcli_username"], helmcli_profile["helmcli_password"] = \
162             config.get_helmcli_access()
163         helmcli_profile["helmcli_kubeconfig"] = _gen_kube_config(
164             deploymentManagerId, profile_data)
165         extensions['profileData'] = helmcli_profile
166     else:
167         return ""
168
169     result['extensions'] = extensions
170     return result
171
172
173 def _gen_kube_config(dmId: str, kubeconfig: dict) -> dict:
174
175     data = config.gen_k8s_config_dict(
176         kubeconfig.pop('cluster_api_endpoint', None),
177         kubeconfig.pop('cluster_ca_cert', None),
178         kubeconfig.pop('admin_user', None),
179         kubeconfig.pop('admin_client_cert', None),
180         kubeconfig.pop('admin_client_key', None),
181     )
182
183     # Generate a random key for tmp kube config file
184     # letters = string.ascii_uppercase
185     # random_key = ''.join(random.choice(letters) for i in range(10))
186     name_key = dmId[:8]
187
188     # Get datetime of now as tag of the tmp file
189     current_time = datetime.now().strftime("%Y%m%d%H%M%S")
190     tmp_file_name = 'kubeconfig_' + name_key + "_" + current_time
191     kube_config_name = 'kubeconfig_' + name_key + '.config'
192
193     # write down the yaml file of kubectl into tmp folder
194     with open('/tmp/' + tmp_file_name, 'w') as file:
195         yaml.dump(data, file)
196
197     # generate the kube config file if not exist or update the file if it
198     # changes
199     if not os.path.exists('/configs/' + kube_config_name) or not \
200             filecmp.cmp('/tmp/'+tmp_file_name, '/configs/'+kube_config_name):
201         shutil.move(os.path.join('/tmp', tmp_file_name),
202                     os.path.join('/configs', kube_config_name))
203
204     return '/configs/'+kube_config_name
205
206
207 def subscriptions(uow: unit_of_work.AbstractUnitOfWork, **kwargs):
208     pagination = Pagination(**kwargs)
209     query_kwargs = pagination.get_pagination()
210     args = gen_filter(Subscription,
211                       kwargs['filter']) if 'filter' in kwargs else []
212     with uow:
213         li = uow.subscriptions.list_with_count(*args, **query_kwargs)
214     return pagination.get_result(li)
215
216
217 def subscription_one(subscriptionId: str,
218                      uow: unit_of_work.AbstractUnitOfWork):
219     with uow:
220         first = uow.subscriptions.get(subscriptionId)
221         return first.serialize() if first is not None else None
222
223
224 def subscription_create(subscriptionDto: SubscriptionDTO.subscription_create,
225                         uow: unit_of_work.AbstractUnitOfWork):
226     filter = subscriptionDto.get('filter', '')
227     consumer_subs_id = subscriptionDto.get('consumerSubscriptionId', '')
228
229     check_filter(ocloud.Resource, filter)
230
231     sub_uuid = str(uuid.uuid4())
232     subscription = Subscription(
233         sub_uuid, subscriptionDto['callback'],
234         consumer_subs_id, filter)
235     with uow:
236         uow.subscriptions.add(subscription)
237         uow.commit()
238         first = uow.subscriptions.get(sub_uuid)
239         return first.serialize()
240
241
242 def subscription_delete(subscriptionId: str,
243                         uow: unit_of_work.AbstractUnitOfWork):
244     with uow:
245         uow.subscriptions.delete(subscriptionId)
246         uow.commit()
247     return True