edit activity workflow plan for NS INIT
[vfc/nfvo/lcm.git] / lcm / workflows / build_in.py
1 # Copyright 2017 ZTE Corporation.
2 #
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
6 #
7 #         http://www.apache.org/licenses/LICENSE-2.0
8 #
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.
14 import json
15 import logging
16 import traceback
17 from threading import Thread
18 import time
19
20 from lcm.pub.utils.syscomm import fun_name
21 from lcm.pub.utils.values import ignore_case_get
22 from lcm.pub.utils import restcall
23 from lcm.pub.exceptions import NSLCMException
24
25 logger = logging.getLogger(__name__)
26
27 RESULT_OK, RESULT_NG = "0", "1"
28 JOB_ERROR = 255
29
30 g_jobs_status = {}
31
32 """
33 format of input_data
34 {
35     "jobId": uuid of job, 
36     "nsInstanceId": id of ns instance,
37     "object_context": json format of nsd,
38     "object_additionalParamForNs": json format of additional parameters for ns,
39     "object_additionalParamForVnf": json format of additional parameters for vnf,
40     "vlCount": int type of VL count,
41     "vnfCount: int type of VNF count,
42     "sfcCount": int type of SFC count, 
43     "sdnControllerId": uuid of SDN controller
44 }
45 """
46 def run_ns_instantiate(input_data):
47     logger.debug("Enter %s, input_data is %s", fun_name(), input_data)
48     ns_instantiate_ok = False
49     job_id = ignore_case_get(input_data, "jobId")
50     ns_inst_id = ignore_case_get(input_data, "nsInstanceId")
51     nsd_json = ignore_case_get(input_data, "object_context")
52     ns_param_json = ignore_case_get(input_data, "object_additionalParamForNs")
53     vnf_param_json = ignore_case_get(input_data, "object_additionalParamForVnf")
54     vl_count = ignore_case_get(input_data, "vlCount")
55     vnf_count = ignore_case_get(input_data, "vnfCount")
56     sfc_count = ignore_case_get(input_data, "sfcCount")
57     sdnc_id = ignore_case_get(input_data, "sdnControllerId")
58     g_jobs_status[job_id] = [1 for i in range(vnf_count)]
59     try:
60         update_job(job_id, 10, "0", "Start to create VL")
61         for i in range(vl_count):
62             create_vl(ns_inst_id, i + 1, nsd_json, ns_param_json)
63
64         update_job(job_id, 30, "0", "Start to create VNF")
65         jobs = [create_vnf(ns_inst_id, i + 1, vnf_param_json) for i in range(vnf_count)] 
66         wait_until_jobs_done(job_id, jobs)
67
68         [confirm_vnf_status(inst_id) for inst_id, _, _ in jobs]
69
70         update_job(job_id, 70, "0", "Start to create SFC")
71         g_jobs_status[job_id] = [1 for i in range(sfc_count)]
72         jobs = [create_sfc(ns_inst_id, i + 1, nsd_json, sdnc_id) for i in range(sfc_count)] 
73         wait_until_jobs_done(job_id, jobs)
74
75         [confirm_sfc_status(inst_id) for inst_id, _, _ in jobs]
76
77         update_job(job_id, 90, "0", "Start to post deal")
78         post_deal(ns_inst_id, "true")
79
80         update_job(job_id, 100, "0", "Create NS successfully.")
81         ns_instantiate_ok = True
82     except NSLCMException as e:
83         logger.error("Failded to Create NS: %s", e.message)
84         update_job(job_id, JOB_ERROR, "255", "Failded to Create NS.")
85         post_deal(ns_inst_id, "false")
86     except:
87         logger.error(traceback.format_exc())
88         update_job(job_id, JOB_ERROR, "255", "Failded to Create NS.")
89         post_deal(ns_inst_id, "false")
90     finally:
91         g_jobs_status.pop(job_id)
92     return ns_instantiate_ok
93
94
95 def create_vl(ns_inst_id, vl_index, nsd, ns_param):
96     uri = "api/nslcm/v1/ns/vls"
97     data = json.JSONEncoder().encode({
98         "nsInstanceId": ns_inst_id,
99         "vlIndex": vl_index,
100         "context": nsd,
101         "additionalParamForNs": ns_param
102     })
103
104     ret = restcall.req_by_msb(uri, "POST", data)
105     if ret[0] != 0:
106         logger.error("Failed to call create_vl(%s): %s", vl_index, ret[1])
107         raise NSLCMException("Failed to call create_vl(index is %s)" % vl_index)
108     ret[1] = json.JSONDecoder().decode(ret[1])
109
110     result = str(ret[1]["result"])
111     detail = ret[1]["detail"]
112     vl_id = ret[1]["vlId"]
113     if result != RESULT_OK:
114         logger.error("Failed to create VL(%s): %s", vl_id, detail)
115         raise NSLCMException("Failed to create VL(%s)" % vl_id)
116
117     logger.debug("Create VL(%s) successfully.", vl_id)
118
119 def create_vnf(ns_inst_id, vnf_index, nf_param):
120     uri = "api/nslcm/v1/ns/vnfs"
121     data = json.JSONEncoder().encode({
122         "nsInstanceId": ns_inst_id,
123         "vnfIndex": vnf_index,
124         "additionalParamForVnf": nf_param
125     })
126
127     ret = restcall.req_by_msb(uri, "POST", data)
128     if ret[0] != 0:
129         logger.error("Failed to call create_vnf(%s): %s", vnf_index, ret[1])
130         raise NSLCMException("Failed to call create_vnf(index is %s)" % vnf_index)
131     ret[1] = json.JSONDecoder().decode(ret[1])
132
133     vnf_inst_id = ret[1]["vnfInstId"]
134     job_id = ret[1]["jobId"]
135     logger.debug("Create VNF(%s) started.", vnf_inst_id)
136     return vnf_inst_id, job_id, vnf_index - 1
137
138 def create_sfc(ns_inst_id, fp_index, nsd_json, sdnc_id):
139     uri = "api/nslcm/v1/ns/sfcs"
140     data = json.JSONEncoder().encode({
141         "nsInstanceId": ns_inst_id,
142         "context": nsd_json,
143         "fpindex": fp_index,
144         "sdnControllerId": sdnc_id
145     })
146
147     ret = restcall.req_by_msb(uri, "POST", data)
148     if ret[0] != 0:
149         logger.error("Failed to call create_sfc(%s): %s", fp_index, ret[1])
150         raise NSLCMException("Failed to call create_sfc(index is %s)" % fp_index)
151     ret[1] = json.JSONDecoder().decode(ret[1])
152
153     sfc_inst_id = ret[1]["sfcInstId"]
154     job_id = ret[1]["jobId"]
155     logger.debug("Create SFC(%s) started.", sfc_inst_id)
156     return sfc_inst_id, job_id, fp_index - 1
157
158 def post_deal(ns_inst_id, status):
159     uri = "api/nslcm/v1/ns/{nsInstanceId}/postdeal".format(nsInstanceId=ns_inst_id) 
160     data = json.JSONEncoder().encode({
161         "status": status
162     })
163
164     ret = restcall.req_by_msb(uri, "POST", data)
165     if ret[0] != 0:
166         logger.error("Failed to call post_deal(%s): %s", ns_inst_id, ret[1])
167     logger.debug("Call post_deal(%s, %s) successfully.", ns_inst_id, status)
168
169 def update_job(job_id, progress, errcode, desc):
170     uri = "api/nslcm/v1/jobs/{jobId}".format(jobId=job_id)
171     data = json.JSONEncoder().encode({
172         "progress": progress,
173         "errcode": errcode,
174         "desc": desc
175     })
176     restcall.req_by_msb(uri, "POST", data)  
177
178 class JobWaitThread(Thread):
179     """
180     Job Wait 
181     """
182
183     def __init__(self, inst_id, job_id, ns_job_id, index):
184         Thread.__init__(self)
185         self.inst_id = inst_id
186         self.job_id = job_id
187         self.ns_job_id = ns_job_id
188         self.index = index
189         self.retry_count = 60
190         self.interval_second = 3
191
192     def run(self):
193         count = 0
194         response_id, new_response_id = 0, 0
195         job_end_normal, job_timeout = False, True
196         while count < self.retry_count:
197             count = count + 1
198             time.sleep(self.interval_second)
199             uri = "/api/nslcm/v1/jobs/%s?responseId=%s" % (self.job_id, response_id)
200             ret = restcall.req_by_msb(uri, "GET")
201             if ret[0] != 0:
202                 logger.error("Failed to query job: %s:%s", ret[2], ret[1])
203                 continue
204             job_result = json.JSONDecoder().decode(ret[1])
205             if "responseDescriptor" not in job_result:
206                 logger.error("Job(%s) does not exist.", self.job_id)
207                 continue
208             progress = job_result["responseDescriptor"]["progress"]
209             new_response_id = job_result["responseDescriptor"]["responseId"]
210             job_desc = job_result["responseDescriptor"]["statusDescription"]
211             if new_response_id != response_id:
212                 logger.debug("%s:%s:%s", progress, new_response_id, job_desc)
213                 response_id = new_response_id
214                 count = 0
215             if progress == JOB_ERROR:
216                 job_timeout = False
217                 logger.error("Job(%s) failed: %s", self.job_id, job_desc)
218                 break
219             elif progress == 100:
220                 job_end_normal, job_timeout = True, False
221                 logger.info("Job(%s) ended normally", self.job_id)
222                 break
223         if job_timeout:
224             logger.error("Job(%s) timeout", self.job_id)
225         if self.ns_job_id in g_jobs_status:
226             if job_end_normal:
227                 g_jobs_status[self.ns_job_id][self.index] = 0
228
229 def wait_until_jobs_done(g_job_id, jobs):
230     job_threads = []
231     for inst_id, job_id, index in jobs:
232         job_threads.append(JobWaitThread(inst_id, job_id, g_job_id, index))
233     for t in job_threads:
234         t.start()
235     for t in job_threads:
236         t.join()
237     if g_job_id in g_jobs_status:
238         if sum(g_jobs_status[g_job_id]) > 0:
239             logger.error("g_jobs_status[%s]: %s", g_job_id, g_jobs_status[g_job_id])
240             raise NSLCMException("Some jobs failed!")
241
242 def confirm_vnf_status(vnf_inst_id):
243     uri = "api/nslcm/v1/ns/vnfs/{vnfInstId}".format(vnfInstId=vnf_inst_id)
244     ret = restcall.req_by_msb(uri, "GET")
245     if ret[0] != 0:
246         raise NSLCMException("Failed to call get_vnf(%s)" % vnf_inst_id)
247     ret[1] = json.JSONDecoder().decode(ret[1])
248
249     vnf_status = ret[1]["vnfStatus"]
250     if vnf_status != "active":
251         raise NSLCMException("Status of VNF(%s) is not active" % vnf_inst_id)
252
253 def confirm_sfc_status(sfc_inst_id):
254     uri = "api/nslcm/v1/ns/sfcs/{sfcInstId}".format(sfcInstId=sfc_inst_id)
255     ret = restcall.req_by_msb(uri, "GET")
256     if ret[0] != 0:
257         raise NSLCMException("Failed to call get_sfc(%s)" % sfc_inst_id)
258     ret[1] = json.JSONDecoder().decode(ret[1])
259
260     sfc_status = ret[1]["sfcStatus"]
261     if sfc_status != "active":
262         raise NSLCMException("Status of SFC(%s) is not active" % sfc_inst_id)
263
264
265
266
267
268       
269