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