a9cf35796b5b716405714784d813feafbfc0ff01
[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                                 infraActiveRequest.setRequestId(requestId);
128                                 requestDbClient.save(infraActiveRequest);
129                         }else{
130                                 ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND,MsoLogger.ErrorCode.DataError).build();
131                                 ValidateException validateException = new ValidateException.Builder("Orchestration RequestId " + requestId + " has a status of " + status + " and can not be unlocked",
132                                                 HttpStatus.SC_BAD_REQUEST,ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
133
134                                 throw validateException;
135                         }
136                 }
137
138                 return Response.status (HttpStatus.SC_NO_CONTENT).entity ("").build ();
139         }
140
141         @GET
142         @Path("/{version:[vV][1]}")
143         @Consumes(MediaType.APPLICATION_JSON)
144         @Produces(MediaType.APPLICATION_JSON)
145         @ApiOperation(value="Get status of an Operational Environment based on filter criteria",response=Response.class)
146         @Transactional
147         public Response getOperationEnvironmentStatusFilter(@Context UriInfo ui, @PathParam("version") String version ) throws ApiException{
148                 MsoLogger.setServiceName ("getOperationEnvironmentStatusFilter");
149                 UUIDChecker.generateUUID(msoLogger);
150
151                 MultivaluedMap<String, String> queryParams = ui.getQueryParameters();
152                 List<String> requestIdKey = queryParams.get("requestId");
153                 String apiVersion = version.substring(1);
154                 
155                 if(queryParams.size() == 1 && requestIdKey != null) {
156                         String requestId = requestIdKey.get(0);
157
158                         CloudOrchestrationResponse cloudOrchestrationGetResponse = new CloudOrchestrationResponse();
159                         TenantIsolationRequest tenantIsolationRequest = new TenantIsolationRequest (requestId);
160                         InfraActiveRequests requestDB = null;
161
162                         try {
163                                 requestDB = requestDbClient.getInfraActiveRequestbyRequestId(requestId);
164                         } catch (Exception e) {
165                                 ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, MsoLogger.ErrorCode.AvailabilityError).build();
166                                 AlarmLoggerInfo alarmLoggerInfo = new AlarmLoggerInfo.Builder("MsoDatabaseAccessError", MsoAlarmLogger.CRITICAL,
167                                                 Messages.getErrors().get (ErrorNumbers.NO_COMMUNICATION_TO_REQUESTS_DB)).build();
168                                 ValidateException validateException = new ValidateException.Builder(e.getMessage(), HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e)
169                                                 .errorInfo(errorLoggerInfo).alarmInfo(alarmLoggerInfo).build();
170
171                                 throw validateException;
172                                 //              TODO Will need to set Status  for  tenantIsolationRequest
173                                 //             tenantIsolationRequest.setStatus (org.onap.so.apihandlerinfra.vnfbeans.RequestStatusType.FAILED);
174                         }
175
176                         if(requestDB == null) {
177                                 ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_COMMUNICATE_ERROR, MsoLogger.ErrorCode.BusinessProcesssError).build();
178                                 ValidateException validateException = new ValidateException.Builder("Orchestration RequestId " + requestId + " is not found in DB",
179                                                 HttpStatus.SC_NO_CONTENT, ErrorNumbers.SVC_DETAILED_SERVICE_ERROR)
180                                                 .errorInfo(errorLoggerInfo).build();
181
182                                 throw validateException;
183                         }
184
185                         Request request = mapInfraActiveRequestToRequest(requestDB);
186                         cloudOrchestrationGetResponse.setRequest(request);
187                         return builder.buildResponse(HttpStatus.SC_OK, requestId, cloudOrchestrationGetResponse, apiVersion);
188
189                 } else  {
190                         TenantIsolationRequest tenantIsolationRequest = new TenantIsolationRequest ();
191                         List<InfraActiveRequests> activeRequests = null;
192                         CloudOrchestrationRequestList orchestrationList = null;
193
194
195                         Map<String, String> orchestrationMap;
196                         try{
197                                 orchestrationMap = tenantIsolationRequest.getOrchestrationFilters(queryParams);
198                         }catch(ValidationException ex){
199                                 ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_GENERAL_EXCEPTION, MsoLogger.ErrorCode.BusinessProcesssError).build();
200                                 ValidateException validateException = new ValidateException.Builder(ex.getMessage(),
201                                                 HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_GENERAL_SERVICE_ERROR).cause(ex)
202                                                 .errorInfo(errorLoggerInfo).build();
203
204                                 throw validateException;
205
206                         }
207                         activeRequests = requestDbClient.getCloudOrchestrationFiltersFromInfraActive(orchestrationMap);
208                         orchestrationList = new CloudOrchestrationRequestList();
209                         List<CloudOrchestrationResponse> requestLists = new ArrayList<CloudOrchestrationResponse>();
210
211                         for(InfraActiveRequests infraActive : activeRequests){
212
213                                 Request request = mapInfraActiveRequestToRequest(infraActive);
214                                 CloudOrchestrationResponse requestList = new CloudOrchestrationResponse();
215                                 requestList.setRequest(request);
216                                 requestLists.add(requestList);
217                         }
218                         orchestrationList.setRequestList(requestLists);
219
220                         return builder.buildResponse(HttpStatus.SC_OK, null, orchestrationList, apiVersion);
221                 }
222         }
223         
224         private Request mapInfraActiveRequestToRequest(InfraActiveRequests iar) throws ApiException  {
225                 Request request = new Request();
226                 request.setRequestId(iar.getRequestId());
227                 request.setRequestScope(iar.getRequestScope());
228                 request.setRequestType(iar.getRequestAction());
229
230                 InstanceReferences ir = new InstanceReferences();
231
232                 if(iar.getOperationalEnvId() != null)
233                         ir.setOperationalEnvironmentId(iar.getOperationalEnvId());
234                 if(iar.getOperationalEnvName() != null)
235                         ir.setOperationalEnvName(iar.getOperationalEnvName());
236                 if(iar.getRequestorId() != null)
237                         ir.setRequestorId(iar.getRequestorId());
238
239                 request.setInstanceReferences(ir);
240                 String requestBody = iar.getRequestBody();
241                 RequestDetails requestDetails = null;
242
243                 if (requestBody != null) {
244                         try {
245                                 ObjectMapper mapper = new ObjectMapper();
246                                 requestDetails = mapper.readValue(requestBody, RequestDetails.class);
247                         } catch (IOException e) {
248                                 ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, MsoLogger.ErrorCode.SchemaError).build();
249                                 ValidateException validateException = new ValidateException.Builder("Mapping of request to JSON object failed.  " + e.getMessage(), HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER)
250                                                 .cause(e).errorInfo(errorLoggerInfo).build();
251                                 throw validateException;
252                         }
253                 }
254
255                 request.setRequestDetails(requestDetails);
256                 String startTimeStamp = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss").format(iar.getStartTime()) + " GMT";
257                 request.setStartTime(startTimeStamp);
258
259                 RequestStatus status = new RequestStatus();
260                 if(iar.getStatusMessage() != null){
261                         status.setStatusMessage(iar.getStatusMessage());
262                 }
263
264                 if(iar.getEndTime() != null){
265                         String endTimeStamp = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss").format(iar.getEndTime()) + " GMT";
266                         status.setTimeStamp(endTimeStamp);
267                 }
268
269                 if(iar.getRequestStatus() != null){
270                         status.setRequestState(iar.getRequestStatus());
271                 }
272
273                 if(iar.getProgress() != null){
274                         status.setPercentProgress(iar.getProgress().toString());
275                 }
276
277                 request.setRequestStatus(status);
278
279                 return request;
280         }
281
282 }