2 * ============LICENSE_START=======================================================
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
13 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
23 package org.onap.so.bpmn.infrastructure.scripts
25 import org.camunda.bpm.engine.delegate.DelegateExecution
26 import org.json.JSONArray
27 import org.json.JSONObject;
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
33 import org.camunda.bpm.engine.delegate.BpmnError
34 import com.fasterxml.jackson.databind.ObjectMapper
35 import org.onap.so.client.HttpClientFactory
36 import org.onap.so.logger.ErrorCode
38 import javax.ws.rs.core.Response
40 import org.onap.so.bpmn.infrastructure.vfcmodel.ScaleResource
41 import org.onap.so.client.HttpClient
42 import org.onap.so.bpmn.infrastructure.vfcmodel.ScaleNsByStepsData
43 import org.onap.so.bpmn.infrastructure.vfcmodel.ScaleNsData
45 import org.onap.so.bpmn.infrastructure.vfcmodel.NSResourceInputParameter
46 import org.onap.so.bpmn.infrastructure.vfcmodel.NsOperationKey
47 import org.onap.so.bpmn.infrastructure.vfcmodel.NsScaleParameters
48 import org.onap.so.bpmn.infrastructure.vfcmodel.NsParameters
49 import org.onap.so.bpmn.infrastructure.vfcmodel.LocationConstraint
50 import org.onap.so.logger.MessageEnum
51 import org.slf4j.Logger
52 import org.slf4j.LoggerFactory
53 import org.onap.so.utils.TargetEntity
59 * This groovy class supports the <class>DoScaleVFCNetworkServiceInstance.bpmn</class> process.
60 * flow for VFC Network Service Scale
62 public class DoScaleVFCNetworkServiceInstance extends AbstractServiceTaskProcessor {
63 private static final Logger logger = LoggerFactory.getLogger( DoScaleVFCNetworkServiceInstance.class);
66 String host = "http://mso.mso.testlab.openecomp.org:8080"
68 String scaleUrl = "/vfc/rest/v1/vfcadapter/ns/{nsInstanceId}/scale"
70 String queryJobUrl = "/vfc/rest/v1/vfcadapter/jobs/{jobId}"
72 ExceptionUtil exceptionUtil = new ExceptionUtil()
74 JsonUtils jsonUtil = new JsonUtils()
77 * Pre Process the BPMN Flow Request
79 * generate the nsOperationKey
80 * generate the nsParameters
82 public void preProcessRequest(DelegateExecution execution) {
83 logger.trace("preProcessRequest() ")
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)
92 requestJsonStr += objectToJsonStr(nsRIP)
94 requestJsonStr += objectToJsonStr(nsRIP) + "|"
98 execution.setVariable("reqBody", requestJsonStr)
100 logger.trace("Exit preProcessRequest ")
106 public void scaleNetworkService(DelegateExecution execution) {
107 def isDebugEnabled = execution.getVariable("isDebugLogEnabled")
109 String saleNsRequest = execution.getVariable("reqBody")
110 String[] nsReqStr = saleNsRequest.split("\\|")
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()
119 String url = host + scaleUrl.replaceAll("\\{nsInstanceId\\}", nsInstanceId)
121 Response apiResponse = postRequest(execution, url, reqBody)
123 String returnCode = apiResponse.getStatus()
124 String aaiResponseAsString = apiResponse.readEntity(String.class)
126 if (returnCode == "200" || returnCode == "202") {
127 jobId = jsonUtil.getJsonValue(aaiResponseAsString, "jobId")
129 logger.info( "scaleNetworkService get a ns scale job Id:" + jobId)
130 execution.setVariable("jobId", jobId)
131 execution.setVariable("nodeTemplateUUID", nodeTemplateUUID)
133 String isScaleFinished = ""
135 if(jobId =="" || jobId == null){
138 // query the requested network service scale status, if finished, then start the next one, otherwise, wait
139 while (isScaleFinished != "finished" && isScaleFinished != "error"){
141 queryNSProgress(execution)
142 isScaleFinished = execution.getVariable("operationStatus")
150 private void queryNSProgress(DelegateExecution execution) {
151 String jobId = execution.getVariable("jobId")
152 String url = host + queryJobUrl.replaceAll("\\{jobId\\}", jobId)
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)
163 Response apiResponse = postRequest(execution,url, queryReqBody)
165 String returnCode = apiResponse.getStatus()
166 String aaiResponseAsString = apiResponse.readEntity(String.class)
168 String operationStatus = "error"
170 if (returnCode == "200") {
171 operationStatus = jsonUtil.getJsonValue(aaiResponseAsString, "responseDescriptor.status")
174 execution.setVariable("operationStatus", operationStatus)
181 private void timeDelay() {
184 } catch (InterruptedException e) {
185 logger.error("{} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(),
186 "Time Delay exception" + e, "BPMN",
187 ErrorCode.UnknownError.getValue());
194 public void finishNSScale(DelegateExecution execution) {
195 //no need to do anything util now
196 System.out.println("Scale finished.")
201 * url: the url of the request
202 * requestBody: the body of the request
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
209 URL url = new URL(urlString);
211 HttpClient httpClient = new HttpClientFactory().newJsonClient(url, TargetEntity.VNF_ADAPTER)
212 httpClient.addAdditionalHeader("Authorization", "Basic QlBFTENsaWVudDpwYXNzd29yZDEk")
214 apiResponse = httpClient.post(requestBody)
216 logger.info("response code:"+ apiResponse.getStatus() +"\nresponse body:"+ apiResponse.readEntity(String.class))
217 logger.trace("Completed Execute VF-C adapter Post Process ")
219 logger.error("{} {} {} {} {}", MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), "Exception occured " +
220 "while executing VFC Post Call.", "BPMN", ErrorCode.UnknownError.getValue(), e);
221 throw new BpmnError("MSOWorkflowException")
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 >
232 private List<ScaleResource> jsonGetNsResourceList(String nsScaleRequestJsonString) {
233 List<ScaleResource> list = new ArrayList<ScaleResource>()
234 JSONObject jsonObject = new JSONObject(nsScaleRequestJsonString)
236 JSONObject jsonResource = jsonObject.getJSONObject("service")
237 JSONArray arr = jsonResource.getJSONArray("resources")
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"))
245 JSONObject jsonScaleNsData = tempResource.getJSONObject("scaleNsData")
246 JSONObject jsonScaleNsByStepData = jsonScaleNsData.getJSONObject("scaleNsByStepsData")
248 ScaleNsData scaleNsData = new ScaleNsData()
249 ScaleNsByStepsData stepsData = new ScaleNsByStepsData()
251 stepsData.setAspectId(jsonScaleNsByStepData.getString("aspectId"))
252 stepsData.setScalingDirection(jsonScaleNsByStepData.getString("scalingDirection"))
253 stepsData.setNumberOfSteps(Integer.parseInt(jsonScaleNsByStepData.getString("numberOfSteps")))
255 scaleNsData.setScaleNsByStepsData(stepsData)
256 resource.setScaleNsData(scaleNsData)
264 * Convert a java class to JSON string
268 private String objectToJsonStr(Object obj) {
269 ObjectMapper mapper = new ObjectMapper()
270 String jsonStr = null
272 jsonStr = mapper.writeValueAsString(obj)
273 } catch (IOException ioe) {
274 System.out.println(ioe.getMessage())
281 * create a NSResourceInputParameter list from a Scale Network request Json string
284 private List<NSResourceInputParameter> convertScaleNsReq2NSResInputParamList(DelegateExecution execution) {
285 String saleNsRequest = execution.getVariable("bpmnRequest")
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")
297 String resource = JsonUtils.getJsonValue(saleNsRequest, "service.resources")
299 // set nsScaleParameters properties
300 List<ScaleResource> scaleResourcesList = jsonGetNsResourceList(saleNsRequest)
301 List<NSResourceInputParameter> nsResourceInputParameterList = new ArrayList<NSResourceInputParameter>()
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>())
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)
319 nsScaleParameters.setScaleType(sr.getScaleType())
320 nsScaleParameters.setNsInstanceId(sr.getResourceInstanceId())
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())
327 List<ScaleNsByStepsData> scaleNsByStepsDataList = new ArrayList<ScaleNsByStepsData>()
328 scaleNsByStepsDataList.add(scaleNsByStepsData)
329 nsScaleParameters.setScaleNsByStepsData(scaleNsByStepsDataList)
331 nsResourceInputParameter.setNsOperationKey(nsOperationKey)
332 nsResourceInputParameter.setNsServiceName(serviceInstanceName)
333 nsResourceInputParameter.setNsServiceDescription(nsServiceDescription)
334 nsResourceInputParameter.setNsParameters(nsParameters)
335 nsResourceInputParameter.setNsScaleParameters(nsScaleParameters)
337 nsResourceInputParameterList.add(nsResourceInputParameter)
339 return nsResourceInputParameterList