d82fd38e9ffdd03b694c6e24c6a09fbf58b4eb94
[so.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2019 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 package org.onap.so.apihandlerinfra;
21
22 import java.io.IOException;
23 import java.sql.Timestamp;
24 import java.util.HashMap;
25 import javax.transaction.Transactional;
26 import javax.ws.rs.Consumes;
27 import javax.ws.rs.POST;
28 import javax.ws.rs.Path;
29 import javax.ws.rs.PathParam;
30 import javax.ws.rs.Produces;
31 import javax.ws.rs.container.ContainerRequestContext;
32 import javax.ws.rs.core.Context;
33 import javax.ws.rs.core.MediaType;
34 import javax.ws.rs.core.Response;
35 import org.apache.http.HttpStatus;
36 import org.onap.logging.ref.slf4j.ONAPLogConstants;
37 import org.onap.so.apihandler.common.ErrorNumbers;
38 import org.onap.so.apihandler.common.RequestClientParameter;
39 import org.onap.so.apihandlerinfra.exceptions.ApiException;
40 import org.onap.so.apihandlerinfra.exceptions.RequestDbFailureException;
41 import org.onap.so.apihandlerinfra.exceptions.ValidateException;
42 import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo;
43 import org.onap.so.db.request.beans.InfraActiveRequests;
44 import org.onap.so.db.request.client.RequestsDbClient;
45 import org.onap.so.logger.ErrorCode;
46 import org.onap.so.logger.HttpHeadersConstants;
47 import org.onap.so.logger.LogConstants;
48 import org.onap.so.logger.MdcConstants;
49 import org.onap.so.logger.MessageEnum;
50 import org.onap.so.serviceinstancebeans.ModelInfo;
51 import org.onap.so.serviceinstancebeans.ModelType;
52 import org.onap.so.serviceinstancebeans.ServiceInstancesRequest;
53 import org.slf4j.Logger;
54 import org.slf4j.LoggerFactory;
55 import org.slf4j.MDC;
56 import org.springframework.beans.factory.annotation.Autowired;
57 import org.springframework.stereotype.Component;
58 import org.springframework.web.client.HttpClientErrorException;
59 import io.swagger.annotations.Api;
60 import io.swagger.annotations.ApiOperation;
61
62 @Path("onap/so/infra/orchestrationRequests")
63 @Api(value = "onap/so/infra/orchestrationRequests")
64 @Component
65 public class ResumeOrchestrationRequest {
66     private static Logger logger = LoggerFactory.getLogger(ResumeOrchestrationRequest.class);
67     private static final String SAVE_TO_DB = "save instance to db";
68     private static String uriPrefix = "/orchestrationRequests/";
69
70     @Autowired
71     private RequestHandlerUtils requestHandlerUtils;
72
73     @Autowired
74     private ServiceInstances serviceInstances;
75
76     @Autowired
77     private RequestsDbClient requestsDbClient;
78
79     @Autowired
80     private MsoRequest msoRequest;
81
82     @POST
83     @Path("/{version:[vV][7]}/{requestId}/resume")
84     @Consumes(MediaType.APPLICATION_JSON)
85     @Produces(MediaType.APPLICATION_JSON)
86     @ApiOperation(value = "Resume request for a given requestId", response = Response.class)
87     @Transactional
88     public Response resumeOrchestrationRequest(@PathParam("requestId") String requestId,
89             @PathParam("version") String version, @Context ContainerRequestContext requestContext) throws ApiException {
90
91         Timestamp startTimeStamp = new Timestamp(System.currentTimeMillis());
92         String currentRequestId = MDC.get(ONAPLogConstants.MDCs.REQUEST_ID);
93         logger.info("Beginning resume operation for new request: {}", currentRequestId);
94         InfraActiveRequests infraActiveRequest = null;
95         String source = MDC.get(MdcConstants.ORIGINAL_PARTNER_NAME);
96         String requestorId = MDC.get(HttpHeadersConstants.REQUESTOR_ID);
97         requestHandlerUtils.getRequestUri(requestContext, uriPrefix);
98         String requestUri = MDC.get(LogConstants.HTTP_URL);
99         version = version.substring(1);
100
101         try {
102             infraActiveRequest = requestsDbClient.getInfraActiveRequestbyRequestId(requestId);
103         } catch (HttpClientErrorException e) {
104             logger.error("Error occurred while performing requestDb lookup by requestId: " + requestId, e);
105             ErrorLoggerInfo errorLoggerInfo =
106                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, ErrorCode.AvailabilityError).build();
107             throw new ValidateException.Builder("Exception while performing requestDb lookup by requestId",
108                     HttpStatus.SC_NOT_FOUND, ErrorNumbers.NO_COMMUNICATION_TO_REQUESTS_DB).cause(e)
109                             .errorInfo(errorLoggerInfo).build();
110         }
111
112         InfraActiveRequests currentActiveRequest = requestHandlerUtils.createNewRecordCopyFromInfraActiveRequest(
113                 infraActiveRequest, currentRequestId, startTimeStamp, source, requestUri, requestorId, requestId);
114
115         if (infraActiveRequest == null) {
116             logger.error("No infraActiveRequest record found for requestId: {} in requesteDb lookup", requestId);
117             ErrorLoggerInfo errorLoggerInfo = new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ATTRIBUTE_NOT_FOUND,
118                     ErrorCode.BusinessProcesssError).build();
119             ValidateException validateException = new ValidateException.Builder(
120                     "Null response from requestDB when searching by requestId: " + requestId, HttpStatus.SC_NOT_FOUND,
121                     ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).errorInfo(errorLoggerInfo).build();
122             requestHandlerUtils.updateStatus(currentActiveRequest, Status.FAILED, validateException.getMessage());
123             throw validateException;
124
125         }
126
127         return resumeRequest(infraActiveRequest, currentActiveRequest, version, requestUri);
128     }
129
130     protected Response resumeRequest(InfraActiveRequests infraActiveRequest, InfraActiveRequests currentActiveRequest,
131             String version, String requestUri) throws ApiException {
132         String requestBody = infraActiveRequest.getRequestBody();
133         Action action = Action.valueOf(infraActiveRequest.getRequestAction());
134         String requestId = currentActiveRequest.getRequestId();
135         String requestScope = infraActiveRequest.getRequestScope();
136         String instanceName = getInstanceName(infraActiveRequest, requestScope, currentActiveRequest);
137         HashMap<String, String> instanceIdMap = setInstanceIdMap(infraActiveRequest, requestScope);
138
139         checkForInProgressRequest(currentActiveRequest, instanceIdMap, requestScope, instanceName, action);
140
141         ServiceInstancesRequest sir = null;
142         sir = requestHandlerUtils.convertJsonToServiceInstanceRequest(requestBody, action, requestId, requestUri);
143         Boolean aLaCarte = sir.getRequestDetails().getRequestParameters().getALaCarte();
144
145         String pnfCorrelationId = serviceInstances.getPnfCorrelationId(sir);
146         RecipeLookupResult recipeLookupResult = serviceInstances.getServiceInstanceOrchestrationURI(sir, action,
147                 msoRequest.getAlacarteFlag(sir), currentActiveRequest);
148
149         requestDbSave(currentActiveRequest);
150
151         if (aLaCarte == null) {
152             aLaCarte = setALaCarteFlagIfNull(requestScope, action);
153         }
154
155         RequestClientParameter requestClientParameter = setRequestClientParameter(recipeLookupResult, version,
156                 infraActiveRequest, currentActiveRequest, pnfCorrelationId, aLaCarte, sir);
157
158         return requestHandlerUtils.postBPELRequest(currentActiveRequest, requestClientParameter,
159                 recipeLookupResult.getOrchestrationURI(), requestScope);
160     }
161
162     protected Boolean setALaCarteFlagIfNull(String requestScope, Action action) {
163         Boolean aLaCarteFlag;
164         if (!requestScope.equalsIgnoreCase(ModelType.service.name()) && action != Action.recreateInstance) {
165             aLaCarteFlag = true;
166         } else {
167             aLaCarteFlag = false;
168         }
169         return aLaCarteFlag;
170     }
171
172     protected HashMap<String, String> setInstanceIdMap(InfraActiveRequests infraActiveRequest, String requestScope) {
173         HashMap<String, String> instanceIdMap = new HashMap<>();
174         ModelType type;
175         try {
176             type = ModelType.valueOf(requestScope);
177             instanceIdMap.put(type.name() + "InstanceId", type.getId(infraActiveRequest));
178         } catch (IllegalArgumentException e) {
179             logger.error("requestScope \"{}\" does not match a ModelType enum.", requestScope);
180         }
181         return instanceIdMap;
182     }
183
184     protected String getInstanceName(InfraActiveRequests infraActiveRequest, String requestScope,
185             InfraActiveRequests currentActiveRequest) throws ValidateException, RequestDbFailureException {
186         ModelType type;
187         String instanceName = "";
188         try {
189             type = ModelType.valueOf(requestScope);
190             instanceName = type.getName(infraActiveRequest);
191         } catch (IllegalArgumentException e) {
192             logger.error("requestScope \"{}\" does not match a ModelType enum.", requestScope);
193             ValidateException validateException = new ValidateException.Builder(
194                     "requestScope: \"" + requestScope + "\" from request: " + infraActiveRequest.getRequestId()
195                             + " does not match a ModelType enum.",
196                     HttpStatus.SC_BAD_REQUEST, ErrorNumbers.SVC_BAD_PARAMETER).cause(e).build();
197             requestHandlerUtils.updateStatus(currentActiveRequest, Status.FAILED, validateException.getMessage());
198             throw validateException;
199         }
200         return instanceName;
201     }
202
203     protected void checkForInProgressRequest(InfraActiveRequests currentActiveRequest,
204             HashMap<String, String> instanceIdMap, String requestScope, String instanceName, Action action)
205             throws ApiException {
206         boolean inProgress = false;
207         InfraActiveRequests requestInProgress = requestHandlerUtils.duplicateCheck(action, instanceIdMap, instanceName,
208                 requestScope, currentActiveRequest);
209         if (requestInProgress != null) {
210             inProgress = requestHandlerUtils.camundaHistoryCheck(requestInProgress, currentActiveRequest);
211         }
212         if (inProgress) {
213             requestHandlerUtils.buildErrorOnDuplicateRecord(currentActiveRequest, action, instanceIdMap, instanceName,
214                     requestScope, requestInProgress);
215         }
216     }
217
218     protected void requestDbSave(InfraActiveRequests currentActiveRequest) throws RequestDbFailureException {
219         try {
220             requestsDbClient.save(currentActiveRequest);
221         } catch (Exception e) {
222             logger.error("Exception while saving request to requestDb", e);
223             ErrorLoggerInfo errorLoggerInfo =
224                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, ErrorCode.DataError)
225                             .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
226             throw new RequestDbFailureException.Builder(SAVE_TO_DB, e.toString(), HttpStatus.SC_INTERNAL_SERVER_ERROR,
227                     ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e).errorInfo(errorLoggerInfo).build();
228         }
229     }
230
231     protected RequestClientParameter setRequestClientParameter(RecipeLookupResult recipeLookupResult, String version,
232             InfraActiveRequests infraActiveRequest, InfraActiveRequests currentActiveRequest, String pnfCorrelationId,
233             Boolean aLaCarte, ServiceInstancesRequest sir) throws ApiException {
234         RequestClientParameter requestClientParameter = null;
235         Action action = Action.valueOf(infraActiveRequest.getRequestAction());
236         ModelInfo modelInfo = sir.getRequestDetails().getModelInfo();
237
238         Boolean isBaseVfModule = false;
239         if (requestHandlerUtils.getModelType(action, modelInfo).equals(ModelType.vfModule)) {
240             isBaseVfModule = requestHandlerUtils.getIsBaseVfModule(modelInfo, action, infraActiveRequest.getVnfType(),
241                     msoRequest.getSDCServiceModelVersion(sir), currentActiveRequest);
242         }
243
244         try {
245             requestClientParameter =
246                     new RequestClientParameter.Builder().setRequestId(currentActiveRequest.getRequestId())
247                             .setBaseVfModule(isBaseVfModule).setRecipeTimeout(recipeLookupResult.getRecipeTimeout())
248                             .setRequestAction(infraActiveRequest.getRequestAction())
249                             .setServiceInstanceId(infraActiveRequest.getServiceInstanceId())
250                             .setPnfCorrelationId(pnfCorrelationId).setVnfId(infraActiveRequest.getVnfId())
251                             .setVfModuleId(infraActiveRequest.getVfModuleId())
252                             .setVolumeGroupId(infraActiveRequest.getVolumeGroupId())
253                             .setNetworkId(infraActiveRequest.getNetworkId())
254                             .setServiceType(infraActiveRequest.getServiceType())
255                             .setVnfType(infraActiveRequest.getVnfType())
256                             .setVfModuleType(msoRequest.getVfModuleType(sir, infraActiveRequest.getRequestScope(),
257                                     action, Integer.parseInt(version)))
258                             .setNetworkType(infraActiveRequest.getNetworkType())
259                             .setRequestDetails(requestHandlerUtils
260                                     .mapJSONtoMSOStyle(infraActiveRequest.getRequestBody(), sir, aLaCarte, action))
261                             .setApiVersion(version).setALaCarte(aLaCarte)
262                             .setRequestUri(currentActiveRequest.getRequestUrl())
263                             .setInstanceGroupId(infraActiveRequest.getInstanceGroupId()).build();
264         } catch (IOException e) {
265             logger.error("IOException while generating requestClientParameter to send to BPMN", e);
266             ErrorLoggerInfo errorLoggerInfo =
267                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.SchemaError)
268                             .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
269             throw new ValidateException.Builder(
270                     "IOException while generating requestClientParameter to send to BPMN: " + e.getMessage(),
271                     HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_BAD_PARAMETER).errorInfo(errorLoggerInfo)
272                             .build();
273         }
274         return requestClientParameter;
275     }
276 }