2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 Huawei Technologies Co., Ltd. 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.apihandlerinfra;
25 import java.io.IOException;
26 import java.util.ArrayList;
27 import java.util.HashMap;
28 import java.util.List;
30 import java.util.UUID;
31 import javax.ws.rs.Consumes;
32 import javax.ws.rs.DELETE;
33 import javax.ws.rs.GET;
34 import javax.ws.rs.POST;
35 import javax.ws.rs.PUT;
36 import javax.ws.rs.Path;
37 import javax.ws.rs.PathParam;
38 import javax.ws.rs.Produces;
39 import javax.ws.rs.core.MediaType;
40 import javax.ws.rs.core.Response;
41 import org.apache.http.HttpResponse;
42 import org.apache.http.HttpStatus;
43 import org.json.JSONObject;
44 import org.onap.so.apihandler.common.ErrorNumbers;
45 import org.onap.so.apihandler.common.RequestClient;
46 import org.onap.so.apihandler.common.RequestClientFactory;
47 import org.onap.so.apihandler.common.RequestClientParameter;
48 import org.onap.so.apihandler.common.ResponseBuilder;
49 import org.onap.so.apihandler.common.ResponseHandler;
50 import org.onap.so.apihandlerinfra.e2eserviceinstancebeans.CompareModelsRequest;
51 import org.onap.so.apihandlerinfra.e2eserviceinstancebeans.E2EServiceInstanceDeleteRequest;
52 import org.onap.so.apihandlerinfra.e2eserviceinstancebeans.E2EServiceInstanceRequest;
53 import org.onap.so.apihandlerinfra.e2eserviceinstancebeans.E2EServiceInstanceScaleRequest;
54 import org.onap.so.apihandlerinfra.e2eserviceinstancebeans.GetE2EServiceInstanceResponse;
55 import org.onap.so.apihandlerinfra.exceptions.ApiException;
56 import org.onap.so.apihandlerinfra.exceptions.ValidateException;
57 import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo;
58 import org.onap.so.db.catalog.beans.Service;
59 import org.onap.so.db.catalog.beans.ServiceRecipe;
60 import org.onap.so.db.catalog.client.CatalogDbClient;
61 import org.onap.so.db.request.beans.OperationStatus;
62 import org.onap.so.db.request.client.RequestsDbClient;
63 import org.onap.so.logger.ErrorCode;
64 import org.onap.so.logger.MessageEnum;
65 import org.onap.so.serviceinstancebeans.ModelInfo;
66 import org.onap.so.serviceinstancebeans.ModelType;
67 import org.onap.so.serviceinstancebeans.RequestDetails;
68 import org.onap.so.serviceinstancebeans.RequestInfo;
69 import org.onap.so.serviceinstancebeans.RequestParameters;
70 import org.onap.so.serviceinstancebeans.ServiceInstancesRequest;
71 import org.onap.so.serviceinstancebeans.SubscriberInfo;
72 import org.slf4j.Logger;
73 import org.slf4j.LoggerFactory;
74 import org.springframework.beans.factory.annotation.Autowired;
75 import org.springframework.stereotype.Component;
76 import com.fasterxml.jackson.databind.ObjectMapper;
77 import io.swagger.annotations.Api;
78 import io.swagger.annotations.ApiOperation;
82 @Path("/onap/so/infra/e2eServiceInstances")
83 @Api(value = "/onap/so/infra/e2eServiceInstances", description = "API Requests for E2E Service Instances")
84 public class E2EServiceInstances {
86 private HashMap<String, String> instanceIdMap = new HashMap<>();
87 private static final Logger logger = LoggerFactory.getLogger(E2EServiceInstances.class);
89 private static final String MSO_PROP_APIHANDLER_INFRA = "MSO_PROP_APIHANDLER_INFRA";
91 private static final String END_OF_THE_TRANSACTION = "End of the transaction, the final response is: ";
94 private MsoRequest msoRequest;
97 private RequestClientFactory requestClientFactory;
100 private RequestsDbClient requestsDbClient;
103 private CatalogDbClient catalogDbClient;
106 private ResponseBuilder builder;
109 * POST Requests for E2E Service create Instance on a version provided
111 * @throws ApiException
115 @Path("/{version:[vV][3-5]}")
116 @Consumes(MediaType.APPLICATION_JSON)
117 @Produces(MediaType.APPLICATION_JSON)
118 @ApiOperation(value = "Create an E2E Service Instance on a version provided", response = Response.class)
119 public Response createE2EServiceInstance(String request, @PathParam("version") String version) throws ApiException {
121 return processE2EserviceInstances(request, Action.createInstance, null, version);
125 * PUT Requests for E2E Service update Instance on a version provided
127 * @throws ApiException
131 @Path("/{version:[vV][3-5]}/{serviceId}")
132 @Consumes(MediaType.APPLICATION_JSON)
133 @Produces(MediaType.APPLICATION_JSON)
134 @ApiOperation(value = "Update an E2E Service Instance on a version provided and serviceId",
135 response = Response.class)
136 public Response updateE2EServiceInstance(String request, @PathParam("version") String version,
137 @PathParam("serviceId") String serviceId) throws ApiException {
139 instanceIdMap.put("serviceId", serviceId);
141 return updateE2EserviceInstances(request, Action.updateInstance, instanceIdMap, version);
145 * DELETE Requests for E2E Service delete Instance on a specified version and serviceId
147 * @throws ApiException
151 @Path("/{version:[vV][3-5]}/{serviceId}")
152 @Consumes(MediaType.APPLICATION_JSON)
153 @Produces(MediaType.APPLICATION_JSON)
154 @ApiOperation(value = "Delete E2E Service Instance on a specified version and serviceId", response = Response.class)
155 public Response deleteE2EServiceInstance(String request, @PathParam("version") String version,
156 @PathParam("serviceId") String serviceId) throws ApiException {
158 instanceIdMap.put("serviceId", serviceId);
160 return deleteE2EserviceInstances(request, Action.deleteInstance, instanceIdMap, version);
164 @Path("/{version:[vV][3-5]}/{serviceId}/operations/{operationId}")
165 @ApiOperation(value = "Find e2eServiceInstances Requests for a given serviceId and operationId",
166 response = Response.class)
167 @Produces(MediaType.APPLICATION_JSON)
168 public Response getE2EServiceInstances(@PathParam("serviceId") String serviceId,
169 @PathParam("version") String version, @PathParam("operationId") String operationId) {
170 return getE2EServiceInstance(serviceId, operationId, version);
174 * Scale Requests for E2E Service scale Instance on a specified version
176 * @throws ApiException
180 @Path("/{version:[vV][3-5]}/{serviceId}/scale")
181 @Consumes(MediaType.APPLICATION_JSON)
182 @Produces(MediaType.APPLICATION_JSON)
183 @ApiOperation(value = "Scale E2E Service Instance on a specified version", response = Response.class)
184 public Response scaleE2EServiceInstance(String request, @PathParam("version") String version,
185 @PathParam("serviceId") String serviceId) throws ApiException {
187 logger.debug("------------------scale begin------------------");
188 instanceIdMap.put("serviceId", serviceId);
189 return scaleE2EserviceInstances(request, Action.scaleInstance, instanceIdMap, version);
193 * GET Requests for Comparing model of service instance with target version
195 * @throws ApiException
199 @Path("/{version:[vV][3-5]}/{serviceId}/modeldifferences")
200 @Consumes(MediaType.APPLICATION_JSON)
201 @Produces(MediaType.APPLICATION_JSON)
203 value = "Find added and deleted resources of target model for the e2eserviceInstance on a given serviceId ",
204 response = Response.class)
205 public Response compareModelwithTargetVersion(String request, @PathParam("serviceId") String serviceId,
206 @PathParam("version") String version) throws ApiException {
208 instanceIdMap.put("serviceId", serviceId);
210 return compareModelwithTargetVersion(request, Action.compareModel, instanceIdMap, version);
213 private Response compareModelwithTargetVersion(String requestJSON, Action action,
214 HashMap<String, String> instanceIdMap, String version) throws ApiException {
216 String requestId = UUID.randomUUID().toString();
217 long startTime = System.currentTimeMillis();
219 CompareModelsRequest e2eCompareModelReq;
221 ObjectMapper mapper = new ObjectMapper();
223 e2eCompareModelReq = mapper.readValue(requestJSON, CompareModelsRequest.class);
225 } catch (Exception e) {
227 logger.debug("Mapping of request to JSON object failed : ", e);
228 Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST,
229 MsoException.ServiceException, "Mapping of request to JSON object failed. " + e.getMessage(),
230 ErrorNumbers.SVC_BAD_PARAMETER, null, version);
231 logger.error("{} {} {} {}", MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA,
232 ErrorCode.SchemaError.getValue(), requestJSON, e);
233 logger.debug(END_OF_THE_TRANSACTION + response.getEntity().toString());
238 return runCompareModelBPMWorkflow(e2eCompareModelReq, requestJSON, requestId, startTime, action, version);
242 private Response runCompareModelBPMWorkflow(CompareModelsRequest e2eCompareModelReq, String requestJSON,
243 String requestId, long startTime, Action action, String version) throws ApiException {
245 // Define RecipeLookupResult info here instead of query DB for efficiency
246 String workflowUrl = "/mso/async/services/CompareModelofE2EServiceInstance";
247 int recipeTimeout = 180;
249 RequestClient requestClient;
250 HttpResponse response;
252 long subStartTime = System.currentTimeMillis();
255 requestClient = requestClientFactory.getRequestClient(workflowUrl);
257 JSONObject jjo = new JSONObject(requestJSON);
258 String bpmnRequest = jjo.toString();
260 // Capture audit event
261 logger.debug("MSO API Handler Posting call to BPEL engine for url: " + requestClient.getUrl());
262 String serviceId = instanceIdMap.get("serviceId");
263 String serviceType = e2eCompareModelReq.getServiceType();
264 RequestClientParameter postParam = new RequestClientParameter.Builder().setRequestId(requestId)
265 .setBaseVfModule(false).setRecipeTimeout(recipeTimeout).setRequestAction(action.name())
266 .setServiceInstanceId(serviceId).setServiceType(serviceType).setRequestDetails(bpmnRequest)
267 .setALaCarte(false).build();
268 response = requestClient.post(postParam);
269 } catch (Exception e) {
270 Response resp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY,
271 MsoException.ServiceException, "Failed calling bpmn " + e.getMessage(),
272 ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version);
273 logger.error("", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, MSO_PROP_APIHANDLER_INFRA, "", "",
274 ErrorCode.AvailabilityError, "Exception while communicate with BPMN engine", e);
275 logger.debug(END_OF_THE_TRANSACTION + resp.getEntity().toString());
279 if (response == null) {
281 msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException,
282 "bpelResponse is null", ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version);
283 logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA,
284 ErrorCode.BusinessProcesssError.getValue(), "Null response from BPEL");
285 logger.debug(END_OF_THE_TRANSACTION + resp.getEntity().toString());
289 ResponseHandler respHandler = new ResponseHandler(response, requestClient.getType());
290 int bpelStatus = respHandler.getStatus();
292 return beplStatusUpdate(requestId, startTime, requestClient, respHandler, bpelStatus, action, instanceIdMap,
296 private Response getE2EServiceInstance(String serviceId, String operationId, String version) {
298 GetE2EServiceInstanceResponse e2eServiceResponse = new GetE2EServiceInstanceResponse();
300 String apiVersion = version.substring(1);
302 long startTime = System.currentTimeMillis();
304 OperationStatus operationStatus;
307 operationStatus = requestsDbClient.getOneByServiceIdAndOperationId(serviceId, operationId);
308 } catch (Exception e) {
309 logger.error("{} {} {} {}", MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA,
310 ErrorCode.AvailabilityError.getValue(),
311 "Exception while communciate with Request DB - Infra Request Lookup", e);
313 msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND, MsoException.ServiceException,
314 e.getMessage(), ErrorNumbers.NO_COMMUNICATION_TO_REQUESTS_DB, null, version);
315 logger.debug(END_OF_THE_TRANSACTION + response.getEntity());
320 if (operationStatus == null) {
321 Response resp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NO_CONTENT,
322 MsoException.ServiceException, "E2E serviceId " + serviceId + " is not found in DB",
323 ErrorNumbers.SVC_DETAILED_SERVICE_ERROR, null, version);
324 logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA,
325 ErrorCode.BusinessProcesssError.getValue(),
326 "Null response from RequestDB when searching by serviceId");
327 logger.debug(END_OF_THE_TRANSACTION + resp.getEntity());
332 e2eServiceResponse.setOperation(operationStatus);
334 return builder.buildResponse(HttpStatus.SC_OK, null, e2eServiceResponse, apiVersion);
337 private Response deleteE2EserviceInstances(String requestJSON, Action action, HashMap<String, String> instanceIdMap,
338 String version) throws ApiException {
339 // TODO should be a new one or the same service instance Id
340 long startTime = System.currentTimeMillis();
341 E2EServiceInstanceDeleteRequest e2eDelReq;
343 ObjectMapper mapper = new ObjectMapper();
345 e2eDelReq = mapper.readValue(requestJSON, E2EServiceInstanceDeleteRequest.class);
347 } catch (Exception e) {
349 logger.debug("Mapping of request to JSON object failed : ", e);
350 Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST,
351 MsoException.ServiceException, "Mapping of request to JSON object failed. " + e.getMessage(),
352 ErrorNumbers.SVC_BAD_PARAMETER, null, version);
353 logger.error("{} {} {} {}", MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA,
354 ErrorCode.SchemaError.getValue(), requestJSON, e);
355 logger.debug(END_OF_THE_TRANSACTION + response.getEntity());
359 String requestId = UUID.randomUUID().toString();
360 RecipeLookupResult recipeLookupResult;
362 // TODO Get the service template model version uuid from AAI.
363 recipeLookupResult = getServiceInstanceOrchestrationURI(null, action);
364 } catch (Exception e) {
365 logger.error(MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA,
366 ErrorCode.AvailabilityError.getValue(), "Exception while communciate with Catalog DB", e);
368 Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND,
369 MsoException.ServiceException, "No communication to catalog DB " + e.getMessage(),
370 ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version);
372 msoRequest.createErrorRequestRecord(Status.FAILED, requestId,
373 "Exception while communciate with " + "Catalog DB", action, ModelType.service.name(), requestJSON);
374 logger.debug(END_OF_THE_TRANSACTION + response.getEntity());
377 if (recipeLookupResult == null) {
378 logger.error("{} {} {} {}", MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND.toString(), MSO_PROP_APIHANDLER_INFRA,
379 ErrorCode.DataError.getValue(), "No recipe found in DB");
380 Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND,
381 MsoException.ServiceException, "Recipe does not exist in catalog DB",
382 ErrorNumbers.SVC_GENERAL_SERVICE_ERROR, null, version);
384 msoRequest.createErrorRequestRecord(Status.FAILED, requestId, "Recipe does not exist in catalog DB", action,
385 ModelType.service.name(), requestJSON);
386 logger.debug(END_OF_THE_TRANSACTION + response.getEntity());
390 RequestClient requestClient;
391 HttpResponse response;
393 long subStartTime = System.currentTimeMillis();
395 requestClient = requestClientFactory.getRequestClient(recipeLookupResult.getOrchestrationURI());
397 JSONObject jjo = new JSONObject(requestJSON);
398 jjo.put("operationId", requestId);
400 String bpmnRequest = jjo.toString();
402 // Capture audit event
403 logger.debug("MSO API Handler Posting call to BPEL engine for url: " + requestClient.getUrl());
404 String serviceId = instanceIdMap.get("serviceId");
405 String serviceInstanceType = e2eDelReq.getServiceType();
406 RequestClientParameter clientParam = new RequestClientParameter.Builder().setRequestId(requestId)
407 .setBaseVfModule(false).setRecipeTimeout(recipeLookupResult.getRecipeTimeout())
408 .setRequestAction(action.name()).setServiceInstanceId(serviceId).setServiceType(serviceInstanceType)
409 .setRequestDetails(bpmnRequest).setApiVersion(version).setALaCarte(false)
410 .setRecipeParamXsd(recipeLookupResult.getRecipeParamXsd()).build();
411 response = requestClient.post(clientParam);
413 } catch (Exception e) {
414 Response resp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY,
415 MsoException.ServiceException, "Failed calling bpmn " + e.getMessage(),
416 ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version);
417 logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA,
418 ErrorCode.AvailabilityError.getValue(), "Exception while communicate with BPMN engine");
419 logger.debug("End of the transaction, the final response is: " + resp.getEntity());
423 if (response == null) {
425 msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException,
426 "bpelResponse is null", ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version);
427 logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA,
428 ErrorCode.BusinessProcesssError.getValue(), "Null response from BPEL");
429 logger.debug(END_OF_THE_TRANSACTION + resp.getEntity());
433 ResponseHandler respHandler = new ResponseHandler(response, requestClient.getType());
434 int bpelStatus = respHandler.getStatus();
436 return beplStatusUpdate(requestId, startTime, requestClient, respHandler, bpelStatus, action, instanceIdMap,
440 private Response updateE2EserviceInstances(String requestJSON, Action action, HashMap<String, String> instanceIdMap,
441 String version) throws ApiException {
443 String requestId = UUID.randomUUID().toString();
444 long startTime = System.currentTimeMillis();
445 E2EServiceInstanceRequest e2eSir;
446 String serviceId = instanceIdMap.get("serviceId");
448 ObjectMapper mapper = new ObjectMapper();
450 e2eSir = mapper.readValue(requestJSON, E2EServiceInstanceRequest.class);
452 } catch (Exception e) {
454 logger.debug("Mapping of request to JSON object failed : ", e);
455 Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST,
456 MsoException.ServiceException, "Mapping of request to JSON object failed. " + e.getMessage(),
457 ErrorNumbers.SVC_BAD_PARAMETER, null, version);
458 logger.error("{} {} {} {}", MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA,
459 ErrorCode.SchemaError.getValue(), requestJSON, e);
460 logger.debug(END_OF_THE_TRANSACTION + response.getEntity());
464 ServiceInstancesRequest sir = mapReqJsonToSvcInstReq(e2eSir, requestJSON);
465 sir.getRequestDetails().getRequestParameters().setaLaCarte(true);
467 parseRequest(sir, instanceIdMap, action, version, requestJSON, false, requestId);
468 } catch (Exception e) {
469 logger.debug("Validation failed: ", e);
471 msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST, MsoException.ServiceException,
472 "Error parsing request. " + e.getMessage(), ErrorNumbers.SVC_BAD_PARAMETER, null, version);
473 if (requestId != null) {
474 logger.debug("Logging failed message to the database");
476 logger.error("{} {} {} {}", MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA,
477 ErrorCode.SchemaError.getValue(), requestJSON, e);
478 logger.debug(END_OF_THE_TRANSACTION + response.getEntity());
482 RecipeLookupResult recipeLookupResult;
484 recipeLookupResult = getServiceInstanceOrchestrationURI(e2eSir.getService().getServiceUuid(), action);
485 } catch (Exception e) {
486 logger.error("{} {} {} {}", MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA,
487 ErrorCode.AvailabilityError.getValue(), "Exception while communciate with Catalog DB", e);
488 Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND,
489 MsoException.ServiceException, "No communication to catalog DB " + e.getMessage(),
490 ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version);
492 logger.debug(END_OF_THE_TRANSACTION + response.getEntity());
497 if (recipeLookupResult == null) {
498 logger.error("{} {} {} {}", MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND.toString(), MSO_PROP_APIHANDLER_INFRA,
499 ErrorCode.DataError.getValue(), "No recipe found in DB");
500 Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND,
501 MsoException.ServiceException, "Recipe does not exist in catalog DB",
502 ErrorNumbers.SVC_GENERAL_SERVICE_ERROR, null, version);
503 logger.debug(END_OF_THE_TRANSACTION + response.getEntity());
508 String serviceInstanceType = e2eSir.getService().getServiceType();
510 RequestClient requestClient;
511 HttpResponse response;
513 long subStartTime = System.currentTimeMillis();
514 String sirRequestJson = convertToString(sir);
517 requestClient = requestClientFactory.getRequestClient(recipeLookupResult.getOrchestrationURI());
519 // Capture audit event
520 logger.debug("MSO API Handler Posting call to BPEL engine for url: " + requestClient.getUrl());
521 RequestClientParameter postParam = new RequestClientParameter.Builder().setRequestId(requestId)
522 .setBaseVfModule(false).setRecipeTimeout(recipeLookupResult.getRecipeTimeout())
523 .setRequestAction(action.name()).setServiceInstanceId(serviceId).setServiceType(serviceInstanceType)
524 .setRequestDetails(sirRequestJson).setApiVersion(version).setALaCarte(false)
525 .setRecipeParamXsd(recipeLookupResult.getRecipeParamXsd()).build();
526 response = requestClient.post(postParam);
527 } catch (Exception e) {
528 logger.debug("Exception while communicate with BPMN engine", e);
529 Response getBPMNResp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY,
530 MsoException.ServiceException, "Failed calling bpmn " + e.getMessage(),
531 ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version);
533 logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA,
534 ErrorCode.AvailabilityError.getValue(), "Exception while communicate with BPMN engine");
535 logger.debug(END_OF_THE_TRANSACTION + getBPMNResp.getEntity());
540 if (response == null) {
541 Response getBPMNResp =
542 msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException,
543 "bpelResponse is null", ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version);
544 logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA,
545 ErrorCode.BusinessProcesssError.getValue(), "Null response from BPEL");
546 logger.debug(END_OF_THE_TRANSACTION + getBPMNResp.getEntity());
550 ResponseHandler respHandler = new ResponseHandler(response, requestClient.getType());
551 int bpelStatus = respHandler.getStatus();
553 return beplStatusUpdate(serviceId, startTime, requestClient, respHandler, bpelStatus, action, instanceIdMap,
557 private Response processE2EserviceInstances(String requestJSON, Action action,
558 HashMap<String, String> instanceIdMap, String version) throws ApiException {
560 String requestId = UUID.randomUUID().toString();
561 long startTime = System.currentTimeMillis();
562 E2EServiceInstanceRequest e2eSir;
564 MsoRequest msoRequest = new MsoRequest();
565 ObjectMapper mapper = new ObjectMapper();
567 e2eSir = mapper.readValue(requestJSON, E2EServiceInstanceRequest.class);
569 } catch (Exception e) {
571 logger.debug("Mapping of request to JSON object failed : ", e);
572 Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST,
573 MsoException.ServiceException, "Mapping of request to JSON object failed. " + e.getMessage(),
574 ErrorNumbers.SVC_BAD_PARAMETER, null, version);
575 logger.error("{} {} {} {}", MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA,
576 ErrorCode.SchemaError.getValue(), requestJSON, e);
577 logger.debug(END_OF_THE_TRANSACTION + response.getEntity());
581 ServiceInstancesRequest sir = mapReqJsonToSvcInstReq(e2eSir, requestJSON);
582 sir.getRequestDetails().getRequestParameters().setaLaCarte(true);
584 parseRequest(sir, instanceIdMap, action, version, requestJSON, false, requestId);
585 } catch (Exception e) {
586 logger.debug("Validation failed: ", e);
588 msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST, MsoException.ServiceException,
589 "Error parsing request. " + e.getMessage(), ErrorNumbers.SVC_BAD_PARAMETER, null, version);
590 if (requestId != null) {
591 logger.debug("Logging failed message to the database");
593 logger.error("{} {} {} {}", MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA,
594 ErrorCode.SchemaError.getValue(), requestJSON, e);
595 logger.debug(END_OF_THE_TRANSACTION + response.getEntity());
599 RecipeLookupResult recipeLookupResult;
601 recipeLookupResult = getServiceInstanceOrchestrationURI(e2eSir.getService().getServiceUuid(), action);
602 } catch (Exception e) {
603 logger.error("{} {} {} {}", MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA,
604 ErrorCode.AvailabilityError.getValue(), "Exception while communciate with Catalog DB", e);
605 Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND,
606 MsoException.ServiceException, "No communication to catalog DB " + e.getMessage(),
607 ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version);
608 logger.debug(END_OF_THE_TRANSACTION + response.getEntity());
612 if (recipeLookupResult == null) {
613 logger.error("{} {} {} {}", MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND.toString(), MSO_PROP_APIHANDLER_INFRA,
614 ErrorCode.DataError.getValue(), "No recipe found in DB");
615 Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND,
616 MsoException.ServiceException, "Recipe does not exist in catalog DB",
617 ErrorNumbers.SVC_GENERAL_SERVICE_ERROR, null, version);
618 logger.debug(END_OF_THE_TRANSACTION + response.getEntity());
622 String serviceInstanceType = e2eSir.getService().getServiceType();
624 String serviceId = "";
625 RequestClient requestClient;
626 HttpResponse response;
628 long subStartTime = System.currentTimeMillis();
629 String sirRequestJson = convertToString(sir);
632 requestClient = requestClientFactory.getRequestClient(recipeLookupResult.getOrchestrationURI());
634 // Capture audit event
635 logger.debug("MSO API Handler Posting call to BPEL engine for url: " + requestClient.getUrl());
636 RequestClientParameter parameter = new RequestClientParameter.Builder().setRequestId(requestId)
637 .setBaseVfModule(false).setRecipeTimeout(recipeLookupResult.getRecipeTimeout())
638 .setRequestAction(action.name()).setServiceInstanceId(serviceId).setServiceType(serviceInstanceType)
639 .setRequestDetails(sirRequestJson).setApiVersion(version).setALaCarte(false)
640 .setRecipeParamXsd(recipeLookupResult.getRecipeParamXsd()).build();
641 response = requestClient.post(parameter);
642 } catch (Exception e) {
643 Response resp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY,
644 MsoException.ServiceException, "Failed calling bpmn " + e.getMessage(),
645 ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version);
647 logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA,
648 ErrorCode.AvailabilityError.getValue(), "Exception while communicate with BPMN engine");
649 logger.debug(END_OF_THE_TRANSACTION + resp.getEntity());
653 if (response == null) {
655 msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException,
656 "bpelResponse is null", ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version);
657 logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA,
658 ErrorCode.BusinessProcesssError.getValue(), "Null response from BPEL");
659 logger.debug(END_OF_THE_TRANSACTION + resp.getEntity());
663 ResponseHandler respHandler = new ResponseHandler(response, requestClient.getType());
664 int bpelStatus = respHandler.getStatus();
666 return beplStatusUpdate(requestId, startTime, requestClient, respHandler, bpelStatus, action, instanceIdMap,
670 private Response scaleE2EserviceInstances(String requestJSON, Action action, HashMap<String, String> instanceIdMap,
671 String version) throws ApiException {
673 String requestId = UUID.randomUUID().toString();
674 long startTime = System.currentTimeMillis();
675 E2EServiceInstanceScaleRequest e2eScaleReq;
677 ObjectMapper mapper = new ObjectMapper();
679 e2eScaleReq = mapper.readValue(requestJSON, E2EServiceInstanceScaleRequest.class);
681 } catch (Exception e) {
683 logger.debug("Mapping of request to JSON object failed : ", e);
684 Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST,
685 MsoException.ServiceException, "Mapping of request to JSON object failed. " + e.getMessage(),
686 ErrorNumbers.SVC_BAD_PARAMETER, null, version);
687 logger.error("{} {} {} {}", MessageEnum.APIH_REQUEST_VALIDATION_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA,
688 ErrorCode.SchemaError.getValue(), requestJSON, e);
689 logger.debug(END_OF_THE_TRANSACTION + response.getEntity());
693 RecipeLookupResult recipeLookupResult;
695 // TODO Get the service template model version uuid from AAI.
696 recipeLookupResult = getServiceInstanceOrchestrationURI(null, action);
697 } catch (Exception e) {
698 logger.error("{} {} {} {}", MessageEnum.APIH_DB_ACCESS_EXC.toString(), MSO_PROP_APIHANDLER_INFRA,
699 ErrorCode.AvailabilityError.getValue(), "Exception while communciate with Catalog DB", e);
701 Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND,
702 MsoException.ServiceException, "No communication to catalog DB " + e.getMessage(),
703 ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version);
705 msoRequest.createErrorRequestRecord(Status.FAILED, requestId,
706 "No communication to catalog DB " + e.getMessage(), action, ModelType.service.name(), requestJSON);
707 logger.debug(END_OF_THE_TRANSACTION + response.getEntity());
710 if (recipeLookupResult == null) {
711 logger.error("{} {} {} {}", MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND.toString(), MSO_PROP_APIHANDLER_INFRA,
712 ErrorCode.DataError.getValue(), "No recipe found in DB");
714 Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_NOT_FOUND,
715 MsoException.ServiceException, "Recipe does not exist in catalog DB",
716 ErrorNumbers.SVC_GENERAL_SERVICE_ERROR, null, version);
717 msoRequest.createErrorRequestRecord(Status.FAILED, requestId, "No recipe found in DB", action,
718 ModelType.service.name(), requestJSON);
719 logger.debug(END_OF_THE_TRANSACTION + response.getEntity());
723 RequestClient requestClient;
724 HttpResponse response;
726 long subStartTime = System.currentTimeMillis();
728 requestClient = requestClientFactory.getRequestClient(recipeLookupResult.getOrchestrationURI());
730 JSONObject jjo = new JSONObject(requestJSON);
731 jjo.put("operationId", requestId);
733 String bpmnRequest = jjo.toString();
735 // Capture audit event
736 logger.debug("MSO API Handler Posting call to BPEL engine for url: " + requestClient.getUrl());
737 String serviceId = instanceIdMap.get("serviceId");
738 String serviceInstanceType = e2eScaleReq.getService().getServiceType();
739 RequestClientParameter postParam = new RequestClientParameter.Builder().setRequestId(requestId)
740 .setBaseVfModule(false).setRecipeTimeout(recipeLookupResult.getRecipeTimeout())
741 .setRequestAction(action.name()).setServiceInstanceId(serviceId).setServiceType(serviceInstanceType)
742 .setRequestDetails(bpmnRequest).setApiVersion(version).setALaCarte(false)
743 .setRecipeParamXsd(recipeLookupResult.getRecipeParamXsd()).build();
744 response = requestClient.post(postParam);
745 } catch (Exception e) {
746 Response resp = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY,
747 MsoException.ServiceException, "Failed calling bpmn " + e.getMessage(),
748 ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version);
750 logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA,
751 ErrorCode.AvailabilityError.getValue(), "Exception while communicate with BPMN engine", e);
752 logger.debug(END_OF_THE_TRANSACTION + resp.getEntity());
756 if (response == null) {
758 msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException,
759 "bpelResponse is null", ErrorNumbers.SVC_NO_SERVER_RESOURCES, null, version);
760 logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_COMMUNICATE_ERROR.toString(), MSO_PROP_APIHANDLER_INFRA,
761 ErrorCode.BusinessProcesssError.getValue(), "Null response from BPEL");
762 logger.debug(END_OF_THE_TRANSACTION + resp.getEntity());
766 ResponseHandler respHandler = new ResponseHandler(response, requestClient.getType());
767 int bpelStatus = respHandler.getStatus();
769 return beplStatusUpdate(requestId, startTime, requestClient, respHandler, bpelStatus, action, instanceIdMap,
773 private Response beplStatusUpdate(String serviceId, long startTime, RequestClient requestClient,
774 ResponseHandler respHandler, int bpelStatus, Action action, HashMap<String, String> instanceIdMap,
777 String apiVersion = version.substring(1);
779 // BPMN accepted the request, the request is in progress
780 if (bpelStatus == HttpStatus.SC_ACCEPTED) {
781 String camundaJSONResponseBody = respHandler.getResponseBody();
782 logger.debug("Received from Camunda: " + camundaJSONResponseBody);
783 logger.debug(END_OF_THE_TRANSACTION + camundaJSONResponseBody);
784 return builder.buildResponse(HttpStatus.SC_ACCEPTED, null, camundaJSONResponseBody, apiVersion);
786 List<String> variables = new ArrayList<>();
787 variables.add(bpelStatus + "");
788 String camundaJSONResponseBody = respHandler.getResponseBody();
789 if (camundaJSONResponseBody != null && !camundaJSONResponseBody.isEmpty()) {
790 Response resp = msoRequest.buildServiceErrorResponse(bpelStatus, MsoException.ServiceException,
791 "Request Failed due to BPEL error with HTTP Status= %1 " + '\n' + camundaJSONResponseBody,
792 ErrorNumbers.SVC_DETAILED_SERVICE_ERROR, variables, version);
793 logger.error("{} {} {} {}", MessageEnum.APIH_BPEL_RESPONSE_ERROR.toString(), requestClient.getUrl(),
794 ErrorCode.BusinessProcesssError.getValue(),
795 "Response from BPEL engine is failed with HTTP Status=" + bpelStatus);
796 logger.debug(END_OF_THE_TRANSACTION + resp.getEntity());
799 Response resp = msoRequest.buildServiceErrorResponse(bpelStatus, MsoException.ServiceException,
800 "Request Failed due to BPEL error with HTTP Status= %1",
801 ErrorNumbers.SVC_DETAILED_SERVICE_ERROR, variables, version);
802 logger.error("", MessageEnum.APIH_BPEL_RESPONSE_ERROR.toString(), requestClient.getUrl(),
803 ErrorCode.BusinessProcesssError.getValue(), "Response from BPEL engine is empty");
804 logger.debug(END_OF_THE_TRANSACTION + resp.getEntity());
811 * Getting recipes from catalogDb
813 * @param serviceModelUUID the service model version uuid
814 * @param action the action for the service
815 * @return the service recipe result
817 private RecipeLookupResult getServiceInstanceOrchestrationURI(String serviceModelUUID, Action action) {
819 RecipeLookupResult recipeLookupResult = getServiceURI(serviceModelUUID, action);
821 if (recipeLookupResult != null) {
822 logger.debug("Orchestration URI is: " + recipeLookupResult.getOrchestrationURI() + ", recipe Timeout is: "
823 + Integer.toString(recipeLookupResult.getRecipeTimeout()));
825 logger.debug("No matching recipe record found");
827 return recipeLookupResult;
831 * Getting recipes from catalogDb If Service recipe is not set, use default recipe, if set , use special recipe.
833 * @param serviceModelUUID the service version uuid
834 * @param action the action of the service.
835 * @return the service recipe result.
837 private RecipeLookupResult getServiceURI(String serviceModelUUID, Action action) {
839 String defaultServiceModelName = "UUI_DEFAULT";
841 Service defaultServiceRecord =
842 catalogDbClient.getFirstByModelNameOrderByModelVersionDesc(defaultServiceModelName);
843 // set recipe as default generic recipe
844 ServiceRecipe recipe =
845 catalogDbClient.getFirstByServiceModelUUIDAndAction(defaultServiceRecord.getModelUUID(), action.name());
846 // check the service special recipe
847 if (null != serviceModelUUID && !serviceModelUUID.isEmpty()) {
848 ServiceRecipe serviceSpecialRecipe =
849 catalogDbClient.getFirstByServiceModelUUIDAndAction(serviceModelUUID, action.name());
850 if (null != serviceSpecialRecipe) {
851 // set service special recipe.
852 recipe = serviceSpecialRecipe;
856 if (recipe == null) {
859 return new RecipeLookupResult(recipe.getOrchestrationUri(), recipe.getRecipeTimeout(), recipe.getParamXsd());
864 * Converting E2EServiceInstanceRequest to ServiceInstanceRequest and passing it to camunda engine.
869 private ServiceInstancesRequest mapReqJsonToSvcInstReq(E2EServiceInstanceRequest e2eSir, String requestJSON) {
871 ServiceInstancesRequest sir = new ServiceInstancesRequest();
873 String returnString = null;
874 RequestDetails requestDetails = new RequestDetails();
875 ModelInfo modelInfo = new ModelInfo();
878 modelInfo.setModelInvariantId(e2eSir.getService().getServiceInvariantUuid());
880 // modelNameVersionId
881 modelInfo.setModelNameVersionId(e2eSir.getService().getServiceUuid());
883 // String modelInfoValue =
884 // e2eSir.getService().getParameters().getNodeTemplateName();
885 // String[] arrayOfInfo = modelInfoValue.split(":");
886 // String modelName = arrayOfInfo[0];
887 // String modelVersion = arrayOfInfo[1];
889 // TODO: To ensure, if we dont get the values from the UUI
890 String modelName = "voLTE";
891 String modelVersion = "1.0";
893 modelInfo.setModelName(modelName);
896 modelInfo.setModelVersion(modelVersion);
899 modelInfo.setModelType(ModelType.service);
901 // setting modelInfo to requestDetails
902 requestDetails.setModelInfo(modelInfo);
904 SubscriberInfo subscriberInfo = new SubscriberInfo();
906 // globalsubscriberId
907 subscriberInfo.setGlobalSubscriberId(e2eSir.getService().getGlobalSubscriberId());
909 // setting subscriberInfo to requestDetails
910 requestDetails.setSubscriberInfo(subscriberInfo);
912 RequestInfo requestInfo = new RequestInfo();
915 requestInfo.setInstanceName(e2eSir.getService().getName());
918 requestInfo.setSource("UUI");
921 requestInfo.setSuppressRollback(true);
923 // setting requestInfo to requestDetails
924 requestDetails.setRequestInfo(requestInfo);
926 RequestParameters requestParameters = new RequestParameters();
928 // subscriptionServiceType
929 requestParameters.setSubscriptionServiceType("MOG");
932 // List<E2EUserParam> userParams;
934 // e2eSir.getService().getParameters().getRequestParameters().getUserParams();
935 List<Map<String, Object>> userParamList = new ArrayList<>();
936 Map<String, Object> userParamMap = new HashMap<>();
937 // complete json request updated in the camunda
938 userParamMap.put("UUIRequest", requestJSON);
939 userParamMap.put("ServiceInstanceName", e2eSir.getService().getName());
941 // Map<String, String> userParamMap3 = null;
942 // for (E2EUserParam userp : userParams) {
943 // userParamMap.put(userp.getName(), userp.getValue());
946 userParamList.add(userParamMap);
947 requestParameters.setUserParams(userParamList);
949 // setting requestParameters to requestDetails
950 requestDetails.setRequestParameters(requestParameters);
952 sir.setRequestDetails(requestDetails);
958 private void parseRequest(ServiceInstancesRequest sir, HashMap<String, String> instanceIdMap, Action action,
959 String version, String requestJSON, Boolean aLaCarte, String requestId) throws ValidateException {
960 int reqVersion = Integer.parseInt(version.substring(1));
962 msoRequest.parse(sir, instanceIdMap, action, version, requestJSON, reqVersion, aLaCarte);
963 } catch (Exception e) {
964 ErrorLoggerInfo errorLoggerInfo =
965 new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError)
966 .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
967 ValidateException validateException =
968 new ValidateException.Builder("Error parsing request: " + e.getMessage(), HttpStatus.SC_BAD_REQUEST,
969 ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build();
971 msoRequest.createErrorRequestRecord(Status.FAILED, requestId, validateException.getMessage(), action,
972 ModelType.service.name(), requestJSON);
974 throw validateException;
978 private String convertToString(ServiceInstancesRequest sir) {
979 String returnString = null;
980 // converting to string
981 ObjectMapper mapper = new ObjectMapper();
983 returnString = mapper.writeValueAsString(sir);
984 } catch (IOException e) {
985 logger.debug("Exception while converting ServiceInstancesRequest object to string", e);