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