c582e429ff045d86b89cc3f9baf1abd1e32af5ca
[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.db.catalog.beans.Workflow;
37 import org.onap.so.db.catalog.client.CatalogDbClient;
38 import org.onap.so.db.request.beans.InfraActiveRequests;
39 import org.onap.so.db.request.client.RequestsDbClient;
40 import org.onap.so.exceptions.ValidationException;
41 import org.onap.so.logger.ErrorCode;
42 import org.onap.so.logger.MessageEnum;
43 import org.onap.so.serviceinstancebeans.ModelType;
44 import org.onap.so.serviceinstancebeans.RequestReferences;
45 import org.onap.so.serviceinstancebeans.ServiceInstancesRequest;
46 import org.onap.so.serviceinstancebeans.ServiceInstancesResponse;
47 import org.slf4j.Logger;
48 import org.slf4j.LoggerFactory;
49 import org.springframework.beans.factory.annotation.Autowired;
50 import org.springframework.stereotype.Component;
51 import javax.transaction.Transactional;
52 import javax.ws.rs.Consumes;
53 import javax.ws.rs.POST;
54 import javax.ws.rs.Path;
55 import javax.ws.rs.PathParam;
56 import javax.ws.rs.Produces;
57 import javax.ws.rs.container.ContainerRequestContext;
58 import javax.ws.rs.core.Context;
59 import javax.ws.rs.core.MediaType;
60 import javax.ws.rs.core.Response;
61 import java.io.IOException;
62 import java.util.HashMap;
63
64 @Component
65 @Path("/onap/so/infra/instanceManagement")
66 @Api(value = "/onap/so/infra/instanceManagement", description = "Infrastructure API Requests for Instance Management")
67 public class InstanceManagement {
68
69     private static Logger logger = LoggerFactory.getLogger(InstanceManagement.class);
70     private static String uriPrefix = "/instanceManagement/";
71     private static final String SAVE_TO_DB = "save instance to db";
72
73     @Autowired
74     private RequestsDbClient infraActiveRequestsClient;
75
76     @Autowired
77     private CatalogDbClient catalogDbClient;
78
79     @Autowired
80     private MsoRequest msoRequest;
81
82     @Autowired
83     private RequestHandlerUtils requestHandlerUtils;
84
85     @POST
86     @Path("/{version:[vV][1]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}/workflows/{workflowUuid}")
87     @Consumes(MediaType.APPLICATION_JSON)
88     @Produces(MediaType.APPLICATION_JSON)
89     @ApiOperation(value = "Execute custom workflow", response = Response.class)
90     @Transactional
91     public Response executeCustomWorkflow(String request, @PathParam("version") String version,
92             @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("vnfInstanceId") String vnfInstanceId,
93             @PathParam("workflowUuid") String workflowUuid, @Context ContainerRequestContext requestContext)
94             throws ApiException {
95         String requestId = requestHandlerUtils.getRequestId(requestContext);
96         HashMap<String, String> instanceIdMap = new HashMap<>();
97         instanceIdMap.put("serviceInstanceId", serviceInstanceId);
98         instanceIdMap.put("vnfInstanceId", vnfInstanceId);
99         instanceIdMap.put("workflowUuid", workflowUuid);
100         return processCustomWorkflowRequest(request, Action.inPlaceSoftwareUpdate, instanceIdMap, version, requestId,
101                 requestContext);
102     }
103
104     private Response processCustomWorkflowRequest(String requestJSON, Actions action,
105             HashMap<String, String> instanceIdMap, String version, String requestId,
106             ContainerRequestContext requestContext) throws ApiException {
107         String serviceInstanceId = null;
108         if (instanceIdMap != null) {
109             serviceInstanceId = instanceIdMap.get("serviceInstanceId");
110         }
111         Boolean aLaCarte = true;
112         long startTime = System.currentTimeMillis();
113         ServiceInstancesRequest sir = null;
114         String apiVersion = version.substring(1);
115
116         String requestUri = requestHandlerUtils.getRequestUri(requestContext, uriPrefix);
117
118         sir = requestHandlerUtils.convertJsonToServiceInstanceRequest(requestJSON, action, requestId, requestUri);
119         String requestScope = requestHandlerUtils.deriveRequestScope(action, sir, requestUri);
120         InfraActiveRequests currentActiveReq =
121                 msoRequest.createRequestObject(sir, action, requestId, Status.IN_PROGRESS, requestJSON, requestScope);
122
123         try {
124             requestHandlerUtils.validateHeaders(requestContext);
125         } catch (ValidationException e) {
126             logger.error("Exception occurred", e);
127             ErrorLoggerInfo errorLoggerInfo =
128                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_VALIDATION_ERROR, ErrorCode.SchemaError)
129                             .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
130             ValidateException validateException =
131                     new ValidateException.Builder(e.getMessage(), HttpStatus.SC_BAD_REQUEST,
132                             ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build();
133             requestHandlerUtils.updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage());
134             throw validateException;
135         }
136
137         requestHandlerUtils.parseRequest(sir, instanceIdMap, action, version, requestJSON, aLaCarte, requestId,
138                 currentActiveReq);
139         requestHandlerUtils.setInstanceId(currentActiveReq, requestScope, null, instanceIdMap);
140
141         int requestVersion = Integer.parseInt(version.substring(1));
142         String vnfType = msoRequest.getVnfType(sir, requestScope, action, requestVersion);
143
144         if (requestScope.equalsIgnoreCase(ModelType.vnf.name()) && vnfType != null) {
145             currentActiveReq.setVnfType(vnfType);
146         }
147
148         InfraActiveRequests dup = null;
149         boolean inProgress = false;
150
151         dup = requestHandlerUtils.duplicateCheck(action, instanceIdMap, null, requestScope, currentActiveReq);
152
153         if (dup != null) {
154             inProgress = requestHandlerUtils.camundaHistoryCheck(dup, currentActiveReq);
155         }
156
157         if (dup != null && inProgress) {
158             requestHandlerUtils.buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, null, requestScope,
159                     dup);
160         }
161         ServiceInstancesResponse serviceResponse = new ServiceInstancesResponse();
162
163         RequestReferences referencesResponse = new RequestReferences();
164
165         referencesResponse.setRequestId(requestId);
166
167         serviceResponse.setRequestReferences(referencesResponse);
168         Boolean isBaseVfModule = false;
169
170         String workflowUuid = null;
171         if (instanceIdMap != null) {
172             workflowUuid = instanceIdMap.get("workflowUuid");
173         }
174
175         RecipeLookupResult recipeLookupResult = getInstanceManagementWorkflowRecipe(currentActiveReq, workflowUuid);
176
177         String serviceInstanceType = requestHandlerUtils.getServiceType(requestScope, sir, true);
178
179         serviceInstanceId = requestHandlerUtils.setServiceInstanceId(requestScope, sir);
180         String vnfId = "";
181
182         if (sir.getVnfInstanceId() != null) {
183             vnfId = sir.getVnfInstanceId();
184         }
185
186         try {
187             infraActiveRequestsClient.save(currentActiveReq);
188         } catch (Exception e) {
189             ErrorLoggerInfo errorLoggerInfo =
190                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, ErrorCode.DataError)
191                             .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
192             throw new RequestDbFailureException.Builder(SAVE_TO_DB, e.toString(), HttpStatus.SC_INTERNAL_SERVER_ERROR,
193                     ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e).errorInfo(errorLoggerInfo).build();
194         }
195
196         RequestClientParameter requestClientParameter = null;
197         try {
198             requestClientParameter = new RequestClientParameter.Builder().setRequestId(requestId)
199                     .setBaseVfModule(isBaseVfModule).setRecipeTimeout(recipeLookupResult.getRecipeTimeout())
200                     .setRequestAction(action.toString()).setServiceInstanceId(serviceInstanceId).setVnfId(vnfId)
201                     .setServiceType(serviceInstanceType).setVnfType(vnfType)
202                     .setRequestDetails(requestHandlerUtils.mapJSONtoMSOStyle(requestJSON, sir, aLaCarte, action))
203                     .setApiVersion(apiVersion).setALaCarte(aLaCarte).setRequestUri(requestUri).build();
204         } catch (IOException e) {
205             ErrorLoggerInfo errorLoggerInfo =
206                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.SchemaError)
207                             .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
208             throw new ValidateException.Builder("Unable to generate RequestClientParamter object" + e.getMessage(),
209                     HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_BAD_PARAMETER).errorInfo(errorLoggerInfo)
210                             .build();
211         }
212         return requestHandlerUtils.postBPELRequest(currentActiveReq, requestClientParameter,
213                 recipeLookupResult.getOrchestrationURI(), requestScope);
214     }
215
216     private RecipeLookupResult getInstanceManagementWorkflowRecipe(InfraActiveRequests currentActiveReq,
217             String workflowUuid) throws ApiException {
218         RecipeLookupResult recipeLookupResult = null;
219
220         try {
221             recipeLookupResult = getCustomWorkflowUri(workflowUuid);
222         } catch (IOException e) {
223             ErrorLoggerInfo errorLoggerInfo =
224                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError)
225                             .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
226             ValidateException validateException =
227                     new ValidateException.Builder(e.getMessage(), HttpStatus.SC_BAD_REQUEST,
228                             ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build();
229             requestHandlerUtils.updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage());
230             throw validateException;
231         }
232
233         if (recipeLookupResult == null) {
234             ErrorLoggerInfo errorLoggerInfo =
235                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, ErrorCode.DataError)
236                             .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
237             RecipeNotFoundException recipeNotFoundExceptionException =
238                     new RecipeNotFoundException.Builder("Recipe could not be retrieved from catalog DB.",
239                             HttpStatus.SC_NOT_FOUND, ErrorNumbers.SVC_GENERAL_SERVICE_ERROR).errorInfo(errorLoggerInfo)
240                                     .build();
241             requestHandlerUtils.updateStatus(currentActiveReq, Status.FAILED,
242                     recipeNotFoundExceptionException.getMessage());
243             throw recipeNotFoundExceptionException;
244         }
245
246         return recipeLookupResult;
247     }
248
249     private RecipeLookupResult getCustomWorkflowUri(String workflowUuid) throws IOException {
250
251         String recipeUri = null;
252         Workflow workflow = catalogDbClient.findWorkflowByArtifactUUID(workflowUuid);
253         if (workflow == null) {
254             return null;
255         } else {
256             String workflowName = workflow.getName();
257             recipeUri = "/mso/async/services/" + workflowName;
258         }
259         return new RecipeLookupResult(recipeUri, 180);
260     }
261 }