fixed for defect SO-70 - recipe lookup mechanism doesn't allow to define default...
[so.git] / mso-api-handlers / mso-api-handler-infra / src / main / java / org / openecomp / mso / apihandlerinfra / ServiceInstances.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * OPENECOMP - MSO
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. 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 package org.openecomp.mso.apihandlerinfra;
21
22 import java.util.ArrayList;
23 import java.util.HashMap;
24 import java.util.List;
25
26 import javax.ws.rs.Consumes;
27 import javax.ws.rs.DELETE;
28 import javax.ws.rs.POST;
29 import javax.ws.rs.PUT;
30 import javax.ws.rs.Path;
31 import javax.ws.rs.PathParam;
32 import javax.ws.rs.Produces;
33 import javax.ws.rs.core.MediaType;
34 import javax.ws.rs.core.Response;
35
36 import org.apache.http.HttpResponse;
37 import org.apache.http.HttpStatus;
38 import org.codehaus.jackson.map.ObjectMapper;
39
40 import org.openecomp.mso.apihandler.common.*;
41 import org.openecomp.mso.apihandlerinfra.serviceinstancebeans.*;
42 import org.openecomp.mso.db.catalog.CatalogDatabase;
43 import org.openecomp.mso.db.catalog.beans.*;
44 import org.openecomp.mso.logger.MessageEnum;
45 import org.openecomp.mso.logger.MsoAlarmLogger;
46 import org.openecomp.mso.logger.MsoLogger;
47 import org.openecomp.mso.properties.MsoJavaProperties;
48 import org.openecomp.mso.properties.MsoPropertiesFactory;
49 import org.openecomp.mso.requestsdb.InfraActiveRequests;
50 import org.openecomp.mso.requestsdb.RequestsDatabase;
51 import org.openecomp.mso.utils.UUIDChecker;
52
53 @Path("/serviceInstances/{version:[vV][2-3]}")
54 public class ServiceInstances {
55
56     private HashMap<String, String> instanceIdMap = new HashMap<String,String>();
57
58     private static MsoLogger msoLogger = MsoLogger.getMsoLogger (MsoLogger.Catalog.APIH);
59
60     private static MsoAlarmLogger alarmLogger = new MsoAlarmLogger ();
61
62     public final static String MSO_PROP_APIHANDLER_INFRA = "MSO_PROP_APIHANDLER_INFRA";
63
64     private static MsoJavaProperties props = MsoPropertiesUtils.loadMsoProperties ();
65
66     /**
67          *
68          */
69         public ServiceInstances() {
70                 // TODO Auto-generated constructor stub
71         }
72
73         @POST
74         @Path("/")
75         @Consumes(MediaType.APPLICATION_JSON)
76         @Produces(MediaType.APPLICATION_JSON)
77         public Response createServiceInstance(String request, @PathParam("version") String version) {
78
79                 Response response = serviceInstances(request, Action.createInstance, null, version);
80
81                 return response;
82         }
83
84         @DELETE
85         @Path("/{serviceInstanceId}")
86         @Consumes(MediaType.APPLICATION_JSON)
87         @Produces(MediaType.APPLICATION_JSON)
88         public Response deleteServiceInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId) {
89
90                 instanceIdMap.put("serviceInstanceId", serviceInstanceId);
91                 Response response = serviceInstances(request, Action.deleteInstance, instanceIdMap, version);
92                 return response;
93         }
94
95         @POST
96         @Path("/{serviceInstanceId}/vnfs")
97         @Consumes(MediaType.APPLICATION_JSON)
98         @Produces(MediaType.APPLICATION_JSON)
99         public Response createVnfInstance(String request,  @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId) {
100         msoLogger.debug ("version is: " + version);
101                 instanceIdMap.put("serviceInstanceId", serviceInstanceId);
102                 Response response = serviceInstances(request, Action.createInstance, instanceIdMap, version);
103
104                 return response;
105         }
106
107         @DELETE
108         @Path("/{serviceInstanceId}/vnfs/{vnfInstanceId}")
109         @Consumes(MediaType.APPLICATION_JSON)
110         @Produces(MediaType.APPLICATION_JSON)
111         public Response deleteVnfInstance(String request,  @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId,
112                                                                                                           @PathParam("vnfInstanceId") String vnfInstanceId) {
113
114                 instanceIdMap.put("serviceInstanceId", serviceInstanceId);
115                 instanceIdMap.put("vnfInstanceId", vnfInstanceId);
116                 Response response = serviceInstances(request, Action.deleteInstance, instanceIdMap, version);
117
118                 return response;
119         }
120
121         @POST
122         @Path("/{serviceInstanceId}/vnfs/{vnfInstanceId}/vfModules")
123         @Consumes(MediaType.APPLICATION_JSON)
124         @Produces(MediaType.APPLICATION_JSON)
125         public Response createVfModuleInstance(String request,  @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId,
126                                                                                                                    @PathParam("vnfInstanceId") String vnfInstanceId) {
127         msoLogger.debug ("version is: " + version);
128                 instanceIdMap.put("serviceInstanceId", serviceInstanceId);
129                 instanceIdMap.put("vnfInstanceId", vnfInstanceId);
130                 Response response = serviceInstances(request, Action.createInstance, instanceIdMap, version);
131
132                 return response;
133         }
134
135         @PUT
136         @Path("/{serviceInstanceId}/vnfs/{vnfInstanceId}/vfModules/{vfmoduleInstanceId}")
137         @Consumes(MediaType.APPLICATION_JSON)
138         @Produces(MediaType.APPLICATION_JSON)
139         public Response updateVfModuleInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId,
140                                                                                                                    @PathParam("vnfInstanceId") String vnfInstanceId,
141                                                                                                                    @PathParam("vfmoduleInstanceId") String vfmoduleInstanceId) {
142
143                 instanceIdMap.put("serviceInstanceId", serviceInstanceId);
144                 instanceIdMap.put("vnfInstanceId", vnfInstanceId);
145                 instanceIdMap.put("vfModuleInstanceId", vfmoduleInstanceId);
146                 Response response = serviceInstances(request, Action.updateInstance, instanceIdMap, version);
147
148                 return response;
149         }
150
151         @DELETE
152         @Path("/{serviceInstanceId}/vnfs/{vnfInstanceId}/vfModules/{vfmoduleInstanceId}")
153         @Consumes(MediaType.APPLICATION_JSON)
154         @Produces(MediaType.APPLICATION_JSON)
155         public Response deleteVfModuleInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId,
156                                                                                                                                                 @PathParam("vnfInstanceId") String vnfInstanceId,
157                                                                                                                                                 @PathParam("vfmoduleInstanceId") String vfmoduleInstanceId) {
158
159
160                 instanceIdMap.put("serviceInstanceId", serviceInstanceId);
161                 instanceIdMap.put("vnfInstanceId", vnfInstanceId);
162                 instanceIdMap.put("vfModuleInstanceId", vfmoduleInstanceId);
163                 Response response = serviceInstances(request, Action.deleteInstance, instanceIdMap, version);
164
165                 return response;
166         }
167
168
169         @POST
170         @Path("/{serviceInstanceId}/vnfs/{vnfInstanceId}/volumeGroups")
171         @Consumes(MediaType.APPLICATION_JSON)
172         @Produces(MediaType.APPLICATION_JSON)
173         public Response createVolumeGroupInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId,
174                                                                                        @PathParam("vnfInstanceId") String vnfInstanceId) {
175
176                 instanceIdMap.put("serviceInstanceId", serviceInstanceId);
177                 instanceIdMap.put("vnfInstanceId", vnfInstanceId);
178                 Response response = serviceInstances(request, Action.createInstance, instanceIdMap, version);
179
180                 return response;
181         }
182
183         @PUT
184         @Path("/{serviceInstanceId}/vnfs/{vnfInstanceId}/volumeGroups/{volumeGroupInstanceId}")
185         @Consumes(MediaType.APPLICATION_JSON)
186         @Produces(MediaType.APPLICATION_JSON)
187         public Response updateVolumeGroupInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId,
188                                                                                                                                                    @PathParam("vnfInstanceId") String vnfInstanceId,
189                                                                                                                                                    @PathParam("volumeGroupInstanceId") String volumeGroupInstanceId) {
190
191
192                 instanceIdMap.put("serviceInstanceId", serviceInstanceId);
193                 instanceIdMap.put("vnfInstanceId", vnfInstanceId);
194                 instanceIdMap.put("volumeGroupInstanceId", volumeGroupInstanceId);
195                 Response response = serviceInstances(request, Action.updateInstance, instanceIdMap, version);
196
197                 return response;
198         }
199
200         @DELETE
201         @Path("/{serviceInstanceId}/vnfs/{vnfInstanceId}/volumeGroups/{volumeGroupInstanceId}")
202         @Consumes(MediaType.APPLICATION_JSON)
203         @Produces(MediaType.APPLICATION_JSON)
204         public Response deleteVolumeGroupInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId,
205                                                                                                                                                    @PathParam("vnfInstanceId") String vnfInstanceId,
206                                                                                                                                                    @PathParam("volumeGroupInstanceId") String volumeGroupInstanceId) {
207
208
209                 instanceIdMap.put("serviceInstanceId", serviceInstanceId);
210                 instanceIdMap.put("vnfInstanceId", vnfInstanceId);
211                 instanceIdMap.put("volumeGroupInstanceId", volumeGroupInstanceId);
212                 Response response = serviceInstances(request, Action.deleteInstance, instanceIdMap, version);
213
214                 return response;
215         }
216
217         @POST
218         @Path("/{serviceInstanceId}/networks")
219         @Consumes(MediaType.APPLICATION_JSON)
220         @Produces(MediaType.APPLICATION_JSON)
221         public Response createNetworkInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId) {
222
223                 instanceIdMap.put("serviceInstanceId", serviceInstanceId);
224                 Response response = serviceInstances(request, Action.createInstance, instanceIdMap, version);
225
226                 return response;
227         }
228
229         @PUT
230         @Path("/{serviceInstanceId}/networks/{networkInstanceId}")
231         @Consumes(MediaType.APPLICATION_JSON)
232         @Produces(MediaType.APPLICATION_JSON)
233         public Response updateNetworkInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId,
234                                                                                                                                            @PathParam("networkInstanceId") String networkInstanceId) {
235
236                 instanceIdMap.put("serviceInstanceId", serviceInstanceId);
237                 instanceIdMap.put("networkInstanceId", networkInstanceId);
238                 Response response = serviceInstances(request, Action.updateInstance, instanceIdMap, version);
239
240                 return response;
241         }
242
243         @DELETE
244         @Path("/{serviceInstanceId}/networks/{networkInstanceId}")
245         @Consumes(MediaType.APPLICATION_JSON)
246         @Produces(MediaType.APPLICATION_JSON)
247         public Response deleteNetworkInstance(String request, @PathParam("version") String version, @PathParam("serviceInstanceId") String serviceInstanceId,
248                                                                                                                                            @PathParam("networkInstanceId") String networkInstanceId) {
249
250                 instanceIdMap.put("serviceInstanceId", serviceInstanceId);
251                 instanceIdMap.put("networkInstanceId", networkInstanceId);
252                 Response response = serviceInstances(request, Action.deleteInstance, instanceIdMap, version);
253
254                 return response;
255         }
256
257
258
259         private Response serviceInstances(String requestJSON, Action action, HashMap<String,String> instanceIdMap, String version) {
260
261            String requestId = UUIDChecker.generateUUID(msoLogger);
262            long startTime = System.currentTimeMillis ();
263            msoLogger.debug ("requestId is: " + requestId);
264            ServiceInstancesRequest sir = null;
265
266            MsoRequest msoRequest = new MsoRequest (requestId);
267
268
269            try{
270         ObjectMapper mapper = new ObjectMapper();
271         sir = mapper.readValue(requestJSON, ServiceInstancesRequest.class);
272
273        } catch(Exception e){
274            msoLogger.debug ("Mapping of request to JSON object failed : ", e);
275            Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST, MsoException.ServiceException,
276                    "Mapping of request to JSON object failed.  " + e.getMessage(),
277                    ErrorNumbers.SVC_BAD_PARAMETER, null);
278            if (msoRequest.getRequestId () != null) {
279                msoLogger.debug ("Mapping of request to JSON object failed");
280                msoRequest.createRequestRecord (Status.FAILED, action);
281            }
282            msoLogger.error (MessageEnum.APIH_REQUEST_VALIDATION_ERROR, MSO_PROP_APIHANDLER_INFRA, "", "", MsoLogger.ErrorCode.SchemaError, requestJSON, e);
283            msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.SchemaError, "Mapping of request to JSON object failed");
284            msoLogger.debug ("End of the transaction, the final response is: " + (String) response.getEntity ());
285            return response;
286        }
287
288
289            try{
290                    msoRequest.parse(sir, instanceIdMap, action, version);
291        } catch (Exception e) {
292            msoLogger.debug ("Validation failed: ", e);
293            Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST, MsoException.ServiceException,
294                    "Error parsing request.  " + e.getMessage(),
295                    ErrorNumbers.SVC_BAD_PARAMETER, null);
296            if (msoRequest.getRequestId () != null) {
297                msoLogger.debug ("Logging failed message to the database");
298                msoRequest.createRequestRecord (Status.FAILED, action);
299            }
300            msoLogger.error (MessageEnum.APIH_REQUEST_VALIDATION_ERROR, MSO_PROP_APIHANDLER_INFRA, "", "", MsoLogger.ErrorCode.SchemaError, requestJSON, e);
301            msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.SchemaError, "Validation of the input request failed");
302            msoLogger.debug ("End of the transaction, the final response is: " + (String) response.getEntity ());
303            return response;
304        }
305
306            InfraActiveRequests dup = null;
307            String instanceName = sir.getRequestDetails().getRequestInfo().getInstanceName();
308            String requestScope = sir.getRequestDetails().getModelInfo().getModelType().name();
309        try {
310            if(!(instanceName==null && requestScope.equals("service") && action == Action.createInstance)){
311                dup = RequestsDatabase.checkInstanceNameDuplicate (instanceIdMap, instanceName, requestScope);
312            }
313           } catch (Exception e) {
314            msoLogger.error (MessageEnum.APIH_DUPLICATE_CHECK_EXC, MSO_PROP_APIHANDLER_INFRA, "", "", MsoLogger.ErrorCode.DataError, "Error during duplicate check ", e);
315
316           Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_INTERNAL_SERVER_ERROR, MsoException.ServiceException,
317                                                                  e.getMessage(),
318                                                                  ErrorNumbers.SVC_DETAILED_SERVICE_ERROR,
319                                                                  null) ;
320
321
322           msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.DBAccessError, "Error during duplicate check");
323           msoLogger.debug ("End of the transaction, the final response is: " + (String) response.getEntity ());
324           return response;
325        }
326
327        if (dup != null) {
328                  // Found the duplicate record. Return the appropriate error.
329                    String instance = null;
330                    if(instanceName != null){
331                            instance = instanceName;
332                    }else{
333                            instance = instanceIdMap.get(requestScope + "InstanceId");
334                    }
335                    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.";
336            //List<String> variables = new ArrayList<String>();
337            //variables.add(dup.getRequestStatus());
338
339            Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_CONFLICT, MsoException.ServiceException,
340                    dupMessage,
341                    ErrorNumbers.SVC_DETAILED_SERVICE_ERROR,
342                    null) ;
343
344
345            msoLogger.warn (MessageEnum.APIH_DUPLICATE_FOUND, dupMessage, "", "", MsoLogger.ErrorCode.SchemaError, "Duplicate request - Subscriber already has a request for this service");
346            msoRequest.createRequestRecord (Status.FAILED, action);
347            msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.Conflict, dupMessage);
348            msoLogger.debug ("End of the transaction, the final response is: " + (String) response.getEntity ());
349            return response;
350        }
351
352
353            ServiceInstancesResponse serviceResponse = new ServiceInstancesResponse();
354
355            RequestReferences referencesResponse = new RequestReferences();
356
357            referencesResponse.setRequestId(requestId);
358
359            serviceResponse.setRequestReferences(referencesResponse);
360
361         CatalogDatabase db = null;
362         try {
363             db = new CatalogDatabase ();
364         } catch (Exception e) {
365             msoLogger.error (MessageEnum.APIH_DB_ACCESS_EXC, MSO_PROP_APIHANDLER_INFRA, "", "", MsoLogger.ErrorCode.AvailabilityError, "Exception while communciate with Catalog DB", e);
366             msoRequest.setStatus (org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);
367             Response response = msoRequest.buildServiceErrorResponse (HttpStatus.SC_NOT_FOUND,
368                     MsoException.ServiceException,
369                     "No communication to catalog DB " + e.getMessage (),
370                     ErrorNumbers.SVC_NO_SERVER_RESOURCES,
371                     null);
372             alarmLogger.sendAlarm ("MsoDatabaseAccessError",
373                     MsoAlarmLogger.CRITICAL,
374                     Messages.errors.get (ErrorNumbers.NO_COMMUNICATION_TO_CATALOG_DB));
375             msoRequest.createRequestRecord (Status.FAILED,action);
376             msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.DBAccessError, "Exception while communciate with DB");
377             msoLogger.debug ("End of the transaction, the final response is: " + (String) response.getEntity ());
378             return response;
379         }
380
381
382
383            RecipeLookupResult recipeLookupResult = null;
384            try {
385                recipeLookupResult = getServiceInstanceOrchestrationURI (db, msoRequest, action);
386            } catch (ValidationException e) {
387                msoLogger.debug ("Validation failed: ", e);
388                Response response = msoRequest.buildServiceErrorResponse(HttpStatus.SC_BAD_REQUEST, MsoException.ServiceException,
389                        "Error validating request.  " + e.getMessage(),
390                        ErrorNumbers.SVC_BAD_PARAMETER, null);
391                if (msoRequest.getRequestId () != null) {
392                    msoLogger.debug ("Logging failed message to the database");
393                    msoRequest.createRequestRecord (Status.FAILED, action);
394                }
395                msoLogger.error (MessageEnum.APIH_REQUEST_VALIDATION_ERROR, MSO_PROP_APIHANDLER_INFRA, "", "", MsoLogger.ErrorCode.SchemaError, requestJSON, e);
396                msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.SchemaError, "Validation of the input request failed");
397                msoLogger.debug ("End of the transaction, the final response is: " + (String) response.getEntity ());
398                return response;
399            } catch (Exception e) {
400                msoLogger.error (MessageEnum.APIH_DB_ACCESS_EXC, MSO_PROP_APIHANDLER_INFRA, "", "", MsoLogger.ErrorCode.DataError, "Exception while querying Catalog DB", e);
401                msoRequest.setStatus (org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);
402                Response response = msoRequest.buildServiceErrorResponse (HttpStatus.SC_NOT_FOUND,
403                        MsoException.ServiceException,
404                        "Recipe could not be retrieved from catalog DB " + e.getMessage (),
405                        ErrorNumbers.SVC_GENERAL_SERVICE_ERROR,
406                        null);
407                alarmLogger.sendAlarm ("MsoDatabaseAccessError",
408                        MsoAlarmLogger.CRITICAL,
409                        Messages.errors.get (ErrorNumbers.ERROR_FROM_CATALOG_DB));
410                msoRequest.createRequestRecord (Status.FAILED,action);
411                msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.DBAccessError, "Exception while querying Catalog DB");
412                msoLogger.debug ("End of the transaction, the final response is: " + (String) response.getEntity ());
413                db.close();
414                return response;
415            }
416
417            if (recipeLookupResult == null) {
418                msoLogger.error (MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND, MSO_PROP_APIHANDLER_INFRA, "", "", MsoLogger.ErrorCode.DataError, "No recipe found in DB");
419                msoRequest.setStatus (org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);
420                Response response = msoRequest.buildServiceErrorResponse (HttpStatus.SC_NOT_FOUND,
421                        MsoException.ServiceException,
422                        "Recipe does not exist in catalog DB",
423                        ErrorNumbers.SVC_GENERAL_SERVICE_ERROR,
424                        null);
425                msoRequest.createRequestRecord (Status.FAILED, action);
426                msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.DataNotFound, "No recipe found in DB");
427                msoLogger.debug ("End of the transaction, the final response is: " + (String) response.getEntity ());
428                db.close();
429                return response;
430            }
431
432
433            Boolean isBaseVfModule = false;
434
435            if (msoRequest.getModelInfo().getModelType().equals(ModelType.vfModule)) {
436                String asdcServiceModelVersion = msoRequest.getAsdcServiceModelVersion ();
437
438                // Get VF Module-specific base module indicator
439                VfModule vfm = null;
440
441                if (asdcServiceModelVersion != null && !asdcServiceModelVersion.isEmpty ()) {
442                    vfm = db.getVfModuleType (msoRequest.getVfModuleType (), asdcServiceModelVersion);
443                }
444                else {
445                    vfm = db.getVfModuleType (msoRequest.getVfModuleType ());
446                }
447
448                if (vfm != null) {
449                    if (vfm.getIsBase() == 1) {
450                        isBaseVfModule = true;
451                    }
452                }
453                else if (action == Action.createInstance || action == Action.updateInstance){
454                    // There is no entry for this vfModuleType with this version, if specified, in VF_MODULE table in Catalog DB.
455                    // This request cannot proceed
456                    msoLogger.error (MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND, MSO_PROP_APIHANDLER_INFRA, "VF Module Type", "", MsoLogger.ErrorCode.DataError, "No VfModuleType found in DB");
457                    msoRequest.setStatus (org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);
458                    String serviceVersionText = "";
459                    if (asdcServiceModelVersion != null && !asdcServiceModelVersion.isEmpty ()) {
460                        serviceVersionText = " with version " + asdcServiceModelVersion;
461                    }
462                    Response response = msoRequest.buildServiceErrorResponse (HttpStatus.SC_NOT_FOUND,
463                            MsoException.ServiceException,
464                            "VnfType " + msoRequest.getVnfType () + " and VF Module Model Name " + msoRequest.getVfModuleModelName() + serviceVersionText + " not found in MSO Catalog DB",
465                            ErrorNumbers.SVC_BAD_PARAMETER,
466                            null);
467                    msoRequest.createRequestRecord (Status.FAILED, action);
468                    msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.DataNotFound, "No matching vfModuleType found in DB");
469                    msoLogger.debug ("End of the transaction, the final response is: " + (String) response.getEntity ());
470                    db.close();
471                    return response;
472                }
473            }
474
475            db.close();
476
477            String serviceInstanceId = "";
478            String vnfId = "";
479            String vfModuleId = "";
480            String volumeGroupId = "";
481            String networkId = "";
482            ServiceInstancesRequest siReq = msoRequest.getServiceInstancesRequest();
483
484            if(siReq.getServiceInstanceId () != null){
485                serviceInstanceId = siReq.getServiceInstanceId ();
486            }
487
488            if(siReq.getVnfInstanceId () != null){
489                vnfId = siReq.getVnfInstanceId ();
490            }
491
492            if(siReq.getVfModuleInstanceId () != null){
493                vfModuleId = siReq.getVfModuleInstanceId ();
494            }
495
496            if(siReq.getVolumeGroupInstanceId () != null){
497                volumeGroupId = siReq.getVolumeGroupInstanceId ();
498            }
499
500            if(siReq.getNetworkInstanceId () != null){
501                networkId = siReq.getNetworkInstanceId ();
502            }
503
504
505            requestId = msoRequest.getRequestId ();
506            msoLogger.debug ("requestId is: " + requestId);
507            msoLogger.debug ("About to insert a record");
508
509            try {
510                msoRequest.createRequestRecord (Status.PENDING, action);
511            } catch (Exception e) {
512                msoLogger.error (MessageEnum.APIH_DB_ACCESS_EXC_REASON, "Exception while creating record in DB", "", "", MsoLogger.ErrorCode.SchemaError, "Exception while creating record in DB", e);
513                msoRequest.setStatus (org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);
514                Response response = msoRequest.buildServiceErrorResponse (HttpStatus.SC_INTERNAL_SERVER_ERROR,
515                        MsoException.ServiceException,
516                        "Exception while creating record in DB " + e.getMessage(),
517                        ErrorNumbers.SVC_BAD_PARAMETER,
518                        null);
519                msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.DBAccessError, "Exception while creating record in DB");
520                msoLogger.debug ("End of the transaction, the final response is: " + (String) response.getEntity ());
521                return response;
522            }
523
524            RequestClient requestClient = null;
525            HttpResponse response = null;
526            long subStartTime = System.currentTimeMillis();
527            try {
528                requestClient = RequestClientFactory.getRequestClient (recipeLookupResult.getOrchestrationURI (), props);
529                // Capture audit event
530                msoLogger.debug ("MSO API Handler Posting call to BPEL engine for url: " + requestClient.getUrl ());
531
532                System.out.println("URL : " + requestClient.getUrl ());
533
534                response = requestClient.post(requestId, isBaseVfModule, recipeLookupResult.getRecipeTimeout (), action.name (),
535                        serviceInstanceId, vnfId, vfModuleId, volumeGroupId, networkId,
536                        msoRequest.getServiceInstanceType (),
537                        msoRequest.getVnfType (), msoRequest.getVfModuleType (),
538                        msoRequest.getNetworkType (), msoRequest.getRequestJSON());
539
540                msoLogger.recordMetricEvent (subStartTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "Successfully received response from BPMN engine", "BPMN", recipeLookupResult.getOrchestrationURI (), null);
541            } catch (Exception e) {
542                msoLogger.recordMetricEvent (subStartTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.CommunicationError, "Exception while communicate with BPMN engine", "BPMN", recipeLookupResult.getOrchestrationURI (), null);
543                msoRequest.setStatus (org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);
544                Response resp = msoRequest.buildServiceErrorResponse (HttpStatus.SC_BAD_GATEWAY,
545                        MsoException.ServiceException,
546                        "Failed calling bpmn " + e.getMessage (),
547                        ErrorNumbers.SVC_NO_SERVER_RESOURCES,
548                        null);
549                alarmLogger.sendAlarm ("MsoConfigurationError",
550                        MsoAlarmLogger.CRITICAL,
551                        Messages.errors.get (ErrorNumbers.NO_COMMUNICATION_TO_BPEL));
552                msoRequest.updateFinalStatus (Status.FAILED);
553                msoLogger.error (MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, MSO_PROP_APIHANDLER_INFRA, "", "", MsoLogger.ErrorCode.AvailabilityError, "Exception while communicate with BPMN engine");
554                msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.CommunicationError, "Exception while communicate with BPMN engine");
555                msoLogger.debug ("End of the transaction, the final response is: " + (String) resp.getEntity ());
556                return resp;
557            }
558
559            if (response == null) {
560                msoRequest.setStatus (org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);
561                Response resp = msoRequest.buildServiceErrorResponse (HttpStatus.SC_BAD_GATEWAY,
562                        MsoException.ServiceException,
563                        "bpelResponse is null",
564                        ErrorNumbers.SVC_NO_SERVER_RESOURCES,
565                        null);
566                msoRequest.updateFinalStatus (Status.FAILED);
567                msoLogger.error (MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, MSO_PROP_APIHANDLER_INFRA, "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Null response from BPEL");
568                msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.InternalError, "Null response from BPMN");
569                msoLogger.debug ("End of the transaction, the final response is: " + (String) resp.getEntity ());
570                return resp;
571            }
572
573            ResponseHandler respHandler = new ResponseHandler (response, requestClient.getType ());
574            int bpelStatus = respHandler.getStatus ();
575
576            // BPEL accepted the request, the request is in progress
577            if (bpelStatus == HttpStatus.SC_ACCEPTED) {
578                String camundaJSONResponseBody = respHandler.getResponseBody ();
579                msoLogger.debug ("Received from Camunda: " + camundaJSONResponseBody);
580                msoRequest.setStatus (org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.IN_PROGRESS);
581                RequestsDatabase.updateInfraStatus (msoRequest.getRequestId (),
582                        Status.IN_PROGRESS.toString (),
583                        Constants.PROGRESS_REQUEST_IN_PROGRESS,
584                        Constants.MODIFIED_BY_APIHANDLER);
585                msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.COMPLETE, MsoLogger.ResponseCode.Suc, "BPMN accepted the request, the request is in progress");
586                msoLogger.debug ("End of the transaction, the final response is: " + (String) camundaJSONResponseBody);
587                return Response.status (HttpStatus.SC_ACCEPTED).entity (camundaJSONResponseBody).build ();
588            } else {
589                List<String> variables = new ArrayList<String>();
590                variables.add(bpelStatus + "");
591                String camundaJSONResponseBody = respHandler.getResponseBody ();
592                if (camundaJSONResponseBody != null && !camundaJSONResponseBody.isEmpty ()) {
593                    msoRequest.setStatus (org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);
594                    Response resp =  msoRequest.buildServiceErrorResponse(bpelStatus,
595                            MsoException.ServiceException,
596                            "Request Failed due to BPEL error with HTTP Status= %1 " + '\n' + camundaJSONResponseBody,
597                            ErrorNumbers.SVC_DETAILED_SERVICE_ERROR,
598                            variables);
599                    msoRequest.updateFinalStatus (Status.FAILED);
600                    msoLogger.error (MessageEnum.APIH_BPEL_RESPONSE_ERROR, requestClient.getUrl (), "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Response from BPEL engine is failed with HTTP Status=" + bpelStatus);
601                    msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.InternalError, "Response from BPMN engine is failed");
602                    msoLogger.debug ("End of the transaction, the final response is: " + (String) resp.getEntity ());
603                    return resp;
604                } else {
605                    msoRequest.setStatus (org.openecomp.mso.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);
606                    Response resp = msoRequest.buildServiceErrorResponse(bpelStatus,
607                            MsoException.ServiceException,
608                            "Request Failed due to BPEL error with HTTP Status= %1" ,
609                            ErrorNumbers.SVC_DETAILED_SERVICE_ERROR,
610                            variables);
611                    msoRequest.updateFinalStatus (Status.FAILED);
612                    msoLogger.error (MessageEnum.APIH_BPEL_RESPONSE_ERROR, requestClient.getUrl (), "", "", MsoLogger.ErrorCode.BusinessProcesssError, "Response from BPEL engine is empty");
613                    msoLogger.recordAuditEvent (startTime, MsoLogger.StatusCode.ERROR, MsoLogger.ResponseCode.InternalError, "Response from BPEL engine is empty");
614                    msoLogger.debug ("End of the transaction, the final response is: " + (String) resp.getEntity ());
615                    return resp;
616                }
617            }
618
619            //return Response.status (HttpStatus.SC_ACCEPTED).entity (serviceResponse).build ();
620            // return serviceResponse;
621         }
622
623     private RecipeLookupResult getServiceInstanceOrchestrationURI (CatalogDatabase db, MsoRequest msoRequest, Action action) throws Exception {
624         RecipeLookupResult recipeLookupResult = null;
625         //if the aLaCarte flag is set to TRUE, the API-H should choose the Ã¢â‚¬Å“VID_DEFAULTâ€\9d recipe for the requested action
626
627         msoLogger.debug("aLaCarteFlag is " + msoRequest.getALaCarteFlag());
628         // Query MSO Catalog DB
629
630         if (msoRequest.getModelInfo().getModelType().equals(ModelType.service)) {
631             recipeLookupResult = getServiceURI(db, msoRequest, action);
632         }
633         else if (msoRequest.getModelInfo().getModelType().equals(ModelType.vfModule) ||
634                 msoRequest.getModelInfo().getModelType().equals(ModelType.volumeGroup) || msoRequest.getModelInfo().getModelType().equals(ModelType.vnf)) {
635
636             recipeLookupResult = getVnfOrVfModuleUri(db, msoRequest, action);
637
638         }else if (msoRequest.getModelInfo().getModelType().equals(ModelType.network)) {
639
640             recipeLookupResult = getNetworkUri(db, msoRequest, action);
641         }
642
643         if (recipeLookupResult != null) {
644             msoLogger.debug ("Orchestration URI is: " + recipeLookupResult.getOrchestrationURI() + ", recipe Timeout is: " + Integer.toString(recipeLookupResult.getRecipeTimeout ()));
645         }
646         else {
647             msoLogger.debug("No matching recipe record found");
648         }
649         return recipeLookupResult;
650     }
651
652
653     private RecipeLookupResult getServiceURI (CatalogDatabase db, MsoRequest msoRequest, Action action) throws Exception {
654         // SERVICE REQUEST
655         // Construct the default service name
656         // TODO need to make this a configurable property
657         String sourceDefaultServiceName = msoRequest.getRequestInfo().getSource() + "_DEFAULT";
658         String defaultService = "*";
659
660         Service serviceRecord = null;
661         int serviceId;
662         ServiceRecipe recipe = null;
663
664         //if an aLaCarte flag was Not sent in the request, look first if there is a custom recipe for the specific model version
665         if(!msoRequest.getALaCarteFlag()){
666             serviceRecord = db.getServiceByVersionAndInvariantId(msoRequest.getModelInfo().getModelInvariantId(), msoRequest.getModelInfo().getModelVersion());
667             if(serviceRecord !=null){
668                 serviceId = serviceRecord.getId();
669                 recipe = db.getServiceRecipe(serviceId, action.name());
670             }
671         }
672
673         if (recipe == null) {
674             //find source(initiator) default recipe
675             recipe = db.getServiceRecipeByServiceNameAndAction(sourceDefaultServiceName, action.name());
676         }
677         if (recipe == null) {
678             //find default recipe
679             recipe = db.getServiceRecipeByServiceNameAndAction(defaultService, action.name());
680         }
681         if(recipe==null){
682             return null;
683         }
684         return new RecipeLookupResult (recipe.getOrchestrationUri (), recipe.getRecipeTimeout ());
685
686     }
687
688
689     private RecipeLookupResult getVnfOrVfModuleUri (CatalogDatabase db, MsoRequest msoRequest, Action action) throws Exception {
690
691         String vnfComponentType = msoRequest.getModelInfo().getModelType().name();
692
693         RelatedInstanceList[] instanceList = null;
694         if (msoRequest.getServiceInstancesRequest().getRequestDetails() != null) {
695             instanceList = msoRequest.getServiceInstancesRequest().getRequestDetails().getRelatedInstanceList();
696         }
697
698         String serviceModelName = null;
699         String vnfModelName = null;
700         String asdcServiceModelVersion = null;
701         String modelVersion = msoRequest.getModelInfo().getModelVersion();
702         Recipe recipe = null;
703         String defaultVnfType = msoRequest.getRequestInfo().getSource() + "_DEFAULT";
704         String modelCustomizationId = msoRequest.getModelInfo().getModelCustomizationId();
705         String vfModuleModelName = msoRequest.getModelInfo().getModelName();
706         if (instanceList != null) {
707
708             for(RelatedInstanceList relatedInstanceList : instanceList){
709
710                 RelatedInstance relatedInstance = relatedInstanceList.getRelatedInstance();
711                 ModelInfo modelInfo = relatedInstance.getModelInfo();
712                 if(modelInfo.getModelType().equals(ModelType.service)){
713                     serviceModelName = modelInfo.getModelName();
714                     asdcServiceModelVersion = modelInfo.getModelVersion();
715                 }
716
717                 if(modelInfo.getModelType().equals(ModelType.vnf)){
718                     vnfModelName = modelInfo.getModelCustomizationName();
719                     if (null == vnfModelName || vnfModelName.trim().isEmpty()) {
720                         VnfResource vnfResource = db.getVnfResourceByModelCustomizationId(modelInfo.getModelCustomizationUuid(), modelInfo.getModelVersion());
721                         vnfModelName = vnfResource.getModelName();
722                     }
723                 }
724             }
725
726             if(msoRequest.getModelInfo().getModelType().equals(ModelType.vnf)) {
727                 String modelCustomizationName = msoRequest.getModelInfo().getModelCustomizationName();
728
729                 VnfResource vnfResource = null;
730
731                 // Validation for vnfResource
732                 if(modelCustomizationName!=null) {
733                     vnfResource = db.getVnfResource(serviceModelName + "/" + modelCustomizationName, asdcServiceModelVersion);
734                 }else{
735                     vnfResource = db.getVnfResourceByModelCustomizationId(modelCustomizationId, asdcServiceModelVersion);
736                 }
737
738                 if(vnfResource==null){
739                     throw new ValidationException("catalog entry");
740                 }
741
742                 VnfRecipe vnfRecipe = db.getVnfRecipe(defaultVnfType, action.name());
743
744                 if (vnfRecipe == null) {
745                     return null;
746                 }
747
748                 return new RecipeLookupResult (vnfRecipe.getOrchestrationUri(), vnfRecipe.getRecipeTimeout());
749             }else{
750                 String vnfType = serviceModelName + "/" + vnfModelName;
751                 String vfModuleType = vnfType + "::" + vfModuleModelName;
752                 List<VfModule> vfModule = db.getVfModule(vfModuleType, modelCustomizationId, asdcServiceModelVersion, modelVersion, action.name());
753                 if(vfModule==null || vfModule.isEmpty()){
754                     throw new ValidationException("catalog entry");
755                 }else{
756                     if(!msoRequest.getALaCarteFlag() && action != Action.deleteInstance){
757                         recipe = db.getVnfComponentsRecipeByVfModule(vfModule, action.name());
758                     }
759                 }
760                 if (recipe == null) {
761                     msoLogger.debug("recipe is null, getting default");
762                     recipe = db.getVnfComponentsRecipeByVfModuleId("VID_DEFAULT", vnfComponentType, action.name());
763
764                     if (recipe == null) {
765                         return null;
766                     }
767                 }
768
769             }
770         } else {
771             msoLogger.debug("recipe is null, getting default");
772
773             if(msoRequest.getModelInfo().getModelType().equals(ModelType.vnf)) {
774                 recipe = db.getVnfRecipe(defaultVnfType, action.name());
775                 if (recipe == null) {
776                     return null;
777                 }
778             } else {
779                 recipe = db.getVnfComponentsRecipeByVfModuleId("VID_DEFAULT", vnfComponentType, action.name());
780
781                 if (recipe == null) {
782                     return null;
783                 }
784             }
785         }
786
787         return new RecipeLookupResult (recipe.getOrchestrationUri (), recipe.getRecipeTimeout ());
788     }
789
790     private RecipeLookupResult getNetworkUri (CatalogDatabase db, MsoRequest msoRequest, Action action) throws Exception {
791
792         String sourceDefaultNetworkType = msoRequest.getRequestInfo().getSource() + "_DEFAULT";
793         String defaultNetworkType = "*";
794
795         String modelName = msoRequest.getModelInfo().getModelName();
796         Recipe recipe = null;
797         //if an aLaCarte flag was Not sent in the request, look first if there is a custom recipe for the specific ModelCustomizationId
798         if(!msoRequest.getALaCarteFlag()){
799             String networkType = null;
800
801             if(msoRequest.getModelInfo().getModelCustomizationId()!=null){
802                 NetworkResource networkResource = db.getNetworkResourceByModelCustUuid(msoRequest.getModelInfo().getModelCustomizationId());
803                 if(networkResource!=null){
804                     networkType = networkResource.getNetworkType();
805                 }else{
806                     throw new ValidationException("no catalog entry found");
807                 }
808             }else{
809                 //ok for version < 3
810                 networkType = modelName;
811             }
812
813             //find latest version Recipe for the given networkType and action
814             recipe = db.getNetworkRecipe(networkType, action.name());
815         }
816
817         if(recipe == null){
818             //find source(initiator) default recipe
819             recipe = db.getNetworkRecipe(sourceDefaultNetworkType, action.name());
820         }
821         if(recipe == null){
822             //find default recipe
823             recipe = db.getNetworkRecipe(defaultNetworkType, action.name());
824         }
825         if (recipe == null) {
826             return null;
827         }
828         return new RecipeLookupResult (recipe.getOrchestrationUri (), recipe.getRecipeTimeout ());
829     }
830 }