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