59c0694ea26bc3e4ecdbf73e46ffb43d9f1f1256
[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.logging.filter.base.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 =
138                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND, ErrorCode.BusinessProcessError)
139                             .build();
140             ValidateException validateException =
141                     new ValidateException.Builder("Orchestration RequestId " + requestId + " is not found in DB",
142                             HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR)
143                                     .errorInfo(errorLoggerInfo).build();
144
145             throw validateException;
146
147         } else {
148             String status = infraActiveRequest.getRequestStatus();
149             if ("IN_PROGRESS".equalsIgnoreCase(status) || "PENDING".equalsIgnoreCase(status)
150                     || "PENDING_MANUAL_TASK".equalsIgnoreCase(status)) {
151                 infraActiveRequest.setRequestStatus("UNLOCKED");
152                 infraActiveRequest.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER);
153                 infraActiveRequest.setRequestId(requestId);
154                 requestDbClient.save(infraActiveRequest);
155             } else {
156                 ErrorLoggerInfo errorLoggerInfo =
157                         new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND, ErrorCode.DataError)
158                                 .build();
159                 ValidateException validateException = new ValidateException.Builder(
160                         "Orchestration RequestId " + requestId + " has a status of " + status
161                                 + " and can not be unlocked",
162                         HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo)
163                                 .build();
164
165                 throw validateException;
166             }
167         }
168
169         return Response.status(HttpStatus.SC_NO_CONTENT).entity("").build();
170     }
171
172     @GET
173     @Path("/{version:[vV][1]}")
174     @Consumes(MediaType.APPLICATION_JSON)
175     @Produces(MediaType.APPLICATION_JSON)
176     @Operation(description = "Get status of an Operational Environment based on filter criteria",
177             responses = @ApiResponse(
178                     content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))
179     @Transactional
180     public Response getOperationEnvironmentStatusFilter(@Context UriInfo ui, @PathParam("version") String version)
181             throws ApiException {
182
183         MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
184         List<String> requestIdKey = queryParams.get("requestId");
185         String apiVersion = version.substring(1);
186
187         if (queryParams.size() == 1 && requestIdKey != null) {
188             String requestId = requestIdKey.get(0);
189
190             CloudOrchestrationResponse cloudOrchestrationGetResponse = new CloudOrchestrationResponse();
191             InfraActiveRequests requestDB;
192
193             try {
194                 requestDB = requestDbClient.getInfraActiveRequestbyRequestId(requestId);
195             } catch (Exception e) {
196                 ErrorLoggerInfo errorLoggerInfo =
197                         new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, ErrorCode.AvailabilityError)
198                                 .build();
199                 ValidateException validateException =
200                         new ValidateException.Builder(e.getMessage(), HttpStatus.SC_INTERNAL_SERVER_ERROR,
201                                 ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e).errorInfo(errorLoggerInfo).build();
202                 throw validateException;
203             }
204
205             if (requestDB == null) {
206                 ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR,
207                         ErrorCode.BusinessProcessError).build();
208                 ValidateException validateException =
209                         new ValidateException.Builder("Orchestration RequestId " + requestId + " is not found in DB",
210                                 HttpStatus.SC_NO_CONTENT, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR)
211                                         .errorInfo(errorLoggerInfo).build();
212
213                 throw validateException;
214             }
215
216             Request request = mapInfraActiveRequestToRequest(requestDB);
217             cloudOrchestrationGetResponse.setRequest(request);
218             return builder.buildResponse(HttpStatus.SC_OK, requestId, cloudOrchestrationGetResponse, apiVersion);
219
220         } else {
221             TenantIsolationRequest tenantIsolationRequest = new TenantIsolationRequest();
222             List<InfraActiveRequests> activeRequests;
223             CloudOrchestrationRequestList orchestrationList;
224
225
226             Map<String, String> orchestrationMap;
227             try {
228                 orchestrationMap = tenantIsolationRequest.getOrchestrationFilters(queryParams);
229             } catch (ValidationException ex) {
230                 ErrorLoggerInfo errorLoggerInfo =
231                         new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, ErrorCode.BusinessProcessError)
232                                 .build();
233                 ValidateException validateException =
234                         new ValidateException.Builder(ex.getMessage(), HttpStatus.SC_INTERNAL_SERVER_ERROR,
235                                 ErrorNumbers.SVC_GENERAL_SERVICE_ERROR).cause(ex).errorInfo(errorLoggerInfo).build();
236
237                 throw validateException;
238
239             }
240             activeRequests = requestDbClient.getCloudOrchestrationFiltersFromInfraActive(orchestrationMap);
241             orchestrationList = new CloudOrchestrationRequestList();
242             List<CloudOrchestrationResponse> requestLists = new ArrayList<>();
243
244             for (InfraActiveRequests infraActive : activeRequests) {
245
246                 Request request = mapInfraActiveRequestToRequest(infraActive);
247                 CloudOrchestrationResponse requestList = new CloudOrchestrationResponse();
248                 requestList.setRequest(request);
249                 requestLists.add(requestList);
250             }
251             orchestrationList.setRequestList(requestLists);
252
253             return builder.buildResponse(HttpStatus.SC_OK, null, orchestrationList, apiVersion);
254         }
255     }
256
257     private Request mapInfraActiveRequestToRequest(InfraActiveRequests iar) throws ApiException {
258         Request request = new Request();
259         request.setRequestId(iar.getRequestId());
260         request.setRequestScope(iar.getRequestScope());
261         request.setRequestType(iar.getRequestAction());
262
263         InstanceReferences ir = new InstanceReferences();
264
265         if (iar.getOperationalEnvId() != null)
266             ir.setOperationalEnvironmentId(iar.getOperationalEnvId());
267         if (iar.getOperationalEnvName() != null)
268             ir.setOperationalEnvName(iar.getOperationalEnvName());
269         if (iar.getRequestorId() != null)
270             ir.setRequestorId(iar.getRequestorId());
271
272         request.setInstanceReferences(ir);
273         String requestBody = iar.getRequestBody();
274         RequestDetails requestDetails = null;
275
276         if (requestBody != null) {
277             try {
278                 ObjectMapper mapper = new ObjectMapper();
279                 requestDetails = mapper.readValue(requestBody, RequestDetails.class);
280             } catch (IOException e) {
281                 ErrorLoggerInfo errorLoggerInfo =
282                         new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError)
283                                 .build();
284                 ValidateException validateException =
285                         new ValidateException.Builder("Mapping of request to JSON object failed.  " + e.getMessage(),
286                                 HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e)
287                                         .errorInfo(errorLoggerInfo).build();
288                 throw validateException;
289             }
290         }
291
292         request.setRequestDetails(requestDetails);
293         String startTimeStamp = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss").format(iar.getStartTime()) + " GMT";
294         request.setStartTime(startTimeStamp);
295
296         RequestStatus status = new RequestStatus();
297         if (iar.getStatusMessage() != null) {
298             status.setStatusMessage(iar.getStatusMessage());
299         }
300
301         if (iar.getEndTime() != null) {
302             String endTimeStamp = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss").format(iar.getEndTime()) + " GMT";
303             status.setTimeStamp(endTimeStamp);
304         }
305
306         if (iar.getRequestStatus() != null) {
307             status.setRequestState(iar.getRequestStatus());
308         }
309
310         if (iar.getProgress() != null) {
311             status.setPercentProgress(iar.getProgress().toString());
312         }
313
314         request.setRequestStatus(status);
315
316         return request;
317     }
318
319 }