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
25 from lcm.pub.msapi.catalog import get_process_id, get_download_url_from_catalog
26 from lcm.pub.msapi.catalog import query_rawdata_from_catalog, 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
37 logger = logging.getLogger(__name__)
40 class InstantNSService(object):
41 def __init__(self, ns_inst_id, plan_content):
42 self.ns_inst_id = ns_inst_id
43 self.req_data = plan_content
47 job_id = JobUtil.create_job("NS", "NS_INST", self.ns_inst_id)
48 logger.debug('ns-instant(%s) workflow starting...' % self.ns_inst_id)
49 logger.debug('req_data=%s' % self.req_data)
50 ns_inst = NSInstModel.objects.get(id=self.ns_inst_id)
53 for key, val in self.req_data['additionalParamForNs'].items():
54 input_parameters.append({"key": key, "value": val})
57 if 'location' in self.req_data['additionalParamForNs']:
58 vim_id = self.req_data['additionalParamForNs']['location']
59 location_constraints = []
60 if 'locationConstraints' in self.req_data:
61 location_constraints = self.req_data['locationConstraints']
63 JobUtil.add_job_status(job_id, 5, 'Start query nsd(%s)' % ns_inst.nspackage_id)
64 src_plan = query_rawdata_from_catalog(ns_inst.nspackage_id, input_parameters)
65 dst_plan = toscautil.convert_nsd_model(src_plan["rawData"])
66 logger.debug('tosca plan dest:%s' % dst_plan)
67 NSInstModel.objects.filter(id=self.ns_inst_id).update(nsd_model=dst_plan)
69 params_json = json.JSONEncoder().encode(self.req_data["additionalParamForNs"])
72 plan_dict = json.JSONDecoder().decode(dst_plan)
73 for vnf in ignore_case_get(plan_dict, "vnfs"):
74 vnfd_id = vnf['properties']['id']
75 vnfd = NfPackageModel.objects.get(vnfdid=vnfd_id)
76 vnfd_model = json.JSONDecoder().decode(vnfd.vnfdmodel)
77 vnfm_type = vnfd_model["metadata"].get("vnfmType", "ztevmanagerdriver")
78 vimid = self.get_vnf_vim_id(vim_id, location_constraints, vnfd_id)
79 vnfm_info = select_vnfm(vnfm_type=vnfm_type, vim_id=vimid)
81 "vnfProfileId": vnf["vnf_id"],
84 "vnfmInstanceId": vnfm_info["vnfmId"],
85 "vnfmType": vnfm_type,
91 self.set_vl_vim_id(vim_id, location_constraints, plan_dict)
92 dst_plan = json.JSONEncoder().encode(plan_dict)
93 logger.debug('tosca plan dest add vimid:%s' % dst_plan)
94 NSInstModel.objects.filter(id=self.ns_inst_id).update(nsd_model=dst_plan)
96 vnf_params_json = json.JSONEncoder().encode(params_vnf)
97 plan_input = {'jobId': job_id,
98 'nsInstanceId': self.req_data["nsInstanceId"],
99 'object_context': dst_plan,
100 'object_additionalParamForNs': params_json,
101 'object_additionalParamForVnf': vnf_params_json}
102 plan_input.update(**self.get_model_count(dst_plan))
103 plan_input["sdnControllerId"] = ignore_case_get(
104 self.req_data['additionalParamForNs'], "sdncontroller")
106 ServiceBaseInfoModel(service_id=self.ns_inst_id,
107 service_name=ns_inst.name,
109 description=ns_inst.description,
111 status=ns_inst.status,
113 create_time=int(time.time()*1000)).save()
115 service_tpl = get_servicetemplate(ns_inst.nsd_id)
116 DefPkgMappingModel(service_id=self.ns_inst_id,
117 service_def_id=service_tpl['csarId'],
118 template_name=service_tpl['templateName'],
119 template_id=service_tpl['serviceTemplateId']).save()
121 for key, val in self.req_data['additionalParamForNs'].items():
122 InputParamMappingModel(service_id=self.ns_inst_id,
123 input_key=key, input_value=val).save()
125 for vnffg in ignore_case_get(plan_dict, "vnffgs"):
126 VNFFGInstModel(vnffgdid=vnffg["vnffg_id"],
127 vnffginstid=str(uuid.uuid4()),
128 nsinstid=self.ns_inst_id,
129 endpointnumber=0).save()
131 if WORKFLOW_OPTION == "wso2":
132 return self.start_wso2_workflow(job_id, ns_inst, plan_input)
133 elif WORKFLOW_OPTION == "activiti":
134 return self.start_activiti_workflow()
136 return self.start_buildin_workflow(job_id, plan_input)
138 except Exception as e:
139 logger.error(traceback.format_exc())
140 logger.error("ns-instant(%s) workflow error:%s" % (self.ns_inst_id, e.message))
141 JobUtil.add_job_status(job_id, 255, 'NS instantiation failed: %s' % e.message)
142 return dict(data={'error': e.message}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
144 def start_wso2_workflow(self, job_id, ns_inst, plan_input):
145 servicetemplate_id = get_servicetemplate_id(ns_inst.nsd_id)
146 process_id = get_process_id('init', servicetemplate_id)
147 data = {"processId": process_id, "params": {"planInput": plan_input}}
148 logger.debug('ns-instant(%s) workflow data:%s' % (self.ns_inst_id, data))
150 ret = workflow_run(data)
151 logger.info("ns-instant(%s) workflow result:%s" % (self.ns_inst_id, ret))
152 JobUtil.add_job_status(job_id, 10, 'NS inst(%s) wso2 workflow started: %s' % (
153 self.ns_inst_id, ret.get('status')))
154 if ret.get('status') == 1:
155 return dict(data={'jobId': job_id}, status=status.HTTP_200_OK)
156 return dict(data={'error': ret['message']}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
158 def start_activiti_workflow(self, job_id, plan_input):
159 plans = WFPlanModel.objects.filter()
161 raise NSLCMException("No plan is found, you should deploy plan first!")
163 "processId": plans[0].process_id,
166 ret = activiti.exec_workflow(data)
167 logger.info("ns-instant(%s) workflow result:%s" % (self.ns_inst_id, ret))
168 JobUtil.add_job_status(job_id, 10, 'NS inst(%s) activiti workflow started: %s' % (
169 self.ns_inst_id, ret.get('status')))
170 if ret.get('status') == 1:
171 return dict(data={'jobId': job_id}, status=status.HTTP_200_OK)
172 return dict(data={'error': ret['message']}, status=status.HTTP_500_INTERNAL_SERVER_ERROR)
174 def start_buildin_workflow(self, job_id, plan_input):
175 JobUtil.add_job_status(job_id, 10, 'NS inst(%s) buildin workflow started.' %
177 build_in.run_ns_instantiate(plan_input)
178 return dict(data={'jobId': job_id}, status=status.HTTP_200_OK)
180 def get_vnf_vim_id(self, vim_id, location_constraints, vnfdid):
181 for location in location_constraints:
182 if "vnfProfileId" in location and vnfdid == location["vnfProfileId"]:
183 return location["locationConstraints"]["vimId"]
186 raise NSLCMException("No Vim info is found for vnf(%s)." % vnfdid)
188 def set_vl_vim_id(self, vim_id, location_constraints, plan_dict):
189 if "vls" not in plan_dict:
190 logger.debug("No vl is found in nsd.")
193 for vnf in ignore_case_get(plan_dict, "vnfs"):
194 if "dependencies" in vnf:
195 for depend in vnf["dependencies"]:
196 vl_vnf[depend["vl_id"]] = vnf['properties']['id']
198 for location in location_constraints:
199 if "vnfProfileId" in location:
200 vnfd_id = location["vnfProfileId"]
201 vnf_vim[vnfd_id] = location["locationConstraints"]["vimId"]
202 for vl in plan_dict["vls"]:
203 vnfdid = ignore_case_get(vl_vnf, vl["vl_id"])
204 vimid = ignore_case_get(vnf_vim, vnfdid)
208 raise NSLCMException("No Vim info for vl(%s) of vnf(%s)." % (vl["vl_id"], vnfdid))
209 if "location_info" not in vl["properties"]:
210 vl["properties"]["location_info"] = {}
211 vl["properties"]["location_info"]["vimid"] = vimid
214 def get_model_count(context):
215 data = json.JSONDecoder().decode(context)
216 vls = len(data.get('vls', []))
217 sfcs = len(data.get('fps', []))
218 vnfs = len(data.get('vnfs', []))
219 return {'vlCount': str(vls), 'sfcCount': str(sfcs), 'vnfCount': str(vnfs)}