Refactor coeds for chg ext conn
[vfc/gvnfm/vnflcm.git] / lcm / lcm / nf / biz / change_ext_conn.py
1 # Copyright 2019 ZTE Corporation.
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 import json
15 import logging
16 import traceback
17 from threading import Thread
18
19 from lcm.nf.biz.common import port_save
20 from lcm.nf.biz.grant_vnf import grant_resource
21 from lcm.nf.const import RESOURCE_MAP, GRANT_TYPE, OPERATION_STATE_TYPE
22 from lcm.nf.const import VNF_STATUS, OPERATION_TASK, OPERATION_TYPE
23 from lcm.pub.database.models import VmInstModel, NfInstModel, PortInstModel
24 from lcm.pub.utils.notificationsutil import NotificationsUtil, prepare_notification
25 from lcm.pub.utils.values import ignore_case_get
26 from lcm.pub.utils.timeutil import now_time
27 from lcm.pub.utils.jobutil import JobUtil
28 from lcm.pub.exceptions import NFLCMException
29 from lcm.pub.vimapi import adaptor
30 from .operate_vnf_lcm_op_occ import VnfLcmOpOcc
31
32 logger = logging.getLogger(__name__)
33
34
35 class ChangeExtConn(Thread):
36     def __init__(self, data, nf_inst_id, job_id):
37         super(ChangeExtConn, self).__init__()
38         self.data = data
39         self.nf_inst_id = nf_inst_id
40         self.job_id = job_id
41         self.vnf_insts = NfInstModel.objects.filter(nfinstid=self.nf_inst_id)
42         self.extVirtualLinks = ignore_case_get(self.data, "extVirtualLinks")
43         self.vimConnectionInfo = ignore_case_get(self.data, "vimConnectionInfo")
44         self.additionalParams = ignore_case_get(self.data, "additionalParams")
45         self.lcm_op_occ = VnfLcmOpOcc(
46             vnf_inst_id=nf_inst_id,
47             lcm_op_id=job_id,
48             operation=OPERATION_TYPE.CHANGE_EXT_CONN,
49             task=OPERATION_TASK.CHANGE_EXT_CONN
50         )
51
52     def run(self):
53         try:
54             self.lcm_op_occ.notify_lcm(OPERATION_STATE_TYPE.STARTING)
55             JobUtil.add_job_status(
56                 self.job_id,
57                 10,
58                 "Start to apply grant."
59             )
60             self.apply_grant()
61             self.lcm_op_occ.notify_lcm(OPERATION_STATE_TYPE.PROCESSING)
62             JobUtil.add_job_status(
63                 self.job_id,
64                 50,
65                 "Start to change ext conn."
66             )
67             self.do_operation()
68             self.vnf_insts.update(
69                 status='INSTANTIATED',
70                 lastuptime=now_time()
71             )
72             self.send_notification()
73             JobUtil.add_job_status(
74                 self.job_id,
75                 100,
76                 "Change ext conn success."
77             )
78         except NFLCMException as e:
79             logger.error(e.message)
80             self.change_ext_conn_failed_handle(e.message)
81         except Exception as e:
82             logger.error(e.message)
83             logger.error(traceback.format_exc())
84             self.change_ext_conn_failed_handle(e.message)
85
86     def apply_grant(self):
87         vdus = VmInstModel.objects.filter(instid=self.nf_inst_id)
88         apply_result = grant_resource(
89             data=self.data,
90             nf_inst_id=self.nf_inst_id,
91             job_id=self.job_id,
92             grant_type=GRANT_TYPE.CHANGE_CONNECTIVITY,
93             vdus=vdus
94         )
95         logger.debug("Grant resource end, response: %s" % apply_result)
96
97     def do_operation(self):
98         logger.info('Operation resource begin')
99         logger.debug("self.vimConnectionInfo: %s" % self.vimConnectionInfo)
100         vnfd_info = json.loads(self.vnf_insts[0].vnfd_model)
101         vm_id = ignore_case_get(self.additionalParams, "vmid")
102         if not vm_id:
103             vms = VmInstModel.objects.filter(instid=self.nf_inst_id)
104             vm_id = vms[0].resourceid
105         vim_id = ignore_case_get(self.vimConnectionInfo[0], "vimid")
106         accessInfo = ignore_case_get(self.vimConnectionInfo[0], "accessInfo")
107         tenant = ignore_case_get(accessInfo, "tenant")
108
109         self.vim_cache, self.res_cache = {}, {}
110         for extVirtualLink in self.extVirtualLinks:
111             network_id = ignore_case_get(extVirtualLink, "resourceId")
112             ext_cps = ignore_case_get(extVirtualLink, "extCps")
113             for ext_cp in ext_cps:
114                 cpd_id = ignore_case_get(ext_cp, "cpdId")
115                 cp_config = ignore_case_get(ext_cp, "cpConfig")
116                 cp_protocol_data = ignore_case_get(cp_config[0], "cpProtocolData")
117                 ip_addresses = ignore_case_get(ignore_case_get(
118                     cp_protocol_data[0],
119                     "ipOverEthernet"
120                 ), "ipAddresses")
121                 # fixed_addresse = ignore_case_get(ip_addresses[0], "fixedAddresses")[0]
122                 # addressRange = ignore_case_get(ip_addresses[0], "addressRange")
123                 # minAddress = ignore_case_get(addressRange, "minAddress")
124                 # maxAddress = ignore_case_get(addressRange, "maxAddress")
125                 subnet_id = ignore_case_get(ip_addresses[0], "subnetId")
126
127                 vdu_id = ""
128                 cps = ignore_case_get(vnfd_info, "cps")
129                 for cp in cps:
130                     cpd_id_in_model = ignore_case_get(cp, "cpd_id")
131                     if cpd_id == cpd_id_in_model:
132                         vdu_id = ignore_case_get(cp, "vdu_id")
133                         break
134
135                 port = {
136                     "cp_id": cpd_id,
137                     "cpd_id": cpd_id,
138                     "vm_id": vm_id,
139                     "description": "",
140                     "properties": {
141                         # "name": "",
142                         # "mac_address": mac_address,
143                         # "ip_address:": fixed_addresse,
144                         # "ip_range_start": minAddress,
145                         # "ip_range_end": maxAddress,
146                         "location_info": {
147                             "vimid": vim_id,
148                             "tenant": tenant
149                         }
150                     },
151                     "vl_id": network_id,
152                     "vdu_id": vdu_id,
153                     "networkId": network_id,
154                     "subnetId": subnet_id
155                 }
156                 for resource_type in ['vdus', 'vls', 'cps', 'volume_storages']:
157                     for resource in ignore_case_get(vnfd_info, resource_type):
158                         if "location_info" not in resource["properties"]:
159                             resource["properties"]["location_info"] = {}
160                         resource["properties"]["location_info"]["vimid"] = vim_id
161                         resource["properties"]["location_info"]["tenant"] = tenant
162
163                 # if cp_instance_id:
164                 #     ret = adaptor.get_port_of_vm(self.vim_cache, self.res_cache, vnfd_info, port,
165                 #                                  self.do_notify_op, "port")
166                 #     port_info = ignore_case_get(ret, "interfaceAttachment")
167                 #     net_id = ignore_case_get(port_info, "net_id")
168                 #     if network_id == net_id:
169                 #         adaptor.update_port(self.vim_cache, self.res_cache, vnfd_info, port,
170                 #                             self.do_notify_op, "port")
171                 #     else:
172                 #         adaptor.delete_port_of_vm(self.vim_cache, self.res_cache, vnfd_info, port,
173                 #                                   self.do_notify_op, "port")
174                 #         adaptor.create_port_of_vm(self.vim_cache, self.res_cache, vnfd_info, port,
175                 #                                   self.do_notify_op, "port")
176                 # else:
177                 adaptor.create_port(
178                     self.vim_cache,
179                     self.res_cache,
180                     vnfd_info, port,
181                     self.do_create_port_notify,
182                     "port"
183                 )
184                 port["port_id"] = self.port_id
185                 logger.debug('create_port_of_vm request data = %s' % port)
186                 adaptor.create_port_of_vm(
187                     self.vim_cache,
188                     self.res_cache,
189                     vnfd_info,
190                     port,
191                     self.do_notify_op,
192                     "port"
193                 )
194                 PortInstModel.objects.filter(resourceid=self.port_id).update(vmid=vm_id)
195         logger.info('Operate resource complete')
196
197     def send_notification(self):
198         data = prepare_notification(
199             nfinstid=self.nf_inst_id,
200             jobid=self.job_id,
201             operation=OPERATION_TYPE.CHANGE_EXT_CONN,
202             operation_state=OPERATION_STATE_TYPE.COMPLETED
203         )
204         self.set_ext_connectivity(data['changedExtConnectivity'])
205
206         logger.debug('Notify request data = %s' % data)
207         NotificationsUtil().send_notification(data)
208
209     def rollback_operation(self):
210         pass
211
212     def query_inst_resource(self, inst_resource):
213         logger.debug('Query resource begin')
214         for resource_type in RESOURCE_MAP.keys():
215             resource_table = globals().get(resource_type + 'InstModel')
216             resource_insts = resource_table.objects.filter(
217                 instid=self.nf_inst_id
218             )
219             for resource_inst in resource_insts:
220                 if not resource_inst.resourceid:
221                     continue
222                 inst_resource[RESOURCE_MAP.get(resource_type)].append(
223                     self.get_resource(resource_inst)
224                 )
225         logger.debug('Query resource end, resource=%s' % inst_resource)
226
227     def get_resource(self, resource):
228         return {
229             "vim_id": resource.vimid,
230             "tenant_id": resource.tenant,
231             "res_id": resource.resourceid
232         }
233
234     def do_create_port_notify(self, res_type, ret):
235         self.port_id = ignore_case_get(ret, "id")
236         port_save("", self.nf_inst_id, ret)
237
238     def do_notify_op(self, operation_type, status, resid):
239         if operation_type == "delete":
240             PortInstModel.objects.filter()
241             # TODO delete port from table
242         elif operation_type == "create":
243             pass
244             # TODO save port in table
245         else:
246             pass
247             # TODO update port in table
248         logger.info('VNF resource %s updated to: %s' % (resid, status))
249
250     def set_ext_connectivity(self, ext_connectivity):
251         for extVirtualLink in self.extVirtualLinks:
252             vim_connection_id = ignore_case_get(extVirtualLink, "vimConnectionId")
253             network_id = ignore_case_get(extVirtualLink, "resourceId")
254             ext_cps = ignore_case_get(extVirtualLink, "extCps")
255             ext_link_ports = []
256             for ext_cp in ext_cps:
257                 cpd_id = ignore_case_get(ext_cp, "cpdId")
258                 cp_config = ignore_case_get(ext_cp, "cpConfig")
259                 cp_instance_id = ignore_case_get(cp_config[0], "cpInstanceId")
260                 ext_link_ports.append({
261                     'id': cp_instance_id,
262                     'resourceHandle': {
263                         'vimConnectionId': vim_connection_id,
264                         'resourceId': self.res_cache.get("port").get(cp_instance_id),
265                         'resourceProviderId': cpd_id,
266                         'vimLevelResourceType': 'port'
267                     },
268                     'cpInstanceId': cp_instance_id
269                 })
270             network_resource = {
271                 'vimConnectionId': vim_connection_id,
272                 'resourceId': network_id,
273                 'resourceProviderId': "",
274                 'vimLevelResourceType': 'network'
275             }
276             ext_connectivity.append({
277                 'id': network_id,
278                 'resourceHandle': network_resource,
279                 'extLinkPorts': ext_link_ports
280             })
281
282     def change_ext_conn_failed_handle(self, error_msg):
283         logger.error('Chnage ext conn failed, detail message: %s', error_msg)
284         self.vnf_insts.update(
285             status=VNF_STATUS.FAILED,
286             lastuptime=now_time()
287         )
288         self.lcm_op_occ.notify_lcm(OPERATION_STATE_TYPE.FAILED, error_msg)
289         JobUtil.add_job_status(self.job_id, 255, error_msg)