1 # Copyright 2019 ZTE Corporation.
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
7 # http://www.apache.org/licenses/LICENSE-2.0
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.
17 from threading import Thread
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
32 logger = logging.getLogger(__name__)
35 class ChangeExtConn(Thread):
36 def __init__(self, data, nf_inst_id, job_id):
37 super(ChangeExtConn, self).__init__()
39 self.nf_inst_id = nf_inst_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,
48 operation=OPERATION_TYPE.CHANGE_EXT_CONN,
49 task=OPERATION_TASK.CHANGE_EXT_CONN
54 self.lcm_op_occ.notify_lcm(OPERATION_STATE_TYPE.STARTING)
55 JobUtil.add_job_status(self.job_id,
57 "Start to apply grant.")
59 self.lcm_op_occ.notify_lcm(OPERATION_STATE_TYPE.PROCESSING)
60 JobUtil.add_job_status(self.job_id,
62 "Start to change ext conn.")
64 self.vnf_insts.update(
65 status='INSTANTIATED',
68 self.send_notification()
69 JobUtil.add_job_status(self.job_id,
71 "Change ext conn success.")
72 except NFLCMException as e:
73 logger.error(e.message)
74 self.change_ext_conn_failed_handle(e.message)
75 except Exception as e:
76 logger.error(e.message)
77 logger.error(traceback.format_exc())
78 self.change_ext_conn_failed_handle(e.message)
80 def apply_grant(self):
81 vdus = VmInstModel.objects.filter(instid=self.nf_inst_id)
82 apply_result = grant_resource(data=self.data,
83 nf_inst_id=self.nf_inst_id,
85 grant_type=GRANT_TYPE.CHANGE_CONNECTIVITY,
87 logger.debug("Grant resource end, response: %s" % apply_result)
89 def do_operation(self):
90 logger.info('Operation resource begin')
91 logger.debug("self.vimConnectionInfo: %s" % self.vimConnectionInfo)
92 vnfd_info = json.loads(self.vnf_insts[0].vnfd_model)
93 vm_id = ignore_case_get(self.additionalParams, "vmid")
95 vms = VmInstModel.objects.filter(instid=self.nf_inst_id)
96 vm_id = vms[0].resourceid
97 vim_id = ignore_case_get(self.vimConnectionInfo[0], "vimid")
98 accessInfo = ignore_case_get(self.vimConnectionInfo[0], "accessInfo")
99 tenant = ignore_case_get(accessInfo, "tenant")
101 self.vim_cache, self.res_cache = {}, {}
102 for extVirtualLink in self.extVirtualLinks:
103 network_id = ignore_case_get(extVirtualLink, "resourceId")
104 ext_cps = ignore_case_get(extVirtualLink, "extCps")
105 for ext_cp in ext_cps:
106 cpd_id = ignore_case_get(ext_cp, "cpdId")
107 cp_config = ignore_case_get(ext_cp, "cpConfig")
108 # cp_instance_id = ignore_case_get(cp_config[0], "cpInstanceId")
109 cp_protocol_data = ignore_case_get(cp_config[0], "cpProtocolData")
110 # mac_address = ignore_case_get(ignore_case_get(cp_protocol_data[0], "ipOverEthernet"), "macAddress")
111 ip_addresses = ignore_case_get(ignore_case_get(cp_protocol_data[0], "ipOverEthernet"), "ipAddresses")
112 # fixed_addresse = ignore_case_get(ip_addresses[0], "fixedAddresses")[0]
113 # addressRange = ignore_case_get(ip_addresses[0], "addressRange")
114 # minAddress = ignore_case_get(addressRange, "minAddress")
115 # maxAddress = ignore_case_get(addressRange, "maxAddress")
116 subnet_id = ignore_case_get(ip_addresses[0], "subnetId")
119 cps = ignore_case_get(vnfd_info, "cps")
121 cpd_id_in_model = ignore_case_get(cp, "cpd_id")
122 if cpd_id == cpd_id_in_model:
123 vdu_id = ignore_case_get(cp, "vdu_id")
133 # "mac_address": mac_address,
134 # "ip_address:": fixed_addresse,
135 # "ip_range_start": minAddress,
136 # "ip_range_end": maxAddress,
144 "networkId": network_id,
145 "subnetId": subnet_id
147 for resource_type in ['vdus', 'vls', 'cps', 'volume_storages']:
148 for resource in ignore_case_get(vnfd_info, resource_type):
149 if "location_info" not in resource["properties"]:
150 resource["properties"]["location_info"] = {}
151 resource["properties"]["location_info"]["vimid"] = vim_id
152 resource["properties"]["location_info"]["tenant"] = tenant
155 # ret = adaptor.get_port_of_vm(self.vim_cache, self.res_cache, vnfd_info, port,
156 # self.do_notify_op, "port")
157 # port_info = ignore_case_get(ret, "interfaceAttachment")
158 # net_id = ignore_case_get(port_info, "net_id")
159 # if network_id == net_id:
160 # adaptor.update_port(self.vim_cache, self.res_cache, vnfd_info, port,
161 # self.do_notify_op, "port")
163 # adaptor.delete_port_of_vm(self.vim_cache, self.res_cache, vnfd_info, port,
164 # self.do_notify_op, "port")
165 # adaptor.create_port_of_vm(self.vim_cache, self.res_cache, vnfd_info, port,
166 # self.do_notify_op, "port")
168 adaptor.create_port(self.vim_cache, self.res_cache, vnfd_info, port, self.do_create_port_notify, "port")
169 port["port_id"] = self.port_id
170 logger.debug('create_port_of_vm request data = %s' % port)
171 adaptor.create_port_of_vm(self.vim_cache, self.res_cache, vnfd_info, port,
172 self.do_notify_op, "port")
173 PortInstModel.objects.filter(resourceid=self.port_id).update(vmid=vm_id)
174 logger.info('Operate resource complete')
176 def send_notification(self):
177 data = prepare_notification(nfinstid=self.nf_inst_id,
179 operation=OPERATION_TYPE.CHANGE_EXT_CONN,
180 operation_state=OPERATION_STATE_TYPE.COMPLETED)
181 self.set_ext_connectivity(data['changedExtConnectivity'])
183 logger.debug('Notify request data = %s' % data)
184 NotificationsUtil().send_notification(data)
186 def rollback_operation(self):
189 def query_inst_resource(self, inst_resource):
190 logger.debug('Query resource begin')
191 for resource_type in RESOURCE_MAP.keys():
192 resource_table = globals().get(resource_type + 'InstModel')
193 resource_insts = resource_table.objects.filter(instid=self.nf_inst_id)
194 for resource_inst in resource_insts:
195 if not resource_inst.resourceid:
197 inst_resource[RESOURCE_MAP.get(resource_type)].append(self.get_resource(resource_inst))
198 logger.debug('Query resource end, resource=%s' % inst_resource)
200 def get_resource(self, resource):
202 "vim_id": resource.vimid,
203 "tenant_id": resource.tenant,
204 "res_id": resource.resourceid
207 def do_create_port_notify(self, res_type, ret):
208 self.port_id = ignore_case_get(ret, "id")
209 port_save("", self.nf_inst_id, ret)
211 def do_notify_op(self, operation_type, status, resid):
212 if operation_type == "delete":
213 PortInstModel.objects.filter()
214 # TODO delete port from table
215 elif operation_type == "create":
217 # TODO save port in table
220 # TODO update port in table
221 logger.info('VNF resource %s updated to: %s' % (resid, status))
223 def set_ext_connectivity(self, ext_connectivity):
224 for extVirtualLink in self.extVirtualLinks:
225 vim_connection_id = ignore_case_get(extVirtualLink, "vimConnectionId")
226 network_id = ignore_case_get(extVirtualLink, "resourceId")
227 ext_cps = ignore_case_get(extVirtualLink, "extCps")
229 for ext_cp in ext_cps:
230 cpd_id = ignore_case_get(ext_cp, "cpdId")
231 cp_config = ignore_case_get(ext_cp, "cpConfig")
232 cp_instance_id = ignore_case_get(cp_config[0], "cpInstanceId")
233 ext_link_ports.append({
234 'id': cp_instance_id,
236 'vimConnectionId': vim_connection_id,
237 'resourceId': self.res_cache.get("port").get(cp_instance_id),
238 'resourceProviderId': cpd_id,
239 'vimLevelResourceType': 'port'
241 'cpInstanceId': cp_instance_id
244 'vimConnectionId': vim_connection_id,
245 'resourceId': network_id,
246 'resourceProviderId': "",
247 'vimLevelResourceType': 'network'
249 ext_connectivity.append({
251 'resourceHandle': network_resource,
252 'extLinkPorts': ext_link_ports
255 def change_ext_conn_failed_handle(self, error_msg):
256 logger.error('Chnage ext conn failed, detail message: %s', error_msg)
257 self.vnf_insts.update(status=VNF_STATUS.FAILED,
258 lastuptime=now_time())
259 self.lcm_op_occ.notify_lcm(OPERATION_STATE_TYPE.FAILED, error_msg)
260 JobUtil.add_job_status(self.job_id, 255, error_msg)