Containerization feature of SO
[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.HttpHeaders;
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
43 import org.apache.http.HttpStatus;
44 import org.onap.so.apihandler.common.CommonConstants;
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 import org.onap.so.apihandlerinfra.logging.AlarmLoggerInfo;
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.data.repository.InfraActiveRequestsRepository;
61 import org.onap.so.exceptions.ValidationException;
62 import org.onap.so.logger.MessageEnum;
63 import org.onap.so.logger.MsoAlarmLogger;
64 import org.onap.so.logger.MsoLogger;
65 import org.onap.so.utils.UUIDChecker;
66 import org.springframework.beans.factory.annotation.Autowired;
67 import org.springframework.core.env.Environment;
68 import org.springframework.stereotype.Component;
69
70 import com.fasterxml.jackson.databind.ObjectMapper;
71 import com.wordnik.swagger.annotations.Api;
72 import com.wordnik.swagger.annotations.ApiOperation;
73
74 @Component
75 @Path("onap/so/infra/cloudResourcesRequests")
76 @Api(value="onap/so/infra/cloudResourcesRequests",description="API GET Requests for cloud resources - Tenant Isolation")
77 public class CloudResourcesOrchestration {
78
79         private static MsoLogger msoLogger = MsoLogger.getMsoLogger (MsoLogger.Catalog.APIH, CloudResourcesOrchestration.class);
80         private static MsoAlarmLogger alarmLogger = new MsoAlarmLogger ();
81         @Autowired
82         private InfraActiveRequestsRepository iarRepo;
83         @Autowired
84         private InfraActiveRequestsRepository infraActiveRequestsRepository;
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                 msoLogger.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 = infraActiveRequestsRepository.findOneByRequestIdOrClientRequestId(requestId, requestId);
123                 }catch(Exception e){
124                         ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, MsoLogger.ErrorCode.AvailabilityError).build();
125                         AlarmLoggerInfo alarmLoggerInfo = new AlarmLoggerInfo.Builder("MsoDatabaseAccessError", MsoAlarmLogger.CRITICAL,
126                                         Messages.getErrors().get (ErrorNumbers.NO_COMMUNICATION_TO_REQUESTS_DB)).build();
127                         ValidateException validateException = new ValidateException.Builder(e.getMessage(), HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e)
128                                         .errorInfo(errorLoggerInfo).alarmInfo(alarmLoggerInfo).build();
129
130                         throw validateException;
131                 }
132                 if(infraActiveRequest == null) {
133
134                         ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND,MsoLogger.ErrorCode.BusinessProcesssError).build();
135                         ValidateException validateException = new ValidateException.Builder("Orchestration RequestId " + requestId + " is not found in DB", HttpStatus.SC_BAD_REQUEST,ErrorNumbers.SVC_DETAILED_SERVICE_ERROR)
136                                         .errorInfo(errorLoggerInfo).build();
137
138                         throw validateException;
139
140                 }else{
141                         String status = infraActiveRequest.getRequestStatus();
142                         if(status.equalsIgnoreCase("IN_PROGRESS") || status.equalsIgnoreCase("PENDING") || status.equalsIgnoreCase("PENDING_MANUAL_TASK")){
143                                 infraActiveRequest.setRequestStatus("UNLOCKED");
144                                 infraActiveRequest.setLastModifiedBy(Constants.MODIFIED_BY_APIHANDLER);
145                                 infraActiveRequestsRepository.save(infraActiveRequest);
146                         }else{
147                                 ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND,MsoLogger.ErrorCode.DataError).build();
148                                 ValidateException validateException = new ValidateException.Builder("Orchestration RequestId " + requestId + " has a status of " + status + " and can not be unlocked",
149                                                 HttpStatus.SC_BAD_REQUEST,ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
150
151                                 throw validateException;
152                         }
153                 }
154
155                 return Response.status (HttpStatus.SC_NO_CONTENT).entity ("").build ();
156         }
157
158         @GET
159         @Path("/{version:[vV][1]}")
160         @Consumes(MediaType.APPLICATION_JSON)
161         @Produces(MediaType.APPLICATION_JSON)
162         @ApiOperation(value="Get status of an Operational Environment based on filter criteria",response=Response.class)
163         @Transactional
164         public Response getOperationEnvironmentStatusFilter(@Context UriInfo ui, @PathParam("version") String version ) throws ApiException{
165                 MsoLogger.setServiceName ("getOperationEnvironmentStatusFilter");
166                 UUIDChecker.generateUUID(msoLogger);
167
168                 MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
169                 List<String> requestIdKey = queryParams.get("requestId");
170                 String apiVersion = version.substring(1);
171                 
172                 if(queryParams.size() == 1 && requestIdKey != null) {
173                         String requestId = requestIdKey.get(0);
174
175                         CloudOrchestrationResponse cloudOrchestrationGetResponse = new CloudOrchestrationResponse();
176                         TenantIsolationRequest tenantIsolationRequest = new TenantIsolationRequest (requestId);
177                         InfraActiveRequests requestDB = null;
178
179                         try {
180                                 requestDB = infraActiveRequestsRepository.findOneByRequestIdOrClientRequestId(requestId, requestId);
181                         } catch (Exception e) {
182                                 ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, MsoLogger.ErrorCode.AvailabilityError).build();
183                                 AlarmLoggerInfo alarmLoggerInfo = new AlarmLoggerInfo.Builder("MsoDatabaseAccessError", MsoAlarmLogger.CRITICAL,
184                                                 Messages.getErrors().get (ErrorNumbers.NO_COMMUNICATION_TO_REQUESTS_DB)).build();
185                                 ValidateException validateException = new ValidateException.Builder(e.getMessage(), HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e)
186                                                 .errorInfo(errorLoggerInfo).alarmInfo(alarmLoggerInfo).build();
187
188                                 throw validateException;
189                                 //              TODO Will need to set Status  for  tenantIsolationRequest
190                                 //             tenantIsolationRequest.setStatus (org.onap.so.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);
191                         }
192
193                         if(requestDB == null) {
194                                 ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, MsoLogger.ErrorCode.BusinessProcesssError).build();
195                                 ValidateException validateException = new ValidateException.Builder("Orchestration RequestId " + requestId + " is not found in DB",
196                                                 HttpStatus.SC_NO_CONTENT, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR)
197                                                 .errorInfo(errorLoggerInfo).build();
198
199                                 throw validateException;
200                         }
201
202                         Request request = mapInfraActiveRequestToRequest(requestDB);
203                         cloudOrchestrationGetResponse.setRequest(request);
204                         return builder.buildResponse(HttpStatus.SC_OK, requestId, cloudOrchestrationGetResponse, apiVersion);
205
206                 } else  {
207                         TenantIsolationRequest tenantIsolationRequest = new TenantIsolationRequest ();
208                         List<InfraActiveRequests> activeRequests = null;
209                         CloudOrchestrationRequestList orchestrationList = null;
210
211
212                         Map<String, String> orchestrationMap;
213                         try{
214                                 orchestrationMap = tenantIsolationRequest.getOrchestrationFilters(queryParams);
215                         }catch(ValidationException ex){
216                                 ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, MsoLogger.ErrorCode.BusinessProcesssError).build();
217                                 ValidateException validateException = new ValidateException.Builder(ex.getMessage(),
218                                                 HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_GENERAL_SERVICE_ERROR).cause(ex)
219                                                 .errorInfo(errorLoggerInfo).build();
220
221                                 throw validateException;
222
223                         }
224                         activeRequests = iarRepo.getCloudOrchestrationFiltersFromInfraActive(orchestrationMap);
225                         orchestrationList = new CloudOrchestrationRequestList();
226                         List<CloudOrchestrationResponse> requestLists = new ArrayList<CloudOrchestrationResponse>();
227
228                         for(InfraActiveRequests infraActive : activeRequests){
229
230                                 Request request = mapInfraActiveRequestToRequest(infraActive);
231                                 CloudOrchestrationResponse requestList = new CloudOrchestrationResponse();
232                                 requestList.setRequest(request);
233                                 requestLists.add(requestList);
234                         }
235                         orchestrationList.setRequestList(requestLists);
236
237                         return builder.buildResponse(HttpStatus.SC_OK, null, orchestrationList, apiVersion);
238                 }
239         }
240         
241         private Request mapInfraActiveRequestToRequest(InfraActiveRequests iar) throws ApiException  {
242                 Request request = new Request();
243                 request.setRequestId(iar.getRequestId());
244                 request.setRequestScope(iar.getRequestScope());
245                 request.setRequestType(iar.getRequestAction());
246
247                 InstanceReferences ir = new InstanceReferences();
248
249                 if(iar.getOperationalEnvId() != null)
250                         ir.setOperationalEnvironmentId(iar.getOperationalEnvId());
251                 if(iar.getOperationalEnvName() != null)
252                         ir.setOperationalEnvName(iar.getOperationalEnvName());
253                 if(iar.getRequestorId() != null)
254                         ir.setRequestorId(iar.getRequestorId());
255
256                 request.setInstanceReferences(ir);
257                 String requestBody = iar.getRequestBody();
258                 RequestDetails requestDetails = null;
259
260                 try{
261                         ObjectMapper mapper = new ObjectMapper();
262                         requestDetails = mapper.readValue(requestBody, RequestDetails.class);
263                 }catch(IOException e){
264                         ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR,MsoLogger.ErrorCode.SchemaError).build();
265                         ValidateException validateException = new ValidateException.Builder("Mapping of request to JSON object failed.  " + e.getMessage(), HttpStatus.SC_BAD_REQUEST,ErrorNumbers.SVC_BAD_PARAMETER)
266                                         .cause(e).errorInfo(errorLoggerInfo).build();
267                         throw validateException;
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 }