2  * ============LICENSE_START=======================================================
 
   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
 
  14  *      http://www.apache.org/licenses/LICENSE-2.0
 
  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=========================================================
 
  24 package org.onap.so.apihandlerinfra;
 
  26 import org.apache.http.HttpStatus;
 
  27 import org.onap.so.apihandler.common.ErrorNumbers;
 
  28 import org.onap.so.apihandler.common.RequestClientParameter;
 
  29 import org.onap.so.apihandlerinfra.exceptions.ApiException;
 
  30 import org.onap.so.apihandlerinfra.exceptions.RecipeNotFoundException;
 
  31 import org.onap.so.apihandlerinfra.exceptions.RequestDbFailureException;
 
  32 import org.onap.so.apihandlerinfra.exceptions.ValidateException;
 
  33 import org.onap.so.apihandlerinfra.logging.ErrorLoggerInfo;
 
  34 import org.onap.so.constants.Status;
 
  35 import org.onap.so.db.catalog.beans.Workflow;
 
  36 import org.onap.so.db.catalog.client.CatalogDbClient;
 
  37 import org.onap.so.db.request.beans.InfraActiveRequests;
 
  38 import org.onap.so.db.request.client.RequestsDbClient;
 
  39 import org.onap.so.exceptions.ValidationException;
 
  40 import org.onap.so.logger.ErrorCode;
 
  41 import org.onap.so.logger.MessageEnum;
 
  42 import org.onap.so.serviceinstancebeans.ModelType;
 
  43 import org.onap.so.serviceinstancebeans.RequestReferences;
 
  44 import org.onap.so.serviceinstancebeans.ServiceInstancesRequest;
 
  45 import org.onap.so.serviceinstancebeans.ServiceInstancesResponse;
 
  46 import org.slf4j.Logger;
 
  47 import org.slf4j.LoggerFactory;
 
  48 import org.springframework.beans.factory.annotation.Autowired;
 
  49 import org.springframework.stereotype.Component;
 
  50 import javax.transaction.Transactional;
 
  51 import javax.ws.rs.Consumes;
 
  52 import javax.ws.rs.POST;
 
  53 import javax.ws.rs.Path;
 
  54 import javax.ws.rs.PathParam;
 
  55 import javax.ws.rs.Produces;
 
  56 import javax.ws.rs.container.ContainerRequestContext;
 
  57 import javax.ws.rs.core.Context;
 
  58 import javax.ws.rs.core.MediaType;
 
  59 import javax.ws.rs.core.Response;
 
  60 import java.io.IOException;
 
  61 import java.util.HashMap;
 
  62 import io.swagger.v3.oas.annotations.OpenAPIDefinition;
 
  63 import io.swagger.v3.oas.annotations.Operation;
 
  64 import io.swagger.v3.oas.annotations.info.Info;
 
  65 import io.swagger.v3.oas.annotations.media.ArraySchema;
 
  66 import io.swagger.v3.oas.annotations.media.Content;
 
  67 import io.swagger.v3.oas.annotations.media.Schema;
 
  68 import io.swagger.v3.oas.annotations.responses.ApiResponse;
 
  71 @Path("/onap/so/infra/instanceManagement")
 
  72 @OpenAPIDefinition(info = @Info(title = "/onap/so/infra/instanceManagement",
 
  73         description = "Infrastructure API Requests for Instance Management"))
 
  74 public class InstanceManagement {
 
  76     private static Logger logger = LoggerFactory.getLogger(InstanceManagement.class);
 
  77     private static String uriPrefix = "/instanceManagement/";
 
  78     private static final String SAVE_TO_DB = "save instance to db";
 
  81     private RequestsDbClient infraActiveRequestsClient;
 
  84     private CatalogDbClient catalogDbClient;
 
  87     private MsoRequest msoRequest;
 
  90     private RequestHandlerUtils requestHandlerUtils;
 
  93     @Path("/{version:[vV][1]}/serviceInstances/{serviceInstanceId}/vnfs/{vnfInstanceId}/workflows/{workflowUuid}")
 
  94     @Consumes(MediaType.APPLICATION_JSON)
 
  95     @Produces(MediaType.APPLICATION_JSON)
 
  96     @Operation(description = "Execute custom workflow", responses = @ApiResponse(
 
  97             content = @Content(array = @ArraySchema(schema = @Schema(implementation = Response.class)))))
 
  99     public Response executeCustomWorkflow(String request, @PathParam("version") String version,
 
 100             @PathParam("serviceInstanceId") String serviceInstanceId, @PathParam("vnfInstanceId") String vnfInstanceId,
 
 101             @PathParam("workflowUuid") String workflowUuid, @Context ContainerRequestContext requestContext)
 
 102             throws ApiException {
 
 103         String requestId = requestHandlerUtils.getRequestId(requestContext);
 
 104         HashMap<String, String> instanceIdMap = new HashMap<>();
 
 105         instanceIdMap.put("serviceInstanceId", serviceInstanceId);
 
 106         instanceIdMap.put("vnfInstanceId", vnfInstanceId);
 
 107         instanceIdMap.put("workflowUuid", workflowUuid);
 
 108         return processCustomWorkflowRequest(request, Action.inPlaceSoftwareUpdate, instanceIdMap, version, requestId,
 
 112     private Response processCustomWorkflowRequest(String requestJSON, Actions action,
 
 113             HashMap<String, String> instanceIdMap, String version, String requestId,
 
 114             ContainerRequestContext requestContext) throws ApiException {
 
 115         String serviceInstanceId;
 
 116         Boolean aLaCarte = true;
 
 117         ServiceInstancesRequest sir;
 
 118         String apiVersion = version.substring(1);
 
 120         String requestUri = requestHandlerUtils.getRequestUri(requestContext, uriPrefix);
 
 122         sir = requestHandlerUtils.convertJsonToServiceInstanceRequest(requestJSON, action, requestId, requestUri);
 
 123         String requestScope = requestHandlerUtils.deriveRequestScope(action, sir, requestUri);
 
 124         InfraActiveRequests currentActiveReq =
 
 125                 msoRequest.createRequestObject(sir, action, requestId, Status.IN_PROGRESS, requestJSON, requestScope);
 
 128             requestHandlerUtils.validateHeaders(requestContext);
 
 129         } catch (ValidationException e) {
 
 130             logger.error("Exception occurred", e);
 
 131             ErrorLoggerInfo errorLoggerInfo =
 
 132                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_VALIDATION_ERROR, ErrorCode.SchemaError)
 
 133                             .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
 
 134             ValidateException validateException =
 
 135                     new ValidateException.Builder(e.getMessage(), HttpStatus.SC_BAD_REQUEST,
 
 136                             ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build();
 
 137             requestHandlerUtils.updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage());
 
 138             throw validateException;
 
 141         requestHandlerUtils.parseRequest(sir, instanceIdMap, action, version, requestJSON, aLaCarte, requestId,
 
 143         requestHandlerUtils.setInstanceId(currentActiveReq, requestScope, null, instanceIdMap);
 
 145         int requestVersion = Integer.parseInt(version.substring(1));
 
 146         String vnfType = msoRequest.getVnfType(sir, requestScope, action, requestVersion);
 
 148         if (requestScope.equalsIgnoreCase(ModelType.vnf.name()) && vnfType != null) {
 
 149             currentActiveReq.setVnfType(vnfType);
 
 152         InfraActiveRequests dup = null;
 
 153         boolean inProgress = false;
 
 155         dup = requestHandlerUtils.duplicateCheck(action, instanceIdMap, null, requestScope, currentActiveReq);
 
 158             inProgress = requestHandlerUtils.camundaHistoryCheck(dup, currentActiveReq);
 
 161         if (dup != null && inProgress) {
 
 162             requestHandlerUtils.buildErrorOnDuplicateRecord(currentActiveReq, action, instanceIdMap, null, requestScope,
 
 165         ServiceInstancesResponse serviceResponse = new ServiceInstancesResponse();
 
 167         RequestReferences referencesResponse = new RequestReferences();
 
 169         referencesResponse.setRequestId(requestId);
 
 171         serviceResponse.setRequestReferences(referencesResponse);
 
 172         Boolean isBaseVfModule = false;
 
 174         String workflowUuid = null;
 
 175         if (instanceIdMap != null) {
 
 176             workflowUuid = instanceIdMap.get("workflowUuid");
 
 179         RecipeLookupResult recipeLookupResult = getInstanceManagementWorkflowRecipe(currentActiveReq, workflowUuid);
 
 181         String serviceInstanceType = requestHandlerUtils.getServiceType(requestScope, sir, true);
 
 183         serviceInstanceId = requestHandlerUtils.setServiceInstanceId(requestScope, sir);
 
 186         if (sir.getVnfInstanceId() != null) {
 
 187             vnfId = sir.getVnfInstanceId();
 
 191             infraActiveRequestsClient.save(currentActiveReq);
 
 192         } catch (Exception e) {
 
 193             ErrorLoggerInfo errorLoggerInfo =
 
 194                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, ErrorCode.DataError)
 
 195                             .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
 
 196             throw new RequestDbFailureException.Builder(SAVE_TO_DB, e.toString(), HttpStatus.SC_INTERNAL_SERVER_ERROR,
 
 197                     ErrorNumbers.SVC_DETAILED_SERVICE_ERROR).cause(e).errorInfo(errorLoggerInfo).build();
 
 200         RequestClientParameter requestClientParameter = null;
 
 202             requestClientParameter = new RequestClientParameter.Builder().setRequestId(requestId)
 
 203                     .setBaseVfModule(isBaseVfModule).setRecipeTimeout(recipeLookupResult.getRecipeTimeout())
 
 204                     .setRequestAction(action.toString()).setServiceInstanceId(serviceInstanceId).setVnfId(vnfId)
 
 205                     .setServiceType(serviceInstanceType).setVnfType(vnfType)
 
 206                     .setRequestDetails(requestHandlerUtils.mapJSONtoMSOStyle(requestJSON, null, aLaCarte, action))
 
 207                     .setApiVersion(apiVersion).setALaCarte(aLaCarte).setRequestUri(requestUri).build();
 
 208         } catch (IOException e) {
 
 209             ErrorLoggerInfo errorLoggerInfo =
 
 210                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_BPEL_RESPONSE_ERROR, ErrorCode.SchemaError)
 
 211                             .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
 
 212             throw new ValidateException.Builder("Unable to generate RequestClientParamter object" + e.getMessage(),
 
 213                     HttpStatus.SC_INTERNAL_SERVER_ERROR, ErrorNumbers.SVC_BAD_PARAMETER).errorInfo(errorLoggerInfo)
 
 216         return requestHandlerUtils.postBPELRequest(currentActiveReq, requestClientParameter,
 
 217                 recipeLookupResult.getOrchestrationURI(), requestScope);
 
 220     private RecipeLookupResult getInstanceManagementWorkflowRecipe(InfraActiveRequests currentActiveReq,
 
 221             String workflowUuid) throws ApiException {
 
 222         RecipeLookupResult recipeLookupResult = null;
 
 225             recipeLookupResult = getCustomWorkflowUri(workflowUuid);
 
 226         } catch (Exception e) {
 
 227             ErrorLoggerInfo errorLoggerInfo =
 
 228                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_REQUEST_VALIDATION_ERROR, ErrorCode.SchemaError)
 
 229                             .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
 
 230             ValidateException validateException =
 
 231                     new ValidateException.Builder(e.getMessage(), HttpStatus.SC_BAD_REQUEST,
 
 232                             ErrorNumbers.SVC_BAD_PARAMETER).cause(e).errorInfo(errorLoggerInfo).build();
 
 233             requestHandlerUtils.updateStatus(currentActiveReq, Status.FAILED, validateException.getMessage());
 
 234             throw validateException;
 
 237         if (recipeLookupResult == null) {
 
 238             ErrorLoggerInfo errorLoggerInfo =
 
 239                     new ErrorLoggerInfo.Builder(MessageEnum.APIH_DB_ACCESS_EXC, ErrorCode.DataError)
 
 240                             .errorSource(Constants.MSO_PROP_APIHANDLER_INFRA).build();
 
 241             RecipeNotFoundException recipeNotFoundExceptionException =
 
 242                     new RecipeNotFoundException.Builder("Recipe could not be retrieved from catalog DB.",
 
 243                             HttpStatus.SC_NOT_FOUND, ErrorNumbers.SVC_GENERAL_SERVICE_ERROR).errorInfo(errorLoggerInfo)
 
 245             requestHandlerUtils.updateStatus(currentActiveReq, Status.FAILED,
 
 246                     recipeNotFoundExceptionException.getMessage());
 
 247             throw recipeNotFoundExceptionException;
 
 250         return recipeLookupResult;
 
 253     private RecipeLookupResult getCustomWorkflowUri(String workflowUuid) {
 
 255         String recipeUri = null;
 
 256         Workflow workflow = catalogDbClient.findWorkflowByArtifactUUID(workflowUuid);
 
 257         if (workflow == null) {
 
 260             String workflowName = workflow.getName();
 
 261             recipeUri = "/mso/async/services/" + workflowName;
 
 263         return new RecipeLookupResult(recipeUri, 180);