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
253 vim_info = self.vim_id.split("_")
255 identifiers.append(vim_info[1])
256 cloudOwner = vim_info[0]
257 required_candidate = [
259 "identifierType": "vimId",
260 "cloudOwner": cloudOwner,
261 "identifiers": identifiers
264 placementDemand["requiredCandidates"] = required_candidate
270 "callbackUrl": callback_uri,
272 "requestType": "create",
274 "optimizers": ["placement"],
278 "requestParameters": {
279 "customerLatitude": CUST_LAT,
280 "customerLongitude": CUST_LONG,
281 "customerName": CUST_NAME
284 "globalSubscriberId": "",
285 "subscriberName": "",
286 "subscriberCommonSiteId": "",
288 "placementDemands": []
291 "serviceInstanceId": self.ns_inst_id,
292 "serviceName": self.ns_inst_name,
294 "modelInvariantId": nsInfo[0].nsd_invariant_id,
295 "modelVersionId": nsInfo[0].nsd_id
299 req_body["placementInfo"]["placementDemands"].append(placementDemand)
300 # Stored the init request info inside DB
301 OOFDataModel.objects.create(
304 request_status="init",
305 request_module_name=self.vnf_id,
306 service_resource_id=self.vnfm_nf_inst_id,
314 def send_homing_request_to_OOF(self):
315 req_body = self.build_homing_request()
316 base_url = OOF_BASE_URL
317 resources = "/api/oof/v1/placement"
318 resp = restcall.call_req(base_url=base_url, user=OOF_USER, passwd=OOF_PASSWD,
319 auth_type=restcall.rest_oneway_auth, resource=resources,
320 method="POST", content=json.dumps(req_body), additional_headers="")
322 resp_status = resp[-1]
324 logger.debug("Got OOF sync response")
326 logger.warn("Missing OOF sync response")
327 logger.debug(("OOF sync response code is %s") % resp_status)
328 if str(resp_status) != '202' or resp[0] != 0:
329 OOFDataModel.objects.filter(request_id=req_body["requestInfo"]["requestId"],
330 transaction_id=req_body["requestInfo"]["transactionId"]).update(
331 request_status="failed",
334 cloud_region_id="none",
337 raise Exception("Received a Bad Sync from OOF with response code %s" % resp_status)
338 logger.info("Completed Homing request to OOF")
340 def send_get_vnfm_request_to_extsys(self):
341 resp_body = get_vnfm_by_id(self.vnfm_inst_id)
342 self.vnfm_inst_name = ignore_case_get(resp_body, 'name')
344 def send_create_vnf_request_to_resmgr(self):
345 pkg_vnfd = self.vnfd_model
347 'nf_inst_id': self.nf_inst_id,
348 'vnfm_nf_inst_id': self.vnfm_nf_inst_id,
349 'vnf_inst_name': self.vnf_inst_name,
350 'ns_inst_id': self.ns_inst_id,
351 'ns_inst_name': self.ns_inst_name,
352 'nf_inst_name': self.vnf_inst_name,
353 'vnfm_inst_id': self.vnfm_inst_id,
354 'vnfm_inst_name': self.vnfm_inst_name,
355 'vnfd_name': pkg_vnfd['metadata'].get('name', 'undefined'),
356 'vnfd_id': self.vnfd_id,
357 'job_id': self.job_id,
358 'nf_inst_status': VNF_STATUS.INSTANTIATING,
359 'vnf_type': pkg_vnfd['metadata'].get('vnf_type', 'undefined'),
360 'nf_package_id': ignore_case_get(self.nf_package_info, "vnfPackageId")
364 def wait_vnfm_job_finish(self):
365 ret = wait_job_finish(vnfm_id=self.vnfm_inst_id,
366 vnfo_job_id=self.job_id,
367 vnfm_job_id=self.vnfm_job_id,
368 progress_range=[10, 90],
369 timeout=NFVO_VNF_INST_TIMEOUT_SECOND)
371 if ret != JOB_MODEL_STATUS.FINISHED:
372 logger.error('VNF instantiation failed on VNFM side. ret=[%s]', ret)
373 raise NSLCMException('VNF instantiation failed on VNFM side.')
377 'vnfInstanceId': self.vnfm_nf_inst_id,
378 'vnfmId': self.vnfm_inst_id
380 SubscriptionCreation(data).do_biz()
382 def write_vnf_creation_info(self):
383 logger.debug("write_vnf_creation_info start")
384 vm_inst_infos = VmInstModel.objects.filter(insttype=INST_TYPE.VNF, instid=self.nf_inst_id)
386 'nf_inst_id': self.nf_inst_id,
387 'ns_inst_id': self.ns_inst_id,
388 'vnfm_inst_id': self.vnfm_inst_id,
389 'vms': [{'vmId': vm_inst_info.resouceid, 'vmName': vm_inst_info.vmname, 'vmStatus': 'ACTIVE'} for
390 vm_inst_info in vm_inst_infos]}
391 create_vnf_creation_info(data)
392 logger.debug("write_vnf_creation_info end")
394 def save_info_to_db(self):
395 logger.debug("save_info_to_db start")
396 do_biz_with_share_lock("set-vnflist-in-vnffginst-%s" % self.ns_inst_id, self.save_vnf_inst_id_in_vnffg)
397 NfInstModel.objects.filter(nfinstid=self.nf_inst_id).update(status=VNF_STATUS.ACTIVE, lastuptime=now_time())
398 logger.debug("save_info_to_db end")
400 def vnf_inst_failed_handle(self, error_msg):
401 logger.error('VNF instantiation failed, detail message: %s' % error_msg)
402 NfInstModel.objects.filter(nfinstid=self.nf_inst_id).update(status=VNF_STATUS.FAILED,
403 lastuptime=now_time())
404 JobUtil.add_job_status(self.job_id, 255, 'VNF instantiation failed, detail message: %s' % error_msg, 0)
406 def save_vnf_inst_id_in_vnffg(self):
407 vnffgs = self.nsd_model['vnffgs']
409 if self.vnf_id not in vnffg['members']:
411 vnffg_inst_infos = VNFFGInstModel.objects.filter(vnffgdid=vnffg['vnffg_Id'], nsinstid=self.ns_inst_id)
412 if not vnffg_inst_infos:
413 logger.error('Vnffg instance not exist.')
414 raise NSLCMException('Vnffg instance not exist.')
415 vnf_list = vnffg_inst_infos[0].vnflist
416 vnffg_inst_infos.update(vnf_list=vnf_list + ',' + self.nf_inst_id if vnf_list else self.nf_inst_id)
418 def create_vnf_in_aai(self):
419 logger.debug("CreateVnfs::create_vnf_in_aai::report vnf instance[%s] to aai." % self.nf_inst_id)
421 ns_insts = NSInstModel.objects.filter(id=self.ns_inst_id)
422 self.global_customer_id = ns_insts[0].global_customer_id
423 self.service_type = ns_insts[0].service_type
425 "vnf-id": self.nf_inst_id,
426 "vnf-name": self.vnf_inst_name,
427 "vnf-type": "vnf-type-test111",
428 "service-id": self.ns_inst_id,
430 "is-closed-loop-disabled": False,
431 "relationship-list": {
434 "related-to": "service-instance",
435 "relationship-data": [
437 "relationship-key": "customer.global-customer-id",
438 "relationship-value": self.global_customer_id
441 "relationship-key": "service-subscription.service-type",
442 "relationship-value": self.service_type
445 "relationship-key": "service-instance.service-instance-id",
446 "relationship-value": self.ns_inst_id
453 resp_data, resp_status = create_vnf_aai(self.nf_inst_id, data)
454 logger.debug("Success to create vnf[%s] to aai, ns instance=[%s], resp_status: [%s]."
455 % (self.nf_inst_id, self.ns_inst_id, resp_status))
456 except NSLCMException as e:
457 logger.debug("Fail to create vnf[%s] to aai, ns instance=[%s], detail message: %s"
458 % (self.nf_inst_id, self.ns_inst_id, e.message))
460 logger.error(traceback.format_exc())