Merge "Added @Override annotation to method signature"
[so.git] / mso-api-handlers / mso-api-handler-infra / src / main / java / org / openecomp / mso / apihandlerinfra / E2EServiceInstances.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
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
10  *
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  *
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.openecomp.mso.apihandlerinfra;
22
23 import java.io.IOException;
24 import java.util.ArrayList;
25 import java.util.HashMap;
26 import java.util.List;
27 import java.util.Map;
28
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;
38
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;
63
64 import com.wordnik.swagger.annotations.Api;
65 import com.wordnik.swagger.annotations.ApiOperation;
66
67 @Path("/e2eServiceInstances")
68 @Api(value="/e2eServiceInstances",description="API Requests for E2E Service Instances")
69 public class E2EServiceInstances {
70
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";
75
76         public E2EServiceInstances() {
77         }
78         
79         /**
80      *POST Requests for E2E Service create Instance on a version provided
81      */
82
83         @POST
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) {
89
90                 Response response = E2EserviceInstances(request, Action.createInstance, null, version);
91
92                 return response;
93         }
94
95         /**
96      *DELETE Requests for E2E Service delete Instance on a specified version and serviceId
97      */
98         
99         @DELETE
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) {
105
106                 instanceIdMap.put("serviceId", serviceId);
107                 Response response = E2EserviceInstances(request, Action.deleteInstance, null, version);
108
109                 return response;
110         }
111         
112         private Response E2EserviceInstances(String requestJSON, Action action,
113                         HashMap<String, String> instanceIdMap, String version) {
114
115                 String requestId = UUIDChecker.generateUUID(msoLogger);
116                 long startTime = System.currentTimeMillis();
117                 msoLogger.debug("requestId is: " + requestId);
118                 E2EServiceInstanceRequest sir = null;
119
120                 MsoRequest msoRequest = new MsoRequest(requestId);
121                 ObjectMapper mapper = new ObjectMapper();
122                 try {
123                         sir = mapper
124                                         .readValue(requestJSON, E2EServiceInstanceRequest.class);
125
126                 } catch (Exception e) {
127
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,
134                                                         null);
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());
143                         return response;
144                 }
145
146                 InfraActiveRequests dup = null;
147                 String instanceName = sir.getService().getName();
148                 String requestScope = sir.getService().getParameters().getNodeType();
149
150                 try {
151                         if(!(instanceName==null && requestScope.equals("service") && (action == Action.createInstance || action == Action.activateInstance))){
152                                 dup = (RequestsDatabase.getInstance()).checkInstanceNameDuplicate (instanceIdMap, instanceName, requestScope);
153                         }
154                 } catch (Exception e) {
155                         msoLogger.error (MessageEnum.APIH_DUPLICATE_CHECK_EXC, MSO_PROP_APIHANDLER_INFRA, "", "", MsoLogger.ErrorCode.DataError, "Error during duplicate check ", e);
156
157                         Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, MsoException.ServiceException,
158                                         e.getMessage(),
159                                         ErrorNumbers.SVC_DETAILED_SERVICE_ERROR,
160                                         null) ;
161
162
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 ());
165                         return response;
166                 }
167
168                 if (dup != null) {
169                         // Found the duplicate record. Return the appropriate error.
170                         String instance = null;
171                         if(instanceName != null){
172                                 instance = instanceName;
173                         }else{
174                                 instance = instanceIdMap.get(requestScope + "InstanceId");
175                         }
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.";
177
178                         Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_CONFLICT, MsoException.ServiceException,
179                                         dupMessage,
180                                         ErrorNumbers.SVC_DETAILED_SERVICE_ERROR,
181                                         null) ;
182
183
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 ());
188                         return response;
189                 }
190
191                 CatalogDatabase db = null;
192                 RecipeLookupResult recipeLookupResult = null;
193                 try {
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,
203                                         null);
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 ());
210                         return response;
211                 } finally {
212                         if(db != null) {
213                             db.close();
214                         }
215                 }
216
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,
224                                         null);
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 ());
228
229                         return response;
230                 }
231
232
233                 String modelInfo = sir.getService().getParameters().getNodeTemplateName();
234                 String[] arrayOfInfo = modelInfo.split(":");
235                 String serviceInstanceType = arrayOfInfo[0];
236
237
238
239                 String serviceId = "";
240
241                 RequestClient requestClient = null;
242                 HttpResponse response = null;
243
244                 long subStartTime = System.currentTimeMillis();
245                 String sirRequestJson = mappingObtainedRequestJSONToServiceInstanceRequest(sir);
246
247                 try {
248                         requestClient = RequestClientFactory.getRequestClient (recipeLookupResult.getOrchestrationURI (), MsoPropertiesUtils.loadMsoProperties ());
249
250                         // Capture audit event
251                         msoLogger.debug ("MSO API Handler Posting call to BPEL engine for url: " + requestClient.getUrl ());
252
253                         response = requestClient.post(requestId, false,
254                                         recipeLookupResult.getRecipeTimeout(),
255                                         action.name(), serviceId, null, null, null, null, serviceInstanceType,
256                                         null, null, null, sirRequestJson);
257
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());
284                         return resp;
285                 }
286
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());
301                         return resp;
302                 }
303
304                 ResponseHandler respHandler = new ResponseHandler(response,
305                                 requestClient.getType());
306                 int bpelStatus = respHandler.getStatus();
307
308                 // BPEL accepted the request, the request is in progress
309                 if (bpelStatus == HttpStatus.SC_ACCEPTED) {
310                         String camundaJSONResponseBody = respHandler.getResponseBody();
311                         msoLogger
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);
317
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();
325                 } else {
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="
340                                                                 + bpelStatus);
341                                 msoLogger.recordAuditEvent(startTime,
342                                                 MsoLogger.StatusCode.ERROR,
343                                                 MsoLogger.ResponseCode.InternalError,
344                                                 "Response from BPMN engine is failed");
345                                 msoLogger
346                                 .debug("End of the transaction, the final response is: "
347                                                 + (String) resp.getEntity());
348                                 return resp;
349                         } else {
350                                 Response resp = msoRequest
351                                                 .buildServiceErrorResponse(
352                                                                 bpelStatus,
353                                                                 MsoException.ServiceException,
354                                                                 "Request Failed due to BPEL error with HTTP Status= %1",
355                                                                 ErrorNumbers.SVC_DETAILED_SERVICE_ERROR,
356                                                                 variables);
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");
365                                 msoLogger
366                                 .debug("End of the transaction, the final response is: "
367                                                 + (String) resp.getEntity());
368                                 return resp;
369                         }
370                 }
371         }
372
373         private RecipeLookupResult getServiceInstanceOrchestrationURI(
374                         CatalogDatabase db, E2EServiceInstanceRequest sir, Action action) {
375
376                 RecipeLookupResult recipeLookupResult = null;
377
378                 recipeLookupResult = getServiceURI(db, sir, action);
379
380                 if (recipeLookupResult != null) {
381                         msoLogger.debug ("Orchestration URI is: " + recipeLookupResult.getOrchestrationURI() + ", recipe Timeout is: " + Integer.toString(recipeLookupResult.getRecipeTimeout ()));
382                 }
383                 else {
384                         msoLogger.debug("No matching recipe record found");
385                 }
386                 return recipeLookupResult;
387         }
388
389         private RecipeLookupResult getServiceURI(CatalogDatabase db,
390                         E2EServiceInstanceRequest sir, Action action) {
391
392                 String defaultServiceModelName = "UUI_DEFAULT";
393
394                 Service serviceRecord = null;
395                 ServiceRecipe recipe = null;
396
397                 serviceRecord = db.getServiceByModelName(defaultServiceModelName);
398                 recipe = db.getServiceRecipeByModelUUID(serviceRecord.getModelUUID(), action.name());
399
400                 if (recipe == null) {
401                         return null;
402                 }
403                 return new RecipeLookupResult(recipe.getOrchestrationUri(),
404                                 recipe.getRecipeTimeout());
405
406         }
407
408         private String mappingObtainedRequestJSONToServiceInstanceRequest(E2EServiceInstanceRequest e2eSir){
409
410                 ServiceInstancesRequest sir = new ServiceInstancesRequest();
411
412                 String returnString = null;
413                 RequestDetails requestDetails = new RequestDetails();
414                 ModelInfo modelInfo = new ModelInfo();
415                 
416                 //ModelInvariantId
417                 modelInfo.setModelInvariantId(e2eSir.getService().getServiceDefId());
418                 
419                 //modelNameVersionId
420                 modelInfo.setModelNameVersionId(e2eSir.getService().getTemplateId());
421                 
422                 String modelInfoValue = e2eSir.getService().getParameters().getNodeTemplateName();
423                 String[] arrayOfInfo = modelInfoValue.split(":");
424                 String modelName = arrayOfInfo[0];
425                 String modelVersion = arrayOfInfo[1];
426                 
427                 //modelName
428                 modelInfo.setModelName(modelName);
429                 
430                 //modelVersion
431                 modelInfo.setModelVersion(modelVersion);
432                 
433                 //modelType
434                 //if(ModelType.service.equals(e2eSir.getService().getParameters().getNodeType())){
435                         modelInfo.setModelType(ModelType.service);
436                 //}
437                 
438                 //setting modelInfo to requestDetails
439                 requestDetails.setModelInfo(modelInfo);
440                 
441                 SubscriberInfo subscriberInfo = new SubscriberInfo();
442
443                 //globalsubscriberId
444                 subscriberInfo.setGlobalSubscriberId(e2eSir.getService().getParameters().getGlobalSubscriberId());
445
446                 //subscriberName
447                 subscriberInfo.setSubscriberName(e2eSir.getService().getParameters().getSubscriberName());
448                 
449                 //setting subscriberInfo to requestDetails
450                 requestDetails.setSubscriberInfo(subscriberInfo);
451                 
452                 RequestInfo requestInfo = new RequestInfo();
453                 
454                 //instanceName
455                 requestInfo.setInstanceName(e2eSir.getService().getName());
456
457                 //source
458                 requestInfo.setSource("UUI");
459
460                 //suppressRollback
461                 requestInfo.setSuppressRollback(true);
462
463                 //setting requestInfo to requestDetails
464                 requestDetails.setRequestInfo(requestInfo);
465                 
466                 RequestParameters requestParameters = new RequestParameters();
467                 
468                 //subscriptionServiceType
469                 requestParameters.setSubscriptionServiceType("MOG");
470
471                 //Userparams
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);
479                 }
480
481                 requestParameters.setUserParams(userParamList);
482                 
483                 //setting requestParameters to requestDetails
484                 requestDetails.setRequestParameters(requestParameters);
485                 
486                 sir.setRequestDetails(requestDetails);
487
488                 //converting to string
489                 ObjectMapper mapper = new ObjectMapper();
490                 try {
491                         returnString = mapper.writeValueAsString(sir);
492                 } catch (IOException e) {
493                         msoLogger.debug("Exception while converting ServiceInstancesRequest object to string", e);
494                 }
495
496                 return returnString;
497         }
498 }