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