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