d8a7cb3f5de4be113b1259b67e4ea471b9490c5c
[so.git] /
1 /*-
2  * ============LICENSE_START=======================================================
3  * ONAP - SO
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved.
7  * ================================================================================
8  * Modifications Copyright (c) 2019 Samsung
9  * ================================================================================
10  * Licensed under the Apache License, Version 2.0 (the "License");
11  * you may not use this file except in compliance with the License.
12  * You may obtain a copy of the License at
13  * 
14  *      http://www.apache.org/licenses/LICENSE-2.0
15  * 
16  * Unless required by applicable law or agreed to in writing, software
17  * distributed under the License is distributed on an "AS IS" BASIS,
18  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
19  * See the License for the specific language governing permissions and
20  * limitations under the License.
21  * ============LICENSE_END=========================================================
22  */
23
24 package org.onap.so.apihandlerinfra;
25
26 import io.swagger.annotations.Api;
27 import io.swagger.annotations.ApiOperation;
28 import org.apache.http.HttpStatus;
29 import org.onap.so.apihandler.common.ErrorNumbers;
30 import org.onap.so.apihandler.common.RequestClientParameter;
31 import org.onap.so.apihandlerinfra.exceptions.ApiException;
32 import org.onap.so.apihandlerinfra.exceptions.RecipeNotFoundException;
33 import org.onap.so.apihandlerinfra.exceptions.RequestDbFailureException;
34 import org.onap.so.apihandlerinfra.exceptions.ValidateException;
35 import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo;
36 import org.onap.so.constants.Status;
37 import org.onap.so.db.catalog.beans.Workflow;
38 import org.onap.so.db.catalog.client.CatalogDbClient;
39 import org.onap.so.db.request.beans.InfraActiveRequests;
40 import org.onap.so.db.request.client.RequestsDbClient;
41 import org.onap.so.exceptions.ValidationException;
42 import org.onap.so.logger.ErrorCode;
43 import org.onap.so.logger.MessageEnum;
44 import org.onap.so.serviceinstancebeans.ModelType;
45 import org.onap.so.serviceinstancebeans.RequestReferences;
46 import org.onap.so.serviceinstancebeans.ServiceInstancesRequest;
47 import org.onap.so.serviceinstancebeans.ServiceInstancesResponse;
48 import org.slf4j.Logger;
49 import org.slf4j.LoggerFactory;
50 import org.springframework.beans.factory.annotation.Autowired;
51 import org.springframework.stereotype.Component;
52 import javax.transaction.Transactional;
53 import javax.ws.rs.Consumes;
54 import javax.ws.rs.POST;
55 import javax.ws.rs.Path;
56 import javax.ws.rs.PathParam;
57 import javax.ws.rs.Produces;
58 import javax.ws.rs.container.ContainerRequestContext;
59 import javax.ws.rs.core.Context;
60 import javax.ws.rs.core.MediaType;
61 import javax.ws.rs.core.Response;
62 import java.io.IOException;
63 import java.util.HashMap;
64
65 @Component
66 @Path("/onap/so/infra/instanceManagement")
67 @Api(value = "/onap/so/infra/instanceManagement", description = "Infrastructure API Requests for Instance Management")
68 public class InstanceManagement {
69
70     private static Logger logger = LoggerFactory.getLogger(InstanceManagement.class);
71     private static String uriPrefix = "/instanceManagement/";
72     private static final String SAVE_TO_DB = "save instance to db";
73
74     @Autowired
75     private RequestsDbClient infraActiveRequestsClient;
76
77     @Autowired
78     private CatalogDbClient catalogDbClient;
79
80     @Autowired
81     private MsoRequest msoRequest;
82
83     @Autowired
84     private RequestHandlerUtils requestHandlerUtils;
85
86     @POST
87     @Path("/{version:[vV][1]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}/workflows/{workflowUuid}")
88     @Consumes(MediaType.APPLICATION_JSON)
89     @Produces(MediaType.APPLICATION_JSON)
90     @ApiOperation(value = "Execute custom workflow", response = Response.class)
91     @Transactional
92     public Response executeCustomWorkflow(String request, @PathParam("version") String version,
93             @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("vnfInstanceId") String vnfInstanceId,
94             @PathParam("workflowUuid") String workflowUuid, @Context ContainerRequestContext requestContext)
95             throws ApiException {
96         String requestId = requestHandlerUtils.getRequestId(requestContext);
97         HashMap<String, String> instanceIdMap = new HashMap<>();
98         instanceIdMap.put("serviceInstanceId", serviceInstanceId);
99         instanceIdMap.put("vnfInstanceId", vnfInstanceId);
100         instanceIdMap.put("workflowUuid", workflowUuid);
101         return processCustomWorkflowRequest(request, Action.inPlaceSoftwareUpdate, instanceIdMap, version, requestId,
102                 requestContext);
103     }
104
105     private Response processCustomWorkflowRequest(String requestJSON, Actions action,
106             HashMap<String, String> instanceIdMap, String version, String requestId,
107             ContainerRequestContext requestContext) throws ApiException {
108         String serviceInstanceId = null;
109         if (instanceIdMap != null) {
110             serviceInstanceId = instanceIdMap.get("serviceInstanceId");
111         }
112         Boolean aLaCarte = true;
113         long startTime = System.currentTimeMillis();
114         ServiceInstancesRequest sir = null;
115         String apiVersion = version.substring(1);
116
117         String requestUri = requestHandlerUtils.getRequestUri(requestContext, uriPrefix);
118
119         sir = requestHandlerUtils.convertJsonToServiceInstanceRequest(requestJSON, action, requestId, requestUri);
120         String requestScope = requestHandlerUtils.deriveRequestScope(action, sir, requestUri);
121         InfraActiveRequests currentActiveReq =
122                 msoRequest.createRequestObject(sir, action, requestId, Status.IN_PROGRESS, requestJSON, requestScope);
123
124         try {
125             requestHandlerUtils.validateHeaders(requestContext);
126         } catch (ValidationException e) {
127             logger.error("Exception occurred", e);
128             ErrorLoggerInfo errorLoggerInfo =
129                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_VALIDATION_ERROR, ErrorCode.SchemaError)
130                             .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
131             ValidateException validateException =
132                     new ValidateException.Builder(e.getMessage(), HttpStatus.SC_BAD_REQUEST,
133                             ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build();
134             requestHandlerUtils.updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage());
135             throw validateException;
136         }
137
138         requestHandlerUtils.parseRequest(sir, instanceIdMap, action, version, requestJSON, aLaCarte, requestId,
139                 currentActiveReq);
140         requestHandlerUtils.setInstanceId(currentActiveReq, requestScope, null, instanceIdMap);
141
142         int requestVersion = Integer.parseInt(version.substring(1));
143         String vnfType = msoRequest.getVnfType(sir, requestScope, action, requestVersion);
144
145         if (requestScope.equalsIgnoreCase(ModelType.vnf.name()) && vnfType != null) {
146             currentActiveReq.setVnfType(vnfType);
147         }
148
149         InfraActiveRequests dup = null;
150         boolean inProgress = false;
151
152         dup = requestHandlerUtils.duplicateCheck(action, instanceIdMap, null, requestScope, currentActiveReq);
153
154         if (dup != null) {
155             inProgress = requestHandlerUtils.camundaHistoryCheck(dup, currentActiveReq);
156         }
157
158         if (dup != null && inProgress) {
159             requestHandlerUtils.buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, null, requestScope,
160                     dup);
161         }
162         ServiceInstancesResponse serviceResponse = new ServiceInstancesResponse();
163
164         RequestReferences referencesResponse = new RequestReferences();
165
166         referencesResponse.setRequestId(requestId);
167
168         serviceResponse.setRequestReferences(referencesResponse);
169         Boolean isBaseVfModule = false;
170
171         String workflowUuid = null;
172         if (instanceIdMap != null) {
173             workflowUuid = instanceIdMap.get("workflowUuid");
174         }
175
176         RecipeLookupResult recipeLookupResult = getInstanceManagementWorkflowRecipe(currentActiveReq, workflowUuid);
177
178         String serviceInstanceType = requestHandlerUtils.getServiceType(requestScope, sir, true);
179
180         serviceInstanceId = requestHandlerUtils.setServiceInstanceId(requestScope, sir);
181         String vnfId = "";
182
183         if (sir.getVnfInstanceId() != null) {
184             vnfId = sir.getVnfInstanceId();
185         }
186
187         try {
188             infraActiveRequestsClient.save(currentActiveReq);
189         } catch (Exception e) {
190             ErrorLoggerInfo errorLoggerInfo =
191                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, ErrorCode.DataError)
192                             .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
193             throw new RequestDbFailureException.Builder(SAVE_TO_DB, e.toString(), HttpStatus.SC_INTERNAL_SERVER_ERROR,
194                     ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e).errorInfo(errorLoggerInfo).build();
195         }
196
197         RequestClientParameter requestClientParameter = null;
198         try {
199             requestClientParameter = new RequestClientParameter.Builder().setRequestId(requestId)
200                     .setBaseVfModule(isBaseVfModule).setRecipeTimeout(recipeLookupResult.getRecipeTimeout())
201                     .setRequestAction(action.toString()).setServiceInstanceId(serviceInstanceId).setVnfId(vnfId)
202                     .setServiceType(serviceInstanceType).setVnfType(vnfType)
203                     .setRequestDetails(requestHandlerUtils.mapJSONtoMSOStyle(requestJSON, sir, aLaCarte, action))
204                     .setApiVersion(apiVersion).setALaCarte(aLaCarte).setRequestUri(requestUri).build();
205         } catch (IOException e) {
206             ErrorLoggerInfo errorLoggerInfo =
207                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.SchemaError)
208                             .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
209             throw new ValidateException.Builder("Unable to generate RequestClientParamter object" + e.getMessage(),
210                     HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_BAD_PARAMETER).errorInfo(errorLoggerInfo)
211                             .build();
212         }
213         return requestHandlerUtils.postBPELRequest(currentActiveReq, requestClientParameter,
214                 recipeLookupResult.getOrchestrationURI(), requestScope);
215     }
216
217     private RecipeLookupResult getInstanceManagementWorkflowRecipe(InfraActiveRequests currentActiveReq,
218             String workflowUuid) throws ApiException {
219         RecipeLookupResult recipeLookupResult = null;
220
221         try {
222             recipeLookupResult = getCustomWorkflowUri(workflowUuid);
223         } catch (IOException e) {
224             ErrorLoggerInfo errorLoggerInfo =
225                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError)
226                             .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
227             ValidateException validateException =
228                     new ValidateException.Builder(e.getMessage(), HttpStatus.SC_BAD_REQUEST,
229                             ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build();
230             requestHandlerUtils.updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage());
231             throw validateException;
232         }
233
234         if (recipeLookupResult == null) {
235             ErrorLoggerInfo errorLoggerInfo =
236                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, ErrorCode.DataError)
237                             .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
238             RecipeNotFoundException recipeNotFoundExceptionException =
239                     new RecipeNotFoundException.Builder("Recipe could not be retrieved from catalog DB.",
240                             HttpStatus.SC_NOT_FOUND, ErrorNumbers.SVC_GENERAL_SERVICE_ERROR).errorInfo(errorLoggerInfo)
241                                     .build();
242             requestHandlerUtils.updateStatus(currentActiveReq, Status.FAILED,
243                     recipeNotFoundExceptionException.getMessage());
244             throw recipeNotFoundExceptionException;
245         }
246
247         return recipeLookupResult;
248     }
249
250     private RecipeLookupResult getCustomWorkflowUri(String workflowUuid) throws IOException {
251
252         String recipeUri = null;
253         Workflow workflow = catalogDbClient.findWorkflowByArtifactUUID(workflowUuid);
254         if (workflow == null) {
255             return null;
256         } else {
257             String workflowName = workflow.getName();
258             recipeUri = "/mso/async/services/" + workflowName;
259         }
260         return new RecipeLookupResult(recipeUri, 180);
261     }
262 }