47d6932730955f91498de2d8464b486ae3eb2260
[so.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Modifications Copyright (c) 2019 Samsung
8  * ================================================================================
9  * Licensed under the Apache License, Version 2.0 (the "License");
10  * you may not use this file except in compliance with the License.
11  * You may obtain a copy of the License at
12  * 
13  *      http://www.apache.org/licenses/LICENSE-2.0
14  * 
15  * Unless required by applicable law or agreed to in writing, software
16  * distributed under the License is distributed on an "AS IS" BASIS,
17  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
18  * See the License for the specific language governing permissions and
19  * limitations under the License.
20  * ============LICENSE_END=========================================================
21  */
22
23 package org.onap.so.apihandlerinfra.tenantisolation;
24
25 import java.io.IOException;
26 import java.text.SimpleDateFormat;
27 import java.util.ArrayList;
28 import java.util.List;
29 import java.util.Map;
30 import javax.transaction.Transactional;
31 import javax.ws.rs.Consumes;
32 import javax.ws.rs.GET;
33 import javax.ws.rs.POST;
34 import javax.ws.rs.Path;
35 import javax.ws.rs.PathParam;
36 import javax.ws.rs.Produces;
37 import javax.ws.rs.core.Context;
38 import javax.ws.rs.core.MediaType;
39 import javax.ws.rs.core.MultivaluedMap;
40 import javax.ws.rs.core.Response;
41 import javax.ws.rs.core.UriInfo;
42 import org.apache.http.HttpStatus;
43 import org.onap.so.apihandler.common.ErrorNumbers;
44 import org.onap.so.apihandler.common.ResponseBuilder;
45 import org.onap.so.apihandlerinfra.Constants;
46 import org.onap.so.apihandlerinfra.exceptions.ApiException;
47 import org.onap.so.apihandlerinfra.exceptions.ValidateException;
48 import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo;
49 import org.onap.so.apihandlerinfra.tenantisolationbeans.CloudOrchestrationRequestList;
50 import org.onap.so.apihandlerinfra.tenantisolationbeans.CloudOrchestrationResponse;
51 import org.onap.so.apihandlerinfra.tenantisolationbeans.InstanceReferences;
52 import org.onap.so.apihandlerinfra.tenantisolationbeans.Request;
53 import org.onap.so.apihandlerinfra.tenantisolationbeans.RequestDetails;
54 import org.onap.so.apihandlerinfra.tenantisolationbeans.RequestStatus;
55 import org.onap.so.db.request.beans.InfraActiveRequests;
56 import org.onap.so.db.request.client.RequestsDbClient;
57 import org.onap.so.exceptions.ValidationException;
58 import org.onap.so.logger.ErrorCode;
59 import org.onap.so.logger.MessageEnum;
60 import org.slf4j.Logger;
61 import org.slf4j.LoggerFactory;
62 import org.springframework.beans.factory.annotation.Autowired;
63 import org.springframework.stereotype.Component;
64 import com.fasterxml.jackson.databind.ObjectMapper;
65 import io.swagger.v3.oas.annotations.OpenAPIDefinition;
66 import io.swagger.v3.oas.annotations.Operation;
67 import io.swagger.v3.oas.annotations.info.Info;
68 import io.swagger.v3.oas.annotations.media.ArraySchema;
69 import io.swagger.v3.oas.annotations.media.Content;
70 import io.swagger.v3.oas.annotations.media.Schema;
71 import io.swagger.v3.oas.annotations.responses.ApiResponse;
72
73 @Component
74 @Path("onap/so/infra/cloudResourcesRequests")
75 @OpenAPIDefinition(info = @Info(title = "onap/so/infra/cloudResourcesRequests",
76         description = "API GET Requests for cloud resources - Tenant Isolation"))
77 public class CloudResourcesOrchestration {
78
79     private static Logger logger = LoggerFactory.getLogger(CloudResourcesOrchestration.class);
80
81     @Autowired
82     RequestsDbClient requestDbClient;
83
84     @Autowired
85     private ResponseBuilder builder;
86
87     @POST
88     @Path("/{version: [vV][1]}/{requestId}/unlock")
89     @Consumes(MediaType.APPLICATION_JSON)
90     @Produces(MediaType.APPLICATION_JSON)
91     @Operation(description = "Unlock CloudOrchestration requests for a specified requestId")
92     @Transactional
93     public Response unlockOrchestrationRequest(String requestJSON, @PathParam("requestId") String requestId,
94             @PathParam("version") String version) throws ApiException {
95         TenantIsolationRequest msoRequest = new TenantIsolationRequest(requestId);
96         InfraActiveRequests infraActiveRequest;
97
98         CloudOrchestrationRequest cor;
99
100         logger.debug("requestId is: {}", requestId);
101
102         try {
103             ObjectMapper mapper = new ObjectMapper();
104             cor = mapper.readValue(requestJSON, CloudOrchestrationRequest.class);
105         } catch (IOException e) {
106             ErrorLoggerInfo errorLoggerInfo =
107                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError)
108                             .build();
109
110             ValidateException validateException =
111                     new ValidateException.Builder("Mapping of request to JSON object failed.  " + e.getMessage(),
112                             HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e)
113                                     .errorInfo(errorLoggerInfo).build();
114             throw validateException;
115         }
116
117         try {
118             msoRequest.parseOrchestration(cor);
119         } catch (ValidationException e) {
120             ErrorLoggerInfo errorLoggerInfo =
121                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError)
122                             .build();
123             ValidateException validateException =
124                     new ValidateException.Builder(e.getMessage(), HttpStatus.SC_BAD_REQUEST,
125                             ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build();
126             throw validateException;
127         }
128         try {
129             infraActiveRequest = requestDbClient.getInfraActiveRequestbyRequestId(requestId);
130         } catch (Exception e) {
131             ValidateException validateException = new ValidateException.Builder(e.getMessage(),
132                     HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e).build();
133             throw validateException;
134         }
135         if (infraActiveRequest == null) {
136
137             ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND,
138                     ErrorCode.BusinessProcesssError).build();
139             ValidateException validateException =
140                     new ValidateException.Builder("Orchestration RequestId " + requestId + " is not found in DB",
141                             HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR)
142                                     .errorInfo(errorLoggerInfo).build();
143
144             throw validateException;
145
146         } else {
147             String status = infraActiveRequest.getRequestStatus();
148             if ("IN_PROGRESS".equalsIgnoreCase(status) || "PENDING".equalsIgnoreCase(status)
149                     || "PENDING_MANUAL_TASK".equalsIgnoreCase(status)) {
150                 infraActiveRequest.setRequestStatus("UNLOCKED");
151                 infraActiveRequest.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER);
152                 infraActiveRequest.setRequestId(requestId);
153                 requestDbClient.save(infraActiveRequest);
154             } else {
155                 ErrorLoggerInfo errorLoggerInfo =
156                         new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND, ErrorCode.DataError)
157                                 .build();
158                 ValidateException validateException = new ValidateException.Builder(
159                         "Orchestration RequestId " + requestId + " has a status of " + status
160                                 + " and can not be unlocked",
161                         HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo)
162                                 .build();
163
164                 throw validateException;
165             }
166         }
167
168         return Response.status(HttpStatus.SC_NO_CONTENT).entity("").build();
169     }
170
171     @GET
172     @Path("/{version:[vV][1]}")
173     @Consumes(MediaType.APPLICATION_JSON)
174     @Produces(MediaType.APPLICATION_JSON)
175     @Operation(description = "Get status of an Operational Environment based on filter criteria",
176             responses = @ApiResponse(
177                     content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))
178     @Transactional
179     public Response getOperationEnvironmentStatusFilter(@Context UriInfo ui, @PathParam("version") String version)
180             throws ApiException {
181
182         MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
183         List<String> requestIdKey = queryParams.get("requestId");
184         String apiVersion = version.substring(1);
185
186         if (queryParams.size() == 1 && requestIdKey != null) {
187             String requestId = requestIdKey.get(0);
188
189             CloudOrchestrationResponse cloudOrchestrationGetResponse = new CloudOrchestrationResponse();
190             InfraActiveRequests requestDB;
191
192             try {
193                 requestDB = requestDbClient.getInfraActiveRequestbyRequestId(requestId);
194             } catch (Exception e) {
195                 ErrorLoggerInfo errorLoggerInfo =
196                         new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, ErrorCode.AvailabilityError)
197                                 .build();
198                 ValidateException validateException =
199                         new ValidateException.Builder(e.getMessage(), HttpStatus.SC_INTERNAL_SERVER_ERROR,
200                                 ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e).errorInfo(errorLoggerInfo).build();
201                 throw validateException;
202             }
203
204             if (requestDB == null) {
205                 ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR,
206                         ErrorCode.BusinessProcesssError).build();
207                 ValidateException validateException =
208                         new ValidateException.Builder("Orchestration RequestId " + requestId + " is not found in DB",
209                                 HttpStatus.SC_NO_CONTENT, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR)
210                                         .errorInfo(errorLoggerInfo).build();
211
212                 throw validateException;
213             }
214
215             Request request = mapInfraActiveRequestToRequest(requestDB);
216             cloudOrchestrationGetResponse.setRequest(request);
217             return builder.buildResponse(HttpStatus.SC_OK, requestId, cloudOrchestrationGetResponse, apiVersion);
218
219         } else {
220             TenantIsolationRequest tenantIsolationRequest = new TenantIsolationRequest();
221             List<InfraActiveRequests> activeRequests;
222             CloudOrchestrationRequestList orchestrationList;
223
224
225             Map<String, String> orchestrationMap;
226             try {
227                 orchestrationMap = tenantIsolationRequest.getOrchestrationFilters(queryParams);
228             } catch (ValidationException ex) {
229                 ErrorLoggerInfo errorLoggerInfo =
230                         new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.BusinessProcesssError)
231                                 .build();
232                 ValidateException validateException =
233                         new ValidateException.Builder(ex.getMessage(), HttpStatus.SC_INTERNAL_SERVER_ERROR,
234                                 ErrorNumbers.SVC_GENERAL_SERVICE_ERROR).cause(ex).errorInfo(errorLoggerInfo).build();
235
236                 throw validateException;
237
238             }
239             activeRequests = requestDbClient.getCloudOrchestrationFiltersFromInfraActive(orchestrationMap);
240             orchestrationList = new CloudOrchestrationRequestList();
241             List<CloudOrchestrationResponse> requestLists = new ArrayList<>();
242
243             for (InfraActiveRequests infraActive : activeRequests) {
244
245                 Request request = mapInfraActiveRequestToRequest(infraActive);
246                 CloudOrchestrationResponse requestList = new CloudOrchestrationResponse();
247                 requestList.setRequest(request);
248                 requestLists.add(requestList);
249             }
250             orchestrationList.setRequestList(requestLists);
251
252             return builder.buildResponse(HttpStatus.SC_OK, null, orchestrationList, apiVersion);
253         }
254     }
255
256     private Request mapInfraActiveRequestToRequest(InfraActiveRequests iar) throws ApiException {
257         Request request = new Request();
258         request.setRequestId(iar.getRequestId());
259         request.setRequestScope(iar.getRequestScope());
260         request.setRequestType(iar.getRequestAction());
261
262         InstanceReferences ir = new InstanceReferences();
263
264         if (iar.getOperationalEnvId() != null)
265             ir.setOperationalEnvironmentId(iar.getOperationalEnvId());
266         if (iar.getOperationalEnvName() != null)
267             ir.setOperationalEnvName(iar.getOperationalEnvName());
268         if (iar.getRequestorId() != null)
269             ir.setRequestorId(iar.getRequestorId());
270
271         request.setInstanceReferences(ir);
272         String requestBody = iar.getRequestBody();
273         RequestDetails requestDetails = null;
274
275         if (requestBody != null) {
276             try {
277                 ObjectMapper mapper = new ObjectMapper();
278                 requestDetails = mapper.readValue(requestBody, RequestDetails.class);
279             } catch (IOException e) {
280                 ErrorLoggerInfo errorLoggerInfo =
281                         new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError)
282                                 .build();
283                 ValidateException validateException =
284                         new ValidateException.Builder("Mapping of request to JSON object failed.  " + e.getMessage(),
285                                 HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e)
286                                         .errorInfo(errorLoggerInfo).build();
287                 throw validateException;
288             }
289         }
290
291         request.setRequestDetails(requestDetails);
292         String startTimeStamp = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss").format(iar.getStartTime()) + " GMT";
293         request.setStartTime(startTimeStamp);
294
295         RequestStatus status = new RequestStatus();
296         if (iar.getStatusMessage() != null) {
297             status.setStatusMessage(iar.getStatusMessage());
298         }
299
300         if (iar.getEndTime() != null) {
301             String endTimeStamp = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss").format(iar.getEndTime()) + " GMT";
302             status.setTimeStamp(endTimeStamp);
303         }
304
305         if (iar.getRequestStatus() != null) {
306             status.setRequestState(iar.getRequestStatus());
307         }
308
309         if (iar.getProgress() != null) {
310             status.setPercentProgress(iar.getProgress().toString());
311         }
312
313         request.setRequestStatus(status);
314
315         return request;
316     }
317
318 }