2  * ============LICENSE_START=======================================================
 
   4  * ================================================================================
 
   5  * Copyright (c) 2019, CMCC Technologies Co., Ltd.
 
   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
 
  11  *      http://www.apache.org/licenses/LICENSE-2.0
 
  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=========================================================
 
  21 package org.onap.so.bpmn.infrastructure.scripts
 
  23 import org.camunda.bpm.engine.delegate.BpmnError
 
  24 import org.camunda.bpm.engine.delegate.DelegateExecution
 
  25 import org.onap.aai.domain.yang.ServiceProfile
 
  26 import org.onap.aai.domain.yang.ServiceProfiles
 
  27 import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor
 
  28 import org.onap.so.bpmn.common.scripts.ExceptionUtil
 
  29 import org.onap.so.bpmn.common.scripts.MsoUtils
 
  30 import org.onap.so.bpmn.common.scripts.RequestDBUtil
 
  31 import org.onap.so.bpmn.core.WorkflowException
 
  32 import org.onap.so.bpmn.core.json.JsonUtils
 
  33 import org.onap.aaiclient.client.aai.AAIObjectType
 
  34 import org.onap.aaiclient.client.aai.AAIResourcesClient
 
  35 import org.onap.aaiclient.client.aai.entities.AAIResultWrapper
 
  36 import org.onap.aaiclient.client.aai.entities.uri.AAIResourceUri
 
  37 import org.onap.aaiclient.client.aai.entities.uri.AAIUriFactory
 
  38 import org.onap.so.db.request.beans.OperationStatus
 
  39 import org.slf4j.Logger
 
  40 import org.slf4j.LoggerFactory
 
  42 import javax.ws.rs.NotFoundException
 
  44 import static org.apache.commons.lang3.StringUtils.isBlank
 
  46 class DeleteSliceService extends AbstractServiceTaskProcessor {
 
  48     private final String PREFIX ="DeleteSliceService"
 
  49     ExceptionUtil exceptionUtil = new ExceptionUtil()
 
  50     JsonUtils jsonUtil = new JsonUtils()
 
  51     private RequestDBUtil requestDBUtil = new RequestDBUtil()
 
  53     private static final Logger LOGGER = LoggerFactory.getLogger( DeleteSliceService.class)
 
  56     void preProcessRequest(DelegateExecution execution) {
 
  57         execution.setVariable("prefix", PREFIX)
 
  60         LOGGER.debug("*****${PREFIX} preProcessRequest *****")
 
  63             // check for incoming json message/input
 
  64             String siRequest = execution.getVariable("bpmnRequest")
 
  65             String requestId = execution.getVariable("mso-request-id")
 
  66             execution.setVariable("msoRequestId", requestId)
 
  68             //e2eslice-service instance id
 
  69             String serviceInstanceId = execution.getVariable("serviceInstanceId")
 
  70             if (isBlank(serviceInstanceId)) {
 
  71                 msg = "e2eslice-service id is null"
 
  72                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
 
  74             LOGGER.info("Input Request: ${siRequest}, reqId: ${requestId}, e2eslice-service: ${serviceInstanceId}")
 
  77             checkAndSetRequestParam(siRequest,"globalSubscriberId",false, execution)
 
  78             checkAndSetRequestParam(siRequest,"serviceType",false, execution)
 
  79             checkAndSetRequestParam(siRequest,"operationId",false, execution)
 
  80             checkAndSetRequestParam(siRequest,"scriptName",false, execution)
 
  81             //prepare init operation status
 
  82             execution.setVariable("progress", "0")
 
  83             execution.setVariable("result", "processing")
 
  84             execution.setVariable("operationType", "DELETE")
 
  85             execution.setVariable("operationContent", "Delete Slice service operation start")
 
  86             updateServiceOperationStatus(execution)
 
  88         } catch (BpmnError e) {
 
  90         } catch (Exception ex) {
 
  91             msg = "Exception in preProcessRequest " + ex.getMessage()
 
  93             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
 
  95         LOGGER.debug("*****${PREFIX} Exit preProcessRequest *****")
 
  99      * send asynchronous response
 
 102     void sendAsyncResponse(DelegateExecution execution) {
 
 103         LOGGER.trace("${PREFIX} Start sendSyncResponse ")
 
 106             String operationId = execution.getVariable("operationId")
 
 107             String syncResponse = """{"operationId":"${operationId}"}""".trim()
 
 108             LOGGER.info("sendSynchResponse: xmlSyncResponse - " + "\n" + syncResponse)
 
 109             sendWorkflowResponse(execution, 202, syncResponse)
 
 111         } catch (Exception ex) {
 
 112             String msg  = "Exception in sendSyncResponse: " + ex.getMessage()
 
 113             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg)
 
 115         LOGGER.trace("${PREFIX} Exit sendSyncResponse")
 
 119      * Deletes the slice service instance in aai
 
 121     void deleteSliceServiceInstance(DelegateExecution execution) {
 
 122         LOGGER.trace("${PREFIX} Start deleteSliceServiceInstance")
 
 125             AAIResourceUri serviceInstanceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, execution.getVariable("globalSubscriberId"), execution.getVariable("serviceType"), execution.getVariable("serviceInstanceId"))
 
 126             getAAIClient().delete(serviceInstanceUri)
 
 128             execution.setVariable("progress", "100")
 
 129             execution.setVariable("result", "finished")
 
 130             execution.setVariable("operationContent", "NSMF completes slicing service termination.")
 
 131             updateServiceOperationStatus(execution)
 
 133             LOGGER.trace("${PREFIX} Exited deleteSliceServiceInstance")
 
 135             LOGGER.debug("Error occured within deleteSliceServiceInstance method: " + e)
 
 136             exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Error occured during deleteSliceServiceInstance from aai")
 
 141      * update operation status
 
 144     private void updateServiceOperationStatus(DelegateExecution execution){
 
 146         OperationStatus operationStatus = new OperationStatus()
 
 147         operationStatus.setServiceId(execution.getVariable("serviceInstanceId"))
 
 148         operationStatus.setOperationId(execution.getVariable("operationId"))
 
 149         operationStatus.setUserId(execution.getVariable("globalSubscriberId"))
 
 150         operationStatus.setResult(execution.getVariable("result"))
 
 151         operationStatus.setProgress(execution.getVariable("progress"))
 
 152         operationStatus.setOperationContent(execution.getVariable("operationContent"))
 
 153         operationStatus.setReason(execution.getVariable("reason"))
 
 154         operationStatus.setOperation(execution.getVariable("operationType"))
 
 156         requestDBUtil.prepareUpdateOperationStatus(execution, operationStatus)
 
 160      * delete service profile from aai
 
 163     void delServiceProfileFromAAI(DelegateExecution execution)
 
 165         String globalSubscriberId = execution.getVariable("globalSubscriberId")
 
 166         String serviceType = execution.getVariable("serviceType")
 
 167         String serviceInstanceId = execution.getVariable("serviceInstanceId")
 
 168         String profileId = ""
 
 172             AAIResourceUri resourceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_PROFILE_ALL, globalSubscriberId, serviceType, serviceInstanceId)
 
 173             AAIResultWrapper wrapper = getAAIClient().get(resourceUri, NotFoundException.class)
 
 174             Optional<ServiceProfiles> serviceProfilesOpt =wrapper.asBean(ServiceProfiles.class)
 
 175             if(serviceProfilesOpt.isPresent()){
 
 176                 ServiceProfiles serviceProfiles = serviceProfilesOpt.get()
 
 177                 ServiceProfile serviceProfile = serviceProfiles.getServiceProfile().get(0)
 
 178                 profileId = serviceProfile ? serviceProfile.getProfileId() : ""
 
 180             resourceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_PROFILE, globalSubscriberId, serviceType, serviceInstanceId, profileId)
 
 181             if (!getAAIClient().exists(resourceUri)) {
 
 182                 exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Service Instance was not found in aai")
 
 184             getAAIClient().delete(resourceUri)
 
 188             String msg = "delete service profile from aai failed! cause-"+any.getCause()
 
 189             LOGGER.error(any.printStackTrace())
 
 190             exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg);
 
 194      void sendSyncError(DelegateExecution execution) {
 
 195         LOGGER.debug("${PREFIX} Start sendSyncError")
 
 198             String errorMessage = "Sending Sync Error."
 
 199             if (execution.getVariable("WorkflowException") instanceof WorkflowException) {
 
 200                 WorkflowException wfe = execution.getVariable("WorkflowException")
 
 201                 errorMessage = wfe.getErrorMessage()
 
 204             String buildworkflowException =
 
 205                     """<aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1">
 
 206                                         <aetgt:ErrorMessage>${MsoUtils.xmlEscape(errorMessage)}</aetgt:ErrorMessage>
 
 207                                         <aetgt:ErrorCode>7000</aetgt:ErrorCode>
 
 208                                    </aetgt:WorkflowException>"""
 
 210             LOGGER.debug(buildworkflowException)
 
 211             sendWorkflowResponse(execution, 500, buildworkflowException)
 
 213         } catch (Exception ex) {
 
 214             LOGGER.error("Sending Sync Error Activity Failed. " + "\n" + ex.getMessage())
 
 219     void prepareEndOperationStatus(DelegateExecution execution){
 
 220         LOGGER.debug(" ======== ${PREFIX} STARTED prepareEndOperationStatus Process ======== ")
 
 222         execution.setVariable("progress", "100")
 
 223         execution.setVariable("result", "error")
 
 224         execution.setVariable("operationContent", "NSSMF Terminate service failure")
 
 226         WorkflowException wfex = execution.getVariable("WorkflowException") as WorkflowException
 
 227         String errorMessage = wfex.getErrorMessage()
 
 228         errorMessage = errorMessage.length() > 200 ? errorMessage.substring(0,200) + "......" : errorMessage
 
 229         execution.setVariable("reason",errorMessage)
 
 230         updateServiceOperationStatus(execution)
 
 232         LOGGER.debug("======== ${PREFIX} COMPLETED prepareEndOperationStatus Process ======== ")
 
 236      * check parameters from request body
 
 240      * @param isErrorException
 
 243     private void checkAndSetRequestParam(String siRequest, String paraName, boolean isErrorException, DelegateExecution execution)
 
 246         String paramValue = jsonUtil.getJsonValue(siRequest, paraName)
 
 247         if (isBlank(paramValue)) {
 
 248             msg = "Input ${paraName} is null"
 
 252                 exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg)
 
 256             execution.setVariable(paraName, paramValue)