0e4aea00ae282ccc853435bcb02b7e6c4dcc21d1
[so.git] /
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
99         String saleNsRequest = execution.getVariable("reqBody")
100         String[] nsReqStr = saleNsRequest.split("\\|")
101
102         def jobIdArray = ['jobId001', 'jobId002'] as String[]
103
104         for (int i = 0; i < nsReqStr.length; i++) {
105             JSONObject reqBodyJsonObj = new JSONObject(nsReqStr[i])
106             String nsInstanceId = reqBodyJsonObj.getJSONObject("nsScaleParameters").getString("nsInstanceId")
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") {
118                 jobId = jsonUtil.getJsonValue(aaiResponseAsString, "jobId")
119             }
120
121             execution.setVariable("jobId", jobIdArray[i])
122
123             String isScaleFinished = ""
124
125             // query the requested network service scale status, if finished, then start the next one, otherwise, wait
126             while (isScaleFinished != "finished" && isScaleFinished != "error"){
127                 timeDelay()
128                 queryNSProgress(execution)
129                 isScaleFinished = execution.getVariable("operationStatus")
130             }
131         }
132     }
133
134     /**
135      * query NS task
136      */
137     private void queryNSProgress(DelegateExecution execution) {
138         String jobId = execution.getVariable("jobId")
139         String url = host + queryJobUrl.replaceAll("\\{jobId\\}", jobId)
140
141         NsOperationKey nsOperationKey = new NsOperationKey()
142         // is this net work service ID or E2E service ID?
143         nsOperationKey.setServiceId(execution.getVariable("serviceId"))
144         nsOperationKey.setServiceType(execution.getVariable("serviceType"))
145         nsOperationKey.setGlobalSubscriberId(execution.getVariable("globalSubscriberId"))
146         nsOperationKey.setNodeTemplateUUID(execution.getVariable("nodeTemplateUUID"))
147         nsOperationKey.setOperationId(execution.getVariable("operationId"))
148         String queryReqBody = objectToJsonStr(nsOperationKey)
149
150         APIResponse apiResponse = postRequest(execution,url, queryReqBody)
151
152         String returnCode = apiResponse.getStatusCode()
153         String aaiResponseAsString = apiResponse.getResponseBodyAsString()
154
155         String operationStatus = "error"
156
157         if (returnCode == "200") {
158             operationStatus = jsonUtil.getJsonValue(aaiResponseAsString, "responseDescriptor.status")
159         }
160
161         execution.setVariable("operationStatus", operationStatus)
162     }
163
164     /**
165      * delay 5 sec
166      *
167      */
168     private void timeDelay() {
169         try {
170             Thread.sleep(5000)
171         } catch (InterruptedException e) {
172             taskProcessor.utils.log("ERROR", "Time Delay exception" + e, isDebugEnabled)
173         }
174     }
175
176     /**
177      * finish NS task
178      */
179     public void finishNSScale(DelegateExecution execution) {
180         //no need to do anything util now
181         System.out.println("Scale finished.")
182     }
183
184     /**
185      * post request
186      * url: the url of the request
187      * requestBody: the body of the request
188      */
189     private APIResponse postRequest(DelegateExecution execution, String url, String requestBody){
190         def isDebugEnabled = execution.getVariable("isDebugLogEnabled")
191         utils.log("INFO"," ***** Started Execute VFC adapter Post Process *****",  isDebugEnabled)
192         utils.log("INFO","url:"+url +"\nrequestBody:"+ requestBody,  isDebugEnabled)
193         APIResponse apiResponse = null
194         try{
195             RESTConfig config = new RESTConfig(url)
196             RESTClient client = new RESTClient(config).addHeader("Content-Type", "application/json").addHeader("Authorization","Basic QlBFTENsaWVudDpwYXNzd29yZDEk")
197 //            RESTClient client = new RESTClient(config).addHeader("Content-Type", "application/json").addHeader("Accept","application/json").addHeader("Authorization","Basic QlBFTENsaWVudDpwYXNzd29yZDEk")
198             apiResponse = client.httpPost(requestBody)
199             utils.log("INFO","response code:"+ apiResponse.getStatusCode() +"\nresponse body:"+ apiResponse.getResponseBodyAsString(),  isDebugEnabled)
200             utils.log("INFO","======== Completed Execute VF-C adapter Post Process ======== ",  isDebugEnabled)
201         }catch(Exception e){
202             utils.log("ERROR","Exception occured while executing VFC Post Call. Exception is: \n" + e,  isDebugEnabled)
203             throw new BpmnError("MSOWorkflowException")
204         }
205         return apiResponse
206     }
207
208     /**
209      * create a Scale Resource object list from a NSScaleRequestJso nString
210      * This method is for the specific request from Scale Network Service BPMN workflow
211      * @param nsScaleRequestJsonString , a specific request Json string which conform to ?? class
212      * @return List < ScaleResource >
213      */
214     private List<ScaleResource> jsonGetNsResourceList(String nsScaleRequestJsonString) {
215         List<ScaleResource> list = new ArrayList<ScaleResource>()
216         JSONObject jsonObject = new JSONObject(nsScaleRequestJsonString)
217
218         JSONObject jsonResource = jsonObject.getJSONObject("service")
219         JSONArray arr = jsonResource.getJSONArray("resources")
220
221         for (int i = 0; i < arr.length(); i++) {
222             JSONObject tempResource = arr.getJSONObject(i)
223             ScaleResource resource = new ScaleResource()
224             resource.setResourceInstanceId(tempResource.getString("resourceInstanceId"))
225             resource.setScaleType(tempResource.getString("scaleType"))
226
227             JSONObject jsonScaleNsData = tempResource.getJSONObject("scaleNsData")
228             JSONObject jsonScaleNsByStepData = jsonScaleNsData.getJSONObject("scaleNsByStepsData")
229
230             ScaleNsData scaleNsData = new ScaleNsData()
231             ScaleNsByStepsData stepsData = new ScaleNsByStepsData()
232
233             stepsData.setAspectId(jsonScaleNsByStepData.getString("aspectId"))
234             stepsData.setScalingDirection(jsonScaleNsByStepData.getString("scalingDirection"))
235             stepsData.setNumberOfSteps(Integer.parseInt(jsonScaleNsByStepData.getString("numberOfSteps")))
236
237             scaleNsData.setScaleNsByStepsData(stepsData)
238             resource.setScaleNsData(scaleNsData)
239             list.add(resource)
240         }
241
242         return list
243     }
244
245     /**
246      * Convert a java class to JSON string
247      * @param obj
248      * @return
249      */
250     private String objectToJsonStr(Object obj) {
251         ObjectMapper mapper = new ObjectMapper()
252         String jsonStr = null
253         try {
254             jsonStr = mapper.writeValueAsString(obj)
255         } catch (IOException ioe) {
256             System.out.println(ioe.getMessage())
257         }
258         return jsonStr
259
260     }
261
262     /**
263      * create a NSResourceInputParameter list from a Scale Network request Json string
264      * @return
265      */
266     private List<NSResourceInputParameter> convertScaleNsReq2NSResInputParamList(DelegateExecution execution) {
267         String saleNsRequest = execution.getVariable("bpmnRequest")
268
269         //String requestId = execution.getVariable("msoRequestId")
270         //String serviceInstanceId = execution.getVariable("serviceInstanceId")
271         String serviceInstanceName = execution.getVariable("serviceInstanceName")
272         //String nodeTemplateUUID = execution.getVariable("nodeTemplateUUID")
273         String serviceType = execution.getVariable("serviceType")
274         String globalSubscriberId = execution.getVariable("globalSubscriberId")
275         String operationId = execution.getVariable("operationId")
276         String serviceId = execution.getVariable("serviceId")
277         String nsServiceDescription = execution.getVariable("requestDescription")
278
279         String resource = JsonUtils.getJsonValue(saleNsRequest, "service.resources")
280
281         // set nsScaleParameters properties
282         List<ScaleResource> scaleResourcesList = jsonGetNsResourceList(saleNsRequest)
283         List<NSResourceInputParameter> nsResourceInputParameterList = new ArrayList<NSResourceInputParameter>()
284
285         for (ScaleResource sr : scaleResourcesList) {
286             NSResourceInputParameter nsResourceInputParameter = new NSResourceInputParameter()
287             NsOperationKey nsOperationKey = new NsOperationKey()
288             NsParameters nsParameters = new NsParameters()
289             NsScaleParameters nsScaleParameters = new NsScaleParameters()
290             nsParameters.setLocationConstraints(new ArrayList<LocationConstraint>())
291             nsParameters.setAdditionalParamForNs(new HashMap<String, Object>())
292
293             // set NsOperationKey properties
294             nsOperationKey.setGlobalSubscriberId(globalSubscriberId)
295             nsOperationKey.setServiceId(serviceId)
296             nsOperationKey.setServiceType(serviceType)
297             // for ns scale the resourceInstanceId is the nodeTemplateUUID
298             nsOperationKey.setNodeTemplateUUID(sr.getResourceInstanceId())
299             nsOperationKey.setOperationId(operationId)
300
301             nsScaleParameters.setScaleType(sr.getScaleType())
302             nsScaleParameters.setNsInstanceId(sr.getResourceInstanceId())
303
304             ScaleNsByStepsData scaleNsByStepsData = new ScaleNsByStepsData()
305             scaleNsByStepsData.setScalingDirection(sr.getScaleNsData().getScaleNsByStepsData().getScalingDirection())
306             scaleNsByStepsData.setNumberOfSteps(sr.getScaleNsData().getScaleNsByStepsData().getNumberOfSteps())
307             scaleNsByStepsData.setAspectId(sr.getScaleNsData().getScaleNsByStepsData().getAspectId())
308
309             List<ScaleNsByStepsData> scaleNsByStepsDataList = new ArrayList<ScaleNsByStepsData>()
310             scaleNsByStepsDataList.add(scaleNsByStepsData)
311             nsScaleParameters.setScaleNsByStepsData(scaleNsByStepsDataList)
312
313             nsResourceInputParameter.setNsOperationKey(nsOperationKey)
314             nsResourceInputParameter.setNsServiceName(serviceInstanceName)
315             nsResourceInputParameter.setNsServiceDescription(nsServiceDescription)
316             nsResourceInputParameter.setNsParameters(nsParameters)
317             nsResourceInputParameter.setNsScaleParameters(nsScaleParameters)
318
319             nsResourceInputParameterList.add(nsResourceInputParameter)
320         }
321         return nsResourceInputParameterList
322     }
323 }
324