Merge "Reorder modifiers"
[so.git] / bpmn / MSOInfrastructureBPMN / src / main / groovy / org / openecomp / mso / bpmn / infrastructure / scripts / DoScaleVFCNetworkServiceInstance.groovy
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2018 CMCC. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.openecomp.mso.bpmn.infrastructure.scripts
22
23 import org.camunda.bpm.engine.delegate.DelegateExecution
24 import org.json.JSONArray
25 import org.json.JSONObject;
26
27 import org.openecomp.mso.bpmn.common.scripts.AbstractServiceTaskProcessor
28 import org.openecomp.mso.bpmn.common.scripts.ExceptionUtil
29 import org.openecomp.mso.bpmn.core.json.JsonUtils
30
31 import org.camunda.bpm.engine.delegate.BpmnError
32 import org.camunda.bpm.engine.runtime.Execution
33 import org.codehaus.jackson.map.ObjectMapper
34
35 import org.openecomp.mso.rest.RESTClient
36 import org.openecomp.mso.rest.RESTConfig
37 import org.openecomp.mso.rest.APIResponse;
38
39 import org.openecomp.mso.bpmn.infrastructure.vfcmodel.ScaleResource
40 import org.openecomp.mso.bpmn.infrastructure.vfcmodel.ScaleNsByStepsData
41 import org.openecomp.mso.bpmn.infrastructure.vfcmodel.ScaleNsData
42
43 import org.openecomp.mso.bpmn.infrastructure.vfcmodel.NSResourceInputParameter
44 import org.openecomp.mso.bpmn.infrastructure.vfcmodel.NsOperationKey
45 import org.openecomp.mso.bpmn.infrastructure.vfcmodel.NsScaleParameters
46 import org.openecomp.mso.bpmn.infrastructure.vfcmodel.NsParameters
47 import org.openecomp.mso.bpmn.infrastructure.vfcmodel.LocationConstraint
48
49
50 /**
51  * This groovy class supports the <class>DoScaleVFCNetworkServiceInstance.bpmn</class> process.
52  * flow for VFC Network Service Scale
53  */
54 public class DoScaleVFCNetworkServiceInstance extends AbstractServiceTaskProcessor {
55
56     String host = "http://mso.mso.testlab.openecomp.org:8080"
57
58     String scaleUrl = "/vfc/rest/v1/vfcadapter/ns/{nsInstanceId}/scale"
59
60     String queryJobUrl = "/vfc/rest/v1/vfcadapter/jobs/{jobId}"
61
62     ExceptionUtil exceptionUtil = new ExceptionUtil()
63
64     JsonUtils jsonUtil = new JsonUtils()
65
66     /**
67      * Pre Process the BPMN Flow Request
68      * Inclouds:
69      * generate the nsOperationKey
70      * generate the nsParameters
71      */
72     public void preProcessRequest(DelegateExecution execution) {
73         def isDebugEnabled = execution.getVariable("isDebugLogEnabled")
74         utils.log("DEBUG", " *** preProcessRequest() *** ", isDebugEnabled)
75
76         List<NSResourceInputParameter> nsRIPList = convertScaleNsReq2NSResInputParamList(execution)
77         String requestJsonStr = ""
78         int size = nsRIPList.size()
79         for (int i = 0; i < size; i++) {
80             NSResourceInputParameter nsRIP = nsRIPList.get(i)
81
82             if (i == size - 1) {
83                 requestJsonStr += objectToJsonStr(nsRIP)
84             } else {
85                 requestJsonStr += objectToJsonStr(nsRIP) + "|"
86             }
87         }
88
89         execution.setVariable("reqBody", requestJsonStr)
90
91         utils.log("DEBUG", " ***** Exit preProcessRequest *****", isDebugEnabled)
92     }
93
94     /**
95      * scale NS task
96      */
97     public void scaleNetworkService(DelegateExecution execution) {
98         def isDebugEnabled = execution.getVariable("isDebugLogEnabled")
99
100         String saleNsRequest = execution.getVariable("reqBody")
101         String[] nsReqStr = saleNsRequest.split("\\|")
102
103         for (int i = 0; i < nsReqStr.length; i++) {
104             JSONObject reqBodyJsonObj = new JSONObject(nsReqStr[i])
105             String nsInstanceId = reqBodyJsonObj.getJSONObject("nsScaleParameters").getString("nsInstanceId")
106             String nodeTemplateUUID = reqBodyJsonObj.getJSONObject("nsOperationKey").getString("nodeTemplateUUID")
107             reqBodyJsonObj.getJSONObject("nsScaleParameters").remove("nsInstanceId")
108             String reqBody = reqBodyJsonObj.toString()
109
110             String url = host + scaleUrl.replaceAll("\\{nsInstanceId\\}", nsInstanceId)
111
112             APIResponse apiResponse = postRequest(execution, url, reqBody)
113
114             String returnCode = apiResponse.getStatusCode()
115             String aaiResponseAsString = apiResponse.getResponseBodyAsString()
116             String jobId = ""
117             if (returnCode == "200" || returnCode == "202") {
118                 jobId = jsonUtil.getJsonValue(aaiResponseAsString, "jobId")
119             }
120             utils.log("INFO", "scaleNetworkService get a ns scale job Id:" + jobId, isDebugEnabled)
121             execution.setVariable("jobId", jobId)
122             execution.setVariable("nodeTemplateUUID", nodeTemplateUUID)
123
124             String isScaleFinished = ""
125
126             if(jobId =="" || jobId == null){
127                 continue
128             }
129             // query the requested network service scale status, if finished, then start the next one, otherwise, wait
130             while (isScaleFinished != "finished" && isScaleFinished != "error"){
131                 timeDelay()
132                 queryNSProgress(execution)
133                 isScaleFinished = execution.getVariable("operationStatus")
134             }
135         }
136     }
137
138     /**
139      * query NS task
140      */
141     private void queryNSProgress(DelegateExecution execution) {
142         String jobId = execution.getVariable("jobId")
143         String url = host + queryJobUrl.replaceAll("\\{jobId\\}", jobId)
144
145         NsOperationKey nsOperationKey = new NsOperationKey()
146         // is this net work service ID or E2E service ID?
147         nsOperationKey.setServiceId(execution.getVariable("serviceId"))
148         nsOperationKey.setServiceType(execution.getVariable("serviceType"))
149         nsOperationKey.setGlobalSubscriberId(execution.getVariable("globalSubscriberId"))
150         nsOperationKey.setNodeTemplateUUID(execution.getVariable("nodeTemplateUUID"))
151         nsOperationKey.setOperationId(execution.getVariable("operationId"))
152         String queryReqBody = objectToJsonStr(nsOperationKey)
153
154         APIResponse apiResponse = postRequest(execution,url, queryReqBody)
155
156         String returnCode = apiResponse.getStatusCode()
157         String aaiResponseAsString = apiResponse.getResponseBodyAsString()
158
159         String operationStatus = "error"
160
161         if (returnCode == "200") {
162             operationStatus = jsonUtil.getJsonValue(aaiResponseAsString, "responseDescriptor.status")
163         }
164
165         execution.setVariable("operationStatus", operationStatus)
166     }
167
168     /**
169      * delay 5 sec
170      *
171      */
172     private void timeDelay() {
173         try {
174             Thread.sleep(5000)
175         } catch (InterruptedException e) {
176             taskProcessor.utils.log("ERROR", "Time Delay exception" + e, isDebugEnabled)
177         }
178     }
179
180     /**
181      * finish NS task
182      */
183     public void finishNSScale(DelegateExecution execution) {
184         //no need to do anything util now
185         System.out.println("Scale finished.")
186     }
187
188     /**
189      * post request
190      * url: the url of the request
191      * requestBody: the body of the request
192      */
193     private APIResponse postRequest(DelegateExecution execution, String url, String requestBody){
194         def isDebugEnabled = execution.getVariable("isDebugLogEnabled")
195         utils.log("INFO"," ***** Started Execute VFC adapter Post Process *****",  isDebugEnabled)
196         utils.log("INFO","url:"+url +"\nrequestBody:"+ requestBody,  isDebugEnabled)
197         APIResponse apiResponse = null
198         try{
199             RESTConfig config = new RESTConfig(url)
200             RESTClient client = new RESTClient(config).addHeader("Content-Type", "application/json").addHeader("Authorization","Basic QlBFTENsaWVudDpwYXNzd29yZDEk")
201 //            RESTClient client = new RESTClient(config).addHeader("Content-Type", "application/json").addHeader("Accept","application/json").addHeader("Authorization","Basic QlBFTENsaWVudDpwYXNzd29yZDEk")
202             apiResponse = client.httpPost(requestBody)
203             utils.log("INFO","response code:"+ apiResponse.getStatusCode() +"\nresponse body:"+ apiResponse.getResponseBodyAsString(),  isDebugEnabled)
204             utils.log("INFO","======== Completed Execute VF-C adapter Post Process ======== ",  isDebugEnabled)
205         }catch(Exception e){
206             utils.log("ERROR","Exception occured while executing VFC Post Call. Exception is: \n" + e,  isDebugEnabled)
207             throw new BpmnError("MSOWorkflowException")
208         }
209         return apiResponse
210     }
211
212     /**
213      * create a Scale Resource object list from a NSScaleRequestJso nString
214      * This method is for the specific request from Scale Network Service BPMN workflow
215      * @param nsScaleRequestJsonString , a specific request Json string which conform to ?? class
216      * @return List < ScaleResource >
217      */
218     private List<ScaleResource> jsonGetNsResourceList(String nsScaleRequestJsonString) {
219         List<ScaleResource> list = new ArrayList<ScaleResource>()
220         JSONObject jsonObject = new JSONObject(nsScaleRequestJsonString)
221
222         JSONObject jsonResource = jsonObject.getJSONObject("service")
223         JSONArray arr = jsonResource.getJSONArray("resources")
224
225         for (int i = 0; i < arr.length(); i++) {
226             JSONObject tempResource = arr.getJSONObject(i)
227             ScaleResource resource = new ScaleResource()
228             resource.setResourceInstanceId(tempResource.getString("resourceInstanceId"))
229             resource.setScaleType(tempResource.getString("scaleType"))
230
231             JSONObject jsonScaleNsData = tempResource.getJSONObject("scaleNsData")
232             JSONObject jsonScaleNsByStepData = jsonScaleNsData.getJSONObject("scaleNsByStepsData")
233
234             ScaleNsData scaleNsData = new ScaleNsData()
235             ScaleNsByStepsData stepsData = new ScaleNsByStepsData()
236
237             stepsData.setAspectId(jsonScaleNsByStepData.getString("aspectId"))
238             stepsData.setScalingDirection(jsonScaleNsByStepData.getString("scalingDirection"))
239             stepsData.setNumberOfSteps(Integer.parseInt(jsonScaleNsByStepData.getString("numberOfSteps")))
240
241             scaleNsData.setScaleNsByStepsData(stepsData)
242             resource.setScaleNsData(scaleNsData)
243             list.add(resource)
244         }
245
246         return list
247     }
248
249     /**
250      * Convert a java class to JSON string
251      * @param obj
252      * @return
253      */
254     private String objectToJsonStr(Object obj) {
255         ObjectMapper mapper = new ObjectMapper()
256         String jsonStr = null
257         try {
258             jsonStr = mapper.writeValueAsString(obj)
259         } catch (IOException ioe) {
260             System.out.println(ioe.getMessage())
261         }
262         return jsonStr
263
264     }
265
266     /**
267      * create a NSResourceInputParameter list from a Scale Network request Json string
268      * @return
269      */
270     private List<NSResourceInputParameter> convertScaleNsReq2NSResInputParamList(DelegateExecution execution) {
271         String saleNsRequest = execution.getVariable("bpmnRequest")
272
273         //String requestId = execution.getVariable("msoRequestId")
274         //String serviceInstanceId = execution.getVariable("serviceInstanceId")
275         String serviceInstanceName = execution.getVariable("serviceInstanceName")
276         //String nodeTemplateUUID = execution.getVariable("nodeTemplateUUID")
277         String serviceType = execution.getVariable("serviceType")
278         String globalSubscriberId = execution.getVariable("globalSubscriberId")
279         String operationId = execution.getVariable("operationId")
280         String serviceId = execution.getVariable("serviceId")
281         String nsServiceDescription = execution.getVariable("requestDescription")
282
283         String resource = JsonUtils.getJsonValue(saleNsRequest, "service.resources")
284
285         // set nsScaleParameters properties
286         List<ScaleResource> scaleResourcesList = jsonGetNsResourceList(saleNsRequest)
287         List<NSResourceInputParameter> nsResourceInputParameterList = new ArrayList<NSResourceInputParameter>()
288
289         for (ScaleResource sr : scaleResourcesList) {
290             NSResourceInputParameter nsResourceInputParameter = new NSResourceInputParameter()
291             NsOperationKey nsOperationKey = new NsOperationKey()
292             NsParameters nsParameters = new NsParameters()
293             NsScaleParameters nsScaleParameters = new NsScaleParameters()
294             nsParameters.setLocationConstraints(new ArrayList<LocationConstraint>())
295             nsParameters.setAdditionalParamForNs(new HashMap<String, Object>())
296
297             // set NsOperationKey properties
298             nsOperationKey.setGlobalSubscriberId(globalSubscriberId)
299             nsOperationKey.setServiceId(serviceId)
300             nsOperationKey.setServiceType(serviceType)
301             // for ns scale the resourceInstanceId is the nodeTemplateUUID
302             nsOperationKey.setNodeTemplateUUID(sr.getResourceInstanceId())
303             nsOperationKey.setOperationId(operationId)
304
305             nsScaleParameters.setScaleType(sr.getScaleType())
306             nsScaleParameters.setNsInstanceId(sr.getResourceInstanceId())
307
308             ScaleNsByStepsData scaleNsByStepsData = new ScaleNsByStepsData()
309             scaleNsByStepsData.setScalingDirection(sr.getScaleNsData().getScaleNsByStepsData().getScalingDirection())
310             scaleNsByStepsData.setNumberOfSteps(sr.getScaleNsData().getScaleNsByStepsData().getNumberOfSteps())
311             scaleNsByStepsData.setAspectId(sr.getScaleNsData().getScaleNsByStepsData().getAspectId())
312
313             List<ScaleNsByStepsData> scaleNsByStepsDataList = new ArrayList<ScaleNsByStepsData>()
314             scaleNsByStepsDataList.add(scaleNsByStepsData)
315             nsScaleParameters.setScaleNsByStepsData(scaleNsByStepsDataList)
316
317             nsResourceInputParameter.setNsOperationKey(nsOperationKey)
318             nsResourceInputParameter.setNsServiceName(serviceInstanceName)
319             nsResourceInputParameter.setNsServiceDescription(nsServiceDescription)
320             nsResourceInputParameter.setNsParameters(nsParameters)
321             nsResourceInputParameter.setNsScaleParameters(nsScaleParameters)
322
323             nsResourceInputParameterList.add(nsResourceInputParameter)
324         }
325         return nsResourceInputParameterList
326     }
327 }
328