1 # Copyright 2016-2017 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.
21 from rest_framework import status
23 from lcm.pub.database.models import DefPkgMappingModel, ServiceBaseInfoModel, InputParamMappingModel
24 from lcm.pub.database.models import NSInstModel, NfPackageModel, VNFFGInstModel, WFPlanModel, NSDModel
25 from lcm.pub.msapi.catalog import get_process_id, query_rawdata_from_catalog
26 from lcm.pub.msapi.catalog import get_servicetemplate_id, get_servicetemplate
27 from lcm.pub.msapi.wso2bpel import workflow_run
28 from lcm.pub.msapi.extsys import select_vnfm
29 from lcm.pub.utils.jobutil import JobUtil
30 from lcm.pub.utils import toscautil
31 from lcm.pub.utils.values import ignore_case_get
32 from lcm.pub.exceptions import NSLCMException
33 from lcm.pub.config.config import WORKFLOW_OPTION
34 from lcm.workflows import build_in
35 from lcm.pub.msapi import activiti
36 from lcm.pub.utils import toscaparser
38 logger = logging.getLogger(__name__)
41 class InstantNSService(object):
42 def __init__(self, ns_inst_id, plan_content):
43 self.ns_inst_id = ns_inst_id
44 self.req_data = plan_content
48 job_id = JobUtil.create_job("NS", "NS_INST", self.ns_inst_id)
49 logger.debug('ns-instant(%s) workflow starting...' % self.ns_inst_id)
50 logger.debug('req_data=%s' % self.req_data)
51 ns_inst = NSInstModel.objects.get(id=self.ns_inst_id)
54 for key, val in self.req_data['additionalParamForNs'].items():
55 input_parameters.append({"key": key, "value": val})
58 if 'location' in self.req_data['additionalParamForNs']:
59 vim_id = self.req_data['additionalParamForNs']['location']
60 location_constraints = []
61 if 'locationConstraints' in self.req_data:
62 location_constraints = self.req_data['locationConstraints']
64 JobUtil.add_job_status(job_id, 5, 'Start query nsd(%s)' % ns_inst.nspackage_id)
66 if WORKFLOW_OPTION == "wso2":
67 src_plan = query_rawdata_from_catalog(ns_inst.nspackage_id, input_parameters)
68 dst_plan = toscautil.convert_nsd_model(src_plan["rawData"])
70 nsd_pkg = NSDModel.objects.get(id=ns_inst.nspackage_id)
71 dst_plan = toscaparser.parse_nsd(nsd_pkg.nsd_path, input_parameters)
72 logger.debug('tosca plan dest:%s' % dst_plan)
74 NSInstModel.objects.filter(id=self.ns_inst_id).update(nsd_model=dst_plan)
76 params_json = json.JSONEncoder().encode(self.req_data["additionalParamForNs"])
79 plan_dict = json.JSONDecoder().decode(dst_plan)
80 for vnf in ignore_case_get(plan_dict, "vnfs"):
81 vnfd_id = vnf['properties']['id']
82 vnfd = NfPackageModel.objects.get(vnfdid=vnfd_id)
83 vnfd_model = json.JSONDecoder().decode(vnfd.vnfdmodel)
84 vnfm_type = vnfd_model["metadata"].get("vnfmType", "ztevmanagerdriver")
85 vimid = self.get_vnf_vim_id(vim_id, location_constraints, vnfd_id)
86 vnfm_info = select_vnfm(vnfm_type=vnfm_type, vim_id=vimid)
88 "vnfProfileId": vnf["vnf_id"],
91 "vnfmInstanceId": vnfm_info["vnfmId"],
92 "vnfmType": vnfm_type,
98 self.set_vl_vim_id(vim_id, location_constraints, plan_dict)
99 dst_plan = json.JSONEncoder().encode(plan_dict)
100 logger.debug('tosca plan dest add vimid:%s' % dst_plan)
101 NSInstModel.objects.filter(id=self.ns_inst_id).update(nsd_model=dst_plan)
103 vnf_params_json = json.JSONEncoder().encode(params_vnf)
104 plan_input = {'jobId': job_id,
105 'nsInstanceId': self.req_data["nsInstanceId"],
106 'object_context': dst_plan,
107 'object_additionalParamForNs': params_json,
108 'object_additionalParamForVnf': vnf_params_json}
109 plan_input.update(**self.get_model_count(dst_plan))
110 plan_input["sdnControllerId"] = ignore_case_get(
111 self.req_data['additionalParamForNs'], "sdncontroller")
113 ServiceBaseInfoModel(service_id=self.ns_inst_id,
114 service_name=ns_inst.name,
116 description=ns_inst.description,
118 status=ns_inst.status,
120 create_time=int(time.time()*1000)).save()
122 if WORKFLOW_OPTION == "wso2":
123 service_tpl = get_servicetemplate(ns_inst.nsd_id)
124 DefPkgMappingModel(service_id=self.ns_inst_id,
125 service_def_id=service_tpl['csarId'],
126 template_name=service_tpl['templateName'],
127 template_id=service_tpl['serviceTemplateId']).save()
132 for key, val in self.req_data['additionalParamForNs'].items():
133 InputParamMappingModel(service_id=self.ns_inst_id,
134 input_key=key, input_value=val).save()
136 for vnffg in ignore_case_get(plan_dict, "vnffgs"):
137 VNFFGInstModel(vnffgdid=vnffg["vnffg_id"],
138 vnffginstid=str(uuid.uuid4()),
139 nsinstid=self.ns_inst_id,
140 endpointnumber=0).save()
142 if WORKFLOW_OPTION == "wso2":
143 return self.start_wso2_workflow(job_id, ns_inst, plan_input)
144 elif WORKFLOW_OPTION == "activiti":
145 return self.start_activiti_workflow()
147 return self.start_buildin_workflow(job_id, plan_input)
149 except Exception as e:
150 logger.error(traceback.format_exc())
151 logger.error("ns-instant(%s) workflow error:%s" % (self.ns_inst_id, e.message))
152 JobUtil.add_job_status(job_id, 255, 'NS instantiation failed: %s' % e.message)
153 return dict(data={'error': e.message}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
155 def start_wso2_workflow(self, job_id, ns_inst, plan_input):
156 servicetemplate_id = get_servicetemplate_id(ns_inst.nsd_id)
157 process_id = get_process_id('init', servicetemplate_id)
158 data = {"processId": process_id, "params": {"planInput": plan_input}}
159 logger.debug('ns-instant(%s) workflow data:%s' % (self.ns_inst_id, data))
161 ret = workflow_run(data)
162 logger.info("ns-instant(%s) workflow result:%s" % (self.ns_inst_id, ret))
163 JobUtil.add_job_status(job_id, 10, 'NS inst(%s) wso2 workflow started: %s' % (
164 self.ns_inst_id, ret.get('status')))
165 if ret.get('status') == 1:
166 return dict(data={'jobId': job_id}, status=status.HTTP_200_OK)
167 return dict(data={'error': ret['message']}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
169 def start_activiti_workflow(self, job_id, plan_input):
170 plans = WFPlanModel.objects.filter()
172 raise NSLCMException("No plan is found, you should deploy plan first!")
174 "processId": plans[0].process_id,
177 ret = activiti.exec_workflow(data)
178 logger.info("ns-instant(%s) workflow result:%s" % (self.ns_inst_id, ret))
179 JobUtil.add_job_status(job_id, 10, 'NS inst(%s) activiti workflow started: %s' % (
180 self.ns_inst_id, ret.get('status')))
181 if ret.get('status') == 1:
182 return dict(data={'jobId': job_id}, status=status.HTTP_200_OK)
183 return dict(data={'error': ret['message']}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
185 def start_buildin_workflow(self, job_id, plan_input):
186 JobUtil.add_job_status(job_id, 10, 'NS inst(%s) buildin workflow started.' %
188 build_in.run_ns_instantiate(plan_input)
189 return dict(data={'jobId': job_id}, status=status.HTTP_200_OK)
191 def get_vnf_vim_id(self, vim_id, location_constraints, vnfdid):
192 for location in location_constraints:
193 if "vnfProfileId" in location and vnfdid == location["vnfProfileId"]:
194 return location["locationConstraints"]["vimId"]
197 raise NSLCMException("No Vim info is found for vnf(%s)." % vnfdid)
199 def set_vl_vim_id(self, vim_id, location_constraints, plan_dict):
200 if "vls" not in plan_dict:
201 logger.debug("No vl is found in nsd.")
204 for vnf in ignore_case_get(plan_dict, "vnfs"):
205 if "dependencies" in vnf:
206 for depend in vnf["dependencies"]:
207 vl_vnf[depend["vl_id"]] = vnf['properties']['id']
209 for location in location_constraints:
210 if "vnfProfileId" in location:
211 vnfd_id = location["vnfProfileId"]
212 vnf_vim[vnfd_id] = location["locationConstraints"]["vimId"]
213 for vl in plan_dict["vls"]:
214 vnfdid = ignore_case_get(vl_vnf, vl["vl_id"])
215 vimid = ignore_case_get(vnf_vim, vnfdid)
219 raise NSLCMException("No Vim info for vl(%s) of vnf(%s)." % (vl["vl_id"], vnfdid))
220 if "location_info" not in vl["properties"]:
221 vl["properties"]["location_info"] = {}
222 vl["properties"]["location_info"]["vimid"] = vimid
225 def get_model_count(context):
226 data = json.JSONDecoder().decode(context)
227 vls = len(data.get('vls', []))
228 sfcs = len(data.get('fps', []))
229 vnfs = len(data.get('vnfs', []))
230 return {'vlCount': str(vls), 'sfcCount': str(sfcs), 'vnfCount': str(vnfs)}