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