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