753b4c48d49682430f0c0481b808426aad5b685a
[so.git] / mso-api-handlers / mso-api-handler-infra / src / main / java / org / onap / so / apihandlerinfra / OrchestrationRequests.java
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
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
21 package org.onap.so.apihandlerinfra;
22
23 import java.io.IOException;
24 import java.text.SimpleDateFormat;
25 import java.util.ArrayList;
26 import java.util.List;
27 import java.util.Map;
28
29 import javax.transaction.Transactional;
30 import javax.ws.rs.Consumes;
31 import javax.ws.rs.GET;
32 import javax.ws.rs.POST;
33 import javax.ws.rs.Path;
34 import javax.ws.rs.PathParam;
35 import javax.ws.rs.Produces;
36 import javax.ws.rs.core.Context;
37 import javax.ws.rs.core.MediaType;
38 import javax.ws.rs.core.MultivaluedMap;
39 import javax.ws.rs.core.Response;
40 import javax.ws.rs.core.UriInfo;
41
42 import org.apache.commons.lang.StringUtils;
43 import org.apache.http.HttpStatus;
44 import org.onap.so.apihandler.common.ErrorNumbers;
45 import org.onap.so.apihandler.common.ResponseBuilder;
46 import org.onap.so.apihandlerinfra.exceptions.ApiException;
47 import org.onap.so.apihandlerinfra.exceptions.ValidateException;
48 import org.onap.so.apihandlerinfra.logging.AlarmLoggerInfo;
49 import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo;
50 import org.onap.so.db.request.beans.InfraActiveRequests;
51 import org.onap.so.exceptions.ValidationException;
52 import org.onap.so.logger.MessageEnum;
53 import org.onap.so.logger.MsoAlarmLogger;
54 import org.onap.so.logger.MsoLogger;
55 import org.onap.so.requestsdb.client.RequestsDbClient;
56 import org.onap.so.serviceinstancebeans.GetOrchestrationListResponse;
57 import org.onap.so.serviceinstancebeans.GetOrchestrationResponse;
58 import org.onap.so.serviceinstancebeans.InstanceReferences;
59 import org.onap.so.serviceinstancebeans.Request;
60 import org.onap.so.serviceinstancebeans.RequestDetails;
61 import org.onap.so.serviceinstancebeans.RequestList;
62 import org.onap.so.serviceinstancebeans.RequestStatus;
63 import org.onap.so.serviceinstancebeans.ServiceInstancesRequest;
64 import org.springframework.beans.factory.annotation.Autowired;
65 import org.springframework.stereotype.Component;
66
67 import com.fasterxml.jackson.databind.ObjectMapper;
68
69 import io.swagger.annotations.Api;
70 import io.swagger.annotations.ApiOperation;
71
72 @Path("onap/so/infra/orchestrationRequests")
73 @Api(value="onap/so/infra/orchestrationRequests",description="API Requests for Orchestration requests")
74 @Component
75 public class OrchestrationRequests {
76
77     private static MsoLogger msoLogger = MsoLogger.getMsoLogger (MsoLogger.Catalog.APIH, OrchestrationRequests.class);
78     
79
80     @Autowired
81         private RequestsDbClient requestsDbClient;
82
83     @Autowired
84     private MsoRequest msoRequest;
85     
86         @Autowired
87         private ResponseBuilder builder;
88
89         @GET
90         @Path("/{version:[vV][4-7]}/{requestId}")
91         @ApiOperation(value="Find Orchestrated Requests for a given requestId",response=Response.class)
92         @Produces(MediaType.APPLICATION_JSON)
93         @Transactional
94         public Response getOrchestrationRequest(@PathParam("requestId") String requestId, @PathParam("version") String version) throws ApiException{
95
96                 String apiVersion = version.substring(1);
97                 GetOrchestrationResponse orchestrationResponse = new GetOrchestrationResponse();
98
99
100                 InfraActiveRequests requestDB = null;
101
102                 try {
103                         requestDB = requestsDbClient.getInfraActiveRequestbyRequestId(requestId);
104
105                 } catch (Exception e) {
106                     msoLogger.error(e);
107                         ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, MsoLogger.ErrorCode.AvailabilityError).build();
108                         AlarmLoggerInfo alarmLoggerInfo = new AlarmLoggerInfo.Builder("MsoDatabaseAccessError", MsoAlarmLogger.CRITICAL, Messages.errors.get(ErrorNumbers.NO_COMMUNICATION_TO_REQUESTS_DB)).build();
109
110
111
112                         ValidateException validateException = new ValidateException.Builder("Exception while communciate with Request DB - Infra Request Lookup",
113                                         HttpStatus.SC_NOT_FOUND,ErrorNumbers.NO_COMMUNICATION_TO_REQUESTS_DB).cause(e).errorInfo(errorLoggerInfo).alarmInfo(alarmLoggerInfo).build();
114
115                         throw validateException;
116
117                 }
118
119         if(requestDB == null) {
120
121             ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, MsoLogger.ErrorCode.BusinessProcesssError).build();
122
123
124             ValidateException validateException = new ValidateException.Builder("Orchestration RequestId " + requestId + " is not found in DB",
125                     HttpStatus.SC_NO_CONTENT, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
126
127             throw validateException;
128         }
129
130         Request request = mapInfraActiveRequestToRequest(requestDB);
131                 request.setRequestId(requestId);
132         orchestrationResponse.setRequest(request);
133         
134         return builder.buildResponse(HttpStatus.SC_OK, requestId, orchestrationResponse, apiVersion);
135         }
136
137         @GET
138         @Path("/{version:[vV][4-7]}")
139         @ApiOperation(value="Find Orchestrated Requests for a URI Information",response=Response.class)
140         @Produces(MediaType.APPLICATION_JSON)
141         @Transactional
142         public Response getOrchestrationRequest(@Context UriInfo ui, @PathParam("version") String version) throws ApiException{
143
144                 long startTime = System.currentTimeMillis ();
145                 
146                 MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
147
148                 List<InfraActiveRequests> activeRequests = null;
149
150                 GetOrchestrationListResponse orchestrationList = null;
151                 Map<String, List<String>> orchestrationMap;
152                 String apiVersion = version.substring(1);
153                 
154                 try {
155                         orchestrationMap = msoRequest.getOrchestrationFilters(queryParams);
156                         if (orchestrationMap.isEmpty()) {
157                                 throw new ValidationException("At least one filter query param must be specified");
158                         }
159                 }catch(ValidationException ex){
160                     msoLogger.error(ex);
161                         ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, MsoLogger.ErrorCode.DataError).build();
162                         ValidateException validateException = new ValidateException.Builder(ex.getMessage(),
163                                         HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_GENERAL_SERVICE_ERROR).cause(ex).errorInfo(errorLoggerInfo).build();
164                         throw validateException;
165
166                 }
167                         
168                 activeRequests = requestsDbClient.getOrchestrationFiltersFromInfraActive(orchestrationMap);
169
170                 orchestrationList = new GetOrchestrationListResponse();
171                 List<RequestList> requestLists = new ArrayList<>();
172                 
173                 for(InfraActiveRequests infraActive : activeRequests){
174                         RequestList requestList = new RequestList();
175                         Request request = mapInfraActiveRequestToRequest(infraActive);
176                         requestList.setRequest(request);
177                         requestLists.add(requestList);
178                 }
179
180                 orchestrationList.setRequestList(requestLists);
181                 return builder.buildResponse(HttpStatus.SC_OK, null, orchestrationList, apiVersion);
182         }
183
184
185         @POST
186         @Path("/{version: [vV][4-7]}/{requestId}/unlock")
187         @Consumes(MediaType.APPLICATION_JSON)
188         @Produces(MediaType.APPLICATION_JSON)
189         @ApiOperation(value="Unlock Orchestrated Requests for a given requestId",response=Response.class)
190         @Transactional
191         public Response unlockOrchestrationRequest(String requestJSON, @PathParam("requestId") String requestId, @PathParam("version") String version) throws ApiException{
192
193                 long startTime = System.currentTimeMillis ();
194                 msoLogger.debug ("requestId is: " + requestId);
195                 ServiceInstancesRequest sir = null;
196
197                 InfraActiveRequests infraActiveRequest = null;
198                 Request request = null;
199                 
200                 try{
201                         ObjectMapper mapper = new ObjectMapper();
202                         sir = mapper.readValue(requestJSON, ServiceInstancesRequest.class);
203                 } catch(IOException e){
204                     msoLogger.error(e);
205             ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, MsoLogger.ErrorCode.SchemaError).build();
206             ValidateException validateException = new ValidateException.Builder("Mapping of request to JSON object failed : " + e.getMessage(),
207                     HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build();
208
209             throw validateException;
210
211                 }
212                 try{
213                         msoRequest.parseOrchestration(sir);
214                 } catch (Exception e) {
215                     msoLogger.error(e);
216                         ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, MsoLogger.ErrorCode.SchemaError).build();
217                          ValidateException validateException = new ValidateException.Builder("Error parsing request: " + e.getMessage(), HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e)
218                          .errorInfo(errorLoggerInfo).build();
219             throw validateException;
220                 }
221
222                 infraActiveRequest = requestsDbClient.getInfraActiveRequestbyRequestId(requestId);
223                 if(infraActiveRequest == null) {
224                         ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND, MsoLogger.ErrorCode.BusinessProcesssError).build();
225
226
227                         ValidateException validateException = new ValidateException.Builder("Null response from RequestDB when searching by RequestId",
228                                         HttpStatus.SC_NOT_FOUND, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
229
230                         throw validateException;
231
232                 }else{
233                         String status = infraActiveRequest.getRequestStatus();
234                         if(status.equalsIgnoreCase("IN_PROGRESS") || status.equalsIgnoreCase("PENDING") || status.equalsIgnoreCase("PENDING_MANUAL_TASK")){
235                                 infraActiveRequest.setRequestStatus("UNLOCKED");
236                                 infraActiveRequest.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER);
237                                 infraActiveRequest.setRequestId(requestId);
238                                 requestsDbClient.save(infraActiveRequest);
239                         }else{
240
241                                 ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND, MsoLogger.ErrorCode.DataError).build();
242
243
244                                 ValidateException validateException = new ValidateException.Builder("Orchestration RequestId " + requestId + " has a status of " + status + " and can not be unlocked",
245                                                 HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
246
247                                 throw validateException;
248                         }
249                 }
250                 return Response.status (HttpStatus.SC_NO_CONTENT).entity ("").build ();
251         }
252
253     private Request mapInfraActiveRequestToRequest(InfraActiveRequests iar)  throws ApiException{
254
255         String requestBody = iar.getRequestBody();
256         Request request = new Request();
257         
258         ObjectMapper mapper = new ObjectMapper();      
259
260        request.setRequestId(iar.getRequestId());
261        request.setRequestScope(iar.getRequestScope());
262        request.setRequestType(iar.getRequestAction());
263
264        InstanceReferences ir = new InstanceReferences();
265        if(iar.getNetworkId() != null)
266         ir.setNetworkInstanceId(iar.getNetworkId());
267        if(iar.getNetworkName() != null)
268         ir.setNetworkInstanceName(iar.getNetworkName());
269        if(iar.getServiceInstanceId() != null)
270         ir.setServiceInstanceId(iar.getServiceInstanceId());
271        if(iar.getServiceInstanceName() != null)
272         ir.setServiceInstanceName(iar.getServiceInstanceName());
273        if(iar.getVfModuleId() != null)
274         ir.setVfModuleInstanceId(iar.getVfModuleId());
275        if(iar.getVfModuleName() != null)
276         ir.setVfModuleInstanceName(iar.getVfModuleName());
277        if(iar.getVnfId() != null)
278         ir.setVnfInstanceId(iar.getVnfId());
279        if(iar.getVnfName() != null)
280         ir.setVnfInstanceName(iar.getVnfName());
281        if(iar.getVolumeGroupId() != null)
282         ir.setVolumeGroupInstanceId(iar.getVolumeGroupId());
283        if(iar.getVolumeGroupName() != null)
284         ir.setVolumeGroupInstanceName(iar.getVolumeGroupName());
285                 if(iar.getRequestorId() != null)
286                         ir.setRequestorId(iar.getRequestorId());
287
288
289                 request.setInstanceReferences(ir);
290
291        RequestDetails requestDetails = null;
292
293        if(StringUtils.isNotBlank(requestBody)) {
294                    try {
295                            if(requestBody.contains("\"requestDetails\":")){
296                                    ServiceInstancesRequest sir = mapper.readValue(requestBody, ServiceInstancesRequest.class);
297                                    requestDetails = sir.getRequestDetails();
298                            } else {
299                                    requestDetails = mapper.readValue(requestBody, RequestDetails.class);
300                            }
301                    } catch (IOException e) {
302                        msoLogger.error(e);
303                            ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, MsoLogger.ErrorCode.SchemaError).build();
304                            ValidateException validateException = new ValidateException.Builder("Mapping of request to JSON object failed : ",
305                                            HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build();
306
307                            throw validateException;
308                    }
309            }
310        request.setRequestDetails(requestDetails);
311        
312        if(iar.getStartTime() != null) {
313                String startTimeStamp = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss").format(iar.getStartTime()) + " GMT";
314                request.setStartTime(startTimeStamp);
315        }
316
317        RequestStatus status = new RequestStatus();
318        if(iar.getStatusMessage() != null){
319            status.setStatusMessage(iar.getStatusMessage());
320        }
321
322        if(iar.getEndTime() != null){
323            String endTimeStamp = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss").format(iar.getEndTime()) + " GMT";
324            status.setFinishTime(endTimeStamp);
325        }
326
327
328        if(iar.getRequestStatus() != null){
329            status.setRequestState(iar.getRequestStatus());
330        }
331
332        if(iar.getProgress() != null){
333            status.setPercentProgress(iar.getProgress().intValue());
334        }
335
336        request.setRequestStatus(status);
337
338        return request;
339    }
340  }