1 # Copyright 2016-2018 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.
19 from threading import Thread
21 from lcm.ns.const import OWNER_TYPE
22 from lcm.pub.config.config import REPORT_TO_AAI
23 from lcm.pub.database.models import NfInstModel, NSInstModel, VmInstModel, VNFFGInstModel, VLInstModel, OOFDataModel
24 from lcm.pub.exceptions import NSLCMException
25 from lcm.pub.msapi.aai import create_vnf_aai
26 from lcm.pub.msapi.extsys import get_vnfm_by_id
27 from lcm.pub.msapi.resmgr import create_vnf, create_vnf_creation_info
28 from lcm.pub.msapi.sdc_run_catalog import query_vnfpackage_by_id
29 from lcm.pub.msapi.vnfmdriver import send_nf_init_request
30 from lcm.pub.utils.jobutil import JOB_MODEL_STATUS, JobUtil, JOB_TYPE
31 from lcm.pub.utils.share_lock import do_biz_with_share_lock
32 from lcm.pub.utils.timeutil import now_time
33 from lcm.pub.utils.values import ignore_case_get
34 from lcm.pub.utils import restcall
35 from lcm.ns_vnfs.const import VNF_STATUS, NFVO_VNF_INST_TIMEOUT_SECOND, INST_TYPE, INST_TYPE_NAME
36 from lcm.ns_vnfs.biz.wait_job import wait_job_finish
37 from lcm.pub.config.config import REG_TO_MSB_REG_PARAM, OOF_BASE_URL, OOF_PASSWD, OOF_USER
38 from lcm.pub.config.config import CUST_NAME, CUST_LAT, CUST_LONG
39 from lcm.ns_vnfs.biz.subscribe import SubscriptionCreation
41 logger = logging.getLogger(__name__)
44 def prepare_create_params():
45 nf_inst_id = str(uuid.uuid4())
46 NfInstModel(nfinstid=nf_inst_id, status=VNF_STATUS.INSTANTIATING, create_time=now_time(),
47 lastuptime=now_time()).save()
48 job_id = JobUtil.create_job(INST_TYPE_NAME.VNF, JOB_TYPE.CREATE_VNF, nf_inst_id)
49 JobUtil.add_job_status(job_id, 0, 'create vnf record in database.', 0)
50 return nf_inst_id, job_id
53 class CreateVnfs(Thread):
54 def __init__(self, data, nf_inst_id, job_id):
55 super(CreateVnfs, self).__init__()
57 self.nf_inst_id = nf_inst_id
62 self.ns_inst_name = ''
65 self.vnf_inst_name = ''
66 self.vnfm_inst_id = ''
68 self.nf_package_info = ''
69 self.vnfm_nf_inst_id = ''
71 self.vnfm_inst_name = ''
77 self.check_nf_name_exist()
80 self.create_vnf_in_aai()
81 self.check_nf_package_valid()
82 self.send_nf_init_request_to_vnfm()
83 self.send_homing_request_to_OOF()
84 self.send_get_vnfm_request_to_extsys()
85 self.send_create_vnf_request_to_resmgr()
86 self.wait_vnfm_job_finish()
88 self.write_vnf_creation_info()
89 self.save_info_to_db()
90 JobUtil.add_job_status(self.job_id, 100, 'vnf instantiation success', 0)
91 except NSLCMException as e:
92 self.vnf_inst_failed_handle(e.message)
94 logger.error(traceback.format_exc())
95 self.vnf_inst_failed_handle('unexpected exception')
98 self.ns_inst_id = self.data['ns_instance_id']
99 vnf_index = int(float(self.data['vnf_index'])) - 1
100 additional_vnf_info = self.data['additional_param_for_vnf'][vnf_index]
101 self.vnf_id = ignore_case_get(additional_vnf_info, 'vnfProfileId')
102 additional_param = ignore_case_get(additional_vnf_info, 'additionalParam')
103 self.properties = ignore_case_get(additional_param, 'properties')
104 self.vnfm_inst_id = ignore_case_get(additional_param, 'vnfmInstanceId')
105 para = ignore_case_get(additional_param, 'inputs')
106 self.inputs = json.loads(para) if isinstance(para, (str, unicode)) else para
107 self.vim_id = ignore_case_get(additional_param, 'vimId')
108 self.vnfd_id = ignore_case_get(additional_param, 'vnfdId')
110 def check_nf_name_exist(self):
111 is_exist = NfInstModel.objects.filter(nf_name=self.vnf_inst_name).exists()
113 logger.error('The name of NF instance already exists.')
114 raise NSLCMException('The name of NF instance already exists.')
116 def get_vnfd_id(self):
118 logger.debug("need not get vnfd_id")
119 self.nsd_model = {'vnfs': [], 'vls': [], 'vnffgs': []}
120 self.vnf_inst_name = self.vnfd_id + str(uuid.uuid4())
121 self.vnf_inst_name = self.vnf_inst_name[:30]
123 ns_inst_info = NSInstModel.objects.get(id=self.ns_inst_id)
124 self.ns_inst_name = ns_inst_info.name
125 self.nsd_model = json.loads(ns_inst_info.nsd_model)
126 for vnf_info in self.nsd_model['vnfs']:
127 if self.vnf_id == vnf_info['vnf_id']:
128 self.vnfd_id = vnf_info['properties']['id']
129 if 'name' not in vnf_info['properties']:
130 # HW vnf instance name must start with alphabet
131 self.vnf_inst_name = 'vnf' + self.vnfd_id[:10] + str(uuid.uuid4())
133 self.vnf_inst_name = vnf_info['properties']['name'] + str(uuid.uuid4())
134 self.vnf_inst_name = self.vnf_inst_name[:30]
135 self.vnf_inst_name = self.vnf_inst_name.replace("-", "_")
137 logger.error('Can not found vnf in nsd model')
138 raise NSLCMException('Can not found vnf in nsd model')
140 def check_nf_package_valid(self):
141 nfpackage_info = query_vnfpackage_by_id(self.vnfd_id)
142 self.nf_package_info = nfpackage_info["packageInfo"]
143 self.vnfd_model = ignore_case_get(self.nf_package_info, "vnfdModel")
144 self.vnfd_model = json.loads(self.vnfd_model)
146 def get_virtual_link_info(self, vnf_id):
147 virtual_link_list, ext_virtual_link = [], []
148 for vnf_info in self.nsd_model['vnfs']:
149 if vnf_info['vnf_id'] != vnf_id:
151 for network_info in vnf_info['networks']:
152 vl_instance = VLInstModel.objects.get(
153 vldid=network_info['vl_id'],
154 ownertype=OWNER_TYPE.NS,
155 ownerid=self.ns_inst_id)
156 vl_instance_id = vl_instance.vlinstanceid
157 network_name, subnet_name = self.get_network_info_of_vl(network_info['vl_id'])
158 virtual_link_list.append({
159 'network_name': network_name,
160 'key_name': network_info['key_name'],
161 'subnetwork_name': subnet_name,
162 'vl_instance_id': vl_instance_id
164 ext_virtual_link.append({
165 "vlInstanceId": vl_instance_id,
166 "resourceId": vl_instance.relatednetworkid,
167 "resourceSubnetId": vl_instance.relatedsubnetworkid,
168 "cpdId": self.get_cpd_id_of_vl(network_info['key_name']),
170 "vimid": vl_instance.vimid
173 "id": vl_instance_id,
174 "vimConnectionId": vl_instance.vimid,
175 "extCps": self.get_cpds_of_vl(network_info['key_name'])
177 return virtual_link_list, ext_virtual_link
179 def get_cpds_of_vl(self, vl_key):
181 logger.debug("vl_keya; %s" % vl_key)
182 for cpd in self.vnfd_model["vnf_exposed"]["external_cps"]:
183 logger.debug("exposed_cpd; %s" % cpd)
184 if vl_key == cpd["key_name"]:
185 cp = {"cpdId": cpd["cpd_id"], "cpConfig": []}
189 def get_cpd_id_of_vl(self, vl_key):
190 for cpd in self.vnfd_model["vnf_exposed"]["external_cps"]:
191 if vl_key == cpd["key_name"]:
195 def get_network_info_of_vl(self, vl_id):
196 for vnf_info in self.nsd_model['vls']:
197 if vnf_info['vl_id'] == vl_id:
198 return vnf_info['properties']['vl_profile']['networkName'], vnf_info['properties']['vl_profile']['networkName'] # ['initiationParameters']['name']
201 def send_nf_init_request_to_vnfm(self):
202 virtual_link_list, ext_virtual_link = self.get_virtual_link_info(self.vnf_id)
203 req_param = json.JSONEncoder().encode({
204 'vnfInstanceName': self.vnf_inst_name,
205 'vnfPackageId': ignore_case_get(self.nf_package_info, "vnfPackageId"),
206 'vnfDescriptorId': self.vnfd_id,
207 'flavourId': "default",
208 'extVirtualLink': ext_virtual_link,
210 "properties": self.properties,
211 "inputs": self.inputs,
212 "vimId": self.vim_id,
213 "extVirtualLinks": virtual_link_list
216 rsp = send_nf_init_request(self.vnfm_inst_id, req_param)
217 self.vnfm_job_id = ignore_case_get(rsp, 'jobId')
218 self.vnfm_nf_inst_id = ignore_case_get(rsp, 'vnfInstanceId')
220 NfInstModel.objects.filter(nfinstid=self.nf_inst_id).update(
221 mnfinstid=self.vnfm_nf_inst_id,
222 nf_name=self.vnf_inst_name,
224 package_id=ignore_case_get(self.nf_package_info, "vnfPackageId"),
225 vnfm_inst_id=self.vnfm_inst_id,
226 ns_inst_id=self.ns_inst_id,
227 version=ignore_case_get(self.nf_package_info, "vnfdVersion"),
228 vendor=ignore_case_get(self.nf_package_info, "vnfdProvider"),
229 vnfd_model=self.vnfd_model,
230 input_params=json.JSONEncoder().encode(self.inputs),
231 lastuptime=now_time())
233 def build_homing_request(self):
234 id = str(uuid.uuid4())
235 callback_uri = "http://{vfcBaseUrl}/api/nslcm/v1/ns/placevnf"
236 IP = REG_TO_MSB_REG_PARAM["nodes"][0]["ip"]
237 PORT = REG_TO_MSB_REG_PARAM["nodes"][0]["port"]
238 vfcBaseUrl = IP + ':' + PORT
239 callback_uri = callback_uri.format(vfcBaseUrl=vfcBaseUrl)
240 modelInvariantId = "no-resourceModelInvariantId"
241 modelVersionId = "no-resourceModelVersionId"
242 nsInfo = NSInstModel.objects.filter(id=self.ns_inst_id)
244 "resourceModuleName": self.vnf_id,
245 "serviceResourceId": self.vnfm_nf_inst_id,
246 "resourceModelInfo": {
247 "modelInvariantId": modelInvariantId,
248 "modelVersionId": modelVersionId
255 "callbackUrl": callback_uri,
257 "requestType": "create",
259 "optimizers": ["placement"],
263 "requestParameters": {
264 "customerLatitude": CUST_LAT,
265 "customerLongitude": CUST_LONG,
266 "customerName": CUST_NAME
269 "globalSubscriberId": "",
270 "subscriberName": "",
271 "subscriberCommonSiteId": "",
273 "placementDemands": []
276 "serviceInstanceId": self.ns_inst_id,
277 "serviceName": self.ns_inst_name,
279 "modelInvariantId": nsInfo[0].nsd_invariant_id,
280 "modelVersionId": nsInfo[0].nsd_id
284 req_body["placementInfo"]["placementDemands"].append(placementDemand)
285 # Stored the init request info inside DB
286 OOFDataModel.objects.create(
289 request_status="init",
290 request_module_name=self.vnf_id,
291 service_resource_id=self.vnfm_nf_inst_id,
299 def send_homing_request_to_OOF(self):
300 req_body = self.build_homing_request()
301 base_url = OOF_BASE_URL
302 resources = "/api/oof/v1/placement"
303 resp = restcall.call_req(base_url=base_url, user=OOF_USER, passwd=OOF_PASSWD,
304 auth_type=restcall.rest_oneway_auth, resource=resources,
305 method="POST", content=json.dumps(req_body), additional_headers="")
307 resp_status = resp[-1]
309 logger.debug("Got OOF sync response")
311 logger.warn("Missing OOF sync response")
312 logger.debug(("OOF sync response code is %s") % resp_status)
313 if str(resp_status) != '202' or resp[0] != 0:
314 OOFDataModel.objects.filter(request_id=req_body["requestInfo"]["requestId"],
315 transaction_id=req_body["requestInfo"]["transactionId"]).update(
316 request_status="failed",
319 cloud_region_id="none",
322 raise Exception("Received a Bad Sync from OOF with response code %s" % resp_status)
323 logger.info("Completed Homing request to OOF")
325 def send_get_vnfm_request_to_extsys(self):
326 resp_body = get_vnfm_by_id(self.vnfm_inst_id)
327 self.vnfm_inst_name = ignore_case_get(resp_body, 'name')
329 def send_create_vnf_request_to_resmgr(self):
330 pkg_vnfd = self.vnfd_model
332 'nf_inst_id': self.nf_inst_id,
333 'vnfm_nf_inst_id': self.vnfm_nf_inst_id,
334 'vnf_inst_name': self.vnf_inst_name,
335 'ns_inst_id': self.ns_inst_id,
336 'ns_inst_name': self.ns_inst_name,
337 'nf_inst_name': self.vnf_inst_name,
338 'vnfm_inst_id': self.vnfm_inst_id,
339 'vnfm_inst_name': self.vnfm_inst_name,
340 'vnfd_name': pkg_vnfd['metadata'].get('name', 'undefined'),
341 'vnfd_id': self.vnfd_id,
342 'job_id': self.job_id,
343 'nf_inst_status': VNF_STATUS.INSTANTIATING,
344 'vnf_type': pkg_vnfd['metadata'].get('vnf_type', 'undefined'),
345 'nf_package_id': ignore_case_get(self.nf_package_info, "vnfPackageId")
349 def wait_vnfm_job_finish(self):
350 ret = wait_job_finish(vnfm_id=self.vnfm_inst_id,
351 vnfo_job_id=self.job_id,
352 vnfm_job_id=self.vnfm_job_id,
353 progress_range=[10, 90],
354 timeout=NFVO_VNF_INST_TIMEOUT_SECOND)
356 if ret != JOB_MODEL_STATUS.FINISHED:
357 logger.error('VNF instantiation failed on VNFM side. ret=[%s]', ret)
358 raise NSLCMException('VNF instantiation failed on VNFM side.')
362 'vnfInstanceId': self.vnfm_nf_inst_id,
363 'vnfmId': self.vnfm_inst_id
365 SubscriptionCreation(data).do_biz()
367 def write_vnf_creation_info(self):
368 logger.debug("write_vnf_creation_info start")
369 vm_inst_infos = VmInstModel.objects.filter(insttype=INST_TYPE.VNF, instid=self.nf_inst_id)
371 'nf_inst_id': self.nf_inst_id,
372 'ns_inst_id': self.ns_inst_id,
373 'vnfm_inst_id': self.vnfm_inst_id,
374 'vms': [{'vmId': vm_inst_info.resouceid, 'vmName': vm_inst_info.vmname, 'vmStatus': 'ACTIVE'} for
375 vm_inst_info in vm_inst_infos]}
376 create_vnf_creation_info(data)
377 logger.debug("write_vnf_creation_info end")
379 def save_info_to_db(self):
380 logger.debug("save_info_to_db start")
381 do_biz_with_share_lock("set-vnflist-in-vnffginst-%s" % self.ns_inst_id, self.save_vnf_inst_id_in_vnffg)
382 NfInstModel.objects.filter(nfinstid=self.nf_inst_id).update(status=VNF_STATUS.ACTIVE, lastuptime=now_time())
383 logger.debug("save_info_to_db end")
385 def vnf_inst_failed_handle(self, error_msg):
386 logger.error('VNF instantiation failed, detail message: %s' % error_msg)
387 NfInstModel.objects.filter(nfinstid=self.nf_inst_id).update(status=VNF_STATUS.FAILED,
388 lastuptime=now_time())
389 JobUtil.add_job_status(self.job_id, 255, 'VNF instantiation failed, detail message: %s' % error_msg, 0)
391 def save_vnf_inst_id_in_vnffg(self):
392 vnffgs = self.nsd_model['vnffgs']
394 if self.vnf_id not in vnffg['members']:
396 vnffg_inst_infos = VNFFGInstModel.objects.filter(vnffgdid=vnffg['vnffg_Id'], nsinstid=self.ns_inst_id)
397 if not vnffg_inst_infos:
398 logger.error('Vnffg instance not exist.')
399 raise NSLCMException('Vnffg instance not exist.')
400 vnf_list = vnffg_inst_infos[0].vnflist
401 vnffg_inst_infos.update(vnf_list=vnf_list + ',' + self.nf_inst_id if vnf_list else self.nf_inst_id)
403 def create_vnf_in_aai(self):
404 logger.debug("CreateVnfs::create_vnf_in_aai::report vnf instance[%s] to aai." % self.nf_inst_id)
406 ns_insts = NSInstModel.objects.filter(id=self.ns_inst_id)
407 self.global_customer_id = ns_insts[0].global_customer_id
408 self.service_type = ns_insts[0].service_type
410 "vnf-id": self.nf_inst_id,
411 "vnf-name": self.vnf_inst_name,
412 "vnf-type": "vnf-type-test111",
413 "service-id": self.ns_inst_id,
415 "is-closed-loop-disabled": False,
416 "relationship-list": {
419 "related-to": "service-instance",
420 "relationship-data": [
422 "relationship-key": "customer.global-customer-id",
423 "relationship-value": self.global_customer_id
426 "relationship-key": "service-subscription.service-type",
427 "relationship-value": self.service_type
430 "relationship-key": "service-instance.service-instance-id",
431 "relationship-value": self.ns_inst_id
438 resp_data, resp_status = create_vnf_aai(self.nf_inst_id, data)
439 logger.debug("Success to create vnf[%s] to aai, ns instance=[%s], resp_status: [%s]."
440 % (self.nf_inst_id, self.ns_inst_id, resp_status))
441 except NSLCMException as e:
442 logger.debug("Fail to create vnf[%s] to aai, ns instance=[%s], detail message: %s"
443 % (self.nf_inst_id, self.ns_inst_id, e.message))
445 logger.error(traceback.format_exc())