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