2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 Huawei Technologies Co., Ltd. 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
11 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
21 package org.openecomp.mso.apihandlerinfra;
23 import java.io.IOException;
24 import java.util.ArrayList;
25 import java.util.HashMap;
26 import java.util.List;
29 import javax.ws.rs.Consumes;
30 import javax.ws.rs.DELETE;
31 import javax.ws.rs.GET;
32 import javax.ws.rs.POST;
33 import javax.ws.rs.Path;
34 import javax.ws.rs.PathParam;
35 import javax.ws.rs.Produces;
36 import javax.ws.rs.core.MediaType;
37 import javax.ws.rs.core.Response;
39 import org.apache.http.HttpResponse;
40 import org.apache.http.HttpStatus;
41 import org.codehaus.jackson.map.ObjectMapper;
42 import org.openecomp.mso.apihandler.common.ErrorNumbers;
43 import org.openecomp.mso.apihandler.common.RequestClient;
44 import org.openecomp.mso.apihandler.common.RequestClientFactory;
45 import org.openecomp.mso.apihandler.common.ResponseHandler;
46 import org.openecomp.mso.apihandlerinfra.e2eserviceinstancebeans.E2EServiceInstanceRequest;
47 import org.openecomp.mso.apihandlerinfra.e2eserviceinstancebeans.E2EUserParam;
48 import org.openecomp.mso.apihandlerinfra.serviceinstancebeans.ModelInfo;
49 import org.openecomp.mso.apihandlerinfra.serviceinstancebeans.RequestDetails;
50 import org.openecomp.mso.apihandlerinfra.serviceinstancebeans.RequestInfo;
51 import org.openecomp.mso.apihandlerinfra.serviceinstancebeans.RequestParameters;
52 import org.openecomp.mso.apihandlerinfra.serviceinstancebeans.ServiceInstancesRequest;
53 import org.openecomp.mso.apihandlerinfra.serviceinstancebeans.SubscriberInfo;
54 import org.openecomp.mso.db.catalog.CatalogDatabase;
55 import org.openecomp.mso.db.catalog.beans.Service;
56 import org.openecomp.mso.db.catalog.beans.ServiceRecipe;
57 import org.openecomp.mso.logger.MessageEnum;
58 import org.openecomp.mso.logger.MsoAlarmLogger;
59 import org.openecomp.mso.logger.MsoLogger;
60 import org.openecomp.mso.requestsdb.InfraActiveRequests;
61 import org.openecomp.mso.requestsdb.RequestsDatabase;
62 import org.openecomp.mso.utils.UUIDChecker;
64 import com.wordnik.swagger.annotations.Api;
65 import com.wordnik.swagger.annotations.ApiOperation;
67 @Path("/e2eServiceInstances")
68 @Api(value="/e2eServiceInstances",description="API Requests for E2E Service Instances")
69 public class E2EServiceInstances {
71 private HashMap<String, String> instanceIdMap = new HashMap<String,String>();
72 private static MsoLogger msoLogger = MsoLogger.getMsoLogger (MsoLogger.Catalog.APIH);
73 private static MsoAlarmLogger alarmLogger = new MsoAlarmLogger ();
74 public final static String MSO_PROP_APIHANDLER_INFRA = "MSO_PROP_APIHANDLER_INFRA";
76 public E2EServiceInstances() {
80 *POST Requests for E2E Service create Instance on a version provided
84 @Path("/{version:[vV][3-5]}")
85 @Consumes(MediaType.APPLICATION_JSON)
86 @Produces(MediaType.APPLICATION_JSON)
87 @ApiOperation(value="Create a E2E Service Instance on a version provided",response=Response.class)
88 public Response createE2EServiceInstance(String request, @PathParam("version") String version) {
90 return E2EserviceInstances(request, Action.createInstance, null, version);
94 *DELETE Requests for E2E Service delete Instance on a specified version and serviceId
98 @Path("/{version:[vV][3-5]}/{serviceId}")
99 @Consumes(MediaType.APPLICATION_JSON)
100 @Produces(MediaType.APPLICATION_JSON)
101 @ApiOperation(value="Delete E2E Service Instance on a specified version and serviceId",response=Response.class)
102 public Response deleteE2EServiceInstance(String request, @PathParam("version") String version, @PathParam("serviceId") String serviceId) {
104 instanceIdMap.put("serviceId", serviceId);
106 return E2EserviceInstances(request, Action.deleteInstance, null, version);
109 private Response E2EserviceInstances(String requestJSON, Action action,
110 HashMap<String, String> instanceIdMap, String version) {
112 String requestId = UUIDChecker.generateUUID(msoLogger);
113 long startTime = System.currentTimeMillis();
114 msoLogger.debug("requestId is: " + requestId);
115 E2EServiceInstanceRequest sir = null;
117 MsoRequest msoRequest = new MsoRequest(requestId);
118 ObjectMapper mapper = new ObjectMapper();
121 .readValue(requestJSON, E2EServiceInstanceRequest.class);
123 } catch (Exception e) {
125 msoLogger.debug("Mapping of request to JSON object failed : ", e);
126 Response response = msoRequest.buildServiceErrorResponse(
127 HttpStatus.SC_BAD_REQUEST,
128 MsoException.ServiceException,
129 "Mapping of request to JSON object failed. "
130 + e.getMessage(), ErrorNumbers.SVC_BAD_PARAMETER,
132 msoLogger.error(MessageEnum.APIH_REQUEST_VALIDATION_ERROR,
133 MSO_PROP_APIHANDLER_INFRA, "", "",
134 MsoLogger.ErrorCode.SchemaError, requestJSON, e);
135 msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR,
136 MsoLogger.ResponseCode.SchemaError,
137 "Mapping of request to JSON object failed");
138 msoLogger.debug("End of the transaction, the final response is: "
139 + (String) response.getEntity());
143 InfraActiveRequests dup = null;
144 String instanceName = sir.getService().getName();
145 String requestScope = sir.getService().getParameters().getNodeType();
148 if(!(instanceName==null && "service".equals(requestScope) && (action == Action.createInstance || action
149 == Action.activateInstance))){
150 dup = (RequestsDatabase.getInstance()).checkInstanceNameDuplicate (instanceIdMap, instanceName, requestScope);
152 } catch (Exception e) {
153 msoLogger.error (MessageEnum.APIH_DUPLICATE_CHECK_EXC, MSO_PROP_APIHANDLER_INFRA, "", "", MsoLogger.ErrorCode.DataError, "Error during duplicate check ", e);
155 Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, MsoException.ServiceException,
157 ErrorNumbers.SVC_DETAILED_SERVICE_ERROR,
161 msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.DBAccessError, "Error during duplicate check");
162 msoLogger.debug ("End of the transaction, the final response is: " + (String) response.getEntity ());
167 // Found the duplicate record. Return the appropriate error.
168 String instance = null;
169 if(instanceName != null){
170 instance = instanceName;
172 instance = instanceIdMap.get(requestScope + "InstanceId");
174 String dupMessage = "Error: Locked instance - This " + requestScope + " (" + instance + ") " + "already has a request being worked with a status of " + dup.getRequestStatus() + " (RequestId - " + dup.getRequestId() + "). The existing request must finish or be cleaned up before proceeding.";
176 Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_CONFLICT, MsoException.ServiceException,
178 ErrorNumbers.SVC_DETAILED_SERVICE_ERROR,
182 msoLogger.warn (MessageEnum.APIH_DUPLICATE_FOUND, dupMessage, "", "", MsoLogger.ErrorCode.SchemaError, "Duplicate request - Subscriber already has a request for this service");
183 msoRequest.createRequestRecord (Status.FAILED, action);
184 msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.Conflict, dupMessage);
185 msoLogger.debug ("End of the transaction, the final response is: " + (String) response.getEntity ());
189 CatalogDatabase db = null;
190 RecipeLookupResult recipeLookupResult = null;
192 db = CatalogDatabase.getInstance();
193 recipeLookupResult = getServiceInstanceOrchestrationURI(db, sir, action);
194 } catch (Exception e) {
195 msoLogger.error (MessageEnum.APIH_DB_ACCESS_EXC, MSO_PROP_APIHANDLER_INFRA, "", "", MsoLogger.ErrorCode.AvailabilityError, "Exception while communciate with Catalog DB", e);
196 msoRequest.setStatus (org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);
197 Response response = msoRequest.buildServiceErrorResponse (HttpStatus.SC_NOT_FOUND,
198 MsoException.ServiceException,
199 "No communication to catalog DB " + e.getMessage (),
200 ErrorNumbers.SVC_NO_SERVER_RESOURCES,
202 alarmLogger.sendAlarm ("MsoDatabaseAccessError",
203 MsoAlarmLogger.CRITICAL,
204 Messages.errors.get (ErrorNumbers.NO_COMMUNICATION_TO_CATALOG_DB));
205 msoRequest.createRequestRecord (Status.FAILED,action);
206 msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.DBAccessError, "Exception while communciate with DB");
207 msoLogger.debug ("End of the transaction, the final response is: " + (String) response.getEntity ());
215 if (recipeLookupResult == null) {
216 msoLogger.error (MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND, MSO_PROP_APIHANDLER_INFRA, "", "", MsoLogger.ErrorCode.DataError, "No recipe found in DB");
217 msoRequest.setStatus (org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);
218 Response response = msoRequest.buildServiceErrorResponse (HttpStatus.SC_NOT_FOUND,
219 MsoException.ServiceException,
220 "Recipe does not exist in catalog DB",
221 ErrorNumbers.SVC_GENERAL_SERVICE_ERROR,
223 msoRequest.createRequestRecord (Status.FAILED, action);
224 msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.DataNotFound, "No recipe found in DB");
225 msoLogger.debug ("End of the transaction, the final response is: " + (String) response.getEntity ());
231 msoRequest.createRequestRecord (Status.PENDING, action);
232 } catch (Exception e) {
233 msoLogger.error (MessageEnum.APIH_DB_ACCESS_EXC_REASON, "Exception while creating record in DB", "", "", MsoLogger.ErrorCode.SchemaError, "Exception while creating record in DB", e);
234 msoRequest.setStatus (org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);
235 Response response = msoRequest.buildServiceErrorResponse (HttpStatus.SC_INTERNAL_SERVER_ERROR,
236 MsoException.ServiceException,
237 "Exception while creating record in DB " + e.getMessage(),
238 ErrorNumbers.SVC_BAD_PARAMETER,
240 msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.DBAccessError, "Exception while creating record in DB");
241 msoLogger.debug ("End of the transaction, the final response is: " + (String) response.getEntity ());
245 String modelInfo = sir.getService().getParameters().getNodeTemplateName();
246 String[] arrayOfInfo = modelInfo.split(":");
247 String serviceInstanceType = arrayOfInfo[0];
251 String serviceId = "";
253 RequestClient requestClient = null;
254 HttpResponse response = null;
256 long subStartTime = System.currentTimeMillis();
257 String sirRequestJson = mappingObtainedRequestJSONToServiceInstanceRequest(sir);
260 requestClient = RequestClientFactory.getRequestClient (recipeLookupResult.getOrchestrationURI (), MsoPropertiesUtils.loadMsoProperties ());
262 // Capture audit event
263 msoLogger.debug ("MSO API Handler Posting call to BPEL engine for url: " + requestClient.getUrl ());
265 response = requestClient.post(requestId, false,
266 recipeLookupResult.getRecipeTimeout(),
267 action.name(), serviceId, null, null, null, null, serviceInstanceType,
268 null, null, null, sirRequestJson);
270 msoLogger.recordMetricEvent(subStartTime,
271 MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc,
272 "Successfully received response from BPMN engine", "BPMN",
273 recipeLookupResult.getOrchestrationURI(), null);
274 } catch (Exception e) {
275 msoLogger.recordMetricEvent(subStartTime,
276 MsoLogger.StatusCode.ERROR,
277 MsoLogger.ResponseCode.CommunicationError,
278 "Exception while communicate with BPMN engine", "BPMN",
279 recipeLookupResult.getOrchestrationURI(), null);
280 Response resp = msoRequest.buildServiceErrorResponse(
281 HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException,
282 "Failed calling bpmn " + e.getMessage(),
283 ErrorNumbers.SVC_NO_SERVER_RESOURCES, null);
284 alarmLogger.sendAlarm("MsoConfigurationError",
285 MsoAlarmLogger.CRITICAL,
286 Messages.errors.get(ErrorNumbers.NO_COMMUNICATION_TO_BPEL));
287 msoLogger.error(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR,
288 MSO_PROP_APIHANDLER_INFRA, "", "",
289 MsoLogger.ErrorCode.AvailabilityError,
290 "Exception while communicate with BPMN engine");
291 msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR,
292 MsoLogger.ResponseCode.CommunicationError,
293 "Exception while communicate with BPMN engine");
294 msoLogger.debug("End of the transaction, the final response is: "
295 + (String) resp.getEntity());
299 if (response == null) {
300 Response resp = msoRequest.buildServiceErrorResponse(
301 HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException,
302 "bpelResponse is null",
303 ErrorNumbers.SVC_NO_SERVER_RESOURCES, null);
304 msoLogger.error(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR,
305 MSO_PROP_APIHANDLER_INFRA, "", "",
306 MsoLogger.ErrorCode.BusinessProcesssError,
307 "Null response from BPEL");
308 msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR,
309 MsoLogger.ResponseCode.InternalError,
310 "Null response from BPMN");
311 msoLogger.debug("End of the transaction, the final response is: "
312 + (String) resp.getEntity());
316 ResponseHandler respHandler = new ResponseHandler(response,
317 requestClient.getType());
318 int bpelStatus = respHandler.getStatus();
320 // BPEL accepted the request, the request is in progress
321 if (bpelStatus == HttpStatus.SC_ACCEPTED) {
322 String camundaJSONResponseBody = respHandler.getResponseBody();
324 .debug("Received from Camunda: " + camundaJSONResponseBody);
325 (RequestsDatabase.getInstance()).updateInfraStatus(requestId,
326 Status.IN_PROGRESS.toString(),
327 Constants.PROGRESS_REQUEST_IN_PROGRESS,
328 Constants.MODIFIED_BY_APIHANDLER);
330 msoLogger.recordAuditEvent(startTime,
331 MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc,
332 "BPMN accepted the request, the request is in progress");
333 msoLogger.debug("End of the transaction, the final response is: "
334 + (String) camundaJSONResponseBody);
335 return Response.status(HttpStatus.SC_ACCEPTED)
336 .entity(camundaJSONResponseBody).build();
338 List<String> variables = new ArrayList<String>();
339 variables.add(bpelStatus + "");
340 String camundaJSONResponseBody = respHandler.getResponseBody();
341 if (camundaJSONResponseBody != null
342 && !camundaJSONResponseBody.isEmpty()) {
343 Response resp = msoRequest.buildServiceErrorResponse(
344 bpelStatus, MsoException.ServiceException,
345 "Request Failed due to BPEL error with HTTP Status= %1 "
346 + '\n' + camundaJSONResponseBody,
347 ErrorNumbers.SVC_DETAILED_SERVICE_ERROR, variables);
348 msoLogger.error(MessageEnum.APIH_BPEL_RESPONSE_ERROR,
349 requestClient.getUrl(), "", "",
350 MsoLogger.ErrorCode.BusinessProcesssError,
351 "Response from BPEL engine is failed with HTTP Status="
353 msoLogger.recordAuditEvent(startTime,
354 MsoLogger.StatusCode.ERROR,
355 MsoLogger.ResponseCode.InternalError,
356 "Response from BPMN engine is failed");
358 .debug("End of the transaction, the final response is: "
359 + (String) resp.getEntity());
362 Response resp = msoRequest
363 .buildServiceErrorResponse(
365 MsoException.ServiceException,
366 "Request Failed due to BPEL error with HTTP Status= %1",
367 ErrorNumbers.SVC_DETAILED_SERVICE_ERROR,
369 msoLogger.error(MessageEnum.APIH_BPEL_RESPONSE_ERROR,
370 requestClient.getUrl(), "", "",
371 MsoLogger.ErrorCode.BusinessProcesssError,
372 "Response from BPEL engine is empty");
373 msoLogger.recordAuditEvent(startTime,
374 MsoLogger.StatusCode.ERROR,
375 MsoLogger.ResponseCode.InternalError,
376 "Response from BPEL engine is empty");
378 .debug("End of the transaction, the final response is: "
379 + (String) resp.getEntity());
385 private RecipeLookupResult getServiceInstanceOrchestrationURI(
386 CatalogDatabase db, E2EServiceInstanceRequest sir, Action action) {
388 RecipeLookupResult recipeLookupResult = null;
390 recipeLookupResult = getServiceURI(db, sir, action);
392 if (recipeLookupResult != null) {
393 msoLogger.debug ("Orchestration URI is: " + recipeLookupResult.getOrchestrationURI() + ", recipe Timeout is: " + Integer.toString(recipeLookupResult.getRecipeTimeout ()));
396 msoLogger.debug("No matching recipe record found");
398 return recipeLookupResult;
401 private RecipeLookupResult getServiceURI(CatalogDatabase db,
402 E2EServiceInstanceRequest sir, Action action) {
404 String defaultServiceModelName = "UUI_DEFAULT";
406 Service serviceRecord = null;
407 ServiceRecipe recipe = null;
409 serviceRecord = db.getServiceByModelName(defaultServiceModelName);
410 recipe = db.getServiceRecipeByModelUUID(serviceRecord.getModelUUID(), action.name());
412 if (recipe == null) {
415 return new RecipeLookupResult(recipe.getOrchestrationUri(),
416 recipe.getRecipeTimeout());
420 private String mappingObtainedRequestJSONToServiceInstanceRequest(E2EServiceInstanceRequest e2eSir){
422 ServiceInstancesRequest sir = new ServiceInstancesRequest();
424 String returnString = null;
425 RequestDetails requestDetails = new RequestDetails();
426 ModelInfo modelInfo = new ModelInfo();
429 modelInfo.setModelInvariantId(e2eSir.getService().getServiceDefId());
432 modelInfo.setModelNameVersionId(e2eSir.getService().getTemplateId());
434 String modelInfoValue = e2eSir.getService().getParameters().getNodeTemplateName();
435 String[] arrayOfInfo = modelInfoValue.split(":");
436 String modelName = arrayOfInfo[0];
437 String modelVersion = arrayOfInfo[1];
440 modelInfo.setModelName(modelName);
443 modelInfo.setModelVersion(modelVersion);
446 //if(ModelType.service.equals(e2eSir.getService().getParameters().getNodeType())){
447 modelInfo.setModelType(ModelType.service);
450 //setting modelInfo to requestDetails
451 requestDetails.setModelInfo(modelInfo);
453 SubscriberInfo subscriberInfo = new SubscriberInfo();
456 subscriberInfo.setGlobalSubscriberId(e2eSir.getService().getParameters().getGlobalSubscriberId());
459 subscriberInfo.setSubscriberName(e2eSir.getService().getParameters().getSubscriberName());
461 //setting subscriberInfo to requestDetails
462 requestDetails.setSubscriberInfo(subscriberInfo);
464 RequestInfo requestInfo = new RequestInfo();
467 requestInfo.setInstanceName(e2eSir.getService().getName());
470 requestInfo.setSource("UUI");
473 requestInfo.setSuppressRollback(true);
475 //setting requestInfo to requestDetails
476 requestDetails.setRequestInfo(requestInfo);
478 RequestParameters requestParameters = new RequestParameters();
480 //subscriptionServiceType
481 requestParameters.setSubscriptionServiceType("MOG");
484 List<E2EUserParam> userParams;
485 userParams = e2eSir.getService().getParameters().getRequestParameters().getUserParams();
486 List<Map<String, String>> userParamList = new ArrayList<>();
487 Map<String,String> userParamMap= new HashMap<>();
488 for(E2EUserParam userp: userParams){
489 userParamMap.put(userp.getName(), userp.getValue());
490 userParamList.add(userParamMap);
493 requestParameters.setUserParams(userParamList);
495 //setting requestParameters to requestDetails
496 requestDetails.setRequestParameters(requestParameters);
498 sir.setRequestDetails(requestDetails);
500 //converting to string
501 ObjectMapper mapper = new ObjectMapper();
503 returnString = mapper.writeValueAsString(sir);
504 } catch (IOException e) {
505 msoLogger.debug("Exception while converting ServiceInstancesRequest object to string", e);