9305b80c13bb3328337f0eadd51997d2238bbe42
[so.git] / mso-api-handlers / mso-api-handler-infra / src / main / java / org / onap / so / apihandlerinfra / tenantisolation / CloudResourcesOrchestration.java
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
31 import javax.transaction.Transactional;
32 import javax.ws.rs.Consumes;
33 import javax.ws.rs.GET;
34 import javax.ws.rs.POST;
35 import javax.ws.rs.Path;
36 import javax.ws.rs.PathParam;
37 import javax.ws.rs.Produces;
38 import javax.ws.rs.core.Context;
39 import javax.ws.rs.core.MediaType;
40 import javax.ws.rs.core.MultivaluedMap;
41 import javax.ws.rs.core.Response;
42 import javax.ws.rs.core.UriInfo;
43
44 import org.apache.http.HttpStatus;
45 import org.onap.so.apihandler.common.ErrorNumbers;
46 import org.onap.so.apihandler.common.ResponseBuilder;
47 import org.onap.so.apihandlerinfra.Constants;
48 import org.onap.so.apihandlerinfra.Messages;
49 import org.onap.so.apihandlerinfra.exceptions.ApiException;
50 import org.onap.so.apihandlerinfra.exceptions.ValidateException;
51
52 import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo;
53 import org.onap.so.apihandlerinfra.tenantisolationbeans.CloudOrchestrationRequestList;
54 import org.onap.so.apihandlerinfra.tenantisolationbeans.CloudOrchestrationResponse;
55 import org.onap.so.apihandlerinfra.tenantisolationbeans.InstanceReferences;
56 import org.onap.so.apihandlerinfra.tenantisolationbeans.Request;
57 import org.onap.so.apihandlerinfra.tenantisolationbeans.RequestDetails;
58 import org.onap.so.apihandlerinfra.tenantisolationbeans.RequestStatus;
59 import org.onap.so.db.request.beans.InfraActiveRequests;
60 import org.onap.so.db.request.client.RequestsDbClient;
61 import org.onap.so.exceptions.ValidationException;
62 import org.onap.so.logger.MessageEnum;
63
64 import org.onap.so.logger.MsoLogger;
65 import org.slf4j.Logger;
66 import org.slf4j.LoggerFactory;
67 import org.springframework.beans.factory.annotation.Autowired;
68 import org.springframework.stereotype.Component;
69
70 import com.fasterxml.jackson.databind.ObjectMapper;
71
72 import io.swagger.annotations.Api;
73 import io.swagger.annotations.ApiOperation;
74
75 @Component
76 @Path("onap/so/infra/cloudResourcesRequests")
77 @Api(value="onap/so/infra/cloudResourcesRequests",description="API GET Requests for cloud resources - Tenant Isolation")
78 public class CloudResourcesOrchestration {
79
80         private static Logger logger = LoggerFactory.getLogger(CloudResourcesOrchestration.class);
81
82         @Autowired
83         RequestsDbClient requestDbClient;
84
85         @Autowired
86         private ResponseBuilder builder;
87         
88         @POST
89         @Path("/{version: [vV][1]}/{requestId}/unlock")
90         @Consumes(MediaType.APPLICATION_JSON)
91         @Produces(MediaType.APPLICATION_JSON)
92         @ApiOperation(value="Unlock CloudOrchestration requests for a specified requestId")
93         @Transactional
94         public Response unlockOrchestrationRequest(String requestJSON, @PathParam("requestId") String requestId, @PathParam("version") String version) throws ApiException{
95                 TenantIsolationRequest msoRequest = new TenantIsolationRequest(requestId);
96                 InfraActiveRequests infraActiveRequest = null;
97
98                 CloudOrchestrationRequest cor = null;
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 = new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR,MsoLogger.ErrorCode.SchemaError).build();
107
108                         ValidateException validateException = new ValidateException.Builder("Mapping of request to JSON object failed.  " + e.getMessage(), HttpStatus.SC_BAD_REQUEST,ErrorNumbers.SVC_BAD_PARAMETER)
109                                         .cause(e).errorInfo(errorLoggerInfo).build();
110                         throw validateException;
111                 }
112
113                 try{
114                         msoRequest.parseOrchestration(cor);
115                 } catch (ValidationException e) {
116                         ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR,MsoLogger.ErrorCode.SchemaError).build();
117                         ValidateException validateException = new ValidateException.Builder(e.getMessage(), HttpStatus.SC_BAD_REQUEST,ErrorNumbers.SVC_BAD_PARAMETER)
118                                         .cause(e).errorInfo(errorLoggerInfo).build();
119                         throw validateException;
120                 }
121                 try {
122                         infraActiveRequest = requestDbClient.getInfraActiveRequestbyRequestId(requestId);
123                 }catch(Exception e){                    
124                         ValidateException validateException = new ValidateException.Builder(e.getMessage(), HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e).build();
125                         throw validateException;
126                 }
127                 if(infraActiveRequest == null) {
128
129                         ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND,MsoLogger.ErrorCode.BusinessProcesssError).build();
130                         ValidateException validateException = new ValidateException.Builder("Orchestration RequestId " + requestId + " is not found in DB", HttpStatus.SC_BAD_REQUEST,ErrorNumbers.SVC_DETAILED_SERVICE_ERROR)
131                                         .errorInfo(errorLoggerInfo).build();
132
133                         throw validateException;
134
135                 }else{
136                         String status = infraActiveRequest.getRequestStatus();
137                         if(status.equalsIgnoreCase("IN_PROGRESS") || status.equalsIgnoreCase("PENDING") || status.equalsIgnoreCase("PENDING_MANUAL_TASK")){
138                                 infraActiveRequest.setRequestStatus("UNLOCKED");
139                                 infraActiveRequest.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER);
140                                 infraActiveRequest.setRequestId(requestId);
141                                 requestDbClient.save(infraActiveRequest);
142                         }else{
143                                 ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND,MsoLogger.ErrorCode.DataError).build();
144                                 ValidateException validateException = new ValidateException.Builder("Orchestration RequestId " + requestId + " has a status of " + status + " and can not be unlocked",
145                                                 HttpStatus.SC_BAD_REQUEST,ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
146
147                                 throw validateException;
148                         }
149                 }
150
151                 return Response.status (HttpStatus.SC_NO_CONTENT).entity ("").build ();
152         }
153
154         @GET
155         @Path("/{version:[vV][1]}")
156         @Consumes(MediaType.APPLICATION_JSON)
157         @Produces(MediaType.APPLICATION_JSON)
158         @ApiOperation(value="Get status of an Operational Environment based on filter criteria",response=Response.class)
159         @Transactional
160         public Response getOperationEnvironmentStatusFilter(@Context UriInfo ui, @PathParam("version") String version ) throws ApiException{
161
162                 MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
163                 List<String> requestIdKey = queryParams.get("requestId");
164                 String apiVersion = version.substring(1);
165                 
166                 if(queryParams.size() == 1 && requestIdKey != null) {
167                         String requestId = requestIdKey.get(0);
168
169                         CloudOrchestrationResponse cloudOrchestrationGetResponse = new CloudOrchestrationResponse();
170                         TenantIsolationRequest tenantIsolationRequest = new TenantIsolationRequest (requestId);
171                         InfraActiveRequests requestDB = null;
172
173                         try {
174                                 requestDB = requestDbClient.getInfraActiveRequestbyRequestId(requestId);
175                         } catch (Exception e) {
176                                 ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, MsoLogger.ErrorCode.AvailabilityError).build();
177                                 ValidateException validateException = new ValidateException.Builder(e.getMessage(), HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e)
178                                                 .errorInfo(errorLoggerInfo).build();
179                                 throw validateException;                                
180                         }
181
182                         if(requestDB == null) {
183                                 ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, MsoLogger.ErrorCode.BusinessProcesssError).build();
184                                 ValidateException validateException = new ValidateException.Builder("Orchestration RequestId " + requestId + " is not found in DB",
185                                                 HttpStatus.SC_NO_CONTENT, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR)
186                                                 .errorInfo(errorLoggerInfo).build();
187
188                                 throw validateException;
189                         }
190
191                         Request request = mapInfraActiveRequestToRequest(requestDB);
192                         cloudOrchestrationGetResponse.setRequest(request);
193                         return builder.buildResponse(HttpStatus.SC_OK, requestId, cloudOrchestrationGetResponse, apiVersion);
194
195                 } else  {
196                         TenantIsolationRequest tenantIsolationRequest = new TenantIsolationRequest ();
197                         List<InfraActiveRequests> activeRequests = null;
198                         CloudOrchestrationRequestList orchestrationList = null;
199
200
201                         Map<String, String> orchestrationMap;
202                         try{
203                                 orchestrationMap = tenantIsolationRequest.getOrchestrationFilters(queryParams);
204                         }catch(ValidationException ex){
205                                 ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, MsoLogger.ErrorCode.BusinessProcesssError).build();
206                                 ValidateException validateException = new ValidateException.Builder(ex.getMessage(),
207                                                 HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_GENERAL_SERVICE_ERROR).cause(ex)
208                                                 .errorInfo(errorLoggerInfo).build();
209
210                                 throw validateException;
211
212                         }
213                         activeRequests = requestDbClient.getCloudOrchestrationFiltersFromInfraActive(orchestrationMap);
214                         orchestrationList = new CloudOrchestrationRequestList();
215                         List<CloudOrchestrationResponse> requestLists = new ArrayList<CloudOrchestrationResponse>();
216
217                         for(InfraActiveRequests infraActive : activeRequests){
218
219                                 Request request = mapInfraActiveRequestToRequest(infraActive);
220                                 CloudOrchestrationResponse requestList = new CloudOrchestrationResponse();
221                                 requestList.setRequest(request);
222                                 requestLists.add(requestList);
223                         }
224                         orchestrationList.setRequestList(requestLists);
225
226                         return builder.buildResponse(HttpStatus.SC_OK, null, orchestrationList, apiVersion);
227                 }
228         }
229         
230         private Request mapInfraActiveRequestToRequest(InfraActiveRequests iar) throws ApiException  {
231                 Request request = new Request();
232                 request.setRequestId(iar.getRequestId());
233                 request.setRequestScope(iar.getRequestScope());
234                 request.setRequestType(iar.getRequestAction());
235
236                 InstanceReferences ir = new InstanceReferences();
237
238                 if(iar.getOperationalEnvId() != null)
239                         ir.setOperationalEnvironmentId(iar.getOperationalEnvId());
240                 if(iar.getOperationalEnvName() != null)
241                         ir.setOperationalEnvName(iar.getOperationalEnvName());
242                 if(iar.getRequestorId() != null)
243                         ir.setRequestorId(iar.getRequestorId());
244
245                 request.setInstanceReferences(ir);
246                 String requestBody = iar.getRequestBody();
247                 RequestDetails requestDetails = null;
248
249                 if (requestBody != null) {
250                         try {
251                                 ObjectMapper mapper = new ObjectMapper();
252                                 requestDetails = mapper.readValue(requestBody, RequestDetails.class);
253                         } catch (IOException e) {
254                                 ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, MsoLogger.ErrorCode.SchemaError).build();
255                                 ValidateException validateException = new ValidateException.Builder("Mapping of request to JSON object failed.  " + e.getMessage(), HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER)
256                                                 .cause(e).errorInfo(errorLoggerInfo).build();
257                                 throw validateException;
258                         }
259                 }
260
261                 request.setRequestDetails(requestDetails);
262                 String startTimeStamp = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss").format(iar.getStartTime()) + " GMT";
263                 request.setStartTime(startTimeStamp);
264
265                 RequestStatus status = new RequestStatus();
266                 if(iar.getStatusMessage() != null){
267                         status.setStatusMessage(iar.getStatusMessage());
268                 }
269
270                 if(iar.getEndTime() != null){
271                         String endTimeStamp = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss").format(iar.getEndTime()) + " GMT";
272                         status.setTimeStamp(endTimeStamp);
273                 }
274
275                 if(iar.getRequestStatus() != null){
276                         status.setRequestState(iar.getRequestStatus());
277                 }
278
279                 if(iar.getProgress() != null){
280                         status.setPercentProgress(iar.getProgress().toString());
281                 }
282
283                 request.setRequestStatus(status);
284
285                 return request;
286         }
287
288 }