ed55ddac4bb03c1593ee1eca9e72cf38bd5aabf4
[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 o2ims.domain import ocloud
26 from o2ims.views.ocloud_dto import SubscriptionDTO
27 from o2ims.domain.subscription_obj import Subscription
28
29 from o2common.helper import o2logging
30 logger = o2logging.get_logger(__name__)
31
32
33 def oclouds(uow: unit_of_work.AbstractUnitOfWork):
34     with uow:
35         li = uow.oclouds.list()
36     return [r.serialize() for r in li]
37
38
39 def ocloud_one(ocloudid: str, uow: unit_of_work.AbstractUnitOfWork):
40     with uow:
41         first = uow.oclouds.get(ocloudid)
42         return first.serialize() if first is not None else None
43
44
45 def resource_types(uow: unit_of_work.AbstractUnitOfWork, **kwargs):
46     pagination = Pagination(**kwargs)
47     filter_kwargs = pagination.get_filter()
48     with uow:
49         li = uow.resource_types.list_with_count(**filter_kwargs)
50     return pagination.get_result(li)
51
52
53 def resource_type_one(resourceTypeId: str,
54                       uow: unit_of_work.AbstractUnitOfWork):
55     with uow:
56         first = uow.resource_types.get(resourceTypeId)
57         return first.serialize() if first is not None else None
58
59
60 def resource_pools(uow: unit_of_work.AbstractUnitOfWork, **kwargs):
61     pagination = Pagination(**kwargs)
62     filter_kwargs = pagination.get_filter()
63     with uow:
64         li = uow.resource_pools.list_with_count(**filter_kwargs)
65     return pagination.get_result(li)
66
67
68 def resource_pool_one(resourcePoolId: str,
69                       uow: unit_of_work.AbstractUnitOfWork):
70     with uow:
71         first = uow.resource_pools.get(resourcePoolId)
72         return first.serialize() if first is not None else None
73
74
75 def resources(resourcePoolId: str, uow: unit_of_work.AbstractUnitOfWork,
76               **kwargs):
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']
82         with uow:
83             # res_types = uow.resource_types.list()
84             # restype_ids = [
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
91
92     if 'parentId' in kwargs:
93         filter_kwargs['parentId'] = kwargs['parentId']
94     if 'sort' in kwargs:
95         filter_kwargs['sort'] = kwargs['sort']
96
97     with uow:
98         ret = uow.resources.list_with_count(resourcePoolId, **filter_kwargs)
99
100     return pagination.get_result(ret)
101
102
103 def resource_one(resourceId: str, uow: unit_of_work.AbstractUnitOfWork):
104     with uow:
105         first = uow.resources.get(resourceId)
106         return first.serialize() if first is not None else None
107
108
109 def deployment_managers(uow: unit_of_work.AbstractUnitOfWork, **kwargs):
110     pagination = Pagination(**kwargs)
111     filter_kwargs = pagination.get_filter()
112     with uow:
113         li = uow.deployment_managers.list_with_count(**filter_kwargs)
114     return pagination.get_result(li)
115
116
117 def deployment_manager_one(deploymentManagerId: str,
118                            uow: unit_of_work.AbstractUnitOfWork,
119                            profile: str = 'default'):
120     profile = profile.lower()
121     with uow:
122         first = uow.deployment_managers.get(deploymentManagerId)
123         if first is None:
124             return first
125         result = first.serialize()
126         if result is None:
127             return None
128
129     profile_data = result.pop("profile", None)
130     result['profileName'] = profile
131
132     if ocloud.DeploymentManagerProfileDefault == profile:
133         pass
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']
141
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
149     else:
150         return None
151
152     return result
153
154
155 def _gen_kube_config(dmId: str, kubeconfig: dict) -> dict:
156
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),
163     )
164
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))
168     name_key = dmId[:8]
169
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'
174
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)
178
179     # generate the kube config file if not exist or update the file if it
180     # changes
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))
185
186     return '/configs/'+kube_config_name
187
188
189 def subscriptions(uow: unit_of_work.AbstractUnitOfWork, **kwargs):
190     pagination = Pagination(**kwargs)
191     filter_kwargs = pagination.get_filter()
192     with uow:
193         li = uow.subscriptions.list_with_count(**filter_kwargs)
194     return pagination.get_result(li)
195
196
197 def subscription_one(subscriptionId: str,
198                      uow: unit_of_work.AbstractUnitOfWork):
199     with uow:
200         first = uow.subscriptions.get(subscriptionId)
201         return first.serialize() if first is not None else None
202
203
204 def subscription_create(subscriptionDto: SubscriptionDTO.subscription,
205                         uow: unit_of_work.AbstractUnitOfWork):
206
207     sub_uuid = str(uuid.uuid4())
208     subscription = Subscription(
209         sub_uuid, subscriptionDto['callback'],
210         subscriptionDto['consumerSubscriptionId'],
211         subscriptionDto['filter'])
212     with uow:
213         uow.subscriptions.add(subscription)
214         uow.commit()
215     return {"subscriptionId": sub_uuid}
216
217
218 def subscription_delete(subscriptionId: str,
219                         uow: unit_of_work.AbstractUnitOfWork):
220     with uow:
221         uow.subscriptions.delete(subscriptionId)
222         uow.commit()
223     return True