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 Response response = E2EserviceInstances(request, Action.createInstance, null, version);
96 *DELETE Requests for E2E Service delete Instance on a specified version and serviceId
100 @Path("/{version:[vV][3-5]}/{serviceId}")
101 @Consumes(MediaType.APPLICATION_JSON)
102 @Produces(MediaType.APPLICATION_JSON)
103 @ApiOperation(value="Delete E2E Service Instance on a specified version and serviceId",response=Response.class)
104 public Response deleteE2EServiceInstance(String request, @PathParam("version") String version, @PathParam("serviceId") String serviceId) {
106 instanceIdMap.put("serviceId", serviceId);
107 Response response = E2EserviceInstances(request, Action.deleteInstance, null, version);
112 private Response E2EserviceInstances(String requestJSON, Action action,
113 HashMap<String, String> instanceIdMap, String version) {
115 String requestId = UUIDChecker.generateUUID(msoLogger);
116 long startTime = System.currentTimeMillis();
117 msoLogger.debug("requestId is: " + requestId);
118 E2EServiceInstanceRequest sir = null;
120 MsoRequest msoRequest = new MsoRequest(requestId);
121 ObjectMapper mapper = new ObjectMapper();
124 .readValue(requestJSON, E2EServiceInstanceRequest.class);
126 } catch (Exception e) {
128 msoLogger.debug("Mapping of request to JSON object failed : ", e);
129 Response response = msoRequest.buildServiceErrorResponse(
130 HttpStatus.SC_BAD_REQUEST,
131 MsoException.ServiceException,
132 "Mapping of request to JSON object failed. "
133 + e.getMessage(), ErrorNumbers.SVC_BAD_PARAMETER,
135 msoLogger.error(MessageEnum.APIH_REQUEST_VALIDATION_ERROR,
136 MSO_PROP_APIHANDLER_INFRA, "", "",
137 MsoLogger.ErrorCode.SchemaError, requestJSON, e);
138 msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR,
139 MsoLogger.ResponseCode.SchemaError,
140 "Mapping of request to JSON object failed");
141 msoLogger.debug("End of the transaction, the final response is: "
142 + (String) response.getEntity());
146 InfraActiveRequests dup = null;
147 String instanceName = sir.getService().getName();
148 String requestScope = sir.getService().getParameters().getNodeType();
151 if(!(instanceName==null && requestScope.equals("service") && (action == Action.createInstance || action == Action.activateInstance))){
152 dup = (RequestsDatabase.getInstance()).checkInstanceNameDuplicate (instanceIdMap, instanceName, requestScope);
154 } catch (Exception e) {
155 msoLogger.error (MessageEnum.APIH_DUPLICATE_CHECK_EXC, MSO_PROP_APIHANDLER_INFRA, "", "", MsoLogger.ErrorCode.DataError, "Error during duplicate check ", e);
157 Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, MsoException.ServiceException,
159 ErrorNumbers.SVC_DETAILED_SERVICE_ERROR,
163 msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.DBAccessError, "Error during duplicate check");
164 msoLogger.debug ("End of the transaction, the final response is: " + (String) response.getEntity ());
169 // Found the duplicate record. Return the appropriate error.
170 String instance = null;
171 if(instanceName != null){
172 instance = instanceName;
174 instance = instanceIdMap.get(requestScope + "InstanceId");
176 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.";
178 Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_CONFLICT, MsoException.ServiceException,
180 ErrorNumbers.SVC_DETAILED_SERVICE_ERROR,
184 msoLogger.warn (MessageEnum.APIH_DUPLICATE_FOUND, dupMessage, "", "", MsoLogger.ErrorCode.SchemaError, "Duplicate request - Subscriber already has a request for this service");
185 msoRequest.createRequestRecord (Status.FAILED, action);
186 msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.Conflict, dupMessage);
187 msoLogger.debug ("End of the transaction, the final response is: " + (String) response.getEntity ());
191 CatalogDatabase db = null;
192 RecipeLookupResult recipeLookupResult = null;
194 db = CatalogDatabase.getInstance();
195 recipeLookupResult = getServiceInstanceOrchestrationURI(db, sir, action);
196 } catch (Exception e) {
197 msoLogger.error (MessageEnum.APIH_DB_ACCESS_EXC, MSO_PROP_APIHANDLER_INFRA, "", "", MsoLogger.ErrorCode.AvailabilityError, "Exception while communciate with Catalog DB", e);
198 msoRequest.setStatus (org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);
199 Response response = msoRequest.buildServiceErrorResponse (HttpStatus.SC_NOT_FOUND,
200 MsoException.ServiceException,
201 "No communication to catalog DB " + e.getMessage (),
202 ErrorNumbers.SVC_NO_SERVER_RESOURCES,
204 alarmLogger.sendAlarm ("MsoDatabaseAccessError",
205 MsoAlarmLogger.CRITICAL,
206 Messages.errors.get (ErrorNumbers.NO_COMMUNICATION_TO_CATALOG_DB));
207 msoRequest.createRequestRecord (Status.FAILED,action);
208 msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.DBAccessError, "Exception while communciate with DB");
209 msoLogger.debug ("End of the transaction, the final response is: " + (String) response.getEntity ());
217 if (recipeLookupResult == null) {
218 msoLogger.error (MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND, MSO_PROP_APIHANDLER_INFRA, "", "", MsoLogger.ErrorCode.DataError, "No recipe found in DB");
219 msoRequest.setStatus (org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);
220 Response response = msoRequest.buildServiceErrorResponse (HttpStatus.SC_NOT_FOUND,
221 MsoException.ServiceException,
222 "Recipe does not exist in catalog DB",
223 ErrorNumbers.SVC_GENERAL_SERVICE_ERROR,
225 msoRequest.createRequestRecord (Status.FAILED, action);
226 msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.DataNotFound, "No recipe found in DB");
227 msoLogger.debug ("End of the transaction, the final response is: " + (String) response.getEntity ());
233 String modelInfo = sir.getService().getParameters().getNodeTemplateName();
234 String[] arrayOfInfo = modelInfo.split(":");
235 String serviceInstanceType = arrayOfInfo[0];
239 String serviceId = "";
241 RequestClient requestClient = null;
242 HttpResponse response = null;
244 long subStartTime = System.currentTimeMillis();
245 String sirRequestJson = mappingObtainedRequestJSONToServiceInstanceRequest(sir);
248 requestClient = RequestClientFactory.getRequestClient (recipeLookupResult.getOrchestrationURI (), MsoPropertiesUtils.loadMsoProperties ());
250 // Capture audit event
251 msoLogger.debug ("MSO API Handler Posting call to BPEL engine for url: " + requestClient.getUrl ());
253 response = requestClient.post(requestId, false,
254 recipeLookupResult.getRecipeTimeout(),
255 action.name(), serviceId, null, null, null, null, serviceInstanceType,
256 null, null, null, sirRequestJson);
258 msoLogger.recordMetricEvent(subStartTime,
259 MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc,
260 "Successfully received response from BPMN engine", "BPMN",
261 recipeLookupResult.getOrchestrationURI(), null);
262 } catch (Exception e) {
263 msoLogger.recordMetricEvent(subStartTime,
264 MsoLogger.StatusCode.ERROR,
265 MsoLogger.ResponseCode.CommunicationError,
266 "Exception while communicate with BPMN engine", "BPMN",
267 recipeLookupResult.getOrchestrationURI(), null);
268 Response resp = msoRequest.buildServiceErrorResponse(
269 HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException,
270 "Failed calling bpmn " + e.getMessage(),
271 ErrorNumbers.SVC_NO_SERVER_RESOURCES, null);
272 alarmLogger.sendAlarm("MsoConfigurationError",
273 MsoAlarmLogger.CRITICAL,
274 Messages.errors.get(ErrorNumbers.NO_COMMUNICATION_TO_BPEL));
275 msoLogger.error(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR,
276 MSO_PROP_APIHANDLER_INFRA, "", "",
277 MsoLogger.ErrorCode.AvailabilityError,
278 "Exception while communicate with BPMN engine");
279 msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR,
280 MsoLogger.ResponseCode.CommunicationError,
281 "Exception while communicate with BPMN engine");
282 msoLogger.debug("End of the transaction, the final response is: "
283 + (String) resp.getEntity());
287 if (response == null) {
288 Response resp = msoRequest.buildServiceErrorResponse(
289 HttpStatus.SC_BAD_GATEWAY, MsoException.ServiceException,
290 "bpelResponse is null",
291 ErrorNumbers.SVC_NO_SERVER_RESOURCES, null);
292 msoLogger.error(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR,
293 MSO_PROP_APIHANDLER_INFRA, "", "",
294 MsoLogger.ErrorCode.BusinessProcesssError,
295 "Null response from BPEL");
296 msoLogger.recordAuditEvent(startTime, MsoLogger.StatusCode.ERROR,
297 MsoLogger.ResponseCode.InternalError,
298 "Null response from BPMN");
299 msoLogger.debug("End of the transaction, the final response is: "
300 + (String) resp.getEntity());
304 ResponseHandler respHandler = new ResponseHandler(response,
305 requestClient.getType());
306 int bpelStatus = respHandler.getStatus();
308 // BPEL accepted the request, the request is in progress
309 if (bpelStatus == HttpStatus.SC_ACCEPTED) {
310 String camundaJSONResponseBody = respHandler.getResponseBody();
312 .debug("Received from Camunda: " + camundaJSONResponseBody);
313 (RequestsDatabase.getInstance()).updateInfraStatus(requestId,
314 Status.IN_PROGRESS.toString(),
315 Constants.PROGRESS_REQUEST_IN_PROGRESS,
316 Constants.MODIFIED_BY_APIHANDLER);
318 msoLogger.recordAuditEvent(startTime,
319 MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc,
320 "BPMN accepted the request, the request is in progress");
321 msoLogger.debug("End of the transaction, the final response is: "
322 + (String) camundaJSONResponseBody);
323 return Response.status(HttpStatus.SC_ACCEPTED)
324 .entity(camundaJSONResponseBody).build();
326 List<String> variables = new ArrayList<String>();
327 variables.add(bpelStatus + "");
328 String camundaJSONResponseBody = respHandler.getResponseBody();
329 if (camundaJSONResponseBody != null
330 && !camundaJSONResponseBody.isEmpty()) {
331 Response resp = msoRequest.buildServiceErrorResponse(
332 bpelStatus, MsoException.ServiceException,
333 "Request Failed due to BPEL error with HTTP Status= %1 "
334 + '\n' + camundaJSONResponseBody,
335 ErrorNumbers.SVC_DETAILED_SERVICE_ERROR, variables);
336 msoLogger.error(MessageEnum.APIH_BPEL_RESPONSE_ERROR,
337 requestClient.getUrl(), "", "",
338 MsoLogger.ErrorCode.BusinessProcesssError,
339 "Response from BPEL engine is failed with HTTP Status="
341 msoLogger.recordAuditEvent(startTime,
342 MsoLogger.StatusCode.ERROR,
343 MsoLogger.ResponseCode.InternalError,
344 "Response from BPMN engine is failed");
346 .debug("End of the transaction, the final response is: "
347 + (String) resp.getEntity());
350 Response resp = msoRequest
351 .buildServiceErrorResponse(
353 MsoException.ServiceException,
354 "Request Failed due to BPEL error with HTTP Status= %1",
355 ErrorNumbers.SVC_DETAILED_SERVICE_ERROR,
357 msoLogger.error(MessageEnum.APIH_BPEL_RESPONSE_ERROR,
358 requestClient.getUrl(), "", "",
359 MsoLogger.ErrorCode.BusinessProcesssError,
360 "Response from BPEL engine is empty");
361 msoLogger.recordAuditEvent(startTime,
362 MsoLogger.StatusCode.ERROR,
363 MsoLogger.ResponseCode.InternalError,
364 "Response from BPEL engine is empty");
366 .debug("End of the transaction, the final response is: "
367 + (String) resp.getEntity());
373 private RecipeLookupResult getServiceInstanceOrchestrationURI(
374 CatalogDatabase db, E2EServiceInstanceRequest sir, Action action) {
376 RecipeLookupResult recipeLookupResult = null;
378 recipeLookupResult = getServiceURI(db, sir, action);
380 if (recipeLookupResult != null) {
381 msoLogger.debug ("Orchestration URI is: " + recipeLookupResult.getOrchestrationURI() + ", recipe Timeout is: " + Integer.toString(recipeLookupResult.getRecipeTimeout ()));
384 msoLogger.debug("No matching recipe record found");
386 return recipeLookupResult;
389 private RecipeLookupResult getServiceURI(CatalogDatabase db,
390 E2EServiceInstanceRequest sir, Action action) {
392 String defaultServiceModelName = "UUI_DEFAULT";
394 Service serviceRecord = null;
395 ServiceRecipe recipe = null;
397 serviceRecord = db.getServiceByModelName(defaultServiceModelName);
398 recipe = db.getServiceRecipeByModelUUID(serviceRecord.getModelUUID(), action.name());
400 if (recipe == null) {
403 return new RecipeLookupResult(recipe.getOrchestrationUri(),
404 recipe.getRecipeTimeout());
408 private String mappingObtainedRequestJSONToServiceInstanceRequest(E2EServiceInstanceRequest e2eSir){
410 ServiceInstancesRequest sir = new ServiceInstancesRequest();
412 String returnString = null;
413 RequestDetails requestDetails = new RequestDetails();
414 ModelInfo modelInfo = new ModelInfo();
417 modelInfo.setModelInvariantId(e2eSir.getService().getServiceDefId());
420 modelInfo.setModelNameVersionId(e2eSir.getService().getTemplateId());
422 String modelInfoValue = e2eSir.getService().getParameters().getNodeTemplateName();
423 String[] arrayOfInfo = modelInfoValue.split(":");
424 String modelName = arrayOfInfo[0];
425 String modelVersion = arrayOfInfo[1];
428 modelInfo.setModelName(modelName);
431 modelInfo.setModelVersion(modelVersion);
434 //if(ModelType.service.equals(e2eSir.getService().getParameters().getNodeType())){
435 modelInfo.setModelType(ModelType.service);
438 //setting modelInfo to requestDetails
439 requestDetails.setModelInfo(modelInfo);
441 SubscriberInfo subscriberInfo = new SubscriberInfo();
444 subscriberInfo.setGlobalSubscriberId(e2eSir.getService().getParameters().getGlobalSubscriberId());
447 subscriberInfo.setSubscriberName(e2eSir.getService().getParameters().getSubscriberName());
449 //setting subscriberInfo to requestDetails
450 requestDetails.setSubscriberInfo(subscriberInfo);
452 RequestInfo requestInfo = new RequestInfo();
455 requestInfo.setInstanceName(e2eSir.getService().getName());
458 requestInfo.setSource("UUI");
461 requestInfo.setSuppressRollback(true);
463 //setting requestInfo to requestDetails
464 requestDetails.setRequestInfo(requestInfo);
466 RequestParameters requestParameters = new RequestParameters();
468 //subscriptionServiceType
469 requestParameters.setSubscriptionServiceType("MOG");
472 List<E2EUserParam> userParams = new ArrayList<>();
473 userParams = e2eSir.getService().getParameters().getRequestParameters().getUserParams();
474 List<Map<String, String>> userParamList = new ArrayList<Map<String,String>>();
475 Map<String,String> userParamMap= new HashMap<String, String>();
476 for(E2EUserParam userp: userParams){
477 userParamMap.put(userp.getName(), userp.getValue());
478 userParamList.add(userParamMap);
481 requestParameters.setUserParams(userParamList);
483 //setting requestParameters to requestDetails
484 requestDetails.setRequestParameters(requestParameters);
486 sir.setRequestDetails(requestDetails);
488 //converting to string
489 ObjectMapper mapper = new ObjectMapper();
491 returnString = mapper.writeValueAsString(sir);
492 } catch (IOException e) {
493 msoLogger.debug("Exception while converting ServiceInstancesRequest object to string", e);