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.ns_vnfs.biz.subscribe import SubscriptionCreation
40 logger = logging.getLogger(__name__)
43 def prepare_create_params():
44 nf_inst_id = str(uuid.uuid4())
45 NfInstModel(nfinstid=nf_inst_id, status=VNF_STATUS.INSTANTIATING, create_time=now_time(),
46 lastuptime=now_time()).save()
47 job_id = JobUtil.create_job(INST_TYPE_NAME.VNF, JOB_TYPE.CREATE_VNF, nf_inst_id)
48 JobUtil.add_job_status(job_id, 0, 'create vnf record in database.', 0)
49 return nf_inst_id, job_id
52 class CreateVnfs(Thread):
53 def __init__(self, data, nf_inst_id, job_id):
54 super(CreateVnfs, self).__init__()
56 self.nf_inst_id = nf_inst_id
61 self.ns_inst_name = ''
64 self.vnf_inst_name = ''
65 self.vnfm_inst_id = ''
67 self.nf_package_info = ''
68 self.vnfm_nf_inst_id = ''
70 self.vnfm_inst_name = ''
76 self.check_nf_name_exist()
79 self.create_vnf_in_aai()
80 self.check_nf_package_valid()
81 self.send_nf_init_request_to_vnfm()
82 self.send_homing_request_to_OOF()
83 self.send_get_vnfm_request_to_extsys()
84 self.send_create_vnf_request_to_resmgr()
85 self.wait_vnfm_job_finish()
87 self.write_vnf_creation_info()
88 self.save_info_to_db()
89 JobUtil.add_job_status(self.job_id, 100, 'vnf instantiation success', 0)
90 except NSLCMException as e:
91 self.vnf_inst_failed_handle(e.message)
93 logger.error(traceback.format_exc())
94 self.vnf_inst_failed_handle('unexpected exception')
97 self.ns_inst_id = self.data['ns_instance_id']
98 vnf_index = int(float(self.data['vnf_index'])) - 1
99 additional_vnf_info = self.data['additional_param_for_vnf'][vnf_index]
100 self.vnf_id = ignore_case_get(additional_vnf_info, 'vnfProfileId')
101 additional_param = ignore_case_get(additional_vnf_info, 'additionalParam')
102 self.properties = ignore_case_get(additional_param, 'properties')
103 self.vnfm_inst_id = ignore_case_get(additional_param, 'vnfmInstanceId')
104 para = ignore_case_get(additional_param, 'inputs')
105 self.inputs = json.loads(para) if isinstance(para, (str, unicode)) else para
106 self.vim_id = ignore_case_get(additional_param, 'vimId')
107 self.vnfd_id = ignore_case_get(additional_param, 'vnfdId')
109 def check_nf_name_exist(self):
110 is_exist = NfInstModel.objects.filter(nf_name=self.vnf_inst_name).exists()
112 logger.error('The name of NF instance already exists.')
113 raise NSLCMException('The name of NF instance already exists.')
115 def get_vnfd_id(self):
117 logger.debug("need not get vnfd_id")
118 self.nsd_model = {'vnfs': [], 'vls': [], 'vnffgs': []}
119 self.vnf_inst_name = self.vnfd_id + str(uuid.uuid4())
120 self.vnf_inst_name = self.vnf_inst_name[:30]
122 ns_inst_info = NSInstModel.objects.get(id=self.ns_inst_id)
123 self.ns_inst_name = ns_inst_info.name
124 self.nsd_model = json.loads(ns_inst_info.nsd_model)
125 for vnf_info in self.nsd_model['vnfs']:
126 if self.vnf_id == vnf_info['vnf_id']:
127 self.vnfd_id = vnf_info['properties']['id']
128 if 'name' not in vnf_info['properties']:
129 # HW vnf instance name must start with alphabet
130 self.vnf_inst_name = 'vnf' + self.vnfd_id[:10] + str(uuid.uuid4())
132 self.vnf_inst_name = vnf_info['properties']['name'] + str(uuid.uuid4())
133 self.vnf_inst_name = self.vnf_inst_name[:30]
134 self.vnf_inst_name = self.vnf_inst_name.replace("-", "_")
136 logger.error('Can not found vnf in nsd model')
137 raise NSLCMException('Can not found vnf in nsd model')
139 def check_nf_package_valid(self):
140 nfpackage_info = query_vnfpackage_by_id(self.vnfd_id)
141 self.nf_package_info = nfpackage_info["packageInfo"]
142 self.vnfd_model = ignore_case_get(self.nf_package_info, "vnfdModel")
143 self.vnfd_model = json.loads(self.vnfd_model)
145 def get_virtual_link_info(self, vnf_id):
146 virtual_link_list, ext_virtual_link = [], []
147 for vnf_info in self.nsd_model['vnfs']:
148 if vnf_info['vnf_id'] != vnf_id:
150 for network_info in vnf_info['networks']:
151 vl_instance = VLInstModel.objects.get(
152 vldid=network_info['vl_id'],
153 ownertype=OWNER_TYPE.NS,
154 ownerid=self.ns_inst_id)
155 vl_instance_id = vl_instance.vlinstanceid
156 network_name, subnet_name = self.get_network_info_of_vl(network_info['vl_id'])
157 virtual_link_list.append({
158 'network_name': network_name,
159 'key_name': network_info['key_name'],
160 'subnetwork_name': subnet_name,
161 'vl_instance_id': vl_instance_id
163 ext_virtual_link.append({
164 "vlInstanceId": vl_instance_id,
165 "resourceId": vl_instance.relatednetworkid,
166 "resourceSubnetId": vl_instance.relatedsubnetworkid,
167 "cpdId": self.get_cpd_id_of_vl(network_info['key_name']),
169 "vimid": vl_instance.vimid
172 return virtual_link_list, ext_virtual_link
174 def get_cpd_id_of_vl(self, vl_key):
175 for cpd in self.vnfd_model["vnf_exposed"]["external_cps"]:
176 if vl_key == cpd["key_name"]:
180 def get_network_info_of_vl(self, vl_id):
181 for vnf_info in self.nsd_model['vls']:
182 if vnf_info['vl_id'] == vl_id:
183 return vnf_info['properties']['vl_profile']['networkName'], vnf_info['properties']['vl_profile']['networkName'] # ['initiationParameters']['name']
186 def send_nf_init_request_to_vnfm(self):
187 virtual_link_list, ext_virtual_link = self.get_virtual_link_info(self.vnf_id)
188 req_param = json.JSONEncoder().encode({
189 'vnfInstanceName': self.vnf_inst_name,
190 'vnfPackageId': ignore_case_get(self.nf_package_info, "vnfPackageId"),
191 'vnfDescriptorId': self.vnfd_id,
192 'extVirtualLink': ext_virtual_link,
194 "properties": self.properties,
195 "inputs": self.inputs,
196 "vimId": self.vim_id,
197 "extVirtualLinks": virtual_link_list
200 rsp = send_nf_init_request(self.vnfm_inst_id, req_param)
201 self.vnfm_job_id = ignore_case_get(rsp, 'jobId')
202 self.vnfm_nf_inst_id = ignore_case_get(rsp, 'vnfInstanceId')
204 NfInstModel.objects.filter(nfinstid=self.nf_inst_id).update(
205 mnfinstid=self.vnfm_nf_inst_id,
206 nf_name=self.vnf_inst_name,
208 package_id=ignore_case_get(self.nf_package_info, "vnfPackageId"),
209 vnfm_inst_id=self.vnfm_inst_id,
210 ns_inst_id=self.ns_inst_id,
211 version=ignore_case_get(self.nf_package_info, "vnfdVersion"),
212 vendor=ignore_case_get(self.nf_package_info, "vnfdProvider"),
213 vnfd_model=self.vnfd_model,
214 input_params=json.JSONEncoder().encode(self.inputs),
215 lastuptime=now_time())
217 def build_homing_request(self):
218 id = str(uuid.uuid4())
219 callback_uri = " {vfcBaseUrl}/api/nslcm/v1/ns/placevnf"
220 IP = REG_TO_MSB_REG_PARAM["nodes"][0]["ip"]
221 PORT = REG_TO_MSB_REG_PARAM["nodes"][0]["port"]
222 vfcBaseUrl = IP + ':' + PORT
223 callback_uri = callback_uri.format(vfcBaseUrl=vfcBaseUrl)
224 modelInvariantId = "no-resourceModelInvariantId"
225 modelVersionId = "no-resourceModelVersionId"
226 nsInfo = NSInstModel.objects.filter(id=self.ns_inst_id)
228 "resourceModuleName": self.vnf_inst_name,
229 "serviceResourceId": self.vnfm_nf_inst_id,
230 "resourceModelInfo": {
231 "modelInvariantId": modelInvariantId,
232 "modelVersionId": modelVersionId
239 "callbackUrl": callback_uri,
241 "requestType": "create",
243 "optimizers": ["placement"],
247 "placementDemands": []
250 "serviceInstanceId": self.ns_inst_id,
251 "serviceName": self.ns_inst_name,
253 "modelInvariantId": nsInfo[0].nsd_invariant_id,
254 "modelVersionId": nsInfo[0].nsd_id
258 req_body["placementInfo"]["placementDemands"].append(placementDemand)
259 # Stored the init request info inside DB
260 OOFDataModel.objects.create(
263 request_status="init",
264 request_module_name=self.vnfm_nf_inst_id,
265 service_resource_id=self.vnf_inst_name,
273 def send_homing_request_to_OOF(self):
274 req_body = self.build_homing_request()
275 base_url = OOF_BASE_URL
276 resources = "/api/oof/v1/placement"
277 resp = restcall.call_req(base_url=base_url, user=OOF_USER, passwd=OOF_PASSWD,
278 auth_type=restcall.rest_oneway_auth, resource=resources,
279 method="POST", content=req_body, additional_headers="")
281 resp_status = resp[-1]
283 logger.debug("Got OOF sync response")
285 logger.warn("Missing OOF sync response")
286 logger.debug(("OOF sync response code is %s") % resp_status)
287 if str(resp_status) != '202' or resp[0] != 0:
288 OOFDataModel.objects.filter(request_id=req_body["requestInfo"]["requestId"],
289 transaction_id=req_body["requestInfo"]["transactionId"]).update(
290 request_status="failed",
293 cloud_region_id="none",
296 raise Exception("Received a Bad Sync from OOF with response code %s" % resp_status)
297 logger.info("Completed Homing request to OOF")
299 def send_get_vnfm_request_to_extsys(self):
300 resp_body = get_vnfm_by_id(self.vnfm_inst_id)
301 self.vnfm_inst_name = ignore_case_get(resp_body, 'name')
303 def send_create_vnf_request_to_resmgr(self):
304 pkg_vnfd = self.vnfd_model
306 'nf_inst_id': self.nf_inst_id,
307 'vnfm_nf_inst_id': self.vnfm_nf_inst_id,
308 'vnf_inst_name': self.vnf_inst_name,
309 'ns_inst_id': self.ns_inst_id,
310 'ns_inst_name': self.ns_inst_name,
311 'nf_inst_name': self.vnf_inst_name,
312 'vnfm_inst_id': self.vnfm_inst_id,
313 'vnfm_inst_name': self.vnfm_inst_name,
314 'vnfd_name': pkg_vnfd['metadata'].get('name', 'undefined'),
315 'vnfd_id': self.vnfd_id,
316 'job_id': self.job_id,
317 'nf_inst_status': VNF_STATUS.INSTANTIATING,
318 'vnf_type': pkg_vnfd['metadata'].get('vnf_type', 'undefined'),
319 'nf_package_id': ignore_case_get(self.nf_package_info, "vnfPackageId")
323 def wait_vnfm_job_finish(self):
324 ret = wait_job_finish(vnfm_id=self.vnfm_inst_id,
325 vnfo_job_id=self.job_id,
326 vnfm_job_id=self.vnfm_job_id,
327 progress_range=[10, 90],
328 timeout=NFVO_VNF_INST_TIMEOUT_SECOND)
330 if ret != JOB_MODEL_STATUS.FINISHED:
331 logger.error('VNF instantiation failed on VNFM side. ret=[%s]', ret)
332 raise NSLCMException('VNF instantiation failed on VNFM side.')
336 'vnfInstanceId': self.vnfm_nf_inst_id,
337 'vnfmId': self.vnfm_inst_id
339 SubscriptionCreation(data).do_biz()
341 def write_vnf_creation_info(self):
342 logger.debug("write_vnf_creation_info start")
343 vm_inst_infos = VmInstModel.objects.filter(insttype=INST_TYPE.VNF, instid=self.nf_inst_id)
345 'nf_inst_id': self.nf_inst_id,
346 'ns_inst_id': self.ns_inst_id,
347 'vnfm_inst_id': self.vnfm_inst_id,
348 'vms': [{'vmId': vm_inst_info.resouceid, 'vmName': vm_inst_info.vmname, 'vmStatus': 'ACTIVE'} for
349 vm_inst_info in vm_inst_infos]}
350 create_vnf_creation_info(data)
351 logger.debug("write_vnf_creation_info end")
353 def save_info_to_db(self):
354 logger.debug("save_info_to_db start")
355 do_biz_with_share_lock("set-vnflist-in-vnffginst-%s" % self.ns_inst_id, self.save_vnf_inst_id_in_vnffg)
356 NfInstModel.objects.filter(nfinstid=self.nf_inst_id).update(status=VNF_STATUS.ACTIVE, lastuptime=now_time())
357 logger.debug("save_info_to_db end")
359 def vnf_inst_failed_handle(self, error_msg):
360 logger.error('VNF instantiation failed, detail message: %s' % error_msg)
361 NfInstModel.objects.filter(nfinstid=self.nf_inst_id).update(status=VNF_STATUS.FAILED,
362 lastuptime=now_time())
363 JobUtil.add_job_status(self.job_id, 255, 'VNF instantiation failed, detail message: %s' % error_msg, 0)
365 def save_vnf_inst_id_in_vnffg(self):
366 vnffgs = self.nsd_model['vnffgs']
368 if self.vnf_id not in vnffg['members']:
370 vnffg_inst_infos = VNFFGInstModel.objects.filter(vnffgdid=vnffg['vnffg_Id'], nsinstid=self.ns_inst_id)
371 if not vnffg_inst_infos:
372 logger.error('Vnffg instance not exist.')
373 raise NSLCMException('Vnffg instance not exist.')
374 vnf_list = vnffg_inst_infos[0].vnflist
375 vnffg_inst_infos.update(vnf_list=vnf_list + ',' + self.nf_inst_id if vnf_list else self.nf_inst_id)
377 def create_vnf_in_aai(self):
378 logger.debug("CreateVnfs::create_vnf_in_aai::report vnf instance[%s] to aai." % self.nf_inst_id)
380 ns_insts = NSInstModel.objects.filter(id=self.ns_inst_id)
381 self.global_customer_id = ns_insts[0].global_customer_id
382 self.service_type = ns_insts[0].service_type
384 "vnf-id": self.nf_inst_id,
385 "vnf-name": self.vnf_inst_name,
386 "vnf-type": "vnf-type-test111",
387 "service-id": self.ns_inst_id,
389 "is-closed-loop-disabled": False,
390 "relationship-list": {
393 "related-to": "service-instance",
394 "relationship-data": [
396 "relationship-key": "customer.global-customer-id",
397 "relationship-value": self.global_customer_id
400 "relationship-key": "service-subscription.service-type",
401 "relationship-value": self.service_type
404 "relationship-key": "service-instance.service-instance-id",
405 "relationship-value": self.ns_inst_id
412 resp_data, resp_status = create_vnf_aai(self.nf_inst_id, data)
413 logger.debug("Success to create vnf[%s] to aai, ns instance=[%s], resp_status: [%s]."
414 % (self.nf_inst_id, self.ns_inst_id, resp_status))
415 except NSLCMException as e:
416 logger.debug("Fail to create vnf[%s] to aai, ns instance=[%s], detail message: %s"
417 % (self.nf_inst_id, self.ns_inst_id, e.message))
419 logger.error(traceback.format_exc())