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