56f970d23ce9d5430f11f97942d00a6193c1a78c
[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 o2ims.domain import ocloud
24 from o2ims.views.ocloud_dto import SubscriptionDTO
25 from o2ims.domain.subscription_obj import Subscription
26
27 from o2common.helper import o2logging
28 from o2common.config import config
29 logger = o2logging.get_logger(__name__)
30
31
32 def oclouds(uow: unit_of_work.AbstractUnitOfWork):
33     with uow:
34         li = uow.oclouds.list()
35     return [r.serialize() for r in li]
36
37
38 def ocloud_one(ocloudid: str, uow: unit_of_work.AbstractUnitOfWork):
39     with uow:
40         first = uow.oclouds.get(ocloudid)
41         return first.serialize() if first is not None else None
42
43
44 def resource_types(uow: unit_of_work.AbstractUnitOfWork):
45     with uow:
46         li = uow.resource_types.list()
47     return [r.serialize() for r in li]
48
49
50 def resource_type_one(resourceTypeId: str,
51                       uow: unit_of_work.AbstractUnitOfWork):
52     with uow:
53         first = uow.resource_types.get(resourceTypeId)
54         return first.serialize() if first is not None else None
55
56
57 def resource_pools(uow: unit_of_work.AbstractUnitOfWork):
58     with uow:
59         li = uow.resource_pools.list()
60     return [r.serialize() for r in li]
61
62
63 def resource_pool_one(resourcePoolId: str,
64                       uow: unit_of_work.AbstractUnitOfWork):
65     with uow:
66         first = uow.resource_pools.get(resourcePoolId)
67         return first.serialize() if first is not None else None
68
69
70 def resources(resourcePoolId: str, uow: unit_of_work.AbstractUnitOfWork,
71               **kwargs):
72
73     filter_kwargs = {}  # filter key should be the same with database name
74     if 'resourceTypeName' in kwargs:
75         resource_type_name = kwargs['resourceTypeName']
76         with uow:
77             # res_types = uow.resource_types.list()
78             # restype_ids = [
79             #     restype.resourceTypeId for restype in res_types
80             #     if resourceTypeName == restype.name]
81             # restype_id = '' if len(restype_ids) == 0 else restype_ids[0]
82             res_type = uow.resource_types.get_by_name(resource_type_name)
83             restype_id = '' if res_type is None else res_type.resourceTypeId
84         filter_kwargs['resourceTypeId'] = restype_id
85
86         #     li = uow.resources.list(resourcePoolId)
87         # return [r.serialize() for r in li if r.resourceTypeId == restype_id]
88     if 'parentId' in kwargs:
89         filter_kwargs['parentId'] = kwargs['parentId']
90
91     with uow:
92         li = uow.resources.list(resourcePoolId, **filter_kwargs)
93     return [r.serialize() for r in li]
94
95
96 def resource_one(resourceId: str, uow: unit_of_work.AbstractUnitOfWork):
97     with uow:
98         first = uow.resources.get(resourceId)
99         return first.serialize() if first is not None else None
100
101
102 def deployment_managers(uow: unit_of_work.AbstractUnitOfWork):
103     with uow:
104         li = uow.deployment_managers.list()
105     return [r.serialize() for r in li]
106
107
108 def deployment_manager_one(deploymentManagerId: str,
109                            uow: unit_of_work.AbstractUnitOfWork,
110                            profile: str = 'default'):
111     profile = profile.lower()
112     with uow:
113         first = uow.deployment_managers.get(deploymentManagerId)
114         if first is None:
115             return first
116         result = first.serialize()
117         if result is None:
118             return None
119
120     profile_data = result.pop("profile", None)
121     result['profileName'] = profile
122
123     if ocloud.DeploymentManagerProfileDefault == profile:
124         pass
125     elif ocloud.DeploymentManagerProfileSOL018 == profile:
126         result['deploymentManagementServiceEndpoint'] = \
127             profile_data['cluster_api_endpoint']
128         result['profileData'] = profile_data
129     elif ocloud.DeploymentManagerProfileSOL018HelmCLI == profile:
130         result['deploymentManagementServiceEndpoint'] = \
131             profile_data['cluster_api_endpoint']
132
133         helmcli_profile = dict()
134         helmcli_profile["helmcli_host_with_port"], helmcli_profile[
135             "helmcli_username"], helmcli_profile["helmcli_password"] = \
136             config.get_helmcli_access()
137         helmcli_profile["helmcli_kubeconfig"] = _gen_kube_config(
138             deploymentManagerId, profile_data)
139         result['profileData'] = helmcli_profile
140     else:
141         return None
142
143     return result
144
145
146 def _gen_kube_config(dmId: str, kubeconfig: dict) -> dict:
147
148     data = config.gen_k8s_config_dict(
149         kubeconfig.pop('cluster_api_endpoint', None),
150         kubeconfig.pop('cluster_ca_cert', None),
151         kubeconfig.pop('admin_user', None),
152         kubeconfig.pop('admin_client_cert', None),
153         kubeconfig.pop('admin_client_key', None),
154     )
155
156     # Generate a random key for tmp kube config file
157     # letters = string.ascii_uppercase
158     # random_key = ''.join(random.choice(letters) for i in range(10))
159     name_key = dmId[:8]
160
161     # Get datetime of now as tag of the tmp file
162     current_time = datetime.now().strftime("%Y%m%d%H%M%S")
163     tmp_file_name = 'kubeconfig_' + name_key + "_" + current_time
164     kube_config_name = 'kubeconfig_' + name_key + '.config'
165
166     # write down the yaml file of kubectl into tmp folder
167     with open('/tmp/' + tmp_file_name, 'w') as file:
168         yaml.dump(data, file)
169
170     # generate the kube config file if not exist or update the file if it
171     # changes
172     if not os.path.exists('/configs/' + kube_config_name) or not \
173             filecmp.cmp('/tmp/'+tmp_file_name, '/configs/'+kube_config_name):
174         shutil.move(os.path.join('/tmp', tmp_file_name),
175                     os.path.join('/configs', kube_config_name))
176
177     return '/configs/'+kube_config_name
178
179
180 def subscriptions(uow: unit_of_work.AbstractUnitOfWork):
181     with uow:
182         li = uow.subscriptions.list()
183     return [r.serialize() for r in li]
184
185
186 def subscription_one(subscriptionId: str,
187                      uow: unit_of_work.AbstractUnitOfWork):
188     with uow:
189         first = uow.subscriptions.get(subscriptionId)
190         return first.serialize() if first is not None else None
191
192
193 def subscription_create(subscriptionDto: SubscriptionDTO.subscription,
194                         uow: unit_of_work.AbstractUnitOfWork):
195
196     sub_uuid = str(uuid.uuid4())
197     subscription = Subscription(
198         sub_uuid, subscriptionDto['callback'],
199         subscriptionDto['consumerSubscriptionId'],
200         subscriptionDto['filter'])
201     with uow:
202         uow.subscriptions.add(subscription)
203         uow.commit()
204     return {"subscriptionId": sub_uuid}
205
206
207 def subscription_delete(subscriptionId: str,
208                         uow: unit_of_work.AbstractUnitOfWork):
209     with uow:
210         uow.subscriptions.delete(subscriptionId)
211         uow.commit()
212     return True