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