diff options
Diffstat (limited to 'bpmn/so-bpmn-infrastructure-common/src')
128 files changed, 62854 insertions, 0 deletions
diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/ActivateSDNCNetworkResource.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/ActivateSDNCNetworkResource.groovy new file mode 100644 index 0000000000..545cba7f8c --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/ActivateSDNCNetworkResource.groovy @@ -0,0 +1,384 @@ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - SO + * ================================================================================ + * Copyright (C) 2018 Huawei Technologies Co., Ltd. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts + +import org.apache.commons.lang3.StringUtils +import org.camunda.bpm.engine.delegate.BpmnError +import org.json.JSONObject +import org.json.XML +import org.onap.so.bpmn.common.recipe.ResourceInput +import org.onap.so.bpmn.common.resource.ResourceRequestBuilder +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.bpmn.common.scripts.ExceptionUtil +import org.onap.so.bpmn.common.scripts.SDNCAdapterUtils +import org.onap.so.logger.MsoLogger + +/** + * This groovy class supports the <class>ActivateSDNCCNetworkResource.bpmn</class> process. + * flow for SDNC Network Resource Activate + */ +public class ActivateSDNCNetworkResource extends AbstractServiceTaskProcessor { + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, CreateSDNCNetworkResource.class); + + String Prefix = "ACTSDNCRES_" + + ExceptionUtil exceptionUtil = new ExceptionUtil() + + JsonUtils jsonUtil = new JsonUtils() + + SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils() + + public void preProcessRequest(DelegateExecution execution) { + msoLogger.trace("Started preProcessRequest ") + + try { + //get bpmn inputs from resource request. + String requestId = execution.getVariable("mso-request-id") + String requestAction = execution.getVariable("requestAction") + msoLogger.info("The requestAction is: " + requestAction) + String recipeParamsFromRequest = execution.getVariable("recipeParams") + msoLogger.info("The recipeParams is: " + recipeParamsFromRequest) + String resourceInput = execution.getVariable("resourceInput") + msoLogger.info("The resourceInput is: " + resourceInput) + //Get ResourceInput Object + ResourceInput resourceInputObj = ResourceRequestBuilder.getJsonObject(resourceInput, ResourceInput.class) + execution.setVariable(Prefix + "resourceInput", resourceInputObj) + + //Deal with recipeParams + String recipeParamsFromWf = execution.getVariable("recipeParamXsd") + String resourceName = resourceInputObj.getResourceInstanceName() + //For sdnc requestAction default is "createNetworkInstance" + String operationType = "Network" + if(!StringUtils.isBlank(recipeParamsFromRequest)){ + //the operationType from worflow(first node) is second priority. + operationType = jsonUtil.getJsonValue(recipeParamsFromRequest, "operationType") + } + if(!StringUtils.isBlank(recipeParamsFromWf)){ + //the operationType from worflow(first node) is highest priority. + operationType = jsonUtil.getJsonValue(recipeParamsFromWf, "operationType") + } + + // TODO: based on the resource type decide action and operation type + String sdnc_svcAction = "activate" + operationType = "SOTNConnectivity" + + String sdnc_requestAction = StringUtils.capitalize(sdnc_svcAction) + operationType +"Instance" + execution.setVariable(Prefix + "svcAction", sdnc_svcAction) + execution.setVariable(Prefix + "requestAction", sdnc_requestAction) + execution.setVariable(Prefix + "serviceInstanceId", resourceInputObj.getServiceInstanceId()) + execution.setVariable("mso-request-id", requestId) + execution.setVariable("mso-service-instance-id", resourceInputObj.getServiceInstanceId()) + } catch (BpmnError e) { + throw e; + } catch (Exception ex){ + msg = "Exception in preProcessRequest " + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + } + + public void prepareUpdateAfterActivateSDNCResource(DelegateExecution execution) { + msoLogger.trace("started prepareUpdateAfterActivateSDNCResource ") + + ResourceInput resourceInputObj = execution.getVariable(Prefix + "resourceInput") + String operType = resourceInputObj.getOperationType() + String resourceCustomizationUuid = resourceInputObj.getResourceModelInfo().getModelCustomizationUuid() + String ServiceInstanceId = resourceInputObj.getServiceInstanceId() + String operationId = resourceInputObj.getOperationId() + String progress = "100" + String status = "finished" + String statusDescription = "SDCN resource creation completed" + + execution.getVariable("operationId") + + String body = """ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" + xmlns:ns="http://org.onap.so/requestsdb"> + <soapenv:Header/> + <soapenv:Body> + <ns:updateResourceOperationStatus> + <operType>${MsoUtils.xmlEscape(operType)}</operType> + <operationId>${MsoUtils.xmlEscape(operationId)}</operationId> + <progress>${MsoUtils.xmlEscape(progress)}</progress> + <resourceTemplateUUID>${MsoUtils.xmlEscape(resourceCustomizationUuid)}</resourceTemplateUUID> + <serviceId>${MsoUtils.xmlEscape(ServiceInstanceId)}</serviceId> + <status>${MsoUtils.xmlEscape(status)}</status> + <statusDescription>${MsoUtils.xmlEscape(statusDescription)}</statusDescription> + </ns:updateResourceOperationStatus> + </soapenv:Body> + </soapenv:Envelope>"""; + + setProgressUpdateVariables(execution, body) + } + + public void prepareSDNCRequest (DelegateExecution execution) { + msoLogger.trace("Started prepareSDNCRequest ") + + try { + // get variables + String sdnc_svcAction = execution.getVariable(Prefix + "svcAction") + String sdnc_requestAction = execution.getVariable(Prefix + "requestAction") + String sdncCallback = execution.getVariable("URN_mso_workflow_sdncadapter_callback") + String createNetworkInput = execution.getVariable(Prefix + "networkRequest") + + String hdrRequestId = execution.getVariable("mso-request-id") + String serviceInstanceId = execution.getVariable(Prefix + "serviceInstanceId") + String source = execution.getVariable("source") + String sdnc_service_id = execution.getVariable(Prefix + "sdncServiceId") + ResourceInput resourceInputObj = execution.getVariable(Prefix + "resourceInput") + String serviceType = resourceInputObj.getServiceType() + String serviceModelInvariantUuid = resourceInputObj.getServiceModelInfo().getModelInvariantUuid() + String serviceModelUuid = resourceInputObj.getServiceModelInfo().getModelUuid() + String serviceModelVersion = resourceInputObj.getServiceModelInfo().getModelVersion() + String serviceModelName = resourceInputObj.getServiceModelInfo().getModelName() + String globalCustomerId = resourceInputObj.getGlobalSubscriberId() + String modelInvariantUuid = resourceInputObj.getResourceModelInfo().getModelInvariantUuid(); + String modelCustomizationUuid = resourceInputObj.getResourceModelInfo().getModelCustomizationUuid() + String modelUuid = resourceInputObj.getResourceModelInfo().getModelUuid() + String modelName = resourceInputObj.getResourceModelInfo().getModelName() + String modelVersion = resourceInputObj.getResourceModelInfo().getModelVersion() + String resourceInputPrameters = resourceInputObj.getResourceParameters() + String networkInputParametersJson = jsonUtil.getJsonValue(resourceInputPrameters, "requestInputs") + //here convert json string to xml string + String netowrkInputParameters = XML.toString(new JSONObject(customizeResourceParam(networkInputParametersJson))) + // 1. prepare assign topology via SDNC Adapter SUBFLOW call + String sdncTopologyActivateRequest = "" + + switch (modelName) { + case ~/^Site$/: + sdncTopologyActivateRequest = + """<aetgt:SDNCAdapterWorkflowRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:sdncadapter="http://org.onap.so/workflow/sdnc/adapter/schema/v1" + xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1"> + <sdncadapter:RequestHeader> + <sdncadapter:RequestId>${MsoUtils.xmlEscape(hdrRequestId)}</sdncadapter:RequestId> + <sdncadapter:SvcInstanceId>${MsoUtils.xmlEscape(serviceInstanceId)}</sdncadapter:SvcInstanceId> + <sdncadapter:SvcAction>${MsoUtils.xmlEscape(sdnc_svcAction)}</sdncadapter:SvcAction> + <sdncadapter:SvcOperation>network-topology-operation</sdncadapter:SvcOperation> + <sdncadapter:CallbackUrl>sdncCallback</sdncadapter:CallbackUrl> + <sdncadapter:MsoAction>generic-resource</sdncadapter:MsoAction> + </sdncadapter:RequestHeader> + <sdncadapterworkflow:SDNCRequestData> + <request-information> + <request-id>${MsoUtils.xmlEscape(hdrRequestId)}</request-id> + <request-action>${MsoUtils.xmlEscape(sdnc_requestAction)}</request-action> + <source>${MsoUtils.xmlEscape(source)}</source> + <notification-url></notification-url> + <order-number></order-number> + <order-version></order-version> + </request-information> + <service-information> + <service-id>${MsoUtils.xmlEscape(serviceInstanceId)}</service-id> + <subscription-service-type>${MsoUtils.xmlEscape(serviceType)}</subscription-service-type> + <onap-model-information> + <model-invariant-uuid>${MsoUtils.xmlEscape(serviceModelInvariantUuid)}</model-invariant-uuid> + <model-uuid>${MsoUtils.xmlEscape(serviceModelUuid)}</model-uuid> + <model-version>${MsoUtils.xmlEscape(serviceModelVersion)}</model-version> + <model-name>${MsoUtils.xmlEscape(serviceModelName)}</model-name> + </onap-model-information> + <service-instance-id>${MsoUtils.xmlEscape(serviceInstanceId)}</service-instance-id> + <global-customer-id>${MsoUtils.xmlEscape(globalCustomerId)}</global-customer-id> + </service-information> + <vnf-information> + <vnf-id></vnf-id> + <vnf-type></vnf-type> + <onap-model-information> + <model-invariant-uuid>${MsoUtils.xmlEscape(modelInvariantUuid)}</model-invariant-uuid> + <model-customization-uuid>${MsoUtils.xmlEscape(modelCustomizationUuid)}</model-customization-uuid> + <model-uuid>${MsoUtils.xmlEscape(modelUuid)}</model-uuid> + <model-version>${MsoUtils.xmlEscape(modelVersion)}</model-version> + <model-name>${MsoUtils.xmlEscape(modelName)}</model-name> + </onap-model-information> + </vnf-information> + <vnf-input-parameters> + <param>${MsoUtils.xmlEscape(netowrkInputParameters)}</param> + </vnf-input-parameters> + <vnf-request-input> + <request-version></request-version> + <vnf-name></vnf-name> + <neutron-id></neutron-id> + <contrail-network-fqdn></contrail-network-fqdn> + <subnets-data> + <subnet-data> + <element> + <ip-version></ip-version> + <subnet-id></subnet-id> + </subnet-data> + </subnets-data> + </vnf-request-input> + </sdncadapterworkflow:SDNCRequestData> + </aetgt:SDNCAdapterWorkflowRequest>""".trim() + break + + case ~/^SOTNAttachment$/: + sdncTopologyActivateRequest = + """<aetgt:SDNCAdapterWorkflowRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:sdncadapter="http://org.onap.so/workflow/sdnc/adapter/schema/v1" + xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1"> + <sdncadapter:RequestHeader> + <sdncadapter:RequestId>${MsoUtils.xmlEscape(hdrRequestId)}</sdncadapter:RequestId> + <sdncadapter:SvcInstanceId>${MsoUtils.xmlEscape(serviceInstanceId)}</sdncadapter:SvcInstanceId> + <sdncadapter:SvcAction>${MsoUtils.xmlEscape(sdnc_svcAction)}</sdncadapter:SvcAction> + <sdncadapter:SvcOperation>network-topology-operation</sdncadapter:SvcOperation> + <sdncadapter:CallbackUrl>sdncCallback</sdncadapter:CallbackUrl> + <sdncadapter:MsoAction>generic-resource</sdncadapter:MsoAction> + </sdncadapter:RequestHeader> + <sdncadapterworkflow:SDNCRequestData> + <request-information> + <request-id>${MsoUtils.xmlEscape(hdrRequestId)}</request-id> + <request-action>${MsoUtils.xmlEscape(sdnc_requestAction)}</request-action> + <source>${MsoUtils.xmlEscape(source)}</source> + <notification-url></notification-url> + <order-number></order-number> + <order-version></order-version> + </request-information> + <service-information> + <service-id>${MsoUtils.xmlEscape(serviceInstanceId)}</service-id> + <subscription-service-type>${MsoUtils.xmlEscape(serviceType)}</subscription-service-type> + <onap-model-information> + <model-invariant-uuid>${MsoUtils.xmlEscape(serviceModelInvariantUuid)}</model-invariant-uuid> + <model-uuid>${MsoUtils.xmlEscape(serviceModelUuid)}</model-uuid> + <model-version>${MsoUtils.xmlEscape(serviceModelVersion)}</model-version> + <model-name>${MsoUtils.xmlEscape(serviceModelName)}</model-name> + </onap-model-information> + <service-instance-id>${MsoUtils.xmlEscape(serviceInstanceId)}</service-instance-id> + <global-customer-id>${MsoUtils.xmlEscape(globalCustomerId)}</global-customer-id> + </service-information> + <allotted-resource-information> + <!-- TODO: to be filled as per the request input --> + <allotted-resource-input></allotted-resource-input> + <allotted-resource-type></allotted-resource-type> + <parent-service-instance-id><parent-service-instance-id> + <onap-model-information> + <model-invariant-uuid>${MsoUtils.xmlEscape(modelInvariantUuid)}</model-invariant-uuid> + <model-customization-uuid>${MsoUtils.xmlEscape(modelCustomizationUuid)}</model-customization-uuid> + <model-uuid>${MsoUtils.xmlEscape(modelUuid)}</model-uuid> + <model-version>${MsoUtils.xmlEscape(modelVersion)}</model-version> + <model-name>${MsoUtils.xmlEscape(modelName)}</model-name> + </onap-model-information> + </allotted-resource-information> + <connection-attachment-request-input> + <param>${MsoUtils.xmlEscape(netowrkInputParameters)}</param> + </connection-attachment-request-input> + </sdncadapterworkflow:SDNCRequestData> + </aetgt:SDNCAdapterWorkflowRequest>""".trim() + break + + default: + sdncTopologyActivateRequest = + """<aetgt:SDNCAdapterWorkflowRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:sdncadapter="http://org.onap.so/workflow/sdnc/adapter/schema/v1" + xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1"> + <sdncadapter:RequestHeader> + <sdncadapter:RequestId>${MsoUtils.xmlEscape(hdrRequestId)}</sdncadapter:RequestId> + <sdncadapter:SvcInstanceId>${MsoUtils.xmlEscape(serviceInstanceId)}</sdncadapter:SvcInstanceId> + <sdncadapter:SvcAction>${MsoUtils.xmlEscape(sdnc_svcAction)}</sdncadapter:SvcAction> + <sdncadapter:SvcOperation>network-topology-operation</sdncadapter:SvcOperation> + <sdncadapter:CallbackUrl>sdncCallback</sdncadapter:CallbackUrl> + <sdncadapter:MsoAction>generic-resource</sdncadapter:MsoAction> + </sdncadapter:RequestHeader> + <sdncadapterworkflow:SDNCRequestData> + <request-information> + <request-id>${MsoUtils.xmlEscape(hdrRequestId)}</request-id> + <request-action>${MsoUtils.xmlEscape(sdnc_requestAction)}</request-action> + <source>${MsoUtils.xmlEscape(source)}</source> + <notification-url></notification-url> + <order-number></order-number> + <order-version></order-version> + </request-information> + <service-information> + <service-id>${MsoUtils.xmlEscape(serviceInstanceId)}</service-id> + <subscription-service-type>${MsoUtils.xmlEscape(serviceType)}</subscription-service-type> + <onap-model-information> + <model-invariant-uuid>${MsoUtils.xmlEscape(serviceModelInvariantUuid)}</model-invariant-uuid> + <model-uuid>${MsoUtils.xmlEscape(serviceModelUuid)}</model-uuid> + <model-version>${MsoUtils.xmlEscape(serviceModelVersion)}</model-version> + <model-name>${MsoUtils.xmlEscape(serviceModelName)}</model-name> + </onap-model-information> + <service-instance-id>${MsoUtils.xmlEscape(serviceInstanceId)}</service-instance-id> + <global-customer-id>${MsoUtils.xmlEscape(globalCustomerId)}</global-customer-id> + </service-information> + <network-information> + <!-- TODO: to be filled by response from create --> + <network-id></network-id> + <onap-model-information> + <model-invariant-uuid>${MsoUtils.xmlEscape(modelInvariantUuid)}</model-invariant-uuid> + <model-customization-uuid>${MsoUtils.xmlEscape(modelCustomizationUuid)}</model-customization-uuid> + <model-uuid>${MsoUtils.xmlEscape(modelUuid)}</model-uuid> + <model-version>${MsoUtils.xmlEscape(modelVersion)}</model-version> + <model-name>${MsoUtils.xmlEscape(modelName)}</model-name> + </onap-model-information> + </network-information> + <network-request-input> + <network-input-parameters>${MsoUtils.xmlEscape(netowrkInputParameters)}</network-input-parameters> + </network-request-input> + </sdncadapterworkflow:SDNCRequestData> + </aetgt:SDNCAdapterWorkflowRequest>""".trim() + + } + + String sdncTopologyActivateRequesAsString = utils.formatXml(sdncTopologyActivateRequest) + msoLogger.debug(sdncTopologyActivateRequesAsString) + execution.setVariable("sdncAdapterWorkflowRequest", sdncTopologyActivateRequesAsString) + msoLogger.debug("sdncAdapterWorkflowRequest - " + "\n" + sdncTopologyActivateRequesAsString) + + } catch (Exception ex) { + String exceptionMessage = " Bpmn error encountered in CreateSDNCCNetworkResource flow. prepareSDNCRequest() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + msoLogger.trace("Exit prepareSDNCRequest ") + } + + public void postCreateSDNCCall(DelegateExecution execution) { + msoLogger.trace("started postCreateSDNCCall ") + + String responseCode = execution.getVariable(Prefix + "sdncCreateReturnCode") + String responseObj = execution.getVariable(Prefix + "SuccessIndicator") + + msoLogger.info("response from sdnc, response code :" + responseCode + " response object :" + responseObj) + } + + public void sendSyncResponse(DelegateExecution execution) { + msoLogger.trace("started sendSyncResponse ") + + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + utils.log("DEBUG", " *** sendSyncResponse *** ", isDebugEnabled) + + try { + String operationStatus = "finished" + // RESTResponse for main flow + String resourceOperationResp = """{"operationStatus":"${operationStatus}"}""".trim() + utils.log("DEBUG", " sendSyncResponse to APIH:" + "\n" + resourceOperationResp, isDebugEnabled) + sendWorkflowResponse(execution, 202, resourceOperationResp) + execution.setVariable("sentSyncResponse", true) + + } catch (Exception ex) { + String msg = "Exceptuion in sendSyncResponse:" + ex.getMessage() + utils.log("DEBUG", msg, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + utils.log("DEBUG"," ***** Exit sendSyncResopnse *****", isDebugEnabled) + } +}
\ No newline at end of file diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CompareModelofE2EServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CompareModelofE2EServiceInstance.groovy new file mode 100644 index 0000000000..880a44c1b2 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CompareModelofE2EServiceInstance.groovy @@ -0,0 +1,256 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2018 Huawei Technologies Co., Ltd. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.so.bpmn.infrastructure.scripts; + +import static org.apache.commons.lang3.StringUtils.*; + +import org.apache.commons.lang3.* +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.onap.so.bpmn.common.scripts.ExceptionUtil +import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.so.bpmn.common.scripts.VidUtils +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.bpmn.core.domain.CompareModelsResult +import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.logger.MsoLogger + +import groovy.json.* + + +/** + * This groovy class supports the <class>CompareModelofE2EServiceInstance.bpmn</class> process. + * + * Inputs: + * @param - msoRequestId + * @param - globalSubscriberId + * @param - subscriptionServiceType + * @param - serviceInstanceId + * @param - modelInvariantIdTarget + * @param - modelVersionIdTarget + + * + * Outputs: + * @param - WorkflowException + */ +public class CompareModelofE2EServiceInstance extends AbstractServiceTaskProcessor { + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, CompareModelofE2EServiceInstance.class); + + String Prefix="CMPMDSI_" + private static final String DebugFlag = "isDebugEnabled" + + ExceptionUtil exceptionUtil = new ExceptionUtil() + JsonUtils jsonUtil = new JsonUtils() + VidUtils vidUtils = new VidUtils() + + public void preProcessRequest (DelegateExecution execution) { + execution.setVariable("prefix",Prefix) + String msg = "" + + msoLogger.trace("preProcessRequest Request ") + + try { + // check for incoming json message/input + String siRequest = execution.getVariable("bpmnRequest") + msoLogger.debug(siRequest) + + + String requestId = execution.getVariable("mso-request-id") + execution.setVariable("msoRequestId", requestId) + msoLogger.info("Input Request:" + siRequest + " reqId:" + requestId) + + String serviceInstanceId = execution.getVariable("serviceInstanceId") + if (isBlank(serviceInstanceId)) { + msg = "Input serviceInstanceId' is null" + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + + //subscriberInfo + String globalSubscriberId = jsonUtil.getJsonValue(siRequest, "globalSubscriberId") + if (isBlank(globalSubscriberId)) { + msg = "Input globalSubscriberId' is null" + utils.log("INFO", msg, isDebugEnabled) + } else { + execution.setVariable("globalSubscriberId", globalSubscriberId) + } + + //subscriptionServiceType + String subscriptionServiceType = jsonUtil.getJsonValue(siRequest, "serviceType") + if (isBlank(subscriptionServiceType)) { + msg = "Input subscriptionServiceType is null" + utils.log("DEBUG", msg, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } else { + execution.setVariable("serviceType", subscriptionServiceType) + } + + //modelInvariantIdTarget + String modelInvariantIdTarget = jsonUtil.getJsonValue(siRequest, "modelInvariantIdTarget") + if (isBlank(modelInvariantIdTarget)) { + msg = "Input modelInvariantIdTarget' is null" + utils.log("INFO", msg, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } else { + execution.setVariable("modelInvariantIdTarget", modelInvariantIdTarget) + } + + //modelVersionIdTarget + String modelVersionIdTarget = jsonUtil.getJsonValue(siRequest, "modelVersionIdTarget") + if (isBlank(modelVersionIdTarget)) { + msg = "Input modelVersionIdTarget is null" + utils.log("DEBUG", msg, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } else { + execution.setVariable("modelVersionIdTarget", modelVersionIdTarget) + } + + execution.setVariable("operationType", "CompareModel") + + } catch (BpmnError e) { + throw e; + } catch (Exception ex){ + msg = "Exception in preProcessRequest " + ex.getMessage() + msoLogger.info(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.trace("Exit preProcessRequest ") + } + + public void sendSyncResponse (DelegateExecution execution) { + msoLogger.trace("sendSyncResponse ") + + try { + CompareModelsResult compareModelsResult = execution.getVariable("compareModelsResult") + + // RESTResponse (for API Handler(APIH) Reply Task) + String syncResponse = compareModelsResult.toJsonStringNoRootName() + msoLogger.info(" sendSynchResponse: xmlSyncResponse - " + "\n" + syncResponse) + sendWorkflowResponse(execution, 202, syncResponse) + + } catch (Exception ex) { + String msg = "Exception in sendSyncResponse: " + ex.getMessage() + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.trace("Exit sendSyncResopnse ") + } + + public void sendSyncError (DelegateExecution execution) { + msoLogger.trace("sendSyncError ") + + try { + String errorMessage = "" + if (execution.getVariable("WorkflowException") instanceof WorkflowException) { + WorkflowException wfe = execution.getVariable("WorkflowException") + errorMessage = wfe.getErrorMessage() + } else { + errorMessage = "Sending Sync Error." + } + + String buildworkflowException = + """<aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1"> + <aetgt:ErrorMessage>${MsoUtils.xmlEscape(errorMessage)}</aetgt:ErrorMessage> + <aetgt:ErrorCode>7000</aetgt:ErrorCode> + </aetgt:WorkflowException>""" + + msoLogger.debug(buildworkflowException) + sendWorkflowResponse(execution, 500, buildworkflowException) + + } catch (Exception ex) { + msoLogger.info(" Sending Sync Error Activity Failed. " + "\n" + ex.getMessage()) + } + + } + + public void prepareCompletionRequest (DelegateExecution execution) { + msoLogger.trace("prepareCompletion ") + + try { + String requestId = execution.getVariable("msoRequestId") + String source = execution.getVariable("source") + String msoCompletionRequest = + """<aetgt:MsoCompletionRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:ns="http://org.onap/so/request/types/v1"> + <request-info xmlns="http://org.onap/so/infra/vnf-request/v1"> + <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> + <action>COMPAREMODEL</action> + <source>${MsoUtils.xmlEscape(source)}</source> + </request-info> + <aetgt:status-message>E2E Service Instance Compare model successfully.</aetgt:status-message> + <aetgt:mso-bpel-name>CompareModelofE2EServiceInstance</aetgt:mso-bpel-name> + </aetgt:MsoCompletionRequest>""" + + // Format Response + String xmlMsoCompletionRequest = utils.formatXml(msoCompletionRequest) + + execution.setVariable("completionRequest", xmlMsoCompletionRequest) + msoLogger.info(" Overall SUCCESS Response going to CompleteMsoProcess - " + "\n" + xmlMsoCompletionRequest) + + } catch (Exception ex) { + String msg = " Exception in prepareCompletion:" + ex.getMessage() + msoLogger.info(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.trace("Exit prepareCompletionRequest ") + } + + public void prepareFalloutRequest(DelegateExecution execution){ + msoLogger.trace("prepareFalloutRequest ") + + try { + WorkflowException wfex = execution.getVariable("WorkflowException") + msoLogger.info(" Input Workflow Exception: " + wfex.toString()) + String requestId = execution.getVariable("msoRequestId") + String source = execution.getVariable("source") + String requestInfo = + """<request-info xmlns="http://org.onap/so/infra/vnf-request/v1"> + <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> + <action>COMPAREMODEL</action> + <source>${MsoUtils.xmlEscape(source)}</source> + </request-info>""" + + String falloutRequest = exceptionUtil.processMainflowsBPMNException(execution, requestInfo) + execution.setVariable("falloutRequest", falloutRequest) + } catch (Exception ex) { + msoLogger.info("Exception prepareFalloutRequest:" + ex.getMessage()) + String errorException = " Bpmn error encountered in CompareModelofE2EServiceInstance flow. FalloutHandlerRequest, buildErrorResponse() - " + ex.getMessage() + String requestId = execution.getVariable("msoRequestId") + String falloutRequest = + """<aetgt:FalloutHandlerRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:ns="http://org.onap/so/request/types/v1" + xmlns:wfsch="http://org.onap/so/workflow/schema/v1"> + <request-info xmlns="http://org.onap/so/infra/vnf-request/v1"> + <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> + <action>COMPAREMODEL</action> + <source>UUI</source> + </request-info> + <aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1"> + <aetgt:ErrorMessage>${MsoUtils.xmlEscape(errorException)}</aetgt:ErrorMessage> + <aetgt:ErrorCode>7000</aetgt:ErrorCode> + </aetgt:WorkflowException> + </aetgt:FalloutHandlerRequest>""" + + execution.setVariable("falloutRequest", falloutRequest) + } + msoLogger.trace("Exit prepareFalloutRequest ") + } + +} + diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/Create3rdONAPE2EServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/Create3rdONAPE2EServiceInstance.groovy new file mode 100644 index 0000000000..80e6e758c0 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/Create3rdONAPE2EServiceInstance.groovy @@ -0,0 +1,604 @@ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - SO + * ================================================================================ + * Copyright (C) 2018 Huawei Technologies Co., Ltd. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License") + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts + +import org.json.JSONObject +import org.json.XML + +import static org.apache.commons.lang3.StringUtils.* +import groovy.xml.XmlUtil +import groovy.json.* +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.onap.so.bpmn.common.scripts.ExceptionUtil +import org.onap.so.bpmn.common.scripts.ExternalAPIUtil +import org.onap.so.bpmn.common.scripts.AaiUtil +import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.so.bpmn.common.recipe.ResourceInput +import org.onap.so.bpmn.common.resource.ResourceRequestBuilder +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.bpmn.infrastructure.workflow.serviceTask.client.builder.AbstractBuilder +import org.onap.so.rest.APIResponse +import org.onap.so.bpmn.common.scripts.SDNCAdapterUtils +import org.onap.so.bpmn.infrastructure.workflow.service.ServicePluginFactory +import java.util.UUID +import org.onap.so.logger.MsoLogger + +import org.camunda.bpm.engine.runtime.Execution +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.apache.commons.lang3.* +import org.apache.commons.codec.binary.Base64 +import org.springframework.web.util.UriUtils +import org.onap.so.rest.RESTClient +import org.onap.so.rest.RESTConfig + +/** + * This groovy class supports the <class>Create3rdONAPE2EServiceInstance.bpmn</class> process. + * flow for Create E2EServiceInstance in 3rdONAP + */ +public class Create3rdONAPE2EServiceInstance extends AbstractServiceTaskProcessor { + + String Prefix = "CRE3rdONAPESI_" + + ExceptionUtil exceptionUtil = new ExceptionUtil() + + JsonUtils jsonUtil = new JsonUtils() + + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, Create3rdONAPE2EServiceInstance.class) + + public void checkSPPartnerInfo (DelegateExecution execution) { + msoLogger.info(" ***** Started checkSPPartnerInfo *****") + try { + //get bpmn inputs from resource request. + String requestId = execution.getVariable("mso-request-id") + String requestAction = execution.getVariable("requestAction") + msoLogger.info("The requestAction is: " + requestAction) + String recipeParamsFromRequest = execution.getVariable("recipeParams") + msoLogger.info("The recipeParams is: " + recipeParamsFromRequest) + String resourceInput = execution.getVariable("resourceInput") + msoLogger.info("The resourceInput is: " + resourceInput) + //Get ResourceInput Object + ResourceInput resourceInputObj = ResourceRequestBuilder.getJsonObject(resourceInput, ResourceInput.class) + String resourceInputPrameters = resourceInputObj.getResourceParameters() + String inputParametersJson = jsonUtil.getJsonValue(resourceInputPrameters, "requestInputs") + JSONObject inputParameters = new JSONObject(customizeResourceParam(inputParametersJson)) + + // set local resourceInput + execution.setVariable(Prefix + "ResourceInput", resourceInputObj) + + boolean is3rdONAPExist = false + + if(inputParameters.has("id")) + { + String sppartnerId = inputParameters.get("id") + } + if(inputParameters.has("url")) + { + String sppartnerUrl = inputParameters.get("url") + if(!isBlank(sppartnerUrl)) { + execution.setVariable(Prefix + "SppartnerUrl", sppartnerUrl) + is3rdONAPExist = true + } + else { + is3rdONAPExist = false + String msg = "sppartner Url is blank." + msoLogger.debug(msg) + } + } + if(inputParameters.has("providingServiceInvarianteUuid")) + { + String sppartnerInvarianteUUID = inputParameters.get("providingServiceInvarianteUuid") + execution.setVariable(Prefix + "SppartnerInvarianteUUID", sppartnerInvarianteUUID) + is3rdONAPExist = true + } + else { + is3rdONAPExist = false + String msg = "sppartner providingServiceInvarianteUuid is blank." + msoLogger.debug(msg) + } + if(inputParameters.has("providingServiceUuid")) + { + String sppartnerUUID = inputParameters.get("providingServiceUuid") + execution.setVariable(Prefix + "SppartnerUUID", sppartnerUUID) + is3rdONAPExist = true + } + else { + is3rdONAPExist = false + String msg = "sppartner providingServiceUuid is blank." + msoLogger.debug(msg) + } + + if(inputParameters.has("handoverMode")) + { + String handoverMode = inputParameters.get("handoverMode") + execution.setVariable(Prefix + "HandoverMode", handoverMode) + is3rdONAPExist = true + } + else { + is3rdONAPExist = false + String msg = "sppartner handoverMode is blank." + msoLogger.debug(msg) + } + + execution.setVariable("Is3rdONAPExist", is3rdONAPExist) + execution.setVariable(Prefix + "ServiceInstanceId", resourceInputObj.getServiceInstanceId()) + execution.setVariable("mso-request-id", requestId) + execution.setVariable("mso-service-instance-id", resourceInputObj.getServiceInstanceId()) + + } catch (BpmnError e) { + throw e + } catch (Exception ex){ + String msg = "Exception in checkSPPartnerInfo " + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + } + + public void checkLocallCall (DelegateExecution execution) { + def isDebugEnabled = execution.getVariable("isDebugLogEnabled") + msoLogger.info(" ***** Started checkLocallCall *****") + try { + + //Get ResourceInput Object + ResourceInput resourceInputObj = execution.getVariable(Prefix + "ResourceInput") + + //uuiRequest + String incomingRequest = resourceInputObj.getRequestsInputs() + String serviceParameters = jsonUtil.getJsonValue(incomingRequest, "service.parameters") + JSONObject inputParameters = new JSONObject(customizeResourceParam(serviceParameters)) + execution.setVariable(Prefix + "ServiceParameters", inputParameters) + + // CallSource is added only when ONAP SO calling 3rdONAP(External API) SO(Remote call) + boolean isLocalCall = true + String callSource = "UUI" + if(inputParameters.has("CallSource")) + { + callSource = inputParameters.get("CallSource") + if("ExternalAPI".equalsIgnoreCase(callSource)) { + isLocalCall = false + } + } + execution.setVariable(Prefix + "CallSource", callSource) + msoLogger.debug("callSource is: " + callSource ) + + execution.setVariable("IsLocalCall", isLocalCall) + + } catch (Exception ex){ + String msg = "Exception in checkLocallCall " + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + } + + public void preProcessRequest(DelegateExecution execution){ + def isDebugEnabled = execution.getVariable("isDebugLogEnabled") + msoLogger.info(" ***** Started preProcessRequest *****") + try { + ResourceInput resourceInputObj = execution.getVariable(Prefix + "ResourceInput") + String msg = "" + + String globalSubscriberId = resourceInputObj.getGlobalSubscriberId() + if (isBlank(globalSubscriberId)) { + msg = "Input globalSubscriberId is null" + msoLogger.info(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + //set local variable + execution.setVariable("globalSubscriberId", globalSubscriberId) + msoLogger.info("globalSubscriberId:" + globalSubscriberId) + + String serviceType = resourceInputObj.getServiceType() + if (isBlank(serviceType)) { + msg = "Input serviceType is null" + msoLogger.info(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + execution.setVariable("serviceType", serviceType) + msoLogger.info("serviceType:" + serviceType) + + String resourceName = resourceInputObj.getResourceInstanceName() + if (isBlank(resourceName)) { + msg = "Input resourceName is null" + msoLogger.info(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + execution.setVariable("resourceName", resourceName) + msoLogger.info("resourceName:" + resourceName) + + int beginIndex = resourceName.indexOf("_") + 1 + String serviceInstanceName = resourceName.substring(beginIndex) + execution.setVariable("serviceInstanceName", serviceInstanceName) + + String serviceInstanceId = resourceInputObj.getServiceInstanceId() + if (isBlank(serviceInstanceId)) { + msg = "Input serviceInstanceId is null" + msoLogger.info(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + execution.setVariable("serviceInstanceId", serviceInstanceId) + msoLogger.info("serviceInstanceId:" + serviceInstanceId) + + } catch (BpmnError e) { + throw e + } catch (Exception ex){ + String msg = "Exception in preProcessRequest " + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + } + + public void prepareUpdateProgress(DelegateExecution execution) { + def isDebugEnabled = execution.getVariable("isDebugLogEnabled") + msoLogger.info(" ***** Started prepareUpdateProgress *****") + ResourceInput resourceInputObj = execution.getVariable(Prefix + "ResourceInput") + String operType = resourceInputObj.getOperationType() + String resourceCustomizationUuid = resourceInputObj.getResourceModelInfo().getModelCustomizationUuid() + String ServiceInstanceId = resourceInputObj.getServiceInstanceId() + String modelName = resourceInputObj.getResourceModelInfo().getModelName() + String operationId = resourceInputObj.getOperationId() + String progress = execution.getVariable("progress") + String status = execution.getVariable("status") + String statusDescription = execution.getVariable("statusDescription") + + String body = """ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" + xmlns:ns="http://org.openecomp.mso/requestsdb"> + <soapenv:Header/> + <soapenv:Body> + <ns:updateResourceOperationStatus> + <operType>${operType}</operType> + <operationId>${operationId}</operationId> + <progress>${progress}</progress> + <resourceTemplateUUID>${resourceCustomizationUuid}</resourceTemplateUUID> + <serviceId>${ServiceInstanceId}</serviceId> + <status>${status}</status> + <statusDescription>${statusDescription}</statusDescription> + </ns:updateResourceOperationStatus> + </soapenv:Body> + </soapenv:Envelope>""" + + setProgressUpdateVariables(execution, body) + msoLogger.info(" ***** Exit prepareUpdateProgress *****") + } + + public void allocateCrossONAPResource(DelegateExecution execution) { + def isDebugEnabled = execution.getVariable("isDebugLogEnabled") + msoLogger.info(" ***** Started allocateCrossONAPResource *****") + + //get TP links from AAI for SOTN handoverMode only + String handoverMode = execution.getVariable(Prefix + "HandoverMode") + if("SOTN".equalsIgnoreCase(handoverMode)) { + //to do get tp link in AAI + + + // Put TP Link info into serviceParameters + String accessProviderId = "" + String accessClientId = "" + String accessTopologyId = "" + String accessNodeId = "" + String accessLtpId = "" + JSONObject inputParameters = execution.getVariable(Prefix + "ServiceParameters") + inputParameters.put("access-provider-id", accessProviderId) + inputParameters.put("access-client-id", accessClientId) + inputParameters.put("access-topology-id", accessTopologyId) + inputParameters.put("access-node-id", accessNodeId) + inputParameters.put("access-ltp-id", accessLtpId) + execution.setVariable(Prefix + "ServiceParameters", inputParameters) + } + + msoLogger.info("Exit " + allocateCrossONAPResource) + } + + public void prepare3rdONAPRequest(DelegateExecution execution) { + def isDebugEnabled = execution.getVariable("isDebugLogEnabled") + msoLogger.info(" ***** Started prepare3rdONAPRequest *****") + + String sppartnerUrl = execution.getVariable(Prefix + "SppartnerUrl") + String extAPIPath = sppartnerUrl + 'serviceOrder' + execution.setVariable("ExternalAPIURL", extAPIPath) + + // ExternalAPI message format + String externalId = execution.getVariable("resourceName") + String category = "E2E Service" + String description = "Service Order from SPPartner" + String requestedStartDate = utils.generateCurrentTimeInUtc() + String requestedCompletionDate = utils.generateCurrentTimeInUtc() + String priority = "1" // 0-4 0:highest + String subscriberId = execution.getVariable("globalSubscriberId") + String customerRole = "" + String subscriberName = "" + String referredType = "Consumer" + String orderItemId = "1" + String action = "add" //for create + String serviceState = "active" + String serviceName = execution.getVariable("serviceInstanceName") + String serviceType = execution.getVariable("serviceType") + String serviceId = execution.getVariable("serviceInstanceId") + + Map<String, String> valueMap = new HashMap<>() + valueMap.put("externalId", '"' + externalId + '"') + valueMap.put("category", '"' + category + '"') + valueMap.put("description", '"' + description + '"') + valueMap.put("requestedStartDate", '"' + requestedStartDate + '"') + valueMap.put("requestedCompletionDate", '"' + requestedCompletionDate + '"') + valueMap.put("priority", '"'+ priority + '"') + valueMap.put("subscriberId", '"' + subscriberId + '"') + valueMap.put("customerRole", '"' + customerRole + '"') + valueMap.put("subscriberName", '"' + subscriberName + '"') + valueMap.put("referredType", '"' + referredType + '"') + valueMap.put("orderItemId", '"' + orderItemId + '"') + valueMap.put("action", '"' + action + '"') + valueMap.put("serviceState", '"' + serviceState + '"') + valueMap.put("serviceName", '"' + serviceName + '"') + valueMap.put("serviceType", '"' + serviceType + '"') + valueMap.put("serviceId", '"' + serviceId + '"') + + ExternalAPIUtil externalAPIUtil = new ExternalAPIUtil(this) + + // insert CallSource='ExternalAPI' to uuiRequest + Map<String, String> callSourceMap = new HashMap<>() + callSourceMap.put("inputName", "CallSource") + callSourceMap.put("inputValue", "ExternalAPI") + String _requestInputs_ = externalAPIUtil.setTemplate(ExternalAPIUtil.RequestInputsTemplate, callSourceMap) + + // Transfer all uuiRequest incomeParameters to ExternalAPI format + JSONObject inputParameters = execution.getVariable(Prefix + "ServiceParameters") + for(String key : inputParameters.keySet()) { + String inputName = key + String inputValue = inputParameters.opt(key) + Map<String, String> requestInputsMap = new HashMap<>() + requestInputsMap.put("inputName", '"' + inputName+ '"') + requestInputsMap.put("inputValue", '"' + inputValue + '"') + _requestInputs_ += ",\n" + externalAPIUtil.setTemplate(ExternalAPIUtil.RequestInputsTemplate, requestInputsMap) + } + valueMap.put("_requestInputs_", _requestInputs_) + + String payload = externalAPIUtil.setTemplate(ExternalAPIUtil.PostServiceOrderRequestsTemplate, valueMap) + execution.setVariable(Prefix + "Payload", payload) + msoLogger.info("Exit " + prepare3rdONAPRequest) + } + + public void doCreateE2ESIin3rdONAP(DelegateExecution execution) { + def isDebugEnabled = execution.getVariable("isDebugLogEnabled") + msoLogger.info(" ***** Started doCreateE2ESIin3rdONAP *****") + + String extAPIPath = execution.getVariable("ExternalAPIURL") + String payload = execution.getVariable(Prefix + "Payload") + + ExternalAPIUtil externalAPIUtil = new ExternalAPIUtil(this) + + APIResponse response = externalAPIUtil.executeExternalAPIPostCall(execution, extAPIPath, payload) + + int responseCode = response.getStatusCode() + execution.setVariable(Prefix + "PostServiceOrderResponseCode", responseCode) + msoLogger.debug("Post ServiceOrder response code is: " + responseCode) + + String extApiResponse = response.getResponseBodyAsString() + JSONObject responseObj = new JSONObject(extApiResponse) + execution.setVariable(Prefix + "PostServiceOrderResponse", extApiResponse) + //Process Response + if(responseCode == 200 || responseCode == 201 || responseCode == 202 ) + //200 OK 201 CREATED 202 ACCEPTED + { + msoLogger.debug("Post ServiceOrder Received a Good Response") + String serviceOrderId = responseObj.get("ServiceOrderId") + execution.setVariable(Prefix + "SuccessIndicator", true) + execution.setVariable("serviceOrderId", serviceOrderId) + } + else{ + msoLogger.debug("Post ServiceOrder Received a Bad Response Code. Response Code is: " + responseCode) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Post ServiceOrder Received a bad response from 3rdONAP External API") + } + + msoLogger.info("Exit " + doCreateE2ESIin3rdONAP) + } + + + public void getE2ESIProgressin3rdONAP(DelegateExecution execution) { + def isDebugEnabled = execution.getVariable("isDebugLogEnabled") + msoLogger.info(" ***** Started getE2ESIProgressin3rdONAP *****") + + String extAPIPath = execution.getVariable("ExternalAPIURL") + extAPIPath += "/" + execution.getVariable("ServiceOrderId") + + ExternalAPIUtil externalAPIUtil = new ExternalAPIUtil(this) + + APIResponse response = externalAPIUtil.executeExternalAPIGetCall(execution, extAPIPath) + + int responseCode = response.getStatusCode() + execution.setVariable(Prefix + "GetServiceOrderResponseCode", responseCode) + msoLogger.debug("Get ServiceOrder response code is: " + responseCode) + + String extApiResponse = response.getResponseBodyAsString() + JSONObject responseObj = new JSONObject(extApiResponse) + execution.setVariable(Prefix + "GetServiceOrderResponse", extApiResponse) + + //Process Response //200 OK 201 CREATED 202 ACCEPTED + if(responseCode == 200 || responseCode == 201 || responseCode == 202 ) + { + msoLogger.debug("Get ServiceOrder Received a Good Response") + String serviceOrderState = responseObj.get("State") + execution.setVariable(Prefix + "SuccessIndicator", true) + execution.setVariable("serviceOrderState", serviceOrderState) + + // Get serviceOrder State and process progress + if("ACKNOWLEDGED".equalsIgnoreCase(serviceOrderState)) { + execution.setVariable("progress", 15) + execution.setVariable("status", "processing") + } + if("INPROGRESS".equalsIgnoreCase(serviceOrderState)) { + execution.setVariable("progress", 40) + execution.setVariable("status", "processing") + } + if("COMPLETED".equalsIgnoreCase(serviceOrderState)) { + execution.setVariable("progress", 100) + execution.setVariable("status", "finished") + } + if("FAILED".equalsIgnoreCase(serviceOrderState)) { + execution.setVariable("progress", 100) + execution.setVariable("status", "error") + } + else { + execution.setVariable("progress", 100) + execution.setVariable("status", "error") + execution.setVariable("statusDescription", "Create Service Order Status is unknown") + } + execution.setVariable("statusDescription", "Create Service Order Status is " + serviceOrderState) + } + else{ + msoLogger.debug("Get ServiceOrder Received a Bad Response Code. Response Code is: " + responseCode) + execution.setVariable("progress", 100) + execution.setVariable("status", "error") + execution.setVariable("statusDescription", "Get ServiceOrder Received a bad response") + exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Get ServiceOrder Received a bad response from 3rdONAP External API") + } + + msoLogger.info("Exit " + getE2ESIProgressin3rdONAP) + } + + /** + * delay 5 sec + */ + public void timeDelay(DelegateExecution execution) { + def isDebugEnabled= execution.getVariable("isDebugLogEnabled") + try { + Thread.sleep(5000) + } catch(InterruptedException e) { + utils.log("ERROR", "Time Delay exception" + e ) + } + } + + public void saveSPPartnerInAAI(DelegateExecution execution) { + def isDebugEnabled = execution.getVariable("isDebugLogEnabled") + msoLogger.info(" ***** Started postCreateE2ESIin3rdONAP *****") + + String sppartnerId = UUID.randomUUID().toString() + String sppartnerUrl = execution.getVariable(Prefix + "SppartnerUrl") + String callSource = execution.getVariable(Prefix + "CallSource") + String serviceInstanceId = execution.getVariable("serviceInstanceId") + String globalSubscriberId = execution.getVariable("globalSubscriberId") + String serviceType = execution.getVariable("serviceType") + + AaiUtil aaiUriUtil = new AaiUtil(this) + String aai_uri = aaiUriUtil.getBusinessSPPartnerUri(execution) + String namespace = aaiUriUtil.getNamespaceFromUri(aai_uri) + + String payload = + """<sp-partner xmlns=\"${namespace}\"> + <id>${sppartnerId}</id> + <url>${sppartnerUrl}</url> + <callsource>${callSource}</callsource> + <relationship-list> + <relationship> + <related-to>service-instance</related-to> + <related-link>/aai/v14/business/customers/customer/${globalSubscriberId}/service-subscriptions/service-subscription/${serviceType}/service-instances/service-instance/${serviceInstanceId}</related-link> + <relationship-data> + <relationship-key>service-instance.service-instance-id</relationship-key> + <relationship-value>${serviceInstanceId}</relationship-value> + </relationship-data> + </relationship> + </relationship-list> + </sp-partner>""".trim() + utils.logAudit(payload) + + String aai_endpoint = execution.getVariable("URN_aai_endpoint") + String serviceAaiPath = "${aai_endpoint}${aai_uri}/" + UriUtils.encode(sppartnerId,"UTF-8") + + APIResponse response = aaiUriUtil.executeAAIPutCall(execution, serviceAaiPath, payload) + int responseCode = response.getStatusCode() + execution.setVariable(Prefix + "PutSppartnerResponseCode", responseCode) + msoLogger.debug(" Put sppartner response code is: " + responseCode) + + String aaiResponse = response.getResponseBodyAsString() + aaiResponse = StringEscapeUtils.unescapeXml(aaiResponse) + execution.setVariable(Prefix + "PutSppartnerResponse", aaiResponse) + + //Process Response + if(responseCode == 200 || responseCode == 201 || responseCode == 202 ) + //200 OK 201 CREATED 202 ACCEPTED + { + msoLogger.debug("PUT sppartner Received a Good Response") + execution.setVariable(Prefix + "SuccessIndicator", true) + } + else + { + msoLogger.debug("Put sppartner Received a Bad Response Code. Response Code is: " + responseCode) + exceptionUtil.MapAAIExceptionToWorkflowExceptionGeneric(execution, aaiResponse, responseCode) + throw new BpmnError("MSOWorkflowException") + } + + msoLogger.info("Exit " + saveSPPartnerInAAI) + } + + private void setProgressUpdateVariables(DelegateExecution execution, String body) { + def dbAdapterEndpoint = execution.getVariable("URN_mso_adapters_openecomp_db_endpoint") + execution.setVariable("CVFMI_dbAdapterEndpoint", dbAdapterEndpoint) + execution.setVariable("CVFMI_updateResOperStatusRequest", body) + } + + public void postProcess(DelegateExecution execution){ + def isDebugEnabled = execution.getVariable("isDebugLogEnabled") + msoLogger.info(" ***** Started postProcess *****") + String responseCode = execution.getVariable(Prefix + "PutSppartnerResponseCode") + String responseObj = execution.getVariable(Prefix + "PutSppartnerResponse") + + msoLogger.info("response from AAI for put sppartner, response code :" + responseCode + " response object :" + responseObj) + msoLogger.info(" ***** Exit postProcess *****") + } + + public void sendSyncResponse (DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + msoLogger.debug(" *** sendSyncResponse *** ") + + try { + String operationStatus = "finished" + // RESTResponse for main flow + String resourceOperationResp = """{"operationStatus":"${operationStatus}"}""".trim() + msoLogger.debug(" sendSyncResponse to APIH:" + "\n" + resourceOperationResp) + sendWorkflowResponse(execution, 202, resourceOperationResp) + execution.setVariable("sentSyncResponse", true) + + } catch (Exception ex) { + String msg = "Exceptuion in sendSyncResponse:" + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.debug(" ***** Exit sendSyncResopnse *****") + } + + String customizeResourceParam(String inputParametersJson) { + List<Map<String, Object>> paramList = new ArrayList() + JSONObject jsonObject = new JSONObject(inputParametersJson) + Iterator iterator = jsonObject.keys() + while (iterator.hasNext()) { + String key = iterator.next() + HashMap<String, String> hashMap = new HashMap() + hashMap.put("name", key) + hashMap.put("value", jsonObject.get(key)) + paramList.add(hashMap) + } + Map<String, List<Map<String, Object>>> paramMap = new HashMap() + paramMap.put("param", paramList) + + return new JSONObject(paramMap).toString() + } +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateCustomE2EServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateCustomE2EServiceInstance.groovy new file mode 100644 index 0000000000..1034fa2d4d --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateCustomE2EServiceInstance.groovy @@ -0,0 +1,331 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts; + +import static org.apache.commons.lang3.StringUtils.*; + +import org.apache.commons.lang3.* +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.onap.so.bpmn.common.scripts.ExceptionUtil +import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.so.bpmn.core.UrnPropertiesReader +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.logger.MessageEnum +import org.onap.so.logger.MsoLogger +import org.springframework.web.util.UriUtils + +import groovy.json.* + +/** + * This groovy class supports the <class>CreateServiceInstance.bpmn</class> process. + * AlaCarte flow for 1702 ServiceInstance Create + * + */ +public class CreateCustomE2EServiceInstance extends AbstractServiceTaskProcessor { + String Prefix="CRESI_" + ExceptionUtil exceptionUtil = new ExceptionUtil() + JsonUtils jsonUtil = new JsonUtils() + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, CreateCustomE2EServiceInstance.class); + + + public void preProcessRequest (DelegateExecution execution) { + msoLogger.trace("start preProcessRequest") + execution.setVariable("prefix",Prefix) + String msg = "" + + try { + String siRequest = execution.getVariable("bpmnRequest") + msoLogger.debug(siRequest) + + String requestId = execution.getVariable("mso-request-id") + execution.setVariable("msoRequestId", requestId) + msoLogger.debug("Input Request:" + siRequest + " reqId:" + requestId) + + String serviceInstanceId = execution.getVariable("serviceInstanceId") + if (isBlank(serviceInstanceId)) { + serviceInstanceId = UUID.randomUUID().toString() + } + msoLogger.debug("Generated new Service Instance:" + serviceInstanceId) + serviceInstanceId = UriUtils.encode(serviceInstanceId,"UTF-8") + execution.setVariable("serviceInstanceId", serviceInstanceId) + + //subscriberInfo + String globalSubscriberId = jsonUtil.getJsonValue(siRequest, "requestDetails.subscriberInfo.globalSubscriberId") + if (isBlank(globalSubscriberId)) { + msg = "Input globalSubscriberId' is null" + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } else { + execution.setVariable("globalSubscriberId", globalSubscriberId) + } + + //requestInfo + execution.setVariable("source", jsonUtil.getJsonValue(siRequest, "requestDetails.requestInfo.source")) + execution.setVariable("serviceInstanceName", jsonUtil.getJsonValue(siRequest, "requestDetails.requestInfo.instanceName")) + execution.setVariable("disableRollback", jsonUtil.getJsonValue(siRequest, "requestDetails.requestInfo.suppressRollback")) + String productFamilyId = jsonUtil.getJsonValue(siRequest, "requestDetails.requestInfo.productFamilyId") + if (isBlank(productFamilyId)) + { + msg = "Input productFamilyId is null" + msoLogger.debug(msg) + //exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } else { + execution.setVariable("productFamilyId", productFamilyId) + } + + //modelInfo + String serviceModelInfo = jsonUtil.getJsonValue(siRequest, "requestDetails.modelInfo") + if (isBlank(serviceModelInfo)) { + msg = "Input serviceModelInfo is null" + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } else + { + execution.setVariable("serviceModelInfo", serviceModelInfo) + } + + msoLogger.debug("modelInfo: " + serviceModelInfo) + + //requestParameters + String subscriptionServiceType = jsonUtil.getJsonValue(siRequest, "requestDetails.requestParameters.subscriptionServiceType") + if (isBlank(subscriptionServiceType)) { + msg = "Input subscriptionServiceType is null" + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } else { + execution.setVariable("subscriptionServiceType", subscriptionServiceType) + } + + + /* + * Extracting User Parameters from incoming Request and converting into a Map + */ + def jsonSlurper = new JsonSlurper() + def jsonOutput = new JsonOutput() + + Map reqMap = jsonSlurper.parseText(siRequest) + + //InputParams + def userParamsList = reqMap.requestDetails?.requestParameters?.userParams + + Map<String, String> inputMap = [:] + if (userParamsList) { + for (def i=0; i<userParamsList.size(); i++) { + def userParams1 = userParamsList.get(i) + userParams1.each { param -> inputMap.put(param.key, param.value)} + } + } + + msoLogger.debug("User Input Parameters map: " + inputMap.toString()) + execution.setVariable("serviceInputParams", inputMap) + execution.setVariable("uuiRequest", inputMap.get("UUIRequest")) + execution.setVariable("mso.adapters.openecomp.db.endpoint","http://mso.mso.testlab.openecomp.org:8080/dbadapters/RequestsDbAdapter") + //TODO + //execution.setVariable("serviceInputParams", jsonUtil.getJsonValue(siRequest, "requestDetails.requestParameters.userParams")) + //execution.setVariable("failExists", true) + } catch (BpmnError e) { + throw e; + } catch (Exception ex){ + msg = "Exception in preProcessRequest " + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.trace("finished preProcessRequest") + } + + public void sendSyncResponse (DelegateExecution execution) { + msoLogger.trace("start sendSyncResponse") + try { + String operationId = execution.getVariable("operationId") + String serviceInstanceId = execution.getVariable("serviceInstanceId") + // RESTResponse for API Handler (APIH) Reply Task + String createServiceRestRequest = """{"service":{"serviceId":"${serviceInstanceId}","operationId":"${operationId}"}}""".trim() + msoLogger.debug(" sendSyncResponse to APIH:" + "\n" + createServiceRestRequest) + sendWorkflowResponse(execution, 202, createServiceRestRequest) + execution.setVariable("sentSyncResponse", true) + } catch (Exception ex) { + String msg = "Exceptuion in sendSyncResponse:" + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.trace("finished sendSyncResponse") + } + + + public void sendSyncError (DelegateExecution execution) { + msoLogger.trace("start sendSyncError") + try { + String errorMessage = "" + if (execution.getVariable("WorkflowException") instanceof WorkflowException) { + WorkflowException wfe = execution.getVariable("WorkflowException") + errorMessage = wfe.getErrorMessage() + } else { + errorMessage = "Sending Sync Error." + } + + String buildworkflowException = + """<aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1"> + <aetgt:ErrorMessage>${MsoUtils.xmlEscape(errorMessage)}</aetgt:ErrorMessage> + <aetgt:ErrorCode>7000</aetgt:ErrorCode> + </aetgt:WorkflowException>""" + + msoLogger.debug(buildworkflowException) + sendWorkflowResponse(execution, 500, buildworkflowException) + + } catch (Exception ex) { + msoLogger.debug("Sending Sync Error Activity Failed. " + "\n" + ex.getMessage()) + } + msoLogger.trace("finished sendSyncError") + } + + public void prepareCompletionRequest (DelegateExecution execution) { + msoLogger.trace("start prepareCompletionRequest") + try { + String requestId = execution.getVariable("msoRequestId") + String serviceInstanceId = execution.getVariable("serviceInstanceId") + String source = execution.getVariable("source") + + String msoCompletionRequest = + """<aetgt:MsoCompletionRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:ns="http://org.onap/so/request/types/v1"> + <request-info xmlns="http://org.onap/so/infra/vnf-request/v1"> + <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> + <action>CREATE</action> + <source>${MsoUtils.xmlEscape(source)}</source> + </request-info> + <status-message>Service Instance was created successfully.</status-message> + <serviceInstanceId>${MsoUtils.xmlEscape(serviceInstanceId)}</serviceInstanceId> + <mso-bpel-name>CreateGenericALaCarteServiceInstance</mso-bpel-name> + </aetgt:MsoCompletionRequest>""" + + // Format Response + String xmlMsoCompletionRequest = utils.formatXml(msoCompletionRequest) + + execution.setVariable("completionRequest", xmlMsoCompletionRequest) + msoLogger.debug("Overall SUCCESS Response going to CompleteMsoProcess - " + "\n" + xmlMsoCompletionRequest) + + } catch (Exception ex) { + String msg = " Exception in prepareCompletion:" + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.trace("finished prepareCompletionRequest") + } + + public void prepareFalloutRequest(DelegateExecution execution){ + msoLogger.trace("start prepareFalloutRequest") + try { + WorkflowException wfex = execution.getVariable("WorkflowException") + msoLogger.debug("Input Workflow Exception: " + wfex.toString()) + String requestId = execution.getVariable("msoRequestId") + String source = execution.getVariable("source") + String requestInfo = + """<request-info xmlns="http://org.onap/so/infra/vnf-request/v1"> + <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> + <action>CREATE</action> + <source>${MsoUtils.xmlEscape(source)}</source> + </request-info>""" + + String falloutRequest = exceptionUtil.processMainflowsBPMNException(execution, requestInfo) + execution.setVariable("falloutRequest", falloutRequest) + } catch (Exception ex) { + msoLogger.debug("Exception prepareFalloutRequest:" + ex.getMessage()) + String errorException = " Bpmn error encountered in CreateGenericALaCarteServiceInstance flow. FalloutHandlerRequest, buildErrorResponse() - " + ex.getMessage() + String requestId = execution.getVariable("msoRequestId") + String falloutRequest = + """<aetgt:FalloutHandlerRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:ns="http://org.onap/so/request/types/v1" + xmlns:wfsch="http://org.onap/so/workflow/schema/v1"> + <request-info xmlns="http://org.onap/so/infra/vnf-request/v1"> + <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> + <action>CREATE</action> + <source>UUI</source> + </request-info> + <aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1"> + <aetgt:ErrorMessage>${MsoUtils.xmlEscape(errorException)}</aetgt:ErrorMessage> + <aetgt:ErrorCode>7000</aetgt:ErrorCode> + </aetgt:WorkflowException> + </aetgt:FalloutHandlerRequest>""" + + execution.setVariable("falloutRequest", falloutRequest) + } + msoLogger.trace("finished prepareFalloutRequest") + } + + /** + * Init the service Operation Status + */ + public void prepareInitServiceOperationStatus(DelegateExecution execution){ + msoLogger.trace("start prepareInitServiceOperationStatus") + try{ + String serviceId = execution.getVariable("serviceInstanceId") + String operationId = UUID.randomUUID().toString() + String operationType = "CREATE" + String userId = "" + String result = "processing" + String progress = "0" + String reason = "" + String operationContent = "Prepare service creation" + msoLogger.debug("Generated new operation for Service Instance serviceId:" + serviceId + " operationId:" + operationId) + serviceId = UriUtils.encode(serviceId,"UTF-8") + execution.setVariable("serviceInstanceId", serviceId) + execution.setVariable("operationId", operationId) + execution.setVariable("operationType", operationType) + + def dbAdapterEndpoint = UrnPropertiesReader.getVariable("mso.adapters.openecomp.db.endpoint",execution) + execution.setVariable("CVFMI_dbAdapterEndpoint", dbAdapterEndpoint) + msoLogger.debug("DB Adapter Endpoint is: " + dbAdapterEndpoint) + + String payload = + """<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" + xmlns:ns="http://org.onap.so/requestsdb"> + <soapenv:Header/> + <soapenv:Body> + <ns:updateServiceOperationStatus xmlns:ns="http://org.onap.so/requestsdb"> + <serviceId>${MsoUtils.xmlEscape(serviceId)}</serviceId> + <operationId>${MsoUtils.xmlEscape(operationId)}</operationId> + <operationType>${MsoUtils.xmlEscape(operationType)}</operationType> + <userId>${MsoUtils.xmlEscape(userId)}</userId> + <result>${MsoUtils.xmlEscape(result)}</result> + <operationContent>${MsoUtils.xmlEscape(operationContent)}</operationContent> + <progress>${MsoUtils.xmlEscape(progress)}</progress> + <reason>${MsoUtils.xmlEscape(reason)}</reason> + </ns:updateServiceOperationStatus> + </soapenv:Body> + </soapenv:Envelope>""" + + payload = utils.formatXml(payload) + execution.setVariable("CVFMI_updateServiceOperStatusRequest", payload) + msoLogger.debug("Outgoing updateServiceOperStatusRequest: \n" + payload) + msoLogger.debug("CreateVfModuleInfra Outgoing updateServiceOperStatusRequest Request: " + payload) + + }catch(Exception e){ + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception Occured Processing prepareInitServiceOperationStatus.", "BPMN", MsoLogger.getServiceName(), + MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + execution.setVariable("CVFMI_ErrorResponse", "Error Occurred during prepareInitServiceOperationStatus Method:\n" + e.getMessage()) + } + msoLogger.trace("finished prepareInitServiceOperationStatus") + } + +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateGenericALaCarteServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateGenericALaCarteServiceInstance.groovy new file mode 100644 index 0000000000..4405718c57 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateGenericALaCarteServiceInstance.groovy @@ -0,0 +1,357 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts; + +import static org.apache.commons.lang3.StringUtils.*; + +import org.apache.commons.lang3.* +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.json.JSONException; +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.onap.so.bpmn.common.scripts.ExceptionUtil +import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.bpmn.core.domain.ServiceDecomposition +import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.logger.MsoLogger +import org.springframework.web.util.UriUtils + +import groovy.json.* + +/** + * This groovy class supports the <class>CreateGenericALaCarteServiceInstance.bpmn</class> process. + * AlaCarte flow for 1702 ServiceInstance Create + * + */ +public class CreateGenericALaCarteServiceInstance extends AbstractServiceTaskProcessor { + String Prefix="CRESI_" + ExceptionUtil exceptionUtil = new ExceptionUtil() + JsonUtils jsonUtil = new JsonUtils() + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, CreateGenericALaCarteServiceInstance.class); + + public void preProcessRequest (DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + String msg = "" + + try { + + String siRequest = execution.getVariable("bpmnRequest") + msoLogger.debug(siRequest) + + String requestId = execution.getVariable("mso-request-id") + execution.setVariable("msoRequestId", requestId) + msoLogger.debug("Input Request:" + siRequest + " reqId:" + requestId) + + String serviceInstanceId = execution.getVariable("serviceInstanceId") + if (isBlank(serviceInstanceId)) { + serviceInstanceId = UUID.randomUUID().toString() + msoLogger.debug("Generated new Service Instance ID:" + serviceInstanceId) + } else { + msoLogger.debug("Using provided Service Instance ID:" + serviceInstanceId) + } + + serviceInstanceId = UriUtils.encode(serviceInstanceId,"UTF-8") + execution.setVariable("serviceInstanceId", serviceInstanceId) + + //subscriberInfo + String globalSubscriberId = jsonUtil.getJsonValue(siRequest, "requestDetails.subscriberInfo.globalSubscriberId") + if (isBlank(globalSubscriberId)) { + msg = "Input globalSubscriberId' is null" + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } else { + execution.setVariable("globalSubscriberId", globalSubscriberId) + } + + //requestInfo + execution.setVariable("source", jsonUtil.getJsonValue(siRequest, "requestDetails.requestInfo.source")) + execution.setVariable("serviceInstanceName", jsonUtil.getJsonValue(siRequest, "requestDetails.requestInfo.instanceName")) + execution.setVariable("disableRollback", jsonUtil.getJsonValue(siRequest, "requestDetails.requestInfo.suppressRollback")) + String productFamilyId = null; + try { + productFamilyId = jsonUtil.getJsonValue(siRequest, "requestDetails.requestInfo.productFamilyId") + } catch (JSONException e) { + productFamilyId = null; + } + if (isBlank(productFamilyId)) + { + msg = "Input productFamilyId is null" + msoLogger.debug(msg) + //exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } else { + execution.setVariable("productFamilyId", productFamilyId) + } + + //modelInfo + String serviceModelInfo = jsonUtil.getJsonValue(siRequest, "requestDetails.modelInfo") + if (isBlank(serviceModelInfo)) { + msg = "Input serviceModelInfo is null" + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } else + { + execution.setVariable("serviceModelInfo", serviceModelInfo) + } + + msoLogger.debug("modelInfo" + serviceModelInfo) + + //requestParameters + String subscriptionServiceType = jsonUtil.getJsonValue(siRequest, "requestDetails.requestParameters.subscriptionServiceType") + if (isBlank(subscriptionServiceType)) { + msg = "Input subscriptionServiceType is null" + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } else { + execution.setVariable("subscriptionServiceType", subscriptionServiceType) + } + + + /* + * Extracting User Parameters from incoming Request and converting into a Map + */ + def jsonSlurper = new JsonSlurper() + def jsonOutput = new JsonOutput() + + Map reqMap = jsonSlurper.parseText(siRequest) + + //InputParams + def userParams = reqMap.requestDetails?.requestParameters?.userParams + + Map<String, String> inputMap = [:] + if (userParams) { + userParams.each { + userParam -> inputMap.put(userParam.name, userParam.value.toString()) + } + } + + msoLogger.debug("User Input Parameters map: " + userParams.toString()) + execution.setVariable("serviceInputParams", inputMap) + + //TODO + //execution.setVariable("failExists", true) + + } catch (BpmnError e) { + throw e; + } catch (Exception ex){ + msg = "Exception in preProcessRequest " + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.trace("Exit preProcessRequest") + } + + public void sendSyncResponse (DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + msoLogger.trace("Start sendSyncResponse") + + try { + String requestId = execution.getVariable("msoRequestId") + String serviceInstanceId = execution.getVariable("serviceInstanceId") + // RESTResponse for API Handler (APIH) Reply Task + String createServiceRestRequest = """{"requestReferences":{"instanceId":"${serviceInstanceId}","requestId":"${requestId}"}}""".trim() + msoLogger.debug(" sendSyncResponse to APIH:" + "\n" + createServiceRestRequest) + sendWorkflowResponse(execution, 202, createServiceRestRequest) + execution.setVariable("sentSyncResponse", true) + + } catch (Exception ex) { + String msg = "Exceptuion in sendSyncResponse:" + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.trace("Exit sendSyncResopnse") + } + + + public void sendSyncError (DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + msoLogger.trace("Start sendSyncError") + + try { + String errorMessage = "" + if (execution.getVariable("WorkflowException") instanceof WorkflowException) { + WorkflowException wfe = execution.getVariable("WorkflowException") + errorMessage = wfe.getErrorMessage() + } else { + errorMessage = "Sending Sync Error." + } + + String buildworkflowException = + """<aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1"> + <aetgt:ErrorMessage>${MsoUtils.xmlEscape(errorMessage)}</aetgt:ErrorMessage> + <aetgt:ErrorCode>7000</aetgt:ErrorCode> + </aetgt:WorkflowException>""" + + msoLogger.debug(buildworkflowException) + sendWorkflowResponse(execution, 500, buildworkflowException) + + } catch (Exception ex) { + msoLogger.debug(" Sending Sync Error Activity Failed. " + "\n" + ex.getMessage()) + } + + } + + // ******************************* + // + // ******************************* + public void prepareDecomposeService(DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + msoLogger.trace("Inside prepareDecomposeService of CreateGenericALaCarteServiceInstance ") + try { + String siRequest = execution.getVariable("bpmnRequest") + String serviceModelInfo = jsonUtil.getJsonValue(siRequest, "requestDetails.modelInfo") + execution.setVariable("serviceModelInfo", serviceModelInfo) + } catch (Exception ex) { + // try error in method block + String exceptionMessage = "Bpmn error encountered in CreateGenericALaCarteServiceInstance flow. Unexpected Error from method prepareDecomposeService() - " + ex.getMessage() + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + } + msoLogger.trace("Completed prepareDecomposeService of CreateGenericALaCarteServiceInstance") + } + + + // ******************************* + // + // ******************************* + public void prepareCreateServiceInstance(DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + + try { + msoLogger.trace("Inside prepareCreateServiceInstance of CreateGenericALaCarteServiceInstance") + + /* + * Extracting User Parameters from incoming Request and converting into a Map + */ + def jsonSlurper = new JsonSlurper() + def jsonOutput = new JsonOutput() + def siRequest = execution.getVariable("bpmnRequest") + Map reqMap = jsonSlurper.parseText(siRequest) + //InputParams + def userParams = reqMap.requestDetails?.requestParameters?.userParams + Map<String, String> inputMap = [:] + if (userParams != null) { + userParams.each { + userParam -> inputMap.put(userParam.name, userParam.value) + } + } + + msoLogger.debug("User Input Parameters map: " + userParams.toString()) + execution.setVariable("serviceInputParams", inputMap) + + ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition") + + String serviceInstanceId = execution.getVariable("serviceInstanceId") + serviceDecomposition.getServiceInstance().setInstanceId(serviceInstanceId) + + String serviceInstanceName = jsonUtil.getJsonValue(siRequest, "requestDetails.requestInfo.instanceName") + serviceDecomposition.getServiceInstance().setInstanceName(serviceInstanceName) + execution.setVariable("serviceInstanceName", serviceInstanceName) + execution.setVariable("serviceDecomposition", serviceDecomposition) + execution.setVariable("serviceDecompositionString", serviceDecomposition.toJsonString()) + msoLogger.debug("serviceDecomposition.serviceInstanceName: " + serviceDecomposition.getServiceInstance().getInstanceName()) + + msoLogger.trace("Completed prepareCreateServiceInstance of CreateGenericALaCarteServiceInstance ***** ") + } catch (Exception ex) { + // try error in method block + String exceptionMessage = "Bpmn error encountered in CreateGenericALaCarteServiceInstance flow. Unexpected Error from method prepareCreateServiceInstance() - " + ex.getMessage() + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + } + } + + + public void prepareCompletionRequest (DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + msoLogger.trace("prepareCompletion *** ") + + try { + String requestId = execution.getVariable("msoRequestId") + String serviceInstanceId = execution.getVariable("serviceInstanceId") + String source = execution.getVariable("source") + + String msoCompletionRequest = + """<aetgt:MsoCompletionRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:ns="http://org.onap/so/request/types/v1"> + <request-info xmlns="http://org.onap/so/infra/vnf-request/v1"> + <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> + <action>CREATE</action> + <source>${MsoUtils.xmlEscape(source)}</source> + </request-info> + <status-message>Service Instance was created successfully.</status-message> + <serviceInstanceId>${MsoUtils.xmlEscape(serviceInstanceId)}</serviceInstanceId> + <mso-bpel-name>CreateGenericALaCarteServiceInstance</mso-bpel-name> + </aetgt:MsoCompletionRequest>""" + + // Format Response + String xmlMsoCompletionRequest = utils.formatXml(msoCompletionRequest) + + execution.setVariable("completionRequest", xmlMsoCompletionRequest) + msoLogger.debug(" Overall SUCCESS Response going to CompleteMsoProcess - " + "\n" + xmlMsoCompletionRequest) + + } catch (Exception ex) { + String msg = " Exception in prepareCompletion:" + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.trace("Exit prepareCompletionRequest") + } + + public void prepareFalloutRequest(DelegateExecution execution){ + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + msoLogger.trace("prepareFalloutRequest") + + try { + WorkflowException wfex = execution.getVariable("WorkflowException") + msoLogger.debug(" Input Workflow Exception: " + wfex.toString()) + String requestId = execution.getVariable("msoRequestId") + String source = execution.getVariable("source") + String requestInfo = + """<request-info xmlns="http://org.onap/so/infra/vnf-request/v1"> + <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> + <action>CREATE</action> + <source>${MsoUtils.xmlEscape(source)}</source> + </request-info>""" + + String falloutRequest = exceptionUtil.processMainflowsBPMNException(execution, requestInfo) + execution.setVariable("falloutRequest", falloutRequest) + } catch (Exception ex) { + msoLogger.debug("Exception prepareFalloutRequest:" + ex.getMessage()) + String errorException = " Bpmn error encountered in CreateGenericALaCarteServiceInstance flow. FalloutHandlerRequest, buildErrorResponse() - " + ex.getMessage() + String requestId = execution.getVariable("msoRequestId") + String falloutRequest = + """<aetgt:FalloutHandlerRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:ns="http://org.onap/so/request/types/v1" + xmlns:wfsch="http://org.onap/so/workflow/schema/v1"> + <request-info xmlns="http://org.onap/so/infra/vnf-request/v1"> + <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> + <action>CREATE</action> + <source>VID</source> + </request-info> + <aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1"> + <aetgt:ErrorMessage>${MsoUtils.xmlEscape(errorException)}</aetgt:ErrorMessage> + <aetgt:ErrorCode>7000</aetgt:ErrorCode> + </aetgt:WorkflowException> + </aetgt:FalloutHandlerRequest>""" + + execution.setVariable("falloutRequest", falloutRequest) + } + msoLogger.trace("Exit prepareFalloutRequest") + } +}
\ No newline at end of file diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateNetworkInstance.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateNetworkInstance.groovy new file mode 100644 index 0000000000..d665de2ba7 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateNetworkInstance.groovy @@ -0,0 +1,455 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts; + +import org.apache.commons.lang3.* +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.onap.so.bpmn.common.scripts.ExceptionUtil +import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.logger.MsoLogger + +import groovy.json.* + +/** + * This groovy class supports the <class>CreateNetworkInstance.bpmn</class> process. + * + */ +public class CreateNetworkInstance extends AbstractServiceTaskProcessor { + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, CreateNetworkInstance.class); + + String Prefix="CRENI_" + ExceptionUtil exceptionUtil = new ExceptionUtil() + JsonUtils jsonUtil = new JsonUtils() + + public InitializeProcessVariables(DelegateExecution execution){ + + execution.setVariable(Prefix + "source", "") + execution.setVariable(Prefix + "Success", false) + + execution.setVariable(Prefix + "CompleteMsoProcessRequest", "") + execution.setVariable(Prefix + "FalloutHandlerRequest", "") + execution.setVariable(Prefix + "isSilentSuccess", false) + + } + + + /** + * This method is executed during the preProcessRequest task of the <class>CreateNetworkInstance.bpmn</class> process. + * @param execution + */ + + // ************************************************** + // Pre or Prepare Request Section + // ************************************************** + /** + * This method is executed during the preProcessRequest task of the <class>CreateNetworkInstance.bpmn</class> process. + * @param execution + */ + public void preProcessRequest (DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + + msoLogger.trace("Start preProcessRequest") + + try { + // initialize flow variables + InitializeProcessVariables(execution) + + String sdncVersion = execution.getVariable("sdncVersion") + if (sdncVersion == null || sdncVersion == '1610') { + // 'a-la-cart' default, sdncVersion = '1610' + execution.setVariable("sdncVersion", "1610") + String bpmnRequest = execution.getVariable("bpmnRequest") + // set 'disableRollback' + if (bpmnRequest != null) { + String disableRollback = jsonUtil.getJsonValue(bpmnRequest, "requestDetails.requestInfo.suppressRollback") + if (disableRollback != null) { + execution.setVariable("disableRollback", disableRollback) + msoLogger.debug("Received 'suppressRollback': " + disableRollback ) + } else { + execution.setVariable("disableRollback", false) + } + msoLogger.debug(" Set 'disableRollback' : " + execution.getVariable("disableRollback") ) + } else { + String dataErrorMessage = " Invalid 'bpmnRequest' request." + msoLogger.debug(dataErrorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + } + + } else { + // 'macro' TEST ONLY, sdncVersion = '1702' + msoLogger.debug(" 'disableRollback' : " + execution.getVariable("disableRollback") ) + } + + // get/set 'msoRequestId' and 'mso-request-id' + String requestId = execution.getVariable("msoRequestId") + if (requestId != null) { + execution.setVariable("mso-request-id", requestId) + } else { + requestId = execution.getVariable("mso-request-id") + } + execution.setVariable(Prefix + "requestId", requestId) + + // get/set 'requestId' + if (execution.getVariable("requestId") == null) { + execution.setVariable("requestId", requestId) + } + + //Place holder for additional code. + + // TODO ??? + // userParams??? 1) pre-loads indicator, 2) 'auto-activation' + // Tag/Value parameters + // + // Map: 'networkInputParams': 'auto-activation'' + // Sample format? + // "requestParameters": { + // "userParams": [ + // { + // "name": "someUserParam1", + // "value": "someValue1" + // } + // ] + // } + // + // String userParams = //use json util to extract "userParams"// + // execution.setVariable("networkInputParams", userParams) + // else: execution.setVariable("networkInputParams", null) + // + + } catch (BpmnError e) { + throw e; + + } catch (Exception ex){ + sendSyncError(execution) + // caught exception + String exceptionMessage = "Exception Encountered in CreateNetworkInstance, PreProcessRequest() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + } + + public void sendSyncResponse (DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + + msoLogger.trace("Start sendSyncResponse") + + try { + String requestId = execution.getVariable("mso-request-id") + + // RESTResponse (for API Handler (APIH) Reply Task) + String createNetworkRestRequest = """{"requestReferences":{"instanceId":"","requestId":"${requestId}"}}""".trim() + + msoLogger.debug(" sendSyncResponse to APIH - " + "\n" + createNetworkRestRequest) + sendWorkflowResponse(execution, 202, createNetworkRestRequest) + + } catch (Exception ex) { + String exceptionMessage = "Bpmn error encountered in CreateNetworkInstance flow. sendSyncResponse() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + } + + } + + + public void getNetworkModelInfo (DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix", Prefix) + + msoLogger.trace("Start getNetworkModelInfo") + + try { + + // For Ala-Carte (sdnc = 1610): + // 1. the Network ModelInfo is expected to be sent + // via requestDetails.modelInfo (modelType = network). + // 2. the Service ModelInfo is expected to be sent but will be IGNORE + // via requestDetails.relatedInstanceList.relatedInstance.modelInfo (modelType = service) + + } catch (Exception ex) { + sendSyncError(execution) + String exceptionMessage = "Bpmn error encountered in CreateNetworkInstance flow. getNetworkModelInfo() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + + public void sendSyncError (DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix", Prefix) + + msoLogger.trace("Start sendSyncError") + + try { + + String requestId = execution.getVariable("mso-request-id") + + // REST Error (for API Handler (APIH) Reply Task) + String syncError = """{"requestReferences":{"instanceId":"","requestId":"${requestId}"}}""".trim() + + sendWorkflowResponse(execution, 500, syncError) + + } catch (Exception ex) { + msoLogger.debug(" Bpmn error encountered in CreateNetworkInstance flow. sendSyncError() - " + ex.getMessage()) + } + + } + + public void prepareDBRequestError (DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + + try { + msoLogger.trace("Start prepareDBRequestError") + + // set DB Header Authorization + setBasicDBAuthHeader(execution, isDebugEnabled) + + String statusMessage = "" + WorkflowException wfe = null + if (execution.getVariable("WorkflowException") instanceof WorkflowException) { + wfe = execution.getVariable("WorkflowException") + statusMessage = wfe.getErrorMessage() + } + + String requestId = execution.getVariable(Prefix + "requestId") + String networkName = execution.getVariable("networkName") !=null ? execution.getVariable("networkName") : "" + String networkId = execution.getVariable("networkId") !=null ? execution.getVariable("networkId") : "" + String dbRequest = + """<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"> + <soapenv:Header/> + <soapenv:Body> + <ns:updateInfraRequest xmlns:ns="http://org.onap.so/requestsdb"> + <requestId>${MsoUtils.xmlEscape(requestId)}</requestId> + <lastModifiedBy>BPMN</lastModifiedBy> + <statusMessage>${MsoUtils.xmlEscape(statusMessage)}</statusMessage> + <responseBody></responseBody> + <requestStatus>FAILED</requestStatus> + <vnfOutputs><network-id>${MsoUtils.xmlEscape(networkId)}</network-id><network-name>${MsoUtils.xmlEscape(networkName)}</network-names></vnfOutputs> + </ns:updateInfraRequest> + </soapenv:Body> + </soapenv:Envelope>""" + + execution.setVariable(Prefix + "createDBRequest", dbRequest) + msoLogger.debug(" DB Adapter Request - " + "\n" + dbRequest) + msoLogger.debug(dbRequest) + + } catch (Exception ex) { + String exceptionMessage = " Bpmn error encountered in CreateNetworkInstance flow. prepareDBRequestError() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + public void prepareCompletion (DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + + msoLogger.trace("Start prepareCompletion") + + try { + + String requestId = execution.getVariable("mso-request-id") + String source = execution.getVariable(Prefix + "source") + + String msoCompletionRequest = + """<aetgt:MsoCompletionRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:ns="http://org.onap/so/request/types/v1"> + <request-info xmlns="http://org.onap/so/infra/vnf-request/v1"> + <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> + <action>CREATE</action> + <source>VID</source> + </request-info> + <aetgt:status-message>Network has been created successfully.</aetgt:status-message> + <aetgt:mso-bpel-name>BPMN Network action: CREATE</aetgt:mso-bpel-name> + </aetgt:MsoCompletionRequest>""" + + // Format Response + String xmlMsoCompletionRequest = utils.formatXml(msoCompletionRequest) + + // normal path + execution.setVariable(Prefix + "Success", true) + execution.setVariable(Prefix + "CompleteMsoProcessRequest", xmlMsoCompletionRequest) + msoLogger.debug(" Overall SUCCESS Response going to CompleteMsoProcess - " + "\n" + xmlMsoCompletionRequest) + + } catch (Exception ex) { + String exceptionMessage = " Bpmn error encountered in CreateNetworkInstance flow. prepareCompletion() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + + + } + + + + + // ************************************************** + // Post or Validate Response Section + // ************************************************** + + public void postProcessResponse (DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix", Prefix) + + msoLogger.trace("Start postProcessResponse") + + try { + + if (execution.getVariable("CMSO_ResponseCode") == "200") { + execution.setVariable(Prefix + "Success", true) + msoLogger.trace("CreateNetworkInstance Success ****") + // Place holder for additional code. + + } else { + execution.setVariable(Prefix + "Success", false) + msoLogger.trace("CreateNetworkInstance Failed in CompletionMsoProces flow!. ****") + + } + + + } catch (Exception ex) { + String exceptionMessage = " Bpmn error encountered in CreateNetworkInstance flow. postProcessResponse() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + + // ******************************* + // Build Error Section + // ******************************* + + public void processRollbackData (DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix", Prefix) + + msoLogger.trace("Start processRollbackData") + + try { + //execution.getVariable("orchestrationStatus") + //execution.getVariable("networkId") + //execution.getVariable("networkName") + //networkOutputParams + //rollbackData + //rolledBack + + } catch (Exception ex) { + msoLogger.debug(" Bpmn error encountered in CreateNetworkInstance flow. callDBCatalog() - " + ex.getMessage()) + } + + } + + // Prepare for FalloutHandler + public void buildErrorResponse (DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix", Prefix) + + msoLogger.debug("DB updateInfraRequest ResponseCode: " + execution.getVariable(Prefix + "dbReturnCode")) + msoLogger.debug("DB updateInfraRequest Response: " + execution.getVariable(Prefix + "createDBResponse")) + + msoLogger.trace("Prepare for FalloutHandler. FAILURE - prepare request for sub-process FalloutHandler.") + + String falloutHandlerRequest = "" + String requestId = execution.getVariable("mso-request-id") + + try { + + WorkflowException wfe = execution.getVariable("WorkflowException") + String errorCode = String.valueOf(wfe.getErrorCode()) + String errorMessage = wfe.getErrorMessage() + falloutHandlerRequest = + """<aetgt:FalloutHandlerRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:ns="http://org.onap/so/request/types/v1" + xmlns:wfsch="http://org.onap/so/workflow/schema/v1"> + <request-info xmlns="http://org.onap/so/infra/vnf-request/v1"> + <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> + <action>CREATE</action> + <source>VID</source> + </request-info> + <aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1"> + <aetgt:ErrorMessage>${MsoUtils.xmlEscape(errorMessage)}</aetgt:ErrorMessage> + <aetgt:ErrorCode>${MsoUtils.xmlEscape(errorCode)}</aetgt:ErrorCode> + </aetgt:WorkflowException> + </aetgt:FalloutHandlerRequest>""" + + msoLogger.debug(falloutHandlerRequest) + execution.setVariable(Prefix + "FalloutHandlerRequest", falloutHandlerRequest) + msoLogger.debug(" Overall Error Response going to FalloutHandler: " + "\n" + falloutHandlerRequest) + + } catch (Exception ex) { + String errorException = " Bpmn error encountered in CreateNetworkInstance flow. FalloutHandlerRequest, buildErrorResponse()" + msoLogger.debug("Exception error in CreateNetworkInstance flow, buildErrorResponse(): " + ex.getMessage()) + falloutHandlerRequest = + """<aetgt:FalloutHandlerRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:ns="http://org.onap/so/request/types/v1" + xmlns:wfsch="http://org.onap/so/workflow/schema/v1"> + <request-info xmlns="http://org.onap/so/infra/vnf-request/v1"> + <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> + <action>CREATE</action> + <source>VID</source> + </request-info> + <aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1"> + <aetgt:ErrorMessage>${MsoUtils.xmlEscape(errorException)}</aetgt:ErrorMessage> + <aetgt:ErrorCode>7000</aetgt:ErrorCode> + </aetgt:WorkflowException> + </aetgt:FalloutHandlerRequest>""" + + execution.setVariable(Prefix + "FalloutHandlerRequest", falloutHandlerRequest) + msoLogger.debug(" Overall Error Response going to FalloutHandler: " + "\n" + falloutHandlerRequest) + + } + + } + + public void processJavaException(DelegateExecution execution){ + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + try{ + msoLogger.debug("Caught a Java Exception in " + Prefix) + msoLogger.debug("Started processJavaException Method") + msoLogger.debug("Variables List: " + execution.getVariables()) + execution.setVariable("UnexpectedError", "Caught a Java Lang Exception - " + Prefix) // Adding this line temporarily until this flows error handling gets updated + exceptionUtil.buildWorkflowException(execution, 500, "Caught a Java Lang Exception") + + }catch(Exception e){ + msoLogger.debug("Caught Exception during processJavaException Method: " + e) + execution.setVariable("UnexpectedError", "Exception in processJavaException method - " + Prefix) // Adding this line temporarily until this flows error handling gets updated + exceptionUtil.buildWorkflowException(execution, 500, "Exception in processJavaException method" + Prefix) + } + msoLogger.debug("Completed processJavaException Method in " + Prefix) + } + +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateSDNCNetworkResource.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateSDNCNetworkResource.groovy new file mode 100644 index 0000000000..c819da4be4 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateSDNCNetworkResource.groovy @@ -0,0 +1,450 @@ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - SO + * ================================================================================ + * Copyright (C) 2018 Huawei Technologies Co., Ltd. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts + +import static org.apache.commons.lang3.StringUtils.*; + +import org.apache.commons.lang3.* +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.json.JSONObject +import org.json.XML; +import org.onap.so.bpmn.common.recipe.ResourceInput; +import org.onap.so.bpmn.common.resource.ResourceRequestBuilder +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.onap.so.bpmn.common.scripts.ExceptionUtil +import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.logger.MsoLogger + +import groovy.json.* + +/** + * This groovy class supports the <class>CreateSDNCCNetworkResource.bpmn</class> process. + * flow for SDNC Network Resource Create + */ +public class CreateSDNCNetworkResource extends AbstractServiceTaskProcessor { + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, CreateSDNCNetworkResource.class); + + String Prefix="CRESDNCRES_" + + ExceptionUtil exceptionUtil = new ExceptionUtil() + + JsonUtils jsonUtil = new JsonUtils() + + public void preProcessRequest(DelegateExecution execution){ + msoLogger.trace("Started preProcessRequest ") + try { + + //get bpmn inputs from resource request. + String requestId = execution.getVariable("mso-request-id") + String requestAction = execution.getVariable("requestAction") + msoLogger.info("The requestAction is: " + requestAction) + String recipeParamsFromRequest = execution.getVariable("recipeParams") + msoLogger.info("The recipeParams is: " + recipeParamsFromRequest) + String resourceInput = execution.getVariable("resourceInput") + msoLogger.info("The resourceInput is: " + resourceInput) + //Get ResourceInput Object + ResourceInput resourceInputObj = ResourceRequestBuilder.getJsonObject(resourceInput, ResourceInput.class) + execution.setVariable(Prefix + "resourceInput", resourceInputObj) + + //Deal with recipeParams + String recipeParamsFromWf = execution.getVariable("recipeParamXsd") + String resourceName = resourceInputObj.getResourceInstanceName() + //For sdnc requestAction default is "createNetworkInstance" + String operationType = "Network" + if(!StringUtils.isBlank(recipeParamsFromRequest)){ + //the operationType from worflow(first node) is second priority. + operationType = jsonUtil.getJsonValue(recipeParamsFromRequest, "operationType") + } + if(!StringUtils.isBlank(recipeParamsFromWf)){ + //the operationType from worflow(first node) is highest priority. + operationType = jsonUtil.getJsonValue(recipeParamsFromWf, "operationType") + } + + + //For sdnc, generate svc_action and request_action + String sdnc_svcAction = "create" + if(StringUtils.containsIgnoreCase(resourceInputObj.getResourceInstanceName(), "overlay")){ + //This will be resolved in R3. + sdnc_svcAction ="activate" + operationType = "NCINetwork" + } + if(StringUtils.containsIgnoreCase(resourceInputObj.getResourceInstanceName(), "underlay")){ + //This will be resolved in R3. + operationType ="Network" + } + String sdnc_requestAction = StringUtils.capitalize(sdnc_svcAction) + operationType +"Instance" + execution.setVariable(Prefix + "svcAction", sdnc_svcAction) + execution.setVariable(Prefix + "requestAction", sdnc_requestAction) + execution.setVariable(Prefix + "serviceInstanceId", resourceInputObj.getServiceInstanceId()) + execution.setVariable("mso-request-id", requestId) + execution.setVariable("mso-service-instance-id", resourceInputObj.getServiceInstanceId()) + //TODO Here build networkrequest + + } catch (BpmnError e) { + throw e; + } catch (Exception ex){ + msg = "Exception in preProcessRequest " + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + } + + String customizeResourceParam(String networkInputParametersJson) { + List<Map<String, Object>> paramList = new ArrayList(); + JSONObject jsonObject = new JSONObject(networkInputParametersJson); + Iterator iterator = jsonObject.keys(); + while (iterator.hasNext()) { + String key = iterator.next(); + HashMap<String, String> hashMap = new HashMap(); + hashMap.put("name", key); + hashMap.put("value", jsonObject.get(key)) + paramList.add(hashMap) + } + Map<String, List<Map<String, Object>>> paramMap = new HashMap(); + paramMap.put("param", paramList); + + return new JSONObject(paramMap).toString(); + } + + /** + * Pre Process the BPMN Flow Request + * Inclouds: + * generate the nsOperationKey + * generate the nsParameters + */ + public void prepareSDNCRequest (DelegateExecution execution) { + msoLogger.trace("Started prepareSDNCRequest ") + + try { + // get variables + String sdnc_svcAction = execution.getVariable(Prefix + "svcAction") + String sdnc_requestAction = execution.getVariable(Prefix + "requestAction") + String sdncCallback = execution.getVariable("URN_mso_workflow_sdncadapter_callback") + String createNetworkInput = execution.getVariable(Prefix + "networkRequest") + + String hdrRequestId = execution.getVariable("mso-request-id") + String serviceInstanceId = execution.getVariable(Prefix + "serviceInstanceId") + String source = execution.getVariable("source") + String sdnc_service_id = execution.getVariable(Prefix + "sdncServiceId") + ResourceInput resourceInputObj = execution.getVariable(Prefix + "resourceInput") + String serviceType = resourceInputObj.getServiceType() + String serviceModelInvariantUuid = resourceInputObj.getServiceModelInfo().getModelInvariantUuid() + String serviceModelUuid = resourceInputObj.getServiceModelInfo().getModelUuid() + String serviceModelVersion = resourceInputObj.getServiceModelInfo().getModelVersion() + String serviceModelName = resourceInputObj.getServiceModelInfo().getModelName() + String globalCustomerId = resourceInputObj.getGlobalSubscriberId() + String modelInvariantUuid = resourceInputObj.getResourceModelInfo().getModelInvariantUuid(); + String modelCustomizationUuid = resourceInputObj.getResourceModelInfo().getModelCustomizationUuid() + String modelUuid = resourceInputObj.getResourceModelInfo().getModelUuid() + String modelName = resourceInputObj.getResourceModelInfo().getModelName() + String modelVersion = resourceInputObj.getResourceModelInfo().getModelVersion() + String resourceInputPrameters = resourceInputObj.getResourceParameters() + String networkInputParametersJson = jsonUtil.getJsonValue(resourceInputPrameters, "requestInputs") + //here convert json string to xml string + String netowrkInputParameters = XML.toString(new JSONObject(customizeResourceParam(networkInputParametersJson))) + // 1. prepare assign topology via SDNC Adapter SUBFLOW call + String sdncTopologyCreateRequest = "" + + switch (modelName) { + case ~/^Site$/: + sdncTopologyCreateRequest = """<aetgt:SDNCAdapterWorkflowRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:sdncadapter="http://org.onap.so/workflow/sdnc/adapter/schema/v1" + xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1"> + <sdncadapter:RequestHeader> + <sdncadapter:RequestId>${MsoUtils.xmlEscape(hdrRequestId)}</sdncadapter:RequestId> + <sdncadapter:SvcInstanceId>${MsoUtils.xmlEscape(serviceInstanceId)}</sdncadapter:SvcInstanceId> + <sdncadapter:SvcAction>${MsoUtils.xmlEscape(sdnc_svcAction)}</sdncadapter:SvcAction> + <sdncadapter:SvcOperation>network-topology-operation</sdncadapter:SvcOperation> + <sdncadapter:CallbackUrl>sdncCallback</sdncadapter:CallbackUrl> + <sdncadapter:MsoAction>generic-resource</sdncadapter:MsoAction> + </sdncadapter:RequestHeader> + <sdncadapterworkflow:SDNCRequestData> + <request-information> + <request-id>${MsoUtils.xmlEscape(hdrRequestId)}</request-id> + <request-action>${MsoUtils.xmlEscape(sdnc_requestAction)}</request-action> + <source>${MsoUtils.xmlEscape(source)}</source> + <notification-url></notification-url> + <order-number></order-number> + <order-version></order-version> + </request-information> + <service-information> + <service-id>${MsoUtils.xmlEscape(serviceInstanceId)}</service-id> + <subscription-service-type>${MsoUtils.xmlEscape(serviceType)}</subscription-service-type> + <onap-model-information> + <model-invariant-uuid>${MsoUtils.xmlEscape(serviceModelInvariantUuid)}</model-invariant-uuid> + <model-uuid>${MsoUtils.xmlEscape(serviceModelUuid)}</model-uuid> + <model-version>${MsoUtils.xmlEscape(serviceModelVersion)}</model-version> + <model-name>${MsoUtils.xmlEscape(serviceModelName)}</model-name> + </onap-model-information> + <service-instance-id>${MsoUtils.xmlEscape(serviceInstanceId)}</service-instance-id> + <global-customer-id>${MsoUtils.xmlEscape(globalCustomerId)}</global-customer-id> + </service-information> + <subscriber-name>${MsoUtils.xmlEscape(globalCustomerId)}</subscriber-name> + <vnf-information> + <!-- TODO: to be filled as per the request input --> + <vnf-id></vnf-id> + <vnf-type></vnf-type> + <onap-model-information> + <model-invariant-uuid>${MsoUtils.xmlEscape(modelInvariantUuid)}</model-invariant-uuid> + <model-customization-uuid>${MsoUtils.xmlEscape(modelCustomizationUuid)}</model-customization-uuid> + <model-uuid>${MsoUtils.xmlEscape(modelUuid)}</model-uuid> + <model-version>${MsoUtils.xmlEscape(modelVersion)}</model-version> + <model-name>${MsoUtils.xmlEscape(modelName)}</model-name> + </onap-model-information> + </network-information> + <vnf-input-parameters> + <network-input-parameters>${MsoUtils.xmlEscape(netowrkInputParameters)}</network-input-parameters> + </vnf-input-parameters> + <vnf-request-input> + <request-version></request-version> + <vnf-name></vnf-name> + <neutron-id></neutron-id> + <contrail-network-fqdn></contrail-network-fqdn> + <subnets-data> + <subnet-data> + <element> + <ip-version></ip-version> + <subnet-id></subnet-id> + </subnet-data> + </subnets-data> + </vnf-request-input> + </sdncadapterworkflow:SDNCRequestData> + </aetgt:SDNCAdapterWorkflowRequest>""".trim() + break + + case ~/^SOTNAttachment$/: + sdncTopologyCreateRequest = """<aetgt:SDNCAdapterWorkflowRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:sdncadapter="http://org.onap.so/workflow/sdnc/adapter/schema/v1" + xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1"> + <sdncadapter:RequestHeader> + <sdncadapter:RequestId>${MsoUtils.xmlEscape(hdrRequestId)}</sdncadapter:RequestId> + <sdncadapter:SvcInstanceId>${MsoUtils.xmlEscape(serviceInstanceId)}</sdncadapter:SvcInstanceId> + <sdncadapter:SvcAction>${MsoUtils.xmlEscape(sdnc_svcAction)}</sdncadapter:SvcAction> + <sdncadapter:SvcOperation>network-topology-operation</sdncadapter:SvcOperation> + <sdncadapter:CallbackUrl>sdncCallback</sdncadapter:CallbackUrl> + <sdncadapter:MsoAction>generic-resource</sdncadapter:MsoAction> + </sdncadapter:RequestHeader> + <sdncadapterworkflow:SDNCRequestData> + <request-information> + <request-id>${MsoUtils.xmlEscape(hdrRequestId)}</request-id> + <request-action>${MsoUtils.xmlEscape(sdnc_requestAction)}</request-action> + <source>${MsoUtils.xmlEscape(source)}</source> + <notification-url></notification-url> + <order-number></order-number> + <order-version></order-version> + </request-information> + <service-information> + <service-id>${MsoUtils.xmlEscape(serviceInstanceId)}</service-id> + <subscription-service-type>${MsoUtils.xmlEscape(serviceType)}</subscription-service-type> + <onap-model-information> + <model-invariant-uuid>${MsoUtils.xmlEscape(serviceModelInvariantUuid)}</model-invariant-uuid> + <model-uuid>${MsoUtils.xmlEscape(serviceModelUuid)}</model-uuid> + <model-version>${MsoUtils.xmlEscape(serviceModelVersion)}</model-version> + <model-name>${MsoUtils.xmlEscape(serviceModelName)}</model-name> + </onap-model-information> + <service-instance-id>${MsoUtils.xmlEscape(serviceInstanceId)}</service-instance-id> + <global-customer-id>${MsoUtils.xmlEscape(globalCustomerId)}</global-customer-id> + </service-information> + <subscriber-name>${MsoUtils.xmlEscape(globalCustomerId)}</subscriber-name> + <allotted-resource-information> + <!-- TODO: to be filled as per the request input --> + <allotted-resource-type></allotted-resource-type> + <parent-service-instance-id><parent-service-instance-id> + <onap-model-information> + <model-invariant-uuid>${MsoUtils.xmlEscape(modelInvariantUuid)}</model-invariant-uuid> + <model-customization-uuid>${MsoUtils.xmlEscape(modelCustomizationUuid)}</model-customization-uuid> + <model-uuid>${MsoUtils.xmlEscape(modelUuid)}</model-uuid> + <model-version>${MsoUtils.xmlEscape(modelVersion)}</model-version> + <model-name>${MsoUtils.xmlEscape(modelName)}</model-name> + </onap-model-information> + </allotted-resource-information> + <connection-attachment-request-input> + <param>${MsoUtils.xmlEscape(netowrkInputParameters)}</param> + </connection-attachment-request-input> + </sdncadapterworkflow:SDNCRequestData> + </aetgt:SDNCAdapterWorkflowRequest>""".trim() + break + + default: + sdncTopologyCreateRequest = """<aetgt:SDNCAdapterWorkflowRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:sdncadapter="http://org.onap.so/workflow/sdnc/adapter/schema/v1" + xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1"> + <sdncadapter:RequestHeader> + <sdncadapter:RequestId>${MsoUtils.xmlEscape(hdrRequestId)}</sdncadapter:RequestId> + <sdncadapter:SvcInstanceId>${MsoUtils.xmlEscape(serviceInstanceId)}</sdncadapter:SvcInstanceId> + <sdncadapter:SvcAction>${MsoUtils.xmlEscape(sdnc_svcAction)}</sdncadapter:SvcAction> + <sdncadapter:SvcOperation>network-topology-operation</sdncadapter:SvcOperation> + <sdncadapter:CallbackUrl>sdncCallback</sdncadapter:CallbackUrl> + <sdncadapter:MsoAction>generic-resource</sdncadapter:MsoAction> + </sdncadapter:RequestHeader> + <sdncadapterworkflow:SDNCRequestData> + <request-information> + <request-id>${MsoUtils.xmlEscape(hdrRequestId)}</request-id> + <request-action>${MsoUtils.xmlEscape(sdnc_requestAction)}</request-action> + <source>${MsoUtils.xmlEscape(source)}</source> + <notification-url></notification-url> + <order-number></order-number> + <order-version></order-version> + </request-information> + <service-information> + <service-id>${MsoUtils.xmlEscape(serviceInstanceId)}</service-id> + <subscription-service-type>${MsoUtils.xmlEscape(serviceType)}</subscription-service-type> + <onap-model-information> + <model-invariant-uuid>${MsoUtils.xmlEscape(serviceModelInvariantUuid)}</model-invariant-uuid> + <model-uuid>${MsoUtils.xmlEscape(serviceModelUuid)}</model-uuid> + <model-version>${MsoUtils.xmlEscape(serviceModelVersion)}</model-version> + <model-name>${MsoUtils.xmlEscape(serviceModelName)}</model-name> + </onap-model-information> + <service-instance-id>${MsoUtils.xmlEscape(serviceInstanceId)}</service-instance-id> + <global-customer-id>${MsoUtils.xmlEscape(globalCustomerId)}</global-customer-id> + </service-information> + <network-information> + <onap-model-information> + <model-invariant-uuid>${MsoUtils.xmlEscape(modelInvariantUuid)}</model-invariant-uuid> + <model-customization-uuid>${MsoUtils.xmlEscape(modelCustomizationUuid)}</model-customization-uuid> + <model-uuid>${MsoUtils.xmlEscape(modelUuid)}</model-uuid> + <model-version>${MsoUtils.xmlEscape(modelVersion)}</model-version> + <model-name>${MsoUtils.xmlEscape(modelName)}</model-name> + </onap-model-information> + </network-information> + <network-request-input> + <network-input-parameters>${MsoUtils.xmlEscape(netowrkInputParameters)}</network-input-parameters> + </network-request-input> + </sdncadapterworkflow:SDNCRequestData> + </aetgt:SDNCAdapterWorkflowRequest>""".trim() + } + + String sndcTopologyCreateRequesAsString = utils.formatXml(sdncTopologyCreateRequest) + msoLogger.debug(sndcTopologyCreateRequesAsString) + execution.setVariable("sdncAdapterWorkflowRequest", sndcTopologyCreateRequesAsString) + msoLogger.debug("sdncAdapterWorkflowRequest - " + "\n" + sndcTopologyCreateRequesAsString) + + } catch (Exception ex) { + String exceptionMessage = " Bpmn error encountered in CreateSDNCCNetworkResource flow. prepareSDNCRequest() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + msoLogger.trace("Exit prepareSDNCRequest ") + } + + private void setProgressUpdateVariables(DelegateExecution execution, String body) { + def dbAdapterEndpoint = execution.getVariable("URN_mso_adapters_openecomp_db_endpoint") + execution.setVariable("CVFMI_dbAdapterEndpoint", dbAdapterEndpoint) + execution.setVariable("CVFMI_updateResOperStatusRequest", body) + } + + public void prepareUpdateBeforeCreateSDNCResource(DelegateExecution execution) { + ResourceInput resourceInputObj = execution.getVariable(Prefix + "resourceInput") + String operType = resourceInputObj.getOperationType() + String resourceCustomizationUuid = resourceInputObj.getResourceModelInfo().getModelCustomizationUuid() + String ServiceInstanceId = resourceInputObj.getServiceInstanceId() + String operationId = resourceInputObj.getOperationId() + String progress = "20" + String status = "processing" + String statusDescription = "SDCN resource creation invoked" + + execution.getVariable("operationId") + + String body = """ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" + xmlns:ns="http://org.onap.so/requestsdb"> + <soapenv:Header/> + <soapenv:Body> + <ns:updateResourceOperationStatus> + <operType>${MsoUtils.xmlEscape(operType)}</operType> + <operationId>${MsoUtils.xmlEscape(operationId)}</operationId> + <progress>${MsoUtils.xmlEscape(progress)}</progress> + <resourceTemplateUUID>${MsoUtils.xmlEscape(resourceCustomizationUuid)}</resourceTemplateUUID> + <serviceId>${MsoUtils.xmlEscape(ServiceInstanceId)}</serviceId> + <status>${MsoUtils.xmlEscape(status)}</status> + <statusDescription>${MsoUtils.xmlEscape(statusDescription)}</statusDescription> + </ns:updateResourceOperationStatus> + </soapenv:Body> + </soapenv:Envelope>"""; + + setProgressUpdateVariables(execution, body) + + } + + public void prepareUpdateAfterCreateSDNCResource(execution) { + ResourceInput resourceInputObj = execution.getVariable(Prefix + "resourceInput") + String operType = resourceInputObj.getOperationType() + String resourceCustomizationUuid = resourceInputObj.getResourceModelInfo().getModelCustomizationUuid() + String ServiceInstanceId = resourceInputObj.getServiceInstanceId() + String operationId = resourceInputObj.getOperationId() + String progress = "100" + String status = "finished" + String statusDescription = "SDCN resource creation completed" + + execution.getVariable("operationId") + + String body = """ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" + xmlns:ns="http://org.onap.so/requestsdb"> + <soapenv:Header/> + <soapenv:Body> + <ns:updateResourceOperationStatus> + <operType>${MsoUtils.xmlEscape(operType)}</operType> + <operationId>${MsoUtils.xmlEscape(operationId)}</operationId> + <progress>${MsoUtils.xmlEscape(progress)}</progress> + <resourceTemplateUUID>${MsoUtils.xmlEscape(resourceCustomizationUuid)}</resourceTemplateUUID> + <serviceId>${MsoUtils.xmlEscape(ServiceInstanceId)}</serviceId> + <status>${MsoUtils.xmlEscape(status)}</status> + <statusDescription>${MsoUtils.xmlEscape(statusDescription)}</statusDescription> + </ns:updateResourceOperationStatus> + </soapenv:Body> + </soapenv:Envelope>"""; + + setProgressUpdateVariables(execution, body) + } + + public void postCreateSDNCCall(DelegateExecution execution){ + msoLogger.trace("Started prepareSDNCRequest ") + String responseCode = execution.getVariable(Prefix + "sdncCreateReturnCode") + String responseObj = execution.getVariable(Prefix + "SuccessIndicator") + + msoLogger.info("response from sdnc, response code :" + responseCode + " response object :" + responseObj) + msoLogger.trace("Exit prepareSDNCRequest ") + } + + public void sendSyncResponse (DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + utils.log("DEBUG", " *** sendSyncResponse *** ", isDebugEnabled) + + try { + String operationStatus = "finished" + // RESTResponse for main flow + String resourceOperationResp = """{"operationStatus":"${operationStatus}"}""".trim() + utils.log("DEBUG", " sendSyncResponse to APIH:" + "\n" + resourceOperationResp, isDebugEnabled) + sendWorkflowResponse(execution, 202, resourceOperationResp) + execution.setVariable("sentSyncResponse", true) + + } catch (Exception ex) { + String msg = "Exceptuion in sendSyncResponse:" + ex.getMessage() + utils.log("DEBUG", msg, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + utils.log("DEBUG"," ***** Exit sendSyncResopnse *****", isDebugEnabled) + } +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateVFCNSResource.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateVFCNSResource.groovy new file mode 100644 index 0000000000..26f12831bd --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateVFCNSResource.groovy @@ -0,0 +1,326 @@ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - SO + * ================================================================================ + * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts; + +import static org.apache.commons.lang3.StringUtils.*; + +import org.apache.commons.lang3.* +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.onap.so.bpmn.common.scripts.ExceptionUtil +import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.logger.MessageEnum +import org.onap.so.logger.MsoLogger +import org.onap.so.rest.APIResponse +import org.onap.so.rest.RESTClient +import org.onap.so.rest.RESTConfig + +import groovy.json.* + +/** + * This groovy class supports the <class>DoCreateVFCNetworkServiceInstance.bpmn</class> process. + * flow for VFC Network Service Create + */ +public class CreateVFCNSResource extends AbstractServiceTaskProcessor { + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, CreateVFCNSResource.class); + + + String vfcUrl = "/vfc/rest/v1/vfcadapter" + + String host = "http://mso.mso.testlab.openecomp.org:8080" + + ExceptionUtil exceptionUtil = new ExceptionUtil() + + JsonUtils jsonUtil = new JsonUtils() + + /** + * CreateVFCNSResource + * Pre Process the BPMN Flow Request + * Inclouds: + * generate the nsOperationKey + * generate the nsParameters + */ + public void preProcessRequest (DelegateExecution execution) { + JsonUtils jsonUtil = new JsonUtils() + + String msg = "" + msoLogger.trace("preProcessRequest() ") + try { + //deal with nsName and Description + String resourceInput = execution.getVariable("resourceInput") + + String resourceParameters = jsonUtil.getJsonValue(resourceInput, "resourceParameters") + // get service name + String resourceName = jsonUtil.getJsonValue(resourceInput, "resourceInstanceName") + execution.setVariable("nsServiceName", resourceName) + + String nsServiceDescription = execution.getVariable("nsServiceDescription") + msoLogger.info("nsServiceName:" + resourceName + " nsServiceDescription:" + nsServiceDescription) + //deal with operation key + String globalSubscriberId = jsonUtil.getJsonValue(resourceInput, "globalSubscriberId") + msoLogger.info("globalSubscriberId:" + globalSubscriberId) + //set local globalSubscriberId variable + execution.setVariable("globalSubscriberId", globalSubscriberId); + String serviceType = execution.getVariable("serviceType") + msoLogger.info("serviceType:" + serviceType) + + String serviceId = execution.getVariable("serviceInstanceId") + msoLogger.info("serviceId:" + serviceId) + + String operationId = jsonUtil.getJsonValue(resourceInput, "operationId") + msoLogger.info("serviceType:" + serviceType) + + String nodeTemplateUUID = jsonUtil.getJsonValue(resourceInput, "resourceModelInfo.modelCustomizationUuid") + String nsServiceModelUUID = jsonUtil.getJsonValue(resourceParameters, "requestInputs.nsd0_providing_service_uuid") + msoLogger.info("nodeTemplateUUID:" + nodeTemplateUUID) + /* + * segmentInformation needed as a object of segment + * { + * "domain":"", + * "nodeTemplateName":"", + * "nodeType":"", + * "nsParameters":{ + * //this is the nsParameters sent to VF-C + * } + * } + */ + String nsParameters = jsonUtil.getJsonValue(resourceInput, "resourceParameters") + msoLogger.info("nsParameters:" + nsParameters) + String nsOperationKey = """{ + "globalSubscriberId":"${globalSubscriberId}", + "serviceType":"${serviceType}", + "serviceId":"${serviceId}", + "operationId":"${operationId}", + "nodeTemplateUUID":"${nodeTemplateUUID}" + }""" + execution.setVariable("nsOperationKey", nsOperationKey); + execution.setVariable("nsParameters", nsParameters) + execution.setVariable("nsServiceModelUUID", nsServiceModelUUID); + + + } catch (BpmnError e) { + throw e; + } catch (Exception ex){ + msg = "Exception in preProcessRequest " + ex.getMessage() + msoLogger.info(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.trace("Exit preProcessRequest ") + } + + /** + * create NS task + */ + public void createNetworkService(DelegateExecution execution) { + msoLogger.trace("createNetworkService ") + String nsOperationKey = execution.getVariable("nsOperationKey"); + String nsServiceModelUUID = execution.getVariable("nsServiceModelUUID"); + String nsParameters = execution.getVariable("nsParameters"); + String nsServiceName = execution.getVariable("nsServiceName") + String nsServiceDescription = execution.getVariable("nsServiceDescription") + String locationConstraints = jsonUtil.getJsonValue(nsParameters, "locationConstraints") + String requestInputs = jsonUtil.getJsonValue(nsParameters, "requestInputs") + String reqBody ="""{ + "nsServiceName":"${nsServiceName}", + "nsServiceDescription":"${nsServiceDescription}", + "nsServiceModelUUID":"${nsServiceModelUUID}", + "nsOperationKey":${nsOperationKey}, + "nsParameters":{ + "locationConstraints":${locationConstraints}, + "additionalParamForNs":${requestInputs} + } + }""" + APIResponse apiResponse = postRequest(execution, host + vfcUrl + "/ns", reqBody) + String returnCode = apiResponse.getStatusCode() + String aaiResponseAsString = apiResponse.getResponseBodyAsString() + String nsInstanceId = ""; + if(returnCode== "200" || returnCode == "201"){ + nsInstanceId = jsonUtil.getJsonValue(aaiResponseAsString, "nsInstanceId") + } + execution.setVariable("nsInstanceId", nsInstanceId) + msoLogger.info(" *****Exit createNetworkService *****") + } + + /** + * instantiate NS task + */ + public void instantiateNetworkService(DelegateExecution execution) { + msoLogger.trace("instantiateNetworkService ") + String nsOperationKey = execution.getVariable("nsOperationKey"); + String nsParameters = execution.getVariable("nsParameters"); + String nsServiceName = execution.getVariable("nsServiceName") + String nsServiceDescription = execution.getVariable("nsServiceDescription") + String reqBody ="""{ + "nsServiceName":"${nsServiceName}", + "nsServiceDescription":"${nsServiceDescription}", + "nsOperationKey":${nsOperationKey}, + "nsParameters":${nsParameters} + }""" + String nsInstanceId = execution.getVariable("nsInstanceId") + String url = host + vfcUrl + "/ns/" +nsInstanceId + "/instantiate" + APIResponse apiResponse = postRequest(execution, url, reqBody) + String returnCode = apiResponse.getStatusCode() + String aaiResponseAsString = apiResponse.getResponseBodyAsString() + String jobId = ""; + if(returnCode== "200"|| returnCode == "201"){ + jobId = jsonUtil.getJsonValue(aaiResponseAsString, "jobId") + } + execution.setVariable("jobId", jobId) + msoLogger.info(" *****Exit instantiateNetworkService *****") + } + + /** + * query NS task + */ + public void queryNSProgress(DelegateExecution execution) { + msoLogger.trace("queryNSProgress ") + String jobId = execution.getVariable("jobId") + String nsOperationKey = execution.getVariable("nsOperationKey"); + String url = host + vfcUrl + "/jobs/" + jobId + APIResponse apiResponse = postRequest(execution, url, nsOperationKey) + String returnCode = apiResponse.getStatusCode() + String aaiResponseAsString = apiResponse.getResponseBodyAsString() + String operationStatus = "error" + if(returnCode== "200"|| returnCode == "201"){ + operationStatus = jsonUtil.getJsonValue(aaiResponseAsString, "responseDescriptor.status") + } + execution.setVariable("operationStatus", operationStatus) + msoLogger.info(" *****Exit queryNSProgress *****") + } + + /** + * delay 5 sec + */ + public void timeDelay(DelegateExecution execution) { + try { + Thread.sleep(5000); + } catch(InterruptedException e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Time Delay exception" + e , "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, ""); + } + } + + /** + * finish NS task + */ + public void addNSRelationship(DelegateExecution execution) { + msoLogger.trace("addNSRelationship ") + String nsInstanceId = execution.getVariable("nsInstanceId") + if(nsInstanceId == null || nsInstanceId == ""){ + msoLogger.info(" create NS failed, so do not need to add relationship") + return + } + String globalSubscriberId = execution.getVariable("globalSubscriberId") + String serviceType = execution.getVariable("serviceType") + String serviceId = execution.getVariable("serviceInstanceId") + String addRelationPayload = """<relationship xmlns="http://org.openecomp.aai.inventory/v11"> + <related-to>service-instance</related-to> + <related-link>/aai/v11/business/customers/customer/${globalSubscriberId}/service-subscriptions/service-subscription/${serviceType}/service-instances/service-instance/${nsInstanceId}</related-link> + <relationship-data> + <relationship-key>customer.global-customer-id</relationship-key> + <relationship-value>${MsoUtils.xmlEscape(globalSubscriberId)}</relationship-value> + </relationship-data> + <relationship-data> + <relationship-key>service-subscription.service-type</relationship-key> + <relationship-value>${MsoUtils.xmlEscape(serviceType)}</relationship-value> + </relationship-data> + <relationship-data> + <relationship-key>service-instance.service-instance-id</relationship-key> + <relationship-value>${MsoUtils.xmlEscape(nsInstanceId)}</relationship-value> + </relationship-data> + </relationship>""" + String endpoint = execution.getVariable("URN_aai_endpoint") + msoLogger.info("Add Relationship req:\n" + addRelationPayload) + String url = endpoint + "/aai/v11/business/customers/customer/" + globalSubscriberId + "/service-subscriptions/service-subscription/" + serviceType + "/service-instances/service-instance/" + serviceId + "/relationship-list/relationship" + APIResponse aaiRsp = executeAAIPutCall(execution, url, addRelationPayload) + msoLogger.info("aai response status code:" + aaiRsp.getStatusCode()) + msoLogger.info("aai response content:" + aaiRsp.getResponseBodyAsString()) + msoLogger.info(" *****Exit addNSRelationship *****") + } + + public APIResponse executeAAIPutCall(DelegateExecution execution, String url, String payload){ + msoLogger.trace("Started Execute AAI Put Process ") + APIResponse apiResponse = null + try{ + String uuid = utils.getRequestID() + msoLogger.info("Generated uuid is: " + uuid) + msoLogger.info("URL to be used is: " + url) + String userName = execution.getVariable("URN_aai_auth") + String password = execution.getVariable("URN_mso_msoKey") + String basicAuthCred = utils.getBasicAuth(userName,password) + RESTConfig config = new RESTConfig(url); + RESTClient client = new RESTClient(config).addHeader("X-FromAppId", "MSO").addHeader("X-TransactionId", uuid).addHeader("Content-Type", "application/xml").addHeader("Accept","application/xml"); + if (basicAuthCred != null && !"".equals(basicAuthCred)) { + client.addAuthorizationHeader(basicAuthCred) + } + apiResponse = client.httpPut(payload) + msoLogger.trace("Completed Execute AAI Put Process ") + }catch(Exception e){ + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception occured while executing AAI Put Call.", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e); + throw new BpmnError("MSOWorkflowException") + } + return apiResponse + } + + /** + * post request + * url: the url of the request + * requestBody: the body of the request + */ + private APIResponse postRequest(DelegateExecution execution, String url, String requestBody){ + msoLogger.trace("Started Execute VFC adapter Post Process ") + msoLogger.info("url:"+url +"\nrequestBody:"+ requestBody) + APIResponse apiResponse = null + try{ + RESTConfig config = new RESTConfig(url); + RESTClient client = new RESTClient(config).addHeader("Content-Type", "application/json").addHeader("Accept","application/json").addHeader("Authorization","Basic QlBFTENsaWVudDpwYXNzd29yZDEk"); + apiResponse = client.httpPost(requestBody) + msoLogger.info("response code:"+ apiResponse.getStatusCode() +"\nresponse body:"+ apiResponse.getResponseBodyAsString()) + msoLogger.trace("Completed Execute VF-C adapter Post Process ") + }catch(Exception e){ + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception occured while executing AAI Post Call.", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e); + throw new BpmnError("MSOWorkflowException") + } + return apiResponse + } + + public void sendSyncResponse (DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + utils.log("DEBUG", " *** sendSyncResponse *** ", isDebugEnabled) + + try { + String operationStatus = execution.getVariable("operationStatus") + // RESTResponse for main flow + String resourceOperationResp = """{"operationStatus":"${operationStatus}"}""".trim() + utils.log("DEBUG", " sendSyncResponse to APIH:" + "\n" + resourceOperationResp, isDebugEnabled) + sendWorkflowResponse(execution, 202, resourceOperationResp) + execution.setVariable("sentSyncResponse", true) + + } catch (Exception ex) { + String msg = "Exceptuion in sendSyncResponse:" + ex.getMessage() + utils.log("DEBUG", msg, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + utils.log("DEBUG"," ***** Exit sendSyncResopnse *****", isDebugEnabled) + } + +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateVfModuleInfra.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateVfModuleInfra.groovy new file mode 100644 index 0000000000..6acabe14a0 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateVfModuleInfra.groovy @@ -0,0 +1,622 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts; + +import org.apache.commons.lang3.* +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.onap.aai.domain.yang.v12.GenericVnf; +import org.onap.appc.client.lcm.model.Action +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor; +import org.onap.so.bpmn.common.scripts.ExceptionUtil; +import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.so.bpmn.common.scripts.SDNCAdapterUtils; +import org.onap.so.bpmn.core.RollbackData +import org.onap.so.bpmn.core.UrnPropertiesReader +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.bpmn.infrastructure.aai.AAICreateResources; +import org.onap.so.logger.MessageEnum +import org.onap.so.logger.MsoLogger +import org.w3c.dom.* +import javax.xml.parsers.* +import org.xml.sax.InputSource +import groovy.json.JsonOutput +import groovy.json.JsonSlurper + +public class CreateVfModuleInfra extends AbstractServiceTaskProcessor { + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, CreateVfModuleInfra.class); + + ExceptionUtil exceptionUtil = new ExceptionUtil() + JsonUtils jsonUtil = new JsonUtils() + + private AbstractServiceTaskProcessor taskProcessor + + public SDNCAdapterUtils(AbstractServiceTaskProcessor taskProcessor) { + this.taskProcessor = taskProcessor + } + + /** + * Validates the request message and sets up the workflow. + * @param execution the execution + */ + public void preProcessRequest(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.preProcessRequest(' + + 'execution=' + execution.getId() + + ')' + + msoLogger.debug('Started ' + method) + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + + execution.setVariable("CVFMI_sentSyncResponse", false) + + def prefix = 'CVFMI_' + execution.setVariable('prefix', prefix) + execution.setVariable("isVidRequest", "false") + + def rollbackData = execution.getVariable("RollbackData") + if (rollbackData == null) { + rollbackData = new RollbackData() + } + execution.setVariable("RollbackData", rollbackData) + + def incomingRequest = execution.getVariable('bpmnRequest') + msoLogger.debug("Incoming Infra Request: " + incomingRequest) + msoLogger.debug("CreateVfModule Infra incoming Request: " + incomingRequest) + + setBasicDBAuthHeader(execution, isDebugLogEnabled) + + // check if request is xml or json + try { + def jsonSlurper = new JsonSlurper() + def jsonOutput = new JsonOutput() + Map reqMap = jsonSlurper.parseText(incomingRequest) + msoLogger.debug(" Request is in JSON format.") + + def serviceInstanceId = execution.getVariable('serviceInstanceId') + def vnfId = execution.getVariable('vnfId') + + execution.setVariable(prefix + 'serviceInstanceId', serviceInstanceId) + execution.setVariable(prefix+'vnfId', vnfId) + execution.setVariable("isVidRequest", "true") + + def vnfName = '' + def asdcServiceModelVersion = '' + def serviceModelInfo = null + def vnfModelInfo = null + + def relatedInstanceList = reqMap.requestDetails?.relatedInstanceList + + if (relatedInstanceList != null) { + relatedInstanceList.each { + if (it.relatedInstance.modelInfo?.modelType == 'service') { + asdcServiceModelVersion = it.relatedInstance.modelInfo?.modelVersion + serviceModelInfo = jsonOutput.toJson(it.relatedInstance.modelInfo) + + } + if (it.relatedInstance.modelInfo.modelType == 'vnf') { + vnfName = it.relatedInstance.instanceName ?: '' + vnfModelInfo = jsonOutput.toJson(it.relatedInstance.modelInfo) + } + } + } + + execution.setVariable(prefix + 'vnfName', vnfName) + execution.setVariable(prefix + 'asdcServiceModelVersion', asdcServiceModelVersion) + execution.setVariable(prefix + 'serviceModelInfo', serviceModelInfo) + execution.setVariable(prefix + 'vnfModelInfo', vnfModelInfo) + + + def vnfType = execution.getVariable('vnfType') + execution.setVariable(prefix + 'vnfType', vnfType) + def vfModuleId = execution.getVariable('vfModuleId') + execution.setVariable(prefix + 'vfModuleId', vfModuleId) + def volumeGroupId = execution.getVariable('volumeGroupId') + execution.setVariable(prefix + 'volumeGroupId', volumeGroupId) + def userParams = reqMap.requestDetails?.requestParameters?.userParams + + Map<String, String> userParamsMap = [:] + if (userParams != null) { + userParams.each { userParam -> + userParamsMap.put(userParam.name, userParam.value.toString()) + } + } + + msoLogger.debug('Processed user params: ' + userParamsMap) + + execution.setVariable(prefix + 'vfModuleInputParams', userParamsMap) + + def isBaseVfModule = "false" + if (execution.getVariable('isBaseVfModule') == true) { + isBaseVfModule = "true" + } + + execution.setVariable(prefix + 'isBaseVfModule', isBaseVfModule) + + def requestId = execution.getVariable("mso-request-id") + execution.setVariable(prefix + 'requestId', requestId) + + def vfModuleModelInfo = jsonOutput.toJson(reqMap.requestDetails?.modelInfo) + execution.setVariable(prefix + 'vfModuleModelInfo', vfModuleModelInfo) + + def suppressRollback = reqMap.requestDetails?.requestInfo?.suppressRollback + + + def backoutOnFailure = "" + if(suppressRollback != null){ + if ( suppressRollback == true) { + backoutOnFailure = "false" + } else if ( suppressRollback == false) { + backoutOnFailure = "true" + } + } + + execution.setVariable('disableRollback', suppressRollback) + + def vfModuleName = reqMap.requestDetails?.requestInfo?.instanceName ?: null + execution.setVariable(prefix + 'vfModuleName', vfModuleName) + + def serviceId = reqMap.requestDetails?.requestParameters?.serviceId ?: '' + execution.setVariable(prefix + 'serviceId', serviceId) + + def usePreload = reqMap.requestDetails?.requestParameters?.usePreload + execution.setVariable(prefix + 'usePreload', usePreload) + + // This is aLaCarte flow, so aLaCarte flag is always on + execution.setVariable(prefix + 'aLaCarte', true) + + def cloudConfiguration = reqMap.requestDetails?.cloudConfiguration + def lcpCloudRegionId = cloudConfiguration.lcpCloudRegionId + execution.setVariable(prefix + 'lcpCloudRegionId', lcpCloudRegionId) + def tenantId = cloudConfiguration.tenantId + execution.setVariable(prefix + 'tenantId', tenantId) + + def globalSubscriberId = reqMap.requestDetails?.subscriberInfo?.globalSubscriberId ?: '' + execution.setVariable(prefix + 'globalSubscriberId', globalSubscriberId) + + execution.setVariable(prefix + 'sdncVersion', '1702') + + execution.setVariable("CreateVfModuleInfraSuccessIndicator", false) + execution.setVariable("RollbackCompleted", false) + + execution.setVariable("isDebugLogEnabled", isDebugLogEnabled) + + + def source = reqMap.requestDetails?.requestInfo?.source + execution.setVariable("CVFMI_source", source) + + //For Completion Handler & Fallout Handler + String requestInfo = + """<request-info xmlns="http://org.onap/so/infra/vnf-request/v1"> + <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> + <action>CREATE</action> + <source>${MsoUtils.xmlEscape(source)}</source> + </request-info>""" + + execution.setVariable("CVFMI_requestInfo", requestInfo) + + //backoutOnFailure + + execution.setVariable("CVFMI_originalWorkflowException", null) + + + def newVfModuleId = UUID.randomUUID().toString() + execution.setVariable("newVfModuleId", newVfModuleId) + execution.setVariable(prefix + 'vfModuleId', newVfModuleId) + execution.setVariable('actionHealthCheck', Action.HealthCheck) + execution.setVariable('actionConfigScaleOut', Action.ConfigScaleOut) + execution.setVariable('controllerType', "APPC") + def controllerType = execution.getVariable('controllerType') + execution.setVariable(prefix + 'controllerType', controllerType) + execution.setVariable('healthCheckIndex0', 0) + + msoLogger.debug('RequestInfo: ' + execution.getVariable("CVFMI_requestInfo")) + + msoLogger.debug('rollbackEnabled: ' + execution.getVariable("CVFMI_rollbackEnabled")) + + msoLogger.trace('Finished ' + method) + } catch (BpmnError bpmnError) { + throw bpmnError + } + catch(groovy.json.JsonException je) { + msoLogger.debug("Request is not in JSON format.") + exceptionUtil.buildAndThrowWorkflowException(execution, 400, "Internal Error - During PreProcessRequest") + } + catch(Exception e) { + String restFaultMessage = e.getMessage() + //execution.setVariable("CVFMODVOL2_RESTFault", restFaultMessage) + //execution.setVariable("CVFMODVOL2_isDataOk", false) + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, " Exception Encountered - " + "\n" + restFaultMessage, "BPMN", MsoLogger.getServiceName(), + MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 400, "Internal Error - During PreProcessRequest") + } + + } + + /** + * Validates a workflow response. + * @param execution the execution + * @param responseVar the execution variable in which the response is stored + * @param responseCodeVar the execution variable in which the response code is stored + * @param errorResponseVar the execution variable in which the error response is stored + */ + public void validateWorkflowResponse(DelegateExecution execution, String responseVar, + String responseCodeVar, String errorResponseVar) { + SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this) + sdncAdapterUtils.validateSDNCResponse(execution, responseVar, responseCodeVar, errorResponseVar) + } + + + /** + * Sends the empty, synchronous response back to the API Handler. + * @param execution the execution + */ + public void sendResponse(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.sendResponse(' + + 'execution=' + execution.getId() + + ')' + + msoLogger.trace('Started ' + method) + + try { + def requestInfo = execution.getVariable('CVFMI_requestInfo') + def requestId = execution.getVariable('CVFMI_requestId') + def source = execution.getVariable('CVFMI_source') + + // RESTResponse (for API Handler (APIH) Reply Task) + def newVfModuleId = execution.getVariable("newVfModuleId") + String synchResponse = """{"requestReferences":{"instanceId":"${newVfModuleId}","requestId":"${requestId}"}}""".trim() + + sendWorkflowResponse(execution, 200, synchResponse) + + execution.setVariable("CVFMI_sentSyncResponse", true) + msoLogger.debug("CreateVfModule Infra Response: " + synchResponse) + msoLogger.trace('Finished ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, " Exception Encountered ", "BPMN", MsoLogger.getServiceName(), + MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in sendResponse(): ' + e.getMessage()) + } + } + + /** + * Query AAI for vnf orchestration status to determine if health check and config scaling should be run + */ + public void queryAAIForVnfOrchestrationStatus(DelegateExecution execution) { + def isDebugEnabled = execution.getVariable("isDebugLogEnabled") + def vnfId = execution.getVariable("CVFMI_vnfId") + execution.setVariable("runHealthCheck", false); + execution.setVariable("runConfigScaleOut", false); + AAICreateResources aaiCreateResources = new AAICreateResources(); + Optional<GenericVnf> vnf = aaiCreateResources.getVnfInstance(vnfId); + if(vnf.isPresent()){ + def vnfOrchestrationStatus = vnf.get().getOrchestrationStatus(); + if("active".equalsIgnoreCase(vnfOrchestrationStatus)){ + execution.setVariable("runHealthCheck", false); + execution.setVariable("runConfigScaleOut", true); + } + } + } + + /** + * Retrieve data for ConfigScaleOut from SDNC topology + */ + + public void retreiveConfigScaleOutData(DelegateExecution execution){ + def isDebugEnabled = execution.getVariable("isDebugLogEnabled") + def vfModuleId = execution.getVariable("CVFMI_vfModuleId") + String ipAddress = ""; + String oamIpAddress = ""; + String vnfHostIpAddress = ""; + + String vnfGetSDNC = execution.getVariable("DCVFM_getSDNCAdapterResponse"); + + String data = utils.getNodeXml(vnfGetSDNC, "response-data") + data = data.replaceAll("<", "<") + data = data.replaceAll(">", ">") + + InputSource source = new InputSource(new StringReader(data)); + DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); + docFactory.setNamespaceAware(true) + DocumentBuilder docBuilder = docFactory.newDocumentBuilder() + Document responseXml = docBuilder.parse(source) + + NodeList paramsList = responseXml.getElementsByTagNameNS("*", "vnf-parameters") + for (int z = 0; z < paramsList.getLength(); z++) { + Node node = paramsList.item(z) + Element eElement = (Element) node + String vnfParameterName = utils.getElementText(eElement, "vnf-parameter-name") + String vnfParameterValue = utils.getElementText(eElement, "vnf-parameter-value") + if (vnfParameterName.equals("vlb_private_ip_1")) { + vnfHostIpAddress = vnfParameterValue + } + else if (vnfParameterName.equals("vdns_private_ip_0")) { + ipAddress = vnfParameterValue + } + else if (vnfParameterName.equals("vdns_private_ip_1")) { + oamIpAddress = vnfParameterValue + } + } + + String payload = "{\"request-parameters\":{\"vnf-host-ip-address\":\"" + vnfHostIpAddress + "\",\"vf-module-id\":\"" + vfModuleId + "\"},\"configuration-parameters\":{\"ip-addr\":\"" + ipAddress +"\", \"oam-ip-addr\":\""+ oamIpAddress +"\",\"enabled\":\"true\"}}" + execution.setVariable("payload", payload); + } + + /** + * + * @param execution the execution + */ + public void postProcessResponse(DelegateExecution execution){ + msoLogger.trace("STARTED PostProcessResponse Process") + try{ + def requestInfo = execution.getVariable("CVFMI_requestInfo") + def action = utils.getNodeText(requestInfo, "action") + + msoLogger.debug("requestInfo is: " + requestInfo) + msoLogger.debug("action is: " + action) + + String payload = + """ <aetgt:MsoCompletionRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:ns="http://org.onap/so/request/types/v1" + xmlns:ns8="http://org.onap/so/workflow/schema/v1"> + <request-info xmlns="http://org.onap/so/infra/vnf-request/v1"> + ${requestInfo} + </request-info> + <ns8:status-message>Vf Module has been created successfully.</ns8:status-message> + <ns8:mso-bpel-name>BPMN</ns8:mso-bpel-name> + </aetgt:MsoCompletionRequest>""" + + payload = utils.formatXml(payload) + execution.setVariable("CVFMI_SuccessFlag", true) + execution.setVariable("CVFMI_msoCompletionRequest", payload) + msoLogger.debug("CreateVfModuleInfra completion request: " + payload) + msoLogger.debug("Outgoing MsoCompletionRequest: \n" + payload) + + }catch(Exception e){ + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, " Exception Occured Processing PostProcessResponse - " + "\n", "BPMN", MsoLogger.getServiceName(), + MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + execution.setVariable("CVFMI_ErrorResponse", "Error Occured during PostProcessResponse Method:\n" + e.getMessage()) + } + msoLogger.trace("COMPLETED PostProcessResponse Process") + } + + + + + + /** + * Validates the request, request id and service instance id. If a problem is found, + * a WorkflowException is generated and an MSOWorkflowException event is thrown. This + * method also sets up the log context for the workflow. + * @param execution the execution + * @return the validated request + */ + public String validateInfraRequest(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.validateInfraRequest(' + + 'execution=' + execution.getId() + + ')' + + msoLogger.trace('Started ' + method) + + String processKey = getProcessKey(execution); + def prefix = execution.getVariable("prefix") + + if (prefix == null) { + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, processKey + " prefix is null") + } + + try { + def request = execution.getVariable(prefix + 'Request') + + if (request == null) { + request = execution.getVariable(processKey + 'Request') + + if (request == null) { + request = execution.getVariable('bpmnRequest') + } + + setVariable(execution, processKey + 'Request', null); + setVariable(execution, 'bpmnRequest', null); + setVariable(execution, prefix + 'Request', request); + } + + if (request == null) { + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, processKey + " request is null") + } + + /* + + def requestId = execution.getVariable("mso-request-id") + + if (requestId == null) { + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, processKey + " request has no mso-request-id") + } + + setVariable(execution, prefix + 'requestId', requestId) + + def serviceInstanceId = execution.getVariable("mso-service-instance-id") + + if (serviceInstanceId == null) { + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, processKey + " request message has no mso-service-instance-id") + } + + utils.logContext(requestId, serviceInstanceId) + */ + msoLogger.debug("CreateVfModule incoming request: " + request) + msoLogger.debug('Incoming message: ' + System.lineSeparator() + request) + msoLogger.trace('Finished ' + method) + return request + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Caught exception in " + method , "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Invalid Message") + } + } + + public void prepareUpdateInfraRequest(DelegateExecution execution){ + msoLogger.trace("STARTED prepareUpdateInfraRequest Process") + try{ + + String requestInfo = execution.getVariable("CVFMI_requestInfo") + def aicCloudRegion = execution.getVariable("CVFMI_lcpCloudRegionId") + def tenantId = execution.getVariable("CVFMI_tenantId") + def requestId = utils.getNodeText(requestInfo, "request-id") + def vnfId = execution.getVariable("CVFMI_vnfId") + def vfModuleId = execution.getVariable("CVFMI_vfModuleId") + // vfModuleName may be generated by DoCreateVfModule subprocess if it is not specified on the input + def vfModuleName = execution.getVariable("CVFMI_vfModuleName") + + def dbAdapterEndpoint = UrnPropertiesReader.getVariable("mso.adapters.openecomp.db.endpoint",execution) + execution.setVariable("CVFMI_dbAdapterEndpoint", dbAdapterEndpoint) + msoLogger.debug("DB Adapter Endpoint is: " + dbAdapterEndpoint) + + String payload = + """<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" + xmlns:ns="http://org.onap.so/requestsdb"> + <soapenv:Header/> + <soapenv:Body> + <ns:updateInfraRequest xmlns:ns="http://org.onap.so/requestsdb"> + <requestId>${MsoUtils.xmlEscape(requestId)}</requestId> + <lastModifiedBy>BPMN</lastModifiedBy> + <statusMessage>VF Module successfully created</statusMessage> + <responseBody></responseBody> + <requestStatus>COMPLETE</requestStatus> + <progress>100</progress> + <vnfOutputs><vnf-outputs xmlns="http://org.onap/so/infra/vnf-request/v1" xmlns:aetgt="http://org.onap/so/infra/vnf-request/v1" xmlns:rest="http://schemas.activebpel.org/REST/2007/12/01/aeREST.xsd"><vnf-id>${MsoUtils.xmlEscape(vnfId)}</vnf-id><vf-module-id>${MsoUtils.xmlEscape(vfModuleId)}</vf-module-id></vnf-outputs></vnfOutputs> + <vfModuleId>${MsoUtils.xmlEscape(vfModuleId)}</vfModuleId> + <vfModuleName>${MsoUtils.xmlEscape(vfModuleName)}</vfModuleName> + </ns:updateInfraRequest> + </soapenv:Body> + </soapenv:Envelope>""" + + payload = utils.formatXml(payload) + execution.setVariable("CVFMI_updateInfraRequest", payload) + msoLogger.debug("Outgoing UpdateInfraRequest: \n" + payload) + msoLogger.debug("CreateVfModuleInfra Outgoing UpdateInfra Request: " + payload) + + }catch(Exception e){ + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception Occured Processing prepareUpdateInfraRequest.", "BPMN", MsoLogger.getServiceName(), + MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + execution.setVariable("CVFMI_ErrorResponse", "Error Occurred during prepareUpdateInfraRequest Method:\n" + e.getMessage()) + } + msoLogger.trace("COMPLETED prepareUpdateInfraRequest Process") + } + + /** + * Builds a "FalloutHandler" request and stores it in the specified execution variable. + * + * @param execution the execution + * @param resultVar the execution variable in which the result will be stored + */ + public void falloutHandlerPrep(DelegateExecution execution, String resultVar) { + def method = getClass().getSimpleName() + '.falloutHandlerPrep(' + + 'execution=' + execution.getId() + + ', resultVar=' + resultVar + + ')' + + msoLogger.trace("Started " + method) + + + try { + def WorkflowException workflowException = execution.getVariable("WorkflowException") + def requestInformation = execution.getVariable("CVFMI_requestInfo") + def errorResponseCode = workflowException.getErrorCode() + def errorResponseMsg = workflowException.getErrorMessage() + def encErrorResponseMsg = "" + if (errorResponseMsg != null) { + encErrorResponseMsg = errorResponseMsg + } + + String content = """ + <aetgt:FalloutHandlerRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:reqtype="http://org.onap/so/request/types/v1" + xmlns:msoservtypes="http://org.onap/so/request/types/v1" + xmlns:structuredtypes="http://org.onap/so/structured/types/v1"> + ${requestInformation} + <aetgt:WorkflowException> + <aetgt:ErrorMessage>${MsoUtils.xmlEscape(encErrorResponseMsg)}</aetgt:ErrorMessage> + <aetgt:ErrorCode>${MsoUtils.xmlEscape(errorResponseCode)}</aetgt:ErrorCode> + </aetgt:WorkflowException> + </aetgt:FalloutHandlerRequest> + """ + + msoLogger.debug("CONTENT before translation: " + content) + content = utils.formatXml(content) + msoLogger.debug(resultVar + ' = ' + System.lineSeparator() + content) + msoLogger.debug("CreateVfModuleInfra FallOutHander Request: " + content) + execution.setVariable(resultVar, content) + + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Caught exception in " + method , "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildWorkflowException(execution, 2000, 'Internal Error') + } + } + + public void logAndSaveOriginalException(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.validateRollbackResponse(' + + 'execution=' + execution.getId() + + ')' + msoLogger.trace('Entered ' + method) + + logWorkflowException(execution, 'CreateVfModuleInfra caught an event') + saveWorkflowException(execution, 'CVFMI_originalWorkflowException') + } + + public void validateRollbackResponse(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.validateRollbackResponse(' + + 'execution=' + execution.getId() + + ')' + msoLogger.trace('Entered ' + method) + def originalException = execution.getVariable("CVFMI_originalWorkflowException") + execution.setVariable("WorkflowException", originalException) + + execution.setVariable("RollbackCompleted", true) + + } + + public void sendErrorResponse(DelegateExecution execution){ + msoLogger.trace("STARTED CreateVfModulenfra sendErrorResponse Process") + try { + def sentSyncResponse = execution.getVariable("CVFMI_sentSyncResponse") + if(sentSyncResponse == false){ + WorkflowException wfex = execution.getVariable("WorkflowException") + String response = exceptionUtil.buildErrorResponseXml(wfex) + msoLogger.debug(response) + sendWorkflowResponse(execution, 500, response) + }else{ + msoLogger.debug("Not Sending Error Response. Sync Response Already Sent") + } + + } catch (Exception ex) { + msoLogger.debug("Error Occured in CreateVfModuleInfra sendErrorResponse Process " + ex.getMessage()) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in CreateVfModuleInfra sendErrorResponse Process") + } + msoLogger.trace("COMPLETED CreateVfModuleInfra sendErrorResponse Process") + } + + +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateVfModuleVolumeInfraV1.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateVfModuleVolumeInfraV1.groovy new file mode 100644 index 0000000000..aa569655f4 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateVfModuleVolumeInfraV1.groovy @@ -0,0 +1,356 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts + +import org.apache.commons.lang3.* +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution; +import org.onap.so.bpmn.common.scripts.AaiUtil; +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor; +import org.onap.so.bpmn.common.scripts.ExceptionUtil; +import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.logger.MessageEnum +import org.onap.so.logger.MsoLogger +import org.onap.so.rest.APIResponse + +import groovy.json.JsonOutput +import groovy.json.JsonSlurper + +class CreateVfModuleVolumeInfraV1 extends AbstractServiceTaskProcessor { + + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, CreateVfModuleVolumeInfraV1.class); + public static final String prefix='CVMVINFRAV1_' + + /** + * Perform initial processing, such as request validation, initialization of variables, etc. + * * @param execution + */ + public void preProcessRequest (DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + setBasicDBAuthHeader(execution, isDebugEnabled) + preProcessRequest(execution, isDebugEnabled) + } + + + /** + * Perform initial processing, such as request validation, initialization of variables, etc. + * @param execution + * @param isDebugEnabled + */ + public void preProcessRequest (DelegateExecution execution, isDebugEnabled) { + + execution.setVariable("prefix",prefix) + setSuccessIndicator(execution, false) + execution.setVariable(prefix+'syncResponseSent', false) + + String createVolumeIncoming = validateRequest(execution, 'vnfId') + msoLogger.debug(createVolumeIncoming) + + try { + def jsonSlurper = new JsonSlurper() + Map reqMap = jsonSlurper.parseText(createVolumeIncoming) + setupVariables(execution, reqMap, isDebugEnabled) + msoLogger.debug("XML request:\n" + createVolumeIncoming) + } + catch(groovy.json.JsonException je) { + (new ExceptionUtil()).buildAndThrowWorkflowException(execution, 2500, 'Request is not a valid JSON document') + } + + // For rollback in this flow + setBasicDBAuthHeader(execution, isDebugEnabled) + setRollbackEnabled(execution, isDebugEnabled) + } + + + /** + * Set up variables that will be passed to the BB DoCreatevfModuleVolume flow + * @param execution + * @param requestMap + * @param serviceInstanceId + * @param isDebugLogEnabled + */ + public void setupVariables(DelegateExecution execution, Map requestMap, isDebugLogEnabled) { + + def jsonOutput = new JsonOutput() + + // volumeGroupId - is generated + String volumeGroupId = UUID.randomUUID() + execution.setVariable('volumeGroupId', volumeGroupId) + msoLogger.debug("Generated volumeGroupId: " + volumeGroupId) + + // volumeGroupName + def volGrpName = requestMap.requestDetails.requestInfo?.instanceName ?: '' + execution.setVariable('volumeGroupName', volGrpName) + + // vfModuleModelInfo + def vfModuleModelInfo = jsonOutput.toJson(requestMap.requestDetails?.modelInfo) + execution.setVariable('vfModuleModelInfo', vfModuleModelInfo) + + // lcpCloudRegonId + def lcpCloudRegionId = requestMap.requestDetails.cloudConfiguration.lcpCloudRegionId + execution.setVariable('lcpCloudRegionId', lcpCloudRegionId) + + // tenant + def tenantId = requestMap.requestDetails.cloudConfiguration.tenantId + execution.setVariable('tenantId', tenantId) + + // source + def source = requestMap.requestDetails.requestInfo.source + execution.setVariable(prefix+'source', source) + + // vnfType and asdcServiceModelVersion + + def serviceName = '' + def asdcServiceModelVersion = '' + def modelCustomizationName = '' + + def relatedInstanceList = requestMap.requestDetails.relatedInstanceList + relatedInstanceList.each { + if (it.relatedInstance.modelInfo?.modelType == 'service') { + serviceName = it.relatedInstance.modelInfo?.modelName + asdcServiceModelVersion = it.relatedInstance.modelInfo?.modelVersion + } + if (it.relatedInstance.modelInfo?.modelType == 'vnf') { + modelCustomizationName = it.relatedInstance.modelInfo?.modelCustomizationName + } + } + + def vnfType = serviceName + '/' + modelCustomizationName + execution.setVariable('vnfType', vnfType) + execution.setVariable('asdcServiceModelVersion', asdcServiceModelVersion) + + // vfModuleInputParams + def userParams = requestMap.requestDetails?.requestParameters?.userParams + Map<String, String> vfModuleInputMap = [:] + + userParams.each { userParam -> + vfModuleInputMap.put(userParam.name, userParam.value.toString()) + } + execution.setVariable('vfModuleInputParams', vfModuleInputMap) + + // disableRollback (true or false) + def disableRollback = requestMap.requestDetails.requestInfo.suppressRollback + execution.setVariable('disableRollback', disableRollback) + msoLogger.debug('disableRollback (suppressRollback) from request: ' + disableRollback) + + } + + + + public void sendSyncResponse (DelegateExecution execution, isDebugEnabled) { + def volumeGroupId = execution.getVariable('volumeGroupId') + def requestId = execution.getVariable("mso-request-id") + def serviceInstanceId = execution.getVariable("serviceInstanceId") + + String syncResponse = """{"requestReferences":{"instanceId":"${volumeGroupId}","requestId":"${requestId}"}}""".trim() + + msoLogger.debug("Sync Response: " + "\n" + syncResponse) + sendWorkflowResponse(execution, 200, syncResponse) + + execution.setVariable(prefix+'syncResponseSent', true) + } + + + public void sendSyncError (DelegateExecution execution, isDebugEnabled) { + WorkflowException we = execution.getVariable('WorkflowException') + def errorCode = we?.getErrorCode() + def errorMessage = we?.getErrorMessage() + //default to 400 since only invalid request will trigger this method + sendWorkflowResponse(execution, 400, errorMessage) + } + + + /** + * Create a WorkflowException + * @param execution + * @param isDebugEnabled + */ + public void buildWorkflowException(DelegateExecution execution, int errorCode, errorMessage, isDebugEnabled) { + msoLogger.debug(errorMessage) + (new ExceptionUtil()).buildWorkflowException(execution, 2500, errorMessage) + } + + + /** + * Build Infra DB Request + * @param execution + * @param isDebugEnabled + */ + public void prepareDbInfraSuccessRequest(DelegateExecution execution, isDebugEnabled) { + def dbVnfOutputs = execution.getVariable(prefix+'volumeOutputs') + def requestId = execution.getVariable('mso-request-id') + def statusMessage = "VolumeGroup successfully created." + def requestStatus = "COMPLETED" + def progress = "100" + + /* + from: $gVolumeGroup/aai:volume-group-id/text() + to: vnfreq:volume-outputs/vnfreq:volume-group-id + */ + // for now assume, generated volumeGroupId is accepted + def volumeGroupId = execution.getVariable(prefix+'volumeGroupId') + + String dbRequest = + """<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"> + <soapenv:Header/> + <soapenv:Body> + <ns:updateInfraRequest xmlns:ns="http://org.onap.so/requestsdb"> + <requestId>${MsoUtils.xmlEscape(requestId)}</requestId> + <lastModifiedBy>BPMN</lastModifiedBy> + <statusMessage>${MsoUtils.xmlEscape(statusMessage)}</statusMessage> + <responseBody></responseBody> + <requestStatus>${MsoUtils.xmlEscape(requestStatus)}</requestStatus> + <progress>${MsoUtils.xmlEscape(progress)}</progress> + <vnfOutputs>${MsoUtils.xmlEscape(dbVnfOutputs)}</vnfOutputs> + <volumeGroupId>${MsoUtils.xmlEscape(volumeGroupId)}</volumeGroupId> + </ns:updateInfraRequest> + </soapenv:Body> + </soapenv:Envelope>""" + + String buildDBRequestAsString = utils.formatXml(dbRequest) + execution.setVariable(prefix+"createDBRequest", buildDBRequestAsString) + msoLogger.debug("DB Infra Request: " + buildDBRequestAsString) + } + + + /** + * Build CommpleteMsoProcess request + * @param execution + * @param isDebugEnabled + */ + public void postProcessResponse (DelegateExecution execution, isDebugEnabled) { + + def dbReturnCode = execution.getVariable(prefix+'dbReturnCode') + def createDBResponse = execution.getVariable(prefix+'createDBResponse') + + msoLogger.debug('DB return code: ' + dbReturnCode) + msoLogger.debug('DB response: ' + createDBResponse) + + def requestId = execution.getVariable("mso-request-id") + def source = execution.getVariable(prefix+'source') + + String msoCompletionRequest = + """<aetgt:MsoCompletionRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:ns="http://org.onap/so/request/types/v1"> + <request-info xmlns="http://org.onap/so/infra/vnf-request/v1"> + <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> + <action>CREATE</action> + <source>${MsoUtils.xmlEscape(source)}</source> + </request-info> + <aetgt:status-message>Volume Group has been created successfully.</aetgt:status-message> + <aetgt:mso-bpel-name>BPMN VF Module Volume action: CREATE</aetgt:mso-bpel-name> + </aetgt:MsoCompletionRequest>""" + + String xmlMsoCompletionRequest = utils.formatXml(msoCompletionRequest) + + execution.setVariable(prefix+'Success', true) + execution.setVariable(prefix+'CompleteMsoProcessRequest', xmlMsoCompletionRequest) + msoLogger.debug(" Overall SUCCESS Response going to CompleteMsoProcess - " + "\n" + xmlMsoCompletionRequest) + + } + + public void prepareFalloutHandlerRequest(DelegateExecution execution, isDebugEnabled) { + + WorkflowException we = execution.getVariable('WorkflowException') + def errorCode = we?.getErrorCode() + def errorMessage = we?.getErrorMessage() + + def requestId = execution.getVariable("mso-request-id") + def source = execution.getVariable(prefix+'source') + + String falloutHandlerRequest = + """<aetgt:FalloutHandlerRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:ns="http://org.onap/so/request/types/v1" + xmlns:wfsch="http://org.onap/so/workflow/schema/v1"> + <request-info xmlns="http://org.onap/so/infra/vnf-request/v1"> + <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> + <action>CREATE</action> + <source>${MsoUtils.xmlEscape(source)}</source> + </request-info> + <aetgt:WorkflowException> + <aetgt:ErrorMessage>${MsoUtils.xmlEscape(errorMessage)}</aetgt:ErrorMessage> + <aetgt:ErrorCode>${MsoUtils.xmlEscape(errorCode)}</aetgt:ErrorCode> + </aetgt:WorkflowException> + + </aetgt:FalloutHandlerRequest>""" + + // Format Response + String xmlHandlerRequest = utils.formatXml(falloutHandlerRequest) + + execution.setVariable(prefix+'FalloutHandlerRequest', xmlHandlerRequest) + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Overall Error Response going to FalloutHandler", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "\n" + xmlHandlerRequest); + } + + + /** + * Query AAI service instance + * @param execution + * @param isDebugEnabled + */ + public void callRESTQueryAAIServiceInstance(DelegateExecution execution, isDebugEnabled) { + + def request = execution.getVariable(prefix+"Request") + def serviceInstanceId = utils.getNodeText(request, "service-instance-id") + + AaiUtil aaiUtil = new AaiUtil(this) + String aaiEndpoint = aaiUtil.getSearchNodesQueryEndpoint(execution) + + def String queryAAIRequest = aaiEndpoint + "?search-node-type=service-instance&filter=service-instance-id:EQUALS:" + serviceInstanceId + msoLogger.debug("AAI query service instance request: " + queryAAIRequest) + + APIResponse response = aaiUtil.executeAAIGetCall(execution, queryAAIRequest) + + String returnCode = response.getStatusCode() + String aaiResponseAsString = response.getResponseBodyAsString() + + msoLogger.debug("AAI query service instance return code: " + returnCode) + msoLogger.debug("AAI query service instance response: " + aaiResponseAsString) + + ExceptionUtil exceptionUtil = new ExceptionUtil() + + if (returnCode=='200') { + msoLogger.debug('Service instance ' + serviceInstanceId + ' found in AAI.') + } else { + if (returnCode=='404') { + def message = 'Service instance ' + serviceInstanceId + ' was not found in AAI. Return code: 404.' + msoLogger.debug(message) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, message) + } else { + WorkflowException aWorkflowException = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) + throw new BpmnError("MSOWorkflowException") + } + } + } + + public void logAndSaveOriginalException(DelegateExecution execution, isDebugLogEnabled) { + logWorkflowException(execution, 'CreateVfModuleVolumeInfraV1 caught an event') + saveWorkflowException(execution, 'CVMVINFRAV1_originalWorkflowException') + } + + public void validateRollbackResponse(DelegateExecution execution, isDebugLogEnabled) { + + def originalException = execution.getVariable("CVMVINFRAV1_originalWorkflowException") + execution.setVariable("WorkflowException", originalException) + execution.setVariable("RollbackCompleted", true) + + } +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateVnfInfra.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateVnfInfra.groovy new file mode 100644 index 0000000000..9c25a57adc --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateVnfInfra.groovy @@ -0,0 +1,542 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts + +import static org.apache.commons.lang3.StringUtils.*; + +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution; +import org.json.JSONArray; +import org.json.JSONObject; +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor; +import org.onap.so.bpmn.common.scripts.CatalogDbUtils; +import org.onap.so.bpmn.common.scripts.ExceptionUtil; +import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.so.bpmn.common.scripts.SDNCAdapterUtils; +import org.onap.so.bpmn.common.scripts.VidUtils; +import org.onap.so.bpmn.core.UrnPropertiesReader +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.bpmn.core.domain.VnfResource +import org.onap.so.bpmn.core.json.JsonUtils; +import org.onap.so.bpmn.infrastructure.aai.groovyflows.AAICreateResources; +import org.onap.so.logger.MessageEnum +import org.onap.so.logger.MsoLogger + + +/** + * This class supports the CreateVnfInfra Flow + * with the creation of a generic vnf for + * infrastructure. + */ +class CreateVnfInfra extends AbstractServiceTaskProcessor { + + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, CreateVnfInfra.class); + + + String Prefix="CREVI_" + ExceptionUtil exceptionUtil = new ExceptionUtil() + JsonUtils jsonUtil = new JsonUtils() + VidUtils vidUtils = new VidUtils(this) + CatalogDbUtils cutils = new CatalogDbUtils() + AAICreateResources aaiCR = new AAICreateResources() + + /** + * This method gets and validates the incoming + * request. + * + * @param - execution + * + */ + public void preProcessRequest(DelegateExecution execution) { + def isDebugEnabled = execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + msoLogger.trace("STARTED CreateVnfInfra PreProcessRequest Process") + + setBasicDBAuthHeader(execution, isDebugEnabled) + execution.setVariable("CREVI_sentSyncResponse", false) + + try{ + // Get Variables + String createVnfRequest = execution.getVariable("bpmnRequest") + execution.setVariable("CREVI_createVnfRequest", createVnfRequest) + msoLogger.debug("Incoming CreateVnfInfra Request is: \n" + createVnfRequest) + + if(createVnfRequest != null){ + + String requestId = execution.getVariable("mso-request-id") + execution.setVariable("CREVI_requestId", requestId) + msoLogger.debug("Incoming Request Id is: " + requestId) + + String serviceInstanceId = execution.getVariable("serviceInstanceId") + execution.setVariable("CREVI_serviceInstanceId", serviceInstanceId) + msoLogger.debug("Incoming Service Instance Id is: " + serviceInstanceId) + + String vnfType = execution.getVariable("vnfType") + execution.setVariable("CREVI_vnfType", vnfType) + msoLogger.debug("Incoming Vnf Type is: " + vnfType) + + String vnfName = jsonUtil.getJsonValue(createVnfRequest, "requestDetails.requestInfo.instanceName") + execution.setVariable("CREVI_vnfName", vnfName) + msoLogger.debug("Incoming Vnf Name is: " + vnfName) + + String serviceId = jsonUtil.getJsonValue(createVnfRequest, "requestDetails.requestInfo.productFamilyId") + execution.setVariable("CREVI_serviceId", serviceId) + msoLogger.debug("Incoming Service Id is: " + serviceId) + + String source = jsonUtil.getJsonValue(createVnfRequest, "requestDetails.requestInfo.source") + execution.setVariable("CREVI_source", source) + msoLogger.debug("Incoming Source is: " + source) + + String suppressRollback = jsonUtil.getJsonValue(createVnfRequest, "requestDetails.requestInfo.suppressRollback") + execution.setVariable("CREVI_suppressRollback", suppressRollback) + msoLogger.debug("Incoming Suppress Rollback is: " + suppressRollback) + + def vnfModelInfo = jsonUtil.getJsonValue(createVnfRequest, "requestDetails.modelInfo") + execution.setVariable("CREVI_vnfModelInfo", vnfModelInfo) + + String modelInvariantId = jsonUtil.getJsonValue(createVnfRequest, "requestDetails.modelInfo.modelInvariantUuid") + execution.setVariable("CREVI_modelInvariantId", modelInvariantId) + msoLogger.debug("Incoming Invariant Id is: " + modelInvariantId) + + String modelVersion = jsonUtil.getJsonValue(createVnfRequest, "requestDetails.modelInfo.modelVersion") + execution.setVariable("CREVI_modelVersion", modelVersion) + msoLogger.debug("Incoming Model Version is: " + modelVersion) + + def cloudConfiguration = jsonUtil.getJsonValue(createVnfRequest, "requestDetails.cloudConfiguration") + execution.setVariable("CREVI_cloudConfiguration", cloudConfiguration) + + String cloudSiteId = jsonUtil.getJsonValue(createVnfRequest, "requestDetails.cloudConfiguration.lcpCloudRegionId") + execution.setVariable("CREVI_cloudSiteId", cloudSiteId) + msoLogger.debug("Incoming Cloud Site Id is: " + cloudSiteId) + + String tenantId = jsonUtil.getJsonValue(createVnfRequest, "requestDetails.cloudConfiguration.tenantId") + execution.setVariable("CREVI_tenantId", tenantId) + msoLogger.debug("Incoming Tenant Id is: " + tenantId) + + //For Completion Handler & Fallout Handler + String requestInfo = + """<request-info xmlns="http://org.onap/so/infra/vnf-request/v1"> + <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> + <action>CREATE</action> + <source>${MsoUtils.xmlEscape(source)}</source> + </request-info>""" + + execution.setVariable("CREVI_requestInfo", requestInfo) + + //TODO: Orch Status - TBD, will come from SDN-C Response in 1702 + String orchStatus = "Created" + execution.setVariable("CREVI_orchStatus", orchStatus) + + //TODO: Equipment Role - Should come from SDN-C Response in 1702 + String equipmentRole = " " + execution.setVariable("CREVI_equipmentRole", equipmentRole) + + String vnfId = execution.getVariable("testVnfId") // for junits + if(isBlank(vnfId)){ + vnfId = UUID.randomUUID().toString() + msoLogger.debug("Generated Vnf Id is: " + vnfId) + } + execution.setVariable("CREVI_vnfId", vnfId) + + // Setting for Sub Flow Calls + execution.setVariable("CREVI_type", "generic-vnf") + execution.setVariable("GENGS_type", "service-instance") + + String sdncCallbackUrl = UrnPropertiesReader.getVariable("mso.workflow.sdncadapter.callback",execution) + if (sdncCallbackUrl == null || sdncCallbackUrl.trim().isEmpty()) { + def msg = 'Required variable \'mso.workflow.sdncadapter.callback\' is missing' + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, msg, "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError); + + exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) + } + execution.setVariable("CREVI_sdncCallbackUrl", sdncCallbackUrl) + + def vnfInputParameters = null + try { + vnfInputParameters = jsonUtil.getJsonValue(createVnfRequest, "requestDetails.requestParameters.userParams") + } + catch (Exception e) { + msoLogger.debug("userParams are not present in the request") + } + execution.setVariable("CREVI_vnfInputParameters", vnfInputParameters) + + + msoLogger.debug("SDNC Callback URL: " + sdncCallbackUrl) + }else{ + exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Incoming Bpmn Request is Null.") + } + + }catch(BpmnError b){ + msoLogger.debug("Rethrowing MSOWorkflowException") + throw b + }catch(Exception e){ + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, " Error Occurred in CreateVnfInfra PreProcessRequest method", "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occurred in CreateVnfInfra PreProcessRequest") + + } + msoLogger.trace("COMPLETED CreateVnfInfra PreProcessRequest Process") + } + + public void sendSyncResponse (DelegateExecution execution) { + execution.setVariable("prefix",Prefix) + + msoLogger.trace("STARTED CreateVnfInfra SendSyncResponse Process") + + try { + String requestId = execution.getVariable("CREVI_requestId") + String vnfId = execution.getVariable("CREVI_vnfId") + + String createVnfResponse = """{"requestReferences":{"instanceId":"${vnfId}","requestId":"${requestId}"}}""".trim() + + msoLogger.debug("CreateVnfInfra Sync Response is: \n" + createVnfResponse) + + sendWorkflowResponse(execution, 202, createVnfResponse) + + execution.setVariable("CREVI_sentSyncResponse", true) + + } catch (Exception ex) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, " Error Occurred in CreateVnfInfra SendSyncResponse Process", "BPMN", MsoLogger.getServiceName(), + MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in CreateVnfInfra SendSyncResponse Process") + + } + msoLogger.trace("COMPLETED CreateVnfInfra SendSyncResponse Process") + } + + + public void preProcessSDNCAssignRequest(DelegateExecution execution){ + execution.setVariable("prefix", Prefix) + msoLogger.trace("STARTED preProcessSDNCAssignRequest") + def vnfId = execution.getVariable("CREVI_vnfId") + def serviceInstanceId = execution.getVariable("CREVI_serviceInstanceId") + msoLogger.debug("NEW VNF ID: " + vnfId) + + try{ + //Build SDNC Request + + String assignSDNCRequest = buildSDNCRequest(execution, serviceInstanceId, "assign") + + assignSDNCRequest = utils.formatXml(assignSDNCRequest) + execution.setVariable("CREVI_assignSDNCRequest", assignSDNCRequest) + msoLogger.debug("Outgoing AssignSDNCRequest is: \n" + assignSDNCRequest) + + }catch(Exception e){ + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception Occurred Processing preProcessSDNCAssignRequest", "BPMN", MsoLogger.getServiceName(), + MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e) + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during prepareProvision Method:\n" + e.getMessage()) + } + msoLogger.trace("COMPLETED preProcessSDNCAssignRequest") + } + + public void preProcessSDNCActivateRequest(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.preProcessSDNCActivateRequest(' + + 'execution=' + execution.getId() + + ')' + msoLogger.trace('Entered ' + method) + execution.setVariable("prefix", Prefix) + msoLogger.trace("STARTED preProcessSDNCActivateRequest Process") + try{ + String vnfId = execution.getVariable("CREVI_vnfId") + String serviceInstanceId = execution.getVariable("CREVI_serviceInstanceId") + + String activateSDNCRequest = buildSDNCRequest(execution, serviceInstanceId, "activate") + + execution.setVariable("CREVI_activateSDNCRequest", activateSDNCRequest) + msoLogger.debug("Outgoing CommitSDNCRequest is: \n" + activateSDNCRequest) + + }catch(Exception e){ + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception Occured Processing preProcessSDNCActivateRequest", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e) + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during preProcessSDNCActivateRequest Method:\n" + e.getMessage()) + } + msoLogger.trace("COMPLETED preProcessSDNCActivateRequest Process") + } + + public String buildSDNCRequest(DelegateExecution execution, String svcInstId, String action){ + + String uuid = execution.getVariable('testReqId') // for junits + if(uuid==null){ + uuid = execution.getVariable("mso-request-id") + "-" + System.currentTimeMillis() + } + def callbackURL = execution.getVariable("CREVI_sdncCallbackUrl") + def requestId = execution.getVariable("CREVI_requestId") + def serviceId = execution.getVariable("CREVI_serviceId") + def vnfType = execution.getVariable("CREVI_vnfType") + def vnfName = execution.getVariable("CREVI_vnfName") + def tenantId = execution.getVariable("CREVI_tenantId") + def source = execution.getVariable("CREVI_source") + def vnfId = execution.getVariable("CREVI_vnfId") + def cloudSiteId = execution.getVariable("CREVI_cloudSiteId") + + String sdncVNFParamsXml = "" + + if(execution.getVariable("CREVI_vnfParamsExistFlag") == true){ + sdncVNFParamsXml = buildSDNCParamsXml(execution) + }else{ + sdncVNFParamsXml = "" + } + + String sdncRequest = + """<sdncadapterworkflow:SDNCAdapterWorkflowRequest xmlns:ns5="http://org.onap/so/request/types/v1" + xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1" + xmlns:sdncadapter="http://org.onap/workflow/sdnc/adapter/schema/v1"> + <sdncadapter:RequestHeader> + <sdncadapter:RequestId>${MsoUtils.xmlEscape(requestId)}</sdncadapter:RequestId> + <sdncadapter:SvcInstanceId>${MsoUtils.xmlEscape(svcInstId)}</sdncadapter:SvcInstanceId> + <sdncadapter:SvcAction>${MsoUtils.xmlEscape(action)}</sdncadapter:SvcAction> + <sdncadapter:SvcOperation>vnf-topology-operation</sdncadapter:SvcOperation> + <sdncadapter:CallbackUrl>${MsoUtils.xmlEscape(callbackURL)}</sdncadapter:CallbackUrl> + </sdncadapter:RequestHeader> + <sdncadapterworkflow:SDNCRequestData> + <request-information> + <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> + <request-action>VNFActivateRequest</request-action> + <source>${MsoUtils.xmlEscape(source)}</source> + <notification-url/> + </request-information> + <service-information> + <service-id>${MsoUtils.xmlEscape(serviceId)}</service-id> + <service-type>${MsoUtils.xmlEscape(serviceId)}</service-type> + <service-instance-id>${MsoUtils.xmlEscape(svcInstId)}</service-instance-id> + <subscriber-name>notsurewecare</subscriber-name> + </service-information> + <vnf-request-information> + <vnf-id>${MsoUtils.xmlEscape(vnfId)}</vnf-id> + <vnf-name>${MsoUtils.xmlEscape(vnfName)}</vnf-name> + <vnf-type>${MsoUtils.xmlEscape(vnfType)}</vnf-type> + <aic-cloud-region>${MsoUtils.xmlEscape(cloudSiteId)}</aic-cloud-region> + <tenant>${MsoUtils.xmlEscape(tenantId)}</tenant> + ${sdncVNFParamsXml} + </vnf-request-information> + </sdncadapterworkflow:SDNCRequestData> + </sdncadapterworkflow:SDNCAdapterWorkflowRequest>""" + + msoLogger.debug("sdncRequest: " + sdncRequest) + return sdncRequest + } + + public void validateSDNCResponse(DelegateExecution execution, String response, String method){ + execution.setVariable("prefix",Prefix) + msoLogger.debug("STARTED ValidateSDNCResponse Process") + + WorkflowException workflowException = execution.getVariable("WorkflowException") + boolean successIndicator = execution.getVariable("SDNCA_SuccessIndicator") + + msoLogger.debug("workflowException: " + workflowException) + + SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this) + sdncAdapterUtils.validateSDNCResponse(execution, response, workflowException, successIndicator) + + msoLogger.debug("SDNCResponse: " + response) + + String sdncResponse = response + if(execution.getVariable(Prefix + 'sdncResponseSuccess') == true){ + msoLogger.trace("Received a Good Response from SDNC Adapter for " + method + " SDNC Call. Response is: \n" + sdncResponse) + + }else{ + msoLogger.debug("Received a BAD Response from SDNC Adapter for " + method + " SDNC Call.") + throw new BpmnError("MSOWorkflowException") + } + msoLogger.trace("COMPLETED ValidateSDNCResponse Process") + } + + public void prepareCompletionHandlerRequest(DelegateExecution execution){ + execution.setVariable("prefix",Prefix) + + msoLogger.trace("STARTED CreateVnfInfra PrepareCompletionHandlerRequest Process") + + try { + String requestInfo = execution.getVariable("CREVI_requestInfo") + String vnfId = execution.getVariable("CREVI_vnfId") + requestInfo = utils.removeXmlPreamble(requestInfo) + + String request = + """<aetgt:MsoCompletionRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:ns="http://org.onap/so/request/types/v1"> + ${requestInfo} + <status-message>Vnf has been created successfully.</status-message> + <vnfId>${MsoUtils.xmlEscape(vnfId)}</vnfId> + <mso-bpel-name>CreateVnfInfra</mso-bpel-name> + </aetgt:MsoCompletionRequest>""" + + execution.setVariable("CREVI_completionHandlerRequest", request) + msoLogger.debug("Completion Handler Request is: " + request) + + execution.setVariable("WorkflowResponse", "Success") // for junits + + } catch (Exception ex) { + msoLogger.debug("Error Occured in CreateVnfInfra PrepareCompletionHandlerRequest Process " + ex.getMessage()) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in CreateVnfInfra PrepareCompletionHandlerRequest Process") + + } + msoLogger.trace("COMPLETED CreateVnfInfra PrepareCompletionHandlerRequest Process") + } + + public void sendErrorResponse(DelegateExecution execution){ + execution.setVariable("prefix",Prefix) + + msoLogger.trace("STARTED CreateVnfInfra sendErrorResponse Process") + try { + def sentSyncResponse = execution.getVariable("CREVI_sentSyncResponse") + if(sentSyncResponse == false){ + WorkflowException wfex = execution.getVariable("WorkflowException") + String response = exceptionUtil.buildErrorResponseXml(wfex) + + msoLogger.debug(response) + sendWorkflowResponse(execution, 500, response) + }else{ + msoLogger.debug("Not Sending Error Response. Sync Response Already Sent") + } + + } catch (Exception ex) { + msoLogger.debug("Error Occured in CreateVnfInfra sendErrorResponse Process " + ex.getMessage()) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in CreateVnfInfra sendErrorResponse Process") + + } + msoLogger.trace("COMPLETED CreateVnfInfra sendErrorResponse Process") + } + + public void prepareFalloutRequest(DelegateExecution execution){ + execution.setVariable("prefix",Prefix) + + msoLogger.trace("STARTED CreateVnfInfra prepareFalloutRequest Process") + + try { + WorkflowException wfex = execution.getVariable("WorkflowException") + msoLogger.debug(" Incoming Workflow Exception: " + wfex.toString()) + String requestInfo = execution.getVariable("CREVI_requestInfo") + msoLogger.debug(" Incoming Request Info: " + requestInfo) + + String falloutRequest = exceptionUtil.processMainflowsBPMNException(execution, requestInfo) + + execution.setVariable("CREVI_falloutRequest", falloutRequest) + + + } catch (Exception ex) { + msoLogger.debug("Error Occured in CreateVnfInfra prepareFalloutRequest Process " + ex.getMessage()) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in CreateVnfInfra prepareFalloutRequest Process") + + } + msoLogger.trace("COMPLETED CreateVnfInfra prepareFalloutRequest Process") + } + + + public void queryCatalogDB (DelegateExecution execution) { + execution.setVariable("prefix",Prefix) + + msoLogger.trace("STARTED CreateVnfInfra QueryCatalogDB Process") + try { + //Get Vnf Info + String vnfModelInfo = execution.getVariable("CREVI_vnfModelInfo") + String vnfModelCustomizationUuid = jsonUtil.getJsonValueForKey(vnfModelInfo, "modelCustomizationUuid") + msoLogger.debug("querying Catalog DB by vnfModelCustomizationUuid: " + vnfModelCustomizationUuid) + + JSONArray vnfs = cutils.getAllVnfsByVnfModelCustomizationUuid(execution, + vnfModelCustomizationUuid, "v2") + msoLogger.debug("obtained VNF list: " + vnfs) + + if (vnfs == null) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "No matching VNFs in Catalog DB for vnfModelCustomizationUuid=" + vnfModelCustomizationUuid, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, ""); + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "No matching VNFs in Catalog DB for vnfModelCustomizationUuid=" + vnfModelCustomizationUuid) + } + + // Only one match here + JSONObject vnf = vnfs.get(0) + + if (vnf == null) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "No matching VNF in Catalog DB for vnfModelCustomizationUuid=" + vnfModelCustomizationUuid, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, ""); + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "No matching VNF in Catalog DB for vnfModelCustomizationUuid=" + vnfModelCustomizationUuid) + } + + VnfResource vnfResource = new VnfResource() + String nfType = jsonUtil.getJsonValueForKey(vnf, "nfType") + vnfResource.setNfType(nfType) + String nfRole = jsonUtil.getJsonValueForKey(vnf, "nfRole") + vnfResource.setNfRole(nfRole) + String nfFunction = jsonUtil.getJsonValueForKey(vnf, "nfFunction") + vnfResource.setNfFunction(nfFunction) + String nfNamingCode = jsonUtil.getJsonValueForKey(vnf, "nfNamingCode") + vnfResource.setNfNamingCode(nfNamingCode) + + execution.setVariable("CREVI_vnfResourceDecomposition", vnfResource) + + }catch(BpmnError e) { + throw e; + }catch(Exception ex) { + msoLogger.debug("Error Occurred in CreateVnfInfra QueryCatalogDB Process " + ex.getMessage()) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occurred in CreateVnfInfra QueryCatalogDB Process") + } + + + msoLogger.trace("COMPLETED CreateVnfInfra QueryCatalogDb Process") + } + public void createPlatform (DelegateExecution execution) { + msoLogger.trace("START createPlatform") + + String request = execution.getVariable("bpmnRequest") + String platformName = jsonUtil.getJsonValue(request, "requestDetails.platform.platformName") + String vnfId = execution.getVariable("CREVI_vnfId") + + msoLogger.debug("Platform NAME: " + platformName) + msoLogger.debug("VnfID: " + vnfId) + + if(platformName == null||platformName.equals("")){ + String msg = "Exception in createPlatform. platformName was not found in the request."; + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + }else{ + msoLogger.debug("platformName was found.") + try{ + AAICreateResources aaiCR = new AAICreateResources() + aaiCR.createAAIPlatform(platformName, vnfId) + }catch(Exception ex){ + String msg = "Exception in createPlatform. " + ex.getMessage(); + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + } + msoLogger.trace("Exit createPlatform") + } + public void createLineOfBusiness (DelegateExecution execution) { + msoLogger.trace("START createLineOfBusiness") + + String request = execution.getVariable("bpmnRequest") + String lineOfBusiness = jsonUtil.getJsonValue(request, "requestDetails.lineOfBusiness.lineOfBusinessName") + String vnfId = execution.getVariable("CREVI_vnfId") + + msoLogger.debug("LineOfBusiness NAME: " + lineOfBusiness) + msoLogger.debug("VnfID: " + vnfId) + + if(lineOfBusiness == null || lineOfBusiness.equals("")){ + msoLogger.debug("LineOfBusiness was not found. Continuing on with flow...") + }else{ + msoLogger.debug("LineOfBusiness was found.") + try{ + AAICreateResources aaiCR = new AAICreateResources() + aaiCR.createAAILineOfBusiness(lineOfBusiness, vnfId) + }catch(Exception ex){ + String msg = "Exception in LineOfBusiness. " + ex.getMessage(); + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, msg, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + ex) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + } + msoLogger.trace("Exit createLineOfBusiness") + } +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeActivateSDNCNetworkResource.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeActivateSDNCNetworkResource.groovy new file mode 100644 index 0000000000..a63aad14a2 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeActivateSDNCNetworkResource.groovy @@ -0,0 +1,385 @@ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - SO + * ================================================================================ + * Copyright (C) 2018 Huawei Technologies Co., Ltd. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts + +import org.apache.commons.lang3.StringUtils +import org.camunda.bpm.engine.delegate.BpmnError +import org.json.JSONObject +import org.json.XML +import org.onap.so.logger.MsoLogger +import org.onap.so.bpmn.common.recipe.ResourceInput +import org.onap.so.bpmn.common.resource.ResourceRequestBuilder +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.bpmn.common.scripts.ExceptionUtil +import org.onap.so.bpmn.common.scripts.SDNCAdapterUtils + +/** + * This groovy class supports the <class>ActivateSDNCCNetworkResource.bpmn</class> process. + * flow for SDNC Network Resource Activate + */ +public class DeActivateSDNCNetworkResource extends AbstractServiceTaskProcessor { + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, + CreateSDNCNetworkResource.class); + String Prefix = "DEACTSDNCRES_" + + ExceptionUtil exceptionUtil = new ExceptionUtil() + + JsonUtils jsonUtil = new JsonUtils() + + SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils() + + public void preProcessRequest(DelegateExecution execution) { + msoLogger.info(" ***** started preProcessRequest*****") + + try { + + //get bpmn inputs from resource request. + String requestId = execution.getVariable("mso-request-id") + String requestAction = execution.getVariable("requestAction") + msoLogger.info("The requestAction is: " + requestAction) + String recipeParamsFromRequest = execution.getVariable("recipeParams") + msoLogger.info("The recipeParams is: " + recipeParamsFromRequest) + String resourceInput = execution.getVariable("resourceInput") + msoLogger.info("The resourceInput is: " + resourceInput) + //Get ResourceInput Object + org.onap.so.bpmn.common.recipe.ResourceInput resourceInputObj = org.onap.so.bpmn.common.resource.ResourceRequestBuilder.getJsonObject(resourceInput, org.onap.so.bpmn.common.recipe.ResourceInput.class) + execution.setVariable(Prefix + "resourceInput", resourceInputObj) + + //Deal with recipeParams + String recipeParamsFromWf = execution.getVariable("recipeParamXsd") + String resourceModelName = resourceInputObj.getResourceModelInfo().getModelName() + //For sdnc requestAction default is "NetworkInstance" + String operationType = "Network" + if(!StringUtils.isBlank(recipeParamsFromRequest) && "null" != recipeParamsFromRequest){ + //the operationType from worflow(first node) is second priority. + operationType = jsonUtil.getJsonValue(recipeParamsFromRequest, "operationType") + } + if(!StringUtils.isBlank(recipeParamsFromWf)){ + //the operationType from worflow(first node) is highest priority. + operationType = jsonUtil.getJsonValue(recipeParamsFromWf, "operationType") + } + + + // TODO: based on the resource type decide action and operation type + String sdnc_svcAction = "deactivate" + operationType = "SOTNConnectivity" + + String sdnc_requestAction = StringUtils.capitalize(sdnc_svcAction) + operationType +"Instance" + execution.setVariable(Prefix + "svcAction", sdnc_svcAction) + execution.setVariable(Prefix + "requestAction", sdnc_requestAction) + execution.setVariable(Prefix + "serviceInstanceId", resourceInputObj.getServiceInstanceId()) + execution.setVariable("mso-request-id", requestId) + execution.setVariable("mso-service-instance-id", resourceInputObj.getServiceInstanceId()) + //TODO Here build networkrequest + + } catch (BpmnError e) { + throw e; + } catch (Exception ex){ + msg = "Exception in preProcessRequest " + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + } + + public void prepareSDNCRequest(DelegateExecution execution) { + msoLogger.info(" ***** started prepareSDNCRequest *****") + + try { + // get variables + String sdnc_svcAction = execution.getVariable(Prefix + "svcAction") + String sdnc_requestAction = execution.getVariable(Prefix + "requestAction") + String sdncCallback = execution.getVariable("URN_mso_workflow_sdncadapter_callback") + String deleteNetworkInput = execution.getVariable(Prefix + "networkRequest") + + String hdrRequestId = execution.getVariable("mso-request-id") + String serviceInstanceId = execution.getVariable(Prefix + "serviceInstanceId") + String source = execution.getVariable("source") + String sdnc_service_id = execution.getVariable(Prefix + "sdncServiceId") + org.onap.so.bpmn.common.recipe.ResourceInput resourceInputObj = execution.getVariable(Prefix + "resourceInput") + String serviceType = resourceInputObj.getServiceType() + String serviceModelInvariantUuid = resourceInputObj.getServiceModelInfo().getModelInvariantUuid() + String serviceModelUuid = resourceInputObj.getServiceModelInfo().getModelUuid() + String serviceModelVersion = resourceInputObj.getServiceModelInfo().getModelVersion() + String serviceModelName = resourceInputObj.getServiceModelInfo().getModelName() + String globalCustomerId = resourceInputObj.getGlobalSubscriberId() + String modelInvariantUuid = resourceInputObj.getResourceModelInfo().getModelInvariantUuid(); + String modelCustomizationUuid = resourceInputObj.getResourceModelInfo().getModelCustomizationUuid() + String modelUuid = resourceInputObj.getResourceModelInfo().getModelUuid() + String modelName = resourceInputObj.getResourceModelInfo().getModelName() + String modelVersion = resourceInputObj.getResourceModelInfo().getModelVersion() + // 1. prepare assign topology via SDNC Adapter SUBFLOW call + String sdncTopologyDeleteRequest = "" + + switch (modelName) { + case ~/^Site$/: + sdncTopologyDeleteRequest = """<aetgt:SDNCAdapterWorkflowRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:sdncadapter="http://org.onap.so/workflow/sdnc/adapter/schema/v1" + xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1"> + <sdncadapter:RequestHeader> + <sdncadapter:RequestId>${MsoUtils.xmlEscape(hdrRequestId)}</sdncadapter:RequestId> + <sdncadapter:SvcInstanceId>${MsoUtils.xmlEscape(serviceInstanceId)}</sdncadapter:SvcInstanceId> + <sdncadapter:SvcAction>${MsoUtils.xmlEscape(sdnc_svcAction)}</sdncadapter:SvcAction> + <sdncadapter:SvcOperation>network-topology-operation</sdncadapter:SvcOperation> + <sdncadapter:CallbackUrl>sdncCallback</sdncadapter:CallbackUrl> + <sdncadapter:MsoAction>generic-resource</sdncadapter:MsoAction> + </sdncadapter:RequestHeader> + <sdncadapterworkflow:SDNCRequestData> + <request-information> + <request-id>${MsoUtils.xmlEscape(hdrRequestId)}</request-id> + <request-action>${MsoUtils.xmlEscape(sdnc_requestAction)}</request-action> + <source>${MsoUtils.xmlEscape(source)}</source> + <notification-url></notification-url> + <order-number></order-number> + <order-version></order-version> + </request-information> + <service-information> + <service-id>${MsoUtils.xmlEscape(serviceInstanceId)}</service-id> + <subscription-service-type>${MsoUtils.xmlEscape(serviceType)}</subscription-service-type> + <onap-model-information> + <model-invariant-uuid>${MsoUtils.xmlEscape(serviceModelInvariantUuid)}</model-invariant-uuid> + <model-uuid>${MsoUtils.xmlEscape(serviceModelUuid)}</model-uuid> + <model-version>${MsoUtils.xmlEscape(serviceModelVersion)}</model-version> + <model-name>${MsoUtils.xmlEscape(serviceModelName)}</model-name> + </onap-model-information> + <service-instance-id>${MsoUtils.xmlEscape(serviceInstanceId)}</service-instance-id> + <global-customer-id>${MsoUtils.xmlEscape(globalCustomerId)}</global-customer-id> + <subscriber-name></subscriber-name> + </service-information> + <vnf-information> + <!-- TODO: to be filled as per the request input --> + <vnf-id></vnf-id> + <vnf-type></vnf-type> + <onap-model-information> + <model-invariant-uuid>${MsoUtils.xmlEscape(modelInvariantUuid)}</model-invariant-uuid> + <model-customization-uuid>${MsoUtils.xmlEscape(modelCustomizationUuid)}</model-customization-uuid> + <model-uuid>${MsoUtils.xmlEscape(modelUuid)}</model-uuid> + <model-version>${MsoUtils.xmlEscape(modelVersion)}</model-version> + <model-name>${MsoUtils.xmlEscape(modelName)}</model-name> + </onap-model-information> + </network-information> + <vnf-request-input> + <request-version></request-version> + <vnf-name></vnf-name> + <vnf-networks> + <vnf-network> + <network-role></network-role> + <network-name></network-name> + <neutron-id></neutron-id> + <network-id></network-id> + <contrail-network-fqdn></contrail-network-fqdn> + <subnets-data> + <subnet-data> + <ip-version></ip-version> + <subnet-id></subnet-id> + </subnet-data> + </subnets-data> + </vnf-network> + </vnf-networks> + </vnf-request-input> + <vnf-input-parameters> + <param></param> + </vnf-input-parameters> + </sdncadapterworkflow:SDNCRequestData> + </aetgt:SDNCAdapterWorkflowRequest>""".trim() + break + + case ~/^SOTNAttachment$/: + sdncTopologyDeleteRequest = """<aetgt:SDNCAdapterWorkflowRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:sdncadapter="http://org.onap.so/workflow/sdnc/adapter/schema/v1" + xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1"> + <sdncadapter:RequestHeader> + <sdncadapter:RequestId>${MsoUtils.xmlEscape(hdrRequestId)}</sdncadapter:RequestId> + <sdncadapter:SvcInstanceId>${MsoUtils.xmlEscape(serviceInstanceId)}</sdncadapter:SvcInstanceId> + <sdncadapter:SvcAction>${MsoUtils.xmlEscape(sdnc_svcAction)}</sdncadapter:SvcAction> + <sdncadapter:SvcOperation>network-topology-operation</sdncadapter:SvcOperation> + <sdncadapter:CallbackUrl>sdncCallback</sdncadapter:CallbackUrl> + <sdncadapter:MsoAction>generic-resource</sdncadapter:MsoAction> + </sdncadapter:RequestHeader> + <sdncadapterworkflow:SDNCRequestData> + <request-information> + <request-id>${MsoUtils.xmlEscape(hdrRequestId)}</request-id> + <request-action>${MsoUtils.xmlEscape(sdnc_requestAction)}</request-action> + <source>${MsoUtils.xmlEscape(source)}</source> + <notification-url></notification-url> + <order-number></order-number> + <order-version></order-version> + </request-information> + <service-information> + <service-id>${MsoUtils.xmlEscape(serviceInstanceId)}</service-id> + <subscription-service-type>${MsoUtils.xmlEscape(serviceType)}</subscription-service-type> + <onap-model-information> + <model-invariant-uuid>${MsoUtils.xmlEscape(serviceModelInvariantUuid)}</model-invariant-uuid> + <model-uuid>${MsoUtils.xmlEscape(serviceModelUuid)}</model-uuid> + <model-version>${MsoUtils.xmlEscape(serviceModelVersion)}</model-version> + <model-name>${MsoUtils.xmlEscape(serviceModelName)}</model-name> + </onap-model-information> + <service-instance-id>${MsoUtils.xmlEscape(serviceInstanceId)}</service-instance-id> + <global-customer-id>${MsoUtils.xmlEscape(globalCustomerId)}</global-customer-id> + <subscriber-name></subscriber-name> + </service-information> + <allotted-resource-information> + <!-- TODO: to be filled as per the request input --> + <allotted-resource-id></allotted-resource-id> + <allotted-resource-type></allotted-resource-type> + <parent-service-instance-id></parent-service-instance-id> + <onap-model-information> + <model-invariant-uuid>${MsoUtils.xmlEscape(modelInvariantUuid)}</model-invariant-uuid> + <model-customization-uuid>${MsoUtils.xmlEscape(modelCustomizationUuid)}</model-customization-uuid> + <model-uuid>${MsoUtils.xmlEscape(modelUuid)}</model-uuid> + <model-version>${MsoUtils.xmlEscape(modelVersion)}</model-version> + <model-name>${MsoUtils.xmlEscape(modelName)}</model-name> + </onap-model-information> + </allotted-resource-information> + <connection-attachment-request-input> + <param></param> + </connection-attachment-request-input> + </sdncadapterworkflow:SDNCRequestData> + </aetgt:SDNCAdapterWorkflowRequest>""".trim() + break + default: + sdncTopologyDeleteRequest = """<aetgt:SDNCAdapterWorkflowRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:sdncadapter="http://org.onap.so/workflow/sdnc/adapter/schema/v1" + xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1"> + <sdncadapter:RequestHeader> + <sdncadapter:RequestId>${MsoUtils.xmlEscape(hdrRequestId)}</sdncadapter:RequestId> + <sdncadapter:SvcInstanceId>${MsoUtils.xmlEscape(serviceInstanceId)}</sdncadapter:SvcInstanceId> + <sdncadapter:SvcAction>${MsoUtils.xmlEscape(sdnc_svcAction)}</sdncadapter:SvcAction> + <sdncadapter:SvcOperation>network-topology-operation</sdncadapter:SvcOperation> + <sdncadapter:CallbackUrl>sdncCallback</sdncadapter:CallbackUrl> + <sdncadapter:MsoAction>generic-resource</sdncadapter:MsoAction> + </sdncadapter:RequestHeader> + <sdncadapterworkflow:SDNCRequestData> + <request-information> + <request-id>${MsoUtils.xmlEscape(hdrRequestId)}</request-id> + <request-action>${MsoUtils.xmlEscape(sdnc_requestAction)}</request-action> + <source>${MsoUtils.xmlEscape(source)}</source> + <notification-url></notification-url> + <order-number></order-number> + <order-version></order-version> + </request-information> + <service-information> + <service-id>${MsoUtils.xmlEscape(serviceInstanceId)}</service-id> + <subscription-service-type>${MsoUtils.xmlEscape(serviceType)}</subscription-service-type> + <onap-model-information> + <model-invariant-uuid>${MsoUtils.xmlEscape(serviceModelInvariantUuid)}</model-invariant-uuid> + <model-uuid>${MsoUtils.xmlEscape(serviceModelUuid)}</model-uuid> + <model-version>${MsoUtils.xmlEscape(serviceModelVersion)}</model-version> + <model-name>${MsoUtils.xmlEscape(serviceModelName)}</model-name> + </onap-model-information> + <service-instance-id>${MsoUtils.xmlEscape(serviceInstanceId)}</service-instance-id> + <global-customer-id>${MsoUtils.xmlEscape(globalCustomerId)}</global-customer-id> + </service-information> + <network-information> + <onap-model-information> + <model-invariant-uuid>${MsoUtils.xmlEscape(modelInvariantUuid)}</model-invariant-uuid> + <model-customization-uuid>${MsoUtils.xmlEscape(modelCustomizationUuid)}</model-customization-uuid> + <model-uuid>${MsoUtils.xmlEscape(modelUuid)}</model-uuid> + <model-version>${MsoUtils.xmlEscape(modelVersion)}</model-version> + <model-name>${MsoUtils.xmlEscape(modelName)}</model-name> + </onap-model-information> + </network-information> + <network-request-input> + <network-input-parameters></network-input-parameters> + </network-request-input> + </sdncadapterworkflow:SDNCRequestData> + </aetgt:SDNCAdapterWorkflowRequest>""".trim() + } + + String sndcTopologyDeleteRequesAsString = utils.formatXml(sdncTopologyDeleteRequest) + utils.logAudit(sndcTopologyDeleteRequesAsString) + execution.setVariable("sdncAdapterWorkflowRequest", sndcTopologyDeleteRequesAsString) + msoLogger.info("sdncAdapterWorkflowRequest - " + "\n" + sndcTopologyDeleteRequesAsString) + + } catch (Exception ex) { + String exceptionMessage = " Bpmn error encountered in DeleteSDNCCNetworkResource flow. prepareSDNCRequest() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + msoLogger.info(" ***** Exit prepareSDNCRequest *****") + } + + public void prepareUpdateAfterDeActivateSDNCResource(DelegateExecution execution) { + msoLogger.info("***** started prepareUpdateAfterDeActivateSDNCResource *****") + + ResourceInput resourceInputObj = execution.getVariable(Prefix + "resourceInput") + String operType = resourceInputObj.getOperationType() + String resourceCustomizationUuid = resourceInputObj.getResourceModelInfo().getModelCustomizationUuid() + String serviceInstanceId = resourceInputObj.getServiceInstanceId() + String operationId = resourceInputObj.getOperationId() + String progress = "100" + String status = "finished" + String statusDescription = "SDCN resource delete completed" + + //String operationId = execution.getVariable("operationId") + + String body = """ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" + xmlns:ns="http://org.onap.so/requestsdb"> + <soapenv:Header/> + <soapenv:Body> + <ns:updateResourceOperationStatus> + <operType>${MsoUtils.xmlEscape(operType)}</operType> + <operationId>${MsoUtils.xmlEscape(operationId)}</operationId> + <progress>${MsoUtils.xmlEscape(progress)}</progress> + <resourceTemplateUUID>${MsoUtils.xmlEscape(resourceCustomizationUuid)}</resourceTemplateUUID> + <serviceId>${MsoUtils.xmlEscape(serviceInstanceId)}</serviceId> + <status>${MsoUtils.xmlEscape(status)}</status> + <statusDescription>${MsoUtils.xmlEscape(statusDescription)}</statusDescription> + </ns:updateResourceOperationStatus> + </soapenv:Body> + </soapenv:Envelope>"""; + + setProgressUpdateVariables(execution, body) + } + + public void postDeactivateSDNCCall(DelegateExecution execution) { + msoLogger.info(" ***** started postDeactivateSDNCCall *****") + String responseCode = execution.getVariable(Prefix + "sdncDeleteReturnCode") + String responseObj = execution.getVariable(Prefix + "SuccessIndicator") + + msoLogger.info("response from sdnc, response code :" + responseCode + " response object :" + responseObj) + msoLogger.info(" ***** Exit prepareSDNCRequest *****") + } + + public void sendSyncResponse(DelegateExecution execution) { + def isDebugEnabled = execution.getVariable("isDebugLogEnabled") + msoLogger.info(" ***** started sendSyncResponse *****") + + try { + String operationStatus = "finished" + // RESTResponse for main flow + String resourceOperationResp = """{"operationStatus":"${operationStatus}"}""".trim() + msoLogger.debug(" sendSyncResponse to APIH:" + "\n" + resourceOperationResp) + sendWorkflowResponse(execution, 202, resourceOperationResp) + execution.setVariable("sentSyncResponse", true) + + } catch (Exception ex) { + String msg = "Exceptuion in sendSyncResponse:" + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.debug(" ***** Exit sendSyncResopnse *****") + } + +}
\ No newline at end of file diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/Delete3rdONAPE2EServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/Delete3rdONAPE2EServiceInstance.groovy new file mode 100644 index 0000000000..88441271b1 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/Delete3rdONAPE2EServiceInstance.groovy @@ -0,0 +1,519 @@ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - SO + * ================================================================================ + * Copyright (C) 2018 Huawei Technologies Co., Ltd. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License") + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts + +import org.json.JSONObject +import org.json.XML + +import static org.apache.commons.lang3.StringUtils.* +import groovy.xml.XmlUtil +import groovy.json.* +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.onap.so.bpmn.common.scripts.ExceptionUtil +import org.onap.so.bpmn.common.scripts.ExternalAPIUtil +import org.onap.so.bpmn.common.scripts.AaiUtil +import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.so.bpmn.common.recipe.ResourceInput +import org.onap.so.bpmn.common.resource.ResourceRequestBuilder +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.bpmn.infrastructure.workflow.serviceTask.client.builder.AbstractBuilder +import org.onap.so.rest.APIResponse +import org.onap.so.bpmn.common.scripts.SDNCAdapterUtils +import org.onap.so.bpmn.infrastructure.workflow.service.ServicePluginFactory +import java.util.UUID + +import org.camunda.bpm.engine.runtime.Execution +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.apache.commons.lang3.* +import org.apache.commons.codec.binary.Base64 +import org.springframework.web.util.UriUtils +import org.onap.so.rest.RESTClient +import org.onap.so.rest.RESTConfig + +/** + * This groovy class supports the <class>Delete3rdONAPE2EServiceInstance.bpmn</class> process. + * flow for Delete E2EServiceInstance in 3rdONAP + */ +public class Delete3rdONAPE2EServiceInstance extends AbstractServiceTaskProcessor { + + String Prefix = "CRE3rdONAPESI_" + + ExceptionUtil exceptionUtil = new ExceptionUtil() + + JsonUtils jsonUtil = new JsonUtils() + + public void checkSPPartnerInfoFromAAI (DelegateExecution execution) { + def isDebugEnabled = execution.getVariable("isDebugLogEnabled") + utils.log("INFO"," ***** Started checkSPPartnerInfo *****", isDebugEnabled) + try { + //get bpmn inputs from resource request. + String requestId = execution.getVariable("mso-request-id") + String requestAction = execution.getVariable("requestAction") + utils.log("INFO","The requestAction is: " + requestAction, isDebugEnabled) + String recipeParamsFromRequest = execution.getVariable("recipeParams") + utils.log("INFO","The recipeParams is: " + recipeParamsFromRequest, isDebugEnabled) + String resourceInput = execution.getVariable("resourceInput") + utils.log("INFO","The resourceInput is: " + resourceInput, isDebugEnabled) + //Get ResourceInput Object + ResourceInput resourceInputObj = ResourceRequestBuilder.getJsonObject(resourceInput, ResourceInput.class) + // set local resourceInput + execution.setVariable(Prefix + "ResourceInput", resourceInputObj) + + String resourceInstanceId = resourceInputObj.getResourceInstancenUuid() + String sppartnerId = resourceInstanceId + execution.setVariable(Prefix + "SppartnerId", sppartnerId) + utils.log("INFO", "sppartnerId:" + sppartnerId, isDebugEnabled) + + // Get Sppartner from AAI + AaiUtil aaiUriUtil = new AaiUtil(this) + String aai_uri = aaiUriUtil.getBusinessSPPartnerUri(execution) + String namespace = aaiUriUtil.getNamespaceFromUri(aai_uri) + String aai_endpoint = execution.getVariable("URN_aai_endpoint") + String serviceAaiPath = "${aai_endpoint}${aai_uri}/" + UriUtils.encode(sppartnerId,"UTF-8") + execution.setVariable(Prefix + "serviceAaiPath", serviceAaiPath) + + getSPPartnerInAAI(execution) + + String callSource = "UUI" + String sppartnerUrl = "" + String sppartnerVersion = "" + if(execution.getVariable(Prefix + "SuccessIndicator")) { + callSource = execution.getVariable(Prefix + "CallSource") + sppartnerId = execution.getVariable(Prefix + "SppartnerId") + sppartnerUrl = execution.getVariable(Prefix + "SppartnerUrl") + sppartnerVersion = execution.getVariable(Prefix + "SppartnerVersion") + } + + boolean is3rdONAPExist = false + if(!isBlank(sppartnerUrl)) { + is3rdONAPExist = true + } + + execution.setVariable("Is3rdONAPExist", is3rdONAPExist) + execution.setVariable(Prefix + "ServiceInstanceId", resourceInputObj.getServiceInstanceId()) + execution.setVariable("mso-request-id", requestId) + execution.setVariable("mso-service-instance-id", resourceInputObj.getServiceInstanceId()) + + } catch (BpmnError e) { + throw e + } catch (Exception ex){ + String msg = "Exception in checkSPPartnerInfoFromAAI " + ex.getMessage() + utils.log("DEBUG", msg, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + } + + public void checkLocallCall (DelegateExecution execution) { + def isDebugEnabled = execution.getVariable("isDebugLogEnabled") + utils.log("INFO"," ***** Started checkLocallCall *****", isDebugEnabled) + + boolean isLocalCall = true + String callSource = execution.getVariable(Prefix + "CallSource") + if("ExternalAPI".equalsIgnoreCase(callSource)) { + isLocalCall = false + } + execution.setVariable("IsLocalCall", isLocalCall) + } + + public void preProcessRequest(DelegateExecution execution){ + def isDebugEnabled = execution.getVariable("isDebugLogEnabled") + utils.log("INFO"," ***** Started preProcessRequest *****", isDebugEnabled) + try { + ResourceInput resourceInputObj = execution.getVariable(Prefix + "resourceInput") + String msg = "" + + String globalSubscriberId = resourceInputObj.getGlobalSubscriberId() + if (isBlank(globalSubscriberId)) { + msg = "Input globalSubscriberId is null" + utils.log("INFO", msg, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + //set local variable + execution.setVariable("globalSubscriberId", globalSubscriberId) + utils.log("INFO", "globalSubscriberId:" + globalSubscriberId, isDebugEnabled) + + String serviceType = resourceInputObj.getServiceType() + if (isBlank(serviceType)) { + msg = "Input serviceType is null" + utils.log("INFO", msg, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + execution.setVariable("serviceType", serviceType) + utils.log("INFO", "serviceType:" + serviceType, isDebugEnabled) + + String operationId = resourceInputObj.getOperationId() + if (isBlank(operationId)) { + msg = "Input operationId is null" + utils.log("INFO", msg, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + execution.setVariable("operationId", operationId) + utils.log("INFO", "operationId:" + operationId, isDebugEnabled) + + String resourceName = resourceInputObj.getResourceInstanceName() + if (isBlank(resourceName)) { + msg = "Input resourceName is null" + utils.log("INFO", msg, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + execution.setVariable("resourceName", resourceName) + utils.log("INFO", "resourceInstanceId:" + resourceName, isDebugEnabled) + + String resourceTemplateId = resourceInputObj.getResourceModelInfo().getModelCustomizationUuid() + if (isBlank(resourceTemplateId)) { + msg = "Input resourceTemplateId is null" + utils.log("INFO", msg, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + execution.setVariable("resourceTemplateId", resourceTemplateId) + utils.log("INFO", "resourceTemplateId:" + resourceTemplateId, isDebugEnabled) + + } catch (BpmnError e) { + throw e + } catch (Exception ex){ + String msg = "Exception in preProcessRequest " + ex.getMessage() + utils.log("DEBUG", msg, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + } + + public void prepareUpdateProgress(DelegateExecution execution) { + def isDebugEnabled = execution.getVariable("isDebugLogEnabled") + utils.log("INFO"," ***** Started prepareUpdateProgress *****", isDebugEnabled) + ResourceInput resourceInputObj = execution.getVariable(Prefix + "ResourceInput") + String operType = resourceInputObj.getOperationType() + String resourceCustomizationUuid = resourceInputObj.getResourceModelInfo().getModelCustomizationUuid() + String ServiceInstanceId = resourceInputObj.getServiceInstanceId() + String modelName = resourceInputObj.getResourceModelInfo().getModelName() + String operationId = resourceInputObj.getOperationId() + String progress = execution.getVariable("progress") + String status = execution.getVariable("status") + String statusDescription = execution.getVariable("statusDescription") + + String body = """ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" + xmlns:ns="http://org.openecomp.mso/requestsdb"> + <soapenv:Header/> + <soapenv:Body> + <ns:updateResourceOperationStatus> + <operType>${operType}</operType> + <operationId>${operationId}</operationId> + <progress>${progress}</progress> + <resourceTemplateUUID>${resourceCustomizationUuid}</resourceTemplateUUID> + <serviceId>${ServiceInstanceId}</serviceId> + <status>${status}</status> + <statusDescription>${statusDescription}</statusDescription> + </ns:updateResourceOperationStatus> + </soapenv:Body> + </soapenv:Envelope>""" + + setProgressUpdateVariables(execution, body) + utils.log("INFO"," ***** End prepareUpdateProgress *****", isDebugEnabled) + } + + public void prepare3rdONAPRequest(DelegateExecution execution) { + def isDebugEnabled = execution.getVariable("isDebugLogEnabled") + utils.log("INFO"," ***** Started prepare3rdONAPRequest *****", isDebugEnabled) + + String sppartnerUrl = execution.getVariable(Prefix + "SppartnerUrl") + String extAPIPath = sppartnerUrl + 'serviceOrder' + execution.setVariable("ExternalAPIURL", extAPIPath) + + // ExternalAPI message format + String externalId = execution.getVariable("resourceName") + String category = "E2E Service" + String description = "Service Order from SPPartner" + String requestedStartDate = utils.generateCurrentTimeInUtc() + String requestedCompletionDate = utils.generateCurrentTimeInUtc() + String priority = "1" // 0-4 0:highest + String subscriberId = execution.getVariable("globalSubscriberId") + String customerRole = "" + String subscriberName = "" + String referredType = "Consumer" + String orderItemId = "1" + String action = "delete" //for delete + String serviceState = "active" + String serviceName = "" + String serviceType = execution.getVariable("serviceType") + String serviceId = execution.getVariable(Prefix + "ServiceInstanceId") + + Map<String, String> valueMap = new HashMap<>() + valueMap.put("externalId", '"' + externalId + '"') + valueMap.put("category", '"' + category + '"') + valueMap.put("description", '"' + description + '"') + valueMap.put("requestedStartDate", '"' + requestedStartDate + '"') + valueMap.put("requestedCompletionDate", '"' + requestedCompletionDate + '"') + valueMap.put("priority", '"'+ priority + '"') + valueMap.put("subscriberId", '"' + subscriberId + '"') + valueMap.put("customerRole", '"' + customerRole + '"') + valueMap.put("subscriberName", '"' + subscriberName + '"') + valueMap.put("referredType", '"' + referredType + '"') + valueMap.put("orderItemId", '"' + orderItemId + '"') + valueMap.put("action", '"' + action + '"') + valueMap.put("serviceState", '"' + serviceState + '"') + valueMap.put("serviceName", '"' + serviceName + '"') + valueMap.put("serviceType", '"' + serviceType + '"') + valueMap.put("serviceId", '"' + serviceId + '"') + + ExternalAPIUtil externalAPIUtil = new ExternalAPIUtil(this) + + valueMap.put("_requestInputs_", "") + + String payload = externalAPIUtil.setTemplate(ExternalAPIUtil.PostServiceOrderRequestsTemplate, valueMap) + execution.setVariable(Prefix + "Payload", payload) + utils.log("INFO", "Exit " + prepare3rdONAPRequest, isDebugEnabled) + } + + public void doDeleteE2ESIin3rdONAP(DelegateExecution execution) { + def isDebugEnabled = execution.getVariable("isDebugLogEnabled") + utils.log("INFO"," ***** Started doDeleteE2ESIin3rdONAP *****", isDebugEnabled) + + String extAPIPath = execution.getVariable("ExternalAPIURL") + String payload = execution.getVariable(Prefix + "Payload") + + ExternalAPIUtil externalAPIUtil = new ExternalAPIUtil(this) + + APIResponse response = externalAPIUtil.executeExternalAPIPostCall(execution, extAPIPath, payload) + + int responseCode = response.getStatusCode() + execution.setVariable(Prefix + "postServiceOrderResponseCode", responseCode) + utils.log("DEBUG", "Post ServiceOrder response code is: " + responseCode, isDebugEnabled) + + String extApiResponse = response.getResponseBodyAsString() + JSONObject responseObj = new JSONObject(extApiResponse) + execution.setVariable(Prefix + "postServiceOrderResponse", extApiResponse) + //Process Response + if(responseCode == 200 || responseCode == 201 || responseCode == 202 ) + //200 OK 201 CREATED 202 ACCEPTED + { + utils.log("DEBUG", "Post ServiceOrder Received a Good Response", isDebugEnabled) + String serviceOrderId = responseObj.get("ServiceOrderId") + execution.setVariable(Prefix + "SuccessIndicator", true) + execution.setVariable("serviceOrderId", serviceOrderId) + } + else{ + utils.log("DEBUG", "Post ServiceOrder Received a Bad Response Code. Response Code is: " + responseCode, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Post ServiceOrder Received a bad response from 3rdONAP External API") + } + + utils.log("INFO", "Exit " + doDeleteE2ESIin3rdONAP, isDebugEnabled) + } + + + public void getE2ESIProgressin3rdONAP(DelegateExecution execution) { + def isDebugEnabled = execution.getVariable("isDebugLogEnabled") + utils.log("INFO"," ***** Started getE2ESIProgressin3rdONAP *****", isDebugEnabled) + + String extAPIPath = execution.getVariable("ExternalAPIURL") + extAPIPath += "/" + execution.getVariable("ServiceOrderId") + + ExternalAPIUtil externalAPIUtil = new ExternalAPIUtil(this) + + APIResponse response = externalAPIUtil.executeExternalAPIGetCall(execution, extAPIPath) + + int responseCode = response.getStatusCode() + execution.setVariable(Prefix + "getServiceOrderResponseCode", responseCode) + utils.log("DEBUG", "Get ServiceOrder response code is: " + responseCode, isDebugEnabled) + + String extApiResponse = response.getResponseBodyAsString() + JSONObject responseObj = new JSONObject(extApiResponse) + execution.setVariable(Prefix + "getServiceOrderResponse", extApiResponse) + + //Process Response //200 OK 201 CREATED 202 ACCEPTED + if(responseCode == 200 || responseCode == 201 || responseCode == 202 ) + { + utils.log("DEBUG", "Get ServiceOrder Received a Good Response", isDebugEnabled) + String serviceOrderState = responseObj.get("State") + execution.setVariable(Prefix + "SuccessIndicator", true) + execution.setVariable("serviceOrderState", serviceOrderState) + + // Get serviceOrder State and process progress + if("ACKNOWLEDGED".equalsIgnoreCase(serviceOrderState)) { + execution.setVariable("progress", 15) + execution.setVariable("status", "processing") + } + if("INPROGRESS".equalsIgnoreCase(serviceOrderState)) { + execution.setVariable("progress", 40) + execution.setVariable("status", "processing") + } + if("COMPLETED".equalsIgnoreCase(serviceOrderState)) { + execution.setVariable("progress", 100) + execution.setVariable("status", "finished") + } + if("FAILED".equalsIgnoreCase(serviceOrderState)) { + execution.setVariable("progress", 100) + execution.setVariable("status", "error") + } + else { + execution.setVariable("progress", 100) + execution.setVariable("status", "error") + execution.setVariable("statusDescription", "Delete Service Order Status is unknown") + } + execution.setVariable("statusDescription", "Delete Service Order Status is " + serviceOrderState) + } + else{ + utils.log("DEBUG", "Get ServiceOrder Received a Bad Response Code. Response Code is: " + responseCode, isDebugEnabled) + execution.setVariable("progress", 100) + execution.setVariable("status", "error") + execution.setVariable("statusDescription", "Get ServiceOrder Received a bad response") + exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Get ServiceOrder Received a bad response from 3rdONAP External API") + } + + utils.log("INFO", "Exit " + getE2ESIProgressin3rdONAP, isDebugEnabled) + } + + /** + * delay 5 sec + */ + public void timeDelay(DelegateExecution execution) { + def isDebugEnabled= execution.getVariable("isDebugLogEnabled") + try { + Thread.sleep(5000) + } catch(InterruptedException e) { + utils.log("ERROR", "Time Delay exception" + e , isDebugEnabled) + } + } + + private void getSPPartnerInAAI(DelegateExecution execution) { + def isDebugEnabled = execution.getVariable("isDebugLogEnabled") + utils.log("INFO"," ***** Started postDeleteE2ESIin3rdONAP *****", isDebugEnabled) + + AaiUtil aaiUriUtil = new AaiUtil(this) + String serviceAaiPath = execution.getVariable(Prefix + "serviceAaiPath") + APIResponse response = aaiUriUtil.executeAAIGetCall(execution, serviceAaiPath) + int responseCode = response.getStatusCode() + execution.setVariable(Prefix + "GetSppartnerResponseCode", responseCode) + utils.log("DEBUG", " Get sppartner response code is: " + responseCode, isDebugEnabled) + + String aaiResponse = response.getResponseBodyAsString() + aaiResponse = StringEscapeUtils.unescapeXml(aaiResponse) + aaiResponse = aaiResponse.replaceAll("&", "&") + execution.setVariable(Prefix + "GetSppartnerResponse", aaiResponse) + + //Process Response + if(responseCode == 200 || responseCode == 201 || responseCode == 202 ) + //200 OK 201 CREATED 202 ACCEPTED + { + utils.log("DEBUG", "GET sppartner Received a Good Response", isDebugEnabled) + execution.setVariable(Prefix + "SuccessIndicator", true) + execution.setVariable(Prefix + "FoundIndicator", true) + + String sppartnerId = utils.getNodeText1(aaiResponse, "sppartner-id") + execution.setVariable(Prefix + "SppartnerId", sppartnerId) + utils.log("DEBUG", " SppartnerId is: " + sppartnerId, isDebugEnabled) + String sppartnerUrl = utils.getNodeText1(aaiResponse, "sppartner-url") + execution.setVariable(Prefix + "SppartnerUrl", sppartnerUrl) + utils.log("DEBUG", " SppartnerUrl is: " + sppartnerUrl, isDebugEnabled) + String callSource = utils.getNodeText1(aaiResponse, "sppartner-callsource") + execution.setVariable(Prefix + "CallSource", callSource) + utils.log("DEBUG", " CallSource is: " + callSource, isDebugEnabled) + String sppartnerVersion = utils.getNodeText1(aaiResponse, "resource-version") + execution.setVariable(Prefix + "SppartnerVersion", sppartnerVersion) + utils.log("DEBUG", " Resource Version is: " + sppartnerVersion, isDebugEnabled) + } + else + { + utils.log("DEBUG", "Get sppartner Received a Bad Response Code. Response Code is: " + responseCode, isDebugEnabled) + exceptionUtil.MapAAIExceptionToWorkflowExceptionGeneric(execution, aaiResponse, responseCode) + throw new BpmnError("MSOWorkflowException") + } + + utils.log("INFO", "Exit " + deleteSPPartnerInAAI, isDebugEnabled) + } + + public void deleteSPPartnerInAAI(DelegateExecution execution) { + def isDebugEnabled = execution.getVariable("isDebugLogEnabled") + utils.log("INFO"," ***** Started postDeleteE2ESIin3rdONAP *****", isDebugEnabled) + + String sppartnerId = execution.getVariable(Prefix + "SppartnerId") + String sppartnerUrl = execution.getVariable(Prefix + "sppartnerUrl") + String sppartnerVersion = execution.getVariable(Prefix + "sppartnerVersion") + + AaiUtil aaiUriUtil = new AaiUtil(this) + String serviceAaiPath = execution.getVariable(Prefix + "serviceAaiPath") + "?resource-version=${sppartnerVersion}" + APIResponse response = aaiUriUtil.executeAAIDeleteCall(execution, serviceAaiPath) + int responseCode = response.getStatusCode() + execution.setVariable(Prefix + "DeleteSppartnerResponseCode", responseCode) + utils.log("DEBUG", " Get sppartner response code is: " + responseCode, isDebugEnabled) + + String aaiResponse = response.getResponseBodyAsString() + aaiResponse = StringEscapeUtils.unescapeXml(aaiResponse) + execution.setVariable(Prefix + "DeleteSppartnerResponse", aaiResponse) + + //Process Response + if(responseCode == 200 || responseCode == 201 || responseCode == 202 ) + //200 OK 201 CREATED 202 ACCEPTED + { + utils.log("DEBUG", "Delete sppartner Received a Good Response", isDebugEnabled) + execution.setVariable(Prefix + "SuccessIndicator", true) + } + else if(responseCode == 404){ + utils.log("DEBUG", " Delete sppartner Received a Not Found (404) Response", isDebugEnabled) + execution.setVariable(Prefix + "FoundIndicator", false) + } + else + { + utils.log("DEBUG", "Delete sppartner Received a Bad Response Code. Response Code is: " + responseCode, isDebugEnabled) + exceptionUtil.MapAAIExceptionToWorkflowExceptionGeneric(execution, aaiResponse, responseCode) + throw new BpmnError("MSOWorkflowException") + } + + utils.log("INFO", "Exit " + deleteSPPartnerInAAI, isDebugEnabled) + } + + private void setProgressUpdateVariables(DelegateExecution execution, String body) { + def dbAdapterEndpoint = execution.getVariable("URN_mso_adapters_openecomp_db_endpoint") + execution.setVariable("CVFMI_dbAdapterEndpoint", dbAdapterEndpoint) + execution.setVariable("CVFMI_updateResOperStatusRequest", body) + } + + public void postProcess(DelegateExecution execution){ + def isDebugEnabled = execution.getVariable("isDebugLogEnabled") + utils.log("INFO"," ***** Started postProcess *****", isDebugEnabled) + String responseCode = execution.getVariable(Prefix + "putSppartnerResponseCode") + String responseObj = execution.getVariable(Prefix + "putSppartnerResponse") + + utils.log("INFO","response from AAI for put sppartner, response code :" + responseCode + " response object :" + responseObj, isDebugEnabled) + utils.log("INFO"," ***** Exit postProcess *****", isDebugEnabled) + } + + public void sendSyncResponse (DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + utils.log("DEBUG", " *** sendSyncResponse *** ", isDebugEnabled) + + try { + String operationStatus = "finished" + // RESTResponse for main flow + String resourceOperationResp = """{"operationStatus":"${operationStatus}"}""".trim() + utils.log("DEBUG", " sendSyncResponse to APIH:" + "\n" + resourceOperationResp, isDebugEnabled) + sendWorkflowResponse(execution, 202, resourceOperationResp) + execution.setVariable("sentSyncResponse", true) + + } catch (Exception ex) { + String msg = "Exceptuion in sendSyncResponse:" + ex.getMessage() + utils.log("DEBUG", msg, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + utils.log("DEBUG"," ***** Exit sendSyncResopnse *****", isDebugEnabled) + } +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteCustomE2EServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteCustomE2EServiceInstance.groovy new file mode 100644 index 0000000000..cbbc5189f4 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteCustomE2EServiceInstance.groovy @@ -0,0 +1,386 @@ +/*- + + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts; + +import static org.apache.commons.lang3.StringUtils.*; + +import org.apache.commons.lang3.* +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.onap.so.bpmn.common.scripts.ExceptionUtil +import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.so.bpmn.common.scripts.VidUtils +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.logger.MsoLogger +import org.springframework.web.util.UriUtils; + +import groovy.json.* + +/** + * This groovy class supports the <class>DelE2EServiceInstance.bpmn</class> process. + * + */ +public class DeleteCustomE2EServiceInstance extends AbstractServiceTaskProcessor { + + String Prefix="DELSI_" + ExceptionUtil exceptionUtil = new ExceptionUtil() + JsonUtils jsonUtil = new JsonUtils() + VidUtils vidUtils = new VidUtils() + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DeleteCustomE2EServiceInstance.class); + + public void preProcessRequest (DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + String msg = "" + + msoLogger.info("Starting preProcessRequest") + + try { + // check for incoming json message/input + String siRequest = execution.getVariable("bpmnRequest") + msoLogger.debug(siRequest) + + + String requestId = execution.getVariable("mso-request-id") + execution.setVariable("msoRequestId", requestId) + msoLogger.info("Input Request:" + siRequest + " reqId:" + requestId) + + String serviceInstanceId = execution.getVariable("serviceInstanceId") + if (isBlank(serviceInstanceId)) { + msg = "Input serviceInstanceId' is null" + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + + + //requestInfo +// String productFamilyId = jsonUtil.getJsonValue(siRequest, "requestDetails.requestInfo.productFamilyId") +// if (isBlank(productFamilyId)) +// { +// msg = "Input productFamilyId is null" +// utils.log("INFO", msg, isDebugEnabled) +// //exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) +// } else { +// execution.setVariable("productFamilyId", productFamilyId) +// } + String source = jsonUtil.getJsonValue(siRequest, "source") + execution.setVariable("source", source) + + //subscriberInfo + String globalSubscriberId = jsonUtil.getJsonValue(siRequest, "globalSubscriberId") + if (isBlank(globalSubscriberId)) { + msg = "Input globalSubscriberId' is null" + msoLogger.info(msg) + } else { + execution.setVariable("globalSubscriberId", globalSubscriberId) + } + + //requestParameters + String subscriptionServiceType = jsonUtil.getJsonValue(siRequest, "serviceType") + if (isBlank(subscriptionServiceType)) { + msg = "Input subscriptionServiceType is null" + msoLogger.debug(msg) + //exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } else { + execution.setVariable("subscriptionServiceType", subscriptionServiceType) + } + String operationId = jsonUtil.getJsonValue(siRequest, "operationId") + execution.setVariable("operationId", operationId) + + execution.setVariable("operationType", "DELETE") + } catch (BpmnError e) { + throw e; + } catch (Exception ex){ + msg = "Exception in preProcessRequest " + ex.getMessage() + msoLogger.info(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.trace("Exit preProcessRequest") + } + + public void sendSyncResponse (DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + msoLogger.trace("Staring sendSyncResponse") + + try { + String operationId = execution.getVariable("operationId") + String syncResponse = """{"operationId":"${operationId}"}""".trim() + msoLogger.info("sendSynchResponse: xmlSyncResponse - " + "\n" + syncResponse) + sendWorkflowResponse(execution, 202, syncResponse) + + } catch (Exception ex) { + String msg = "Exception in sendSyncResponse: " + ex.getMessage() + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + } + msoLogger.trace("Exit sendSyncResopnse") + } + + public void sendSyncError (DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + msoLogger.info("Starting sendSyncError") + + try { + String errorMessage = "" + if (execution.getVariable("WorkflowException") instanceof WorkflowException) { + WorkflowException wfe = execution.getVariable("WorkflowException") + errorMessage = wfe.getErrorMessage() + } else { + errorMessage = "Sending Sync Error." + } + + String buildworkflowException = + """<aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1"> + <aetgt:ErrorMessage>${MsoUtils.xmlEscape(errorMessage)}</aetgt:ErrorMessage> + <aetgt:ErrorCode>7000</aetgt:ErrorCode> + </aetgt:WorkflowException>""" + + msoLogger.info(buildworkflowException) + sendWorkflowResponse(execution, 500, buildworkflowException) + + } catch (Exception ex) { + msoLogger.info("Sending Sync Error Activity Failed. " + "\n" + ex.getMessage()) + } + + } + + public void prepareCompletionRequest (DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + msoLogger.trace("Starting prepareCompletion") + + try { + String requestId = execution.getVariable("msoRequestId") + String source = execution.getVariable("source") + String msoCompletionRequest = + """<aetgt:MsoCompletionRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:ns="http://org.onap/so/request/types/v1"> + <request-info xmlns="http://org.onap/so/infra/vnf-request/v1"> + <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> + <action>DELETE</action> + <source>${MsoUtils.xmlEscape(source)}</source> + </request-info> + <aetgt:status-message>E2E Service Instance was deleted successfully.</aetgt:status-message> + <aetgt:mso-bpel-name>DeleteCustomE2EServiceInstance</aetgt:mso-bpel-name> + </aetgt:MsoCompletionRequest>""" + + // Format Response + String xmlMsoCompletionRequest = utils.formatXml(msoCompletionRequest) + + execution.setVariable("completionRequest", xmlMsoCompletionRequest) + msoLogger.info(" Overall SUCCESS Response going to CompleteMsoProcess - " + "\n" + xmlMsoCompletionRequest) + + } catch (Exception ex) { + String msg = " Exception in prepareCompletion:" + ex.getMessage() + msoLogger.info(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.trace("Exit prepareCompletionRequest") + } + + public void prepareFalloutRequest(DelegateExecution execution){ + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + msoLogger.trace("Starting prepareFalloutRequest ") + + try { + WorkflowException wfex = execution.getVariable("WorkflowException") + msoLogger.info(" Input Workflow Exception: " + wfex.toString()) + String requestId = execution.getVariable("msoRequestId") + String source = execution.getVariable("source") + String requestInfo = + """<request-info xmlns="http://org.onap/so/infra/vnf-request/v1"> + <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> + <action>DELETE</action> + <source>${MsoUtils.xmlEscape(source)}</source> + </request-info>""" + + String falloutRequest = exceptionUtil.processMainflowsBPMNException(execution, requestInfo) + execution.setVariable("falloutRequest", falloutRequest) + } catch (Exception ex) { + msoLogger.info("Exception prepareFalloutRequest:" + ex.getMessage()) + String errorException = " Bpmn error encountered in CreateServiceInstance flow. FalloutHandlerRequest, buildErrorResponse() - " + ex.getMessage() + String requestId = execution.getVariable("msoRequestId") + String falloutRequest = + """<aetgt:FalloutHandlerRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:ns="http://org.onap/so/request/types/v1" + xmlns:wfsch="http://org.onap/so/workflow/schema/v1"> + <request-info xmlns="http://org.onap/so/infra/vnf-request/v1"> + <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> + <action>DELETE</action> + <source>VID</source> + </request-info> + <aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1"> + <aetgt:ErrorMessage>${MsoUtils.xmlEscape(errorException)}</aetgt:ErrorMessage> + <aetgt:ErrorCode>7000</aetgt:ErrorCode> + </aetgt:WorkflowException> + </aetgt:FalloutHandlerRequest>""" + + execution.setVariable("falloutRequest", falloutRequest) + } + msoLogger.trace("Exit prepareFalloutRequest") + } + + + // ******************************* + // Build DB request Section + // ******************************* + public void prepareDBRequest (DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix", Prefix) + + try { + msoLogger.info("Starting prepareDBRequest") + + String requestId = execution.getVariable("DELSI_requestId") + String statusMessage = "E2E Service Instance successfully deleted." + + //TODO - verify the format for Service Instance Delete, + String dbRequest = + """<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"> + <soapenv:Header/> + <soapenv:Body> + <ns:updateInfraRequest xmlns:ns="http://org.onap.so/requestsdb"> + <requestId>${MsoUtils.xmlEscape(requestId)}</requestId> + <lastModifiedBy>BPMN</lastModifiedBy> + <statusMessage>${MsoUtils.xmlEscape(statusMessage)}</statusMessage> + <responseBody></responseBody> + <requestStatus>COMPLETED</requestStatus> + <progress>100</progress> + </ns:updateInfraRequest> + </soapenv:Body> + </soapenv:Envelope>""" + + String buildDeleteDBRequestAsString = utils.formatXml(dbRequest) + execution.setVariable("DELSI_createDBRequest", buildDeleteDBRequestAsString) + msoLogger.info(buildDeleteDBRequestAsString) + + } catch (Exception ex) { + // try error in method block + String exceptionMessage = "Bpmn error encountered in DeleteCustomE2EServiceInstance flow. Unexpected Error from method prepareDBRequest() - " + ex.getMessage() + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + // ******************************* + // Build Error Section + // ******************************* + public void prepareDBRequestError (DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix", Prefix) + + msoLogger.trace("Start prepareDBRequestError") + + try { + String requestId = execution.getVariable("DELSI_requestId") + String statusMessage = "" + if (execution.getVariable("WorkflowException") instanceof WorkflowException) { + WorkflowException wfe = execution.getVariable("WorkflowException") + statusMessage = wfe.getErrorMessage() + + } else { + statusMessage = "Encountered Error during DeleteCustomE2EServiceInstance proccessing. " + } + + //TODO - verify the format for Service Instance Create, + String dbRequest = + """<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"> + <soapenv:Header/> + <soapenv:Body> + <ns:updateInfraRequest xmlns:ns="http://org.onap.so/requestsdb"> + <requestId>${MsoUtils.xmlEscape(requestId)}</requestId> + <lastModifiedBy>BPMN</lastModifiedBy> + <statusMessage>${MsoUtils.xmlEscape(statusMessage)}</statusMessage> + <responseBody></responseBody> + <requestStatus>FAILED</requestStatus> + </ns:updateInfraRequest> + </soapenv:Body> + </soapenv:Envelope>""" + + String buildDBRequestAsString = utils.formatXml(dbRequest) + execution.setVariable("DELSI_createDBInfraErrorRequest", buildDBRequestAsString) + msoLogger.info(buildDBRequestAsString) + + } catch (Exception ex) { + // try error in method block + String exceptionMessage = "Bpmn error encountered in DeleteCustomE2EServiceInstance flow. Unexpected Error from method prepareDBRequestError() - " + ex.getMessage() + exceptionUtil.buildWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + public void processJavaException(DelegateExecution execution) { + //TODO: + } + + /** + * Init the service Operation Status + */ + public void prepareInitServiceOperationStatus(DelegateExecution execution){ + def isDebugEnabled = execution.getVariable("isDebugLogEnabled") + utils.log("DEBUG", " ======== STARTED prepareInitServiceOperationStatus Process ======== ", isDebugEnabled) + try{ + String serviceId = execution.getVariable("serviceInstanceId") + String operationId = execution.getVariable("operationId") + String userId = "" + String result = "processing" + String progress = "0" + String reason = "" + String operationContent = "Prepare service creation" + utils.log("DEBUG", "Generated new operation for Service Instance serviceId:" + serviceId + " operationId:" + operationId, isDebugEnabled) + serviceId = UriUtils.encode(serviceId,"UTF-8") + + def dbAdapterEndpoint = execution.getVariable("URN_mso_adapters_openecomp_db_endpoint") + execution.setVariable("CVFMI_dbAdapterEndpoint", dbAdapterEndpoint) + utils.log("DEBUG", "DB Adapter Endpoint is: " + dbAdapterEndpoint, isDebugEnabled) + + String payload = + """<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" + xmlns:ns="http://org.onap.so/requestsdb"> + <soapenv:Header/> + <soapenv:Body> + <ns:updateServiceOperationStatus xmlns:ns="http://org.onap.so/requestsdb"> + <serviceId>${MsoUtils.xmlEscape(serviceId)}</serviceId> + <operationId>${MsoUtils.xmlEscape(operationId)}</operationId> + <operationType>DELETE</operationType> + <userId>${MsoUtils.xmlEscape(userId)}</userId> + <result>${MsoUtils.xmlEscape(result)}</result> + <operationContent>${MsoUtils.xmlEscape(operationContent)}</operationContent> + <progress>${MsoUtils.xmlEscape(progress)}</progress> + <reason>${MsoUtils.xmlEscape(reason)}</reason> + </ns:updateServiceOperationStatus> + </soapenv:Body> + </soapenv:Envelope>""" + + payload = utils.formatXml(payload) + execution.setVariable("CVFMI_updateServiceOperStatusRequest", payload) + utils.log("DEBUG", "Outgoing updateServiceOperStatusRequest: \n" + payload, isDebugEnabled) + + }catch(Exception e){ + utils.log("ERROR", "Exception Occured Processing prepareInitServiceOperationStatus. Exception is:\n" + e, isDebugEnabled) + execution.setVariable("CVFMI_ErrorResponse", "Error Occurred during prepareInitServiceOperationStatus Method:\n" + e.getMessage()) + } + utils.log("DEBUG", "======== COMPLETED prepareInitServiceOperationStatus Process ======== ", isDebugEnabled) + } +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteGenericALaCarteServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteGenericALaCarteServiceInstance.groovy new file mode 100644 index 0000000000..b43a96bdb0 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteGenericALaCarteServiceInstance.groovy @@ -0,0 +1,362 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts; + +import static org.apache.commons.lang3.StringUtils.*; + +import org.apache.commons.lang3.* +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.onap.so.bpmn.common.scripts.ExceptionUtil +import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.so.bpmn.common.scripts.VidUtils +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.logger.MsoLogger + +import groovy.json.* + +/** + * This groovy class supports the <class>DelServiceInstance.bpmn</class> process. + * + */ +public class DeleteGenericALaCarteServiceInstance extends AbstractServiceTaskProcessor { + + String Prefix="DELSI_" + ExceptionUtil exceptionUtil = new ExceptionUtil() + JsonUtils jsonUtil = new JsonUtils() + VidUtils vidUtils = new VidUtils() + + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DeleteGenericALaCarteServiceInstance.class); + + public void preProcessRequest (DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + String msg = "" + + msoLogger.trace("Start preProcessRequest") + + try { + // check for incoming json message/input + String siRequest = execution.getVariable("bpmnRequest") + + String requestId = execution.getVariable("mso-request-id") + execution.setVariable("msoRequestId", requestId) + msoLogger.debug("Input Request:" + siRequest + " reqId:" + requestId) + + String serviceInstanceId = execution.getVariable("serviceInstanceId") + if (isBlank(serviceInstanceId)) { + msg = "Input serviceInstanceId' is null" + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + + //String xmlRequestDetails = vidUtils.getJsonRequestDetailstoXml(siRequest) + //execution.setVariable("requestDetails", xmlRequestDetails) + + //modelInfo + String serviceModelInfo = jsonUtil.getJsonValue(siRequest, "requestDetails.modelInfo") + if (isBlank(serviceModelInfo)) { + msg = "Input serviceModelInfo is null" + msoLogger.debug(msg) + } else + { + execution.setVariable("serviceModelInfo", serviceModelInfo) + //msoLogger.debug("modelInfo" + serviceModelInfo) + } + + //requestInfo + String productFamilyId = jsonUtil.getJsonValue(siRequest, "requestDetails.requestInfo.productFamilyId") + if (isBlank(productFamilyId)) + { + msg = "Input productFamilyId is null" + msoLogger.debug(msg) + //exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } else { + execution.setVariable("productFamilyId", productFamilyId) + } + String source = jsonUtil.getJsonValue(siRequest, "requestDetails.requestInfo.source") + execution.setVariable("source", source) + + //subscriberInfo + String globalSubscriberId = jsonUtil.getJsonValue(siRequest, "requestDetails.subscriberInfo.globalSubscriberId") + if (isBlank(globalSubscriberId)) { + msg = "Input globalSubscriberId' is null" + msoLogger.debug(msg) + } else { + execution.setVariable("globalSubscriberId", globalSubscriberId) + } + + //requestParameters + String subscriptionServiceType = jsonUtil.getJsonValue(siRequest, "requestDetails.requestParameters.subscriptionServiceType") + if (isBlank(subscriptionServiceType)) { + msg = "Input subscriptionServiceType is null" + msoLogger.debug(msg) + //exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } else { + execution.setVariable("subscriptionServiceType", subscriptionServiceType) + } + + /* + * Extracting User Parameters from incoming Request and converting into a Map + */ + def jsonSlurper = new JsonSlurper() + def jsonOutput = new JsonOutput() + + Map reqMap = jsonSlurper.parseText(siRequest) + + //InputParams + def userParams = reqMap.requestDetails?.requestParameters?.userParams + + Map<String, String> inputMap = [:] + if (userParams) { + userParams.each { + userParam -> inputMap.put(userParam.name, userParam.value.toString()) + } + } + + msoLogger.debug("User Input Parameters map: " + userParams.toString()) + execution.setVariable("serviceInputParams", inputMap) + + } catch (BpmnError e) { + throw e; + } catch (Exception ex){ + msg = "Exception in preProcessRequest " + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.trace("Exit preProcessRequest") + } + + public void sendSyncResponse (DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + msoLogger.trace("Start sendSyncResponse") + + try { + String requestId = execution.getVariable("msoRequestId") + String serviceInstanceId = execution.getVariable("serviceInstanceId") + + // RESTResponse (for API Handler (APIH) Reply Task) + String syncResponse = """{"requestReferences":{"instanceId":"${serviceInstanceId}","requestId":"${requestId}"}}""".trim() + msoLogger.debug(" sendSynchResponse: xmlSyncResponse - " + "\n" + syncResponse) + sendWorkflowResponse(execution, 202, syncResponse) + + } catch (Exception ex) { + String msg = "Exception in sendSyncResponse: " + ex.getMessage() + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + } + msoLogger.trace("Exit sendSyncResopnse") + } + + public void sendSyncError (DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + msoLogger.trace("Start sendSyncError") + + try { + String errorMessage = "" + if (execution.getVariable("WorkflowException") instanceof WorkflowException) { + WorkflowException wfe = execution.getVariable("WorkflowException") + errorMessage = wfe.getErrorMessage() + } else { + errorMessage = "Sending Sync Error." + } + + String buildworkflowException = + """<aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1"> + <aetgt:ErrorMessage>${MsoUtils.xmlEscape(errorMessage)}</aetgt:ErrorMessage> + <aetgt:ErrorCode>7000</aetgt:ErrorCode> + </aetgt:WorkflowException>""" + + MsoLogger.info(buildworkflowException) + sendWorkflowResponse(execution, 500, buildworkflowException) + + } catch (Exception ex) { + msoLogger.debug(" Sending Sync Error Activity Failed. " + "\n" + ex.getMessage()) + } + + } + + public void prepareCompletionRequest (DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + msoLogger.trace("Start prepareCompletion") + + try { + String requestId = execution.getVariable("msoRequestId") + String source = execution.getVariable("source") + String msoCompletionRequest = + """<aetgt:MsoCompletionRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:ns="http://org.onap/so/request/types/v1"> + <request-info xmlns="http://org.onap/so/infra/vnf-request/v1"> + <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> + <action>DELETE</action> + <source>${MsoUtils.xmlEscape(source)}</source> + </request-info> + <aetgt:status-message>Service Instance was deleted successfully.</aetgt:status-message> + <aetgt:mso-bpel-name>DeleteGenericALaCarteServiceInstance</aetgt:mso-bpel-name> + </aetgt:MsoCompletionRequest>""" + + // Format Response + String xmlMsoCompletionRequest = utils.formatXml(msoCompletionRequest) + + execution.setVariable("completionRequest", xmlMsoCompletionRequest) + msoLogger.debug(" Overall SUCCESS Response going to CompleteMsoProcess - " + "\n" + xmlMsoCompletionRequest) + + } catch (Exception ex) { + String msg = " Exception in prepareCompletion:" + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.trace("Exit prepareCompletionRequest") + } + + public void prepareFalloutRequest(DelegateExecution execution){ + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + msoLogger.trace("Start prepareFalloutRequest") + + try { + WorkflowException wfex = execution.getVariable("WorkflowException") + msoLogger.debug(" Input Workflow Exception: " + wfex.toString()) + String requestId = execution.getVariable("msoRequestId") + String source = execution.getVariable("source") + String requestInfo = + """<request-info xmlns="http://org.onap/so/infra/vnf-request/v1"> + <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> + <action>DELETE</action> + <source>${MsoUtils.xmlEscape(source)}</source> + </request-info>""" + + String falloutRequest = exceptionUtil.processMainflowsBPMNException(execution, requestInfo) + execution.setVariable("falloutRequest", falloutRequest) + } catch (Exception ex) { + msoLogger.debug("Exception prepareFalloutRequest:" + ex.getMessage()) + String errorException = " Bpmn error encountered in CreateServiceInstance flow. FalloutHandlerRequest, buildErrorResponse() - " + ex.getMessage() + String requestId = execution.getVariable("msoRequestId") + String falloutRequest = + """<aetgt:FalloutHandlerRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:ns="http://org.onap/so/request/types/v1" + xmlns:wfsch="http://org.onap/so/workflow/schema/v1"> + <request-info xmlns="http://org.onap/so/infra/vnf-request/v1"> + <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> + <action>DELETE</action> + <source>VID</source> + </request-info> + <aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1"> + <aetgt:ErrorMessage>${MsoUtils.xmlEscape(errorException)}</aetgt:ErrorMessage> + <aetgt:ErrorCode>7000</aetgt:ErrorCode> + </aetgt:WorkflowException> + </aetgt:FalloutHandlerRequest>""" + + execution.setVariable("falloutRequest", falloutRequest) + } + msoLogger.trace("Exit prepareFalloutRequest ") + } + + + // ******************************* + // Build DB request Section + // ******************************* + public void prepareDBRequest (DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix", Prefix) + + try { + msoLogger.trace("Inside prepareDBRequest of DeleteGenericALaCarteServiceInstance ") + + String requestId = execution.getVariable("DELSI_requestId") + String statusMessage = "Service Instance successfully deleted." + + //TODO - verify the format for Service Instance Delete, + String dbRequest = + """<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"> + <soapenv:Header/> + <soapenv:Body> + <ns:updateInfraRequest xmlns:ns="http://org.onap.so/requestsdb"> + <requestId>${MsoUtils.xmlEscape(requestId)}</requestId> + <lastModifiedBy>BPMN</lastModifiedBy> + <statusMessage>${MsoUtils.xmlEscape(statusMessage)}</statusMessage> + <responseBody></responseBody> + <requestStatus>COMPLETED</requestStatus> + <progress>100</progress> + </ns:updateInfraRequest> + </soapenv:Body> + </soapenv:Envelope>""" + + String buildDeleteDBRequestAsString = utils.formatXml(dbRequest) + execution.setVariable("DELSI_createDBRequest", buildDeleteDBRequestAsString) + msoLogger.info(buildDeleteDBRequestAsString) + + } catch (Exception ex) { + // try error in method block + String exceptionMessage = "Bpmn error encountered in DeleteGenericALaCarteServiceInstance flow. Unexpected Error from method prepareDBRequest() - " + ex.getMessage() + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + // ******************************* + // Build Error Section + // ******************************* + public void prepareDBRequestError (DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix", Prefix) + + msoLogger.trace("Inside prepareDBRequestError of DeleteGenericALaCarteServiceInstance ") + + try { + String requestId = execution.getVariable("DELSI_requestId") + String statusMessage = "" + if (execution.getVariable("WorkflowException") instanceof WorkflowException) { + WorkflowException wfe = execution.getVariable("WorkflowException") + statusMessage = wfe.getErrorMessage() + + } else { + statusMessage = "Encountered Error during DeleteGenericALaCarteServiceInstance proccessing. " + } + + //TODO - verify the format for Service Instance Create, + String dbRequest = + """<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"> + <soapenv:Header/> + <soapenv:Body> + <ns:updateInfraRequest xmlns:ns="http://org.onap.so/requestsdb"> + <requestId>${MsoUtils.xmlEscape(requestId)}</requestId> + <lastModifiedBy>BPMN</lastModifiedBy> + <statusMessage>${MsoUtils.xmlEscape(statusMessage)}</statusMessage> + <responseBody></responseBody> + <requestStatus>FAILED</requestStatus> + </ns:updateInfraRequest> + </soapenv:Body> + </soapenv:Envelope>""" + + String buildDBRequestAsString = utils.formatXml(dbRequest) + execution.setVariable("DELSI_createDBInfraErrorRequest", buildDBRequestAsString) + msoLogger.info(buildDBRequestAsString) + + } catch (Exception ex) { + // try error in method block + String exceptionMessage = "Bpmn error encountered in DeleteGenericALaCarteServiceInstance flow. Unexpected Error from method prepareDBRequestError() - " + ex.getMessage() + exceptionUtil.buildWorkflowException(execution, 7000, exceptionMessage) + + } + + } +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteNetworkInstance.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteNetworkInstance.groovy new file mode 100644 index 0000000000..816ba859ee --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteNetworkInstance.groovy @@ -0,0 +1,420 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts; + +import org.apache.commons.lang3.* +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.onap.so.bpmn.common.scripts.ExceptionUtil +import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.so.bpmn.common.scripts.NetworkUtils +import org.onap.so.bpmn.common.scripts.VidUtils +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.bpmn.core.json.JsonUtils; +import org.onap.so.logger.MessageEnum +import org.onap.so.logger.MsoLogger + +import groovy.json.* + +public class DeleteNetworkInstance extends AbstractServiceTaskProcessor { + String Prefix="DELNI_" + String groovyClassName = "DeleteNetworkInstance" + ExceptionUtil exceptionUtil = new ExceptionUtil() + JsonUtils jsonUtil = new JsonUtils() + VidUtils vidUtils = new VidUtils(this) + NetworkUtils networkUtils = new NetworkUtils() + + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DeleteNetworkInstance.class); + + + public InitializeProcessVariables(DelegateExecution execution){ + + execution.setVariable(Prefix + "Success", false) + + execution.setVariable(Prefix + "CompleteMsoProcessRequest", "") + execution.setVariable(Prefix + "FalloutHandlerRequest", "") + execution.setVariable(Prefix + "isSilentSuccess", false) + + } + + // ************************************************** + // Pre or Prepare Request Section + // ************************************************** + + public void preProcessRequest (DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + + msoLogger.trace("Inside preProcessRequest() of " + groovyClassName + "") + + try { + // initialize flow variables + InitializeProcessVariables(execution) + + String sdncVersion = execution.getVariable("sdncVersion") + if (sdncVersion == null || sdncVersion == '1610') { + // 'a-la-cart' default, sdncVersion = '1610' + execution.setVariable("sdncVersion", "1610") + String bpmnRequest = execution.getVariable("bpmnRequest") + // set 'disableRollback' + if (bpmnRequest != null) { + String disableRollback = jsonUtil.getJsonValue(bpmnRequest, "requestDetails.requestInfo.suppressRollback") + if (disableRollback != null) { + execution.setVariable("disableRollback", disableRollback) + msoLogger.debug("Received 'suppressRollback': " + disableRollback ) + } else { + execution.setVariable("disableRollback", false) + } + msoLogger.debug(" Set 'disableRollback' : " + execution.getVariable("disableRollback") ) + } else { + String dataErrorMessage = " Invalid 'bpmnRequest' request." + msoLogger.debug(dataErrorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + } + + } else { + // 'macro' test ONLY, sdncVersion = '1702' + msoLogger.debug(" 'disableRollback' : " + execution.getVariable("disableRollback") ) + } + + // get/set 'msoRequestId' and 'mso-request-id' + String requestId = execution.getVariable("msoRequestId") + if (requestId != null) { + execution.setVariable("mso-request-id", requestId) + } else { + requestId = execution.getVariable("mso-request-id") + } + execution.setVariable(Prefix + "requestId", requestId) + + // get/set 'requestId' + if (execution.getVariable("requestId") == null) { + execution.setVariable("requestId", requestId) + } + + // set action to "DELETE" + execution.setVariable("action", "DELETE") + + //Place holder for additional code. + + // TODO ??? + // userParams??? 1) pre-loads indicator, 2) 'auto-activation' + // Tag/Value parameters + // + // Map: 'networkInputParams': 'auto-activation'' + // Sample format? + // "requestParameters": { + // "userParams": [ + // { + // "name": "someUserParam1", + // "value": "someValue1" + // } + // ] + // } + // + // String userParams = //use json util to extract "userParams"// + // execution.setVariable("networkInputParams", userParams) + // else: execution.setVariable("networkInputParams", null) + // + + + } catch (Exception ex){ + sendSyncError(execution) + String exceptionMessage = "Exception Encountered in " + groovyClassName + ", PreProcessRequest() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + public void getNetworkModelInfo (DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix", Prefix) + + msoLogger.trace("Inside getNetworkModelInfo() of DeleteNetworkInstance") + + try { + + // For Ala-Carte (sdnc = 1610): + // 1. the Network ModelInfo is expected to be sent + // via requestDetails.modelInfo (modelType = network), ex: modelCustomizationId. + // 2. the Service ModelInfo is expected to be sent but will be IGNORE + // via requestDetails.relatedInstanceList.relatedInstance.modelInfo (modelType = service) + + } catch (Exception ex) { + sendSyncError(execution) + String exceptionMessage = "Bpmn error encountered in DeleteNetworkInstance flow. getNetworkModelInfo() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + public void sendSyncResponse (DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + + msoLogger.trace("Inside sendSyncResponse() of DeleteNetworkInstance") + + try { + String requestId = execution.getVariable("mso-request-id") + String serviceInstanceId = execution.getVariable("serviceInstanceId") + + // RESTResponse (for API Handler (APIH) Reply Task) + String deleteNetworkRestRequest = """{"requestReferences":{"instanceId":"${serviceInstanceId}","requestId":"${requestId}"}}""".trim() + + msoLogger.debug(" sendSyncResponse to APIH - " + "\n" + deleteNetworkRestRequest) + + sendWorkflowResponse(execution, 202, deleteNetworkRestRequest) + + } catch (Exception ex) { + // caught exception + String exceptionMessage = "Exception Encountered in DeleteNetworkInstance, sendSyncResponse() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + public void prepareCompletion (DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + + msoLogger.trace("Inside prepareCompletion() of CreateNetworkInstance") + + try { + + String requestId = execution.getVariable("mso-request-id") + String source = execution.getVariable(Prefix + "source") + + String msoCompletionRequest = + """<aetgt:MsoCompletionRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:ns="http://org.onap/so/request/types/v1"> + <request-info xmlns="http://org.onap/so/infra/vnf-request/v1"> + <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> + <action>DELETE</action> + <source>VID</source> + </request-info> + <aetgt:status-message>Network has been deleted successfully.</aetgt:status-message> + <aetgt:mso-bpel-name>BPMN Network action: DELETE</aetgt:mso-bpel-name> + </aetgt:MsoCompletionRequest>""" + + // Format Response + String xmlMsoCompletionRequest = utils.formatXml(msoCompletionRequest) + + // normal path + execution.setVariable(Prefix + "CompleteMsoProcessRequest", xmlMsoCompletionRequest) + msoLogger.debug(" Overall SUCCESS Response going to CompleteMsoProcess - " + "\n" + xmlMsoCompletionRequest) + + } catch (Exception ex) { + String exceptionMessage = " Bpmn error encountered in CreateNetworkInstance flow. prepareCompletion() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + + + } + + public void prepareDBRequestError (DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix", Prefix) + + try { + msoLogger.trace("Inside prepareDBRequestError of DeleteNetworkInstance") + + // set DB Header Authorization + setBasicDBAuthHeader(execution, isDebugEnabled) + + WorkflowException wfe = execution.getVariable("WorkflowException") + String statusMessage = wfe.getErrorMessage() + String requestId = execution.getVariable(Prefix +"requestId") + + String dbRequest = + """<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"> + <soapenv:Header/> + <soapenv:Body> + <ns:updateInfraRequest xmlns:ns="http://org.onap.so/requestsdb"> + <requestId>${MsoUtils.xmlEscape(requestId)}</requestId> + <lastModifiedBy>BPMN</lastModifiedBy> + <statusMessage>${MsoUtils.xmlEscape(statusMessage)}</statusMessage> + <responseBody></responseBody> + <requestStatus>FAILED</requestStatus> + <progress></progress> + <vnfOutputs><network-outputs xmlns="http://org.onap/so/infra/vnf-request/v1" xmlns:aetgt="http://org.onap/so/infra/vnf-request/v1" xmlns:rest="http://schemas.activebpel.org/REST/2007/12/01/aeREST.xsd"/></vnfOutputs> + </ns:updateInfraRequest> + </soapenv:Body> + </soapenv:Envelope>""" + + execution.setVariable(Prefix + "deleteDBRequest", dbRequest) + msoLogger.debug(" DB Adapter Request - " + "\n" + dbRequest) + + } catch (Exception ex) { + // caught exception + String exceptionMessage = "Bpmn error encountered in DeleteNetworkInstance, prepareDBRequestError() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + // ************************************************** + // Post or Validate Response Section + // ************************************************** + + public void postProcessResponse (DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix", Prefix) + + msoLogger.trace("Inside postProcessResponse() of DeleteNetworkInstance") + + try { + if (execution.getVariable("CMSO_ResponseCode") == "200") { + execution.setVariable(Prefix + "Success", true) + msoLogger.trace("DeleteNetworkInstance Success") + // Place holder for additional code. + + } else { + execution.setVariable(Prefix + "Success", false) + msoLogger.trace("DeleteNetworkInstance Failed in CompletionMsoProces flow!.") + + } + + + } catch (Exception ex) { + String exceptionMessage = " Bpmn error encountered in DeleteNetworkInstance flow. postProcessResponse() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + + // ******************************* + // Build Error Section + // ******************************* + + // Prepare for FalloutHandler + public void buildErrorResponse (DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix", Prefix) + + msoLogger.trace("Prepare for FalloutHandler. FAILURE - prepare request for sub-process FalloutHandler.") + + String dbReturnCode = execution.getVariable(Prefix + "dbReturnCode") + msoLogger.debug("DB Update Response Code : " + dbReturnCode) + msoLogger.debug("DB Update Response String: " + '\n' + execution.getVariable(Prefix + "deleteDBResponse")) + + String falloutHandlerRequest = "" + String requestId = execution.getVariable("mso-request-id") + String source = execution.getVariable(Prefix + "source") + execution.setVariable(Prefix + "Success", false) + try { + WorkflowException wfe = execution.getVariable("WorkflowException") + String errorCode = String.valueOf(wfe.getErrorCode()) + String errorMessage = wfe.getErrorMessage() + + falloutHandlerRequest = + """<aetgt:FalloutHandlerRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:ns="http://org.onap/so/request/types/v1" + xmlns:wfsch="http://org.onap/so/workflow/schema/v1"> + <request-info xmlns="http://org.onap/so/infra/vnf-request/v1"> + <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> + <action>DELETE</action> + <source>${MsoUtils.xmlEscape(source)}</source> + </request-info> + <aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1"> + <aetgt:ErrorMessage>${MsoUtils.xmlEscape(errorMessage)}</aetgt:ErrorMessage> + <aetgt:ErrorCode>${MsoUtils.xmlEscape(errorCode)}</aetgt:ErrorCode> + </aetgt:WorkflowException> + </aetgt:FalloutHandlerRequest>""" + + msoLogger.debug(falloutHandlerRequest) + execution.setVariable(Prefix + "FalloutHandlerRequest", falloutHandlerRequest) + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG,"Overall Error Response going to FalloutHandler: " + "\n" + falloutHandlerRequest,"BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "") + + } catch (Exception ex) { + // caught exception + String exceptionMessage = "Bpmn error encountered in DeleteNetworkInstance, buildErrorResponse() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + falloutHandlerRequest = + """<aetgt:FalloutHandlerRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:ns="http://org.onap/so/request/types/v1" + xmlns:wfsch="http://org.onap/so/workflow/schema/v1"> + <request-info xmlns="http://org.onap/so/infra/vnf-request/v1"> + <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> + <action>DELEtE</action> + <source>${MsoUtils.xmlEscape(source)}</source> + </request-info> + <aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1"> + <aetgt:ErrorMessage>${MsoUtils.xmlEscape(exceptionMessage)}</aetgt:ErrorMessage> + <aetgt:ErrorCode>9999</aetgt:ErrorCode> + </aetgt:WorkflowException> + </aetgt:FalloutHandlerRequest>""" + execution.setVariable(Prefix + "FalloutHandlerRequest", falloutHandlerRequest) + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG,"Overall Error Response going to FalloutHandler: " + "\n" + falloutHandlerRequest,"BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + ex) + } + } + + + public void sendSyncError (DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix", Prefix) + + try { + String requestId = execution.getVariable("mso-request-id") + String serviceInstanceId = execution.getVariable("serviceInstanceId") + + // RESTResponse (for API Handler (APIH) Reply Task) + String deleteNetworkRestError = """{"requestReferences":{"instanceId":"${serviceInstanceId}","requestId":"${requestId}"}}""".trim() + + msoLogger.debug(" sendSyncResponse to APIH - " + "\n" + deleteNetworkRestError) + + sendWorkflowResponse(execution, 500, deleteNetworkRestError) + + } catch (Exception ex) { + msoLogger.debug(" Sending Sync Error Activity Failed - DeleteNetworkInstance, sendSyncError(): " + "\n" + ex.getMessage()) + } + } + + public void processJavaException(DelegateExecution execution){ + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + try{ + msoLogger.debug("Caught a Java Exception") + msoLogger.debug("Started processJavaException Method") + msoLogger.debug("Variables List: " + execution.getVariables()) + execution.setVariable("UnexpectedError", "Caught a Java Lang Exception") // Adding this line temporarily until this flows error handling gets updated + exceptionUtil.buildWorkflowException(execution, 500, "Caught a Java Lang Exception") + + }catch(Exception e){ + msoLogger.debug("Caught Exception during processJavaException Method: " + e) + execution.setVariable("UnexpectedError", "Exception in processJavaException method") // Adding this line temporarily until this flows error handling gets updated + exceptionUtil.buildWorkflowException(execution, 500, "Exception in processJavaException method") + } + msoLogger.debug("Completed processJavaException Method of " + Prefix) + } + +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteSDNCNetworkResource.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteSDNCNetworkResource.groovy new file mode 100644 index 0000000000..04b62d7f73 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteSDNCNetworkResource.groovy @@ -0,0 +1,439 @@ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - SO + * ================================================================================ + * Copyright (C) 2018 Huawei Technologies Co., Ltd. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts + +import org.onap.so.logger.MsoLogger + +import static org.apache.commons.lang3.StringUtils.*; + +import org.apache.commons.lang3.* +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.onap.so.bpmn.common.recipe.ResourceInput; +import org.onap.so.bpmn.common.resource.ResourceRequestBuilder +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.onap.so.bpmn.common.scripts.ExceptionUtil +import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.so.bpmn.common.scripts.SDNCAdapterUtils +import org.onap.so.bpmn.core.json.JsonUtils + +import groovy.json.* + +/** + * This groovy class supports the <class>DeleteSDNCCNetworkResource.bpmn</class> process. + * flow for SDNC Network Resource + */ +public class DeleteSDNCNetworkResource extends AbstractServiceTaskProcessor { + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, + CreateSDNCNetworkResource.class); + + String Prefix="DELSDNCRES_" + + ExceptionUtil exceptionUtil = new ExceptionUtil() + + JsonUtils jsonUtil = new JsonUtils() + + SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils() + + public void preProcessRequest(DelegateExecution execution){ + msoLogger.info("***** Started preProcessRequest *****") + try { + + //get bpmn inputs from resource request. + String requestId = execution.getVariable("mso-request-id") + String requestAction = execution.getVariable("requestAction") + msoLogger.info("The requestAction is: " + requestAction) + String recipeParamsFromRequest = execution.getVariable("recipeParams") + msoLogger.info("The recipeParams is: " + recipeParamsFromRequest) + String resourceInput = execution.getVariable("resourceInput") + msoLogger.info("The resourceInput is: " + resourceInput) + //Get ResourceInput Object + ResourceInput resourceInputObj = ResourceRequestBuilder.getJsonObject(resourceInput, ResourceInput.class) + execution.setVariable(Prefix + "resourceInput", resourceInputObj) + + //Deal with recipeParams + String recipeParamsFromWf = execution.getVariable("recipeParamXsd") + String resourceModelName = resourceInputObj.getResourceModelInfo().getModelName() + //For sdnc requestAction default is "NetworkInstance" + String operationType = "Network" + if(!StringUtils.isBlank(recipeParamsFromRequest) && "null" != recipeParamsFromRequest){ + //the operationType from worflow(first node) is second priority. + operationType = jsonUtil.getJsonValue(recipeParamsFromRequest, "operationType") + } + if(!StringUtils.isBlank(recipeParamsFromWf)){ + //the operationType from worflow(first node) is highest priority. + operationType = jsonUtil.getJsonValue(recipeParamsFromWf, "operationType") + } + + + //For sdnc, generate svc_action and request_action + String sdnc_svcAction = "delete" + if(StringUtils.containsIgnoreCase(resourceModelName, "overlay")){ + //This will be resolved in R3. + sdnc_svcAction ="deactivate" + operationType = "NCINetwork" + } + if(StringUtils.containsIgnoreCase(resourceModelName, "underlay")){ + //This will be resolved in R3. + operationType ="Network" + } + String sdnc_requestAction = StringUtils.capitalize(sdnc_svcAction) + operationType +"Instance" + execution.setVariable(Prefix + "svcAction", sdnc_svcAction) + execution.setVariable(Prefix + "requestAction", sdnc_requestAction) + execution.setVariable(Prefix + "serviceInstanceId", resourceInputObj.getServiceInstanceId()) + execution.setVariable("mso-request-id", requestId) + execution.setVariable("mso-service-instance-id", resourceInputObj.getServiceInstanceId()) + //TODO Here build networkrequest + + } catch (BpmnError e) { + throw e; + } catch (Exception ex){ + msg = "Exception in preProcessRequest " + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + } + + /** + * Pre Process the BPMN Flow Request + * Inclouds: + * generate the nsOperationKey + * generate the nsParameters + */ + public void prepareSDNCRequest (DelegateExecution execution) { + msoLogger.info("***** Started prepareSDNCRequest *****") + + try { + // get variables + String sdnc_svcAction = execution.getVariable(Prefix + "svcAction") + String sdnc_requestAction = execution.getVariable(Prefix + "requestAction") + String sdncCallback = execution.getVariable("URN_mso_workflow_sdncadapter_callback") + String deleteNetworkInput = execution.getVariable(Prefix + "networkRequest") + + String hdrRequestId = execution.getVariable("mso-request-id") + String serviceInstanceId = execution.getVariable(Prefix + "serviceInstanceId") + String source = execution.getVariable("source") + String sdnc_service_id = execution.getVariable(Prefix + "sdncServiceId") + ResourceInput resourceInputObj = execution.getVariable(Prefix + "resourceInput") + String serviceType = resourceInputObj.getServiceType() + String serviceModelInvariantUuid = resourceInputObj.getServiceModelInfo().getModelInvariantUuid() + String serviceModelUuid = resourceInputObj.getServiceModelInfo().getModelUuid() + String serviceModelVersion = resourceInputObj.getServiceModelInfo().getModelVersion() + String serviceModelName = resourceInputObj.getServiceModelInfo().getModelName() + String globalCustomerId = resourceInputObj.getGlobalSubscriberId() + String modelInvariantUuid = resourceInputObj.getResourceModelInfo().getModelInvariantUuid(); + String modelCustomizationUuid = resourceInputObj.getResourceModelInfo().getModelCustomizationUuid() + String modelUuid = resourceInputObj.getResourceModelInfo().getModelUuid() + String modelName = resourceInputObj.getResourceModelInfo().getModelName() + String modelVersion = resourceInputObj.getResourceModelInfo().getModelVersion() + // 1. prepare assign topology via SDNC Adapter SUBFLOW call + String sndcTopologyDeleteRequest = "" + + switch (modelName) { + case ~/^Site$/: + sndcTopologyDeleteRequest = """<aetgt:SDNCAdapterWorkflowRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:sdncadapter="http://org.onap.so/workflow/sdnc/adapter/schema/v1" + xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1"> + <sdncadapter:RequestHeader> + <sdncadapter:RequestId>${MsoUtils.xmlEscape(hdrRequestId)}</sdncadapter:RequestId> + <sdncadapter:SvcInstanceId>${MsoUtils.xmlEscape(serviceInstanceId)}</sdncadapter:SvcInstanceId> + <sdncadapter:SvcAction>${MsoUtils.xmlEscape(sdnc_svcAction)}</sdncadapter:SvcAction> + <sdncadapter:SvcOperation>network-topology-operation</sdncadapter:SvcOperation> + <sdncadapter:CallbackUrl>sdncCallback</sdncadapter:CallbackUrl> + <sdncadapter:MsoAction>generic-resource</sdncadapter:MsoAction> + </sdncadapter:RequestHeader> + <sdncadapterworkflow:SDNCRequestData> + <request-information> + <request-id>${MsoUtils.xmlEscape(hdrRequestId)}</request-id> + <request-action>${MsoUtils.xmlEscape(sdnc_requestAction)}</request-action> + <source>${MsoUtils.xmlEscape(source)}</source> + <notification-url></notification-url> + <order-number></order-number> + <order-version></order-version> + </request-information> + <service-information> + <service-id>${MsoUtils.xmlEscape(serviceInstanceId)}</service-id> + <subscription-service-type>${MsoUtils.xmlEscape(serviceType)}</subscription-service-type> + <onap-model-information> + <model-invariant-uuid>${MsoUtils.xmlEscape(serviceModelInvariantUuid)}</model-invariant-uuid> + <model-uuid>${MsoUtils.xmlEscape(serviceModelUuid)}</model-uuid> + <model-version>${MsoUtils.xmlEscape(serviceModelVersion)}</model-version> + <model-name>${MsoUtils.xmlEscape(serviceModelName)}</model-name> + </onap-model-information> + <service-instance-id>${MsoUtils.xmlEscape(serviceInstanceId)}</service-instance-id> + <global-customer-id>${MsoUtils.xmlEscape(globalCustomerId)}</global-customer-id> + <subscriber-name></subscriber-name> + </service-information> + <vnf-information> + <!-- TODO: to be filled as per the request input --> + <vnf-id></vnf-id> + <vnf-type></vnf-type> + <onap-model-information> + <model-invariant-uuid>${MsoUtils.xmlEscape(modelInvariantUuid)}</model-invariant-uuid> + <model-customization-uuid>${MsoUtils.xmlEscape(modelCustomizationUuid)}</model-customization-uuid> + <model-uuid>${MsoUtils.xmlEscape(modelUuid)}</model-uuid> + <model-version>${MsoUtils.xmlEscape(modelVersion)}</model-version> + <model-name>${MsoUtils.xmlEscape(modelName)}</model-name> + </onap-model-information> + </vnf-information> + <vnf-request-input> + <request-version></request-version> + <vnf-name></vnf-name> + <vnf-networks> + <vnf-network> + <network-role></network-role> + <network-name></network-name> + <neutron-id></neutron-id> + <network-id></network-id> + <contrail-network-fqdn></contrail-network-fqdn> + <subnets-data> + <subnet-data> + <ip-version></ip-version> + <subnet-id></subnet-id> + </subnet-data> + </subnets-data> + </vnf-network> + </vnf-networks> + </vnf-request-input> + <vnf-input-parameters> + <param></param> + </vnf-input-parameters> + </sdncadapterworkflow:SDNCRequestData> + </aetgt:SDNCAdapterWorkflowRequest>""".trim() + break + + case ~/^SOTNAttachment$/: + sndcTopologyDeleteRequest = """<aetgt:SDNCAdapterWorkflowRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:sdncadapter="http://org.onap.so/workflow/sdnc/adapter/schema/v1" + xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1"> + <sdncadapter:RequestHeader> + <sdncadapter:RequestId>${MsoUtils.xmlEscape(hdrRequestId)}</sdncadapter:RequestId> + <sdncadapter:SvcInstanceId>${MsoUtils.xmlEscape(serviceInstanceId)}</sdncadapter:SvcInstanceId> + <sdncadapter:SvcAction>${MsoUtils.xmlEscape(sdnc_svcAction)}</sdncadapter:SvcAction> + <sdncadapter:SvcOperation>network-topology-operation</sdncadapter:SvcOperation> + <sdncadapter:CallbackUrl>sdncCallback</sdncadapter:CallbackUrl> + <sdncadapter:MsoAction>generic-resource</sdncadapter:MsoAction> + </sdncadapter:RequestHeader> + <sdncadapterworkflow:SDNCRequestData> + <request-information> + <request-id>${MsoUtils.xmlEscape(hdrRequestId)}</request-id> + <request-action>${MsoUtils.xmlEscape(sdnc_requestAction)}</request-action> + <source>${MsoUtils.xmlEscape(source)}</source> + <notification-url></notification-url> + <order-number></order-number> + <order-version></order-version> + </request-information> + <service-information> + <service-id>${MsoUtils.xmlEscape(serviceInstanceId)}</service-id> + <subscription-service-type>${MsoUtils.xmlEscape(serviceType)}</subscription-service-type> + <onap-model-information> + <model-invariant-uuid>${MsoUtils.xmlEscape(serviceModelInvariantUuid)}</model-invariant-uuid> + <model-uuid>${MsoUtils.xmlEscape(serviceModelUuid)}</model-uuid> + <model-version>${MsoUtils.xmlEscape(serviceModelVersion)}</model-version> + <model-name>${MsoUtils.xmlEscape(serviceModelName)}</model-name> + </onap-model-information> + <service-instance-id>${MsoUtils.xmlEscape(serviceInstanceId)}</service-instance-id> + <global-customer-id>${MsoUtils.xmlEscape(globalCustomerId)}</global-customer-id> + <subscriber-name></subscriber-name> + </service-information> + <allotted-resource-information> + <allotted-resource-id></allotted-resource-id> + <allotted-resource-type></allotted-resource-type> + <parent-service-instance-id></parent-service-instance-id> + <onap-model-information> + <model-invariant-uuid>${MsoUtils.xmlEscape(modelInvariantUuid)}</model-invariant-uuid> + <model-customization-uuid>${MsoUtils.xmlEscape(modelCustomizationUuid)}</model-customization-uuid> + <model-uuid>${MsoUtils.xmlEscape(modelUuid)}</model-uuid> + <model-version>${MsoUtils.xmlEscape(modelVersion)}</model-version> + <model-name>${MsoUtils.xmlEscape(modelName)}</model-name> + </onap-model-information> + </allotted-resource-information> + <connection-attachment-request-input> + <param></param> + </connection-attachment-request-input> + </sdncadapterworkflow:SDNCRequestData> + </aetgt:SDNCAdapterWorkflowRequest>""".trim() + break + + default: + sndcTopologyDeleteRequest = """<aetgt:SDNCAdapterWorkflowRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:sdncadapter="http://org.onap.so/workflow/sdnc/adapter/schema/v1" + xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1"> + <sdncadapter:RequestHeader> + <sdncadapter:RequestId>${MsoUtils.xmlEscape(hdrRequestId)}</sdncadapter:RequestId> + <sdncadapter:SvcInstanceId>${MsoUtils.xmlEscape(serviceInstanceId)}</sdncadapter:SvcInstanceId> + <sdncadapter:SvcAction>${MsoUtils.xmlEscape(sdnc_svcAction)}</sdncadapter:SvcAction> + <sdncadapter:SvcOperation>network-topology-operation</sdncadapter:SvcOperation> + <sdncadapter:CallbackUrl>sdncCallback</sdncadapter:CallbackUrl> + <sdncadapter:MsoAction>generic-resource</sdncadapter:MsoAction> + </sdncadapter:RequestHeader> + <sdncadapterworkflow:SDNCRequestData> + <request-information> + <request-id>${MsoUtils.xmlEscape(hdrRequestId)}</request-id> + <request-action>${MsoUtils.xmlEscape(sdnc_requestAction)}</request-action> + <source>${MsoUtils.xmlEscape(source)}</source> + <notification-url></notification-url> + <order-number></order-number> + <order-version></order-version> + </request-information> + <service-information> + <service-id>${MsoUtils.xmlEscape(serviceInstanceId)}</service-id> + <subscription-service-type>${MsoUtils.xmlEscape(serviceType)}</subscription-service-type> + <onap-model-information> + <model-invariant-uuid>${MsoUtils.xmlEscape(serviceModelInvariantUuid)}</model-invariant-uuid> + <model-uuid>${MsoUtils.xmlEscape(serviceModelUuid)}</model-uuid> + <model-version>${MsoUtils.xmlEscape(serviceModelVersion)}</model-version> + <model-name>${MsoUtils.xmlEscape(serviceModelName)}</model-name> + </onap-model-information> + <service-instance-id>${MsoUtils.xmlEscape(serviceInstanceId)}</service-instance-id> + <global-customer-id>${MsoUtils.xmlEscape(globalCustomerId)}</global-customer-id> + </service-information> + <network-information> + <!-- TODO: to be filled as per the request input --> + <network-id></network-id> + <onap-model-information> + <model-invariant-uuid>${MsoUtils.xmlEscape(modelInvariantUuid)}</model-invariant-uuid> + <model-customization-uuid>${MsoUtils.xmlEscape(modelCustomizationUuid)}</model-customization-uuid> + <model-uuid>${MsoUtils.xmlEscape(modelUuid)}</model-uuid> + <model-version>${MsoUtils.xmlEscape(modelVersion)}</model-version> + <model-name>${MsoUtils.xmlEscape(modelName)}</model-name> + </onap-model-information> + </network-information> + <network-request-input> + <network-input-parameters></network-input-parameters> + </network-request-input> + </sdncadapterworkflow:SDNCRequestData> + </aetgt:SDNCAdapterWorkflowRequest>""".trim() + } + + String sndcTopologyDeleteRequesAsString = utils.formatXml(sndcTopologyDeleteRequest) + utils.logAudit(sndcTopologyDeleteRequesAsString) + execution.setVariable("sdncAdapterWorkflowRequest", sndcTopologyDeleteRequesAsString) + msoLogger.info("sdncAdapterWorkflowRequest - " + "\n" + sndcTopologyDeleteRequesAsString) + + } catch (Exception ex) { + String exceptionMessage = " Bpmn error encountered in DeleteSDNCCNetworkResource flow. prepareSDNCRequest() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + msoLogger.info(" ***** Exit prepareSDNCRequest *****") + } + + private void setProgressUpdateVariables(DelegateExecution execution, String body) { + def dbAdapterEndpoint = execution.getVariable("URN_mso_adapters_openecomp_db_endpoint") + execution.setVariable("CVFMI_dbAdapterEndpoint", dbAdapterEndpoint) + execution.setVariable("CVFMI_updateResOperStatusRequest", body) + } + + public void prepareUpdateBeforeDeleteSDNCResource(DelegateExecution execution) { + ResourceInput resourceInputObj = execution.getVariable(Prefix + "resourceInput") + String operType = resourceInputObj.getOperationType() + String resourceCustomizationUuid = resourceInputObj.getResourceModelInfo().getModelCustomizationUuid() + String serviceInstanceId = resourceInputObj.getServiceInstanceId() + String operationId = resourceInputObj.getOperationId() + String progress = "20" + String status = "processing" + String statusDescription = "SDCN resource delete invoked" + + //String operationId = execution.getVariable("operationId") + + String body = """ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" + xmlns:ns="http://org.onap.so/requestsdb"> + <soapenv:Header/> + <soapenv:Body> + <ns:updateResourceOperationStatus> + <operType>${MsoUtils.xmlEscape(operType)}</operType> + <operationId>${MsoUtils.xmlEscape(operationId)}</operationId> + <progress>${MsoUtils.xmlEscape(progress)}</progress> + <resourceTemplateUUID>${MsoUtils.xmlEscape(resourceCustomizationUuid)}</resourceTemplateUUID> + <serviceId>${MsoUtils.xmlEscape(serviceInstanceId)}</serviceId> + <status>${MsoUtils.xmlEscape(status)}</status> + <statusDescription>${MsoUtils.xmlEscape(statusDescription)}</statusDescription> + </ns:updateResourceOperationStatus> + </soapenv:Body> + </soapenv:Envelope>"""; + + setProgressUpdateVariables(execution, body) + + } + + public void prepareUpdateAfterDeleteSDNCResource(DelegateExecution execution) { + ResourceInput resourceInputObj = execution.getVariable(Prefix + "resourceInput") + String operType = resourceInputObj.getOperationType() + String resourceCustomizationUuid = resourceInputObj.getResourceModelInfo().getModelCustomizationUuid() + String serviceInstanceId = resourceInputObj.getServiceInstanceId() + String operationId = resourceInputObj.getOperationId() + String progress = "100" + String status = "finished" + String statusDescription = "SDCN resource delete completed" + + //String operationId = execution.getVariable("operationId") + + String body = """ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" + xmlns:ns="http://org.onap.so/requestsdb"> + <soapenv:Header/> + <soapenv:Body> + <ns:updateResourceOperationStatus> + <operType>${MsoUtils.xmlEscape(operType)}</operType> + <operationId>${MsoUtils.xmlEscape(operationId)}</operationId> + <progress>${MsoUtils.xmlEscape(progress)}</progress> + <resourceTemplateUUID>${MsoUtils.xmlEscape(resourceCustomizationUuid)}</resourceTemplateUUID> + <serviceId>${MsoUtils.xmlEscape(serviceInstanceId)}</serviceId> + <status>${MsoUtils.xmlEscape(status)}</status> + <statusDescription>${MsoUtils.xmlEscape(statusDescription)}</statusDescription> + </ns:updateResourceOperationStatus> + </soapenv:Body> + </soapenv:Envelope>"""; + + setProgressUpdateVariables(execution, body) + } + + public void postDeleteSDNCCall(DelegateExecution execution){ + msoLogger.info(" ***** Started prepareSDNCRequest *****") + String responseCode = execution.getVariable(Prefix + "sdncDeleteReturnCode") + String responseObj = execution.getVariable(Prefix + "SuccessIndicator") + + msoLogger.info("response from sdnc, response code :" + responseCode + " response object :" + responseObj) + msoLogger.info(" ***** Exit prepareSDNCRequest *****") + } + + public void sendSyncResponse (DelegateExecution execution) { + msoLogger.info(" *** sendSyncResponse *** ") + + try { + String operationStatus = "finished" + // RESTResponse for main flow + String resourceOperationResp = """{"operationStatus":"${operationStatus}"}""".trim() + utils.log("DEBUG", " sendSyncResponse to APIH:" + "\n" + resourceOperationResp, isDebugEnabled) + sendWorkflowResponse(execution, 202, resourceOperationResp) + execution.setVariable("sentSyncResponse", true) + + } catch (Exception ex) { + String msg = "Exceptuion in sendSyncResponse:" + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.info(" ***** Exit sendSyncResopnse *****") + } +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteVFCNSResource.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteVFCNSResource.groovy new file mode 100644 index 0000000000..536783bc33 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteVFCNSResource.groovy @@ -0,0 +1,87 @@ + +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2018 Huawei Technologies Co., Ltd. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.so.bpmn.infrastructure.scripts + +import com.fasterxml.jackson.databind.ObjectMapper +import org.onap.so.bpmn.common.recipe.ResourceInput +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.bpmn.common.scripts.ExceptionUtil + + +public class DeleteVFCNSResource extends AbstractServiceTaskProcessor { + + String Prefix = "DCUSE_" + ExceptionUtil exceptionUtil = new ExceptionUtil() + JsonUtils jsonUtil = new JsonUtils() + + public void preProcessRequest (DelegateExecution execution) { + def isDebugEnabled = execution.getVariable("isDebugLogEnabled") + utils.log("INFO"," ***** start preProcessRequest *****", isDebugEnabled) + + String resourceInputStr = execution.getVariable("resourceInput") + ResourceInput resourceInput = new ObjectMapper().readValue(resourceInputStr, ResourceInput.class) + + String globalSubscriberId = resourceInput.getGlobalSubscriberId() + String serviceType = execution.getVariable("serviceType") + String operationId = resourceInput.getOperationId() + String resourceModeluuid = resourceInput.getResourceModelInfo().getModelCustomizationUuid() + String resourceInstanceId = resourceInput.getResourceInstancenUuid() + + + execution.setVariable("globalSubscriberId",globalSubscriberId) + execution.setVariable("serviceType", serviceType) + execution.setVariable("operationId", operationId) + execution.setVariable("resourceTemplateId", resourceModeluuid) + execution.setVariable("resourceInstanceId", resourceInstanceId) + + utils.log("INFO"," ***** end preProcessRequest *****", isDebugEnabled) + } + + public void postProcessRequest (DelegateExecution execution) { + def isDebugEnabled = execution.getVariable("isDebugLogEnabled") + utils.log("INFO"," ***** start postProcessRequest *****", isDebugEnabled) + + utils.log("INFO"," ***** end postProcessRequest *****", isDebugEnabled) + } + + public void sendSyncResponse (DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + utils.log("DEBUG", " *** sendSyncResponse *** ", isDebugEnabled) + + try { + String nsInstanceId = execution.getVariable("nsInstanceId") + String operationStatus = execution.getVariable("operationStatus") + // RESTResponse for main flow + String createVFCResourceRestRsp = """{"nsInstanceId":"${nsInstanceId}","operationStatus":"${operationStatus}"}""".trim() + utils.log("DEBUG", " sendSyncResponse to APIH:" + "\n" + createVFCResourceRestRsp, isDebugEnabled) + sendWorkflowResponse(execution, 202, createVFCResourceRestRsp) + execution.setVariable("sentSyncResponse", true) + + } catch (Exception ex) { + String msg = "Exceptuion in sendSyncResponse:" + ex.getMessage() + utils.log("DEBUG", msg, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + utils.log("DEBUG"," ***** Exit sendSyncResopnse *****", isDebugEnabled) + } +}
\ No newline at end of file diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteVfModuleInfra.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteVfModuleInfra.groovy new file mode 100644 index 0000000000..682421e806 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteVfModuleInfra.groovy @@ -0,0 +1,367 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts + +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor; +import org.onap.so.bpmn.common.scripts.ExceptionUtil; +import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.so.bpmn.common.scripts.VidUtils; +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.bpmn.core.json.JsonUtils; +import org.onap.so.logger.MessageEnum +import org.onap.so.logger.MsoLogger + +import groovy.json.JsonSlurper + + + +public class DeleteVfModuleInfra extends AbstractServiceTaskProcessor { + + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DeleteVfModuleInfra.class); + ExceptionUtil exceptionUtil = new ExceptionUtil() + JsonUtils jsonUtil = new JsonUtils() + /** + * Initialize the flow's variables. + * + * @param execution The flow's execution instance. + */ + public void initProcessVariables(DelegateExecution execution) { + execution.setVariable('prefix', 'DELVfModI_') + execution.setVariable('DELVfModI_requestInfo', null) + execution.setVariable('DELVfModI_requestId', null) + execution.setVariable('DELVfModI_source', null) + execution.setVariable('DELVfModI_vnfInputs', null) + execution.setVariable('DELVfModI_vnfId', null) + execution.setVariable('DELVfModI_vfModuleId', null) + execution.setVariable('DELVfModI_tenantId', null) + execution.setVariable('DELVfModI_volumeGroupId', null) + execution.setVariable('DELVfModI_vnfParams', null) + execution.setVariable('DELVfModI_updateInfraRequest', null) + execution.setVariable('DeleteVfModuleRequest', null) + execution.setVariable('DeleteVfModuleSuccessIndicator', false) + } + + /** + * Process the incoming DELETE_VF_MODULE vnf-request. + * + * @param execution The flow's execution instance. + */ + public void preProcessRequest(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.preProcessRequest(' + + 'execution=' + execution.getId() + + ')' + msoLogger.trace('Entered ' + method) + execution.setVariable("isVidRequest", "false") + initProcessVariables(execution) + + def prefix = execution.getVariable('prefix') + + def incomingRequest = execution.getVariable('bpmnRequest') + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + + msoLogger.debug("Incoming Infra Request: " + incomingRequest) + + // check if request is xml or json + try { + def jsonSlurper = new JsonSlurper() + Map reqMap = jsonSlurper.parseText(incomingRequest) + msoLogger.debug(" Request is in JSON format.") + + def serviceInstanceId = execution.getVariable('serviceInstanceId') + msoLogger.debug("serviceInstanceId is: " + serviceInstanceId) + def vnfId = execution.getVariable('vnfId') + msoLogger.debug("vnfId is: " + vnfId) + def cloudConfiguration = jsonUtil.getJsonValue(incomingRequest, "requestDetails.cloudConfiguration") + execution.setVariable("cloudConfiguration", cloudConfiguration) + msoLogger.debug("CloudConfiguration is: " + cloudConfiguration) + def vfModuleModelInfo = jsonUtil.getJsonValue(incomingRequest, "requestDetails.modelInfo") + + execution.setVariable("vfModuleModelInfo", vfModuleModelInfo) + msoLogger.debug("VfModuleModelInfo is: " + vfModuleModelInfo) + + // This is aLaCarte flow, so aLaCarte flag is always on + execution.setVariable('aLaCarte', true) + + def vidUtils = new VidUtils(this) + + String requestInXmlFormat = vidUtils.createXmlVfModuleRequest(execution, reqMap, 'DELETE_VF_MODULE', serviceInstanceId) + + msoLogger.debug(" Request in XML format: " + requestInXmlFormat) + + setBasicDBAuthHeader(execution, isDebugLogEnabled) + + execution.setVariable(prefix + 'Request', requestInXmlFormat) + execution.setVariable(prefix+'vnfId', vnfId) + execution.setVariable("isVidRequest", "true") + + } + catch(groovy.json.JsonException je) { + msoLogger.debug(" Request is not in JSON format.") + exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Internal Error - During PreProcess Request") + + } + catch(Exception e) { + String restFaultMessage = e.getMessage() + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG,"Caught exception", "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Internal Error - During PreProcess Request") + } + + + try { + + String request = validateRequest(execution) + execution.setVariable('DeleteVfModuleRequest', request) + msoLogger.debug("DeleteVfModuleInfra Request: " + request) + + def requestInfo = getRequiredNodeXml(execution, request, 'request-info') + execution.setVariable('DELVfModI_requestInfo', requestInfo) + execution.setVariable('DELVfModI_requestId', getRequiredNodeText(execution, requestInfo, 'request-id')) + execution.setVariable('DELVfModI_source', getNodeTextForce(requestInfo, 'source')) + + def vnfInputs = getRequiredNodeXml(execution, request, 'vnf-inputs') + execution.setVariable('DELVfModI_vnfInputs', vnfInputs) + execution.setVariable('DELVfModI_vnfId', getRequiredNodeText(execution, vnfInputs, 'vnf-id')) + execution.setVariable('DELVfModI_vfModuleId', getRequiredNodeText(execution, vnfInputs, 'vf-module-id')) + execution.setVariable('DELVfModI_vfModuleName', getNodeTextForce(vnfInputs, 'vf-module-name')) + execution.setVariable('DELVfModI_tenantId', getRequiredNodeText(execution, vnfInputs, 'tenant-id')) + execution.setVariable('DELVfModI_volumeGroupId', getNodeTextForce(vnfInputs, 'volume-group-id')) + + def vnfParams = utils.getNodeXml(request, 'vnf-params') + execution.setVariable('DELVfModI_vnfParams', vnfParams) + + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG,"Caught exception in "+method, "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in preProcessRequest(): ' + e.getMessage()) + } + } + + /** + * Sends the 'IN_PROGRESS' synchronous response. + * + * @param execution The flow's execution instance. + */ + public void sendSynchResponse(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.sendResponse(' + + 'execution=' + execution.getId() + + ')' + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + msoLogger.trace('Entered ' + method) + + try { + def requestInfo = execution.getVariable('DELVfModI_requestInfo') + def requestId = execution.getVariable('DELVfModI_requestId') + def source = execution.getVariable('DELVfModI_source') + def progress = getNodeTextForce(requestInfo, 'progress') + if (progress.isEmpty()) { + progress = '0' + } + def startTime = getNodeTextForce(requestInfo, 'start-time') + if (startTime.isEmpty()) { + startTime = System.currentTimeMillis() + } + + // RESTResponse (for API Handler (APIH) Reply Task) + def vfModuleId = execution.getVariable('DELVfModI_vfModuleId') + String synchResponse = """{"requestReferences":{"instanceId":"${vfModuleId}","requestId":"${requestId}"}}""".trim() + + msoLogger.debug("DeleteVfModuleInfra Synch Response: " + synchResponse) + sendWorkflowResponse(execution, 200, synchResponse) + + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG,"Caught exception in "+method, "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in sendResponse(): ' + e.getMessage()) + } + } + + /** + * Currently passing the entire DELETE_VF_MODULE vnf-request to DoDeleteVfModule. + * 'DeleteVfModuleRequest' is now being set in preProcessRequest(). + * TBD: may want to eventually create a specific request that only contains the needed fields. + * + * @param execution The flow's execution instance. + */ + public void prepDoDeleteVfModule(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.prepDoDeleteVfModule(' + + 'execution=' + execution.getId() + + ')' + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + msoLogger.trace('Entered ' + method) + + try { + + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in prepDoDeleteVfModule(): ' + e.getMessage()) + } + } + + /** + * Prepare the DB update to add an entry for the Vf Module request. + * + * @param execution The flow's execution instance. + */ + public void prepUpdateInfraRequest(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.prepUpdateInfraRequest(' + + 'execution=' + execution.getId() + + ')' + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + msoLogger.trace('Entered ' + method) + + try { + def requestId = execution.getVariable('DELVfModI_requestId') + def vnfId = execution.getVariable('DELVfModI_vnfId') + def vfModuleId = execution.getVariable('DELVfModI_vfModuleId') + def tenantId = execution.getVariable('DELVfModI_tenantId') + def volumeGroupId = execution.getVariable('DELVfModI_volumeGroupId') + + String updateInfraRequest = """ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" + xmlns:req="http://org.onap.so/requestsdb"> + <soapenv:Header/> + <soapenv:Body> + <req:updateInfraRequest> + <requestId>${MsoUtils.xmlEscape(requestId)}</requestId> + <lastModifiedBy>BPMN</lastModifiedBy> + <requestStatus>COMPLETED</requestStatus> + <progress>100</progress> + </req:updateInfraRequest> + </soapenv:Body> + </soapenv:Envelope> + """ + + updateInfraRequest = utils.formatXml(updateInfraRequest) + execution.setVariable('DELVfModI_updateInfraRequest', updateInfraRequest) + msoLogger.debug('Request for Update Infra Request:\n' + updateInfraRequest) + + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in prepInfraRequest(): ' + e.getMessage()) + } + } + + /** + * Builds a "CompletionHandler" request and stores it in the specified execution variable. + * + * @param execution the execution + * @param resultVar the execution variable in which the result will be stored + */ + public void completionHandlerPrep(DelegateExecution execution, String resultVar) { + def method = getClass().getSimpleName() + '.completionHandlerPrep(' + + 'execution=' + execution.getId() + + ', resultVar=' + resultVar + + ')' + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + msoLogger.trace('Entered ' + method) + + try { + def request = execution.getVariable("DeleteVfModuleRequest") + def requestInfo = utils.getNodeXml(request, 'request-info', false) + def action = utils.getNodeText(requestInfo, "action") + + String content = + """ <aetgt:MsoCompletionRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:ns="http://org.onap/so/request/types/v1" + xmlns:ns8="http://org.onap/so/workflow/schema/v1"> + <request-info xmlns="http://org.onap/so/infra/vnf-request/v1"> + ${requestInfo} + </request-info> + <ns8:status-message>Vf Module has been deleted successfully.</ns8:status-message> + <ns8:mso-bpel-name>BPMN</ns8:mso-bpel-name> + </aetgt:MsoCompletionRequest>""" + + content = utils.formatXml(content) + msoLogger.debug(resultVar + ' = ' + System.lineSeparator() + content) + execution.setVariable(resultVar, content) + + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 2000, 'Internal Error') + } + } + + /** + * Builds a "FalloutHandler" request and stores it in the specified execution variable. + * + * @param execution the execution + * @param resultVar the execution variable in which the result will be stored + */ + public void falloutHandlerPrep(DelegateExecution execution, String resultVar) { + def method = getClass().getSimpleName() + '.falloutHandlerPrep(' + + 'execution=' + execution.getId() + + ', resultVar=' + resultVar + + ')' + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + msoLogger.trace('Entered ' + method) + + try { + def prefix = execution.getVariable('prefix') + def request = execution.getVariable("DeleteVfModuleRequest") + def requestInfo = utils.getNodeXml(request, 'request-info', false) + def WorkflowException workflowException = execution.getVariable("WorkflowException") + def errorResponseCode = workflowException.getErrorCode() + def errorResponseMsg = workflowException.getErrorMessage() + def encErrorResponseMsg = "" + if (errorResponseMsg != null) { + encErrorResponseMsg = errorResponseMsg + } + + String content = """ + <sdncadapterworkflow:FalloutHandlerRequest xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1" + xmlns:reqtype="http://org.onap/so/request/types/v1" + xmlns:msoservtypes="http://org.onap/so/request/types/v1" + xmlns:structuredtypes="http://org.onap/so/structured/types/v1"> + ${requestInfo} + <sdncadapterworkflow:WorkflowException> + <sdncadapterworkflow:ErrorMessage>${MsoUtils.xmlEscape(encErrorResponseMsg)}</sdncadapterworkflow:ErrorMessage> + <sdncadapterworkflow:ErrorCode>${MsoUtils.xmlEscape(errorResponseCode)}</sdncadapterworkflow:ErrorCode> + </sdncadapterworkflow:WorkflowException> + </sdncadapterworkflow:FalloutHandlerRequest> + """ + content = utils.formatXml(content) + msoLogger.debug(resultVar + ' = ' + System.lineSeparator() + content) + execution.setVariable(resultVar, content) + + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildWorkflowException(execution, 2000, 'Internal Error') + } + } +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteVfModuleVolumeInfraV1.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteVfModuleVolumeInfraV1.groovy new file mode 100644 index 0000000000..2cbfeac239 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteVfModuleVolumeInfraV1.groovy @@ -0,0 +1,545 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts; + +import org.apache.commons.lang3.* +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.onap.so.bpmn.common.scripts.AaiUtil; +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor; +import org.onap.so.bpmn.common.scripts.ExceptionUtil; +import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.so.bpmn.common.scripts.VidUtils; +import org.onap.so.bpmn.core.UrnPropertiesReader +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.logger.MessageEnum +import org.onap.so.logger.MsoLogger +import org.onap.so.rest.APIResponse +import org.springframework.web.util.UriUtils + +import groovy.json.JsonSlurper + +/** + * This groovy class supports the <class>DeleteVfModuleVolume.bpmn</class> process. + */ +public class DeleteVfModuleVolumeInfraV1 extends AbstractServiceTaskProcessor { + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DeleteVfModuleVolumeInfraV1.class); + + private XmlParser xmlParser = new XmlParser() + /** + * This method is executed during the preProcessRequest task of the <class>DeleteVfModuleVolume.bpmn</class> process. + * @param execution + */ + public InitializeProcessVariables(DelegateExecution execution){ + execution.setVariable('prefix', 'DELVfModVol_') + execution.setVariable("DELVfModVol_volumeRequest", null) + execution.setVariable('DELVfModVol_requestInfo', null) + execution.setVariable('DELVfModVol_requestId', null) + execution.setVariable('DELVfModVol_source', null) + execution.setVariable('DELVfModVol_volumeInputs', null) + execution.setVariable('DELVfModVol_volumeOutputs', null) + execution.setVariable('DELVfModVol_volumeGroupId', null) + execution.setVariable('DELVfModVol_vnfType', null) + execution.setVariable('DELVfModVol_serviceId', null) + execution.setVariable('DELVfModVol_cloudRegion', null) + execution.setVariable('DELVfModVol_tenantId', null) + execution.setVariable('DELVfModVol_volumeParams', null) + execution.setVariable('DELVfModVol_volumeGroupHeatStackId', null) + execution.setVariable('DELVfModVol_volumeGroupTenantId', null) + execution.setVariable("DELVfModVol_queryAAIVolGrpResponse", null) + execution.setVariable('DELVfModVol_messageId', null) + execution.setVariable('DELVfModVol_deleteVnfARequest', null) + execution.setVariable('DELVfModVol_updateInfraRequest', null) + execution.setVariable('DELVfModVol_CompleteMsoProcessRequest', null) + execution.setVariable('DELVfModVol_WorkflowException', null) + execution.setVariable('DELVfModVol_TransactionSuccessIndicator', false) + execution.setVariable("DELVfModVol_isErrorMessageException", false) + execution.setVariable('DELVfModVol_syncResponseSent', false) + } + + /** + * Perform initial processing, such as request validation, initialization of variables, etc. + * * @param execution + */ + public void preProcessRequest (DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + preProcessRequest(execution, isDebugEnabled) + } + + /** + * This method is executed during the preProcessRequest task of the <class>DeleteVfModuleVolume.bpmn</class> process. + * @param execution + */ + public void preProcessRequest (DelegateExecution execution, isDebugLogEnabled) { + + InitializeProcessVariables(execution) + + String createVolumeIncoming = validateRequest(execution) + + // check if request is xml or json + try { + def jsonSlurper = new JsonSlurper() + Map reqMap = jsonSlurper.parseText(createVolumeIncoming) + msoLogger.debug(" Request is in JSON format.") + + def serviceInstanceId = execution.getVariable('serviceInstanceId') + def volumeGroupId = execution.getVariable('volumeGroupId') + def vidUtils = new VidUtils(this) + createVolumeIncoming = vidUtils.createXmlVolumeRequest(reqMap, 'DELETE_VF_MODULE_VOL', serviceInstanceId, volumeGroupId) + execution.setVariable("DELVfModVol_isVidRequest", true) + } + catch(groovy.json.JsonException je) { + msoLogger.debug(" Request is in XML format.") + // assume request is in XML format - proceed as usual to process XML request + } + + String request = utils.getNodeXml(createVolumeIncoming, "volume-request").drop(38).trim().replace("tag0:","").replace(":tag0","") + execution.setVariable("DELVfModVol_volumeRequest", request) + + def requestInfo = getRequiredNodeXml(execution, request, 'request-info') + execution.setVariable('DELVfModVol_requestInfo', requestInfo) + String requestId = execution.getVariable("mso-request-id") + if (requestId == null || requestId == "") { + requestId = getRequiredNodeText(execution, requestInfo, 'request-id') + } + execution.setVariable('DELVfModVol_requestId', requestId) + execution.setVariable('DELVfModVol_source', getNodeTextForce(requestInfo, 'source')) + + def volumeInputs = getRequiredNodeXml(execution, request, 'volume-inputs') + execution.setVariable('DELVfModVol_volumeInputs', volumeInputs) + execution.setVariable('DELVfModVol_volumeGroupId', getRequiredNodeText(execution, volumeInputs, 'volume-group-id')) + execution.setVariable('DELVfModVol_vnfType', getRequiredNodeText(execution, volumeInputs, 'vnf-type')) + execution.setVariable('DELVfModVol_serviceId', utils.getNodeText(volumeInputs, 'service-id')) + execution.setVariable('DELVfModVol_tenantId', getRequiredNodeText(execution, volumeInputs, 'tenant-id')) + execution.setVariable('DELVfModVol_messageId', UUID.randomUUID().toString()) + execution.setVariable('DELVfModVol_volumeOutputs', utils.getNodeXml(request, 'volume-outputs', false)) + execution.setVariable('DELVfModVol_volumeParams', utils.getNodeXml(request, 'volume-params')) + execution.setVariable('DELVfModVol_cloudRegion', utils.getNodeText(request, 'aic-cloud-region')) + + setBasicDBAuthHeader(execution, isDebugLogEnabled) + + msoLogger.debug('Request: ' + createVolumeIncoming) + } + + public void sendSyncResponse (DelegateExecution execution, isDebugEnabled) { + + String volumeRequest = execution.getVariable("DELVfModVol_volumeRequest") + msoLogger.debug(" DELVfModVol_volumeRequest - " + "\n" + volumeRequest) + // RESTResponse (for API Handler (APIH) Reply Task) + String deleteVolumeRequest = + """<rest:RESTResponse xmlns:rest="http://schemas.activebpel.org/REST/2007/12/01/aeREST.xsd" statusCode="200"> + <rest:payload xmlns:rest="http://schemas.activebpel.org/REST/2007/12/01/aeREST.xsd" + contentType="text/xml"> + ${volumeRequest} + </rest:payload> + </rest:RESTResponse>""".trim() + + def isVidRequest = execution.getVariable('DELVfModVol_isVidRequest') + def syncResponse = '' + + if(isVidRequest) { + def serviceInstanceId = execution.getVariable('serviceInstanceId') + def volumeGroupId = execution.getVariable('volumeGroupId') + def requestId = execution.getVariable('DELVfModVol_requestId') + syncResponse = """{"requestReferences":{"instanceId":"${volumeGroupId}","requestId":"${requestId}"}}""".trim() + } + else { + syncResponse = utils.formatXml(deleteVolumeRequest) + } + + execution.setVariable('DELVfModVol_syncResponseSent', true) + + sendWorkflowResponse(execution, 200, syncResponse) + } + + + public void sendSyncError (DelegateExecution execution, isDebugEnabled) { + WorkflowException we = execution.getVariable('WorkflowException') + def errorCode = we?.getErrorCode() + def errorMessage = we?.getErrorMessage() + //default to 400 since only invalid request will trigger this method + sendWorkflowResponse(execution, 400, errorMessage) + } + + + public void callRESTQueryAAICloudRegion (DelegateExecution execution, isDebugEnabled) { + + String cloudRegion = execution.getVariable('DELVfModVol_cloudRegion') + + String aai_endpoint = UrnPropertiesReader.getVariable("aai.endpoint", execution) + AaiUtil aaiUtil = new AaiUtil(this) + String aai_uri = aaiUtil.getCloudInfrastructureCloudRegionUri(execution) + String queryCloudRegionRequest = "${aai_endpoint}${aai_uri}/" + cloudRegion + execution.setVariable("DELVfModVol_queryCloudRegionRequest", queryCloudRegionRequest) + msoLogger.debug(" DELVfModVol_queryCloudRegionRequest - " + "\n" + queryCloudRegionRequest) + + cloudRegion = aaiUtil.getAAICloudReqion(execution, queryCloudRegionRequest, "PO", cloudRegion) + + ExceptionUtil exceptionUtil = new ExceptionUtil() + + if ((cloudRegion != "ERROR")) { + if(execution.getVariable("DELVfModVol_queryCloudRegionReturnCode") == "404"){ + execution.setVariable("DELVfModVol_aicCloudRegion", "AAIAIC25") + }else{ + execution.setVariable("DELVfModVol_aicCloudRegion", cloudRegion) + } + execution.setVariable("DELVfModVol_cloudRegion", cloudRegion) + execution.setVariable("DELVfModVol_isCloudRegionGood", true) + + } else { + msoLogger.debug("AAI Query Cloud Region Unsuccessful.") + execution.setVariable("DELVfModVol_isCloudRegionGood", false) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "AAI Query Cloud Region Unsuccessful. Return Code: " + execution.getVariable("DELVfModVol_queryCloudRegionReturnCode")) + } + + msoLogger.debug(" is Cloud Region Good: " + execution.getVariable("DELVfModVol_isCloudRegionGood")) + } + + /** + * Query volume group by id + * @param execution + */ + public void queryAAIForVolumeGroup(DelegateExecution execution, isDebugLogEnabled) { + + ExceptionUtil exceptionUtil = new ExceptionUtil() + + def volumeGroupId = execution.getVariable('DELVfModVol_volumeGroupId') + if(volumeGroupId == null) { + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, 'volume-group-id is not provided in the request') + throw new Exception('volume-group-id is not provided in the request') + } + String cloudRegion = execution.getVariable('DELVfModVol_aicCloudRegion') + + AaiUtil aaiUtil = new AaiUtil(this) + String aaiEndpoint = aaiUtil.getCloudInfrastructureCloudRegionEndpoint(execution) + String queryAAIVolumeGroupRequest = aaiEndpoint + '/' + URLEncoder.encode(cloudRegion, "UTF-8") + "/volume-groups/volume-group/" + UriUtils.encode(volumeGroupId, "UTF-8") + + msoLogger.debug('Query AAI volume group by ID: ' + queryAAIVolumeGroupRequest) + + APIResponse response = aaiUtil.executeAAIGetCall(execution, queryAAIVolumeGroupRequest) + + String returnCode = response.getStatusCode() + String aaiResponseAsString = response.getResponseBodyAsString() + + msoLogger.debug("AAI query volume group by id return code: " + returnCode) + msoLogger.debug("AAI query volume group by id response: " + aaiResponseAsString) + + execution.setVariable("DELVfModVol_queryAAIVolGrpResponse", aaiResponseAsString) + + if (returnCode=='200' || returnCode == '204') { + + def heatStackId = getNodeTextForce(aaiResponseAsString, 'heat-stack-id') + execution.setVariable('DELVfModVol_volumeGroupHeatStackId', heatStackId) + + if(hasVfModuleRelationship(aaiResponseAsString)){ + msoLogger.debug('Volume Group ' + volumeGroupId + ' currently in use') + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Volume Group ${volumeGroupId} currently in use - found vf-module relationship.") + } + + def volumeGroupTenantId = getTenantIdFromVolumeGroup(aaiResponseAsString) + if (volumeGroupTenantId == null) { + msoLogger.debug("Could not find Tenant Id element in Volume Group with Volume Group Id ${volumeGroupId}") + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Could not find Tenant Id element in Volume Group with Volume Group Id ${volumeGroupId}") + } + + execution.setVariable('DELVfModVol_volumeGroupTenantId', volumeGroupTenantId) + msoLogger.debug('Received Tenant Id ' + volumeGroupTenantId + ' from AAI for Volume Group with Volume Group Id ' + volumeGroupId ) + } + else { + if (returnCode=='404') { + msoLogger.debug("Volume Group ${volumeGroupId} not found in AAI") + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Volume Group ${volumeGroupId} not found in AAI. Response code: 404") + } + else { + WorkflowException aWorkflowException = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) + throw new BpmnError("MSOWorkflowException") + } + } + } + + /** + * Extract the Tenant Id from the Volume Group information returned by AAI. + * + * @param volumeGroupXml Volume Group XML returned by AAI. + * @return the Tenant Id extracted from the Volume Group information. 'null' is returned if + * the Tenant Id is missing or could not otherwise be extracted. + */ + private String getTenantIdFromVolumeGroup(String volumeGroupXml) { + def Node volumeGroupNode = xmlParser.parseText(volumeGroupXml) + def Node relationshipList = utils.getChildNode(volumeGroupNode, 'relationship-list') + if (relationshipList != null) { + def NodeList relationships = utils.getIdenticalChildren(relationshipList, 'relationship') + for (Node relationship in relationships) { + def Node relatedTo = utils.getChildNode(relationship, 'related-to') + if ((relatedTo != null) && (relatedTo.text().equals('tenant'))) { + def NodeList relationshipDataList = utils.getIdenticalChildren(relationship, 'relationship-data') + for (Node relationshipData in relationshipDataList) { + def Node relationshipKey = utils.getChildNode(relationshipData, 'relationship-key') + if ((relationshipKey != null) && (relationshipKey.text().equals('tenant.tenant-id'))) { + def Node relationshipValue = utils.getChildNode(relationshipData, 'relationship-value') + if (relationshipValue != null) { + return relationshipValue.text() + } + } + } + } + } + } + return null + } + + private boolean hasVnfRelationship(String volumeGroupXml) { + def Node volumeGroupNode = xmlParser.parseText(volumeGroupXml) + def Node relationshipList = utils.getChildNode(volumeGroupNode, 'relationship-list') + if (relationshipList != null) { + def NodeList relationships = utils.getIdenticalChildren(relationshipList, 'relationship') + for (Node relationship in relationships) { + def Node relatedTo = utils.getChildNode(relationship, 'related-to') + if ((relatedTo != null) && (relatedTo.text().equals('generic-vnf'))) { + def Node relatedLink = utils.getChildNode(relationship, 'related-link') + if (relatedLink !=null && relatedLink.text() != null){ + return true + } + } + } + } + return false + } + + private boolean hasVfModuleRelationship(String volumeGroupXml) { + def Node volumeGroupNode = xmlParser.parseText(volumeGroupXml) + def Node relationshipList = utils.getChildNode(volumeGroupNode, 'relationship-list') + if (relationshipList != null) { + def NodeList relationships = utils.getIdenticalChildren(relationshipList, 'relationship') + for (Node relationship in relationships) { + def Node relatedTo = utils.getChildNode(relationship, 'related-to') + if ((relatedTo != null) && (relatedTo.text().equals('vf-module'))) { + def Node relatedLink = utils.getChildNode(relationship, 'related-link') + if (relatedLink !=null && relatedLink.text() != null){ + return true + } + } + } + } + return false + } + + public void prepareVnfAdapterDeleteRequest(DelegateExecution execution, isDebugLogEnabled) { + def cloudRegion = execution.getVariable('DELVfModVol_cloudRegion') + def tenantId = execution.getVariable('DELVfModVol_tenantId') + def volumeGroupId = execution.getVariable('DELVfModVol_volumeGroupId') + def volumeGroupHeatStackId = execution.getVariable('DELVfModVol_volumeGroupHeatStackId') + def requestId = execution.getVariable('DELVfModVol_requestId') + def serviceId = execution.getVariable('DELVfModVol_serviceId') + + def messageId = execution.getVariable('DELVfModVol_messageId') + def notificationUrl = createCallbackURL(execution, "VNFAResponse", messageId) + def useQualifiedHostName = UrnPropertiesReader.getVariable("mso.use.qualified.host", execution) + if ('true'.equals(useQualifiedHostName)) { + notificationUrl = utils.getQualifiedHostNameForCallback(notificationUrl) + } + + String vnfAdapterRestRequest = """ + <deleteVolumeGroupRequest> + <cloudSiteId>${MsoUtils.xmlEscape(cloudRegion)}</cloudSiteId> + <tenantId>${MsoUtils.xmlEscape(tenantId)}</tenantId> + <volumeGroupId>${MsoUtils.xmlEscape(volumeGroupId)}</volumeGroupId> + <volumeGroupStackId>${MsoUtils.xmlEscape(volumeGroupHeatStackId)}</volumeGroupStackId> + <skipAAI>true</skipAAI> + <msoRequest> + <requestId>${MsoUtils.xmlEscape(requestId)}</requestId> + <serviceInstanceId>${MsoUtils.xmlEscape(serviceId)}</serviceInstanceId> + </msoRequest> + <messageId>${MsoUtils.xmlEscape(messageId)}</messageId> + <notificationUrl>${MsoUtils.xmlEscape(notificationUrl)}</notificationUrl> + </deleteVolumeGroupRequest> + """ + vnfAdapterRestRequest = utils.formatXml(vnfAdapterRestRequest) + execution.setVariable('DELVfModVol_deleteVnfARequest', vnfAdapterRestRequest) + msoLogger.debug('Request for VNFAdapter Rest:\n' + vnfAdapterRestRequest) + } + + + public void deleteVolGrpId(DelegateExecution execution, isDebugEnabled) { + + // get variables + String queryAAIVolGrpIdResponse = execution.getVariable("DELVfModVol_queryAAIVolGrpResponse") + String groupId = utils.getNodeText(queryAAIVolGrpIdResponse, "volume-group-id") + String resourceVersion = utils.getNodeText(queryAAIVolGrpIdResponse, "resource-version") + String messageId = execution.getVariable('DELVfModVol_messageId') + String cloudRegion = execution.getVariable('DELVfModVol_aicCloudRegion') + + AaiUtil aaiUtil = new AaiUtil(this) + String aaiEndpoint = aaiUtil.getCloudInfrastructureCloudRegionEndpoint(execution) + String deleteAAIVolumeGrpIdRequest = aaiEndpoint + '/' + URLEncoder.encode(cloudRegion, "UTF-8") + "/volume-groups/volume-group/" + UriUtils.encode(groupId, "UTF-8") + + if(resourceVersion !=null){ + deleteAAIVolumeGrpIdRequest = deleteAAIVolumeGrpIdRequest +'?resource-version=' + UriUtils.encode(resourceVersion, 'UTF-8') + } + + msoLogger.debug("Delete AAI volume group : " + deleteAAIVolumeGrpIdRequest) + + APIResponse response = aaiUtil.executeAAIDeleteCall(execution, deleteAAIVolumeGrpIdRequest) + + String returnCode = response.getStatusCode() + String aaiResponseAsString = response.getResponseBodyAsString() + + msoLogger.debug("AAI delete volume group return code: " + returnCode) + msoLogger.debug("AAI delete volume group response: " + aaiResponseAsString) + + ExceptionUtil exceptionUtil = new ExceptionUtil() + if (returnCode=='200' || (returnCode == '204')) { + msoLogger.debug("Volume group $groupId deleted.") + } else { + if (returnCode=='404') { + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Volume group $groupId not found for delete in AAI Response code: 404") + } else { + WorkflowException aWorkflowException = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) + throw new BpmnError("MSOWorkflowException") + } + } + } + + + public void prepareDBRequest (DelegateExecution execution, isDebugLogEnabled) { + + WorkflowException workflowExceptionObj = execution.getVariable("WorkflowException") + ExceptionUtil exceptionUtil = new ExceptionUtil(); + def requestId = execution.getVariable('DELVfModVol_requestId') + def volOutputs = execution.getVariable('DELVfModVol_volumeOutputs') + def statusMessage = "VolumeGroup successfully deleted" + def progress = "100" + def requestStatus = "COMPLETE" + + if (workflowExceptionObj != null) { + statusMessage = (workflowExceptionObj.getErrorMessage()) + execution.setVariable("DELVfModVol_WorkflowExceptionMessage", statusMessage) + execution.setVariable("DELVfModVol_WorkflowExceptionCode", workflowExceptionObj.getErrorCode()) + requestStatus = "FAILURE" + progress = "" + } + + String updateInfraRequest = """ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" + xmlns:req="http://org.onap.so/requestsdb"> + <soapenv:Header/> + <soapenv:Body> + <req:updateInfraRequest> + <requestId>${MsoUtils.xmlEscape(requestId)}</requestId> + <lastModifiedBy>BPMN</lastModifiedBy> + <statusMessage>${MsoUtils.xmlEscape(statusMessage)}</statusMessage> + <requestStatus>${MsoUtils.xmlEscape(requestStatus)}</requestStatus> + <progress>${MsoUtils.xmlEscape(progress)}</progress> + <vnfOutputs>${MsoUtils.xmlEscape(volOutputs)}</vnfOutputs> + </req:updateInfraRequest> + </soapenv:Body> + </soapenv:Envelope> + """ + + updateInfraRequest = utils.formatXml(updateInfraRequest) + execution.setVariable('DELVfModVol_updateInfraRequest', updateInfraRequest) + msoLogger.debug('Request for Update Infra Request:\n' + updateInfraRequest) + + } + + + public void prepareCompletionHandlerRequest (DelegateExecution execution, isDebugLogEnabled) { + def requestId = execution.getVariable("mso-request-id") + def source = execution.getVariable("DELVfModVol_source") + + String msoCompletionRequest = + """<aetgt:MsoCompletionRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:ns="http://org.onap/so/request/types/v1"> + <request-info xmlns="http://org.onap/so/infra/vnf-request/v1"> + <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> + <action>DELETE</action> + <source>${MsoUtils.xmlEscape(source)}</source> + </request-info> + <aetgt:status-message>Volume Group has been deleted successfully.</aetgt:status-message> + <aetgt:mso-bpel-name>BPMN VF Module Volume action: DELETE</aetgt:mso-bpel-name> + </aetgt:MsoCompletionRequest>""" + + String xmlMsoCompletionRequest = utils.formatXml(msoCompletionRequest) + execution.setVariable('DELVfModVol_CompleteMsoProcessRequest', xmlMsoCompletionRequest) + msoLogger.debug(" Overall SUCCESS Response going to CompleteMsoProcess - " + "\n" + xmlMsoCompletionRequest) + + } + + + + public void prepareFalloutHandler (DelegateExecution execution, isDebugEnabled) { + + execution.setVariable("DELVfModVol_Success", false) + String requestId = execution.getVariable("DELVfModVol_requestId") + String source = execution.getVariable("DELVfModVol_source") + + WorkflowException workflowExceptionObj = execution.getVariable("WorkflowException") + def errorMessage = workflowExceptionObj.getErrorMessage() + def errorCode = workflowExceptionObj.getErrorCode() + + String falloutHandlerRequest = + """<aetgt:FalloutHandlerRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:ns="http://org.onap/so/request/types/v1" + xmlns:wfsch="http://org.onap/so/workflow/schema/v1"> + <request-info xmlns="http://org.onap/so/infra/vnf-request/v1"> + <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> + <action>DELETE</action> + <source>${MsoUtils.xmlEscape(source)}</source> + </request-info> + <aetgt:WorkflowException> + <aetgt:ErrorMessage>${MsoUtils.xmlEscape(errorMessage)}</aetgt:ErrorMessage> + <aetgt:ErrorCode>${MsoUtils.xmlEscape(errorCode)}</aetgt:ErrorCode> + </aetgt:WorkflowException> + </aetgt:FalloutHandlerRequest>""" + + // Format Response + String xmlHandlerRequest = utils.formatXml(falloutHandlerRequest) + msoLogger.debug(xmlHandlerRequest) + + execution.setVariable("DELVfModVol_FalloutHandlerRequest", xmlHandlerRequest) + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, " Overall Error Response going to FalloutHandler", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "\n" + xmlHandlerRequest); + + } + + + /** + * Create a WorkflowException for the error case where the Tenant Id from + * AAI did not match the Tenant Id in the incoming request. + * + * @param execution The flow's execution instance. + */ + public void handleTenantIdMismatch(DelegateExecution execution, isDebugLogEnabled) { + + def volumeGroupId = execution.getVariable('DELVfModVol_volumeGroupId') + def aicCloudRegion = execution.getVariable('DELVfModVol_aicCloudRegion') + def tenantId = execution.getVariable('DELVfModVol_tenantId') + def volumeGroupTenantId = execution.getVariable('DELVfModVol_volumeGroupTenantId') + + def String errorMessage = 'TenantId ' + tenantId + ' in incoming request does not match Tenant Id ' + volumeGroupTenantId + + ' retrieved from AAI for Volume Group Id ' + volumeGroupId + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Error in DeleteVfModuleVolume: " + "\n" + errorMessage, "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError); + + ExceptionUtil exceptionUtil = new ExceptionUtil() + exceptionUtil.buildWorkflowException(execution, 5000, errorMessage) + + } + +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteVnfInfra.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteVnfInfra.groovy new file mode 100644 index 0000000000..9dfb9107b2 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteVnfInfra.groovy @@ -0,0 +1,207 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts + + +import org.apache.commons.lang3.* +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor; +import org.onap.so.bpmn.common.scripts.ExceptionUtil; +import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.so.bpmn.common.scripts.VidUtils; +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.bpmn.core.json.JsonUtils; +import org.onap.so.logger.MsoLogger + + +/** + * This class supports the DeleteVnfInfra Flow + * with the Deletion of a generic vnf for + * infrastructure. + */ +class DeleteVnfInfra extends AbstractServiceTaskProcessor { + + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DeleteVnfInfra.class); + + String Prefix="DELVI_" + ExceptionUtil exceptionUtil = new ExceptionUtil() + JsonUtils jsonUtil = new JsonUtils() + VidUtils vidUtils = new VidUtils(this) + + /** + * This method gets and validates the incoming + * request. + * + * @param - execution + */ + public void preProcessRequest(DelegateExecution execution) { + execution.setVariable("prefix",Prefix) + msoLogger.trace("STARTED DeleteVnfInfra PreProcessRequest Process") + + execution.setVariable("DELVI_SuccessIndicator", false) + execution.setVariable("DELVI_vnfInUse", false) + + try{ + // Get Variables + String deleteVnfRequest = execution.getVariable("bpmnRequest") + execution.setVariable("DELVI_DeleteVnfRequest", deleteVnfRequest) + msoLogger.debug("Incoming DeleteVnfInfra Request is: \n" + deleteVnfRequest) + + if(deleteVnfRequest != null){ + + String requestId = execution.getVariable("mso-request-id") + execution.setVariable("DELVI_requestId", requestId) + + String serviceInstanceId = execution.getVariable("serviceInstanceId") + execution.setVariable("DELVI_serviceInstanceId", serviceInstanceId) + msoLogger.debug("Incoming Service Instance Id is: " + serviceInstanceId) + + String vnfId = execution.getVariable("vnfId") + execution.setVariable("DELVI_vnfId", vnfId) + msoLogger.debug("Incoming Vnf(Instance) Id is: " + vnfId) + + String source = jsonUtil.getJsonValue(deleteVnfRequest, "requestDetails.requestInfo.source") + execution.setVariable("DELVI_source", source) + msoLogger.debug("Incoming Source is: " + source) + + def cloudConfiguration = jsonUtil.getJsonValue(deleteVnfRequest, "requestDetails.cloudConfiguration") + execution.setVariable("DELVI_cloudConfiguration", cloudConfiguration) + + boolean cascadeDelete = false + Boolean cascadeDeleteObj = jsonUtil.getJsonRawValue(deleteVnfRequest, "requestDetails.requestParameters.cascadeDelete") + if(cascadeDeleteObj!=null){ + cascadeDelete = cascadeDeleteObj.booleanValue() + } + execution.setVariable("DELVI_cascadeDelete", cascadeDelete) + msoLogger.debug("Incoming cascadeDelete is: " + cascadeDelete) + + //For Completion Handler & Fallout Handler + String requestInfo = + """<request-info xmlns="http://org.onap/so/infra/vnf-request/v1"> + <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> + <action>DELETE</action> + <source>${MsoUtils.xmlEscape(source)}</source> + </request-info>""" + + execution.setVariable("DELVI_requestInfo", requestInfo) + + // Setting for sub flow calls + execution.setVariable("DELVI_type", "generic-vnf") + + }else{ + exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Incoming Bpmn Request is Null.") + } + + }catch(BpmnError b){ + msoLogger.debug("Rethrowing MSOWorkflowException") + throw b + }catch(Exception e){ + msoLogger.debug(" Error Occured in DeleteVnfInfra PreProcessRequest method!" + e) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in DeleteVnfInfra PreProcessRequest") + + } + msoLogger.trace("COMPLETED DeleteVnfInfra PreProcessRequest Process") + } + + public void sendSyncResponse (DelegateExecution execution) { + execution.setVariable("prefix",Prefix) + + msoLogger.trace("STARTED DeleteVnfInfra SendSyncResponse Process") + + try { + String requestId = execution.getVariable("DELVI_requestId") + String vnfId = execution.getVariable("DELVI_vnfId") + + String DeleteVnfResponse = """{"requestReferences":{"instanceId":"${vnfId}","requestId":"${requestId}"}}""".trim() + + msoLogger.debug("DeleteVnfInfra Sync Response is: \n" + DeleteVnfResponse) + execution.setVariable("DELVI_sentSyncResponse", true) + + sendWorkflowResponse(execution, 202, DeleteVnfResponse) + + } catch (Exception ex) { + msoLogger.debug("Error Occured in DeleteVnfInfra SendSyncResponse Process " + ex.getMessage()) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in DeleteVnfInfra SendSyncResponse Process") + + } + msoLogger.trace("COMPLETED DeleteVnfInfra SendSyncResponse Process") + } + + public void prepareCompletionHandlerRequest(DelegateExecution execution){ + execution.setVariable("prefix",Prefix) + + msoLogger.trace("STARTED DeleteVnfInfra PrepareCompletionHandlerRequest Process") + + try { + String requestInfo = execution.getVariable("DELVI_requestInfo") + requestInfo = utils.removeXmlPreamble(requestInfo) + String vnfId = execution.getVariable("DELVI_vnfId") + + String request = + """<aetgt:MsoCompletionRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:ns="http://org.onap/so/request/types/v1"> + ${requestInfo} + <status-message>Vnf has been deleted successfully.</status-message> + <vnfId>${MsoUtils.xmlEscape(vnfId)}</vnfId> + <mso-bpel-name>DeleteVnfInfra</mso-bpel-name> + </aetgt:MsoCompletionRequest>""" + + execution.setVariable("DELVI_completionHandlerRequest", request) + msoLogger.debug("Completion Handler Request is: " + request) + + execution.setVariable("WorkflowResponse", "Success") // for junits + + } catch (Exception ex) { + msoLogger.debug("Error Occured in DeleteVnfInfra PrepareCompletionHandlerRequest Process " + ex.getMessage()) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in DeleteVnfInfra PrepareCompletionHandlerRequest Process") + + } + msoLogger.trace("COMPLETED DeleteVnfInfra PrepareCompletionHandlerRequest Process") + } + + public void sendErrorResponse(DelegateExecution execution){ + execution.setVariable("prefix",Prefix) + + msoLogger.trace("STARTED DeleteVnfInfra sendErrorResponse Process") + try { + def sentSyncResponse = execution.getVariable("DELVI_sentSyncResponse") + if(sentSyncResponse == false){ + msoLogger.debug("Sending a Sync Error Response") + WorkflowException wfex = execution.getVariable("WorkflowException") + String response = exceptionUtil.buildErrorResponseXml(wfex) + + msoLogger.debug(response) + sendWorkflowResponse(execution, 500, response) + }else{ + msoLogger.debug("A Sync Response has already been sent. Skipping Send Sync Error Response.") + } + + } catch(Exception ex) { + msoLogger.debug("Error Occured in DeleteVnfInfra sendErrorResponse Process " + ex.getMessage()) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in DeleteVnfInfra sendErrorResponse Process") + } + msoLogger.trace("COMPLETED DeleteVnfInfra sendErrorResponse Process") + } + + + +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCompareModelVersions.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCompareModelVersions.groovy new file mode 100644 index 0000000000..98605fea8b --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCompareModelVersions.groovy @@ -0,0 +1,258 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2018 Huawei Technologies Co., Ltd. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.so.bpmn.infrastructure.scripts; + +import static org.apache.commons.lang3.StringUtils.*; +import groovy.xml.XmlUtil +import groovy.json.* + +import org.onap.so.bpmn.core.domain.ServiceDecomposition +import org.onap.so.bpmn.core.domain.ServiceInstance +import org.onap.so.bpmn.core.domain.ModelInfo +import org.onap.so.bpmn.core.domain.Resource +import org.onap.so.bpmn.core.domain.AllottedResource +import org.onap.so.bpmn.core.domain.NetworkResource +import org.onap.so.bpmn.core.domain.VnfResource +import org.onap.so.bpmn.common.recipe.ResourceInput +import org.onap.so.bpmn.common.recipe.BpmnRestClient +import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.bpmn.common.scripts.AaiUtil +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.onap.so.bpmn.common.scripts.ExceptionUtil +import org.onap.so.bpmn.common.scripts.SDNCAdapterUtils +import org.onap.so.bpmn.common.scripts.CatalogDbUtils; +import org.onap.so.bpmn.core.RollbackData +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.rest.APIResponse; +import org.onap.so.rest.RESTClient +import org.onap.so.rest.RESTConfig + +import java.util.List; +import java.util.UUID; + +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.runtime.Execution +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.json.JSONObject; +import org.json.JSONArray; +import org.apache.commons.lang3.* +import org.apache.commons.codec.binary.Base64; +import org.springframework.web.util.UriUtils; +import org.onap.so.logger.MessageEnum +import org.onap.so.logger.MsoLogger + + + +/** + * This groovy class supports the <class>DoCompareModelVersions.bpmn</class> process. + * + * Inputs: + * @param - model-invariant-id-target + * @param - model-version-id-target + * @param - model-invariant-id-original + * @param - model-version-id-original + * + * Outputs: + * @param - addResourceList + * @param - delResourceList + * + */ +public class DoCompareModelVersions extends AbstractServiceTaskProcessor { + + String Prefix="DCMPMDV_" + ExceptionUtil exceptionUtil = new ExceptionUtil() + JsonUtils jsonUtil = new JsonUtils() + CatalogDbUtils cutils = new CatalogDbUtils() + + public void preProcessRequest (DelegateExecution execution) { + def isDebugEnabled = execution.getVariable("isDebugLogEnabled") + String msg = "" + utils.log("INFO"," ***** preProcessRequest *****", isDebugEnabled) + + try { + execution.setVariable("prefix", Prefix) + + //Inputs + String modelInvariantUuid_target = execution.getVariable("model-invariant-id-target") + if (isBlank(modelInvariantUuid_target)) { + msg = "Input model-invariant-id-target is null" + utils.log("INFO", msg, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + + String modelUuid_target = execution.getVariable("model-version-id-target") + if (isBlank(modelUuid_target)) { + msg = "Input model-version-id-target is null" + utils.log("INFO", msg, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + + String modelInvariantUuid_original = execution.getVariable("model-invariant-id-original") + if (isBlank(modelInvariantUuid_original)) { + msg = "Input model-invariant-id-original is null" + utils.log("INFO", msg, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + + String modelUuid_original = execution.getVariable("model-version-id-original") + if (isBlank(modelUuid_original)) { + msg = "Input model-version-id-original is null" + utils.log("INFO", msg, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + + // Target and original modelInvariantUuid must to be the same + if(modelInvariantUuid_target != modelInvariantUuid_original){ + msg = "Input model-invariant-id-target and model-invariant-id-original must to be the same" + utils.log("INFO", msg, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + + // Target and original modelUuid must not to be the same + if(modelUuid_target == modelUuid_original){ + msg = "Input model-version-id-target and model-version-id-original must not to be the same" + utils.log("INFO", msg, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + + } catch (Exception ex){ + msg = "Exception in preProcessRequest " + ex.getMessage() + utils.log("INFO", msg, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + utils.log("INFO"," ***** Exit preProcessRequest *****", isDebugEnabled) + } + + public void prepareDecomposeService_Target(DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + + try { + utils.log("DEBUG", " ***** Inside prepareDecomposeService_Target of update generic e2e service ***** ", isDebugEnabled) + String modelInvariantUuid = execution.getVariable("model-invariant-id-target") + String modelUuid = execution.getVariable("model-version-id-target") + //here modelVersion is not set, we use modelUuid to decompose the service. + String serviceModelInfo = """{ + "modelInvariantUuid":"${modelInvariantUuid}", + "modelUuid":"${modelUuid}", + "modelVersion":"" + }""" + + execution.setVariable("serviceModelInfo_Target", serviceModelInfo) + + utils.log("DEBUG", " ***** Completed prepareDecomposeService_Target of update generic e2e service ***** ", isDebugEnabled) + } catch (Exception ex) { + // try error in method block + String exceptionMessage = "Bpmn error encountered in update generic e2e service flow. Unexpected Error from method prepareDecomposeService_Target() - " + ex.getMessage() + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + } + } + + public void processDecomposition_Target(DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + + utils.log("DEBUG", " ***** Inside processDecomposition_Target() of update generic e2e service flow ***** ", isDebugEnabled) + try { + ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition") + execution.setVariable("serviceDecomposition_Target", serviceDecomposition) + } catch (Exception ex) { + String exceptionMessage = "Bpmn error encountered in update generic e2e service flow. Unexpected Error from method processDecomposition_Target() - " + ex.getMessage() + utils.log("DEBUG", exceptionMessage, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + } + } + + public void prepareDecomposeService_Original(DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + + try { + utils.log("DEBUG", " ***** Inside prepareDecomposeService_Original of update generic e2e service ***** ", isDebugEnabled) + String modelInvariantUuid = execution.getVariable("model-invariant-id-original") + String modelUuid = execution.getVariable("model-version-id-original") + //here modelVersion is not set, we use modelUuid to decompose the service. + String serviceModelInfo = """{ + "modelInvariantUuid":"${modelInvariantUuid}", + "modelUuid":"${modelUuid}", + "modelVersion":"" + }""" + + execution.setVariable("serviceModelInfo_Original", serviceModelInfo) + + utils.log("DEBUG", " ***** Completed prepareDecomposeService_Original of update generic e2e service ***** ", isDebugEnabled) + } catch (Exception ex) { + // try error in method block + String exceptionMessage = "Bpmn error encountered in update generic e2e service flow. Unexpected Error from method prepareDecomposeService_Original() - " + ex.getMessage() + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + } + } + + public void processDecomposition_Original(DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + + utils.log("DEBUG", " ***** Inside processDecomposition_Original() of update generic e2e service flow ***** ", isDebugEnabled) + try { + ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition") + execution.setVariable("serviceDecomposition_Original", serviceDecomposition) + } catch (Exception ex) { + String exceptionMessage = "Bpmn error encountered in update generic e2e service flow. processDecomposition_Original() - " + ex.getMessage() + utils.log("DEBUG", exceptionMessage, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + } + } + + public void doCompareModelVersions(DelegateExecution execution){ + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + utils.log("INFO", "======== Start doCompareModelVersions Process ======== ", isDebugEnabled) + + ServiceDecomposition serviceDecomposition_Target = execution.getVariable("serviceDecomposition_Target") + ServiceDecomposition serviceDecomposition_Original = execution.getVariable("serviceDecomposition_Original") + + List<Resource> allSR_target = serviceDecomposition_Target.getServiceResources(); + List<Resource> allSR_original = serviceDecomposition_Original.getServiceResources(); + + List<Resource> addResourceList = new ArrayList<String>() + List<Resource> delResourceList = new ArrayList<String>() + + addResourceList.addAll(allSR_target) + delResourceList.addAll(allSR_original) + + //Compare + for (Resource rc_t : allSR_target){ + String muuid = rc_t.getModelInfo().getModelUuid() + String mIuuid = rc_t.getModelInfo().getModelInvariantUuid() + String mCuuid = rc_t.getModelInfo().getModelCustomizationUuid() + for (Resource rc_o : allSR_original){ + if(rc_o.getModelInfo().getModelUuid() == muuid + && rc_o.getModelInfo().getModelInvariantUuid() == mIuuid + && rc_o.getModelInfo().getModelCustomizationUuid() == mCuuid) { + addResourceList.remove(rc_t); + delResourceList.remove(rc_o); + } + } + } + + execution.setVariable("addResourceList", addResourceList) + execution.setVariable("delResourceList", delResourceList) + utils.log("INFO", "addResourceList: " + addResourceList, isDebugEnabled) + utils.log("INFO", "delResourceList: " + delResourceList, isDebugEnabled) + + utils.log("INFO", "======== COMPLETED doCompareModelVersions Process ======== ", isDebugEnabled) + } + +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCompareModelofE2EServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCompareModelofE2EServiceInstance.groovy new file mode 100644 index 0000000000..3702862a04 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCompareModelofE2EServiceInstance.groovy @@ -0,0 +1,205 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2018 Huawei Technologies Co., Ltd. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.so.bpmn.infrastructure.scripts; + +import static org.apache.commons.lang3.StringUtils.*; + +import javax.ws.rs.NotFoundException + +import org.apache.commons.lang3.* +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.onap.aai.domain.yang.ServiceInstance +import org.onap.so.bpmn.common.resource.ResourceRequestBuilder +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.onap.so.bpmn.common.scripts.ExceptionUtil +import org.onap.so.bpmn.core.domain.CompareModelsResult +import org.onap.so.bpmn.core.domain.ModelInfo +import org.onap.so.bpmn.core.domain.Resource +import org.onap.so.bpmn.core.domain.ResourceModelInfo +import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.client.aai.AAIObjectType +import org.onap.so.client.aai.AAIResourcesClient +import org.onap.so.client.aai.entities.AAIResultWrapper +import org.onap.so.client.aai.entities.uri.AAIResourceUri +import org.onap.so.client.aai.entities.uri.AAIUriFactory + +import groovy.json.* + +/** + * This groovy class supports the <class>DoCompareModelofE2EServiceInstance.bpmn</class> process. + * + * Inputs: + * @param - msoRequestId + * @param - globalSubscriberId + * @param - subscriptionServiceType + * @param - serviceInstanceId + * @param - modelInvariantIdTarget + * @param - modelVersionIdTarget + * + * Outputs: + * @param - compareModelsResult CompareModelsResult + + */ +public class DoCompareModelofE2EServiceInstance extends AbstractServiceTaskProcessor { + + String Prefix="DCMPMDSI_" + private static final String DebugFlag = "isDebugEnabled" + + ExceptionUtil exceptionUtil = new ExceptionUtil() + JsonUtils jsonUtil = new JsonUtils() + + public void preProcessRequest (DelegateExecution execution) { + + def method = getClass().getSimpleName() + '.preProcessRequest(' +'execution=' + execution.getId() +')' + def isDebugEnabled = execution.getVariable("isDebugLogEnabled") + utils.log("INFO","Entered " + method, isDebugEnabled) + String msg = "" + utils.log("INFO"," ***** Enter DoCompareModelofE2EServiceInstance preProcessRequest *****", isDebugEnabled) + + execution.setVariable("prefix", Prefix) + //Inputs + + //subscriberInfo. for AAI GET + String globalSubscriberId = execution.getVariable("globalSubscriberId") + utils.log("INFO"," ***** globalSubscriberId *****" + globalSubscriberId, isDebugEnabled) + + String serviceType = execution.getVariable("serviceType") + utils.log("INFO"," ***** serviceType *****" + serviceType, isDebugEnabled) + + if (isBlank(globalSubscriberId)) { + msg = "Input globalSubscriberId is null" + utils.log("INFO", msg, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + + if (isBlank(serviceType)) { + msg = "Input serviceType is null" + utils.log("INFO", msg, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + + String serviceInstanceId = execution.getVariable("serviceInstanceId") + if (isBlank(serviceInstanceId)){ + msg = "Input serviceInstanceId is null" + utils.log("INFO", msg, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + + String modelInvariantUuid = execution.getVariable("modelInvariantIdTarget") + if (isBlank(modelInvariantUuid)){ + msg = "Input modelInvariantUuid is null" + utils.log("INFO", msg, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + + String modelUuid = execution.getVariable("modelVersionIdTarget") + if (isBlank(modelUuid)){ + msg = "Input modelUuid is null" + utils.log("INFO", msg, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + + // Set Target Template info + execution.setVariable("model-invariant-id-target", modelInvariantUuid) + execution.setVariable("model-version-id-target", modelUuid) + + + utils.log("INFO", "Exited " + method, isDebugEnabled) + } + + /** + * Gets the service instance from aai + * + * @author cb645j + */ + public void getServiceInstance(DelegateExecution execution) { + try { + String serviceInstanceId = execution.getVariable('serviceInstanceId') + String globalSubscriberId = execution.getVariable('globalSubscriberId') + String serviceType = execution.getVariable('serviceType') + + AAIResourcesClient resourceClient = new AAIResourcesClient() + AAIResourceUri serviceInstanceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, globalSubscriberId, serviceType, serviceInstanceId) + AAIResultWrapper wrapper = resourceClient.get(serviceInstanceUri, NotFoundException.class) + + ServiceInstance si = wrapper.asBean(ServiceInstance.class) + execution.setVariable("model-invariant-id-original", si.getModelInvariantId()) + execution.setVariable("model-version-id-original", si.getModelVersionId()) + + }catch(BpmnError e) { + throw e; + }catch(NotFoundException e) { + exceptionUtil.buildAndThrowWorkflowException(execution, 404, "Service-instance does not exist AAI") + }catch(Exception ex) { + String msg = "Internal Error in getServiceInstance: " + ex.getMessage() + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + } + + public void postCompareModelVersions(DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + + + List<Resource> addResourceList = execution.getVariable("addResourceList") + List<Resource> delResourceList = execution.getVariable("delResourceList") + + CompareModelsResult cmpResult = new CompareModelsResult() + List<ResourceModelInfo> addedResourceList = new ArrayList<ResourceModelInfo>() + List<ResourceModelInfo> deletedResourceList = new ArrayList<ResourceModelInfo>() + + + String serviceModelUuid = execution.getVariable("model-version-id-target") + List<String> requestInputs = new ArrayList<String>() + ModelInfo mi = null; + for(Resource rc : addResourceList) { + mi = rc.getModelInfo() + String resourceCustomizationUuid = mi.getModelCustomizationUuid() + ResourceModelInfo rmodel = new ResourceModelInfo() + rmodel.setResourceName(mi.getModelName()) + rmodel.setResourceInvariantUuid(mi.getModelInvariantUuid()) + rmodel.setResourceUuid(mi.getModelUuid()) + rmodel.setResourceCustomizationUuid(resourceCustomizationUuid) + addedResourceList.add(rmodel) + + Map<String, Object> resourceParameters = ResourceRequestBuilder.buildResouceRequest(serviceModelUuid, resourceCustomizationUuid, null) + requestInputs.addAll(resourceParameters.keySet()) + } + + for(Resource rc : delResourceList) { + mi = rc.getModelInfo() + String resourceCustomizationUuid = mi.getModelCustomizationUuid() + ResourceModelInfo rmodel = new ResourceModelInfo() + rmodel.setResourceName(mi.getModelName()) + rmodel.setResourceInvariantUuid(mi.getModelInvariantUuid()) + rmodel.setResourceUuid(mi.getModelUuid()) + rmodel.setResourceCustomizationUuid(resourceCustomizationUuid) + deletedResourceList.add(rmodel) + } + + cmpResult.setAddedResourceList(addedResourceList) + cmpResult.setDeletedResourceList(deletedResourceList) + cmpResult.setRequestInputs(requestInputs) + + execution.setVariable("compareModelsResult", cmpResult) + } + +} + diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateE2EServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateE2EServiceInstance.groovy new file mode 100644 index 0000000000..b5d196181b --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateE2EServiceInstance.groovy @@ -0,0 +1,485 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.so.bpmn.infrastructure.scripts; + +import static org.apache.commons.lang3.StringUtils.*; + +import javax.ws.rs.NotFoundException + +import org.apache.commons.lang3.* +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.onap.aai.domain.yang.ServiceInstance +import org.onap.so.bpmn.common.scripts.AaiUtil +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.onap.so.bpmn.common.scripts.CatalogDbUtils; +import org.onap.so.bpmn.common.scripts.ExceptionUtil +import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.so.bpmn.core.RollbackData +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.bpmn.core.domain.Resource +import org.onap.so.bpmn.core.domain.ServiceDecomposition +import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.client.aai.AAIObjectType +import org.onap.so.client.aai.AAIResourcesClient +import org.onap.so.client.aai.entities.AAIResultWrapper +import org.onap.so.client.aai.entities.uri.AAIResourceUri +import org.onap.so.client.aai.entities.uri.AAIUriFactory +import org.onap.so.logger.MessageEnum +import org.onap.so.logger.MsoLogger +import org.springframework.web.util.UriUtils; + +import groovy.json.* + + + +/** + * This groovy class supports the <class>DoCreateServiceInstance.bpmn</class> process. + * + * Inputs: + * @param - msoRequestId + * @param - globalSubscriberId + * @param - subscriptionServiceType + * @param - serviceInstanceId + * @param - serviceInstanceName - O + * @param - serviceModelInfo + * @param - productFamilyId + * @param - disableRollback + * @param - failExists - TODO + * @param - serviceInputParams (should contain aic_zone for serviceTypes TRANSPORT,ATM) + * @param - sdncVersion ("1610") + * @param - serviceDecomposition - Decomposition for R1710 + * (if macro provides serviceDecompsition then serviceModelInfo, serviceInstanceId & serviceInstanceName will be ignored) + * + * Outputs: + * @param - rollbackData (localRB->null) + * @param - rolledBack (no localRB->null, localRB F->false, localRB S->true) + * @param - WorkflowException + * @param - serviceInstanceName - (GET from AAI if null in input) + * + */ +public class DoCreateE2EServiceInstance extends AbstractServiceTaskProcessor { + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoCreateE2EServiceInstance.class); + + + String Prefix="DCRESI_" + ExceptionUtil exceptionUtil = new ExceptionUtil() + JsonUtils jsonUtil = new JsonUtils() + CatalogDbUtils cutils = new CatalogDbUtils() + + public void preProcessRequest (DelegateExecution execution) { + String msg = "" + msoLogger.trace("preProcessRequest ") + + try { + execution.setVariable("prefix", Prefix) + //Inputs + //requestDetails.subscriberInfo. for AAI GET & PUT & SDNC assignToplology + String globalSubscriberId = execution.getVariable("globalSubscriberId") //globalCustomerId + msoLogger.info(" ***** globalSubscriberId *****" + globalSubscriberId) + //requestDetails.requestParameters. for AAI PUT & SDNC assignTopology + String serviceType = execution.getVariable("serviceType") + msoLogger.info(" ***** serviceType *****" + serviceType) + //requestDetails.requestParameters. for SDNC assignTopology + String productFamilyId = execution.getVariable("productFamilyId") //AAI productFamilyId + + if (isBlank(globalSubscriberId)) { + msg = "Input globalSubscriberId is null" + msoLogger.info(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + + if (isBlank(serviceType)) { + msg = "Input serviceType is null" + msoLogger.info(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + + if (productFamilyId == null) { + execution.setVariable("productFamilyId", "") + } + + String sdncCallbackUrl = execution.getVariable('URN_mso_workflow_sdncadapter_callback') + if (isBlank(sdncCallbackUrl)) { + msg = "URN_mso_workflow_sdncadapter_callback is null" + msoLogger.info(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + execution.setVariable("sdncCallbackUrl", sdncCallbackUrl) + msoLogger.info("SDNC Callback URL: " + sdncCallbackUrl) + + //requestDetails.modelInfo.for AAI PUT servieInstanceData + //requestDetails.requestInfo. for AAI GET/PUT serviceInstanceData + String serviceInstanceName = execution.getVariable("serviceInstanceName") + String serviceInstanceId = execution.getVariable("serviceInstanceId") + String uuiRequest = execution.getVariable("uuiRequest") + String modelInvariantUuid = jsonUtil.getJsonValue(uuiRequest, "service.serviceInvariantUuid") + String modelUuid = jsonUtil.getJsonValue(uuiRequest, "service.serviceUuid") + String serviceModelName = jsonUtil.getJsonValue(uuiRequest, "service.parameters.templateName") + execution.setVariable("serviceModelName", serviceModelName) + //aai serviceType and Role can be setted as fixed value now. + String aaiServiceType = "E2E Service" + String aaiServiceRole = "E2E Service" + + execution.setVariable("modelInvariantUuid", modelInvariantUuid) + execution.setVariable("modelUuid", modelUuid) + + //AAI PUT + String oStatus = execution.getVariable("initialStatus") ?: "" + if ("TRANSPORT".equalsIgnoreCase(serviceType)) + { + oStatus = "Created" + } + + String statusLine = isBlank(oStatus) ? "" : "<orchestration-status>${MsoUtils.xmlEscape(oStatus)}</orchestration-status>" + + AaiUtil aaiUriUtil = new AaiUtil(this) + String aai_uri = aaiUriUtil.getBusinessCustomerUri(execution) + String namespace = aaiUriUtil.getNamespaceFromUri(aai_uri) + String serviceInstanceData = + """<service-instance xmlns=\"${namespace}\"> + <service-instance-id>${MsoUtils.xmlEscape(serviceInstanceId)}</service-instance-id> + <service-instance-name>${MsoUtils.xmlEscape(serviceInstanceName)}</service-instance-name> + <service-type>${MsoUtils.xmlEscape(aaiServiceType)}</service-type> + <service-role>${MsoUtils.xmlEscape(aaiServiceRole)}</service-role> + ${statusLine} + <model-invariant-id>${MsoUtils.xmlEscape(modelInvariantUuid)}</model-invariant-id> + <model-version-id>${MsoUtils.xmlEscape(modelUuid)}</model-version-id> + </service-instance>""".trim() + execution.setVariable("serviceInstanceData", serviceInstanceData) + msoLogger.debug(serviceInstanceData) + msoLogger.info(" aai_uri " + aai_uri + " namespace:" + namespace) + msoLogger.info(" 'payload' to create Service Instance in AAI - " + "\n" + serviceInstanceData) + + } catch (BpmnError e) { + throw e; + } catch (Exception ex){ + msg = "Exception in preProcessRequest " + ex.getMessage() + msoLogger.info(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.trace("Exit preProcessRequest ") + } + + public void prepareDecomposeService(DelegateExecution execution) { + try { + msoLogger.trace("Inside prepareDecomposeService of create generic e2e service ") + String modelInvariantUuid = execution.getVariable("modelInvariantUuid") + String modelUuid = execution.getVariable("modelUuid") + //here modelVersion is not set, we use modelUuid to decompose the service. + String serviceModelInfo = """{ + "modelInvariantUuid":"${modelInvariantUuid}", + "modelUuid":"${modelUuid}", + "modelVersion":"" + }""" + execution.setVariable("serviceModelInfo", serviceModelInfo) + + msoLogger.trace("Completed prepareDecomposeService of create generic e2e service ") + } catch (Exception ex) { + // try error in method block + String exceptionMessage = "Bpmn error encountered in create generic e2e service flow. Unexpected Error from method prepareDecomposeService() - " + ex.getMessage() + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + } + } + + public void processDecomposition(DelegateExecution execution) { + msoLogger.trace("Inside processDecomposition() of create generic e2e service flow ") + try { + ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition") + } catch (Exception ex) { + String exceptionMessage = "Bpmn error encountered in create generic e2e service flow. processDecomposition() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + } + } + + public void doServicePreOperation(DelegateExecution execution){ + //we need a service plugin platform here. + ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition") + String uuiRequest = execution.getVariable("uuiRequest") + String newUuiRequest = ServicePluginFactory.getInstance().preProcessService(serviceDecomposition, uuiRequest); + execution.setVariable("uuiRequest", newUuiRequest) + } + + public void doServiceHoming(DelegateExecution execution) { + //we need a service plugin platform here. + ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition") + String uuiRequest = execution.getVariable("uuiRequest") + String newUuiRequest = ServicePluginFactory.getInstance().doServiceHoming(serviceDecomposition, uuiRequest); + execution.setVariable("uuiRequest", newUuiRequest) + } + + public void postProcessAAIGET(DelegateExecution execution) { + msoLogger.trace("postProcessAAIGET ") + String msg = "" + + try { + String serviceInstanceName = execution.getVariable("serviceInstanceName") + boolean succInAAI = execution.getVariable("GENGS_SuccessIndicator") + if(!succInAAI){ + msoLogger.info("Error getting Service-instance from AAI", + serviceInstanceName) + WorkflowException workflowException = execution.getVariable("WorkflowException") + msoLogger.debug("workflowException: " + workflowException) + if(workflowException != null){ + exceptionUtil.buildAndThrowWorkflowException(execution, workflowException.getErrorCode(), workflowException.getErrorMessage()) + } + else + { + msg = "Failure in postProcessAAIGET GENGS_SuccessIndicator:" + succInAAI + msoLogger.info(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg) + } + } + else + { + boolean foundInAAI = execution.getVariable("GENGS_FoundIndicator") + if(foundInAAI){ + msoLogger.info("Found Service-instance in AAI") + msg = "ServiceInstance already exists in AAI:" + serviceInstanceName + msoLogger.info(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg) + } + } + } catch (BpmnError e) { + throw e; + } catch (Exception ex) { + msg = "Exception in DoCreateServiceInstance.postProcessAAIGET. " + ex.getMessage() + msoLogger.info(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.trace("Exit postProcessAAIGET ") + } + + //TODO use create if not exist + public void postProcessAAIPUT(DelegateExecution execution) { + msoLogger.trace("postProcessAAIPUT ") + String msg = "" + try { + String serviceInstanceId = execution.getVariable("serviceInstanceId") + boolean succInAAI = execution.getVariable("GENPS_SuccessIndicator") + if(!succInAAI){ + msoLogger.info("Error putting Service-instance in AAI", + serviceInstanceId) + WorkflowException workflowException = execution.getVariable("WorkflowException") + msoLogger.debug("workflowException: " + workflowException) + if(workflowException != null){ + exceptionUtil.buildAndThrowWorkflowException(execution, workflowException.getErrorCode(), workflowException.getErrorMessage()) + } + } + else + { + //start rollback set up + RollbackData rollbackData = new RollbackData() + def disableRollback = execution.getVariable("disableRollback") + rollbackData.put("SERVICEINSTANCE", "disableRollback", disableRollback.toString()) + rollbackData.put("SERVICEINSTANCE", "rollbackAAI", "true") + rollbackData.put("SERVICEINSTANCE", "serviceInstanceId", serviceInstanceId) + rollbackData.put("SERVICEINSTANCE", "subscriptionServiceType", execution.getVariable("subscriptionServiceType")) + rollbackData.put("SERVICEINSTANCE", "globalSubscriberId", execution.getVariable("globalSubscriberId")) + execution.setVariable("rollbackData", rollbackData) + } + + } catch (BpmnError e) { + throw e; + } catch (Exception ex) { + msg = "Exception in DoCreateServiceInstance.postProcessAAIDEL. " + ex.getMessage() + msoLogger.info(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.trace("Exit postProcessAAIPUT ") + } + + /** + * Gets the service instance and its relationships from aai + */ + public void getServiceInstance(DelegateExecution execution) { + try { + String serviceInstanceId = execution.getVariable('serviceInstanceId') + String globalSubscriberId = execution.getVariable('globalSubscriberId') + String serviceType = execution.getVariable('subscriptionServiceType') + + AAIResourcesClient resourceClient = new AAIResourcesClient() + AAIResourceUri serviceInstanceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, globalSubscriberId, serviceType, serviceInstanceId) + AAIResultWrapper wrapper = resourceClient.get(serviceInstanceUri, NotFoundException.class) + + ServiceInstance si = wrapper.asBean(ServiceInstance.class) + execution.setVariable("serviceInstanceName", si.getServiceInstanceName()) + + }catch(BpmnError e) { + throw e; + }catch(Exception ex) { + String msg = "Internal Error in getServiceInstance: " + ex.getMessage() + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + } + + + public void postProcessAAIGET2(DelegateExecution execution) { + msoLogger.trace("postProcessAAIGET2 ") + String msg = "" + + try { + String serviceInstanceName = execution.getVariable("serviceInstanceName") + boolean succInAAI = execution.getVariable("GENGS_SuccessIndicator") + if(!succInAAI){ + msoLogger.info("Error getting Service-instance from AAI in postProcessAAIGET2", + serviceInstanceName) + WorkflowException workflowException = execution.getVariable("WorkflowException") + msoLogger.debug("workflowException: " + workflowException) + if(workflowException != null){ + exceptionUtil.buildAndThrowWorkflowException(execution, workflowException.getErrorCode(), workflowException.getErrorMessage()) + } + else + { + msg = "Failure in postProcessAAIGET2 GENGS_SuccessIndicator:" + succInAAI + msoLogger.info(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg) + } + } + else + { + boolean foundInAAI = execution.getVariable("GENGS_FoundIndicator") + if(foundInAAI){ + String aaiService = execution.getVariable("GENGS_service") + if (!isBlank(aaiService) && (utils.nodeExists(aaiService, "service-instance-name"))) { + execution.setVariable("serviceInstanceName", utils.getNodeText(aaiService, "service-instance-name")) + msoLogger.info("Found Service-instance in AAI.serviceInstanceName:" + execution.getVariable("serviceInstanceName")) + } + } + } + } catch (BpmnError e) { + throw e; + } catch (Exception ex) { + msg = "Exception in DoCreateServiceInstance.postProcessAAIGET2 " + ex.getMessage() + msoLogger.info(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.trace("Exit postProcessAAIGET2 ") + } + + public void preProcessRollback (DelegateExecution execution) { + msoLogger.trace("preProcessRollback ") + try { + + Object workflowException = execution.getVariable("WorkflowException"); + + if (workflowException instanceof WorkflowException) { + msoLogger.info("Prev workflowException: " + workflowException.getErrorMessage()) + execution.setVariable("prevWorkflowException", workflowException); + //execution.setVariable("WorkflowException", null); + } + } catch (BpmnError e) { + msoLogger.info("BPMN Error during preProcessRollback") + } catch(Exception ex) { + String msg = "Exception in preProcessRollback. " + ex.getMessage() + msoLogger.info(msg) + } + msoLogger.trace("Exit preProcessRollback ") + } + + public void postProcessRollback (DelegateExecution execution) { + msoLogger.trace("postProcessRollback ") + String msg = "" + try { + Object workflowException = execution.getVariable("prevWorkflowException"); + if (workflowException instanceof WorkflowException) { + msoLogger.info("Setting prevException to WorkflowException: ") + execution.setVariable("WorkflowException", workflowException); + } + execution.setVariable("rollbackData", null) + } catch (BpmnError b) { + msoLogger.info("BPMN Error during postProcessRollback") + throw b; + } catch(Exception ex) { + msg = "Exception in postProcessRollback. " + ex.getMessage() + msoLogger.info(msg) + } + msoLogger.trace("Exit postProcessRollback ") + } + + public void preInitResourcesOperStatus(DelegateExecution execution){ + msoLogger.trace("STARTED preInitResourcesOperStatus Process ") + try{ + String serviceId = execution.getVariable("serviceInstanceId") + String operationId = execution.getVariable("operationId") + String operationType = execution.getVariable("operationType") + String resourceTemplateUUIDs = "" + String result = "processing" + String progress = "0" + String reason = "" + String operationContent = "Prepare service creation" + msoLogger.info("Generated new operation for Service Instance serviceId:" + serviceId + " operationId:" + operationId + " operationType:" + operationType) + serviceId = UriUtils.encode(serviceId,"UTF-8") + execution.setVariable("serviceInstanceId", serviceId) + execution.setVariable("operationId", operationId) + execution.setVariable("operationType", operationType) + ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition") + List<Resource> resourceList = serviceDecomposition.getServiceResources() + + for(Resource resource : resourceList){ + resourceTemplateUUIDs = resourceTemplateUUIDs + resource.getModelInfo().getModelCustomizationUuid() + ":" + } + + def dbAdapterEndpoint = "http://mso.mso.testlab.openecomp.org:8080/dbadapters/RequestsDbAdapter" + execution.setVariable("CVFMI_dbAdapterEndpoint", dbAdapterEndpoint) + msoLogger.info("DB Adapter Endpoint is: " + dbAdapterEndpoint) + + String payload = + """<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" + xmlns:ns="http://org.onap.so/requestsdb"> + <soapenv:Header/> + <soapenv:Body> + <ns:initResourceOperationStatus xmlns:ns="http://org.onap.so/requestsdb"> + <serviceId>${MsoUtils.xmlEscape(serviceId)}</serviceId> + <operationId>${MsoUtils.xmlEscape(operationId)}</operationId> + <operationType>${MsoUtils.xmlEscape(operationType)}</operationType> + <resourceTemplateUUIDs>${MsoUtils.xmlEscape(resourceTemplateUUIDs)}</resourceTemplateUUIDs> + </ns:initResourceOperationStatus> + </soapenv:Body> + </soapenv:Envelope>""" + + payload = utils.formatXml(payload) + execution.setVariable("CVFMI_initResOperStatusRequest", payload) + msoLogger.info("Outgoing initResourceOperationStatus: \n" + payload) + msoLogger.debug("CreateVfModuleInfra Outgoing initResourceOperationStatus Request: " + payload) + + }catch(Exception e){ + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception Occured Processing preInitResourcesOperStatus.", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e); + execution.setVariable("CVFMI_ErrorResponse", "Error Occurred during preInitResourcesOperStatus Method:\n" + e.getMessage()) + } + msoLogger.trace("COMPLETED preInitResourcesOperStatus Process ") + } + + // prepare input param for using DoCreateResources.bpmn + public void preProcessForAddResource(DelegateExecution execution) { + msoLogger.trace("STARTED preProcessForAddResource Process ") + + ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition") + List<Resource> addResourceList = serviceDecomposition.getServiceResources() + execution.setVariable("addResourceList", addResourceList) + + msoLogger.trace("COMPLETED preProcessForAddResource Process ") + } + + public void postProcessForAddResource(DelegateExecution execution) { + // do nothing now + + } + +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateE2EServiceInstanceRollback.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateE2EServiceInstanceRollback.groovy new file mode 100644 index 0000000000..82355beed2 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateE2EServiceInstanceRollback.groovy @@ -0,0 +1,268 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts + + +import static org.apache.commons.lang3.StringUtils.*; + +import groovy.xml.XmlUtil +import groovy.json.* + +import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.onap.so.bpmn.common.scripts.SDNCAdapterUtils +import org.onap.so.bpmn.core.RollbackData +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.rest.APIResponse; +import org.onap.so.rest.RESTClient +import org.onap.so.rest.RESTConfig +import org.onap.so.logger.MsoLogger +import org.onap.so.logger.MessageEnum +import org.onap.so.bpmn.common.scripts.ExceptionUtil; +import org.onap.so.client.aai.entities.uri.AAIResourceUri +import org.onap.so.client.aai.entities.uri.AAIUriFactory +import org.onap.so.client.aai.AAIObjectType +import org.onap.so.client.aai.AAIResourcesClient + +import java.util.UUID; + +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.json.JSONObject; +import org.apache.commons.lang3.* +import org.apache.commons.codec.binary.Base64; +import org.springframework.web.util.UriUtils; +/** + * This groovy class supports the <class>DoCreateServiceInstanceRollback.bpmn</class> process. + * + * Inputs: + * @param - msoRequestId + * @param - rollbackData with + * globalCustomerId + * subscriptionServiceType + * serviceInstanceId + * disableRollback + * rollbackAAI + * rollbackSDNC + * sdncRollbackRequest + * + * + * Outputs: + * @param - rollbackError + * @param - rolledBack (no localRB->null, localRB F->false, localRB S->true) + * + */ +public class DoCreateE2EServiceInstanceRollback extends AbstractServiceTaskProcessor{ + + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoCreateE2EServiceInstanceRollback.class); + String Prefix="DCRESIRB_" + + public void preProcessRequest(DelegateExecution execution) { + def isDebugEnabled = execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + String msg = "" + msoLogger.trace("Start preProcessRequest") + execution.setVariable("rollbackAAI",false) + execution.setVariable("rollbackSDNC",false) + + try { + def rollbackData = execution.getVariable("rollbackData") + msoLogger.debug("RollbackData:" + rollbackData) + + if (rollbackData != null) { + if (rollbackData.hasType("SERVICEINSTANCE")) { + + def serviceInstanceId = rollbackData.get("SERVICEINSTANCE", "serviceInstanceId") + execution.setVariable("serviceInstanceId", serviceInstanceId) + + def subscriptionServiceType = rollbackData.get("SERVICEINSTANCE", "subscriptionServiceType") + execution.setVariable("subscriptionServiceType", subscriptionServiceType) + + def globalSubscriberId = rollbackData.get("SERVICEINSTANCE", "globalSubscriberId") + execution.setVariable("globalSubscriberId", globalSubscriberId) + + def rollbackAAI = rollbackData.get("SERVICEINSTANCE", "rollbackAAI") + if ("true".equals(rollbackAAI)) + { + execution.setVariable("rollbackAAI",true) + } + + def rollbackSDNC = rollbackData.get("SERVICEINSTANCE", "rollbackSDNC") + if ("true".equals(rollbackSDNC)) + { + execution.setVariable("rollbackSDNC", true) + } + + if (execution.getVariable("rollbackAAI") != true && execution.getVariable("rollbackSDNC") != true) + { + execution.setVariable("skipRollback", true) + } + + def sdncDelete = rollbackData.get("SERVICEINSTANCE", "sdncDelete") + execution.setVariable("sdncDelete", sdncDelete) + def sdncDeactivate = rollbackData.get("SERVICEINSTANCE", "sdncDeactivate") + execution.setVariable("sdncDeactivate", sdncDeactivate) + msoLogger.debug("sdncDeactivate:\n" + sdncDeactivate) + msoLogger.debug("sdncDelete:\n" + sdncDelete) + } + else { + execution.setVariable("skipRollback", true) + } + } + else { + execution.setVariable("skipRollback", true) + } + if (execution.getVariable("disableRollback").equals("true" )) + { + execution.setVariable("skipRollback", true) + } + + } catch (BpmnError e) { + throw e; + } catch (Exception ex){ + msg = "Exception in Create ServiceInstance Rollback preProcessRequest " + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) //TODO how does this even compile without exceptionUtil being declared + } + msoLogger.trace("Exit preProcessRequest ") + } + + public void validateSDNCResponse(DelegateExecution execution, String response, String method) { + + msoLogger.trace("validateSDNCResponse") + String msg = "" + try { + WorkflowException workflowException = execution.getVariable("WorkflowException") + boolean successIndicator = execution.getVariable("SDNCA_SuccessIndicator") + msoLogger.debug("SDNCResponse: " + response) + msoLogger.debug("workflowException: " + workflowException) + + SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this) + sdncAdapterUtils.validateSDNCResponse(execution, response, workflowException, successIndicator) + + if(execution.getVariable(Prefix + 'sdncResponseSuccess') == true){ + msg = "SDNC Adapter service-instance rollback successful for " + method + msoLogger.debug(msg) + }else{ + execution.setVariable("rolledBack", false) + msg = "Error Response from SDNC Adapter service-instance rollback for " + method + execution.setVariable("rollbackError", msg) + msoLogger.debug(msg) + throw new BpmnError("MSOWorkflowException") + } + } catch (BpmnError e) { + throw e; + } catch (Exception ex){ + msg = "Exception in Create ServiceInstance rollback for " + method + " Exception:" + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.trace("Exit validateSDNCResponse ") + } + + /** + * Deletes the service instance in aai + */ + public void deleteServiceInstance(DelegateExecution execution) { + msoLogger.trace("Started Delete Service Instance") + try { + String globalCustId = execution.getVariable("globalSubscriberId") + String serviceType = execution.getVariable("subscriptionServiceType") + String serviceInstanceId = execution.getVariable("serviceInstanceId") + + AAIResourcesClient resourceClient = new AAIResourcesClient(); + AAIResourceUri serviceInstanceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, globalCustId, serviceType, serviceInstanceId) + resourceClient.delete(serviceInstanceUri) + + msoLogger.trace("Completed Delete Service Instance") + }catch(Exception e){ + msoLogger.debug("Error occured within deleteServiceInstance method: " + e) + } + } + + public void postProcessRequest(DelegateExecution execution) { + + msoLogger.trace("postProcessRequest") + String msg = "" + try { + execution.setVariable("rollbackData", null) + String serviceInstanceId = execution.getVariable("serviceInstanceId") + boolean rollbackAAI = execution.getVariable("rollbackAAI") + boolean rollbackSDNC = execution.getVariable("rollbackSDNC") + if (rollbackAAI || rollbackSDNC) + { + execution.setVariable("rolledBack", true) + } + if (rollbackAAI) + { + boolean succInAAI = execution.getVariable("GENDS_SuccessIndicator") + if(!succInAAI){ + execution.setVariable("rolledBack", false) //both sdnc and aai must be successful to declare rollback Succesful + execution.setVariable("rollbackError", "Error deleting service-instance in AAI for rollback") + msoLogger.debug("Error deleting service-instance in AAI for rollback", + serviceInstanceId) + } + } + msoLogger.trace("Exit postProcessRequest ") + + } catch (BpmnError e) { + msg = "Exception in Create ServiceInstance Rollback postProcessRequest. " + e.getMessage() + msoLogger.debug(msg) + } catch (Exception ex) { + msg = "Exception in Create ServiceInstance Rollback postProcessRequest. " + ex.getMessage() + msoLogger.debug(msg) + } + + } + + public void processRollbackException(DelegateExecution execution){ + + msoLogger.trace("processRollbackException") + try{ + msoLogger.debug("Caught an Exception in DoCreateServiceInstanceRollback") + execution.setVariable("rollbackData", null) + execution.setVariable("rollbackError", "Caught exception in ServiceInstance Create Rollback") + execution.setVariable("WorkflowException", null) + + }catch(BpmnError b){ + msoLogger.debug("BPMN Error during processRollbackExceptions Method: ") + }catch(Exception e){ + msoLogger.debug("Caught Exception during processRollbackExceptions Method: " + e.getMessage()) + } + + msoLogger.trace(" Exit processRollbackException") + } + + public void processRollbackJavaException(DelegateExecution execution){ + + msoLogger.trace("processRollbackJavaException") + try{ + execution.setVariable("rollbackData", null) + execution.setVariable("rollbackError", "Caught Java exception in ServiceInstance Create Rollback") + msoLogger.debug("Caught Exception in processRollbackJavaException") + + }catch(Exception e){ + msoLogger.debug("Caught Exception in processRollbackJavaException " + e.getMessage()) + } + msoLogger.trace("Exit processRollbackJavaException") + } + +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateNetworkInstance.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateNetworkInstance.groovy new file mode 100644 index 0000000000..a376e581fe --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateNetworkInstance.groovy @@ -0,0 +1,1712 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts; + +import org.apache.commons.lang3.* +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.onap.so.bpmn.common.scripts.AaiUtil +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.onap.so.bpmn.common.scripts.ExceptionUtil +import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.so.bpmn.common.scripts.NetworkUtils +import org.onap.so.bpmn.common.scripts.SDNCAdapterUtils +import org.onap.so.bpmn.common.scripts.VidUtils +import org.onap.so.bpmn.core.UrnPropertiesReader +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.logger.MsoLogger +import org.onap.so.rest.APIResponse; +import org.springframework.web.util.UriUtils +import org.onap.so.client.aai.AAIResourcesClient +import org.onap.so.client.aai.AAIObjectType +import org.onap.so.client.aai.entities.AAIResultWrapper +import org.onap.so.client.aai.entities.Relationships +import org.onap.so.client.aai.entities.uri.AAIResourceUri +import org.onap.so.client.aai.entities.uri.AAIUriFactory +import org.json.JSONObject +import javax.ws.rs.NotFoundException + +import groovy.json.* +import groovy.xml.XmlUtil + + +/** + * This groovy class supports the <class>DoCreateNetworkInstance.bpmn</class> process. + * + */ +public class DoCreateNetworkInstance extends AbstractServiceTaskProcessor { + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoCreateNetworkInstance.class); + + String Prefix="CRENWKI_" + ExceptionUtil exceptionUtil = new ExceptionUtil() + JsonUtils jsonUtil = new JsonUtils() + VidUtils vidUtils = new VidUtils(this) + NetworkUtils networkUtils = new NetworkUtils() + SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils() + + def className = getClass().getSimpleName() + + /** + * This method is executed during the preProcessRequest task of the <class>DoCreateNetworkInstance.bpmn</class> process. + * @param execution + */ + public InitializeProcessVariables(DelegateExecution execution){ + /* Initialize all the process variables in this block */ + + execution.setVariable(Prefix + "networkRequest", "") + execution.setVariable(Prefix + "rollbackEnabled", null) + execution.setVariable(Prefix + "networkInputs", "") + //execution.setVariable(Prefix + "requestId", "") + execution.setVariable(Prefix + "messageId", "") + execution.setVariable(Prefix + "source", "") + execution.setVariable("BasicAuthHeaderValuePO", "") + execution.setVariable("BasicAuthHeaderValueSDNC", "") + execution.setVariable(Prefix + "serviceInstanceId","") + execution.setVariable("GENGS_type", "") + execution.setVariable(Prefix + "rsrc_endpoint", null) + execution.setVariable(Prefix + "networkOutputs", "") + execution.setVariable(Prefix + "networkId","") + execution.setVariable(Prefix + "networkName","") + + // AAI query Name + execution.setVariable(Prefix + "queryNameAAIRequest","") + execution.setVariable(Prefix + "queryNameAAIResponse", "") + execution.setVariable(Prefix + "aaiNameReturnCode", "") + execution.setVariable(Prefix + "isAAIqueryNameGood", false) + + // AAI query Cloud Region + execution.setVariable(Prefix + "queryCloudRegionRequest","") + execution.setVariable(Prefix + "queryCloudRegionReturnCode","") + execution.setVariable(Prefix + "queryCloudRegionResponse","") + execution.setVariable(Prefix + "cloudRegionPo","") + execution.setVariable(Prefix + "cloudRegionSdnc","") + execution.setVariable(Prefix + "isCloudRegionGood", false) + + // AAI query Id + execution.setVariable(Prefix + "queryIdAAIRequest","") + execution.setVariable(Prefix + "queryIdAAIResponse", "") + execution.setVariable(Prefix + "aaiIdReturnCode", "") + + // AAI query vpn binding + execution.setVariable(Prefix + "queryVpnBindingAAIRequest","") + execution.setVariable(Prefix + "queryVpnBindingAAIResponse", "") + execution.setVariable(Prefix + "aaiQqueryVpnBindingReturnCode", "") + execution.setVariable(Prefix + "vpnBindings", null) + execution.setVariable(Prefix + "vpnCount", 0) + execution.setVariable(Prefix + "routeCollection", "") + + // AAI query network policy + execution.setVariable(Prefix + "queryNetworkPolicyAAIRequest","") + execution.setVariable(Prefix + "queryNetworkPolicyAAIResponse", "") + execution.setVariable(Prefix + "aaiQqueryNetworkPolicyReturnCode", "") + execution.setVariable(Prefix + "networkPolicyUriList", null) + execution.setVariable(Prefix + "networkPolicyCount", 0) + execution.setVariable(Prefix + "networkCollection", "") + + // AAI query route table reference + execution.setVariable(Prefix + "queryNetworkTableRefAAIRequest","") + execution.setVariable(Prefix + "queryNetworkTableRefAAIResponse", "") + execution.setVariable(Prefix + "aaiQqueryNetworkTableRefReturnCode", "") + execution.setVariable(Prefix + "networkTableRefUriList", null) + execution.setVariable(Prefix + "networkTableRefCount", 0) + execution.setVariable(Prefix + "tableRefCollection", "") + + // AAI requery Id + execution.setVariable(Prefix + "requeryIdAAIRequest","") + execution.setVariable(Prefix + "requeryIdAAIResponse", "") + execution.setVariable(Prefix + "aaiRequeryIdReturnCode", "") + + // AAI update contrail + execution.setVariable(Prefix + "updateContrailAAIUrlRequest","") + execution.setVariable(Prefix + "updateContrailAAIPayloadRequest","") + execution.setVariable(Prefix + "updateContrailAAIResponse", "") + execution.setVariable(Prefix + "aaiUpdateContrailReturnCode", "") + + execution.setVariable(Prefix + "createNetworkRequest", "") + execution.setVariable(Prefix + "createNetworkResponse", "") + execution.setVariable(Prefix + "rollbackNetworkRequest", "") + //execution.setVariable(Prefix + "rollbackNetworkResponse", "") + execution.setVariable(Prefix + "networkReturnCode", "") + //execution.setVariable(Prefix + "rollbackNetworkReturnCode", "") + execution.setVariable(Prefix + "isNetworkRollbackNeeded", false) + + execution.setVariable(Prefix + "assignSDNCRequest", "") + execution.setVariable(Prefix + "assignSDNCResponse", "") + execution.setVariable(Prefix + "rollbackSDNCRequest", "") + //execution.setVariable(Prefix + "rollbackSDNCResponse", "") + execution.setVariable(Prefix + "sdncReturnCode", "") + //execution.setVariable(Prefix + "rollbackSDNCReturnCode", "") + execution.setVariable(Prefix + "isSdncRollbackNeeded", false) + execution.setVariable(Prefix + "sdncResponseSuccess", false) + + execution.setVariable(Prefix + "activateSDNCRequest", "") + execution.setVariable(Prefix + "activateSDNCResponse", "") + execution.setVariable(Prefix + "rollbackActivateSDNCRequest", "") + //execution.setVariable(Prefix + "rollbackActivateSDNCResponse", "") + execution.setVariable(Prefix + "sdncActivateReturnCode", "") + //execution.setVariable(Prefix + "rollbackActivateSDNCReturnCode", "") + execution.setVariable(Prefix + "isSdncActivateRollbackNeeded", false) + execution.setVariable(Prefix + "sdncActivateResponseSuccess", false) + + execution.setVariable(Prefix + "orchestrationStatus", "") + execution.setVariable(Prefix + "isVnfBindingPresent", false) + execution.setVariable(Prefix + "Success", false) + + execution.setVariable(Prefix + "isException", false) + + } + + // ************************************************** + // Pre or Prepare Request Section + // ************************************************** + /** + * This method is executed during the preProcessRequest task of the <class>DoCreateNetworkInstance.bpmn</class> process. + * @param execution + */ + public void preProcessRequest (DelegateExecution execution) { + + execution.setVariable("prefix",Prefix) + msoLogger.trace("Inside preProcessRequest() of " + className + ".groovy") + + try { + // initialize flow variables + InitializeProcessVariables(execution) + + // GET Incoming request & validate 3 kinds of format. + execution.setVariable("action", "CREATE") + String networkRequest = execution.getVariable("bpmnRequest") + if (networkRequest != null) { + if (networkRequest.contains("requestDetails")) { + // JSON format request is sent, create xml + try { + def prettyJson = JsonOutput.prettyPrint(networkRequest.toString()) + msoLogger.debug(" Incoming message formatted . . . : " + '\n' + prettyJson) + networkRequest = vidUtils.createXmlNetworkRequestInfra(execution, networkRequest) + + } catch (Exception ex) { + String dataErrorMessage = " Invalid json format Request - " + ex.getMessage() + msoLogger.debug(dataErrorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + } + } else { + // XML format request is sent + + } + } else { + // vIPR format request is sent, create xml from individual variables + networkRequest = vidUtils.createXmlNetworkRequestInstance(execution) + } + + networkRequest = utils.formatXml(networkRequest) + execution.setVariable(Prefix + "networkRequest", networkRequest) + msoLogger.debug(Prefix + "networkRequest - " + '\n' + networkRequest) + + // validate 'backout-on-failure' to override 'mso.rollback' + boolean rollbackEnabled = networkUtils.isRollbackEnabled(execution, networkRequest) + execution.setVariable(Prefix + "rollbackEnabled", rollbackEnabled) + msoLogger.debug(Prefix + "rollbackEnabled - " + rollbackEnabled) + + String networkInputs = utils.getNodeXml(networkRequest, "network-inputs", false).replace("tag0:","").replace(":tag0","") + execution.setVariable(Prefix + "networkInputs", networkInputs) + msoLogger.debug(Prefix + "networkInputs - " + '\n' + networkInputs) + + // prepare messageId + String messageId = execution.getVariable("testMessageId") // for testing + if (messageId == null || messageId == "") { + messageId = UUID.randomUUID() + msoLogger.debug(Prefix + "messageId, random generated: " + messageId) + } else { + msoLogger.debug(Prefix + "messageId, pre-assigned: " + messageId) + } + execution.setVariable(Prefix + "messageId", messageId) + + String source = utils.getNodeText(networkRequest, "source") + execution.setVariable(Prefix + "source", source) + msoLogger.debug(Prefix + "source - " + source) + + // validate cloud region + String lcpCloudRegionId = utils.getNodeText(networkRequest, "aic-cloud-region") + if ((lcpCloudRegionId == null) || (lcpCloudRegionId == "") || (lcpCloudRegionId == "null")) { + String dataErrorMessage = "Missing value/element: 'lcpCloudRegionId' or 'cloudConfiguration' or 'aic-cloud-region'." + msoLogger.debug(" Invalid Request - " + dataErrorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + } + + // validate service instance id + String serviceInstanceId = utils.getNodeText(networkRequest, "service-instance-id") + if ((serviceInstanceId == null) || (serviceInstanceId == "") || (serviceInstanceId == "null")) { + String dataErrorMessage = "Missing value/element: 'serviceInstanceId'." + msoLogger.debug(" Invalid Request - " + dataErrorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + } + + // PO Authorization Info / headers Authorization= + String basicAuthValuePO = UrnPropertiesReader.getVariable("mso.adapters.po.auth",execution) + + try { + def encodedString = utils.getBasicAuth(basicAuthValuePO, UrnPropertiesReader.getVariable("mso.msoKey",execution)) + execution.setVariable("BasicAuthHeaderValuePO",encodedString) + execution.setVariable("BasicAuthHeaderValueSDNC", encodedString) + + } catch (IOException ex) { + String exceptionMessage = "Exception Encountered in DoCreateNetworkInstance, PreProcessRequest() - " + String dataErrorMessage = exceptionMessage + " Unable to encode PO/SDNC user/password string - " + ex.getMessage() + msoLogger.debug(dataErrorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + } + + // Set variables for Generic Get Sub Flow use + execution.setVariable(Prefix + "serviceInstanceId", serviceInstanceId) + msoLogger.debug(Prefix + "serviceInstanceId - " + serviceInstanceId) + + execution.setVariable("GENGS_type", "service-instance") + msoLogger.debug("GENGS_type - " + "service-instance") + msoLogger.debug(" Url for SDNC adapter: " + UrnPropertiesReader.getVariable("mso.adapters.sdnc.endpoint",execution)) + + String sdncVersion = execution.getVariable("sdncVersion") + msoLogger.debug("sdncVersion? : " + sdncVersion) + + // build 'networkOutputs' + String networkId = utils.getNodeText(networkRequest, "network-id") + if ((networkId == null) || (networkId == "null")) { + networkId = "" + } + String networkName = utils.getNodeText(networkRequest, "network-name") + if ((networkName == null) || (networkName == "null")) { + networkName = "" + } + String networkOutputs = + """<network-outputs> + <network-id>${MsoUtils.xmlEscape(networkId)}</network-id> + <network-name>${MsoUtils.xmlEscape(networkName)}</network-name> + </network-outputs>""" + execution.setVariable(Prefix + "networkOutputs", networkOutputs) + msoLogger.debug(Prefix + "networkOutputs - " + '\n' + networkOutputs) + execution.setVariable(Prefix + "networkId", networkId) + execution.setVariable(Prefix + "networkName", networkName) + + } catch (BpmnError e) { + throw e; + + } catch (Exception ex) { + sendSyncError(execution) + // caught exception + String exceptionMessage = "Exception Encountered in PreProcessRequest() of " + className + ".groovy ***** : " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + /** + * Gets the service instance uri from aai + */ + public void getServiceInstance(DelegateExecution execution) { + try { + String serviceInstanceId = execution.getVariable('CRENWKI_serviceInstanceId') + + AAIResourcesClient resourceClient = new AAIResourcesClient() + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, serviceInstanceId) + + if(!resourceClient.exists(uri)){ + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Service instance was not found in aai") + } + + }catch(BpmnError e) { + throw e; + }catch (Exception ex){ + String msg = "Exception in getServiceInstance. " + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + } + + + public void callRESTQueryAAINetworkName (DelegateExecution execution) { + + execution.setVariable("prefix",Prefix) + + msoLogger.debug(" ***** Inside callRESTQueryAAINetworkName() of DoCreateNetworkInstance ***** " ) + + // get variables + String networkInputs = execution.getVariable(Prefix + "networkInputs") + String networkName = utils.getNodeText(networkInputs, "network-name") + networkName = UriUtils.encode(networkName,"UTF-8") + + // Prepare AA&I url with network-name + String aai_endpoint = UrnPropertiesReader.getVariable("aai.endpoint", execution) + AaiUtil aaiUriUtil = new AaiUtil(this) + String aai_uri = aaiUriUtil.getNetworkL3NetworkUri(execution) + String queryAAINameRequest = "${aai_endpoint}${aai_uri}" + "?network-name=" + networkName + execution.setVariable(Prefix + "queryNameAAIRequest", queryAAINameRequest) + msoLogger.debug(Prefix + "queryNameAAIRequest - " + "\n" + queryAAINameRequest) + + try { + APIResponse response = aaiUriUtil.executeAAIGetCall(execution, queryAAINameRequest) + String returnCode = response.getStatusCode() + execution.setVariable(Prefix + "aaiNameReturnCode", returnCode) + msoLogger.debug(" ***** AAI Query Name Response Code : " + returnCode) + + String aaiResponseAsString = response.getResponseBodyAsString() + msoLogger.debug(" ***** AAI Query Name Response : " +'\n'+ aaiResponseAsString) + + if (returnCode=='200') { + execution.setVariable(Prefix + "queryNameAAIResponse", aaiResponseAsString) + execution.setVariable(Prefix + "isAAIqueryNameGood", true) + String orchestrationStatus = "" + try { + // response is NOT empty + orchestrationStatus = utils.getNodeText(aaiResponseAsString, "orchestration-status") + execution.setVariable(Prefix + "orchestrationStatus", orchestrationStatus.toUpperCase()) + msoLogger.debug(Prefix + "orchestrationStatus - " + orchestrationStatus.toUpperCase()) + execution.setVariable("orchestrationStatus", orchestrationStatus) + + } catch (Exception ex) { + // response is empty + execution.setVariable(Prefix + "orchestrationStatus", orchestrationStatus) + msoLogger.debug(Prefix + "orchestrationStatus - " + orchestrationStatus) + } + + } else { + if (returnCode=='404') { + msoLogger.debug(" QueryAAINetworkName return code = '404' (Not Found). Proceed with the Create !!! ") + + } else { + // aai all errors + String dataErrorMessage = "Unexpected Error Response from QueryAAINetworkName - " + returnCode + msoLogger.debug(dataErrorMessage) + exceptionUtil.buildWorkflowException(execution, 2500, dataErrorMessage) + + } + + } + + msoLogger.debug(Prefix + "isAAIqueryNameGood? : " + execution.getVariable(Prefix + "isAAIqueryNameGood")) + + } catch (BpmnError e) { + throw e; + + } catch (Exception ex) { + // try error + String exceptionMessage = "Bpmn error encountered in DoCreateNetworkInstance flow - callRESTQueryAAINetworkName() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + public void callRESTQueryAAICloudRegion (DelegateExecution execution) { + + execution.setVariable("prefix",Prefix) + + msoLogger.debug(" ***** Inside callRESTQueryAAICloudRegion() of DoCreateNetworkInstance ***** " ) + + try { + String networkInputs = execution.getVariable(Prefix + "networkInputs") + String cloudRegion = utils.getNodeText(networkInputs, "aic-cloud-region") + cloudRegion = UriUtils.encode(cloudRegion,"UTF-8") + + // Prepare AA&I url + String aai_endpoint = UrnPropertiesReader.getVariable("aai.endpoint", execution) + AaiUtil aaiUtil = new AaiUtil(this) + String aai_uri = aaiUtil.getCloudInfrastructureCloudRegionUri(execution) + String queryCloudRegionRequest = "${aai_endpoint}${aai_uri}/" + cloudRegion + execution.setVariable(Prefix + "queryCloudRegionRequest", queryCloudRegionRequest) + msoLogger.debug(Prefix + "queryCloudRegionRequest - " + "\n" + queryCloudRegionRequest) + + String cloudRegionPo = aaiUtil.getAAICloudReqion(execution, queryCloudRegionRequest, "PO", cloudRegion) + String cloudRegionSdnc = aaiUtil.getAAICloudReqion(execution, queryCloudRegionRequest, "SDNC", cloudRegion) + + if ((cloudRegionPo != "ERROR") && (cloudRegionSdnc != "ERROR")) { + execution.setVariable(Prefix + "cloudRegionPo", cloudRegionPo) + execution.setVariable(Prefix + "cloudRegionSdnc", cloudRegionSdnc) + execution.setVariable(Prefix + "isCloudRegionGood", true) + + } else { + String dataErrorMessage = "QueryAAICloudRegion Unsuccessful. Return Code: " + execution.getVariable(Prefix + "queryCloudRegionReturnCode") + msoLogger.debug(dataErrorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + + } + + msoLogger.debug(" is Cloud Region Good: " + execution.getVariable(Prefix + "isCloudRegionGood")) + + } catch (BpmnError e) { + throw e; + + } catch (Exception ex) { + // try error + String exceptionMessage = "Bpmn error encountered in DoCreateNetworkInstance flow - callRESTQueryAAICloudRegion() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + public void callRESTQueryAAINetworkId(DelegateExecution execution) { + + execution.setVariable("prefix",Prefix) + + msoLogger.debug(" ***** Inside callRESTQueryAAINetworkId() of DoCreateNetworkInstance ***** " ) + + try { + // get variables + String networkId = "" + String assignSDNCResponse = execution.getVariable(Prefix + "assignSDNCResponse") + if (execution.getVariable("sdncVersion") != "1610") { + String networkResponseInformation = "" + try { + networkResponseInformation = utils.getNodeXml(assignSDNCResponse, "network-response-information", false).replace("tag0:","").replace(":tag0","") + networkId = utils.getNodeText(networkResponseInformation, "instance-id") + } catch (Exception ex) { + String dataErrorMessage = " SNDC Response network validation for 'instance-id' (network-id) failed: Empty <network-response-information>" + msoLogger.debug(dataErrorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + } + + } else { + networkId = utils.getNodeText(assignSDNCResponse, "network-id") + } + if (networkId == null || networkId == "null") { + String dataErrorMessage = "SNDC Response did not contains 'instance-id' or 'network-id' element, or the value is null." + msoLogger.debug(dataErrorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + } else { + msoLogger.debug(" SNDC Response network validation for 'instance-id' (network-id)' is good: " + networkId) + } + + + execution.setVariable(Prefix + "networkId", networkId) + String networkName = utils.getNodeText(assignSDNCResponse, "network-name") + execution.setVariable(Prefix + "networkName", networkName) + + networkId = UriUtils.encode(networkId,"UTF-8") + + // Prepare AA&I url + String aai_endpoint = UrnPropertiesReader.getVariable("aai.endpoint", execution) + AaiUtil aaiUriUtil = new AaiUtil(this) + String aai_uri = aaiUriUtil.getNetworkL3NetworkUri(execution) + String queryIdAAIRequest = "${aai_endpoint}${aai_uri}/" + networkId + "?depth=all" + execution.setVariable(Prefix + "queryIdAAIRequest", queryIdAAIRequest) + msoLogger.debug(Prefix + "queryIdAAIRequest - " + "\n" + queryIdAAIRequest) + + APIResponse response = aaiUriUtil.executeAAIGetCall(execution, queryIdAAIRequest) + String returnCode = response.getStatusCode() + execution.setVariable(Prefix + "aaiIdReturnCode", returnCode) + + msoLogger.debug(" ***** AAI Response Code : " + returnCode) + + String aaiResponseAsString = response.getResponseBodyAsString() + + if (returnCode=='200') { + execution.setVariable(Prefix + "queryIdAAIResponse", aaiResponseAsString) + msoLogger.debug(" QueryAAINetworkId Success REST Response - " + "\n" + aaiResponseAsString) + + String netId = utils.getNodeText(aaiResponseAsString, "network-id") + execution.setVariable(Prefix + "networkId", netId) + String netName = utils.getNodeText(aaiResponseAsString, "network-name") + execution.setVariable(Prefix + "networkName", netName) + + } else { + if (returnCode=='404') { + String dataErrorMessage = "Response Error from QueryAAINetworkId is 404 (Not Found)." + msoLogger.debug(" AAI Query Failed. " + dataErrorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + + } else { + if (aaiResponseAsString.contains("RESTFault")) { + WorkflowException exceptionObject = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) + execution.setVariable("WorkflowException", exceptionObject) + throw new BpmnError("MSOWorkflowException") + + } else { + // aai all errors + String dataErrorMessage = "Unexpected Response from QueryAAINetworkId - " + returnCode + msoLogger.debug("Unexpected Response from QueryAAINetworkId - " + dataErrorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + + } + } + } + + } catch (BpmnError e) { + throw e; + + } catch (Exception ex) { + String exceptionMessage = "Bpmn error encountered in DoCreateNetworkInstance flow. callRESTQueryAAINetworkId() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + public void callRESTReQueryAAINetworkId(DelegateExecution execution) { + + execution.setVariable("prefix",Prefix) + + msoLogger.debug(" ***** Inside callRESTReQueryAAINetworkId() of DoCreateNetworkInstance ***** " ) + + try { + // get variables + String networkId = execution.getVariable(Prefix + "networkId") + String netId = networkId + networkId = UriUtils.encode(networkId,"UTF-8") + + // Prepare AA&I url + String aai_endpoint = UrnPropertiesReader.getVariable("aai.endpoint", execution) + AaiUtil aaiUriUtil = new AaiUtil(this) + String aai_uri = aaiUriUtil.getNetworkL3NetworkUri(execution) + String requeryIdAAIRequest = "${aai_endpoint}${aai_uri}/" + networkId + "?depth=all" + execution.setVariable(Prefix + "requeryIdAAIRequest", requeryIdAAIRequest) + msoLogger.debug(Prefix + "requeryIdAAIRequest - " + "\n" + requeryIdAAIRequest) + + APIResponse response = aaiUriUtil.executeAAIGetCall(execution, requeryIdAAIRequest) + String returnCode = response.getStatusCode() + execution.setVariable(Prefix + "aaiRequeryIdReturnCode", returnCode) + msoLogger.debug(" ***** AAI ReQuery Response Code : " + returnCode) + + String aaiResponseAsString = response.getResponseBodyAsString() + + if (returnCode=='200') { + execution.setVariable(Prefix + "requeryIdAAIResponse", aaiResponseAsString) + msoLogger.debug(" ReQueryAAINetworkId Success REST Response - " + "\n" + aaiResponseAsString) + + String netName = utils.getNodeText(aaiResponseAsString, "network-name") + String networkOutputs = + """<network-outputs> + <network-id>${MsoUtils.xmlEscape(netId)}</network-id> + <network-name>${MsoUtils.xmlEscape(netName)}</network-name> + </network-outputs>""" + execution.setVariable(Prefix + "networkOutputs", networkOutputs) + msoLogger.debug(" networkOutputs - " + '\n' + networkOutputs) + + } else { + if (returnCode=='404') { + String dataErrorMessage = "Response Error from ReQueryAAINetworkId is 404 (Not Found)." + msoLogger.debug(" AAI ReQuery Failed. - " + dataErrorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + + } else { + if (aaiResponseAsString.contains("RESTFault")) { + WorkflowException exceptionObject = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) + execution.setVariable("WorkflowException", exceptionObject) + throw new BpmnError("MSOWorkflowException") + + } else { + // aai all errors + String dataErrorMessage = "Unexpected Response from ReQueryAAINetworkId - " + returnCode + msoLogger.debug(dataErrorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + + } + } + } + + } catch (BpmnError e) { + throw e; + + } catch (Exception ex) { + String exceptionMessage = "Bpmn error encountered in DoCreateNetworkInstance flow. callRESTReQueryAAINetworkId() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + public void callRESTQueryAAINetworkVpnBinding(DelegateExecution execution) { + + execution.setVariable("prefix",Prefix) + + msoLogger.debug(" ***** Inside callRESTQueryAAINetworkVpnBinding() of DoCreateNetworkInstance ***** " ) + + try { + + // get variables + String queryIdAAIResponse = execution.getVariable(Prefix + "queryIdAAIResponse").replace('<?xml version="1.0" encoding="UTF-8"?>', "") + String relationship = networkUtils.getFirstNodeXml(queryIdAAIResponse, "relationship-list").trim().replace("tag0:","").replace(":tag0","") + msoLogger.debug(" relationship - " + relationship) + + // Check if Vnf Binding is present, then build a List of vnfBinding + List vpnBindingUri = networkUtils.getVnfBindingObject(relationship) + int vpnCount = vpnBindingUri.size() + execution.setVariable(Prefix + "vpnCount", vpnCount) + msoLogger.debug(Prefix + "vpnCount - " + vpnCount) + + String aai_endpoint = UrnPropertiesReader.getVariable("aai.endpoint", execution) + AaiUtil aaiUriUtil = new AaiUtil(this) + + if (vpnCount > 0) { + execution.setVariable(Prefix + "vpnBindings", vpnBindingUri) + msoLogger.debug(" vpnBindingUri List - " + vpnBindingUri) + + String routeTargets = "" + // AII loop call using list vpnBindings + for (i in 0..vpnBindingUri.size()-1) { + + int counting = i+1 + + // prepare url using vpnBinding + String queryVpnBindingAAIRequest = "" + String aai_uri = aaiUriUtil.getNetworkVpnBindingUri(execution) + + // Note: By default, the vpnBinding url is found in 'related-link' of the response, + // so, the default in URN mappings for this is set to "" (ie, space), unless forced to use the URN mapping. + if (aai_uri == null || aai_uri == "") { + // using value of 'related-link' from response + if (vpnBindingUri[i].charAt(vpnBindingUri[i].length()-1) == '/') { + queryVpnBindingAAIRequest = "${aai_endpoint}" + vpnBindingUri[i].substring(0, vpnBindingUri[i].length()-1) + "?depth=all" + } else { + queryVpnBindingAAIRequest = "${aai_endpoint}" + vpnBindingUri[i] + "?depth=all" + } + + } else { + // using uri value in URN mapping + String vpnBindingId = vpnBindingUri[i].substring(vpnBindingUri[i].indexOf("/vpn-binding/")+13, vpnBindingUri[i].length()) + if (vpnBindingId.charAt(vpnBindingId.length()-1) == '/') { + vpnBindingId = vpnBindingId.substring(0, vpnBindingId.length()-1) + } + queryVpnBindingAAIRequest = "${aai_endpoint}${aai_uri}/" + vpnBindingId + "?depth=all" + } + + execution.setVariable(Prefix + "queryVpnBindingAAIRequest", queryVpnBindingAAIRequest) + msoLogger.debug(Prefix + "queryVpnBindingAAIRequest, , vpnBinding #" + counting + " : " + "\n" + queryVpnBindingAAIRequest) + + APIResponse response = aaiUriUtil.executeAAIGetCall(execution, queryVpnBindingAAIRequest) + String returnCode = response.getStatusCode() + execution.setVariable(Prefix + "aaiQqueryVpnBindingReturnCode", returnCode) + msoLogger.debug(" ***** AAI query vpn binding Response Code, vpnBinding #" + counting + " : " + returnCode) + + String aaiResponseAsString = response.getResponseBodyAsString() + + if (returnCode=='200') { + execution.setVariable(Prefix + "queryVpnBindingAAIResponse", aaiResponseAsString) + msoLogger.debug(" AAI Query Vpn Binding Success REST Response, , vpnBinding #" + counting + " : " + "\n" + aaiResponseAsString) + + String routeTarget = "" + String routeRole = "" + if (utils.nodeExists(aaiResponseAsString, "route-targets")) { + String aaiRouteTargets = utils.getNodeXml(aaiResponseAsString, "route-targets", false) + def aaiRouteTargetsXml = new XmlSlurper().parseText(aaiRouteTargets) + def aaiRouteTarget = aaiRouteTargetsXml.'**'.findAll {it.name() == "route-target"} + for (j in 0..aaiRouteTarget.size()-1) { + routeTarget = utils.getNodeText(XmlUtil.serialize(aaiRouteTarget[j]), "global-route-target") + routeRole = utils.getNodeText(XmlUtil.serialize(aaiRouteTarget[j]), "route-target-role") + routeTargets += "<routeTargets>" + '\n' + + " <routeTarget>" + routeTarget + "</routeTarget>" + '\n' + + " <routeTargetRole>" + routeRole + "</routeTargetRole>" + '\n' + + "</routeTargets>" + '\n' + } + } + + } else { + if (returnCode=='404') { + String dataErrorMessage = "Response Error from AAINetworkVpnBinding is 404 (Not Found)." + msoLogger.debug(dataErrorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + + } else { + if (aaiResponseAsString.contains("RESTFault")) { + WorkflowException exceptionObject = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) + execution.setVariable("WorkflowException", exceptionObject) + throw new BpmnError("MSOWorkflowException") + + } else { + // aai all errors + String dataErrorMessage = " Unexpected Response from AAINetworkVpnBinding - " + returnCode + msoLogger.debug(dataErrorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + + } + } + } + + } // end loop + + execution.setVariable(Prefix + "routeCollection", routeTargets) + msoLogger.debug(Prefix + "routeCollection - " + '\n' + routeTargets) + + } else { + // reset return code to success + execution.setVariable(Prefix + "aaiQqueryVpnBindingReturnCode", "200") + String aai_uri = aaiUriUtil.getNetworkL3NetworkUri(execution) + String schemaVersion = aaiUriUtil.getNamespaceFromUri(execution, aai_uri) + String aaiStubResponse = + """ <rest:payload contentType="text/xml" xmlns:rest="http://schemas.activebpel.org/REST/2007/12/01/aeREST.xsd"> + <vpn-binding xmlns="${schemaVersion}"> + <global-route-target/> + </vpn-binding> + </rest:payload>""" + String aaiStubResponseAsXml = utils.formatXml(aaiStubResponse) + execution.setVariable(Prefix + "queryVpnBindingAAIResponse", aaiStubResponseAsXml) + execution.setVariable(Prefix + "routeCollection", "<routeTargets/>") + msoLogger.debug(" No vpnBinding, using this stub as response - " + '\n' + aaiStubResponseAsXml) + + } + + } catch (BpmnError e) { + throw e; + + } catch (Exception ex) { + String exceptionMessage = "Bpmn error encountered in DoCreateNetworkInstance flow. callRESTQueryAAINetworkVpnBinding() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + public void callRESTQueryAAINetworkPolicy(DelegateExecution execution) { + + execution.setVariable("prefix",Prefix) + + msoLogger.debug(" ***** Inside callRESTQueryAAINetworkPolicy() of DoCreateNetworkInstance ***** " ) + + try { + // get variables + String queryIdAAIResponse = execution.getVariable(Prefix + "queryIdAAIResponse").replace('<?xml version="1.0" encoding="UTF-8"?>', "") + String relationship = networkUtils.getFirstNodeXml(queryIdAAIResponse, "relationship-list").trim().replace("tag0:","").replace(":tag0","") + msoLogger.debug(" relationship - " + relationship) + + // Check if Network Policy is present, then build a List of network policy + List networkPolicyUriList = networkUtils.getNetworkPolicyObject(relationship) + int networkPolicyCount = networkPolicyUriList.size() + execution.setVariable(Prefix + "networkPolicyCount", networkPolicyCount) + msoLogger.debug(Prefix + "networkPolicyCount - " + networkPolicyCount) + + String aai_endpoint = UrnPropertiesReader.getVariable("aai.endpoint", execution) + AaiUtil aaiUriUtil = new AaiUtil(this) + + if (networkPolicyCount > 0) { + execution.setVariable(Prefix + "networkPolicyUriList", networkPolicyUriList) + msoLogger.debug(" networkPolicyUri List - " + networkPolicyUriList) + + String networkPolicies = "" + // AII loop call using list vpnBindings + for (i in 0..networkPolicyUriList.size()-1) { + + int counting = i+1 + + // prepare url using vpnBinding + String queryNetworkPolicyAAIRequest = "" + + String aai_uri = aaiUriUtil.getNetworkPolicyUri(execution) + + // Note: By default, the network policy url is found in 'related-link' of the response, + // so, the default in URN mappings for this is set to "" (ie, space), unless forced to use the URN mapping. + if (aai_uri == null || aai_uri == "") { + // using value of 'related-link' from response + if (networkPolicyUriList[i].charAt(networkPolicyUriList[i].length()-1) == '/') { + queryNetworkPolicyAAIRequest = "${aai_endpoint}" + networkPolicyUriList[i].substring(0, networkPolicyUriList[i].length()-1) + "?depth=all" + } else { + queryNetworkPolicyAAIRequest = "${aai_endpoint}" + networkPolicyUriList[i] + "?depth=all" + } + } else { + // using uri value in URN mapping + String networkPolicyId = networkPolicyUriList[i].substring(networkPolicyUriList[i].indexOf("/network-policy/")+16, networkPolicyUriList[i].length()) + println " networkPolicyId - " + networkPolicyId + if (networkPolicyId.charAt(networkPolicyId.length()-1) == '/') { + networkPolicyId = networkPolicyId.substring(0, networkPolicyId.length()-1) + } + queryNetworkPolicyAAIRequest = "${aai_endpoint}${aai_uri}/" + networkPolicyId + "?depth=all" + + } + + + execution.setVariable(Prefix + "queryNetworkPolicyAAIRequest", queryNetworkPolicyAAIRequest) + msoLogger.debug(Prefix + "queryNetworkPolicyAAIRequest, , NetworkPolicy #" + counting + " : " + "\n" + queryNetworkPolicyAAIRequest) + + APIResponse response = aaiUriUtil.executeAAIGetCall(execution, queryNetworkPolicyAAIRequest) + String returnCode = response.getStatusCode() + execution.setVariable(Prefix + "aaiQqueryNetworkPolicyReturnCode", returnCode) + msoLogger.debug(" ***** AAI query network policy Response Code, NetworkPolicy #" + counting + " : " + returnCode) + + String aaiResponseAsString = response.getResponseBodyAsString() + + if (returnCode=='200') { + execution.setVariable(Prefix + "queryNetworkPolicyAAIResponse", aaiResponseAsString) + msoLogger.debug(" QueryAAINetworkPolicy Success REST Response, , NetworkPolicy #" + counting + " : " + "\n" + aaiResponseAsString) + + String networkPolicy = "" + if (utils.nodeExists(aaiResponseAsString, "network-policy-fqdn")) { + networkPolicy = utils.getNodeText(aaiResponseAsString, "network-policy-fqdn") + networkPolicies += "<policyFqdns>" + networkPolicy + "</policyFqdns>" + '\n' + } + + } else { + if (returnCode=='404') { + String dataErrorMessage = "Response Error from QueryAAINetworkPolicy is 404 (Not Found)." + msoLogger.debug(dataErrorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + + } else { + if (aaiResponseAsString.contains("RESTFault")) { + WorkflowException exceptionObject = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) + execution.setVariable("WorkflowException", exceptionObject) + throw new BpmnError("MSOWorkflowException") + + } else { + // aai all errors + String dataErrorMessage = "Unexpected Response from QueryAAINetworkPolicy - " + returnCode + msoLogger.debug(dataErrorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + + } + } + } + + } // end loop + + execution.setVariable(Prefix + "networkCollection", networkPolicies) + msoLogger.debug(Prefix + "networkCollection - " + '\n' + networkPolicies) + + } else { + // reset return code to success + execution.setVariable(Prefix + "aaiQqueryNetworkPolicyReturnCode", "200") + String aai_uri = aaiUriUtil.getNetworkL3NetworkUri(execution) + String schemaVersion = aaiUriUtil.getNamespaceFromUri(execution, aai_uri) + String aaiStubResponse = + """ <rest:payload contentType="text/xml" xmlns:rest="http://schemas.activebpel.org/REST/2007/12/01/aeREST.xsd"> + <network-policy xmlns="${schemaVersion}"> + <network-policy-fqdn/> + </network-policy> + </rest:payload>""" + String aaiStubResponseAsXml = utils.formatXml(aaiStubResponse) + execution.setVariable(Prefix + "queryNetworkPolicyAAIResponse", aaiStubResponseAsXml) + execution.setVariable(Prefix + "networkCollection", "<policyFqdns/>") + msoLogger.debug(" No net policies, using this stub as response - " + '\n' + aaiStubResponseAsXml) + + } + + } catch (BpmnError e) { + throw e; + + } catch (Exception ex) { + String exceptionMessage = "Bpmn error encountered in DoCreateNetworkInstance flow. callRESTQueryAAINetworkPolicy() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + public void callRESTQueryAAINetworkTableRef(DelegateExecution execution) { + + execution.setVariable("prefix",Prefix) + + msoLogger.debug(" ***** Inside callRESTQueryAAINetworkTableRef() of DoCreateNetworkInstance ***** " ) + + try { + // get variables + String queryIdAAIResponse = execution.getVariable(Prefix + "queryIdAAIResponse").replace('<?xml version="1.0" encoding="UTF-8"?>', "") + String relationship = networkUtils.getFirstNodeXml(queryIdAAIResponse, "relationship-list").trim().replace("tag0:","").replace(":tag0","") + msoLogger.debug(" relationship - " + relationship) + + // Check if Network TableREf is present, then build a List of network policy + List networkTableRefUriList = networkUtils.getNetworkTableRefObject(relationship) + int networkTableRefCount = networkTableRefUriList.size() + execution.setVariable(Prefix + "networkTableRefCount", networkTableRefCount) + msoLogger.debug(Prefix + "networkTableRefCount - " + networkTableRefCount) + + String aai_endpoint = UrnPropertiesReader.getVariable("aai.endpoint", execution) + AaiUtil aaiUriUtil = new AaiUtil(this) + + if (networkTableRefCount > 0) { + execution.setVariable(Prefix + "networkTableRefUriList", networkTableRefUriList) + msoLogger.debug(" networkTableRefUri List - " + networkTableRefUriList) + + // AII loop call using list vpnBindings + String networkTableRefs = "" + for (i in 0..networkTableRefUriList.size()-1) { + + int counting = i+1 + + // prepare url using tableRef + String queryNetworkTableRefAAIRequest = "" + + String aai_uri = aaiUriUtil.getNetworkTableReferencesUri(execution) + + // Note: By default, the network policy url is found in 'related-link' of the response, + // so, the default in URN mappings for this is set to "" (ie, space), unless forced to use the URN mapping. + if (aai_uri == null || aai_uri == "") { + // using value of 'related-link' from response + if (networkTableRefUriList[i].charAt(networkTableRefUriList[i].length()-1) == '/') { + queryNetworkTableRefAAIRequest = "${aai_endpoint}" + networkTableRefUriList[i].substring(0, networkTableRefUriList[i].length()-1) + "?depth=all" + } else { + queryNetworkTableRefAAIRequest = "${aai_endpoint}" + networkTableRefUriList[i] + "?depth=all" + } + } else { + // using uri value in URN mapping + String networkTableRefId = networkTableRefUriList[i].substring(networkTableRefUriList[i].indexOf("/route-table-reference/")+23, networkTableRefUriList[i].length()) + + if (networkTableRefId.charAt(networkTableRefId.length()-1) == '/') { + networkTableRefId = networkTableRefId.substring(0, networkTableRefId.length()-1) + } + queryNetworkTableRefAAIRequest = "${aai_endpoint}${aai_uri}/" + networkTableRefId + "?depth=all" + + } + + + execution.setVariable(Prefix + "queryNetworkTableRefAAIRequest", queryNetworkTableRefAAIRequest) + msoLogger.debug(Prefix + "queryNetworkTableRefAAIRequest, , NetworkTableRef #" + counting + " : " + "\n" + queryNetworkTableRefAAIRequest) + + APIResponse response = aaiUriUtil.executeAAIGetCall(execution, queryNetworkTableRefAAIRequest) + String returnCode = response.getStatusCode() + execution.setVariable(Prefix + "aaiQqueryNetworkTableRefReturnCode", returnCode) + msoLogger.debug(" ***** AAI query network Table Reference Response Code, NetworkTableRef #" + counting + " : " + returnCode) + + String aaiResponseAsString = response.getResponseBodyAsString() + + if (returnCode=='200') { + execution.setVariable(Prefix + "queryNetworkTableRefAAIResponse", aaiResponseAsString) + msoLogger.debug(" QueryAAINetworkTableRef Success REST Response, , NetworkTableRef #" + counting + " : " + "\n" + aaiResponseAsString) + + String networkTableRef = "" + if (utils.nodeExists(aaiResponseAsString, "route-table-reference-fqdn")) { + networkTableRef = utils.getNodeText(aaiResponseAsString, "route-table-reference-fqdn") + networkTableRefs += "<routeTableFqdns>" + networkTableRef + "</routeTableFqdns>" + '\n' + } + + } else { + if (returnCode=='404') { + String dataErrorMessage = "Response Error from QueryAAINetworkTableRef is 404 (Not Found)." + msoLogger.debug(dataErrorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + + } else { + if (aaiResponseAsString.contains("RESTFault")) { + WorkflowException exceptionObject = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) + execution.setVariable("WorkflowException", exceptionObject) + throw new BpmnError("MSOWorkflowException") + + } else { + // aai all errors + String dataErrorMessage = "Unexpected Response from QueryAAINetworkTableRef - " + returnCode + msoLogger.debug(dataErrorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + + } + } + } + + } // end loop + + execution.setVariable(Prefix + "tableRefCollection", networkTableRefs) + msoLogger.debug(Prefix + "tableRefCollection - " + '\n' + networkTableRefs) + + } else { + // reset return code to success + execution.setVariable(Prefix + "aaiQqueryNetworkTableRefReturnCode", "200") + String aai_uri = aaiUriUtil.getNetworkL3NetworkUri(execution) + String schemaVersion = aaiUriUtil.getNamespaceFromUri(execution, aai_uri) + String aaiStubResponse = + """ <rest:payload contentType="text/xml" xmlns:rest="http://schemas.activebpel.org/REST/2007/12/01/aeREST.xsd"> + <route-table-references xmlns="${schemaVersion}"> + <route-table-reference-fqdn/> + </route-table-references> + </rest:payload>""" + String aaiStubResponseAsXml = utils.formatXml(aaiStubResponse) + execution.setVariable(Prefix + "queryNetworkTableRefAAIResponse", aaiStubResponseAsXml) + execution.setVariable(Prefix + "tableRefCollection", "<routeTableFqdns/>") + msoLogger.debug(" No net table references, using this stub as response - " + '\n' + aaiStubResponseAsXml) + + } + + } catch (BpmnError e) { + throw e; + + } catch (Exception ex) { + String exceptionMessage = "Bpmn error encountered in DoCreateNetworkInstance flow. callRESTQueryAAINetworkTableRef() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + + public void callRESTUpdateContrailAAINetwork(DelegateExecution execution) { + + execution.setVariable("prefix",Prefix) + + msoLogger.debug(" ***** Inside callRESTUpdateContrailAAINetwork() of DoCreateNetworkInstance ***** " ) + + try { + // get variables + String networkId = execution.getVariable(Prefix + "networkId") + networkId = UriUtils.encode(networkId,"UTF-8") + String requeryIdAAIResponse = execution.getVariable(Prefix + "requeryIdAAIResponse") + String createNetworkResponse = execution.getVariable(Prefix + "createNetworkResponse") + + // Prepare url + String aai_endpoint = UrnPropertiesReader.getVariable("aai.endpoint", execution) + AaiUtil aaiUriUtil = new AaiUtil(this) + String aai_uri = aaiUriUtil.getNetworkL3NetworkUri(execution) + String updateContrailAAIUrlRequest = "${aai_endpoint}${aai_uri}/" + networkId + "?depth=all" + + execution.setVariable(Prefix + "updateContrailAAIUrlRequest", updateContrailAAIUrlRequest) + msoLogger.debug(Prefix + "updateContrailAAIUrlRequest - " + "\n" + updateContrailAAIUrlRequest) + + //Prepare payload (PUT) + String schemaVersion = aaiUriUtil.getNamespaceFromUri(execution, aai_uri) + String payload = networkUtils.ContrailNetworkCreatedUpdate(requeryIdAAIResponse, createNetworkResponse, schemaVersion) + String payloadXml = utils.formatXml(payload) + execution.setVariable(Prefix + "updateContrailAAIPayloadRequest", payloadXml) + msoLogger.debug(" 'payload' to Update Contrail - " + "\n" + payloadXml) + + APIResponse response = aaiUriUtil.executeAAIPutCall(execution, updateContrailAAIUrlRequest, payloadXml) + + String returnCode = response.getStatusCode() + execution.setVariable(Prefix + "aaiUpdateContrailReturnCode", returnCode) + msoLogger.debug(" ***** AAI Update Contrail Response Code : " + returnCode) + String aaiUpdateContrailResponseAsString = response.getResponseBodyAsString() + if (returnCode=='200') { + execution.setVariable(Prefix + "updateContrailAAIResponse", aaiUpdateContrailResponseAsString) + msoLogger.debug(" AAI Update Contrail Success REST Response - " + "\n" + aaiUpdateContrailResponseAsString) + // Point-of-no-return is set to false, rollback not needed. + String rollbackEnabled = execution.getVariable(Prefix + "rollbackEnabled") + if (rollbackEnabled == "true") { + execution.setVariable(Prefix + "isPONR", false) + } else { + execution.setVariable(Prefix + "isPONR", true) + } + msoLogger.debug(Prefix + "isPONR" + ": " + execution.getVariable(Prefix + "isPONR")) + } else { + if (returnCode=='404') { + String dataErrorMessage = " Response Error from UpdateContrailAAINetwork is 404 (Not Found)." + msoLogger.debug(dataErrorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + + } else { + if (aaiUpdateContrailResponseAsString.contains("RESTFault")) { + WorkflowException exceptionObject = exceptionUtil.MapAAIExceptionToWorkflowException(aaiUpdateContrailResponseAsString, execution) + execution.setVariable("WorkflowException", exceptionObject) + throw new BpmnError("MSOWorkflowException") + + } else { + // aai all errors + String errorMessage = "Unexpected Response from UpdateContrailAAINetwork - " + returnCode + msoLogger.debug(errorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, errorMessage) + } + } + } + + } catch (BpmnError e) { + throw e; + + } catch (Exception ex) { + String exceptionMessage = "Bpmn error encountered in DoCreateNetworkInstance flow. callRESTUpdateContrailAAINetwork() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + public void prepareCreateNetworkRequest (DelegateExecution execution) { + + execution.setVariable("prefix",Prefix) + + msoLogger.trace("Inside prepareCreateNetworkRequest() of DoCreateNetworkInstance") + + try { + + // get variables + String requestId = execution.getVariable("msoRequestId") + if (requestId == null) { + requestId = execution.getVariable("mso-request-id") + } + String messageId = execution.getVariable(Prefix + "messageId") + String source = execution.getVariable(Prefix + "source") + + String requestInput = execution.getVariable(Prefix + "networkRequest") + String queryIdResponse = execution.getVariable(Prefix + "queryIdAAIResponse") + String cloudRegionId = execution.getVariable(Prefix + "cloudRegionPo") + String backoutOnFailure = execution.getVariable(Prefix + "rollbackEnabled") + + // Prepare Network request + String routeCollection = execution.getVariable(Prefix + "routeCollection") + String policyCollection = execution.getVariable(Prefix + "networkCollection") + String tableCollection = execution.getVariable(Prefix + "tableRefCollection") + String createNetworkRequest = networkUtils.CreateNetworkRequestV2(execution, requestId, messageId, requestInput, queryIdResponse, routeCollection, policyCollection, tableCollection, cloudRegionId, backoutOnFailure, source ) + // Format Response + String buildDeleteNetworkRequestAsString = utils.formatXml(createNetworkRequest) + buildDeleteNetworkRequestAsString = buildDeleteNetworkRequestAsString.replace(":w1aac13n0", "").replace("w1aac13n0:", "") + + execution.setVariable(Prefix + "createNetworkRequest", buildDeleteNetworkRequestAsString) + msoLogger.debug(Prefix + "createNetworkRequest - " + "\n" + buildDeleteNetworkRequestAsString) + + } catch (Exception ex) { + String exceptionMessage = " Bpmn error encountered in DoCreateNetworkInstance flow. prepareCreateNetworkRequest() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + public void prepareSDNCRequest (DelegateExecution execution) { + + execution.setVariable("prefix",Prefix) + + msoLogger.trace("Inside prepareSDNCRequest() of DoCreateNetworkInstance") + + try { + // get variables + String sdncCallback = UrnPropertiesReader.getVariable("mso.workflow.sdncadapter.callback",execution) + String createNetworkInput = execution.getVariable(Prefix + "networkRequest") + String cloudRegionId = execution.getVariable(Prefix + "cloudRegionSdnc") + + String networkId = execution.getVariable(Prefix + "networkId") + String serviceInstanceId = execution.getVariable(Prefix + "serviceInstanceId") + + // get/set 'msoRequestId' and 'mso-request-id' + String requestId = execution.getVariable("msoRequestId") + if (requestId != null) { + execution.setVariable("mso-request-id", requestId) + } else { + requestId = execution.getVariable("mso-request-id") + } + execution.setVariable(Prefix + "requestId", requestId) + + // 1. prepare assign topology via SDNC Adapter SUBFLOW call + String sndcTopologyCreateRequest = sdncAdapterUtils.sdncTopologyRequestV2(execution, createNetworkInput, serviceInstanceId, sdncCallback, "assign", "NetworkActivateRequest", cloudRegionId, networkId, null, null) + + String sndcTopologyCreateRequesAsString = utils.formatXml(sndcTopologyCreateRequest) + execution.setVariable(Prefix + "assignSDNCRequest", sndcTopologyCreateRequesAsString) + msoLogger.debug(Prefix + "assignSDNCRequest - " + "\n" + sndcTopologyCreateRequesAsString) + + + } catch (Exception ex) { + String exceptionMessage = " Bpmn error encountered in DoCreateNetworkInstance flow. prepareSDNCRequest() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + public void prepareRpcSDNCRequest (DelegateExecution execution) { + + execution.setVariable("prefix",Prefix) + + msoLogger.trace("Inside prepareRpcSDNCRequest() of DoCreateNetworkInstance") + + try { + // get variables + + String sdncCallback = UrnPropertiesReader.getVariable("mso.workflow.sdncadapter.callback",execution) + String createNetworkInput = execution.getVariable(Prefix + "networkRequest") + String cloudRegionId = execution.getVariable(Prefix + "cloudRegionSdnc") + + String networkId = execution.getVariable(Prefix + "networkId") + String serviceInstanceId = execution.getVariable(Prefix + "serviceInstanceId") + + // 1. prepare assign topology via SDNC Adapter SUBFLOW call + String sndcTopologyCreateRequest = sdncAdapterUtils.sdncTopologyRequestRsrc(execution, createNetworkInput, serviceInstanceId, sdncCallback, "assign", "CreateNetworkInstance", cloudRegionId, networkId, null) + + String sndcTopologyCreateRequesAsString = utils.formatXml(sndcTopologyCreateRequest) + execution.setVariable(Prefix + "assignSDNCRequest", sndcTopologyCreateRequesAsString) + msoLogger.debug(Prefix + "assignSDNCRequest - " + "\n" + sndcTopologyCreateRequesAsString) + + } catch (Exception ex) { + String exceptionMessage = " Bpmn error encountered in DoCreateNetworkInstance flow. prepareRpcSDNCRequest() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + public void prepareRpcSDNCActivateRequest (DelegateExecution execution) { + + execution.setVariable("prefix",Prefix) + + msoLogger.trace("Inside prepareRpcSDNCActivateRequest() of DoCreateNetworkInstance") + + try { + // get variables + String sdncCallback = UrnPropertiesReader.getVariable("mso.workflow.sdncadapter.callback",execution) + String createNetworkInput = execution.getVariable(Prefix + "networkRequest") + String cloudRegionId = execution.getVariable(Prefix + "cloudRegionSdnc") + String networkId = execution.getVariable(Prefix + "networkId") + String serviceInstanceId = execution.getVariable(Prefix + "serviceInstanceId") + + // 1. prepare assign topology via SDNC Adapter SUBFLOW call + String sndcTopologyCreateRequest = sdncAdapterUtils.sdncTopologyRequestRsrc(execution, createNetworkInput, serviceInstanceId, sdncCallback, "activate", "CreateNetworkInstance", cloudRegionId, networkId, null) + + String sndcTopologyCreateRequesAsString = utils.formatXml(sndcTopologyCreateRequest) + execution.setVariable(Prefix + "activateSDNCRequest", sndcTopologyCreateRequesAsString) + msoLogger.debug(Prefix + "activateSDNCRequest - " + "\n" + sndcTopologyCreateRequesAsString) + + + } catch (Exception ex) { + String exceptionMessage = " Bpmn error encountered in DoCreateNetworkInstance flow. prepareRpcSDNCActivateRequest() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + + + + // ************************************************** + // Post or Validate Response Section + // ************************************************** + + public void validateCreateNetworkResponse (DelegateExecution execution) { + + execution.setVariable("prefix",Prefix) + + msoLogger.trace("Inside validateNetworkResponse() of DoCreateNetworkInstance") + + try { + String returnCode = execution.getVariable(Prefix + "networkReturnCode") + String networkResponse = execution.getVariable(Prefix + "createNetworkResponse") + if (networkResponse==null) { + networkResponse="" // reset + } + + msoLogger.debug(" Network Adapter create responseCode: " + returnCode) + + String errorMessage = "" + if (returnCode == "200") { + execution.setVariable(Prefix + "isNetworkRollbackNeeded", true) + execution.setVariable(Prefix + "createNetworkResponse", networkResponse) + msoLogger.debug(" Network Adapter create Success Response - " + "\n" + networkResponse) + + // prepare rollback data + String rollbackData = utils.getNodeXml(networkResponse, "rollback", false).replace("tag0:","").replace(":tag0","") + rollbackData = rollbackData.replace("rollback>", "networkRollback>") + String rollbackNetwork = + """<rollbackNetworkRequest> + ${rollbackData} + </rollbackNetworkRequest>""" + String rollbackNetworkXml = utils.formatXml(rollbackNetwork) + execution.setVariable(Prefix + "rollbackNetworkRequest", rollbackNetworkXml) + msoLogger.debug(" Network Adapter rollback data - " + "\n" + rollbackNetworkXml) + + } else { // network error + if (returnCode.toInteger() > 399 && returnCode.toInteger() < 600) { //4xx, 5xx + if (networkResponse.contains("createNetworkError")) { + networkResponse = networkResponse.replace('<?xml version="1.0" encoding="UTF-8" standalone="yes"?>', '') + errorMessage = utils.getNodeText(networkResponse, "message") + errorMessage = "Received error from Network Adapter: " + errorMessage + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, errorMessage) + + } else { // CatchAll exception + if (returnCode == "500") { + errorMessage = "JBWEB000065: HTTP Status 500." + } else { + errorMessage = "Return code is " + returnCode + } + errorMessage = "Received error from Network Adapter: " + errorMessage + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, errorMessage) + + } + + } else { // CatchAll exception + String dataErrorMessage = "Received error from Network Adapter. Return code is: " + returnCode + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + + } + + } + + } catch (BpmnError e) { + throw e; + + } catch (Exception ex) { + String exceptionMessage = " Bpmn error encountered in DoCreateNetworkInstance flow. validateCreateNetworkResponse() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + + + } + + public void validateSDNCResponse (DelegateExecution execution) { + + execution.setVariable("prefix",Prefix) + + msoLogger.trace("Inside validateSDNCResponse() of DoCreateNetworkInstance") + + String response = execution.getVariable(Prefix + "assignSDNCResponse") + boolean successIndicator = execution.getVariable("SDNCA_SuccessIndicator") + WorkflowException workflowException = execution.getVariable("WorkflowException") + + SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this) + sdncAdapterUtils.validateSDNCResponse(execution, response, workflowException, successIndicator) + // reset variable + String assignSDNCResponseDecodeXml = execution.getVariable(Prefix + "assignSDNCResponse") + assignSDNCResponseDecodeXml = assignSDNCResponseDecodeXml.replace('<?xml version="1.0" encoding="UTF-8"?>', "") + execution.setVariable(Prefix + "assignSDNCResponse", assignSDNCResponseDecodeXml) + + if (execution.getVariable(Prefix + "sdncResponseSuccess") == true) { // from sdnc util, Prefix+'sdncResponseSuccess' + execution.setVariable(Prefix + "isSdncRollbackNeeded", true) + msoLogger.debug("Successfully Validated SDNC Response") + + } else { + msoLogger.debug("Did NOT Successfully Validated SDNC Response") + throw new BpmnError("MSOWorkflowException") + } + + } + + public void validateRpcSDNCActivateResponse (DelegateExecution execution) { + + execution.setVariable("prefix",Prefix) + + msoLogger.trace("Inside validateRpcSDNCActivateResponse() of DoCreateNetworkInstance") + + String response = execution.getVariable(Prefix + "activateSDNCResponse") + boolean successIndicator = execution.getVariable("SDNCA_SuccessIndicator") + WorkflowException workflowException = execution.getVariable("WorkflowException") + + SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this) + sdncAdapterUtils.validateSDNCResponse(execution, response, workflowException, successIndicator) + // reset variable + String assignSDNCResponseDecodeXml = execution.getVariable(Prefix + "activateSDNCResponse") + assignSDNCResponseDecodeXml = assignSDNCResponseDecodeXml.replace('<?xml version="1.0" encoding="UTF-8"?>', "") + execution.setVariable(Prefix + "activateSDNCResponse", assignSDNCResponseDecodeXml) + + if (execution.getVariable(Prefix + "sdncResponseSuccess") == true) { // from sdnc util, Prefix+'sdncResponseSuccess' + execution.setVariable(Prefix + "isSdncActivateRollbackNeeded", true) + msoLogger.debug("Successfully Validated Rpc SDNC Activate Response") + + } else { + msoLogger.debug("Did NOT Successfully Validated Rpc SDNC Activate Response") + throw new BpmnError("MSOWorkflowException") + } + + } + + + public void prepareSDNCRollbackRequest (DelegateExecution execution) { + + execution.setVariable("prefix",Prefix) + + msoLogger.trace("Inside prepareSDNCRollbackRequest() of DoCreateNetworkInstance") + + try { + // get variables + String sdncCallback = UrnPropertiesReader.getVariable("mso.workflow.sdncadapter.callback",execution) + String createNetworkInput = execution.getVariable(Prefix + "networkRequest") + String cloudRegionId = execution.getVariable(Prefix + "cloudRegionSdnc") + String assignSDNCResponse = execution.getVariable(Prefix + "assignSDNCResponse") + String networkId = execution.getVariable(Prefix + "networkId") + if (networkId == 'null') {networkId = ""} + String serviceInstanceId = execution.getVariable(Prefix + "serviceInstanceId") + + // 2. prepare rollback topology via SDNC Adapter SUBFLOW call + String sndcTopologyRollbackRequest = sdncAdapterUtils.sdncTopologyRequestV2(execution, createNetworkInput, serviceInstanceId, sdncCallback, "rollback", "NetworkActivateRequest", cloudRegionId, networkId, null, null) + String sndcTopologyRollbackRequestAsString = utils.formatXml(sndcTopologyRollbackRequest) + execution.setVariable(Prefix + "rollbackSDNCRequest", sndcTopologyRollbackRequestAsString) + msoLogger.debug(" Preparing request for SDNC Topology 'rollback-NetworkActivateRequest' rollback . . . - " + "\n" + sndcTopologyRollbackRequestAsString) + + + } catch (Exception ex) { + String exceptionMessage = " Bpmn error encountered in DoCreateNetworkInstance flow. prepareSDNCRollbackRequest() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + public void prepareRpcSDNCRollbackRequest (DelegateExecution execution) { + + execution.setVariable("prefix",Prefix) + + msoLogger.trace("Inside prepareRpcSDNCRollbackRequest() of DoCreateNetworkInstance") + + try { + // get variables + String sdncCallback = UrnPropertiesReader.getVariable("mso.workflow.sdncadapter.callback",execution) + String createNetworkInput = execution.getVariable(Prefix + "networkRequest") + String cloudRegionId = execution.getVariable(Prefix + "cloudRegionSdnc") + String assignSDNCResponse = execution.getVariable(Prefix + "assignSDNCResponse") + String networkId = execution.getVariable(Prefix + "networkId") + if (networkId == 'null') {networkId = ""} + String serviceInstanceId = execution.getVariable(Prefix + "serviceInstanceId") + + // 2. prepare rollback topology via SDNC Adapter SUBFLOW call + String sndcTopologyRollbackRpcRequest = sdncAdapterUtils.sdncTopologyRequestRsrc(execution, createNetworkInput, serviceInstanceId, sdncCallback, "unassign", "DeleteNetworkInstance", cloudRegionId, networkId, null) + String sndcTopologyRollbackRpcRequestAsString = utils.formatXml(sndcTopologyRollbackRpcRequest) + execution.setVariable(Prefix + "rollbackSDNCRequest", sndcTopologyRollbackRpcRequestAsString) + msoLogger.debug(" Preparing request for SDNC Topology 'unassign-DeleteNetworkInstance' rollback . . . - " + "\n" + sndcTopologyRollbackRpcRequestAsString) + + + } catch (Exception ex) { + String exceptionMessage = " Bpmn error encountered in DoCreateNetworkInstance flow. prepareRpcSDNCRollbackRequest() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + public void prepareRpcSDNCActivateRollback(DelegateExecution execution) { + + execution.setVariable("prefix",Prefix) + + msoLogger.trace("Inside prepareRpcSDNCActivateRollback() of DoCreateNetworkInstance") + + try { + + // get variables + String sdncCallback = UrnPropertiesReader.getVariable("mso.workflow.sdncadapter.callback",execution) + String createNetworkInput = execution.getVariable(Prefix + "networkRequest") + String cloudRegionId = execution.getVariable(Prefix + "cloudRegionSdnc") + String activateSDNCResponse = execution.getVariable(Prefix + "activateSDNCResponse") + String networkId = execution.getVariable(Prefix + "networkId") + if (networkId == 'null') {networkId = ""} + String serviceInstanceId = execution.getVariable(Prefix + "serviceInstanceId") + + // 2. prepare rollback topology via SDNC Adapter SUBFLOW call + String sndcTopologyRollbackRpcRequest = sdncAdapterUtils.sdncTopologyRequestRsrc(execution, createNetworkInput, serviceInstanceId, sdncCallback, "deactivate", "DeleteNetworkInstance", cloudRegionId, networkId, null) + String sndcTopologyRollbackRpcRequestAsString = utils.formatXml(sndcTopologyRollbackRpcRequest) + execution.setVariable(Prefix + "rollbackActivateSDNCRequest", sndcTopologyRollbackRpcRequestAsString) + msoLogger.debug(" Preparing request for RPC SDNC Topology 'deactivate-DeleteNetworkInstance' rollback . . . - " + "\n" + sndcTopologyRollbackRpcRequestAsString) + + + } catch (Exception ex) { + String exceptionMessage = " Bpmn error encountered in DoCreateNetworkInstance flow. prepareRpcSDNCActivateRollback() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + public void prepareRollbackData(DelegateExecution execution) { + + execution.setVariable("prefix",Prefix) + + msoLogger.trace("Inside prepareRollbackData() of DoCreateNetworkInstance") + + try { + + Map<String, String> rollbackData = new HashMap<String, String>(); + String rollbackSDNCRequest = execution.getVariable(Prefix + "rollbackSDNCRequest") + if (rollbackSDNCRequest != null) { + if (rollbackSDNCRequest != "") { + rollbackData.put("rollbackSDNCRequest", execution.getVariable(Prefix + "rollbackSDNCRequest")) + } + } + String rollbackNetworkRequest = execution.getVariable(Prefix + "rollbackNetworkRequest") + if (rollbackNetworkRequest != null) { + if (rollbackNetworkRequest != "") { + rollbackData.put("rollbackNetworkRequest", execution.getVariable(Prefix + "rollbackNetworkRequest")) + } + } + String rollbackActivateSDNCRequest = execution.getVariable(Prefix + "rollbackActivateSDNCRequest") + if (rollbackActivateSDNCRequest != null) { + if (rollbackActivateSDNCRequest != "") { + rollbackData.put("rollbackActivateSDNCRequest", execution.getVariable(Prefix + "rollbackActivateSDNCRequest")) + } + } + execution.setVariable("rollbackData", rollbackData) + msoLogger.debug("** rollbackData : " + rollbackData) + + execution.setVariable("WorkflowException", execution.getVariable(Prefix + "WorkflowException")) + msoLogger.debug("** WorkflowException : " + execution.getVariable("WorkflowException")) + + } catch (Exception ex) { + String exceptionMessage = " Bpmn error encountered in DoCreateNetworkInstance flow. prepareRollbackData() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + public void postProcessResponse(DelegateExecution execution) { + + execution.setVariable("prefix",Prefix) + + msoLogger.trace("Inside postProcessResponse() of DoCreateNetworkInstance") + + try { + + //Conditions: + // 1. Silent Success: execution.getVariable("CRENWKI_orchestrationStatus") == "ACTIVE" + // 2. Success: execution.getVariable("WorkflowException") == null (NULL) + // 3. WorkflowException: execution.getVariable("WorkflowException") != null (NOT NULL) + + msoLogger.debug(" ***** Is Exception Encountered (isException)? : " + execution.getVariable(Prefix + "isException")) + // successful flow + if (execution.getVariable(Prefix + "isException") == false) { + // set rollback data + execution.setVariable("orchestrationStatus", "") + execution.setVariable("networkId", execution.getVariable(Prefix + "networkId")) + execution.setVariable("networkName", execution.getVariable(Prefix + "networkName")) + prepareSuccessRollbackData(execution) // populate rollbackData + execution.setVariable("WorkflowException", null) + execution.setVariable(Prefix + "Success", true) + msoLogger.debug(" ***** postProcessResponse(), GOOD !!!") + } else { + // inside sub-flow logic + execution.setVariable(Prefix + "Success", false) + execution.setVariable("rollbackData", null) + String exceptionMessage = " Exception encountered in MSO Bpmn. " + if (execution.getVariable("workflowException") != null) { // Output of Rollback flow. + msoLogger.debug(" ***** workflowException: " + execution.getVariable("workflowException")) + WorkflowException wfex = execution.getVariable("workflowException") + exceptionMessage = wfex.getErrorMessage() + } else { + if (execution.getVariable(Prefix + "WorkflowException") != null) { + WorkflowException pwfex = execution.getVariable(Prefix + "WorkflowException") + exceptionMessage = pwfex.getErrorMessage() + } + } + // going to the Main flow: a-la-carte or macro + msoLogger.debug(" ***** postProcessResponse(), BAD !!!") + exceptionUtil.buildWorkflowException(execution, 7000, exceptionMessage) + throw new BpmnError("MSOWorkflowException") + } + + } catch(BpmnError b){ + msoLogger.debug("Rethrowing MSOWorkflowException") + throw b + + } catch (Exception ex) { + String exceptionMessage = " Bpmn error encountered in DoCreateNetworkInstance flow. postProcessResponse() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildWorkflowException(execution, 7000, exceptionMessage) + throw new BpmnError("MSOWorkflowException") + + } + + + + } + + public void prepareSuccessRollbackData(DelegateExecution execution) { + + execution.setVariable("prefix",Prefix) + + msoLogger.trace("Inside prepareSuccessRollbackData() of DoCreateNetworkInstance") + + try { + + if (execution.getVariable("sdncVersion") != '1610') { + prepareRpcSDNCRollbackRequest(execution) + prepareRpcSDNCActivateRollback(execution) + } else { + prepareSDNCRollbackRequest(execution) + } + + Map<String, String> rollbackData = new HashMap<String, String>(); + String rollbackSDNCRequest = execution.getVariable(Prefix + "rollbackSDNCRequest") + if (rollbackSDNCRequest != null) { + if (rollbackSDNCRequest != "") { + rollbackData.put("rollbackSDNCRequest", rollbackSDNCRequest) + } + } + String rollbackNetworkRequest = execution.getVariable(Prefix + "rollbackNetworkRequest") + if (rollbackNetworkRequest != null) { + if (rollbackNetworkRequest != "") { + rollbackData.put("rollbackNetworkRequest", rollbackNetworkRequest) + } + } + String rollbackActivateSDNCRequest = execution.getVariable(Prefix + "rollbackActivateSDNCRequest") + if (rollbackActivateSDNCRequest != null) { + if (rollbackActivateSDNCRequest != "") { + rollbackData.put("rollbackActivateSDNCRequest", rollbackActivateSDNCRequest) + } + } + execution.setVariable("rollbackData", rollbackData) + + msoLogger.debug("** 'rollbackData' for Full Rollback : " + rollbackData) + execution.setVariable("WorkflowException", null) + + + } catch (Exception ex) { + String exceptionMessage = " Bpmn error encountered in DoCreateNetworkInstance flow. prepareSuccessRollbackData() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + public void setExceptionFlag(DelegateExecution execution){ + + execution.setVariable("prefix",Prefix) + + msoLogger.trace("Inside setExceptionFlag() of DoCreateNetworkInstance") + + try { + + execution.setVariable(Prefix + "isException", true) + + if (execution.getVariable("SavedWorkflowException1") != null) { + execution.setVariable(Prefix + "WorkflowException", execution.getVariable("SavedWorkflowException1")) + } else { + execution.setVariable(Prefix + "WorkflowException", execution.getVariable("WorkflowException")) + } + msoLogger.debug(Prefix + "WorkflowException - " +execution.getVariable(Prefix + "WorkflowException")) + + } catch(Exception ex){ + String exceptionMessage = "Bpmn error encountered in DoCreateNetworkInstance flow. setExceptionFlag(): " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildWorkflowException(execution, 7000, exceptionMessage) + } + + } + + + // ******************************* + // Build Error Section + // ******************************* + + + + public void processJavaException(DelegateExecution execution){ + + execution.setVariable("prefix",Prefix) + + try{ + msoLogger.debug( "Caught a Java Exception in " + Prefix) + msoLogger.debug("Started processJavaException Method") + msoLogger.debug("Variables List: " + execution.getVariables()) + execution.setVariable("UnexpectedError", "Caught a Java Lang Exception - " + Prefix) // Adding this line temporarily until this flows error handling gets updated + exceptionUtil.buildWorkflowException(execution, 500, "Caught a Java Lang Exception") + + }catch(Exception e){ + msoLogger.debug("Caught Exception during processJavaException Method: " + e) + execution.setVariable("UnexpectedError", "Exception in processJavaException method - " + Prefix) // Adding this line temporarily until this flows error handling gets updated + exceptionUtil.buildWorkflowException(execution, 500, "Exception in processJavaException method" + Prefix) + } + msoLogger.debug( "Completed processJavaException Method in " + Prefix) + } + +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateNetworkInstanceRollback.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateNetworkInstanceRollback.groovy new file mode 100644 index 0000000000..7e00f05b90 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateNetworkInstanceRollback.groovy @@ -0,0 +1,393 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts; + +import groovy.xml.XmlUtil + +import groovy.json.* +import org.onap.so.bpmn.core.UrnPropertiesReader +import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.logger.MsoLogger +import org.onap.so.logger.MessageEnum + +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.onap.so.bpmn.common.scripts.ExceptionUtil +import org.onap.so.bpmn.common.scripts.NetworkUtils +import org.onap.so.bpmn.common.scripts.SDNCAdapterUtils +import org.onap.so.bpmn.common.scripts.VidUtils +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.rest.APIResponse; +import org.onap.so.rest.RESTClient +import org.onap.so.rest.RESTConfig + +import java.util.UUID; + +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.apache.commons.lang3.* +import org.apache.commons.codec.binary.Base64; +import org.springframework.web.util.UriUtils + +/** + * This groovy class supports the <class>DoCreateNetworkInstance.bpmn</class> process. + * + */ +public class DoCreateNetworkInstanceRollback extends AbstractServiceTaskProcessor { + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoCreateNetworkInstanceRollback.class); + + String Prefix="CRENWKIR_" + ExceptionUtil exceptionUtil = new ExceptionUtil() + JsonUtils jsonUtil = new JsonUtils() + VidUtils vidUtils = new VidUtils(this) + NetworkUtils networkUtils = new NetworkUtils() + SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils() + + def className = getClass().getSimpleName() + + /** + * This method is executed during the preProcessRequest task of the <class>DoCreateNetworkInstanceRollback.bpmn</class> process. + * @param execution + */ + public InitializeProcessVariables(DelegateExecution execution){ + /* Initialize all the process variables in this block */ + + execution.setVariable(Prefix + "rollbackNetworkRequest", null) + execution.setVariable(Prefix + "rollbackSDNCRequest", null) + execution.setVariable(Prefix + "rollbackActivateSDNCRequest", null) + execution.setVariable(Prefix + "WorkflowException", null) + + execution.setVariable(Prefix + "rollbackNetworkRequest", "") + execution.setVariable(Prefix + "rollbackNetworkResponse", "") + execution.setVariable(Prefix + "rollbackNetworkReturnCode", "") + + execution.setVariable(Prefix + "rollbackSDNCRequest", "") + execution.setVariable(Prefix + "rollbackSDNCResponse", "") + execution.setVariable(Prefix + "rollbackSDNCReturnCode", "") + + execution.setVariable(Prefix + "rollbackActivateSDNCRequest", "") + execution.setVariable(Prefix + "rollbackActivateSDNCResponse", "") + execution.setVariable(Prefix + "rollbackActivateSDNCReturnCode", "") + + execution.setVariable(Prefix + "Success", false) + execution.setVariable(Prefix + "fullRollback", false) + execution.setVariable(Prefix + "networkId", "") + execution.setVariable(Prefix + "urlRollbackPoNetwork", "") + + } + + // ************************************************** + // Pre or Prepare Request Section + // ************************************************** + /** + * This method is executed during the preProcessRequest task of the <class>DoCreateNetworkInstanceRollback.bpmn</class> process. + * @param execution + */ + public void preProcessRequest (DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + + msoLogger.trace("Inside preProcessRequest() of " + className + ".groovy") + + try { + // initialize flow variables + InitializeProcessVariables(execution) + + // GET Incoming request/variables + String rollbackNetworkRequest = null + String rollbackSDNCRequest = null + String rollbackActivateSDNCRequest = null + + // Partial Rollback + Map<String, String> rollbackData = execution.getVariable("rollbackData") + if (rollbackData != null && rollbackData instanceof Map) { + + if(rollbackData.containsKey("rollbackSDNCRequest")) { + rollbackSDNCRequest = rollbackData["rollbackSDNCRequest"] + } + + if(rollbackData.containsKey("rollbackNetworkRequest")) { + rollbackNetworkRequest = rollbackData["rollbackNetworkRequest"] + } + + if(rollbackData.containsKey("rollbackActivateSDNCRequest")) { + rollbackActivateSDNCRequest = rollbackData["rollbackActivateSDNCRequest"] + } + + } + + execution.setVariable(Prefix + "rollbackNetworkRequest", rollbackNetworkRequest) + execution.setVariable(Prefix + "rollbackSDNCRequest", rollbackSDNCRequest) + execution.setVariable(Prefix + "rollbackActivateSDNCRequest", rollbackActivateSDNCRequest) + msoLogger.debug("'rollbackData': " + '\n' + execution.getVariable("rollbackData")) + + String sdncVersion = execution.getVariable("sdncVersion") + msoLogger.debug("sdncVersion? : " + sdncVersion) + + // PO Authorization Info / headers Authorization= + String basicAuthValuePO = UrnPropertiesReader.getVariable("mso.adapters.po.auth",execution) + try { + def encodedString = utils.getBasicAuth(basicAuthValuePO, UrnPropertiesReader.getVariable("mso.msoKey", execution)) + execution.setVariable("BasicAuthHeaderValuePO",encodedString) + execution.setVariable("BasicAuthHeaderValueSDNC", encodedString) + + } catch (IOException ex) { + String exceptionMessage = "Exception Encountered in DoCreateNetworkInstance, PreProcessRequest() - " + String dataErrorMessage = exceptionMessage + " Unable to encode PO/SDNC user/password string - " + ex.getMessage() + msoLogger.debug(dataErrorMessage ) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + } + + if (execution.getVariable("SavedWorkflowException1") != null) { + execution.setVariable(Prefix + "WorkflowException", execution.getVariable("SavedWorkflowException1")) + } else { + execution.setVariable(Prefix + "WorkflowException", execution.getVariable("WorkflowException")) + } + msoLogger.debug("*** WorkflowException : " + execution.getVariable(Prefix + "WorkflowException")) + if(execution.getVariable(Prefix + "WorkflowException") != null) { + // called by: DoCreateNetworkInstance, partial rollback + execution.setVariable(Prefix + "fullRollback", false) + + } else { + // called by: Macro - Full Rollback, WorkflowException = null + execution.setVariable(Prefix + "fullRollback", true) + + } + msoLogger.debug("*** fullRollback? : " + execution.getVariable(Prefix + "fullRollback")) + + + } catch (BpmnError e) { + throw e; + + } catch (Exception ex) { + // caught exception + String exceptionMessage = "Exception Encountered in PreProcessRequest() of " + className + ".groovy ***** : " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + public void callPONetworkAdapter (DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + + msoLogger.trace("Inside callPONetworkAdapter() of " + className + "") + + try { + String poUrl = UrnPropertiesReader.getVariable("mso.adapters.network.rest.endpoint",execution) + String rollbackSDNCRequest = execution.getVariable(Prefix + "rollbackSDNCRequest") + String networkId = utils.getNodeText(rollbackSDNCRequest, "network-id") + + String rollbackNetworkRequest = execution.getVariable(Prefix + "rollbackNetworkRequest") + + String urlRollbackPoNetwork = poUrl+ "/" + networkId + "/rollback" + msoLogger.debug("'urlRollbackPoNetwork': " + urlRollbackPoNetwork) + execution.setVariable(Prefix + "urlRollbackPoNetwork", urlRollbackPoNetwork) + + RESTConfig config = new RESTConfig(urlRollbackPoNetwork) + RESTClient client = new RESTClient(config). + addHeader("Content-Type", "application/xml"). + addAuthorizationHeader(execution.getVariable("BasicAuthHeaderValuePO")); + + APIResponse response = client.httpDelete(rollbackNetworkRequest) + String responseCode = response.getStatusCode() + String responseBody = response.getResponseBodyAsString() + + execution.setVariable(Prefix + "rollbackNetworkReturnCode", responseCode) + execution.setVariable(Prefix + "rollbackNetworkResponse", responseBody) + + msoLogger.debug(" Network Adapter rollback responseCode: " + responseCode) + msoLogger.debug(" Network Adapter rollback responseBody: " + responseBody) + + + } catch (Exception ex) { + String exceptionMessage = "Exception Encountered in callPONetworkAdapter() of DoCreateNetworkInstanceRollback flow - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + } + + } + + + public void validateRollbackResponses (DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + + msoLogger.trace("Inside validateRollbackResponses() of DoCreateNetworkInstanceRollback") + + try { + // validate PO network rollback response + String rollbackNetworkErrorMessages = "" + String rollbackNetworkReturnCode = "200" + if (execution.getVariable(Prefix + "rollbackNetworkRequest") != null) { + rollbackNetworkReturnCode = execution.getVariable(Prefix + "rollbackNetworkReturnCode") + String rollbackNetworkResponse = execution.getVariable(Prefix + "rollbackNetworkResponse") + msoLogger.debug(" NetworkRollback Code - " + rollbackNetworkReturnCode) + msoLogger.debug(" NetworkRollback Response - " + rollbackNetworkResponse) + if (rollbackNetworkReturnCode != "200") { + rollbackNetworkErrorMessages = " + PO Network rollback failed. " + } else { + rollbackNetworkErrorMessages = " + PO Network rollback completed." + } + } + + // validate SDNC rollback response + String rollbackSdncErrorMessages = "" + String rollbackSDNCReturnCode = "200" + if (execution.getVariable(Prefix + "rollbackSDNCRequest") != null) { + rollbackSDNCReturnCode = execution.getVariable(Prefix + "rollbackSDNCReturnCode") + String rollbackSDNCResponse = execution.getVariable(Prefix + "rollbackSDNCResponse") + String rollbackSDNCReturnInnerCode = "" + SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this) + rollbackSDNCResponse = rollbackSDNCResponse + rollbackSDNCResponse = rollbackSDNCResponse.replace('$', '').replace('<?xml version="1.0" encoding="UTF-8"?>', "") + if (rollbackSDNCReturnCode == "200") { + if (utils.nodeExists(rollbackSDNCResponse, "response-code")) { + rollbackSDNCReturnInnerCode = utils.getNodeText(rollbackSDNCResponse, "response-code") + if (rollbackSDNCReturnInnerCode == "200" || rollbackSDNCReturnInnerCode == "" || rollbackSDNCReturnInnerCode == "0") { + rollbackSdncErrorMessages = " + SNDC assign rollback completed." + } else { + rollbackSdncErrorMessages = " + SDNC assign rollback failed. " + } + } else { + rollbackSdncErrorMessages = " + SNDC assign rollback completed." + } + } else { + rollbackSdncErrorMessages = " + SDNC assign rollback failed. " + } + msoLogger.debug(" SDNC assign rollback Code - " + rollbackSDNCReturnCode) + msoLogger.debug(" SDNC assign rollback Response - " + rollbackSDNCResponse) + } + + // validate SDNC activate rollback response + String rollbackActivateSdncErrorMessages = "" + String rollbackActivateSDNCReturnCode = "200" + if (execution.getVariable(Prefix + "rollbackActivateSDNCRequest") != null) { + rollbackActivateSDNCReturnCode = execution.getVariable(Prefix + "rollbackActivateSDNCReturnCode") + String rollbackActivateSDNCResponse = execution.getVariable(Prefix + "rollbackActivateSDNCResponse") + String rollbackActivateSDNCReturnInnerCode = "" + rollbackActivateSDNCResponse = rollbackActivateSDNCResponse + rollbackActivateSDNCResponse = rollbackActivateSDNCResponse.replace('$', '').replace('<?xml version="1.0" encoding="UTF-8"?>', "") + if (rollbackActivateSDNCReturnCode == "200") { + if (utils.nodeExists(rollbackActivateSDNCResponse, "response-code")) { + rollbackActivateSDNCReturnInnerCode = utils.getNodeText(rollbackActivateSDNCResponse, "response-code") + if (rollbackActivateSDNCReturnInnerCode == "200" || rollbackActivateSDNCReturnInnerCode == "" || rollbackActivateSDNCReturnInnerCode == "0") { + rollbackActivateSdncErrorMessages = " + SNDC activate rollback completed." + } else { + rollbackActivateSdncErrorMessages = " + SDNC activate rollback failed. " + } + } else { + rollbackActivateSdncErrorMessages = " + SNDC activate rollback completed." + } + } else { + rollbackActivateSdncErrorMessages = " + SDNC activate rollback failed. " + } + msoLogger.debug(" SDNC activate rollback Code - " + rollbackActivateSDNCReturnCode) + msoLogger.debug(" SDNC activate rollback Response - " + rollbackActivateSDNCResponse) + } + + + String statusMessage = "" + int errorCode = 7000 + msoLogger.debug("*** fullRollback? : " + execution.getVariable(Prefix + "fullRollback")) + if (execution.getVariable(Prefix + "fullRollback") == false) { + // original WorkflowException, + WorkflowException wfe = execution.getVariable(Prefix + "WorkflowException") + if (wfe != null) { + // rollback due to failure in DoCreate - Partial rollback + statusMessage = wfe.getErrorMessage() + errorCode = wfe.getErrorCode() + } else { + statusMessage = "See Previous Camunda flows for cause of Error: Undetermined Exception." + errorCode = '7000' + } + + // set if all rolledbacks are successful + if (rollbackNetworkReturnCode == "200" && rollbackSDNCReturnCode == "200" && rollbackActivateSDNCReturnCode == "200") { + execution.setVariable("rolledBack", true) + execution.setVariable("wasDeleted", true) + + } else { + execution.setVariable("rolledBack", false) + execution.setVariable("wasDeleted", true) + } + + statusMessage = statusMessage + rollbackActivateSdncErrorMessages + rollbackNetworkErrorMessages + rollbackSdncErrorMessages + msoLogger.debug("Final DoCreateNetworkInstanceRollback status message: " + statusMessage) + String processKey = getProcessKey(execution); + WorkflowException exception = new WorkflowException(processKey, errorCode, statusMessage); + execution.setVariable("workflowException", exception); + + } else { + // rollback due to failures in Main flow (Macro) - Full rollback + // WorkflowException = null + if (rollbackNetworkReturnCode == "200" && rollbackSDNCReturnCode == "200" && rollbackActivateSDNCReturnCode == "200") { + execution.setVariable("rollbackSuccessful", true) + execution.setVariable("rollbackError", false) + } else { + String exceptionMessage = "Network Create Rollback was not Successful. " + msoLogger.debug(exceptionMessage) + execution.setVariable("rollbackSuccessful", false) + execution.setVariable("rollbackError", true) + exceptionUtil.buildWorkflowException(execution, 7000, exceptionMessage) + throw new BpmnError("MSOWorkflowException") + } + + } + + + } catch (Exception ex) { + String errorMessage = "See Previous Camunda flows for cause of Error: Undetermined Exception." + String exceptionMessage = " Bpmn error encountered in DoCreateNetworkInstanceRollback flow. validateRollbackResponses() - " + errorMessage + ": " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + // ******************************* + // Build Error Section + // ******************************* + + + + public void processJavaException(DelegateExecution execution){ + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + + try{ + msoLogger.debug("Caught a Java Exception in " + Prefix) + msoLogger.debug("Started processJavaException Method") + msoLogger.debug("Variables List: " + execution.getVariables()) + execution.setVariable("UnexpectedError", "Caught a Java Lang Exception - " + Prefix) // Adding this line temporarily until this flows error handling gets updated + exceptionUtil.buildWorkflowException(execution, 500, "Caught a Java Lang Exception") + + }catch(Exception e){ + msoLogger.debug("Caught Exception during processJavaException Method: " + e) + execution.setVariable("UnexpectedError", "Exception in processJavaException method - " + Prefix) // Adding this line temporarily until this flows error handling gets updated + exceptionUtil.buildWorkflowException(execution, 500, "Exception in processJavaException method" + Prefix) + } + msoLogger.debug("Completed processJavaException Method in " + Prefix) + } + +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateResources.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateResources.groovy new file mode 100644 index 0000000000..9591898ed0 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateResources.groovy @@ -0,0 +1,281 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2018 Huawei Technologies Co., Ltd. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts + +import org.codehaus.jackson.map.ObjectMapper +import org.onap.so.bpmn.infrastructure.properties.BPMNProperties + +import java.util.ArrayList +import java.util.Iterator +import java.util.List +import org.apache.commons.lang3.StringUtils +import org.apache.http.HttpResponse +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.codehaus.groovy.runtime.ArrayUtil +import org.codehaus.groovy.runtime.ScriptBytecodeAdapter +import org.codehaus.groovy.runtime.callsite.CallSite +import org.codehaus.groovy.runtime.typehandling.DefaultTypeTransformation +import org.codehaus.groovy.runtime.typehandling.ShortTypeHandling +import org.json.JSONArray +import org.json.JSONObject +import org.onap.so.bpmn.common.recipe.BpmnRestClient +import org.onap.so.bpmn.common.recipe.ResourceInput +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.onap.so.bpmn.common.scripts.CatalogDbUtils +import org.onap.so.bpmn.common.scripts.ExceptionUtil +import org.onap.so.bpmn.core.domain.AllottedResource +import org.onap.so.bpmn.core.domain.NetworkResource +import org.onap.so.bpmn.core.domain.Resource +import org.onap.so.bpmn.core.domain.ServiceDecomposition +import org.onap.so.bpmn.core.domain.VnfResource +import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.bpmn.common.resource.ResourceRequestBuilder +import org.onap.so.logger.MessageEnum +import org.onap.so.logger.MsoLogger + + + +/** + * This groovy class supports the <class>DoCreateResources.bpmn</class> process. + * + * Inputs: + * @param - msoRequestId + * @param - globalSubscriberId - O + * @param - subscriptionServiceType - O + * @param - serviceInstanceId + * @param - serviceInstanceName - O + * @param - serviceInputParams (should contain aic_zone for serviceTypes TRANSPORT,ATM) + * @param - sdncVersion + * + * @param - addResourceList + * + * Outputs: + * @param - WorkflowException + + */ +public class DoCreateResources extends AbstractServiceTaskProcessor{ + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoCreateResources.class); + + ExceptionUtil exceptionUtil = new ExceptionUtil() + JsonUtils jsonUtil = new JsonUtils() + CatalogDbUtils cutils = new CatalogDbUtils() + + public void preProcessRequest(DelegateExecution execution) + { + msoLogger.trace("preProcessRequest ") + String msg = "" + + List addResourceList = execution.getVariable("addResourceList") + if (addResourceList == null) + { + msg = "Input addResourceList is null" + msoLogger.info(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + else if (addResourceList.size() == 0) + { + msg = "No resource in addResourceList" + msoLogger.info(msg) + } + msoLogger.trace("Exit preProcessRequest ") + } + + public void sequenceResoure(DelegateExecution execution) + { + msoLogger.trace("Start sequenceResoure Process ") + + String serviceModelUUID = execution.getVariable("modelUuid") + + List<Resource> addResourceList = execution.getVariable("addResourceList") + + List<NetworkResource> networkResourceList = new ArrayList<NetworkResource>() + + List<Resource> sequencedResourceList = new ArrayList<Resource>() + + String serviceDecompose = execution.getVariable("serviceDecomposition") + String serviceModelName = jsonUtil.getJsonValue(serviceDecompose, "serviceResources.modelInfo.modelName") + def resourceSequence = BPMNProperties.getResourceSequenceProp(serviceModelName) + + if(resourceSequence != null) { + // sequence is defined in config file + for (resourceType in resourceSequence) { + for (resource in addResourceList) { + if (StringUtils.containsIgnoreCase(resource.getModelInfo().getModelName(), resourceType)) { + sequencedResourceList.add(resource) + + if (resource instanceof NetworkResource) { + networkResourceList.add(resource) + } + } + } + } + } else { + + //define sequenced resource list, we deploy vf first and then network and then ar + //this is defaule sequence + List<VnfResource> vnfResourceList = new ArrayList<VnfResource>() + List<AllottedResource> arResourceList = new ArrayList<AllottedResource>() + + for (Resource rc : addResourceList){ + if (rc instanceof VnfResource) { + vnfResourceList.add(rc) + } else if (rc instanceof NetworkResource) { + networkResourceList.add(rc) + } else if (rc instanceof AllottedResource) { + arResourceList.add(rc) + } + } + sequencedResourceList.addAll(vnfResourceList) + sequencedResourceList.addAll(networkResourceList) + sequencedResourceList.addAll(arResourceList) + } + + String isContainsWanResource = networkResourceList.isEmpty() ? "false" : "true" + execution.setVariable("isContainsWanResource", isContainsWanResource) + execution.setVariable("currentResourceIndex", 0) + execution.setVariable("sequencedResourceList", sequencedResourceList) + msoLogger.info("sequencedResourceList: " + sequencedResourceList) + msoLogger.trace("COMPLETED sequenceResoure Process ") + } + + public prepareServiceTopologyRequest(DelegateExecution execution) { + + def isDebugEnabled = execution.getVariable("isDebugLogEnabled") + utils.log("INFO", "======== Start prepareServiceTopologyRequest Process ======== ", isDebugEnabled) + + String serviceDecompose = execution.getVariable("serviceDecomposition") + + execution.setVariable("operationType", "create") + execution.setVariable("resourceType", "") + + String serviceInvariantUuid = jsonUtil.getJsonValue(serviceDecompose, "serviceResources.modelInfo.modelInvariantUuid") + String serviceUuid = jsonUtil.getJsonValue(serviceDecompose, "serviceResources.modelInfo.modelUuid") + String serviceModelName = jsonUtil.getJsonValue(serviceDecompose, "serviceResources.modelInfo.modelName") + + execution.setVariable("modelInvariantUuid", serviceInvariantUuid) + execution.setVariable("modelUuid", serviceUuid) + execution.setVariable("serviceModelName", serviceModelName) + + utils.log("INFO", "======== End prepareServiceTopologyRequest Process ======== ", isDebugEnabled) + } + + public void getCurrentResoure(DelegateExecution execution){ + msoLogger.trace("Start getCurrentResoure Process ") + def currentIndex = execution.getVariable("currentResourceIndex") + List<Resource> sequencedResourceList = execution.getVariable("sequencedResourceList") + Resource currentResource = sequencedResourceList.get(currentIndex) + execution.setVariable("resourceType", currentResource.getModelInfo().getModelName()) + msoLogger.info("Now we deal with resouce:" + currentResource.getModelInfo().getModelName()) + msoLogger.trace("COMPLETED getCurrentResoure Process ") + } + + public void parseNextResource(DelegateExecution execution){ + msoLogger.trace("Start parseNextResource Process ") + def currentIndex = execution.getVariable("currentResourceIndex") + def nextIndex = currentIndex + 1 + execution.setVariable("currentResourceIndex", nextIndex) + List<String> sequencedResourceList = execution.getVariable("sequencedResourceList") + if(nextIndex >= sequencedResourceList.size()){ + execution.setVariable("allResourceFinished", "true") + }else{ + execution.setVariable("allResourceFinished", "false") + } + msoLogger.trace("COMPLETED parseNextResource Process ") + } + + public void prepareResourceRecipeRequest(DelegateExecution execution){ + msoLogger.trace("Start prepareResourceRecipeRequest Process ") + ResourceInput resourceInput = new ResourceInput() + String serviceInstanceName = execution.getVariable("serviceInstanceName") + String resourceType = execution.getVariable("resourceType") + String resourceInstanceName = resourceType + "_" + serviceInstanceName + resourceInput.setResourceInstanceName(resourceInstanceName) + msoLogger.info("Prepare Resource Request resourceInstanceName:" + resourceInstanceName) + String globalSubscriberId = execution.getVariable("globalSubscriberId") + String serviceType = execution.getVariable("serviceType") + String serviceInstanceId = execution.getVariable("serviceInstanceId") + String operationId = execution.getVariable("operationId") + String operationType = "createInstance" + resourceInput.setGlobalSubscriberId(globalSubscriberId) + resourceInput.setServiceType(serviceType) + resourceInput.setServiceInstanceId(serviceInstanceId) + resourceInput.setOperationId(operationId) + resourceInput.setOperationType(operationType); + def currentIndex = execution.getVariable("currentResourceIndex") + List<Resource> sequencedResourceList = execution.getVariable("sequencedResourceList") + Resource currentResource = sequencedResourceList.get(currentIndex) + resourceInput.setResourceModelInfo(currentResource.getModelInfo()); + ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition") + resourceInput.setServiceModelInfo(serviceDecomposition.getModelInfo()); + def String resourceCustomizationUuid = currentResource.getModelInfo().getModelCustomizationUuid(); + + String incomingRequest = execution.getVariable("uuiRequest") + //set the requestInputs from tempalte To Be Done + String serviceModelUuid = jsonUtil.getJsonValue(incomingRequest,"service.serviceUuid") + String serviceParameters = jsonUtil.getJsonValue(incomingRequest, "service.parameters") + String resourceParameters = ResourceRequestBuilder.buildResourceRequestParameters(execution, serviceModelUuid, resourceCustomizationUuid, serviceParameters) + resourceInput.setResourceParameters(resourceParameters) + resourceInput.setRequestsInputs(incomingRequest) + execution.setVariable("resourceInput", resourceInput) + msoLogger.trace("COMPLETED prepareResourceRecipeRequest Process ") + } + + public void executeResourceRecipe(DelegateExecution execution){ + msoLogger.trace("Start executeResourceRecipe Process ") + + try { + String requestId = execution.getVariable("msoRequestId") + String serviceInstanceId = execution.getVariable("serviceInstanceId") + String serviceType = execution.getVariable("serviceType") + ResourceInput resourceInput = execution.getVariable("resourceInput") + + // requestAction is action, not opertiontype + //String requestAction = resourceInput.getOperationType() + String requestAction = "createInstance" + JSONObject resourceRecipe = cutils.getResourceRecipe(execution, resourceInput.getResourceModelInfo().getModelUuid(), requestAction) + + if (resourceRecipe != null) { + String recipeURL = BPMNProperties.getProperty("bpelURL", "http://mso:8080") + resourceRecipe.getString("orchestrationUri") + int recipeTimeOut = resourceRecipe.getInt("recipeTimeout") + String recipeParamXsd = resourceRecipe.get("paramXSD") + HttpResponse resp = BpmnRestClient.post(recipeURL, requestId, recipeTimeOut, requestAction, serviceInstanceId, serviceType, resourceInput.toString(), recipeParamXsd) + } else { + String exceptionMessage = "Resource receipe is not found for resource modeluuid: " + + resourceInput.getResourceModelInfo().getModelUuid() + utils.log("ERROR", exceptionMessage, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, exceptionMessage) + } + + msoLogger.trace("======== end executeResourceRecipe Process ======== ") + }catch(BpmnError b){ + msoLogger.debug("Rethrowing MSOWorkflowException") + throw b + }catch(Exception e){ + msoLogger.debug("Error occured within DoCreateResources executeResourceRecipe method: " + e) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured during DoCreateResources executeResourceRecipe Catalog") + } + } + + public void postConfigRequest(DelegateExecution execution){ + //now do noting + } +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateServiceInstance.groovy new file mode 100644 index 0000000000..b44940eb20 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateServiceInstance.groovy @@ -0,0 +1,753 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts; + +import static org.apache.commons.lang3.StringUtils.*; + +import org.apache.commons.lang3.* +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.onap.aai.domain.yang.OwningEntity +import org.onap.so.bpmn.common.scripts.AaiUtil +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.onap.so.bpmn.common.scripts.CatalogDbUtils +import org.onap.so.bpmn.common.scripts.ExceptionUtil +import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.so.bpmn.common.scripts.SDNCAdapterUtils +import org.onap.so.bpmn.core.RollbackData +import org.onap.so.bpmn.core.UrnPropertiesReader +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.bpmn.core.domain.ModelInfo +import org.onap.so.bpmn.core.domain.ServiceDecomposition +import org.onap.so.bpmn.core.domain.ServiceInstance +import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.bpmn.infrastructure.aai.groovyflows.AAICreateResources +import org.onap.so.logger.MessageEnum +import org.onap.so.logger.MsoLogger +import org.onap.so.rest.APIResponse +import org.springframework.web.util.UriUtils + +import groovy.json.* + +/** + * This groovy class supports the <class>DoCreateServiceInstance.bpmn</class> process. + * + * Inputs: + * @param - msoRequestId + * @param - globalSubscriberId + * @param - subscriptionServiceType + * @param - serviceInstanceId + * @param - serviceInstanceName - O + * @param - serviceModelInfo + * @param - productFamilyId + * @param - disableRollback + * @param - failExists - TODO + * @param - serviceInputParams (should contain aic_zone for serviceTypes TRANSPORT,ATM) + * @param - sdncVersion ("1610") + * @param - serviceDecomposition - Decomposition for R1710 + * (if macro provides serviceDecompsition then serviceModelInfo, serviceInstanceId & serviceInstanceName will be ignored) + * + * Outputs: + * @param - rollbackData (localRB->null) + * @param - rolledBack (no localRB->null, localRB F->false, localRB S->true) + * @param - WorkflowException + * @param - serviceInstanceName - (GET from AAI if null in input) + * + * This BB processes Macros(except TRANSPORT all sent to sdnc) and Alacartes(sdncSvcs && nonSdncSvcs) + */ +public class DoCreateServiceInstance extends AbstractServiceTaskProcessor { + + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoCreateServiceInstance.class); + String Prefix="DCRESI_" + ExceptionUtil exceptionUtil = new ExceptionUtil() + JsonUtils jsonUtil = new JsonUtils() + CatalogDbUtils cutils = new CatalogDbUtils() + + public void preProcessRequest (DelegateExecution execution) { + def isDebugEnabled = execution.getVariable("isDebugLogEnabled") + String msg = "" + msoLogger.trace("preProcessRequest") + + try { + String requestId = execution.getVariable("msoRequestId") + execution.setVariable("prefix", Prefix) + + setBasicDBAuthHeader(execution, isDebugEnabled) + //Inputs + //requestDetails.subscriberInfo. for AAI GET & PUT & SDNC assignToplology + String globalSubscriberId = execution.getVariable("globalSubscriberId") //globalCustomerId + + //requestDetails.requestParameters. for AAI PUT & SDNC assignTopology + String subscriptionServiceType = execution.getVariable("subscriptionServiceType") + + //requestDetails.requestParameters. for SDNC assignTopology + String productFamilyId = execution.getVariable("productFamilyId") //AAI productFamilyId + + if (isBlank(globalSubscriberId)) { + msg = "Input globalSubscriberId is null" + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + + if (isBlank(subscriptionServiceType)) { + msg = "Input subscriptionServiceType is null" + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + + if (productFamilyId == null) { + execution.setVariable("productFamilyId", "") + } + + String sdncCallbackUrl = UrnPropertiesReader.getVariable("mso.workflow.sdncadapter.callback",execution) + if (isBlank(sdncCallbackUrl)) { + msg = "mso.workflow.sdncadapter.callback is null" + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + execution.setVariable("sdncCallbackUrl", sdncCallbackUrl) + msoLogger.debug("SDNC Callback URL: " + sdncCallbackUrl) + + //requestDetails.modelInfo.for AAI PUT servieInstanceData & SDNC assignTopology + String modelInvariantUuid = "" + String modelVersion = "" + String modelUuid = "" + String modelName = "" + String serviceInstanceName = "" + //Generated in parent.for AAI PUT + String serviceInstanceId = "" + String serviceType = "" + String serviceRole = "" + + ServiceDecomposition serviceDecomp = (ServiceDecomposition) execution.getVariable("serviceDecomposition") + if (serviceDecomp != null) + { + serviceType = serviceDecomp.getServiceType() ?: "" + msoLogger.debug("serviceType:" + serviceType) + serviceRole = serviceDecomp.getServiceRole() ?: "" + + ServiceInstance serviceInstance = serviceDecomp.getServiceInstance() + if (serviceInstance != null) + { + serviceInstanceId = serviceInstance.getInstanceId() ?: "" + serviceInstanceName = serviceInstance.getInstanceName() ?: "" + execution.setVariable("serviceInstanceId", serviceInstanceId) + execution.setVariable("serviceInstanceName", serviceInstanceName) + } + + ModelInfo modelInfo = serviceDecomp.getModelInfo() + if (modelInfo != null) + { + modelInvariantUuid = modelInfo.getModelInvariantUuid() ?: "" + modelVersion = modelInfo.getModelVersion() ?: "" + modelUuid = modelInfo.getModelUuid() ?: "" + modelName = modelInfo.getModelName() ?: "" + } + else + { + msg = "Input serviceModelInfo is null" + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + } + else + { + //requestDetails.requestInfo. for AAI GET/PUT serviceInstanceData & SDNC assignToplology + serviceInstanceName = execution.getVariable("serviceInstanceName") ?: "" + serviceInstanceId = execution.getVariable("serviceInstanceId") ?: "" + + String serviceModelInfo = execution.getVariable("serviceModelInfo") + if (isBlank(serviceModelInfo)) { + msg = "Input serviceModelInfo is null" + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + modelInvariantUuid = jsonUtil.getJsonValue(serviceModelInfo, "modelInvariantUuid") ?: "" + modelVersion = jsonUtil.getJsonValue(serviceModelInfo, "modelVersion") ?: "" + modelUuid = jsonUtil.getJsonValue(serviceModelInfo, "modelUuid") ?: "" + modelName = jsonUtil.getJsonValue(serviceModelInfo, "modelName") ?: "" + //modelCustomizationUuid NA for SI + + } + + execution.setVariable("serviceType", serviceType) + execution.setVariable("serviceRole", serviceRole) + execution.setVariable("serviceInstanceName", serviceInstanceName) + + execution.setVariable("modelInvariantUuid", modelInvariantUuid) + execution.setVariable("modelVersion", modelVersion) + execution.setVariable("modelUuid", modelUuid) + execution.setVariable("modelName", modelName) + + //alacarte SIs are NOT sent to sdnc. exceptions are listed in config variable + String svcTypes = UrnPropertiesReader.getVariable("sdnc.si.svc.types",execution) ?: "" + msoLogger.debug("SDNC SI serviceTypes:" + svcTypes) + List<String> svcList = Arrays.asList(svcTypes.split("\\s*,\\s*")); + boolean isSdncService= false + for (String listEntry : svcList){ + if (listEntry.equalsIgnoreCase(serviceType)){ + isSdncService = true + break; + } + } + + //All Macros are sent to SDNC, TRANSPORT(Macro) is sent to SDNW + //Alacartes are sent to SDNC if they are listed in config variable above + execution.setVariable("sendToSDNC", true) + if(execution.getVariable("sdncVersion").equals("1610")) //alacarte + { + if(!isSdncService){ + execution.setVariable("sendToSDNC", false) + //alacarte non-sdnc svcs must provide name (sdnc provides name for rest) + if (isBlank(execution.getVariable("serviceInstanceName" ))) + { + msg = "Input serviceInstanceName must be provided for alacarte" + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + } + } + + msoLogger.debug("isSdncService: " + isSdncService) + msoLogger.debug("Send To SDNC: " + execution.getVariable("sendToSDNC")) + msoLogger.debug("Service Type: " + execution.getVariable("serviceType")) + + //macro may provide name and alacarte-portm may provide name + execution.setVariable("checkAAI", false) + if (!isBlank(execution.getVariable("serviceInstanceName" ))) + { + execution.setVariable("checkAAI", true) + } + + if (isBlank(serviceInstanceId)){ + msg = "Input serviceInstanceId is null" + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + + + StringBuilder sbParams = new StringBuilder() + Map<String, String> paramsMap = execution.getVariable("serviceInputParams") + if (paramsMap != null) + { + sbParams.append("<service-input-parameters>") + for (Map.Entry<String, String> entry : paramsMap.entrySet()) { + String paramsXml + String paramName = entry.getKey() + String paramValue = entry.getValue() + paramsXml = + """ <param> + <name>${MsoUtils.xmlEscape(paramName)}</name> + <value>${MsoUtils.xmlEscape(paramValue)}</value> + </param> + """ + sbParams.append(paramsXml) + } + sbParams.append("</service-input-parameters>") + } + String siParamsXml = sbParams.toString() + if (siParamsXml == null) + siParamsXml = "" + execution.setVariable("siParamsXml", siParamsXml) + + //AAI PUT + String oStatus = execution.getVariable("initialStatus") ?: "Active" + if ("TRANSPORT".equalsIgnoreCase(serviceType)) + { + oStatus = "Created" + } + + String statusLine = isBlank(oStatus) ? "" : "<orchestration-status>${MsoUtils.xmlEscape(oStatus)}</orchestration-status>" + String serviceTypeLine = isBlank(serviceType) ? "" : "<service-type>${MsoUtils.xmlEscape(serviceType)}</service-type>" + String serviceRoleLine = isBlank(serviceRole) ? "" : "<service-role>${MsoUtils.xmlEscape(serviceRole)}</service-role>" + + //QUERY CATALOG DB AND GET WORKLOAD / ENVIRONMENT CONTEXT + String environmentContext = "" + String workloadContext ="" + + try{ + String json = cutils.getServiceResourcesByServiceModelInvariantUuidString(execution,modelInvariantUuid ) + + msoLogger.debug("JSON IS: "+json) + + environmentContext = jsonUtil.getJsonValue(json, "serviceResources.environmentContext") ?: "" + workloadContext = jsonUtil.getJsonValue(json, "serviceResources.workloadContext") ?: "" + msoLogger.debug("Env Context is: "+ environmentContext) + msoLogger.debug("Workload Context is: "+ workloadContext) + }catch(BpmnError e){ + throw e + } catch (Exception ex){ + msg = "Exception in preProcessRequest " + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + + //Create AAI Payload + AaiUtil aaiUriUtil = new AaiUtil(this) + String aai_uri = aaiUriUtil.getBusinessCustomerUri(execution) + String namespace = aaiUriUtil.getNamespaceFromUri(aai_uri) + String serviceInstanceData = + """<service-instance xmlns=\"${namespace}\"> + <service-instance-name>${MsoUtils.xmlEscape(serviceInstanceName)}</service-instance-name> + ${serviceTypeLine} + ${serviceRoleLine} + ${statusLine} + <model-invariant-id>${MsoUtils.xmlEscape(modelInvariantUuid)}</model-invariant-id> + <model-version-id>${MsoUtils.xmlEscape(modelUuid)}</model-version-id> + <environment-context>${MsoUtils.xmlEscape(environmentContext)}</environment-context> + <workload-context>${MsoUtils.xmlEscape(workloadContext)}</workload-context> + </service-instance>""".trim() + + execution.setVariable("serviceInstanceData", serviceInstanceData) + msoLogger.debug(" 'payload' to create Service Instance in AAI - " + "\n" + serviceInstanceData) + + } catch (BpmnError e) { + throw e; + } catch (Exception ex){ + msg = "Exception in preProcessRequest " + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.trace("Exit preProcessRequest") + } + + public void getAAICustomerById (DelegateExecution execution) { + // https://{aaiEP}/aai/v8/business/customers/customer/{globalCustomerId} + def isDebugEnabled = execution.getVariable("isDebugLogEnabled") + String msg = "" + try { + + String globalCustomerId = execution.getVariable("globalSubscriberId") //VID to AAI name map + msoLogger.debug(" ***** getAAICustomerById ***** globalCustomerId:" + globalCustomerId) + + String aai_endpoint = UrnPropertiesReader.getVariable("aai.endpoint", execution) + AaiUtil aaiUriUtil = new AaiUtil(this) + String aai_uri = aaiUriUtil.getBusinessCustomerUri(execution) + if (isBlank(aai_endpoint) || isBlank(aai_uri)) + { + msg = "AAI URL is invalid. Endpoint:" + aai_endpoint + aai_uri + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + String getAAICustomerUrl = "${aai_endpoint}${aai_uri}/" + UriUtils.encode(globalCustomerId,"UTF-8") + + msoLogger.debug("getAAICustomerById Url:" + getAAICustomerUrl) + APIResponse response = aaiUriUtil.executeAAIGetCall(execution, getAAICustomerUrl) + String returnCode = response.getStatusCode() + String aaiResponseAsString = response.getResponseBodyAsString() + + msg = "getAAICustomerById ResponseCode:" + returnCode + " ResponseString:" + aaiResponseAsString + msoLogger.debug(msg) + + if (returnCode=='200') { + // Customer found by ID. FLow to proceed. + msoLogger.debug(msg) + + //TODO Deferred + //we might verify that service-subscription with matching name exists + //and throw error if not. If not checked, we will get exception in subsequent step on Create call + //in 1610 we assume both customer & service subscription were pre-created + + } else { + if (returnCode=='404') { + msg = "GlobalCustomerId:" + globalCustomerId + " not found (404) in AAI" + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg) + + } else { + if (aaiResponseAsString.contains("RESTFault")) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, aaiResponseAsString, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, ""); + WorkflowException workflowException = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) + execution.setVariable("WorkflowException", workflowException) + throw new BpmnError("MSOWorkflowException") + + } else { + // aai all errors + msg = "Error in getAAICustomerById ResponseCode:" + returnCode + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg) + } + } + } + + } catch (BpmnError e) { + throw e; + } catch (Exception ex) { + msg = "Exception in getAAICustomerById. " + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.trace("Exit getAAICustomerById") + + } + + public void postProcessAAIPUT(DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + msoLogger.trace("postProcessAAIPUT") + String msg = "" + try { + String serviceInstanceId = execution.getVariable("serviceInstanceId") + boolean succInAAI = execution.getVariable("GENPS_SuccessIndicator") + if(!succInAAI){ + msoLogger.debug("Error putting Service-instance in AAI", + serviceInstanceId) + WorkflowException workflowException = execution.getVariable("WorkflowException") + msoLogger.debug("workflowException: " + workflowException) + if(workflowException != null){ + exceptionUtil.buildAndThrowWorkflowException(execution, workflowException.getErrorCode(), workflowException.getErrorMessage()) + } + } + else + { + //start rollback set up + RollbackData rollbackData = new RollbackData() + def disableRollback = execution.getVariable("disableRollback") + rollbackData.put("SERVICEINSTANCE", "disableRollback", disableRollback.toString()) + rollbackData.put("SERVICEINSTANCE", "rollbackAAI", "true") + rollbackData.put("SERVICEINSTANCE", "serviceInstanceId", serviceInstanceId) + rollbackData.put("SERVICEINSTANCE", "subscriptionServiceType", execution.getVariable("subscriptionServiceType")) + rollbackData.put("SERVICEINSTANCE", "globalSubscriberId", execution.getVariable("globalSubscriberId")) + execution.setVariable("rollbackData", rollbackData) + } + + } catch (BpmnError e) { + throw e; + } catch (Exception ex) { + msg = "Exception in DoCreateServiceInstance.postProcessAAIDEL. " + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.trace("Exit postProcessAAIPUT") + } + + public void preProcessSDNCAssignRequest(DelegateExecution execution) { + def isDebugEnabled = execution.getVariable("isDebugLogEnabled") + String msg = "" + msoLogger.trace("preProcessSDNCAssignRequest") + + try { + def serviceInstanceId = execution.getVariable("serviceInstanceId") + def serviceInstanceName = execution.getVariable("serviceInstanceName") + def callbackURL = execution.getVariable("sdncCallbackUrl") + def requestId = execution.getVariable("msoRequestId") + def serviceId = execution.getVariable("productFamilyId") + def subscriptionServiceType = execution.getVariable("subscriptionServiceType") + def globalSubscriberId = execution.getVariable("globalSubscriberId") //globalCustomerId + def msoAction = "" + + def modelInvariantUuid = execution.getVariable("modelInvariantUuid") + def modelVersion = execution.getVariable("modelVersion") + def modelUuid = execution.getVariable("modelUuid") + def modelName = execution.getVariable("modelName") + + def sdncRequestId = UUID.randomUUID().toString() + + def siParamsXml = execution.getVariable("siParamsXml") + + // special URL for SDNW, msoAction helps set diff url in SDNCA + if("TRANSPORT".equalsIgnoreCase(execution.getVariable("serviceType"))) + { + msoAction = "TRANSPORT" + } + + String sdncAssignRequest = + """<sdncadapterworkflow:SDNCAdapterWorkflowRequest xmlns:ns5="http://org.onap/so/request/types/v1" + xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1" + xmlns:sdncadapter="http://org.onap/workflow/sdnc/adapter/schema/v1"> + <sdncadapter:RequestHeader> + <sdncadapter:RequestId>${MsoUtils.xmlEscape(sdncRequestId)}</sdncadapter:RequestId> + <sdncadapter:SvcInstanceId>${MsoUtils.xmlEscape(serviceInstanceId)}</sdncadapter:SvcInstanceId> + <sdncadapter:SvcAction>assign</sdncadapter:SvcAction> + <sdncadapter:SvcOperation>service-topology-operation</sdncadapter:SvcOperation> + <sdncadapter:CallbackUrl>${MsoUtils.xmlEscape(callbackURL)}</sdncadapter:CallbackUrl> + <sdncadapter:MsoAction>${MsoUtils.xmlEscape(msoAction)}</sdncadapter:MsoAction> + </sdncadapter:RequestHeader> + <sdncadapterworkflow:SDNCRequestData> + <request-information> + <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> + <source>MSO</source> + <notification-url/> + <order-number/> + <order-version/> + <request-action>CreateServiceInstance</request-action> + </request-information> + <service-information> + <service-id>${MsoUtils.xmlEscape(serviceId)}</service-id> + <subscription-service-type>${MsoUtils.xmlEscape(subscriptionServiceType)}</subscription-service-type> + <onap-model-information> + <model-invariant-uuid>${MsoUtils.xmlEscape(modelInvariantUuid)}</model-invariant-uuid> + <model-uuid>${MsoUtils.xmlEscape(modelUuid)}</model-uuid> + <model-version>${MsoUtils.xmlEscape(modelVersion)}</model-version> + <model-name>${MsoUtils.xmlEscape(modelName)}</model-name> + </onap-model-information> + <service-instance-id>${MsoUtils.xmlEscape(serviceInstanceId)}</service-instance-id> + <subscriber-name/> + <global-customer-id>${MsoUtils.xmlEscape(globalSubscriberId)}</global-customer-id> + </service-information> + <service-request-input> + <service-instance-name>${MsoUtils.xmlEscape(serviceInstanceName)}</service-instance-name> + ${siParamsXml} + </service-request-input> + </sdncadapterworkflow:SDNCRequestData> + </sdncadapterworkflow:SDNCAdapterWorkflowRequest>""" + + msoLogger.debug("sdncAssignRequest:\n" + sdncAssignRequest) + sdncAssignRequest = utils.formatXml(sdncAssignRequest) + execution.setVariable("sdncAssignRequest", sdncAssignRequest) + msoLogger.debug("sdncAssignRequest: " + sdncAssignRequest) + + def sdncRequestId2 = UUID.randomUUID().toString() + String sdncDelete = sdncAssignRequest.replace(">assign<", ">delete<").replace(">CreateServiceInstance<", ">DeleteServiceInstance<").replace(">${sdncRequestId}<", ">${sdncRequestId2}<") + def sdncRequestId3 = UUID.randomUUID().toString() + String sdncDeactivate = sdncDelete.replace(">delete<", ">deactivate<").replace(">${sdncRequestId2}<", ">${sdncRequestId3}<") + def rollbackData = execution.getVariable("rollbackData") + rollbackData.put("SERVICEINSTANCE", "sdncDeactivate", sdncDeactivate) + rollbackData.put("SERVICEINSTANCE", "sdncDelete", sdncDelete) + execution.setVariable("rollbackData", rollbackData) + + msoLogger.debug("rollbackData:\n" + rollbackData.toString()) + + } catch (BpmnError e) { + throw e; + } catch(Exception ex) { + msg = "Exception in preProcessSDNCAssignRequest. " + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.trace("Exit preProcessSDNCAssignRequest") + } + + public void postProcessSDNCAssign (DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + msoLogger.trace("postProcessSDNCAssign") + try { + WorkflowException workflowException = execution.getVariable("WorkflowException") + msoLogger.debug("workflowException: " + workflowException) + + boolean successIndicator = execution.getVariable("SDNCA_SuccessIndicator") + + String response = execution.getVariable("sdncAdapterResponse") + msoLogger.debug("SDNCResponse: " + response) + + SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this) + sdncAdapterUtils.validateSDNCResponse(execution, response, workflowException, successIndicator) + + if(execution.getVariable(Prefix + 'sdncResponseSuccess') == true){ + msoLogger.debug("Good response from SDNC Adapter for service-instance topology assign: \n" + response) + + def rollbackData = execution.getVariable("rollbackData") + rollbackData.put("SERVICEINSTANCE", "rollbackSDNC", "true") + execution.setVariable("rollbackData", rollbackData) + + }else{ + msoLogger.debug("Bad Response from SDNC Adapter for service-instance assign") + throw new BpmnError("MSOWorkflowException") + } + + } catch (BpmnError e) { + throw e; + } catch(Exception ex) { + msg = "Exception in postProcessSDNCAssign. " + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.trace("Exit postProcessSDNCAssign") + } + + public void postProcessAAIGET2(DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + msoLogger.trace("postProcessAAIGET2") + String msg = "" + + try { + String serviceInstanceName = execution.getVariable("serviceInstanceName") + boolean succInAAI = execution.getVariable("GENGS_SuccessIndicator") + if(!succInAAI){ + msoLogger.debug("Error getting Service-instance from AAI in postProcessAAIGET2", + serviceInstanceName) + WorkflowException workflowException = execution.getVariable("WorkflowException") + msoLogger.debug("workflowException: " + workflowException) + if(workflowException != null){ + exceptionUtil.buildAndThrowWorkflowException(execution, workflowException.getErrorCode(), workflowException.getErrorMessage()) + } + else + { + msg = "Failure in postProcessAAIGET2 GENGS_SuccessIndicator:" + succInAAI + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg) + } + } + else + { + boolean foundInAAI = execution.getVariable("GENGS_FoundIndicator") + if(foundInAAI){ + String aaiService = execution.getVariable("GENGS_service") + if (!isBlank(aaiService) && (utils.nodeExists(aaiService, "service-instance-name"))) { + execution.setVariable("serviceInstanceName", utils.getNodeText(aaiService, "service-instance-name")) + msoLogger.debug("Found Service-instance in AAI.serviceInstanceName:" + execution.getVariable("serviceInstanceName")) + } + } + } + } catch (BpmnError e) { + throw e; + } catch (Exception ex) { + msg = "Exception in DoCreateServiceInstance.postProcessAAIGET2 " + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.trace("Exit postProcessAAIGET2") + } + + public void preProcessRollback (DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + msoLogger.trace("preProcessRollback") + try { + + Object workflowException = execution.getVariable("WorkflowException"); + + if (workflowException instanceof WorkflowException) { + msoLogger.debug("Prev workflowException: " + workflowException.getErrorMessage()) + execution.setVariable("prevWorkflowException", workflowException); + //execution.setVariable("WorkflowException", null); + } + } catch (BpmnError e) { + msoLogger.debug("BPMN Error during preProcessRollback") + } catch(Exception ex) { + String msg = "Exception in preProcessRollback. " + ex.getMessage() + msoLogger.debug(msg) + } + msoLogger.trace("Exit preProcessRollback") + } + + public void postProcessRollback (DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + msoLogger.trace("postProcessRollback") + String msg = "" + try { + Object workflowException = execution.getVariable("prevWorkflowException"); + if (workflowException instanceof WorkflowException) { + msoLogger.debug("Setting prevException to WorkflowException: ") + execution.setVariable("WorkflowException", workflowException); + } + execution.setVariable("rollbackData", null) + } catch (BpmnError b) { + msoLogger.debug("BPMN Error during postProcessRollback") + throw b; + } catch(Exception ex) { + msg = "Exception in postProcessRollback. " + ex.getMessage() + msoLogger.debug(msg) + } + msoLogger.trace("Exit postProcessRollback") + } + + public void createProject(DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + msoLogger.trace("createProject") + + String bpmnRequest = execution.getVariable("requestJson") + String projectName = jsonUtil.getJsonValue(bpmnRequest, "requestDetails.project.projectName") + String serviceInstance = execution.getVariable("serviceInstanceId") + + msoLogger.debug("BPMN REQUEST IS: "+ bpmnRequest) + msoLogger.debug("PROJECT NAME: " + projectName) + msoLogger.debug("Service Instance: " + serviceInstance) + + if(projectName == null||projectName.equals("")){ + msoLogger.debug("Project Name was not found in input. Skipping task...") + }else{ + try{ + AAICreateResources aaiCR = new AAICreateResources() + aaiCR.createAAIProject(projectName, serviceInstance) + }catch(Exception ex){ + String msg = "Exception in createProject. " + ex.getMessage(); + msoLogger.debug(msg) + msoLogger.error(ex); + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + } + msoLogger.trace("Exit createProject") + } + + public void createOwningEntity(DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + msoLogger.trace("createOwningEntity") + String msg = ""; + String bpmnRequest = execution.getVariable("requestJson") + String owningEntityId = jsonUtil.getJsonValue(bpmnRequest, "requestDetails.owningEntity.owningEntityId") + String owningEntityName = jsonUtil.getJsonValue(bpmnRequest,"requestDetails.owningEntity.owningEntityName"); + String serviceInstance = execution.getVariable("serviceInstanceId") + + msoLogger.debug("owningEntity: " + owningEntityId) + msoLogger.debug("OwningEntityName: "+ owningEntityName) + msoLogger.debug("Service Instance: " + serviceInstance) + + try{ + AAICreateResources aaiCR = new AAICreateResources() + if(owningEntityId==null||owningEntityId.equals("")){ + msg = "Exception in createOwningEntity. OwningEntityId is null in input."; + throw new IllegalStateException(); + }else{ + if(aaiCR.existsOwningEntity(owningEntityId)){ + aaiCR.connectOwningEntityandServiceInstance(owningEntityId,serviceInstance) + }else{ + if(owningEntityName==null||owningEntityName.equals("")){ + msg = "Exception in createOwningEntity. Can't create an owningEntity without an owningEntityName in input."; + throw new IllegalStateException(); + }else{ + Optional<OwningEntity> owningEntity = aaiCR.getOwningEntityNames(owningEntityName); + if(owningEntity.isPresent()){ + msg = "Exception in createOwningEntity. Can't create OwningEntity as name already exists in AAI associated with a different owning-entity-id (name must be unique)."; + throw new IllegalStateException(); + } else { + aaiCR.createAAIOwningEntity(owningEntityId, owningEntityName, serviceInstance) + } + } + } + } + }catch(Exception ex){ + msoLogger.debug(msg) + msoLogger.error(ex); + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.trace("Exit createOwningEntity") + } + + // ******************************* + // Build Error Section + // ******************************* + + public void processJavaException(DelegateExecution execution){ + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + + try{ + msoLogger.debug("Caught a Java Exception in DoCreateServiceInstance") + msoLogger.debug("Started processJavaException Method") + msoLogger.debug("Variables List: " + execution.getVariables()) + execution.setVariable("UnexpectedError", "Caught a Java Lang Exception in DoCreateServiceInstance") // Adding this line temporarily until this flows error handling gets updated + exceptionUtil.buildWorkflowException(execution, 500, "Caught a Java Lang Exception in DoCreateServiceInstance") + + }catch(Exception e){ + msoLogger.debug("Caught Exception during processJavaException Method: " + e) + execution.setVariable("UnexpectedError", "Exception in processJavaException") // Adding this line temporarily until this flows error handling gets updated + exceptionUtil.buildWorkflowException(execution, 500, "Exception in processJavaException method") + } + msoLogger.trace("Completed processJavaException Method in DoCreateServiceInstance") + } + +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateServiceInstanceRollback.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateServiceInstanceRollback.groovy new file mode 100644 index 0000000000..dd56b8f2cc --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateServiceInstanceRollback.groovy @@ -0,0 +1,242 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts + + +import static org.apache.commons.lang3.StringUtils.*; +import groovy.xml.XmlUtil +import groovy.json.* + +import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.onap.so.bpmn.common.scripts.SDNCAdapterUtils +import org.onap.so.bpmn.core.RollbackData +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.rest.APIResponse; +import org.onap.so.rest.RESTClient +import org.onap.so.rest.RESTConfig +import org.onap.so.logger.MsoLogger +import org.onap.so.logger.MessageEnum + +import java.util.UUID; + +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.json.JSONObject; +import org.apache.commons.lang3.* +import org.apache.commons.codec.binary.Base64; +import org.springframework.web.util.UriUtils; +/** + * This groovy class supports the <class>DoCreateServiceInstanceRollback.bpmn</class> process. + * + * Inputs: + * @param - msoRequestId + * @param - rollbackData with + * globalCustomerId + * subscriptionServiceType + * serviceInstanceId + * disableRollback + * rollbackAAI + * rollbackSDNC + * sdncRollbackRequest + * + * + * Outputs: + * @param - rollbackError + * @param - rolledBack (no localRB->null, localRB F->false, localRB S->true) + * + */ +public class DoCreateServiceInstanceRollback extends AbstractServiceTaskProcessor{ + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoCreateServiceInstanceRollback.class); + + + String Prefix="DCRESIRB_" + + public void preProcessRequest(DelegateExecution execution) { + def isDebugEnabled = execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + String msg = "" + msoLogger.trace("preProcessRequest") + execution.setVariable("rollbackAAI",false) + execution.setVariable("rollbackSDNC",false) + + try { + def rollbackData = execution.getVariable("rollbackData") + msoLogger.debug("RollbackData:" + rollbackData) + + if (rollbackData != null) { + if (rollbackData.hasType("SERVICEINSTANCE")) { + + def serviceInstanceId = rollbackData.get("SERVICEINSTANCE", "serviceInstanceId") + execution.setVariable("serviceInstanceId", serviceInstanceId) + + def subscriptionServiceType = rollbackData.get("SERVICEINSTANCE", "subscriptionServiceType") + execution.setVariable("subscriptionServiceType", subscriptionServiceType) + + def globalSubscriberId = rollbackData.get("SERVICEINSTANCE", "globalSubscriberId") + execution.setVariable("globalSubscriberId", globalSubscriberId) + + def rollbackAAI = rollbackData.get("SERVICEINSTANCE", "rollbackAAI") + if ("true".equals(rollbackAAI)) + { + execution.setVariable("rollbackAAI",true) + } + + def rollbackSDNC = rollbackData.get("SERVICEINSTANCE", "rollbackSDNC") + if ("true".equals(rollbackSDNC)) + { + execution.setVariable("rollbackSDNC", true) + } + + if (execution.getVariable("rollbackAAI") != true && execution.getVariable("rollbackSDNC") != true) + { + execution.setVariable("skipRollback", true) + } + + def sdncDelete = rollbackData.get("SERVICEINSTANCE", "sdncDelete") + execution.setVariable("sdncDelete", sdncDelete) + def sdncDeactivate = rollbackData.get("SERVICEINSTANCE", "sdncDeactivate") + execution.setVariable("sdncDeactivate", sdncDeactivate) + msoLogger.debug("sdncDeactivate:\n" + sdncDeactivate) + msoLogger.debug("sdncDelete:\n" + sdncDelete) + } + else { + execution.setVariable("skipRollback", true) + } + } + else { + execution.setVariable("skipRollback", true) + } + if (execution.getVariable("disableRollback").equals("true" )) + { + execution.setVariable("skipRollback", true) + } + + } catch (BpmnError e) { + throw e; + } catch (Exception ex){ + msg = "Exception in Create ServiceInstance Rollback preProcessRequest " + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.trace("Exit preProcessRequest") + } + + public void validateSDNCResponse(DelegateExecution execution, String response, String method) { + + msoLogger.trace("validateSDNCResponse") + String msg = "" + try { + WorkflowException workflowException = execution.getVariable("WorkflowException") + boolean successIndicator = execution.getVariable("SDNCA_SuccessIndicator") + msoLogger.debug("SDNCResponse: " + response) + msoLogger.debug("workflowException: " + workflowException) + + SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this) + sdncAdapterUtils.validateSDNCResponse(execution, response, workflowException, successIndicator) + + if(execution.getVariable(Prefix + 'sdncResponseSuccess') == true){ + msg = "SDNC Adapter service-instance rollback successful for " + method + msoLogger.debug(msg) + }else{ + execution.setVariable("rolledBack", false) + msg = "Error Response from SDNC Adapter service-instance rollback for " + method + execution.setVariable("rollbackError", msg) + msoLogger.debug(msg) + throw new BpmnError("MSOWorkflowException") + } + } catch (BpmnError e) { + throw e; + } catch (Exception ex){ + msg = "Exception in Create ServiceInstance rollback for " + method + " Exception:" + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.trace("Exit validateSDNCResponse") + } + + public void postProcessRequest(DelegateExecution execution) { + + msoLogger.trace("postProcessRequest") + String msg = "" + try { + execution.setVariable("rollbackData", null) + String serviceInstanceId = execution.getVariable("serviceInstanceId") + boolean rollbackAAI = execution.getVariable("rollbackAAI") + boolean rollbackSDNC = execution.getVariable("rollbackSDNC") + if (rollbackAAI || rollbackSDNC) + { + execution.setVariable("rolledBack", true) + } + if (rollbackAAI) + { + boolean succInAAI = execution.getVariable("GENDS_SuccessIndicator") + if(!succInAAI){ + execution.setVariable("rolledBack", false) //both sdnc and aai must be successful to declare rollback Succesful + execution.setVariable("rollbackError", "Error deleting service-instance in AAI for rollback") + msoLogger.debug("Error deleting service-instance in AAI for rollback", + serviceInstanceId) + } + } + msoLogger.trace("Exit postProcessRequest") + + } catch (BpmnError e) { + msg = "Exception in Create ServiceInstance Rollback postProcessRequest. " + e.getMessage() + msoLogger.debug(msg) + } catch (Exception ex) { + msg = "Exception in Create ServiceInstance Rollback postProcessRequest. " + ex.getMessage() + msoLogger.debug(msg) + } + + } + + public void processRollbackException(DelegateExecution execution){ + + msoLogger.trace("processRollbackException") + try{ + msoLogger.debug("Caught an Exception in DoCreateServiceInstanceRollback") + execution.setVariable("rollbackData", null) + execution.setVariable("rollbackError", "Caught exception in ServiceInstance Create Rollback") + execution.setVariable("WorkflowException", null) + + }catch(BpmnError b){ + msoLogger.debug("BPMN Error during processRollbackExceptions Method: ") + }catch(Exception e){ + msoLogger.debug("Caught Exception during processRollbackExceptions Method: " + e.getMessage()) + } + + msoLogger.debug("Exit processRollbackException") + } + + public void processRollbackJavaException(DelegateExecution execution){ + + msoLogger.trace("processRollbackJavaException") + try{ + execution.setVariable("rollbackData", null) + execution.setVariable("rollbackError", "Caught Java exception in ServiceInstance Create Rollback") + msoLogger.debug("Caught Exception in processRollbackJavaException") + + }catch(Exception e){ + msoLogger.debug("Caught Exception in processRollbackJavaException " + e.getMessage()) + } + msoLogger.trace("Exit processRollbackJavaException") + } + +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVFCNetworkServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVFCNetworkServiceInstance.groovy new file mode 100644 index 0000000000..10f6acd403 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVFCNetworkServiceInstance.groovy @@ -0,0 +1,282 @@ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - SO + * ================================================================================ + * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts; + +import static org.apache.commons.lang3.StringUtils.*; + +import org.apache.commons.lang3.* +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.onap.so.bpmn.common.scripts.ExceptionUtil +import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.so.bpmn.core.UrnPropertiesReader; +import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.logger.MessageEnum +import org.onap.so.logger.MsoLogger +import org.onap.so.rest.APIResponse +import org.onap.so.rest.RESTClient +import org.onap.so.rest.RESTConfig + +import groovy.json.* + +/** + * This groovy class supports the <class>DoCreateVFCNetworkServiceInstance.bpmn</class> process. + * flow for VFC Network Service Create + */ +public class DoCreateVFCNetworkServiceInstance extends AbstractServiceTaskProcessor { + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoCreateVFCNetworkServiceInstance.class); + + String vfcUrl = "/vfc/rest/v1/vfcadapter" + + String host = "http://mso.mso.testlab.openecomp.org:8080" + + ExceptionUtil exceptionUtil = new ExceptionUtil() + + JsonUtils jsonUtil = new JsonUtils() + + /** + * Pre Process the BPMN Flow Request + * Inclouds: + * generate the nsOperationKey + * generate the nsParameters + */ + public void preProcessRequest (DelegateExecution execution) { + String msg = "" + msoLogger.trace("preProcessRequest()") + try { + //deal with nsName and Description + String nsServiceName = execution.getVariable("nsServiceName") + String nsServiceDescription = execution.getVariable("nsServiceDescription") + msoLogger.debug("nsServiceName:" + nsServiceName + " nsServiceDescription:" + nsServiceDescription) + //deal with operation key + String globalSubscriberId = execution.getVariable("globalSubscriberId") + msoLogger.debug("globalSubscriberId:" + globalSubscriberId) + String serviceType = execution.getVariable("serviceType") + msoLogger.debug("serviceType:" + serviceType) + String serviceId = execution.getVariable("serviceId") + msoLogger.debug("serviceId:" + serviceId) + String operationId = execution.getVariable("operationId") + msoLogger.debug("serviceType:" + serviceType) + String nodeTemplateUUID = execution.getVariable("resourceUUID") + msoLogger.debug("nodeTemplateUUID:" + nodeTemplateUUID) + /* + * segmentInformation needed as a object of segment + * { + * "domain":"", + * "nodeTemplateName":"", + * "nodeType":"", + * "nsParameters":{ + * //this is the nsParameters sent to VF-C + * } + * } + */ + String nsParameters = execution.getVariable("resourceParameters") + msoLogger.debug("nsParameters:" + nsParameters) + String nsOperationKey = """{ + "globalSubscriberId":"${globalSubscriberId}", + "serviceType":"${serviceType}", + "serviceId":"${serviceId}", + "operationId":"${operationId}", + "nodeTemplateUUID":"${nodeTemplateUUID}" + }""" + execution.setVariable("nsOperationKey", nsOperationKey); + execution.setVariable("nsParameters", nsParameters) + + + } catch (BpmnError e) { + throw e; + } catch (Exception ex){ + msg = "Exception in preProcessRequest " + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.trace("Exit preProcessRequest") + } + + /** + * create NS task + */ + public void createNetworkService(DelegateExecution execution) { + msoLogger.trace("createNetworkService") + String nsOperationKey = execution.getVariable("nsOperationKey"); + String nsParameters = execution.getVariable("nsParameters"); + String nsServiceName = execution.getVariable("nsServiceName") + String nsServiceDescription = execution.getVariable("nsServiceDescription") + String reqBody ="""{ + "nsServiceName":"${nsServiceName}", + "nsServiceDescription":"${nsServiceDescription}", + "nsOperationKey":${nsOperationKey}, + "nsParameters":${nsParameters} + }""" + APIResponse apiResponse = postRequest(execution, host + vfcUrl + "/ns", reqBody) + String returnCode = apiResponse.getStatusCode() + String aaiResponseAsString = apiResponse.getResponseBodyAsString() + String nsInstanceId = ""; + if(returnCode== "200" || returnCode == "201"){ + nsInstanceId = jsonUtil.getJsonValue(aaiResponseAsString, "nsInstanceId") + } + execution.setVariable("nsInstanceId", nsInstanceId) + msoLogger.trace("Exit createNetworkService") + } + + /** + * instantiate NS task + */ + public void instantiateNetworkService(DelegateExecution execution) { + msoLogger.trace("instantiateNetworkService") + String nsOperationKey = execution.getVariable("nsOperationKey"); + String nsParameters = execution.getVariable("nsParameters"); + String nsServiceName = execution.getVariable("nsServiceName") + String nsServiceDescription = execution.getVariable("nsServiceDescription") + String reqBody ="""{ + "nsServiceName":"${nsServiceName}", + "nsServiceDescription":"${nsServiceDescription}", + "nsOperationKey":${nsOperationKey}, + "nsParameters":${nsParameters} + }""" + String nsInstanceId = execution.getVariable("nsInstanceId") + String url = host + vfcUrl + "/ns/" +nsInstanceId + "/instantiate" + APIResponse apiResponse = postRequest(execution, url, reqBody) + String returnCode = apiResponse.getStatusCode() + String aaiResponseAsString = apiResponse.getResponseBodyAsString() + String jobId = ""; + if(returnCode== "200"|| returnCode == "201"){ + jobId = jsonUtil.getJsonValue(aaiResponseAsString, "jobId") + } + execution.setVariable("jobId", jobId) + msoLogger.trace("Exit instantiateNetworkService") + } + + /** + * query NS task + */ + public void queryNSProgress(DelegateExecution execution) { + msoLogger.trace("queryNSProgress") + String jobId = execution.getVariable("jobId") + String nsOperationKey = execution.getVariable("nsOperationKey"); + String url = host + vfcUrl + "/jobs/" + jobId + APIResponse apiResponse = postRequest(execution, url, nsOperationKey) + String returnCode = apiResponse.getStatusCode() + String aaiResponseAsString = apiResponse.getResponseBodyAsString() + String operationStatus = "error" + if(returnCode== "200"|| returnCode == "201"){ + operationStatus = jsonUtil.getJsonValue(aaiResponseAsString, "responseDescriptor.status") + } + execution.setVariable("operationStatus", operationStatus) + msoLogger.trace("Exit queryNSProgress") + } + + /** + * delay 5 sec + */ + public void timeDelay(DelegateExecution execution) { + try { + Thread.sleep(5000); + } catch(InterruptedException e) { + msoLogger.debug("Time Delay exception" + e ) + } + } + + /** + * finish NS task + */ + public void addNSRelationship(DelegateExecution execution) { + msoLogger.trace("addNSRelationship") + String nsInstanceId = execution.getVariable("nsInstanceId") + if(nsInstanceId == null || nsInstanceId == ""){ + msoLogger.debug(" create NS failed, so do not need to add relationship") + return + } + String globalSubscriberId = execution.getVariable("globalSubscriberId") + String serviceType = execution.getVariable("serviceType") + String serviceId = execution.getVariable("serviceId") + String addRelationPayload = """<relationship xmlns="http://org.openecomp.aai.inventory/v11"> + <related-to>service-instance</related-to> + <related-link>/aai/v11/business/customers/customer/${globalSubscriberId}/service-subscriptions/service-subscription/${serviceType}/service-instances/service-instance/${nsInstanceId}</related-link> + <relationship-data> + <relationship-key>customer.global-customer-id</relationship-key> + <relationship-value>${MsoUtils.xmlEscape(globalSubscriberId)}</relationship-value> + </relationship-data> + <relationship-data> + <relationship-key>service-subscription.service-type</relationship-key> + <relationship-value>${MsoUtils.xmlEscape(serviceType)}</relationship-value> + </relationship-data> + <relationship-data> + <relationship-key>service-instance.service-instance-id</relationship-key> + <relationship-value>${MsoUtils.xmlEscape(nsInstanceId)}</relationship-value> + </relationship-data> + </relationship>""" + String endpoint = UrnPropertiesReader.getVariable("aai.endpoint", execution) + msoLogger.debug("Add Relationship req:\n" + addRelationPayload) + String url = endpoint + "/aai/v11/business/customers/customer/" + globalSubscriberId + "/service-subscriptions/service-subscription/" + serviceType + "/service-instances/service-instance/" + serviceId + "/relationship-list/relationship" + APIResponse aaiRsp = executeAAIPutCall(execution, url, addRelationPayload) + msoLogger.debug("aai response status code:" + aaiRsp.getStatusCode()) + msoLogger.debug("aai response content:" + aaiRsp.getResponseBodyAsString()) + msoLogger.trace("Exit addNSRelationship") + } + + public APIResponse executeAAIPutCall(DelegateExecution execution, String url, String payload){ + msoLogger.trace("Started Execute AAI Put Process") + APIResponse apiResponse = null + try{ + String uuid = utils.getRequestID() + msoLogger.debug("Generated uuid is: " + uuid) + msoLogger.debug("URL to be used is: " + url) + String userName = UrnPropertiesReader.getVariable("aai.auth", execution) + String password = UrnPropertiesReader.getVariable("mso.msoKey", execution) + String basicAuthCred = utils.getBasicAuth(userName,password) + RESTConfig config = new RESTConfig(url); + RESTClient client = new RESTClient(config).addHeader("X-FromAppId", "MSO").addHeader("X-TransactionId", uuid).addHeader("Content-Type", "application/xml").addHeader("Accept","application/xml"); + if (basicAuthCred != null && !"".equals(basicAuthCred)) { + client.addAuthorizationHeader(basicAuthCred) + } + apiResponse = client.httpPut(payload) + msoLogger.trace("Completed Execute AAI Put Process") + }catch(Exception e){ + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception occured while executing AAI Put Call", "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + throw new BpmnError("MSOWorkflowException") + } + return apiResponse + } + + /** + * post request + * url: the url of the request + * requestBody: the body of the request + */ + private APIResponse postRequest(DelegateExecution execution, String url, String requestBody){ + msoLogger.trace("Started Execute VFC adapter Post Process") + msoLogger.debug("url:"+url +"\nrequestBody:"+ requestBody) + APIResponse apiResponse = null + try{ + RESTConfig config = new RESTConfig(url); + RESTClient client = new RESTClient(config).addHeader("Content-Type", "application/json").addHeader("Accept","application/json").addHeader("Authorization","Basic QlBFTENsaWVudDpwYXNzd29yZDEk"); + apiResponse = client.httpPost(requestBody) + msoLogger.debug("response code:"+ apiResponse.getStatusCode() +"\nresponse body:"+ apiResponse.getResponseBodyAsString()) + msoLogger.trace("Completed Execute VF-C adapter Post Process") + }catch(Exception e){ + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception occured while executing AAI Post Call", "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + throw new BpmnError("MSOWorkflowException") + } + return apiResponse + } +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModule.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModule.groovy new file mode 100644 index 0000000000..59d38bfe86 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModule.groovy @@ -0,0 +1,2133 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts + +import javax.xml.parsers.DocumentBuilder +import javax.xml.parsers.DocumentBuilderFactory + +import org.apache.commons.lang3.* +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.json.JSONArray +import org.json.JSONObject +import org.onap.so.bpmn.common.scripts.AaiUtil +import org.onap.so.bpmn.common.scripts.CatalogDbUtils +import org.onap.so.bpmn.common.scripts.ExceptionUtil +import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.so.bpmn.common.scripts.NetworkUtils +import org.onap.so.bpmn.common.scripts.SDNCAdapterUtils +import org.onap.so.bpmn.common.scripts.VfModuleBase +import org.onap.so.bpmn.core.RollbackData +import org.onap.so.bpmn.core.UrnPropertiesReader +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.bpmn.core.domain.CloudFlavor +import org.onap.so.bpmn.core.domain.VnfResource +import org.onap.so.bpmn.core.json.DecomposeJsonUtil +import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.client.aai.AAIObjectType; +import org.onap.so.client.aai.AAIResourcesClient +import org.onap.so.client.aai.entities.AAIResultWrapper +import org.onap.so.client.aai.entities.uri.AAIUri +import org.onap.so.client.aai.entities.uri.AAIUriFactory; +import org.onap.so.logger.MessageEnum +import org.onap.so.logger.MsoLogger +import org.onap.so.rest.APIResponse +import org.onap.so.rest.RESTClient +import org.onap.so.rest.RESTConfig +import org.springframework.web.util.UriUtils +import org.w3c.dom.Document +import org.w3c.dom.Element +import org.w3c.dom.NamedNodeMap +import org.w3c.dom.Node +import org.w3c.dom.NodeList +import org.xml.sax.InputSource + +import com.fasterxml.jackson.databind.ObjectMapper + + + +public class DoCreateVfModule extends VfModuleBase { + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoCreateVfModule.class); + + String Prefix="DCVFM_" + ExceptionUtil exceptionUtil = new ExceptionUtil() + JsonUtils jsonUtil = new JsonUtils() + SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this) + CatalogDbUtils catalog = new CatalogDbUtils() + DecomposeJsonUtil decomposeJsonUtils = new DecomposeJsonUtil() + + /** + * Validates the request message and sets up the workflow. + * @param execution the execution + */ + public void preProcessRequest(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.preProcessRequest(' + + 'execution=' + execution.getId() + + ')' + + msoLogger.trace('Entered ' + method) + + execution.setVariable('prefix', Prefix) + try{ + def rollbackData = execution.getVariable("rollbackData") + if (rollbackData == null) { + rollbackData = new RollbackData() + } + + execution.setVariable("DCVFM_vnfParamsExistFlag", false) + execution.setVariable("DCVFM_oamManagementV4Address", "") + execution.setVariable("DCVFM_oamManagementV6Address", "") + + String request = execution.getVariable("DoCreateVfModuleRequest") + + if (request == null || request.isEmpty()) { + // Building Block-type request + + String vfModuleModelInfo = execution.getVariable("vfModuleModelInfo") + + def serviceModelInfo = execution.getVariable("serviceModelInfo") + msoLogger.debug("serviceModelInfo: " + serviceModelInfo) + String modelInvariantUuid = jsonUtil.getJsonValue(serviceModelInfo, "modelInvariantUuid") + msoLogger.debug("modelInvariantUuid: " + modelInvariantUuid) + + def vnfModelInfo = execution.getVariable("vnfModelInfo") + + //tenantId + def tenantId = execution.getVariable("tenantId") + execution.setVariable("DCVFM_tenantId", tenantId) + rollbackData.put("VFMODULE", "tenantid", tenantId) + //volumeGroupId + def volumeGroupId = execution.getVariable("volumeGroupId") + execution.setVariable("DCVFM_volumeGroupId", volumeGroupId) + //volumeGroupName + def volumeGroupName = execution.getVariable("volumeGroupName") + execution.setVariable("DCVFM_volumeGroupName", volumeGroupName) + //cloudSiteId + def cloudSiteId = execution.getVariable("lcpCloudRegionId") + execution.setVariable("DCVFM_cloudSiteId", cloudSiteId) + rollbackData.put("VFMODULE", "aiccloudregion", cloudSiteId) + msoLogger.debug("cloudSiteId: " + cloudSiteId) + //vnfType + def vnfType = execution.getVariable("vnfType") + execution.setVariable("DCVFM_vnfType", vnfType) + rollbackData.put("VFMODULE", "vnftype", vnfType) + msoLogger.debug("vnfType: " + vnfType) + //vnfName + def vnfName = execution.getVariable("vnfName") + execution.setVariable("DCVFM_vnfName", vnfName) + rollbackData.put("VFMODULE", "vnfname", vnfName) + msoLogger.debug("vnfName: " + vnfName) + //vnfId + def vnfId = execution.getVariable("vnfId") + execution.setVariable("DCVFM_vnfId", vnfId) + rollbackData.put("VFMODULE", "vnfid", vnfId) + msoLogger.debug("vnfId: " + vnfId) + //vfModuleName + def vfModuleName = execution.getVariable("vfModuleName") + execution.setVariable("DCVFM_vfModuleName", vfModuleName) + rollbackData.put("VFMODULE", "vfmodulename", vfModuleName) + msoLogger.debug("vfModuleName: " + vfModuleName) + //vfModuleModelName + def vfModuleModelName = jsonUtil.getJsonValue(vfModuleModelInfo, "modelName") + execution.setVariable("DCVFM_vfModuleModelName", vfModuleModelName) + rollbackData.put("VFMODULE", "vfmodulemodelname", vfModuleModelName) + msoLogger.debug("vfModuleModelName: " + vfModuleModelName) + //modelCustomizationUuid + def modelCustomizationUuid = jsonUtil.getJsonValue(vfModuleModelInfo, "modelCustomizationUuid") + execution.setVariable("DCVFM_modelCustomizationUuid", modelCustomizationUuid) + rollbackData.put("VFMODULE", "modelcustomizationuuid", modelCustomizationUuid) + msoLogger.debug("modelCustomizationUuid: " + modelCustomizationUuid) + //vfModuleId + def vfModuleId = execution.getVariable("vfModuleId") + execution.setVariable("DCVFM_vfModuleId", vfModuleId) + msoLogger.debug("vfModuleId: " + vfModuleId) + def requestId = execution.getVariable("msoRequestId") + execution.setVariable("DCVFM_requestId", requestId) + msoLogger.debug("requestId: " + requestId) + rollbackData.put("VFMODULE", "msorequestid", requestId) + // Set mso-request-id to request-id for VNF Adapter interface + execution.setVariable("mso-request-id", requestId) + //serviceId + def serviceId = execution.getVariable("serviceId") + execution.setVariable("DCVFM_serviceId", serviceId) + msoLogger.debug("serviceId: " + serviceId) + //serviceInstanceId + def serviceInstanceId = execution.getVariable("serviceInstanceId") + execution.setVariable("DCVFM_serviceInstanceId", serviceInstanceId) + rollbackData.put("VFMODULE", "serviceInstanceId", serviceInstanceId) + msoLogger.debug("serviceInstanceId: " + serviceInstanceId) + //flavorList + ArrayList<CloudFlavor> flavorList = execution.getVariable(cloudSiteId + "_flavorList") + if (flavorList != null) { + execution.setVariable("DCVFM_flavorList", flavorList) + logDebug("flavorList is: " + flavorList, isDebugLogEnabled) + } + //source - HARDCODED + def source = "VID" + execution.setVariable("DCVFM_source", source) + rollbackData.put("VFMODULE", "source", source) + msoLogger.debug("source: " + source) + //backoutOnFailure + def disableRollback = execution.getVariable("disableRollback") + def backoutOnFailure = true + if (disableRollback != null && disableRollback == true) { + backoutOnFailure = false + } + execution.setVariable("DCVFM_backoutOnFailure", backoutOnFailure) + msoLogger.debug("backoutOnFailure: " + backoutOnFailure) + //isBaseVfModule + def isBaseVfModule = execution.getVariable("isBaseVfModule") + execution.setVariable("DCVFM_isBaseVfModule", isBaseVfModule) + msoLogger.debug("isBaseVfModule: " + isBaseVfModule) + //asdcServiceModelVersion + def asdcServiceModelVersion = execution.getVariable("asdcServiceModelVersion") + execution.setVariable("DCVFM_asdcServiceModelVersion", asdcServiceModelVersion) + msoLogger.debug("asdcServiceModelVersion: " + asdcServiceModelVersion) + //personaModelId + execution.setVariable("DCVFM_personaModelId", jsonUtil.getJsonValue(vfModuleModelInfo, "modelInvariantUuid")) + //personaModelVersion + execution.setVariable("DCVFM_personaModelVersion", jsonUtil.getJsonValue(vfModuleModelInfo, "modelUuid")) + //vfModuleLabel + def vfModuleLabel = execution.getVariable("vfModuleLabel") + if (vfModuleLabel != null) { + execution.setVariable("DCVFM_vfModuleLabel", vfModuleLabel) + msoLogger.debug("vfModuleLabel: " + vfModuleLabel) + } + //Get or Generate UUID + String uuid = execution.getVariable("DCVFM_uuid") + if(uuid == null){ + uuid = UUID.randomUUID() + msoLogger.debug("Generated messageId (UUID) is: " + uuid) + }else{ + msoLogger.debug("Found messageId (UUID) is: " + uuid) + } + //isVidRequest + String isVidRequest = execution.getVariable("isVidRequest") + // default to true + if (isVidRequest == null || isVidRequest.isEmpty()) { + execution.setVariable("isVidRequest", "true") + } + //globalSubscriberId + String globalSubscriberId = execution.getVariable("globalSubscriberId") + execution.setVariable("DCVFM_globalSubscriberId", globalSubscriberId) + msoLogger.debug("globalSubsrciberId: " + globalSubscriberId) + Map<String,String> vfModuleInputParams = execution.getVariable("vfModuleInputParams") + if (vfModuleInputParams != null) { + execution.setVariable("DCVFM_vnfParamsMap", vfModuleInputParams) + execution.setVariable("DCVFM_vnfParamsExistFlag", true) + } + //usePreload + def usePreload = execution.getVariable("usePreload") + execution.setVariable("DCVFM_usePreload", usePreload) + msoLogger.debug("usePreload: " + usePreload) + //aLaCarte + def aLaCarte = execution.getVariable("aLaCarte") + execution.setVariable("DCVFM_aLaCarte", aLaCarte) + msoLogger.debug("aLaCarte: " + aLaCarte) + + //get workload and environment context from parent SI + String environmentContext = "" + String workloadContext ="" + String serviceType ="" + + try{ + String json = catalog.getServiceResourcesByServiceModelInvariantUuidString(execution,modelInvariantUuid ) + serviceType = jsonUtil.getJsonValue(json, "serviceResources.serviceType") + }catch(BpmnError e){ + throw e + } catch (Exception ex){ + String msg = "Exception in preProcessRequest " + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + + try{ + AAIUri serviceInstanceURI = AAIUriFactory.create(AAIObjectType.SERVICE_INSTANCE, globalSubscriberId,serviceType,serviceInstanceId) + AAIResourcesClient aaiRC = new AAIResourcesClient() + AAIResultWrapper aaiRW = aaiRC.get(serviceInstanceURI) + Map<String, Object> aaiJson = aaiRW.asMap() + environmentContext = aaiJson.getOrDefault("environment-context","") + workloadContext = aaiJson.getOrDefault("workload-context","") + + }catch (Exception ex) { + msoLogger.debug("Error retreiving parent service instance information") + } + + execution.setVariable("DCVFM_environmentContext",environmentContext) + execution.setVariable("DCVFM_workloadContext",workloadContext) + + } + else { + // The info is inside the request - DEAD CODE + msoLogger.debug("DoCreateVfModule request: " + request) + + //tenantId + def tenantId = "" + if (utils.nodeExists(request, "tenant-id")) { + tenantId = utils.getNodeText(request, "tenant-id") + } + execution.setVariable("DCVFM_tenantId", tenantId) + rollbackData.put("VFMODULE", "tenantid", tenantId) + //volumeGroupId + def volumeGroupId = "" + if (utils.nodeExists(request, "volume-group-id")) { + volumeGroupId = utils.getNodeText(request, "volume-group-id") + } + execution.setVariable("DCVFM_volumeGroupId", volumeGroupId) + //volumeGroupId + def volumeGroupName = "" + if (utils.nodeExists(request, "volume-group-name")) { + volumeGroupName = utils.getNodeText(request, "volume-group-name") + } + execution.setVariable("DCVFM_volumeGroupName", volumeGroupName) + //cloudSiteId + def cloudSiteId = "" + if (utils.nodeExists(request, "aic-cloud-region")) { + cloudSiteId = utils.getNodeText(request, "aic-cloud-region") + } + execution.setVariable("DCVFM_cloudSiteId", cloudSiteId) + rollbackData.put("VFMODULE", "aiccloudregion", cloudSiteId) + msoLogger.debug("cloudSiteId: " + cloudSiteId) + //vnfType + def vnfType = "" + if (utils.nodeExists(request, "vnf-type")) { + vnfType = utils.getNodeText(request, "vnf-type") + } + execution.setVariable("DCVFM_vnfType", vnfType) + rollbackData.put("VFMODULE", "vnftype", vnfType) + msoLogger.debug("vnfType: " + vnfType) + //vnfName + def vnfName = "" + if (utils.nodeExists(request, "vnf-name")) { + vnfName = utils.getNodeText(request, "vnf-name") + } + execution.setVariable("DCVFM_vnfName", vnfName) + rollbackData.put("VFMODULE", "vnfname", vnfName) + msoLogger.debug("vnfName: " + vnfName) + //vnfId + def vnfId = "" + if (utils.nodeExists(request, "vnf-id")) { + vnfId = utils.getNodeText(request, "vnf-id") + } + execution.setVariable("DCVFM_vnfId", vnfId) + rollbackData.put("VFMODULE", "vnfid", vnfId) + msoLogger.debug("vnfId: " + vnfId) + //vfModuleName + def vfModuleName = "" + if (utils.nodeExists(request, "vf-module-name")) { + vfModuleName = utils.getNodeText(request, "vf-module-name") + } + execution.setVariable("DCVFM_vfModuleName", vfModuleName) + rollbackData.put("VFMODULE", "vfmodulename", vfModuleName) + msoLogger.debug("vfModuleName: " + vfModuleName) + //vfModuleModelName + def vfModuleModelName = "" + if (utils.nodeExists(request, "vf-module-model-name")) { + vfModuleModelName = utils.getNodeText(request, "vf-module-model-name") + } + execution.setVariable("DCVFM_vfModuleModelName", vfModuleModelName) + rollbackData.put("VFMODULE", "vfmodulemodelname", vfModuleModelName) + msoLogger.debug("vfModuleModelName: " + vfModuleModelName) + //modelCustomizationUuid + def modelCustomizationUuid = "" + if (utils.nodeExists(request, "model-customization-id")) { + modelCustomizationUuid = utils.getNodeText(request, "model-customization-id") + } + execution.setVariable("DCVFM_modelCustomizationUuid", modelCustomizationUuid) + rollbackData.put("VFMODULE", "modelcustomizationuuid", modelCustomizationUuid) + msoLogger.debug("modelCustomizationUuid: " + modelCustomizationUuid) + //vfModuleId + def vfModuleId = "" + if (utils.nodeExists(request, "vf-module-id")) { + vfModuleId = utils.getNodeText(request, "vf-module-id") + } + execution.setVariable("DCVFM_vfModuleId", vfModuleId) + msoLogger.debug("vfModuleId: " + vfModuleId) + def requestId = "" + if (utils.nodeExists(request, "request-id")) { + requestId = utils.getNodeText(request, "request-id") + } + execution.setVariable("DCVFM_requestId", requestId) + msoLogger.debug("requestId: " + requestId) + //serviceId + def serviceId = "" + if (utils.nodeExists(request, "service-id")) { + serviceId = utils.getNodeText(request, "service-id") + } + execution.setVariable("DCVFM_serviceId", serviceId) + msoLogger.debug("serviceId: " + serviceId) + //serviceInstanceId + def serviceInstanceId = "" + if (utils.nodeExists(request, "service-instance-id")) { + serviceInstanceId = utils.getNodeText(request, "service-instance-id") + } + execution.setVariable("DCVFM_serviceInstanceId", serviceInstanceId) + rollbackData.put("VFMODULE", "serviceInstanceId", serviceInstanceId) + msoLogger.debug("serviceInstanceId: " + serviceInstanceId) + //source + def source = "" + if (utils.nodeExists(request, "source")) { + source = utils.getNodeText(request, "source") + } + execution.setVariable("DCVFM_source", source) + rollbackData.put("VFMODULE", "source", source) + msoLogger.debug("source: " + source) + //backoutOnFailure + NetworkUtils networkUtils = new NetworkUtils() + def backoutOnFailure = networkUtils.isRollbackEnabled(execution,request) + execution.setVariable("DCVFM_backoutOnFailure", backoutOnFailure) + msoLogger.debug("backoutOnFailure: " + backoutOnFailure) + //isBaseVfModule + def isBaseVfModule = "false" + if (utils.nodeExists(request, "is-base-vf-module")) { + isBaseVfModule = utils.getNodeText(request, "is-base-vf-module") + } + execution.setVariable("DCVFM_isBaseVfModule", isBaseVfModule) + msoLogger.debug("isBaseVfModule: " + isBaseVfModule) + //asdcServiceModelVersion + def asdcServiceModelVersion = "" + if (utils.nodeExists(request, "asdc-service-model-version")) { + asdcServiceModelVersion = utils.getNodeText(request, "asdc-service-model-version") + } + execution.setVariable("DCVFM_asdcServiceModelVersion", asdcServiceModelVersion) + msoLogger.debug("asdcServiceModelVersion: " + asdcServiceModelVersion) + + //personaModelId + def personaModelId = "" + if (utils.nodeExists(request, "persona-model-id")) { + personaModelId = utils.getNodeText(request, "persona-model-id") + } + execution.setVariable("DCVFM_personaModelId", personaModelId) + msoLogger.debug("personaModelId: " + personaModelId) + + //personaModelVersion + def personaModelVersion = "" + if (utils.nodeExists(request, "persona-model-version")) { + personaModelVersion = utils.getNodeText(request, "persona-model-version") + } + execution.setVariable("DCVFM_personaModelVersion", personaModelVersion) + msoLogger.debug("personaModelVersion: " + personaModelVersion) + + // Process the parameters + + String vnfParamsChildNodes = utils.getChildNodes(request, "vnf-params") + if(vnfParamsChildNodes == null || vnfParamsChildNodes.length() < 1){ + msoLogger.debug("Request contains NO VNF Params") + }else{ + msoLogger.debug("Request does contain VNF Params") + execution.setVariable("DCVFM_vnfParamsExistFlag", true) + + InputSource xmlSource = new InputSource(new StringReader(request)); + DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); + docFactory.setNamespaceAware(true) + DocumentBuilder docBuilder = docFactory.newDocumentBuilder() + Document xml = docBuilder.parse(xmlSource) + //Get params, build map + Map<String, String> paramsMap = new HashMap<String, String>() + NodeList paramsList = xml.getElementsByTagNameNS("*", "param") + + for (int z = 0; z < paramsList.getLength(); z++) { + Node node = paramsList.item(z) + String paramValue = node.getTextContent() + NamedNodeMap e = node.getAttributes() + String paramName = e.getNamedItem("name").getTextContent() + paramsMap.put(paramName, paramValue) + } + execution.setVariable("DCVFM_vnfParamsMap", paramsMap) + } + } + + //Get or Generate UUID + String uuid = execution.getVariable("DCVFM_uuid") + if(uuid == null){ + uuid = UUID.randomUUID() + msoLogger.debug("Generated messageId (UUID) is: " + uuid) + }else{ + msoLogger.debug("Found messageId (UUID) is: " + uuid) + } + // Get sdncVersion, default to empty + String sdncVersion = execution.getVariable("sdncVersion") + if (sdncVersion == null) { + sdncVersion = "" + } + msoLogger.debug("sdncVersion: " + sdncVersion) + execution.setVariable("DCVFM_sdncVersion", sdncVersion) + + execution.setVariable("DCVFM_uuid", uuid) + execution.setVariable("DCVFM_baseVfModuleId", "") + execution.setVariable("DCVFM_baseVfModuleHeatStackId", "") + execution.setVariable("DCVFM_heatStackId", "") + execution.setVariable("DCVFM_contrailServiceInstanceFqdn", "") + execution.setVariable("DCVFM_volumeGroupStackId", "") + execution.setVariable("DCVFM_cloudRegionForVolume", "") + execution.setVariable("DCVFM_contrailNetworkPolicyFqdnList", "") + execution.setVariable("DCVFM_vnfTypeToQuery", "generic-vnf") + rollbackData.put("VFMODULE", "rollbackPrepareUpdateVfModule", "false") + rollbackData.put("VFMODULE", "rollbackUpdateAAIVfModule", "false") + rollbackData.put("VFMODULE", "rollbackVnfAdapterCreate", "false") + rollbackData.put("VFMODULE", "rollbackSDNCRequestActivate", "false") + rollbackData.put("VFMODULE", "rollbackSDNCRequestAssign", "false") + rollbackData.put("VFMODULE", "rollbackCreateAAIVfModule", "false") + rollbackData.put("VFMODULE", "rollbackCreateNetworkPoliciesAAI", "false") + rollbackData.put("VFMODULE", "rollbackUpdateVnfAAI", "false") + rollbackData.put("VFMODULE", "heatstackid", "") + + String sdncCallbackUrl = (String) UrnPropertiesReader.getVariable("mso.workflow.sdncadapter.callback",execution) + if (sdncCallbackUrl == null || sdncCallbackUrl.trim().isEmpty()) { + def msg = 'Required variable \'mso.workflow.sdncadapter.callback\' is missing' + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, msg, "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, msg); + + exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) + } + execution.setVariable("DCVFM_sdncCallbackUrl", sdncCallbackUrl) + msoLogger.debug("SDNC Callback URL is: " + sdncCallbackUrl) + + + execution.setVariable("rollbackData", rollbackData) + }catch(BpmnError b){ + throw b + }catch(Exception e){ + exceptionUtil.buildAndThrowWorkflowException(execution, 2000, "Internal Error encountered in PreProcess method!") + } + + msoLogger.trace('Exited ' + method) + } + + /** + * Validates a workflow response. + * @param execution the execution + * @param responseVar the execution variable in which the response is stored + * @param responseCodeVar the execution variable in which the response code is stored + * @param errorResponseVar the execution variable in which the error response is stored + */ + public void validateWorkflowResponse(DelegateExecution execution, String responseVar, + String responseCodeVar, String errorResponseVar) { + SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this) + sdncAdapterUtils.validateSDNCResponse(execution, responseVar, responseCodeVar, errorResponseVar) + } + + + /** + * Sends the empty, synchronous response back to the API Handler. + * @param execution the execution + */ + public void sendResponse(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.sendResponse(' + + 'execution=' + execution.getId() + + ')' + + msoLogger.trace('Entered ' + method) + + try { + sendWorkflowResponse(execution, 200, "") + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Internal Error') + } + } + + /** + * Using the received vnfId and vfModuleId, query AAI to get the corresponding VNF info. + * A 200 response is expected with the VNF info in the response body. Will find out the base module info + * and existing VNF's name for add-on modules + * + * @param execution The flow's execution instance. + */ + public void postProcessCreateAAIVfModule(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.getVfModule(' + + 'execution=' + execution.getId() + + ')' + + msoLogger.trace('Entered ' + method) + + try { + def createResponse = execution.getVariable('DCVFM_createVfModuleResponse') + msoLogger.debug("createVfModule Response: " + createResponse) + + def rollbackData = execution.getVariable("rollbackData") + String vnfName = utils.getNodeText(createResponse, 'vnf-name') + if (vnfName != null) { + execution.setVariable('DCVFM_vnfName', vnfName) + msoLogger.debug("vnfName retrieved from AAI is: " + vnfName) + rollbackData.put("VFMODULE", "vnfname", vnfName) + } + String vnfId = utils.getNodeText(createResponse, 'vnf-id') + execution.setVariable('DCVFM_vnfId', vnfId) + msoLogger.debug("vnfId is: " + vnfId) + String vfModuleId = utils.getNodeText(createResponse, 'vf-module-id') + execution.setVariable('DCVFM_vfModuleId', vfModuleId) + msoLogger.debug("vfModuleId is: " + vfModuleId) + String vfModuleIndex= utils.getNodeText(createResponse, 'vf-module-index') + execution.setVariable('DCVFM_vfModuleIndex', vfModuleIndex) + msoLogger.debug("vfModuleIndex is: " + vfModuleIndex) + rollbackData.put("VFMODULE", "vnfid", vnfId) + rollbackData.put("VFMODULE", "vfmoduleid", vfModuleId) + rollbackData.put("VFMODULE", "rollbackCreateAAIVfModule", "true") + rollbackData.put("VFMODULE", "rollbackPrepareUpdateVfModule", "true") + execution.setVariable("rollbackData", rollbackData) + } catch (Exception ex) { + ex.printStackTrace() + msoLogger.debug('Exception occurred while postProcessing CreateAAIVfModule request:' + ex.getMessage()) + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Bad response from CreateAAIVfModule' + ex.getMessage()) + } + msoLogger.trace('Exited ' + method) + } + + + /** + * Using the received vnfId and vfModuleId, query AAI to get the corresponding VNF info. + * A 200 response is expected with the VNF info in the response body. Will find out the base module info. + * + * @param execution The flow's execution instance. + */ + public void queryAAIVfModule(DelegateExecution execution) { + + def method = getClass().getSimpleName() + '.getVfModule(' + + 'execution=' + execution.getId() + + ')' + msoLogger.trace('Entered ' + method) + + try { + def vnfId = execution.getVariable('DCVFM_vnfId') + def vfModuleId = execution.getVariable('DCVFM_vfModuleId') + + AaiUtil aaiUriUtil = new AaiUtil(this) + String aai_uri = aaiUriUtil.getNetworkGenericVnfUri(execution) + msoLogger.debug('AAI URI is: ' + aai_uri) + + String endPoint = UrnPropertiesReader.getVariable("aai.endpoint", execution) + "${aai_uri}/" + UriUtils.encode(vnfId, "UTF-8") + "?depth=1" + + try { + RESTConfig config = new RESTConfig(endPoint); + def responseData = '' + def aaiRequestId = UUID.randomUUID().toString() + RESTClient client = new RESTClient(config). + addHeader('X-TransactionId', aaiRequestId). + addHeader('X-FromAppId', 'MSO'). + addHeader('Content-Type', 'application/xml'). + addHeader('Accept','application/xml'); + msoLogger.debug('sending GET to AAI endpoint \'' + endPoint + '\'') + APIResponse response = client.httpGet() + + responseData = response.getResponseBodyAsString() + if (responseData != null) { + msoLogger.debug("Received generic VNF data: " + responseData) + + } + + execution.setVariable('DCVFM_queryAAIVfModuleResponseCode', response.getStatusCode()) + execution.setVariable('DCVFM_queryAAIVfModuleResponse', responseData) + msoLogger.debug('Response code:' + response.getStatusCode()) + msoLogger.debug('Response:' + System.lineSeparator() + responseData) + if (response.getStatusCode() == 200) { + // Parse the VNF record from A&AI to find base module info + msoLogger.debug('Parsing the VNF data to find base module info') + if (responseData != null) { + def vfModulesText = utils.getNodeXml(responseData, "vf-modules") + def xmlVfModules= new XmlSlurper().parseText(vfModulesText) + def vfModules = xmlVfModules.'**'.findAll {it.name() == "vf-module"} + int vfModulesSize = 0 + for (i in 0..vfModules.size()-1) { + def vfModuleXml = groovy.xml.XmlUtil.serialize(vfModules[i]) + def isBaseVfModule = utils.getNodeText(vfModuleXml, "is-base-vf-module") + + if (isBaseVfModule == "true") { + String baseModuleId = utils.getNodeText(vfModuleXml, "vf-module-id") + execution.setVariable("DCVFM_baseVfModuleId", baseModuleId) + msoLogger.debug('Received baseVfModuleId: ' + baseModuleId) + String baseModuleHeatStackId = utils.getNodeText(vfModuleXml, "heat-stack-id") + execution.setVariable("DCVFM_baseVfModuleHeatStackId", baseModuleHeatStackId) + msoLogger.debug('Received baseVfModuleHeatStackId: ' + baseModuleHeatStackId) + } + } + } + } + } catch (Exception ex) { + ex.printStackTrace() + msoLogger.debug('Exception occurred while executing AAI GET:' + ex.getMessage()) + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'AAI GET Failed:' + ex.getMessage()) + } + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in queryAAIVfModule(): ' + e.getMessage()) + } + } + + /** + * Using the vnfId and vfModuleName provided in the inputs, + * query AAI to get the corresponding VF Module info. + * A 200 response is expected with the VF Module info in the response body, + * or a 404 response if the module does not exist yet. Will determine VF Module's + * orchestration status if one exists + * + * @param execution The flow's execution instance. + */ + public void queryAAIVfModuleForStatus(DelegateExecution execution) { + + def method = getClass().getSimpleName() + '.queryAAIVfModuleForStatus(' + + 'execution=' + execution.getId() + + ')' + msoLogger.trace('Entered ' + method) + + execution.setVariable('DCVFM_orchestrationStatus', '') + + try { + def vnfId = execution.getVariable('DCVFM_vnfId') + def vfModuleName = execution.getVariable('DCVFM_vfModuleName') + + AaiUtil aaiUriUtil = new AaiUtil(this) + String aai_uri = aaiUriUtil.getNetworkGenericVnfUri(execution) + msoLogger.debug('AAI URI is: ' + aai_uri) + + String endPoint = UrnPropertiesReader.getVariable("aai.endpoint", execution) + "${aai_uri}/" + UriUtils.encode(vnfId, "UTF-8") + + "/vf-modules/vf-module?vf-module-name=" + UriUtils.encode(vfModuleName, "UTF-8") + msoLogger.debug("AAI endPoint: " + endPoint) + + try { + RESTConfig config = new RESTConfig(endPoint); + def responseData = '' + def aaiRequestId = UUID.randomUUID().toString() + RESTClient client = new RESTClient(config). + addHeader('X-TransactionId', aaiRequestId). + addHeader('X-FromAppId', 'MSO'). + addHeader('Content-Type', 'application/xml'). + addHeader('Accept','application/xml'); + msoLogger.debug('sending GET to AAI endpoint \'' + endPoint + '\'') + APIResponse response = client.httpGet() + msoLogger.debug("createVfModule - invoking httpGet() to AAI") + + responseData = response.getResponseBodyAsString() + if (responseData != null) { + msoLogger.debug("Received generic VNF data: " + responseData) + + } + + execution.setVariable('DCVFM_queryAAIVfModuleForStatusResponseCode', response.getStatusCode()) + execution.setVariable('DCVFM_queryAAIVfModuleForStatusResponse', responseData) + msoLogger.debug('Response code:' + response.getStatusCode()) + msoLogger.debug('Response:' + System.lineSeparator() + responseData) + // Retrieve VF Module info and its orchestration status; if not found, do nothing + if (response.getStatusCode() == 200) { + // Parse the VNF record from A&AI to find base module info + msoLogger.debug('Parsing the VNF data to find orchestration status') + if (responseData != null) { + def vfModuleText = utils.getNodeXml(responseData, "vf-module") + //def xmlVfModule= new XmlSlurper().parseText(vfModuleText) + def orchestrationStatus = utils.getNodeText(vfModuleText, "orchestration-status") + execution.setVariable("DCVFM_orchestrationStatus", orchestrationStatus) + // Also retrieve vfModuleId + def vfModuleId = utils.getNodeText(vfModuleText, "vf-module-id") + execution.setVariable("DCVFM_vfModuleId", vfModuleId) + msoLogger.debug("Received orchestration status from A&AI: " + orchestrationStatus) + + } + } + } catch (Exception ex) { + ex.printStackTrace() + msoLogger.debug('Exception occurred while executing AAI GET:' + ex.getMessage()) + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'AAI GET Failed:' + ex.getMessage()) + } + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in queryAAIVfModuleForStatus(): ' + e.getMessage()) + } + } + + + public void preProcessSDNCAssignRequest(DelegateExecution execution){ + + execution.setVariable("prefix", Prefix) + msoLogger.trace("STARTED preProcessSDNCAssignRequest") + def vnfId = execution.getVariable("DCVFM_vnfId") + def vfModuleId = execution.getVariable("DCVFM_vfModuleId") + def serviceInstanceId = execution.getVariable("DCVFM_serviceInstanceId") + msoLogger.debug("NEW VNF ID: " + vnfId) + + try{ + + //Build SDNC Request + + def svcInstId = "" + if (serviceInstanceId == null || serviceInstanceId.isEmpty()) { + svcInstId = vfModuleId + } + else { + svcInstId = serviceInstanceId + } + + String assignSDNCRequest = buildSDNCRequest(execution, svcInstId, "assign") + + assignSDNCRequest = utils.formatXml(assignSDNCRequest) + execution.setVariable("DCVFM_assignSDNCRequest", assignSDNCRequest) + msoLogger.debug("Outgoing AssignSDNCRequest is: \n" + assignSDNCRequest) + + }catch(Exception e){ + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, " Exception Occurred Processing preProcessSDNCAssignRequest", "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during prepareProvision Method:\n" + e.getMessage()) + } + msoLogger.trace("COMPLETED preProcessSDNCAssignRequest") + } + + public void preProcessSDNCGetRequest(DelegateExecution execution, String element){ + + String sdncVersion = execution.getVariable("DCVFM_sdncVersion") + execution.setVariable("prefix", Prefix) + msoLogger.trace("STARTED preProcessSDNCGetRequest Process") + try{ + def serviceInstanceId = execution.getVariable('DCVFM_serviceInstanceId') + + String uuid = execution.getVariable('testReqId') // for junits + if(uuid==null){ + uuid = execution.getVariable("mso-request-id") + "-" + System.currentTimeMillis() + } + + def callbackUrl = execution.getVariable("DCVFM_sdncCallbackUrl") + msoLogger.debug("callbackUrl:" + callbackUrl) + + def vfModuleId = execution.getVariable('DCVFM_vfModuleId') + + def svcInstId = "" + if (serviceInstanceId == null || serviceInstanceId.isEmpty()) { + svcInstId = vfModuleId + } + else { + svcInstId = serviceInstanceId + } + + def msoAction = "" + if (!sdncVersion.equals("1707")) { + msoAction = "mobility" + } + else { + msoAction = "vfmodule" + } + // For VNF, serviceOperation (URI for topology GET) will be retrieved from "selflink" element + // in the response from GenericGetVnf + // For VF Module, in 1707 serviceOperation will be retrieved from "object-path" element + // in SDNC Assign Response + // For VF Module for older versions, serviceOperation is constructed using vfModuleId + + String serviceOperation = "" + if (element.equals("vnf")) { + def vnfQueryResponse = execution.getVariable("DCVFM_vnfQueryResponse") + serviceOperation = utils.getNodeText(vnfQueryResponse, "selflink") + msoLogger.debug("VNF - service operation: " + serviceOperation) + } + else if (element.equals("vfmodule")) { + String response = execution.getVariable("DCVFM_assignSDNCAdapterResponse") + msoLogger.debug("DCVFM_assignSDNCAdapterResponse is: \n" + response) + + if (!sdncVersion.equals("1707")) { + serviceOperation = "/VNF-API:vnfs/vnf-list/" + vfModuleId + msoLogger.debug("VF Module with sdncVersion before 1707 - service operation: " + serviceOperation) + } + else { + String data = utils.getNodeXml(response, "response-data") + msoLogger.debug("responseData: " + data) + serviceOperation = utils.getNodeText(data, "object-path") + msoLogger.debug("VF Module with sdncVersion of 1707 - service operation: " + serviceOperation) + } + } + + //!!!! TEMPORARY WORKAROUND FOR SDNC REPLICATION ISSUE + sleep(5000) + + String SDNCGetRequest = + """<sdncadapterworkflow:SDNCAdapterWorkflowRequest xmlns:ns5="http://org.onap/so/request/types/v1" + xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1" + xmlns:sdncadapter="http://org.onap/workflow/sdnc/adapter/schema/v1"> + <sdncadapter:RequestHeader> + <sdncadapter:RequestId>${MsoUtils.xmlEscape(uuid)}</sdncadapter:RequestId> + <sdncadapter:SvcInstanceId>${MsoUtils.xmlEscape(svcInstId)}</sdncadapter:SvcInstanceId> + <sdncadapter:SvcAction>query</sdncadapter:SvcAction> + <sdncadapter:SvcOperation>${MsoUtils.xmlEscape(serviceOperation)}</sdncadapter:SvcOperation> + <sdncadapter:CallbackUrl>${MsoUtils.xmlEscape(callbackUrl)}</sdncadapter:CallbackUrl> + <sdncadapter:MsoAction>${MsoUtils.xmlEscape(msoAction)}</sdncadapter:MsoAction> + </sdncadapter:RequestHeader> + <sdncadapterworkflow:SDNCRequestData></sdncadapterworkflow:SDNCRequestData> + </sdncadapterworkflow:SDNCAdapterWorkflowRequest>""" + + execution.setVariable("DCVFM_getSDNCRequest", SDNCGetRequest) + msoLogger.debug("Outgoing GetSDNCRequest is: \n" + SDNCGetRequest) + + }catch(Exception e){ + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception Occurred Processing preProcessSDNCGetRequest", "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during prepareProvision Method:\n" + e.getMessage()) + } + msoLogger.trace("COMPLETED preProcessSDNCGetRequest Process") + } + + + public void preProcessVNFAdapterRequest(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.VNFAdapterCreateVfModule(' + + 'execution=' + execution.getId() + + ')' + + msoLogger.trace('Entered ' + method) + + //def xml = execution.getVariable("DoCreateVfModuleRequest") + //msoLogger.debug('VNF REQUEST is: ' + xml) + + //Get variables + //cloudSiteId + def cloudSiteId = execution.getVariable("DCVFM_cloudSiteId") + //tenantId + def tenantId = execution.getVariable("DCVFM_tenantId") + //vnfType + def vnfType = execution.getVariable("DCVFM_vnfType") + //vnfName + def vnfName = execution.getVariable("DCVFM_vnfName") + //vnfId + def vnfId = execution.getVariable("DCVFM_vnfId") + //vfModuleName + def vfModuleName = execution.getVariable("DCVFM_vfModuleName") + //vfModuleModelName + def vfModuleModelName = execution.getVariable("DCVFM_vfModuleModelName") + //vfModuleId + def vfModuleId = execution.getVariable("DCVFM_vfModuleId") + //vfModuleIndex + def vfModuleIndex = execution.getVariable("DCVFM_vfModuleIndex") + //requestId + def requestId = execution.getVariable("DCVFM_requestId") + //serviceId + def serviceId = execution.getVariable("DCVFM_serviceId") + //serviceInstanceId + def serviceInstanceId = execution.getVariable("DCVFM_serviceInstanceId") + //flavorList + ArrayList<CloudFlavor> flavorList = execution.getVariable("DCVFM_flavorList") + //backoutOnFailure + def backoutOnFailure = execution.getVariable("DCVFM_backoutOnFailure") + //volumeGroupId + def volumeGroupId = execution.getVariable("DCVFM_volumeGroupId") + // baseVfModuleId + def baseVfModuleId = execution.getVariable("DCVFM_baseVfModuleId") + // baseVfModuleStackId + def baseVfModuleStackId = execution.getVariable("DCVFM_baseVfModuleHeatStackId") + // asdcServiceModelVersion + def asdcServiceModelVersion = execution.getVariable("DCVFM_asdcServiceModelVersion") + //volumeGroupStackId + def volumeGroupStackId = execution.getVariable("DCVFM_volumeGroupStackId") + //modelCustomizationUuid + def modelCustomizationUuid = execution.getVariable("DCVFM_modelCustomizationUuid") + //environmentContext + String environmentContext = execution.getVariable("DCVFM_environmentContext") + //workloadContext + String workloadContext = execution.getVariable("DCVFM_workloadContext") + msoLogger.debug("workloadContext: " + workloadContext) + msoLogger.debug("environmentContext: " + environmentContext) + + def messageId = execution.getVariable('mso-request-id') + '-' + + System.currentTimeMillis() + + def notificationUrl = createCallbackURL(execution, "VNFAResponse", messageId) + def useQualifiedHostName = UrnPropertiesReader.getVariable("mso.use.qualified.host",execution) + + msoLogger.debug("notificationUrl: " + notificationUrl) + msoLogger.debug("QualifiedHostName: " + useQualifiedHostName) + + if ('true'.equals(useQualifiedHostName)) { + notificationUrl = utils.getQualifiedHostNameForCallback(notificationUrl) + } + + Map<String, String> vnfParamsMap = execution.getVariable("DCVFM_vnfParamsMap") + // Add flavorLabel List to vnfParamsMap + flavorList.each { cloudFlavor -> + vnfParamsMap.put("label_" + cloudFlavor.getFlavorLabel(), cloudFlavor.getFlavor()) + } + String vfModuleParams = "" + //Get SDNC Response Data for VF Module Topology + String vfModuleSdncGetResponse = execution.getVariable('DCVFM_getSDNCAdapterResponse') + msoLogger.debug("sdncGetResponse: " + vfModuleSdncGetResponse) + def sdncVersion = execution.getVariable("sdncVersion") + + if (!sdncVersion.equals("1707")) { + + vfModuleParams = buildVfModuleParams(vnfParamsMap, vfModuleSdncGetResponse, vnfId, vnfName, + vfModuleId, vfModuleName, vfModuleIndex, environmentContext, workloadContext) + } + else { + //Get SDNC Response Data for Vnf Topology + String vnfSdncGetResponse = execution.getVariable('DCVFM_getVnfSDNCAdapterResponse') + msoLogger.debug("vnfSdncGetResponse: " + vnfSdncGetResponse) + + vfModuleParams = buildVfModuleParamsFromCombinedTopologies(vnfParamsMap, vnfSdncGetResponse, vfModuleSdncGetResponse, vnfId, vnfName, + vfModuleId, vfModuleName, vfModuleIndex, environmentContext, workloadContext) + } + + def svcInstId = "" + if (serviceInstanceId == null || serviceInstanceId.isEmpty()) { + svcInstId = serviceId + } + else { + svcInstId = serviceInstanceId + } + + def createVnfARequest = """ + <createVfModuleRequest> + <cloudSiteId>${MsoUtils.xmlEscape(cloudSiteId)}</cloudSiteId> + <tenantId>${MsoUtils.xmlEscape(tenantId)}</tenantId> + <vnfId>${MsoUtils.xmlEscape(vnfId)}</vnfId> + <vnfName>${MsoUtils.xmlEscape(vnfName)}</vnfName> + <vfModuleName>${MsoUtils.xmlEscape(vfModuleName)}</vfModuleName> + <vfModuleId>${MsoUtils.xmlEscape(vfModuleId)}</vfModuleId> + <vnfType>${MsoUtils.xmlEscape(vnfType)}</vnfType> + <vfModuleType>${MsoUtils.xmlEscape(vfModuleModelName)}</vfModuleType> + <vnfVersion>${MsoUtils.xmlEscape(asdcServiceModelVersion)}</vnfVersion> + <modelCustomizationUuid>${MsoUtils.xmlEscape(modelCustomizationUuid)}</modelCustomizationUuid> + <requestType></requestType> + <volumeGroupId>${MsoUtils.xmlEscape(volumeGroupId)}</volumeGroupId> + <volumeGroupStackId>${MsoUtils.xmlEscape(volumeGroupStackId)}</volumeGroupStackId> + <baseVfModuleId>${MsoUtils.xmlEscape(baseVfModuleId)}</baseVfModuleId> + <baseVfModuleStackId>${MsoUtils.xmlEscape(baseVfModuleStackId)}</baseVfModuleStackId> + <skipAAI>true</skipAAI> + <backout>${MsoUtils.xmlEscape(backoutOnFailure)}</backout> + <failIfExists>true</failIfExists> + <vfModuleParams> + ${vfModuleParams} + </vfModuleParams> + <msoRequest> + <requestId>${MsoUtils.xmlEscape(requestId)}</requestId> + <serviceInstanceId>${MsoUtils.xmlEscape(svcInstId)}</serviceInstanceId> + </msoRequest> + <messageId>${MsoUtils.xmlEscape(messageId)}</messageId> + <notificationUrl>${MsoUtils.xmlEscape(notificationUrl)}</notificationUrl> + </createVfModuleRequest>""" + + msoLogger.debug("Create VfModule Request to VNF Adapter: " + createVnfARequest) + execution.setVariable("DCVFM_createVnfARequest", createVnfARequest) + } + + /** + * Validates the request, request id and service instance id. If a problem is found, + * a WorkflowException is generated and an MSOWorkflowException event is thrown. This + * method also sets up the log context for the workflow. + * @param execution the execution + * @return the validated request + */ + public String validateInfraRequest(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.validateInfraRequest(' + + 'execution=' + execution.getId() + + ')' + + msoLogger.trace('Entered ' + method) + + String processKey = getProcessKey(execution); + def prefix = execution.getVariable("prefix") + + if (prefix == null) { + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, processKey + " prefix is null") + } + + try { + def request = execution.getVariable(prefix + 'Request') + + if (request == null) { + request = execution.getVariable(processKey + 'Request') + + if (request == null) { + request = execution.getVariable('bpmnRequest') + } + + setVariable(execution, processKey + 'Request', null); + setVariable(execution, 'bpmnRequest', null); + setVariable(execution, prefix + 'Request', request); + } + + if (request == null) { + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, processKey + " request is null") + } + msoLogger.debug("DoCreateVfModule Request: " + request) + + /* + + def requestId = execution.getVariable("mso-request-id") + + if (requestId == null) { + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, processKey + " request has no mso-request-id") + } + + def serviceInstanceId = execution.getVariable("mso-service-instance-id") + + if (serviceInstanceId == null) { + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, processKey + " request message has no mso-service-instance-id") + } + + utils.logContext(requestId, serviceInstanceId) + */ + msoLogger.debug('Incoming message: ' + System.lineSeparator() + request) + msoLogger.trace('Exited ' + method) + return request + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Invalid Message") + } + } + + public boolean isVolumeGroupIdPresent(DelegateExecution execution) { + + def method = getClass().getSimpleName() + '.isVolumeGroupIdPresent(' + + 'execution=' + execution.getId() + + ')' + + msoLogger.trace('Entered ' + method) + + def request = execution.getVariable('DoCreateVfModuleRequest') + String volumeGroupId = utils.getNodeText(request, "volume-group-id") + if (volumeGroupId == null || volumeGroupId.isEmpty()) { + msoLogger.debug('No volume group id is present') + return false + } + else { + msoLogger.debug('Volume group id is present') + return true + } + + } + + public boolean isVolumeGroupNamePresent(DelegateExecution execution) { + + def method = getClass().getSimpleName() + '.isVolumeGroupNamePresent(' + + 'execution=' + execution.getId() + + ')' + + msoLogger.trace('Entered ' + method) + + def request = execution.getVariable('DoCreateVfModuleRequest') + String volumeGroupName = utils.getNodeText(request, "volume-group-name") + if (volumeGroupName == null || volumeGroupName.isEmpty()) { + msoLogger.debug('No volume group name is present') + return false + } + else { + msoLogger.debug('Volume group name is present') + return true + } + + } + + public String buildSDNCRequest(DelegateExecution execution, String svcInstId, String action){ + + String uuid = execution.getVariable('testReqId') // for junits + if(uuid==null){ + uuid = execution.getVariable("mso-request-id") + "-" + System.currentTimeMillis() + } + def callbackURL = execution.getVariable("DCVFM_sdncCallbackUrl") + def requestId = execution.getVariable("DCVFM_requestId") + def serviceId = execution.getVariable("DCVFM_serviceId") + def vnfType = execution.getVariable("DCVFM_vnfType") + def vnfName = execution.getVariable("DCVFM_vnfName") + def tenantId = execution.getVariable("DCVFM_tenantId") + def source = execution.getVariable("DCVFM_source") + def backoutOnFailure = execution.getVariable("DCVFM_backoutOnFailure") + def vfModuleId = execution.getVariable("DCVFM_vfModuleId") + def vfModuleName = execution.getVariable("DCVFM_vfModuleName") + def vfModuleModelName = execution.getVariable("DCVFM_vfModuleModelName") + def vnfId = execution.getVariable("DCVFM_vnfId") + def cloudSiteId = execution.getVariable("DCVFM_cloudSiteId") + def sdncVersion = execution.getVariable("DCVFM_sdncVersion") + def serviceModelInfo = execution.getVariable("serviceModelInfo") + def vnfModelInfo = execution.getVariable("vnfModelInfo") + def vfModuleModelInfo = execution.getVariable("vfModuleModelInfo") + String serviceEcompModelInformation = sdncAdapterUtils.modelInfoToEcompModelInformation(serviceModelInfo) + String vnfEcompModelInformation = sdncAdapterUtils.modelInfoToEcompModelInformation(vnfModelInfo) + String vfModuleEcompModelInformation = sdncAdapterUtils.modelInfoToEcompModelInformation(vfModuleModelInfo) + def globalSubscriberId = execution.getVariable("DCVFM_globalSubscriberId") + boolean usePreload = execution.getVariable("DCVFM_usePreload") + String usePreloadToSDNC = usePreload ? "Y" : "N" + def modelCustomizationUuid = execution.getVariable("DCVFM_modelCustomizationUuid") + def modelCustomizationUuidString = "" + if (!usePreload) { + modelCustomizationUuidString = "<model-customization-uuid>" + modelCustomizationUuid + "</model-customization-uuid>" + } + + String sdncVNFParamsXml = "" + + if(execution.getVariable("DCVFM_vnfParamsExistFlag") == true){ + if (!sdncVersion.equals("1707")) { + sdncVNFParamsXml = buildSDNCParamsXml(execution) + } + else { + sdncVNFParamsXml = buildCompleteSDNCParamsXml(execution) + } + }else{ + sdncVNFParamsXml = "" + } + + String sdncRequest = "" + + if (!sdncVersion.equals("1707")) { + + sdncRequest = + """<sdncadapterworkflow:SDNCAdapterWorkflowRequest xmlns:ns5="http://org.onap/so/request/types/v1" + xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1" + xmlns:sdncadapter="http://org.onap/workflow/sdnc/adapter/schema/v1"> + <sdncadapter:RequestHeader> + <sdncadapter:RequestId>${MsoUtils.xmlEscape(uuid)}</sdncadapter:RequestId> + <sdncadapter:SvcInstanceId>${MsoUtils.xmlEscape(svcInstId)}</sdncadapter:SvcInstanceId> + <sdncadapter:SvcAction>${MsoUtils.xmlEscape(action)}</sdncadapter:SvcAction> + <sdncadapter:SvcOperation>vnf-topology-operation</sdncadapter:SvcOperation> + <sdncadapter:CallbackUrl>${MsoUtils.xmlEscape(callbackURL)}</sdncadapter:CallbackUrl> + </sdncadapter:RequestHeader> + <sdncadapterworkflow:SDNCRequestData> + <request-information> + <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> + <request-action>VNFActivateRequest</request-action> + <source>${MsoUtils.xmlEscape(source)}</source> + <notification-url/> + </request-information> + <service-information> + <service-id>${MsoUtils.xmlEscape(serviceId)}</service-id> + <service-type>${MsoUtils.xmlEscape(serviceId)}</service-type> + <service-instance-id>${MsoUtils.xmlEscape(svcInstId)}</service-instance-id> + <subscriber-name>notsurewecare</subscriber-name> + </service-information> + <vnf-request-information> + <vnf-id>${MsoUtils.xmlEscape(vfModuleId)}</vnf-id> + <vnf-type>${MsoUtils.xmlEscape(vfModuleModelName)}</vnf-type> + <vnf-name>${MsoUtils.xmlEscape(vfModuleName)}</vnf-name> + <generic-vnf-id>${MsoUtils.xmlEscape(vnfId)}</generic-vnf-id> + <generic-vnf-name>${MsoUtils.xmlEscape(vnfName)}</generic-vnf-name> + <generic-vnf-type>${MsoUtils.xmlEscape(vnfType)}</generic-vnf-type> + <aic-cloud-region>${MsoUtils.xmlEscape(cloudSiteId)}</aic-cloud-region> + <tenant>${MsoUtils.xmlEscape(tenantId)}</tenant> + ${modelCustomizationUuidString} + <use-preload>${MsoUtils.xmlEscape(usePreloadToSDNC)}</use-preload> + ${sdncVNFParamsXml} + </vnf-request-information> + </sdncadapterworkflow:SDNCRequestData> + </sdncadapterworkflow:SDNCAdapterWorkflowRequest>""" + + } + else { + + sdncRequest = + """<sdncadapterworkflow:SDNCAdapterWorkflowRequest xmlns:ns5="http://org.onap/so/request/types/v1" + xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1" + xmlns:sdncadapter="http://org.onap/workflow/sdnc/adapter/schema/v1"> + <sdncadapter:RequestHeader> + <sdncadapter:RequestId>${MsoUtils.xmlEscape(uuid)}</sdncadapter:RequestId> + <sdncadapter:SvcInstanceId>${MsoUtils.xmlEscape(svcInstId)}</sdncadapter:SvcInstanceId> + <sdncadapter:SvcAction>${MsoUtils.xmlEscape(action)}</sdncadapter:SvcAction> + <sdncadapter:SvcOperation>vf-module-topology-operation</sdncadapter:SvcOperation> + <sdncadapter:CallbackUrl>${MsoUtils.xmlEscape(callbackURL)}</sdncadapter:CallbackUrl> + <sdncadapter:MsoAction>generic-resource</sdncadapter:MsoAction> + </sdncadapter:RequestHeader> + <sdncadapterworkflow:SDNCRequestData> + <request-information> + <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> + <request-action>CreateVfModuleInstance</request-action> + <source>${MsoUtils.xmlEscape(source)}</source> + <notification-url/> + </request-information> + <service-information> + <service-id>${MsoUtils.xmlEscape(serviceId)}</service-id> + <subscription-service-type>${MsoUtils.xmlEscape(serviceId)}</subscription-service-type> + ${serviceEcompModelInformation} + <service-instance-id>${MsoUtils.xmlEscape(svcInstId)}</service-instance-id> + <global-customer-id>${MsoUtils.xmlEscape(globalSubscriberId)}</global-customer-id> + </service-information> + <vnf-information> + <vnf-id>${MsoUtils.xmlEscape(vnfId)}</vnf-id> + <vnf-type>${MsoUtils.xmlEscape(vnfType)}</vnf-type> + ${vnfEcompModelInformation} + </vnf-information> + <vf-module-information> + <vf-module-id>${MsoUtils.xmlEscape(vfModuleId)}</vf-module-id> + <vf-module-type>${MsoUtils.xmlEscape(vfModuleModelName)}</vf-module-type> + ${vfModuleEcompModelInformation} + </vf-module-information> + <vf-module-request-input> + <vf-module-name>${MsoUtils.xmlEscape(vfModuleName)}</vf-module-name> + <tenant>${MsoUtils.xmlEscape(tenantId)}</tenant> + <aic-cloud-region>${MsoUtils.xmlEscape(cloudSiteId)}</aic-cloud-region> + ${sdncVNFParamsXml} + </vf-module-request-input> + </sdncadapterworkflow:SDNCRequestData> + </sdncadapterworkflow:SDNCAdapterWorkflowRequest>""" + + + /* + sdncRequest = + """<sdncadapterworkflow:SDNCAdapterWorkflowRequest xmlns:ns5="http://org.onap/so/request/types/v1" + xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1" + xmlns:sdncadapter="http://org.onap/workflow/sdnc/adapter/schema/v1"> + <sdncadapter:RequestHeader> + <sdncadapter:RequestId>${MsoUtils.xmlEscape(requestId)}</sdncadapter:RequestId> + <sdncadapter:SvcInstanceId>${MsoUtils.xmlEscape(svcInstId)}</sdncadapter:SvcInstanceId> + <sdncadapter:SvcAction>${MsoUtils.xmlEscape(action)}</sdncadapter:SvcAction> + <sdncadapter:SvcOperation>vnf-topology-operation</sdncadapter:SvcOperation> + <sdncadapter:CallbackUrl>${MsoUtils.xmlEscape(callbackURL)}</sdncadapter:CallbackUrl> + </sdncadapter:RequestHeader> + <sdncadapterworkflow:SDNCRequestData> + <request-information> + <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> + <request-action>CreateVfModuleInstance</request-action> + <source>${MsoUtils.xmlEscape(source)}</source> + <notification-url/> + </request-information> + <service-information> + <service-id>${MsoUtils.xmlEscape(serviceId)}</service-id> + <service-type>${MsoUtils.xmlEscape(serviceId)}</service-type> + ${serviceEcompModelInformation} + <service-instance-id>${MsoUtils.xmlEscape(svcInstId)}</service-instance-id> + <global-customer-id>${MsoUtils.xmlEscape(globalSubscriberId)}</global-customer-id> + </service-information> + <vnf-information> + <vnf-id>${MsoUtils.xmlEscape(vnfId)}</vnf-id> + <vnf-type>${MsoUtils.xmlEscape(vnfType)}</vnf-type> + ${vnfEcompModelInformation} + </vnf-information> + <vf-module-information> + <vf-module-id>${MsoUtils.xmlEscape(vfModuleId)}</vf-module-id> + <vf-module-type>${MsoUtils.xmlEscape(vfModuleModelName)}</vf-module-type> + ${vfModuleEcompModelInformation} + </vf-module-information> + <vf-module-request-input> + <vf-module-name>${MsoUtils.xmlEscape(vfModuleName)}</vf-module-name> + <tenant>${MsoUtils.xmlEscape(tenantId)}</tenant> + <aic-cloud-region>${MsoUtils.xmlEscape(cloudSiteId)}</aic-cloud-region> + ${sdncVNFParamsXml} + </vf-module-request-input> + </sdncadapterworkflow:SDNCRequestData> + </sdncadapterworkflow:SDNCAdapterWorkflowRequest>""" + */ + + } + + msoLogger.debug("sdncRequest: " + sdncRequest) + return sdncRequest + + } + + public void preProcessSDNCActivateRequest(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.preProcessSDNCActivateRequest(' + + 'execution=' + execution.getId() + + ')' + + msoLogger.trace('Entered ' + method) + execution.setVariable("prefix", Prefix) + msoLogger.trace("STARTED preProcessSDNCActivateRequest Process") + try{ + String vnfId = execution.getVariable("DCVFM_vnfId") + String vfModuleId = execution.getVariable("DCVFM_vfModuleId") + String serviceInstanceId = execution.getVariable("DCVFM_serviceInstanceId") + + def svcInstId = "" + if (serviceInstanceId == null || serviceInstanceId.isEmpty()) { + svcInstId = vfModuleId + } + else { + svcInstId = serviceInstanceId + } + String activateSDNCRequest = buildSDNCRequest(execution, svcInstId, "activate") + + execution.setVariable("DCVFM_activateSDNCRequest", activateSDNCRequest) + msoLogger.debug("Outgoing CommitSDNCRequest is: \n" + activateSDNCRequest) + + }catch(Exception e){ + msoLogger.debug("Exception Occured Processing preProcessSDNCActivateRequest. Exception is:\n" + e) + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during preProcessSDNCActivateRequest Method:\n" + e.getMessage()) + } + msoLogger.trace("COMPLETED preProcessSDNCActivateRequest Process") + } + + public void postProcessVNFAdapterRequest(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.postProcessVNFAdapterRequest(' + + 'execution=' + execution.getId() + + ')' + + msoLogger.trace('Entered ' + method) + execution.setVariable("prefix",Prefix) + try{ + msoLogger.debug("STARTED postProcessVNFAdapterRequest Process") + + String vnfResponse = execution.getVariable("DCVFM_createVnfAResponse") + msoLogger.debug("VNF Adapter Response is: " + vnfResponse) + + RollbackData rollbackData = execution.getVariable("rollbackData") + if(vnfResponse != null){ + + if(vnfResponse.contains("createVfModuleResponse")){ + msoLogger.debug("Received a Good Response from VNF Adapter for CREATE_VF_MODULE Call.") + execution.setVariable("DCVFM_vnfVfModuleCreateCompleted", true) + String heatStackId = utils.getNodeText(vnfResponse, "vfModuleStackId") + execution.setVariable("DCVFM_heatStackId", heatStackId) + msoLogger.debug("Received heat stack id from VNF Adapter: " + heatStackId) + rollbackData.put("VFMODULE", "heatstackid", heatStackId) + // Parse vnfOutputs for network_fqdn + if (vnfResponse.contains("vfModuleOutputs")) { + def vfModuleOutputsXml = utils.getNodeXml(vnfResponse, "vfModuleOutputs") + InputSource source = new InputSource(new StringReader(vfModuleOutputsXml)); + DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); + docFactory.setNamespaceAware(true) + DocumentBuilder docBuilder = docFactory.newDocumentBuilder() + Document outputsXml = docBuilder.parse(source) + + NodeList entries = outputsXml.getElementsByTagNameNS("*", "entry") + List contrailNetworkPolicyFqdnList = [] + for (int i = 0; i< entries.getLength(); i++) { + Node node = entries.item(i) + if (node.getNodeType() == Node.ELEMENT_NODE) { + Element element = (Element) node + String key = element.getElementsByTagNameNS("*", "key").item(0).getTextContent() + if (key.equals("contrail-service-instance-fqdn")) { + String contrailServiceInstanceFqdn = element.getElementsByTagNameNS("*", "value").item(0).getTextContent() + msoLogger.debug("Obtained contrailServiceInstanceFqdn: " + contrailServiceInstanceFqdn) + execution.setVariable("DCVFM_contrailServiceInstanceFqdn", contrailServiceInstanceFqdn) + } + else if (key.endsWith("contrail_network_policy_fqdn")) { + String contrailNetworkPolicyFqdn = element.getElementsByTagNameNS("*", "value").item(0).getTextContent() + msoLogger.debug("Obtained contrailNetworkPolicyFqdn: " + contrailNetworkPolicyFqdn) + contrailNetworkPolicyFqdnList.add(contrailNetworkPolicyFqdn) + } + else if (key.equals("oam_management_v4_address")) { + String oamManagementV4Address = element.getElementsByTagNameNS("*", "value").item(0).getTextContent() + msoLogger.debug("Obtained oamManagementV4Address: " + oamManagementV4Address) + execution.setVariable("DCVFM_oamManagementV4Address", oamManagementV4Address) + } + else if (key.equals("oam_management_v6_address")) { + String oamManagementV6Address = element.getElementsByTagNameNS("*", "value").item(0).getTextContent() + msoLogger.debug("Obtained oamManagementV6Address: " + oamManagementV6Address) + execution.setVariable("DCVFM_oamManagementV6Address", oamManagementV6Address) + } + + } + } + if (!contrailNetworkPolicyFqdnList.isEmpty()) { + execution.setVariable("DCVFM_contrailNetworkPolicyFqdnList", contrailNetworkPolicyFqdnList) + } + } + }else{ + msoLogger.debug("Received a BAD Response from VNF Adapter for CREATE_VF_MODULE Call.") + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "VNF Adapter Error") + } + }else{ + msoLogger.debug("Response from VNF Adapter is Null for CREATE_VF_MODULE Call.") + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Empty response from VNF Adapter") + } + + rollbackData.put("VFMODULE", "rollbackVnfAdapterCreate", "true") + execution.setVariable("rollbackData", rollbackData) + + }catch(BpmnError b){ + throw b + }catch(Exception e){ + msoLogger.debug("Internal Error Occured in PostProcess Method") + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Internal Error Occured in PostProcess Method") + } + msoLogger.trace("COMPLETED postProcessVnfAdapterResponse Process") + } + + + public void preProcessUpdateAAIVfModuleRequestOrch(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.preProcessUpdateAAIVfModuleRequestOrch(' + + 'execution=' + execution.getId() + + ')' + + msoLogger.trace('Entered ' + method) + execution.setVariable("prefix", Prefix) + msoLogger.trace("STARTED preProcessUpdateAAIVfModuleRequestOrch") + + try{ + + //Build UpdateAAIVfModule Request + boolean setContrailServiceInstanceFqdn = false + def contrailServiceInstanceFqdn = execution.getVariable("DCVFM_contrailServiceInstanceFqdn") + if (!contrailServiceInstanceFqdn.equals("")) { + setContrailServiceInstanceFqdn = true + } + + execution.setVariable("DCVFM_orchestrationStatus", "Created") + + String updateAAIVfModuleRequest = buildUpdateAAIVfModuleRequest(execution, false, true, true, setContrailServiceInstanceFqdn) + + updateAAIVfModuleRequest = utils.formatXml(updateAAIVfModuleRequest) + execution.setVariable("DCVFM_updateAAIVfModuleRequest", updateAAIVfModuleRequest) + msoLogger.debug("Outgoing UpdateAAIVfModuleRequest is: \n" + updateAAIVfModuleRequest) + + }catch(Exception e){ + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception Occured Processing preProcessUpdateAAIVfModuleRequestOrch", "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during preProcessUpdateAAIVfModuleRequestOrch Method:\n" + e.getMessage()) + } + msoLogger.trace("COMPLETED preProcessUpdateAAIVfModuleRequestOrch") + + } + + public void preProcessUpdateAAIVfModuleRequestStatus(DelegateExecution execution, String status) { + def method = getClass().getSimpleName() + '.preProcessUpdateAAIVfModuleStatus(' + + 'execution=' + execution.getId() + + ')' + + msoLogger.trace('Entered ' + method) + execution.setVariable("prefix", Prefix) + msoLogger.trace("STARTED preProcessUpdateAAIVfModuleStatus") + + try{ + + //Build UpdateAAIVfModule Request + execution.setVariable("DCVFM_orchestrationStatus", status) + + String updateAAIVfModuleRequest = buildUpdateAAIVfModuleRequest(execution, false, true, false, false) + + updateAAIVfModuleRequest = utils.formatXml(updateAAIVfModuleRequest) + execution.setVariable("DCVFM_updateAAIVfModuleRequest", updateAAIVfModuleRequest) + msoLogger.debug("Outgoing UpdateAAIVfModuleRequest is: \n" + updateAAIVfModuleRequest) + + }catch(Exception e){ + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception Occured Processing preProcessUpdateAAIVfModuleStatus", "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during preProcessUpdateAAIVfModuleStatus Method:\n" + e.getMessage()) + } + msoLogger.trace("COMPLETED preProcessUpdateAAIVfModuleStatus") + + } + + + public void preProcessUpdateAAIVfModuleRequestGroup(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.preProcessUpdateAAIVfModuleRequestGroup(' + + 'execution=' + execution.getId() + + ')' + + msoLogger.trace('Entered ' + method) + execution.setVariable("prefix", Prefix) + msoLogger.trace("STARTED preProcessUpdateAAIVfModuleRequestGroup") + + try{ + + //Build UpdateAAIVfModule Request + + String updateAAIVfModuleRequest = buildUpdateAAIVfModuleRequest(execution, true, false, false, false) + + updateAAIVfModuleRequest = utils.formatXml(updateAAIVfModuleRequest) + execution.setVariable("DCVFM_updateAAIVfModuleRequest", updateAAIVfModuleRequest) + msoLogger.debug("Outgoing UpdateAAIVfModuleRequest is: \n" + updateAAIVfModuleRequest) + + }catch(Exception e){ + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception Occured Processing preProcessUpdateAAIVfModuleRequestGroup", "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during preProcessUpdateAAIVfModuleRequestGroup Method:\n" + e.getMessage()) + } + msoLogger.trace("COMPLETED preProcessUpdateAAIVfModuleRequestGroup") + + } + + public void validateSDNCResponse(DelegateExecution execution, String response, String method){ + + execution.setVariable("prefix",Prefix) + msoLogger.debug("STARTED ValidateSDNCResponse Process") + + WorkflowException workflowException = execution.getVariable("WorkflowException") + boolean successIndicator = execution.getVariable("SDNCA_SuccessIndicator") + + msoLogger.debug("workflowException: " + workflowException) + + SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this) + sdncAdapterUtils.validateSDNCResponse(execution, response, workflowException, successIndicator) + + String sdncResponse = response + if(execution.getVariable(Prefix + 'sdncResponseSuccess') == true){ + msoLogger.debug("Received a Good Response from SDNC Adapter for " + method + " SDNC Call. Response is: \n" + sdncResponse) + RollbackData rollbackData = execution.getVariable("rollbackData") + + if(method.equals("assign")){ + rollbackData.put("VFMODULE", "rollbackSDNCRequestAssign", "true") + execution.setVariable("CRTGVNF_sdncAssignCompleted", true) + } + else if (method.equals("activate")) { + rollbackData.put("VFMODULE", "rollbackSDNCRequestActivate", "true") + } + execution.setVariable("rollbackData", rollbackData) + }else{ + msoLogger.debug("Received a BAD Response from SDNC Adapter for " + method + " SDNC Call.") + throw new BpmnError("MSOWorkflowException") + } + msoLogger.trace("COMPLETED ValidateSDNCResponse Process") + } + + public void preProcessUpdateAfterCreateRequest(DelegateExecution execution){ + + execution.setVariable("prefix", Prefix) + msoLogger.trace("STARTED preProcessRequest Process") + try{ + String response = execution.getVariable("DCVFM_assignSDNCAdapterResponse") + msoLogger.debug("DCVFM_assignSDNCAdapterResponse: " + response) + + String data = utils.getNodeXml(response, "response-data") + String vnfId = utils.getNodeText(data, "vnf-id") + + String uuid = execution.getVariable('testReqId') // for junits + if(uuid==null){ + uuid = execution.getVariable("mso-request-id") + "-" + System.currentTimeMillis() + } + + String serviceOperation = "/VNF-API:vnfs/vnf-list/" + vnfId + def callbackUrl = execution.getVariable("DCVFM_sdncCallbackUrl") + msoLogger.debug("callbackUrl: " + callbackUrl) + + String SDNCGetRequest = + """<sdncadapterworkflow:SDNCAdapterWorkflowRequest xmlns:ns5="http://org.onap/so/request/types/v1" + xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1" + xmlns:sdncadapter="http://org.onap/workflow/sdnc/adapter/schema/v1"> + <sdncadapter:RequestHeader> + <sdncadapter:RequestId>${MsoUtils.xmlEscape(uuid)}</sdncadapter:RequestId> + <sdncadapter:SvcAction>query</sdncadapter:SvcAction> + <sdncadapter:SvcOperation>${MsoUtils.xmlEscape(serviceOperation)}</sdncadapter:SvcOperation> + <sdncadapter:CallbackUrl>${MsoUtils.xmlEscape(callbackUrl)}</sdncadapter:CallbackUrl> + <sdncadapter:MsoAction>mobility</sdncadapter:MsoAction> + </sdncadapter:RequestHeader> + <sdncadapterworkflow:SDNCRequestData></sdncadapterworkflow:SDNCRequestData> + </sdncadapterworkflow:SDNCAdapterWorkflowRequest>""" + + execution.setVariable("DCVFM_getSDNCRequest", SDNCGetRequest) + msoLogger.debug("Outgoing GetSDNCRequest is: \n" + SDNCGetRequest) + + }catch(Exception e){ + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception Occured Processing preProcessSDNCGetRequest", "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during prepareProvision Method:\n" + e.getMessage()) + } + msoLogger.trace("COMPLETED preProcessSDNCGetRequest Process") + } + + public String buildUpdateAAIVfModuleRequest(DelegateExecution execution, boolean updateVolumeGroupId, + boolean updateOrchestrationStatus, boolean updateHeatStackId, boolean updateContrailFqdn){ + + def vnfId = execution.getVariable("DCVFM_vnfId") + def vfModuleId = execution.getVariable("DCVFM_vfModuleId") + def volumeGroupIdString = "" + if (updateVolumeGroupId) { + volumeGroupIdString = "<volume-group-id>" + execution.getVariable("DCVFM_volumeGroupId") + + "</volume-group-id>" + } + def orchestrationStatusString = "" + if (updateOrchestrationStatus) { + orchestrationStatusString = "<orchestration-status>" + execution.getVariable("DCVFM_orchestrationStatus") + "</orchestration-status>" + } + def heatStackIdString = "" + if (updateHeatStackId) { + heatStackIdString = "<heat-stack-id>" + execution.getVariable("DCVFM_heatStackId") + "</heat-stack-id>" + } + def contrailFqdnString = "" + if (updateContrailFqdn) { + contrailFqdnString = "<contrail-service-instance-fqdn>" + execution.getVariable("DCVFM_contrailServiceInstanceFqdn") + + "</contrail-service-instance-fqdn>" + } + + String updateAAIVfModuleRequest = + """<UpdateAAIVfModuleRequest> + <vnf-id>${MsoUtils.xmlEscape(vnfId)}</vnf-id> + <vf-module-id>${MsoUtils.xmlEscape(vfModuleId)}</vf-module-id> + ${heatStackIdString} + ${orchestrationStatusString} + ${volumeGroupIdString} + ${contrailFqdnString} + </UpdateAAIVfModuleRequest>""" + + msoLogger.trace("updateAAIVfModule Request: " + updateAAIVfModuleRequest) + return updateAAIVfModuleRequest + + } + + public String buildSDNCParamsXml(DelegateExecution execution){ + + String params = "" + StringBuilder sb = new StringBuilder() + Map<String, String> paramsMap = execution.getVariable("DCVFM_vnfParamsMap") + + for (Map.Entry<String, String> entry : paramsMap.entrySet()) { + String paramsXml + String key = entry.getKey(); + if(key.endsWith("_network")){ + String requestKey = key.substring(0, key.indexOf("_network")) + String requestValue = entry.getValue() + paramsXml = +"""<vnf-networks> + <network-role>{ functx:substring-before-match(data($param/@name), '_network') }</network-role> + <network-name>{ $param/text() }</network-name> +</vnf-networks>""" + }else{ + paramsXml = "" + } + params = sb.append(paramsXml) + } + return params + } + + public String buildCompleteSDNCParamsXml(DelegateExecution execution){ + + String params = "" + StringBuilder sb = new StringBuilder() + Map<String, String> paramsMap = execution.getVariable("DCVFM_vnfParamsMap") + + for (Map.Entry<String, String> entry : paramsMap.entrySet()) { + String paramsXml + String key = entry.getKey(); + String value = entry.getValue() + paramsXml = """<${key}>$value</$key>""" + params = sb.append(paramsXml) + } + return params + } + + public void queryCloudRegion (DelegateExecution execution) { + + execution.setVariable("prefix", Prefix) + msoLogger.trace("STARTED queryCloudRegion") + + try { + String cloudRegion = execution.getVariable("DCVFM_cloudSiteId") + + // Prepare AA&I url + String aai_endpoint = UrnPropertiesReader.getVariable("aai.endpoint", execution) + AaiUtil aaiUtil = new AaiUtil(this) + String aai_uri = aaiUtil.getCloudInfrastructureCloudRegionUri(execution) + String queryCloudRegionRequest = "${aai_endpoint}${aai_uri}/" + cloudRegion + + execution.setVariable("DCVFM_queryCloudRegionRequest", queryCloudRegionRequest) + msoLogger.debug("DCVFM_queryCloudRegionRequest - " + "\n" + queryCloudRegionRequest) + + cloudRegion = aaiUtil.getAAICloudReqion(execution, queryCloudRegionRequest, "PO", cloudRegion) + + if ((cloudRegion != "ERROR")) { + if(execution.getVariable("DCVFM_queryCloudRegionReturnCode") == "404"){ + execution.setVariable("DCVFM_cloudRegionForVolume", "AAIAIC25") + }else{ + execution.setVariable("DCVFM_cloudRegionForVolume", cloudRegion) + } + execution.setVariable("DCVFM_isCloudRegionGood", true) + } else { + String errorMessage = "AAI Query Cloud Region Unsuccessful. AAI Response Code: " + execution.getVariable("DCVFM_queryCloudRegionReturnCode") + msoLogger.debug(errorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, errorMessage) + execution.setVariable("DCVFM_isCloudRegionGood", false) + } + msoLogger.debug(" is Cloud Region Good: " + execution.getVariable("DCVFM_isCloudRegionGood")) + + } catch(BpmnError b){ + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Rethrowing MSOWorkflowException", "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + b.getMessage()); + throw b + }catch (Exception ex) { + // try error + String errorMessage = "Bpmn error encountered in CreateVfModule flow. Unexpected Response from AAI - " + ex.getMessage() + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "AAI Query Cloud Region Failed "+errorMessage, "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + ex); + exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Exception occured during queryCloudRegion method") + } + } + + /** + * + *This method occurs when an MSOWorkflowException is caught. It logs the + *variables and ensures that the "WorkflowException" Variable is set. + * + */ + public void processBPMNException(DelegateExecution execution){ + + execution.setVariable("prefix",Prefix) + try{ + msoLogger.debug("Caught a BPMN Exception") + msoLogger.debug("Started processBPMNException Method") + msoLogger.debug("Variables List: " + execution.getVariables()) + if(execution.getVariable("WorkflowException") == null){ + exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Exception occured during DoCreateVfModule Sub Process") + } + + }catch(Exception e){ + msoLogger.debug("Caught Exception during processBPMNException Method: " + e) + } + msoLogger.debug("Completed processBPMNException Method") + } + + public void prepareCreateAAIVfModuleVolumeGroupRequest(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.prepareCreateAAIVfModuleVolumeGroupRequest(' + + 'execution=' + execution.getId() + + ')' + + msoLogger.trace('Entered ' + method) + execution.setVariable("prefix", Prefix) + msoLogger.trace("STARTED prepareCreateAAIVfModuleVolumeGroupRequest") + + try{ + + //Build CreateAAIVfModuleVolumeGroup Request + + def vnfId = execution.getVariable("DCVFM_vnfId") + def vfModuleId = execution.getVariable("DCVFM_vfModuleId") + def volumeGroupId = execution.getVariable("DCVFM_volumeGroupId") + //def aicCloudRegion = execution.getVariable("DCVFM_cloudSiteId") + def aicCloudRegion = execution.getVariable("DCVFM_cloudRegionForVolume") + String createAAIVfModuleVolumeGroupRequest = + """<CreateAAIVfModuleVolumeGroupRequest> + <vnf-id>${MsoUtils.xmlEscape(vnfId)}</vnf-id> + <vf-module-id>${MsoUtils.xmlEscape(vfModuleId)}</vf-module-id> + <volume-group-id>${MsoUtils.xmlEscape(volumeGroupId)}</volume-group-id> + <aic-cloud-region>${MsoUtils.xmlEscape(aicCloudRegion)}</aic-cloud-region> + </CreateAAIVfModuleVolumeGroupRequest>""" + + createAAIVfModuleVolumeGroupRequest = utils.formatXml(createAAIVfModuleVolumeGroupRequest) + execution.setVariable("DCVFM_createAAIVfModuleVolumeGroupRequest", createAAIVfModuleVolumeGroupRequest) + msoLogger.debug("Outgoing CreateAAIVfModuleVolumeGroupRequest is: \n" + createAAIVfModuleVolumeGroupRequest) + + }catch(Exception e){ + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Exception Occured Processing prepareCreateAAIVfModuleVolumeGroupRequest', "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during prepareCreateAAIVfModuleVolumeGroupRequest Method:\n" + e.getMessage()) + } + msoLogger.trace("COMPLETED prepareCreateAAIVfModuleVolumeGroupRequest") + + } + + public void createNetworkPoliciesInAAI(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.createNetworkPoliciesInAAI(' + + 'execution=' + execution.getId() + + ')' + + msoLogger.trace('Entered ' + method) + execution.setVariable("prefix", Prefix) + msoLogger.trace("STARTED createNetworkPoliciesInAAI") + + try { + // get variables + List fqdnList = execution.getVariable("DCVFM_contrailNetworkPolicyFqdnList") + int fqdnCount = fqdnList.size() + def rollbackData = execution.getVariable("rollbackData") + + execution.setVariable("DCVFM_networkPolicyFqdnCount", fqdnCount) + msoLogger.debug("DCVFM_networkPolicyFqdnCount - " + fqdnCount) + + String aai_endpoint = UrnPropertiesReader.getVariable("aai.endpoint", execution) + AaiUtil aaiUriUtil = new AaiUtil(this) + String aai_uri = aaiUriUtil.getNetworkPolicyUri(execution) + + if (fqdnCount > 0) { + + // AII loop call over contrail network policy fqdn list + for (i in 0..fqdnCount-1) { + + int counting = i+1 + String fqdn = fqdnList[i] + + // Query AAI for this network policy FQDN + + String queryNetworkPolicyByFqdnAAIRequest = "${aai_endpoint}${aai_uri}?network-policy-fqdn=" + UriUtils.encode(fqdn, "UTF-8") + + def aaiRequestId = UUID.randomUUID().toString() + RESTConfig config = new RESTConfig(queryNetworkPolicyByFqdnAAIRequest); + RESTClient client = new RESTClient(config).addHeader("X-TransactionId", aaiRequestId) + .addHeader("X-FromAppId", "MSO") + .addHeader("Content-Type", "application/xml") + .addHeader("Accept","application/xml"); + APIResponse response = client.get() + int returnCode = response.getStatusCode() + execution.setVariable("DCVFM_aaiQqueryNetworkPolicyByFqdnReturnCode", returnCode) + msoLogger.debug(" ***** AAI query network policy Response Code, NetworkPolicy #" + counting + " : " + returnCode) + + String aaiResponseAsString = response.getResponseBodyAsString() + + if (isOneOf(returnCode, 200, 201)) { + msoLogger.debug("The return code is: " + returnCode) + // This network policy FQDN already exists in AAI + execution.setVariable("DCVFM_queryNetworkPolicyByFqdnAAIResponse", aaiResponseAsString) + msoLogger.debug(" QueryAAINetworkPolicyByFQDN Success REST Response, , NetworkPolicy #" + counting + " : " + "\n" + aaiResponseAsString) + + } else { + if (returnCode == 404) { + // This network policy FQDN is not in AAI yet. Add it now + msoLogger.debug("The return code is: " + returnCode) + msoLogger.debug("This network policy FQDN is not in AAI yet: " + fqdn) + // Add the network policy with this FQDN to AAI + def networkPolicyId = UUID.randomUUID().toString() + msoLogger.debug("Adding network-policy with network-policy-id " + networkPolicyId) + + String aaiNamespace = aaiUriUtil.getNamespaceFromUri(execution, aai_uri) + msoLogger.debug('AAI namespace is: ' + aaiNamespace) + String payload = """<network-policy xmlns="${aaiNamespace}"> + <network-policy-id>${MsoUtils.xmlEscape(networkPolicyId)}</network-policy-id> + <network-policy-fqdn>${MsoUtils.xmlEscape(fqdn)}</network-policy-fqdn> + <heat-stack-id>${MsoUtils.xmlEscape(execution.getVariable("DCVFM_heatStackId"))}</heat-stack-id> + </network-policy>""" as String + + execution.setVariable("DCVFM_addNetworkPolicyAAIRequestBody", payload) + + String addNetworkPolicyAAIRequest = "${aai_endpoint}${aai_uri}/" + UriUtils.encode(networkPolicyId, "UTF-8") + msoLogger.debug("AAI request endpoint: " + addNetworkPolicyAAIRequest) + + def aaiRequestIdPut = UUID.randomUUID().toString() + RESTConfig configPut = new RESTConfig(addNetworkPolicyAAIRequest); + RESTClient clientPut = new RESTClient(configPut).addHeader("X-TransactionId", aaiRequestIdPut) + .addHeader("X-FromAppId", "MSO") + .addHeader("Content-Type", "application/xml") + .addHeader("Accept","application/xml"); + msoLogger.debug("invoking PUT call to AAI with payload:"+System.lineSeparator()+payload) + APIResponse responsePut = clientPut.httpPut(payload) + int returnCodePut = responsePut.getStatusCode() + execution.setVariable("DCVFM_aaiAddNetworkPolicyReturnCode", returnCodePut) + msoLogger.debug(" ***** AAI add network policy Response Code, NetworkPolicy #" + counting + " : " + returnCodePut) + + String aaiResponseAsStringPut = responsePut.getResponseBodyAsString() + if (isOneOf(returnCodePut, 200, 201)) { + msoLogger.debug("The return code from adding network policy is: " + returnCodePut) + // This network policy was created in AAI successfully + execution.setVariable("DCVFM_addNetworkPolicyAAIResponse", aaiResponseAsStringPut) + msoLogger.debug(" AddAAINetworkPolicy Success REST Response, , NetworkPolicy #" + counting + " : " + "\n" + aaiResponseAsStringPut) + rollbackData.put("VFMODULE", "rollbackCreateNetworkPoliciesAAI", "true") + rollbackData.put("VFMODULE", "contrailNetworkPolicyFqdn" + i, fqdn) + execution.setVariable("rollbackData", rollbackData) + + } else { + // aai all errors + String putErrorMessage = "Unable to add network-policy to AAI createNetworkPoliciesInAAI - " + returnCodePut + msoLogger.debug(putErrorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, putErrorMessage) + } + + } else { + if (aaiResponseAsString.contains("RESTFault")) { + WorkflowException exceptionObject = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) + execution.setVariable("WorkflowException", exceptionObject) + throw new BpmnError("MSOWorkflowException") + + } else { + // aai all errors + String dataErrorMessage = "Unexpected Response from createNetworkPoliciesInAAI - " + returnCode + msoLogger.debug(dataErrorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + + } + } + } + + } // end loop + + + } else { + msoLogger.debug("No contrail network policies to query/create") + + } + + } catch (BpmnError e) { + throw e; + + } catch (Exception ex) { + String exceptionMessage = "Bpmn error encountered in DoCreateVfModule flow. createNetworkPoliciesInAAI() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + } + + } + + /** + * Prepare a Request for invoking the UpdateAAIGenericVnf subflow. + * + * @param execution The flow's execution instance. + */ + public void prepUpdateAAIGenericVnf(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.prepUpdateAAIGenericVnf(' + + 'execution=' + execution.getId() + + ')' + + msoLogger.trace('Entered ' + method) + + try { + def rollbackData = execution.getVariable("rollbackData") + def vnfId = execution.getVariable('DCVFM_vnfId') + def oamManagementV4Address = execution.getVariable("DCVFM_oamManagementV4Address") + def oamManagementV6Address = execution.getVariable("DCVFM_oamManagementV6Address") + def ipv4OamAddressElement = '' + def managementV6AddressElement = '' + + if (oamManagementV4Address != null && !oamManagementV4Address.isEmpty()) { + ipv4OamAddressElement = '<ipv4-oam-address>' + oamManagementV4Address + '</ipv4-oam-address>' + } + + if (oamManagementV6Address != null && !oamManagementV6Address.isEmpty()) { + managementV6AddressElement = '<management-v6-address>' + oamManagementV6Address + '</management-v6-address>' + } + + rollbackData.put("VFMODULE", "oamManagementV4Address", oamManagementV4Address) + + + String updateAAIGenericVnfRequest = """ + <UpdateAAIGenericVnfRequest> + <vnf-id>${MsoUtils.xmlEscape(vnfId)}</vnf-id> + ${ipv4OamAddressElement} + ${managementV6AddressElement} + </UpdateAAIGenericVnfRequest> + """ + updateAAIGenericVnfRequest = utils.formatXml(updateAAIGenericVnfRequest) + execution.setVariable('DCVM_updateAAIGenericVnfRequest', updateAAIGenericVnfRequest) + msoLogger.debug('Request for UpdateAAIGenericVnf:\n' + updateAAIGenericVnfRequest) + + + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, " Exception Encountered in " + method, "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in prepUpdateAAIGenericVnf(): ' + e.getMessage()) + } + } + + /** + * Post process a result from invoking the UpdateAAIGenericVnf subflow. + * + * @param execution The flow's execution instance. + */ + public void postProcessUpdateAAIGenericVnf(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.postProcessUpdateAAIGenericVnf(' + + 'execution=' + execution.getId() + + ')' + + msoLogger.trace('Entered ' + method) + + try { + def rollbackData = execution.getVariable("rollbackData") + + rollbackData.put("VFMODULE", "rollbackUpdateVnfAAI", "true") + + def vnfId = execution.getVariable('DCVFM_vnfId') + def oamManagementV4Address = execution.getVariable("DCVFM_oamManagementV4Address") + def oamManagementV6Address = execution.getVariable("DCVFM_oamManagementV6Address") + def ipv4OamAddressElement = '' + def managementV6AddressElement = '' + + if (oamManagementV4Address != null && !oamManagementV4Address.isEmpty()) { + rollbackData.put("VFMODULE", "oamManagementV4Address", oamManagementV4Address) + } + + if (oamManagementV6Address != null && !oamManagementV6Address.isEmpty()) { + rollbackData.put("VFMODULE", "oamManagementV6Address", oamManagementV6Address) + } + + execution.setVariable("rollbackData", rollbackData) + + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in postProcessUpdateAAIGenericVnf(): ' + e.getMessage()) + } + } + + public void queryCatalogDB (DelegateExecution execution) { + + String msg = "" + msoLogger.trace("queryCatalogDB ") + + try { + boolean twoPhaseDesign = false + // check for input + + String vfModuleModelName = execution.getVariable("DCVFM_vfModuleModelName") + msoLogger.debug("vfModuleModelName: " + vfModuleModelName) + def vnfModelInfo = execution.getVariable("vnfModelInfo") + def vnfModelCustomizationUuid = jsonUtil.getJsonValue(vnfModelInfo, "modelCustomizationUuid") + + msoLogger.debug("vnfModelCustomizationUuid: " + vnfModelCustomizationUuid) + + JSONArray vnfs = catalog.getAllVnfsByVnfModelCustomizationUuid(execution, vnfModelCustomizationUuid, "v2") + + msoLogger.debug("Incoming Query Catalog DB for Vnf Response is: " + vnfModelCustomizationUuid) + // Only one match here + if (vnfs != null) { + JSONObject vnfObject = vnfs.get(0) + if (vnfObject != null) { + String vnfJson = vnfObject.toString() + // + ObjectMapper om = new ObjectMapper(); + VnfResource vnf = om.readValue(vnfJson, VnfResource.class); + + // Get multiStageDesign flag + + String multiStageDesignValue = vnf.getMultiStageDesign() + msoLogger.debug("multiStageDesign value from Catalog DB is: " + multiStageDesignValue) + if (multiStageDesignValue != null) { + if (multiStageDesignValue.equalsIgnoreCase("true")) { + twoPhaseDesign = true + } + } + } + } + + msoLogger.debug("setting twoPhaseDesign flag to: " + twoPhaseDesign) + + execution.setVariable("DCVFM_twoPhaseDesign", twoPhaseDesign) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in queryCatalogDB', "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in queryCatalogDB(): ' + e.getMessage()) + } + } + + + public void preProcessRollback (DelegateExecution execution) { + + msoLogger.trace("preProcessRollback") + try { + + Object workflowException = execution.getVariable("WorkflowException"); + + if (workflowException instanceof WorkflowException) { + msoLogger.debug("Prev workflowException: " + workflowException.getErrorMessage()) + execution.setVariable("prevWorkflowException", workflowException); + //execution.setVariable("WorkflowException", null); + } + } catch (BpmnError e) { + msoLogger.debug("BPMN Error during preProcessRollback") + } catch(Exception ex) { + String msg = "Exception in preProcessRollback. " + ex.getMessage() + msoLogger.debug(msg) + } + msoLogger.trace("Exit preProcessRollback") + } + + public void postProcessRollback (DelegateExecution execution) { + + msoLogger.trace("postProcessRollback") + String msg = "" + try { + Object workflowException = execution.getVariable("prevWorkflowException"); + if (workflowException instanceof WorkflowException) { + msoLogger.debug("Setting prevException to WorkflowException: ") + execution.setVariable("WorkflowException", workflowException); + } + execution.setVariable("rollbackData", null) + } catch (BpmnError b) { + msoLogger.debug("BPMN Error during postProcessRollback") + throw b; + } catch(Exception ex) { + msg = "Exception in postProcessRollback. " + ex.getMessage() + msoLogger.debug(msg) + } + msoLogger.trace("Exit postProcessRollback") + } + +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModuleRollback.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModuleRollback.groovy new file mode 100644 index 0000000000..a0b7dabb32 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModuleRollback.groovy @@ -0,0 +1,666 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.onap.so.bpmn.common.scripts.AaiUtil +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.onap.so.bpmn.common.scripts.ExceptionUtil +import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.so.bpmn.common.scripts.SDNCAdapterUtils +import org.onap.so.bpmn.core.UrnPropertiesReader +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.logger.MessageEnum +import org.onap.so.logger.MsoLogger +import org.onap.so.rest.APIResponse +import org.springframework.web.util.UriUtils + + + +public class DoCreateVfModuleRollback extends AbstractServiceTaskProcessor{ + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoCreateVfModuleRollback.class); + + def Prefix="DCVFMR_" + ExceptionUtil exceptionUtil = new ExceptionUtil() + + public void initProcessVariables(DelegateExecution execution) { + execution.setVariable("prefix",Prefix) + } + + // parse the incoming DELETE_VF_MODULE request for the Generic Vnf and Vf Module Ids + // and formulate the outgoing request for PrepareUpdateAAIVfModuleRequest + public void preProcessRequest(DelegateExecution execution) { + + + initProcessVariables(execution) + + try { + + execution.setVariable("rolledBack", null) + execution.setVariable("rollbackError", null) + + def rollbackData = execution.getVariable("rollbackData") + msoLogger.debug("RollbackData:" + rollbackData) + + if (rollbackData != null) { + String vnfId = rollbackData.get("VFMODULE", "vnfid") + execution.setVariable("DCVFMR_vnfId", vnfId) + String vfModuleId = rollbackData.get("VFMODULE", "vfmoduleid") + execution.setVariable("DCVFMR_vfModuleId", vfModuleId) + String source = rollbackData.get("VFMODULE", "source") + execution.setVariable("DCVFMR_source", source) + String serviceInstanceId = rollbackData.get("VFMODULE", "serviceInstanceId") + execution.setVariable("DCVFMR_serviceInstanceId", serviceInstanceId) + String serviceId = rollbackData.get("VFMODULE", "service-id") + execution.setVariable("DCVFMR_serviceId", serviceId) + String vnfType = rollbackData.get("VFMODULE", "vnftype") + execution.setVariable("DCVFMR_vnfType", vnfType) + String vnfName = rollbackData.get("VFMODULE", "vnfname") + execution.setVariable("DCVFMR_vnfName", vnfName) + String tenantId = rollbackData.get("VFMODULE", "tenantid") + execution.setVariable("DCVFMR_tenantId", tenantId) + String vfModuleName = rollbackData.get("VFMODULE", "vfmodulename") + execution.setVariable("DCVFMR_vfModuleName", vfModuleName) + String vfModuleModelName = rollbackData.get("VFMODULE", "vfmodulemodelname") + execution.setVariable("DCVFMR_vfModuleModelName", vfModuleModelName) + String cloudSiteId = rollbackData.get("VFMODULE", "aiccloudregion") + execution.setVariable("DCVFMR_cloudSiteId", cloudSiteId) + String heatStackId = rollbackData.get("VFMODULE", "heatstackid") + execution.setVariable("DCVFMR_heatStackId", heatStackId) + String requestId = rollbackData.get("VFMODULE", "msorequestid") + execution.setVariable("DCVFMR_requestId", requestId) + // Set mso-request-id to request-id for VNF Adapter interface + execution.setVariable("mso-request-id", requestId) + List createdNetworkPolicyFqdnList = [] + int i = 0 + while (i < 100) { + String fqdn = rollbackData.get("VFMODULE", "contrailNetworkPolicyFqdn" + i) + if (fqdn == null) { + break + } + createdNetworkPolicyFqdnList.add(fqdn) + msoLogger.debug("got fqdn # " + i + ": " + fqdn) + i = i + 1 + + } + + execution.setVariable("DCVFMR_createdNetworkPolicyFqdnList", createdNetworkPolicyFqdnList) + String oamManagementV4Address = rollbackData.get("VFMODULE", "oamManagementV4Address") + execution.setVariable("DCVFMR_oamManagementV4Address", oamManagementV4Address) + String oamManagementV6Address = rollbackData.get("VFMODULE", "oamManagementV6Address") + execution.setVariable("DCVFMR_oamManagementV6Address", oamManagementV6Address) + //String serviceInstanceId = rollbackData.get("VFMODULE", "msoserviceinstanceid") + //execution.setVariable("DCVFMR_serviceInstanceId", serviceInstanceId) + execution.setVariable("DCVFMR_rollbackPrepareUpdateVfModule", rollbackData.get("VFMODULE", "rollbackPrepareUpdateVfModule")) + execution.setVariable("DCVFMR_rollbackUpdateAAIVfModule", rollbackData.get("VFMODULE", "rollbackUpdateAAIVfModule")) + execution.setVariable("DCVFMR_rollbackVnfAdapterCreate", rollbackData.get("VFMODULE", "rollbackVnfAdapterCreate")) + execution.setVariable("DCVFMR_rollbackSDNCRequestAssign", rollbackData.get("VFMODULE", "rollbackSDNCRequestAssign")) + execution.setVariable("DCVFMR_rollbackSDNCRequestActivate", rollbackData.get("VFMODULE", "rollbackSDNCRequestActivate")) + execution.setVariable("DCVFMR_rollbackCreateAAIVfModule", rollbackData.get("VFMODULE", "rollbackCreateAAIVfModule")) + execution.setVariable("DCVFMR_rollbackCreateNetworkPoliciesAAI", rollbackData.get("VFMODULE", "rollbackCreateNetworkPoliciesAAI")) + execution.setVariable("DCVFMR_rollbackUpdateVnfAAI", rollbackData.get("VFMODULE", "rollbackUpdateVnfAAI")) + + // formulate the request for PrepareUpdateAAIVfModule + String request = """<PrepareUpdateAAIVfModuleRequest> + <vnf-id>${MsoUtils.xmlEscape(vnfId)}</vnf-id> + <vf-module-id>${MsoUtils.xmlEscape(vfModuleId)}</vf-module-id> + <orchestration-status>pending-delete</orchestration-status> + </PrepareUpdateAAIVfModuleRequest>""" as String + msoLogger.debug("PrepareUpdateAAIVfModuleRequest :" + request) + execution.setVariable("PrepareUpdateAAIVfModuleRequest", request) + } else { + execution.setVariable("skipRollback", true) + } + + if (execution.getVariable("disableRollback").equals("true" )) { + execution.setVariable("skipRollback", true) + } + + } catch (BpmnError e) { + throw e; + } catch (Exception ex){ + def msg = "Exception in DoCreateVfModuleRollback preProcessRequest " + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + } + + // build a SDNC vnf-topology-operation request for the specified action + // (note: the action passed is expected to be 'changedelete' or 'delete') + public void prepSDNCAdapterRequest(DelegateExecution execution) { + + String srvInstId = execution.getVariable("DCVFMR_serviceInstanceId") + + String uuid = execution.getVariable('testReqId') // for junits + if(uuid==null){ + uuid = execution.getVariable("DCVFMR_requestId") + "-" + System.currentTimeMillis() + } + + def callbackUrl = UrnPropertiesReader.getVariable("mso.workflow.sdncadapter.callback",execution) + + String source = execution.getVariable("DCVFMR_source") + String serviceId = execution.getVariable("DCVFMR_serviceId") + String vnfId = execution.getVariable("DCVFMR_vnfId") + String vnfType = execution.getVariable("DCVFMR_vnfType") + String vnfName = execution.getVariable("DCVFMR_vnfName") + String tenantId = execution.getVariable("DCVFMR_tenantId") + String vfModuleId = execution.getVariable("DCVFMR_vfModuleId") + String vfModuleName = execution.getVariable("DCVFMR_vfModuleName") + String vfModuleModelName = execution.getVariable("DCVFMR_vfModuleModelName") + String cloudSiteId = execution.getVariable("DCVFMR_cloudSiteId") + String requestId = execution.getVariable("DCVFMR_requestId") + + String serviceInstanceIdToSdnc = "" + if (srvInstId != null && !srvInstId.isEmpty()) { + serviceInstanceIdToSdnc = srvInstId + } else { + serviceInstanceIdToSdnc = vfModuleId + } + + def doSDNCActivateRollback = execution.getVariable("DCVFMR_rollbackSDNCRequestActivate") + def doSDNCAssignRollback = execution.getVariable("DCVFMR_rollbackSDNCRequestAssign") + + def action = "" + def requestAction = "" + + if (doSDNCActivateRollback.equals("true")) { + action = "delete" + requestAction = "DisconnectVNFRequest" + } + else if (doSDNCAssignRollback.equals("true")) { + action = "rollback" + requestAction = "VNFActivateRequest" + } + else + return + + + String request = """<sdncadapterworkflow:SDNCAdapterWorkflowRequest xmlns:ns5="http://org.onap/so/request/types/v1" + xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1" + xmlns:sdncadapter="http://org.onap/workflow/sdnc/adapter/schema/v1"> + <sdncadapter:RequestHeader> + <sdncadapter:RequestId>${MsoUtils.xmlEscape(uuid)}</sdncadapter:RequestId> + <sdncadapter:SvcInstanceId>${MsoUtils.xmlEscape(vfModuleId)}</sdncadapter:SvcInstanceId> + <sdncadapter:SvcAction>${MsoUtils.xmlEscape(action)}</sdncadapter:SvcAction> + <sdncadapter:SvcOperation>vnf-topology-operation</sdncadapter:SvcOperation> + <sdncadapter:CallbackUrl>${MsoUtils.xmlEscape(callbackUrl)}</sdncadapter:CallbackUrl> + </sdncadapter:RequestHeader> + <sdncadapterworkflow:SDNCRequestData> + <request-information> + <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> + <request-action>${MsoUtils.xmlEscape(requestAction)}</request-action> + <source>${MsoUtils.xmlEscape(source)}</source> + <notification-url/> + <order-number/> + <order-version/> + </request-information> + <service-information> + <service-id>${MsoUtils.xmlEscape(serviceId)}</service-id> + <service-type>${MsoUtils.xmlEscape(serviceId)}</service-type> + <service-instance-id>${MsoUtils.xmlEscape(serviceInstanceIdToSdnc)}</service-instance-id> + <subscriber-name>notsurewecare</subscriber-name> + </service-information> + <vnf-request-information> + <vnf-id>${MsoUtils.xmlEscape(vfModuleId)}</vnf-id> + <vnf-type>${MsoUtils.xmlEscape(vfModuleModelName)}</vnf-type> + <vnf-name>${MsoUtils.xmlEscape(vfModuleName)}</vnf-name> + <generic-vnf-id>${MsoUtils.xmlEscape(vnfId)}</generic-vnf-id> + <generic-vnf-name>${MsoUtils.xmlEscape(vnfName)}</generic-vnf-name> + <generic-vnf-type>${MsoUtils.xmlEscape(vnfType)}</generic-vnf-type> + <aic-cloud-region>${MsoUtils.xmlEscape(cloudSiteId)}</aic-cloud-region> + <tenant>${MsoUtils.xmlEscape(tenantId)}</tenant> + </vnf-request-information> + </sdncadapterworkflow:SDNCRequestData> + </sdncadapterworkflow:SDNCAdapterWorkflowRequest>""" + + msoLogger.debug("sdncAdapterWorkflowRequest: " + request) + execution.setVariable("sdncAdapterWorkflowRequest", request) + } + + public void preProcessSDNCDeactivateRequest(DelegateExecution execution){ + + execution.setVariable("prefix", Prefix) + msoLogger.trace("STARTED preProcessSDNCDeactivateRequest") + + def serviceInstanceId = execution.getVariable("DCVFMR_serviceInstanceId") + + try{ + //Build SDNC Request + + String deactivateSDNCRequest = buildSDNCRequest(execution, serviceInstanceId, "deactivate") + + deactivateSDNCRequest = utils.formatXml(deactivateSDNCRequest) + execution.setVariable("DCVFMR_deactivateSDNCRequest", deactivateSDNCRequest) + msoLogger.debug("Outgoing DeactivateSDNCRequest is: \n" + deactivateSDNCRequest) + + }catch(Exception e){ + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception Occured Processing preProcessSDNCDeactivateRequest.", "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during preProcessSDNCDeactivateRequest Method:\n" + e.getMessage()) + } + msoLogger.trace("COMPLETED preProcessSDNCDeactivateRequest") + } + + public void preProcessSDNCUnassignRequest(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.preProcessSDNCUnassignRequest(' + + 'execution=' + execution.getId() + + ')' + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + msoLogger.trace('Entered ' + method) + execution.setVariable("prefix", Prefix) + msoLogger.trace("STARTED preProcessSDNCUnassignRequest Process") + try{ + String serviceInstanceId = execution.getVariable("DCVFMR_serviceInstanceId") + + String unassignSDNCRequest = buildSDNCRequest(execution, serviceInstanceId, "unassign") + + execution.setVariable("DCVFMR_unassignSDNCRequest", unassignSDNCRequest) + msoLogger.debug("Outgoing UnassignSDNCRequest is: \n" + unassignSDNCRequest) + + }catch(Exception e){ + msoLogger.debug("Exception Occured Processing preProcessSDNCUnassignRequest. Exception is:\n" + e) + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during preProcessSDNCUnassignRequest Method:\n" + e.getMessage()) + } + msoLogger.trace("COMPLETED preProcessSDNCUnassignRequest Process") + } + + public String buildSDNCRequest(DelegateExecution execution, String svcInstId, String action){ + + String uuid = execution.getVariable('testReqId') // for junits + if(uuid==null){ + uuid = execution.getVariable("DCVFMR_requestId") + "-" + System.currentTimeMillis() + } + def callbackURL = UrnPropertiesReader.getVariable("mso.workflow.sdncadapter.callback",execution) + def requestId = execution.getVariable("DCVFMR_requestId") + def serviceId = execution.getVariable("DCVFMR_serviceId") + def serviceInstanceId = execution.getVariable("DCVFMR_serviceInstanceId") + def vfModuleId = execution.getVariable("DCVFMR_vfModuleId") + def source = execution.getVariable("DCVFMR_source") + def vnfId = execution.getVariable("DCVFMR_vnfId") + + def sdncVersion = execution.getVariable("sdncVersion") + + String sdncRequest = + """<sdncadapterworkflow:SDNCAdapterWorkflowRequest xmlns:ns5="http://org.onap/so/request/types/v1" + xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1" + xmlns:sdncadapter="http://org.onap.so/workflow/sdnc/adapter/schema/v1"> + <sdncadapter:RequestHeader> + <sdncadapter:RequestId>${MsoUtils.xmlEscape(uuid)}</sdncadapter:RequestId> + <sdncadapter:SvcInstanceId>${MsoUtils.xmlEscape(svcInstId)}</sdncadapter:SvcInstanceId> + <sdncadapter:SvcAction>${MsoUtils.xmlEscape(action)}</sdncadapter:SvcAction> + <sdncadapter:SvcOperation>vf-module-topology-operation</sdncadapter:SvcOperation> + <sdncadapter:CallbackUrl>${MsoUtils.xmlEscape(callbackURL)}</sdncadapter:CallbackUrl> + <sdncadapter:MsoAction>generic-resource</sdncadapter:MsoAction> + </sdncadapter:RequestHeader> + <sdncadapterworkflow:SDNCRequestData> + <request-information> + <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> + <request-action>DeleteVfModuleInstance</request-action> + <source>${MsoUtils.xmlEscape(source)}</source> + <notification-url/> + <order-number/> + <order-version/> + </request-information> + <service-information> + <service-id/> + <subscription-service-type/> + <service-instance-id>${MsoUtils.xmlEscape(serviceInstanceId)}</service-instance-id> + <global-customer-id/> + </service-information> + <vnf-information> + <vnf-id>${MsoUtils.xmlEscape(vnfId)}</vnf-id> + <vnf-type/> + </vnf-information> + <vf-module-information> + <vf-module-id>${MsoUtils.xmlEscape(vfModuleId)}</vf-module-id> + </vf-module-information> + <vf-module-request-input/> + </sdncadapterworkflow:SDNCRequestData> + </sdncadapterworkflow:SDNCAdapterWorkflowRequest>""" + + msoLogger.debug("sdncRequest: " + sdncRequest) + return sdncRequest + } + + // parse the incoming DELETE_VF_MODULE request + // and formulate the outgoing VnfAdapterDeleteV1 request + public void prepVNFAdapterRequest(DelegateExecution execution) { + + String requestId = UUID.randomUUID().toString() + String origRequestId = execution.getVariable("DCVFMR_requestId") + String srvInstId = execution.getVariable("DCVFMR_serviceInstanceId") + String aicCloudRegion = execution.getVariable("DCVFMR_cloudSiteId") + String vnfId = execution.getVariable("DCVFMR_vnfId") + String vfModuleId = execution.getVariable("DCVFMR_vfModuleId") + String vfModuleStackId = execution.getVariable("DCVFMR_heatStackId") + String tenantId = execution.getVariable("DCVFMR_tenantId") + def messageId = execution.getVariable('mso-request-id') + '-' + + System.currentTimeMillis() + def notificationUrl = createCallbackURL(execution, "VNFAResponse", messageId) + def useQualifiedHostName = UrnPropertiesReader.getVariable("mso.use.qualified.host",execution) + if ('true'.equals(useQualifiedHostName)) { + notificationUrl = utils.getQualifiedHostNameForCallback(notificationUrl) + } + + String request = """ + <deleteVfModuleRequest> + <cloudSiteId>${MsoUtils.xmlEscape(aicCloudRegion)}</cloudSiteId> + <tenantId>${MsoUtils.xmlEscape(tenantId)}</tenantId> + <vnfId>${MsoUtils.xmlEscape(vnfId)}</vnfId> + <vfModuleId>${MsoUtils.xmlEscape(vfModuleId)}</vfModuleId> + <vfModuleStackId>${MsoUtils.xmlEscape(vfModuleStackId)}</vfModuleStackId> + <skipAAI>true</skipAAI> + <msoRequest> + <requestId>${MsoUtils.xmlEscape(origRequestId)}</requestId> + <serviceInstanceId>${MsoUtils.xmlEscape(srvInstId)}</serviceInstanceId> + </msoRequest> + <messageId>${MsoUtils.xmlEscape(messageId)}</messageId> + <notificationUrl>${MsoUtils.xmlEscape(notificationUrl)}</notificationUrl> + </deleteVfModuleRequest> + """ as String + + msoLogger.debug("vnfAdapterRestV1Request: " + request) + execution.setVariable("vnfAdapterRestV1Request", request) + } + + // parse the incoming DELETE_VF_MODULE request + // and formulate the outgoing UpdateAAIVfModuleRequest request + public void prepUpdateAAIVfModule(DelegateExecution execution) { + + String vnfId = execution.getVariable("DCVFMR_vnfId") + String vfModuleId = execution.getVariable("DCVFMR_vfModuleId") + // formulate the request for UpdateAAIVfModule + String request = """<UpdateAAIVfModuleRequest> + <vnf-id>${MsoUtils.xmlEscape(vnfId)}</vnf-id> + <vf-module-id>${MsoUtils.xmlEscape(vfModuleId)}</vf-module-id> + <heat-stack-id>DELETE</heat-stack-id> + <orchestration-status>deleted</orchestration-status> + </UpdateAAIVfModuleRequest>""" as String + msoLogger.debug("UpdateAAIVfModuleRequest :" + request) + execution.setVariable("UpdateAAIVfModuleRequest", request) + } + + // parse the incoming DELETE_VF_MODULE request + // and formulate the outgoing UpdateAAIVfModuleRequest request + public void prepUpdateAAIVfModuleToAssigned(DelegateExecution execution) { + + String vnfId = execution.getVariable("DCVFMR_vnfId") + String vfModuleId = execution.getVariable("DCVFMR_vfModuleId") + // formulate the request for UpdateAAIVfModule + String request = """<UpdateAAIVfModuleRequest> + <vnf-id>${MsoUtils.xmlEscape(vnfId)}</vnf-id> + <vf-module-id>${MsoUtils.xmlEscape(vfModuleId)}</vf-module-id> + <heat-stack-id></heat-stack-id> + <orchestration-status>Assigned</orchestration-status> + </UpdateAAIVfModuleRequest>""" as String + msoLogger.debug("UpdateAAIVfModuleRequest :" + request) + execution.setVariable("UpdateAAIVfModuleRequest", request) + } + + // parse the incoming DELETE_VF_MODULE request + // and formulate the outgoing DeleteAAIVfModuleRequest request + public void prepDeleteAAIVfModule(DelegateExecution execution) { + + String vnfId = execution.getVariable("DCVFMR_vnfId") + String vfModuleId = execution.getVariable("DCVFMR_vfModuleId") + // formulate the request for UpdateAAIVfModule + String request = """<DeleteAAIVfModuleRequest> + <vnf-id>${MsoUtils.xmlEscape(vnfId)}</vnf-id> + <vf-module-id>${MsoUtils.xmlEscape(vfModuleId)}</vf-module-id> + </DeleteAAIVfModuleRequest>""" as String + msoLogger.debug("DeleteAAIVfModuleRequest :" + request) + execution.setVariable("DeleteAAIVfModuleRequest", request) + } + + // generates a WorkflowException if + // - + public void handleDoDeleteVfModuleFailure(DelegateExecution execution) { + + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "AAI error occurred deleting the Generic Vnf"+ execution.getVariable("DoDVfMod_deleteGenericVnfResponse"), "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError); + String processKey = getProcessKey(execution); + exceptionUtil.buildWorkflowException(execution, 5000, "Failure in DoDeleteVfModule") + + } + + public void sdncValidateResponse(DelegateExecution execution, String response){ + + execution.setVariable("prefix",Prefix) + + WorkflowException workflowException = execution.getVariable("WorkflowException") + boolean successIndicator = execution.getVariable("SDNCA_SuccessIndicator") + + SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this) + sdncAdapterUtils.validateSDNCResponse(execution, response, workflowException, successIndicator) + + if(execution.getVariable(Prefix + 'sdncResponseSuccess') == true){ + msoLogger.debug("Successfully Validated SDNC Response") + }else{ + throw new BpmnError("MSOWorkflowException") + } + } + + public void deleteNetworkPoliciesFromAAI(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.deleteNetworkPoliciesFromAAI(' + + 'execution=' + execution.getId() + + ')' + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + msoLogger.trace('Entered ' + method) + execution.setVariable("prefix", Prefix) + msoLogger.trace("STARTED deleteNetworkPoliciesFromAAI") + + try { + // get variables + List fqdnList = execution.getVariable(Prefix + "createdNetworkPolicyFqdnList") + if (fqdnList == null) { + msoLogger.debug("No network policies to delete") + return + } + int fqdnCount = fqdnList.size() + + execution.setVariable(Prefix + "networkPolicyFqdnCount", fqdnCount) + msoLogger.debug("networkPolicyFqdnCount - " + fqdnCount) + + String aai_endpoint = UrnPropertiesReader.getVariable("aai.endpoint", execution) + AaiUtil aaiUriUtil = new AaiUtil(this) + String aai_uri = aaiUriUtil.getNetworkPolicyUri(execution) + + if (fqdnCount > 0) { + // AII loop call over contrail network policy fqdn list + for (i in 0..fqdnCount-1) { + + int counting = i+1 + String fqdn = fqdnList[i] + + // Query AAI for this network policy FQDN + + String queryNetworkPolicyByFqdnAAIRequest = "${aai_endpoint}${aai_uri}?network-policy-fqdn=" + UriUtils.encode(fqdn, "UTF-8") + msoLogger.debug("AAI request endpoint: " + queryNetworkPolicyByFqdnAAIRequest) + + def aaiRequestId = UUID.randomUUID().toString() + APIResponse response = aaiUriUtil.executeAAIGetCall(execution, queryNetworkPolicyByFqdnAAIRequest) + int returnCode = response.getStatusCode() + execution.setVariable(Prefix + "aaiQueryNetworkPolicyByFqdnReturnCode", returnCode) + msoLogger.debug("AAI query network policy Response Code, NetworkPolicy #" + counting + " : " + returnCode) + + String aaiResponseAsString = response.getResponseBodyAsString() + + if (isOneOf(returnCode, 200, 201)) { + msoLogger.debug("The return code is: " + returnCode) + // This network policy FQDN exists in AAI - need to delete it now + execution.setVariable(Prefix + "queryNetworkPolicyByFqdnAAIResponse", aaiResponseAsString) + msoLogger.debug("QueryAAINetworkPolicyByFQDN Success REST Response, , NetworkPolicy #" + counting + " : " + "\n" + aaiResponseAsString) + // Retrieve the network policy id for this FQDN + def networkPolicyId = utils.getNodeText(aaiResponseAsString, "network-policy-id") + msoLogger.debug("Deleting network-policy with network-policy-id " + networkPolicyId) + + // Retrieve the resource version for this network policy + def resourceVersion = utils.getNodeText(aaiResponseAsString, "resource-version") + msoLogger.debug("Deleting network-policy with resource-version " + resourceVersion) + + String delNetworkPolicyAAIRequest = "${aai_endpoint}${aai_uri}/" + UriUtils.encode(networkPolicyId, "UTF-8") + + "?resource-version=" + UriUtils.encode(resourceVersion, "UTF-8") + + msoLogger.debug("AAI request endpoint: " + delNetworkPolicyAAIRequest) + + def aaiRequestIdDel = UUID.randomUUID().toString() + msoLogger.debug("Sending DELETE call to AAI with Endpoint /n" + delNetworkPolicyAAIRequest) + + APIResponse responseDel = aaiUriUtil.executeAAIDeleteCall(execution, delNetworkPolicyAAIRequest) + + int returnCodeDel = responseDel.getStatusCode() + execution.setVariable(Prefix + "aaiDeleteNetworkPolicyReturnCode", returnCodeDel) + msoLogger.debug("AAI delete network policy Response Code, NetworkPolicy #" + counting + " : " + returnCodeDel) + + if (isOneOf(returnCodeDel, 200, 201, 204)) { + msoLogger.debug("The return code from deleting network policy is: " + returnCodeDel) + // This network policy was deleted from AAI successfully + msoLogger.debug(" DelAAINetworkPolicy Success REST Response, , NetworkPolicy #" + counting + " : ") + + } else { + // aai all errors + String delErrorMessage = "Unable to delete network-policy to AAI deleteNetworkPoliciesFromAAI - " + returnCodeDel + msoLogger.debug(delErrorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, delErrorMessage) + } + } else if (returnCode == 404) { + // This network policy FQDN is not in AAI. No need to delete. + msoLogger.debug("The return code is: " + returnCode) + msoLogger.debug("This network policy FQDN is not in AAI: " + fqdn) + } else { + if (aaiResponseAsString.contains("RESTFault")) { + WorkflowException exceptionObject = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) + execution.setVariable("WorkflowException", exceptionObject) + throw new BpmnError("MSOWorkflowException") + + } else { + // aai all errors + String dataErrorMessage = "Unexpected Response from deleteNetworkPoliciesFromAAI - " + returnCode + msoLogger.debug(dataErrorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + + } + } + + + + } // end loop + + + } else { + msoLogger.debug("No contrail network policies to query/create") + + } + + } catch (BpmnError e) { + throw e; + + } catch (Exception ex) { + String exceptionMessage = "Bpmn error encountered in DoCreateVfModuleRollback flow. deleteNetworkPoliciesFromAAI() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + } + + } + + + /** + * Prepare a Request for invoking the UpdateAAIGenericVnf subflow. + * + * @param execution The flow's execution instance. + */ + public void preProcessUpdateAAIGenericVnf(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.preProcessUpdateAAIGenericVnf((' + + 'execution=' + execution.getId() + + ')' + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + msoLogger.trace('Entered ' + method) + + try { + def vnfId = execution.getVariable('DCVFMR_vnfId') + def oamManagementV4Address = execution.getVariable(Prefix + 'oamManagementV4Address') + def oamManagementV6Address = execution.getVariable(Prefix + 'oamManagementV6Address') + def ipv4OamAddressElement = '' + def managementV6AddressElement = '' + + if (oamManagementV4Address != null) { + ipv4OamAddressElement = '<ipv4-oam-address>' + 'DELETE' + '</ipv4-oam-address>' + } + + if (oamManagementV6Address != null) { + managementV6AddressElement = '<management-v6-address>' + 'DELETE' + '</management-v6-address>' + } + + + String updateAAIGenericVnfRequest = """ + <UpdateAAIGenericVnfRequest> + <vnf-id>${MsoUtils.xmlEscape(vnfId)}</vnf-id> + ${ipv4OamAddressElement} + ${managementV6AddressElement} + </UpdateAAIGenericVnfRequest> + """ + updateAAIGenericVnfRequest = utils.formatXml(updateAAIGenericVnfRequest) + execution.setVariable(Prefix + 'updateAAIGenericVnfRequest', updateAAIGenericVnfRequest) + msoLogger.debug('Request for UpdateAAIGenericVnf:\n' + updateAAIGenericVnfRequest) + + + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in preProcessUpdateAAIGenericVnf((): ' + e.getMessage()) + } + } + + public void setSuccessfulRollbackStatus (DelegateExecution execution){ + + execution.setVariable("prefix", Prefix) + msoLogger.trace("STARTED setSuccessfulRollbackStatus") + + try{ + // Set rolledBack to true, rollbackError to null + execution.setVariable("rolledBack", true) + execution.setVariable("rollbackError", null) + + }catch(Exception e){ + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception Occured Processing setSuccessfulRollbackStatus.", "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during setSuccessfulRollbackStatus Method:\n" + e.getMessage()) + } + msoLogger.trace("COMPLETED setSuccessfulRollbackStatus") + } + + public void setFailedRollbackStatus (DelegateExecution execution){ + + execution.setVariable("prefix", Prefix) + msoLogger.trace("STARTED setFailedRollbackStatus") + + try{ + // Set rolledBack to false, rollbackError to actual value, rollbackData to null + execution.setVariable("rolledBack", false) + execution.setVariable("rollbackError", 'Caught exception in DoCreateVfModuleRollback') + execution.setVariable("rollbackData", null) + + }catch(Exception e){ + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception Occured Processing setFailedRollbackStatus.", "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during setFailedRollbackStatus Method:\n" + e.getMessage()) + } + msoLogger.trace("COMPLETED setFailedRollbackStatus") + } +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModuleVolumeRollback.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModuleVolumeRollback.groovy new file mode 100644 index 0000000000..5995b6b099 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModuleVolumeRollback.groovy @@ -0,0 +1,242 @@ +/* + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts; + +import groovy.xml.XmlUtil + +import groovy.json.* + + +import java.util.UUID; + +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.apache.commons.lang3.* +import org.apache.commons.codec.binary.Base64; +import org.onap.so.bpmn.common.scripts.AaiUtil +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.onap.so.bpmn.common.scripts.ExceptionUtil +import org.onap.so.bpmn.common.scripts.VidUtils +import org.onap.so.bpmn.core.RollbackData +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.rest.APIResponse +import org.springframework.web.util.UriUtils +import org.onap.so.logger.MsoLogger +import org.onap.so.logger.MessageEnum + + +public class DoCreateVfModuleVolumeRollback extends AbstractServiceTaskProcessor { + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoCreateVfModuleVolumeRollback.class); + + String Prefix="DCVFMODVOLRBK_" + ExceptionUtil exceptionUtil = new ExceptionUtil() + JsonUtils jsonUtil = new JsonUtils() + VidUtils vidUtils = new VidUtils(this) + + def className = getClass().getSimpleName() + + /** + * This method is executed during the preProcessRequest task of the <class>DoCreateVfModuleVolumeRollback.bpmn</class> process. + * @param execution + */ + public InitializeProcessVariables(DelegateExecution execution){ + /* Initialize all the process variables in this block */ + + execution.setVariable(Prefix + "volumeGroupName", null) + execution.setVariable(Prefix + "lcpCloudRegionId", null) + execution.setVariable(Prefix + "rollbackVnfARequest", null) + + } + + // ************************************************** + // Pre or Prepare Request Section + // ************************************************** + /** + * This method is executed during the preProcessRequest task of the <class>DoCreateVfModuleVolumeRollback.bpmn</class> process. + * @param execution + */ + public void preProcessRequest (DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + + InitializeProcessVariables(execution) +// rollbackData.put("DCVFMODULEVOL", "aiccloudregion", cloudSiteId) + RollbackData rollbackData = execution.getVariable("rollbackData") + +// String vnfId = rollbackData.get("DCVFMODULEVOL", "vnfid") +// execution.setVariable("DCVFMODVOLRBK_vnfId", vnfId) +// String vfModuleId = rollbackData.get("DCVFMODULEVOL", "vfmoduleid") +// execution.setVariable("DCVFMODVOLRBK_vfModuleId", vfModuleId) +// String source = rollbackData.get("DCVFMODULEVOL", "source") +// execution.setVariable("DCVFMODVOLRBK_source", source) +// String serviceInstanceId = rollbackData.get("DCVFMODULEVOL", "serviceInstanceId") +// execution.setVariable("DCVFMODVOLRBK_serviceInstanceId", serviceInstanceId) +// String serviceId = rollbackData.get("DCVFMODULEVOL", "service-id") +// execution.setVariable("DCVFMODVOLRBK_serviceId", serviceId) +// String vnfType = rollbackData.get("DCVFMODULEVOL", "vnftype") +// execution.setVariable("DCVFMODVOLRBK_vnfType", vnfType) +// String vnfName = rollbackData.get("DCVFMODULEVOL", "vnfname") +// execution.setVariable("DCVFMODVOLRBK_vnfName", vnfName) +// String tenantId = rollbackData.get("DCVFMODULEVOL", "tenantid") +// execution.setVariable("DCVFMODVOLRBK_tenantId", tenantId) +// String vfModuleName = rollbackData.get("DCVFMODULEVOL", "vfmodulename") +// execution.setVariable("DCVFMODVOLRBK_vfModuleName", vfModuleName) +// String vfModuleModelName = rollbackData.get("DCVFMODULEVOL", "vfmodulemodelname") +// execution.setVariable("DCVFMODVOLRBK_vfModuleModelName", vfModuleModelName) +// String cloudSiteId = rollbackData.get("DCVFMODULEVOL", "aiccloudregion") +// execution.setVariable("DCVFMODVOLRBK_cloudSiteId", cloudSiteId) +// String heatStackId = rollbackData.get("DCVFMODULEVOL", "heatstackid") +// execution.setVariable("DCVFMODVOLRBK_heatStackId", heatStackId) +// String requestId = rollbackData.get("DCVFMODULEVOL", "msorequestid") +// execution.setVariable("DCVFMODVOLRBK_requestId", requestId) + + String volumeGroupName = rollbackData.get("DCVFMODULEVOL", "volumeGroupName") + execution.setVariable("DCVFMODVOLRBK_volumeGroupName", volumeGroupName) + + String lcpCloudRegionId = rollbackData.get("DCVFMODULEVOL", "aiccloudregion") + execution.setVariable("DCVFMODVOLRBK_lcpCloudRegionId", lcpCloudRegionId) + + execution.setVariable("DCVFMODVOLRBK_rollbackVnfARequest", rollbackData.get("DCVFMODULEVOL", "rollbackVnfARequest")) + execution.setVariable("DCVFMODVOLRBK_backoutOnFailure", rollbackData.get("DCVFMODULEVOL", "backoutOnFailure")) + execution.setVariable("DCVFMODVOLRBK_isCreateVnfRollbackNeeded", rollbackData.get("DCVFMODULEVOL", "isCreateVnfRollbackNeeded")) + execution.setVariable("DCVFMODVOLRBK_isAAIRollbackNeeded", rollbackData.get("DCVFMODULEVOL", "isAAIRollbackNeeded")) + + } + + /** + * Query AAI volume group by name + * @param execution + * @param isDebugEnabled + */ + public void callRESTQueryAAIVolGrpName(DelegateExecution execution, isDebugEnabled) { + + def volumeGroupName = execution.getVariable('DCVFMODVOLRBK_volumeGroupName') + def cloudRegion = execution.getVariable('DCVFMODVOLRBK_lcpCloudRegionId') + + // This is for stub testing + def testVolumeGroupName = execution.getVariable('test-volume-group-name') + if (testVolumeGroupName != null && testVolumeGroupName.length() > 0) { + volumeGroupName = testVolumeGroupName + } + + AaiUtil aaiUtil = new AaiUtil(this) + String aaiEndpoint = aaiUtil.getCloudInfrastructureCloudRegionEndpoint(execution) + String queryAAIVolumeNameRequest = aaiEndpoint + '/' + cloudRegion + "/volume-groups" + "?volume-group-name=" + UriUtils.encode(volumeGroupName, 'UTF-8') + + msoLogger.debug('Query AAI volume group by name: ' + queryAAIVolumeNameRequest) + + APIResponse response = aaiUtil.executeAAIGetCall(execution, queryAAIVolumeNameRequest) + + String returnCode = response.getStatusCode() + String aaiResponseAsString = response.getResponseBodyAsString() + + msoLogger.debug("AAI query volume group by name return code: " + returnCode) + msoLogger.debug("AAI query volume group by name response: " + aaiResponseAsString) + + ExceptionUtil exceptionUtil = new ExceptionUtil() + + execution.setVariable(prefix+"queryAAIVolGrpNameResponse", aaiResponseAsString) + execution.setVariable(prefix+'AaiReturnCode', returnCode) + + if (returnCode=='200') { + // @TODO: verify error code + // @TODO: create class of literals representing error codes + execution.setVariable(prefix+'queryAAIVolGrpNameResponse', aaiResponseAsString) + msoLogger.debug("Volume Group Name $volumeGroupName exists in AAI.") + } else { + if (returnCode=='404') { + msoLogger.debug("Volume Group Name $volumeGroupName does not exist in AAI.") + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Volume group $volumeGroupName not found in AAI. Response code: 404") + } else { + WorkflowException aWorkflowException = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) + throw new BpmnError("MSOWorkflowException") + } + } + } + + + + public void callRESTDeleteAAIVolumeGroup(DelegateExecution execution, isDebugEnabled) { + + callRESTQueryAAIVolGrpName(execution, isDebugEnabled) + + def queryAaiVolumeGroupResponse = execution.getVariable(prefix+'queryAAIVolGrpNameResponse') + + def volumeGroupId = utils.getNodeText(queryAaiVolumeGroupResponse, "volume-group-id") + def resourceVersion = utils.getNodeText(queryAaiVolumeGroupResponse, "resource-version") + + def cloudRegion = execution.getVariable("DCVFMODVOLRBK_lcpCloudRegionId") + + AaiUtil aaiUtil = new AaiUtil(this) + String aaiEndpoint = aaiUtil.getCloudInfrastructureCloudRegionEndpoint(execution) + String deleteAAIVolumeGrpIdRequest = aaiEndpoint + '/' + cloudRegion + "/volume-groups/volume-group" + '/' + volumeGroupId + "?resource-version=" + UriUtils.encode(resourceVersion, "UTF-8") + + msoLogger.debug('Delete AAI volume group : ' + deleteAAIVolumeGrpIdRequest) + + APIResponse response = aaiUtil.executeAAIDeleteCall(execution, deleteAAIVolumeGrpIdRequest) + + String returnCode = response.getStatusCode() + String aaiResponseAsString = response.getResponseBodyAsString() + + msoLogger.debug("AAI delete volume group return code: " + returnCode) + msoLogger.debug("AAI delete volume group response: " + aaiResponseAsString) + + ExceptionUtil exceptionUtil = new ExceptionUtil() + + def volumeGroupNameFound = prefix+'volumeGroupNameFound' + if (returnCode=='200' || returnCode=='204' ) { + msoLogger.debug("Volume group $volumeGroupId deleted.") + } else { + if (returnCode=='404') { + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Volume group $volumeGroupId not found for delete in AAI Response code: 404") + } else { + WorkflowException aWorkflowException = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) + throw new BpmnError("MSOWorkflowException") + } + } + } + + // ******************************* + // Build Error Section + // ******************************* + + + + public void processJavaException(DelegateExecution execution){ + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + + try{ + msoLogger.debug("Caught a Java Exception in " + Prefix) + msoLogger.debug("Started processJavaException Method") + msoLogger.debug("Variables List: " + execution.getVariables()) + execution.setVariable("UnexpectedError", "Caught a Java Lang Exception - " + Prefix) // Adding this line temporarily until this flows error handling gets updated + exceptionUtil.buildWorkflowException(execution, 500, "Caught a Java Lang Exception") + + }catch(Exception e){ + msoLogger.debug("Caught Exception during processJavaException Method: " + e) + execution.setVariable("UnexpectedError", "Exception in processJavaException method - " + Prefix) // Adding this line temporarily until this flows error handling gets updated + exceptionUtil.buildWorkflowException(execution, 500, "Exception in processJavaException method" + Prefix) + } + msoLogger.debug("Completed processJavaException Method in " + Prefix) + } + +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModuleVolumeV2.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModuleVolumeV2.groovy new file mode 100644 index 0000000000..f87f32c610 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModuleVolumeV2.groovy @@ -0,0 +1,628 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts + +import org.apache.commons.lang3.* +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.onap.so.bpmn.common.scripts.AaiUtil +import org.onap.so.bpmn.common.scripts.ExceptionUtil +import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.so.bpmn.common.scripts.NetworkUtils +import org.onap.so.bpmn.common.scripts.VfModuleBase; +import org.onap.so.bpmn.core.RollbackData +import org.onap.so.bpmn.core.UrnPropertiesReader +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.bpmn.core.json.JsonUtils; +import org.onap.so.logger.MsoLogger +import org.onap.so.rest.APIResponse +import org.springframework.web.util.UriUtils +import org.onap.so.client.aai.AAIResourcesClient +import org.onap.so.client.aai.AAIObjectType +import org.onap.so.client.aai.entities.AAIResultWrapper +import org.onap.so.client.aai.entities.Relationships +import org.onap.so.client.aai.entities.uri.AAIResourceUri +import org.onap.so.client.aai.entities.uri.AAIUriFactory +import org.json.JSONObject +import javax.ws.rs.NotFoundException + +class DoCreateVfModuleVolumeV2 extends VfModuleBase { + + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoCreateVfModuleVolumeV2.class); + String prefix='DCVFMODVOLV2_' + JsonUtils jsonUtil = new JsonUtils() + + + /** + * Perform initial processing, such as request validation, initialization of variables, etc. + * * @param execution + */ + public void preProcessRequest(DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + preProcessRequest(execution, isDebugEnabled) + } + + public void preProcessRequest(DelegateExecution execution, isDebugLogEnabled) { + + execution.setVariable("prefix",prefix) + execution.setVariable(prefix+'SuccessIndicator', false) + execution.setVariable(prefix+'isPONR', false) + + displayInput(execution, isDebugLogEnabled) + setRollbackData(execution, isDebugLogEnabled) + setRollbackEnabled(execution, isDebugLogEnabled) + + + def tenantId = execution.getVariable("tenantId") + if (tenantId == null) { + String cloudConfiguration = execution.getVariable("cloudConfiguration") + tenantId = jsonUtil.getJsonValue(cloudConfiguration, "cloudConfiguration.tenantId") + execution.setVariable("tenantId", tenantId) + } + + def cloudSiteId = execution.getVariable("lcpCloudRegionId") + if (cloudSiteId == null) { + String cloudConfiguration = execution.getVariable("cloudConfiguration") + cloudSiteId = jsonUtil.getJsonValue(cloudConfiguration, "cloudConfiguration.lcpCloudRegionId") + execution.setVariable("lcpCloudRegionId", cloudSiteId) + } + + // Extract attributes from modelInfo + String vfModuleModelInfo = execution.getVariable("vfModuleModelInfo") + + //modelCustomizationUuid + def modelCustomizationUuid = jsonUtil.getJsonValue(vfModuleModelInfo, "modelCustomizationUuid") + execution.setVariable("modelCustomizationId", modelCustomizationUuid) + msoLogger.debug("modelCustomizationId: " + modelCustomizationUuid) + + //modelName + def modelName = jsonUtil.getJsonValue(vfModuleModelInfo, "modelName") + execution.setVariable("modelName", modelName) + msoLogger.debug("modelName: " + modelName) + + // The following is used on the get Generic Service Instance call + execution.setVariable('GENGS_type', 'service-instance') + } + + + /** + * Display input variables + * @param execution + * @param isDebugLogEnabled + */ + public void displayInput(DelegateExecution execution, isDebugLogEnabled) { + def input = ['mso-request-id', 'msoRequestId', 'isDebugLogEnabled', 'disableRollback', 'failIfExists', 'serviceInstanceId', + 'vnfId', 'vnfName', 'tenantId', 'volumeGroupId', 'volumeGroupName', 'lcpCloudRegionId', 'vnfType', 'vfModuleModelInfo', 'asdcServiceModelVersion', + 'test-volume-group-name', 'test-volume-group-id', 'vfModuleInputParams'] + + msoLogger.debug('Begin input: ') + input.each { + msoLogger.debug(it + ': ' + execution.getVariable(it)) + } + msoLogger.debug('End input.') + } + + + /** + * Define and set rollbackdata object + * @param execution + * @param isDebugEnabled + */ + public void setRollbackData(DelegateExecution execution, isDebugEnabled) { + def rollbackData = execution.getVariable("rollbackData") + if (rollbackData == null) { + rollbackData = new RollbackData() + } + def volumeGroupName = execution.getVariable('volumeGroupName') + rollbackData.put("DCVFMODULEVOL", "volumeGroupName", volumeGroupName) + execution.setVariable("rollbackData", rollbackData) + } + + + /** + * Gets the service instance uri from aai + */ + public void getServiceInstance(DelegateExecution execution) { + try { + String serviceInstanceId = execution.getVariable('serviceInstanceId') + + AAIResourcesClient resourceClient = new AAIResourcesClient() + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, serviceInstanceId) + + if(!resourceClient.exists(uri)){ + (new ExceptionUtil()).buildAndThrowWorkflowException(execution, 2500, "Service instance was not found in aai") + } + + }catch(BpmnError e) { + throw e; + }catch (Exception ex){ + String msg = "Exception in getServiceInstance. " + ex.getMessage() + msoLogger.debug(msg) + (new ExceptionUtil()).buildAndThrowWorkflowException(execution, 2500, msg) + } + } + + /** + * Get cloud region + * @param execution + * @param isDebugEnabled + */ + public void callRESTQueryAAICloudRegion (DelegateExecution execution, isDebugEnabled) { + + def cloudRegion = execution.getVariable("lcpCloudRegionId") + msoLogger.debug('Request cloud region is: ' + cloudRegion) + + AaiUtil aaiUtil = new AaiUtil(this) + String aaiEndpoint = aaiUtil.getCloudInfrastructureCloudRegionEndpoint(execution) + String queryCloudRegionRequest = aaiEndpoint + '/' + cloudRegion + + msoLogger.debug(queryCloudRegionRequest) + + cloudRegion = aaiUtil.getAAICloudReqion(execution, queryCloudRegionRequest, "PO", cloudRegion) + + def aaiCloudRegion = aaiUtil.getAAICloudReqion(execution, queryCloudRegionRequest, "AAI", cloudRegion) + if ((aaiCloudRegion != "ERROR")) { + execution.setVariable("lcpCloudRegionId", aaiCloudRegion) + msoLogger.debug("AIC Cloud Region for AAI: " + aaiCloudRegion) + } else { + String errorMessage = "AAI Query Cloud Region Unsuccessful. Return Code: " + execution.getVariable(prefix+"queryCloudRegionReturnCode") + msoLogger.debug(errorMessage) + (new ExceptionUtil()).buildAndThrowWorkflowException(execution, 2500, errorMessage) + } + + def poCloudRegion = aaiUtil.getAAICloudReqion(execution, queryCloudRegionRequest, "PO", cloudRegion) + if ((poCloudRegion != "ERROR")) { + execution.setVariable("poLcpCloudRegionId", poCloudRegion) + msoLogger.debug("AIC Cloud Region for PO: " + poCloudRegion) + } else { + String errorMessage = "AAI Query Cloud Region Unsuccessful. Return Code: " + execution.getVariable(prefix+"queryCloudRegionReturnCode") + msoLogger.debug(errorMessage) + (new ExceptionUtil()).buildAndThrowWorkflowException(execution, 2500, errorMessage) + } + + def rollbackData = execution.getVariable("rollbackData") + rollbackData.put("DCVFMODULEVOL", "aiccloudregion", cloudRegion) + } + + + /** + * Query AAI volume group by name + * @param execution + * @param isDebugEnabled + */ + public void callRESTQueryAAIVolGrpName(DelegateExecution execution, isDebugEnabled) { + + def volumeGroupName = execution.getVariable('volumeGroupName') + def cloudRegion = execution.getVariable('lcpCloudRegionId') + + // This is for stub testing + def testVolumeGroupName = execution.getVariable('test-volume-group-name') + if (testVolumeGroupName != null && testVolumeGroupName.length() > 0) { + volumeGroupName = testVolumeGroupName + } + + AaiUtil aaiUtil = new AaiUtil(this) + String aaiEndpoint = aaiUtil.getCloudInfrastructureCloudRegionEndpoint(execution) + String queryAAIVolumeNameRequest = aaiEndpoint + '/' + cloudRegion + "/volume-groups" + "?volume-group-name=" + UriUtils.encode(volumeGroupName, 'UTF-8') + + msoLogger.debug('Query AAI volume group by name: ' + queryAAIVolumeNameRequest) + + APIResponse response = aaiUtil.executeAAIGetCall(execution, queryAAIVolumeNameRequest) + + String returnCode = response.getStatusCode() + String aaiResponseAsString = response.getResponseBodyAsString() + + msoLogger.debug("AAI query volume group by name return code: " + returnCode) + msoLogger.debug("AAI query volume group by name response: " + aaiResponseAsString) + + ExceptionUtil exceptionUtil = new ExceptionUtil() + + execution.setVariable(prefix+"queryAAIVolGrpNameResponse", aaiResponseAsString) + execution.setVariable(prefix+'AaiReturnCode', returnCode) + + if (returnCode=='200') { + execution.setVariable(prefix+'queryAAIVolGrpNameResponse', aaiResponseAsString) + msoLogger.debug("Volume Group Name $volumeGroupName exists in AAI.") + } else { + if (returnCode=='404') { + msoLogger.debug("Volume Group Name $volumeGroupName does not exist in AAI.") + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Volume group $volumeGroupName not found in AAI. Response code: 404") + } else { + WorkflowException aWorkflowException = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) + throw new BpmnError("MSOWorkflowException") + } + } + } + + + /** + * Create a WorkflowException + * @param execution + * @param isDebugEnabled + */ + public void buildWorkflowException(DelegateExecution execution, int errorCode, errorMessage, isDebugEnabled) { + msoLogger.debug(errorMessage) + (new ExceptionUtil()).buildWorkflowException(execution, 2500, errorMessage) + } + + + /** + * Create a WorkflowException + * @param execution + * @param isDebugEnabled + */ + public void handleError(DelegateExecution execution, isDebugEnabled) { + WorkflowException we = execution.getVariable('WorkflowException') + if (we == null) { + (new ExceptionUtil()).buildWorkflowException(execution, 2500, "Enexpected error encountered!") + } + throw new BpmnError("MSOWorkflowException") + } + + + /** + * Create volume group in AAI + * @param execution + * @param isDebugEnabled + */ + public void callRESTCreateAAIVolGrpName(DelegateExecution execution, isDebugEnabled) { + + def vnfId = execution.getVariable('vnfId') + def volumeGroupId = execution.getVariable('volumeGroupId') + def volumeName = execution.getVariable("volumeGroupName") + def modelCustomizationId = execution.getVariable("modelCustomizationId") + def vnfType = execution.getVariable("vnfType") + def tenantId = execution.getVariable("tenantId") + def cloudRegion = execution.getVariable('lcpCloudRegionId') + + msoLogger.debug("volumeGroupId: " + volumeGroupId) + + def testGroupId = execution.getVariable('test-volume-group-id') + if (testGroupId != null && testGroupId.trim() != '') { + msoLogger.debug("test volumeGroupId is present: " + testGroupId) + volumeGroupId = testGroupId + execution.setVariable("test-volume-group-name", "MSOTESTVOL101a-vSAMP12_base_vol_module-0") + } + + msoLogger.debug("volumeGroupId to be used: " + volumeGroupId) + + AaiUtil aaiUtil = new AaiUtil(this) + String aaiEndpoint = aaiUtil.getCloudInfrastructureCloudRegionEndpoint(execution) + String createAAIVolumeGrpNameUrlRequest = aaiEndpoint + '/' + cloudRegion + "/volume-groups/volume-group/" + UriUtils.encode(volumeGroupId, "UTF-8") + + String namespace = aaiUtil.getNamespaceFromUri(aaiUtil.getCloudInfrastructureCloudRegionUri(execution)) + msoLogger.debug("AAI namespace is: " + namespace) + + msoLogger.debug("Request URL for PUT: " + createAAIVolumeGrpNameUrlRequest) + + NetworkUtils networkUtils = new NetworkUtils() + String payload = networkUtils.createCloudRegionVolumeRequest(volumeGroupId, volumeName, vnfType, vnfId, tenantId, cloudRegion, namespace, modelCustomizationId) + String payloadXml = utils.formatXml(payload) + msoLogger.debug("Request payload for PUT: " + payloadXml) + + APIResponse response = aaiUtil.executeAAIPutCall(execution, createAAIVolumeGrpNameUrlRequest, payloadXml) + + String returnCode = response.getStatusCode() + String aaiResponseAsString = response.getResponseBodyAsString() + + msoLogger.debug("AAI create volume group return code: " + returnCode) + msoLogger.debug("AAI create volume group response: " + aaiResponseAsString) + + execution.setVariable(prefix+"createAAIVolumeGrpNameReturnCode", returnCode) + execution.setVariable(prefix+"createAAIVolumeGrpNameResponse", aaiResponseAsString) + + ExceptionUtil exceptionUtil = new ExceptionUtil() + + if (returnCode =='201') { + RollbackData rollbackData = execution.getVariable("rollbackData") + rollbackData.put("DCVFMODULEVOL", "isAAIRollbackNeeded", "true") + } else { + execution.setVariable(prefix+"isErrorMessageException", true) + if (returnCode=='404') { + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Unable to create volume group in AAI. Response code: 404") + } else { + WorkflowException aWorkflowException = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) + msoLogger.debug(" AAI Adapter Query Failed. WorkflowException - " + "\n" + aWorkflowException) + throw new BpmnError("MSOWorkflowException") + } + } + } + + + /** + * Prepare VNF adapter create request XML + * @param execution + */ + public void prepareVnfAdapterCreateRequest(DelegateExecution execution, isDebugEnabled) { + + def aaiGenericVnfResponse = execution.getVariable(prefix+'AAIQueryGenericVfnResponse') + def vnfId = utils.getNodeText(aaiGenericVnfResponse, 'vnf-id') + def vnfName = utils.getNodeText(aaiGenericVnfResponse, 'vnf-name') + def vnfType = utils.getNodeText(aaiGenericVnfResponse, "vnf-type") + + def requestId = execution.getVariable('msoRequestId') + def serviceId = execution.getVariable('serviceInstanceId') + def cloudSiteId = execution.getVariable('poLcpCloudRegionId') + def tenantId = execution.getVariable('tenantId') + def volumeGroupId = execution.getVariable('volumeGroupId') + def volumeGroupnName = execution.getVariable('volumeGroupName') + + def vnfVersion = execution.getVariable("asdcServiceModelVersion") + def vnfModuleType = execution.getVariable("modelName") + + def modelCustomizationId = execution.getVariable("modelCustomizationId") + + // for testing + msoLogger.debug("volumeGroupId: " + volumeGroupId) + def testGroupId = execution.getVariable('test-volume-group-id') + if (testGroupId != null && testGroupId.trim() != '') { + msoLogger.debug("test volumeGroupId is present: " + testGroupId) + volumeGroupId = testGroupId + execution.setVariable("test-volume-group-name", "MSOTESTVOL101a-vSAMP12_base_vol_module-0") + } + msoLogger.debug("volumeGroupId to be used: " + volumeGroupId) + + // volume group parameters + + String volumeGroupParams = '' + StringBuilder sbParams = new StringBuilder() + Map<String, String> paramsMap = execution.getVariable("vfModuleInputParams") + for (Map.Entry<String, String> entry : paramsMap.entrySet()) { + String paramsXml + String paramName = entry.getKey(); + String paramValue = entry.getValue() + paramsXml = + """ <entry> + <key>${MsoUtils.xmlEscape(paramName)}</key> + <value>${MsoUtils.xmlEscape(paramValue)}</value> + </entry> + """ + sbParams.append(paramsXml) + } + + volumeGroupParams = sbParams.toString() + msoLogger.debug("volumeGroupParams: "+ volumeGroupParams) + + def backoutOnFailure = execution.getVariable(prefix+"backoutOnFailure") + msoLogger.debug("backoutOnFailure: "+ backoutOnFailure) + + def failIfExists = execution.getVariable("failIfExists") + if(failIfExists == null) { + failIfExists = 'true' + } + + String messageId = UUID.randomUUID() + msoLogger.debug("messageId to be used is generated: " + messageId) + + def notificationUrl = createCallbackURL(execution, "VNFAResponse", messageId) + def useQualifiedHostName = UrnPropertiesReader.getVariable("mso.use.qualified.host",execution) + if ('true'.equals(useQualifiedHostName)) { + notificationUrl = utils.getQualifiedHostNameForCallback(notificationUrl) + } + msoLogger.debug("CreateVfModuleVolume - notificationUrl: "+ notificationUrl) + + // build request + String vnfSubCreateWorkflowRequest = + """ + <createVolumeGroupRequest> + <cloudSiteId>${MsoUtils.xmlEscape(cloudSiteId)}</cloudSiteId> + <tenantId>${MsoUtils.xmlEscape(tenantId)}</tenantId> + <vnfId>${MsoUtils.xmlEscape(vnfId)}</vnfId> + <vnfName>${MsoUtils.xmlEscape(vnfName)}</vnfName> + <volumeGroupId>${MsoUtils.xmlEscape(volumeGroupId)}</volumeGroupId> + <volumeGroupName>${MsoUtils.xmlEscape(volumeGroupnName)}</volumeGroupName> + <vnfType>${MsoUtils.xmlEscape(vnfType)}</vnfType> + <vnfVersion>${MsoUtils.xmlEscape(vnfVersion)}</vnfVersion> + <vfModuleType>${MsoUtils.xmlEscape(vnfModuleType)}</vfModuleType> + <modelCustomizationUuid>${MsoUtils.xmlEscape(modelCustomizationId)}</modelCustomizationUuid> + <volumeGroupParams> + <entry> + <key>vnf_id</key> + <value>${MsoUtils.xmlEscape(vnfId)}</value> + </entry> + <entry> + <key>vnf_name</key> + <value>${MsoUtils.xmlEscape(vnfName)}</value> + </entry> + <entry> + <key>vf_module_id</key> + <value>${MsoUtils.xmlEscape(volumeGroupId)}</value> + </entry> + <entry> + <key>vf_module_name</key> + <value>${MsoUtils.xmlEscape(volumeGroupnName)}</value> + </entry> + ${volumeGroupParams} + </volumeGroupParams> + <skipAAI>true</skipAAI> + <backout>${MsoUtils.xmlEscape(backoutOnFailure)}</backout> + <failIfExists>${MsoUtils.xmlEscape(failIfExists)}</failIfExists> + <msoRequest> + <requestId>${MsoUtils.xmlEscape(requestId)}</requestId> + <serviceInstanceId>${MsoUtils.xmlEscape(serviceId)}</serviceInstanceId> + </msoRequest> + <messageId>${MsoUtils.xmlEscape(messageId)}</messageId> + <notificationUrl>${MsoUtils.xmlEscape(notificationUrl)}</notificationUrl> + </createVolumeGroupRequest> + """ + + String vnfSubCreateWorkflowRequestAsString = utils.formatXml(vnfSubCreateWorkflowRequest) + msoLogger.debug(vnfSubCreateWorkflowRequestAsString) + msoLogger.debug(vnfSubCreateWorkflowRequestAsString) + execution.setVariable(prefix+"createVnfARequest", vnfSubCreateWorkflowRequestAsString) + + // build rollback request for use later if needed + String vnfSubRollbackWorkflowRequest = buildRollbackVolumeGroupRequestXml(volumeGroupId, cloudSiteId, tenantId, requestId, serviceId, messageId, notificationUrl) + + msoLogger.debug("Sub Vnf flow rollback request: vnfSubRollbackWorkflowRequest " + "\n" + vnfSubRollbackWorkflowRequest) + + String vnfSubRollbackWorkflowRequestAsString = utils.formatXml(vnfSubRollbackWorkflowRequest) + execution.setVariable(prefix+"rollbackVnfARequest", vnfSubRollbackWorkflowRequestAsString) + } + + public String buildRollbackVolumeGroupRequestXml(volumeGroupId, cloudSiteId, tenantId, requestId, serviceId, messageId, notificationUrl) { + + def request = """ + <rollbackVolumeGroupRequest> + <volumeGroupRollback> + <volumeGroupId>${MsoUtils.xmlEscape(volumeGroupId)}</volumeGroupId> + <volumeGroupStackId>{{VOLUMEGROUPSTACKID}}</volumeGroupStackId> + <tenantId>${MsoUtils.xmlEscape(tenantId)}</tenantId> + <cloudSiteId>${MsoUtils.xmlEscape(cloudSiteId)}</cloudSiteId> + <volumeGroupCreated>true</volumeGroupCreated> + <msoRequest> + <requestId>${MsoUtils.xmlEscape(requestId)}</requestId> + <serviceInstanceId>${MsoUtils.xmlEscape(serviceId)}</serviceInstanceId> + </msoRequest> + <messageId>${MsoUtils.xmlEscape(messageId)}</messageId> + </volumeGroupRollback> + <skipAAI>true</skipAAI> + <notificationUrl>${MsoUtils.xmlEscape(notificationUrl)}</notificationUrl> + </rollbackVolumeGroupRequest> + """ + + return request + } + + public String updateRollbackVolumeGroupRequestXml(String rollabackRequest, String heatStackId) { + String newRequest = rollabackRequest.replace("{{VOLUMEGROUPSTACKID}}", heatStackId) + return newRequest + } + + /** + * Validate VNF adapter response + * @param execution + */ + public void validateVnfResponse(DelegateExecution execution, isDebugEnabled) { + def vnfSuccess = execution.getVariable('VNFREST_SuccessIndicator') + msoLogger.debug("vnfAdapterSuccessIndicator: "+ vnfSuccess) + if(vnfSuccess==true) { + String createVnfAResponse = execution.getVariable(prefix+"createVnfAResponse") + String heatStackID = utils.getNodeText(createVnfAResponse, "volumeGroupStackId") + String vnfRollbackRequest = execution.getVariable(prefix+"rollbackVnfARequest") + String updatedVnfRollbackRequest = updateRollbackVolumeGroupRequestXml(vnfRollbackRequest, heatStackID) + msoLogger.debug("vnfAdapter rollback request: "+ updatedVnfRollbackRequest) + RollbackData rollbackData = execution.getVariable("rollbackData") + rollbackData.put("DCVFMODULEVOL", "rollbackVnfARequest", updatedVnfRollbackRequest) + rollbackData.put("DCVFMODULEVOL", "isCreateVnfRollbackNeeded", "true") + } + } + + + /** + * Update voulume group in AAI + * @TODO: Can we re-use the create method?? + * @param execution + * @param isDebugEnabled + */ + public void callRESTUpdateCreatedVolGrpName(DelegateExecution execution, isDebugEnabled) { + + String requeryAAIVolGrpNameResponse = execution.getVariable(prefix+"queryAAIVolGrpNameResponse") + String volumeGroupId = utils.getNodeText(requeryAAIVolGrpNameResponse, "volume-group-id") + String modelCustomizationId = execution.getVariable("modelCustomizationId") + String cloudRegion = execution.getVariable("lcpCloudRegionId") + + AaiUtil aaiUtil = new AaiUtil(this) + String aaiEndpoint = aaiUtil.getCloudInfrastructureCloudRegionEndpoint(execution) + String updateAAIVolumeGroupUrlRequest = aaiEndpoint + '/' + cloudRegion + "/volume-groups/volume-group/" + UriUtils.encode(volumeGroupId, 'UTF-8') + + String namespace = aaiUtil.getNamespaceFromUri(aaiUtil.getCloudInfrastructureCloudRegionUri(execution)) + + msoLogger.debug("updateAAIVolumeGroupUrlRequest - " + updateAAIVolumeGroupUrlRequest) + + String createVnfAResponse = execution.getVariable(prefix+"createVnfAResponse") + def heatStackID = utils.getNodeText(createVnfAResponse, "volumeGroupStackId") + + execution.setVariable(prefix+"heatStackId", heatStackID) + + NetworkUtils networkUtils = new NetworkUtils() + String payload = networkUtils.updateCloudRegionVolumeRequest(requeryAAIVolGrpNameResponse, heatStackID, namespace, modelCustomizationId) + String payloadXml = utils.formatXml(payload) + + msoLogger.debug("Payload to Update Created VolumeGroupName - " + "\n" + payloadXml) + + APIResponse response = aaiUtil.executeAAIPutCall(execution, updateAAIVolumeGroupUrlRequest, payloadXml) + + String returnCode = response.getStatusCode() + String aaiResponseAsString = response.getResponseBodyAsString() + + msoLogger.debug("AAI create volume group return code: " + returnCode) + msoLogger.debug("AAI create volume group response: " + aaiResponseAsString) + + ExceptionUtil exceptionUtil = new ExceptionUtil() + + if (returnCode =='200') { + execution.setVariable(prefix+"updateCreatedAAIVolumeGrpNameResponse", aaiResponseAsString) + execution.setVariable(prefix+"isPONR", true) + } else { + execution.setVariable(prefix+"isErrorMessageException", true) + if (returnCode=='404') { + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Unable to update volume group in AAI. Response code: 404") + } else { + WorkflowException aWorkflowException = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) + msoLogger.debug(" AAI Adapter Query Failed. WorkflowException - " + "\n" + aWorkflowException) + throw new BpmnError("MSOWorkflowException") + } + } + } + + + /** + * Query AAI Generic VNF + * @param execution + * @param isDebugEnabled + */ + public void callRESTQueryAAIGenericVnf(DelegateExecution execution, isDebugEnabled) { + + def vnfId = execution.getVariable('vnfId') + + AaiUtil aaiUtil = new AaiUtil(this) + String aaiEndpoint = aaiUtil.getNetworkGenericVnfEndpoint(execution) + def String queryAAIRequest = aaiEndpoint + "/" + UriUtils.encode(vnfId, "UTF-8") + + msoLogger.debug("AAI query generic vnf request: " + queryAAIRequest) + + APIResponse response = aaiUtil.executeAAIGetCall(execution, queryAAIRequest) + + String returnCode = response.getStatusCode() + String aaiResponseAsString = response.getResponseBodyAsString() + + msoLogger.debug("AAI query generic vnf return code: " + returnCode) + msoLogger.debug("AAI query generic vnf response: " + aaiResponseAsString) + + ExceptionUtil exceptionUtil = new ExceptionUtil() + + if (returnCode=='200') { + msoLogger.debug('Generic vnf ' + vnfId + ' found in AAI.') + execution.setVariable(prefix+'AAIQueryGenericVfnResponse', aaiResponseAsString) + } else { + if (returnCode=='404') { + def message = 'Generic vnf ' + vnfId + ' was not found in AAI. Return code: 404.' + msoLogger.debug(message) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, message) + } else { + WorkflowException aWorkflowException = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) + throw new BpmnError("MSOWorkflowException") + } + } + } + +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVnf.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVnf.groovy new file mode 100644 index 0000000000..7fa8b4409b --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVnf.groovy @@ -0,0 +1,645 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts + +import static org.apache.commons.lang3.StringUtils.* + +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.onap.so.bpmn.common.scripts.AaiUtil +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.onap.so.bpmn.common.scripts.ExceptionUtil +import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.so.bpmn.common.scripts.SDNCAdapterUtils +import org.onap.so.bpmn.common.scripts.VidUtils +import org.onap.so.bpmn.core.RollbackData +import org.onap.so.bpmn.core.UrnPropertiesReader +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.bpmn.core.domain.VnfResource +import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.logger.MessageEnum +import org.onap.so.logger.MsoLogger +import org.onap.so.client.aai.AAIObjectType; +import org.onap.so.client.aai.AAIResourcesClient +import org.onap.so.client.aai.entities.AAIResultWrapper +import org.onap.so.client.aai.entities.uri.AAIResourceUri +import org.onap.so.client.aai.entities.uri.AAIUriFactory; +import org.springframework.web.util.UriUtils +import org.json.JSONObject + + +/** + * This class supports the DoCreateVnf building block subflow + * with the creation of a generic vnf for + * infrastructure. + * + */ +class DoCreateVnf extends AbstractServiceTaskProcessor { + + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoCreateVnf.class); + String Prefix="DoCVNF_" + ExceptionUtil exceptionUtil = new ExceptionUtil() + JsonUtils jsonUtil = new JsonUtils() + VidUtils vidUtils = new VidUtils(this) + SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this) + + /** + * This method gets and validates the incoming + * request. + * + * @param - execution + * + */ + public void preProcessRequest(DelegateExecution execution) { + def isDebugEnabled = execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + msoLogger.debug("STARTED DoCreateVnf PreProcessRequest Process") + + // DISABLE SDNC INTERACTION FOR NOW + execution.setVariable("SDNCInteractionEnabled", false) + + + /*******************/ + try{ + // Get Variables + + def rollbackData = execution.getVariable("rollbackData") + if (rollbackData == null) { + rollbackData = new RollbackData() + } + + String vnfModelInfo = execution.getVariable("vnfModelInfo") + String serviceModelInfo = execution.getVariable("serviceModelInfo") + + String requestId = execution.getVariable("msoRequestId") + execution.setVariable("DoCVNF_requestId", requestId) + execution.setVariable("mso-request-id", requestId) + msoLogger.debug("Incoming Request Id is: " + requestId) + + String serviceInstanceId = execution.getVariable("serviceInstanceId") + execution.setVariable("DoCVNF_serviceInstanceId", serviceInstanceId) + rollbackData.put("VNF", "serviceInstanceId", serviceInstanceId) + msoLogger.debug("Incoming Service Instance Id is: " + serviceInstanceId) + + String vnfType = execution.getVariable("vnfType") + execution.setVariable("DoCVNF_vnfType", vnfType) + msoLogger.debug("Incoming Vnf Type is: " + vnfType) + + String vnfName = execution.getVariable("vnfName") + if (vnfName.equals("") || vnfName.equals("null")) { + vnfName = null + } + execution.setVariable("DoCVNF_vnfName", vnfName) + msoLogger.debug("Incoming Vnf Name is: " + vnfName) + + String serviceId = execution.getVariable("productFamilyId") + execution.setVariable("DoCVNF_serviceId", serviceId) + msoLogger.debug("Incoming Service Id is: " + serviceId) + + String source = "VID" + execution.setVariable("DoCVNF_source", source) + rollbackData.put("VNF", "source", source) + msoLogger.debug("Incoming Source is: " + source) + + String suppressRollback = execution.getVariable("disableRollback") + execution.setVariable("DoCVNF_suppressRollback", suppressRollback) + msoLogger.debug("Incoming Suppress Rollback is: " + suppressRollback) + + String modelInvariantId = jsonUtil.getJsonValue(vnfModelInfo, "modelInvariantUuid") + execution.setVariable("DoCVNF_modelInvariantId", modelInvariantId) + msoLogger.debug("Incoming Invariant Id is: " + modelInvariantId) + + String modelVersionId = jsonUtil.getJsonValue(vnfModelInfo, "modelUuid") + if (modelVersionId == null) { + modelVersionId = "" + } + execution.setVariable("DoCVNF_modelVersionId", modelVersionId) + msoLogger.debug("Incoming Version Id is: " + modelVersionId) + + String modelVersion = jsonUtil.getJsonValue(vnfModelInfo, "modelVersion") + execution.setVariable("DoCVNF_modelVersion", modelVersion) + msoLogger.debug("Incoming Model Version is: " + modelVersion) + + String modelName = jsonUtil.getJsonValue(vnfModelInfo, "modelName") + execution.setVariable("DoCVNF_modelName", modelName) + msoLogger.debug("Incoming Model Name is: " + modelName) + + String modelCustomizationId = jsonUtil.getJsonValue(vnfModelInfo, "modelCustomizationUuid") + if (modelCustomizationId == null) { + modelCustomizationId = "" + } + execution.setVariable("DoCVNF_modelCustomizationId", modelCustomizationId) + msoLogger.debug("Incoming Model Customization Id is: " + modelCustomizationId) + + String cloudSiteId = execution.getVariable("lcpCloudRegionId") + execution.setVariable("DoCVNF_cloudSiteId", cloudSiteId) + rollbackData.put("VNF", "cloudSiteId", cloudSiteId) + msoLogger.debug("Incoming Cloud Site Id is: " + cloudSiteId) + + String tenantId = execution.getVariable("tenantId") + execution.setVariable("DoCVNF_tenantId", tenantId) + rollbackData.put("VNF", "tenantId", tenantId) + msoLogger.debug("Incoming Tenant Id is: " + tenantId) + + String globalSubscriberId = execution.getVariable("globalSubscriberId") + if (globalSubscriberId == null) { + globalSubscriberId = "" + } + execution.setVariable("DoCVNF_globalSubscriberId", globalSubscriberId) + msoLogger.debug("Incoming Global Subscriber Id is: " + globalSubscriberId) + + String sdncVersion = execution.getVariable("sdncVersion") + if (sdncVersion == null) { + sdncVersion = "1702" + } + execution.setVariable("DoCVNF_sdncVersion", sdncVersion) + msoLogger.debug("Incoming Sdnc Version is: " + sdncVersion) + + //For Completion Handler & Fallout Handler + String requestInfo = + """<request-info xmlns="http://org.onap/so/infra/vnf-request/v1"> + <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> + <action>CREATE</action> + <source>${MsoUtils.xmlEscape(source)}</source> + </request-info>""" + + execution.setVariable("DoCVNF_requestInfo", requestInfo) + //TODO: Orch Status - TBD, will come from SDN-C Response in 1702 + String orchStatus = "Created" + execution.setVariable("DoCVNF_orchStatus", orchStatus) + + //TODO: Equipment Role - Should come from SDN-C Response in 1702 + String equipmentRole = " " + execution.setVariable("DoCVNF_equipmentRole", equipmentRole) + String vnfId = execution.getVariable("testVnfId") // for junits + if(isBlank(vnfId)){ + vnfId = execution.getVariable("vnfId") + if (isBlank(vnfId)) { + vnfId = UUID.randomUUID().toString() + msoLogger.debug("Generated Vnf Id is: " + vnfId) + } + } + execution.setVariable("DoCVNF_vnfId", vnfId) + + // Setting for Sub Flow Calls + execution.setVariable("DoCVNF_type", "generic-vnf") + execution.setVariable("GENGS_type", "service-instance") + + String sdncCallbackUrl = (String) UrnPropertiesReader.getVariable("mso.workflow.sdncadapter.callback",execution) + if (sdncCallbackUrl == null || sdncCallbackUrl.trim().isEmpty()) { + def msg = 'Required variable \'mso.workflow.sdncadapter.callback\' is missing' + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, msg, "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError); + exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) + } + execution.setVariable("DoCVNF_sdncCallbackUrl", sdncCallbackUrl) + rollbackData.put("VNF", "sdncCallbackUrl", sdncCallbackUrl) + msoLogger.debug("SDNC Callback URL is: " + sdncCallbackUrl) + + VnfResource vnfResource = (VnfResource) execution.getVariable((String)"vnfResourceDecomposition") + String nfRole = vnfResource.getNfRole() + + execution.setVariable("DoCVNF_nfRole", nfRole) + msoLogger.debug("NF Role is: " + nfRole) + + String nfNamingCode = vnfResource.getNfNamingCode() + execution.setVariable("DoCVNF_nfNamingCode", nfNamingCode) + msoLogger.debug("NF Naming Code is: " + nfNamingCode) + + String nfType = vnfResource.getNfType() + execution.setVariable("DoCVNF_nfType", nfType) + msoLogger.debug("NF Type is: " + nfType) + + String nfFunction = vnfResource.getNfFunction() + execution.setVariable("DoCVNF_nfFunction", nfFunction) + msoLogger.debug("NF Function is: " + nfFunction) + + rollbackData.put("VNF", "rollbackSDNCAssign", "false") + rollbackData.put("VNF", "rollbackSDNCActivate", "false") + rollbackData.put("VNF", "rollbackVnfCreate", "false") + + execution.setVariable("rollbackData", rollbackData) + + }catch(BpmnError b){ + msoLogger.debug("Rethrowing MSOWorkflowException") + throw b + }catch(Exception e){ + msoLogger.debug(" Error Occured in DoCreateVnf PreProcessRequest method!" + e.getMessage()) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in DoCreateVnf PreProcessRequest") + + } + msoLogger.trace("COMPLETED DoCreateVnf PreProcessRequest Process") + } + + /** + * Gets the service instance from aai + */ + public void getServiceInstance(DelegateExecution execution) { + try { + String serviceInstanceId = execution.getVariable('DoCVNF_serviceInstanceId') + + AAIResourcesClient resourceClient = new AAIResourcesClient() + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, serviceInstanceId) + + if(resourceClient.exists(uri)){ + execution.setVariable("GENGS_siResourceLink", uri.build().toString()) + + }else{ + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Service instance was not found in aai") + } + + }catch(BpmnError e) { + throw e; + }catch(Exception ex) { + String msg = "Exception in getServiceInstance. " + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + } + + private Object getVariableEnforced(DelegateExecution execution, String name){ + Object enforced = execution.getVariable(name) + if(!enforced){ + return ""; + } + return enforced; + } + + public void createGenericVnf (DelegateExecution execution) { + execution.setVariable("prefix",Prefix) + msoLogger.trace("STARTED DoCreateVnf CreateGenericVnf Process") + try { + //Get Vnf Info + String vnfId = getVariableEnforced(execution, "DoCVNF_vnfId") + String vnfName = getVariableEnforced(execution, "DoCVNF_vnfName") + if (vnfName == null) { + vnfName = "sdncGenerated" + msoLogger.debug("Sending a dummy VNF name to AAI - the name will be generated by SDNC: " + vnfName) + } + String vnfType = getVariableEnforced(execution, "DoCVNF_vnfType") + String serviceId = getVariableEnforced(execution, "DoCVNF_serviceId") + String orchStatus = getVariableEnforced(execution, "DoCVNF_orchStatus") + String modelInvariantId = getVariableEnforced(execution, "DoCVNF_modelInvariantId") + String modelVersionId = getVariableEnforced(execution, "DoCVNF_modelVersionId") + String modelCustomizationId = getVariableEnforced(execution, "DoCVNF_modelCustomizationId") + String equipmentRole = getVariableEnforced(execution, "DoCVNF_equipmentRole") + String nfType = getVariableEnforced(execution, "DoCVNF_nfType") + String nfRole = getVariableEnforced(execution, "DoCVNF_nfRole") + String nfFunction = getVariableEnforced(execution, "DoCVNF_nfFunction") + String nfNamingCode = getVariableEnforced(execution, "DoCVNF_nfNamingCode") + + //Get Service Instance Info + String serviceInstanceId = getVariableEnforced(execution, "DoCVNF_serviceInstanceId") + String siRelatedLink = getVariableEnforced(execution, "GENGS_siResourceLink") + + int custStart = siRelatedLink.indexOf("customer/") + int custEnd = siRelatedLink.indexOf("/service-subscriptions") + String globalCustId = siRelatedLink.substring(custStart + 9, custEnd) + int serviceStart = siRelatedLink.indexOf("service-subscription/") + int serviceEnd = siRelatedLink.indexOf("/service-instances/") + String serviceType = siRelatedLink.substring(serviceStart + 21, serviceEnd) + + Map<String, String> payload = new LinkedHashMap<>(); + payload.put("vnf-id", vnfId); + payload.put("vnf-name", vnfName); + payload.put("service-id", serviceId); + payload.put("vnf-type", vnfType); + payload.put("prov-status", "PREPROV"); + payload.put("orchestration-status", orchStatus); + payload.put("model-invariant-id", modelInvariantId); + payload.put("model-version-id", modelVersionId); + payload.put("model-customization-id", modelCustomizationId); + payload.put("nf-type", nfType); + payload.put("nf-role", nfRole); + payload.put("nf-function", nfFunction); + payload.put("nf-naming-code", nfNamingCode); + + AAIResourcesClient resourceClient = new AAIResourcesClient(); + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId) + resourceClient.create(uri, payload) + + AAIResourceUri siUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, globalCustId, serviceType, serviceInstanceId) + resourceClient.connect(uri, siUri) + + }catch(Exception ex) { + msoLogger.debug("Error Occured in DoCreateVnf CreateGenericVnf Process " + ex.getMessage()) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in DoCreateVnf CreateGenericVnf Process") + } + msoLogger.trace("COMPLETED DoCreateVnf CreateGenericVnf Process") + } + + public void postProcessCreateGenericVnf (DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + + msoLogger.trace("STARTED DoCreateVnf PostProcessCreateGenericVnf Process") + try { + //Get Vnf Info + String vnfId = execution.getVariable("DoCVNF_vnfId") + def rollbackData = execution.getVariable("rollbackData") + rollbackData.put("VNF", "vnfId", vnfId) + rollbackData.put("VNF", "rollbackVnfCreate", "true") + execution.setVariable("rollbackData", rollbackData) + }catch(Exception ex) { + msoLogger.debug("Error Occured in DoCreateVnf PostProcessCreateGenericVnf Process " + ex.getMessage()) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in DoCreateVnf PostProcessCreateGenericVnf Process") + } + msoLogger.trace("COMPLETED DoCreateVnf PostProcessCreateGenericVnf Process") + } + + + public void preProcessSDNCAssignRequest(DelegateExecution execution){ + def isDebugLogEnabled = execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix", Prefix) + msoLogger.trace("STARTED preProcessSDNCAssignRequest") + def vnfId = execution.getVariable("DoCVNF_vnfId") + def serviceInstanceId = execution.getVariable("DoCVNF_serviceInstanceId") + msoLogger.debug("NEW VNF ID: " + vnfId) + + try{ + //Build SDNC Request + + String assignSDNCRequest = buildSDNCRequest(execution, serviceInstanceId, "assign") + + assignSDNCRequest = utils.formatXml(assignSDNCRequest) + execution.setVariable("DoCVNF_assignSDNCRequest", assignSDNCRequest) + msoLogger.debug("Outgoing AssignSDNCRequest is: \n" + assignSDNCRequest) + + }catch(Exception e){ + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception Occured Processing preProcessSDNCAssignRequest" , "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e) + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during preProcessSDNCAssignRequest Method:\n" + e.getMessage()) + } + msoLogger.trace("COMPLETED preProcessSDNCAssignRequest") + } + + public void preProcessSDNCActivateRequest(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.preProcessSDNCActivateRequest(' + + 'execution=' + execution.getId() + + ')' + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + msoLogger.trace('Entered ' + method) + execution.setVariable("prefix", Prefix) + msoLogger.trace("STARTED preProcessSDNCActivateRequest Process") + try{ + String vnfId = execution.getVariable("DoCVNF_vnfId") + String serviceInstanceId = execution.getVariable("DoCVNF_serviceInstanceId") + + String activateSDNCRequest = buildSDNCRequest(execution, serviceInstanceId, "activate") + + execution.setVariable("DoCVNF_activateSDNCRequest", activateSDNCRequest) + msoLogger.debug("Outgoing CommitSDNCRequest is: \n" + activateSDNCRequest) + + }catch(Exception e){ + msoLogger.debug("Exception Occured Processing preProcessSDNCActivateRequest. Exception is:\n" + e) + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during preProcessSDNCActivateRequest Method:\n" + e.getMessage()) + } + msoLogger.trace("COMPLETED preProcessSDNCActivateRequest Process") + } + + public String buildSDNCRequest(DelegateExecution execution, String svcInstId, String action){ + + String uuid = execution.getVariable('testReqId') // for junits + if(uuid==null){ + uuid = execution.getVariable("DoCVNF_requestId") + "-" + System.currentTimeMillis() + } + def callbackURL = execution.getVariable("DoCVNF_sdncCallbackUrl") + def requestId = execution.getVariable("DoCVNF_requestId") + def serviceId = execution.getVariable("DoCVNF_serviceId") + def vnfType = execution.getVariable("DoCVNF_vnfType") + def vnfName = execution.getVariable("DoCVNF_vnfName") + // Only send vnfName to SDNC if it is not null, otherwise it will get generated by SDNC on Assign + String vnfNameString = "" + if (vnfName != null) { + vnfNameString = """<vnf-name>${MsoUtils.xmlEscape(vnfName)}</vnf-name>""" + } + def tenantId = execution.getVariable("DoCVNF_tenantId") + def source = execution.getVariable("DoCVNF_source") + def vnfId = execution.getVariable("DoCVNF_vnfId") + def cloudSiteId = execution.getVariable("DoCVNF_cloudSiteId") + def modelCustomizationId = execution.getVariable("DoCVNF_modelCustomizationId") + def serviceModelInfo = execution.getVariable("serviceModelInfo") + def vnfModelInfo = execution.getVariable("vnfModelInfo") + String serviceEcompModelInformation = sdncAdapterUtils.modelInfoToEcompModelInformation(serviceModelInfo) + String vnfEcompModelInformation = sdncAdapterUtils.modelInfoToEcompModelInformation(vnfModelInfo) + def globalSubscriberId = execution.getVariable("DoCVNF_globalSubscriberId") + def sdncVersion = execution.getVariable("DoCVNF_sdncVersion") + + String sdncVNFParamsXml = "" + + if(execution.getVariable("DoCVNF_vnfParamsExistFlag") == true){ + sdncVNFParamsXml = buildSDNCParamsXml(execution) + }else{ + sdncVNFParamsXml = "" + } + + String sdncRequest = + """<sdncadapterworkflow:SDNCAdapterWorkflowRequest xmlns:ns5="http://org.onap/so/request/types/v1" + xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1" + xmlns:sdncadapter="http://org.onap/workflow/sdnc/adapter/schema/v1"> + <sdncadapter:RequestHeader> + <sdncadapter:RequestId>${MsoUtils.xmlEscape(uuid)}</sdncadapter:RequestId> + <sdncadapter:SvcInstanceId>${MsoUtils.xmlEscape(svcInstId)}</sdncadapter:SvcInstanceId> + <sdncadapter:SvcAction>${MsoUtils.xmlEscape(action)}</sdncadapter:SvcAction> + <sdncadapter:SvcOperation>vnf-topology-operation</sdncadapter:SvcOperation> + <sdncadapter:CallbackUrl>${MsoUtils.xmlEscape(callbackURL)}</sdncadapter:CallbackUrl> + <sdncadapter:MsoAction>generic-resource</sdncadapter:MsoAction> + </sdncadapter:RequestHeader> + <sdncadapterworkflow:SDNCRequestData> + <request-information> + <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> + <request-action>CreateVnfInstance</request-action> + <source>${MsoUtils.xmlEscape(source)}</source> + <notification-url/> + <order-number/> + <order-version/> + </request-information> + <service-information> + <service-id>${MsoUtils.xmlEscape(serviceId)}</service-id> + <subscription-service-type>${MsoUtils.xmlEscape(serviceId)}</subscription-service-type> + ${serviceEcompModelInformation} + <service-instance-id>${MsoUtils.xmlEscape(svcInstId)}</service-instance-id> + <global-customer-id>${MsoUtils.xmlEscape(globalSubscriberId)}</global-customer-id> + </service-information> + <vnf-information> + <vnf-id>${MsoUtils.xmlEscape(vnfId)}</vnf-id> + <vnf-type>${MsoUtils.xmlEscape(vnfType)}</vnf-type> + ${vnfEcompModelInformation} + </vnf-information> + <vnf-request-input> + ${vnfNameString} + <tenant>${MsoUtils.xmlEscape(tenantId)}</tenant> + <aic-cloud-region>${MsoUtils.xmlEscape(cloudSiteId)}</aic-cloud-region> + ${sdncVNFParamsXml} + </vnf-request-input> + </sdncadapterworkflow:SDNCRequestData> + </sdncadapterworkflow:SDNCAdapterWorkflowRequest>""" + + msoLogger.debug("sdncRequest: " + sdncRequest) + return sdncRequest + } + + public void validateSDNCResponse(DelegateExecution execution, String response, String method){ + def isDebugLogEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + msoLogger.debug("STARTED ValidateSDNCResponse Process") + + WorkflowException workflowException = execution.getVariable("WorkflowException") + boolean successIndicator = execution.getVariable("SDNCA_SuccessIndicator") + + msoLogger.debug("workflowException: " + workflowException) + + SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this) + sdncAdapterUtils.validateSDNCResponse(execution, response, workflowException, successIndicator) + + msoLogger.debug("SDNCResponse: " + response) + + String sdncResponse = response + if(execution.getVariable(Prefix + 'sdncResponseSuccess') == true){ + msoLogger.debug("Received a Good Response from SDNC Adapter for " + method + " SDNC Call. Response is: \n" + sdncResponse) + if(method.equals("get")){ + String topologyGetResponse = execution.getVariable("DoCVNF_getSDNCAdapterResponse") + String data = utils.getNodeXml(topologyGetResponse, "response-data") + msoLogger.debug("topologyGetResponseData: " + data) + String vnfName = utils.getNodeText(data, "vnf-name") + msoLogger.debug("vnfName received from SDNC: " + vnfName) + execution.setVariable("vnfName", vnfName) + execution.setVariable("DoCVNF_vnfName", vnfName) + } + def rollbackData = execution.getVariable("rollbackData") + if (method.equals("assign")) { + rollbackData.put("VNF", "rollbackSDNCAssign", "true") + } + else if (method.equals("activate")) { + rollbackData.put("VNF", "rollbackSDNCActivate", "true") + } + execution.setVariable("rollbackData", rollbackData) + + + }else{ + msoLogger.debug("Received a BAD Response from SDNC Adapter for " + method + " SDNC Call.") + throw new BpmnError("MSOWorkflowException") + } + msoLogger.debug("COMPLETED ValidateSDNCResponse Process") + } + + public void preProcessSDNCGetRequest(DelegateExecution execution){ + def isDebugLogEnabled = execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix", Prefix) + msoLogger.trace("STARTED preProcessSDNCGetRequest Process") + try{ + def serviceInstanceId = execution.getVariable('DoCVNF_serviceInstanceId') + + String uuid = execution.getVariable('testReqId') // for junits + if(uuid==null){ + uuid = execution.getVariable("mso-request-id") + "-" + System.currentTimeMillis() + } + + def callbackUrl = execution.getVariable("DoCVFM_sdncCallbackUrl") + msoLogger.debug("callbackUrl:" + callbackUrl) + + def vnfId = execution.getVariable('DCVFM_vnfId') + + def svcInstId = "" + if (serviceInstanceId == null || serviceInstanceId.isEmpty()) { + svcInstId = vnfId + } + else { + svcInstId = serviceInstanceId + } + // serviceOperation will be retrieved from "object-path" element + // in SDNC Assign Response for VNF + String response = execution.getVariable("DoCVNF_assignSDNCAdapterResponse") + msoLogger.debug("DoCVNF_assignSDNCAdapterResponse is: \n" + response) + + String serviceOperation = "" + + String data = utils.getNodeXml(response, "response-data") + msoLogger.debug("responseData: " + data) + serviceOperation = utils.getNodeText(data, "object-path") + msoLogger.debug("VNF with sdncVersion of 1707 or later - service operation: " + serviceOperation) + + + //!!!! TEMPORARY WORKAROUND FOR SDNC REPLICATION ISSUE + sleep(5000) + + String SDNCGetRequest = + """<sdncadapterworkflow:SDNCAdapterWorkflowRequest xmlns:ns5="http://org.onap/so/request/types/v1" + xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1" + xmlns:sdncadapter="http://org.onap/workflow/sdnc/adapter/schema/v1"> + <sdncadapter:RequestHeader> + <sdncadapter:RequestId>${MsoUtils.xmlEscape(uuid)}</sdncadapter:RequestId> + <sdncadapter:SvcInstanceId>${MsoUtils.xmlEscape(svcInstId)}</sdncadapter:SvcInstanceId> + <sdncadapter:SvcAction>query</sdncadapter:SvcAction> + <sdncadapter:SvcOperation>${MsoUtils.xmlEscape(serviceOperation)}</sdncadapter:SvcOperation> + <sdncadapter:CallbackUrl>${MsoUtils.xmlEscape(callbackUrl)}</sdncadapter:CallbackUrl> + <sdncadapter:MsoAction>vfmodule</sdncadapter:MsoAction> + </sdncadapter:RequestHeader> + <sdncadapterworkflow:SDNCRequestData></sdncadapterworkflow:SDNCRequestData> + </sdncadapterworkflow:SDNCAdapterWorkflowRequest>""" + + + execution.setVariable("DoCVNF_getSDNCRequest", SDNCGetRequest) + msoLogger.debug("Outgoing GetSDNCRequest is: \n" + SDNCGetRequest) + + }catch(Exception e){ + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception Occurred Processing preProcessSDNCGetRequest. ", "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during prepareProvision Method:\n" + e.getMessage()) + } + msoLogger.trace("COMPLETED preProcessSDNCGetRequest Process") + } + + /** + * Prepare a Request for invoking the UpdateAAIGenericVnf subflow. + * + * @param execution The flow's execution instance. + */ + public void prepUpdateAAIGenericVnf(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.prepUpdateAAIGenericVnf(' + + 'execution=' + execution.getId() + + ')' + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + msoLogger.trace('Entered ' + method) + + try { + def vnfId = execution.getVariable('DoCVNF_vnfId') + msoLogger.debug("VNF ID: " + vnfId) + + String updateAAIGenericVnfRequest = """ + <UpdateAAIGenericVnfRequest> + <vnf-id>${MsoUtils.xmlEscape(vnfId)}</vnf-id> + <orchestration-status>Active</orchestration-status> + </UpdateAAIGenericVnfRequest> + """ + updateAAIGenericVnfRequest = utils.formatXml(updateAAIGenericVnfRequest) + execution.setVariable('DoCVNF_updateAAIGenericVnfRequest', updateAAIGenericVnfRequest) + msoLogger.debug('Request for UpdateAAIGenericVnf:\n' + updateAAIGenericVnfRequest) + + + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Caught exception in " + method , "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in prepUpdateAAIGenericVnf(): ' + e.getMessage()) + } + } + + +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVnfAndModules.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVnfAndModules.groovy new file mode 100644 index 0000000000..d3dbd9107e --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVnfAndModules.groovy @@ -0,0 +1,467 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts + +import java.util.UUID; + +import java.util.List + +import org.json.JSONObject; +import org.json.JSONArray; +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.onap.so.bpmn.common.scripts.CatalogDbUtils +import org.onap.so.bpmn.common.scripts.ExceptionUtil +import org.onap.so.bpmn.common.scripts.VidUtils +import org.onap.so.bpmn.core.RollbackData +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.bpmn.core.domain.ModelInfo +import org.onap.so.bpmn.core.domain.ModuleResource +import org.onap.so.bpmn.core.domain.ServiceDecomposition +import org.onap.so.bpmn.core.domain.VnfResource +import org.onap.so.bpmn.core.json.DecomposeJsonUtil +import org.onap.so.bpmn.core.json.JsonUtils +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution; +import org.onap.so.bpmn.infrastructure.aai.groovyflows.AAICreateResources; +import org.onap.so.logger.MsoLogger +import org.onap.so.logger.MessageEnum + +import static org.apache.commons.lang3.StringUtils.*; + + + +/** +* This class supports the macro VID Flow +* with the creation of a generic vnf and related VF modules. +*/ +class DoCreateVnfAndModules extends AbstractServiceTaskProcessor { + + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoCreateVnfAndModules.class); + String Prefix="DCVAM_" + ExceptionUtil exceptionUtil = new ExceptionUtil() + JsonUtils jsonUtil = new JsonUtils() + VidUtils vidUtils = new VidUtils(this) + CatalogDbUtils cutils = new CatalogDbUtils() + + /** + * This method gets and validates the incoming + * request. + * + * @param - execution + */ + public void preProcessRequest(DelegateExecution execution) { + + execution.setVariable("prefix",Prefix) + msoLogger.trace("STARTED DoCreateVnfAndModules PreProcessRequest Process") + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + + setBasicDBAuthHeader(execution, isDebugLogEnabled) + try{ + // Get Variables + + ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition") + + String vnfModelInfo = execution.getVariable("vnfModelInfo") + + String requestId = execution.getVariable("msoRequestId") + execution.setVariable("requestId", requestId) + execution.setVariable("mso-request-id", requestId) + msoLogger.debug("Incoming Request Id is: " + requestId) + + String serviceInstanceId = execution.getVariable("serviceInstanceId") + msoLogger.debug("Incoming Service Instance Id is: " + serviceInstanceId) + + String vnfName = execution.getVariable("vnfName") + execution.setVariable("CREVI_vnfName", vnfName) + msoLogger.debug("Incoming Vnf Name is: " + vnfName) + + String productFamilyId = execution.getVariable("productFamilyId") + msoLogger.debug("Incoming Product Family Id is: " + productFamilyId) + + String source = "VID" + execution.setVariable("source", source) + msoLogger.debug("Incoming Source is: " + source) + + String lcpCloudRegionId = execution.getVariable("lcpCloudRegionId") + msoLogger.debug("Incoming LCP Cloud Region Id is: " + lcpCloudRegionId) + + String tenantId = execution.getVariable("tenantId") + msoLogger.debug("Incoming Tenant Id is: " + tenantId) + + String disableRollback = execution.getVariable("disableRollback") + msoLogger.debug("Incoming Disable Rollback is: " + disableRollback) + + String asdcServiceModelVersion = execution.getVariable("asdcServiceModelVersion") + msoLogger.debug("Incoming asdcServiceModelVersion: " + asdcServiceModelVersion) + + String vnfId = execution.getVariable("testVnfId") // for junits + if(isBlank(vnfId)){ + vnfId = execution.getVariable("vnfId") + if (isBlank(vnfId)) { + vnfId = UUID.randomUUID().toString() + msoLogger.debug("Generated Vnf Id is: " + vnfId) + } + } + execution.setVariable("vnfId", vnfId) + + // Set aLaCarte to false + execution.setVariable("aLaCarte", false) + + def rollbackData = execution.getVariable("rollbackData") + if (rollbackData == null) { + rollbackData = new RollbackData() + } + + def isTest = execution.getVariable("isTest") + + if (isTest == null || isTest == false) { + execution.setVariable("isBaseVfModule", "true") + } + execution.setVariable("numOfCreatedAddOnModules", 0) + + rollbackData.put("VNFANDMODULES", "numOfCreatedAddOnModules", "0") + execution.setVariable("rollbackData", rollbackData) + + sleep (20000) + + + }catch(BpmnError b){ + msoLogger.debug("Rethrowing MSOWorkflowException") + throw b + }catch(Exception e){ + msoLogger.debug(" Error Occured in DoCreateVnfAndModules PreProcessRequest method!" + e.getMessage()) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in DoCreateVnf PreProcessRequest") + + } + msoLogger.trace("COMPLETED DoCreateVnfAndModules PreProcessRequest Process") + } + + + public void queryCatalogDB (DelegateExecution execution) { + + execution.setVariable("prefix",Prefix) + + msoLogger.trace("STARTED DoCreateVnfAndModules QueryCatalogDB Process") + try { + VnfResource vnf = null + ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition") + // if serviceDecomposition is specified, get info from serviceDecomposition + if (serviceDecomposition != null) { + msoLogger.debug("Getting Catalog DB data from ServiceDecomposition object: " + serviceDecomposition.toJsonString()) + List<VnfResource> vnfs = serviceDecomposition.getVnfResources() + msoLogger.debug("Read vnfs") + if (vnfs == null) { + msoLogger.debug("Error - vnfs are empty in serviceDecomposition object") + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in DoCreateVnf queryCatalogDB, vnfs are empty") + } + vnf = vnfs[0] + String serviceModelName = serviceDecomposition.getModelInfo().getModelName() + vnf.constructVnfType(serviceModelName) + String vnfType = vnf.getVnfType() + msoLogger.debug("Incoming Vnf Type is: " + vnfType) + execution.setVariable("vnfType", vnfType) + } + else { + //Get Vnf Info + String vnfModelInfo = execution.getVariable("vnfModelInfo") + msoLogger.debug("vnfModelInfo: " + vnfModelInfo) + String vnfModelCustomizationUuid = jsonUtil.getJsonValueForKey(vnfModelInfo, "modelCustomizationUuid") + if (vnfModelCustomizationUuid == null) { + vnfModelCustomizationUuid = "" + } + msoLogger.debug("querying Catalog DB by vnfModelCustomizationUuid: " + vnfModelCustomizationUuid) + + JSONArray vnfs = cutils.getAllVnfsByVnfModelCustomizationUuid(execution, + vnfModelCustomizationUuid) + msoLogger.debug("obtained VNF list") + // Only one match here + JSONObject vnfObject = vnfs[0] + vnf = DecomposeJsonUtil.jsonToVnfResource(vnfObject.toString()) + } + msoLogger.debug("Read vnfResource") + if (vnf == null) { + msoLogger.debug("Error - vnf is empty in serviceDecomposition object") + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in DoCreateVnf queryCatalogDB, vnf is null") + } + execution.setVariable("vnfResourceDecomposition", vnf) + + List<ModuleResource> vfModules = vnf.getAllVfModuleObjects() + msoLogger.debug("Read vfModules") + if (vfModules == null) { + msoLogger.debug("Error - vfModules are empty in serviceDecomposition object") + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in DoCreateVnf queryCatalogDB, vf modules are empty") + } + + ModuleResource baseVfModule = null + + for (int i = 0; i < vfModules.size; i++) { + msoLogger.debug("handling VF Module ") + ModuleResource vfModule = vfModules[i] + boolean isBase = vfModule.getIsBase() + if (isBase) { + ModelInfo baseVfModuleModelInfoObject = vfModule.getModelInfo() + String baseVfModuleModelInfoWithRoot = baseVfModuleModelInfoObject.toString() + String baseVfModuleModelInfo = jsonUtil.getJsonValue(baseVfModuleModelInfoWithRoot, "modelInfo") + execution.setVariable("baseVfModuleModelInfo", baseVfModuleModelInfo) + String baseVfModuleLabel = vfModule.getVfModuleLabel() + execution.setVariable("baseVfModuleLabel", baseVfModuleLabel) + String basePersonaModelId = baseVfModuleModelInfoObject.getModelInvariantUuid() + execution.setVariable("basePersonaModelId", basePersonaModelId) + baseVfModule = vfModule + break + } + + } + + List<ModuleResource>addOnModules = vfModules - baseVfModule + + int addOnModulesToDeploy = 0 + if (addOnModules != null) { + addOnModulesToDeploy = addOnModules.size + } + + + execution.setVariable("addOnModules", addOnModules) + execution.setVariable("addOnModulesToDeploy", addOnModulesToDeploy) + execution.setVariable("addOnModulesDeployed", 0) + + }catch(Exception ex) { + msoLogger.debug("Error Occured in DoCreateVnfAndModules QueryCatalogDB Process " + ex.getMessage()) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in DoCreateVnfAndModules QueryCatalogDB Process") + } + + // Generate vfModuleId for base VF Module + def baseVfModuleId = UUID.randomUUID().toString() + execution.setVariable("baseVfModuleId", baseVfModuleId) + // For JUnits + String requestId = execution.getVariable("requestId") + if (requestId.equals("testRequestId123")) { + execution.setVariable("vnfId", "skask") + } + + msoLogger.trace("COMPLETED DoCreateVnfAndModules QueryCatalogDB Process") + } + + public void preProcessAddOnModule(DelegateExecution execution){ + + execution.setVariable("prefix", Prefix) + msoLogger.debug("STARTED preProcessAddOnModule") + + try { + List<ModuleResource>addOnModules = execution.getVariable("addOnModules") + int addOnIndex = (int) execution.getVariable("addOnModulesDeployed") + + ModuleResource addOnModule = addOnModules[addOnIndex] + + msoLogger.debug("Got addon module") + + def newVfModuleId = UUID.randomUUID().toString() + execution.setVariable("addOnVfModuleId", newVfModuleId) + execution.setVariable("isBaseVfModule", "false") + + execution.setVariable("instancesOfThisModuleDeployed", 0) + + ModelInfo addOnVfModuleModelInfoObject = addOnModule.getModelInfo() + String addOnVfModuleModelInfoWithRoot = addOnVfModuleModelInfoObject.toString() + String addOnVfModuleModelInfo = jsonUtil.getJsonValue(addOnVfModuleModelInfoWithRoot, "modelInfo") + execution.setVariable("addOnVfModuleModelInfo", addOnVfModuleModelInfo) + String addOnVfModuleLabel = addOnModule.getVfModuleLabel() + execution.setVariable("addOnVfModuleLabel", addOnVfModuleLabel) + String addOnPersonaModelId = addOnVfModuleModelInfoObject.getModelInvariantUuid() + execution.setVariable("addOnPersonaModelId", addOnPersonaModelId) + int addOnInitialCount = addOnModule.getInitialCount() + execution.setVariable("initialCount", addOnInitialCount) + + + }catch(Exception e){ + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception Occured Processing preProcessAddOnModule ", "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during preProcessAddOnModule Method:\n" + e.getMessage()) + } + msoLogger.trace("COMPLETED preProcessAddOnModule") + } + + public void postProcessAddOnModule(DelegateExecution execution){ + + execution.setVariable("prefix", Prefix) + msoLogger.trace("STARTED postProcessAddOnModule") + + try { + int addOnModulesDeployed = execution.getVariable("addOnModulesDeployed") + execution.setVariable("addOnModulesDeployed", addOnModulesDeployed + 1) + + }catch(Exception e){ + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception Occured Processing postProcessAddOnModule ", "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during postProcessAddOnModule Method:\n" + e.getMessage()) + } + msoLogger.trace("COMPLETED postProcessAddOnModule") + } + + public void validateBaseModule(DelegateExecution execution){ + + execution.setVariable("prefix", Prefix) + msoLogger.trace("STARTED validateBaseModule") + + try { + def baseRollbackData = execution.getVariable("DCVAM_baseRollbackData") + def rollbackData = execution.getVariable("rollbackData") + + def baseModuleMap = baseRollbackData.get("VFMODULE") + baseModuleMap.each{ k, v -> rollbackData.put("VFMODULE_BASE", "${k}","${v}") } + execution.setVariable("rollbackData", rollbackData) + msoLogger.debug("addOnModulesDeployed: " + execution.getVariable("addOnModulesDeployed")) + msoLogger.debug("addOnModulesToDeploy: " + execution.getVariable("addOnModulesToDeploy")) + if (execution.getVariable("addOnModulesDeployed") < execution.getVariable("addOnModulesToDeploy")) { + msoLogger.debug("More add on modules to deploy") + } + else { + msoLogger.debug("No more add on modules to deploy") + } + + }catch(Exception e){ + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception Occured Processing validateBaseModule ", "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during validateBaseModule Method:\n" + e.getMessage()) + } + msoLogger.trace("COMPLETED validateBaseModule") + } + + public void validateAddOnModule(DelegateExecution execution){ + + execution.setVariable("prefix", Prefix) + msoLogger.trace("STARTED validateAddOnModule") + + try { + int instancesOfThisModuleDeployed = execution.getVariable("instancesOfThisModuleDeployed") + int numOfCreatedAddOnModules = execution.getVariable("numOfCreatedAddOnModules") + def addOnRollbackData = execution.getVariable("DCVAM_addOnRollbackData") + def rollbackData = execution.getVariable("rollbackData") + + def addOnModuleMap = addOnRollbackData.get("VFMODULE") + numOfCreatedAddOnModules = numOfCreatedAddOnModules + 1 + addOnModuleMap.each{ k, v -> rollbackData.put("VFMODULE_ADDON_" + numOfCreatedAddOnModules, "${k}","${v}") } + + execution.setVariable("DCVAM_addOnRollbackData", null) + + execution.setVariable("instancesOfThisModuleDeployed", instancesOfThisModuleDeployed + 1) + + execution.setVariable("numOfCreatedAddOnModules", numOfCreatedAddOnModules) + rollbackData.put("VNFANDMODULES", "numOfCreatedAddOnModules", "${numOfCreatedAddOnModules}") + execution.setVariable("rollbackData", rollbackData) + }catch(Exception e){ + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception Occured Processing preProcessAddOnModule ", "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during preProcessAddOnModule Method:\n" + e.getMessage()) + } + msoLogger.trace("COMPLETED validateAddOnModule") + } + + public void preProcessRollback (DelegateExecution execution) { + + msoLogger.trace("preProcessRollback") + try { + + Object workflowException = execution.getVariable("WorkflowException"); + + if (workflowException instanceof WorkflowException) { + msoLogger.debug("Prev workflowException: " + workflowException.getErrorMessage()) + execution.setVariable("prevWorkflowException", workflowException); + //execution.setVariable("WorkflowException", null); + } + } catch (BpmnError e) { + msoLogger.debug("BPMN Error during preProcessRollback") + } catch(Exception ex) { + String msg = "Exception in preProcessRollback. " + ex.getMessage() + msoLogger.debug(msg) + } + msoLogger.trace("Exit preProcessRollback") + } + + public void postProcessRollback (DelegateExecution execution) { + + msoLogger.trace("postProcessRollback") + String msg = "" + try { + Object workflowException = execution.getVariable("prevWorkflowException"); + if (workflowException instanceof WorkflowException) { + msoLogger.debug("Setting prevException to WorkflowException: ") + execution.setVariable("WorkflowException", workflowException); + } + execution.setVariable("rollbackData", null) + } catch (BpmnError b) { + msoLogger.debug("BPMN Error during postProcessRollback") + throw b; + } catch(Exception ex) { + msg = "Exception in postProcessRollback. " + ex.getMessage() + msoLogger.debug(msg) + } + msoLogger.trace("Exit postProcessRollback") + } + + public void createPlatform (DelegateExecution execution) { + + msoLogger.trace("START createPlatform") + + String platformName = execution.getVariable("platformName") + String vnfId = execution.getVariable("vnfId") + + msoLogger.debug("Platform NAME: " + platformName) + msoLogger.debug("VnfID: " + vnfId) + + if(isBlank(platformName)){ + msoLogger.debug("platformName was not found. Continuing on with flow...") + }else{ + msoLogger.debug("platformName was found.") + try{ + AAICreateResources aaiCR = new AAICreateResources() + aaiCR.createAAIPlatform(platformName, vnfId) + }catch(Exception ex){ + String msg = "Exception in createPlatform. " + ex.getMessage(); + msoLogger.debug(msg) + } + } + msoLogger.trace("Exit createPlatform") + } + + public void createLineOfBusiness (DelegateExecution execution) { + + msoLogger.trace("START createLineOfBusiness") + + String lineOfBusiness = execution.getVariable("lineOfBusiness") + String vnfId = execution.getVariable("vnfId") + + msoLogger.debug("LineOfBusiness NAME: " + lineOfBusiness) + msoLogger.debug("VnfID: " + vnfId) + + if(isBlank(lineOfBusiness)){ + msoLogger.debug("LineOfBusiness was not found. Continuing on with flow...") + }else{ + msoLogger.debug("LineOfBusiness was found.") + try{ + AAICreateResources aaiCR = new AAICreateResources() + aaiCR.createAAILineOfBusiness(lineOfBusiness, vnfId) + }catch(Exception ex){ + String msg = "Exception in LineOfBusiness. " + ex.getMessage(); + msoLogger.debug(msg) + } + } + msoLogger.trace("Exit createLineOfBusiness") + } + + +}
\ No newline at end of file diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVnfAndModulesRollback.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVnfAndModulesRollback.groovy new file mode 100644 index 0000000000..eafc39b1dd --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVnfAndModulesRollback.groovy @@ -0,0 +1,360 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts + +import static org.apache.commons.lang3.StringUtils.*; + +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution; +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.onap.so.bpmn.common.scripts.ExceptionUtil +import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.so.bpmn.common.scripts.SDNCAdapterUtils +import org.onap.so.bpmn.core.RollbackData +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.logger.MessageEnum +import org.onap.so.logger.MsoLogger + +/** + * This class supports the macro VID Flow + * with the rollback of a creation of a generic vnf and related VF modules. + */ +class DoCreateVnfAndModulesRollback extends AbstractServiceTaskProcessor { + + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoCreateVnfAndModulesRollback.class); + String Prefix="DCVAMR_" + ExceptionUtil exceptionUtil = new ExceptionUtil() + JsonUtils jsonUtil = new JsonUtils() + + + /** + * This method gets and validates the incoming + * request. + * + * @param - execution + * + */ + public void preProcessRequest(DelegateExecution execution) { + + execution.setVariable("prefix",Prefix) + msoLogger.debug("STARTED DoCreateVnfAndModulesRollback PreProcessRequest Process") + + try{ + // Get Rollback Variables + + def rollbackData = execution.getVariable("rollbackData") + msoLogger.debug("Incoming RollbackData is: " + rollbackData.toString()) + execution.setVariable("rolledBack", null) + execution.setVariable("rollbackError", null) + + if (execution.getVariable("disableRollback").equals("true" )) + { + execution.setVariable("skipRollback", true) + } + + String vnfId = rollbackData.get("VNF", "vnfId") + msoLogger.debug("Rollback vnfId is: " + vnfId) + execution.setVariable("DCVAMR_vnfId", vnfId) + + execution.setVariable("mso-request-id", execution.getVariable("msoRequestId")) + + execution.setVariable("DCVAMR_rollbackSDNCAssign", rollbackData.get("VNF", "rollbackSDNCAssign")) + execution.setVariable("DCVAMR_rollbackSDNCActivate", rollbackData.get("VNF", "rollbackSDNCActivate")) + execution.setVariable("DCVAMR_rollbackVnfCreate", rollbackData.get("VNF", "rollbackVnfCreate")) + + String sdncCallbackUrl = rollbackData.get("VNF", "sdncCallbackUrl") + msoLogger.debug("Rollback sdncCallbackUrl is: " + sdncCallbackUrl) + execution.setVariable("DCVAMR_sdncCallbackUrl", sdncCallbackUrl) + + String tenantId= rollbackData.get("VNF", "tenantId") + msoLogger.debug("Rollback tenantId is: " + tenantId) + execution.setVariable("DCVAMR_tenantId", tenantId) + + String source= rollbackData.get("VNF", "source") + msoLogger.debug("Rollback source is: " + source) + execution.setVariable("DCVAMR_source", source) + + String serviceInstanceId = rollbackData.get("VNF", "serviceInstanceId") + msoLogger.debug("Rollback serviceInstanceId is: " + serviceInstanceId) + execution.setVariable("DCVAMR_serviceInstanceId", serviceInstanceId) + + String cloudSiteId = rollbackData.get("VNF", "cloudSiteId") + msoLogger.debug("Rollback cloudSiteId is: " + cloudSiteId) + execution.setVariable("DCVAMR_cloudSiteId", cloudSiteId) + + def numOfAddOnModulesString = rollbackData.get("VNFANDMODULES", "numOfCreatedAddOnModules") + int numOfAddOnModules = 0 + if (numOfAddOnModulesString != null) { + numOfAddOnModules = Integer.parseInt(numOfAddOnModulesString) + } + execution.setVariable("DCVAMR_numOfAddOnModules", numOfAddOnModules) + + def baseVfModuleRollbackMap = rollbackData.get("VFMODULE_BASE") + if (baseVfModuleRollbackMap == null) { + // there are no VF Modules to delete + execution.setVariable("DCVAMR_numOfModulesToDelete", 0) + } + else { + execution.setVariable("DCVAMR_numOfModulesToDelete", numOfAddOnModules + 1) + } + + // Set aLaCarte to false + execution.setVariable("DCVAMR_aLaCarte", false) + + }catch(BpmnError b){ + msoLogger.debug("Rethrowing MSOWorkflowException") + throw b + }catch(Exception e){ + msoLogger.debug(" Error Occured in DoCreateVnfAndModulesRollback PreProcessRequest method!" + e.getMessage()) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in DoCreateVnfAndModulesRollback PreProcessRequest") + + } + msoLogger.trace("COMPLETED DoCreateVnfAndModulesRollback PreProcessRequest Process") + } + + + + public void preProcessCreateVfModuleRollback(DelegateExecution execution){ + + execution.setVariable("prefix", Prefix) + msoLogger.trace("STARTED preProcessCreateVfModuleRollback") + + try { + + def rollbackData = execution.getVariable("rollbackData") + + def vfModuleRollbackData = new RollbackData() + + def numOfModulesToDelete = execution.getVariable("DCVAMR_numOfModulesToDelete") + msoLogger.debug("numOfModulesToDelete: " + numOfModulesToDelete) + def moduleMap = null + + if (numOfModulesToDelete > 1) { + int addOnModuleIndex = numOfModulesToDelete - 1 + moduleMap = rollbackData.get("VFMODULE_ADDON_" + addOnModuleIndex) + msoLogger.debug("Removing ADDON VF module # " + addOnModuleIndex) + } + else { + moduleMap = rollbackData.get("VFMODULE_BASE") + msoLogger.debug("Removing BASE VF module") + } + moduleMap.each{ k, v -> vfModuleRollbackData.put("VFMODULE", "${k}","${v}") } + execution.setVariable("DCVAMR_RollbackData", vfModuleRollbackData) + + }catch(Exception e){ + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception Occured Processing preProcessCreateVfModuleRollback ", "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during preProcessCreateVfModuleRollback Method:\n" + e.getMessage()) + } + msoLogger.trace("COMPLETED preProcessCreateVfModuleRollback") + } + + + public void postProcessCreateVfModuleRollback(DelegateExecution execution){ + + execution.setVariable("prefix", Prefix) + msoLogger.trace("STARTED postProcessCreateVfModuleRollback") + def rolledBack = false + + try { + rolledBack = execution.getVariable("DCVM_rolledBack") + def numOfModulesToDelete = execution.getVariable("DCVAMR_numOfModulesToDelete") + execution.setVariable("DCVAMR_numOfModulesToDelete", numOfModulesToDelete - 1) + }catch(Exception e){ + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception Occured Processing postProcessCreateVfModuleRollback ", "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during postProcessCreateVfModuleRollback Method:\n" + e.getMessage()) + } + if (rolledBack == false) { + msoLogger.debug("Failure on DoCreateVfModuleRollback") + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Unsuccessful rollback of DoCreateVfModule ", "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during rollback of DoCreateVfModule") + } + msoLogger.trace("COMPLETED postProcessCreateVfModuleRollback") + } + + + public void preProcessSDNCDeactivateRequest(DelegateExecution execution){ + + execution.setVariable("prefix", Prefix) + msoLogger.trace("STARTED preProcessSDNCDeactivateRequest") + def vnfId = execution.getVariable("vnfId") + def serviceInstanceId = execution.getVariable("serviceInstanceId") + + try{ + //Build SDNC Request + + String deactivateSDNCRequest = buildSDNCRequest(execution, serviceInstanceId, "deactivate") + + deactivateSDNCRequest = utils.formatXml(deactivateSDNCRequest) + execution.setVariable(Prefix + "deactivateSDNCRequest", deactivateSDNCRequest) + msoLogger.debug("Outgoing DeactivateSDNCRequest is: \n" + deactivateSDNCRequest) + + }catch(Exception e){ + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception Occured Processing preProcessSDNCDeactivateRequest ", "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during preProcessSDNCDeactivateRequest Method:\n" + e.getMessage()) + } + msoLogger.trace("COMPLETED preProcessSDNCDeactivateRequest") + } + + public void preProcessSDNCUnassignRequest(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.preProcessSDNCUnassignRequest(' + + 'execution=' + execution.getId() + + ')' + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + msoLogger.trace('Entered ' + method) + execution.setVariable("prefix", Prefix) + msoLogger.trace("STARTED preProcessSDNCUnassignRequest Process") + try{ + String vnfId = execution.getVariable("vnfId") + String serviceInstanceId = execution.getVariable("serviceInstanceId") + + String unassignSDNCRequest = buildSDNCRequest(execution, serviceInstanceId, "unassign") + + execution.setVariable(Prefix + "unassignSDNCRequest", unassignSDNCRequest) + msoLogger.debug("Outgoing UnassignSDNCRequest is: \n" + unassignSDNCRequest) + + }catch(Exception e){ + msoLogger.debug("Exception Occured Processing preProcessSDNCUnassignRequest. Exception is:\n" + e) + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during preProcessSDNCUnassignRequest Method:\n" + e.getMessage()) + } + msoLogger.trace("COMPLETED preProcessSDNCUnassignRequest Process") + } + + public String buildSDNCRequest(DelegateExecution execution, String svcInstId, String action){ + + String uuid = execution.getVariable('testReqId') // for junits + if(uuid==null){ + uuid = execution.getVariable("msoRequestId") + "-" + System.currentTimeMillis() + } + def callbackURL = execution.getVariable(Prefix + "sdncCallbackUrl") + def requestId = execution.getVariable("msoRequestId") + def tenantId = execution.getVariable(Prefix + "tenantId") + def source = execution.getVariable(Prefix + "source") + def vnfId = execution.getVariable(Prefix + "vnfId") + def serviceInstanceId = execution.getVariable(Prefix + "serviceInstanceId") + def cloudSiteId = execution.getVariable(Prefix + "cloudSiteId") + + String sdncRequest = + """<sdncadapterworkflow:SDNCAdapterWorkflowRequest xmlns:ns5="http://org.onap/so/request/types/v1" + xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1" + xmlns:sdncadapter="http://org.onap.so/workflow/sdnc/adapter/schema/v1"> + <sdncadapter:RequestHeader> + <sdncadapter:RequestId>${MsoUtils.xmlEscape(uuid)}</sdncadapter:RequestId> + <sdncadapter:SvcInstanceId>${MsoUtils.xmlEscape(svcInstId)}</sdncadapter:SvcInstanceId> + <sdncadapter:SvcAction>${MsoUtils.xmlEscape(action)}</sdncadapter:SvcAction> + <sdncadapter:SvcOperation>vnf-topology-operation</sdncadapter:SvcOperation> + <sdncadapter:CallbackUrl>${MsoUtils.xmlEscape(callbackURL)}</sdncadapter:CallbackUrl> + <sdncadapter:MsoAction>generic-resource</sdncadapter:MsoAction> + </sdncadapter:RequestHeader> + <sdncadapterworkflow:SDNCRequestData> + <request-information> + <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> + <request-action>DeleteVnfInstance</request-action> + <source>${MsoUtils.xmlEscape(source)}</source> + <notification-url/> + <order-number/> + <order-version/> + </request-information> + <service-information> + <service-id/> + <subscription-service-type/> + <service-instance-id>${MsoUtils.xmlEscape(serviceInstanceId)}</service-instance-id> + <global-customer-id/> + </service-information> + <vnf-information> + <vnf-id>${MsoUtils.xmlEscape(vnfId)}</vnf-id> + <vnf-type/> + </vnf-information> + <vnf-request-input> + <vnf-name/> + <tenant>${MsoUtils.xmlEscape(tenantId)}</tenant> + <aic-cloud-region>${MsoUtils.xmlEscape(cloudSiteId)}</aic-cloud-region> + </vnf-request-input> + </sdncadapterworkflow:SDNCRequestData> + </sdncadapterworkflow:SDNCAdapterWorkflowRequest>""" + + msoLogger.debug("sdncRequest: " + sdncRequest) + return sdncRequest + } + + public void validateSDNCResponse(DelegateExecution execution, String response, String method){ + + execution.setVariable("prefix",Prefix) + msoLogger.debug("STARTED ValidateSDNCResponse Process") + + WorkflowException workflowException = execution.getVariable("WorkflowException") + boolean successIndicator = execution.getVariable("SDNCA_SuccessIndicator") + + msoLogger.debug("workflowException: " + workflowException) + + SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this) + sdncAdapterUtils.validateSDNCResponse(execution, response, workflowException, successIndicator) + + String sdncResponse = response + if(execution.getVariable(Prefix + 'sdncResponseSuccess') == true){ + msoLogger.debug("Received a Good Response from SDNC Adapter for " + method + " SDNC Call. Response is: \n" + sdncResponse) + }else{ + msoLogger.debug("Received a BAD Response from SDNC Adapter for " + method + " SDNC Call.") + throw new BpmnError("MSOWorkflowException") + } + msoLogger.debug("COMPLETED ValidateSDNCResponse Process") + } + + public void setSuccessfulRollbackStatus (DelegateExecution execution){ + + execution.setVariable("prefix", Prefix) + msoLogger.trace("STARTED setSuccessfulRollbackStatus") + + try{ + // Set rolledBack to true, rollbackError to null + execution.setVariable("rolledBack", true) + execution.setVariable("rollbackError", null) + + }catch(Exception e){ + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception Occured Processing setSuccessfulRollbackStatus ", "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during setSuccessfulRollbackStatus Method:\n" + e.getMessage()) + } + msoLogger.trace("COMPLETED setSuccessfulRollbackStatus") + } + + public void setFailedRollbackStatus (DelegateExecution execution){ + + execution.setVariable("prefix", Prefix) + msoLogger.trace("STARTED setFailedRollbackStatus") + + try{ + // Set rolledBack to false, rollbackError to actual value, rollbackData to null + execution.setVariable("rolledBack", false) + def rollbackError = execution.getVariable("rollbackError") + if (rollbackError == null) { + execution.setVariable("rollbackError", 'Caught exception in DoCreateVnfAndModulesRollback') + } + execution.setVariable("rollbackData", null) + + }catch(Exception e){ + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception Occured Processing setFailedRollbackStatus. ", "BPMN", MsoLogger.getServiceName(),MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during setFailedRollbackStatus Method:\n" + e.getMessage()) + } + msoLogger.trace("COMPLETED setFailedRollbackStatus") + } + + +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCustomDeleteE2EServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCustomDeleteE2EServiceInstance.groovy new file mode 100644 index 0000000000..238ac82c01 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCustomDeleteE2EServiceInstance.groovy @@ -0,0 +1,640 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.so.bpmn.infrastructure.scripts + +import static org.apache.commons.lang3.StringUtils.*; + +import javax.xml.parsers.DocumentBuilder +import javax.xml.parsers.DocumentBuilderFactory + +import org.apache.commons.lang3.* +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.json.JSONArray; +import org.json.JSONObject; +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.onap.so.bpmn.common.scripts.ExceptionUtil +import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.so.bpmn.core.UrnPropertiesReader +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.logger.MessageEnum +import org.onap.so.logger.MsoLogger +import org.springframework.web.util.UriUtils; +import org.w3c.dom.Document +import org.w3c.dom.Element +import org.w3c.dom.Node +import org.w3c.dom.NodeList +import org.xml.sax.InputSource +import org.onap.so.client.aai.entities.uri.AAIResourceUri +import org.onap.so.client.aai.entities.uri.AAIUriFactory +import org.onap.so.client.aai.AAIObjectType +import org.onap.so.client.aai.AAIResourcesClient + +import groovy.json.* + + + +/** + * This groovy class supports the <class>DoDeleteE2EServiceInstance.bpmn</class> process. + * + * Inputs: + * @param - msoRequestId + * @param - globalSubscriberId - O + * @param - subscriptionServiceType - O + * @param - serviceInstanceId + * @param - serviceInstanceName - O + * @param - serviceInputParams (should contain aic_zone for serviceTypes TRANSPORT,ATM) + * @param - sdncVersion + * @param - failNotFound - TODO + * @param - serviceInputParams - TODO + * + * Outputs: + * @param - WorkflowException + * + * Rollback - Deferred + */ +public class DoCustomDeleteE2EServiceInstance extends AbstractServiceTaskProcessor { + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoCustomDeleteE2EServiceInstance.class); + + + String Prefix="DDELSI_" + ExceptionUtil exceptionUtil = new ExceptionUtil() + JsonUtils jsonUtil = new JsonUtils() + + public void preProcessRequest (DelegateExecution execution) { + msoLogger.trace("preProcessRequest ") + String msg = "" + + try { + String requestId = execution.getVariable("msoRequestId") + execution.setVariable("prefix",Prefix) + + //Inputs + //requestDetails.subscriberInfo. for AAI GET & PUT & SDNC assignToplology + String globalSubscriberId = execution.getVariable("globalSubscriberId") //globalCustomerId + if (globalSubscriberId == null) + { + execution.setVariable("globalSubscriberId", "") + } + + //requestDetails.requestParameters. for AAI PUT & SDNC assignTopology + String serviceType = execution.getVariable("serviceType") + if (serviceType == null) + { + execution.setVariable("serviceType", "") + } + + //Generated in parent for AAI PUT + String serviceInstanceId = execution.getVariable("serviceInstanceId") + if (isBlank(serviceInstanceId)){ + msg = "Input serviceInstanceId is null" + msoLogger.info(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + + String sdncCallbackUrl = UrnPropertiesReader.getVariable('mso.workflow.sdncadapter.callback',execution) + if (isBlank(sdncCallbackUrl)) { + msg = "URN_mso_workflow_sdncadapter_callback is null" + msoLogger.info(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + execution.setVariable("sdncCallbackUrl", sdncCallbackUrl) + msoLogger.info("SDNC Callback URL: " + sdncCallbackUrl) + + StringBuilder sbParams = new StringBuilder() + Map<String, String> paramsMap = execution.getVariable("serviceInputParams") + if (paramsMap != null) + { + sbParams.append("<service-input-parameters>") + for (Map.Entry<String, String> entry : paramsMap.entrySet()) { + String paramsXml + String paramName = entry.getKey() + String paramValue = entry.getValue() + paramsXml = + """ <param> + <name>${MsoUtils.xmlEscape(paramName)}</name> + <value>${MsoUtils.xmlEscape(paramValue)}</value> + </param> + """ + sbParams.append(paramsXml) + } + sbParams.append("</service-input-parameters>") + } + String siParamsXml = sbParams.toString() + if (siParamsXml == null) + siParamsXml = "" + execution.setVariable("siParamsXml", siParamsXml) + + } catch (BpmnError e) { + throw e; + } catch (Exception ex){ + msg = "Exception in preProcessRequest " + ex.getMessage() + msoLogger.info(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.trace("Exit preProcessRequest ") + } + + + public void preProcessVFCDelete (DelegateExecution execution) { + } + + public void postProcessVFCDelete(DelegateExecution execution, String response, String method) { + } + + public void preProcessSDNCDelete (DelegateExecution execution) { + msoLogger.trace("preProcessSDNCDelete ") + String msg = "" + + try { + def serviceInstanceId = execution.getVariable("serviceInstanceId") + def serviceInstanceName = execution.getVariable("serviceInstanceName") + def callbackURL = execution.getVariable("sdncCallbackUrl") + def requestId = execution.getVariable("msoRequestId") + def serviceId = execution.getVariable("productFamilyId") + def subscriptionServiceType = execution.getVariable("subscriptionServiceType") + def globalSubscriberId = execution.getVariable("globalSubscriberId") //globalCustomerId + + String serviceModelInfo = execution.getVariable("serviceModelInfo") + def modelInvariantUuid = "" + def modelVersion = "" + def modelUuid = "" + def modelName = "" + if (!isBlank(serviceModelInfo)) + { + modelInvariantUuid = jsonUtil.getJsonValue(serviceModelInfo, "modelInvariantUuid") + modelVersion = jsonUtil.getJsonValue(serviceModelInfo, "modelVersion") + modelUuid = jsonUtil.getJsonValue(serviceModelInfo, "modelUuid") + modelName = jsonUtil.getJsonValue(serviceModelInfo, "modelName") + + if (modelInvariantUuid == null) { + modelInvariantUuid = "" + } + if (modelVersion == null) { + modelVersion = "" + } + if (modelUuid == null) { + modelUuid = "" + } + if (modelName == null) { + modelName = "" + } + } + if (serviceInstanceName == null) { + serviceInstanceName = "" + } + if (serviceId == null) { + serviceId = "" + } + + def siParamsXml = execution.getVariable("siParamsXml") + def serviceType = execution.getVariable("serviceType") + if (serviceType == null) + { + serviceType = "" + } + + def sdncRequestId = UUID.randomUUID().toString() + + String sdncDelete = + """<sdncadapterworkflow:SDNCAdapterWorkflowRequest xmlns:ns5="http://org.onap/so/request/types/v1" + xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1" + xmlns:sdncadapter="http://org.onap/workflow/sdnc/adapter/schema/v1"> + <sdncadapter:RequestHeader> + <sdncadapter:RequestId>${MsoUtils.xmlEscape(sdncRequestId)}</sdncadapter:RequestId> + <sdncadapter:SvcInstanceId>${MsoUtils.xmlEscape(serviceInstanceId)}</sdncadapter:SvcInstanceId> + <sdncadapter:SvcAction>delete</sdncadapter:SvcAction> + <sdncadapter:SvcOperation>service-topology-operation</sdncadapter:SvcOperation> + <sdncadapter:CallbackUrl>${MsoUtils.xmlEscape(callbackURL)}</sdncadapter:CallbackUrl> + <sdncadapter:MsoAction>${MsoUtils.xmlEscape(serviceType)}</sdncadapter:MsoAction> + </sdncadapter:RequestHeader> + <sdncadapterworkflow:SDNCRequestData> + <request-information> + <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> + <source>MSO</source> + <notification-url/> + <order-number/> + <order-version/> + <request-action>DeleteServiceInstance</request-action> + </request-information> + <service-information> + <service-id>${MsoUtils.xmlEscape(serviceId)}</service-id> + <subscription-service-type>${MsoUtils.xmlEscape(subscriptionServiceType)}</subscription-service-type> + <onap-model-information> + <model-invariant-uuid>${MsoUtils.xmlEscape(modelInvariantUuid)}</model-invariant-uuid> + <model-uuid>${MsoUtils.xmlEscape(modelUuid)}</model-uuid> + <model-version>${MsoUtils.xmlEscape(modelVersion)}</model-version> + <model-name>${MsoUtils.xmlEscape(modelName)}</model-name> + </onap-model-information> + <service-instance-id>${MsoUtils.xmlEscape(serviceInstanceId)}</service-instance-id> + <subscriber-name/> + <global-customer-id>${MsoUtils.xmlEscape(globalSubscriberId)}</global-customer-id> + </service-information> + <service-request-input> + <service-instance-name>${MsoUtils.xmlEscape(serviceInstanceName)}</service-instance-name> + ${siParamsXml} + </service-request-input> + </sdncadapterworkflow:SDNCRequestData> + </sdncadapterworkflow:SDNCAdapterWorkflowRequest>""" + + sdncDelete = utils.formatXml(sdncDelete) + def sdncRequestId2 = UUID.randomUUID().toString() + String sdncDeactivate = sdncDelete.replace(">delete<", ">deactivate<").replace(">${sdncRequestId}<", ">${sdncRequestId2}<") + execution.setVariable("sdncDelete", sdncDelete) + execution.setVariable("sdncDeactivate", sdncDeactivate) + msoLogger.info("sdncDeactivate:\n" + sdncDeactivate) + msoLogger.info("sdncDelete:\n" + sdncDelete) + + } catch (BpmnError e) { + throw e; + } catch(Exception ex) { + msg = "Exception in preProcessSDNCDelete. " + ex.getMessage() + msoLogger.info(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, "Exception Occured in preProcessSDNCDelete.\n" + ex.getMessage()) + } + msoLogger.info(" *****Exit preProcessSDNCDelete *****") + } + + public void postProcessSDNCDelete(DelegateExecution execution, String response, String method) { + + msoLogger.trace("postProcessSDNC " + method + " ") + String msg = "" + + /*try { + WorkflowException workflowException = execution.getVariable("WorkflowException") + boolean successIndicator = execution.getVariable("SDNCA_SuccessIndicator") + msoLogger.info("SDNCResponse: " + response) + msoLogger.info("workflowException: " + workflowException) + + SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this) + sdncAdapterUtils.validateSDNCResponse(execution, response, workflowException, successIndicator) + if(execution.getVariable(Prefix + 'sdncResponseSuccess') == "true"){ + msoLogger.info("Good response from SDNC Adapter for service-instance " + method + "response:\n" + response) + + }else{ + msg = "Bad Response from SDNC Adapter for service-instance " + method + msoLogger.info(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 3500, msg) + } + } catch (BpmnError e) { + throw e; + } catch(Exception ex) { + msg = "Exception in postProcessSDNC " + method + " Exception:" + ex.getMessage() + msoLogger.info(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + }*/ + msoLogger.trace("Exit postProcessSDNC " + method + " ") + } + + public void postProcessAAIGET(DelegateExecution execution) { + msoLogger.trace("postProcessAAIGET ") + String msg = "" + + try { + String serviceInstanceId = execution.getVariable("serviceInstanceId") + boolean foundInAAI = execution.getVariable("GENGS_FoundIndicator") + String serviceType = "" + + if(foundInAAI){ + msoLogger.info("Found Service-instance in AAI") + + String siData = execution.getVariable("GENGS_service") + msoLogger.info("SI Data") + if (isBlank(siData)) + { + msg = "Could not retrive ServiceInstance data from AAI to delete id:" + serviceInstanceId + msoLogger.info(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + else + { + msoLogger.info("SI Data" + siData) + //Confirm there are no related service instances (vnf/network or volume) + if (utils.nodeExists(siData, "relationship-list")) { + msoLogger.info("SI Data relationship-list exists:") + InputSource source = new InputSource(new StringReader(siData)); + DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder docBuilder = docFactory.newDocumentBuilder() + Document serviceXml = docBuilder.parse(source) + serviceXml.getDocumentElement().normalize() + //test(siData) + NodeList nodeList = serviceXml.getElementsByTagName("relationship") + JSONArray jArray = new JSONArray() + for (int x = 0; x < nodeList.getLength(); x++) { + Node node = nodeList.item(x) + if (node.getNodeType() == Node.ELEMENT_NODE) { + Element eElement = (Element) node + def e = eElement.getElementsByTagName("related-to").item(0).getTextContent() //for ns + if(e.equals("service-instance")){ + def relatedObject = eElement.getElementsByTagName("related-link").item(0).getTextContent() + msoLogger.info("ServiceInstance Related NS :" + relatedObject) + NodeList dataList = node.getChildNodes() + if(null != dataList) { + JSONObject jObj = new JSONObject() + for (int i = 0; i < dataList.getLength(); i++) { + Node dNode = dataList.item(i) + if(dNode.getNodeName() == "relationship-data") { + Element rDataEle = (Element)dNode + def eKey = rDataEle.getElementsByTagName("relationship-key").item(0).getTextContent() + def eValue = rDataEle.getElementsByTagName("relationship-value").item(0).getTextContent() + if(eKey.equals("service-instance.service-instance-id")){ + jObj.put("resourceInstanceId", eValue) + } + } + else if(dNode.getNodeName() == "related-to-property"){ + Element rDataEle = (Element)dNode + def eKey = rDataEle.getElementsByTagName("property-key").item(0).getTextContent() + def eValue = rDataEle.getElementsByTagName("property-value").item(0).getTextContent() + if(eKey.equals("service-instance.service-instance-name")){ + jObj.put("resourceType", eValue) + } + } + } + msoLogger.info("Relationship related to Resource:" + jObj.toString()) + jArray.put(jObj) + } + //for overlay/underlay + }else if (e.equals("configuration")){ + def relatedObject = eElement.getElementsByTagName("related-link").item(0).getTextContent() + msoLogger.info("ServiceInstance Related Configuration :" + relatedObject) + NodeList dataList = node.getChildNodes() + if(null != dataList) { + JSONObject jObj = new JSONObject() + for (int i = 0; i < dataList.getLength(); i++) { + Node dNode = dataList.item(i) + if(dNode.getNodeName() == "relationship-data") { + Element rDataEle = (Element)dNode + def eKey = rDataEle.getElementsByTagName("relationship-key").item(0).getTextContent() + def eValue = rDataEle.getElementsByTagName("relationship-value").item(0).getTextContent() + if(eKey.equals("configuration.configuration-id")){ + jObj.put("resourceInstanceId", eValue) + } + } + else if(dNode.getNodeName() == "related-to-property"){ + Element rDataEle = (Element)dNode + def eKey = rDataEle.getElementsByTagName("property-key").item(0).getTextContent() + def eValue = rDataEle.getElementsByTagName("property-value").item(0).getTextContent() + if(eKey.equals("configuration.configuration-type")){ + jObj.put("resourceType", eValue) + } + } + } + msoLogger.info("Relationship related to Resource:" + jObj.toString()) + jArray.put(jObj) + } + } + } + } + execution.setVariable("serviceRelationShip", jArray.toString()) + } + } + }else{ + boolean succInAAI = execution.getVariable("GENGS_SuccessIndicator") + if(!succInAAI){ + msoLogger.info("Error getting Service-instance from AAI", + serviceInstanceId) + WorkflowException workflowException = execution.getVariable("WorkflowException") + msoLogger.debug("workflowException: " + workflowException) + if(workflowException != null){ + exceptionUtil.buildAndThrowWorkflowException(execution, workflowException.getErrorCode(), workflowException.getErrorMessage()) + } + else + { + msg = "Failure in postProcessAAIGET GENGS_SuccessIndicator:" + succInAAI + msoLogger.info(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg) + } + } + + msoLogger.info("Service-instance NOT found in AAI. Silent Success") + } + }catch (BpmnError e) { + throw e; + } catch (Exception ex) { + msg = "Exception in DoDeleteE2EServiceInstance.postProcessAAIGET. " + ex.getMessage() + msoLogger.info(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.trace("Exit postProcessAAIGET ") + } + + /** + * Deletes the service instance in aai + */ + public void deleteServiceInstance(DelegateExecution execution) { + msoLogger.trace("Entered deleteServiceInstance") + try { + String globalCustId = execution.getVariable("globalSubscriberId") + String serviceType = execution.getVariable("serviceType") + String serviceInstanceId = execution.getVariable("serviceInstanceId") + + AAIResourcesClient resourceClient = new AAIResourcesClient(); + AAIResourceUri serviceInstanceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, globalCustId, serviceType, serviceInstanceId) + resourceClient.delete(serviceInstanceUri) + + msoLogger.trace("Exited deleteServiceInstance") + }catch(Exception e){ + msoLogger.debug("Error occured within deleteServiceInstance method: " + e) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Error occured during deleteServiceInstance from aai") + } + } + + public void preInitResourcesOperStatus(DelegateExecution execution){ + msoLogger.trace("STARTED preInitResourcesOperStatus Process ") + try{ + String serviceId = execution.getVariable("serviceInstanceId") + String operationId = execution.getVariable("operationId") + String operationType = execution.getVariable("operationType") + String resourceTemplateUUIDs = "" + String result = "processing" + String progress = "0" + String reason = "" + String operationContent = "Prepare service creation" + msoLogger.info("Generated new operation for Service Instance serviceId:" + serviceId + " operationId:" + operationId + " operationType:" + operationType) + serviceId = UriUtils.encode(serviceId,"UTF-8") + execution.setVariable("serviceInstanceId", serviceId) + execution.setVariable("operationId", operationId) + execution.setVariable("operationType", operationType) + // we use resource instance ids for delete flow as resourceTemplateUUIDs + /*[ + { + "resourceInstanceId":"1111", + "resourceType":"vIMS" + }, + { + "resourceInstanceId":"222", + "resourceType":"vEPC" + }, + { + "resourceInstanceId":"3333", + "resourceType":"overlay" + }, + { + "resourceInstanceId":"4444", + "resourceType":"underlay" + } + ]*/ + String serviceRelationShip = execution.getVariable("serviceRelationShip") + + def jsonSlurper = new JsonSlurper() + def jsonOutput = new JsonOutput() + List relationShipList = jsonSlurper.parseText(serviceRelationShip) + + if (relationShipList != null) { + relationShipList.each { + resourceTemplateUUIDs = resourceTemplateUUIDs + it.resourceInstanceId + ":" + } + } + execution.setVariable("URN_mso_adapters_openecomp_db_endpoint","http://mso.mso.testlab.openecomp.org:8080/dbadapters/RequestsDbAdapter") + + String payload = + """<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" + xmlns:ns="http://org.onap.so/requestsdb"> + <soapenv:Header/> + <soapenv:Body> + <ns:initResourceOperationStatus xmlns:ns="http://org.onap.so/requestsdb"> + <serviceId>${MsoUtils.xmlEscape(serviceId)}</serviceId> + <operationId>${MsoUtils.xmlEscape(operationId)}</operationId> + <operationType>${MsoUtils.xmlEscape(operationType)}</operationType> + <resourceTemplateUUIDs>${MsoUtils.xmlEscape(resourceTemplateUUIDs)}</resourceTemplateUUIDs> + </ns:initResourceOperationStatus> + </soapenv:Body> + </soapenv:Envelope>""" + + payload = utils.formatXml(payload) + execution.setVariable("CVFMI_initResOperStatusRequest", payload) + msoLogger.info("Outgoing initResourceOperationStatus: \n" + payload) + msoLogger.debug("CreateVfModuleInfra Outgoing initResourceOperationStatus Request: " + payload) + + }catch(Exception e){ + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception Occured Processing preInitResourcesOperStatus.", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e); + execution.setVariable("CVFMI_ErrorResponse", "Error Occurred during preInitResourcesOperStatus Method:\n" + e.getMessage()) + } + msoLogger.trace("COMPLETED preInitResourcesOperStatus Process ") + } + + /** + * prepare delete parameters + */ + public void preResourceDelete(execution, resourceName){ + // we use resource instance ids for delete flow as resourceTemplateUUIDs + /*[ + { + "resourceInstanceId":"1111", + "resourceType":"vIMS" + }, + { + "resourceInstanceId":"222", + "resourceType":"vEPC" + }, + { + "resourceInstanceId":"3333", + "resourceType":"overlay" + }, + { + "resourceInstanceId":"4444", + "resourceType":"underlay" + } + ]*/ + msoLogger.trace("STARTED preResourceDelete Process ") + String serviceRelationShip = execution.getVariable("serviceRelationShip") + def jsonSlurper = new JsonSlurper() + def jsonOutput = new JsonOutput() + List relationShipList = jsonSlurper.parseText(serviceRelationShip) + + if (relationShipList != null) { + relationShipList.each { + if(StringUtils.containsIgnoreCase(it.resourceType, resourceName)) { + String resourceInstanceUUID = it.resourceInstanceId + String resourceTemplateUUID = it.resourceInstanceId + execution.setVariable("resourceTemplateId", resourceTemplateUUID) + execution.setVariable("resourceInstanceId", resourceInstanceUUID) + execution.setVariable("resourceType", resourceName) + msoLogger.info("Delete Resource Info resourceTemplate Id :" + resourceTemplateUUID + " resourceInstanceId: " + resourceInstanceUUID + " resourceType: " + resourceName) + } + } + } + msoLogger.trace("END preResourceDelete Process ") + } + + public void sequenceResource(execution){ + msoLogger.trace("STARTED sequenceResource Process ") + List<String> nsResources = new ArrayList<String>() + List<String> wanResources = new ArrayList<String>() + List<String> resourceSequence = new ArrayList<String>() + + String serviceRelationShip = execution.getVariable("serviceRelationShip") + + + def jsonSlurper = new JsonSlurper() + def jsonOutput = new JsonOutput() + List relationShipList = jsonSlurper.parseText(serviceRelationShip) + + if (relationShipList != null) { + relationShipList.each { + if(StringUtils.containsIgnoreCase(it.resourceType, "overlay") || StringUtils.containsIgnoreCase(it.resourceType, "underlay")){ + wanResources.add(it.resourceType) + }else{ + nsResources.add(it.resourceType) + } + } + } + resourceSequence.addAll(wanResources) + resourceSequence.addAll(nsResources) + String isContainsWanResource = wanResources.isEmpty() ? "false" : "true" + execution.setVariable("isContainsWanResource", isContainsWanResource) + execution.setVariable("currentResourceIndex", 0) + execution.setVariable("resourceSequence", resourceSequence) + msoLogger.info("resourceSequence: " + resourceSequence) + execution.setVariable("wanResources", wanResources) + msoLogger.trace("END sequenceResource Process ") + } + + public void getCurrentResource(execution){ + msoLogger.trace("Start getCurrentResoure Process ") + def currentIndex = execution.getVariable("currentResourceIndex") + List<String> resourceSequence = execution.getVariable("resourceSequence") + List<String> wanResources = execution.getVariable("wanResources") + String resourceName = resourceSequence.get(currentIndex) + execution.setVariable("resourceType",resourceName) + if(wanResources.contains(resourceName)){ + execution.setVariable("controllerInfo", "SDN-C") + }else{ + execution.setVariable("controllerInfo", "VF-C") + } + msoLogger.trace("COMPLETED getCurrentResoure Process ") + } + + public void parseNextResource(execution){ + msoLogger.trace("Start parseNextResource Process ") + def currentIndex = execution.getVariable("currentResourceIndex") + def nextIndex = currentIndex + 1 + execution.setVariable("currentResourceIndex", nextIndex) + List<String> resourceSequence = execution.getVariable("resourceSequence") + if(nextIndex >= resourceSequence.size()){ + execution.setVariable("allResourceFinished", "true") + }else{ + execution.setVariable("allResourceFinished", "false") + } + msoLogger.trace("COMPLETED parseNextResource Process ") + } + +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCustomDeleteE2EServiceInstanceV2.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCustomDeleteE2EServiceInstanceV2.groovy new file mode 100644 index 0000000000..21bf0f2c5c --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCustomDeleteE2EServiceInstanceV2.groovy @@ -0,0 +1,1099 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.so.bpmn.infrastructure.scripts + +import static org.apache.commons.lang3.StringUtils.*; + +import org.apache.commons.lang3.* +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.json.JSONArray; +import org.json.JSONObject; +import org.onap.so.bpmn.common.scripts.AaiUtil +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.onap.so.bpmn.common.scripts.ExceptionUtil +import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.logger.MessageEnum +import org.onap.so.logger.MsoLogger +import org.onap.so.rest.APIResponse; +import org.springframework.web.util.UriUtils; +import org.onap.so.client.aai.AAIResourcesClient +import org.onap.so.client.aai.AAIObjectType +import org.onap.so.client.aai.entities.AAIResultWrapper +import org.onap.so.client.aai.entities.Relationships +import org.onap.so.client.aai.entities.uri.AAIResourceUri +import org.onap.so.client.aai.entities.uri.AAIUriFactory +import org.json.JSONObject +import javax.ws.rs.NotFoundException +import groovy.json.* + + + +/** + * This groovy class supports the <class>DoDeleteE2EServiceInstance.bpmn</class> process. + * + * Inputs: + * @param - msoRequestId + * @param - globalSubscriberId - O + * @param - subscriptionServiceType - O + * @param - serviceInstanceId + * @param - serviceInstanceName - O + * @param - serviceInputParams (should contain aic_zone for serviceTypes TRANSPORT,ATM) + * @param - sdncVersion + * @param - failNotFound - TODO + * @param - serviceInputParams - TODO + * + * Outputs: + * @param - WorkflowException + * + * Rollback - Deferred + */ +public class DoCustomDeleteE2EServiceInstanceV2 extends AbstractServiceTaskProcessor { + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoCustomDeleteE2EServiceInstanceV2.class); + + + String Prefix="DDELSI_" + private static final String DebugFlag = "isDebugEnabled" + ExceptionUtil exceptionUtil = new ExceptionUtil() + JsonUtils jsonUtil = new JsonUtils() + + public void preProcessRequest (DelegateExecution execution) { + + def method = getClass().getSimpleName() + '.buildAPPCRequest(' +'execution=' + execution.getId() +')' + msoLogger.info("Entered " + method) + msoLogger.trace("preProcessRequest ") + String msg = "" + + try { + String requestId = execution.getVariable("msoRequestId") + execution.setVariable("prefix",Prefix) + + //Inputs + //requestDetails.subscriberInfo. for AAI GET & PUT & SDNC assignToplology + String globalSubscriberId = execution.getVariable("globalSubscriberId") //globalCustomerId + if (globalSubscriberId == null) + { + execution.setVariable("globalSubscriberId", "") + } + + //requestDetails.requestParameters. for AAI PUT & SDNC assignTopology + String serviceType = execution.getVariable("serviceType") + if (serviceType == null) + { + execution.setVariable("serviceType", "") + } + + //Generated in parent for AAI PUT + String serviceInstanceId = execution.getVariable("serviceInstanceId") + if (isBlank(serviceInstanceId)){ + msg = "Input serviceInstanceId is null" + msoLogger.info(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + + String sdncCallbackUrl = execution.getVariable('URN_mso_workflow_sdncadapter_callback') + if (isBlank(sdncCallbackUrl)) { + msg = "URN_mso_workflow_sdncadapter_callback is null" + msoLogger.info(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + execution.setVariable("sdncCallbackUrl", sdncCallbackUrl) + msoLogger.info("SDNC Callback URL: " + sdncCallbackUrl) + + StringBuilder sbParams = new StringBuilder() + Map<String, String> paramsMap = execution.getVariable("serviceInputParams") + if (paramsMap != null) + { + sbParams.append("<service-input-parameters>") + for (Map.Entry<String, String> entry : paramsMap.entrySet()) { + String paramsXml + String paramName = entry.getKey() + String paramValue = entry.getValue() + paramsXml = + """ <param> + <name>${MsoUtils.xmlEscape(paramName)}</name> + <value>${MsoUtils.xmlEscape(paramValue)}</value> + </param> + """ + sbParams.append(paramsXml) + } + sbParams.append("</service-input-parameters>") + } + String siParamsXml = sbParams.toString() + if (siParamsXml == null) + siParamsXml = "" + execution.setVariable("siParamsXml", siParamsXml) + execution.setVariable("operationStatus", "Waiting delete resource...") + execution.setVariable("progress", "0") + + } catch (BpmnError e) { + throw e; + } catch (Exception ex){ + msg = "Exception in preProcessRequest " + ex.getMessage() + msoLogger.info(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.info("Exited " + method) + } + + /** + * Gets the service instance and its relationships from aai + * + * @author cb645j + */ + public void getServiceInstance(DelegateExecution execution) { + try { + String serviceInstanceId = execution.getVariable('serviceInstanceId') + String globalSubscriberId = execution.getVariable('globalSubscriberId') + String serviceType = execution.getVariable('serviceType') + + AAIResourcesClient resourceClient = new AAIResourcesClient() + AAIResourceUri serviceInstanceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, globalSubscriberId, serviceType, serviceInstanceId) + AAIResultWrapper wrapper = resourceClient.get(serviceInstanceUri, NotFoundException.class) + String json = wrapper.getJson() + + execution.setVariable("serviceInstance", json) + + }catch(BpmnError e) { + throw e; + }catch(NotFoundException e) { + msoLogger.info("SI not found in aai. Silent Success ") + }catch(Exception ex) { + String msg = "Internal Error in getServiceInstance: " + ex.getMessage() + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + } + + private void loadResourcesProperties(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.loadResourcesProperties(' +'execution=' + execution.getId() +')' + def isDebugEnabled = execution.getVariable("isDebugEnabled") + msoLogger.info("Entered " + method) + String loadFilePath = "/etc/mso/config.d/reources.json" + try{ + def jsonPayload = new File(loadFilePath).text + msoLogger.info("jsonPayload: " + jsonPayload) + + String resourcesProperties = jsonUtil.prettyJson(jsonPayload.toString()) + msoLogger.info("resourcesProperties: " + resourcesProperties) + + String createResourceSort = jsonUtil.getJsonValue(resourcesProperties, "CreateResourceSort") + msoLogger.info("createResourceSort: " + createResourceSort) + execution.setVariable("createResourceSort", createResourceSort) + + String deleteResourceSort = jsonUtil.getJsonValue(resourcesProperties, "DeleteResourceSort") + msoLogger.info("deleteResourceSort: " + deleteResourceSort) + execution.setVariable("deleteResourceSort", deleteResourceSort) + + + String resourceControllerType = jsonUtil.getJsonValue(resourcesProperties, "ResourceControllerType") + msoLogger.info("resourceControllerType: " + resourceControllerType) + execution.setVariable("resourceControllerType", resourceControllerType) + + + }catch(Exception ex){ + // try error in method block + String exceptionMessage = "Bpmn error encountered in " + method + " - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + } + msoLogger.info("Exited " + method) + } + private void sortDeleteResource(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.sortDeleteResource(' +'execution=' + execution.getId() +')' + def isDebugEnabled = execution.getVariable("isDebugEnabled") + msoLogger.info("Entered " + method) + String deleteResourceSortDef = """[ + { + "resourceType":"GRE_SAR" + }, + { + "resourceType":"VPN_SAR" + }, + { + "resourceType":"APN_AAR" + }, + { + "resourceType":"GRE_AAR" + }, + { + "resourceType":"Overlay" + }, + { + "resourceType":"Underlay" + }, + { + "resourceType":"vIMS" + }, + { + "resourceType":"vCPE" + }, + { + "resourceType":"vFW" + }, + { + "resourceType":"vEPC" + } + + + ]""".trim() + + try{ + loadResourcesProperties(execution) + String deleteResourceSort = execution.getVariable("deleteResourceSort") + if (isBlank(deleteResourceSort)) { + deleteResourceSort = deleteResourceSortDef; + } + + List<String> sortResourceList = jsonUtil.StringArrayToList(execution, deleteResourceSort) + msoLogger.info("sortResourceList : " + sortResourceList) + + JSONArray newResourceList = new JSONArray() + int resSortCount = sortResourceList.size() + + for ( int currentResource = 0 ; currentResource < resSortCount ; currentResource++ ) { + String currentSortResource = sortResourceList[currentResource] + String sortResourceType = jsonUtil.getJsonValue(currentSortResource, "resourceType") + List<String> resourceList = execution.getVariable(Prefix+"resourceList") + + for (String resource : resourceList) { + msoLogger.info("resource : " + resource) + String resourceType = jsonUtil.getJsonValue(resource, "resourceType") + + if (StringUtils.containsIgnoreCase(resourceType, sortResourceType)) { + JSONObject jsonObj = new JSONObject(resource) + newResourceList.put(jsonObj) + } + msoLogger.info("Get next sort type " ) + } + } + + String newResourceStr = newResourceList.toString() + List<String> newResourceListStr = jsonUtil.StringArrayToList(execution, newResourceStr) + + execution.setVariable(Prefix+"resourceList", newResourceListStr) + msoLogger.info("newResourceList : " + newResourceListStr) + + }catch(Exception ex){ + // try error in method block + String exceptionMessage = "Bpmn error encountered in " + method + " - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + } + msoLogger.info("Exited " + method) + + } + public void prepareServiceDeleteResource(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.prepareServiceDeleteResource(' +'execution=' + execution.getId() +')' + msoLogger.info("Entered " + method) + + try { + + String serviceInstanceId = execution.getVariable("serviceInstanceId") + + + execution.setVariable(Prefix+"resourceList", "") + execution.setVariable(Prefix+"resourceCount", 0) + execution.setVariable(Prefix+"nextResource", 0) + execution.setVariable(Prefix+"resourceFinish", true) + + String aaiJsonRecord = execution.getVariable("serviceInstance"); + msoLogger.info("serviceInstanceAaiRecord: " +aaiJsonRecord) + + msoLogger.info("aaiJsonRecord: " +aaiJsonRecord) + def serviceInstanceName = jsonUtil.getJsonValue(aaiJsonRecord, "service-instance.service-instance-name") + execution.setVariable("serviceInstanceName",serviceInstanceName) + + def serviceType = jsonUtil.getJsonValue(aaiJsonRecord, "service-instance.service-type") + execution.setVariable("serviceType",serviceType) + + + String relationshipList = jsonUtil.getJsonValue(aaiJsonRecord, "service-instance.relationship-list") + msoLogger.info("relationship-list:" + relationshipList) + if (! isBlank(relationshipList)){ + msoLogger.info("relationship-list exists" ) + String relationShip = jsonUtil.getJsonValue(relationshipList, "relationship") + msoLogger.info("relationship: " + relationShip) + JSONArray allResources = new JSONArray() + JSONArray serviceResources = new JSONArray() + JSONArray networkResources = new JSONArray() + JSONArray allottedResources = new JSONArray() + + + if (! isBlank(relationShip)){ + JSONArray jsonArray = new JSONArray(); + if (relationShip.startsWith("{") && relationShip.endsWith("}")) { + JSONObject jsonObject = new JSONObject(relationShip); + jsonArray.put(jsonObject); + } else if (relationShip.startsWith("[") && relationShip.endsWith("]")) { + jsonArray = new JSONArray(relationShip); + } else { + msoLogger.info("The relationShip fomart is error" ) + } + + List<String> relationList = jsonUtil.StringArrayToList(execution, jsonArray.toString()) + + msoLogger.info("relationList: " + relationList) + + int relationNum =relationList.size() + msoLogger.info("**************relationList size: " + relationNum) + + for ( int currentRelation = 0 ; currentRelation < relationNum ; currentRelation++ ) { + msoLogger.info("current Relation num: " + currentRelation) + String relation = relationList[currentRelation] + msoLogger.info("relation: " + relation) + + String relatedTo = jsonUtil.getJsonValue(relation, "related-to") + msoLogger.info("relatedTo: " + relatedTo) + + String relatedLink = jsonUtil.getJsonValue(relation, "related-link") + msoLogger.info("relatedLink: " + relatedLink) + + if (StringUtils.equalsIgnoreCase(relatedTo, "allotted-resource")) { + msoLogger.info("allotted-resource exists ") + + String aaiArRsp = getAaiAr(execution, relatedLink) + msoLogger.info("aaiArRsp: " + aaiArRsp) + if (! isBlank(aaiArRsp)) { + def type = utils.getNodeText(aaiArRsp, "type") + def id = utils.getNodeText(aaiArRsp, "id") + def role = utils.getNodeText(aaiArRsp, "role") + def resourceVersion = utils.getNodeText(aaiArRsp, "resource-version") + + JSONObject jObject = new JSONObject() + jObject.put("resourceType", type) + jObject.put("resourceInstanceId", id) + jObject.put("resourceRole", role) + jObject.put("resourceVersion", resourceVersion) + + allResources.put(jObject) + msoLogger.info("allResources: " + allResources) + allottedResources.put(jObject) + msoLogger.info("allottedResources: " + allottedResources) + } + } + else if (StringUtils.equalsIgnoreCase(relatedTo, "service-instance")){ + msoLogger.info("service-instance exists ") + JSONObject jObject = new JSONObject() + + //relationship-data + String rsDataStr = jsonUtil.getJsonValue(relation, "relationship-data") + msoLogger.info("rsDataStr: " + rsDataStr) + List<String> rsDataList = jsonUtil.StringArrayToList(execution, rsDataStr) + msoLogger.info("rsDataList: " + rsDataList) + for(String rsData : rsDataList){ + msoLogger.info("rsData: " + rsData) + def eKey = jsonUtil.getJsonValue(rsData, "relationship-key") + def eValue = jsonUtil.getJsonValue(rsData, "relationship-value") + if(eKey.equals("service-instance.service-instance-id")){ + jObject.put("resourceInstanceId", eValue) + } + if(eKey.equals("service-subscription.service-type")){ + jObject.put("resourceType", eValue) + } + } + + //related-to-property + String rPropertyStr = jsonUtil.getJsonValue(relation, "related-to-property") + msoLogger.info("related-to-property: " + rPropertyStr) + if (rPropertyStr instanceof JSONArray){ + List<String> rPropertyList = jsonUtil.StringArrayToList(execution, rPropertyStr) + for (String rProperty : rPropertyList) { + msoLogger.info("rProperty: " + rProperty) + def eKey = jsonUtil.getJsonValue(rProperty, "property-key") + def eValue = jsonUtil.getJsonValue(rProperty, "property-value") + if(eKey.equals("service-instance.service-instance-name")){ + jObject.put("resourceName", eValue) + } + } + } + else { + String rProperty = rPropertyStr + msoLogger.info("rProperty: " + rProperty) + def eKey = jsonUtil.getJsonValue(rProperty, "property-key") + def eValue = jsonUtil.getJsonValue(rProperty, "property-value") + if (eKey.equals("service-instance.service-instance-name")) { + jObject.put("resourceName", eValue) + } + } + + allResources.put(jObject) + msoLogger.info("allResources: " + allResources) + + serviceResources.put(jObject) + msoLogger.info("serviceResources: " + serviceResources) + } + else if (StringUtils.equalsIgnoreCase(relatedTo, "configuration")) { + msoLogger.info("configuration ") + JSONObject jObject = new JSONObject() + + //relationship-data + String rsDataStr = jsonUtil.getJsonValue(relation, "relationship-data") + msoLogger.info("rsDataStr: " + rsDataStr) + List<String> rsDataList = jsonUtil.StringArrayToList(execution, rsDataStr) + msoLogger.info("rsDataList: " + rsDataList) + for (String rsData : rsDataList) { + msoLogger.info("rsData: " + rsData) + def eKey = jsonUtil.getJsonValue(rsData, "relationship-key") + def eValue = jsonUtil.getJsonValue(rsData, "relationship-value") + if(eKey.equals("configuration.configuration-id")){ + jObject.put("resourceInstanceId", eValue) + } + } + + + //related-to-property + String rPropertyStr = jsonUtil.getJsonValue(relation, "related-to-property") + msoLogger.info("related-to-property: " + rPropertyStr) + if (rPropertyStr instanceof JSONArray){ + List<String> rPropertyList = jsonUtil.StringArrayToList(execution, rPropertyStr) + for(String rProperty : rPropertyList){ + msoLogger.info("rProperty: " + rProperty) + def eKey = jsonUtil.getJsonValue(rProperty, "property-key") + def eValue = jsonUtil.getJsonValue(rProperty, "property-value") + if(eKey.equals("configuration.configuration-type")){ + jObject.put("resourceType", eValue) + } + } + } + else { + String rProperty = rPropertyStr + msoLogger.info("rProperty: " + rProperty) + def eKey = jsonUtil.getJsonValue(rProperty, "property-key") + def eValue = jsonUtil.getJsonValue(rProperty, "property-value") + if(eKey.equals("configuration.configuration-type")){ + jObject.put("resourceType", eValue) + } + } + allResources.put(jObject) + msoLogger.info("allResources: " + allResources) + + networkResources.put(jObject) + msoLogger.info("networkResources: " + networkResources) + } + msoLogger.info("Get Next releation resource " ) + + } + msoLogger.info("Get releation finished. " ) + } + + execution.setVariable("serviceRelationShip", allResources.toString()) + msoLogger.info("allResources: " + allResources.toString()) + String serviceRelationShip = execution.getVariable("serviceRelationShip") + msoLogger.info("serviceRelationShip: " + serviceRelationShip) + if ((! isBlank(serviceRelationShip)) && (! serviceRelationShip.isEmpty())) { + + List<String> relationShipList = jsonUtil.StringArrayToList(execution, serviceRelationShip) + msoLogger.info("relationShipList: " + relationShipList) + execution.setVariable(Prefix+"resourceList", relationShipList) + + int resourceCount = relationShipList.size() + msoLogger.info("resourceCount: " + resourceCount) + execution.setVariable(Prefix+"resourceCount",resourceCount ) + + int resourceNum = 0 + execution.setVariable(Prefix+"nextResource", resourceNum) + msoLogger.info("start sort delete resource: ") + sortDeleteResource(execution) + + + if (resourceNum < resourceCount) { + execution.setVariable(Prefix+"resourceFinish", false) + } + else { + execution.setVariable(Prefix+"resourceFinish", true) + } + msoLogger.info("Resource list set end : " + resourceCount) + } + + execution.setVariable("serviceResources", serviceResources.toString()) + msoLogger.info("serviceResources: " + serviceResources) + String serviceResourcesShip = execution.getVariable("serviceResources") + msoLogger.info("serviceResourcesShip: " + serviceResourcesShip) + + if ((! isBlank(serviceResourcesShip)) && (! serviceResourcesShip.isEmpty())) { + List<String> serviceResourcesList = jsonUtil.StringArrayToList(execution, serviceResourcesShip) + msoLogger.info("serviceResourcesList: " + serviceResourcesList) + execution.setVariable(Prefix+"serviceResourceList", serviceResourcesList) + execution.setVariable(Prefix+"serviceResourceCount", serviceResourcesList.size()) + execution.setVariable(Prefix+"nextServiceResource", 0) + msoLogger.info("Service Resource list set end : " + serviceResourcesList.size()) + + } + + execution.setVariable("allottedResources", allottedResources.toString()) + msoLogger.info("allottedResources: " + allottedResources) + String allottedResourcesShip = execution.getVariable("allottedResources") + msoLogger.info("allottedResourcesShip: " + allottedResourcesShip) + if ((! isBlank(allottedResourcesShip)) && (! allottedResourcesShip.isEmpty())) { + List<String> allottedResourcesList = jsonUtil.StringArrayToList(execution, allottedResourcesShip) + msoLogger.info("allottedResourcesList: " + allottedResourcesList) + execution.setVariable(Prefix+"allottedResourcesList", allottedResourcesList) + execution.setVariable(Prefix+"allottedResourcesListCount", allottedResourcesList.size()) + execution.setVariable(Prefix+"nextAllottedResourcesList", 0) + msoLogger.info("Allotted Resource list set end : " + allottedResourcesList.size()) + + } + execution.setVariable("networkResources", networkResources.toString()) + msoLogger.info("networkResources: " + networkResources) + String networkResourcesShip = execution.getVariable("networkResources") + msoLogger.info("networkResourcesShip: " + networkResourcesShip) + if ((! isBlank(networkResourcesShip)) && (! networkResourcesShip.isEmpty())) { + List<String> networkResourcesList = jsonUtil.StringArrayToList(execution, networkResourcesShip) + msoLogger.info("networkResourcesList: " + networkResourcesList) + execution.setVariable(Prefix+"networkResourcesList", networkResourcesList) + execution.setVariable(Prefix+"networkResourcesListCount", networkResourcesList.size()) + execution.setVariable(Prefix+"nextNetworkResourcesList", 0) + msoLogger.info("Network Resource list set end : " + networkResourcesList.size()) + + } + } + } catch (BpmnError e){ + throw e; + } catch (Exception ex) { + String exceptionMessage = "Bpmn error encountered in DeleteMobileAPNCustService flow. prepareServiceDeleteResource() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + } + msoLogger.info("Exited " + method) + } + + private String getAaiAr(DelegateExecution execution, String relink) { + def method = getClass().getSimpleName() + '.getAaiAr(' +'execution=' + execution.getId() +')' + msoLogger.info("Entered " + method) + AaiUtil aaiUtil = new AaiUtil(this) + String aaiEndpoint = execution.getVariable("URN_aai_endpoint") + relink + + msoLogger.debug("get AR info " + aaiEndpoint) + APIResponse response = aaiUtil.executeAAIGetCall(execution, aaiEndpoint) + + int responseCode = response.getStatusCode() + msoLogger.debug("get AR info responseCode:" + responseCode) + + String aaiResponse = response.getResponseBodyAsString() + msoLogger.debug("get AR info " + aaiResponse) + + if(responseCode < 200 || responseCode >= 300 || isBlank(aaiResponse)) { + return null + } + + msoLogger.info("Exited " + method) + return aaiResponse + } + /** + * prepare Decompose next resource to create request + */ + public void preProcessDecomposeNextResource(DelegateExecution execution){ + def method = getClass().getSimpleName() + '.getAaiAr(' +'execution=' + execution.getId() +')' + msoLogger.info("Entered " + method) + msoLogger.trace("STARTED preProcessDecomposeNextResource Process ") + try{ + int resourceNum = execution.getVariable(Prefix+"nextServiceResource") + List<String> serviceResourceList = execution.getVariable(Prefix+"serviceResourceList") + msoLogger.info("Service Resource List : " + serviceResourceList) + + String serviceResource = serviceResourceList[resourceNum] + execution.setVariable(Prefix+"serviceResource", serviceResource) + msoLogger.info("Current Service Resource : " + serviceResource) + + String resourceType = jsonUtil.getJsonValue(serviceResource, "resourceType") + execution.setVariable("resourceType", resourceType) + msoLogger.info("resourceType : " + resourceType) + + String resourceInstanceId = jsonUtil.getJsonValue(serviceResource, "resourceInstanceId") + execution.setVariable("resourceInstanceId", resourceInstanceId) + msoLogger.info("resourceInstanceId : " + resourceInstanceId) + + String resourceRole = jsonUtil.getJsonValue(serviceResource, "resourceRole") + execution.setVariable("resourceRole", resourceRole) + msoLogger.info("resourceRole : " + resourceRole) + + String resourceVersion = jsonUtil.getJsonValue(serviceResource, "resourceVersion") + execution.setVariable("resourceVersion", resourceVersion) + msoLogger.info("resourceVersion : " + resourceVersion) + + String resourceName = jsonUtil.getJsonValue(serviceResource, "resourceName") + if (isBlank(resourceName)){ + resourceName = resourceInstanceId + } + execution.setVariable(Prefix+"resourceName", resourceName) + msoLogger.info("resource Name : " + resourceName) + + + execution.setVariable(Prefix+"nextServiceResource", resourceNum + 1) + + int serviceResourceCount = execution.getVariable(Prefix+"serviceResourceCount") + if (serviceResourceCount >0 ){ + int progress = (resourceNum*100) / serviceResourceCount + execution.setVariable("progress", progress.toString() ) + } + execution.setVariable("operationStatus", resourceName ) + + }catch(Exception e){ + // try error in method block + String exceptionMessage = "Bpmn error encountered in CreateMobileAPNCustService flow. Unexpected Error from method preProcessDecomposeNextResource() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + } + msoLogger.info("Exited " + method) + } + /** + * post Decompose next resource to create request + */ + public void postProcessDecomposeNextResource(DelegateExecution execution){ + def method = getClass().getSimpleName() + '.postProcessDecomposeNextResource(' +'execution=' + execution.getId() +')' + msoLogger.info("Entered " + method) + msoLogger.trace("STARTED postProcessDecomposeNextResource Process ") + try{ + String resourceName = execution.getVariable(Prefix+"resourceName") + int resourceNum = execution.getVariable(Prefix+"nextServiceResource") + msoLogger.debug("Current Resource count:"+ execution.getVariable(Prefix+"nextServiceResource")) + + int resourceCount = execution.getVariable(Prefix+"serviceResourceCount") + msoLogger.debug("Total Resource count:"+ execution.getVariable(Prefix+"serviceResourceCount")) + + if (resourceNum < resourceCount) { + execution.setVariable(Prefix+"resourceFinish", false) + } + else { + execution.setVariable(Prefix+"resourceFinish", true) + } + + msoLogger.debug("Resource Finished:"+ execution.getVariable(Prefix+"resourceFinish")) + + if (resourceCount >0 ){ + int progress = (resourceNum*100) / resourceCount + + execution.setVariable("progress", progress.toString() ) + msoLogger.trace(":"+ execution.getVariable("")) + } + execution.setVariable("operationStatus", resourceName ) + + + }catch(Exception e){ + // try error in method block + String exceptionMessage = "Bpmn error encountered in CreateMobileAPNCustService flow. Unexpected Error from method postProcessDecomposeNextResource() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + } + msoLogger.info("Exited " + method) + } + /** + * prepare post Unkown Resource Type + */ + public void postOtherControllerType(DelegateExecution execution){ + def method = getClass().getSimpleName() + '.postOtherControllerType(' +'execution=' + execution.getId() +')' + def isDebugEnabled = execution.getVariable("isDebugEnabled") + msoLogger.info("Entered " + method) + + try{ + + String resourceName = execution.getVariable(Prefix+"resourceName") + String resourceType = execution.getVariable(Prefix+"resourceType") + String controllerType = execution.getVariable("controllerType") + + String msg = "Resource name: "+ resourceName + " resource Type: " + resourceType+ " controller Type: " + controllerType + " can not be processed n the workflow" + msoLogger.debug(msg) + + }catch(Exception e){ + // try error in method block + String exceptionMessage = "Bpmn error encountered in DoCreateMobileAPNServiceInstance flow. Unexpected Error from method postOtherControllerType() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + } + msoLogger.info("Exited " + method) + } + + /** + * prepare delete parameters + */ + public void preSDNCResourceDelete(execution, resourceName){ + // we use resource instance ids for delete flow as resourceTemplateUUIDs + + def method = getClass().getSimpleName() + '.preSDNCResourceDelete(' +'execution=' + execution.getId() +')' + msoLogger.info("Entered " + method) + + msoLogger.trace("STARTED preSDNCResourceDelete Process ") + String networkResources = execution.getVariable("networkResources") + + + execution.setVariable("foundResource", false) + if (networkResources != null) { + def jsonSlurper = new JsonSlurper() + List relationShipList = jsonSlurper.parseText(networkResources) + relationShipList.each { + if(StringUtils.containsIgnoreCase(it.resourceType, resourceName)) { + String resourceInstanceUUID = it.resourceInstanceId + String resourceTemplateUUID = it.resourceInstanceId + execution.setVariable("resourceTemplateId", resourceTemplateUUID) + execution.setVariable("resourceInstanceId", resourceInstanceUUID) + execution.setVariable("resourceType", resourceName) + execution.setVariable("foundResource", true) + msoLogger.info("Delete Resource Info resourceTemplate Id :" + resourceTemplateUUID + " resourceInstanceId: " + resourceInstanceUUID + " resourceType: " + resourceName) + } + } + } + msoLogger.info("Exited " + method) + } + public void preProcessSDNCDelete (DelegateExecution execution) { + def method = getClass().getSimpleName() + '.preProcessSDNCDelete(' +'execution=' + execution.getId() +')' + msoLogger.info("Entered " + method) + msoLogger.trace("preProcessSDNCDelete ") + String msg = "" + + try { + def serviceInstanceId = execution.getVariable("serviceInstanceId") + def serviceInstanceName = execution.getVariable("serviceInstanceName") + def callbackURL = execution.getVariable("sdncCallbackUrl") + def requestId = execution.getVariable("msoRequestId") + def serviceId = execution.getVariable("productFamilyId") + def subscriptionServiceType = execution.getVariable("subscriptionServiceType") + def globalSubscriberId = execution.getVariable("globalSubscriberId") //globalCustomerId + + String serviceModelInfo = execution.getVariable("serviceModelInfo") + def modelInvariantUuid = "" + def modelVersion = "" + def modelUuid = "" + def modelName = "" + if (!isBlank(serviceModelInfo)) + { + modelInvariantUuid = jsonUtil.getJsonValue(serviceModelInfo, "modelInvariantUuid") + modelVersion = jsonUtil.getJsonValue(serviceModelInfo, "modelVersion") + modelUuid = jsonUtil.getJsonValue(serviceModelInfo, "modelUuid") + modelName = jsonUtil.getJsonValue(serviceModelInfo, "modelName") + + if (modelInvariantUuid == null) { + modelInvariantUuid = "" + } + if (modelVersion == null) { + modelVersion = "" + } + if (modelUuid == null) { + modelUuid = "" + } + if (modelName == null) { + modelName = "" + } + } + if (serviceInstanceName == null) { + serviceInstanceName = "" + } + if (serviceId == null) { + serviceId = "" + } + + def siParamsXml = execution.getVariable("siParamsXml") + def serviceType = execution.getVariable("serviceType") + if (serviceType == null) + { + serviceType = "" + } + + def sdncRequestId = UUID.randomUUID().toString() + + String sdncDelete = + """<sdncadapterworkflow:SDNCAdapterWorkflowRequest xmlns:ns5="http://org.onap/so/request/types/v1" + xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1" + xmlns:sdncadapter="http://org.onap/workflow/sdnc/adapter/schema/v1"> + <sdncadapter:RequestHeader> + <sdncadapter:RequestId>${MsoUtils.xmlEscape(sdncRequestId)}</sdncadapter:RequestId> + <sdncadapter:SvcInstanceId>${MsoUtils.xmlEscape(serviceInstanceId)}</sdncadapter:SvcInstanceId> + <sdncadapter:SvcAction>delete</sdncadapter:SvcAction> + <sdncadapter:SvcOperation>service-topology-operation</sdncadapter:SvcOperation> + <sdncadapter:CallbackUrl>${MsoUtils.xmlEscape(callbackURL)}</sdncadapter:CallbackUrl> + <sdncadapter:MsoAction>${MsoUtils.xmlEscape(serviceType)}</sdncadapter:MsoAction> + </sdncadapter:RequestHeader> + <sdncadapterworkflow:SDNCRequestData> + <request-information> + <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> + <source>MSO</source> + <notification-url/> + <order-number/> + <order-version/> + <request-action>DeleteServiceInstance</request-action> + </request-information> + <service-information> + <service-id>${MsoUtils.xmlEscape(serviceId)}</service-id> + <subscription-service-type>${MsoUtils.xmlEscape(subscriptionServiceType)}</subscription-service-type> + <onap-model-information> + <model-invariant-uuid>${MsoUtils.xmlEscape(modelInvariantUuid)}</model-invariant-uuid> + <model-uuid>${MsoUtils.xmlEscape(modelUuid)}</model-uuid> + <model-version>${MsoUtils.xmlEscape(modelVersion)}</model-version> + <model-name>${MsoUtils.xmlEscape(modelName)}</model-name> + </onap-model-information> + <service-instance-id>${MsoUtils.xmlEscape(serviceInstanceId)}</service-instance-id> + <subscriber-name/> + <global-customer-id>${MsoUtils.xmlEscape(globalSubscriberId)}</global-customer-id> + </service-information> + <service-request-input> + <service-instance-name>${MsoUtils.xmlEscape(serviceInstanceName)}</service-instance-name> + ${siParamsXml} + </service-request-input> + </sdncadapterworkflow:SDNCRequestData> + </sdncadapterworkflow:SDNCAdapterWorkflowRequest>""" + + sdncDelete = utils.formatXml(sdncDelete) + def sdncRequestId2 = UUID.randomUUID().toString() + String sdncDeactivate = sdncDelete.replace(">delete<", ">deactivate<").replace(">${sdncRequestId}<", ">${sdncRequestId2}<") + execution.setVariable("sdncDelete", sdncDelete) + execution.setVariable("sdncDeactivate", sdncDeactivate) + msoLogger.info("sdncDeactivate:\n" + sdncDeactivate) + msoLogger.info("sdncDelete:\n" + sdncDelete) + + } catch (BpmnError e) { + throw e; + } catch(Exception ex) { + msg = "Exception in preProcessSDNCDelete. " + ex.getMessage() + msoLogger.info(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, "Exception Occured in preProcessSDNCDelete.\n" + ex.getMessage()) + } + msoLogger.info("Exited " + method) + } + + public void postProcessSDNCDelete(DelegateExecution execution, String response, String action) { + + def method = getClass().getSimpleName() + '.postProcessSDNCDelete(' +'execution=' + execution.getId() +')' + msoLogger.info("Entered " + method) + msoLogger.trace("postProcessSDNC " + action + " ") + String msg = "" + + /*try { + WorkflowException workflowException = execution.getVariable("WorkflowException") + boolean successIndicator = execution.getVariable("SDNCA_SuccessIndicator") + msoLogger.info("SDNCResponse: " + response) + msoLogger.info("workflowException: " + workflowException) + + SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this) + sdncAdapterUtils.validateSDNCResponse(execution, response, workflowException, successIndicator) + if(execution.getVariable(Prefix + 'sdncResponseSuccess') == "true"){ + msoLogger.info("Good response from SDNC Adapter for service-instance " + action + "response:\n" + response) + + }else{ + msg = "Bad Response from SDNC Adapter for service-instance " + action + msoLogger.info(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 3500, msg) + } + } catch (BpmnError e) { + throw e; + } catch(Exception ex) { + msg = "Exception in postProcessSDNC " + action + " Exception:" + ex.getMessage() + msoLogger.info(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + }*/ + msoLogger.info("Exited " + method) + } + + /** + * Init the service Operation Status + */ + public void preUpdateServiceOperationStatus(DelegateExecution execution){ + def method = getClass().getSimpleName() + '.preUpdateServiceOperationStatus(' +'execution=' + execution.getId() +')' + msoLogger.info("Entered " + method) + + try{ + String serviceId = execution.getVariable("serviceInstanceId") + String operationId = execution.getVariable("operationId") + String serviceName = execution.getVariable("serviceInstanceName") + String operationType = "DELETE" + String userId = "" + String result = "processing" + String progress = execution.getVariable("progress") + msoLogger.info("progress: " + progress ) + if ("100".equalsIgnoreCase(progress)) + { + result = "finished" + } + String reason = "" + String operationContent = "Prepare service delete: " + execution.getVariable("operationStatus") + msoLogger.info("Generated new operation for Service Instance serviceId:" + serviceId + " operationId:" + operationId) + serviceId = UriUtils.encode(serviceId,"UTF-8") + execution.setVariable("serviceInstanceId", serviceId) + execution.setVariable("operationId", operationId) + execution.setVariable("operationType", operationType) + + def dbAdapterEndpoint = execution.getVariable("URN_mso_adapters_openecomp_db_endpoint") + execution.setVariable("CVFMI_dbAdapterEndpoint", dbAdapterEndpoint) + msoLogger.info("DB Adapter Endpoint is: " + dbAdapterEndpoint) + + execution.setVariable("URN_mso_openecomp_adapters_db_endpoint","http://mso.mso.testlab.openecomp.org:8080/dbadapters/RequestsDbAdapter") + + String payload = + """<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" + xmlns:ns="http://org.onap.so/requestsdb"> + <soapenv:Header/> + <soapenv:Body> + <ns:updateServiceOperationStatus xmlns:ns="http://org.onap.so/requestsdb"> + <serviceId>${MsoUtils.xmlEscape(serviceId)}</serviceId> + <operationId>${MsoUtils.xmlEscape(operationId)}</operationId> + <serviceName>${MsoUtils.xmlEscape(serviceName)}</serviceName> + <operationType>${MsoUtils.xmlEscape(operationType)}</operationType> + <userId>${MsoUtils.xmlEscape(userId)}</userId> + <result>${MsoUtils.xmlEscape(result)}</result> + <operationContent>${MsoUtils.xmlEscape(operationContent)}</operationContent> + <progress>${MsoUtils.xmlEscape(progress)}</progress> + <reason>${MsoUtils.xmlEscape(reason)}</reason> + </ns:updateServiceOperationStatus> + </soapenv:Body> + </soapenv:Envelope>""" + + payload = utils.formatXml(payload) + execution.setVariable("CVFMI_updateServiceOperStatusRequest", payload) + msoLogger.info("Outgoing preUpdateServiceOperationStatus: \n" + payload) + + + }catch(Exception e){ + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception Occured Processing preUpdateServiceOperationStatus.", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e); + execution.setVariable("CVFMI_ErrorResponse", "Error Occurred during preUpdateServiceOperationStatus Method:\n" + e.getMessage()) + } + msoLogger.trace("COMPLETED preUpdateServiceOperationStatus Process ") + msoLogger.info("Exited " + method) + } + + public void preInitResourcesOperStatus(DelegateExecution execution){ + def method = getClass().getSimpleName() + '.preInitResourcesOperStatus(' +'execution=' + execution.getId() +')' + msoLogger.info("Entered " + method) + + msoLogger.trace("STARTED preInitResourcesOperStatus Process ") + String msg="" + try{ + String serviceId = execution.getVariable("serviceInstanceId") + String operationId = execution.getVariable("operationId") + String operationType = "DELETE" + String resourceTemplateUUIDs = "" + String result = "processing" + String progress = "0" + String reason = "" + String operationContent = "Prepare service delete" + msoLogger.info("Generated new operation for Service Instance serviceId:" + serviceId + " operationId:" + operationId + " operationType:" + operationType) + serviceId = UriUtils.encode(serviceId,"UTF-8") + execution.setVariable("serviceInstanceId", serviceId) + execution.setVariable("operationId", operationId) + execution.setVariable("operationType", operationType) + + String serviceRelationShip = execution.getVariable("serviceRelationShip") + msoLogger.info("serviceRelationShip: " + serviceRelationShip) + if (! isBlank(serviceRelationShip)) { + def jsonSlurper = new JsonSlurper() + def jsonOutput = new JsonOutput() + List relationShipList = jsonSlurper.parseText(serviceRelationShip) + + if (relationShipList != null) { + relationShipList.each { + resourceTemplateUUIDs = resourceTemplateUUIDs + it.resourceInstanceId + ":" + } + } + } + def dbAdapterEndpoint = "http://mso.mso.testlab.openecomp.org:8080/dbadapters/RequestsDbAdapter" + execution.setVariable("CVFMI_dbAdapterEndpoint", dbAdapterEndpoint) + msoLogger.info("DB Adapter Endpoint is: " + dbAdapterEndpoint) + + String payload = + """<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" + xmlns:ns="http://org.onap.so/requestsdb"> + <soapenv:Header/> + <soapenv:Body> + <ns:initResourceOperationStatus xmlns:ns="http://org.onap.so/requestsdb"> + <serviceId>${MsoUtils.xmlEscape(serviceId)}</serviceId> + <operationId>${MsoUtils.xmlEscape(operationId)}</operationId> + <operationType>${MsoUtils.xmlEscape(operationType)}</operationType> + <resourceTemplateUUIDs>${MsoUtils.xmlEscape(resourceTemplateUUIDs)}</resourceTemplateUUIDs> + </ns:initResourceOperationStatus> + </soapenv:Body> + </soapenv:Envelope>""" + + payload = utils.formatXml(payload) + execution.setVariable("CVFMI_initResOperStatusRequest", payload) + msoLogger.info("Outgoing initResourceOperationStatus: \n" + payload) + msoLogger.debug("DoCustomDeleteE2EServiceInstanceV2 Outgoing initResourceOperationStatus Request: " + payload) + + }catch (BpmnError e) { + throw e; + } catch (Exception ex) { + msg = "Exception in DoCustomDeleteE2EServiceInstanceV2.preInitResourcesOperStatus. " + ex.getMessage() + msoLogger.info(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.info("Exited " + method) + } + + + + /** + * prepare delete parameters + */ + public void preProcessVFCResourceDelete(execution){ + // we use resource instance ids for delete flow as resourceTemplateUUIDs + + def method = getClass().getSimpleName() + '.preProcessVFCResourceDelete(' +'execution=' + execution.getId() +')' + msoLogger.info("Entered " + method) + + msoLogger.trace("STARTED preProcessVFCResourceDelete Process ") + try{ + String serviceResource = execution.getVariable("serviceResource") + msoLogger.info("serviceResource : " + serviceResource) + + String resourceInstanceId = execution.getVariable("resourceInstanceId") + msoLogger.info("resourceInstanceId : " + resourceInstanceId) + + execution.setVariable("resourceTemplateId", resourceInstanceId) + msoLogger.info("resourceTemplateId : " + resourceInstanceId) + + String resourceType = execution.getVariable("resourceType") + msoLogger.info("resourceType : " + resourceType) + + + String resourceName = execution.getVariable(Prefix+"resourceName") + if (isBlank(resourceName)){ + resourceName = resourceInstanceId + } + execution.setVariable("resourceName", resourceName) + msoLogger.info("resource Name : " + resourceName) + + msoLogger.info("Delete Resource Info: resourceInstanceId :" + resourceInstanceId + " resourceTemplateId: " + resourceInstanceId + " resourceType: " + resourceType) + }catch (BpmnError e) { + throw e; + } catch (Exception ex) { + msg = "Exception in DoDeleteE2EServiceInstance.preProcessVFCResourceDelete. " + ex.getMessage() + msoLogger.info(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.info("Exited " + method) + } + + public void postProcessVFCDelete(DelegateExecution execution, String response, String action) { + def method = getClass().getSimpleName() + '.postProcessVFCDelete(' +'execution=' + execution.getId() +')' + msoLogger.info("Entered " + method) + + msoLogger.trace("STARTED postProcessVFCDelete Process ") + try{ + + }catch (BpmnError e) { + throw e; + } catch (Exception ex) { + msg = "Exception in DoDeleteE2EServiceInstance.postProcessVFCDelete. " + ex.getMessage() + msoLogger.info(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.info("Exited " + method) + } +} + diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteE2EServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteE2EServiceInstance.groovy new file mode 100644 index 0000000000..6d23ae7c65 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteE2EServiceInstance.groovy @@ -0,0 +1,500 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2018 Huawei Technologies Co., Ltd. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.so.bpmn.infrastructure.scripts + +import static org.apache.commons.lang3.StringUtils.*; + +import javax.xml.parsers.DocumentBuilder +import javax.xml.parsers.DocumentBuilderFactory + +import org.apache.commons.lang3.* +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.json.JSONArray +import org.json.JSONObject; +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.onap.so.bpmn.common.scripts.ExceptionUtil +import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.bpmn.core.domain.Resource +import org.onap.so.bpmn.core.domain.ServiceDecomposition; +import org.onap.so.bpmn.core.json.JsonUtils +import org.springframework.web.util.UriUtils; +import org.w3c.dom.Document +import org.w3c.dom.Element +import org.w3c.dom.Node +import org.w3c.dom.NodeList +import org.xml.sax.InputSource + +import groovy.json.* + +/** + * This groovy class supports the <class>DoDeleteE2EServiceInstance.bpmn</class> process. + * + * Inputs: + * @param - msoRequestId + * @param - globalSubscriberId - O + * @param - subscriptionServiceType - O + * @param - serviceInstanceId + * @param - serviceInstanceName - O + * @param - serviceInputParams (should contain aic_zone for serviceTypes TRANSPORT,ATM) + * @param - sdncVersion + * @param - failNotFound - TODO + * @param - serviceInputParams - TODO + * + * @param - delResourceList + * @param - serviceRelationShip + * + * Outputs: + * @param - WorkflowException + * + * Rollback - Deferred + */ +public class DoDeleteE2EServiceInstance extends AbstractServiceTaskProcessor { + + String Prefix="DDEESI_" + ExceptionUtil exceptionUtil = new ExceptionUtil() + JsonUtils jsonUtil = new JsonUtils() + + public void preProcessRequest (DelegateExecution execution) { + def isDebugEnabled = execution.getVariable("isDebugLogEnabled") + utils.log("INFO"," ***** preProcessRequest *****", isDebugEnabled) + String msg = "" + + try { + String requestId = execution.getVariable("msoRequestId") + execution.setVariable("prefix",Prefix) + + //Inputs + //requestDetails.subscriberInfo. for AAI GET & PUT & SDNC assignToplology + String globalSubscriberId = execution.getVariable("globalSubscriberId") //globalCustomerId + if (globalSubscriberId == null) + { + execution.setVariable("globalSubscriberId", "") + } + + //requestDetails.requestParameters. for AAI PUT & SDNC assignTopology + String serviceType = execution.getVariable("serviceType") + if (serviceType == null) + { + execution.setVariable("serviceType", "") + } + + //Generated in parent for AAI PUT + String serviceInstanceId = execution.getVariable("serviceInstanceId") + if (isBlank(serviceInstanceId)){ + msg = "Input serviceInstanceId is null" + utils.log("INFO", msg, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + + String sdncCallbackUrl = execution.getVariable('URN_mso_workflow_sdncadapter_callback') + if (isBlank(sdncCallbackUrl)) { + msg = "URN_mso_workflow_sdncadapter_callback is null" + utils.log("INFO", msg, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + execution.setVariable("sdncCallbackUrl", sdncCallbackUrl) + utils.log("INFO","SDNC Callback URL: " + sdncCallbackUrl, isDebugEnabled) + + StringBuilder sbParams = new StringBuilder() + Map<String, String> paramsMap = execution.getVariable("serviceInputParams") + if (paramsMap != null) + { + sbParams.append("<service-input-parameters>") + for (Map.Entry<String, String> entry : paramsMap.entrySet()) { + String paramsXml + String paramName = entry.getKey() + String paramValue = entry.getValue() + paramsXml = + """ <param> + <name>${MsoUtils.xmlEscape(paramName)}</name> + <value>${MsoUtils.xmlEscape(paramValue)}</value> + </param> + """ + sbParams.append(paramsXml) + } + sbParams.append("</service-input-parameters>") + } + String siParamsXml = sbParams.toString() + if (siParamsXml == null) + siParamsXml = "" + execution.setVariable("siParamsXml", siParamsXml) + + } catch (BpmnError e) { + throw e; + } catch (Exception ex){ + msg = "Exception in preProcessRequest " + ex.getMessage() + utils.log("INFO", msg, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + utils.log("INFO"," ***** Exit preProcessRequest *****", isDebugEnabled) + } + + public void postProcessAAIGET(DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + utils.log("INFO"," ***** postProcessAAIGET ***** ", isDebugEnabled) + String msg = "" + + try { + String serviceInstanceId = execution.getVariable("serviceInstanceId") + boolean foundInAAI = execution.getVariable("GENGS_FoundIndicator") + String serviceType = "" + + if(foundInAAI){ + utils.log("INFO","Found Service-instance in AAI", isDebugEnabled) + + String siData = execution.getVariable("GENGS_service") + utils.log("INFO", "SI Data", isDebugEnabled) + if (isBlank(siData)) + { + msg = "Could not retrive ServiceInstance data from AAI to delete id:" + serviceInstanceId + utils.log("INFO", msg, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + else + { + InputSource source = new InputSource(new StringReader(siData)); + DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder docBuilder = docFactory.newDocumentBuilder() + Document serviceXml = docBuilder.parse(source) + serviceXml.getDocumentElement().normalize() + // get model invariant id + // Get Template uuid and version + if (utils.nodeExists(siData, "model-invariant-id") && utils.nodeExists(siData, "model-version-id") ) { + utils.log("INFO", "SI Data model-invariant-id and model-version-id exist:", isDebugEnabled) + def modelInvariantId = serviceXml.getElementsByTagName("model-invariant-id").item(0).getTextContent() + def modelVersionId = serviceXml.getElementsByTagName("model-version-id").item(0).getTextContent() + + // Set Original Template info + execution.setVariable("model-invariant-id-original", modelInvariantId) + execution.setVariable("model-version-id-original", modelVersionId) + } + + utils.log("INFO", "SI Data" + siData, isDebugEnabled) + //Confirm there are no related service instances (vnf/network or volume) + if (utils.nodeExists(siData, "relationship-list")) { + utils.log("INFO", "SI Data relationship-list exists:", isDebugEnabled) + JSONArray jArray = new JSONArray() + + XmlParser xmlParser = new XmlParser() + Node root = xmlParser.parseText(siData) + def relation_list = utils.getChildNode(root, 'relationship-list') + def relationships = utils.getIdenticalChildren(relation_list, 'relationship') + + for (def relation: relationships) { + def jObj = getRelationShipData(relation, isDebugEnabled) + jArray.put(jObj) + } + + execution.setVariable("serviceRelationShip", jArray.toString()) + +// //test(siData) +// NodeList nodeList = serviceXml.getElementsByTagName("relationship") +// JSONArray jArray = new JSONArray() +// for (int x = 0; x < nodeList.getLength(); x++) { +// Node node = nodeList.item(x) +// if (node.getNodeType() == Node.ELEMENT_NODE) { +// Element eElement = (Element) node +// def e = eElement.getElementsByTagName("related-to").item(0).getTextContent() //for ns +// if(e.equals("service-instance")){ +// def relatedObject = eElement.getElementsByTagName("related-link").item(0).getTextContent() +// utils.log("INFO", "ServiceInstance Related NS :" + relatedObject, isDebugEnabled) +// NodeList dataList = node.getChildNodes() +// if(null != dataList) { +// JSONObject jObj = new JSONObject() +// for (int i = 0; i < dataList.getLength(); i++) { +// Node dNode = dataList.item(i) +// if(dNode.getNodeName() == "relationship-data") { +// Element rDataEle = (Element)dNode +// def eKey = rDataEle.getElementsByTagName("relationship-key").item(0).getTextContent() +// def eValue = rDataEle.getElementsByTagName("relationship-value").item(0).getTextContent() +// if(eKey.equals("service-instance.service-instance-id")){ +// jObj.put("resourceInstanceId", eValue) +// } +// +// } +// else if(dNode.getNodeName() == "related-to-property"){ +// Element rDataEle = (Element)dNode +// def eKey = rDataEle.getElementsByTagName("property-key").item(0).getTextContent() +// def eValue = rDataEle.getElementsByTagName("property-value").item(0).getTextContent() +// if(eKey.equals("service-instance.service-instance-name")){ +// jObj.put("resourceType", eValue) +// } +// } +// } +// utils.log("INFO", "Relationship related to Resource:" + jObj.toString(), isDebugEnabled) +// jArray.put(jObj) +// } +// //for overlay/underlay +// }else if (e.equals("configuration")){ +// def relatedObject = eElement.getElementsByTagName("related-link").item(0).getTextContent() +// utils.log("INFO", "ServiceInstance Related Configuration :" + relatedObject, isDebugEnabled) +// NodeList dataList = node.getChildNodes() +// if(null != dataList) { +// JSONObject jObj = new JSONObject() +// for (int i = 0; i < dataList.getLength(); i++) { +// Node dNode = dataList.item(i) +// if(dNode.getNodeName() == "relationship-data") { +// Element rDataEle = (Element)dNode +// def eKey = rDataEle.getElementsByTagName("relationship-key").item(0).getTextContent() +// def eValue = rDataEle.getElementsByTagName("relationship-value").item(0).getTextContent() +// if(eKey.equals("configuration.configuration-id")){ +// jObj.put("resourceInstanceId", eValue) +// } +// } +// else if(dNode.getNodeName() == "related-to-property"){ +// Element rDataEle = (Element)dNode +// def eKey = rDataEle.getElementsByTagName("property-key").item(0).getTextContent() +// def eValue = rDataEle.getElementsByTagName("property-value").item(0).getTextContent() +// if(eKey.equals("configuration.configuration-type")){ +// jObj.put("resourceType", eValue) +// } +// } +// } +// utils.log("INFO", "Relationship related to Resource:" + jObj.toString(), isDebugEnabled) +// jArray.put(jObj) +// } +// // for SP-Partner +// }else if (e.equals("sp-partner")){ +// +// } +// } +// } +// execution.setVariable("serviceRelationShip", jArray.toString()) + } + } + }else{ + boolean succInAAI = execution.getVariable("GENGS_SuccessIndicator") + if(!succInAAI){ + utils.log("INFO","Error getting Service-instance from AAI", + serviceInstanceId, isDebugEnabled) + WorkflowException workflowException = execution.getVariable("WorkflowException") + utils.logAudit("workflowException: " + workflowException) + if(workflowException != null){ + exceptionUtil.buildAndThrowWorkflowException(execution, workflowException.getErrorCode(), workflowException.getErrorMessage()) + } + else + { + msg = "Failure in postProcessAAIGET GENGS_SuccessIndicator:" + succInAAI + utils.log("INFO", msg, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg) + } + } + + utils.log("INFO","Service-instance NOT found in AAI. Silent Success", isDebugEnabled) + } + }catch (BpmnError e) { + throw e; + } catch (Exception ex) { + msg = "Exception in DoDeleteE2EServiceInstance.postProcessAAIGET. " + ex.getMessage() + utils.log("INFO", msg, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + utils.log("INFO"," *** Exit postProcessAAIGET *** ", isDebugEnabled) + } + + private JSONObject getRelationShipData(node, isDebugEnabled){ + JSONObject jObj = new JSONObject() + + def relation = utils.nodeToString(node) + def rt = utils.getNodeText1(relation, "related-to") + + def rl = utils.getNodeText1(relation, "related-link") + utils.log("INFO", "ServiceInstance Related NS/Configuration :" + rl, isDebugEnabled) + + def rl_datas = utils.getIdenticalChildren(node, "relationship-data") + for(def rl_data : rl_datas) { + def eKey = utils.getChildNodeText(rl_data, "relationship-key") + def eValue = utils.getChildNodeText(rl_data, "relationship-value") + + if ((rt == "service-instance" && eKey.equals("service-instance.service-instance-id")) + //for overlay/underlay + || (rt == "configuration" && eKey.equals("configuration.configuration-id") + )){ + jObj.put("resourceInstanceId", eValue) + } + // for sp-partner + if(rt == "sp-partner" && eKey.equals("sp-partner.id")) { + jObj.put("resourceInstanceId", eValue) + String sppartnerName = "sp-partner" + eValue + jObj.put("resourceType", sppartnerName) + } + } + + def rl_props = utils.getIdenticalChildren(node, "related-to-property") + for(def rl_prop : rl_props) { + def eKey = utils.getChildNodeText(rl_prop, "property-key") + def eValue = utils.getChildNodeText(rl_prop, "property-value") + if((rt == "service-instance" && eKey.equals("service-instance.service-instance-name")) + //for overlay/underlay + || (rt == "configuration" && eKey.equals("configuration.configuration-type"))){ + jObj.put("resourceType", eValue) + } + } + + utils.log("INFO", "Relationship related to Resource:" + jObj.toString(), isDebugEnabled) + + return jObj + } + + public void getCurrentNS(DelegateExecution execution){ + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + utils.log("INFO", "======== Start getCurrentNS Process ======== ", isDebugEnabled) + + def currentIndex = execution.getVariable("currentNSIndex") + List<String> nsSequence = execution.getVariable("nsSequence") + String nsResourceType = nsSequence.get(currentIndex) + + // GET AAI by Name, not ID, for process convenient + execution.setVariable("GENGS_type", "service-instance") + execution.setVariable("GENGS_serviceInstanceId", "") + execution.setVariable("GENGS_serviceInstanceName", nsResourceType) + + utils.log("INFO", "======== COMPLETED getCurrentNS Process ======== ", isDebugEnabled) + } + + public void prepareDecomposeService(DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + + try { + utils.log("DEBUG", " ***** Inside prepareDecomposeService of create generic e2e service ***** ", isDebugEnabled) + String modelInvariantUuid = execution.getVariable("model-invariant-id-original") + String modelVersionId = execution.getVariable("model-version-id-original") + + String serviceModelInfo = """{ + "modelInvariantUuid":"${modelInvariantUuid}", + "modelUuid":"${modelVersionId}", + "modelVersion":"" + }""" + execution.setVariable("serviceModelInfo", serviceModelInfo) + + utils.log("DEBUG", " ***** Completed prepareDecomposeService of create generic e2e service ***** ", isDebugEnabled) + } catch (Exception ex) { + // try error in method block + String exceptionMessage = "Bpmn error encountered in create generic e2e service flow. Unexpected Error from method prepareDecomposeService() - " + ex.getMessage() + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + } + } + + public void postDecomposeService(DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + + utils.log("DEBUG", " ***** Inside processDecomposition() of delete generic e2e service flow ***** ", isDebugEnabled) + try { + ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition") + + // service model info + execution.setVariable("serviceModelInfo", serviceDecomposition.getModelInfo()) + + List<Resource> deleteResourceList = serviceDecomposition.getServiceResources() + String serviceRelationShip = execution.getVariable("serviceRelationShip") + def jsonSlurper = new JsonSlurper() + def jsonOutput = new JsonOutput() + + List relationShipList = null + if (serviceRelationShip != null) { + relationShipList = jsonSlurper.parseText(serviceRelationShip) + } + + //Set the real resource instance id to the decomosed resource list + for (Resource resource: deleteResourceList) { + //reset the resource instance id , because in the decompose flow ,its a random one. + resource.setResourceId(""); + //match the resource-instance-name and the model name + if (relationShipList != null) { + relationShipList.each { + if (StringUtils.containsIgnoreCase(it.resourceType, resource.getModelInfo().getModelName())) { + resource.setResourceId(it.resourceInstanceId); + } + } + } + } + execution.setVariable("deleteResourceList", deleteResourceList) + utils.log("DEBUG", "delete resource list : " + deleteResourceList, isDebugEnabled) + } catch (Exception ex) { + String exceptionMessage = "Bpmn error encountered in create generic e2e service flow. processDecomposition() - " + ex.getMessage() + utils.log("DEBUG", exceptionMessage, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + } + utils.log("DEBUG", " ***** exit processDecomposition() of delete generic e2e service flow ***** ", isDebugEnabled) + } + + public void preInitResourcesOperStatus(DelegateExecution execution){ + def isDebugEnabled = execution.getVariable("isDebugLogEnabled") + + utils.log("INFO", " ======== STARTED preInitResourcesOperStatus Process ======== ", isDebugEnabled) + try{ + String serviceId = execution.getVariable("serviceInstanceId") + String operationId = execution.getVariable("operationId") + String operationType = execution.getVariable("operationType") + String resourceTemplateUUIDs = "" + String result = "processing" + String progress = "0" + String reason = "" + String operationContent = "Prepare service creation" + utils.log("INFO", "Generated new operation for Service Instance serviceId:" + serviceId + " operationId:" + operationId + " operationType:" + operationType, isDebugEnabled) + serviceId = UriUtils.encode(serviceId,"UTF-8") + execution.setVariable("serviceInstanceId", serviceId) + execution.setVariable("operationId", operationId) + execution.setVariable("operationType", operationType) + List<Resource> deleteResourceList = execution.getVariable("deleteResourceList") + + String serviceRelationShip = execution.getVariable("serviceRelationShip") + for(Resource resource : deleteResourceList){ + resourceTemplateUUIDs = resourceTemplateUUIDs + resource.getModelInfo().getModelCustomizationUuid() + ":" + } + + + execution.setVariable("URN_mso_adapters_openecomp_db_endpoint","http://mso.mso.testlab.openecomp.org:8080/dbadapters/RequestsDbAdapter") + + String payload = + """<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" + xmlns:ns="http://org.onap.so/requestsdb"> + <soapenv:Header/> + <soapenv:Body> + <ns:initResourceOperationStatus xmlns:ns="http://org.onap.so/requestsdb"> + <serviceId>${MsoUtils.xmlEscape(serviceId)}</serviceId> + <operationId>${MsoUtils.xmlEscape(operationId)}</operationId> + <operationType>${MsoUtils.xmlEscape(operationType)}</operationType> + <resourceTemplateUUIDs>${MsoUtils.xmlEscape(resourceTemplateUUIDs)}</resourceTemplateUUIDs> + </ns:initResourceOperationStatus> + </soapenv:Body> + </soapenv:Envelope>""" + + payload = utils.formatXml(payload) + execution.setVariable("CVFMI_initResOperStatusRequest", payload) + utils.log("INFO", "Outgoing initResourceOperationStatus: \n" + payload, isDebugEnabled) + utils.logAudit("CreateVfModuleInfra Outgoing initResourceOperationStatus Request: " + payload) + + }catch(Exception e){ + utils.log("ERROR", "Exception Occured Processing preInitResourcesOperStatus. Exception is:\n" + e, isDebugEnabled) + execution.setVariable("CVFMI_ErrorResponse", "Error Occurred during preInitResourcesOperStatus Method:\n" + e.getMessage()) + } + utils.log("INFO", "======== COMPLETED preInitResourcesOperStatus Process ======== ", isDebugEnabled) + } + + /** + * post config request. + */ + public void postConfigRequest(execution){ + //to do + } + +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteNetworkInstance.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteNetworkInstance.groovy new file mode 100644 index 0000000000..3ee059cb02 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteNetworkInstance.groovy @@ -0,0 +1,1077 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts; + +import org.apache.commons.lang3.* +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.onap.so.bpmn.common.scripts.AaiUtil +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.onap.so.bpmn.common.scripts.ExceptionUtil +import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.so.bpmn.common.scripts.NetworkUtils +import org.onap.so.bpmn.common.scripts.SDNCAdapterUtils +import org.onap.so.bpmn.common.scripts.VidUtils +import org.onap.so.bpmn.core.UrnPropertiesReader +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.logger.MessageEnum +import org.onap.so.logger.MsoLogger +import org.onap.so.rest.APIResponse; +import org.onap.so.rest.RESTClient +import org.onap.so.rest.RESTConfig +import org.springframework.web.util.UriUtils + +import groovy.json.* + +public class DoDeleteNetworkInstance extends AbstractServiceTaskProcessor { + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoDeleteNetworkInstance.class); + + String Prefix= "DELNWKI_" + String groovyClassName = "DoDeleteNetworkInstance" + ExceptionUtil exceptionUtil = new ExceptionUtil() + JsonUtils jsonUtil = new JsonUtils() + VidUtils vidUtils = new VidUtils(this) + NetworkUtils networkUtils = new NetworkUtils() + SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils() + + public InitializeProcessVariables(DelegateExecution execution){ + /* Initialize all the process variables in this block */ + + execution.setVariable(Prefix + "networkRequest", "") + execution.setVariable(Prefix + "isSilentSuccess", false) + execution.setVariable(Prefix + "Success", false) + + execution.setVariable(Prefix + "requestId", "") + execution.setVariable(Prefix + "source", "") + execution.setVariable(Prefix + "lcpCloudRegion", "") + execution.setVariable(Prefix + "networkInputs", "") + execution.setVariable(Prefix + "tenantId", "") + + execution.setVariable(Prefix + "queryAAIRequest","") + execution.setVariable(Prefix + "queryAAIResponse", "") + execution.setVariable(Prefix + "aaiReturnCode", "") + execution.setVariable(Prefix + "isAAIGood", false) + execution.setVariable(Prefix + "isVfRelationshipExist", false) + + // AAI query Cloud Region + execution.setVariable(Prefix + "queryCloudRegionRequest","") + execution.setVariable(Prefix + "queryCloudRegionReturnCode","") + execution.setVariable(Prefix + "queryCloudRegionResponse","") + execution.setVariable(Prefix + "cloudRegionPo","") + execution.setVariable(Prefix + "cloudRegionSdnc","") + + execution.setVariable(Prefix + "deleteNetworkRequest", "") + execution.setVariable(Prefix + "deleteNetworkResponse", "") + execution.setVariable(Prefix + "networkReturnCode", "") + execution.setVariable(Prefix + "rollbackNetworkRequest", "") + + execution.setVariable(Prefix + "deleteSDNCRequest", "") + execution.setVariable(Prefix + "deleteSDNCResponse", "") + execution.setVariable(Prefix + "sdncReturnCode", "") + execution.setVariable(Prefix + "sdncResponseSuccess", false) + + execution.setVariable(Prefix + "deactivateSDNCRequest", "") + execution.setVariable(Prefix + "deactivateSDNCResponse", "") + execution.setVariable(Prefix + "deactivateSdncReturnCode", "") + execution.setVariable(Prefix + "isSdncDeactivateRollbackNeeded", "") + + execution.setVariable(Prefix + "rollbackDeactivateSDNCRequest", "") + execution.setVariable(Prefix + "isException", false) + + + } + + // ************************************************** + // Pre or Prepare Request Section + // ************************************************** + + public void preProcessRequest (DelegateExecution execution) { + + execution.setVariable("prefix",Prefix) + + msoLogger.trace("Inside preProcessRequest() of " + groovyClassName + " Request ") + + // initialize flow variables + InitializeProcessVariables(execution) + + try { + // get incoming message/input + execution.setVariable("action", "DELETE") + String deleteNetwork = execution.getVariable("bpmnRequest") + if (deleteNetwork != null) { + if (deleteNetwork.contains("requestDetails")) { + // JSON format request is sent, create xml + try { + def prettyJson = JsonOutput.prettyPrint(deleteNetwork.toString()) + msoLogger.debug(" Incoming message formatted . . . : " + '\n' + prettyJson) + deleteNetwork = vidUtils.createXmlNetworkRequestInfra(execution, deleteNetwork) + + } catch (Exception ex) { + String dataErrorMessage = " Invalid json format Request - " + ex.getMessage() + msoLogger.debug(dataErrorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + } + } else { + // XML format request is sent + + } + } else { + // vIPR format request is sent, create xml from individual variables + deleteNetwork = vidUtils.createXmlNetworkRequestInstance(execution) + } + + deleteNetwork = utils.formatXml(deleteNetwork) + msoLogger.debug(deleteNetwork) + execution.setVariable(Prefix + "networkRequest", deleteNetwork) + msoLogger.debug(Prefix + "networkRequest - " + '\n' + deleteNetwork) + + // validate 'backout-on-failure' to override 'mso.rollback' + boolean rollbackEnabled = networkUtils.isRollbackEnabled(execution, deleteNetwork) + execution.setVariable(Prefix + "rollbackEnabled", rollbackEnabled) + msoLogger.debug(Prefix + "rollbackEnabled - " + rollbackEnabled) + + String networkInputs = utils.getNodeXml(deleteNetwork, "network-inputs", false).replace("tag0:","").replace(":tag0","") + execution.setVariable(Prefix + "networkInputs", networkInputs) + + // prepare messageId + String messageId = execution.getVariable("testMessageId") // for testing + if (messageId == null || messageId == "") { + messageId = UUID.randomUUID() + msoLogger.debug(Prefix + "messageId, random generated: " + messageId) + } else { + msoLogger.debug(Prefix + "messageId, pre-assigned: " + messageId) + } + execution.setVariable(Prefix + "messageId", messageId) + + String source = utils.getNodeText(deleteNetwork, "source") + execution.setVariable(Prefix + "source", source) + msoLogger.debug(Prefix + "source - " + source) + + String networkId = "" + if (utils.nodeExists(networkInputs, "network-id")) { + networkId = utils.getNodeText(networkInputs, "network-id") + if (networkId == null || networkId == "" || networkId == 'null' ) { + sendSyncError(execution) + // missing value of network-id + String dataErrorMessage = "network-request has missing 'network-id' element/value." + msoLogger.debug(" Invalid Request - " + dataErrorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + } + } + + // lcpCloudRegion or tenantId not sent, will be extracted from query AA&I + def lcpCloudRegion = null + if (utils.nodeExists(networkInputs, "aic-cloud-region")) { + lcpCloudRegion = utils.getNodeText(networkInputs, "aic-cloud-region") + if (lcpCloudRegion == 'null') { + lcpCloudRegion = null + } + } + execution.setVariable(Prefix + "lcpCloudRegion", lcpCloudRegion) + msoLogger.debug("lcpCloudRegion : " + lcpCloudRegion) + + String tenantId = null + if (utils.nodeExists(networkInputs, "tenant-id")) { + tenantId = utils.getNodeText(networkInputs, "tenant-id") + if (tenantId == 'null') { + tenantId = null + } + + } + execution.setVariable(Prefix + "tenantId", tenantId) + msoLogger.debug("tenantId : " + tenantId) + + String sdncVersion = execution.getVariable("sdncVersion") + msoLogger.debug("sdncVersion? : " + sdncVersion) + + // PO Authorization Info / headers Authorization= + String basicAuthValuePO = UrnPropertiesReader.getVariable("mso.adapters.po.auth", execution) + + try { + def encodedString = utils.getBasicAuth(basicAuthValuePO, UrnPropertiesReader.getVariable("mso.msoKey", execution)) + execution.setVariable("BasicAuthHeaderValuePO",encodedString) + execution.setVariable("BasicAuthHeaderValueSDNC", encodedString) + + } catch (IOException ex) { + String dataErrorMessage = " Unable to encode PO/SDNC user/password string - " + ex.getMessage() + msoLogger.debug(dataErrorMessage ) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + } + + } catch (BpmnError e) { + throw e; + + } catch (Exception ex){ + // caught exception + String exceptionMessage = "Exception Encountered in DoDeleteNetworkInstance, PreProcessRequest() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + + public void callRESTQueryAAI (DelegateExecution execution) { + + execution.setVariable("prefix",Prefix) + + msoLogger.debug(" ***** Inside callRESTQueryAAI() of DoDoDeleteNetworkInstance ***** " ) + + // get variables + String networkInputs = execution.getVariable(Prefix + "networkInputs") + String networkId = utils.getNodeText(networkInputs, "network-id") + networkId = UriUtils.encode(networkId,"UTF-8") + + // Prepare AA&I url + String aai_endpoint = UrnPropertiesReader.getVariable("aai.endpoint", execution) + AaiUtil aaiUriUtil = new AaiUtil(this) + String aai_uri = aaiUriUtil.getNetworkL3NetworkUri(execution) + String queryAAIRequest = "${aai_endpoint}${aai_uri}/" + networkId + "?depth=all" + msoLogger.debug(queryAAIRequest) + execution.setVariable(Prefix + "queryAAIRequest", queryAAIRequest) + msoLogger.debug(Prefix + "AAIRequest - " + "\n" + queryAAIRequest) + + RESTConfig config = new RESTConfig(queryAAIRequest); + + ExceptionUtil exceptionUtil = new ExceptionUtil() + Boolean isVfRelationshipExist = false + try { + APIResponse response = aaiUriUtil.executeAAIGetCall(execution, queryAAIRequest) + String returnCode = response.getStatusCode() + execution.setVariable(Prefix + "aaiReturnCode", returnCode) + + msoLogger.debug(" ***** AAI Response Code : " + returnCode) + + String aaiResponseAsString = response.getResponseBodyAsString() + execution.setVariable(Prefix + "queryAAIResponse", aaiResponseAsString) + + if (returnCode=='200' || returnCode=='204') { + msoLogger.debug(aaiResponseAsString) + execution.setVariable(Prefix + "isAAIGood", true) + msoLogger.debug(" AAI Query Success REST Response - " + "\n" + aaiResponseAsString) + // verify if vf or vnf relationship exist + if (utils.nodeExists(aaiResponseAsString, "relationship")) { + NetworkUtils networkUtils = new NetworkUtils() + isVfRelationshipExist = networkUtils.isVfRelationshipExist(aaiResponseAsString) + execution.setVariable(Prefix + "isVfRelationshipExist", isVfRelationshipExist) + if (isVfRelationshipExist == true) { + String relationshipMessage = "AAI Query Success Response but 'vf-module' relationship exist, not allowed to delete: network Id: " + networkId + exceptionUtil.buildWorkflowException(execution, 2500, relationshipMessage) + + } else { + // verify if lcpCloudRegion was sent as input, if not get value from AAI Response + if (execution.getVariable(Prefix + "lcpCloudRegion") == null ) { + String lcpCloudRegion = networkUtils.getCloudRegion(aaiResponseAsString) + execution.setVariable(Prefix + "lcpCloudRegion", lcpCloudRegion) + msoLogger.debug(" Get AAI getCloudRegion() : " + lcpCloudRegion) + } + if (execution.getVariable(Prefix + "tenantId") == null ) { + String tenantId = networkUtils.getTenantId(aaiResponseAsString) + execution.setVariable(Prefix + "tenantId", tenantId) + msoLogger.debug(" Get AAI getTenantId() : " + tenantId) + } + + } + } + msoLogger.debug(Prefix + "isVfRelationshipExist - " + isVfRelationshipExist) + + } else { + execution.setVariable(Prefix + "isAAIGood", false) + if (returnCode=='404' || aaiResponseAsString == "" || aaiResponseAsString == null) { + // not found // empty aai response + execution.setVariable(Prefix + "isSilentSuccess", true) + msoLogger.debug(" AAI Query is Silent Success") + + } else { + if (aaiResponseAsString.contains("RESTFault")) { + WorkflowException exceptionObject = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) + execution.setVariable("WorkflowException", exceptionObject) + + } else { + // aai all errors + String dataErrorMessage = "Unexpected Error Response from callRESTQueryAAI() - " + returnCode + msoLogger.debug(dataErrorMessage) + exceptionUtil.buildWorkflowException(execution, 2500, dataErrorMessage) + + } + } + } + + msoLogger.debug(" AAI Query call, isAAIGood? : " + execution.getVariable(Prefix + "isAAIGood")) + + } catch (Exception ex) { + // caught exception + String exceptionMessage = "Exception Encountered in DoDeleteNetworkInstance, callRESTQueryAAI() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + public void callRESTQueryAAICloudRegion (DelegateExecution execution) { + + execution.setVariable("prefix", Prefix) + + msoLogger.debug(" ***** Inside callRESTQueryAAICloudRegion of DoDeleteNetworkInstance ***** " ) + + try { + String networkInputs = execution.getVariable(Prefix + "networkInputs") + // String cloudRegion = utils.getNodeText(networkInputs, "aic-cloud-region") + String cloudRegion = execution.getVariable(Prefix + "lcpCloudRegion") + cloudRegion = UriUtils.encode(cloudRegion,"UTF-8") + // Prepare AA&I url + String aai_endpoint = UrnPropertiesReader.getVariable("aai.endpoint", execution) + AaiUtil aaiUtil = new AaiUtil(this) + String aai_uri = aaiUtil.getCloudInfrastructureCloudRegionUri(execution) + String queryCloudRegionRequest = "${aai_endpoint}${aai_uri}/" + cloudRegion + msoLogger.debug(queryCloudRegionRequest) + execution.setVariable(Prefix + "queryCloudRegionRequest", queryCloudRegionRequest) + msoLogger.debug(Prefix + "queryCloudRegionRequest - " + "\n" + queryCloudRegionRequest) + + String cloudRegionPo = aaiUtil.getAAICloudReqion(execution, queryCloudRegionRequest, "PO", cloudRegion) + String cloudRegionSdnc = aaiUtil.getAAICloudReqion(execution, queryCloudRegionRequest, "SDNC", cloudRegion) + + if ((cloudRegionPo != "ERROR") && (cloudRegionSdnc != "ERROR")) { + execution.setVariable(Prefix + "cloudRegionPo", cloudRegionPo) + execution.setVariable(Prefix + "cloudRegionSdnc", cloudRegionSdnc) + + } else { + String dataErrorMessage = "QueryAAICloudRegion Unsuccessful. Return Code: " + execution.getVariable(Prefix + "queryCloudRegionReturnCode") + msoLogger.debug(dataErrorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + + } + + } catch (BpmnError e) { + throw e; + + } catch (Exception ex) { + // caught exception + String exceptionMessage = "Bpmn error encountered in DoDeleteNetworkInstance, callRESTQueryAAICloudRegion(). Unexpected Response from AAI - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + public void prepareNetworkRequest (DelegateExecution execution) { + + execution.setVariable("prefix", Prefix) + + msoLogger.trace("Inside prepareNetworkRequest of DoDeleteNetworkInstance ") + ExceptionUtil exceptionUtil = new ExceptionUtil() + try { + // get variables + String networkRequest = execution.getVariable(Prefix + "networkRequest") + String cloudSiteId = execution.getVariable(Prefix + "cloudRegionPo") + String tenantId = execution.getVariable(Prefix + "tenantId") + + String queryAAIResponse = execution.getVariable(Prefix + "queryAAIResponse") + String networkType = utils.getNodeText(queryAAIResponse, "network-type") + String networkId = utils.getNodeText(queryAAIResponse, "network-id") + String backoutOnFailure = execution.getVariable(Prefix + "rollbackEnabled") + + String networkStackId = "" + networkStackId = utils.getNodeText(queryAAIResponse, "heat-stack-id") + if (networkStackId == 'null' || networkStackId == "" || networkStackId == null) { + networkStackId = "force_delete" + } + + String requestId = execution.getVariable("msoRequestId") + if (requestId != null) { + execution.setVariable("mso-request-id", requestId) + } else { + requestId = execution.getVariable("mso-request-id") + } + String serviceInstanceId = execution.getVariable("serviceInstanceId") + + // Added new Elements + String messageId = execution.getVariable(Prefix + "messageId") + String notificationUrl = "" //TODO - is this coming from URN? What variable/value to use? + //String notificationUrl = execution.getVariable("URN_?????") //TODO - is this coming from URN? What variable/value to use? + + String modelCustomizationUuid = "" + if (utils.nodeExists(networkRequest, "networkModelInfo")) { + String networkModelInfo = utils.getNodeXml(networkRequest, "networkModelInfo", false).replace("tag0:","").replace(":tag0","") + modelCustomizationUuid = utils.getNodeText(networkModelInfo, "modelCustomizationUuid") + } else { + modelCustomizationUuid = utils.getNodeText(networkRequest, "modelCustomizationId") + } + + String deleteNetworkRequest = """ + <deleteNetworkRequest> + <cloudSiteId>${MsoUtils.xmlEscape(cloudSiteId)}</cloudSiteId> + <tenantId>${MsoUtils.xmlEscape(tenantId)}</tenantId> + <networkId>${MsoUtils.xmlEscape(networkId)}</networkId> + <networkStackId>${MsoUtils.xmlEscape(networkStackId)}</networkStackId> + <networkType>${MsoUtils.xmlEscape(networkType)}</networkType> + <modelCustomizationUuid>${MsoUtils.xmlEscape(modelCustomizationUuid)}</modelCustomizationUuid> + <skipAAI>true</skipAAI> + <msoRequest> + <requestId>${MsoUtils.xmlEscape(requestId)}</requestId> + <serviceInstanceId>${MsoUtils.xmlEscape(serviceInstanceId)}</serviceInstanceId> + </msoRequest> + <messageId>${MsoUtils.xmlEscape(messageId)}</messageId> + <notificationUrl>${MsoUtils.xmlEscape(notificationUrl)}</notificationUrl> + </deleteNetworkRequest> + """.trim() + + msoLogger.debug(Prefix + "deleteNetworkRequest - " + "\n" + deleteNetworkRequest) + // Format Response + String buildDeleteNetworkRequestAsString = utils.formatXml(deleteNetworkRequest) + msoLogger.debug(buildDeleteNetworkRequestAsString) + msoLogger.debug(Prefix + "deleteNetworkRequestAsString - " + "\n" + buildDeleteNetworkRequestAsString) + + String restURL = UrnPropertiesReader.getVariable("mso.adapters.network.rest.endpoint", execution) + execution.setVariable("mso.adapters.network.rest.endpoint", restURL + "/" + networkId) + msoLogger.debug("mso.adapters.network.rest.endpoint - " + "\n" + restURL + "/" + networkId) + + execution.setVariable(Prefix + "deleteNetworkRequest", buildDeleteNetworkRequestAsString) + msoLogger.debug(Prefix + "deleteNetworkRequest - " + "\n" + buildDeleteNetworkRequestAsString) + } + catch (Exception ex) { + // caught exception + String exceptionMessage = "Bpmn error encountered in DoDeleteNetworkInstance, prepareNetworkRequest(). Unexpected Response from AAI - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + } + + /** + * This method is used instead of an HTTP Connector task because the + * connector does not allow DELETE with a body. + */ + public void sendRequestToVnfAdapter(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.sendRequestToVnfAdapter(' + + 'execution=' + execution.getId() + + ')' + + msoLogger.trace('Entered ' + method) + + try { + + String vnfAdapterUrl = UrnPropertiesReader.getVariable("mso.adapters.network.rest.endpoint",execution) + String vnfAdapterRequest = execution.getVariable(Prefix + "deleteNetworkRequest") + + RESTConfig config = new RESTConfig(vnfAdapterUrl) + RESTClient client = new RESTClient(config). + addHeader("Content-Type", "application/xml"). + addAuthorizationHeader(execution.getVariable("BasicAuthHeaderValuePO")); + + APIResponse response; + + response = client.httpDelete(vnfAdapterRequest) + + execution.setVariable(Prefix + "networkReturnCode", response.getStatusCode()) + execution.setVariable(Prefix + "deleteNetworkResponse", response.getResponseBodyAsString()) + + } catch (Exception ex) { + // caught exception + String exceptionMessage = "Bpmn error encountered in DoDeleteNetworkInstance, sendRequestToVnfAdapter() - " + ex.getMessage() + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, exceptionMessage, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + ex); + msoLogger.debug(exceptionMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + } + + + public void prepareSDNCRequest (DelegateExecution execution) { + + execution.setVariable("prefix", Prefix) + + msoLogger.trace("Inside prepareSDNCRequest of DoDeleteNetworkInstance ") + + try { + // get variables + String sdncCallback = UrnPropertiesReader.getVariable("mso.workflow.sdncadapter.callback",execution) + String deleteNetworkInput = execution.getVariable(Prefix + "networkRequest") + + String networkId = "" + if (utils.nodeExists(deleteNetworkInput, "network-id")) { + networkId = utils.getNodeText(deleteNetworkInput, "network-id") + } + if (networkId == 'null') {networkId = ""} + + String serviceInstanceId = utils.getNodeText(deleteNetworkInput, "service-instance-id") + + // get/set 'msoRequestId' and 'mso-request-id' + String requestId = execution.getVariable("msoRequestId") + if (requestId != null) { + execution.setVariable("mso-request-id", requestId) + } else { + requestId = execution.getVariable("mso-request-id") + } + execution.setVariable(Prefix + "requestId", requestId) + msoLogger.debug(Prefix + "requestId " + requestId) + String queryAAIResponse = execution.getVariable(Prefix + "queryAAIResponse") + + SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils() + String cloudRegionId = execution.getVariable(Prefix + "cloudRegionSdnc") + // 1. prepare delete topology via SDNC Adapter SUBFLOW call + String sndcTopologyDeleteRequest = sdncAdapterUtils.sdncTopologyRequestV2(execution, deleteNetworkInput, serviceInstanceId, sdncCallback, "delete", "DisconnectNetworkRequest", cloudRegionId, networkId, queryAAIResponse, null) + String sndcTopologyDeleteRequesAsString = utils.formatXml(sndcTopologyDeleteRequest) + msoLogger.debug(sndcTopologyDeleteRequesAsString) + execution.setVariable(Prefix + "deleteSDNCRequest", sndcTopologyDeleteRequesAsString) + msoLogger.debug(Prefix + "deleteSDNCRequest - " + "\n" + sndcTopologyDeleteRequesAsString) + + } catch (Exception ex) { + // caught exception + String exceptionMessage = "Bpmn error encountered in DoDeleteNetworkInstance, prepareSDNCRequest() - " + ex.getMessage() + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, exceptionMessage, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + ex); + msoLogger.debug(exceptionMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + public void prepareRpcSDNCRequest (DelegateExecution execution) { + + execution.setVariable("prefix", Prefix) + + msoLogger.trace("Inside prepareRpcSDNCRequest of DoDeleteNetworkInstance ") + + try { + // get variables + String sdncCallback = UrnPropertiesReader.getVariable("mso.workflow.sdncadapter.callback",execution) + String deleteNetworkInput = execution.getVariable(Prefix + "networkRequest") + + String networkId = "" + if (utils.nodeExists(deleteNetworkInput, "network-id")) { + networkId = utils.getNodeText(deleteNetworkInput, "network-id") + } + if (networkId == 'null') {networkId = ""} + + String serviceInstanceId = utils.getNodeText(deleteNetworkInput, "service-instance-id") + + SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils() + String cloudRegionId = execution.getVariable(Prefix + "cloudRegionSdnc") + // 1. prepare delete topology via SDNC Adapter SUBFLOW call + String sndcTopologyRollbackRpcRequest = sdncAdapterUtils.sdncTopologyRequestRsrc(execution, deleteNetworkInput, serviceInstanceId, sdncCallback, "unassign", "DeleteNetworkInstance", cloudRegionId, networkId, null) + String sndcTopologyDeleteRequesAsString = utils.formatXml(sndcTopologyRollbackRpcRequest) + msoLogger.debug(sndcTopologyDeleteRequesAsString) + execution.setVariable(Prefix + "deleteSDNCRequest", sndcTopologyDeleteRequesAsString) + msoLogger.debug(Prefix + "deleteSDNCRequest - " + "\n" + sndcTopologyDeleteRequesAsString) + + } catch (Exception ex) { + // caught exception + String exceptionMessage = "Bpmn error encountered in DoDeleteNetworkInstance, prepareSDNCRequest() - " + ex.getMessage() + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, exceptionMessage, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + ex); + msoLogger.debug(exceptionMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + + public void prepareRpcSDNCDeactivate(DelegateExecution execution) { + + execution.setVariable("prefix",Prefix) + + msoLogger.trace("Inside prepareRpcSDNCDeactivate() of DoDeleteNetworkInstance ") + + try { + + // get variables + String sdncCallback = UrnPropertiesReader.getVariable("mso.workflow.sdncadapter.callback",execution) + String deleteNetworkInput = execution.getVariable(Prefix + "networkRequest") + String cloudRegionId = execution.getVariable(Prefix + "cloudRegionSdnc") + String networkId = "" + if (utils.nodeExists(deleteNetworkInput, "network-id")) { + networkId = utils.getNodeText(deleteNetworkInput, "network-id") + } + if (networkId == 'null') {networkId = ""} + String serviceInstanceId = utils.getNodeText(deleteNetworkInput, "service-instance-id") + + String sndcTopologyRollbackRpcRequest = sdncAdapterUtils.sdncTopologyRequestRsrc(execution, deleteNetworkInput, serviceInstanceId, sdncCallback, "deactivate", "DeleteNetworkInstance", cloudRegionId, networkId, null) + String sndcTopologyRollbackRpcRequestAsString = utils.formatXml(sndcTopologyRollbackRpcRequest) + execution.setVariable(Prefix + "deactivateSDNCRequest", sndcTopologyRollbackRpcRequestAsString) + msoLogger.debug(" Preparing request for RPC SDNC Topology deactivate - " + "\n" + sndcTopologyRollbackRpcRequestAsString) + + + } catch (Exception ex) { + String exceptionMessage = " Bpmn error encountered in DoDeleteNetworkInstance flow. prepareRpcSDNCActivateRollback() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + // ************************************************** + // Post or Validate Response Section + // ************************************************** + + public void validateNetworkResponse (DelegateExecution execution) { + + execution.setVariable("prefix", Prefix) + + msoLogger.trace("Inside validateNetworkResponse of DoDeleteNetworkInstance ") + + try { + String returnCode = execution.getVariable(Prefix + "networkReturnCode") + String networkResponse = execution.getVariable(Prefix + "deleteNetworkResponse") + + msoLogger.debug(" Network Adapter responseCode: " + returnCode) + msoLogger.debug("Network Adapter Response - " + "\n" + networkResponse) + msoLogger.debug(networkResponse) + + String errorMessage = "" + if (returnCode == "200") { + msoLogger.debug(" Network Adapter Response is successful - " + "\n" + networkResponse) + + // prepare rollback data + String rollbackData = utils.getNodeXml(networkResponse, "rollback", false).replace("tag0:","").replace(":tag0","") + if ((rollbackData == null) || (rollbackData.isEmpty())) { + msoLogger.debug(" Network Adapter 'rollback' data is not Sent: " + "\n" + networkResponse) + execution.setVariable(Prefix + "rollbackNetworkRequest", "") + } else { + String rollbackNetwork = + """<NetworkAdapter:rollbackNetwork xmlns:NetworkAdapter="http://org.onap.so/network"> + ${rollbackData} + </NetworkAdapter:rollbackNetwork>""" + String rollbackNetworkXml = utils.formatXml(rollbackNetwork) + execution.setVariable(Prefix + "rollbackNetworkRequest", rollbackNetworkXml) + msoLogger.debug(" Network Adapter rollback data - " + "\n" + rollbackNetworkXml) + } + + + } else { // network error + if (returnCode.toInteger() > 399 && returnCode.toInteger() < 600) { //4xx, 5xx + if (networkResponse.contains("deleteNetworkError") ) { + networkResponse = networkResponse.replace('<?xml version="1.0" encoding="UTF-8" standalone="yes"?>', '') + errorMessage = utils.getNodeText(networkResponse, "message") + errorMessage = "Received error from Network Adapter: " + errorMessage + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, errorMessage) + + } else { // CatchAll exception + if (returnCode == "500") { + errorMessage = "JBWEB000065: HTTP Status 500." + } else { + errorMessage = "Return code is " + returnCode + } + errorMessage = "Received error from Network Adapter: " + errorMessage + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, errorMessage) + + } + + } else { // CatchAll exception + String dataErrorMessage = "Received error from Network Adapter. Return code is: " + returnCode + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + + } + + } + + } catch (BpmnError e) { + throw e; + + } catch (Exception ex) { + // caught exception + String exceptionMessage = "Bpmn error encountered in DoDeleteNetworkInstance, validateNetworkResponse() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + public void validateSDNCResponse (DelegateExecution execution) { + + execution.setVariable("prefix", Prefix) + + msoLogger.trace("Inside validateSDNCResponse of DoDeleteNetworkInstance ") + + String response = execution.getVariable(Prefix + "deleteSDNCResponse") + boolean successIndicator = execution.getVariable("SDNCA_SuccessIndicator") + WorkflowException workflowException = execution.getVariable("WorkflowException") + + SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this) + sdncAdapterUtils.validateSDNCResponse(execution, response, workflowException, successIndicator) + // reset variable + String deleteSDNCResponseDecodeXml = execution.getVariable(Prefix + "deleteSDNCResponse") + deleteSDNCResponseDecodeXml = deleteSDNCResponseDecodeXml.replace('<?xml version="1.0" encoding="UTF-8"?>', "") + execution.setVariable(Prefix + "deleteSDNCResponse", deleteSDNCResponseDecodeXml) + + if (execution.getVariable(Prefix + "sdncResponseSuccess") == true) { // from sdnc util, prefix+'sdncResponseSuccess' + execution.setVariable(Prefix + "isSdncRollbackNeeded", true) // + execution.setVariable(Prefix + "isPONR", true) + msoLogger.debug("Successfully Validated SDNC Response") + } else { + msoLogger.debug("Did NOT Successfully Validated SDNC Response") + throw new BpmnError("MSOWorkflowException") + } + + } + + public void validateRpcSDNCDeactivateResponse (DelegateExecution execution) { + + execution.setVariable("prefix",Prefix) + + msoLogger.trace("Inside validateRpcSDNCDeactivateResponse() of DoDeleteNetworkInstance ") + + String response = execution.getVariable(Prefix + "deactivateSDNCResponse") + boolean successIndicator = execution.getVariable("SDNCA_SuccessIndicator") + WorkflowException workflowException = execution.getVariable("WorkflowException") + + SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this) + sdncAdapterUtils.validateSDNCResponse(execution, response, workflowException, successIndicator) + // reset variable + String assignSDNCResponseDecodeXml = execution.getVariable(Prefix + "deactivateSDNCResponse") + assignSDNCResponseDecodeXml = assignSDNCResponseDecodeXml.replace('<?xml version="1.0" encoding="UTF-8"?>', "") + execution.setVariable(Prefix + "deactivateSDNCResponse", assignSDNCResponseDecodeXml) + + if (execution.getVariable(Prefix + "sdncResponseSuccess") == true) { // from sdnc util, Prefix+'sdncResponseSuccess' + execution.setVariable(Prefix + "isSdncDeactivateRollbackNeeded", true) + msoLogger.debug("Successfully Validated Rpc SDNC Activate Response") + + } else { + msoLogger.debug("Did NOT Successfully Validated Rpc SDNC Deactivate Response") + throw new BpmnError("MSOWorkflowException") + } + + } + + public void prepareRpcSDNCDeactivateRollback(DelegateExecution execution) { + + execution.setVariable("prefix",Prefix) + + msoLogger.trace("Inside prepareRpcSDNCDeactivateRollback() of DoDeleteNetworkInstance ") + + try { + + // get variables + String sdncCallback = UrnPropertiesReader.getVariable("mso.workflow.sdncadapter.callback",execution) + String deleteNetworkInput = execution.getVariable(Prefix + "networkRequest") + String cloudRegionId = execution.getVariable(Prefix + "cloudRegionSdnc") + String deactivateSDNCResponse = execution.getVariable(Prefix + "deactivateSDNCResponse") + String networkId = utils.getNodeText(deactivateSDNCResponse, "network-id") + if (networkId == 'null') {networkId = ""} + String serviceInstanceId = utils.getNodeText(deleteNetworkInput, "service-instance-id") + + // 2. prepare rollback topology via SDNC Adapter SUBFLOW call + String sndcTopologyRollbackRpcRequest = sdncAdapterUtils.sdncTopologyRequestRsrc(execution, deleteNetworkInput, serviceInstanceId, sdncCallback, "activate", "CreateNetworkInstance", cloudRegionId, networkId, null) + String sndcTopologyRollbackRpcRequestAsString = utils.formatXml(sndcTopologyRollbackRpcRequest) + execution.setVariable(Prefix + "rollbackDeactivateSDNCRequest", sndcTopologyRollbackRpcRequestAsString) + msoLogger.debug(" Preparing request for RPC SDNC Topology 'activate-CreateNetworkInstance' rollback . . . - " + "\n" + sndcTopologyRollbackRpcRequestAsString) + + + } catch (Exception ex) { + String exceptionMessage = " Bpmn error encountered in DoDeleteNetworkInstance flow. prepareRpcSDNCDeactivateRollback() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + public void prepareRollbackData(DelegateExecution execution) { + + execution.setVariable("prefix",Prefix) + + msoLogger.trace("Inside prepareRollbackData() of DoDeleteNetworkInstance ") + + try { + + Map<String, String> rollbackData = new HashMap<String, String>(); + String rollbackNetworkRequest = execution.getVariable(Prefix + "rollbackNetworkRequest") + if (rollbackNetworkRequest != null) { + if (rollbackNetworkRequest != "") { + rollbackData.put("rollbackNetworkRequest", execution.getVariable(Prefix + "rollbackNetworkRequest")) + } + } + String rollbackDeactivateSDNCRequest = execution.getVariable(Prefix + "rollbackDeactivateSDNCRequest") + if (rollbackDeactivateSDNCRequest != null) { + if (rollbackDeactivateSDNCRequest != "") { + rollbackData.put("rollbackDeactivateSDNCRequest", execution.getVariable(Prefix + "rollbackDeactivateSDNCRequest")) + } + } + execution.setVariable("rollbackData", rollbackData) + msoLogger.debug("** rollbackData : " + rollbackData) + + execution.setVariable("WorkflowException", execution.getVariable("WorkflowException")) + msoLogger.debug("** WorkflowException : " + execution.getVariable("WorkflowException")) + + } catch (Exception ex) { + String exceptionMessage = " Bpmn error encountered in DoDeleteNetworkInstance flow. prepareRollbackData() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + public void postProcessResponse (DelegateExecution execution) { + + execution.setVariable("prefix", Prefix) + + msoLogger.trace("Inside postProcessResponse of DoDeleteNetworkInstance ") + + try { + + msoLogger.debug(" ***** Is Exception Encountered (isException)? : " + execution.getVariable(Prefix + "isException")) + if (execution.getVariable(Prefix + "isException") == false) { + execution.setVariable(Prefix + "Success", true) + execution.setVariable("WorkflowException", null) + if (execution.getVariable(Prefix + "isSilentSuccess") == true) { + execution.setVariable("rolledBack", false) + } else { + execution.setVariable("rolledBack", true) + } + prepareSuccessRollbackData(execution) // populate rollbackData + + } else { + execution.setVariable(Prefix + "Success", false) + execution.setVariable("rollbackData", null) + String exceptionMessage = " Exception encountered in MSO Bpmn. " + if (execution.getVariable("workflowException") != null) { // Output of Rollback flow. + msoLogger.debug(" ***** workflowException: " + execution.getVariable("workflowException")) + WorkflowException wfex = execution.getVariable("workflowException") + exceptionMessage = wfex.getErrorMessage() + } else { + if (execution.getVariable(Prefix + "WorkflowException") != null) { + WorkflowException pwfex = execution.getVariable(Prefix + "WorkflowException") + exceptionMessage = pwfex.getErrorMessage() + } else { + if (execution.getVariable("WorkflowException") != null) { + WorkflowException pwfex = execution.getVariable("WorkflowException") + exceptionMessage = pwfex.getErrorMessage() + } + } + } + + // going to the Main flow: a-la-carte or macro + msoLogger.debug(" ***** postProcessResponse(), BAD !!!") + exceptionUtil.buildWorkflowException(execution, 7000, exceptionMessage) + throw new BpmnError("MSOWorkflowException") + + } + + } catch(BpmnError b){ + msoLogger.debug("Rethrowing MSOWorkflowException") + throw b + + } catch (Exception ex) { + // caught exception + String exceptionMessage = "Bpmn error encountered in DoDeleteNetworkInstance, postProcessResponse() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildWorkflowException(execution, 7000, exceptionMessage) + throw new BpmnError("MSOWorkflowException") + + } + + } + + public void prepareSuccessRollbackData(DelegateExecution execution) { + + execution.setVariable("prefix",Prefix) + + msoLogger.trace("Inside prepareSuccessRollbackData() of DoDeleteNetworkInstance ") + + try { + + if (execution.getVariable("sdncVersion") != '1610') { + prepareRpcSDNCDeactivateRollback(execution) + prepareRpcSDNCUnassignRollback(execution) + } else { + prepareSDNCRollback(execution) + } + + Map<String, String> rollbackData = new HashMap<String, String>(); + String rollbackSDNCRequest = execution.getVariable(Prefix + "rollbackSDNCRequest") + if (rollbackSDNCRequest != null) { + if (rollbackSDNCRequest != "") { + rollbackData.put("rollbackSDNCRequest", execution.getVariable(Prefix + "rollbackSDNCRequest")) + } + } + String rollbackNetworkRequest = execution.getVariable(Prefix + "rollbackNetworkRequest") + if (rollbackNetworkRequest != null) { + if (rollbackNetworkRequest != "") { + rollbackData.put("rollbackNetworkRequest", execution.getVariable(Prefix + "rollbackNetworkRequest")) + } + } + String rollbackDeactivateSDNCRequest = execution.getVariable(Prefix + "rollbackDeactivateSDNCRequest") + if (rollbackDeactivateSDNCRequest != null) { + if (rollbackDeactivateSDNCRequest != "") { + rollbackData.put("rollbackDeactivateSDNCRequest", execution.getVariable(Prefix + "rollbackDeactivateSDNCRequest")) + } + } + execution.setVariable("rollbackData", rollbackData) + + msoLogger.debug("** rollbackData : " + rollbackData) + execution.setVariable("WorkflowException", null) + + + } catch (Exception ex) { + String exceptionMessage = " Bpmn error encountered in DoDeleteNetworkInstance flow. prepareSuccessRollbackData() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + public void prepareRpcSDNCUnassignRollback(DelegateExecution execution) { + + execution.setVariable("prefix",Prefix) + + msoLogger.trace("Inside prepareRpcSDNCUnassignRollbac() of DoDeleteNetworkInstance ") + + try { + + // get variables + String sdncCallback = UrnPropertiesReader.getVariable("mso.workflow.sdncadapter.callback",execution) + String deleteNetworkInput = execution.getVariable(Prefix + "networkRequest") + + String deleteSDNCResponse = execution.getVariable(Prefix + "deleteSDNCResponse") + String networkId = utils.getNodeText(deleteSDNCResponse, "network-id") + if (networkId == 'null') {networkId = ""} + String serviceInstanceId = utils.getNodeText(deleteNetworkInput, "service-instance-id") + + SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils() + String cloudRegionId = execution.getVariable(Prefix + "cloudRegionSdnc") + // 1. prepare delete topology via SDNC Adapter SUBFLOW call + String sndcTopologyRollbackRpcRequest = sdncAdapterUtils.sdncTopologyRequestRsrc(execution, deleteNetworkInput, serviceInstanceId, sdncCallback, "assign", "CreateNetworkInstance", cloudRegionId, networkId, null) + String sndcTopologyDeleteRequesAsString = utils.formatXml(sndcTopologyRollbackRpcRequest) + msoLogger.debug(sndcTopologyDeleteRequesAsString) + execution.setVariable(Prefix + "rollbackSDNCRequest", sndcTopologyDeleteRequesAsString) + msoLogger.debug(Prefix + "rollbackSDNCRequest" + "\n" + sndcTopologyDeleteRequesAsString) + msoLogger.debug(" Preparing request for RPC SDNC Topology 'assign-CreateNetworkInstance' rollback . . . - " + "\n" + sndcTopologyDeleteRequesAsString) + + + } catch (Exception ex) { + String exceptionMessage = " Bpmn error encountered in DoDeleteNetworkInstance flow. prepareRpcSDNCUnassignRollback() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + public void prepareSDNCRollback (DelegateExecution execution) { + + execution.setVariable("prefix", Prefix) + + msoLogger.trace("Inside prepareSDNCRollback of DoDeleteNetworkInstance ") + + try { + + // get variables + String sdncCallback = UrnPropertiesReader.getVariable("mso.workflow.sdncadapter.callback",execution) + String deleteNetworkInput = execution.getVariable(Prefix + "networkRequest") + + String networkId = "" + if (utils.nodeExists(deleteNetworkInput, "network-id")) { + networkId = utils.getNodeText(deleteNetworkInput, "network-id") + } + if (networkId == 'null') {networkId = ""} + + String serviceInstanceId = utils.getNodeText(deleteNetworkInput, "service-instance-id") + + // get/set 'msoRequestId' and 'mso-request-id' + String requestId = execution.getVariable("msoRequestId") + if (requestId != null) { + execution.setVariable("mso-request-id", requestId) + } else { + requestId = execution.getVariable("mso-request-id") + } + execution.setVariable(Prefix + "requestId", requestId) + + String queryAAIResponse = execution.getVariable(Prefix + "queryAAIResponse") + + SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils() + String cloudRegionId = execution.getVariable(Prefix + "cloudRegionSdnc") + // 1. prepare delete topology via SDNC Adapter SUBFLOW call + String sndcTopologyDeleteRequest = sdncAdapterUtils.sdncTopologyRequestV2(execution, deleteNetworkInput, serviceInstanceId, sdncCallback, "rollback", "DisconnectNetworkRequest", cloudRegionId, networkId, queryAAIResponse, null) + String sndcTopologyDeleteRequesAsString = utils.formatXml(sndcTopologyDeleteRequest) + msoLogger.debug(sndcTopologyDeleteRequesAsString) + execution.setVariable(Prefix + "rollbackSDNCRequest", sndcTopologyDeleteRequesAsString) + msoLogger.debug(Prefix + "rollbackSDNCRequest - " + "\n" + sndcTopologyDeleteRequesAsString) + msoLogger.debug(" Preparing request for RPC SDNC Topology 'rollback-DisconnectNetworkRequest' rollback . . . - " + "\n" + sndcTopologyDeleteRequesAsString) + + + } catch (Exception ex) { + // caught exception + String exceptionMessage = "Bpmn error encountered in DoDeleteNetworkInstance, prepareSDNCRollback() - " + ex.getMessage() + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, exceptionMessage, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + ex); + msoLogger.debug(exceptionMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + public void setExceptionFlag(DelegateExecution execution){ + + execution.setVariable("prefix",Prefix) + + msoLogger.trace("Inside setExceptionFlag() of DoDeleteNetworkInstance ") + + try { + + execution.setVariable(Prefix + "isException", true) + + if (execution.getVariable("SavedWorkflowException1") != null) { + execution.setVariable(Prefix + "WorkflowException", execution.getVariable("SavedWorkflowException1")) + } else { + execution.setVariable(Prefix + "WorkflowException", execution.getVariable("WorkflowException")) + } + msoLogger.debug(Prefix + "WorkflowException - " +execution.getVariable(Prefix + "WorkflowException")) + + } catch(Exception ex){ + String exceptionMessage = "Bpmn error encountered in DoDeleteNetworkInstance flow. setExceptionFlag(): " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildWorkflowException(execution, 7000, exceptionMessage) + } + + } + + + // ******************************* + // Build Error Section + // ******************************* + + public void processJavaException(DelegateExecution execution){ + + execution.setVariable("prefix",Prefix) + try{ + msoLogger.debug("Caught a Java Exception") + msoLogger.debug("Started processJavaException Method") + msoLogger.debug("Variables List: " + execution.getVariables()) + execution.setVariable("UnexpectedError", "Caught a Java Lang Exception") // Adding this line temporarily until this flows error handling gets updated + exceptionUtil.buildWorkflowException(execution, 500, "Caught a Java Lang Exception") + + }catch(Exception e){ + msoLogger.debug("Caught Exception during processJavaException Method: " + e) + execution.setVariable("UnexpectedError", "Exception in processJavaException method") // Adding this line temporarily until this flows error handling gets updated + exceptionUtil.buildWorkflowException(execution, 500, "Exception in processJavaException method") + } + msoLogger.debug("Completed processJavaException Method of " + Prefix) + } + +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteNetworkInstanceRollback.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteNetworkInstanceRollback.groovy new file mode 100644 index 0000000000..ca6e21eedc --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteNetworkInstanceRollback.groovy @@ -0,0 +1,338 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts; + +import groovy.xml.XmlUtil +import groovy.json.* +import org.onap.so.bpmn.core.UrnPropertiesReader +import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.onap.so.bpmn.common.scripts.ExceptionUtil +import org.onap.so.bpmn.common.scripts.NetworkUtils +import org.onap.so.bpmn.common.scripts.SDNCAdapterUtils +import org.onap.so.bpmn.common.scripts.VidUtils +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.rest.APIResponse; +import org.onap.so.rest.RESTClient +import org.onap.so.rest.RESTConfig + +import java.util.UUID; + +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.apache.commons.lang3.* +import org.apache.commons.codec.binary.Base64; +import org.springframework.web.util.UriUtils + +import org.onap.so.logger.MessageEnum +import org.onap.so.logger.MsoLogger + +/** + * This groovy class supports the <class>DoCreateNetworkInstanceRollback.bpmn</class> process. + * + */ +public class DoDeleteNetworkInstanceRollback extends AbstractServiceTaskProcessor { + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoDeleteNetworkInstanceRollback.class); + + String Prefix="DELNWKIR_" + ExceptionUtil exceptionUtil = new ExceptionUtil() + JsonUtils jsonUtil = new JsonUtils() + VidUtils vidUtils = new VidUtils(this) + NetworkUtils networkUtils = new NetworkUtils() + SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils() + + def className = getClass().getSimpleName() + + /** + * This method is executed during the preProcessRequest task of the <class>DoDeleteNetworkInstanceRollback.bpmn</class> process. + * @param execution + */ + public InitializeProcessVariables(DelegateExecution execution){ + /* Initialize all the process variables in this block */ + + execution.setVariable(Prefix + "WorkflowException", null) + + execution.setVariable(Prefix + "rollbackDeactivateSDNCRequest", null) + execution.setVariable(Prefix + "rollbackDeactivateSDNCResponse", "") + execution.setVariable(Prefix + "rollbackDeactivateSDNCReturnCode", "") + + execution.setVariable(Prefix + "rollbackSDNCRequest", "") + execution.setVariable(Prefix + "rollbackSDNCResponse", "") + execution.setVariable(Prefix + "rollbackSDNCReturnCode", "") + + execution.setVariable(Prefix + "rollbackNetworkRequest", null) + execution.setVariable(Prefix + "rollbackNetworkResponse", "") + execution.setVariable(Prefix + "rollbackNetworkReturnCode", "") + + execution.setVariable(Prefix + "Success", false) + execution.setVariable(Prefix + "fullRollback", false) + + } + + // ************************************************** + // Pre or Prepare Request Section + // ************************************************** + /** + * This method is executed during the preProcessRequest task of the <class>DoDeleteNetworkInstanceRollback.bpmn</class> process. + * @param execution + */ + public void preProcessRequest (DelegateExecution execution) { + + execution.setVariable("prefix",Prefix) + + msoLogger.trace("Inside preProcessRequest() of " + className + ".groovy ") + + try { + // initialize flow variables + InitializeProcessVariables(execution) + + // GET Incoming request/variables + String rollbackDeactivateSDNCRequest = null + String rollbackSDNCRequest = null + String rollbackNetworkRequest = null + + Map<String, String> rollbackData = execution.getVariable("rollbackData") + if (rollbackData != null && rollbackData instanceof Map) { + + if(rollbackData.containsKey("rollbackDeactivateSDNCRequest")) { + rollbackDeactivateSDNCRequest = rollbackData["rollbackDeactivateSDNCRequest"] + } + + if(rollbackData.containsKey("rollbackSDNCRequest")) { + rollbackSDNCRequest = rollbackData["rollbackSDNCRequest"] + } + + if(rollbackData.containsKey("rollbackNetworkRequest")) { + rollbackNetworkRequest = rollbackData["rollbackNetworkRequest"] + } + } + + execution.setVariable(Prefix + "rollbackNetworkRequest", rollbackNetworkRequest) + execution.setVariable(Prefix + "rollbackSDNCRequest", rollbackSDNCRequest) + execution.setVariable(Prefix + "rollbackDeactivateSDNCRequest", rollbackDeactivateSDNCRequest) + msoLogger.debug("'rollbackData': " + '\n' + execution.getVariable("rollbackData")) + + String sdncVersion = execution.getVariable("sdncVersion") + msoLogger.debug("sdncVersion? : " + sdncVersion) + + // PO Authorization Info / headers Authorization= + String basicAuthValuePO = UrnPropertiesReader.getVariable("mso.adapters.po.auth",execution) + try { + def encodedString = utils.getBasicAuth(basicAuthValuePO, UrnPropertiesReader.getVariable("mso.msoKey", execution)) + execution.setVariable("BasicAuthHeaderValuePO",encodedString) + execution.setVariable("BasicAuthHeaderValueSDNC", encodedString) + + } catch (IOException ex) { + String exceptionMessage = "Exception Encountered in DoCreateNetworkInstance, PreProcessRequest() - " + String dataErrorMessage = exceptionMessage + " Unable to encode PO/SDNC user/password string - " + ex.getMessage() + msoLogger.debug(dataErrorMessage ) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + } + + if (execution.getVariable("SavedWorkflowException1") != null) { + execution.setVariable(Prefix + "WorkflowException", execution.getVariable("SavedWorkflowException1")) + } else { + execution.setVariable(Prefix + "WorkflowException", execution.getVariable("WorkflowException")) + } + msoLogger.debug("*** WorkflowException : " + execution.getVariable(Prefix + "WorkflowException")) + if(execution.getVariable(Prefix + "WorkflowException") != null) { + // called by: DoCreateNetworkInstance, partial rollback + execution.setVariable(Prefix + "fullRollback", false) + + } else { + // called by: Macro - Full Rollback, WorkflowException = null + execution.setVariable(Prefix + "fullRollback", true) + + } + + msoLogger.debug("*** fullRollback? : " + execution.getVariable(Prefix + "fullRollback")) + + } catch (BpmnError e) { + throw e; + + } catch (Exception ex) { + sendSyncError(execution) + // caught exception + String exceptionMessage = "Exception Encountered in PreProcessRequest() of " + className + ".groovy ***** : " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + public void validateRollbackResponses (DelegateExecution execution) { + + execution.setVariable("prefix",Prefix) + + msoLogger.trace("Inside validateRollbackResponses() of DoDeleteNetworkInstanceRollback ") + + try { + + // validate SDNC activate response + String rollbackDeactivateSDNCMessages = "" + String rollbackDeactivateSDNCReturnCode = "200" + if (execution.getVariable(Prefix + "rollbackDeactivateSDNCRequest") != null) { + rollbackDeactivateSDNCReturnCode = execution.getVariable(Prefix + "rollbackDeactivateSDNCReturnCode") + String rollbackDeactivateSDNCResponse = execution.getVariable(Prefix + "rollbackDeactivateSDNCResponse") + String rollbackDeactivateSDNCReturnInnerCode = "" + rollbackDeactivateSDNCResponse = rollbackDeactivateSDNCResponse.replace('$', '').replace('<?xml version="1.0" encoding="UTF-8"?>', "") + if (rollbackDeactivateSDNCReturnCode == "200") { + if (utils.nodeExists(rollbackDeactivateSDNCResponse, "response-code")) { + rollbackDeactivateSDNCReturnInnerCode = utils.getNodeText(rollbackDeactivateSDNCResponse, "response-code") + if (rollbackDeactivateSDNCReturnInnerCode == "200" || rollbackDeactivateSDNCReturnInnerCode == "" || rollbackDeactivateSDNCReturnInnerCode == "0") { + rollbackDeactivateSDNCMessages = " + SNDC deactivate rollback completed." + } else { + rollbackDeactivateSDNCMessages = " + SDNC deactivate rollback failed. " + } + } else { + rollbackDeactivateSDNCMessages = " + SNDC deactivate rollback completed." + } + } else { + rollbackDeactivateSDNCMessages = " + SDNC deactivate rollback failed. " + } + msoLogger.debug(" SDNC deactivate rollback Code - " + rollbackDeactivateSDNCReturnCode) + msoLogger.debug(" SDNC deactivate rollback Response - " + rollbackDeactivateSDNCResponse) + } + + // validate SDNC rollback response + String rollbackSdncErrorMessages = "" + String rollbackSDNCReturnCode = "200" + if (execution.getVariable(Prefix + "rollbackSDNCRequest") != null) { + rollbackSDNCReturnCode = execution.getVariable(Prefix + "rollbackSDNCReturnCode") + String rollbackSDNCResponse = execution.getVariable(Prefix + "rollbackSDNCResponse") + String rollbackSDNCReturnInnerCode = "" + SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this) + rollbackSDNCResponse = rollbackSDNCResponse.replace('$', '').replace('<?xml version="1.0" encoding="UTF-8"?>', "") + if (rollbackSDNCReturnCode == "200") { + if (utils.nodeExists(rollbackSDNCResponse, "response-code")) { + rollbackSDNCReturnInnerCode = utils.getNodeText(rollbackSDNCResponse, "response-code") + if (rollbackSDNCReturnInnerCode == "200" || rollbackSDNCReturnInnerCode == "" || rollbackSDNCReturnInnerCode == "0") { + rollbackSdncErrorMessages = " + SNDC unassign rollback completed." + } else { + rollbackSdncErrorMessages = " + SDNC unassign rollback failed. " + } + } else { + rollbackSdncErrorMessages = " + SNDC unassign rollback completed." + } + } else { + rollbackSdncErrorMessages = " + SDNC unassign rollback failed. " + } + msoLogger.debug(" SDNC assign rollback Code - " + rollbackSDNCReturnCode) + msoLogger.debug(" SDNC assign rollback Response - " + rollbackSDNCResponse) + } + + // validate PO network rollback response + String rollbackNetworkErrorMessages = "" + String rollbackNetworkReturnCode = "200" + if (execution.getVariable(Prefix + "rollbackNetworkRequest") != null) { + rollbackNetworkReturnCode = execution.getVariable(Prefix + "rollbackNetworkReturnCode") + String rollbackNetworkResponse = execution.getVariable(Prefix + "rollbackNetworkResponse") + if (rollbackNetworkReturnCode != "200") { + rollbackNetworkErrorMessages = " + PO Network rollback failed. " + } else { + rollbackNetworkErrorMessages = " + PO Network rollback completed." + } + + msoLogger.debug(" NetworkRollback Code - " + rollbackNetworkReturnCode) + msoLogger.debug(" NetworkRollback Response - " + rollbackNetworkResponse) + } + + String statusMessage = "" + int errorCode = 7000 + msoLogger.debug("*** fullRollback? : " + execution.getVariable(Prefix + "fullRollback")) + if (execution.getVariable(Prefix + "fullRollback") == false) { + WorkflowException wfe = execution.getVariable(Prefix + "WorkflowException") // original WorkflowException + if (wfe != null) { + statusMessage = wfe.getErrorMessage() + errorCode = wfe.getErrorCode() + } else { + statusMessage = "See Previous Camunda flows for cause of Error: Undetermined Exception." + errorCode = '7000' + } + + // set if all rolledbacks are successful + if (rollbackDeactivateSDNCReturnCode == "200" && rollbackNetworkReturnCode == "200" && rollbackSDNCReturnCode == "200") { + execution.setVariable("rolledBack", true) + execution.setVariable("wasDeleted", true) + + } else { + execution.setVariable("rolledBack", false) + execution.setVariable("wasDeleted", true) + } + + statusMessage = statusMessage + rollbackDeactivateSDNCMessages + rollbackNetworkErrorMessages + rollbackSdncErrorMessages + msoLogger.debug("Final DoDeleteNetworkInstanceRollback status message: " + statusMessage) + String processKey = getProcessKey(execution); + WorkflowException exception = new WorkflowException(processKey, errorCode, statusMessage); + execution.setVariable("workflowException", exception); + + } else { + // rollback due to failures in Main flow (Macro or a-ala-carte) - Full rollback + if (rollbackDeactivateSDNCReturnCode == "200" && rollbackNetworkReturnCode == "200" && rollbackSDNCReturnCode == "200") { + execution.setVariable("rollbackSuccessful", true) + execution.setVariable("rollbackError", false) + } else { + String exceptionMessage = "Network Delete Rollback was not Successful. " + msoLogger.debug(exceptionMessage) + execution.setVariable("rollbackSuccessful", false) + execution.setVariable("rollbackError", true) + exceptionUtil.buildWorkflowException(execution, 7000, exceptionMessage) + throw new BpmnError("MSOWorkflowException") + } + } + + } catch (Exception ex) { + String errorMessage = "See Previous Camunda flows for cause of Error: Undetermined Exception." + String exceptionMessage = " Bpmn error encountered in DoDeleteNetworkInstanceRollback flow. validateRollbackResponses() - " + errorMessage + ": " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + // ******************************* + // Build Error Section + // ******************************* + + + + public void processJavaException(DelegateExecution execution){ + + execution.setVariable("prefix",Prefix) + + try{ + msoLogger.debug("Caught a Java Exception in " + Prefix) + msoLogger.debug("Started processJavaException Method") + msoLogger.debug("Variables List: " + execution.getVariables()) + execution.setVariable("UnexpectedError", "Caught a Java Lang Exception - " + Prefix) // Adding this line temporarily until this flows error handling gets updated + exceptionUtil.buildWorkflowException(execution, 500, "Caught a Java Lang Exception") + + }catch(Exception e){ + msoLogger.debug("Caught Exception during processJavaException Method: " + e) + execution.setVariable("UnexpectedError", "Exception in processJavaException method - " + Prefix) // Adding this line temporarily until this flows error handling gets updated + exceptionUtil.buildWorkflowException(execution, 500, "Exception in processJavaException method" + Prefix) + } + msoLogger.debug("Completed processJavaException Method in " + Prefix) + } + +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteResourcesV1.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteResourcesV1.groovy new file mode 100644 index 0000000000..a5a96f3bd3 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteResourcesV1.groovy @@ -0,0 +1,400 @@ + +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2018 Huawei Technologies Co., Ltd. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.so.bpmn.infrastructure.scripts + +import static org.apache.commons.lang3.StringUtils.isBlank + +import org.apache.commons.lang3.StringUtils +import org.apache.http.HttpResponse +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.json.JSONObject +import org.onap.so.bpmn.common.recipe.BpmnRestClient +import org.onap.so.bpmn.common.recipe.ResourceInput +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.onap.so.bpmn.common.scripts.CatalogDbUtils +import org.onap.so.bpmn.common.scripts.ExceptionUtil +import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.so.bpmn.core.domain.AllottedResource +import org.onap.so.bpmn.core.domain.NetworkResource +import org.onap.so.bpmn.core.domain.Resource +import org.onap.so.bpmn.core.domain.ServiceDecomposition +import org.onap.so.bpmn.core.domain.VnfResource +import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.bpmn.infrastructure.properties.BPMNProperties +import org.onap.so.logger.MsoLogger + +/** + * input for script : + * msoRequestId + * isDebugLogEnabled + * globalSubscriberId + * serviceType + * serviceInstanceId + * URN_mso_workflow_sdncadapter_callback + * serviceInputParams + * deleteResourceList + * resourceInstanceIDs + * + * output from script: + * + */ + +public class DoDeleteResourcesV1 extends AbstractServiceTaskProcessor { + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoDeleteResourcesV1.class); + + String Prefix="DDR_" + ExceptionUtil exceptionUtil = new ExceptionUtil() + JsonUtils jsonUtil = new JsonUtils() + CatalogDbUtils cutils = new CatalogDbUtils() + + public void preProcessRequest (DelegateExecution execution) { + def isDebugEnabled = execution.getVariable("isDebugLogEnabled") + utils.log("INFO"," ***** preProcessRequest *****", isDebugEnabled) + String msg = "" + + try { + String requestId = execution.getVariable("msoRequestId") + execution.setVariable("prefix",Prefix) + + //Inputs + //requestDetails.subscriberInfo. for AAI GET & PUT & SDNC assignToplology + String globalSubscriberId = execution.getVariable("globalSubscriberId") //globalCustomerId + if (globalSubscriberId == null) + { + execution.setVariable("globalSubscriberId", "") + } + + //requestDetails.requestParameters. for AAI PUT & SDNC assignTopology + String serviceType = execution.getVariable("serviceType") + if (serviceType == null) + { + execution.setVariable("serviceType", "") + } + + //Generated in parent for AAI PUT + String serviceInstanceId = execution.getVariable("serviceInstanceId") + if (isBlank(serviceInstanceId)){ + msg = "Input serviceInstanceId is null" + utils.log("INFO", msg, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + + String sdncCallbackUrl = execution.getVariable('URN_mso_workflow_sdncadapter_callback') + if (isBlank(sdncCallbackUrl)) { + msg = "URN_mso_workflow_sdncadapter_callback is null" + utils.log("INFO", msg, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + execution.setVariable("sdncCallbackUrl", sdncCallbackUrl) + utils.log("INFO","SDNC Callback URL: " + sdncCallbackUrl, isDebugEnabled) + + StringBuilder sbParams = new StringBuilder() + Map<String, String> paramsMap = execution.getVariable("serviceInputParams") + if (paramsMap != null) + { + sbParams.append("<service-input-parameters>") + for (Map.Entry<String, String> entry : paramsMap.entrySet()) { + String paramsXml + String paramName = entry.getKey() + String paramValue = entry.getValue() + paramsXml = + """ <param> + <name>${MsoUtils.xmlEscape(paramName)}</name> + <value>${MsoUtils.xmlEscape(paramValue)}</value> + </param> + """ + sbParams.append(paramsXml) + } + sbParams.append("</service-input-parameters>") + } + String siParamsXml = sbParams.toString() + if (siParamsXml == null) + siParamsXml = "" + execution.setVariable("siParamsXml", siParamsXml) + + } catch (BpmnError e) { + throw e; + } catch (Exception ex){ + msg = "Exception in preProcessRequest " + ex.getMessage() + utils.log("INFO", msg, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + utils.log("INFO"," ***** Exit preProcessRequest *****", isDebugEnabled) + } + + public void sequenceResource(DelegateExecution execution){ + def isDebugEnabled = execution.getVariable("isDebugLogEnabled") + + utils.log("INFO", " ======== STARTED sequenceResource Process ======== ", isDebugEnabled) + List<Resource> sequencedResourceList = new ArrayList<Resource>() + List<Resource> wanResources = new ArrayList<Resource>() + + // get delete resource list and order list + List<Resource> delResourceList = execution.getVariable("deleteResourceList") + + def resourceSequence = BPMNProperties.getResourceSequenceProp() + + if(resourceSequence != null) { + for (resourceType in resourceSequence.reverse()) { + for (resource in delResourceList) { + if (StringUtils.containsIgnoreCase(resource.getModelInfo().getModelName(), resourceType)) { + sequencedResourceList.add(resource) + + if (resource instanceof NetworkResource) { + wanResources.add(resource) + } + } + } + } + }else { + //define sequenced resource list, we deploy vf first and then network and then ar + //this is defaule sequence + List<VnfResource> vnfResourceList = new ArrayList<VnfResource>() + List<AllottedResource> arResourceList = new ArrayList<AllottedResource>() + for (Resource rc : delResourceList) { + if (rc instanceof VnfResource) { + vnfResourceList.add(rc) + } else if (rc instanceof NetworkResource) { + wanResources.add(rc) + } else if (rc instanceof AllottedResource) { + arResourceList.add(rc) + } + } + + sequencedResourceList.addAll(arResourceList) + sequencedResourceList.addAll(wanResources) + sequencedResourceList.addAll(vnfResourceList) + } + + String isContainsWanResource = wanResources.isEmpty() ? "false" : "true" + execution.setVariable("isContainsWanResource", isContainsWanResource) + execution.setVariable("currentResourceIndex", 0) + execution.setVariable("sequencedResourceList", sequencedResourceList) + utils.log("INFO", "resourceSequence: " + resourceSequence, isDebugEnabled) + utils.log("INFO", " ======== END sequenceResource Process ======== ", isDebugEnabled) + } + + /** + * prepare delete parameters + */ + public void preResourceDelete(DelegateExecution execution){ + + def isDebugEnabled = execution.getVariable("isDebugLogEnabled") + + utils.log("INFO", " ======== STARTED preResourceDelete Process ======== ", isDebugEnabled) + + List<Resource> sequencedResourceList = execution.getVariable("sequencedResourceList") + + int currentIndex = execution.getVariable("currentResourceIndex") + Resource curResource = sequencedResourceList.get(currentIndex); + + String resourceInstanceUUID = curResource.getResourceId() + String resourceTemplateUUID = curResource.getModelInfo().getModelUuid() + execution.setVariable("resourceInstanceId", resourceInstanceUUID) + execution.setVariable("currentResource", curResource) + utils.log("INFO", "Delete Resource Info resourceTemplate Id :" + resourceTemplateUUID + " resourceInstanceId: " + + resourceInstanceUUID + " resourceModelName: " + curResource.getModelInfo().getModelName(), isDebugEnabled) + + utils.log("INFO", " ======== END preResourceDelete Process ======== ", isDebugEnabled) + } + + + /** + * Execute delete workflow for resource + */ + public void executeResourceDelete(DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + utils.log("INFO", "======== Start executeResourceDelete Process ======== ", isDebugEnabled) + try { + String requestId = execution.getVariable("msoRequestId") + String serviceInstanceId = execution.getVariable("serviceInstanceId") + String serviceType = execution.getVariable("serviceType") + + String resourceInstanceId = execution.getVariable("resourceInstanceId") + + Resource currentResource = execution.getVariable("currentResource") + String action = "deleteInstance" + JSONObject resourceRecipe = cutils.getResourceRecipe(execution, currentResource.getModelInfo().getModelUuid(), action) + String recipeUri = resourceRecipe.getString("orchestrationUri") + int recipeTimeout = resourceRecipe.getInt("recipeTimeout") + String recipeParamXsd = resourceRecipe.get("paramXSD") + + + ResourceInput resourceInput = new ResourceInput(); + resourceInput.setServiceInstanceId(serviceInstanceId) + resourceInput.setResourceInstanceName(currentResource.getResourceInstanceName()) + resourceInput.setResourceInstancenUuid(currentResource.getResourceId()) + resourceInput.setOperationId(execution.getVariable("operationId")) + resourceInput.setOperationType(execution.getVariable("operationType")) + String globalSubscriberId = execution.getVariable("globalSubscriberId") + resourceInput.setGlobalSubscriberId(globalSubscriberId) + resourceInput.setResourceModelInfo(currentResource.getModelInfo()); + ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition") + resourceInput.setServiceModelInfo(serviceDecomposition.getModelInfo()); + resourceInput.setServiceType(serviceType) + + String recipeURL = BPMNProperties.getProperty("bpelURL", "http://mso:8080") + recipeUri + + HttpResponse resp = BpmnRestClient.post(recipeURL, requestId, recipeTimeout, action, serviceInstanceId, serviceType, resourceInput.toString(), recipeParamXsd) + utils.log("INFO", " ======== END executeResourceDelete Process ======== ", isDebugEnabled) + }catch(BpmnError b){ + msoLogger.debug("Rethrowing MSOWorkflowException") + throw b + }catch(Exception e){ + msoLogger.debug("Error occured within DoDeleteResourcesV1 executeResourceDelete method: " + e) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured during DoDeleteResourcesV1 executeResourceDelete Catalog") + } + } + + + public void parseNextResource(DelegateExecution execution){ + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + utils.log("INFO", "======== Start parseNextResource Process ======== ", isDebugEnabled) + def currentIndex = execution.getVariable("currentResourceIndex") + def nextIndex = currentIndex + 1 + execution.setVariable("currentResourceIndex", nextIndex) + List<String> sequencedResourceList = execution.getVariable("sequencedResourceList") + if(nextIndex >= sequencedResourceList.size()){ + execution.setVariable("allResourceFinished", "true") + }else{ + execution.setVariable("allResourceFinished", "false") + } + utils.log("INFO", "======== COMPLETED parseNextResource Process ======== ", isDebugEnabled) + } + + public void prepareFinishedProgressForResource(DelegateExecution execution) { + + String serviceInstanceId = execution.getVariable("serviceInstanceId") + String serviceType = execution.getVariable("serviceType") + String resourceInstanceId = execution.getVariable("resourceInstanceId") + Resource currentResource = execution.getVariable("currentResource") + String resourceCustomizationUuid = currentResource.getModelInfo().getModelCustomizationUuid() + String resourceModelName = currentResource.getModelInfo().getModelName() + String operationType = execution.getVariable("operationType") + String progress = "100" + String status = "finished" + String statusDescription = "The resource instance does not exist for " + resourceModelName + String operationId = execution.getVariable("operationId") + + String body = """ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" + xmlns:ns="http://org.onap.so/requestsdb"> + <soapenv:Header/> + <soapenv:Body> + <ns:updateResourceOperationStatus> + <operType>${MsoUtils.xmlEscape(operationType)}</operType> + <operationId>${MsoUtils.xmlEscape(operationId)}</operationId> + <progress>${MsoUtils.xmlEscape(progress)}</progress> + <resourceTemplateUUID>${MsoUtils.xmlEscape(resourceCustomizationUuid)}</resourceTemplateUUID> + <serviceId>${MsoUtils.xmlEscape(serviceInstanceId)}</serviceId> + <status>${MsoUtils.xmlEscape(status)}</status> + <statusDescription>${MsoUtils.xmlEscape(statusDescription)}</statusDescription> + </ns:updateResourceOperationStatus> + </soapenv:Body> + </soapenv:Envelope>"""; + + def dbAdapterEndpoint = execution.getVariable("URN_mso_adapters_openecomp_db_endpoint") + execution.setVariable("CVFMI_dbAdapterEndpoint", dbAdapterEndpoint) + execution.setVariable("CVFMI_updateResOperStatusRequest", body) + } + + public void prepareSDNCServiceDeactivateRequest (DelegateExecution execution) { + prepareSDNCServiceRequest (execution, "deactivate") + } + + public void prepareSDNCServiceDeleteRequest (DelegateExecution execution) { + prepareSDNCServiceRequest (execution, "delete") + } + + public void prepareSDNCServiceRequest (DelegateExecution execution, String svcAction) { + def isDebugEnabled = execution.getVariable("isDebugLogEnabled") + utils.log("INFO"," ***** Started prepareSDNCServiceRequest for " + svcAction + "*****", isDebugEnabled) + + try { + // get variables + String sdnc_svcAction = svcAction + String sdncCallback = execution.getVariable("URN_mso_workflow_sdncadapter_callback") + String hdrRequestId = execution.getVariable("msoRequestId") + String serviceInstanceId = execution.getVariable("serviceInstanceId") + String source = execution.getVariable("source") + String sdnc_service_id = serviceInstanceId + ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition") + String serviceType = execution.getVariable("serviceType") + String globalCustomerId = execution.getVariable("globalSubscriberId") + String serviceModelInvariantUuid = serviceDecomposition.getModelInfo().getModelInvariantUuid() + String serviceModelUuid = serviceDecomposition.getModelInfo().getModelUuid() + String serviceModelVersion = serviceDecomposition.getModelInfo().getModelVersion() + String serviceModelName = serviceDecomposition.getModelInfo().getModelName() + + // 1. prepare assign topology via SDNC Adapter SUBFLOW call + String sndcTopologyDeleteRequest = + """<aetgt:SDNCAdapterWorkflowRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:sdncadapter="http://org.onap.so/workflow/sdnc/adapter/schema/v1" + xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1"> + <sdncadapter:RequestHeader> + <sdncadapter:RequestId>${MsoUtils.xmlEscape(hdrRequestId)}</sdncadapter:RequestId> + <sdncadapter:SvcInstanceId>${MsoUtils.xmlEscape(serviceInstanceId)}</sdncadapter:SvcInstanceId> + <sdncadapter:SvcAction>${MsoUtils.xmlEscape(sdnc_svcAction)}</sdncadapter:SvcAction> + <sdncadapter:SvcOperation>service-topology-operation</sdncadapter:SvcOperation> + <sdncadapter:CallbackUrl>sdncCallback</sdncadapter:CallbackUrl> + <sdncadapter:MsoAction>generic-resource</sdncadapter:MsoAction> + </sdncadapter:RequestHeader> + <sdncadapterworkflow:SDNCRequestData> + <request-information> + <request-id>${MsoUtils.xmlEscape(hdrRequestId)}</request-id> + <request-action>DeleteServiceInstance</request-action> + <source>${MsoUtils.xmlEscape(source)}</source> + <notification-url></notification-url> + <order-number></order-number> + <order-version></order-version> + </request-information> + <service-information> + <service-id>${MsoUtils.xmlEscape(serviceInstanceId)}</service-id> + <subscription-service-type>${MsoUtils.xmlEscape(serviceType)}</subscription-service-type> + <onap-model-information> + <model-invariant-uuid>${MsoUtils.xmlEscape(serviceModelInvariantUuid)}</model-invariant-uuid> + <model-uuid>${MsoUtils.xmlEscape(serviceModelUuid)}</model-uuid> + <model-version>${MsoUtils.xmlEscape(serviceModelVersion)}</model-version> + <model-name>${MsoUtils.xmlEscape(serviceModelName)}</model-name> + </onap-model-information> + <service-instance-id>${MsoUtils.xmlEscape(serviceInstanceId)}</service-instance-id> + <global-customer-id>${MsoUtils.xmlEscape(globalCustomerId)}</global-customer-id> + </service-information> + <service-request-input> + </service-request-input> + </sdncadapterworkflow:SDNCRequestData> + </aetgt:SDNCAdapterWorkflowRequest>""".trim() + + String sndcTopologyDeleteRequesAsString = utils.formatXml(sndcTopologyDeleteRequest) + utils.logAudit(sndcTopologyDeleteRequesAsString) + execution.setVariable("sdncAdapterWorkflowRequest", sndcTopologyDeleteRequesAsString) + utils.log("INFO","sdncAdapterWorkflowRequest - " + "\n" + sndcTopologyDeleteRequesAsString, isDebugEnabled) + + } catch (Exception ex) { + String exceptionMessage = " Bpmn error encountered in DoDeleteResourcesV1 flow. prepareSDNCServiceRequest() - " + ex.getMessage() + utils.log("DEBUG", exceptionMessage, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + utils.log("INFO","***** Exit prepareSDNCServiceRequest for " + svcAction + "*****", isDebugEnabled) + } +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteServiceInstance.groovy new file mode 100644 index 0000000000..c7e3eb437c --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteServiceInstance.groovy @@ -0,0 +1,382 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts + +import static org.apache.commons.lang3.StringUtils.*; + +import org.apache.commons.lang3.* +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.onap.aai.domain.yang.ServiceInstance +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.onap.so.bpmn.common.scripts.ExceptionUtil +import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.so.bpmn.common.scripts.SDNCAdapterUtils +import org.onap.so.bpmn.core.UrnPropertiesReader; +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.client.aai.AAIObjectType +import org.onap.so.client.aai.AAIResourcesClient +import org.onap.so.client.aai.entities.AAIResultWrapper +import org.onap.so.client.aai.entities.uri.AAIResourceUri +import org.onap.so.client.aai.entities.uri.AAIUriFactory +import org.onap.so.logger.MsoLogger +import org.springframework.web.util.UriUtils; + +import groovy.json.* + +/** + * This groovy class supports the <class>DoDeleteServiceInstance.bpmn</class> process. + * + * Inputs: + * @param - msoRequestId + * @param - globalSubscriberId - O + * @param - subscriptionServiceType - O + * @param - serviceInstanceId + * @param - serviceInstanceName - O + * @param - serviceModelInfo - O + * @param - productFamilyId + * @param - serviceInputParams (should contain aic_zone for serviceTypes TRANSPORT,ATM) + * @param - sdncVersion + * @param - failNotFound - TODO + * @param - serviceInputParams - TODO + * + * Outputs: + * @param - WorkflowException + * + * Rollback - Deferred + */ +public class DoDeleteServiceInstance extends AbstractServiceTaskProcessor { + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoDeleteServiceInstance.class); + + String Prefix="DDELSI_" + ExceptionUtil exceptionUtil = new ExceptionUtil() + JsonUtils jsonUtil = new JsonUtils() + + public void preProcessRequest (DelegateExecution execution) { + + msoLogger.trace("preProcessRequest ") + String msg = "" + + try { + String requestId = execution.getVariable("msoRequestId") + execution.setVariable("prefix",Prefix) + + //Inputs + //requestDetails.subscriberInfo. for AAI GET & PUT & SDNC assignToplology + String globalSubscriberId = execution.getVariable("globalSubscriberId") //globalCustomerId + if (globalSubscriberId == null) + { + execution.setVariable("globalSubscriberId", "") + } + + //requestDetails.requestParameters. for AAI PUT & SDNC assignTopology + String subscriptionServiceType = execution.getVariable("subscriptionServiceType") + if (subscriptionServiceType == null) + { + execution.setVariable("subscriptionServiceType", "") + } + + //Generated in parent for AAI PUT + String serviceInstanceId = execution.getVariable("serviceInstanceId") + if (isBlank(serviceInstanceId)){ + msg = "Input serviceInstanceId is null" + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + + String sdncCallbackUrl = UrnPropertiesReader.getVariable('mso.workflow.sdncadapter.callback',execution) + if (isBlank(sdncCallbackUrl)) { + msg = "mso.workflow.sdncadapter.callback is null" + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + execution.setVariable("sdncCallbackUrl", sdncCallbackUrl) + msoLogger.debug("SDNC Callback URL: " + sdncCallbackUrl) + + StringBuilder sbParams = new StringBuilder() + Map<String, String> paramsMap = execution.getVariable("serviceInputParams") + if (paramsMap != null) + { + sbParams.append("<service-input-parameters>") + for (Map.Entry<String, String> entry : paramsMap.entrySet()) { + String paramsXml + String paramName = entry.getKey() + String paramValue = entry.getValue() + paramsXml = + """ <param> + <name>${MsoUtils.xmlEscape(paramName)}</name> + <value>${MsoUtils.xmlEscape(paramValue)}</value> + </param> + """ + sbParams.append(paramsXml) + } + sbParams.append("</service-input-parameters>") + } + String siParamsXml = sbParams.toString() + if (siParamsXml == null) + siParamsXml = "" + execution.setVariable("siParamsXml", siParamsXml) + + } catch (BpmnError e) { + throw e; + } catch (Exception ex){ + msg = "Exception in preProcessRequest " + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.trace("Exit preProcessRequest ") + } + + public void preProcessSDNCDelete (DelegateExecution execution) { + + msoLogger.trace("preProcessSDNCDelete ") + String msg = "" + + try { + def serviceInstanceId = execution.getVariable("serviceInstanceId") ?: "" + def serviceInstanceName = execution.getVariable("serviceInstanceName") ?: "" + def callbackURL = execution.getVariable("sdncCallbackUrl") ?: "" + def requestId = execution.getVariable("msoRequestId") ?: "" + def serviceId = execution.getVariable("productFamilyId") ?: "" + def subscriptionServiceType = execution.getVariable("subscriptionServiceType") ?: "" + def globalSubscriberId = execution.getVariable("globalSubscriberId") ?: "" //globalCustomerId + + String serviceModelInfo = execution.getVariable("serviceModelInfo") ?: "" + def modelInvariantUuid = "" + def modelVersion = "" + def modelUuid = "" + def modelName = "" + if (!isBlank(serviceModelInfo)) + { + modelInvariantUuid = jsonUtil.getJsonValue(serviceModelInfo, "modelInvariantUuid") ?: "" + modelVersion = jsonUtil.getJsonValue(serviceModelInfo, "modelVersion") ?: "" + modelUuid = jsonUtil.getJsonValue(serviceModelInfo, "modelUuid") ?: "" + modelName = jsonUtil.getJsonValue(serviceModelInfo, "modelName") ?: "" + + } + + def siParamsXml = execution.getVariable("siParamsXml") ?: "" + def msoAction = "" + // special URL for SDNW, msoAction helps set diff url in SDNCA + if("TRANSPORT".equalsIgnoreCase(execution.getVariable("serviceType"))) + { + msoAction = "TRANSPORT" + } + + def sdncRequestId = UUID.randomUUID().toString() + + String sdncDelete = + """<sdncadapterworkflow:SDNCAdapterWorkflowRequest xmlns:ns5="http://org.onap/so/request/types/v1" + xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1" + xmlns:sdncadapter="http://org.onap/workflow/sdnc/adapter/schema/v1"> + <sdncadapter:RequestHeader> + <sdncadapter:RequestId>${MsoUtils.xmlEscape(sdncRequestId)}</sdncadapter:RequestId> + <sdncadapter:SvcInstanceId>${MsoUtils.xmlEscape(serviceInstanceId)}</sdncadapter:SvcInstanceId> + <sdncadapter:SvcAction>delete</sdncadapter:SvcAction> + <sdncadapter:SvcOperation>service-topology-operation</sdncadapter:SvcOperation> + <sdncadapter:CallbackUrl>${MsoUtils.xmlEscape(callbackURL)}</sdncadapter:CallbackUrl> + <sdncadapter:MsoAction>${MsoUtils.xmlEscape(msoAction)}</sdncadapter:MsoAction> + </sdncadapter:RequestHeader> + <sdncadapterworkflow:SDNCRequestData> + <request-information> + <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> + <source>MSO</source> + <notification-url/> + <order-number/> + <order-version/> + <request-action>DeleteServiceInstance</request-action> + </request-information> + <service-information> + <service-id>${MsoUtils.xmlEscape(serviceId)}</service-id> + <subscription-service-type>${MsoUtils.xmlEscape(subscriptionServiceType)}</subscription-service-type> + <onap-model-information> + <model-invariant-uuid>${MsoUtils.xmlEscape(modelInvariantUuid)}</model-invariant-uuid> + <model-uuid>${MsoUtils.xmlEscape(modelUuid)}</model-uuid> + <model-version>${MsoUtils.xmlEscape(modelVersion)}</model-version> + <model-name>${MsoUtils.xmlEscape(modelName)}</model-name> + </onap-model-information> + <service-instance-id>${MsoUtils.xmlEscape(serviceInstanceId)}</service-instance-id> + <subscriber-name/> + <global-customer-id>${MsoUtils.xmlEscape(globalSubscriberId)}</global-customer-id> + </service-information> + <service-request-input> + <service-instance-name>${MsoUtils.xmlEscape(serviceInstanceName)}</service-instance-name> + ${siParamsXml} + </service-request-input> + </sdncadapterworkflow:SDNCRequestData> + </sdncadapterworkflow:SDNCAdapterWorkflowRequest>""" + + sdncDelete = utils.formatXml(sdncDelete) + def sdncRequestId2 = UUID.randomUUID().toString() + String sdncDeactivate = sdncDelete.replace(">delete<", ">deactivate<").replace(">${sdncRequestId}<", ">${sdncRequestId2}<") + execution.setVariable("sdncDelete", sdncDelete) + execution.setVariable("sdncDeactivate", sdncDeactivate) + msoLogger.debug("sdncDeactivate:\n" + sdncDeactivate) + msoLogger.debug("sdncDelete:\n" + sdncDelete) + + } catch (BpmnError e) { + throw e; + } catch(Exception ex) { + msg = "Exception in preProcessSDNCDelete. " + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, "Exception Occured in preProcessSDNCDelete.\n" + ex.getMessage()) + } + msoLogger.debug(" *****Exit preProcessSDNCDelete *****") + } + + public void postProcessSDNCDelete(DelegateExecution execution, String response, String method) { + + + msoLogger.trace("postProcessSDNC " + method + " ") + String msg = "" + + try { + WorkflowException workflowException = execution.getVariable("WorkflowException") + boolean successIndicator = execution.getVariable("SDNCA_SuccessIndicator") + msoLogger.debug("SDNCResponse: " + response) + msoLogger.debug("workflowException: " + workflowException) + + SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this) + sdncAdapterUtils.validateSDNCResponse(execution, response, workflowException, successIndicator) + + if(execution.getVariable(Prefix + 'sdncResponseSuccess') == true){ + msoLogger.debug("Good response from SDNC Adapter for service-instance " + method + "response:\n" + response) + + }else{ + msg = "Bad Response from SDNC Adapter for service-instance " + method + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 3500, msg) + } + } catch (BpmnError e) { + throw e; + } catch(Exception ex) { + msg = "Exception in postProcessSDNC " + method + " Exception:" + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.trace("Exit postProcessSDNC " + method + " ") + } + + /** + * Gets the service instance uri from aai + */ + public void getServiceInstance(DelegateExecution execution) { + msoLogger.trace("getServiceInstance ") + try { + String serviceInstanceId = execution.getVariable('serviceInstanceId') + + AAIResourcesClient resourceClient = new AAIResourcesClient() + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, serviceInstanceId) + + if(resourceClient.exists(uri)){ + execution.setVariable("GENGS_siResourceLink", uri.build().toString()) + Map<String, String> keys = uri.getURIKeys() + String globalSubscriberId = execution.getVariable("globalSubscriberId") + if(isBlank(globalSubscriberId)){ + globalSubscriberId = keys.get("global-customer-id") + execution.setVariable("globalSubscriberId", globalSubscriberId) + } + + //Extract Service Type if not provided on request + String subscriptionServiceType = execution.getVariable("subscriptionServiceType") + if(isBlank(subscriptionServiceType)){ + String serviceTypeEncoded = keys.get("service-type") //TODO will this produce as already decoded? + subscriptionServiceType = UriUtils.decode(serviceTypeEncoded, "UTF-8") + execution.setVariable("subscriptionServiceType", subscriptionServiceType) + } + + AAIResultWrapper wrapper = resourceClient.get(uri) + List<AAIResourceUri> uriList = wrapper.getRelationships().get().getRelatedAAIUris(AAIObjectType.ALLOTTED_RESOURCE) + uriList.addAll(wrapper.getRelationships().get().getRelatedAAIUris(AAIObjectType.GENERIC_VNF)) + uriList.addAll(wrapper.getRelationships().get().getRelatedAAIUris(AAIObjectType.L3_NETWORK)) + + if(uriList.isEmpty){ + ServiceInstance si = wrapper.asBean(ServiceInstance.class) + String orchestrationStatus = si.getOrchestrationStatus() + String serviceType = si.getServiceType() + execution.setVariable("serviceType", serviceType) + execution.setVariable("serviceRole", si.getServiceRole()) + + if("TRANSPORT".equalsIgnoreCase(serviceType)){ + if("PendingDelete".equals(orchestrationStatus)){ + execution.setVariable("skipDeactivate", true) + }else{ + exceptionUtil.buildAndThrowWorkflowException(execution, 500, "ServiceInstance of type TRANSPORT must in PendingDelete status to allow Delete. Orchestration-status: " + orchestrationStatus) + } + } + + String svcTypes = UrnPropertiesReader.getVariable("sdnc.si.svc.types",execution) ?: "" + List<String> svcList = Arrays.asList(svcTypes.split("\\s*,\\s*")); + boolean isSdncService= false + for(String listEntry : svcList){ + if(listEntry.equalsIgnoreCase(serviceType)){ + isSdncService = true + break; + } + } + execution.setVariable("sendToSDNC", true) + if(execution.getVariable("sdncVersion").equals("1610")){ + if(!isSdncService){ + execution.setVariable("sendToSDNC", false) + } + } + + }else{ + execution.setVariable("siInUse", true) + msoLogger.debug("Stopped deleting Service Instance, it has dependencies") + exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Stopped deleting Service Instance, it has dependencies") + } + }else{ + exceptionUtil.buildAndThrowWorkflowException(execution, 500, "ServiceInstance not found in aai") + } + + }catch(BpmnError e) { + throw e; + }catch (Exception ex){ + String msg = "Exception in getServiceInstance. " + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + } + + /** + * Deletes the service instance in aai + */ + public void deleteServiceInstance(DelegateExecution execution) { + msoLogger.trace("Entered deleteServiceInstance") + try { + String globalCustId = execution.getVariable("globalSubscriberId") + String serviceType = execution.getVariable("subscriptionServiceType") + String serviceInstanceId = execution.getVariable("serviceInstanceId") + + AAIResourcesClient resourceClient = new AAIResourcesClient(); + AAIResourceUri serviceInstanceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, globalCustId, serviceType, serviceInstanceId) + resourceClient.delete(serviceInstanceUri) + + msoLogger.trace("Exited deleteServiceInstance") + }catch(Exception e){ + msoLogger.debug("Error occured within deleteServiceInstance method: " + e) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Error occured during deleteServiceInstance from aai") + } + } + +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVFCNetworkServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVFCNetworkServiceInstance.groovy new file mode 100644 index 0000000000..0069bf4f0a --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVFCNetworkServiceInstance.groovy @@ -0,0 +1,285 @@ +/*- + * ============LICENSE_START======================================================= + * OPENECOMP - SO + * ================================================================================ + * Copyright (C) 2017 Huawei Technologies Co., Ltd. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts; + +import static org.apache.commons.lang3.StringUtils.* + +import org.apache.commons.lang3.* +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.onap.so.bpmn.common.scripts.ExceptionUtil +import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.logger.MessageEnum +import org.onap.so.logger.MsoLogger +import org.onap.so.rest.APIResponse +import org.onap.so.rest.RESTClient +import org.onap.so.rest.RESTConfig + +import groovy.json.* + +/** + * This groovy class supports the <class>DoDeleteVFCNetworkServiceInstance.bpmn</class> process. + * flow for E2E ServiceInstance Delete + */ +public class DoDeleteVFCNetworkServiceInstance extends AbstractServiceTaskProcessor { + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoDeleteVFCNetworkServiceInstance.class); + + + String vfcUrl = "/vfc/rest/v1/vfcadapter" + + String host = "http://mso.mso.testlab.openecomp.org:8080" + + ExceptionUtil exceptionUtil = new ExceptionUtil() + + JsonUtils jsonUtil = new JsonUtils() + + /** + * Pre Process the BPMN Flow Request + * Inclouds: + * generate the nsOperationKey + */ + public void preProcessRequest (DelegateExecution execution) { + + String msg = "" + msoLogger.trace("preProcessRequest() ") + try { + //deal with operation key + String globalSubscriberId = execution.getVariable("globalSubscriberId") + msoLogger.info("globalSubscriberId:" + globalSubscriberId) + String serviceType = execution.getVariable("serviceType") + msoLogger.info("serviceType:" + serviceType) + String serviceId = execution.getVariable("serviceId") + msoLogger.info("serviceId:" + serviceId) + String operationId = execution.getVariable("operationId") + msoLogger.info("serviceType:" + serviceType) + String nodeTemplateUUID = execution.getVariable("resourceTemplateId") + msoLogger.info("nodeTemplateUUID:" + nodeTemplateUUID) + String nsInstanceId = execution.getVariable("resourceInstanceId") + msoLogger.info("nsInstanceId:" + nsInstanceId) + execution.setVariable("nsInstanceId",nsInstanceId) + String nsOperationKey = """{ + "globalSubscriberId":"${globalSubscriberId}", + "serviceType":"${serviceType}", + "serviceId":"${serviceId}", + "operationId":"${operationId}", + "nodeTemplateUUID":"${nodeTemplateUUID}" + }""" + execution.setVariable("nsOperationKey", nsOperationKey); + msoLogger.info("nsOperationKey:" + nsOperationKey) + } catch (BpmnError e) { + throw e; + } catch (Exception ex){ + msg = "Exception in preProcessRequest " + ex.getMessage() + msoLogger.info(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.trace("Exit preProcessRequest ") + } + + /** + * unwind NS from AAI relationship + */ + public void deleteNSRelationship(DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + utils.log("INFO"," ***** deleteNSRelationship *****", isDebugEnabled) + String nsInstanceId = execution.getVariable("resourceInstanceId") + if(nsInstanceId == null || nsInstanceId == ""){ + utils.log("INFO"," Delete NS failed", isDebugEnabled) + return + } + String globalSubscriberId = execution.getVariable("globalSubscriberId") + String serviceType = execution.getVariable("serviceType") + String serviceId = execution.getVariable("serviceId") + String deleteRelationPayload = """<relationship xmlns="http://org.openecomp.aai.inventory/v11"> + <related-to>service-instance</related-to> + <related-link>/aai/v11/business/customers/customer/${globalSubscriberId}/service-subscriptions/service-subscription/${serviceType}/service-instances/service-instance/${nsInstanceId}</related-link> + <relationship-data> + <relationship-key>customer.global-customer-id</relationship-key> + <relationship-value>${MsoUtils.xmlEscape(globalSubscriberId)}</relationship-value> + </relationship-data> + <relationship-data> + <relationship-key>service-subscription.service-type</relationship-key> + <relationship-value>${MsoUtils.xmlEscape(serviceType)}</relationship-value> + </relationship-data> + <relationship-data> + <relationship-key>service-instance.service-instance-id</relationship-key> + <relationship-value>${MsoUtils.xmlEscape(nsInstanceId)}</relationship-value> + </relationship-data> + </relationship>""" + String endpoint = execution.getVariable("URN_aai_endpoint") + utils.log("INFO","Delete Relationship req:\n" + deleteRelationPayload, isDebugEnabled) + String url = endpoint + "/aai/v11/business/customers/customer/" + globalSubscriberId + "/service-subscriptions/service-subscription/" + serviceType + "/service-instances/service-instance/" + serviceId + "/relationship-list/relationship" + + APIResponse aaiRsp = executeAAIDeleteCall(execution, url, deleteRelationPayload) + utils.log("INFO","aai response status code:" + aaiRsp.getStatusCode(), isDebugEnabled) + utils.log("INFO","aai response content:" + aaiRsp.getResponseBodyAsString(), isDebugEnabled) + utils.log("INFO"," *****Exit deleteNSRelationship *****", isDebugEnabled) + } + + public APIResponse executeAAIDeleteCall(DelegateExecution execution, String url, String payload){ + def isDebugEnabled = execution.getVariable("isDebugLogEnabled") + utils.log("INFO", " ======== Started Execute AAI Delete Process ======== ", isDebugEnabled) + APIResponse apiResponse = null + try{ + String uuid = utils.getRequestID() + utils.log("INFO","Generated uuid is: " + uuid, isDebugEnabled) + utils.log("INFO","URL to be used is: " + url, isDebugEnabled) + String userName = execution.getVariable("URN_aai_auth") + String password = execution.getVariable("URN_mso_msoKey") + String basicAuthCred = utils.getBasicAuth(userName,password) + RESTConfig config = new RESTConfig(url); + RESTClient client = new RESTClient(config).addHeader("X-FromAppId", "MSO").addHeader("X-TransactionId", uuid).addHeader("Content-Type", "application/xml").addHeader("Accept","application/xml"); + if (basicAuthCred != null && !"".equals(basicAuthCred)) { + client.addAuthorizationHeader(basicAuthCred) + } + apiResponse = client.httpDelete(payload) + utils.log("INFO","======== Completed Execute AAI Delete Process ======== ", isDebugEnabled) + }catch(Exception e){ + utils.log("ERROR","Exception occured while executing AAI Put Call. Exception is: \n" + e, isDebugEnabled) + throw new BpmnError("MSOWorkflowException") + } + return apiResponse + } + + /** + * delete NS task + */ + public void deleteNetworkService(DelegateExecution execution) { + + msoLogger.trace("deleteNetworkService start ") + String nsOperationKey = execution.getVariable("nsOperationKey"); + String url = host + vfcUrl + "/ns/" + execution.getVariable("nsInstanceId") + APIResponse apiResponse = deleteRequest(execution, url, nsOperationKey) + String returnCode = apiResponse.getStatusCode() + String apiResponseAsString = apiResponse.getResponseBodyAsString() + String operationStatus = "error"; + if(returnCode== "200" || returnCode== "202"){ + operationStatus = "finished" + } + execution.setVariable("operationStatus", operationStatus) + + msoLogger.trace("deleteNetworkService end ") + } + + /** + * instantiate NS task + */ + public void terminateNetworkService(DelegateExecution execution) { + + msoLogger.trace("terminateNetworkService start ") + String nsOperationKey = execution.getVariable("nsOperationKey") + String url = host + vfcUrl + "/ns/" + execution.getVariable("nsInstanceId") + "/terminate" + APIResponse apiResponse = postRequest(execution, url, nsOperationKey) + String returnCode = apiResponse.getStatusCode() + String aaiResponseAsString = apiResponse.getResponseBodyAsString() + String jobId = ""; + if(returnCode== "200" || returnCode== "202"){ + jobId = jsonUtil.getJsonValue(aaiResponseAsString, "jobId") + } + execution.setVariable("jobId", jobId) + msoLogger.trace("terminateNetworkService end ") + } + + /** + * query NS task + */ + public void queryNSProgress(DelegateExecution execution) { + + msoLogger.trace("queryNSProgress start ") + String jobId = execution.getVariable("jobId") + String nsOperationKey = execution.getVariable("nsOperationKey"); + String url = host + vfcUrl + "/jobs/" + execution.getVariable("jobId") + APIResponse apiResponse = postRequest(execution, url, nsOperationKey) + String returnCode = apiResponse.getStatusCode() + String apiResponseAsString = apiResponse.getResponseBodyAsString() + String operationProgress = "100" + if(returnCode== "200"){ + operationProgress = jsonUtil.getJsonValue(apiResponseAsString, "responseDescriptor.progress") + } + execution.setVariable("operationProgress", operationProgress) + msoLogger.trace("queryNSProgress end ") + } + + /** + * delay 5 sec + */ + public void timeDelay(DelegateExecution execution) { + try { + Thread.sleep(5000); + } catch(InterruptedException e) { + msoLogger.info("Time Delay exception" + e) + } + } + + /** + * finish NS task + */ + public void finishNSDelete(DelegateExecution execution) { + //no need to do anything util now + } + + /** + * post request + * url: the url of the request + * requestBody: the body of the request + */ + private APIResponse postRequest(DelegateExecution execution, String url, String requestBody){ + + msoLogger.trace("Started Execute VFC adapter Post Process ") + msoLogger.info("url:"+url +"\nrequestBody:"+ requestBody) + APIResponse apiResponse = null + try{ + RESTConfig config = new RESTConfig(url); + RESTClient client = new RESTClient(config).addHeader("Content-Type", "application/json").addHeader("Accept","application/json").addHeader("Authorization","Basic QlBFTENsaWVudDpwYXNzd29yZDEk");; + apiResponse = client.httpPost(requestBody) + msoLogger.info("response code:"+ apiResponse.getStatusCode() +"\nresponse body:"+ apiResponse.getResponseBodyAsString()) + msoLogger.trace("Completed Execute VF-C adapter Post Process ") + }catch(Exception e){ + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception occured while executing VF-C Post Call. Exception is: \n" + e, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + throw new BpmnError("MSOWorkflowException") + } + return apiResponse + } + /** + * delete request + * url: the url of the request + * requestBody: the body of the request + */ + private APIResponse deleteRequest(DelegateExecution execution, String url, String requestBody){ + + msoLogger.trace("Started Execute VFC adapter Delete Process ") + msoLogger.info("url:"+url +"\nrequestBody:"+ requestBody) + APIResponse apiResponse = null + try{ + RESTConfig config = new RESTConfig(url); + RESTClient client = new RESTClient(config).addHeader("Content-Type", "application/json").addHeader("Accept","application/json").addHeader("Authorization","Basic QlBFTENsaWVudDpwYXNzd29yZDEk"); + apiResponse = client.httpDelete(requestBody) + msoLogger.info("response code:"+ apiResponse.getStatusCode() +"\nresponse body:"+ apiResponse.getResponseBodyAsString()) + msoLogger.trace("Completed Execute VF-C adapter Delete Process ") + }catch(Exception e){ + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception occured while executing VF-C Post Call. Exception is: \n" + e, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + throw new BpmnError("MSOWorkflowException") + } + return apiResponse + } +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVfModule.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVfModule.groovy new file mode 100644 index 0000000000..b41b74e509 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVfModule.groovy @@ -0,0 +1,711 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts + +import javax.xml.parsers.DocumentBuilder +import javax.xml.parsers.DocumentBuilderFactory + +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.onap.so.bpmn.common.scripts.AaiUtil +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.onap.so.bpmn.common.scripts.ExceptionUtil +import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.so.bpmn.common.scripts.SDNCAdapterUtils +import org.onap.so.bpmn.common.scripts.VfModule +import org.onap.so.bpmn.core.UrnPropertiesReader +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.logger.MessageEnum +import org.onap.so.logger.MsoLogger +import org.onap.so.rest.APIResponse +import org.onap.so.rest.RESTClient +import org.onap.so.rest.RESTConfig +import org.springframework.web.util.UriUtils +import org.w3c.dom.Document +import org.w3c.dom.Element +import org.w3c.dom.Node +import org.w3c.dom.NodeList; +import org.xml.sax.InputSource + +/* Subflow for Delete VF Module. When no DoDeleteVfModuleRequest is specified on input, + * functions as a building block subflow + +* Inputs for building block interface: +* @param - requestId +* @param - isDebugLogEnabled +* @param - vnfId +* @param - vfModuleId +* @param - serviceInstanceId +* @param - vfModuleName O +* @param - vfModuleModelInfo +* @param - cloudConfiguration* +* @param - sdncVersion ("1610") +* @param - retainResources +* @param - aLaCarte +* +* Outputs: +* @param - WorkflowException +* +*/ +public class DoDeleteVfModule extends AbstractServiceTaskProcessor{ + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoDeleteVfModule.class); + + def Prefix="DoDVfMod_" + + ExceptionUtil exceptionUtil = new ExceptionUtil() + JsonUtils jsonUtil = new JsonUtils() + + public void initProcessVariables(DelegateExecution execution) { + execution.setVariable("prefix",Prefix) + execution.setVariable("DoDVfMod_contrailNetworkPolicyFqdnList", null) + execution.setVariable("DoDVfMod_oamManagementV4Address", null) + execution.setVariable("DoDVfMod_oamManagementV6Address", null) + + } + + // parse the incoming DELETE_VF_MODULE request for the Generic Vnf and Vf Module Ids + // and formulate the outgoing request for PrepareUpdateAAIVfModuleRequest + public void preProcessRequest(DelegateExecution execution) { + + initProcessVariables(execution) + + try { + def xml = execution.getVariable("DoDeleteVfModuleRequest") + String vnfId = "" + String vfModuleId = "" + + if (xml == null || xml.isEmpty()) { + // Building Block-type request + + // Set mso-request-id to request-id for VNF Adapter interface + String requestId = execution.getVariable("requestId") + execution.setVariable("mso-request-id", requestId) + + String cloudConfiguration = execution.getVariable("cloudConfiguration") + String vfModuleModelInfo = execution.getVariable("vfModuleModelInfo") + String tenantId = jsonUtil.getJsonValue(cloudConfiguration, "tenantId") + execution.setVariable("tenantId", tenantId) + String cloudSiteId = jsonUtil.getJsonValue(cloudConfiguration, "lcpCloudRegionId") + execution.setVariable("cloudSiteId", cloudSiteId) + // Source is HARDCODED + String source = "VID" + execution.setVariable("source", source) + // SrvInstId is hardcoded to empty + execution.setVariable("srvInstId", "") + // ServiceId is hardcoded to empty + execution.setVariable("serviceId", "") + String serviceInstanceId = execution.getVariable("serviceInstanceId") + vnfId = execution.getVariable("vnfId") + vfModuleId = execution.getVariable("vfModuleId") + if (serviceInstanceId == null || serviceInstanceId.isEmpty()) { + execution.setVariable(Prefix + "serviceInstanceIdToSdnc", vfModuleId) + } + else { + execution.setVariable(Prefix + "serviceInstanceIdToSdnc", serviceInstanceId) + } + //vfModuleModelName + def vfModuleModelName = jsonUtil.getJsonValue(vfModuleModelInfo, "modelName") + execution.setVariable("vfModuleModelName", vfModuleModelName) + // retainResources + def retainResources = execution.getVariable("retainResources") + if (retainResources == null) { + retainResources = false + } + execution.setVariable("retainResources", retainResources) + } + else { + + msoLogger.debug("DoDeleteVfModule Request: " + xml) + + msoLogger.debug("input request xml: " + xml) + + vnfId = utils.getNodeText(xml,"vnf-id") + execution.setVariable("vnfId", vnfId) + vfModuleId = utils.getNodeText(xml,"vf-module-id") + execution.setVariable("vfModuleId", vfModuleId) + def srvInstId = execution.getVariable("mso-service-instance-id") + execution.setVariable("srvInstId", srvInstId) + String requestId = "" + try { + requestId = execution.getVariable("mso-request-id") + } catch (Exception ex) { + requestId = utils.getNodeText(xml, "request-id") + } + execution.setVariable("requestId", requestId) + String source = utils.getNodeText(xml, "source") + execution.setVariable("source", source) + String serviceId = utils.getNodeText(xml, "service-id") + execution.setVariable("serviceId", serviceId) + String tenantId = utils.getNodeText(xml, "tenant-id") + execution.setVariable("tenantId", tenantId) + + String serviceInstanceIdToSdnc = "" + if (xml.contains("service-instance-id")) { + serviceInstanceIdToSdnc = utils.getNodeText(xml, "service-instance-id") + } else { + serviceInstanceIdToSdnc = vfModuleId + } + execution.setVariable(Prefix + "serviceInstanceIdToSdnc", serviceInstanceIdToSdnc) + String vfModuleName = utils.getNodeText(xml, "vf-module-name") + execution.setVariable("vfModuleName", vfModuleName) + String vfModuleModelName = utils.getNodeText(xml, "vf-module-model-name") + execution.setVariable("vfModuleModelName", vfModuleModelName) + String cloudSiteId = utils.getNodeText(xml, "aic-cloud-region") + execution.setVariable("cloudSiteId", cloudSiteId) + } + + // formulate the request for PrepareUpdateAAIVfModule + String request = """<PrepareUpdateAAIVfModuleRequest> + <vnf-id>${MsoUtils.xmlEscape(vnfId)}</vnf-id> + <vf-module-id>${MsoUtils.xmlEscape(vfModuleId)}</vf-module-id> + <orchestration-status>pending-delete</orchestration-status> + </PrepareUpdateAAIVfModuleRequest>""" as String + msoLogger.debug("PrepareUpdateAAIVfModuleRequest :" + request) + msoLogger.debug("UpdateAAIVfModule Request: " + request) + execution.setVariable("PrepareUpdateAAIVfModuleRequest", request) + execution.setVariable("vfModuleFromAAI", null) + }catch(BpmnError b){ + throw b + }catch(Exception e){ + exceptionUtil.buildAndThrowWorkflowException(execution, 2000, "Internal Error encountered in PreProcess method!") + } + } + + // build a SDNC vnf-topology-operation request for the specified action + // (note: the action passed is expected to be 'changedelete' or 'delete') + public void prepSDNCAdapterRequest(DelegateExecution execution, String action) { + + + String uuid = execution.getVariable('testReqId') // for junits + if(uuid==null){ + uuid = execution.getVariable("requestId") + "-" + System.currentTimeMillis() + } + + def srvInstId = execution.getVariable("srvInstId") + def callbackUrl = UrnPropertiesReader.getVariable("mso.workflow.sdncadapter.callback",execution) + String requestId = execution.getVariable("requestId") + String source = execution.getVariable("source") + String serviceId = execution.getVariable("serviceId") + String vnfId = execution.getVariable("vnfId") + String tenantId = execution.getVariable("tenantId") + String vfModuleId = execution.getVariable("vfModuleId") + String serviceInstanceIdToSdnc = execution.getVariable(Prefix + "serviceInstanceIdToSdnc") + String vfModuleName = execution.getVariable("vfModuleName") + // Get vfModuleName from AAI response if it was not specified on the request + if (vfModuleName == null || vfModuleName.isEmpty()) { + if (execution.getVariable("vfModuleFromAAI") != null) { + VfModule vfModuleFromAAI = execution.getVariable("vfModuleFromAAI") + vfModuleName = vfModuleFromAAI.getElementText("vf-module-name") + } + } + String vfModuleModelName = execution.getVariable("vfModuleModelName") + String cloudSiteId = execution.getVariable("cloudSiteId") + boolean retainResources = execution.getVariable("retainResources") + String requestSubActionString = "" + if (retainResources) { + requestSubActionString = "<request-sub-action>RetainResource</request-sub-action>" + } + String request = """<sdncadapterworkflow:SDNCAdapterWorkflowRequest xmlns:ns5="http://org.onap/so/request/types/v1" + xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1" + xmlns:sdncadapter="http://org.onap/workflow/sdnc/adapter/schema/v1"> + <sdncadapter:RequestHeader> + <sdncadapter:RequestId>${MsoUtils.xmlEscape(uuid)}</sdncadapter:RequestId> + <sdncadapter:SvcInstanceId>${MsoUtils.xmlEscape(vfModuleId)}</sdncadapter:SvcInstanceId> + <sdncadapter:SvcAction>${MsoUtils.xmlEscape(action)}</sdncadapter:SvcAction> + <sdncadapter:SvcOperation>vnf-topology-operation</sdncadapter:SvcOperation> + <sdncadapter:CallbackUrl>${MsoUtils.xmlEscape(callbackUrl)}</sdncadapter:CallbackUrl> + </sdncadapter:RequestHeader> + <sdncadapterworkflow:SDNCRequestData> + <request-information> + <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> + <request-action>DisconnectVNFRequest</request-action> + ${requestSubActionString} + <source>${MsoUtils.xmlEscape(source)}</source> + <notification-url/> + <order-number/> + <order-version/> + </request-information> + <service-information> + <service-id>${MsoUtils.xmlEscape(serviceId)}</service-id> + <service-type>${MsoUtils.xmlEscape(serviceId)}</service-type> + <service-instance-id>${MsoUtils.xmlEscape(serviceInstanceIdToSdnc)}</service-instance-id> + <subscriber-name>notsurewecare</subscriber-name> + </service-information> + <vnf-request-information> + <vnf-id>${MsoUtils.xmlEscape(vfModuleId)}</vnf-id> + <vnf-type>${MsoUtils.xmlEscape(vfModuleModelName)}</vnf-type> + <vnf-name>${MsoUtils.xmlEscape(vfModuleName)}</vnf-name> + <generic-vnf-id>${MsoUtils.xmlEscape(vnfId)}</generic-vnf-id> + <generic-vnf-name></generic-vnf-name> + <generic-vnf-type></generic-vnf-type> + <aic-cloud-region>${MsoUtils.xmlEscape(cloudSiteId)}</aic-cloud-region> + <tenant>${MsoUtils.xmlEscape(tenantId)}</tenant> + </vnf-request-information> + </sdncadapterworkflow:SDNCRequestData> + </sdncadapterworkflow:SDNCAdapterWorkflowRequest>""" + + msoLogger.debug("sdncAdapterWorkflowRequest: " + request) + msoLogger.debug("DoDeleteVfModule - SDNCAdapterWorkflowRequest: " + request) + execution.setVariable("sdncAdapterWorkflowRequest", request) + } + + // parse the incoming DELETE_VF_MODULE request + // and formulate the outgoing VnfAdapterDeleteV1 request + public void prepVNFAdapterRequest(DelegateExecution execution) { + + def requestId = UUID.randomUUID().toString() + def origRequestId = execution.getVariable('requestId') + def srvInstId = execution.getVariable("serviceInstanceId") + def aicCloudRegion = execution.getVariable("cloudSiteId") + def vnfId = execution.getVariable("vnfId") + def vfModuleId = execution.getVariable("vfModuleId") + def vfModuleStackId = execution.getVariable('DoDVfMod_heatStackId') + def tenantId = execution.getVariable("tenantId") + def messageId = execution.getVariable('requestId') + '-' + + System.currentTimeMillis() + def notificationUrl = createCallbackURL(execution, "VNFAResponse", messageId) + def useQualifiedHostName = UrnPropertiesReader.getVariable("mso.use.qualified.host",execution) + if ('true'.equals(useQualifiedHostName)) { + notificationUrl = utils.getQualifiedHostNameForCallback(notificationUrl) + } + + String request = """ + <deleteVfModuleRequest> + <cloudSiteId>${MsoUtils.xmlEscape(aicCloudRegion)}</cloudSiteId> + <tenantId>${MsoUtils.xmlEscape(tenantId)}</tenantId> + <vnfId>${MsoUtils.xmlEscape(vnfId)}</vnfId> + <vfModuleId>${MsoUtils.xmlEscape(vfModuleId)}</vfModuleId> + <vfModuleStackId>${MsoUtils.xmlEscape(vfModuleStackId)}</vfModuleStackId> + <skipAAI>true</skipAAI> + <msoRequest> + <requestId>${MsoUtils.xmlEscape(origRequestId)}</requestId> + <serviceInstanceId>${MsoUtils.xmlEscape(srvInstId)}</serviceInstanceId> + </msoRequest> + <messageId>${MsoUtils.xmlEscape(messageId)}</messageId> + <notificationUrl>${MsoUtils.xmlEscape(notificationUrl)}</notificationUrl> + </deleteVfModuleRequest> + """ as String + + msoLogger.debug("vnfAdapterRestV1Request: " + request) + msoLogger.debug("deleteVfModuleRequest: " + request) + execution.setVariable("vnfAdapterRestV1Request", request) + } + + // parse the incoming DELETE_VF_MODULE request + // and formulate the outgoing UpdateAAIVfModuleRequest request + public void prepUpdateAAIVfModule(DelegateExecution execution) { + + def vnfId = execution.getVariable("vnfId") + def vfModuleId = execution.getVariable("vfModuleId") + // formulate the request for UpdateAAIVfModule + String request = """<UpdateAAIVfModuleRequest> + <vnf-id>${MsoUtils.xmlEscape(vnfId)}</vnf-id> + <vf-module-id>${MsoUtils.xmlEscape(vfModuleId)}</vf-module-id> + <heat-stack-id>DELETE</heat-stack-id> + <orchestration-status>deleted</orchestration-status> + </UpdateAAIVfModuleRequest>""" as String + msoLogger.debug("UpdateAAIVfModuleRequest :" + request) + msoLogger.debug("UpdateAAIVfModuleRequest: " + request) + execution.setVariable("UpdateAAIVfModuleRequest", request) + } + + // parse the incoming DELETE_VF_MODULE request + // and formulate the outgoing DeleteAAIVfModuleRequest request + public void prepDeleteAAIVfModule(DelegateExecution execution) { + + + def vnfId = execution.getVariable("vnfId") + def vfModuleId = execution.getVariable("vfModuleId") + // formulate the request for UpdateAAIVfModule + String request = """<DeleteAAIVfModuleRequest> + <vnf-id>${MsoUtils.xmlEscape(vnfId)}</vnf-id> + <vf-module-id>${MsoUtils.xmlEscape(vfModuleId)}</vf-module-id> + </DeleteAAIVfModuleRequest>""" as String + msoLogger.debug("DeleteAAIVfModuleRequest :" + request) + msoLogger.debug("DeleteAAIVfModuleRequest: " + request) + execution.setVariable("DeleteAAIVfModuleRequest", request) + } + + // generates a WorkflowException if + // - + public void handleDoDeleteVfModuleFailure(DelegateExecution execution) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "AAI error occurred deleting the Generic Vnf: " + execution.getVariable("DoDVfMod_deleteGenericVnfResponse"), "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception"); + String processKey = getProcessKey(execution); + WorkflowException exception = new WorkflowException(processKey, 5000, + execution.getVariable("DoDVfMod_deleteGenericVnfResponse")) + execution.setVariable("WorkflowException", exception) + } + + public void sdncValidateResponse(DelegateExecution execution, String response){ + + execution.setVariable("prefix",Prefix) + + WorkflowException workflowException = execution.getVariable("WorkflowException") + boolean successIndicator = execution.getVariable("SDNCA_SuccessIndicator") + + SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this) + sdncAdapterUtils.validateSDNCResponse(execution, response, workflowException, successIndicator) + + if(execution.getVariable(Prefix + 'sdncResponseSuccess') == true){ + msoLogger.debug("Successfully Validated SDNC Response") + }else{ + throw new BpmnError("MSOWorkflowException") + } + } + + public void postProcessVNFAdapterRequest(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.postProcessVNFAdapterRequest(' + + 'execution=' + execution.getId() + + ')' + + msoLogger.trace('Entered ' + method) + execution.setVariable("prefix",Prefix) + try{ + msoLogger.trace("STARTED postProcessVNFAdapterRequest Process") + + String vnfResponse = execution.getVariable("DoDVfMod_doDeleteVfModuleResponse") + msoLogger.debug("VNF Adapter Response is: " + vnfResponse) + msoLogger.debug("deleteVnfAResponse is: \n" + vnfResponse) + + if(vnfResponse != null){ + + if(vnfResponse.contains("deleteVfModuleResponse")){ + msoLogger.debug("Received a Good Response from VNF Adapter for DELETE_VF_MODULE Call.") + execution.setVariable("DoDVfMod_vnfVfModuleDeleteCompleted", true) + + // Parse vnfOutputs for contrail network polcy FQDNs + if (vnfResponse.contains("vfModuleOutputs")) { + def vfModuleOutputsXml = utils.getNodeXml(vnfResponse, "vfModuleOutputs") + InputSource source = new InputSource(new StringReader(vfModuleOutputsXml)); + DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); + docFactory.setNamespaceAware(true) + DocumentBuilder docBuilder = docFactory.newDocumentBuilder() + Document outputsXml = docBuilder.parse(source) + + NodeList entries = outputsXml.getElementsByTagNameNS("*", "entry") + List contrailNetworkPolicyFqdnList = [] + for (int i = 0; i< entries.getLength(); i++) { + Node node = entries.item(i) + if (node.getNodeType() == Node.ELEMENT_NODE) { + Element element = (Element) node + String key = element.getElementsByTagNameNS("*", "key").item(0).getTextContent() + if (key.endsWith("contrail_network_policy_fqdn")) { + String contrailNetworkPolicyFqdn = element.getElementsByTagNameNS("*", "value").item(0).getTextContent() + msoLogger.debug("Obtained contrailNetworkPolicyFqdn: " + contrailNetworkPolicyFqdn) + contrailNetworkPolicyFqdnList.add(contrailNetworkPolicyFqdn) + } + else if (key.equals("oam_management_v4_address")) { + String oamManagementV4Address = element.getElementsByTagNameNS("*", "value").item(0).getTextContent() + msoLogger.debug("Obtained oamManagementV4Address: " + oamManagementV4Address) + execution.setVariable(Prefix + "oamManagementV4Address", oamManagementV4Address) + } + else if (key.equals("oam_management_v6_address")) { + String oamManagementV6Address = element.getElementsByTagNameNS("*", "value").item(0).getTextContent() + msoLogger.debug("Obtained oamManagementV6Address: " + oamManagementV6Address) + execution.setVariable(Prefix + "oamManagementV6Address", oamManagementV6Address) + } + + } + } + if (!contrailNetworkPolicyFqdnList.isEmpty()) { + msoLogger.debug("Setting the fqdn list") + execution.setVariable("DoDVfMod_contrailNetworkPolicyFqdnList", contrailNetworkPolicyFqdnList) + } + } + }else{ + msoLogger.debug("Received a BAD Response from VNF Adapter for DELETE_VF_MODULE Call.") + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "VNF Adapter Error") + } + }else{ + msoLogger.debug("Response from VNF Adapter is Null for DELETE_VF_MODULE Call.") + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Empty response from VNF Adapter") + } + + }catch(BpmnError b){ + throw b + }catch(Exception e){ + msoLogger.debug("Internal Error Occured in PostProcess Method") + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Internal Error Occured in PostProcess Method") + } + msoLogger.trace("COMPLETED postProcessVnfAdapterResponse Process") + } + + public void deleteNetworkPoliciesFromAAI(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.deleteNetworkPoliciesFromAAI(' + + 'execution=' + execution.getId() + + ')' + + msoLogger.trace('Entered ' + method) + execution.setVariable("prefix", Prefix) + msoLogger.trace("STARTED deleteNetworkPoliciesFromAAI ") + + try { + // get variables + List fqdnList = execution.getVariable("DoDVfMod_contrailNetworkPolicyFqdnList") + if (fqdnList == null) { + msoLogger.debug("No network policies to delete") + return + } + int fqdnCount = fqdnList.size() + + execution.setVariable("DoDVfMod_networkPolicyFqdnCount", fqdnCount) + msoLogger.debug("DoDVfMod_networkPolicyFqdnCount - " + fqdnCount) + + String aai_endpoint = UrnPropertiesReader.getVariable("aai.endpoint", execution) + AaiUtil aaiUriUtil = new AaiUtil(this) + String aai_uri = aaiUriUtil.getNetworkPolicyUri(execution) + + if (fqdnCount > 0) { + // AII loop call over contrail network policy fqdn list + for (i in 0..fqdnCount-1) { + + int counting = i+1 + String fqdn = fqdnList[i] + + // Query AAI for this network policy FQDN + + String queryNetworkPolicyByFqdnAAIRequest = "${aai_endpoint}${aai_uri}?network-policy-fqdn=" + UriUtils.encode(fqdn, "UTF-8") + msoLogger.debug("AAI request endpoint: " + queryNetworkPolicyByFqdnAAIRequest) + msoLogger.debug("AAI request endpoint: " + queryNetworkPolicyByFqdnAAIRequest) + + APIResponse response = aaiUriUtil.executeAAIGetCall(execution, queryNetworkPolicyByFqdnAAIRequest) + int returnCode = response.getStatusCode() + execution.setVariable("DCVFM_aaiQueryNetworkPolicyByFqdnReturnCode", returnCode) + msoLogger.debug(" ***** AAI query network policy Response Code, NetworkPolicy #" + counting + " : " + returnCode) + + String aaiResponseAsString = response.getResponseBodyAsString() + + if (isOneOf(returnCode, 200, 201)) { + msoLogger.debug("The return code is: " + returnCode) + // This network policy FQDN exists in AAI - need to delete it now + msoLogger.debug(aaiResponseAsString) + execution.setVariable("DoDVfMod_queryNetworkPolicyByFqdnAAIResponse", aaiResponseAsString) + msoLogger.debug("QueryAAINetworkPolicyByFQDN Success REST Response, , NetworkPolicy #" + counting + " : " + "\n" + aaiResponseAsString) + // Retrieve the network policy id for this FQDN + def networkPolicyId = utils.getNodeText(aaiResponseAsString, "network-policy-id") + msoLogger.debug("Deleting network-policy with network-policy-id " + networkPolicyId) + + // Retrieve the resource version for this network policy + def resourceVersion = utils.getNodeText(aaiResponseAsString, "resource-version") + msoLogger.debug("Deleting network-policy with resource-version " + resourceVersion) + + String delNetworkPolicyAAIRequest = "${aai_endpoint}${aai_uri}/" + UriUtils.encode(networkPolicyId, "UTF-8") + + "?resource-version=" + UriUtils.encode(resourceVersion, "UTF-8") + msoLogger.debug("AAI request endpoint: " + delNetworkPolicyAAIRequest) + msoLogger.debug("AAI request endpoint: " + delNetworkPolicyAAIRequest) + + msoLogger.debug("invoking DELETE call to AAI") + msoLogger.debug("Sending DELETE call to AAI with Endpoint /n" + delNetworkPolicyAAIRequest) + APIResponse responseDel = aaiUriUtil.executeAAIDeleteCall(execution, delNetworkPolicyAAIRequest) + int returnCodeDel = responseDel.getStatusCode() + execution.setVariable("DoDVfMod_aaiDeleteNetworkPolicyReturnCode", returnCodeDel) + msoLogger.debug(" ***** AAI delete network policy Response Code, NetworkPolicy #" + counting + " : " + returnCodeDel) + + if (isOneOf(returnCodeDel, 200, 201, 204)) { + msoLogger.debug("The return code from deleting network policy is: " + returnCodeDel) + // This network policy was deleted from AAI successfully + msoLogger.debug(" DelAAINetworkPolicy Success REST Response, , NetworkPolicy #" + counting + " : ") + + } else { + // aai all errors + String delErrorMessage = "Unable to delete network-policy to AAI deleteNetworkPoliciesFromAAI - " + returnCodeDel + msoLogger.debug(delErrorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, delErrorMessage) + } + } else if (returnCode == 404) { + // This network policy FQDN is not in AAI. No need to delete. + msoLogger.debug("The return code is: " + returnCode) + msoLogger.debug("This network policy FQDN is not in AAI: " + fqdn) + msoLogger.debug("Network policy FQDN is not in AAI") + } else { + if (aaiResponseAsString.contains("RESTFault")) { + WorkflowException exceptionObject = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) + execution.setVariable("WorkflowException", exceptionObject) + throw new BpmnError("MSOWorkflowException") + + } else { + // aai all errors + String dataErrorMessage = "Unexpected Response from deleteNetworkPoliciesFromAAI - " + returnCode + msoLogger.debug(dataErrorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + + } + } + + + + } // end loop + + + } else { + msoLogger.debug("No contrail network policies to query/create") + + } + + } catch (BpmnError e) { + throw e; + + } catch (Exception ex) { + String exceptionMessage = "Bpmn error encountered in DoDeletVfModule flow. deleteNetworkPoliciesFromAAI() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + } + + } + + /** + * Prepare a Request for invoking the UpdateAAIGenericVnf subflow. + * + * @param execution The flow's execution instance. + */ + public void prepUpdateAAIGenericVnf(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.prepUpdateAAIGenericVnf(' + + 'execution=' + execution.getId() + + ')' + + msoLogger.trace('Entered ' + method) + + try { + def vnfId = execution.getVariable('vnfId') + def oamManagementV4Address = execution.getVariable(Prefix + 'oamManagementV4Address') + def oamManagementV6Address = execution.getVariable(Prefix + 'oamManagementV6Address') + def ipv4OamAddressElement = '' + def managementV6AddressElement = '' + + if (oamManagementV4Address != null) { + ipv4OamAddressElement = '<ipv4-oam-address>' + 'DELETE' + '</ipv4-oam-address>' + } + + if (oamManagementV6Address != null) { + managementV6AddressElement = '<management-v6-address>' + 'DELETE' + '</management-v6-address>' + } + + + String updateAAIGenericVnfRequest = """ + <UpdateAAIGenericVnfRequest> + <vnf-id>${MsoUtils.xmlEscape(vnfId)}</vnf-id> + ${ipv4OamAddressElement} + ${managementV6AddressElement} + </UpdateAAIGenericVnfRequest> + """ + updateAAIGenericVnfRequest = utils.formatXml(updateAAIGenericVnfRequest) + execution.setVariable(Prefix + 'updateAAIGenericVnfRequest', updateAAIGenericVnfRequest) + msoLogger.debug("updateAAIGenericVnfRequest : " + updateAAIGenericVnfRequest) + msoLogger.debug('Request for UpdateAAIGenericVnf:\n' + updateAAIGenericVnfRequest) + + + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in prepUpdateAAIGenericVnf(): ' + e.getMessage()) + } + } + + /** + * Using the vnfId and vfModuleId provided in the inputs, + * query AAI to get the corresponding VF Module info. + * A 200 response is expected with the VF Module info in the response body, + * Will determine VF Module's orchestration status if one exists + * + * @param execution The flow's execution instance. + */ + public void queryAAIVfModuleForStatus(DelegateExecution execution) { + + def method = getClass().getSimpleName() + '.queryAAIVfModuleForStatus(' + + 'execution=' + execution.getId() + + ')' + msoLogger.trace('Entered ' + method) + + execution.setVariable(Prefix + 'orchestrationStatus', '') + + try { + def vnfId = execution.getVariable('vnfId') + def vfModuleId = execution.getVariable('vfModuleId') + + AaiUtil aaiUriUtil = new AaiUtil(this) + String aai_uri = aaiUriUtil.getNetworkGenericVnfUri(execution) + msoLogger.debug('AAI URI is: ' + aai_uri) + + String endPoint = UrnPropertiesReader.getVariable("aai.endpoint",execution) + "${aai_uri}/" + UriUtils.encode(vnfId, "UTF-8") + + "/vf-modules/vf-module/" + UriUtils.encode(vfModuleId, "UTF-8") + msoLogger.debug("AAI endPoint: " + endPoint) + + try { + RESTConfig config = new RESTConfig(endPoint); + def responseData = '' + def aaiRequestId = UUID.randomUUID().toString() + RESTClient client = new RESTClient(config). + addHeader('X-TransactionId', aaiRequestId). + addHeader('X-FromAppId', 'MSO'). + addHeader('Content-Type', 'application/xml'). + addHeader('Accept','application/xml'); + msoLogger.debug('sending GET to AAI endpoint \'' + endPoint + '\'') + APIResponse response = client.httpGet() + msoLogger.debug("createVfModule - invoking httpGet() to AAI") + + responseData = response.getResponseBodyAsString() + if (responseData != null) { + msoLogger.debug("Received generic VNF data: " + responseData) + + } + + msoLogger.debug("deleteVfModule - queryAAIVfModule Response: " + responseData) + msoLogger.debug("deleteVfModule - queryAAIVfModule ResponseCode: " + response.getStatusCode()) + + execution.setVariable(Prefix + 'queryAAIVfModuleForStatusResponseCode', response.getStatusCode()) + execution.setVariable(Prefix + 'queryAAIVfModuleForStatusResponse', responseData) + msoLogger.debug('Response code:' + response.getStatusCode()) + msoLogger.debug('Response:' + System.lineSeparator() + responseData) + // Retrieve VF Module info and its orchestration status; if not found, do nothing + if (response.getStatusCode() == 200) { + // Parse the VNF record from A&AI to find base module info + msoLogger.debug('Parsing the VNF data to find orchestration status') + if (responseData != null) { + def vfModuleText = utils.getNodeXml(responseData, "vf-module") + //def xmlVfModule= new XmlSlurper().parseText(vfModuleText) + def orchestrationStatus = utils.getNodeText(vfModuleText, "orchestration-status") + execution.setVariable(Prefix + "orchestrationStatus", orchestrationStatus) + msoLogger.debug("Received orchestration status from A&AI: " + orchestrationStatus) + + } + } + } catch (Exception ex) { + ex.printStackTrace() + msoLogger.debug('Exception occurred while executing AAI GET:' + ex.getMessage()) + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'AAI GET Failed:' + ex.getMessage()) + } + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in queryAAIVfModuleForStatus(): ' + e.getMessage()) + } + } + + + + + +}
\ No newline at end of file diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVfModuleFromVnf.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVfModuleFromVnf.groovy new file mode 100644 index 0000000000..1024fc57da --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVfModuleFromVnf.groovy @@ -0,0 +1,609 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts + +import static org.apache.commons.lang3.StringUtils.* + +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.onap.so.bpmn.common.scripts.AaiUtil +import org.onap.so.bpmn.common.scripts.ExceptionUtil +import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.so.bpmn.common.scripts.SDNCAdapterUtils +import org.onap.so.bpmn.common.scripts.VfModule +import org.onap.so.bpmn.common.scripts.VfModuleBase +import org.onap.so.bpmn.core.UrnPropertiesReader +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.logger.MessageEnum +import org.onap.so.logger.MsoLogger +import org.onap.so.rest.APIResponse +import org.springframework.web.util.UriUtils + +public class DoDeleteVfModuleFromVnf extends VfModuleBase { + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoDeleteVfModuleFromVnf.class); + + def Prefix="DDVFMV_" + ExceptionUtil exceptionUtil = new ExceptionUtil() + JsonUtils jsonUtil = new JsonUtils() + + public void initProcessVariables(DelegateExecution execution) { + execution.setVariable("prefix",Prefix) + execution.setVariable("DDVFMV_contrailNetworkPolicyFqdnList", null) + } + + // parse the incoming request + public void preProcessRequest(DelegateExecution execution) { + + initProcessVariables(execution) + + try { + + // Building Block-type request + + // Set mso-request-id to request-id for VNF Adapter interface + String requestId = execution.getVariable("msoRequestId") + execution.setVariable("mso-request-id", requestId) + execution.setVariable("requestId", requestId) + msoLogger.debug("msoRequestId: " + requestId) + String tenantId = execution.getVariable("tenantId") + msoLogger.debug("tenantId: " + tenantId) + String cloudSiteId = execution.getVariable("lcpCloudRegionId") + execution.setVariable("cloudSiteId", cloudSiteId) + msoLogger.debug("cloudSiteId: " + cloudSiteId) + // Source is HARDCODED + String source = "VID" + execution.setVariable("source", source) + // isVidRequest is hardcoded to "true" + execution.setVariable("isVidRequest", "true") + // SrvInstId is hardcoded to empty + execution.setVariable("srvInstId", "") + // ServiceId is hardcoded to empty + execution.setVariable("serviceId", "") + String serviceInstanceId = execution.getVariable("serviceInstanceId") + msoLogger.debug("serviceInstanceId: " + serviceInstanceId) + String vnfId = execution.getVariable("vnfId") + msoLogger.debug("vnfId: " + vnfId) + String vfModuleId = execution.getVariable("vfModuleId") + msoLogger.debug("vfModuleId: " + vfModuleId) + if (serviceInstanceId == null || serviceInstanceId.isEmpty()) { + execution.setVariable(Prefix + "serviceInstanceIdToSdnc", vfModuleId) + } + else { + execution.setVariable(Prefix + "serviceInstanceIdToSdnc", serviceInstanceId) + } + + String sdncVersion = execution.getVariable("sdncVersion") + if (sdncVersion == null) { + sdncVersion = "1707" + } + execution.setVariable(Prefix + "sdncVersion", sdncVersion) + msoLogger.debug("Incoming Sdnc Version is: " + sdncVersion) + + String sdncCallbackUrl = (String) UrnPropertiesReader.getVariable("mso.workflow.sdncadapter.callback",execution) + if (sdncCallbackUrl == null || sdncCallbackUrl.trim().isEmpty()) { + def msg = 'Required variable \'mso.workflow.sdncadapter.callback\' is missing' + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, msg, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception"); + exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) + } + execution.setVariable("sdncCallbackUrl", sdncCallbackUrl) + msoLogger.debug("SDNC Callback URL: " + sdncCallbackUrl) + msoLogger.debug("SDNC Callback URL is: " + sdncCallbackUrl) + + + + }catch(BpmnError b){ + throw b + }catch(Exception e){ + msoLogger.debug("Exception is: " + e.getMessage()) + exceptionUtil.buildAndThrowWorkflowException(execution, 2000, "Internal Error encountered in PreProcess method!") + } + } + + public void queryAAIForVfModule(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.queryAAIForVfModule(' + + 'execution=' + execution.getId() + + ')' + + msoLogger.trace('Entered ' + method) + + try { + def vnfId = execution.getVariable('vnfId') + + AaiUtil aaiUriUtil = new AaiUtil(this) + def aai_uri = aaiUriUtil.getNetworkGenericVnfUri(execution) + msoLogger.debug('AAI URI is: ' + aai_uri) + + String endPoint = UrnPropertiesReader.getVariable("aai.endpoint", execution) + "${aai_uri}/" + UriUtils.encode(vnfId, "UTF-8") + "?depth=1" + + msoLogger.debug("DoDeleteVfModuleFromVnf: AAI endPoint : " + endPoint) + + try { + msoLogger.debug("DoDeleteVfModuleFromVnf: - invoking httpGet to AAI") + APIResponse response = aaiUriUtil.executeAAIGetCall(execution, endPoint) + + def responseData = response.getResponseBodyAsString() + execution.setVariable('DDVMFV_getVnfResponseCode', response.getStatusCode()) + execution.setVariable('DDVMFV_getVnfResponse', responseData) + + msoLogger.debug("DoDeleteVfModuleFromVnf: AAI Response : " + responseData) + msoLogger.debug("DoDeleteVfModuleFromVnf: AAI ResponseCode : " + response.getStatusCode()) + + msoLogger.debug('Response code:' + response.getStatusCode()) + msoLogger.debug('Response:' + System.lineSeparator() + responseData) + + } catch (Exception ex) { + ex.printStackTrace() + msoLogger.debug('Exception occurred while executing AAI GET:' + ex.getMessage()) + execution.setVariable('DDVMFV_getVnfResponseCode', 500) + execution.setVariable('DDVFMV_getVnfResponse', 'AAI GET Failed:' + ex.getMessage()) + } + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in queryAAIForVfModule(): ' + e.getMessage()) + } + } + + /** + * Validate the VF Module. That is, confirm that a VF Module with the input VF Module ID + * exists in the retrieved Generic VNF. Then, check to make sure that if that VF Module + * is the base VF Module and it's not the only VF Module for this Generic VNF, that we're not + * attempting to delete it. + * + * @param execution The flow's execution instance. + */ + public void validateVfModule(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.validateVfModule(' + + 'execution=' + execution.getId() + + ')' + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + msoLogger.trace('Entered ' + method) + + try { + def genericVnf = execution.getVariable('DDVMFV_getVnfResponse') + def vnfId = execution.getVariable('_vnfId') + def vfModuleId = execution.getVariable('vfModuleId') + def VfModule vfModule = findVfModule(genericVnf, vfModuleId) + if (vfModule == null) { + def String msg = 'VF Module \'' + vfModuleId + '\' does not exist in Generic VNF \'' + vnfId + '\'' + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, msg) + } else { + + if (isDebugLogEnabled) { + msoLogger.debug('VF Module \'' + vfModuleId + '\': isBaseVfModule=' + vfModule.isBaseVfModule() + ', isOnlyVfModule=' + vfModule.isOnlyVfModule()) + } + if (vfModule.isBaseVfModule() && !vfModule.isOnlyVfModule()) { + def String msg = 'Cannot delete VF Module \'' + vfModuleId + + '\'since it is the base VF Module and it\'s not the only VF Module in Generic VNF \'' + vnfId + '\'' + msoLogger.debug("Received a BAD Response from VNF Adapter for CREATE_VF_MODULE Call.") + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "VNF Adapter Error") + } + + def heatStackId = vfModule.getElementText('heat-stack-id') + execution.setVariable('DDVMFV_heatStackId', heatStackId) + msoLogger.debug('VF Module heatStackId retrieved from AAI: ' + heatStackId) + } + + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in validateVfModule(): ' + e.getMessage()) + } + } + + + public void preProcessSDNCDeactivateRequest(DelegateExecution execution){ + + execution.setVariable("prefix", Prefix) + msoLogger.trace("STARTED preProcessSDNCDeactivateRequest ") + + def serviceInstanceId = execution.getVariable("serviceInstanceId") + + try{ + //Build SDNC Request + + String deactivateSDNCRequest = buildSDNCRequest(execution, serviceInstanceId, "deactivate") + + deactivateSDNCRequest = utils.formatXml(deactivateSDNCRequest) + execution.setVariable("DDVMFV_deactivateSDNCRequest", deactivateSDNCRequest) + msoLogger.debug("Outgoing DeactivateSDNCRequest is: \n" + deactivateSDNCRequest) + + + }catch(Exception e){ + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception Occured Processing preProcessSDNCDeactivateRequest. Exception is:\n" + e, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during preProcessSDNCDeactivateRequest Method:\n" + e.getMessage()) + } + msoLogger.trace("COMPLETED preProcessSDNCDeactivateRequest ") + } + + public void preProcessSDNCUnassignRequest(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.preProcessSDNCUnassignRequest(' + + 'execution=' + execution.getId() + + ')' + + msoLogger.trace('Entered ' + method) + execution.setVariable("prefix", Prefix) + msoLogger.trace("STARTED preProcessSDNCUnassignRequest Process ") + try{ + String serviceInstanceId = execution.getVariable("serviceInstanceId") + + String unassignSDNCRequest = buildSDNCRequest(execution, serviceInstanceId, "unassign") + + execution.setVariable("DDVMFV_unassignSDNCRequest", unassignSDNCRequest) + msoLogger.debug("Outgoing UnassignSDNCRequest is: \n" + unassignSDNCRequest) + + + }catch(Exception e){ + msoLogger.debug("Exception Occured Processing preProcessSDNCUnassignRequest. Exception is:\n" + e) + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during preProcessSDNCUnassignRequest Method:\n" + e.getMessage()) + } + msoLogger.trace("COMPLETED preProcessSDNCUnassignRequest Process ") + } + + public String buildSDNCRequest(DelegateExecution execution, String svcInstId, String action){ + + String uuid = execution.getVariable('testReqId') // for junits + if(uuid==null){ + uuid = execution.getVariable("msoRequestId") + "-" + System.currentTimeMillis() + } + def callbackURL = execution.getVariable("sdncCallbackUrl") + def requestId = execution.getVariable("msoRequestId") + def serviceId = execution.getVariable("serviceId") + def serviceInstanceId = execution.getVariable("serviceInstanceId") + def vfModuleId = execution.getVariable("vfModuleId") + def source = execution.getVariable("source") + def vnfId = execution.getVariable("vnfId") + + def sdncVersion = execution.getVariable(Prefix + "sdncVersion") + + String sdncRequest = + """<sdncadapterworkflow:SDNCAdapterWorkflowRequest xmlns:ns5="http://org.onap/so/request/types/v1" + xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1" + xmlns:sdncadapter="http://org.onap.so/workflow/sdnc/adapter/schema/v1"> + <sdncadapter:RequestHeader> + <sdncadapter:RequestId>${MsoUtils.xmlEscape(uuid)}</sdncadapter:RequestId> + <sdncadapter:SvcInstanceId>${MsoUtils.xmlEscape(svcInstId)}</sdncadapter:SvcInstanceId> + <sdncadapter:SvcAction>${MsoUtils.xmlEscape(action)}</sdncadapter:SvcAction> + <sdncadapter:SvcOperation>vf-module-topology-operation</sdncadapter:SvcOperation> + <sdncadapter:CallbackUrl>${MsoUtils.xmlEscape(callbackURL)}</sdncadapter:CallbackUrl> + <sdncadapter:MsoAction>generic-resource</sdncadapter:MsoAction> + </sdncadapter:RequestHeader> + <sdncadapterworkflow:SDNCRequestData> + <request-information> + <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> + <request-action>DeleteVfModuleInstance</request-action> + <source>${MsoUtils.xmlEscape(source)}</source> + <notification-url/> + <order-number/> + <order-version/> + </request-information> + <service-information> + <service-id/> + <subscription-service-type/> + <service-instance-id>${MsoUtils.xmlEscape(serviceInstanceId)}</service-instance-id> + <global-customer-id/> + </service-information> + <vnf-information> + <vnf-id>${MsoUtils.xmlEscape(vnfId)}</vnf-id> + <vnf-type/> + </vnf-information> + <vf-module-information> + <vf-module-id>${MsoUtils.xmlEscape(vfModuleId)}</vf-module-id> + </vf-module-information> + <vf-module-request-input/> + </sdncadapterworkflow:SDNCRequestData> + </sdncadapterworkflow:SDNCAdapterWorkflowRequest>""" + + msoLogger.debug("sdncRequest: " + sdncRequest) + return sdncRequest + } + + public void validateSDNCResponse(DelegateExecution execution, String response, String method){ + + execution.setVariable("prefix",Prefix) + msoLogger.trace("STARTED ValidateSDNCResponse Process") + + WorkflowException workflowException = execution.getVariable("WorkflowException") + boolean successIndicator = execution.getVariable("SDNCA_SuccessIndicator") + + msoLogger.debug("workflowException: " + workflowException) + + SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this) + sdncAdapterUtils.validateSDNCResponse(execution, response, workflowException, successIndicator) + + msoLogger.debug("SDNCResponse: " + response) + + String sdncResponse = response + if(execution.getVariable(Prefix + 'sdncResponseSuccess') == true){ + msoLogger.debug("Received a Good Response from SDNC Adapter for " + method + " SDNC Call. Response is: \n" + sdncResponse) + }else{ + msoLogger.debug("Received a BAD Response from SDNC Adapter for " + method + " SDNC Call.") + throw new BpmnError("MSOWorkflowException") + } + msoLogger.trace("COMPLETED ValidateSDNCResponse Process") + } + + + // parse the incoming DELETE_VF_MODULE request + // and formulate the outgoing VnfAdapterDeleteV1 request + public void prepVNFAdapterRequest(DelegateExecution execution) { + + def requestId = UUID.randomUUID().toString() + def origRequestId = execution.getVariable('requestId') + def srvInstId = execution.getVariable("serviceInstanceId") + def aicCloudRegion = execution.getVariable("cloudSiteId") + def vnfId = execution.getVariable("vnfId") + def vfModuleId = execution.getVariable("vfModuleId") + def vfModuleStackId = execution.getVariable('DDVMFV_heatStackId') + def tenantId = execution.getVariable("tenantId") + def messageId = execution.getVariable('requestId') + '-' + + System.currentTimeMillis() + def notificationUrl = createCallbackURL(execution, "VNFAResponse", messageId) + def useQualifiedHostName = UrnPropertiesReader.getVariable("mso.use.qualified.host",execution) + if ('true'.equals(useQualifiedHostName)) { + notificationUrl = utils.getQualifiedHostNameForCallback(notificationUrl) + } + + String request = """ + <deleteVfModuleRequest> + <cloudSiteId>${MsoUtils.xmlEscape(aicCloudRegion)}</cloudSiteId> + <tenantId>${MsoUtils.xmlEscape(tenantId)}</tenantId> + <vnfId>${MsoUtils.xmlEscape(vnfId)}</vnfId> + <vfModuleId>${MsoUtils.xmlEscape(vfModuleId)}</vfModuleId> + <vfModuleStackId>${MsoUtils.xmlEscape(vfModuleStackId)}</vfModuleStackId> + <skipAAI>true</skipAAI> + <msoRequest> + <requestId>${MsoUtils.xmlEscape(origRequestId)}</requestId> + <serviceInstanceId>${MsoUtils.xmlEscape(srvInstId)}</serviceInstanceId> + </msoRequest> + <messageId>${MsoUtils.xmlEscape(messageId)}</messageId> + <notificationUrl>${MsoUtils.xmlEscape(notificationUrl)}</notificationUrl> + </deleteVfModuleRequest> + """ as String + + msoLogger.debug("vnfAdapterRestV1Request: " + request) + msoLogger.debug("deleteVfModuleRequest: " + request) + execution.setVariable("vnfAdapterRestV1Request", request) + } + + + // generates a WorkflowException if + // - + public void handleDoDeleteVfModuleFailure(DelegateExecution execution) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "AAI error occurred deleting the Generic Vnf: " + execution.getVariable("DDVFMV_deleteGenericVnfResponse"), "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception"); + String processKey = getProcessKey(execution); + WorkflowException exception = new WorkflowException(processKey, 5000, + execution.getVariable("DDVFMV_deleteGenericVnfResponse")) + execution.setVariable("WorkflowException", exception) + } + + public void postProcessVNFAdapterRequest(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.postProcessVNFAdapterRequest(' + + 'execution=' + execution.getId() + + ')' + + msoLogger.trace('Entered ' + method) + execution.setVariable("prefix",Prefix) + try{ + msoLogger.trace("STARTED postProcessVNFAdapterRequest Process") + + String vnfResponse = execution.getVariable("DDVMFV_doDeleteVfModuleResponse") + msoLogger.debug("VNF Adapter Response is: " + vnfResponse) + msoLogger.debug("deleteVnfAResponse is: \n" + vnfResponse) + + if(vnfResponse != null){ + + if(vnfResponse.contains("deleteVfModuleResponse")){ + msoLogger.debug("Received a Good Response from VNF Adapter for DELETE_VF_MODULE Call.") + execution.setVariable("DDVFMV_vnfVfModuleDeleteCompleted", true) + + // Parse vnfOutputs for contrail network polcy FQDNs + def vfModuleOutputsXml = utils.getNodeXml(vnfResponse, "vfModuleOutputs") + if(!isBlank(vfModuleOutputsXml)) { + vfModuleOutputsXml = utils.removeXmlNamespaces(vfModuleOutputsXml) + List contrailNetworkPolicyFqdnList = [] + for(Node node: utils.getMultNodeObjects(vfModuleOutputsXml, "entry")) { + String key = utils.getChildNodeText(node, "key") + if(key == null) { + + } else if (key.endsWith("contrail_network_policy_fqdn")) { + String contrailNetworkPolicyFqdn = utils.getChildNodeText(node, "value") + msoLogger.debug("Obtained contrailNetworkPolicyFqdn: " + contrailNetworkPolicyFqdn) + contrailNetworkPolicyFqdnList.add(contrailNetworkPolicyFqdn) + } + else if (key.equals("oam_management_v4_address")) { + String oamManagementV4Address = utils.getChildNodeText(node, "value") + msoLogger.debug("Obtained oamManagementV4Address: " + oamManagementV4Address) + execution.setVariable(Prefix + "oamManagementV4Address", oamManagementV4Address) + } + else if (key.equals("oam_management_v6_address")) { + String oamManagementV6Address = utils.getChildNodeText(node, "value") + msoLogger.debug("Obtained oamManagementV6Address: " + oamManagementV6Address) + execution.setVariable(Prefix + "oamManagementV6Address", oamManagementV6Address) + } + } + if (!contrailNetworkPolicyFqdnList.isEmpty()) { + msoLogger.debug("Setting the fqdn list") + execution.setVariable("DDVFMV_contrailNetworkPolicyFqdnList", contrailNetworkPolicyFqdnList) + } + } + }else{ + msoLogger.debug("Received a BAD Response from VNF Adapter for DELETE_VF_MODULE Call.") + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "VNF Adapter Error") + } + }else{ + msoLogger.debug("Response from VNF Adapter is Null for DELETE_VF_MODULE Call.") + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Empty response from VNF Adapter") + } + + }catch(BpmnError b){ + throw b + }catch(Exception e){ + msoLogger.debug("Internal Error Occured in PostProcess Method") + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Internal Error Occured in PostProcess Method") + } + msoLogger.trace("COMPLETED postProcessVnfAdapterResponse Process") + } + + public void deleteNetworkPoliciesFromAAI(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.deleteNetworkPoliciesFromAAI(' + + 'execution=' + execution.getId() + + ')' + + msoLogger.trace('Entered ' + method) + execution.setVariable("prefix", Prefix) + msoLogger.trace("STARTED deleteNetworkPoliciesFromAAI ") + + try { + // get variables + List fqdnList = execution.getVariable("DDVFMV_contrailNetworkPolicyFqdnList") + if (fqdnList == null) { + msoLogger.debug("No network policies to delete") + return + } + int fqdnCount = fqdnList.size() + + execution.setVariable("DDVFMV_networkPolicyFqdnCount", fqdnCount) + msoLogger.debug("DDVFMV_networkPolicyFqdnCount - " + fqdnCount) + + String aai_endpoint = UrnPropertiesReader.getVariable("aai.endpoint", execution) + AaiUtil aaiUriUtil = new AaiUtil(this) + String aai_uri = aaiUriUtil.getNetworkPolicyUri(execution) + + if (fqdnCount > 0) { + // AII loop call over contrail network policy fqdn list + for (i in 0..fqdnCount-1) { + + int counting = i+1 + String fqdn = fqdnList[i] + + // Query AAI for this network policy FQDN + + String queryNetworkPolicyByFqdnAAIRequest = "${aai_endpoint}${aai_uri}?network-policy-fqdn=" + UriUtils.encode(fqdn, "UTF-8") + msoLogger.debug("AAI request endpoint: " + queryNetworkPolicyByFqdnAAIRequest) + + + APIResponse response = aaiUriUtil.executeAAIGetCall(execution, queryNetworkPolicyByFqdnAAIRequest) + int returnCode = response.getStatusCode() + execution.setVariable("DCVFM_aaiQueryNetworkPolicyByFqdnReturnCode", returnCode) + msoLogger.debug(" ***** AAI query network policy Response Code, NetworkPolicy #" + counting + " : " + returnCode) + + String aaiResponseAsString = response.getResponseBodyAsString() + + if (isOneOf(returnCode, 200, 201)) { + msoLogger.debug("The return code is: " + returnCode) + // This network policy FQDN exists in AAI - need to delete it now + msoLogger.debug(aaiResponseAsString) + execution.setVariable("DDVFMV_queryNetworkPolicyByFqdnAAIResponse", aaiResponseAsString) + msoLogger.debug("QueryAAINetworkPolicyByFQDN Success REST Response, , NetworkPolicy #" + counting + " : " + "\n" + aaiResponseAsString) + // Retrieve the network policy id for this FQDN + def networkPolicyId = utils.getNodeText(aaiResponseAsString, "network-policy-id") + msoLogger.debug("Deleting network-policy with network-policy-id " + networkPolicyId) + + // Retrieve the resource version for this network policy + def resourceVersion = utils.getNodeText(aaiResponseAsString, "resource-version") + msoLogger.debug("Deleting network-policy with resource-version " + resourceVersion) + + String delNetworkPolicyAAIRequest = "${aai_endpoint}${aai_uri}/" + UriUtils.encode(networkPolicyId, "UTF-8") + + "?resource-version=" + UriUtils.encode(resourceVersion, "UTF-8") + msoLogger.debug("AAI request endpoint: " + delNetworkPolicyAAIRequest) + + msoLogger.debug("invoking DELETE call to AAI") + msoLogger.debug("Sending DELETE call to AAI with Endpoint /n" + delNetworkPolicyAAIRequest) + APIResponse responseDel = aaiUriUtil.executeAAIDeleteCall(execution, delNetworkPolicyAAIRequest) + int returnCodeDel = responseDel.getStatusCode() + execution.setVariable("DDVFMV_aaiDeleteNetworkPolicyReturnCode", returnCodeDel) + msoLogger.debug(" ***** AAI delete network policy Response Code, NetworkPolicy #" + counting + " : " + returnCodeDel) + + if (isOneOf(returnCodeDel, 200, 201, 204)) { + msoLogger.debug("The return code from deleting network policy is: " + returnCodeDel) + // This network policy was deleted from AAI successfully + msoLogger.debug(" DelAAINetworkPolicy Success REST Response, , NetworkPolicy #" + counting + " : ") + + } else { + // aai all errors + String delErrorMessage = "Unable to delete network-policy to AAI deleteNetworkPoliciesFromAAI - " + returnCodeDel + msoLogger.debug(delErrorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, delErrorMessage) + } + } else if (returnCode == 404) { + // This network policy FQDN is not in AAI. No need to delete. + msoLogger.debug("The return code is: " + returnCode) + msoLogger.debug("This network policy FQDN is not in AAI: " + fqdn) + msoLogger.debug("Network policy FQDN is not in AAI") + } else { + if (aaiResponseAsString.contains("RESTFault")) { + WorkflowException exceptionObject = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) + execution.setVariable("WorkflowException", exceptionObject) + throw new BpmnError("MSOWorkflowException") + + } else { + // aai all errors + String dataErrorMessage = "Unexpected Response from deleteNetworkPoliciesFromAAI - " + returnCode + msoLogger.debug(dataErrorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + + } + } + + + + } // end loop + + + } else { + msoLogger.debug("No contrail network policies to query/create") + + } + + } catch (BpmnError e) { + throw e; + + } catch (Exception ex) { + String exceptionMessage = "Bpmn error encountered in DoDeletVfModule flow. deleteNetworkPoliciesFromAAI() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + } + + } + + // and formulate the outgoing DeleteAAIVfModuleRequest request + public void prepDeleteAAIVfModule(DelegateExecution execution) { + + + def vnfId = execution.getVariable("vnfId") + def vfModuleId = execution.getVariable("vfModuleId") + // formulate the request for UpdateAAIVfModule + String request = """<DeleteAAIVfModuleRequest> + <vnf-id>${MsoUtils.xmlEscape(vnfId)}</vnf-id> + <vf-module-id>${MsoUtils.xmlEscape(vfModuleId)}</vf-module-id> + </DeleteAAIVfModuleRequest>""" as String + msoLogger.debug("DeleteAAIVfModuleRequest :" + request) + + execution.setVariable("DeleteAAIVfModuleRequest", request) + } +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVfModuleVolumeV2.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVfModuleVolumeV2.groovy new file mode 100644 index 0000000000..b1cef477be --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVfModuleVolumeV2.groovy @@ -0,0 +1,355 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts + +import org.apache.commons.lang3.* +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.onap.so.bpmn.common.scripts.AaiUtil +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.onap.so.bpmn.common.scripts.ExceptionUtil +import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.so.bpmn.core.UrnPropertiesReader; +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.logger.MsoLogger +import org.onap.so.rest.APIResponse +import org.springframework.web.util.UriUtils + +class DoDeleteVfModuleVolumeV2 extends AbstractServiceTaskProcessor{ + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoDeleteVfModuleVolumeV2.class); + + String prefix="DDVMV_" + ExceptionUtil exceptionUtil = new ExceptionUtil() + XmlParser xmlParser = new XmlParser() + JsonUtils jsonUtil = new JsonUtils() + + @Override + public void preProcessRequest(DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + preProcessRequest(execution, isDebugEnabled) + } + + /** + * Set default variable values + * @param execution + * @param isDebugLogEnabled + */ + public void preProcessRequest (DelegateExecution execution, isDebugEnabled) { + + //Input: + // msoRequestId + // isDebugLogEnabled + // failIfNotFound (Optional) + // serviceInstanceId (Optional) + // vnfId (Optional) + // volumeGroupId + // vfModuleModelInfo (Optional) + // lcpCloudRegionId (Optional) @TODO: this is actually required + // tenantId (Optional) @TODO: this is actually required + // cloudConfiguration @TODO: temporary solution? this contains lcpCloudregion and tenantId + // + //Output: + // workflowException @TODO: actual variable name is WorkflowException + // rolledBack + // wasDeleted + + execution.setVariable('prefix', prefix) + execution.setVariable('wasDeleted', 'false') + + def tenantId = execution.getVariable("tenantId") + def cloudSiteId = execution.getVariable("lcpCloudRegionId") + + // if tenantId or lcpCloudregionId is not passed, get it from cloudRegionConfiguration variable + if(!tenantId || !cloudSiteId) { + def cloudConfiguration = execution.getVariable("cloudConfiguration") + msoLogger.debug("Using cloudConfiguration variable to get tenantId and lcpCloudRegionId - " + cloudConfiguration) + tenantId = jsonUtil.getJsonValue(cloudConfiguration, "tenantId") + execution.setVariable("tenantId", tenantId) + cloudSiteId = jsonUtil.getJsonValue(cloudConfiguration, "lcpCloudRegionId") + execution.setVariable("lcpCloudRegionId", cloudSiteId) + } + } + + + /** + * Set out 'wasDeleted' variable to 'true' + * @param execution + * @param isDebugLogEnabled + */ + public void postProcess(DelegateExecution execution, isDebugLogEnabled) { + execution.setVariable('wasDeleted', 'true') + } + + + /** + * Query and set cloud region to use for AAI calls + * Output variables: prefix+'aicCloudRegion', prefix+'cloudRegion' + * @param execution + * @param isDebugEnabled + */ + public void callRESTQueryAAICloudRegion(DelegateExecution execution, isDebugEnabled) { + + String cloudRegion = execution.getVariable('lcpCloudRegionId') + String aai_endpoint = UrnPropertiesReader.getVariable("aai.endpoint",execution) + AaiUtil aaiUtil = new AaiUtil(this) + String aai_uri = aaiUtil.getCloudInfrastructureCloudRegionUri(execution) + String queryCloudRegionRequest = "${aai_endpoint}${aai_uri}/" + cloudRegion + msoLogger.debug(queryCloudRegionRequest) + msoLogger.debug("AAI query cloud region URI - " + queryCloudRegionRequest) + + cloudRegion = aaiUtil.getAAICloudReqion(execution, queryCloudRegionRequest, "PO", cloudRegion) + + if ((cloudRegion != "ERROR")) { + if(execution.getVariable(prefix+"queryCloudRegionReturnCode") == "404") { + execution.setVariable(prefix+"aicCloudRegion", "AAIAIC25") + } + else{ + execution.setVariable(prefix+"aicCloudRegion", cloudRegion) + } + } + else { + msoLogger.debug("AAI Query Cloud Region Unsuccessful.") + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "AAI Query Cloud Region Unsuccessful. Return Code: " + execution.getVariable(prefix+"queryCloudRegionReturnCode")) + } + } + + + /** + * Query AAI Volume Group + * Output variables: prefix+'queryAAIVolGrpResponse'; prefix+'volumeGroupHeatStackId' + * @param execution + * @param isDebugLogEnabled + */ + public void callRESTQueryAAIForVolumeGroup(DelegateExecution execution, isDebugLogEnabled) { + + def tenantId = execution.getVariable('tenantId') + def volumeGroupId = execution.getVariable('volumeGroupId') + if(volumeGroupId == null) { + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, 'volumeGroupId is not provided in the request') + throw new Exception('volume-group-id is not provided in the request') + } + String cloudRegion = execution.getVariable(prefix+'aicCloudRegion') + + AaiUtil aaiUtil = new AaiUtil(this) + String aaiEndpoint = aaiUtil.getCloudInfrastructureCloudRegionEndpoint(execution) + String queryAAIVolumeGroupRequest = aaiEndpoint + '/' + URLEncoder.encode(cloudRegion, "UTF-8") + "/volume-groups/volume-group/" + UriUtils.encode(volumeGroupId, "UTF-8") + + msoLogger.debug('Query AAI volume group by ID: ' + queryAAIVolumeGroupRequest) + msoLogger.debug('Query AAI volume group by ID: ' + queryAAIVolumeGroupRequest) + + APIResponse response = aaiUtil.executeAAIGetCall(execution, queryAAIVolumeGroupRequest) + + String returnCode = response.getStatusCode() + String aaiResponseAsString = response.getResponseBodyAsString() + + msoLogger.debug("AAI query volume group by id return code: " + returnCode) + msoLogger.debug("AAI query volume group by id response: " + aaiResponseAsString) + msoLogger.debug('AAI query volume group by id return code: ' + returnCode) + msoLogger.debug('AAI query volume group by id response: ' + aaiResponseAsString) + + execution.setVariable(prefix+"queryAAIVolGrpResponse", aaiResponseAsString) + + if (returnCode=='200' || returnCode == '204') { + + def heatStackId = getNodeTextForce(aaiResponseAsString, 'heat-stack-id') + execution.setVariable(prefix+'volumeGroupHeatStackId', heatStackId) + + msoLogger.debug('Heat stack id from AAI response: ' + heatStackId) + + if(hasVfModuleRelationship(aaiResponseAsString)){ + msoLogger.debug('Volume Group ' + volumeGroupId + ' currently in use') + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Volume Group ${volumeGroupId} currently in use - found vf-module relationship.") + } + + def volumeGroupTenantId = getTenantIdFromVolumeGroup(aaiResponseAsString) + msoLogger.debug('Tenant ID from AAI response: ' + volumeGroupTenantId) + + if (volumeGroupTenantId == null) { + msoLogger.debug("Could not find Tenant Id element in Volume Group with Volume Group Id ${volumeGroupId}") + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Could not find Tenant Id element in Volume Group with Volume Group Id ${volumeGroupId}") + } + + if (volumeGroupTenantId != tenantId) { + def String errorMessage = 'TenantId ' + tenantId + ' in incoming request does not match Tenant Id ' + volumeGroupTenantId + ' retrieved from AAI for Volume Group Id ' + volumeGroupId + msoLogger.debug("Error in DeleteVfModuleVolume: " + errorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 5000, errorMessage) + } + msoLogger.debug('Received Tenant Id ' + volumeGroupTenantId + ' from AAI for Volume Group with Volume Group Id ' + volumeGroupId ) + } + else { + if (returnCode=='404') { + msoLogger.debug("Volume Group ${volumeGroupId} not found in AAI") + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Volume Group ${volumeGroupId} not found in AAI. Response code: 404") + } + else { + WorkflowException aWorkflowException = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) + throw new BpmnError("MSOWorkflowException") + } + } + } + + /** + * Format VNF Adapter subflow request XML + * Variables: prefix+'deleteVnfARequest' + * @param execution + * @param isDebugLogEnabled + */ + public void prepareVnfAdapterDeleteRequest(DelegateExecution execution, isDebugLogEnabled) { + def cloudRegion = execution.getVariable(prefix+'aicCloudRegion') + def tenantId = execution.getVariable('tenantId') // input parameter (optional) - see preProcessRequest + def volumeGroupId = execution.getVariable('volumeGroupId') // input parameter (required) + def volumeGroupHeatStackId = execution.getVariable(prefix+'volumeGroupHeatStackId') // from AAI query volume group + def requestId = execution.getVariable('msoRequestId') // input parameter (required) + def serviceId = execution.getVariable('serviceInstanceId') // imput parameter (optional) + + def messageId = UUID.randomUUID().toString() + def notificationUrl = createCallbackURL(execution, "VNFAResponse", messageId) + def useQualifiedHostName = UrnPropertiesReader.getVariable("mso.use.qualified.host",execution) + if ('true'.equals(useQualifiedHostName)) { + notificationUrl = utils.getQualifiedHostNameForCallback(notificationUrl) + } + + String vnfAdapterRestRequest = """ + <deleteVolumeGroupRequest> + <cloudSiteId>${MsoUtils.xmlEscape(cloudRegion)}</cloudSiteId> + <tenantId>${MsoUtils.xmlEscape(tenantId)}</tenantId> + <volumeGroupId>${MsoUtils.xmlEscape(volumeGroupId)}</volumeGroupId> + <volumeGroupStackId>${MsoUtils.xmlEscape(volumeGroupHeatStackId)}</volumeGroupStackId> + <skipAAI>true</skipAAI> + <msoRequest> + <requestId>${MsoUtils.xmlEscape(requestId)}</requestId> + <serviceInstanceId>${MsoUtils.xmlEscape(serviceId)}</serviceInstanceId> + </msoRequest> + <messageId>${MsoUtils.xmlEscape(messageId)}</messageId> + <notificationUrl>${MsoUtils.xmlEscape(notificationUrl)}</notificationUrl> + </deleteVolumeGroupRequest> + """ + vnfAdapterRestRequest = utils.formatXml(vnfAdapterRestRequest) + execution.setVariable(prefix+'deleteVnfARequest', vnfAdapterRestRequest) + msoLogger.debug('Request for VNFAdapter Rest:\n' + vnfAdapterRestRequest) + } + + + /** + * Delete volume group in AAI + * @param execution + * @param isDebugEnabled + */ + public void callRESTDeleteAAIVolumeGroup(DelegateExecution execution, isDebugEnabled) { + + // get variables + String queryAAIVolGrpIdResponse = execution.getVariable(prefix+"queryAAIVolGrpResponse") + String groupId = utils.getNodeText(queryAAIVolGrpIdResponse, "volume-group-id") + String resourceVersion = utils.getNodeText(queryAAIVolGrpIdResponse, "resource-version") + + String messageId = UUID.randomUUID().toString() + String cloudRegion = execution.getVariable(prefix+'aicCloudRegion') + + AaiUtil aaiUtil = new AaiUtil(this) + String aaiEndpoint = aaiUtil.getCloudInfrastructureCloudRegionEndpoint(execution) + String deleteAAIVolumeGrpIdRequest = aaiEndpoint + '/' + URLEncoder.encode(cloudRegion, "UTF-8") + "/volume-groups/volume-group/" + UriUtils.encode(groupId, "UTF-8") + + if(resourceVersion !=null){ + deleteAAIVolumeGrpIdRequest = deleteAAIVolumeGrpIdRequest +'?resource-version=' + UriUtils.encode(resourceVersion, 'UTF-8') + } + + msoLogger.debug('Delete AAI volume group : ' + deleteAAIVolumeGrpIdRequest) + msoLogger.debug("Delete AAI volume group : " + deleteAAIVolumeGrpIdRequest) + + APIResponse response = aaiUtil.executeAAIDeleteCall(execution, deleteAAIVolumeGrpIdRequest) + + String returnCode = response.getStatusCode() + String aaiResponseAsString = response.getResponseBodyAsString() + + msoLogger.debug("AAI delete volume group return code: " + returnCode) + msoLogger.debug("AAI delete volume group response: " + aaiResponseAsString) + msoLogger.debug("AAI delete volume group return code: " + returnCode) + msoLogger.debug("AAI delete volume group response: " + aaiResponseAsString) + + ExceptionUtil exceptionUtil = new ExceptionUtil() + if (returnCode=='200' || (returnCode == '204')) { + msoLogger.debug("Volume group $groupId deleted.") + } else { + if (returnCode=='404') { + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Volume group $groupId not found for delete in AAI Response code: 404") + } else { + WorkflowException aWorkflowException = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) + throw new BpmnError("MSOWorkflowException") + } + } + } + + + /** + * Check if volume group has a relationship to vf-module + * @param volumeGroupXml + * @return + */ + private boolean hasVfModuleRelationship(String volumeGroupXml) { + def Node volumeGroupNode = xmlParser.parseText(volumeGroupXml) + def Node relationshipList = utils.getChildNode(volumeGroupNode, 'relationship-list') + if (relationshipList != null) { + def NodeList relationships = utils.getIdenticalChildren(relationshipList, 'relationship') + for (Node relationship in relationships) { + def Node relatedTo = utils.getChildNode(relationship, 'related-to') + if ((relatedTo != null) && (relatedTo.text().equals('vf-module'))) { + def Node relatedLink = utils.getChildNode(relationship, 'related-link') + if (relatedLink !=null && relatedLink.text() != null){ + return true + } + } + } + } + return false + } + + + /** + * Extract the Tenant Id from the Volume Group information returned by AAI. + * @param volumeGroupXml Volume Group XML returned by AAI. + * @return the Tenant Id extracted from the Volume Group information. 'null' is returned if + * the Tenant Id is missing or could not otherwise be extracted. + */ + private String getTenantIdFromVolumeGroup(String volumeGroupXml) { + def Node volumeGroupNode = xmlParser.parseText(volumeGroupXml) + def Node relationshipList = utils.getChildNode(volumeGroupNode, 'relationship-list') + if (relationshipList != null) { + def NodeList relationships = utils.getIdenticalChildren(relationshipList, 'relationship') + for (Node relationship in relationships) { + def Node relatedTo = utils.getChildNode(relationship, 'related-to') + if ((relatedTo != null) && (relatedTo.text().equals('tenant'))) { + def NodeList relationshipDataList = utils.getIdenticalChildren(relationship, 'relationship-data') + for (Node relationshipData in relationshipDataList) { + def Node relationshipKey = utils.getChildNode(relationshipData, 'relationship-key') + if ((relationshipKey != null) && (relationshipKey.text().equals('tenant.tenant-id'))) { + def Node relationshipValue = utils.getChildNode(relationshipData, 'relationship-value') + if (relationshipValue != null) { + return relationshipValue.text() + } + } + } + } + } + } + return null + } +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVnf.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVnf.groovy new file mode 100644 index 0000000000..699e9bf40a --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVnf.groovy @@ -0,0 +1,161 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts + + +import javax.xml.parsers.DocumentBuilder +import javax.xml.parsers.DocumentBuilderFactory + +import org.apache.commons.lang3.* +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.onap.so.bpmn.common.scripts.ExceptionUtil +import org.onap.so.bpmn.common.scripts.VidUtils +import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.client.aai.AAIResourcesClient +import org.onap.so.client.aai.AAIObjectType +import org.onap.so.client.aai.entities.uri.AAIResourceUri +import org.onap.so.client.aai.entities.uri.AAIUriFactory +import org.w3c.dom.Document +import org.w3c.dom.Element +import org.w3c.dom.Node +import org.w3c.dom.NodeList +import org.xml.sax.InputSource + +import org.onap.so.logger.MessageEnum +import org.onap.so.logger.MsoLogger + +/** + * This class supports the DoDeleteVnf subFlow + * with the Deletion of a generic vnf for + * infrastructure. + * + */ +class DoDeleteVnf extends AbstractServiceTaskProcessor { + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoDeleteVnf.class); + + String Prefix="DoDVNF_" + ExceptionUtil exceptionUtil = new ExceptionUtil() + JsonUtils jsonUtil = new JsonUtils() + VidUtils vidUtils = new VidUtils(this) + + /** + * This method gets and validates the incoming + * request. + * + * @param - execution + * + */ + public void preProcessRequest(DelegateExecution execution) { + + execution.setVariable("prefix",Prefix) + msoLogger.trace("STARTED DoDeleteVnf PreProcessRequest Process") + + execution.setVariable("DoDVNF_SuccessIndicator", false) + execution.setVariable("DoDVNF_vnfInUse", false) + + try{ + // Get Variables + + String vnfId = execution.getVariable("vnfId") + execution.setVariable("DoDVNF_vnfId", vnfId) + msoLogger.debug("Incoming Vnf(Instance) Id is: " + vnfId) + + // Setting for sub flow calls + execution.setVariable("DoDVNF_type", "generic-vnf") + }catch(BpmnError b){ + msoLogger.debug("Rethrowing MSOWorkflowException") + throw b + }catch(Exception e){ + msoLogger.debug(" Error Occured in DoDeleteVnf PreProcessRequest method!" + e) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in DoDeleteVnf PreProcessRequest") + + } + msoLogger.trace("COMPLETED DoDeleteVnf PreProcessRequest Process ") + } + + + public void processGetVnfResponse(DelegateExecution execution){ + + execution.setVariable("prefix",Prefix) + msoLogger.trace("STARTED DoDeleteVnf processGetVnfResponse Process ") + try { + String vnf = execution.getVariable("DoDVNF_genericVnf") + String resourceVersion = utils.getNodeText(vnf, "resource-version") + execution.setVariable("DoDVNF_resourceVersion", resourceVersion) + + if(utils.nodeExists(vnf, "relationship")){ + InputSource source = new InputSource(new StringReader(vnf)); + DocumentBuilderFactory docFactory = DocumentBuilderFactory.newInstance(); + DocumentBuilder docBuilder = docFactory.newDocumentBuilder() + Document vnfXml = docBuilder.parse(source) + + NodeList nodeList = vnfXml.getElementsByTagName("relationship") + for (int x = 0; x < nodeList.getLength(); x++) { + Node node = nodeList.item(x) + if (node.getNodeType() == Node.ELEMENT_NODE) { + Element eElement = (Element) node + def e = eElement.getElementsByTagName("related-to").item(0).getTextContent() + if(e.equals("volume-group") || e.equals("l3-network")){ + msoLogger.debug("Generic Vnf still has relationship to OpenStack.") + execution.setVariable("DoDVNF_vnfInUse", true) + }else{ + msoLogger.debug("Relationship NOT related to OpenStack") + } + } + } + } + + if(utils.nodeExists(vnf, "vf-module")){ + execution.setVariable("DoDVNF_vnfInUse", true) + msoLogger.debug("Generic Vnf still has vf-modules.") + } + + + } catch (Exception ex) { + msoLogger.debug("Error Occured in DoDeleteVnf processGetVnfResponse Process " + ex.getMessage()) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in DoDeleteVnf processGetVnfResponse Process") + + } + msoLogger.trace("COMPLETED DoDeleteVnf processGetVnfResponse Process ") + } + + /** + * Deletes the generic vnf from aai + */ + public void deleteVnf(DelegateExecution execution) { + msoLogger.trace("STARTED deleteVnf") + try { + String vnfId = execution.getVariable("DoDVNF_vnfId") + + AAIResourcesClient resourceClient = new AAIResourcesClient(); + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId) + resourceClient.delete(uri) + + msoLogger.trace("COMPLETED deleteVnf") + } catch (Exception ex) { + msoLogger.debug("Error Occured in DoDeleteVnf deleteVnf Process " + ex.getMessage()) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in DoDeleteVnf deleteVnf Process") + } + } + +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVnfAndModules.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVnfAndModules.groovy new file mode 100644 index 0000000000..d448dd3e79 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVnfAndModules.groovy @@ -0,0 +1,538 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts + +import static org.apache.commons.lang3.StringUtils.*; + +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution; +import org.json.JSONArray; +import org.json.JSONObject; +import org.onap.so.bpmn.common.scripts.AaiUtil +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.onap.so.bpmn.common.scripts.ExceptionUtil +import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.so.bpmn.common.scripts.SDNCAdapterUtils +import org.onap.so.bpmn.common.scripts.VidUtils +import org.onap.so.bpmn.core.UrnPropertiesReader +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.bpmn.core.domain.ModelInfo +import org.onap.so.bpmn.core.domain.ModuleResource +import org.onap.so.bpmn.core.domain.ServiceDecomposition +import org.onap.so.bpmn.core.domain.VnfResource +import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.logger.MessageEnum +import org.onap.so.logger.MsoLogger +import org.onap.so.rest.APIResponse +import org.springframework.web.util.UriUtils; + +/** + * This class supports the macro VID Flow + * with the deletion of a generic vnf and related VF modules. + */ +class DoDeleteVnfAndModules extends AbstractServiceTaskProcessor { + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoDeleteVnfAndModules.class); + + String Prefix="DDVAM_" + ExceptionUtil exceptionUtil = new ExceptionUtil() + JsonUtils jsonUtil = new JsonUtils() + VidUtils vidUtils = new VidUtils(this) + SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this) + + /** + * This method gets and validates the incoming + * request. + * + * @param - execution + * + */ + public void preProcessRequest(DelegateExecution execution) { + + execution.setVariable("prefix",Prefix) + msoLogger.trace("STARTED DoDeleteVnfAndModules PreProcessRequest Process") + + try{ + // Get Variables + + String cloudConfiguration = execution.getVariable("cloudConfiguration") + msoLogger.debug("Cloud Configuration: " + cloudConfiguration) + + String requestId = execution.getVariable("msoRequestId") + execution.setVariable("requestId", requestId) + execution.setVariable("mso-request-id", requestId) + msoLogger.debug("Incoming Request Id is: " + requestId) + + String serviceInstanceId = execution.getVariable("serviceInstanceId") + msoLogger.debug("Incoming Service Instance Id is: " + serviceInstanceId) + + String vnfId = execution.getVariable("vnfId") + msoLogger.debug("Incoming Vnf Id is: " + vnfId) + + String source = "VID" + execution.setVariable("DDVAM_source", source) + msoLogger.debug("Incoming Source is: " + source) + + execution.setVariable("DDVAM_isVidRequest", "true") + + String sdncVersion = execution.getVariable("sdncVersion") + if (sdncVersion == null) { + sdncVersion = "1702" + } + execution.setVariable("DDVAM_sdncVersion", sdncVersion) + msoLogger.debug("Incoming Sdnc Version is: " + sdncVersion) + + // Set aLaCarte flag to false + execution.setVariable("aLaCarte", false) + + String sdncCallbackUrl = (String) UrnPropertiesReader.getVariable("mso.workflow.sdncadapter.callback", execution) + if (sdncCallbackUrl == null || sdncCallbackUrl.trim().isEmpty()) { + def msg = 'Required variable \'mso.workflow.sdncadapter.callback\' is missing' + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, msg, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception"); + exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) + } + execution.setVariable("sdncCallbackUrl", sdncCallbackUrl) + msoLogger.debug("SDNC Callback URL: " + sdncCallbackUrl) + msoLogger.debug("SDNC Callback URL is: " + sdncCallbackUrl) + + + if (!sdncVersion.equals("1702")) { + //String vnfModelInfo = execution.getVariable("vnfModelInfo") + //String serviceModelInfo = execution.getVariable("serviceModelInfo") + + String serviceId = execution.getVariable("productFamilyId") + execution.setVariable("DDVAM_serviceId", serviceId) + msoLogger.debug("Incoming Service Id is: " + serviceId) + + + //String modelInvariantId = jsonUtil.getJsonValue(vnfModelInfo, "modelInvariantId") + //execution.setVariable("DDVAM_modelInvariantId", modelInvariantId) + //msoLogger.debug("Incoming Invariant Id is: " + modelInvariantId) + + //String modelVersionId = jsonUtil.getJsonValue(vnfModelInfo, "modelVersionId") + //if (modelVersionId == null) { + // modelVersionId = "" + //} + //execution.setVariable("DDVAM_modelVersionId", modelVersionId) + //msoLogger.debug("Incoming Version Id is: " + modelVersionId) + + //String modelVersion = jsonUtil.getJsonValue(vnfModelInfo, "modelVersion") + //execution.setVariable("DDVAM_modelVersion", modelVersion) + //msoLogger.debug("Incoming Model Version is: " + modelVersion) + + //String modelName = jsonUtil.getJsonValue(vnfModelInfo, "modelName") + //execution.setVariable("DDVAM_modelName", modelName) + //msoLogger.debug("Incoming Model Name is: " + modelName) + + //String modelCustomizationId = jsonUtil.getJsonValue(vnfModelInfo, "modelCustomizationId") + //if (modelCustomizationId == null) { + // modelCustomizationId = "" + //} + //execution.setVariable("DDVAM_modelCustomizationId", modelCustomizationId) + //msoLogger.debug("Incoming Model Customization Id is: " + modelCustomizationId) + + String cloudSiteId = execution.getVariable("lcpCloudRegionId") + execution.setVariable("DDVAM_cloudSiteId", cloudSiteId) + msoLogger.debug("Incoming Cloud Site Id is: " + cloudSiteId) + + String tenantId = execution.getVariable("tenantId") + execution.setVariable("DDVAM_tenantId", tenantId) + msoLogger.debug("Incoming Tenant Id is: " + tenantId) + + String globalSubscriberId = execution.getVariable("globalSubscriberId") + if (globalSubscriberId == null) { + globalSubscriberId = "" + } + execution.setVariable("DDVAM_globalSubscriberId", globalSubscriberId) + msoLogger.debug("Incoming Global Subscriber Id is: " + globalSubscriberId) + + } + execution.setVariable("DDVAM_vfModulesFromDecomposition", null) + // Retrieve serviceDecomposition if present + ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition") + if (serviceDecomposition != null) { + msoLogger.debug("Getting Catalog DB data from ServiceDecomposition object: " + serviceDecomposition.toJsonString()) + List<VnfResource> vnfs = serviceDecomposition.getVnfResources() + msoLogger.debug("Read vnfs") + if (vnfs == null) { + msoLogger.debug("Error - vnfs are empty in serviceDecomposition object") + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in preProcessRequest - vnfs are empty") + } + VnfResource vnf = vnfs[0] + + if (vnf == null) { + msoLogger.debug("Error - vnf is empty in serviceDecomposition object") + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in preProcessRequest - vnf is empty") + } + + List<ModuleResource> vfModules = vnf.getAllVfModuleObjects() + + execution.setVariable("DDVAM_vfModulesFromDecomposition", vfModules) + } + + execution.setVariable("DDVAM_moduleCount", 0) + execution.setVariable("DDVAM_nextModule", 0) + + + }catch(BpmnError b){ + msoLogger.debug("Rethrowing MSOWorkflowException") + throw b + }catch(Exception e){ + msoLogger.debug(" Error Occured in DoCreateVnfAndModules PreProcessRequest method!" + e.getMessage()) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in DoCreateVnf PreProcessRequest") + + } + msoLogger.trace("COMPLETED DoDeleteVnfAndModules PreProcessRequest Process ") + } + + + + public void preProcessAddOnModule(DelegateExecution execution){ + + execution.setVariable("prefix", Prefix) + msoLogger.trace("STARTED preProcessAddOnModule ") + + try { + JSONArray addOnModules = (JSONArray) execution.getVariable("addOnModules") + int addOnIndex = (int) execution.getVariable("addOnModulesDeployed") + + JSONObject addOnModule = addOnModules[addOnIndex] + + def newVfModuleId = UUID.randomUUID().toString() + execution.setVariable("addOnVfModuleId", newVfModuleId) + + execution.setVariable("instancesOfThisModelDeployed", 0) + + JSONObject addOnVfModuleModelInfoObject = jsonUtil.getJsonValueForKey(addOnModule, "modelInfo") + String addOnVfModuleModelInfo = addOnVfModuleModelInfoObject.toString() + execution.setVariable("addOnVfModuleModelInfo", addOnVfModuleModelInfo) + String addOnVfModuleLabel = jsonUtil.getJsonValueForKey(addOnModule, "vfModuleLabel") + execution.setVariable("addOnVfModuleLabel", addOnVfModuleLabel) + String addOnPersonaModelId = jsonUtil.getJsonValueForKey(addOnVfModuleModelInfoObject, "modelInvariantUuid") + execution.setVariable("addOnPersonaModelId", addOnPersonaModelId) + String addOnInitialCount = jsonUtil.getJsonValueForKey(addOnModule, "initialCount") + execution.setVariable("initialCount", addOnInitialCount) + + + }catch(Exception e){ + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception Occured Processing preProcessAddOnModule." + e, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during preProcessAddOnModule Method:\n" + e.getMessage()) + } + msoLogger.trace("COMPLETED preProcessSDNCAssignRequest ") + } + + /** + * Using the received vnfId and vfModuleId, query AAI to get the corresponding VNF info. + * A 200 response is expected with the VNF info in the response body. Will find out the base module info. + * + * @param execution The flow's execution instance. + */ + public void queryAAIVfModule(DelegateExecution execution) { + + def method = getClass().getSimpleName() + '.queryAAIVfModule(' + + 'execution=' + execution.getId() + + ')' + msoLogger.trace('Entered ' + method) + + try { + def vnfId = execution.getVariable('vnfId') + + AaiUtil aaiUriUtil = new AaiUtil(this) + String aai_uri = aaiUriUtil.getNetworkGenericVnfUri(execution) + msoLogger.debug('AAI URI is: ' + aai_uri) + + String endPoint = UrnPropertiesReader.getVariable("aai.endpoint", execution) + "${aai_uri}/" + UriUtils.encode(vnfId, "UTF-8") + "?depth=1" + msoLogger.debug("AAI endPoint: " + endPoint) + + try { + msoLogger.debug("createVfModule - invoking httpGet() to AAI") + APIResponse response = aaiUriUtil.executeAAIGetCall(execution, endPoint) + + def responseData = response.getResponseBodyAsString() + if (responseData != null) { + msoLogger.debug("Received generic VNF data: " + responseData) + + } + + msoLogger.debug("createVfModule - queryAAIVfModule Response: " + responseData) + msoLogger.debug("createVfModule - queryAAIVfModule ResponseCode: " + response.getStatusCode()) + + execution.setVariable('DCVFM_queryAAIVfModuleResponseCode', response.getStatusCode()) + execution.setVariable('DCVFM_queryAAIVfModuleResponse', responseData) + msoLogger.debug('Response code:' + response.getStatusCode()) + msoLogger.debug('Response:' + System.lineSeparator() + responseData) + //Map<String, String>[] vfModules = new HashMap<String,String>[] + List<ModuleResource> vfModulesFromDecomposition = execution.getVariable("DDVAM_vfModulesFromDecomposition") + def vfModulesList = new ArrayList<Map<String,String>>() + def vfModules = null + def vfModuleBaseEntry = null + if (response.getStatusCode() == 200) { + // Parse the VNF record from A&AI to find base module info + msoLogger.debug('Parsing the VNF data to find base module info') + if (responseData != null) { + def vfModulesText = utils.getNodeXml(responseData, "vf-modules") + msoLogger.debug("vModulesText: " + vfModulesText) + if (vfModulesText != null && !vfModulesText.trim().isEmpty()) { + def xmlVfModules= new XmlSlurper().parseText(vfModulesText) + vfModules = xmlVfModules.'**'.findAll {it.name() == "vf-module"} + execution.setVariable("DDVAM_moduleCount", vfModules.size()) + int vfModulesSize = 0 + ModelInfo vfModuleModelInfo = null + for (i in 0..vfModules.size()-1) { + def vfModuleXml = groovy.xml.XmlUtil.serialize(vfModules[i]) + + Map<String, String> vfModuleEntry = new HashMap<String, String>() + def vfModuleId = utils.getNodeText(vfModuleXml, "vf-module-id") + vfModuleEntry.put("vfModuleId", vfModuleId) + def vfModuleName = utils.getNodeText(vfModuleXml, "vf-module-name") + vfModuleEntry.put("vfModuleName", vfModuleName) + + // Find the model for this vf module in decomposition if specified + if (vfModulesFromDecomposition != null) { + msoLogger.debug("vfModulesFromDecomposition is not null") + def vfModuleUuid = utils.getNodeText(vfModuleXml, "model-version-id") + if (vfModuleUuid == null) { + vfModuleUuid = utils.getNodeText(vfModuleXml, "persona-model-version") + } + msoLogger.debug("vfModule UUID is: " + vfModuleUuid) + for (j in 0..vfModulesFromDecomposition.size()-1) { + ModuleResource mr = vfModulesFromDecomposition[j] + if (mr.getModelInfo().getModelUuid() == vfModuleUuid) { + msoLogger.debug("Found modelInfo") + vfModuleModelInfo = mr.getModelInfo() + break + } + + } + } + if (vfModuleModelInfo != null) { + String vfModuleModelInfoString = vfModuleModelInfo.toString() + def vfModuleModelInfoValue = jsonUtil.getJsonValue(vfModuleModelInfoString, "modelInfo") + vfModuleEntry.put("vfModuleModelInfo", vfModuleModelInfoValue) + } + else { + vfModuleEntry.put("vfModuleModelInfo", null) + } + + + def isBaseVfModule = utils.getNodeText(vfModuleXml, "is-base-vf-module") + // Save base vf module for last + if (isBaseVfModule == "true") { + vfModuleBaseEntry = vfModuleEntry + } + else { + vfModulesList.add(vfModuleEntry) + } + } + if (vfModuleBaseEntry != null) { + vfModulesList.add(vfModuleBaseEntry) + } + } + + } + } + execution.setVariable("DDVAM_vfModules", vfModulesList) + } catch (Exception ex) { + ex.printStackTrace() + msoLogger.debug('Exception occurred while executing AAI GET:' + ex.getMessage()) + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'AAI GET Failed:' + ex.getMessage()) + } + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in queryAAIVfModule(): ' + e.getMessage()) + } + } + + public void prepareNextModuleToDelete(DelegateExecution execution){ + + execution.setVariable("prefix", Prefix) + msoLogger.trace("STARTED prepareNextModuleToDelete ") + + try { + int i = execution.getVariable("DDVAM_nextModule") + def vfModules = execution.getVariable("DDVAM_vfModules") + def vfModule = vfModules[i] + + def vfModuleId = vfModule.get("vfModuleId") + execution.setVariable("DDVAM_vfModuleId", vfModuleId) + + def vfModuleName = vfModule.get("vfModuleName") + execution.setVariable("DDVAM_vfModuleName", vfModuleName) + + def vfModuleModelInfo = vfModule.get("vfModuleModelInfo") + msoLogger.debug("vfModuleModelInfo for module delete: " + vfModuleModelInfo) + execution.setVariable("DDVAM_vfModuleModelInfo", vfModuleModelInfo) + + }catch(Exception e){ + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception Occured Processing preProcessAddOnModule." + e, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during prepareNextModuleToDelete Method:\n" + e.getMessage()) + } + msoLogger.trace("COMPLETED prepareNextModuleToDelete ") + } + + public void preProcessSDNCDeactivateRequest(DelegateExecution execution){ + + execution.setVariable("prefix", Prefix) + msoLogger.trace("STARTED preProcessSDNCDeactivateRequest ") + def vnfId = execution.getVariable("vnfId") + def serviceInstanceId = execution.getVariable("serviceInstanceId") + + try{ + //Build SDNC Request + + String deactivateSDNCRequest = buildSDNCRequest(execution, serviceInstanceId, "deactivate") + + deactivateSDNCRequest = utils.formatXml(deactivateSDNCRequest) + execution.setVariable("DDVAM_deactivateSDNCRequest", deactivateSDNCRequest) + msoLogger.debug("Outgoing DeactivateSDNCRequest is: \n" + deactivateSDNCRequest) + msoLogger.debug("Outgoing DeactivateSDNCRequest is: \n" + deactivateSDNCRequest) + + }catch(Exception e){ + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception Occured Processing preProcessSDNCDeactivateRequest." + e, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during preProcessSDNCDeactivateRequest Method:\n" + e.getMessage()) + } + msoLogger.trace("COMPLETED preProcessSDNCDeactivateRequest ") + } + + public void preProcessSDNCUnassignRequest(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.preProcessSDNCUnassignRequest(' + + 'execution=' + execution.getId() + + ')' + + msoLogger.trace('Entered ' + method) + execution.setVariable("prefix", Prefix) + msoLogger.trace("STARTED preProcessSDNCUnassignRequest Process ") + try{ + String vnfId = execution.getVariable("vnfId") + String serviceInstanceId = execution.getVariable("serviceInstanceId") + + String unassignSDNCRequest = buildSDNCRequest(execution, serviceInstanceId, "unassign") + + execution.setVariable("DDVAM_unassignSDNCRequest", unassignSDNCRequest) + msoLogger.debug("Outgoing UnassignSDNCRequest is: \n" + unassignSDNCRequest) + msoLogger.debug("Outgoing UnassignSDNCRequest is: \n" + unassignSDNCRequest) + + }catch(Exception e){ + msoLogger.debug("Exception Occured Processing preProcessSDNCUnassignRequest. Exception is:\n" + e) + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during preProcessSDNCUnassignRequest Method:\n" + e.getMessage()) + } + msoLogger.trace("COMPLETED preProcessSDNCUnassignRequest Process ") + } + + public String buildSDNCRequest(DelegateExecution execution, String svcInstId, String action){ + + String uuid = execution.getVariable('testReqId') // for junits + if(uuid==null){ + uuid = execution.getVariable("msoRequestId") + "-" + System.currentTimeMillis() + } + def callbackURL = execution.getVariable("sdncCallbackUrl") + def requestId = execution.getVariable("msoRequestId") + def serviceId = execution.getVariable("DDVAM_serviceId") + def tenantId = execution.getVariable("DDVAM_tenantId") + def source = execution.getVariable("DDVAM_source") + def vnfId = execution.getVariable("vnfId") + def serviceInstanceId = execution.getVariable("serviceInstanceId") + def cloudSiteId = execution.getVariable("DDVAM_cloudSiteId") + def modelCustomizationId = execution.getVariable("DDVAM_modelCustomizationId") + //def serviceModelInfo = execution.getVariable("serviceModelInfo") + //def vnfModelInfo = execution.getVariable("vnfModelInfo") + //String serviceEcompModelInformation = sdncAdapterUtils.modelInfoToEcompModelInformation(serviceModelInfo) + //String vnfEcompModelInformation = sdncAdapterUtils.modelInfoToEcompModelInformation(vnfModelInfo) + def globalSubscriberId = execution.getVariable("DDVAM_globalSubscriberId") + def sdncVersion = execution.getVariable("DDVAM_sdncVersion") + + String sdncRequest = + """<sdncadapterworkflow:SDNCAdapterWorkflowRequest xmlns:ns5="http://org.onap/so/request/types/v1" + xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1" + xmlns:sdncadapter="http://org.onap/workflow/sdnc/adapter/schema/v1"> + <sdncadapter:RequestHeader> + <sdncadapter:RequestId>${MsoUtils.xmlEscape(uuid)}</sdncadapter:RequestId> + <sdncadapter:SvcInstanceId>${MsoUtils.xmlEscape(svcInstId)}</sdncadapter:SvcInstanceId> + <sdncadapter:SvcAction>${MsoUtils.xmlEscape(action)}</sdncadapter:SvcAction> + <sdncadapter:SvcOperation>vnf-topology-operation</sdncadapter:SvcOperation> + <sdncadapter:CallbackUrl>${MsoUtils.xmlEscape(callbackURL)}</sdncadapter:CallbackUrl> + <sdncadapter:MsoAction>generic-resource</sdncadapter:MsoAction> + </sdncadapter:RequestHeader> + <sdncadapterworkflow:SDNCRequestData> + <request-information> + <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> + <request-action>DeleteVnfInstance</request-action> + <source>${MsoUtils.xmlEscape(source)}</source> + <notification-url/> + <order-number/> + <order-version/> + </request-information> + <service-information> + <service-id/> + <subscription-service-type/> + <service-instance-id>${MsoUtils.xmlEscape(serviceInstanceId)}</service-instance-id> + <global-customer-id/> + </service-information> + <vnf-information> + <vnf-id>${MsoUtils.xmlEscape(vnfId)}</vnf-id> + <vnf-type/> + </vnf-information> + <vnf-request-input> + <vnf-name/> + <tenant>${MsoUtils.xmlEscape(tenantId)}</tenant> + <aic-cloud-region>${MsoUtils.xmlEscape(cloudSiteId)}</aic-cloud-region> + </vnf-request-input> + </sdncadapterworkflow:SDNCRequestData> + </sdncadapterworkflow:SDNCAdapterWorkflowRequest>""" + + msoLogger.debug("sdncRequest: " + sdncRequest) + return sdncRequest + } + + public void validateSDNCResponse(DelegateExecution execution, String response, String method){ + + execution.setVariable("prefix",Prefix) + msoLogger.trace("STARTED ValidateSDNCResponse Process") + + WorkflowException workflowException = execution.getVariable("WorkflowException") + boolean successIndicator = execution.getVariable("SDNCA_SuccessIndicator") + + msoLogger.debug("workflowException: " + workflowException) + + SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this) + sdncAdapterUtils.validateSDNCResponse(execution, response, workflowException, successIndicator) + + msoLogger.debug("SDNCResponse: " + response) + + String sdncResponse = response + if(execution.getVariable(Prefix + 'sdncResponseSuccess') == true){ + msoLogger.debug("Received a Good Response from SDNC Adapter for " + method + " SDNC Call. Response is: \n" + sdncResponse) + }else{ + msoLogger.debug("Received a BAD Response from SDNC Adapter for " + method + " SDNC Call.") + throw new BpmnError("MSOWorkflowException") + } + msoLogger.trace("COMPLETED ValidateSDNCResponse Process") + } + + + + + + + +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoScaleE2EServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoScaleE2EServiceInstance.groovy new file mode 100644 index 0000000000..41d9384f52 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoScaleE2EServiceInstance.groovy @@ -0,0 +1,142 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2018 CMCC All rights reserved. * + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.so.bpmn.infrastructure.scripts + +import static org.apache.commons.lang3.StringUtils.*; + +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.json.JSONArray; +import org.json.JSONObject; +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.onap.so.bpmn.common.scripts.ExceptionUtil +import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.logger.MessageEnum +import org.onap.so.logger.MsoLogger +import org.springframework.web.util.UriUtils; + + + +/** + * This groovy class supports the <class>DoScaleServiceInstance.bpmn</class> process. + * + */ +public class DoScaleE2EServiceInstance extends AbstractServiceTaskProcessor { + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoScaleE2EServiceInstance.class); + + + String Prefix = "DCRESI_" + ExceptionUtil exceptionUtil = new ExceptionUtil() + JsonUtils jsonUtil = new JsonUtils() + + public void preProcessRequest(DelegateExecution execution) { + String msg = "" + msoLogger.trace("preProcessRequest ") + + try { + String requestId = execution.getVariable("msoRequestId") + execution.setVariable("prefix", Prefix) + + //Inputs + String globalSubscriberId = execution.getVariable("globalSubscriberId") + + String serviceType = execution.getVariable("serviceType") + String serviceInstanceName = execution.getVariable("serviceInstanceName") + String serviceInstanceId = execution.getVariable("serviceInstanceId") + + execution.setVariable("serviceType", serviceType) + + String resourceTemplateUUIDs = "" + String scaleNsRequest = execution.getVariable("bpmnRequest") + JSONObject jsonObject = new JSONObject(scaleNsRequest).getJSONObject("service") + JSONArray jsonArray = jsonObject.getJSONArray("resources") + + for (int i = 0; i < jsonArray.size(); i++) { + JSONObject reqBodyJsonObj = jsonArray.getJSONObject(i) + String nsInstanceId = reqBodyJsonObj.getString("resourceInstanceId") + resourceTemplateUUIDs = resourceTemplateUUIDs + nsInstanceId + ":" + } + + execution.setVariable("resourceTemplateUUIDs", resourceTemplateUUIDs) + + if (serviceInstanceName == null) { + execution.setVariable("serviceInstanceName", "") + } + if (isBlank(serviceInstanceId)) { + msg = "Input serviceInstanceId is null" + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + } catch (BpmnError e) { + throw e; + } catch (Exception ex) { + msg = "Exception in preProcessRequest " + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.trace("Exit preProcessRequest ") + } + + + public void preInitResourcesOperStatus(DelegateExecution execution){ + msoLogger.trace("STARTED preInitResourcesOperStatus Process ") + try{ + String serviceId = execution.getVariable("serviceInstanceId") + String operationId = execution.getVariable("operationId") + String operationType = "SCALE" + + // resourceTemplateUUIDs should be created ?? + String resourceTemplateUUIDs = execution.getVariable("resourceTemplateUUIDs") + msoLogger.info("Generated new operation for Service Instance serviceId:" + serviceId + " operationId:" + operationId + " operationType:" + operationType) + serviceId = UriUtils.encode(serviceId,"UTF-8") + execution.setVariable("serviceInstanceId", serviceId) + execution.setVariable("operationId", operationId) + execution.setVariable("operationType", operationType) + + execution.setVariable("URN_mso_openecomp_adapters_db_endpoint","http://mso.mso.testlab.openecomp.org:8080/dbadapters/RequestsDbAdapter") + + String payload = + """<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" + xmlns:ns="http://org.onap.so/requestsdb"> + <soapenv:Header/> + <soapenv:Body> + <ns:initResourceOperationStatus xmlns:ns="http://org.onap.so/requestsdb"> + <serviceId>${MsoUtils.xmlEscape(serviceId)}</serviceId> + <operationId>${MsoUtils.xmlEscape(operationId)}</operationId> + <operationType>${MsoUtils.xmlEscape(operationType)}</operationType> + <resourceTemplateUUIDs>${MsoUtils.xmlEscape(resourceTemplateUUIDs)}</resourceTemplateUUIDs> + </ns:initResourceOperationStatus> + </soapenv:Body> + </soapenv:Envelope>""" + + payload = utils.formatXml(payload) + execution.setVariable("CVFMI_initResOperStatusRequest", payload) + msoLogger.info("Outgoing initResourceOperationStatus: \n" + payload) + msoLogger.debug("CreateVfModuleInfra Outgoing initResourceOperationStatus Request: " + payload) + + }catch(Exception e){ + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception Occured Processing preInitResourcesOperStatus.", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e); + execution.setVariable("CVFMI_ErrorResponse", "Error Occurred during preInitResourcesOperStatus Method:\n" + e.getMessage()) + } + msoLogger.trace("COMPLETED preInitResourcesOperStatus Process ") + } + +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoScaleVFCNetworkServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoScaleVFCNetworkServiceInstance.groovy new file mode 100644 index 0000000000..e06e5238c6 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoScaleVFCNetworkServiceInstance.groovy @@ -0,0 +1,332 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2018 CMCC. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts + +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.json.JSONArray +import org.json.JSONObject; + +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.onap.so.bpmn.common.scripts.ExceptionUtil +import org.onap.so.bpmn.core.json.JsonUtils + +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.runtime.Execution +import com.fasterxml.jackson.databind.ObjectMapper + +import org.onap.so.rest.RESTClient +import org.onap.so.rest.RESTConfig +import org.onap.so.rest.APIResponse; + +import org.onap.so.bpmn.infrastructure.vfcmodel.ScaleResource +import org.onap.so.bpmn.infrastructure.vfcmodel.ScaleNsByStepsData +import org.onap.so.bpmn.infrastructure.vfcmodel.ScaleNsData + +import org.onap.so.bpmn.infrastructure.vfcmodel.NSResourceInputParameter +import org.onap.so.bpmn.infrastructure.vfcmodel.NsOperationKey +import org.onap.so.bpmn.infrastructure.vfcmodel.NsScaleParameters +import org.onap.so.bpmn.infrastructure.vfcmodel.NsParameters +import org.onap.so.bpmn.infrastructure.vfcmodel.LocationConstraint +import org.onap.so.logger.MessageEnum +import org.onap.so.logger.MsoLogger + + + + +/** + * This groovy class supports the <class>DoScaleVFCNetworkServiceInstance.bpmn</class> process. + * flow for VFC Network Service Scale + */ +public class DoScaleVFCNetworkServiceInstance extends AbstractServiceTaskProcessor { + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoScaleVFCNetworkServiceInstance.class); + + + String host = "http://mso.mso.testlab.openecomp.org:8080" + + String scaleUrl = "/vfc/rest/v1/vfcadapter/ns/{nsInstanceId}/scale" + + String queryJobUrl = "/vfc/rest/v1/vfcadapter/jobs/{jobId}" + + ExceptionUtil exceptionUtil = new ExceptionUtil() + + JsonUtils jsonUtil = new JsonUtils() + + /** + * Pre Process the BPMN Flow Request + * Inclouds: + * generate the nsOperationKey + * generate the nsParameters + */ + public void preProcessRequest(DelegateExecution execution) { + msoLogger.trace("preProcessRequest() ") + + List<NSResourceInputParameter> nsRIPList = convertScaleNsReq2NSResInputParamList(execution) + String requestJsonStr = "" + int size = nsRIPList.size() + for (int i = 0; i < size; i++) { + NSResourceInputParameter nsRIP = nsRIPList.get(i) + + if (i == size - 1) { + requestJsonStr += objectToJsonStr(nsRIP) + } else { + requestJsonStr += objectToJsonStr(nsRIP) + "|" + } + } + + execution.setVariable("reqBody", requestJsonStr) + + msoLogger.trace("Exit preProcessRequest ") + } + + /** + * scale NS task + */ + public void scaleNetworkService(DelegateExecution execution) { + def isDebugEnabled = execution.getVariable("isDebugLogEnabled") + + String saleNsRequest = execution.getVariable("reqBody") + String[] nsReqStr = saleNsRequest.split("\\|") + + for (int i = 0; i < nsReqStr.length; i++) { + JSONObject reqBodyJsonObj = new JSONObject(nsReqStr[i]) + String nsInstanceId = reqBodyJsonObj.getJSONObject("nsScaleParameters").getString("nsInstanceId") + String nodeTemplateUUID = reqBodyJsonObj.getJSONObject("nsOperationKey").getString("nodeTemplateUUID") + reqBodyJsonObj.getJSONObject("nsScaleParameters").remove("nsInstanceId") + String reqBody = reqBodyJsonObj.toString() + + String url = host + scaleUrl.replaceAll("\\{nsInstanceId\\}", nsInstanceId) + + APIResponse apiResponse = postRequest(execution, url, reqBody) + + String returnCode = apiResponse.getStatusCode() + String aaiResponseAsString = apiResponse.getResponseBodyAsString() + String jobId = "" + if (returnCode == "200" || returnCode == "202") { + jobId = jsonUtil.getJsonValue(aaiResponseAsString, "jobId") + } + utils.log("INFO", "scaleNetworkService get a ns scale job Id:" + jobId, isDebugEnabled) + execution.setVariable("jobId", jobId) + execution.setVariable("nodeTemplateUUID", nodeTemplateUUID) + + String isScaleFinished = "" + + if(jobId =="" || jobId == null){ + continue + } + // query the requested network service scale status, if finished, then start the next one, otherwise, wait + while (isScaleFinished != "finished" && isScaleFinished != "error"){ + timeDelay() + queryNSProgress(execution) + isScaleFinished = execution.getVariable("operationStatus") + } + } + } + + /** + * query NS task + */ + private void queryNSProgress(DelegateExecution execution) { + String jobId = execution.getVariable("jobId") + String url = host + queryJobUrl.replaceAll("\\{jobId\\}", jobId) + + NsOperationKey nsOperationKey = new NsOperationKey() + // is this net work service ID or E2E service ID? + nsOperationKey.setServiceId(execution.getVariable("serviceId")) + nsOperationKey.setServiceType(execution.getVariable("serviceType")) + nsOperationKey.setGlobalSubscriberId(execution.getVariable("globalSubscriberId")) + nsOperationKey.setNodeTemplateUUID(execution.getVariable("nodeTemplateUUID")) + nsOperationKey.setOperationId(execution.getVariable("operationId")) + String queryReqBody = objectToJsonStr(nsOperationKey) + + APIResponse apiResponse = postRequest(execution,url, queryReqBody) + + String returnCode = apiResponse.getStatusCode() + String aaiResponseAsString = apiResponse.getResponseBodyAsString() + + String operationStatus = "error" + + if (returnCode == "200") { + operationStatus = jsonUtil.getJsonValue(aaiResponseAsString, "responseDescriptor.status") + } + + execution.setVariable("operationStatus", operationStatus) + } + + /** + * delay 5 sec + * + */ + private void timeDelay() { + try { + Thread.sleep(5000) + } catch (InterruptedException e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Time Delay exception" + e, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, ""); + } + } + + /** + * finish NS task + */ + public void finishNSScale(DelegateExecution execution) { + //no need to do anything util now + System.out.println("Scale finished.") + } + + /** + * post request + * url: the url of the request + * requestBody: the body of the request + */ + private APIResponse postRequest(DelegateExecution execution, String url, String requestBody){ + msoLogger.trace("Started Execute VFC adapter Post Process ") + msoLogger.info("url:"+url +"\nrequestBody:"+ requestBody) + APIResponse apiResponse = null + try{ + RESTConfig config = new RESTConfig(url) + RESTClient client = new RESTClient(config).addHeader("Content-Type", "application/json").addHeader("Authorization","Basic QlBFTENsaWVudDpwYXNzd29yZDEk") +// RESTClient client = new RESTClient(config).addHeader("Content-Type", "application/json").addHeader("Accept","application/json").addHeader("Authorization","Basic QlBFTENsaWVudDpwYXNzd29yZDEk") + apiResponse = client.httpPost(requestBody) + msoLogger.info("response code:"+ apiResponse.getStatusCode() +"\nresponse body:"+ apiResponse.getResponseBodyAsString()) + msoLogger.trace("Completed Execute VF-C adapter Post Process ") + }catch(Exception e){ + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception occured while executing VFC Post Call.", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e); + throw new BpmnError("MSOWorkflowException") + } + return apiResponse + } + + /** + * create a Scale Resource object list from a NSScaleRequestJso nString + * This method is for the specific request from Scale Network Service BPMN workflow + * @param nsScaleRequestJsonString , a specific request Json string which conform to ?? class + * @return List < ScaleResource > + */ + private List<ScaleResource> jsonGetNsResourceList(String nsScaleRequestJsonString) { + List<ScaleResource> list = new ArrayList<ScaleResource>() + JSONObject jsonObject = new JSONObject(nsScaleRequestJsonString) + + JSONObject jsonResource = jsonObject.getJSONObject("service") + JSONArray arr = jsonResource.getJSONArray("resources") + + for (int i = 0; i < arr.length(); i++) { + JSONObject tempResource = arr.getJSONObject(i) + ScaleResource resource = new ScaleResource() + resource.setResourceInstanceId(tempResource.getString("resourceInstanceId")) + resource.setScaleType(tempResource.getString("scaleType")) + + JSONObject jsonScaleNsData = tempResource.getJSONObject("scaleNsData") + JSONObject jsonScaleNsByStepData = jsonScaleNsData.getJSONObject("scaleNsByStepsData") + + ScaleNsData scaleNsData = new ScaleNsData() + ScaleNsByStepsData stepsData = new ScaleNsByStepsData() + + stepsData.setAspectId(jsonScaleNsByStepData.getString("aspectId")) + stepsData.setScalingDirection(jsonScaleNsByStepData.getString("scalingDirection")) + stepsData.setNumberOfSteps(Integer.parseInt(jsonScaleNsByStepData.getString("numberOfSteps"))) + + scaleNsData.setScaleNsByStepsData(stepsData) + resource.setScaleNsData(scaleNsData) + list.add(resource) + } + + return list + } + + /** + * Convert a java class to JSON string + * @param obj + * @return + */ + private String objectToJsonStr(Object obj) { + ObjectMapper mapper = new ObjectMapper() + String jsonStr = null + try { + jsonStr = mapper.writeValueAsString(obj) + } catch (IOException ioe) { + System.out.println(ioe.getMessage()) + } + return jsonStr + + } + + /** + * create a NSResourceInputParameter list from a Scale Network request Json string + * @return + */ + private List<NSResourceInputParameter> convertScaleNsReq2NSResInputParamList(DelegateExecution execution) { + String saleNsRequest = execution.getVariable("bpmnRequest") + + //String requestId = execution.getVariable("msoRequestId") + //String serviceInstanceId = execution.getVariable("serviceInstanceId") + String serviceInstanceName = execution.getVariable("serviceInstanceName") + //String nodeTemplateUUID = execution.getVariable("nodeTemplateUUID") + String serviceType = execution.getVariable("serviceType") + String globalSubscriberId = execution.getVariable("globalSubscriberId") + String operationId = execution.getVariable("operationId") + String serviceId = execution.getVariable("serviceId") + String nsServiceDescription = execution.getVariable("requestDescription") + + String resource = JsonUtils.getJsonValue(saleNsRequest, "service.resources") + + // set nsScaleParameters properties + List<ScaleResource> scaleResourcesList = jsonGetNsResourceList(saleNsRequest) + List<NSResourceInputParameter> nsResourceInputParameterList = new ArrayList<NSResourceInputParameter>() + + for (ScaleResource sr : scaleResourcesList) { + NSResourceInputParameter nsResourceInputParameter = new NSResourceInputParameter() + NsOperationKey nsOperationKey = new NsOperationKey() + NsParameters nsParameters = new NsParameters() + NsScaleParameters nsScaleParameters = new NsScaleParameters() + nsParameters.setLocationConstraints(new ArrayList<LocationConstraint>()) + nsParameters.setAdditionalParamForNs(new HashMap<String, Object>()) + + // set NsOperationKey properties + nsOperationKey.setGlobalSubscriberId(globalSubscriberId) + nsOperationKey.setServiceId(serviceId) + nsOperationKey.setServiceType(serviceType) + // for ns scale the resourceInstanceId is the nodeTemplateUUID + nsOperationKey.setNodeTemplateUUID(sr.getResourceInstanceId()) + nsOperationKey.setOperationId(operationId) + + nsScaleParameters.setScaleType(sr.getScaleType()) + nsScaleParameters.setNsInstanceId(sr.getResourceInstanceId()) + + ScaleNsByStepsData scaleNsByStepsData = new ScaleNsByStepsData() + scaleNsByStepsData.setScalingDirection(sr.getScaleNsData().getScaleNsByStepsData().getScalingDirection()) + scaleNsByStepsData.setNumberOfSteps(sr.getScaleNsData().getScaleNsByStepsData().getNumberOfSteps()) + scaleNsByStepsData.setAspectId(sr.getScaleNsData().getScaleNsByStepsData().getAspectId()) + + List<ScaleNsByStepsData> scaleNsByStepsDataList = new ArrayList<ScaleNsByStepsData>() + scaleNsByStepsDataList.add(scaleNsByStepsData) + nsScaleParameters.setScaleNsByStepsData(scaleNsByStepsDataList) + + nsResourceInputParameter.setNsOperationKey(nsOperationKey) + nsResourceInputParameter.setNsServiceName(serviceInstanceName) + nsResourceInputParameter.setNsServiceDescription(nsServiceDescription) + nsResourceInputParameter.setNsParameters(nsParameters) + nsResourceInputParameter.setNsScaleParameters(nsScaleParameters) + + nsResourceInputParameterList.add(nsResourceInputParameter) + } + return nsResourceInputParameterList + } +} + diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateE2EServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateE2EServiceInstance.groovy new file mode 100644 index 0000000000..cb50fbbee6 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateE2EServiceInstance.groovy @@ -0,0 +1,404 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2018 Huawei Technologies Co., Ltd. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.so.bpmn.infrastructure.scripts; + +import static org.apache.commons.lang3.StringUtils.*; + +import org.apache.commons.lang3.* +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.onap.so.bpmn.common.scripts.AaiUtil +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.onap.so.bpmn.common.scripts.ExceptionUtil +import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.so.bpmn.core.RollbackData +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.bpmn.core.domain.Resource +import org.onap.so.bpmn.core.json.JsonUtils +import org.springframework.web.util.UriUtils; + +import groovy.json.* + + +/** + * This groovy class supports the <class>DoUpdateE2EServiceInstance.bpmn</class> process. + * + * Inputs: + * @param - msoRequestId + * @param - globalSubscriberId + * @param - serviceType + * @param - serviceInstanceId + * @param - serviceInstanceName + * @param - serviceModelInfo + * @param - productFamilyId + * @param - uuiRequest + * @param - serviceDecomposition_Target + * @param - serviceDecomposition_Original + * @param - addResourceList + * @param - delResourceList + * + * Outputs: + * @param - rollbackData (localRB->null) + * @param - rolledBack (no localRB->null, localRB F->false, localRB S->true) + * @param - WorkflowException + */ +public class DoUpdateE2EServiceInstance extends AbstractServiceTaskProcessor { + + String Prefix="DUPDSI_" + private static final String DebugFlag = "isDebugEnabled" + + ExceptionUtil exceptionUtil = new ExceptionUtil() + JsonUtils jsonUtil = new JsonUtils() + + public void preProcessRequest (DelegateExecution execution) { + def isDebugEnabled = execution.getVariable("isDebugLogEnabled") + utils.log("INFO"," ***** Enter DoUpdateE2EServiceInstance preProcessRequest *****", isDebugEnabled) + + String msg = "" + + try { + execution.setVariable("prefix", Prefix) + //Inputs + //for AAI GET & PUT & SDNC assignToplology + String globalSubscriberId = execution.getVariable("globalSubscriberId") //globalCustomerId + utils.log("INFO"," ***** globalSubscriberId *****" + globalSubscriberId, isDebugEnabled) + + //for AAI PUT & SDNC assignTopology + String serviceType = execution.getVariable("serviceType") + utils.log("INFO"," ***** serviceType *****" + serviceType, isDebugEnabled) + + //for SDNC assignTopology + String productFamilyId = execution.getVariable("productFamilyId") //AAI productFamilyId + + if (isBlank(globalSubscriberId)) { + msg = "Input globalSubscriberId is null" + utils.log("INFO", msg, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + + if (isBlank(serviceType)) { + msg = "Input serviceType is null" + utils.log("INFO", msg, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + + //Generated in parent for AAI + String serviceInstanceId = execution.getVariable("serviceInstanceId") + if (isBlank(serviceInstanceId)){ + msg = "Input serviceInstanceId is null" + utils.log("INFO", msg, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + + String serviceInstanceName = execution.getVariable("serviceInstanceName") + + // user params + String uuiRequest = execution.getVariable("uuiRequest") + + // target model Invariant uuid + String modelInvariantUuid = jsonUtil.getJsonValue(uuiRequest, "service.serviceInvariantUuid") + execution.setVariable("modelInvariantUuid", modelInvariantUuid) + utils.log("INFO", "modelInvariantUuid: " + modelInvariantUuid, isDebugEnabled) + + // target model uuid + String modelUuid = jsonUtil.getJsonValue(uuiRequest, "service.serviceUuid") + execution.setVariable("modelUuid", modelUuid) + + utils.log("INFO","modelUuid: " + modelUuid, isDebugEnabled) + + } catch (BpmnError e) { + throw e; + } catch (Exception ex){ + msg = "Exception in preProcessRequest " + ex.getMessage() + utils.log("INFO", msg, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + utils.log("INFO", "======== COMPLETED preProcessRequest Process ======== ", isDebugEnabled) + } + + + public void preInitResourcesOperStatus(DelegateExecution execution){ + def isDebugEnabled = execution.getVariable("isDebugLogEnabled") + + utils.log("INFO", " ======== STARTED preInitResourcesOperStatus Process ======== ", isDebugEnabled) + try{ + String serviceId = execution.getVariable("serviceInstanceId") + String operationId = execution.getVariable("operationId") + String operationType = execution.getVariable("operationType") + String resourceTemplateUUIDs = "" + String result = "processing" + String progress = "0" + String reason = "" + String operationContent = "Prepare service updating" + utils.log("INFO", "Generated new operation for Service Instance serviceId:" + serviceId + " operationId:" + operationId + " operationType:" + operationType, isDebugEnabled) + serviceId = UriUtils.encode(serviceId,"UTF-8") + execution.setVariable("serviceInstanceId", serviceId) + execution.setVariable("operationId", operationId) + execution.setVariable("operationType", operationType) + + List<Resource> resourceList = new ArrayList<String>() + List<Resource> addResourceList = execution.getVariable("addResourceList") + List<Resource> delResourceList = execution.getVariable("delResourceList") + resourceList.addAll(addResourceList) + resourceList.addAll(delResourceList) + for(Resource resource : resourceList){ + resourceTemplateUUIDs = resourceTemplateUUIDs + resource.getModelInfo().getModelCustomizationUuid() + ":" + } + + def dbAdapterEndpoint = "http://mso.mso.testlab.openecomp.org:8080/dbadapters/RequestsDbAdapter" + execution.setVariable("CVFMI_dbAdapterEndpoint", dbAdapterEndpoint) + utils.log("INFO", "DB Adapter Endpoint is: " + dbAdapterEndpoint, isDebugEnabled) + + String payload = + """<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" + xmlns:ns="http://org.onap.so/requestsdb"> + <soapenv:Header/> + <soapenv:Body> + <ns:initResourceOperationStatus xmlns:ns="http://org.onap.so/requestsdb"> + <serviceId>${MsoUtils.xmlEscape(serviceId)}</serviceId> + <operationId>${MsoUtils.xmlEscape(operationId)}</operationId> + <operationType>${MsoUtils.xmlEscape(operationType)}</operationType> + <resourceTemplateUUIDs>${MsoUtils.xmlEscape(resourceTemplateUUIDs)}</resourceTemplateUUIDs> + </ns:initResourceOperationStatus> + </soapenv:Body> + </soapenv:Envelope>""" + + payload = utils.formatXml(payload) + execution.setVariable("CVFMI_initResOperStatusRequest", payload) + utils.log("INFO", "Outgoing initResourceOperationStatus: \n" + payload, isDebugEnabled) + utils.logAudit("CreateVfModuleInfra Outgoing initResourceOperationStatus Request: " + payload) + + }catch(Exception e){ + utils.log("ERROR", "Exception Occured Processing preInitResourcesOperStatus. Exception is:\n" + e, isDebugEnabled) + execution.setVariable("CVFMI_ErrorResponse", "Error Occurred during preInitResourcesOperStatus Method:\n" + e.getMessage()) + } + utils.log("INFO", "======== COMPLETED preInitResourcesOperStatus Process ======== ", isDebugEnabled) + } + + + public void preProcessForAddResource(DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + utils.log("INFO"," ***** preProcessForAddResource ***** ", isDebugEnabled) + + execution.setVariable("operationType", "create") + + execution.setVariable("hasResourcetoAdd", false) + List<Resource> addResourceList = execution.getVariable("addResourceList") + if(addResourceList != null && !addResourceList.isEmpty()) { + execution.setVariable("hasResourcetoAdd", true) + } + + utils.log("INFO"," *** Exit preProcessForAddResource *** ", isDebugEnabled) + } + + public void postProcessForAddResource(DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + utils.log("INFO"," ***** postProcessForAddResource ***** ", isDebugEnabled) + + execution.setVariable("operationType", "update") + + utils.log("INFO"," *** Exit postProcessForAddResource *** ", isDebugEnabled) + } + + public void preProcessForDeleteResource(DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + utils.log("INFO"," ***** preProcessForDeleteResource ***** ", isDebugEnabled) + + execution.setVariable("operationType", "delete") + + def hasResourcetoDelete = false + List<Resource> delResourceList = execution.getVariable("delResourceList") + if(delResourceList != null && !delResourceList.isEmpty()) { + hasResourcetoDelete = true + } + execution.setVariable("hasResourcetoDelete", hasResourcetoDelete) + + if(hasResourcetoDelete) { + def jsonSlurper = new JsonSlurper() + String serviceRelationShip = execution.getVariable("serviceRelationShip") + List relationShipList = jsonSlurper.parseText(serviceRelationShip) + + //Set the real resource instance id to the decomosed resource list + for(Resource resource: delResourceList){ + //reset the resource instance id , because in the decompose flow ,its a random one. + resource.setResourceId(""); + //match the resource-instance-name and the model name + if (relationShipList != null) { + relationShipList.each { + if(StringUtils.containsIgnoreCase(it.resourceType, resource.getModelInfo().getModelName())){ + resource.setResourceId(it.resourceInstanceId); + } + } + } + } + } + + execution.setVariable("deleteResourceList", delResourceList) + + utils.log("INFO"," *** Exit preProcessForDeleteResource *** ", isDebugEnabled) + } + + public void postProcessForDeleteResource(DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + utils.log("INFO"," ***** postProcessForDeleteResource ***** ", isDebugEnabled) + + execution.setVariable("operationType", "update") + + utils.log("INFO"," *** Exit postProcessForDeleteResource *** ", isDebugEnabled) + } + + public void preProcessAAIPUT(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.preProcessRequest(' +'execution=' + execution.getId() +')' + def isDebugEnabled = execution.getVariable("isDebugLogEnabled") + utils.log("INFO","Entered " + method, isDebugEnabled) + String msg = "" + utils.log("INFO"," ***** preProcessAAIPUT *****", isDebugEnabled) + + + String serviceInstanceVersion = execution.getVariable("serviceInstanceVersion") + //execution.setVariable("GENPS_serviceResourceVersion", serviceInstanceVersion) + + //requestDetails.modelInfo.for AAI PUT servieInstanceData + //requestDetails.requestInfo. for AAI GET/PUT serviceInstanceData + String serviceInstanceName = execution.getVariable("serviceInstanceName") + String serviceInstanceId = execution.getVariable("serviceInstanceId") + //aai serviceType and Role can be setted as fixed value now. + String aaiServiceType = "E2E Service" + String aaiServiceRole = "E2E Service" + String modelInvariantUuid = execution.getVariable("modelInvariantUuid") + String modelUuid = execution.getVariable("modelUuid") + + + AaiUtil aaiUriUtil = new AaiUtil(this) + utils.log("INFO","start create aai uri: " + aaiUriUtil, isDebugEnabled) + String aai_uri = aaiUriUtil.getBusinessCustomerUri(execution) + utils.log("INFO","aai_uri: " + aai_uri, isDebugEnabled) + String namespace = aaiUriUtil.getNamespaceFromUri(aai_uri) + utils.log("INFO","namespace: " + namespace, isDebugEnabled) + + //update target model to aai + String serviceInstanceData = + """<service-instance xmlns=\"${namespace}\"> + <service-instance-id>${MsoUtils.xmlEscape(serviceInstanceId)}</service-instance-id> + <service-instance-name>${MsoUtils.xmlEscape(serviceInstanceName)}</service-instance-name> + <service-type>${MsoUtils.xmlEscape(aaiServiceType)}</service-type> + <service-role>${MsoUtils.xmlEscape(aaiServiceRole)}</service-role> + <resource-version>${MsoUtils.xmlEscape(serviceInstanceVersion)}</resource-version> + <model-invariant-id>${MsoUtils.xmlEscape(modelInvariantUuid)}</model-invariant-id> + <model-version-id>${MsoUtils.xmlEscape(modelUuid)}</model-version-id> + </service-instance>""".trim() + + execution.setVariable("serviceInstanceData", serviceInstanceData) + utils.log("INFO","serviceInstanceData: " + serviceInstanceData, isDebugEnabled) + utils.logAudit(serviceInstanceData) + utils.log("INFO", " aai_uri " + aai_uri + " namespace:" + namespace, isDebugEnabled) + utils.log("INFO", " 'payload' to update Service Instance in AAI - " + "\n" + serviceInstanceData, isDebugEnabled) + + utils.log("INFO", "Exited " + method, isDebugEnabled) + } + + public void postProcessAAIPUT(DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + utils.log("INFO"," ***** postProcessAAIPUT ***** ", isDebugEnabled) + String msg = "" + try { + String serviceInstanceId = execution.getVariable("serviceInstanceId") + boolean succInAAI = execution.getVariable("GENPS_SuccessIndicator") + if(!succInAAI){ + utils.log("INFO","Error putting Service-instance in AAI", + serviceInstanceId, isDebugEnabled) + WorkflowException workflowException = execution.getVariable("WorkflowException") + utils.logAudit("workflowException: " + workflowException) + if(workflowException != null){ + exceptionUtil.buildAndThrowWorkflowException(execution, workflowException.getErrorCode(), workflowException.getErrorMessage()) + } + } + else + { + //start rollback set up + RollbackData rollbackData = new RollbackData() + def disableRollback = execution.getVariable("disableRollback") + rollbackData.put("SERVICEINSTANCE", "disableRollback", disableRollback.toString()) + rollbackData.put("SERVICEINSTANCE", "rollbackAAI", "true") + rollbackData.put("SERVICEINSTANCE", "serviceInstanceId", serviceInstanceId) + rollbackData.put("SERVICEINSTANCE", "serviceType", execution.getVariable("serviceType")) + rollbackData.put("SERVICEINSTANCE", "globalSubscriberId", execution.getVariable("globalSubscriberId")) + execution.setVariable("rollbackData", rollbackData) + } + + } catch (BpmnError e) { + throw e; + } catch (Exception ex) { + msg = "Exception in DoCreateServiceInstance.postProcessAAIDEL. " + ex.getMessage() + utils.log("INFO", msg, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + utils.log("INFO"," *** Exit postProcessAAIPUT *** ", isDebugEnabled) + } + + public void preProcessRollback (DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + utils.log("INFO"," ***** preProcessRollback ***** ", isDebugEnabled) + try { + + Object workflowException = execution.getVariable("WorkflowException"); + + if (workflowException instanceof WorkflowException) { + utils.log("INFO", "Prev workflowException: " + workflowException.getErrorMessage(), isDebugEnabled) + execution.setVariable("prevWorkflowException", workflowException); + //execution.setVariable("WorkflowException", null); + } + } catch (BpmnError e) { + utils.log("INFO", "BPMN Error during preProcessRollback", isDebugEnabled) + } catch(Exception ex) { + String msg = "Exception in preProcessRollback. " + ex.getMessage() + utils.log("INFO", msg, isDebugEnabled) + } + utils.log("INFO"," *** Exit preProcessRollback *** ", isDebugEnabled) + } + + public void postProcessRollback (DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + utils.log("INFO"," ***** postProcessRollback ***** ", isDebugEnabled) + String msg = "" + try { + Object workflowException = execution.getVariable("prevWorkflowException"); + if (workflowException instanceof WorkflowException) { + utils.log("INFO", "Setting prevException to WorkflowException: ", isDebugEnabled) + execution.setVariable("WorkflowException", workflowException); + } + execution.setVariable("rollbackData", null) + } catch (BpmnError b) { + utils.log("INFO", "BPMN Error during postProcessRollback", isDebugEnabled) + throw b; + } catch(Exception ex) { + msg = "Exception in postProcessRollback. " + ex.getMessage() + utils.log("INFO", msg, isDebugEnabled) + } + utils.log("INFO"," *** Exit postProcessRollback *** ", isDebugEnabled) + } + + + public void postConfigRequest(execution){ + //now do noting + } + + +} + diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateE2EServiceInstanceRollback.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateE2EServiceInstanceRollback.groovy new file mode 100644 index 0000000000..257142e8bd --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateE2EServiceInstanceRollback.groovy @@ -0,0 +1,300 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2018 Huawei Technologies Co., Ltd. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.so.bpmn.infrastructure.scripts + + +import static org.apache.commons.lang3.StringUtils.*; + +import org.apache.commons.lang3.* +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.logger.MsoLogger +import org.onap.so.bpmn.common.scripts.ExceptionUtil; +import groovy.json.* +import org.onap.so.bpmn.common.scripts.AaiUtil; + +/** + * This groovy class supports the <class>DoUpdateE2EServiceInstanceRollback.bpmn</class> process. + * + * Inputs: + * @param - msoRequestId + * @param - rollbackData with + * globalCustomerId + * subscriptionServiceType + * serviceInstanceId + * disableRollback + * rollbackAAI + * rollbackAdded + * rollbackDeleted + * + * + * Outputs: + * @param - rollbackError + * @param - rolledBack (no localRB->null, localRB F->false, localRB S->true) + * + */ +public class DoUpdateE2EServiceInstanceRollback extends AbstractServiceTaskProcessor{ + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoUpdateE2EServiceInstanceRollback.class); + + + String Prefix="DUPDSIRB_" + ExceptionUtil exceptionUtil = new ExceptionUtil() + + public void preProcessRequest(DelegateExecution execution) { + execution.setVariable("prefix",Prefix) + String msg = "" + msoLogger.trace("preProcessRequest ") + execution.setVariable("rollbackAAI",false) + execution.setVariable("rollbackAdded",false) + execution.setVariable("rollbackDeleted",false) + + List addResourceList = execution.getVariable("addResourceList") + List delResourceList = execution.getVariable("delResourceList") + execution.setVariable("addResourceList_o", addResourceList) + execution.setVariable("delResourceList_o", delResourceList) + //exchange add and delete resource list + execution.setVariable("addResourceList", delResourceList) + execution.setVariable("delResourceList", addResourceList) + + try { + def rollbackData = execution.getVariable("rollbackData") + msoLogger.debug("RollbackData:" + rollbackData) + + if (rollbackData != null) { + if (rollbackData.hasType("SERVICEINSTANCE")) { + + def serviceInstanceId = rollbackData.get("SERVICEINSTANCE", "serviceInstanceId") + execution.setVariable("serviceInstanceId", serviceInstanceId) + + def subscriptionServiceType = rollbackData.get("SERVICEINSTANCE", "subscriptionServiceType") + execution.setVariable("subscriptionServiceType", subscriptionServiceType) + + def globalSubscriberId = rollbackData.get("SERVICEINSTANCE", "globalSubscriberId") + execution.setVariable("globalSubscriberId", globalSubscriberId) + + def rollbackAAI = rollbackData.get("SERVICEINSTANCE", "rollbackAAI") + if ("true".equals(rollbackAAI)) + { + execution.setVariable("rollbackAAI",true) + } + + def rollbackAdded = rollbackData.get("SERVICEINSTANCE", "rollbackAdded") + if ("true".equals(rollbackAdded)) + { + execution.setVariable("rollbackAdded", true) + } + + def rollbackDeleted = rollbackData.get("SERVICEINSTANCE", "rollbackDeleted") + if ("true".equals(rollbackDeleted)) + { + execution.setVariable("rollbackDeleted", true) + } + + if (execution.getVariable("rollbackAAI") != true && execution.getVariable("rollbackAdded") != true + && execution.getVariable("rollbackDeleted") != true) + { + execution.setVariable("skipRollback", true) + } + + } + else { + execution.setVariable("skipRollback", true) + } + } + else { + execution.setVariable("skipRollback", true) + } + if (execution.getVariable("disableRollback").equals("true" )) + { + execution.setVariable("skipRollback", true) + } + + } catch (BpmnError e) { + throw e; + } catch (Exception ex){ + msg = "Exception in Update ServiceInstance Rollback preProcessRequest " + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.trace("Exit preProcessRequest ") + } + + public void postProcessRequest(DelegateExecution execution) { + msoLogger.trace("postProcessRequest ") + String msg = "" + try { + execution.setVariable("rollbackData", null) + String serviceInstanceId = execution.getVariable("serviceInstanceId") + boolean rollbackAAI = execution.getVariable("rollbackAAI") + boolean rollbackAdded = execution.getVariable("rollbackAdded") + boolean rollbackDeleted = execution.getVariable("rollbackDeleted") + + List addResourceList = execution.getVariable("addResourceList_o") + List delResourceList = execution.getVariable("delResourceList_o") + execution.setVariable("addResourceList", addResourceList) + execution.setVariable("delResourceList", delResourceList) + + if (rollbackAAI || rollbackAdded || rollbackDeleted) + { + execution.setVariable("rolledBack", true) + } + if (rollbackAAI) + { + boolean succInAAI = execution.getVariable("GENDS_SuccessIndicator") + if(!succInAAI){ + execution.setVariable("rolledBack", false) //both sdnc and aai must be successful to declare rollback Succesful + execution.setVariable("rollbackError", "Error deleting service-instance in AAI for rollback") + msoLogger.debug("Error deleting service-instance in AAI for rollback", + serviceInstanceId) + } + } + msoLogger.trace("Exit postProcessRequest ") + + } catch (BpmnError e) { + msg = "Exception in Create ServiceInstance Rollback postProcessRequest. " + e.getMessage() + msoLogger.debug(msg) + } catch (Exception ex) { + msg = "Exception in Create ServiceInstance Rollback postProcessRequest. " + ex.getMessage() + msoLogger.debug(msg) + } + } + + + public void preProcessForAddResource(DelegateExecution execution) { + } + + public void postProcessForAddResource(DelegateExecution execution) { + } + + public void preProcessForDeleteResource(DelegateExecution execution) { + } + + public void postProcessForDeleteResource(DelegateExecution execution) { + } + + public void preProcessAAIPUT(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.preProcessRequest(' +'execution=' + execution.getId() +')' + msoLogger.info("Entered " + method) + String msg = "" + msoLogger.trace("preProcessAAIPUT ") + + String serviceInstanceVersion = execution.getVariable("serviceInstanceVersion_n") +// execution.setVariable("GENPS_serviceResourceVersion", serviceInstanceVersion) + + //requestDetails.modelInfo.for AAI PUT servieInstanceData + //requestDetails.requestInfo. for AAI GET/PUT serviceInstanceData + String serviceInstanceName = execution.getVariable("serviceInstanceName") + String serviceInstanceId = execution.getVariable("serviceInstanceId") + //aai serviceType and Role can be setted as fixed value now. + String aaiServiceType = "E2E Service" + String aaiServiceRole = "E2E Service" + String modelInvariantUuid = execution.getVariable("modelInvariantUuid") + String modelUuid = execution.getVariable("model-version-id-original") + + //AAI PUT + AaiUtil aaiUriUtil = new AaiUtil(this) + utils.log("INFO","start create aai uri: " + aaiUriUtil, isDebugEnabled) + String aai_uri = aaiUriUtil.getBusinessCustomerUri(execution) + utils.log("INFO","aai_uri: " + aai_uri, isDebugEnabled) + String namespace = aaiUriUtil.getNamespaceFromUri(aai_uri) + utils.log("INFO","namespace: " + namespace, isDebugEnabled) + + String serviceInstanceData = + """<service-instance xmlns=\"${namespace}\"> + <service-instance-id>${MsoUtils.xmlEscape(serviceInstanceId)}</service-instance-id> + <service-instance-name>${MsoUtils.xmlEscape(serviceInstanceName)}</service-instance-name> + <service-type>${MsoUtils.xmlEscape(aaiServiceType)}</service-type> + <service-role>${MsoUtils.xmlEscape(aaiServiceRole)}</service-role> + <resource-version>${MsoUtils.xmlEscape(serviceInstanceVersion)}</resource-version> + <model-invariant-id>${MsoUtils.xmlEscape(modelInvariantUuid)}</model-invariant-id> + <model-version-id>${MsoUtils.xmlEscape(modelUuid)}</model-version-id> + </service-instance>""".trim() + + execution.setVariable("serviceInstanceData", serviceInstanceData) + msoLogger.info("serviceInstanceData: " + serviceInstanceData) + msoLogger.debug(serviceInstanceData) + msoLogger.info(" aai_uri " + aai_uri + " namespace:" + namespace) + msoLogger.info(" 'payload' to update Service Instance in AAI - " + "\n" + serviceInstanceData) + + msoLogger.info("Exited " + method) + } + + public void postProcessAAIPUT(DelegateExecution execution) { + msoLogger.trace("postProcessAAIPUT ") + String msg = "" + try { + String serviceInstanceId = execution.getVariable("serviceInstanceId") + boolean succInAAI = execution.getVariable("GENPS_SuccessIndicator") + if(!succInAAI){ + msoLogger.info("Error putting Service-instance in AAI", + serviceInstanceId) + WorkflowException workflowException = execution.getVariable("WorkflowException") + msoLogger.debug("workflowException: " + workflowException) + if(workflowException != null){ + exceptionUtil.buildAndThrowWorkflowException(execution, workflowException.getErrorCode(), workflowException.getErrorMessage()) + } + } + else + { + + } + + } catch (BpmnError e) { + throw e; + } catch (Exception ex) { + msg = "Exception in DoCreateServiceInstance.postProcessAAIDEL. " + ex.getMessage() + msoLogger.info(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.trace("Exit postProcessAAIPUT ") + } + + public void processRollbackException(DelegateExecution execution){ + msoLogger.trace("processRollbackException ") + try{ + msoLogger.debug("Caught an Exception in DoUpdateE2EServiceInstanceRollback") + execution.setVariable("rollbackData", null) + execution.setVariable("rollbackError", "Caught exception in ServiceInstance Update Rollback") + execution.setVariable("WorkflowException", null) + + }catch(BpmnError b){ + msoLogger.debug("BPMN Error during processRollbackExceptions Method: ") + }catch(Exception e){ + msoLogger.debug("Caught Exception during processRollbackExceptions Method: " + e.getMessage()) + } + + msoLogger.debug(" Exit processRollbackException") + } + + public void processRollbackJavaException(DelegateExecution execution){ + msoLogger.trace("processRollbackJavaException ") + try{ + execution.setVariable("rollbackData", null) + execution.setVariable("rollbackError", "Caught Java exception in ServiceInstance Update Rollback") + msoLogger.debug("Caught Exception in processRollbackJavaException") + + }catch(Exception e){ + msoLogger.debug("Caught Exception in processRollbackJavaException " + e.getMessage()) + } + msoLogger.trace("Exit processRollbackJavaException ") + } + +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateNetworkInstance.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateNetworkInstance.groovy new file mode 100644 index 0000000000..4f6fbf9966 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateNetworkInstance.groovy @@ -0,0 +1,1440 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts; + +import org.apache.commons.lang3.* +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.onap.so.bpmn.common.scripts.AaiUtil +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.onap.so.bpmn.common.scripts.ExceptionUtil +import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.so.bpmn.common.scripts.NetworkUtils +import org.onap.so.bpmn.common.scripts.SDNCAdapterUtils +import org.onap.so.bpmn.common.scripts.VidUtils +import org.onap.so.bpmn.core.UrnPropertiesReader +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.logger.MsoLogger +import org.onap.so.rest.APIResponse +import org.springframework.web.util.UriUtils + +import org.onap.so.client.aai.AAIResourcesClient +import org.onap.so.client.aai.AAIObjectType +import org.onap.so.client.aai.entities.AAIResultWrapper +import org.onap.so.client.aai.entities.Relationships +import org.onap.so.client.aai.entities.uri.AAIResourceUri +import org.onap.so.client.aai.entities.uri.AAIUriFactory +import org.json.JSONObject +import javax.ws.rs.NotFoundException + +import groovy.json.* +import groovy.xml.XmlUtil + +/** + * This groovy class supports the <class>DoUpdateNetworkInstance.bpmn</class> process. + * + */ +public class DoUpdateNetworkInstance extends AbstractServiceTaskProcessor { + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoUpdateNetworkInstance.class); + + String Prefix="UPDNETI_" + ExceptionUtil exceptionUtil = new ExceptionUtil() + JsonUtils jsonUtil = new JsonUtils() + VidUtils vidUtils = new VidUtils(this) + NetworkUtils networkUtils = new NetworkUtils() + SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils() + + /** + * This method is executed during the preProcessRequest task of the <class>DoUpdateNetworkInstance.bpmn</class> process. + * @param execution + */ + public InitializeProcessVariables(DelegateExecution execution){ + /* Initialize all the process variables in this block */ + + execution.setVariable(Prefix + "messageId", "") + execution.setVariable("BasicAuthHeaderValuePO", "") + execution.setVariable("BasicAuthHeaderValueSDNC", "") + execution.setVariable(Prefix + "networkRequest", "") + execution.setVariable(Prefix + "networkInputs", "") + execution.setVariable(Prefix + "networkOutputs", "") + execution.setVariable(Prefix + "requestId", "") + execution.setVariable(Prefix + "source", "") + execution.setVariable(Prefix + "networkId", "") + + execution.setVariable(Prefix + "isPONR", false) // Point-of-no-return, means, rollback is not needed + + // AAI query Cloud Region + execution.setVariable(Prefix + "queryCloudRegionRequest","") + execution.setVariable(Prefix + "queryCloudRegionReturnCode","") + execution.setVariable(Prefix + "queryCloudRegionResponse","") + execution.setVariable(Prefix + "cloudRegionPo","") + execution.setVariable(Prefix + "cloudRegionSdnc","") + execution.setVariable(Prefix + "isCloudRegionGood", false) + + // AAI query Id + execution.setVariable(Prefix + "queryIdAAIRequest","") + execution.setVariable(Prefix + "queryIdAAIResponse", "") + execution.setVariable(Prefix + "aaiIdReturnCode", "") + + // AAI query vpn binding + execution.setVariable(Prefix + "queryVpnBindingAAIRequest","") + execution.setVariable(Prefix + "queryVpnBindingAAIResponse", "") + execution.setVariable(Prefix + "aaiQqueryVpnBindingReturnCode", "") + execution.setVariable(Prefix + "vpnBindings", null) + execution.setVariable(Prefix + "vpnCount", 0) + execution.setVariable(Prefix + "routeCollection", "") + + // AAI query network policy + execution.setVariable(Prefix + "queryNetworkPolicyAAIRequest","") + execution.setVariable(Prefix + "queryNetworkPolicyAAIResponse", "") + execution.setVariable(Prefix + "aaiQqueryNetworkPolicyReturnCode", "") + execution.setVariable(Prefix + "networkPolicyUriList", null) + execution.setVariable(Prefix + "networkPolicyCount", 0) + execution.setVariable(Prefix + "networkCollection", "") + + // AAI query route table reference + execution.setVariable(Prefix + "queryNetworkTableRefAAIRequest","") + execution.setVariable(Prefix + "queryNetworkTableRefAAIResponse", "") + execution.setVariable(Prefix + "aaiQqueryNetworkTableRefReturnCode", "") + execution.setVariable(Prefix + "networkTableRefUriList", null) + execution.setVariable(Prefix + "networkTableRefCount", 0) + execution.setVariable(Prefix + "tableRefCollection", "") + + // AAI requery Id + execution.setVariable(Prefix + "requeryIdAAIRequest","") + execution.setVariable(Prefix + "requeryIdAAIResponse", "") + execution.setVariable(Prefix + "aaiRequeryIdReturnCode", "") + + // AAI update contrail + execution.setVariable(Prefix + "updateContrailAAIUrlRequest","") + execution.setVariable(Prefix + "updateContrailAAIPayloadRequest","") + execution.setVariable(Prefix + "updateContrailAAIResponse", "") + execution.setVariable(Prefix + "aaiUpdateContrailReturnCode", "") + + execution.setVariable(Prefix + "updateNetworkRequest", "") + execution.setVariable(Prefix + "updateNetworkResponse", "") + execution.setVariable(Prefix + "rollbackNetworkRequest", "") + execution.setVariable(Prefix + "networkReturnCode", "") + execution.setVariable(Prefix + "isNetworkRollbackNeeded", false) + + execution.setVariable(Prefix + "changeAssignSDNCRequest", "") + execution.setVariable(Prefix + "changeAssignSDNCResponse", "") + execution.setVariable(Prefix + "rollbackSDNCRequest", "") + execution.setVariable(Prefix + "sdncReturnCode", "") + execution.setVariable(Prefix + "isSdncRollbackNeeded", false) + execution.setVariable(Prefix + "sdncResponseSuccess", false) + + execution.setVariable(Prefix + "isVnfBindingPresent", false) + execution.setVariable(Prefix + "Success", false) + execution.setVariable(Prefix + "serviceInstanceId", "") + + execution.setVariable(Prefix + "isException", false) + + } + + // ************************************************** + // Pre or Prepare Request Section + // ************************************************** + /** + * This method is executed during the preProcessRequest task of the <class>DoUpdateNetworkInstance.bpmn</class> process. + * @param execution + */ + public void preProcessRequest (DelegateExecution execution) { + + execution.setVariable("prefix",Prefix) + + msoLogger.trace("Inside preProcessRequest DoUpdateNetworkInstance Request ") + + try { + // initialize flow variables + InitializeProcessVariables(execution) + + // GET Incoming request & validate 3 kinds of format. + execution.setVariable("action", "UPDATE") + String networkRequest = execution.getVariable("bpmnRequest") + if (networkRequest != null) { + if (networkRequest.contains("requestDetails")) { + // JSON format request is sent, create xml + try { + def prettyJson = JsonOutput.prettyPrint(networkRequest.toString()) + msoLogger.debug(" Incoming message formatted . . . : " + '\n' + prettyJson) + networkRequest = vidUtils.createXmlNetworkRequestInfra(execution, networkRequest) + + } catch (Exception ex) { + String dataErrorMessage = " Invalid json format Request - " + ex.getMessage() + msoLogger.debug(dataErrorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + } + } else { + // XML format request is sent + + } + } else { + // vIPR format request is sent, create xml from individual variables + networkRequest = vidUtils.createXmlNetworkRequestInstance(execution) + } + + networkRequest = utils.formatXml(networkRequest) + msoLogger.debug(networkRequest) + execution.setVariable(Prefix + "networkRequest", networkRequest) + msoLogger.debug(" network-request - " + '\n' + networkRequest) + + // validate 'disableRollback' (aka, 'suppressRollback') + boolean rollbackEnabled = networkUtils.isRollbackEnabled(execution, networkRequest) + execution.setVariable(Prefix + "rollbackEnabled", rollbackEnabled) + msoLogger.debug(Prefix + "rollbackEnabled - " + rollbackEnabled) + + String networkInputs = utils.getNodeXml(networkRequest, "network-inputs", false).replace("tag0:","").replace(":tag0","") + execution.setVariable(Prefix + "networkInputs", networkInputs) + msoLogger.debug(Prefix + "networkInputs - " + '\n' + networkInputs) + + // prepare messageId + String messageId = execution.getVariable(Prefix + "messageId") // for testing + if (messageId == null || messageId == "") { + messageId = UUID.randomUUID() + msoLogger.debug(" UPDNETI_messageId, random generated: " + messageId) + } else { + msoLogger.debug(" UPDNETI_messageId, pre-assigned: " + messageId) + } + execution.setVariable(Prefix + "messageId", messageId) + + String source = utils.getNodeText(networkRequest, "source") + execution.setVariable(Prefix + "source", source) + msoLogger.debug(Prefix + "source - " + source) + + String networkId = "" + if (utils.nodeExists(networkRequest, "network-id")) { + networkId = utils.getNodeText(networkRequest, "network-id") + if (networkId == 'null' || networkId == "") { + sendSyncError(execution) + // missing value of networkId + String dataErrorMessage = "Variable 'network-id' value/element is missing." + msoLogger.debug(" Invalid Request - " + dataErrorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + + } + } + + String lcpCloudRegion = "" + if (utils.nodeExists(networkRequest, "aic-cloud-region")) { + lcpCloudRegion = utils.getNodeText(networkRequest, "aic-cloud-region") + if ((lcpCloudRegion == 'null') || (lcpCloudRegion == "")) { + sendSyncError(execution) + String dataErrorMessage = "requestDetails has missing 'aic-cloud-region' value/element." + msoLogger.debug(" Invalid Request - " + dataErrorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + } + } + + String serviceInstanceId = "" + if (utils.nodeExists(networkRequest, "service-instance-id")) { + serviceInstanceId = utils.getNodeText(networkRequest, "service-instance-id") + if ((serviceInstanceId == 'null') || (lcpCloudRegion == "")) { + sendSyncError(execution) + String dataErrorMessage = "Variable 'serviceInstanceId' value/element is missing." + msoLogger.debug(" Invalid Request - " + dataErrorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + } + } + + // PO Authorization Info / headers Authorization= + String basicAuthValuePO = UrnPropertiesReader.getVariable("mso.adapters.po.auth",execution) + + + try { + def encodedString = utils.getBasicAuth(basicAuthValuePO, UrnPropertiesReader.getVariable("mso.msoKey", execution)) + execution.setVariable("BasicAuthHeaderValuePO",encodedString) + execution.setVariable("BasicAuthHeaderValueSDNC", encodedString) + + } catch (IOException ex) { + String exceptionMessage = "Exception Encountered in DoUpdateNetworkInstance, PreProcessRequest() - " + String dataErrorMessage = exceptionMessage + " Unable to encode PO/SDNC user/password string - " + ex.getMessage() + msoLogger.debug(dataErrorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + } + + // Set variables for Generic Get Sub Flow use + execution.setVariable(Prefix + "serviceInstanceId", serviceInstanceId) + msoLogger.debug(Prefix + "serviceInstanceId - " + serviceInstanceId) + + msoLogger.debug(" Url for SDNC adapter: " + UrnPropertiesReader.getVariable("mso.adapters.sdnc.endpoint",execution)) + + String sdncVersion = execution.getVariable("sdncVersion") + msoLogger.debug("sdncVersion? : " + sdncVersion) + + // build 'networkOutputs' + networkId = utils.getNodeText(networkRequest, "network-id") + if ((networkId == null) || (networkId == "null")) { + networkId = "" + } + String networkName = utils.getNodeText(networkRequest, "network-name") + if ((networkName == null) || (networkName == "null")) { + networkName = "" + } + String networkOutputs = + """<network-outputs> + <network-id>${MsoUtils.xmlEscape(networkId)}</network-id> + <network-name>${MsoUtils.xmlEscape(networkName)}</network-name> + </network-outputs>""" + execution.setVariable(Prefix + "networkOutputs", networkOutputs) + msoLogger.debug(Prefix + "networkOutputs - " + '\n' + networkOutputs) + execution.setVariable(Prefix + "networkId", networkId) + execution.setVariable(Prefix + "networkName", networkName) + + + } catch (BpmnError e) { + throw e; + + } catch (Exception ex){ + sendSyncError(execution) + // caught exception + String exceptionMessage = "Exception Encountered in DoUpdateNetworkInstance, PreProcessRequest() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + } + + /** + * Gets the service instance uri from aai + * + */ + public void getServiceInstance(DelegateExecution execution) { + msoLogger.trace("getServiceInstance ") + try { + String serviceInstanceId = execution.getVariable('serviceInstanceId') + + AAIResourcesClient resourceClient = new AAIResourcesClient() + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, serviceInstanceId) + + if(!resourceClient.exists(uri)){ + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, "Service Instance not found in aai") + } + + }catch(BpmnError e) { + throw e; + }catch (Exception ex){ + String msg = "Exception in getServiceInstance. " + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + } + + public void callRESTQueryAAICloudRegion (DelegateExecution execution) { + + execution.setVariable("prefix", Prefix) + + msoLogger.debug(" ***** Inside callRESTQueryAAICloudRegion of DoUpdateNetworkInstance ***** " ) + + try { + String networkInputs = execution.getVariable(Prefix + "networkInputs") + String cloudRegion = utils.getNodeText(networkInputs, "aic-cloud-region") + cloudRegion = UriUtils.encode(cloudRegion,"UTF-8") + + // Prepare AA&I url + String aai_endpoint = UrnPropertiesReader.getVariable("aai.endpoint", execution) + AaiUtil aaiUtil = new AaiUtil(this) + String aai_uri = aaiUtil.getCloudInfrastructureCloudRegionUri(execution) + String queryCloudRegionRequest = "${aai_endpoint}${aai_uri}/" + cloudRegion + msoLogger.debug(queryCloudRegionRequest) + execution.setVariable(Prefix + "queryCloudRegionRequest", queryCloudRegionRequest) + msoLogger.debug(" UPDNETI_queryCloudRegionRequest - " + "\n" + queryCloudRegionRequest) + + String cloudRegionPo = aaiUtil.getAAICloudReqion(execution, queryCloudRegionRequest, "PO", cloudRegion) + String cloudRegionSdnc = aaiUtil.getAAICloudReqion(execution, queryCloudRegionRequest, "SDNC", cloudRegion) + + if ((cloudRegionPo != "ERROR") && (cloudRegionSdnc != "ERROR")) { + execution.setVariable(Prefix + "cloudRegionPo", cloudRegionPo) + execution.setVariable(Prefix + "cloudRegionSdnc", cloudRegionSdnc) + execution.setVariable(Prefix + "isCloudRegionGood", true) + + } else { + String dataErrorMessage = "QueryAAICloudRegion Unsuccessful. Return Code: " + execution.getVariable(Prefix + "queryCloudRegionReturnCode") + msoLogger.debug(dataErrorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + + } + + msoLogger.debug(" is Cloud Region Good: " + execution.getVariable(Prefix + "isCloudRegionGood")) + + } catch (BpmnError e) { + throw e; + + } catch (Exception ex) { + // try error + String exceptionMessage = "Bpmn error encountered in DoUpdateNetworkInstance flow - callRESTQueryAAICloudRegion() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + public void callRESTQueryAAINetworkId(DelegateExecution execution) { + + execution.setVariable("prefix", Prefix) + + msoLogger.debug(" ***** Inside callRESTQueryAAINetworkId of DoUpdateNetworkInstance ***** " ) + + try { + // get variables + String networkRequest = execution.getVariable(Prefix + "networkRequest") + String networkId = utils.getNodeText(networkRequest, "network-id") + networkId = UriUtils.encode(networkId,"UTF-8") + execution.setVariable(Prefix + "networkId", networkId) + + // Prepare AA&I url + String aai_endpoint = UrnPropertiesReader.getVariable("aai.endpoint", execution) + AaiUtil aaiUriUtil = new AaiUtil(this) + String aai_uri = aaiUriUtil.getNetworkL3NetworkUri(execution) + String queryIdAAIRequest = "${aai_endpoint}${aai_uri}/" + networkId + "?depth=all" + msoLogger.debug(queryIdAAIRequest) + execution.setVariable(Prefix + "queryIdAAIRequest", queryIdAAIRequest) + msoLogger.debug(Prefix + "queryIdAAIRequest - " + "\n" + queryIdAAIRequest) + + APIResponse response = aaiUriUtil.executeAAIGetCall(execution, queryIdAAIRequest) + String returnCode = response.getStatusCode() + execution.setVariable(Prefix + "aaiIdReturnCode", returnCode) + msoLogger.debug(" ***** AAI Response Code : " + returnCode) + + String aaiResponseAsString = response.getResponseBodyAsString() + + if (returnCode=='200') { + msoLogger.debug(aaiResponseAsString) + execution.setVariable(Prefix + "queryIdAAIResponse", aaiResponseAsString) + msoLogger.debug(" QueryAAINetworkId Success REST Response - " + "\n" + aaiResponseAsString) + + } else { + if (returnCode=='404') { + String dataErrorMessage = "Response Error from QueryAAINetworkId is 404 (Not Found)." + msoLogger.debug(" AAI Query Failed. " + dataErrorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + + } else { + if (aaiResponseAsString.contains("RESTFault")) { + WorkflowException exceptionObject = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) + execution.setVariable("WorkflowException", exceptionObject) + throw new BpmnError("MSOWorkflowException") + + } else { + // aai all errors + String dataErrorMessage = "Unexpected Response from QueryAAINetworkId - " + returnCode + msoLogger.debug("Unexpected Response from QueryAAINetworkId - " + dataErrorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + + } + } + } + + } catch (BpmnError e) { + throw e; + + } catch (Exception ex) { + String exceptionMessage = "Bpmn error encountered in DoUpdateNetworkInstance flow. callRESTQueryAAINetworkId() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + public void callRESTReQueryAAINetworkId(DelegateExecution execution) { + + execution.setVariable("prefix", Prefix) + + msoLogger.debug(" ***** Inside callRESTReQueryAAINetworkId of DoUpdateNetworkInstance ***** " ) + + try { + // get variables + String networkRequest = execution.getVariable(Prefix + "networkRequest") + String networkId = utils.getNodeText(networkRequest, "network-id") + networkId = UriUtils.encode(networkId,"UTF-8") + + // Prepare AA&I url + String aai_endpoint = UrnPropertiesReader.getVariable("aai.endpoint", execution) + AaiUtil aaiUriUtil = new AaiUtil(this) + String aai_uri = aaiUriUtil.getNetworkL3NetworkUri(execution) + String requeryIdAAIRequest = "${aai_endpoint}${aai_uri}/" + networkId + "?depth=all" + msoLogger.debug(requeryIdAAIRequest) + execution.setVariable(Prefix + "requeryIdAAIRequest", requeryIdAAIRequest) + msoLogger.debug(" UPDNETI_requeryIdAAIRequest - " + "\n" + requeryIdAAIRequest) + + APIResponse response = aaiUriUtil.executeAAIGetCall(execution, requeryIdAAIRequest) + String returnCode = response.getStatusCode() + execution.setVariable(Prefix + "aaiRequeryIdReturnCode", returnCode) + msoLogger.debug(" ***** AAI ReQuery Response Code : " + returnCode) + + String aaiResponseAsString = response.getResponseBodyAsString() + + if (returnCode=='200') { + msoLogger.debug(aaiResponseAsString) + execution.setVariable(Prefix + "requeryIdAAIResponse", aaiResponseAsString) + msoLogger.debug(" ReQueryAAINetworkId Success REST Response - " + "\n" + aaiResponseAsString) + + String netId = utils.getNodeText(aaiResponseAsString, "network-id") + String netName = utils.getNodeText(aaiResponseAsString, "network-name") + String networkOutputs = + """<network-outputs> + <network-id>${MsoUtils.xmlEscape(netId)}</network-id> + <network-name>${MsoUtils.xmlEscape(netName)}</network-name> + </network-outputs>""" + execution.setVariable(Prefix + "networkOutputs", networkOutputs) + msoLogger.debug(" networkOutputs - " + '\n' + networkOutputs) + + } else { + if (returnCode=='404') { + String dataErrorMessage = "Response Error from ReQueryAAINetworkId is 404 (Not Found)." + msoLogger.debug(" AAI ReQuery Failed. - " + dataErrorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + + } else { + if (aaiResponseAsString.contains("RESTFault")) { + WorkflowException exceptionObject = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) + execution.setVariable("WorkflowException", exceptionObject) + throw new BpmnError("MSOWorkflowException") + + } else { + // aai all errors + String dataErrorMessage = "Unexpected Response from ReQueryAAINetworkId - " + returnCode + msoLogger.debug(dataErrorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + + } + } + } + + } catch (BpmnError e) { + throw e; + + } catch (Exception ex) { + String exceptionMessage = "Bpmn error encountered in DoUpdateNetworkInstance flow. callRESTReQueryAAINetworkId() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + public void callRESTQueryAAINetworkVpnBinding(DelegateExecution execution) { + + execution.setVariable("prefix", Prefix) + + msoLogger.debug(" ***** Inside callRESTQueryAAINetworkVpnBinding of DoUpdateNetworkInstance ***** " ) + + try { + + // get variables + String queryIdAAIResponse = execution.getVariable(Prefix + "requeryIdAAIResponse").replace('<?xml version="1.0" encoding="UTF-8"?>', "") + String relationship = networkUtils.getFirstNodeXml(queryIdAAIResponse, "relationship-list").trim().replace("tag0:","").replace(":tag0","") + msoLogger.debug(" relationship - " + relationship) + + // Check if Vnf Binding is present, then build a List of vnfBinding + List vpnBindingUri = networkUtils.getVnfBindingObject(relationship) + int vpnCount = vpnBindingUri.size() + execution.setVariable(Prefix + "vpnCount", vpnCount) + msoLogger.debug(" UPDNETI_vpnCount - " + vpnCount) + + String aai_endpoint = UrnPropertiesReader.getVariable("aai.endpoint", execution) + AaiUtil aaiUriUtil = new AaiUtil(this) + + if (vpnCount > 0) { + execution.setVariable(Prefix + "vpnBindings", vpnBindingUri) + msoLogger.debug(" vpnBindingUri List - " + vpnBindingUri) + + String routeTargets = "" + // AII loop call using list vpnBindings + for (i in 0..vpnBindingUri.size()-1) { + + int counting = i+1 + + // prepare url using vpnBinding + String queryVpnBindingAAIRequest = "" + String aai_uri = aaiUriUtil.getNetworkVpnBindingUri(execution) + + // Note: By default, the vpnBinding url is found in 'related-link' of the response, + // so, the default in URN mappings for this is set to "" (ie, space), unless forced to use the URN mapping. + if (aai_uri == null || aai_uri == "") { + // using value of 'related-link' from response + if (vpnBindingUri[i].charAt(vpnBindingUri[i].length()-1) == '/') { + queryVpnBindingAAIRequest = "${aai_endpoint}" + vpnBindingUri[i].substring(0, vpnBindingUri[i].length()-1) + "?depth=all" + } else { + queryVpnBindingAAIRequest = "${aai_endpoint}" + vpnBindingUri[i] + "?depth=all" + } + + } else { + // using uri value in URN mapping + String vpnBindingId = vpnBindingUri[i].substring(vpnBindingUri[i].indexOf("/vpn-binding/")+13, vpnBindingUri[i].length()) + if (vpnBindingId.charAt(vpnBindingId.length()-1) == '/') { + vpnBindingId = vpnBindingId.substring(0, vpnBindingId.length()-1) + } + queryVpnBindingAAIRequest = "${aai_endpoint}${aai_uri}/" + vpnBindingId + "?depth=all" + } + + msoLogger.debug(queryVpnBindingAAIRequest) + execution.setVariable(Prefix + "queryVpnBindingAAIRequest", queryVpnBindingAAIRequest) + msoLogger.debug(" UPDNETI_queryVpnBindingAAIRequest, , vpnBinding #" + counting + " : " + "\n" + queryVpnBindingAAIRequest) + + APIResponse response = aaiUriUtil.executeAAIGetCall(execution, queryVpnBindingAAIRequest) + String returnCode = response.getStatusCode() + execution.setVariable(Prefix + "aaiQqueryVpnBindingReturnCode", returnCode) + msoLogger.debug(" ***** AAI query vpn binding Response Code, vpnBinding #" + counting + " : " + returnCode) + + String aaiResponseAsString = response.getResponseBodyAsString() + + if (returnCode=='200') { + msoLogger.debug(aaiResponseAsString) + execution.setVariable(Prefix + "queryVpnBindingAAIResponse", aaiResponseAsString) + msoLogger.debug(" AAI Query Vpn Binding Success REST Response, , vpnBinding #" + counting + " : " + "\n" + aaiResponseAsString) + + String routeTarget = "" + String routeRole = "" + if (utils.nodeExists(aaiResponseAsString, "route-targets")) { + String aaiRouteTargets = utils.getNodeXml(aaiResponseAsString, "route-targets", false) + def aaiRouteTargetsXml = new XmlSlurper().parseText(aaiRouteTargets) + def aaiRouteTarget = aaiRouteTargetsXml.'**'.findAll {it.name() == "route-target"} + for (j in 0..aaiRouteTarget.size()-1) { + routeTarget = utils.getNodeText(XmlUtil.serialize(aaiRouteTarget[j]), "global-route-target") + routeRole = utils.getNodeText(XmlUtil.serialize(aaiRouteTarget[j]), "route-target-role") + routeTargets += "<routeTargets>" + '\n' + + " <routeTarget>" + routeTarget + "</routeTarget>" + '\n' + + " <routeTargetRole>" + routeRole + "</routeTargetRole>" + '\n' + + "</routeTargets>" + '\n' + } + } + + } else { + if (returnCode=='404') { + String dataErrorMessage = "Response Error from AAINetworkVpnBinding is 404 (Not Found)." + msoLogger.debug(dataErrorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + + } else { + if (aaiResponseAsString.contains("RESTFault")) { + WorkflowException exceptionObject = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) + execution.setVariable("WorkflowException", exceptionObject) + throw new BpmnError("MSOWorkflowException") + + } else { + // aai all errors + String dataErrorMessage = " Unexpected Response from AAINetworkVpnBinding - " + returnCode + msoLogger.debug(dataErrorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + + } + } + } + + } // end loop + + execution.setVariable(Prefix + "routeCollection", routeTargets) + msoLogger.debug(" UPDNETI_routeCollection - " + '\n' + routeTargets) + + } else { + // reset return code to success + execution.setVariable(Prefix + "aaiQqueryVpnBindingReturnCode", "200") + String aai_uri = aaiUriUtil.getNetworkL3NetworkUri(execution) + String schemaVersion = aaiUriUtil.getNamespaceFromUri(execution, aai_uri) + String aaiStubResponse = + """ <rest:payload contentType="text/xml" xmlns:rest="http://schemas.activebpel.org/REST/2007/12/01/aeREST.xsd"> + <vpn-binding xmlns="${schemaVersion}"> + <global-route-target/> + </vpn-binding> + </rest:payload>""" + String aaiStubResponseAsXml = utils.formatXml(aaiStubResponse) + execution.setVariable(Prefix + "queryVpnBindingAAIResponse", aaiStubResponseAsXml) + execution.setVariable(Prefix + "routeCollection", "<routeTargets/>") + msoLogger.debug(" No vpnBinding, using this stub as response - " + '\n' + aaiStubResponseAsXml) + + } + + } catch (BpmnError e) { + throw e; + + } catch (Exception ex) { + String exceptionMessage = "Bpmn error encountered in DoUpdateNetworkInstance flow. callRESTQueryAAINetworkVpnBinding() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + public void callRESTQueryAAINetworkPolicy(DelegateExecution execution) { + + execution.setVariable("prefix", Prefix) + + msoLogger.debug(" ***** Inside callRESTQueryAAINetworkPolicy of DoUpdateNetworkInstance ***** " ) + + try { + // get variables + String queryIdAAIResponse = execution.getVariable(Prefix + "requeryIdAAIResponse").replace('<?xml version="1.0" encoding="UTF-8"?>', "") + String relationship = networkUtils.getFirstNodeXml(queryIdAAIResponse, "relationship-list").trim().replace("tag0:","").replace(":tag0","") + msoLogger.debug(" relationship - " + relationship) + + // Check if Network Policy is present, then build a List of network policy + List networkPolicyUriList = networkUtils.getNetworkPolicyObject(relationship) + int networkPolicyCount = networkPolicyUriList.size() + execution.setVariable(Prefix + "networkPolicyCount", networkPolicyCount) + msoLogger.debug(" UPDNETI_networkPolicyCount - " + networkPolicyCount) + + String aai_endpoint = UrnPropertiesReader.getVariable("aai.endpoint", execution) + AaiUtil aaiUriUtil = new AaiUtil(this) + + if (networkPolicyCount > 0) { + execution.setVariable(Prefix + "networkPolicyUriList", networkPolicyUriList) + msoLogger.debug(" networkPolicyUri List - " + networkPolicyUriList) + + String networkPolicies = "" + // AII loop call using list vpnBindings + for (i in 0..networkPolicyUriList.size()-1) { + + int counting = i+1 + + // prepare url using vpnBinding + String queryNetworkPolicyAAIRequest = "" + + String aai_uri = aaiUriUtil.getNetworkPolicyUri(execution) + + // Note: By default, the network policy url is found in 'related-link' of the response, + // so, the default in URN mappings for this is set to "" (ie, space), unless forced to use the URN mapping. + if (aai_uri == null || aai_uri == "") { + // using value of 'related-link' from response + if (networkPolicyUriList[i].charAt(networkPolicyUriList[i].length()-1) == '/') { + queryNetworkPolicyAAIRequest = "${aai_endpoint}" + networkPolicyUriList[i].substring(0, networkPolicyUriList[i].length()-1) + "?depth=all" + } else { + queryNetworkPolicyAAIRequest = "${aai_endpoint}" + networkPolicyUriList[i] + "?depth=all" + } + } else { + // using uri value in URN mapping + String networkPolicyId = networkPolicyUriList[i].substring(networkPolicyUriList[i].indexOf("/network-policy/")+16, networkPolicyUriList[i].length()) + println " networkPolicyId - " + networkPolicyId + if (networkPolicyId.charAt(networkPolicyId.length()-1) == '/') { + networkPolicyId = networkPolicyId.substring(0, networkPolicyId.length()-1) + } + queryNetworkPolicyAAIRequest = "${aai_endpoint}${aai_uri}/" + networkPolicyId + "?depth=all" + + } + + + msoLogger.debug(queryNetworkPolicyAAIRequest) + execution.setVariable(Prefix + "queryNetworkPolicyAAIRequest", queryNetworkPolicyAAIRequest) + msoLogger.debug(" UPDNETI_queryNetworkPolicyAAIRequest, , NetworkPolicy #" + counting + " : " + "\n" + queryNetworkPolicyAAIRequest) + + APIResponse response = aaiUriUtil.executeAAIGetCall(execution, queryNetworkPolicyAAIRequest) + String returnCode = response.getStatusCode() + execution.setVariable(Prefix + "aaiQqueryNetworkPolicyReturnCode", returnCode) + msoLogger.debug(" ***** AAI query network policy Response Code, NetworkPolicy #" + counting + " : " + returnCode) + + String aaiResponseAsString = response.getResponseBodyAsString() + + if (returnCode=='200') { + msoLogger.debug(aaiResponseAsString) + execution.setVariable(Prefix + "queryNetworkPolicyAAIResponse", aaiResponseAsString) + msoLogger.debug(" QueryAAINetworkPolicy Success REST Response, , NetworkPolicy #" + counting + " : " + "\n" + aaiResponseAsString) + + String networkPolicy = "" + if (utils.nodeExists(aaiResponseAsString, "network-policy-fqdn")) { + networkPolicy = utils.getNodeText(aaiResponseAsString, "network-policy-fqdn") + networkPolicies += "<policyFqdns>" + networkPolicy + "</policyFqdns>" + '\n' + } + + } else { + if (returnCode=='404') { + String dataErrorMessage = "Response Error from QueryAAINetworkPolicy is 404 (Not Found)." + msoLogger.debug(dataErrorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + + } else { + if (aaiResponseAsString.contains("RESTFault")) { + WorkflowException exceptionObject = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) + execution.setVariable("WorkflowException", exceptionObject) + throw new BpmnError("MSOWorkflowException") + + } else { + // aai all errors + String dataErrorMessage = "Unexpected Response from QueryAAINetworkPolicy - " + returnCode + msoLogger.debug(dataErrorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + + } + } + } + + } // end loop + + execution.setVariable(Prefix + "networkCollection", networkPolicies) + msoLogger.debug(" UPDNETI_networkCollection - " + '\n' + networkPolicies) + + } else { + // reset return code to success + execution.setVariable(Prefix + "aaiQqueryNetworkPolicyReturnCode", "200") + String aai_uri = aaiUriUtil.getNetworkL3NetworkUri(execution) + String schemaVersion = aaiUriUtil.getNamespaceFromUri(execution, aai_uri) + String aaiStubResponse = + """ <rest:payload contentType="text/xml" xmlns:rest="http://schemas.activebpel.org/REST/2007/12/01/aeREST.xsd"> + <network-policy xmlns="${schemaVersion}"> + <network-policy-fqdn/> + </network-policy> + </rest:payload>""" + String aaiStubResponseAsXml = utils.formatXml(aaiStubResponse) + execution.setVariable(Prefix + "queryNetworkPolicyAAIResponse", aaiStubResponseAsXml) + execution.setVariable(Prefix + "networkCollection", "<policyFqdns/>") + msoLogger.debug(" No net policies, using this stub as response - " + '\n' + aaiStubResponseAsXml) + + } + + } catch (BpmnError e) { + throw e; + + } catch (Exception ex) { + String exceptionMessage = "Bpmn error encountered in DoUpdateNetworkInstance flow. callRESTQueryAAINetworkPolicy() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + public void callRESTQueryAAINetworkTableRef(DelegateExecution execution) { + + execution.setVariable("prefix", Prefix) + + msoLogger.debug(" ***** Inside callRESTQueryAAINetworkTableRef of DoUpdateNetworkInstance ***** " ) + + try { + // get variables + String queryIdAAIResponse = execution.getVariable(Prefix + "requeryIdAAIResponse").replace('<?xml version="1.0" encoding="UTF-8"?>', "") + String relationship = networkUtils.getFirstNodeXml(queryIdAAIResponse, "relationship-list").trim().replace("tag0:","").replace(":tag0","") + msoLogger.debug(" relationship - " + relationship) + + // Check if Network TableREf is present, then build a List of network policy + List networkTableRefUriList = networkUtils.getNetworkTableRefObject(relationship) + int networkTableRefCount = networkTableRefUriList.size() + execution.setVariable(Prefix + "networkTableRefCount", networkTableRefCount) + msoLogger.debug(" UPDNETI_networkTableRefCount - " + networkTableRefCount) + + String aai_endpoint = UrnPropertiesReader.getVariable("aai.endpoint", execution) + AaiUtil aaiUriUtil = new AaiUtil(this) + + if (networkTableRefCount > 0) { + execution.setVariable(Prefix + "networkTableRefUriList", networkTableRefUriList) + msoLogger.debug(" networkTableRefUri List - " + networkTableRefUriList) + + // AII loop call using list vpnBindings + String networkTableRefs = "" + for (i in 0..networkTableRefUriList.size()-1) { + + int counting = i+1 + + // prepare url using tableRef + String queryNetworkTableRefAAIRequest = "" + + String aai_uri = aaiUriUtil.getNetworkTableReferencesUri(execution) + + // Note: By default, the network policy url is found in 'related-link' of the response, + // so, the default in URN mappings for this is set to "" (ie, space), unless forced to use the URN mapping. + if (aai_uri == null || aai_uri == "") { + // using value of 'related-link' from response + if (networkTableRefUriList[i].charAt(networkTableRefUriList[i].length()-1) == '/') { + queryNetworkTableRefAAIRequest = "${aai_endpoint}" + networkTableRefUriList[i].substring(0, networkTableRefUriList[i].length()-1) + "?depth=all" + } else { + queryNetworkTableRefAAIRequest = "${aai_endpoint}" + networkTableRefUriList[i] + "?depth=all" + } + } else { + // using uri value in URN mapping + String networkTableRefId = networkTableRefUriList[i].substring(networkTableRefUriList[i].indexOf("/route-table-reference/")+23, networkTableRefUriList[i].length()) + + if (networkTableRefId.charAt(networkTableRefId.length()-1) == '/') { + networkTableRefId = networkTableRefId.substring(0, networkTableRefId.length()-1) + } + queryNetworkTableRefAAIRequest = "${aai_endpoint}${aai_uri}/" + networkTableRefId + "?depth=all" + + } + + + msoLogger.debug(queryNetworkTableRefAAIRequest) + execution.setVariable(Prefix + "queryNetworkTableRefAAIRequest", queryNetworkTableRefAAIRequest) + msoLogger.debug(" UPDNETI_queryNetworkTableRefAAIRequest, , NetworkTableRef #" + counting + " : " + "\n" + queryNetworkTableRefAAIRequest) + + APIResponse response = aaiUriUtil.executeAAIGetCall(execution, queryNetworkTableRefAAIRequest) + String returnCode = response.getStatusCode() + execution.setVariable(Prefix + "aaiQqueryNetworkTableRefReturnCode", returnCode) + msoLogger.debug(" ***** AAI query network Table Reference Response Code, NetworkTableRef #" + counting + " : " + returnCode) + + String aaiResponseAsString = response.getResponseBodyAsString() + + if (returnCode=='200') { + msoLogger.debug(aaiResponseAsString) + execution.setVariable(Prefix + "queryNetworkTableRefAAIResponse", aaiResponseAsString) + msoLogger.debug(" QueryAAINetworkTableRef Success REST Response, , NetworkTableRef #" + counting + " : " + "\n" + aaiResponseAsString) + + String networkTableRef = "" + if (utils.nodeExists(aaiResponseAsString, "route-table-reference-fqdn")) { + networkTableRef = utils.getNodeText(aaiResponseAsString, "route-table-reference-fqdn") + networkTableRefs += "<routeTableFqdns>" + networkTableRef + "</routeTableFqdns>" + '\n' + } + + } else { + if (returnCode=='404') { + String dataErrorMessage = "Response Error from QueryAAINetworkTableRef is 404 (Not Found)." + msoLogger.debug(dataErrorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + + } else { + if (aaiResponseAsString.contains("RESTFault")) { + WorkflowException exceptionObject = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) + execution.setVariable("WorkflowException", exceptionObject) + throw new BpmnError("MSOWorkflowException") + + } else { + // aai all errors + String dataErrorMessage = "Unexpected Response from QueryAAINetworkTableRef - " + returnCode + msoLogger.debug(dataErrorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + + } + } + } + + } // end loop + + execution.setVariable(Prefix + "tableRefCollection", networkTableRefs) + msoLogger.debug(" UPDNETI_tableRefCollection - " + '\n' + networkTableRefs) + + } else { + // reset return code to success + execution.setVariable(Prefix + "aaiQqueryNetworkTableRefReturnCode", "200") + String aai_uri = aaiUriUtil.getNetworkL3NetworkUri(execution) + String schemaVersion = aaiUriUtil.getNamespaceFromUri(execution, aai_uri) + String aaiStubResponse = + """ <rest:payload contentType="text/xml" xmlns:rest="http://schemas.activebpel.org/REST/2007/12/01/aeREST.xsd"> + <route-table-references xmlns="${schemaVersion}"> + <route-table-reference-fqdn/> + </route-table-references> + </rest:payload>""" + String aaiStubResponseAsXml = utils.formatXml(aaiStubResponse) + execution.setVariable(Prefix + "queryNetworkTableRefAAIResponse", aaiStubResponseAsXml) + execution.setVariable(Prefix + "tableRefCollection", "<routeTableFqdns/>") + msoLogger.debug(" No net table references, using this stub as response - " + '\n' + aaiStubResponseAsXml) + + } + + } catch (BpmnError e) { + throw e; + + } catch (Exception ex) { + String exceptionMessage = "Bpmn error encountered in DoUpdateNetworkInstance flow. callRESTQueryAAINetworkTableRef() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + public void callRESTUpdateContrailAAINetwork(DelegateExecution execution) { + + execution.setVariable("prefix", Prefix) + + msoLogger.debug(" ***** Inside callRESTUpdateContrailAAINetwork of DoUpdateNetworkInstance ***** " ) + + try { + // get variables + String networkRequest = execution.getVariable(Prefix + "networkRequest") + String networkId = utils.getNodeText(networkRequest, "network-id") + networkId = UriUtils.encode(networkId,"UTF-8") + String requeryIdAAIResponse = execution.getVariable(Prefix + "requeryIdAAIResponse") + String updateNetworkResponse = execution.getVariable(Prefix + "updateNetworkResponse") + + // Prepare url + String aai_endpoint = UrnPropertiesReader.getVariable("aai.endpoint", execution) + AaiUtil aaiUriUtil = new AaiUtil(this) + String aai_uri = aaiUriUtil.getNetworkL3NetworkUri(execution) + String updateContrailAAIUrlRequest = "${aai_endpoint}${aai_uri}/" + networkId + "?depth=all" + + msoLogger.debug(updateContrailAAIUrlRequest) + execution.setVariable(Prefix + "updateContrailAAIUrlRequest", updateContrailAAIUrlRequest) + msoLogger.debug(" UPDNETI_updateContrailAAIUrlRequest - " + "\n" + updateContrailAAIUrlRequest) + + //Prepare payload (PUT) + String schemaVersion = aaiUriUtil.getNamespaceFromUri(execution, aai_uri) + String payload = networkUtils.ContrailNetworkCreatedUpdate(requeryIdAAIResponse, updateNetworkResponse, schemaVersion) + String payloadXml = utils.formatXml(payload) + msoLogger.debug(payloadXml) + execution.setVariable(Prefix + "updateContrailAAIPayloadRequest", payloadXml) + msoLogger.debug(" 'payload' to Update Contrail - " + "\n" + payloadXml) + + APIResponse response = aaiUriUtil.executeAAIPutCall(execution, updateContrailAAIUrlRequest, payload) + String returnCode = response.getStatusCode() + String aaiUpdateContrailResponseAsString = response.getResponseBodyAsString() + + execution.setVariable(Prefix + "aaiUpdateContrailReturnCode", returnCode) + msoLogger.debug(" ***** AAI Update Contrail Response Code : " + returnCode) + + + if (returnCode=='200') { + msoLogger.debug(aaiUpdateContrailResponseAsString) + execution.setVariable(Prefix + "updateContrailAAIResponse", aaiUpdateContrailResponseAsString) + msoLogger.debug(" AAI Update Contrail Success REST Response - " + "\n" + aaiUpdateContrailResponseAsString) + // Point-of-no-return is set to false, rollback not needed. + execution.setVariable(Prefix + "isPONR", true) + + } else { + if (returnCode=='404') { + String dataErrorMessage = " Response Error from UpdateContrailAAINetwork is 404 (Not Found)." + msoLogger.debug(dataErrorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + + } else { + if (aaiUpdateContrailResponseAsString.contains("RESTFault")) { + WorkflowException exceptionObject = exceptionUtil.MapAAIExceptionToWorkflowException(aaiUpdateContrailResponseAsString, execution) + execution.setVariable("WorkflowException", exceptionObject) + throw new BpmnError("MSOWorkflowException") + + } else { + // aai all errors + String errorMessage = "Unexpected Response from UpdateContrailAAINetwork - " + returnCode + msoLogger.debug(errorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, errorMessage) + } + } + } + + } catch (BpmnError e) { + throw e; + + } catch (Exception ex) { + String exceptionMessage = "Bpmn error encountered in DoUpdateNetworkInstance flow. callRESTUpdateContrailAAINetwork() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + public void prepareUpdateNetworkRequest (DelegateExecution execution) { + + execution.setVariable("prefix", Prefix) + + msoLogger.trace("Inside prepareUpdateNetworkRequest of DoUpdateNetworkInstance ") + + try { + + // get variables + String requestId = execution.getVariable(Prefix + "requestId") + String messageId = execution.getVariable(Prefix + "messageId") + String source = execution.getVariable(Prefix + "source") + + String requestInput = execution.getVariable(Prefix + "networkRequest") + String queryIdResponse = execution.getVariable(Prefix + "requeryIdAAIResponse") + String cloudRegionId = execution.getVariable(Prefix + "cloudRegionPo") + String backoutOnFailure = execution.getVariable(Prefix + "rollbackEnabled") + + // Prepare Network request + String routeCollection = execution.getVariable(Prefix + "routeCollection") + String policyCollection = execution.getVariable(Prefix + "networkCollection") + String tableCollection = execution.getVariable(Prefix + "tableRefCollection") + String updateNetworkRequest = networkUtils.UpdateNetworkRequestV2(execution, requestId, messageId, requestInput, queryIdResponse, routeCollection, policyCollection, tableCollection, cloudRegionId, backoutOnFailure, source ) + // Format Response + String buildUpdateNetworkRequestAsString = utils.formatXml(updateNetworkRequest) + buildUpdateNetworkRequestAsString = buildUpdateNetworkRequestAsString.replace(":w1aac13n0", "").replace("w1aac13n0:", "") + msoLogger.debug(buildUpdateNetworkRequestAsString) + + execution.setVariable(Prefix + "updateNetworkRequest", buildUpdateNetworkRequestAsString) + msoLogger.debug(" UPDNETI_updateNetworkRequest - " + "\n" + buildUpdateNetworkRequestAsString) + + } catch (Exception ex) { + String exceptionMessage = " Bpmn error encountered in DoUpdateNetworkInstance flow. prepareUpdateNetworkRequest() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + public void prepareSDNCRequest (DelegateExecution execution) { + + execution.setVariable("prefix", Prefix) + + msoLogger.trace("Inside prepareSDNCRequest of DoUpdateNetworkInstance ") + + try { + // get variables + String sdncCallback = UrnPropertiesReader.getVariable("mso.workflow.sdncadapter.callback",execution) + String updateNetworkInput = execution.getVariable(Prefix + "networkRequest") + String cloudRegionId = execution.getVariable(Prefix + "cloudRegionSdnc") + + String networkId = "" + if (utils.nodeExists(updateNetworkInput, "network-id")) { + networkId = utils.getNodeText(updateNetworkInput, "network-id") + } + if (networkId == null) {networkId = ""} + + String serviceInstanceId = utils.getNodeText(updateNetworkInput, "service-instance-id") + + String queryAAIResponse = execution.getVariable(Prefix + "queryIdAAIResponse") + + // 1. prepare assign topology via SDNC Adapter SUBFLOW call + String sndcTopologyCreateRequest = sdncAdapterUtils.sdncTopologyRequestV2(execution, updateNetworkInput, serviceInstanceId, sdncCallback, "changeassign", "NetworkActivateRequest", cloudRegionId, networkId, queryAAIResponse, null) + + String sndcTopologyUpdateRequesAsString = utils.formatXml(sndcTopologyCreateRequest) + msoLogger.debug(sndcTopologyUpdateRequesAsString) + execution.setVariable(Prefix + "changeAssignSDNCRequest", sndcTopologyUpdateRequesAsString) + msoLogger.debug(" UPDNETI_changeAssignSDNCRequest - " + "\n" + sndcTopologyUpdateRequesAsString) + + + } catch (Exception ex) { + String exceptionMessage = " Bpmn error encountered in DoUpdateNetworkInstance flow. prepareSDNCRequest() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + + + + // ************************************************** + // Post or Validate Response Section + // ************************************************** + + public void validateUpdateNetworkResponse (DelegateExecution execution) { + + execution.setVariable("prefix", Prefix) + + msoLogger.trace("Inside validateUpdateNetworkResponse of DoUpdateNetworkInstance ") + + try { + String returnCode = execution.getVariable(Prefix + "networkReturnCode") + String networkResponse = execution.getVariable(Prefix + "updateNetworkResponse") + if (networkResponse==null) { + networkResponse="" // reset + } + + msoLogger.debug(" Network Adapter update responseCode: " + returnCode) + + String errorMessage = "" + if (returnCode == "200") { + execution.setVariable(Prefix + "isNetworkRollbackNeeded", true) + msoLogger.debug(networkResponse) + execution.setVariable(Prefix + "updateNetworkResponse", networkResponse) + msoLogger.debug(" Network Adapter update Success Response - " + "\n" + networkResponse) + + // prepare rollback data + String rollbackData = utils.getNodeXml(networkResponse, "rollback", false).replace("tag0:","").replace(":tag0","") + rollbackData = rollbackData.replace("rollback>", "networkRollback>") + String rollbackNetwork = + """<rollbackNetworkRequest> + ${rollbackData} + </rollbackNetworkRequest>""" + String rollbackNetworkXml = utils.formatXml(rollbackNetwork) + execution.setVariable(Prefix + "rollbackNetworkRequest", rollbackNetworkXml) + msoLogger.debug(" Network Adapter rollback data - " + "\n" + rollbackNetworkXml) + + } else { // network error + if (returnCode.toInteger() > 399 && returnCode.toInteger() < 600) { //4xx, 5xx + if (networkResponse.contains("updateNetworkError")) { + networkResponse = networkResponse.replace('<?xml version="1.0" encoding="UTF-8" standalone="yes"?>', '') + errorMessage = utils.getNodeText(networkResponse, "message") + errorMessage = "Received error from Network Adapter: " + errorMessage + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, errorMessage) + + } else { // CatchAll exception + if (returnCode == "500") { + errorMessage = "JBWEB000065: HTTP Status 500." + } else { + errorMessage = "Return code is " + returnCode + } + errorMessage = "Received error from Network Adapter: " + errorMessage + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, errorMessage) + + } + + } else { // CatchAll exception + String dataErrorMessage = "Received error from Network Adapter. Return code is: " + returnCode + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + + } + + } + + } catch (BpmnError e) { + throw e; + + } catch (Exception ex) { + String exceptionMessage = " Bpmn error encountered in DoUpdateNetworkInstance flow. validateUpdateNetworkResponse() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + + + } + + public void validateSDNCResponse (DelegateExecution execution) { + + execution.setVariable("prefix", Prefix) + + msoLogger.trace("Inside validateSDNCResponse of DoUpdateNetworkInstance ") + + String response = execution.getVariable(Prefix + "changeAssignSDNCResponse") + WorkflowException workflowException = null + try { + workflowException = execution.getVariable(Prefix + "WorkflowException") + //execution.setVariable("WorkflowException", workflowException) + } catch (Exception ex) { + msoLogger.debug(" Sdnc 'WorkflowException' object is empty or null. ") + } + + boolean successIndicator = execution.getVariable("SDNCA_SuccessIndicator") + + SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this) + sdncAdapterUtils.validateSDNCResponse(execution, response, workflowException, successIndicator) + // reset variable + String changeAssignSDNCResponseDecodeXml = execution.getVariable(Prefix + "changeAssignSDNCResponse") + changeAssignSDNCResponseDecodeXml = changeAssignSDNCResponseDecodeXml.replace('<?xml version="1.0" encoding="UTF-8"?>', "") + execution.setVariable(Prefix + "changeAssignSDNCResponse", changeAssignSDNCResponseDecodeXml) + + if (execution.getVariable(Prefix + "sdncResponseSuccess") == true) { // from sdnc util, prefix+'sdncResponseSuccess' + execution.setVariable(Prefix + "isSdncRollbackNeeded", true) + msoLogger.debug("Successfully Validated SDNC Response") + + } else { + msoLogger.debug("Did NOT Successfully Validated SDNC Response") + throw new BpmnError("MSOWorkflowException") + } + + } + + + public void postProcessResponse (DelegateExecution execution) { + + execution.setVariable("prefix", Prefix) + + msoLogger.trace("Inside postProcessResponse of DoUpdateNetworkInstance ") + + try { + msoLogger.debug(" ***** Is Exception Encountered (isException)? : " + execution.getVariable(Prefix + "isException")) + if (execution.getVariable(Prefix + "isException") == false) { + // set rollback data + execution.setVariable("orchestrationStatus", "") + execution.setVariable("networkId", execution.getVariable(Prefix + "networkId")) + execution.setVariable("networkName", execution.getVariable(Prefix + "networkName")) + prepareSuccessRollbackData(execution) // populate rollbackData + execution.setVariable("WorkflowException", null) + execution.setVariable(Prefix + "Success", true) + msoLogger.debug(" ***** postProcessResponse(), GOOD !!!") + } else { + execution.setVariable(Prefix + "Success", false) + execution.setVariable("rollbackData", null) + String exceptionMessage = " Exception encountered in MSO Bpmn. " + if (execution.getVariable("workflowException") != null) { // Output of Rollback flow. + msoLogger.debug(" ***** workflowException: " + execution.getVariable("workflowException")) + WorkflowException wfex = execution.getVariable("workflowException") + exceptionMessage = wfex.getErrorMessage() + } else { + if (execution.getVariable(Prefix + "WorkflowException") != null) { + WorkflowException pwfex = execution.getVariable(Prefix + "WorkflowException") + exceptionMessage = pwfex.getErrorMessage() + } + } + // going to the Main flow: a-la-carte or macro + msoLogger.debug(" ***** postProcessResponse(), BAD !!!") + exceptionUtil.buildWorkflowException(execution, 7000, exceptionMessage) + throw new BpmnError("MSOWorkflowException") + } + + } catch(BpmnError b){ + msoLogger.debug("Rethrowing MSOWorkflowException") + throw b + + + } catch (Exception ex) { + String exceptionMessage = " Bpmn error encountered in DoUpdateNetworkInstance flow. postProcessResponse() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + + + } + + public void prepareSDNCRollbackRequest (DelegateExecution execution) { + + execution.setVariable("prefix", Prefix) + + msoLogger.trace("Inside prepareSDNCRollbackRequest of DoUpdateNetworkInstance ") + + try { + // for some reason the WorkflowException object is null after the sdnc rollback call task, need to save WorkflowException. + execution.setVariable(Prefix + "WorkflowException", execution.getVariable("WorkflowException")) + // get variables + String sdncCallback = UrnPropertiesReader.getVariable("mso.workflow.sdncadapter.callback",execution) + String updateNetworkInput = execution.getVariable(Prefix + "networkRequest") + String cloudRegionId = execution.getVariable(Prefix + "cloudRegionSdnc") + String changeAssignSDNCResponse = execution.getVariable(Prefix + "changeAssignSDNCResponse") + String networkId = utils.getNodeText(changeAssignSDNCResponse, "network-id") + + String serviceInstanceId = utils.getNodeText(updateNetworkInput, "service-instance-id") + + // 2. prepare rollback topology via SDNC Adapter SUBFLOW call + String sndcTopologyRollbackRequest = sdncAdapterUtils.sdncTopologyRequestV2(execution, updateNetworkInput, serviceInstanceId, sdncCallback, "rollback", "NetworkActivateRequest", cloudRegionId, networkId, null, null) + String sndcTopologyRollbackRequestAsString = utils.formatXml(sndcTopologyRollbackRequest) + execution.setVariable(Prefix + "rollbackSDNCRequest", sndcTopologyRollbackRequestAsString) + msoLogger.debug(" Preparing request for SDNC Topology assign's rollback/compensation . . . - " + "\n" + sndcTopologyRollbackRequestAsString) + + } catch (Exception ex) { + String exceptionMessage = " Bpmn error encountered in DoUpdateNetworkInstance flow. prepareSDNCRollbackRequest() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + public void prepareRollbackData(DelegateExecution execution) { + + execution.setVariable("prefix",Prefix) + + msoLogger.trace("Inside prepareRollbackData() of DoUpdateNetworkInstance ") + + try { + + Map<String, String> rollbackData = new HashMap<String, String>(); + String rollbackSDNCRequest = execution.getVariable(Prefix + "rollbackSDNCRequest") + if (rollbackSDNCRequest != null) { + if (rollbackSDNCRequest != "") { + rollbackData.put("rollbackSDNCRequest", execution.getVariable(Prefix + "rollbackSDNCRequest")) + } + } + String rollbackNetworkRequest = execution.getVariable(Prefix + "rollbackNetworkRequest") + if (rollbackNetworkRequest != null) { + if (rollbackNetworkRequest != "") { + rollbackData.put("rollbackNetworkRequest", execution.getVariable(Prefix + "rollbackNetworkRequest")) + } + } + execution.setVariable("rollbackData", rollbackData) + msoLogger.debug("** rollbackData : " + rollbackData) + + execution.setVariable("WorkflowException", execution.getVariable(Prefix + "WorkflowException")) + msoLogger.debug("** WorkflowException : " + execution.getVariable("WorkflowException")) + + } catch (Exception ex) { + String exceptionMessage = " Bpmn error encountered in DoUpdateNetworkInstance flow. prepareRollbackData() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + public void prepareSuccessRollbackData(DelegateExecution execution) { + + execution.setVariable("prefix",Prefix) + + msoLogger.trace("Inside prepareSuccessRollbackData() of DoUpdateNetworkInstance ") + + try { + + if (execution.getVariable("sdncVersion") != '1610') { + // skip: 1702 for 'changeassign' or equivalent not yet defined in SNDC, so no rollback. + } else { + prepareSDNCRollbackRequest(execution) + } + + Map<String, String> rollbackData = new HashMap<String, String>(); + String rollbackSDNCRequest = execution.getVariable(Prefix + "rollbackSDNCRequest") + if (rollbackSDNCRequest != null) { + if (rollbackSDNCRequest != "") { + rollbackData.put("rollbackSDNCRequest", rollbackSDNCRequest) + } + } + String rollbackNetworkRequest = execution.getVariable(Prefix + "rollbackNetworkRequest") + if (rollbackNetworkRequest != null) { + if (rollbackNetworkRequest != "") { + rollbackData.put("rollbackNetworkRequest", rollbackNetworkRequest) + } + } + execution.setVariable("rollbackData", rollbackData) + + msoLogger.debug("** 'rollbackData' for Full Rollback : " + rollbackData) + execution.setVariable("WorkflowException", null) + + + } catch (Exception ex) { + String exceptionMessage = " Bpmn error encountered in DoUpdateNetworkInstance flow. prepareSuccessRollbackData() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + public void setExceptionFlag(DelegateExecution execution){ + + execution.setVariable("prefix",Prefix) + + msoLogger.trace("Inside setExceptionFlag() of DoUpdateNetworkInstance ") + + try { + + execution.setVariable(Prefix + "isException", true) + + if (execution.getVariable("SavedWorkflowException1") != null) { + execution.setVariable(Prefix + "WorkflowException", execution.getVariable("SavedWorkflowException1")) + } else { + execution.setVariable(Prefix + "WorkflowException", execution.getVariable("WorkflowException")) + } + msoLogger.debug(Prefix + "WorkflowException - " +execution.getVariable(Prefix + "WorkflowException")) + + } catch(Exception ex){ + String exceptionMessage = "Bpmn error encountered in DoUpdateNetworkInstance flow. setExceptionFlag(): " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildWorkflowException(execution, 7000, exceptionMessage) + } + + } + + + // ******************************* + // Build Error Section + // ******************************* + + public void processJavaException(DelegateExecution execution){ + + execution.setVariable("prefix",Prefix) + try{ + msoLogger.debug("Caught a Java Exception") + msoLogger.debug("Started processJavaException Method") + msoLogger.debug("Variables List: " + execution.getVariables()) + execution.setVariable("UnexpectedError", "Caught a Java Lang Exception - " + Prefix) // Adding this line temporarily until this flows error handling gets updated + exceptionUtil.buildWorkflowException(execution, 500, "Caught a Java Lang Exception") + + }catch(Exception e){ + msoLogger.debug("Caught Exception during processJavaException Method: " + e) + execution.setVariable("UnexpectedError", "Exception in processJavaException method") // Adding this line temporarily until this flows error handling gets updated + exceptionUtil.buildWorkflowException(execution, 500, "Exception in processJavaException method") + } + msoLogger.debug("Completed processJavaException Method") + } + +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateNetworkInstanceRollback.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateNetworkInstanceRollback.groovy new file mode 100644 index 0000000000..8a13b3c392 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateNetworkInstanceRollback.groovy @@ -0,0 +1,310 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts; + +import groovy.xml.XmlUtil +import groovy.json.* + +import org.onap.so.bpmn.common.scripts.AaiUtil +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.onap.so.bpmn.common.scripts.ExceptionUtil +import org.onap.so.bpmn.common.scripts.NetworkUtils +import org.onap.so.bpmn.common.scripts.SDNCAdapterUtils +import org.onap.so.bpmn.common.scripts.VidUtils +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.bpmn.core.UrnPropertiesReader +import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.rest.APIResponse + +import java.util.UUID; + +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.apache.commons.lang3.* +import org.apache.commons.codec.binary.Base64; +import org.springframework.web.util.UriUtils + +import org.onap.so.logger.MessageEnum +import org.onap.so.logger.MsoLogger + +/** + * This groovy class supports the <class>DoCreateNetworkInstance.bpmn</class> process. + * + */ +public class DoUpdateNetworkInstanceRollback extends AbstractServiceTaskProcessor { + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoUpdateNetworkInstanceRollback.class); + + String Prefix="UPDNETIR_" + ExceptionUtil exceptionUtil = new ExceptionUtil() + JsonUtils jsonUtil = new JsonUtils() + VidUtils vidUtils = new VidUtils(this) + NetworkUtils networkUtils = new NetworkUtils() + SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils() + + def className = getClass().getSimpleName() + + /** + * This method is executed during the preProcessRequest task of the <class>DoUpdateNetworkInstanceRollback.bpmn</class> process. + * @param execution + */ + public InitializeProcessVariables(DelegateExecution execution){ + /* Initialize all the process variables in this block */ + + execution.setVariable(Prefix + "rollbackNetworkRequest", null) + execution.setVariable(Prefix + "rollbackSDNCRequest", null) + execution.setVariable(Prefix + "WorkflowException", null) + + execution.setVariable(Prefix + "rollbackNetworkRequest", "") + execution.setVariable(Prefix + "rollbackNetworkResponse", "") + execution.setVariable(Prefix + "rollbackNetworkReturnCode", "") + + execution.setVariable(Prefix + "rollbackSDNCRequest", "") + execution.setVariable(Prefix + "rollbackSDNCResponse", "") + execution.setVariable(Prefix + "rollbackSDNCReturnCode", "") + + execution.setVariable(Prefix + "Success", false) + execution.setVariable(Prefix + "fullRollback", false) + + } + + // ************************************************** + // Pre or Prepare Request Section + // ************************************************** + /** + * This method is executed during the preProcessRequest task of the <class>DoUpdateNetworkInstanceRollback.bpmn</class> process. + * @param execution + */ + public void preProcessRequest (DelegateExecution execution) { + + execution.setVariable("prefix",Prefix) + + msoLogger.trace("Inside preProcessRequest() of " + className + ".groovy ") + + try { + // initialize flow variables + InitializeProcessVariables(execution) + + // GET Incoming request/variables + String rollbackNetworkRequest = null + String rollbackSDNCRequest = null + + // Partial Rollback + Map<String, String> rollbackData = execution.getVariable("rollbackData") + if (rollbackData != null && rollbackData instanceof Map) { + + if(rollbackData.containsKey("rollbackNetworkRequest")) { + rollbackNetworkRequest = rollbackData["rollbackNetworkRequest"] + } + + if(rollbackData.containsKey("rollbackSDNCRequest")) { + rollbackSDNCRequest = rollbackData["rollbackSDNCRequest"] + } + } + + execution.setVariable(Prefix + "rollbackNetworkRequest", rollbackNetworkRequest) + execution.setVariable(Prefix + "rollbackSDNCRequest", rollbackSDNCRequest) + msoLogger.debug("'rollbackData': " + '\n' + execution.getVariable("rollbackData")) + + String sdncVersion = execution.getVariable("sdncVersion") + msoLogger.debug("sdncVersion? : " + sdncVersion) + + // PO Authorization Info / headers Authorization= + String basicAuthValuePO = UrnPropertiesReader.getVariable("mso.adapters.po.auth",execution) + + try { + def encodedString = utils.getBasicAuth(basicAuthValuePO, UrnPropertiesReader.getVariable("mso.msoKey", execution)) + execution.setVariable("BasicAuthHeaderValuePO",encodedString) + execution.setVariable("BasicAuthHeaderValueSDNC", encodedString) + + } catch (IOException ex) { + String exceptionMessage = "Exception Encountered in DoCreateNetworkInstance, PreProcessRequest() - " + String dataErrorMessage = exceptionMessage + " Unable to encode PO/SDNC user/password string - " + ex.getMessage() + msoLogger.debug(dataErrorMessage ) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + } + + if (execution.getVariable("SavedWorkflowException1") != null) { + execution.setVariable(Prefix + "WorkflowException", execution.getVariable("SavedWorkflowException1")) + } else { + execution.setVariable(Prefix + "WorkflowException", execution.getVariable("WorkflowException")) + } + msoLogger.debug("*** WorkflowException : " + execution.getVariable(Prefix + "WorkflowException")) + if(execution.getVariable(Prefix + "WorkflowException") != null) { + // called by: DoCreateNetworkInstance, partial rollback + execution.setVariable(Prefix + "fullRollback", false) + + } else { + // called by: Macro - Full Rollback, WorkflowException = null + execution.setVariable(Prefix + "fullRollback", true) + + } + msoLogger.debug("*** fullRollback? : " + execution.getVariable(Prefix + "fullRollback")) + + + } catch (BpmnError e) { + throw e; + + } catch (Exception ex) { + sendSyncError(execution) + // caught exception + String exceptionMessage = "Exception Encountered in PreProcessRequest() of " + className + ".groovy ***** : " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + public void validateRollbackResponses (DelegateExecution execution) { + + execution.setVariable("prefix",Prefix) + + msoLogger.trace("Inside validateRollbackResponses() of DoUpdateNetworkInstanceRollback ") + + try { + // validate PO network rollback response + String rollbackNetworkErrorMessages = "" + String rollbackNetworkReturnCode = "200" + if (execution.getVariable(Prefix + "rollbackNetworkRequest") != null) { + rollbackNetworkReturnCode = execution.getVariable(Prefix + "rollbackNetworkReturnCode") + String rollbackNetworkResponse = execution.getVariable(Prefix + "rollbackNetworkResponse") + msoLogger.debug(" NetworkRollback Code - " + rollbackNetworkReturnCode) + msoLogger.debug(" NetworkRollback Response - " + rollbackNetworkResponse) + if (rollbackNetworkReturnCode != "200") { + rollbackNetworkErrorMessages = " + PO Network rollback failed. " + } else { + rollbackNetworkErrorMessages = " + PO Network rollback completed." + } + } + + // validate SDNC rollback response + String rollbackSdncErrorMessages = "" + String rollbackSDNCReturnCode = "200" + if (execution.getVariable(Prefix + "rollbackSDNCRequest") != null) { + rollbackSDNCReturnCode = execution.getVariable(Prefix + "rollbackSDNCReturnCode") + String rollbackSDNCResponse = execution.getVariable(Prefix + "rollbackSDNCResponse") + String rollbackSDNCReturnInnerCode = "" + SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this) + rollbackSDNCResponse = rollbackSDNCResponse.replace('$', '').replace('<?xml version="1.0" encoding="UTF-8"?>', "") + if (rollbackSDNCReturnCode == "200") { + if (utils.nodeExists(rollbackSDNCResponse, "response-code")) { + rollbackSDNCReturnInnerCode = utils.getNodeText(rollbackSDNCResponse, "response-code") + if (rollbackSDNCReturnInnerCode == "200" || rollbackSDNCReturnInnerCode == "" || rollbackSDNCReturnInnerCode == "0") { + rollbackSdncErrorMessages = " + SNDC changeassign rollback completed." + } else { + rollbackSdncErrorMessages = " + SDNC changeassign rollback failed. " + } + } else { + rollbackSdncErrorMessages = " + SNDC changeassign rollback completed." + } + } else { + rollbackSdncErrorMessages = " + SDNC changeassign rollback failed. " + } + msoLogger.debug(" SDNC changeassign rollback Code - " + rollbackSDNCReturnCode) + msoLogger.debug(" SDNC changeassign rollback Response - " + rollbackSDNCResponse) + } + + String statusMessage = "" + int errorCode = 7000 + msoLogger.debug("*** fullRollback? : " + execution.getVariable(Prefix + "fullRollback")) + if (execution.getVariable(Prefix + "fullRollback") == false) { + // original WorkflowException, + WorkflowException wfe = execution.getVariable(Prefix + "WorkflowException") + if (wfe != null) { + // rollback due to failure in DoCreate - Partial rollback + statusMessage = wfe.getErrorMessage() + errorCode = wfe.getErrorCode() + } else { + statusMessage = "See Previous Camunda flows for cause of Error: Undetermined Exception." + errorCode = '7000' + } + + // set if all rolledbacks are successful + if (rollbackNetworkReturnCode == "200" && rollbackSDNCReturnCode == "200") { + execution.setVariable("rolledBack", true) + + } else { + execution.setVariable("rolledBack", false) + + } + + statusMessage = statusMessage + rollbackNetworkErrorMessages + rollbackSdncErrorMessages + msoLogger.debug("Final DoUpdateNetworkInstanceRollback status message: " + statusMessage) + String processKey = getProcessKey(execution); + WorkflowException exception = new WorkflowException(processKey, errorCode, statusMessage); + execution.setVariable("workflowException", exception); + + } else { + // rollback due to failures in Main flow (Macro) - Full rollback + // WorkflowException = null + if (rollbackNetworkReturnCode == "200" && rollbackSDNCReturnCode == "200") { + execution.setVariable("rollbackSuccessful", true) + execution.setVariable("rollbackError", false) + } else { + String exceptionMessage = "Network Update Rollback was not Successful. " + msoLogger.debug(exceptionMessage) + execution.setVariable("rollbackSuccessful", false) + execution.setVariable("rollbackError", true) + exceptionUtil.buildWorkflowException(execution, 7000, exceptionMessage) + throw new BpmnError("MSOWorkflowException") + } + + } + + + } catch (Exception ex) { + execution.setVariable("WorkflowException", null) + String errorMessage = "See Previous Camunda flows for cause of Error: Undetermined Exception." + String exceptionMessage = " Bpmn error encountered in DoUpdateNetworkInstanceRollback flow. validateRollbackResponses() - " + errorMessage + ": " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildWorkflowException(execution, 7000, exceptionMessage) + execution.setVariable("WorkflowException", execution.getVariable("WorkflowException")) + + } + + } + + // ******************************* + // Build Error Section + // ******************************* + + + + public void processJavaException(DelegateExecution execution){ + + execution.setVariable("prefix",Prefix) + + try{ + msoLogger.debug("Caught a Java Exception in " + Prefix) + msoLogger.debug("Started processJavaException Method") + msoLogger.debug("Variables List: " + execution.getVariables()) + execution.setVariable("UnexpectedError", "Caught a Java Lang Exception - " + Prefix) // Adding this line temporarily until this flows error handling gets updated + exceptionUtil.buildWorkflowException(execution, 500, "Caught a Java Lang Exception") + + }catch(Exception e){ + msoLogger.debug("Caught Exception during processJavaException Method: " + e) + execution.setVariable("UnexpectedError", "Exception in processJavaException method - " + Prefix) // Adding this line temporarily until this flows error handling gets updated + exceptionUtil.buildWorkflowException(execution, 500, "Exception in processJavaException method" + Prefix) + } + msoLogger.trace("Completed processJavaException Method in " + Prefix) + } + +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateVfModule.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateVfModule.groovy new file mode 100644 index 0000000000..451e0293ef --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateVfModule.groovy @@ -0,0 +1,1040 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts + +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.onap.so.bpmn.common.scripts.AaiUtil +import org.onap.so.bpmn.common.scripts.CatalogDbUtils +import org.onap.so.bpmn.common.scripts.ExceptionUtil +import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.so.bpmn.common.scripts.NetworkUtils +import org.onap.so.bpmn.common.scripts.SDNCAdapterUtils +import org.onap.so.bpmn.common.scripts.VfModule +import org.onap.so.bpmn.common.scripts.VfModuleBase +import org.onap.so.bpmn.core.UrnPropertiesReader +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.bpmn.core.json.JsonUtils; +import org.onap.so.client.aai.AAIObjectType; +import org.onap.so.client.aai.AAIResourcesClient +import org.onap.so.client.aai.entities.AAIResultWrapper +import org.onap.so.client.aai.entities.uri.AAIUri +import org.onap.so.client.aai.entities.uri.AAIUriFactory; +import org.onap.so.logger.MessageEnum +import org.onap.so.logger.MsoLogger +import org.onap.so.rest.APIResponse +import org.springframework.web.util.UriUtils + +public class DoUpdateVfModule extends VfModuleBase { + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoUpdateVfModule.class); + + ExceptionUtil exceptionUtil = new ExceptionUtil() + JsonUtils jsonUtil = new JsonUtils() + CatalogDbUtils catalog = new CatalogDbUtils() + + /** + * Initialize the flow's variables. + * + * @param execution The flow's execution instance. + */ + public void initProcessVariables(DelegateExecution execution) { + execution.setVariable('prefix', 'DOUPVfMod_') + execution.setVariable('DOUPVfMod_requestInfo', null) + execution.setVariable('DOUPVfMod_serviceInstanceId', null) + execution.setVariable('DOUPVfMod_requestId', null) + execution.setVariable('DOUPVfMod_vnfInputs', null) + execution.setVariable('DOUPVfMod_vnfId', null) + execution.setVariable('DOUPVfMod_vnfName', null) + execution.setVariable('DOUPVfMod_vnfNameFromAAI', null) + execution.setVariable('DOUPVfMod_vfModuleName', null) + execution.setVariable('DOUPVfMod_vfModuleId', null) + execution.setVariable('DOUPVfMod_vnfType', null) + execution.setVariable('DOUPVfMod_asdcServiceModelVersion', null) + execution.setVariable('DOUPVfMod_vfModuleModelName', null) + execution.setVariable('DOUPVfMod_modelCustomizationUuid', null) + execution.setVariable("DOUPVfMod_isBaseVfModule", "false") + execution.setVariable('DOUPVfMod_serviceId', null) + execution.setVariable('DOUPVfMod_aicCloudRegion', null) + execution.setVariable('DOUPVfMod_tenantId', null) + execution.setVariable('DOUPVfMod_volumeGroupId', null) + execution.setVariable("DOUPVfMod_volumeGroupStackId", "") + execution.setVariable('DOUPVfMod_vfModule', null) + execution.setVariable('DOUPVfMod_vnfParams', null) + execution.setVariable("DOUPVfMod_baseVfModuleId", "") + execution.setVariable("DOUPVfMod_baseVfModuleHeatStackId", "") + execution.setVariable('DOUPVfMod_prepareUpdateAAIVfModuleRequest', null) + execution.setVariable('DOUPVfMod_sdncChangeAssignRequest', null) + execution.setVariable('DOUPVfMod_sdncChangeAssignResponse', null) + execution.setVariable('DOUPVfMod_sdncActivateRequest', null) + execution.setVariable('DOUPVfMod_sdncActivateResponse', null) + execution.setVariable('DOUPVfMod_sdncTopologyRequest', null) + execution.setVariable('DOUPVfMod_sdncTopologyResponse', null) + execution.setVariable('DOUPVfMod_vnfAdapterRestRequest', null) + execution.setVariable('DOUPVfMod_updateAAIGenericVnfRequest', null) + execution.setVariable('DOUPVfMod_updateAAIVfModuleRequest', null) + execution.setVariable('DOUPVfMod_skipUpdateGenericVnf', false) + execution.setVariable('DoUpdateVfModuleSuccessIndicator', false) + } + + /** + * Check for missing elements in the received request. + * + * @param execution The flow's execution instance. + */ + public void preProcessRequest(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.preProcessRequest(' + + 'execution=' + execution.getId() + + ')' + + msoLogger.trace('Entered ' + method) + + try { + initProcessVariables(execution) + def xml = getVariable(execution, 'DoUpdateVfModuleRequest') + msoLogger.debug("DoUpdateVfModule request: " + xml) + msoLogger.debug('Received request xml:\n' + xml) + + if (xml == null || xml.isEmpty()) { + // Building Block-type request + + String cloudConfiguration = execution.getVariable("cloudConfiguration") + String vfModuleModelInfo = execution.getVariable("vfModuleModelInfo") + + def serviceModelInfo = execution.getVariable("serviceModelInfo") + msoLogger.debug("serviceModelInfo: " + serviceModelInfo) + String modelInvariantUuid = jsonUtil.getJsonValue(serviceModelInfo, "modelInvariantUuid") + msoLogger.debug("modelInvariantUuid: " + modelInvariantUuid) + def vnfModelInfo = execution.getVariable("vnfModelInfo") + + //tenantId + def tenantId = execution.getVariable("tenantId") + execution.setVariable("DOUPVfMod_tenantId", tenantId) + + //volumeGroupId + def volumeGroupId = execution.getVariable("volumeGroupId") + execution.setVariable("DOUPVfMod_volumeGroupId", volumeGroupId) + + //cloudSiteId + def cloudSiteId = execution.getVariable("lcpCloudRegionId") + execution.setVariable("DOUPVfMod_aicCloudRegion", cloudSiteId) + + msoLogger.debug("cloudSiteId: " + cloudSiteId) + //vnfType + def vnfType = execution.getVariable("vnfType") + execution.setVariable("DOUPVfMod_vnfType", vnfType) + + msoLogger.debug("vnfType: " + vnfType) + //vnfName + def vnfName = execution.getVariable("vnfName") + execution.setVariable("DOUPVfMod_vnfName", vnfName) + + msoLogger.debug("vnfName: " + vnfName) + //vnfId + def vnfId = execution.getVariable("vnfId") + execution.setVariable("DOUPVfMod_vnfId", vnfId) + + msoLogger.debug("vnfId: " + vnfId) + //vfModuleName + def vfModuleName = execution.getVariable("vfModuleName") + execution.setVariable("DOUPVfMod_vfModuleName", vfModuleName) + + msoLogger.debug("vfModuleName: " + vfModuleName) + //vfModuleModelName + def vfModuleModelName = jsonUtil.getJsonValue(vfModuleModelInfo, "modelName") + execution.setVariable("DOUPVfMod_vfModuleModelName", vfModuleModelName) + + msoLogger.debug("vfModuleModelName: " + vfModuleModelName) + //modelCustomizationUuid + def modelCustomizationUuid = jsonUtil.getJsonValue(vfModuleModelInfo, "modelCustomizationUuid") + if (modelCustomizationUuid == null) { + modelCustomizationUuid = "" + } + execution.setVariable("DOUPVfMod_modelCustomizationUuid", modelCustomizationUuid) + + msoLogger.debug("modelCustomizationUuid: " + modelCustomizationUuid) + //vfModuleId + def vfModuleId = execution.getVariable("vfModuleId") + execution.setVariable("DOUPVfMod_vfModuleId", vfModuleId) + msoLogger.debug("vfModuleId: " + vfModuleId) + def requestId = execution.getVariable("msoRequestId") + execution.setVariable("DOUPVfMod_requestId", requestId) + msoLogger.debug("requestId: " + requestId) + // Set mso-request-id to request-id for VNF Adapter interface + execution.setVariable("mso-request-id", requestId) + //serviceId + def serviceId = execution.getVariable("serviceId") + execution.setVariable("DOUPVfMod_serviceId", serviceId) + msoLogger.debug("serviceId: " + serviceId) + //serviceInstanceId + def serviceInstanceId = execution.getVariable("serviceInstanceId") + execution.setVariable("DOUPVfMod_serviceInstanceId", serviceInstanceId) + + msoLogger.debug("serviceInstanceId: " + serviceInstanceId) + //source - HARDCODED + def source = "VID" + execution.setVariable("DOUPVfMod_source", source) + + msoLogger.debug("source: " + source) + //backoutOnFailure + def disableRollback = execution.getVariable("disableRollback") + def backoutOnFailure = true + if (disableRollback != null && disableRollback.equals("true")) { + backoutOnFailure = false + } + execution.setVariable("DOUPVfMod_backoutOnFailure", backoutOnFailure) + msoLogger.debug("backoutOnFailure: " + backoutOnFailure) + //isBaseVfModule + def isBaseVfModule = execution.getVariable("isBaseVfModule") + execution.setVariable("DOUPVfMod_isBaseVfModule", isBaseVfModule) + msoLogger.debug("isBaseVfModule: " + isBaseVfModule) + //asdcServiceModelVersion + def asdcServiceModelVersion = execution.getVariable("asdcServiceModelVersion") + execution.setVariable("DOUPVfMod_asdcServiceModelVersion", asdcServiceModelVersion) + msoLogger.debug("asdcServiceModelVersion: " + asdcServiceModelVersion) + //personaModelId + execution.setVariable("DOUPVfMod_personaModelId", jsonUtil.getJsonValue(vfModuleModelInfo, "modelInvariantUuid")) + //personaModelVersion + execution.setVariable("DOUPVfMod_personaModelVersion", jsonUtil.getJsonValue(vfModuleModelInfo, "modelVersion")) + //Get or Generate UUID + String uuid = execution.getVariable("DOUPVfMod_uuid") + if(uuid == null){ + uuid = UUID.randomUUID() + msoLogger.debug("Generated messageId (UUID) is: " + uuid) + }else{ + msoLogger.debug("Found messageId (UUID) is: " + uuid) + } + //isVidRequest + String isVidRequest = execution.getVariable("isVidRequest") + // default to true + if (isVidRequest == null || isVidRequest.isEmpty()) { + execution.setVariable("isVidRequest", "true") + } + //usePreload + def usePreload = execution.getVariable("usePreload") + execution.setVariable("DOUPVfMod_usePreload", usePreload) + msoLogger.debug("usePreload: " + usePreload) + //globalSubscriberId + String globalSubscriberId = execution.getVariable("globalSubscriberId") + execution.setVariable("DOUPVfMod_globalSubscriberId", globalSubscriberId) + msoLogger.debug("globalSubsrciberId: " + globalSubscriberId) + //vnfQueryPath + String vnfQueryPath = execution.getVariable("vnfQueryPath") + execution.setVariable("DOUPVfMod_vnfQueryPath", vnfQueryPath) + msoLogger.debug("vnfQueryPath: " + vnfQueryPath) + + Map<String,String> vfModuleInputParams = execution.getVariable("vfModuleInputParams") + if (vfModuleInputParams != null) { + execution.setVariable("DOUPVfMod_vnfParamsMap", vfModuleInputParams) + } + //get workload and environment context from parent SI + String environmentContext = "" + String workloadContext ="" + String serviceType ="" + + try{ + String json = catalog.getServiceResourcesByServiceModelInvariantUuidString(execution,modelInvariantUuid ) + serviceType = jsonUtil.getJsonValue(json, "serviceResources.serviceType") + }catch(BpmnError e){ + throw e + } catch (Exception ex){ + String msg = "Exception in preProcessRequest " + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + + try{ + AAIUri serviceInstanceURI = AAIUriFactory.create(AAIObjectType.SERVICE_INSTANCE, globalSubscriberId,serviceType,serviceInstanceId) + AAIResourcesClient aaiRC = new AAIResourcesClient() + AAIResultWrapper aaiRW = aaiRC.get(serviceInstanceURI) + Map<String, Object> aaiJson = aaiRW.asMap() + environmentContext = aaiJson.getOrDefault("environment-context","") + workloadContext = aaiJson.getOrDefault("workload-context","") + + }catch (Exception ex) { + msoLogger.debug("Error retreiving parent service instance information") + } + + execution.setVariable("DCVFM_environmentContext",environmentContext) + execution.setVariable("DCVFM_workloadContext",workloadContext) + } + else { + + def requestInfo = getRequiredNodeXml(execution, xml, 'request-info') + execution.setVariable('DOUPVfMod_requestInfo', requestInfo) + execution.setVariable('DOUPVfMod_requestId', getRequiredNodeText(execution, requestInfo, 'request-id')) + def serviceInstanceId = execution.getVariable('mso-service-instance-id') + if (serviceInstanceId == null) { + serviceInstanceId = '' + } + execution.setVariable('DOUPVfMod_serviceInstanceId', serviceInstanceId) + + def vnfInputs = getRequiredNodeXml(execution, xml, 'vnf-inputs') + execution.setVariable('DOUPVfMod_vnfInputs', vnfInputs) + execution.setVariable('DOUPVfMod_vnfId', getRequiredNodeText(execution, vnfInputs, 'vnf-id')) + execution.setVariable('DOUPVfMod_vfModuleId', getRequiredNodeText(execution, vnfInputs, 'vf-module-id')) + execution.setVariable('DOUPVfMod_vfModuleName', getNodeTextForce(vnfInputs, 'vf-module-name')) + execution.setVariable('DOUPVfMod_vnfType', getNodeTextForce(vnfInputs, 'vnf-type')) + execution.setVariable('DOUPVfMod_vnfName', getNodeTextForce(vnfInputs, 'vnf-name')) + execution.setVariable('DOUPVfMod_asdcServiceModelVersion', getNodeTextForce(vnfInputs, 'asdc-service-model-version')) + execution.setVariable('DOUPVfMod_vfModuleModelName', getRequiredNodeText(execution, vnfInputs, 'vf-module-model-name')) + execution.setVariable('DOUPVfMod_modelCustomizationUuid', getNodeTextForce(vnfInputs, 'model-customization-id')) + execution.setVariable('DOUPVfMod_serviceId', getRequiredNodeText(execution, vnfInputs, 'service-id')) + execution.setVariable('DOUPVfMod_aicCloudRegion', getRequiredNodeText(execution, vnfInputs, 'aic-cloud-region')) + execution.setVariable('DOUPVfMod_tenantId', getRequiredNodeText(execution, vnfInputs, 'tenant-id')) + //isBaseVfModule + def isBaseVfModule = "false" + if (utils.nodeExists(xml, "is-base-vf-module")) { + isBaseVfModule = utils.getNodeText(xml, "is-base-vf-module") + execution.setVariable("DOUPVfMod_isBaseVfModule", isBaseVfModule) + } + msoLogger.debug("isBaseVfModule: " + isBaseVfModule) + + NetworkUtils networkUtils = new NetworkUtils() + def backoutOnFailure = networkUtils.isRollbackEnabled(execution, xml) + execution.setVariable("DOUPVfMod_backoutOnFailure", backoutOnFailure) + + def String vgi = getNodeTextForce(vnfInputs, 'volume-group-id') + execution.setVariable('DOUPVfMod_volumeGroupId', vgi) + + execution.setVariable('DOUPVfMod_vnfParams', utils.getNodeXml(xml, 'vnf-params', false)) + } + + def sdncCallbackUrl = (String) UrnPropertiesReader.getVariable("mso.workflow.sdncadapter.callback",execution) + if (sdncCallbackUrl == null || sdncCallbackUrl.trim().isEmpty()) { + def msg = 'Required variable \'mso.workflow.sdncadapter.callback\' is missing' + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, msg, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, ""); + exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) + } + + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in preProcessRequest(): ' + e.getMessage()) + } + } + + /** + * Prepare a Request for invoking the PrepareUpdateAAIVfModule subflow. This will + * set the orchestration-status to 'pending-update'. + * + * @param execution The flow's execution instance. + */ + public void prepPrepareUpdateAAIVfModule(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.preparePrepareUpdateAAIVfModule(' + + 'execution=' + execution.getId() + + ')' + + msoLogger.trace('Entered ' + method) + + try { + def vnfId = execution.getVariable('DOUPVfMod_vnfId') + def vfModuleId = execution.getVariable('DOUPVfMod_vfModuleId') + def orchestrationStatus = 'pending-update' + + String prepareUpdateAAIVfModuleRequest = """ + <PrepareUpdateAAIVfModuleRequest> + <vnf-id>${MsoUtils.xmlEscape(vnfId)}</vnf-id> + <vf-module-id>${MsoUtils.xmlEscape(vfModuleId)}</vf-module-id> + <orchestration-status>${MsoUtils.xmlEscape(orchestrationStatus)}</orchestration-status> + </PrepareUpdateAAIVfModuleRequest> + """ + prepareUpdateAAIVfModuleRequest = utils.formatXml(prepareUpdateAAIVfModuleRequest) + execution.setVariable('DOUPVfMod_prepareUpdateAAIVfModuleRequest', prepareUpdateAAIVfModuleRequest) + msoLogger.debug("DoUpdateAAIVfModule request: " + prepareUpdateAAIVfModuleRequest) + msoLogger.debug('Request for PrepareUpdateAAIVfModule:\n' + prepareUpdateAAIVfModuleRequest) + + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in preparePrepareUpdateAAIVfModule(): ' + e.getMessage()) + } + } + + /** + * Prepare a Request for invoking the ConfirmVolumeGroupTenant subflow. + * Determine cloud region id for the volume group. + * + * @param execution The flow's execution instance. + */ + public void prepConfirmVolumeGroupTenant(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.prepConfirmVolumeGroupTenant(' + + 'execution=' + execution.getId() + + ')' + + def prefix = execution.getVariable("prefix") + + msoLogger.trace('Entered ' + method) + + try { + String cloudRegion = execution.getVariable(prefix + "aicCloudRegion") + + // Prepare AA&I url + String aai_endpoint = UrnPropertiesReader.getVariable("aai.endpoint", execution) + AaiUtil aaiUtil = new AaiUtil(this) + String aai_uri = aaiUtil.getCloudInfrastructureCloudRegionUri(execution) + String queryCloudRegionRequest = "${aai_endpoint}${aai_uri}/" + cloudRegion + msoLogger.debug("CloudRegion Request: " + queryCloudRegionRequest) + + execution.setVariable(prefix + "queryCloudRegionRequest", queryCloudRegionRequest) + msoLogger.debug(prefix + "queryCloudRegionRequest - " + "\n" + queryCloudRegionRequest) + + cloudRegion = aaiUtil.getAAICloudReqion(execution, queryCloudRegionRequest, "AAI", cloudRegion) + + if ((cloudRegion != "ERROR")) { + if(execution.getVariable(prefix + "queryCloudRegionReturnCode") == "404"){ + execution.setVariable(prefix + "cloudRegionForVolume", "AAIAIC25") + }else{ + execution.setVariable(prefix + "cloudRegionForVolume", cloudRegion) + } + execution.setVariable(prefix + "isCloudRegionGood", true) + } else { + String errorMessage = "AAI Query Cloud Region Unsuccessful. AAI Response Code: " + execution.getVariable(prefix + "queryCloudRegionReturnCode") + msoLogger.debug(errorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, errorMessage) + execution.setVariable(prefix + "isCloudRegionGood", false) + } + msoLogger.debug(" is Cloud Region Good: " + execution.getVariable(prefix + "isCloudRegionGood")) + + } catch(BpmnError b){ + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Rethrowing MSOWorkflowException", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + b); + throw b + }catch (Exception e) { + // try error + String errorMessage = "Bpmn error encountered in CreateVfModule flow. Unexpected Response from AAI - " + e.getMessage() + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, " AAI Query Cloud Region Failed. Exception - " + "\n" + errorMessage, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Exception occured during prepConfirmVolumeGroupTenant(): " + e.getMessage()) + } + msoLogger.trace('Exited ' + method) + + } + + /** + * Prepare a Request for invoking the SDNC Adapter subflow to perform + * a VNF topology 'changeassign' operation. + * + * @param execution The flow's execution instance. + */ + public void prepSDNCTopologyChg(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.prepSDNCTopologyChg(' + + 'execution=' + execution.getId() + + ')' + + msoLogger.trace('Entered ' + method) + + try { + def requestId = execution.getVariable('DOUPVfMod_requestId') + String uuid = execution.getVariable('testReqId') // for junits + if(uuid==null){ + uuid = execution.getVariable("DOUPVfMod_requestId") + "-" + System.currentTimeMillis() + } + def serviceInstanceId = execution.getVariable('DOUPVfMod_serviceInstanceId') + def callbackUrl = (String) UrnPropertiesReader.getVariable("mso.workflow.sdncadapter.callback",execution) + def serviceId = execution.getVariable('DOUPVfMod_serviceId') + def vnfId = execution.getVariable('DOUPVfMod_vnfId') + def vnfType = execution.getVariable('DOUPVfMod_vnfType') + def vfModuleId = execution.getVariable('DOUPVfMod_vfModuleId') + def vfModuleModelName = execution.getVariable('DOUPVfMod_vfModuleModelName') + def VfModule vfModule = (VfModule) execution.getVariable('DOUPVfMod_vfModule') + def vfModuleName = vfModule.getElementText('vf-module-name') + def tenantId = execution.getVariable('DOUPVfMod_tenantId') + def aicCloudRegion = execution.getVariable('DOUPVfMod_aicCloudRegion') + boolean usePreload = execution.getVariable("DOUPVfMod_usePreload") + String usePreloadToSDNC = usePreload ? "Y" : "N" + def modelCustomizationUuid = execution.getVariable("DoUPVfMod_modelCustomizationUuid") + def modelCustomizationUuidString = "" + if (!usePreload) { + modelCustomizationUuidString = "<modelCustomizationUuid>" + modelCustomizationUuid + "</modelCustomizationUuid>" + } + + // Retrieve vnf name from AAI response + def vnfName = execution.getVariable('DOUPVfMod_vnfNameFromAAI') + execution.setVariable('DOUPVfMod_vnfName', vnfName) + + def vnfParamsXml = execution.getVariable('DOUPVfMod_vnfParams') + def vnfNetworks = transformNetworkParamsToVnfNetworks(vnfParamsXml) + + String sdncTopologyRequest = """ + <sdncadapterworkflow:SDNCAdapterWorkflowRequest + xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1" + xmlns:sdncadapter="http://org.onap/workflow/sdnc/adapter/schema/v1"> + <sdncadapter:RequestHeader> + <sdncadapter:RequestId>${MsoUtils.xmlEscape(uuid)}</sdncadapter:RequestId> + <sdncadapter:SvcInstanceId>${MsoUtils.xmlEscape(serviceInstanceId)}</sdncadapter:SvcInstanceId> + <sdncadapter:SvcAction>changeassign</sdncadapter:SvcAction> + <sdncadapter:SvcOperation>vnf-topology-operation</sdncadapter:SvcOperation> + <sdncadapter:CallbackUrl>${MsoUtils.xmlEscape(callbackUrl)}</sdncadapter:CallbackUrl> + </sdncadapter:RequestHeader> + <sdncadapterworkflow:SDNCRequestData> + <request-information> + <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> + <request-action>ChangeVNFActivateRequest</request-action> + <source>PORTAL</source> + <notification-url/> + <order-number/> + <order-version/> + </request-information> + <service-information> + <service-type>${MsoUtils.xmlEscape(serviceId)}</service-type> + <service-instance-id>${MsoUtils.xmlEscape(vnfId)}</service-instance-id> + <subscriber-name>dontcare</subscriber-name> + </service-information> + <vnf-request-information> + <vnf-id>${MsoUtils.xmlEscape(vfModuleId)}</vnf-id> + <vnf-type>${MsoUtils.xmlEscape(vfModuleModelName)}</vnf-type> + <vnf-name>${MsoUtils.xmlEscape(vfModuleName)}</vnf-name> + <generic-vnf-id>${MsoUtils.xmlEscape(vnfId)}</generic-vnf-id> + <generic-vnf-name>${MsoUtils.xmlEscape(vnfName)}</generic-vnf-name> + <generic-vnf-type>${MsoUtils.xmlEscape(vnfType)}</generic-vnf-type> + <tenant>${MsoUtils.xmlEscape(tenantId)}</tenant> + <aic-cloud-region>${MsoUtils.xmlEscape(aicCloudRegion)}</aic-cloud-region> + ${modelCustomizationUuidString} + <use-preload>${MsoUtils.xmlEscape(usePreloadToSDNC)}</use-preload> + ${vnfNetworks} + </vnf-request-information> + </sdncadapterworkflow:SDNCRequestData> + </sdncadapterworkflow:SDNCAdapterWorkflowRequest> + """ + sdncTopologyRequest = utils.formatXml(sdncTopologyRequest) + execution.setVariable('DOUPVfMod_sdncChangeAssignRequest', sdncTopologyRequest) + msoLogger.debug("sdncChangeAssignRequest : " + sdncTopologyRequest) + msoLogger.debug('Request for SDNCAdapter topology/changeassign:\n' + sdncTopologyRequest) + + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in prepSDNCTopologyChg(): ' + e.getMessage()) + } + } + + /** + * Prepare a Request for invoking the SDNC Adapter subflow to perform + * a VNF topology 'query' operation. + * + * @param execution The flow's execution instance. + */ + public void prepSDNCTopologyQuery(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.prepSDNCTopologyQuery(' + + 'execution=' + execution.getId() + + ')' + + msoLogger.trace('Entered ' + method) + + try { + String uuid = execution.getVariable('testReqId') // for junits + if(uuid==null){ + uuid = execution.getVariable("DOUPVfMod_requestId") + "-" + System.currentTimeMillis() + } + def requestId = execution.getVariable('DOUPVfMod_requestId') + def serviceInstanceId = execution.getVariable('DOUPVfMod_serviceInstanceId') + def callbackUrl = (String) UrnPropertiesReader.getVariable("mso.workflow.sdncadapter.callback",execution) + def vfModuleId = execution.getVariable('DOUPVfMod_vfModuleId') + + def svcInstId = "" + if (serviceInstanceId == null || serviceInstanceId.isEmpty()) { + svcInstId = vfModuleId + } + else { + svcInstId = serviceInstanceId + } + + //!!!! TEMPORARY WORKAROUND FOR SDNC REPLICATION ISSUE + sleep(5000) + + String sdncTopologyRequest = """ + <sdncadapterworkflow:SDNCAdapterWorkflowRequest + xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1" + xmlns:sdncadapter="http://org.onap/workflow/sdnc/adapter/schema/v1"> + <sdncadapter:RequestHeader> + <sdncadapter:RequestId>${MsoUtils.xmlEscape(uuid)}</sdncadapter:RequestId> + <sdncadapter:SvcInstanceId>${MsoUtils.xmlEscape(svcInstId)}</sdncadapter:SvcInstanceId> + <sdncadapter:SvcAction>query</sdncadapter:SvcAction> + <sdncadapter:SvcOperation>/VNF-API:vnfs/vnf-list/${vfModuleId}</sdncadapter:SvcOperation> + <sdncadapter:CallbackUrl>${MsoUtils.xmlEscape(callbackUrl)}</sdncadapter:CallbackUrl> + <sdncadapter:MsoAction>mobility</sdncadapter:MsoAction> + </sdncadapter:RequestHeader> + </sdncadapterworkflow:SDNCAdapterWorkflowRequest> + """ + sdncTopologyRequest = utils.formatXml(sdncTopologyRequest) + execution.setVariable('DOUPVfMod_sdncTopologyRequest', sdncTopologyRequest) + msoLogger.debug("sdncTopologyRequest : " + sdncTopologyRequest) + msoLogger.debug('Request for SDNCAdapter query:\n' + sdncTopologyRequest) + + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in prepSDNCTopologyQuery(): ' + e.getMessage()) + } + } + + /** + * Prepare a Request for invoking the VnfAdapterRest subflow. + * + * @param execution The flow's execution instance. + */ + public void prepVnfAdapterRest(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.prepVnfAdapterRest(' + + 'execution=' + execution.getId() + + ')' + + msoLogger.trace('Entered ' + method) + + try { + def requestId = execution.getVariable('DOUPVfMod_requestId') + def serviceInstanceId = execution.getVariable('DOUPVfMod_serviceInstanceId') + def vnfId = execution.getVariable('DOUPVfMod_vnfId') + def vfModuleId = execution.getVariable('DOUPVfMod_vfModuleId') + def vfModuleName = execution.getVariable('DOUPVfMod_vfModuleName') + def vnfInputs = execution.getVariable('DOUPVfMod_vnfInputs') + def tenantId = execution.getVariable('DOUPVfMod_tenantId') + def volumeGroupId = execution.getVariable('DOUPVfMod_volumeGroupId') + def volumeGroupStackId = execution.getVariable('DOUPVfMod_volumeGroupStackId') + def VfModule vfModule = (VfModule) execution.getVariable('DOUPVfMod_vfModule') + def heatStackId = vfModule.getElementText('heat-stack-id') + def cloudId = execution.getVariable('DOUPVfMod_aicCloudRegion') + def vnfType = execution.getVariable('DOUPVfMod_vnfType') + def vnfName = execution.getVariable('DOUPVfMod_vnfName') + def vfModuleModelName = execution.getVariable('DOUPVfMod_vfModuleModelName') + def baseVfModuleId = execution.getVariable("DOUPVfMod_baseVfModuleId") + def baseVfModuleStackId = execution.getVariable("DOUPVfMod_baseVfModuleHeatStackId") + def asdcServiceModelVersion = execution.getVariable('DOUPVfMod_asdcServiceModelVersion') + def modelCustomizationUuid = execution.getVariable('DOUPVfMod_modelCustomizationUuid') + def backoutOnFailure = execution.getVariable("DOUPVfMod_backoutOnFailure") + + def messageId = execution.getVariable('mso-request-id') + '-' + System.currentTimeMillis() + def notificationUrl = createCallbackURL(execution, "VNFAResponse", messageId) + def useQualifiedHostName = UrnPropertiesReader.getVariable("mso.use.qualified.host",execution) + if ('true'.equals(useQualifiedHostName)) { + notificationUrl = utils.getQualifiedHostNameForCallback(notificationUrl) + } + + String environmentContext = execution.getVariable("DOUPVEnvironment_context") + String workloadContext = execution.getVariable("DOUPVWorkload_context") + msoLogger.debug("workloadContext: " + workloadContext) + msoLogger.debug("environmentContext: " + environmentContext) + + Map<String, String> vnfParamsMap = execution.getVariable("DOUPVfMod_vnfParamsMap") + + String sdncGetResponse = execution.getVariable('DOUPVfMod_sdncTopologyResponse') + + String vfModuleParams = buildVfModuleParams(vnfParamsMap, sdncGetResponse, vnfId, vnfName, + vfModuleId, vfModuleName, null, environmentContext, workloadContext) + + + String vnfAdapterRestRequest = """ + <updateVfModuleRequest> + <cloudSiteId>${MsoUtils.xmlEscape(cloudId)}</cloudSiteId> + <tenantId>${MsoUtils.xmlEscape(tenantId)}</tenantId> + <vnfId>${MsoUtils.xmlEscape(vnfId)}</vnfId> + <vfModuleId>${MsoUtils.xmlEscape(vfModuleId)}</vfModuleId> + <vfModuleStackId>${MsoUtils.xmlEscape(heatStackId)}</vfModuleStackId> + <vnfType>${MsoUtils.xmlEscape(vnfType)}</vnfType> + <vnfVersion>${MsoUtils.xmlEscape(asdcServiceModelVersion)}</vnfVersion> + <modelCustomizationUuid>${MsoUtils.xmlEscape(modelCustomizationUuid)}</modelCustomizationUuid> + <vfModuleType>${MsoUtils.xmlEscape(vfModuleModelName)}</vfModuleType> + <volumeGroupId>${MsoUtils.xmlEscape(volumeGroupId)}</volumeGroupId> + <volumeGroupStackId>${MsoUtils.xmlEscape(volumeGroupStackId)}</volumeGroupStackId> + <baseVfModuleId>${MsoUtils.xmlEscape(baseVfModuleId)}</baseVfModuleId> + <baseVfModuleStackId>${MsoUtils.xmlEscape(baseVfModuleStackId)}</baseVfModuleStackId> + <skipAAI>true</skipAAI> + <backout>${MsoUtils.xmlEscape(backoutOnFailure)}</backout> + <failIfExists>false</failIfExists> + <vfModuleParams> + ${vfModuleParams} + </vfModuleParams> + <msoRequest> + <requestId>${MsoUtils.xmlEscape(requestId)}</requestId> + <serviceInstanceId>${MsoUtils.xmlEscape(serviceInstanceId)}</serviceInstanceId> + </msoRequest> + <messageId>${MsoUtils.xmlEscape(messageId)}</messageId> + <notificationUrl>${MsoUtils.xmlEscape(notificationUrl)}</notificationUrl> + </updateVfModuleRequest> + """ + vnfAdapterRestRequest = utils.formatXml(vnfAdapterRestRequest) + execution.setVariable('DOUPVfMod_vnfAdapterRestRequest', vnfAdapterRestRequest) + msoLogger.debug("vnfAdapterRestRequest : " + vnfAdapterRestRequest) + msoLogger.debug('Request for VNFAdapter Rest:\n' + vnfAdapterRestRequest) + + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in prepVnfAdapterRest(): ' + e.getMessage()) + } + } + + /** + * Prepare a Request for invoking the UpdateAAIGenericVnf subflow. + * + * @param execution The flow's execution instance. + */ + public void prepUpdateAAIGenericVnf(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.prepUpdateAAIGenericVnf(' + + 'execution=' + execution.getId() + + ')' + msoLogger.trace('Entered ' + method) + + try { + def vnfId = execution.getVariable('DOUPVfMod_vnfId') + def vnfInputs = execution.getVariable('DOUPVfMod_vnfInputs') + + def personaModelId = utils.getNodeText(vnfInputs, 'vnf-persona-model-id') + def personaModelVersion = utils.getNodeText(vnfInputs, 'vnf-persona-model-version') + if ((personaModelId == null) || (personaModelVersion == null)) { + msoLogger.debug("Skipping update for Generic VNF ' + vnfId + ' because either \'vnf-persona-model-id\' or \'vnf-persona-model-version\' is absent") + execution.setVariable('DOUPVfMod_skipUpdateGenericVnf', true) + } else { + def personaModelIdElement = '<model-invariant-id>' + personaModelId + '</model-invariant-id>' + def personaModelVersionElement = '<model-version-id>' + personaModelVersion + '</model-version-id>' + + String updateAAIGenericVnfRequest = """ + <UpdateAAIGenericVnfRequest> + <vnf-id>${MsoUtils.xmlEscape(vnfId)}</vnf-id> + ${personaModelIdElement} + ${personaModelVersionElement} + </UpdateAAIGenericVnfRequest> + """ + updateAAIGenericVnfRequest = utils.formatXml(updateAAIGenericVnfRequest) + execution.setVariable('DOUPVfMod_updateAAIGenericVnfRequest', updateAAIGenericVnfRequest) + msoLogger.debug("updateAAIGenericVnfRequest : " + updateAAIGenericVnfRequest) + msoLogger.debug('Request for UpdateAAIGenericVnf:\n' + updateAAIGenericVnfRequest) + } + + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in prepUpdateAAIGenericVnf(): ' + e.getMessage()) + } + } + + /** + * Prepare a Request for invoking the UpdateAAIVfModule subflow. + * + * @param execution The flow's execution instance. + */ + public void prepUpdateAAIVfModule(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.prepUpdateAAIVfModule(' + + 'execution=' + execution.getId() + + ')' + + msoLogger.trace('Entered ' + method) + + try { + def vnfId = execution.getVariable('DOUPVfMod_vnfId') + def vfModuleId = execution.getVariable('DOUPVfMod_vfModuleId') + def orchestrationStatus = 'updated' + def vnfInputs = execution.getVariable('DOUPVfMod_vnfInputs') + + def volumeGroupIdElement = '' + def volumeGroupId = execution.getVariable('DOUPVfMod_volumeGroupId') + if (volumeGroupId != null) { + volumeGroupIdElement = '<volume-group-id>' + volumeGroupId + '</volume-group-id>' + } + def personaModelIdElement = '' + def personaModelId = utils.getNodeText(vnfInputs, 'persona-model-id') + if (personaModelId != null) { + personaModelIdElement = '<model-invariant-id>' + personaModelId + '</model-invariant-id>' + } + def personaModelVersionElement = '' + def personaModelVersion = utils.getNodeText(vnfInputs, 'persona-model-version') + if (personaModelVersion != null) { + personaModelVersionElement = '<model-version-id>' + personaModelVersion + '</model-version-id>' + } + def contrailServiceInstanceFqdnElement = '' + def contrailServiceInstanceFqdn = utils.getNodeText(vnfInputs, 'contrail-service-instance-fqdn') + if (contrailServiceInstanceFqdn != null) { + contrailServiceInstanceFqdnElement = '<contrail-service-instance-fqdn>' + contrailServiceInstanceFqdn + '</contrail-service-instance-fqdn>' + } + def personaModelCustomizationIdElement = '' + def modelCustomizationId = execution.getVariable('DOUPVfMod_modelCustomizationUuid') + if (modelCustomizationId != null) { + personaModelCustomizationIdElement = '<model-customization-id>' + modelCustomizationId + '</model-customization-id>' + } + + String updateAAIVfModuleRequest = """ + <UpdateAAIVfModuleRequest> + <vnf-id>${MsoUtils.xmlEscape(vnfId)}</vnf-id> + <vf-module-id>${MsoUtils.xmlEscape(vfModuleId)}</vf-module-id> + <orchestration-status>${MsoUtils.xmlEscape(orchestrationStatus)}</orchestration-status> + ${volumeGroupIdElement} + ${personaModelIdElement} + ${personaModelVersionElement} + ${contrailServiceInstanceFqdnElement} + ${personaModelCustomizationIdElement} + </UpdateAAIVfModuleRequest> + """ + + msoLogger.debug('Unformatted updateAAIVfModuleRequest: ' + updateAAIVfModuleRequest) + updateAAIVfModuleRequest = utils.formatXml(updateAAIVfModuleRequest) + execution.setVariable('DOUPVfMod_updateAAIVfModuleRequest', updateAAIVfModuleRequest) + msoLogger.debug("updateAAIVfModuleRequest : " + updateAAIVfModuleRequest) + msoLogger.debug('Request for UpdateAAIVfModule:\n' + updateAAIVfModuleRequest) + + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in prepUpdateAAIVfModule(): ' + e.getMessage()) + } + } + + /** + * Prepare a Request for invoking the SDNC Adapter subflow to perform + * a VNF topology 'activate' operation. + * + * @param execution The flow's execution instance. + */ + public void prepSDNCTopologyAct(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.prepSDNCTopologyAct(' + + 'execution=' + execution.getId() + + ')' + + msoLogger.trace('Entered ' + method) + + try { + String uuid = execution.getVariable('testReqId') // for junits + if(uuid==null){ + uuid = execution.getVariable("DOUPVfMod_requestId") + "-" + System.currentTimeMillis() + } + def requestId = execution.getVariable('DOUPVfMod_requestId') + def serviceInstanceId = execution.getVariable('DOUPVfMod_serviceInstanceId') + def callbackUrl = (String) UrnPropertiesReader.getVariable("mso.workflow.sdncadapter.callback",execution) + def serviceId = execution.getVariable('DOUPVfMod_serviceId') + def vnfId = execution.getVariable('DOUPVfMod_vnfId') + def vnfName = execution.getVariable('DOUPVfMod_vnfName') + def vnfType = execution.getVariable('DOUPVfMod_vnfType') + def vfModuleId = execution.getVariable('DOUPVfMod_vfModuleId') + def vfModuleModelName = execution.getVariable('DOUPVfMod_vfModuleModelName') + def VfModule vfModule = (VfModule) execution.getVariable('DOUPVfMod_vfModule') + def vfModuleName = vfModule.getElementText('vf-module-name') + def tenantId = execution.getVariable('DOUPVfMod_tenantId') + def aicCloudRegion = execution.getVariable('DOUPVfMod_aicCloudRegion') + + boolean usePreload = execution.getVariable("DOUPVfMod_usePreload") + String usePreloadToSDNC = usePreload ? "Y" : "N" + def modelCustomizationUuid = execution.getVariable("DoUPVfMod_modelCustomizationUuid") + def modelCustomizationUuidString = "" + if (!usePreload) { + modelCustomizationUuidString = "<modelCustomizationUuid>" + modelCustomizationUuid + "</modelCustomizationUuid>" + } + + def vnfParamsXml = execution.getVariable('DOUPVfMod_vnfParams') + def vnfNetworks = transformNetworkParamsToVnfNetworks(vnfParamsXml) + + String sdncTopologyRequest = """ + <sdncadapterworkflow:SDNCAdapterWorkflowRequest + xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1" + xmlns:sdncadapter="http://org.onap/workflow/sdnc/adapter/schema/v1"> + <sdncadapter:RequestHeader> + <sdncadapter:RequestId>${MsoUtils.xmlEscape(uuid)}</sdncadapter:RequestId> + <sdncadapter:SvcInstanceId>${MsoUtils.xmlEscape(serviceInstanceId)}</sdncadapter:SvcInstanceId> + <sdncadapter:SvcAction>activate</sdncadapter:SvcAction> + <sdncadapter:SvcOperation>vnf-topology-operation</sdncadapter:SvcOperation> + <sdncadapter:CallbackUrl>${MsoUtils.xmlEscape(callbackUrl)}</sdncadapter:CallbackUrl> + </sdncadapter:RequestHeader> + <sdncadapterworkflow:SDNCRequestData> + <request-information> + <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> + <request-action>ChangeVNFActivateRequest</request-action> + <source>PORTAL</source> + <notification-url/> + <order-number/> + <order-version/> + </request-information> + <service-information> + <service-type>${MsoUtils.xmlEscape(serviceId)}</service-type> + <service-instance-id>${MsoUtils.xmlEscape(vnfId)}</service-instance-id> + <subscriber-name>dontcare</subscriber-name> + </service-information> + <vnf-request-information> + <vnf-id>${MsoUtils.xmlEscape(vfModuleId)}</vnf-id> + <vnf-type>${MsoUtils.xmlEscape(vfModuleModelName)}</vnf-type> + <vnf-name>${MsoUtils.xmlEscape(vfModuleName)}</vnf-name> + <generic-vnf-id>${MsoUtils.xmlEscape(vnfId)}</generic-vnf-id> + <generic-vnf-name>${MsoUtils.xmlEscape(vnfName)}</generic-vnf-name> + <generic-vnf-type>${MsoUtils.xmlEscape(vnfType)}</generic-vnf-type> + <tenant>${MsoUtils.xmlEscape(tenantId)}</tenant> + <aic-cloud-region>${MsoUtils.xmlEscape(aicCloudRegion)}</aic-cloud-region> + ${modelCustomizationUuidString} + <use-preload>${MsoUtils.xmlEscape(usePreloadToSDNC)}</use-preload> + </vnf-request-information> + </sdncadapterworkflow:SDNCRequestData> + </sdncadapterworkflow:SDNCAdapterWorkflowRequest> + """ + sdncTopologyRequest = utils.formatXml(sdncTopologyRequest) + execution.setVariable('DOUPVfMod_sdncActivateRequest', sdncTopologyRequest) + msoLogger.debug("sdncActivateRequest : " + sdncTopologyRequest) + msoLogger.debug('Request for SDNCAdapter topology/activate:\n' + sdncTopologyRequest) + + + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in prepSDNCTopologyAct(): ' + e.getMessage()) + } + } + + /** + * Log a WorkflowException that has been created. + * + * @param execution The flow's execution instance. + */ + public void handleWorkflowException(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.handleWorkflowException(' + + 'execution=' + execution.getId() + + ')' + + msoLogger.trace('Entered ' + method) + + try { + def WorkflowException workflowException = (WorkflowException) execution.getVariable('WorkflowException') + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, method + ' caught WorkflowException: ' + workflowException.getErrorMessage(), "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, ""); + + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildWorkflowException(execution, 1002, 'Error in handleWorkflowException(): ' + e.getMessage()) + } + } + + public void validateSDNCResponse(DelegateExecution execution, String response, String method){ + + def prefix = execution.getVariable("prefix") + + msoLogger.trace("STARTED ValidateSDNCResponse Process") + + WorkflowException workflowException = execution.getVariable("WorkflowException") + boolean successIndicator = execution.getVariable("SDNCA_SuccessIndicator") + + msoLogger.debug("workflowException: " + workflowException) + + SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this) + sdncAdapterUtils.validateSDNCResponse(execution, response, workflowException, successIndicator) + + msoLogger.debug("SDNCResponse: " + response) + + String sdncResponse = response + if(execution.getVariable(prefix + 'sdncResponseSuccess') == true){ + msoLogger.debug("Received a Good Response from SDNC Adapter for " + method + " SDNC Call. Response is: \n" + sdncResponse) + }else{ + msoLogger.debug("Received a BAD Response from SDNC Adapter for " + method + " SDNC Call.") + throw new BpmnError("MSOWorkflowException") + } + msoLogger.trace("COMPLETED ValidateSDNCResponse Process") + } + + /** + * Using the received vnfId and vfModuleId, query AAI to get the corresponding VNF info. + * A 200 response is expected with the VNF info in the response body. Will find out the base module info. + * + * @param execution The flow's execution instance. + */ + public void queryAAIVfModule(DelegateExecution execution) { + + def method = getClass().getSimpleName() + '.getVfModule(' + + 'execution=' + execution.getId() + + ')' + msoLogger.trace('Entered ' + method) + + try { + def vnfId = execution.getVariable('DOUPVfMod_vnfId') + def vfModuleId = execution.getVariable('DOUPVfMod_vfModuleId') + + AaiUtil aaiUriUtil = new AaiUtil(this) + String aai_uri = aaiUriUtil.getNetworkGenericVnfUri(execution) + msoLogger.debug('AAI URI is: ' + aai_uri) + + String endPoint = UrnPropertiesReader.getVariable("aai.endpoint", execution) + "${aai_uri}/" + UriUtils.encode(vnfId, "UTF-8") + "?depth=1" + msoLogger.debug("AAI endPoint: " + endPoint) + + try { + def aaiRequestId = UUID.randomUUID().toString() + msoLogger.debug('sending GET to AAI endpoint \'' + endPoint + '\'') + APIResponse response = aaiUriUtil.executeAAIGetCall(execution, endPoint) + msoLogger.debug("createVfModule - invoking httpGet() to AAI") + + def responseData = response.getResponseBodyAsString() + if (responseData != null) { + msoLogger.debug("Received generic VNF data: " + responseData) + + } + + msoLogger.debug("createVfModule - queryAAIVfModule Response: " + responseData) + msoLogger.debug("createVfModule - queryAAIVfModule ResponseCode: " + response.getStatusCode()) + + execution.setVariable('DOUPVfMod_queryAAIVfModuleResponseCode', response.getStatusCode()) + execution.setVariable('DOUPVfMod_queryAAIVfModuleResponse', responseData) + msoLogger.debug('Response code:' + response.getStatusCode()) + msoLogger.debug('Response:' + System.lineSeparator() + responseData) + if (response.getStatusCode() == 200) { + // Parse the VNF record from A&AI to find base module info + msoLogger.debug('Parsing the VNF data to find base module info') + if (responseData != null) { + def vfModulesText = utils.getNodeXml(responseData, "vf-modules") + def xmlVfModules= new XmlSlurper().parseText(vfModulesText) + def vfModules = xmlVfModules.'**'.findAll {it.name() == "vf-module"} + int vfModulesSize = 0 + for (i in 0..vfModules.size()-1) { + def vfModuleXml = groovy.xml.XmlUtil.serialize(vfModules[i]) + def isBaseVfModule = utils.getNodeText(vfModuleXml, "is-base-vf-module") + + if (isBaseVfModule == "true") { + String baseModuleId = utils.getNodeText(vfModuleXml, "vf-module-id") + execution.setVariable("DOUPVfMod_baseVfModuleId", baseModuleId) + msoLogger.debug('Received baseVfModuleId: ' + baseModuleId) + String baseModuleHeatStackId = utils.getNodeText(vfModuleXml, "heat-stack-id") + execution.setVariable("DOUPVfMod_baseVfModuleHeatStackId", baseModuleHeatStackId) + msoLogger.debug('Received baseVfModuleHeatStackId: ' + baseModuleHeatStackId) + } + } + } + } + } catch (Exception ex) { + ex.printStackTrace() + msoLogger.debug('Exception occurred while executing AAI GET:' + ex.getMessage()) + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'AAI GET Failed:' + ex.getMessage()) + } + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in queryAAIVfModule(): ' + e.getMessage()) + } + } + + +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateVnfAndModules.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateVnfAndModules.groovy new file mode 100644 index 0000000000..34a73bd35c --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateVnfAndModules.groovy @@ -0,0 +1,414 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts + +import static org.apache.commons.lang3.StringUtils.*; + +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution; +import org.onap.so.bpmn.common.scripts.AaiUtil +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.onap.so.bpmn.common.scripts.ExceptionUtil +import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.so.bpmn.core.UrnPropertiesReader +import org.onap.so.bpmn.core.domain.ModelInfo +import org.onap.so.bpmn.core.domain.ModuleResource +import org.onap.so.bpmn.core.domain.VnfResource +import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.logger.MessageEnum +import org.onap.so.logger.MsoLogger +import org.onap.so.rest.APIResponse +import org.onap.so.rest.RESTClient +import org.onap.so.rest.RESTConfig +import org.springframework.web.util.UriUtils; + +/** + * This class supports the VID Flow + * with the update of a generic vnf and related VF modules. + */ +class DoUpdateVnfAndModules extends AbstractServiceTaskProcessor { + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoUpdateVnfAndModules.class); + + String Prefix="DUVAM_" + ExceptionUtil exceptionUtil = new ExceptionUtil() + JsonUtils jsonUtil = new JsonUtils() + + /** + * This method gets and validates the incoming + * request. + * + * @param - execution + * + */ + public void preProcessRequest(DelegateExecution execution) { + + execution.setVariable("prefix",Prefix) + msoLogger.trace("STARTED DoUpdateVnfAndModules PreProcessRequest Process") + + try{ + // Get Variables + + String requestId = execution.getVariable("msoRequestId") + execution.setVariable("requestId", requestId) + execution.setVariable("mso-request-id", requestId) + msoLogger.debug("Incoming Request Id is: " + requestId) + + String serviceInstanceId = execution.getVariable("serviceInstanceId") + msoLogger.debug("Incoming Service Instance Id is: " + serviceInstanceId) + + String vnfId = execution.getVariable("vnfId") + msoLogger.debug("Incoming Vnf Id is: " + vnfId) + + String source = "VID" + execution.setVariable("DUVAM_source", source) + msoLogger.debug("Incoming Source is: " + source) + + String sdncVersion = execution.getVariable("sdncVersion") + if (sdncVersion == null) { + sdncVersion = "1702" + } + execution.setVariable("DUVAM_sdncVersion", sdncVersion) + msoLogger.debug("Incoming Sdnc Version is: " + sdncVersion) + + VnfResource vnfResource = (VnfResource) execution.getVariable("vnfResourceDecomposition") + + String vnfModelInfo = execution.getVariable("vnfModelInfo") + String serviceModelInfo = execution.getVariable("serviceModelInfo") + + String serviceId = execution.getVariable("productFamilyId") + execution.setVariable("DUVAM_serviceId", serviceId) + msoLogger.debug("Incoming Service Id is: " + serviceId) + + String modelUuid = jsonUtil.getJsonValue(vnfModelInfo, "modelUuid") + execution.setVariable("DUVAM_modelUuid", modelUuid) + msoLogger.debug("Incoming modelUuid is: " + modelUuid) + + String modelCustomizationUuid = jsonUtil.getJsonValue(vnfModelInfo, "modelCustomizationUuid") + execution.setVariable("DUVAM_modelCustomizationUuid", modelCustomizationUuid) + msoLogger.debug("Incoming Model Customization Uuid is: " + modelCustomizationUuid) + + String cloudSiteId = execution.getVariable("lcpCloudRegionId") + execution.setVariable("DUVAM_cloudSiteId", cloudSiteId) + msoLogger.debug("Incoming Cloud Site Id is: " + cloudSiteId) + + String tenantId = execution.getVariable("tenantId") + execution.setVariable("DUVAM_tenantId", tenantId) + msoLogger.debug("Incoming Tenant Id is: " + tenantId) + + String globalSubscriberId = execution.getVariable("globalSubscriberId") + if (globalSubscriberId == null) { + globalSubscriberId = "" + } + execution.setVariable("DUVAM_globalSubscriberId", globalSubscriberId) + msoLogger.debug("Incoming Global Subscriber Id is: " + globalSubscriberId) + + execution.setVariable("DUVAM_moduleCount", 0) + execution.setVariable("DUVAM_nextModule", 0) + + + }catch(BpmnError b){ + msoLogger.debug("Rethrowing MSOWorkflowException") + throw b + }catch(Exception e){ + msoLogger.debug(" Error Occured in DoUpdateVnfAndModules PreProcessRequest method!" + e.getMessage()) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in DoUpdateVnfAndModules PreProcessRequest") + + } + msoLogger.trace("COMPLETED DoUpdateVnfAndModules PreProcessRequest Process ") + } + + /** + * Using the received vnfId and vfModuleId, query AAI to get the corresponding VNF info. + * A 200 response is expected with the VNF info in the response body. Will find out the base module info. + * + * @param execution The flow's execution instance. + */ + public void queryAAIVfModule(DelegateExecution execution) { + + def method = getClass().getSimpleName() + '.queryAAIVfModule(' + + 'execution=' + execution.getId() + + ')' + msoLogger.trace('Entered ' + method) + + try { + def vnfId = execution.getVariable('vnfId') + + AaiUtil aaiUriUtil = new AaiUtil(this) + String aai_uri = aaiUriUtil.getNetworkGenericVnfUri(execution) + msoLogger.debug('AAI URI is: ' + aai_uri) + + String endPoint = UrnPropertiesReader.getVariable("aai.endpoint", execution) + "${aai_uri}/" + UriUtils.encode(vnfId, "UTF-8") + "?depth=1" + msoLogger.debug("AAI endPoint: " + endPoint) + + try { + RESTConfig config = new RESTConfig(endPoint); + def responseData = '' + def aaiRequestId = UUID.randomUUID().toString() + RESTClient client = new RESTClient(config). + addHeader('X-TransactionId', aaiRequestId). + addHeader('X-FromAppId', 'MSO'). + addHeader('Content-Type', 'application/xml'). + addHeader('Accept','application/xml'); + msoLogger.debug('sending GET to AAI endpoint \'' + endPoint + '\'') + APIResponse response = client.httpGet() + msoLogger.debug("createVfModule - invoking httpGet() to AAI") + + responseData = response.getResponseBodyAsString() + if (responseData != null) { + msoLogger.debug("Received generic VNF data: " + responseData) + + } + + msoLogger.debug("createVfModule - queryAAIVfModule Response: " + responseData) + msoLogger.debug("createVfModule - queryAAIVfModule ResponseCode: " + response.getStatusCode()) + + execution.setVariable('DUVAM_queryAAIVfModuleResponseCode', response.getStatusCode()) + execution.setVariable('DUVAM_queryAAIVfModuleResponse', responseData) + msoLogger.debug('Response code:' + response.getStatusCode()) + msoLogger.debug('Response:' + System.lineSeparator() + responseData) + //Map<String, String>[] vfModules = new HashMap<String,String>[] + def vfModulesList = new ArrayList<Map<String,String>>() + def vfModules = null + def vfModuleBaseEntry = null + if (response.getStatusCode() == 200) { + // Parse the VNF record from A&AI to find base module info + msoLogger.debug('Parsing the VNF data to find base module info') + if (responseData != null) { + def vfModulesText = utils.getNodeXml(responseData, "vf-modules") + msoLogger.debug("vModulesText: " + vfModulesText) + if (vfModulesText != null && !vfModulesText.trim().isEmpty()) { + def xmlVfModules= new XmlSlurper().parseText(vfModulesText) + vfModules = xmlVfModules.'**'.findAll {it.name() == "vf-module"} + execution.setVariable("DUVAM_moduleCount", vfModules.size()) + int vfModulesSize = 0 + for (i in 0..vfModules.size()-1) { + def vfModuleXml = groovy.xml.XmlUtil.serialize(vfModules[i]) + + Map<String, String> vfModuleEntry = new HashMap<String, String>() + def vfModuleId = utils.getNodeText(vfModuleXml, "vf-module-id") + vfModuleEntry.put("vfModuleId", vfModuleId) + def vfModuleName = utils.getNodeText(vfModuleXml, "vf-module-name") + vfModuleEntry.put("vfModuleName", vfModuleName) + def modelInvariantUuid = utils.getNodeText(vfModuleXml, "model-invariant-id") + vfModuleEntry.put("modelInvariantUuid", modelInvariantUuid) + def modelUuid = utils.getNodeText(vfModuleXml, "model-version-id") + vfModuleEntry.put("modelUuid", modelUuid) + def modelCustomizationUuid = utils.getNodeText(vfModuleXml, "model-customization-id") + vfModuleEntry.put("modelCustomizationUuid", modelCustomizationUuid) + + def isBaseVfModule = utils.getNodeText(vfModuleXml, "is-base-vf-module") + vfModuleEntry.put("isBaseVfModule", isBaseVfModule) + + String volumeGroupId = '' + + msoLogger.debug("Next module!") + def vfModuleRelationships = vfModules[i].'**'.findAll {it.name() == 'relationship-data'} + if (vfModuleRelationships.size() > 0) { + for (j in 0..vfModuleRelationships.size()-1) { + if (vfModuleRelationships[j] != null) { + + def relationshipKey = vfModuleRelationships[j].'**'.findAll {it.name() == 'relationship-key'} + + if (relationshipKey[0] == 'volume-group.volume-group-id') { + def relationshipValue = vfModuleRelationships[j].'**'.findAll {it.name() == 'relationship-value'} + volumeGroupId = relationshipValue[0] + break + } + } + } + } + + vfModuleEntry.put("volumeGroupId", volumeGroupId) + msoLogger.debug("volumeGroupId is: " + volumeGroupId) + + // Save base vf module to add it to the start of the list later + if (isBaseVfModule == "true") { + vfModuleBaseEntry = vfModuleEntry + } + else { + vfModulesList.add(vfModuleEntry) + } + } + // Start the list with the base module if any + if (vfModuleBaseEntry != null) { + vfModulesList.add(0, vfModuleBaseEntry) + } + } + + } + } + else { + msoLogger.debug('Response code from AAI GET is: ' + response.getStatusCode()) + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Response code from AAI GET is: ' + response.getStatusCode()) + } + execution.setVariable("DUVAM_vfModules", vfModulesList) + } catch (Exception ex) { + ex.printStackTrace() + msoLogger.debug('Exception occurred while executing AAI GET:' + ex.getMessage()) + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'AAI GET Failed:' + ex.getMessage()) + } + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in queryAAIVfModule(): ' + e.getMessage()) + } + } + + public void prepareNextModuleToUpdate(DelegateExecution execution){ + + execution.setVariable("prefix", Prefix) + msoLogger.trace("STARTED prepareNextModuleToUpdate ") + + try { + int i = execution.getVariable("DUVAM_nextModule") + def vfModules = execution.getVariable("DUVAM_vfModules") + def vfModule = vfModules[i] + + def vfModuleId = vfModule.get("vfModuleId") + execution.setVariable("DUVAM_vfModuleId", vfModuleId) + + def vfModuleName = vfModule.get("vfModuleName") + execution.setVariable("DUVAM_vfModuleName", vfModuleName) + + def isBaseVfModule = vfModule.get("isBaseVfModule") + execution.setVariable("DUVAM_isBaseVfModule", isBaseVfModule) + + String modelInvariantUuid = vfModule.get("modelInvariantUuid") + msoLogger.debug("ModelInvariantUuid: " + modelInvariantUuid) + + def volumeGroupId = vfModule.get("volumeGroupId") + execution.setVariable("DUVAM_volumeGroupId", volumeGroupId) + + execution.setVariable("DUVAM_volumeGroupName", "") + + VnfResource vnfResource = (VnfResource) execution.getVariable("vnfResourceDecomposition") + List<ModuleResource> moduleResources = vnfResource.getVfModules() + + for (j in 0..moduleResources.size()-1) { + ModelInfo modelInfo = moduleResources[j].getModelInfo() + String modelInvariantUuidFromDecomposition = modelInfo.getModelInvariantUuid() + msoLogger.debug("modelInvariantUuidFromDecomposition: " + modelInvariantUuidFromDecomposition) + + if (modelInvariantUuid.equals(modelInvariantUuidFromDecomposition)) { + String vfModuleModelInfo = modelInfo.toJsonString() + String vfModuleModelInfoValue = jsonUtil.getJsonValue(vfModuleModelInfo, "modelInfo") + execution.setVariable("DUVAM_vfModuleModelInfo", vfModuleModelInfoValue) + msoLogger.debug("vfModuleModelInfo: " + vfModuleModelInfoValue) + break + } + + } + + }catch(Exception e){ + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception Occured Processing preProcessAddOnModule. Exception is:\n" + e, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during prepareNextModuleToUpdate Method:\n" + e.getMessage()) + } + msoLogger.trace("COMPLETED prepareNextModuleToUpdate ") + } + + + /** + * Prepare a Request for invoking the UpdateAAIGenericVnf subflow. + * + * @param execution The flow's execution instance. + */ + public void prepUpdateAAIGenericVnf(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.prepUpdateAAIGenericVnf(' + + 'execution=' + execution.getId() + + ')' + + msoLogger.trace('Entered ' + method) + + try { + def vnfId = execution.getVariable('vnfId') + VnfResource vnfResource = (VnfResource) execution.getVariable("vnfResourceDecomposition") + ModelInfo vnfDecompModelInfo = vnfResource.getModelInfo() + String vnfModelInfo = execution.getVariable("vnfModelInfo") + String modelUuid = execution.getVariable("DUVAM_modelUuid") + if (modelUuid == null || modelUuid.isEmpty()) { + modelUuid = vnfDecompModelInfo.getModelUuid() + } + String modelCustomizationUuid = execution.getVariable("DUVAM_modelCustomizationUuid") + if (modelCustomizationUuid == null || modelCustomizationUuid.isEmpty()) { + modelCustomizationUuid = vnfDecompModelInfo.getModelCustomizationUuid() + } + String nfType = vnfResource.getNfType() + String nfTypeString = '' + if (nfType != null && !nfType.isEmpty()) { + nfTypeString = "<nf-type>" + nfType + "</nf-type>" + } + String nfRole = vnfResource.getNfRole() + String nfRoleString = '' + if (nfRole != null && !nfRole.isEmpty()) { + nfRoleString = "<nf-role>" + nfRole + "</nf-role>" + } + String nfFunction = vnfResource.getNfFunction() + String nfFunctionString = '' + if (nfFunction != null && !nfFunction.isEmpty()) { + nfFunctionString = "<nf-function>" + nfFunction + "</nf-function>" + } + String nfNamingCode = vnfResource.getNfNamingCode() + String nfNamingCodeString = '' + if (nfNamingCode != null && !nfNamingCode.isEmpty()) { + nfNamingCodeString = "<nf-naming-code>" + nfNamingCode + "</nf-naming-code>" + } + + String updateAAIGenericVnfRequest = """ + <UpdateAAIGenericVnfRequest> + <vnf-id>${MsoUtils.xmlEscape(vnfId)}</vnf-id> + <model-version-id>${MsoUtils.xmlEscape(modelUuid)}</model-version-id> + <model-customization-id>${MsoUtils.xmlEscape(modelCustomizationUuid)}</model-customization-id> + ${nfTypeString} + ${nfRoleString} + ${nfFunctionString} + ${nfNamingCodeString} + </UpdateAAIGenericVnfRequest> + """ + updateAAIGenericVnfRequest = utils.formatXml(updateAAIGenericVnfRequest) + execution.setVariable('DUVAM_updateAAIGenericVnfRequest', updateAAIGenericVnfRequest) + msoLogger.debug("updateAAIGenericVnfRequest : " + updateAAIGenericVnfRequest) + msoLogger.debug('Request for UpdateAAIGenericVnf:\n' + updateAAIGenericVnfRequest) + + + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in prepUpdateAAIGenericVnf(): ' + e.getMessage()) + } + } + + /** + * APP-C Call - placeholder. + * + * @param execution The flow's execution instance. + */ + public void callAppCf(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.callAppC(' + + 'execution=' + execution.getId() + + ')' + + msoLogger.trace('Entered ' + method) + } +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/HealchCheckActivate.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/HealchCheckActivate.groovy new file mode 100644 index 0000000000..4deb53f0ce --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/HealchCheckActivate.groovy @@ -0,0 +1,59 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts; + +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor; +import org.apache.commons.lang3.* +import org.onap.so.logger.MessageEnum +import org.onap.so.logger.MsoLogger + + + +public class HealthCheckActivate extends AbstractServiceTaskProcessor { + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, HealthCheckActivate.class); + + + /** + * Validates the request message and sets up the workflow. + * @param execution the execution + */ + public void preProcessRequest(DelegateExecution execution) { + + } + + + /** + * Sends the synchronous response back to the API Handler. + * @param execution the execution + */ + public void sendResponse(DelegateExecution execution) { + def status = execution.getVariable("healthyStatus") + def healthcheckmessage = execution.getVariable("healthcheckmessage") + if (status == "true") { + sendWorkflowResponse(execution, 200, healthcheckmessage) + }else{ + sendWorkflowResponse(execution, 503, healthcheckmessage) + } + } + +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/ReplaceVnfInfra.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/ReplaceVnfInfra.groovy new file mode 100644 index 0000000000..8673ee7662 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/ReplaceVnfInfra.groovy @@ -0,0 +1,611 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts + +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.onap.appc.client.lcm.model.Action; +import org.onap.appc.client.lcm.model.Status +import org.onap.so.bpmn.common.scripts.ExceptionUtil +import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.so.bpmn.core.domain.ModelInfo +import org.onap.so.bpmn.core.domain.ServiceDecomposition +import org.onap.so.bpmn.core.domain.VnfResource +import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.client.aai.* +import org.onap.so.client.appc.ApplicationControllerOrchestrator +import org.onap.so.client.appc.ApplicationControllerSupport +import org.onap.so.logger.MessageEnum +import org.onap.so.logger.MsoLogger + +import groovy.json.JsonOutput +import groovy.json.JsonSlurper + +public class ReplaceVnfInfra extends VnfCmBase { + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, ReplaceVnfInfra.class); + + ExceptionUtil exceptionUtil = new ExceptionUtil() + JsonUtils jsonUtils = new JsonUtils() + def prefix = "RPLVnfI_" + + /** + * Initialize the flow's variables. + * + * @param execution The flow's execution instance. + */ + public void initProcessVariables(DelegateExecution execution) { + execution.setVariable('prefix', 'RPLVnfI_') + execution.setVariable('Request', null) + execution.setVariable('requestInfo', null) + execution.setVariable('source', null) + execution.setVariable('vnfInputs', null) + execution.setVariable('tenantId', null) + execution.setVariable('vnfParams', null) + execution.setVariable('controllerType', null) + execution.setVariable('cloudConfiguration', null) + execution.setVariable('ReplaceVnfSuccessIndicator', false) + execution.setVariable('serviceType', null) + execution.setVariable('nfRole', null) + execution.setVariable('currentActivity', 'RPLVnfI') + execution.setVariable('workStep', null) + execution.setVariable('failedActivity', null) + execution.setVariable('errorCode', "0") + execution.setVariable('errorText', null) + execution.setVariable('healthCheckIndex', 1) + execution.setVariable('retainResources', true) + execution.setVariable('productFamilyId', null) + execution.setVariable('healthCheckIndex0', 0) + execution.setVariable('healthCheckIndex1', 1) + execution.setVariable("rollbackSetClosedLoopDisabledFlag", false) + execution.setVariable("rollbackVnfStop", false) + execution.setVariable("rollbackVnfLock", false) + execution.setVariable("rollbackQuiesceTraffic", false) + execution.setVariable("rollbackSetVnfInMaintenanceFlag", false) + execution.setVariable("platform", null) + execution.setVariable("lineOfBusiness", null) + } + + /** + * Check for missing elements in the received request. + * + * @param execution The flow's execution instance. + */ + public void preProcessRequest(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.preProcessRequest(' + + 'execution=' + execution.getId() + + ')' + initProcessVariables(execution) + + msoLogger.trace('Entered ' + method) + + initProcessVariables(execution) + + def incomingRequest = execution.getVariable('bpmnRequest') + + msoLogger.debug("Incoming Infra Request: " + incomingRequest) + try { + def jsonSlurper = new JsonSlurper() + def jsonOutput = new JsonOutput() + Map reqMap = jsonSlurper.parseText(incomingRequest) + msoLogger.debug(" Request is in JSON format.") + + def serviceInstanceId = execution.getVariable('serviceInstanceId') + def vnfId = execution.getVariable('vnfId') + + execution.setVariable('serviceInstanceId', serviceInstanceId) + execution.setVariable("isVidRequest", "true") + execution.setVariable('serviceType', 'Mobility') + execution.setVariable('retainResources', true) + execution.setVariable('disableRollback', true) + execution.setVariable('payload', "") + execution.setVariable('actionLock', Action.Lock) + execution.setVariable('actionUnlock', Action.Unlock) + execution.setVariable('actionHealthCheck', Action.HealthCheck) + execution.setVariable('actionStart', Action.Start) + execution.setVariable('actionStop', Action.Stop) + + def asdcServiceModelVersion = '' + def serviceModelInfo = null + + def relatedInstanceList = reqMap.requestDetails?.relatedInstanceList + + if (relatedInstanceList != null) { + relatedInstanceList.each { + if (it.relatedInstance.modelInfo?.modelType == 'service') { + msoLogger.debug("PROCESSING SERVICE INFO") + asdcServiceModelVersion = it.relatedInstance.modelInfo?.modelVersion + serviceModelInfo = jsonOutput.toJson(it.relatedInstance.modelInfo) + msoLogger.debug("ServiceModelInfo: " + serviceModelInfo) + def modelInvariant = jsonUtils.getJsonValue(serviceModelInfo, "modelInvariantUuid") + msoLogger.debug("modelInvariant: " + modelInvariant) + } + + } + } + + execution.setVariable('asdcServiceModelVersion', asdcServiceModelVersion) + execution.setVariable('serviceModelInfo', serviceModelInfo) + def vnfModelInfo = jsonOutput.toJson(reqMap.requestDetails?.modelInfo) + execution.setVariable('vnfModelInfo', vnfModelInfo) + def vnfModelInvariantUuid = jsonUtils.getJsonValue(vnfModelInfo, "modelInvariantUuid") + execution.setVariable('vnfModelInvariantUuid', vnfModelInvariantUuid) + msoLogger.debug("vnfModelInvariantUuid: " + vnfModelInvariantUuid) + + def vnfType = execution.getVariable('vnfType') + execution.setVariable('vnfType', vnfType) + + + def controllerType = reqMap.requestDetails?.requestParameters?.controllerType + execution.setVariable('controllerType', controllerType) + + msoLogger.debug('Controller Type: ' + controllerType) + + def userParams = reqMap.requestDetails?.requestParameters?.userParams + + Map<String, String> userParamsMap = [:] + if (userParams != null) { + userParams.each { userParam -> + userParamsMap.put(userParam.name, userParam.value.toString()) + } + } + + msoLogger.debug('Processed user params: ' + userParamsMap) + + execution.setVariable('vfModuleInputParams', userParamsMap) + + def requestId = execution.getVariable("requestId") + execution.setVariable('msoRequestId', requestId) + msoLogger.debug("requestId is: " + requestId) + + def vnfName = reqMap.requestDetails?.requestInfo?.instanceName ?: null + execution.setVariable('vnfName', vnfName) + + def requestorId = reqMap.requestDetails?.requestInfo?.requestorId ?: null + execution.setVariable('requestorId', requestorId) + + def usePreload = reqMap.requestDetails?.requestParameters?.usePreload + execution.setVariable('usePreload', usePreload) + + def productFamilyId = reqMap.requestDetails?.requestInfo?.productFamilyId ?: null + execution.setVariable('productFamilyId', productFamilyId) + + def cloudConfiguration = jsonOutput.toJson(reqMap.requestDetails?.cloudConfiguration) + execution.setVariable('cloudConfiguration', cloudConfiguration) + def lcpCloudRegionId = jsonUtils.getJsonValue(cloudConfiguration, "lcpCloudRegionId") + execution.setVariable('lcpCloudRegionId', lcpCloudRegionId) + def tenantId = jsonUtils.getJsonValue(cloudConfiguration, "tenantId") + execution.setVariable('tenantId', tenantId) + + def globalSubscriberId = reqMap.requestDetails?.subscriberInfo?.globalSubscriberId ?: '' + execution.setVariable('globalSubscriberId', globalSubscriberId) + + execution.setVariable('sdncVersion', '1702') + + execution.setVariable("ReplaceVnfInfraSuccessIndicator", false) + + + + def source = reqMap.requestDetails?.requestInfo?.source + execution.setVariable("source", source) + + //For Completion Handler & Fallout Handler + String requestInfo = + """<request-info xmlns="http://org.onap/so/infra/vnf-request/v1"> + <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> + <action>REPLACE</action> + <source>${MsoUtils.xmlEscape(source)}</source> + </request-info>""" + + execution.setVariable("requestInfo", requestInfo) + + msoLogger.debug('RequestInfo: ' + execution.getVariable("requestInfo")) + + msoLogger.trace('Exited ' + method) + + } + catch(groovy.json.JsonException je) { + msoLogger.debug(" Request is not in JSON format.") + exceptionUtil.buildAndThrowWorkflowException(execution, 5000, "Invalid request format") + + } + catch(Exception e) { + String restFaultMessage = e.getMessage() + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, " Exception Encountered - " + "\n" + restFaultMessage, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 5000, restFaultMessage) + } + } + + /** + * Prepare and send the sychronous response for this flow. + * + * @param execution The flow's execution instance. + */ + public void sendSynchResponse(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.sendSynchResponse(' + + 'execution=' + execution.getId() + + ')' + + msoLogger.trace('Entered ' + method) + + + try { + def requestInfo = execution.getVariable('requestInfo') + def requestId = execution.getVariable('requestId') + def source = execution.getVariable('source') + def progress = getNodeTextForce(requestInfo, 'progress') + if (progress.isEmpty()) { + progress = '0' + } + def startTime = getNodeTextForce(requestInfo, 'start-time') + if (startTime.isEmpty()) { + startTime = System.currentTimeMillis() + } + + // RESTResponse (for API Handler (APIH) Reply Task) + def vnfId = execution.getVariable("vnfId") + String synchResponse = """{"requestReferences":{"instanceId":"${vnfId}","requestId":"${requestId}"}}""".trim() + + sendWorkflowResponse(execution, 200, synchResponse) + + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in sendResponse(): ' + e.getMessage()) + } + } + + + + /** + * Get VnfResource decomposition object for this VNF. + * + * + * @param execution The flow's execution instance. + */ + public void getVnfResourceDecomposition(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.getVnfResourceDecomposition(' + + 'execution=' + execution.getId() + + ')' + + msoLogger.trace('Entered ' + method) + + try { + ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition") + String vnfModelInvariantUuid = execution.getVariable('vnfModelInvariantUuid') + msoLogger.debug("vnfModelInvariantUuid: " + vnfModelInvariantUuid) + List<VnfResource> vnfResources = serviceDecomposition.getVnfResources() + + for (i in 0..vnfResources.size()-1) { + ModelInfo modelInfo = vnfResources[i].getModelInfo() + String modelInvariantUuidFromDecomposition = modelInfo.getModelInvariantUuid() + msoLogger.debug("modelInvariantUuidFromDecomposition: " + modelInvariantUuidFromDecomposition) + + if (vnfModelInvariantUuid.equals(modelInvariantUuidFromDecomposition)) { + VnfResource vnfResourceDecomposition = vnfResources[i] + execution.setVariable('vnfResourceDecomposition', vnfResourceDecomposition) + def nfRole = vnfResourceDecomposition.getNfRole() + execution.setVariable('nfRole', nfRole) + msoLogger.debug("vnfResourceDecomposition: " + vnfResourceDecomposition.toJsonString()) + break + } + else { + //exception! + } + + } + + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in getVnfResourceDecomposition(): ' + e.getMessage()) + } + } + + /** + * Check if this VNF is already in maintenance in A&AI. + * + * + * @param execution The flow's execution instance. + */ + public void checkIfVnfInMaintInAAI(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.checkIfVnfInMaintInAAI(' + + 'execution=' + execution.getId() + + ')' + + execution.setVariable('errorCode', "0") + execution.setVariable("workStep", "checkIfVnfInMaintInAAI") + execution.setVariable("failedActivity", "AAI") + msoLogger.trace('Entered ' + method) + + try { + def transactionLoggingUuid = UUID.randomUUID().toString() + AAIRestClientImpl client = new AAIRestClientImpl() + AAIValidatorImpl aaiValidator = new AAIValidatorImpl() + aaiValidator.setClient(client) + def vnfId = execution.getVariable("vnfId") + boolean isInMaint = aaiValidator.isVNFLocked(vnfId, transactionLoggingUuid) + msoLogger.debug("isInMaint result: " + isInMaint) + execution.setVariable('isVnfInMaintenance', isInMaint) + + if (isInMaint) { + execution.setVariable("errorCode", "1003") + execution.setVariable("errorText", "VNF is in maintenance in A&AI") + } + + + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + execution.setVariable("errorCode", "1002") + execution.setVariable("errorText", e.getMessage()) + //exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in checkIfVnfInMaintInAAI(): ' + e.getMessage()) + } + } + + + /** + * Check if this VNF's pservers are locked in A&AI. + * + * + * @param execution The flow's execution instance. + */ + public void checkIfPserversInMaintInAAI(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.checkIfPserversInMaintInAAI(' + + 'execution=' + execution.getId() + + ')' + + execution.setVariable('errorCode', "0") + msoLogger.trace('Entered ' + method) + execution.setVariable("workStep", "checkIfPserversInMaintInAAI") + execution.setVariable("failedActivity", "AAI") + + try { + def transactionLoggingUuid = UUID.randomUUID().toString() + AAIRestClientImpl client = new AAIRestClientImpl() + AAIValidatorImpl aaiValidator = new AAIValidatorImpl() + aaiValidator.setClient(client) + def vnfId = execution.getVariable("vnfId") + boolean areLocked = aaiValidator.isPhysicalServerLocked(vnfId, transactionLoggingUuid) + msoLogger.debug("areLocked result: " + areLocked) + execution.setVariable('arePserversLocked', areLocked) + + if (areLocked) { + execution.setVariable("errorCode", "1003") + execution.setVariable("errorText", "pServers are locked in A&AI") + } + + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + execution.setVariable("errorCode", "1002") + execution.setVariable("errorText", e.getMessage()) + //exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in checkIfPserversInMaintInAAI(): ' + e.getMessage()) + } + } + + /** + * Set inMaint flag for this VNF to the specified value in A&AI. + * + * + * @param execution The flow's execution instance. + * @param inMaint The boolean value of the flag to set + */ + public void setVnfInMaintFlagInAAI(DelegateExecution execution, boolean inMaint) { + def method = getClass().getSimpleName() + '.setVnfInMaintFlagInAAI(' + + 'execution=' + execution.getId() + + ')' + + execution.setVariable('errorCode', "0") + msoLogger.trace('Entered ' + method) + if (inMaint) { + execution.setVariable("workStep", "setVnfInMaintFlagInAAI") + } + else { + execution.setVariable("workStep", "unsetVnfInMaintFlagInAAI") + } + execution.setVariable("failedActivity", "AAI") + + try { + def transactionLoggingUuid = UUID.randomUUID().toString() + AAIRestClientImpl client = new AAIRestClientImpl() + AAIUpdatorImpl aaiUpdator = new AAIUpdatorImpl() + aaiUpdator.setClient(client) + def vnfId = execution.getVariable("vnfId") + if (inMaint) { + aaiUpdator.updateVnfToLocked(vnfId, transactionLoggingUuid) + execution.setVariable("rollbackSetVnfInMaintenanceFlag", true) + } + else { + aaiUpdator.updateVnfToUnLocked(vnfId, transactionLoggingUuid) + } + + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + execution.setVariable("errorCode", "1002") + execution.setVariable("errorText", e.getMessage()) + //exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in setVnfInMaintFlagInAAI(): ' + e.getMessage()) + } + } + + /** + * Call APP-C client to execute specified APP-C command for this VNF. + * + * + * @param execution The flow's execution instance. + * @param action The action to take in APP-C. + */ + public void runAppcCommand(DelegateExecution execution, Action action) { + def method = getClass().getSimpleName() + '.runAppcCommand(' + + 'execution=' + execution.getId() + + ')' + + execution.setVariable('errorCode', "0") + msoLogger.trace('Entered ' + method) + + try { + msoLogger.debug("Running APP-C action: " + action.toString()) + String vnfId = execution.getVariable('vnfId') + String msoRequestId = execution.getVariable('requestId') + execution.setVariable('msoRequestId', msoRequestId) + execution.setVariable("failedActivity", "APP-C") + execution.setVariable("workStep", action.toString() + "VNF") + + ApplicationControllerOrchestrator appcClient = new ApplicationControllerOrchestrator() + Status appcStatus = null + switch(action) { + case Action.Lock: + execution.setVariable('workStep', "LockVNF") + appcStatus = appcClient.runCommand(Action.Lock,msoRequestId,vnfId,null) + break + case Action.Unlock: + execution.setVariable('workStep', "UnlockVNF") + appcStatus = appcClient.runCommand(Action.Unlock,msoRequestId,vnfId,null) + break + case Action.HealthCheck: + def healthCheckIndex = execution.getVariable('healthCheckIndex') + execution.setVariable('workStep', "HealthCheckVNF" + healthCheckIndex) + execution.setVariable('healthCheckIndex', healthCheckIndex + 1) + appcStatus = appcClient.runCommand(Action.HealthCheck,msoRequestId,vnfId,null) + break + case Action.Start: + execution.setVariable('workStep', "StartVNF") + appcStatus = appcClient.runCommand(Action.Start,msoRequestId,vnfId,null) + break + case Action.Stop: + execution.setVariable('workStep', "StopVNF") + appcStatus = appcClient.runCommand(Action.Stop,msoRequestId,vnfId,null) + break + default: + break + } + msoLogger.debug("Completed AppC request") + int appcCode = appcStatus.getCode() + msoLogger.debug("AppC status code is: " + appcCode) + msoLogger.debug("AppC status message is: " + appcStatus.getMessage()) + if (support.getCategoryOf(appcStatus) == ApplicationControllerSupport.StatusCategory.ERROR) { + execution.setVariable("errorCode", Integer.toString(appcCode)) + execution.setVariable("errorText", appcStatus.getMessage()) + } + + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + execution.setVariable("errorCode", "1002") + execution.setVariable("errorText", e.getMessage()) + } catch (java.lang.NoSuchMethodError e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + execution.setVariable("errorCode", "1002") + execution.setVariable("errorText", e.getMessage()) + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + execution.setVariable("errorCode", "1002") + execution.setVariable("errorText", e.getMessage()) + } + } + + + + /** + * Prepare DoDeleteVnfAndModules call. + * + * + * @param execution The flow's execution instance. + */ + public void prepDoDeleteVnfAndModules(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.prepDoDeleteVnfAndModules(' + + 'execution=' + execution.getId() + + ')' + + execution.setVariable('errorCode', "0") + msoLogger.trace('Entered ' + method) + execution.setVariable("workStep", "doDeleteVnfAndModules") + execution.setVariable("failedActivity", "MSO Delete VNF") + msoLogger.trace('Exited ' + method) + + } + + /** + * Prepare DoCreateVnfAndModules call. + * + * + * @param execution The flow's execution instance. + */ + public void prepDoCreateVnfAndModules(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.prepDoReplaceVnfAndModules(' + + 'execution=' + execution.getId() + + ')' + + execution.setVariable('errorCode', "0") + msoLogger.trace('Entered ' + method) + execution.setVariable("workStep", "doCreateVnfAndModules") + execution.setVariable("failedActivity", "MSO Create VNF") + msoLogger.trace('Exited ' + method) + + } + + + /** + * Handle Abort disposition from RainyDayHandler + * + * @param execution The flow's execution instance. + */ + public void abortProcessing(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.abortProcessing(' + + 'execution=' + execution.getId() + + ')' + + msoLogger.trace('Entered ' + method) + + def errorText = execution.getVariable("errorText") + def errorCode = execution.getVariable("errorCode") + + exceptionUtil.buildAndThrowWorkflowException(execution, errorCode as Integer, errorText) + } + + /** + * Handle Manual disposition from RainyDayHandler + * + * @param execution The flow's execution instance. + */ + public void manualProcessing(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.manualProcessing(' + + 'execution=' + execution.getId() + + ')' + + msoLogger.trace('Entered ' + method) + + def taskId = execution.getVariable("taskId") + + exceptionUtil.buildAndThrowWorkflowException(execution, 2000, "Processing halted - manual task created: " + taskId) + } + + +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/RollbackVnf.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/RollbackVnf.groovy new file mode 100644 index 0000000000..d729c770ca --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/RollbackVnf.groovy @@ -0,0 +1,148 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts + +import groovy.json.JsonOutput + +import groovy.json.JsonSlurper +import groovy.util.Node +import groovy.util.XmlParser; +import groovy.xml.QName + +import java.io.Serializable; +import java.util.UUID; +import org.onap.so.bpmn.common.scripts.ExceptionUtil +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.impl.cmd.AbstractSetVariableCmd +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.onap.so.rest.APIResponse +import org.onap.so.rest.RESTClient +import org.onap.so.rest.RESTConfig +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor; +import org.onap.so.bpmn.common.scripts.VidUtils; +import org.onap.so.bpmn.core.RollbackData +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.bpmn.common.scripts.ExceptionUtil +import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.bpmn.core.domain.ModelInfo +import org.onap.so.bpmn.core.domain.ServiceDecomposition +import org.onap.so.bpmn.core.domain.VnfResource +import org.onap.so.client.aai.* + +import org.onap.so.client.appc.ApplicationControllerClient; +import org.onap.so.client.appc.ApplicationControllerSupport; +import org.onap.so.client.aai.AAIResourcesClient +import org.onap.so.client.aai.entities.AAIResultWrapper +import org.onap.so.client.aai.entities.uri.AAIUri +import org.onap.so.client.aai.entities.uri.AAIUriFactory +import org.onap.appc.client.lcm.model.Action; + +import org.onap.so.logger.MessageEnum +import org.onap.so.logger.MsoLogger + +public class RollbackVnf extends VnfCmBase { + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, RollbackVnf.class); + + ExceptionUtil exceptionUtil = new ExceptionUtil() + JsonUtils jsonUtils = new JsonUtils() + def prefix = "VnfIPU_" + + /** + * Initialize the flow's variables. + * + * @param execution The flow's execution instance. + */ + public void initProcessVariables(DelegateExecution execution) { + execution.setVariable('prefix', 'RVnf_') + + execution.setVariable('rollbackSuccessful', false) + execution.setVariable('currentActivity', 'RVnf') + execution.setVariable('workStep', null) + execution.setVariable('failedActivity', null) + execution.setVariable('errorCode', "0") + execution.setVariable('actionUnlock', Action.Unlock) + execution.setVariable('actionStart', Action.Start) + execution.setVariable('actionResumeTraffic', Action.ResumeTraffic) + + } + + /** + * Check for missing elements in the received request. + * + * @param execution The flow's execution instance. + */ + public void preProcessRequest(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.preProcessRequest(' + + 'execution=' + execution.getId() + + ')' + initProcessVariables(execution) + + msoLogger.trace('Entered ' + method) + + initProcessVariables(execution) + + try { + + execution.setVariable("rollbackErrorCode", "0") + + if (execution.getVariable("rollbackSetClosedLoopDisabledFlag") == true) { + msoLogger.debug("Will call setClosedLoopDisabledFlag") + } + + + msoLogger.trace('Exited ' + method) + + } + catch(Exception e) { + String restFaultMessage = e.getMessage() + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, " Exception Encountered - " + "\n" + restFaultMessage, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + execution.setVariable("rollbackErrorCode", "1") + exceptionUtil.buildAndThrowWorkflowException(execution, 5000, restFaultMessage) + } + } + + /** + * Determine success of rollback execution. + * + * @param execution The flow's execution instance. + */ + public void setRollbackResult(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.setRollbackResult(' + + 'execution=' + execution.getId() + + ')' + initProcessVariables(execution) + + msoLogger.trace('Entered ' + method) + + def rollbackErrorCode = execution.getVariable('rollbackErrorCode') + if (rollbackErrorCode == "0") { + execution.setVariable('rollbackSuccessful', true) + msoLogger.debug("rollback successful") + } + else { + execution.setVariable('rollbackSuccessful', false) + msoLogger.debug("rollback unsuccessful") + } + + msoLogger.trace('Exited ' + method) + + } + +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/ScaleCustomE2EServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/ScaleCustomE2EServiceInstance.groovy new file mode 100644 index 0000000000..3a309cf5a2 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/ScaleCustomE2EServiceInstance.groovy @@ -0,0 +1,296 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2018 CMCC. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts + +import static org.apache.commons.lang3.StringUtils.* + +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.onap.so.bpmn.common.scripts.ExceptionUtil +import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.logger.MessageEnum +import org.onap.so.logger.MsoLogger +import org.onap.so.utils.UUIDChecker +import org.springframework.web.util.UriUtils + + +/** + * This groovy class supports the <class>ScaleCustomE2EServiceInstance.bpmn</class> process. + * + */ +public class ScaleCustomE2EServiceInstance extends AbstractServiceTaskProcessor { + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, ScaleCustomE2EServiceInstance.class); + + String Prefix = "CRESI_" + ExceptionUtil exceptionUtil = new ExceptionUtil() + JsonUtils jsonUtil = new JsonUtils() + + public void preProcessRequest(DelegateExecution execution) { + execution.setVariable("prefix", Prefix) + String msg = "" + msoLogger.trace("preProcessRequest() ") + + try { + + String siRequest = execution.getVariable("bpmnRequest") + msoLogger.debug(siRequest) + + String requestId = execution.getVariable("mso-request-id") + execution.setVariable("msoRequestId", requestId) + msoLogger.debug("Input Request:" + siRequest + " reqId:" + requestId) + + String serviceInstanceId = execution.getVariable("serviceInstanceId") + if (isBlank(serviceInstanceId)) { + serviceInstanceId = "NULL".toString() + } + msoLogger.debug("Generated new Service Instance:" + serviceInstanceId) + serviceInstanceId = UriUtils.encode(serviceInstanceId, "UTF-8") + execution.setVariable("serviceInstanceId", serviceInstanceId) + + // service instance ID is also service ID + execution.setVariable("serviceId", serviceInstanceId) + // service instance name + String serviceInstanceName = jsonUtil.getJsonValue(siRequest, "service.serviceInstanceName") + execution.setVariable("serviceInstanceName", serviceInstanceName) + + // service instance name + String serviceType = jsonUtil.getJsonValue(siRequest, "service.serviceType") + execution.setVariable("serviceType", serviceType) + + // operationa ID (key) + //String operationKey = UUIDChecker.generateUUID(msoLogger) + String operationId = jsonUtil.getJsonValue(siRequest, "operationId") + execution.setVariable("operationId", operationId) + msoLogger.debug("Input Request:" + siRequest + " operationId:" + operationId) + + + String resources = jsonUtil.getJsonValue(siRequest, "service.resources") + execution.setVariable("resources", resources) + + // node template UUID + String nodeTemplateUUID = UUIDChecker.generateUUID(msoLogger) + execution.setVariable("nodeTemplateUUID", nodeTemplateUUID) + + //subscriberInfo + String globalSubscriberId = jsonUtil.getJsonValue(siRequest, "service.globalSubscriberId") + if (isBlank(globalSubscriberId)) { + msg = "Input globalSubscriberId' is null" + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } else { + execution.setVariable("globalSubscriberId", globalSubscriberId) + } + + String requestDescription = "request description for test" + execution.setVariable("requestDescription", requestDescription) + execution.setVariable("URN_mso_adapters_openecomp_db_endpoint","http://mso.mso.testlab.openecomp.org:8080/dbadapters/RequestsDbAdapter") + + } catch (BpmnError e) { + throw e; + } catch (Exception ex) { + msg = "Exception in preProcessRequest " + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.trace("Exit preProcessRequest ") + } + + public void sendSyncResponse(DelegateExecution execution) { + msoLogger.trace("sendSyncResponse ") + + try { + String operationId = execution.getVariable("operationId") + String serviceInstanceId = execution.getVariable("serviceInstanceId") + // RESTResponse for API Handler (APIH) Reply Task + String scaleServiceRestRequest = """{"operationId":"${operationId}"}""".trim() + msoLogger.debug(" sendSyncResponse to APIH:" + "\n" + scaleServiceRestRequest) + sendWorkflowResponse(execution, 202, scaleServiceRestRequest) + execution.setVariable("sentSyncResponse", true) + + } catch (Exception ex) { + String msg = "Exceptuion in sendSyncResponse:" + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.trace("Exit sendSyncResopnse ") + } + + + public void sendSyncError(DelegateExecution execution) { + msoLogger.trace("sendSyncError ") + + try { + String errorMessage = "" + if (execution.getVariable("WorkflowException") instanceof WorkflowException) { + WorkflowException wfe = execution.getVariable("WorkflowException") + errorMessage = wfe.getErrorMessage() + } else { + errorMessage = "Sending Sync Error." + } + + String buildworkflowException = + """<aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1"> + <aetgt:ErrorMessage>${MsoUtils.xmlEscape(errorMessage)}</aetgt:ErrorMessage> + <aetgt:ErrorCode>7000</aetgt:ErrorCode> + </aetgt:WorkflowException>""" + + msoLogger.debug(buildworkflowException) + sendWorkflowResponse(execution, 500, buildworkflowException) + + } catch (Exception ex) { + msoLogger.debug(" Sending Sync Error Activity Failed. " + "\n" + ex.getMessage()) + } + + } + + public void prepareCompletionRequest(DelegateExecution execution) { + msoLogger.trace("prepareCompletion ") + + try { + String requestId = execution.getVariable("msoRequestId") + String serviceInstanceId = execution.getVariable("serviceInstanceId") + String source = execution.getVariable("source") + + String msoCompletionRequest = + """<aetgt:MsoCompletionRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:ns="http://org.onap/so/request/types/v1"> + <request-info xmlns="http://org.onap/so/infra/vnf-request/v1"> + <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> + <action>SCALE</action> + <source>${MsoUtils.xmlEscape(source)}</source> + </request-info> + <status-message>Service Instance was scaled successfully.</status-message> + <serviceInstanceId>${MsoUtils.xmlEscape(serviceInstanceId)}</serviceInstanceId> + <mso-bpel-name>ScaleGenericALaCarteServiceInstance</mso-bpel-name> + </aetgt:MsoCompletionRequest>""" + + // Format Response + String xmlMsoCompletionRequest = utils.formatXml(msoCompletionRequest) + + execution.setVariable("CompleteMsoProcessRequest", xmlMsoCompletionRequest) + msoLogger.debug(" Overall SUCCESS Response going to CompleteMsoProcess - " + "\n" + xmlMsoCompletionRequest) + + } catch (Exception ex) { + String msg = " Exception in prepareCompletion:" + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.trace("Exit prepareCompletionRequest ") + } + + public void prepareFalloutRequest(DelegateExecution execution) { + msoLogger.trace("prepareFalloutRequest ") + + try { + WorkflowException wfex = execution.getVariable("WorkflowException") + msoLogger.debug(" Input Workflow Exception: " + wfex.toString()) + String requestId = execution.getVariable("msoRequestId") + String source = execution.getVariable("source") + String requestInfo = + """<request-info xmlns="http://org.onap/so/infra/vnf-request/v1"> + <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> + <action>SCALE</action> + <source>${MsoUtils.xmlEscape(source)}</source> + </request-info>""" + + String falloutRequest = exceptionUtil.processMainflowsBPMNException(execution, requestInfo) + execution.setVariable("falloutRequest", falloutRequest) + } catch (Exception ex) { + msoLogger.debug("Exception prepareFalloutRequest:" + ex.getMessage()) + String errorException = " Bpmn error encountered in ScaleGenericALaCarteServiceInstance flow. FalloutHandlerRequest, buildErrorResponse() - " + ex.getMessage() + String requestId = execution.getVariable("msoRequestId") + String falloutRequest = + """<aetgt:FalloutHandlerRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:ns="http://org.onap/so/request/types/v1" + xmlns:wfsch="http://org.onap/so/workflow/schema/v1"> + <request-info xmlns="http://org.onap/so/infra/vnf-request/v1"> + <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> + <action>SCALE</action> + <source>UUI</source> + </request-info> + <aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1"> + <aetgt:ErrorMessage>${MsoUtils.xmlEscape(errorException)}</aetgt:ErrorMessage> + <aetgt:ErrorCode>7000</aetgt:ErrorCode> + </aetgt:WorkflowException> + </aetgt:FalloutHandlerRequest>""" + + execution.setVariable("falloutRequest", falloutRequest) + } + msoLogger.trace("Exit prepareFalloutRequest ") + } + + + /** + * Init the service Operation Status + */ + public void prepareInitServiceOperationStatus(DelegateExecution execution){ + msoLogger.trace("STARTED prepareInitServiceOperationStatus Process ") + try{ + String serviceId = execution.getVariable("serviceInstanceId") + //String serviceName = execution.getVariable("serviceInstanceName") + String operationId = execution.getVariable("operationId") + String operationType = "SCALE" + String userId = "" + String result = "processing" + String progress = "0" + String reason = "" + String operationContent = "Prepare service scaling" + execution.setVariable("serviceInstanceId", serviceId) + execution.setVariable("operationId", operationId) + execution.setVariable("operationType", operationType) + + def dbAdapterEndpoint = execution.getVariable("URN_mso_adapters_openecomp_db_endpoint") + execution.setVariable("CVFMI_dbAdapterEndpoint", dbAdapterEndpoint) + msoLogger.info("DB Adapter Endpoint is: " + dbAdapterEndpoint) + + String payload = + """<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" + xmlns:ns="http://org.onap.so/requestsdb"> + <soapenv:Header/> + <soapenv:Body> + <ns:updateServiceOperationStatus xmlns:ns="http://org.onap.so/requestsdb"> + <serviceId>${MsoUtils.xmlEscape(serviceId)}</serviceId> + <operationId>${MsoUtils.xmlEscape(operationId)}</operationId> + <serviceName>${MsoUtils.xmlEscape(serviceName)}</serviceName> + <operationType>${MsoUtils.xmlEscape(operationType)}</operationType> + <userId>${MsoUtils.xmlEscape(userId)}</userId> + <result>${MsoUtils.xmlEscape(result)}</result> + <operationContent>${MsoUtils.xmlEscape(operationContent)}</operationContent> + <progress>${MsoUtils.xmlEscape(progress)}</progress> + <reason>${MsoUtils.xmlEscape(reason)}</reason> + </ns:updateServiceOperationStatus> + </soapenv:Body> + </soapenv:Envelope>""" + + payload = utils.formatXml(payload) + execution.setVariable("CVFMI_updateServiceOperStatusRequest", payload) + msoLogger.info("Outgoing updateServiceOperStatusRequest: \n" + payload) + msoLogger.debug("Scale network service updateServiceOperStatusRequest Request: " + payload) + + }catch(Exception e){ + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception Occured Processing prepareInitServiceOperationStatus.", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, e); + execution.setVariable("CVFMI_ErrorResponse", "Error Occurred during prepareInitServiceOperationStatus Method:\n" + e.getMessage()) + } + msoLogger.trace("COMPLETED prepareInitServiceOperationStatus Process ") + } +}
\ No newline at end of file diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/UpdateCustomE2EServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/UpdateCustomE2EServiceInstance.groovy new file mode 100644 index 0000000000..ac8e506e1f --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/UpdateCustomE2EServiceInstance.groovy @@ -0,0 +1,483 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2018 Huawei Technologies Co., Ltd. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts; + +import static org.apache.commons.lang3.StringUtils.*; + +import javax.ws.rs.NotFoundException + +import org.apache.commons.lang3.* +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.json.JSONArray +import org.json.JSONObject +import org.onap.aai.domain.yang.ServiceInstance +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.onap.so.bpmn.common.scripts.ExceptionUtil +import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.bpmn.core.domain.Resource +import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.client.aai.AAIObjectType +import org.onap.so.client.aai.AAIResourcesClient +import org.onap.so.client.aai.entities.AAIResultWrapper +import org.onap.so.client.aai.entities.uri.AAIResourceUri +import org.onap.so.client.aai.entities.uri.AAIUriFactory +import org.springframework.web.util.UriUtils + +import groovy.json.* + +/** + * This groovy class supports the <class>UpdateCustomE2EServiceInstance.bpmn</class> process. + * AlaCarte flow for 1702 ServiceInstance Update + * + */ +public class UpdateCustomE2EServiceInstance extends AbstractServiceTaskProcessor { + String Prefix="UPDSI_" + ExceptionUtil exceptionUtil = new ExceptionUtil() + JsonUtils jsonUtil = new JsonUtils() + + + public void preProcessRequest (DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + execution.setVariable("prefix",Prefix) + String msg = "" + utils.log("INFO", " *** preProcessRequest() *** ", isDebugEnabled) + + try { + + String siRequest = execution.getVariable("bpmnRequest") + utils.logAudit(siRequest) + + String requestId = execution.getVariable("mso-request-id") + execution.setVariable("msoRequestId", requestId) + utils.log("INFO", "Input Request:" + siRequest + " reqId:" + requestId, isDebugEnabled) + + String serviceInstanceId = execution.getVariable("serviceInstanceId") + if (isBlank(serviceInstanceId)) { + msg = "Input serviceInstanceId' is null" + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + + //subscriberInfo for aai + String globalSubscriberId = jsonUtil.getJsonValue(siRequest, "requestDetails.subscriberInfo.globalSubscriberId") + if (isBlank(globalSubscriberId)) { + msg = "Input globalSubscriberId' is null" + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } else { + execution.setVariable("globalSubscriberId", globalSubscriberId) + } + + //requestDetails + execution.setVariable("source", jsonUtil.getJsonValue(siRequest, "requestDetails.requestInfo.source")) + execution.setVariable("serviceInstanceName", jsonUtil.getJsonValue(siRequest, "requestDetails.requestInfo.instanceName")) + execution.setVariable("disableRollback", jsonUtil.getJsonValue(siRequest, "requestDetails.requestInfo.suppressRollback")) + String productFamilyId = jsonUtil.getJsonValue(siRequest, "requestDetails.requestInfo.productFamilyId") + if (isBlank(productFamilyId)) + { + msg = "Input productFamilyId is null" + utils.log("INFO", msg, isDebugEnabled) + } else { + execution.setVariable("productFamilyId", productFamilyId) + } + + //user params + String userParams = jsonUtil.getJsonValue(siRequest, "requestDetails.requestParameters.userParams") + utils.log("INFO", "userParams:" + userParams, isDebugEnabled) + List<String> paramList = jsonUtil.StringArrayToList(execution, userParams) + String uuiRequest = jsonUtil.getJsonValue(paramList.get(0), "UUIRequest") + if (isBlank(uuiRequest)) { + msg = "Input uuiRequest is null" + utils.log("INFO", msg, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } else + { + execution.setVariable("uuiRequest", uuiRequest) + } + + utils.log("INFO", "uuiRequest:\n" + uuiRequest, isDebugEnabled) + + //serviceType for aai + String serviceType = jsonUtil.getJsonValue(uuiRequest, "service.serviceType") + if (isBlank(serviceType)) { + msg = "Input serviceType is null" + utils.log("INFO", msg, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } else { + execution.setVariable("serviceType", serviceType) + } + + // target model info + String modelInvariantUuid = jsonUtil.getJsonValue(uuiRequest, "service.serviceInvariantUuid") + utils.log("INFO","modelInvariantUuid: " + modelInvariantUuid, isDebugEnabled) + execution.setVariable("modelInvariantUuid", modelInvariantUuid) + execution.setVariable("model-invariant-id-target", modelInvariantUuid) + + String modelUuid = jsonUtil.getJsonValue(uuiRequest, "service.serviceUuid") + utils.log("INFO","modelUuid: " + modelUuid, isDebugEnabled) + execution.setVariable("modelUuid", modelUuid) + execution.setVariable("model-version-id-target", modelUuid) + + String serviceModelName = jsonUtil.getJsonValue(uuiRequest, "service.parameters.templateName") + utils.log("INFO","serviceModelName: " + serviceModelName, isDebugEnabled) + if(serviceModelName == null) { + serviceModelName = "" + } + execution.setVariable("serviceModelName", serviceModelName) + + //operationId + String operationId = jsonUtil.getJsonValue(siRequest, "operationId") + if (isBlank(operationId)) { + operationId = UUID.randomUUID().toString() + } + execution.setVariable("operationId", operationId) + execution.setVariable("operationType", "update") + execution.setVariable("hasResourcetoUpdate", false) + + execution.setVariable("URN_mso_adapters_openecomp_db_endpoint","http://mso.mso.testlab.openecomp.org:8080/dbadapters/RequestsDbAdapter") + + } catch (BpmnError e) { + throw e; + } catch (Exception ex){ + msg = "Exception in preProcessRequest " + ex.getMessage() + utils.log("INFO", msg, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + utils.log("INFO"," ***** Exit preProcessRequest *****", isDebugEnabled) + } + + /** + * Gets the service instance and its relationships from aai + */ + public void getServiceInstance(DelegateExecution execution) { + try { + String serviceInstanceId = execution.getVariable('serviceInstanceId') + String globalSubscriberId = execution.getVariable('globalSubscriberId') + String serviceType = execution.getVariable('serviceType') + + AAIResourcesClient resourceClient = new AAIResourcesClient() + AAIResourceUri serviceInstanceUri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, globalSubscriberId, serviceType, serviceInstanceId) + AAIResultWrapper wrapper = resourceClient.get(serviceInstanceUri, NotFoundException.class) + + ServiceInstance si = wrapper.asBean(ServiceInstance.class) + execution.setVariable("serviceInstanceName", si.getServiceInstanceName()) + execution.setVariable("model-invariant-id-original", si.getModelInvariantId()) + execution.setVariable("model-version-id-original", si.getModelVersionId()) + + JSONObject ob = new JSONObject(wrapper.getJson()) + JSONArray ar = ob.getJSONObject("relationship-list").getJSONArray("relationship") + + execution.setVariable("serviceRelationShip", ar.toString()) + + + }catch(BpmnError e) { + throw e; + }catch(NotFoundException e) { + exceptionUtil.buildAndThrowWorkflowException(execution, 404, "Service-instance does not exist AAI") + }catch(Exception ex) { + String msg = "Internal Error in getServiceInstance: " + ex.getMessage() + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + } + + public void preCompareModelVersions(DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + } + + public void postCompareModelVersions(DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + utils.log("DEBUG", " ======== STARTED postCompareModelVersions Process ======== ", isDebugEnabled) + + def hasResourcetoUpdate = false + def hasResourcetoAdd = false + def hasResourcetoDelete = false + List<Resource> addResourceList = execution.getVariable("addResourceList") + List<Resource> delResourceList = execution.getVariable("delResourceList") + + if(addResourceList != null && !addResourceList.isEmpty()) { + hasResourcetoAdd = true + } + + if(delResourceList != null && !delResourceList.isEmpty()) { + hasResourcetoDelete = true + } + + hasResourcetoUpdate = hasResourcetoAdd || hasResourcetoDelete + execution.setVariable("hasResourcetoUpdate", hasResourcetoUpdate) + + utils.log("DEBUG", "======== COMPLETED postCompareModelVersions Process ======== ", isDebugEnabled) + } + + /** + * Init the service Operation Status + */ + public void prepareInitServiceOperationStatus(DelegateExecution execution){ + def isDebugEnabled = execution.getVariable("isDebugLogEnabled") + utils.log("DEBUG", " ======== STARTED prepareInitServiceOperationStatus Process ======== ", isDebugEnabled) + try{ + String serviceId = execution.getVariable("serviceInstanceId") + String operationId = execution.getVariable("operationId") + String operationType = execution.getVariable("operationType") + String userId = "" + String result = "processing" + String progress = "0" + String reason = "" + String operationContent = "Prepare service updating" + utils.log("DEBUG", "Generated new operation for Service Instance serviceId:" + serviceId + " operationId:" + operationId, isDebugEnabled) + serviceId = UriUtils.encode(serviceId,"UTF-8") + execution.setVariable("serviceInstanceId", serviceId) + execution.setVariable("operationId", operationId) + execution.setVariable("operationType", operationType) + + def dbAdapterEndpoint = execution.getVariable("URN_mso_adapters_openecomp_db_endpoint") + execution.setVariable("CVFMI_dbAdapterEndpoint", dbAdapterEndpoint) + utils.log("DEBUG", "DB Adapter Endpoint is: " + dbAdapterEndpoint, isDebugEnabled) + + String payload = + """<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" + xmlns:ns="http://org.onap.so/requestsdb"> + <soapenv:Header/> + <soapenv:Body> + <ns:updateServiceOperationStatus xmlns:ns="http://org.onap.so/requestsdb"> + <serviceId>${MsoUtils.xmlEscape(serviceId)}</serviceId> + <operationId>${MsoUtils.xmlEscape(operationId)}</operationId> + <operationType>${MsoUtils.xmlEscape(operationType)}</operationType> + <userId>${MsoUtils.xmlEscape(userId)}</userId> + <result>${MsoUtils.xmlEscape(result)}</result> + <operationContent>${MsoUtils.xmlEscape(operationContent)}</operationContent> + <progress>${MsoUtils.xmlEscape(progress)}</progress> + <reason>${MsoUtils.xmlEscape(reason)}</reason> + </ns:updateServiceOperationStatus> + </soapenv:Body> + </soapenv:Envelope>""" + + payload = utils.formatXml(payload) + execution.setVariable("CVFMI_updateServiceOperStatusRequest", payload) + utils.log("DEBUG", "Outgoing updateServiceOperStatusRequest: \n" + payload, isDebugEnabled) + utils.logAudit("CreateVfModuleInfra Outgoing updateServiceOperStatusRequest Request: " + payload) + + }catch(Exception e){ + utils.log("ERROR", "Exception Occured Processing prepareInitServiceOperationStatus. Exception is:\n" + e, isDebugEnabled) + execution.setVariable("CVFMI_ErrorResponse", "Error Occurred during prepareInitServiceOperationStatus Method:\n" + e.getMessage()) + } + utils.log("DEBUG", "======== COMPLETED prepareInitServiceOperationStatus Process ======== ", isDebugEnabled) + } + + /** + * Update the service Operation Status + */ + public void preUpdateServiceOperationStatus(DelegateExecution execution){ + def method = getClass().getSimpleName() + '.preUpdateServiceOperationStatus(' +'execution=' + execution.getId() +')' + def isDebugEnabled = execution.getVariable("isDebugLogEnabled") + utils.log("INFO","Entered " + method, isDebugEnabled) + + try{ + String serviceId = execution.getVariable("serviceInstanceId") + String operationId = execution.getVariable("operationId") + String operationType = execution.getVariable("operationType") + String serviceName = execution.getVariable("serviceInstanceName") + String result = execution.getVariable("operationResult") + String progress = execution.getVariable("progress") + String reason = execution.getVariable("operationReason") + String userId = "" + utils.log("INFO", "progress: " + progress , isDebugEnabled) + + String operationContent = "Prepare service : " + execution.getVariable("operationStatus") + + utils.log("INFO", "Generated new operation for Service Instance serviceId:" + serviceId + " operationId:" + operationId, isDebugEnabled) + serviceId = UriUtils.encode(serviceId,"UTF-8") + execution.setVariable("serviceInstanceId", serviceId) + execution.setVariable("operationId", operationId) + execution.setVariable("operationType", operationType) + + def dbAdapterEndpoint = "http://mso.mso.testlab.openecomp.org:8080/dbadapters/RequestsDbAdapter" + execution.setVariable("CVFMI_dbAdapterEndpoint", dbAdapterEndpoint) + utils.log("INFO", "DB Adapter Endpoint is: " + dbAdapterEndpoint, isDebugEnabled) + + execution.setVariable("URN_mso_openecomp_adapters_db_endpoint","http://mso.mso.testlab.openecomp.org:8080/dbadapters/RequestsDbAdapter") + String payload = + """<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" + xmlns:ns="http://org.onap.so/requestsdb"> + <soapenv:Header/> + <soapenv:Body> + <ns:updateServiceOperationStatus xmlns:ns="http://org.onap.so/requestsdb"> + <serviceId>${MsoUtils.xmlEscape(serviceId)}</serviceId> + <operationId>${MsoUtils.xmlEscape(operationId)}</operationId> + <operationType>${MsoUtils.xmlEscape(operationType)}</operationType> + <userId>${MsoUtils.xmlEscape(userId)}</userId> + <result>${MsoUtils.xmlEscape(result)}</result> + <operationContent>${MsoUtils.xmlEscape(operationContent)}</operationContent> + <progress>${MsoUtils.xmlEscape(progress)}</progress> + <reason>${MsoUtils.xmlEscape(reason)}</reason> + </ns:updateServiceOperationStatus> + </soapenv:Body> + </soapenv:Envelope>""" + + payload = utils.formatXml(payload) + execution.setVariable("CVFMI_updateServiceOperStatusRequest", payload) + utils.log("INFO", "Outgoing preUpdateServiceOperationStatus: \n" + payload, isDebugEnabled) + + + }catch(Exception e){ + utils.log("ERROR", "Exception Occured Processing preUpdateServiceOperationStatus. Exception is:\n" + e, isDebugEnabled) + execution.setVariable("CVFMI_ErrorResponse", "Error Occurred during preUpdateServiceOperationStatus Method:\n" + e.getMessage()) + } + utils.log("INFO", "======== COMPLETED preUpdateServiceOperationStatus Process ======== ", isDebugEnabled) + utils.log("INFO", "Exited " + method, isDebugEnabled) + } + + public void sendSyncResponse (DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + utils.log("INFO", " *** sendSyncResponse *** ", isDebugEnabled) + + try { + String operationId = execution.getVariable("operationId") + def hasResourcetoUpdate = execution.getVariable("hasResourcetoUpdate") + + String updateServiceResp = "" + if(hasResourcetoUpdate) { + // RESTResponse for API Handler (APIH) Reply Task + updateServiceResp = """{"operationId":"${operationId}"}""".trim() + } + else { + updateServiceResp = """{"OperationResult":"No Resource to Add or Delete or Service Instance not found in AAI."}""" + } + + utils.log("INFO", " sendSyncResponse to APIH:" + "\n" + updateServiceResp, isDebugEnabled) + sendWorkflowResponse(execution, 202, updateServiceResp) + execution.setVariable("sentSyncResponse", true) + + } catch (Exception ex) { + String msg = "Exceptuion in sendSyncResponse:" + ex.getMessage() + utils.log("INFO", msg, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + utils.log("INFO"," ***** Exit sendSyncResopnse *****", isDebugEnabled) + } + + public void sendSyncError (DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + utils.log("INFO", " *** sendSyncError *** ", isDebugEnabled) + + try { + String errorMessage = "" + int errorCode = 7000 + if (execution.getVariable("WorkflowException") instanceof WorkflowException) { + WorkflowException wfe = execution.getVariable("WorkflowException") + errorMessage = wfe.getErrorMessage() + errorCode = wfe.getErrorCode() + } else { + errorMessage = "Sending Sync Error." + } + + String buildworkflowException = + """<aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1"> + <aetgt:ErrorMessage>${MsoUtils.xmlEscape(errorMessage)}</aetgt:ErrorMessage> + <aetgt:ErrorCode>${MsoUtils.xmlEscape(errorCode)}</aetgt:ErrorCode> + </aetgt:WorkflowException>""" + + utils.logAudit(buildworkflowException) + sendWorkflowResponse(execution, 500, buildworkflowException) + + } catch (Exception ex) { + utils.log("INFO", " Sending Sync Error Activity Failed. " + "\n" + ex.getMessage(), isDebugEnabled) + } + + } + + public void prepareCompletionRequest (DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + utils.log("INFO", " *** prepareCompletion *** ", isDebugEnabled) + + try { + String requestId = execution.getVariable("msoRequestId") + String serviceInstanceId = execution.getVariable("serviceInstanceId") + String source = execution.getVariable("source") + + String msoCompletionRequest = + """<aetgt:MsoCompletionRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:ns="http://org.onap/so/request/types/v1"> + <request-info xmlns="http://org.onap/so/infra/vnf-request/v1"> + <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> + <action>UPDATE</action> + <source>${MsoUtils.xmlEscape(source)}</source> + </request-info> + <status-message>Service Instance was updated successfully.</status-message> + <serviceInstanceId>${MsoUtils.xmlEscape(serviceInstanceId)}</serviceInstanceId> + <mso-bpel-name>UpdateCustomE2EServiceInstance</mso-bpel-name> + </aetgt:MsoCompletionRequest>""" + + // Format Response + String xmlMsoCompletionRequest = utils.formatXml(msoCompletionRequest) + + execution.setVariable("completionRequest", xmlMsoCompletionRequest) + utils.log("INFO", " Overall SUCCESS Response going to CompleteMsoProcess - " + "\n" + xmlMsoCompletionRequest, isDebugEnabled) + + } catch (Exception ex) { + String msg = " Exception in prepareCompletion:" + ex.getMessage() + utils.log("INFO", msg, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + utils.log("INFO", "*** Exit prepareCompletionRequest ***", isDebugEnabled) + } + + public void prepareFalloutRequest(DelegateExecution execution){ + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + utils.log("INFO", " *** prepareFalloutRequest *** ", isDebugEnabled) + + try { + WorkflowException wfex = execution.getVariable("WorkflowException") + utils.log("INFO", " Input Workflow Exception: " + wfex.toString(), isDebugEnabled) + String requestId = execution.getVariable("msoRequestId") + String source = execution.getVariable("source") + String requestInfo = + """<request-info xmlns="http://org.onap/so/infra/vnf-request/v1"> + <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> + <action>UPDATE</action> + <source>${MsoUtils.xmlEscape(source)}</source> + </request-info>""" + + String falloutRequest = exceptionUtil.processMainflowsBPMNException(execution, requestInfo) + execution.setVariable("falloutRequest", falloutRequest) + } catch (Exception ex) { + utils.log("INFO", "Exception prepareFalloutRequest:" + ex.getMessage(), isDebugEnabled) + String errorException = " Bpmn error encountered in UpdateCustomE2EServiceInstance flow. FalloutHandlerRequest, buildErrorResponse() - " + ex.getMessage() + String requestId = execution.getVariable("msoRequestId") + String falloutRequest = + """<aetgt:FalloutHandlerRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:ns="http://org.onap/so/request/types/v1" + xmlns:wfsch="http://org.onap/so/workflow/schema/v1"> + <request-info xmlns="http://org.onap/so/infra/vnf-request/v1"> + <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> + <action>UPDATE</action> + <source>UUI</source> + </request-info> + <aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1"> + <aetgt:ErrorMessage>${MsoUtils.xmlEscape(errorException)}</aetgt:ErrorMessage> + <aetgt:ErrorCode>7000</aetgt:ErrorCode> + </aetgt:WorkflowException> + </aetgt:FalloutHandlerRequest>""" + + execution.setVariable("falloutRequest", falloutRequest) + } + utils.log("INFO", "*** Exit prepareFalloutRequest ***", isDebugEnabled) + } +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/UpdateNetworkInstance.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/UpdateNetworkInstance.groovy new file mode 100644 index 0000000000..329d58aa58 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/UpdateNetworkInstance.groovy @@ -0,0 +1,403 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts; + +import org.apache.commons.lang3.* +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.onap.so.bpmn.common.scripts.ExceptionUtil +import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.logger.MsoLogger + +import groovy.json.* + +/** + * This groovy class supports the <class>UpdateNetworkInstance.bpmn</class> process. + * + */ +public class UpdateNetworkInstance extends AbstractServiceTaskProcessor { + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, UpdateNetworkInstance.class); + + String Prefix="UPDNI_" + ExceptionUtil exceptionUtil = new ExceptionUtil() + JsonUtils jsonUtil = new JsonUtils() + + public InitializeProcessVariables(DelegateExecution execution){ + + execution.setVariable(Prefix + "source", "") + execution.setVariable(Prefix + "Success", false) + + execution.setVariable(Prefix + "CompleteMsoProcessRequest", "") + execution.setVariable(Prefix + "FalloutHandlerRequest", "") + + } + + + /** + * This method is executed during the preProcessRequest task of the <class>UpdateNetworkInstance.bpmn</class> process. + * @param execution + */ + + // ************************************************** + // Pre or Prepare Request Section + // ************************************************** + /** + * This method is executed during the preProcessRequest task of the <class>UpdateNetworkInstance.bpmn</class> process. + * @param execution + */ + public void preProcessRequest (DelegateExecution execution) { + + execution.setVariable("prefix",Prefix) + + msoLogger.trace("Inside preProcessRequest() of UpdateNetworkInstance Request") + + try { + // initialize flow variables + InitializeProcessVariables(execution) + + String sdncVersion = execution.getVariable("sdncVersion") + if (sdncVersion == null || sdncVersion == "1610") { + // 'a-la-cart' default, sdncVersion = '1610' + execution.setVariable("sdncVersion", "1610") + String bpmnRequest = execution.getVariable("bpmnRequest") + if (bpmnRequest != null) { + String disableRollback = jsonUtil.getJsonValue(bpmnRequest, "requestDetails.requestInfo.suppressRollback") + if (disableRollback != null) { + execution.setVariable("disableRollback", disableRollback) + msoLogger.debug("Received 'suppressRollback': " + disableRollback ) + } else { + execution.setVariable("disableRollback", false) + } + msoLogger.debug(" Set 'disableRollback' : " + execution.getVariable("disableRollback") ) + } else { + String dataErrorMessage = " Invalid 'bpmnRequest' request." + msoLogger.debug(dataErrorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + } + + } else { + // 'macro' TEST ONLY, sdncVersion = '1702' + msoLogger.debug(" \'disableRollback\' : " + execution.getVariable("disableRollback") ) + } + + String requestId = execution.getVariable("msoRequestId") + if (requestId != null) { + execution.setVariable("mso-request-id", requestId) + } else { + requestId = execution.getVariable("mso-request-id") + } + execution.setVariable(Prefix + "requestId", requestId) + + // get/set 'requestId' + if (execution.getVariable("requestId") == null) { + execution.setVariable("requestId", requestId) + } + + //Place holder for additional code. + + // TODO ??? + // userParams??? 1) pre-loads indicator, 2) 'auto-activation' + // Tag/Value parameters + // + // Map: 'networkInputParams': 'auto-activation'' + // Sample format? + // "requestParameters": { + // "userParams": [ + // { + // "name": "someUserParam1", + // "value": "someValue1" + // } + // ] + // } + // + // String userParams = //use json util to extract "userParams"// + // execution.setVariable("networkInputParams", userParams) + // else: execution.setVariable("networkInputParams", null) + // + + } catch (BpmnError e) { + throw e; + + } catch (Exception ex){ + sendSyncError(execution) + // caught exception + String exceptionMessage = "Exception Encountered in UpdateNetworkInstance, PreProcessRequest() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + } + + public void sendSyncResponse (DelegateExecution execution) { + + execution.setVariable("prefix",Prefix) + + msoLogger.trace("Inside sendSyncResponse() of UpdateNetworkInstance") + + try { + String requestId = execution.getVariable("mso-request-id") + String serviceInstanceId = execution.getVariable("serviceInstanceId") + + // RESTResponse (for API Handler (APIH) Reply Task) + String updateNetworkRestRequest = """{"requestReferences":{"instanceId":"${serviceInstanceId}","requestId":"${requestId}"}}""".trim() + + msoLogger.debug(" sendSyncResponse to APIH - " + "\n" + updateNetworkRestRequest) + sendWorkflowResponse(execution, 202, updateNetworkRestRequest) + + } catch (Exception ex) { + String exceptionMessage = "Bpmn error encountered in UpdateNetworkInstance flow. sendSyncResponse() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + } + + } + + + public void getNetworkModelInfo (DelegateExecution execution) { + + execution.setVariable("prefix", Prefix) + + msoLogger.trace("Inside getNetworkModelInfo() of UpdateNetworkInstance") + + try { + + // For Ala-Carte (sdnc = 1610): + // 1. the Network ModelInfo is expected to be sent + // via requestDetails.modelInfo (modelType = network), ex: modelCustomizationId + // 2. the Service ModelInfo is expected to be sent but will be IGNORE + // via requestDetails.relatedInstanceList.relatedInstance.modelInfo (modelType = service) + + } catch (Exception ex) { + sendSyncError(execution) + String exceptionMessage = "Bpmn error encountered in UpdateNetworkInstance flow. getNetworkModelInfo() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + + public void sendSyncError (DelegateExecution execution) { + + execution.setVariable("prefix", Prefix) + + msoLogger.trace("Inside sendSyncError() of UpdateNetworkInstance") + + try { + + String requestId = execution.getVariable("mso-request-id") + String serviceInstanceId = execution.getVariable("serviceInstanceId") + + // REST Error (for API Handler (APIH) Reply Task) + String syncError = """{"requestReferences":{"instanceId":"${serviceInstanceId}","requestId":"${requestId}"}}""".trim() + + sendWorkflowResponse(execution, 500, syncError) + + } catch (Exception ex) { + msoLogger.debug(" Bpmn error encountered in UpdateNetworkInstance flow. sendSyncError() - " + ex.getMessage()) + } + + } + + public void prepareCompletion (DelegateExecution execution) { + + execution.setVariable("prefix",Prefix) + + msoLogger.trace("Inside prepareCompletion() of UpdateNetworkInstance") + + try { + + String requestId = execution.getVariable("mso-request-id") + String source = execution.getVariable(Prefix + "source") + + String msoCompletionRequest = + """<aetgt:MsoCompletionRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:ns="http://org.onap/so/request/types/v1"> + <request-info xmlns="http://org.onap/so/infra/vnf-request/v1"> + <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> + <action>UPDATE</action> + <source>VID</source> + </request-info> + <aetgt:status-message>Network has been updated successfully.</aetgt:status-message> + <aetgt:mso-bpel-name>BPMN Network action: UPDATE</aetgt:mso-bpel-name> + </aetgt:MsoCompletionRequest>""" + + // Format Response + String xmlMsoCompletionRequest = utils.formatXml(msoCompletionRequest) + + // normal path + execution.setVariable(Prefix + "Success", true) + execution.setVariable(Prefix + "CompleteMsoProcessRequest", xmlMsoCompletionRequest) + msoLogger.debug(" Overall SUCCESS Response going to CompleteMsoProcess - " + "\n" + xmlMsoCompletionRequest) + + } catch (Exception ex) { + String exceptionMessage = " Bpmn error encountered in UpdateNetworkInstance flow. prepareCompletion() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + + + } + + + + + // ************************************************** + // Post or Validate Response Section + // ************************************************** + + public void postProcessResponse (DelegateExecution execution) { + + execution.setVariable("prefix", Prefix) + + msoLogger.trace("Inside postProcessResponse() of UpdateNetworkInstance") + + try { + + if (execution.getVariable("CMSO_ResponseCode") == "200") { + execution.setVariable(Prefix + "Success", true) + msoLogger.trace("UpdateNetworkInstance Success ") + // Place holder for additional code. + + } else { + execution.setVariable(Prefix + "Success", false) + msoLogger.trace("UpdateNetworkInstance Failed in CompletionMsoProces flow!. ") + + } + + + } catch (Exception ex) { + String exceptionMessage = " Bpmn error encountered in UpdateNetworkInstance flow. postProcessResponse() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + + } + + + // ******************************* + // Build Error Section + // ******************************* + + public void processRollbackData (DelegateExecution execution) { + + execution.setVariable("prefix", Prefix) + + msoLogger.trace("Inside processRollbackData() of UpdateNetworkInstance") + + try { + //execution.getVariable("orchestrationStatus") + //execution.getVariable("networkId") + //execution.getVariable("networkName") + //networkOutputParams + //rollbackData + //rolledBack + + } catch (Exception ex) { + msoLogger.debug(" Bpmn error encountered in UpdateNetworkInstance flow. callDBCatalog() - " + ex.getMessage()) + } + + } + + // Prepare for FalloutHandler + public void buildErrorResponse (DelegateExecution execution) { + + execution.setVariable("prefix", Prefix) + + msoLogger.trace("Prepare for FalloutHandler. FAILURE - prepare request for sub-process FalloutHandler. ") + + String falloutHandlerRequest = "" + String requestId = execution.getVariable("mso-request-id") + + try { + + WorkflowException wfe = execution.getVariable("WorkflowException") + String errorCode = String.valueOf(wfe.getErrorCode()) + String errorMessage = wfe.getErrorMessage() + falloutHandlerRequest = + """<aetgt:FalloutHandlerRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:ns="http://org.onap/so/request/types/v1" + xmlns:wfsch="http://org.onap/so/workflow/schema/v1"> + <request-info xmlns="http://org.onap/so/infra/vnf-request/v1"> + <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> + <action>UPDATE</action> + <source>VID</source> + </request-info> + <aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1"> + <aetgt:ErrorMessage>${MsoUtils.xmlEscape(errorMessage)}</aetgt:ErrorMessage> + <aetgt:ErrorCode>${MsoUtils.xmlEscape(errorCode)}</aetgt:ErrorCode> + </aetgt:WorkflowException> + </aetgt:FalloutHandlerRequest>""" + + msoLogger.debug(falloutHandlerRequest) + execution.setVariable(Prefix + "FalloutHandlerRequest", falloutHandlerRequest) + msoLogger.debug(" Overall Error Response going to FalloutHandler: " + "\n" + falloutHandlerRequest) + + } catch (Exception ex) { + String errorException = " Bpmn error encountered in UpdateNetworkInstance flow. FalloutHandlerRequest, buildErrorResponse() - " + msoLogger.debug("Exception error in UpdateNetworkInstance flow, buildErrorResponse(): " + ex.getMessage()) + falloutHandlerRequest = + """<aetgt:FalloutHandlerRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:ns="http://org.onap/so/request/types/v1" + xmlns:wfsch="http://org.onap/so/workflow/schema/v1"> + <request-info xmlns="http://org.onap/so/infra/vnf-request/v1"> + <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> + <action>UPDATE</action> + <source>VID</source> + </request-info> + <aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1"> + <aetgt:ErrorMessage>${MsoUtils.xmlEscape(errorException)}</aetgt:ErrorMessage> + <aetgt:ErrorCode>7000</aetgt:ErrorCode> + </aetgt:WorkflowException> + </aetgt:FalloutHandlerRequest>""" + + execution.setVariable(Prefix + "FalloutHandlerRequest", falloutHandlerRequest) + msoLogger.debug(" Overall Error Response going to FalloutHandler: " + "\n" + falloutHandlerRequest) + + } + + } + + public void processJavaException(DelegateExecution execution){ + + execution.setVariable("prefix",Prefix) + try{ + msoLogger.debug("Caught a Java Exception in " + Prefix) + msoLogger.debug("Started processJavaException Method") + msoLogger.debug("Variables List: " + execution.getVariables()) + execution.setVariable("UnexpectedError", "Caught a Java Lang Exception - " + Prefix) // Adding this line temporarily until this flows error handling gets updated + exceptionUtil.buildWorkflowException(execution, 500, "Caught a Java Lang Exception") + + }catch(Exception e){ + msoLogger.debug("Caught Exception during processJavaException Method: " + e) + execution.setVariable("UnexpectedError", "Exception in processJavaException method - " + Prefix) // Adding this line temporarily until this flows error handling gets updated + exceptionUtil.buildWorkflowException(execution, 500, "Exception in processJavaException method" + Prefix) + } + msoLogger.debug("Completed processJavaException Method in " + Prefix) + } + +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/UpdateVfModule.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/UpdateVfModule.groovy new file mode 100644 index 0000000000..b1aaf5ea5f --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/UpdateVfModule.groovy @@ -0,0 +1,326 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts + +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.onap.so.bpmn.common.scripts.ExceptionUtil +import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.logger.MessageEnum +import org.onap.so.logger.MsoLogger + + +public class UpdateVfModule extends AbstractServiceTaskProcessor { + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, UpdateVfModule.class); + + ExceptionUtil exceptionUtil = new ExceptionUtil() + + /** + * Initialize the flow's variables. + * + * @param execution The flow's execution instance. + */ + public void initProcessVariables(DelegateExecution execution) { + execution.setVariable('prefix', 'UPDVfMod_') + execution.setVariable('UPDVfMod_Request', null) + execution.setVariable('UPDVfMod_requestInfo', null) + execution.setVariable('UPDVfMod_requestId', null) + execution.setVariable('UPDVfMod_source', null) + execution.setVariable('UPDVfMod_vnfInputs', null) + execution.setVariable('UPDVfMod_vnfId', null) + execution.setVariable('UPDVfMod_vfModuleId', null) + execution.setVariable('UPDVfMod_tenantId', null) + execution.setVariable('UPDVfMod_volumeGroupId', null) + execution.setVariable('UPDVfMod_vnfParams', null) + execution.setVariable('UPDVfMod_updateInfraRequest', null) + execution.setVariable('UpdateVfModuleSuccessIndicator', false) + } + + /** + * Check for missing elements in the received request. + * + * @param execution The flow's execution instance. + */ + public void preProcessRequest(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.preProcessRequest(' + + 'execution=' + execution.getId() + + ')' + + msoLogger.trace('Entered ' + method) + + try { + initProcessVariables(execution) + String request = validateRequest(execution) + + msoLogger.debug("UpdateVfModule request: " + request) + def requestInfo = getRequiredNodeXml(execution, request, 'request-info') + execution.setVariable('UPDVfMod_requestInfo', requestInfo) + execution.setVariable('UPDVfMod_requestId', getRequiredNodeText(execution, requestInfo, 'request-id')) + execution.setVariable('UPDVfMod_source', getNodeTextForce(requestInfo, 'source')) + + def vnfInputs = getRequiredNodeXml(execution, request, 'vnf-inputs') + execution.setVariable('UPDVfMod_vnfInputs', vnfInputs) + execution.setVariable('UPDVfMod_vnfId', getRequiredNodeText(execution, vnfInputs, 'vnf-id')) + execution.setVariable('UPDVfMod_vfModuleId', getRequiredNodeText(execution, vnfInputs, 'vf-module-id')) + execution.setVariable('UPDVfMod_tenantId', getRequiredNodeText(execution, vnfInputs, 'tenant-id')) + execution.setVariable('UPDVfMod_volumeGroupId', getNodeTextForce(vnfInputs, 'volume-group-id')) + + def vnfParams = utils.getNodeXml(request, 'vnf-params') + execution.setVariable('UPDVfMod_vnfParams', vnfParams) + + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in preProcessRequest(): ' + e.getMessage()) + } + } + + /** + * Prepare and send the synchronous response for this flow. + * + * @param execution The flow's execution instance. + */ + public void sendSynchResponse(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.sendSynchResponse(' + + 'execution=' + execution.getId() + + ')' + + msoLogger.trace('Entered ' + method) + + try { + def requestInfo = execution.getVariable('UPDVfMod_requestInfo') + def requestId = execution.getVariable('UPDVfMod_requestId') + def source = execution.getVariable('UPDVfMod_source') + def progress = getNodeTextForce(requestInfo, 'progress') + if (progress.isEmpty()) { + progress = '0' + } + def startTime = getNodeTextForce(requestInfo, 'start-time') + if (startTime.isEmpty()) { + startTime = System.currentTimeMillis() + } + def vnfInputs = execution.getVariable('UPDVfMod_vnfInputs') + + String synchResponse = """ + <vnf-request xmlns="http://org.onap/so/infra/vnf-request/v1"> + <request-info> + <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> + <action>UPDATE_VF_MODULE</action> + <request-status>IN_PROGRESS</request-status> + <progress>${MsoUtils.xmlEscape(progress)}</progress> + <start-time>${MsoUtils.xmlEscape(startTime)}</start-time> + <source>${MsoUtils.xmlEscape(source)}</source> + </request-info> + ${vnfInputs} + </vnf-request> + """ + + synchResponse = utils.formatXml(synchResponse) + sendWorkflowResponse(execution, 200, synchResponse) + + msoLogger.debug("UpdateVfModule Synch Response: " + synchResponse) + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in sendSynchResponse(): ' + e.getMessage()) + } + } + + /** + * Prepare the Request for invoking the DoUpdateVfModule subflow. + * + * NOTE: Currently, the method just logs passing through as the + * incoming Request to this main flow is used as the Request to + * the DoUpdateVfModule subflow. No preparation processing is + * necessary. + * + * @param execution The flow's execution instance. + */ + public void prepDoUpdateVfModule(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.prepDoUpdateVfModule(' + + 'execution=' + execution.getId() + + ')' + + msoLogger.trace('Entered ' + method) + + try { + + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in prepDoUpdateVfModule(): ' + e.getMessage()) + } + } + + /** + * Prepare the Request for updating the DB for this Infra Request. + * + * @param execution The flow's execution instance. + */ + public void prepUpdateInfraRequest(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.prepUpdateInfraRequest(' + + 'execution=' + execution.getId() + + ')' + + msoLogger.trace('Entered ' + method) + + try { + def requestId = execution.getVariable('UPDVfMod_requestId') + def vnfId = execution.getVariable('UPDVfMod_vnfId') + def vfModuleId = execution.getVariable('UPDVfMod_vfModuleId') + def tenantId = execution.getVariable('UPDVfMod_tenantId') + def volumeGroupId = execution.getVariable('UPDVfMod_volumeGroupId') + + String updateInfraRequest = """ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" + xmlns:req="http://org.onap.so/requestsdb"> + <soapenv:Header/> + <soapenv:Body> + <req:updateInfraRequest> + <requestId>${MsoUtils.xmlEscape(requestId)}</requestId> + <lastModifiedBy>BPEL</lastModifiedBy> + <requestStatus>COMPLETE</requestStatus> + <progress>100</progress> + <vnfOutputs> + <vnf-id>${MsoUtils.xmlEscape(vnfId)}</vnf-id> + <vf-module-id>${MsoUtils.xmlEscape(vfModuleId)}</vf-module-id> + <tenant-id>${MsoUtils.xmlEscape(tenantId)}</tenant-id> + <volume-group-id>${MsoUtils.xmlEscape(volumeGroupId)}</volume-group-id> + </vnfOutputs> + </req:updateInfraRequest> + </soapenv:Body> + </soapenv:Envelope> + """ + + updateInfraRequest = utils.formatXml(updateInfraRequest) + execution.setVariable('UPDVfMod_updateInfraRequest', updateInfraRequest) + msoLogger.debug('Request for Update Infra Request:\n' + updateInfraRequest) + + msoLogger.debug("UpdateVfModule Infra Request: " + updateInfraRequest) + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in prepUpdateInfraRequest(): ' + e.getMessage()) + } + } + + /** + * Builds a "CompletionHandler" request and stores it in the specified execution variable. + * + * @param execution the execution + * @param resultVar the execution variable in which the result will be stored + */ + public void completionHandlerPrep(DelegateExecution execution, String resultVar) { + def method = getClass().getSimpleName() + '.completionHandlerPrep(' + + 'execution=' + execution.getId() + + ', resultVar=' + resultVar + + ')' + + msoLogger.trace('Entered ' + method) + + try { + def requestInfo = getVariable(execution, 'UPDVfMod_requestInfo') + + String content = """ + <sdncadapterworkflow:MsoCompletionRequest xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1" + xmlns:reqtype="http://org.onap/so/request/types/v1"> + ${requestInfo} + <sdncadapterworkflow:mso-bpel-name>MSO_ACTIVATE_BPEL</sdncadapterworkflow:mso-bpel-name> + </sdncadapterworkflow:MsoCompletionRequest> + """ + + content = utils.formatXml(content) + msoLogger.debug(resultVar + ' = ' + System.lineSeparator() + content) + execution.setVariable(resultVar, content) + + msoLogger.debug("UpdateVfModule CompletionHandler Request: " + content) + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 2000, 'Internal Error') + } + } + + /** + * Builds a "FalloutHandler" request and stores it in the specified execution variable. + * + * @param execution the execution + * @param resultVar the execution variable in which the result will be stored + */ + public void falloutHandlerPrep(DelegateExecution execution, String resultVar) { + def method = getClass().getSimpleName() + '.falloutHandlerPrep(' + + 'execution=' + execution.getId() + + ', resultVar=' + resultVar + + ')' + + msoLogger.trace('Entered ' + method) + + try { + def prefix = execution.getVariable('prefix') + def request = getVariable(execution, prefix+'Request') + def requestInformation = utils.getNodeXml(request, 'request-information', false) + + def WorkflowException workflowException = execution.getVariable("WorkflowException") + def errorResponseCode = workflowException.getErrorCode() + def errorResponseMsg = workflowException.getErrorMessage() + def encErrorResponseMsg = "" + if (errorResponseMsg != null) { + encErrorResponseMsg = errorResponseMsg + } + + String content = """ + <sdncadapterworkflow:FalloutHandlerRequest xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1" + xmlns:reqtype="http://org.onap/so/request/types/v1" + xmlns:msoservtypes="http://org.onap/so/request/types/v1" + xmlns:structuredtypes="http://org.onap/so/structured/types/v1"> + ${requestInformation} + <sdncadapterworkflow:WorkflowException> + <sdncadapterworkflow:ErrorMessage>${MsoUtils.xmlEscape(encErrorResponseMsg)}</sdncadapterworkflow:ErrorMessage> + <sdncadapterworkflow:ErrorCode>${MsoUtils.xmlEscape(errorResponseCode)}</sdncadapterworkflow:ErrorCode> + </sdncadapterworkflow:WorkflowException> + </sdncadapterworkflow:FalloutHandlerRequest> + """ + content = utils.formatXml(content) + msoLogger.debug(resultVar + ' = ' + System.lineSeparator() + content) + execution.setVariable(resultVar, content) + + msoLogger.debug("UpdateVfModule fallOutHandler Request: " + content) + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildWorkflowException(execution, 2000, 'Internal Error') + } + } +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/UpdateVfModuleInfra.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/UpdateVfModuleInfra.groovy new file mode 100644 index 0000000000..416d0d6e60 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/UpdateVfModuleInfra.groovy @@ -0,0 +1,504 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts + +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor; +import org.onap.so.bpmn.common.scripts.ExceptionUtil +import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.logger.MessageEnum +import org.onap.so.logger.MsoLogger + +import groovy.json.JsonOutput +import groovy.json.JsonSlurper + +public class UpdateVfModuleInfra extends AbstractServiceTaskProcessor { + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, UpdateVfModuleInfra.class); + + ExceptionUtil exceptionUtil = new ExceptionUtil() + + /** + * Initialize the flow's variables. + * + * @param execution The flow's execution instance. + */ + public void initProcessVariables(DelegateExecution execution) { + execution.setVariable('prefix', 'UPDVfModI_') + execution.setVariable('UPDVfModI_Request', null) + execution.setVariable('UPDVfModI_requestInfo', null) + execution.setVariable('UPDVfModI_requestId', null) + execution.setVariable('UPDVfModI_source', null) + execution.setVariable('UPDVfModI_vnfInputs', null) + execution.setVariable('UPDVfModI_vnfId', null) + execution.setVariable('UPDVfModI_vfModuleId', null) + execution.setVariable('UPDVfModI_tenantId', null) + execution.setVariable('UPDVfModI_volumeGroupId', null) + execution.setVariable('UPDVfModI_vnfParams', null) + execution.setVariable('UPDVfModI_updateInfraRequest', null) + execution.setVariable('UpdateVfModuleSuccessIndicator', false) + } + + /** + * Check for missing elements in the received request. + * + * @param execution The flow's execution instance. + */ + public void preProcessRequest(DelegateExecution execution) { + + def method = getClass().getSimpleName() + '.preProcessRequest(' + + 'execution=' + execution.getId() + + ')' + + msoLogger.trace('Entered ' + method) + + initProcessVariables(execution) + + def prefix = "UPDVfModI_" + + def incomingRequest = execution.getVariable('bpmnRequest') + + msoLogger.debug("Incoming Infra Request: " + incomingRequest) + try { + def jsonSlurper = new JsonSlurper() + def jsonOutput = new JsonOutput() + Map reqMap = jsonSlurper.parseText(incomingRequest) + msoLogger.debug(" Request is in JSON format.") + + def serviceInstanceId = execution.getVariable('serviceInstanceId') + def vnfId = execution.getVariable('vnfId') + + execution.setVariable(prefix + 'serviceInstanceId', serviceInstanceId) + execution.setVariable(prefix+'vnfId', vnfId) + execution.setVariable("isVidRequest", "true") + + def vnfName = '' + def asdcServiceModelVersion = '' + def serviceModelInfo = null + def vnfModelInfo = null + + def relatedInstanceList = reqMap.requestDetails?.relatedInstanceList + + if (relatedInstanceList != null) { + relatedInstanceList.each { + if (it.relatedInstance.modelInfo?.modelType == 'service') { + asdcServiceModelVersion = it.relatedInstance.modelInfo?.modelVersion + serviceModelInfo = jsonOutput.toJson(it.relatedInstance.modelInfo) + + } + if (it.relatedInstance.modelInfo.modelType == 'vnf') { + vnfName = it.relatedInstance.instanceName ?: '' + vnfModelInfo = jsonOutput.toJson(it.relatedInstance.modelInfo) + } + } + } + + execution.setVariable(prefix + 'vnfName', vnfName) + execution.setVariable(prefix + 'asdcServiceModelVersion', asdcServiceModelVersion) + execution.setVariable(prefix + 'serviceModelInfo', serviceModelInfo) + execution.setVariable(prefix + 'vnfModelInfo', vnfModelInfo) + + def vnfType = execution.getVariable('vnfType') + execution.setVariable(prefix + 'vnfType', vnfType) + def vfModuleId = execution.getVariable('vfModuleId') + execution.setVariable(prefix + 'vfModuleId', vfModuleId) + def volumeGroupId = execution.getVariable('volumeGroupId') + execution.setVariable(prefix + 'volumeGroupId', volumeGroupId) + def userParams = reqMap.requestDetails?.requestParameters?.userParams + + Map<String, String> userParamsMap = [:] + if (userParams != null) { + userParams.each { userParam -> + userParamsMap.put(userParam.name, userParam.value.toString()) + } + } + + msoLogger.debug('Processed user params: ' + userParamsMap) + + execution.setVariable(prefix + 'vfModuleInputParams', userParamsMap) + + def isBaseVfModule = "false" + if (execution.getVariable('isBaseVfModule') == true) { + isBaseVfModule = "true" + } + + execution.setVariable(prefix + 'isBaseVfModule', isBaseVfModule) + + def requestId = execution.getVariable("mso-request-id") + execution.setVariable(prefix + 'requestId', requestId) + + def vfModuleModelInfo = jsonOutput.toJson(reqMap.requestDetails?.modelInfo) + execution.setVariable(prefix + 'vfModuleModelInfo', vfModuleModelInfo) + + def suppressRollback = reqMap.requestDetails?.requestInfo?.suppressRollback + + + def backoutOnFailure = "" + if(suppressRollback != null){ + if ( suppressRollback == true) { + backoutOnFailure = "false" + } else if ( suppressRollback == false) { + backoutOnFailure = "true" + } + } + + execution.setVariable('disableRollback', suppressRollback) + + def vfModuleName = reqMap.requestDetails?.requestInfo?.instanceName ?: null + execution.setVariable(prefix + 'vfModuleName', vfModuleName) + + def serviceId = reqMap.requestDetails?.requestParameters?.serviceId ?: '' + execution.setVariable(prefix + 'serviceId', serviceId) + + def usePreload = reqMap.requestDetails?.requestParameters?.usePreload + execution.setVariable(prefix + 'usePreload', usePreload) + + def cloudConfiguration = reqMap.requestDetails?.cloudConfiguration + def lcpCloudRegionId = cloudConfiguration.lcpCloudRegionId + execution.setVariable(prefix + 'lcpCloudRegionId', lcpCloudRegionId) + def tenantId = cloudConfiguration.tenantId + execution.setVariable(prefix + 'tenantId', tenantId) + + def globalSubscriberId = reqMap.requestDetails?.subscriberInfo?.globalSubscriberId ?: '' + execution.setVariable(prefix + 'globalSubscriberId', globalSubscriberId) + + execution.setVariable(prefix + 'sdncVersion', '1702') + + execution.setVariable("UpdateVfModuleInfraSuccessIndicator", false) + + + + + def source = reqMap.requestDetails?.requestInfo?.source + execution.setVariable(prefix + "source", source) + + //For Completion Handler & Fallout Handler + String requestInfo = + """<request-info xmlns="http://org.onap/so/infra/vnf-request/v1"> + <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> + <action>UPDATE</action> + <source>${MsoUtils.xmlEscape(source)}</source> + </request-info>""" + + execution.setVariable(prefix + "requestInfo", requestInfo) + + //backoutOnFailure + + msoLogger.debug('RequestInfo: ' + execution.getVariable(prefix + "requestInfo")) + + msoLogger.trace('Exited ' + method) + + } + catch(groovy.json.JsonException je) { + msoLogger.debug(" Request is not in JSON format.") + exceptionUtil.buildAndThrowWorkflowException(execution, 5000, "Invalid request format") + + } + catch(Exception e) { + String restFaultMessage = e.getMessage() + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, " Exception Encountered - " + "\n" + restFaultMessage, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 5000, restFaultMessage) + } + } + + /** + * Prepare and send the sychronous response for this flow. + * + * @param execution The flow's execution instance. + */ + public void sendSynchResponse(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.sendSynchResponse(' + + 'execution=' + execution.getId() + + ')' + + msoLogger.trace('Entered ' + method) + + + try { + def requestInfo = execution.getVariable('UPDVfModI_requestInfo') + def requestId = execution.getVariable('UPDVfModI_requestId') + def source = execution.getVariable('UPDVfModI_source') + def progress = getNodeTextForce(requestInfo, 'progress') + if (progress.isEmpty()) { + progress = '0' + } + def startTime = getNodeTextForce(requestInfo, 'start-time') + if (startTime.isEmpty()) { + startTime = System.currentTimeMillis() + } + + // RESTResponse (for API Handler (APIH) Reply Task) + def vfModuleId = execution.getVariable("vfModuleId") + String synchResponse = """{"requestReferences":{"instanceId":"${vfModuleId}","requestId":"${requestId}"}}""".trim() + + sendWorkflowResponse(execution, 200, synchResponse) + + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in sendResponse(): ' + e.getMessage()) + } + } + + /** + * Prepare the Request for invoking the DoUpdateVfModule subflow. + * + * NOTE: Currently, the method just logs passing through as the + * incoming Request to this main flow is used as the Request to + * the DoUpdateVfModule subflow. No preparation processing is + * necessary. + * + * @param execution The flow's execution instance. + */ + public void prepDoUpdateVfModule(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.prepDoUpdateVfModule(' + + 'execution=' + execution.getId() + + ')' + + msoLogger.trace('Entered ' + method) + + try { + + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in prepDoUpdateVfModule(): ' + e.getMessage()) + } + } + + /** + * Prepare the Request for updating the DB for this Infra Request. + * + * @param execution The flow's execution instance. + */ + public void prepUpdateInfraRequest(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.prepUpdateInfraRequest(' + + 'execution=' + execution.getId() + + ')' + + msoLogger.trace('Entered ' + method) + + try { + def requestId = execution.getVariable('UPDVfModI_requestId') + def vnfId = execution.getVariable('UPDVfModI_vnfId') + def vfModuleId = execution.getVariable('UPDVfModI_vfModuleId') + def tenantId = execution.getVariable('UPDVfModI_tenantId') + def volumeGroupId = execution.getVariable('UPDVfModI_volumeGroupId') + + String updateInfraRequest = """ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" + xmlns:req="http://org.onap.so/requestsdb"> + <soapenv:Header/> + <soapenv:Body> + <req:updateInfraRequest> + <requestId>${MsoUtils.xmlEscape(requestId)}</requestId> + <lastModifiedBy>BPEL</lastModifiedBy> + <requestStatus>COMPLETE</requestStatus> + <progress>100</progress> + <vnfOutputs> + <vnf-id>${MsoUtils.xmlEscape(vnfId)}</vnf-id> + <vf-module-id>${MsoUtils.xmlEscape(vfModuleId)}</vf-module-id> + <tenant-id>${MsoUtils.xmlEscape(tenantId)}</tenant-id> + <volume-group-id>${MsoUtils.xmlEscape(volumeGroupId)}</volume-group-id> + </vnfOutputs> + </req:updateInfraRequest> + </soapenv:Body> + </soapenv:Envelope> + """ + + updateInfraRequest = utils.formatXml(updateInfraRequest) + execution.setVariable('UPDVfModI_updateInfraRequest', updateInfraRequest) + msoLogger.debug('Request for Update Infra Request:\n' + updateInfraRequest) + + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in prepUpdateInfraRequest(): ' + e.getMessage()) + } + } + + /** + * Builds a "CompletionHandler" request and stores it in the specified execution variable. + * + * @param execution the execution + * @param resultVar the execution variable in which the result will be stored + */ + public void completionHandlerPrep(DelegateExecution execution, String resultVar) { + def method = getClass().getSimpleName() + '.completionHandlerPrep(' + + 'execution=' + execution.getId() + + ', resultVar=' + resultVar + + ')' + + msoLogger.trace('Entered ' + method) + + try { + def requestInfo = getVariable(execution, 'UPDVfModI_requestInfo') + + String content = """ + <sdncadapterworkflow:MsoCompletionRequest xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1" + xmlns:reqtype="http://org.onap/so/request/types/v1"> + ${requestInfo} + <sdncadapterworkflow:mso-bpel-name>MSO_ACTIVATE_BPEL</sdncadapterworkflow:mso-bpel-name> + </sdncadapterworkflow:MsoCompletionRequest> + """ + + content = utils.formatXml(content) + msoLogger.debug(resultVar + ' = ' + System.lineSeparator() + content) + execution.setVariable(resultVar, content) + + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 2000, 'Internal Error') + } + } + + /** + * Builds a "FalloutHandler" request and stores it in the specified execution variable. + * + * @param execution the execution + * @param resultVar the execution variable in which the result will be stored + */ + public void falloutHandlerPrep(DelegateExecution execution, String resultVar) { + def method = getClass().getSimpleName() + '.falloutHandlerPrep(' + + 'execution=' + execution.getId() + + ', resultVar=' + resultVar + + ')' + + msoLogger.trace('Entered ' + method) + + try { + def prefix = execution.getVariable('prefix') + def request = getVariable(execution, prefix+'Request') + def requestInformation = execution.getVariable(prefix + "requestInfo") + + def WorkflowException workflowException = execution.getVariable("WorkflowException") + def errorResponseCode = workflowException.getErrorCode() + def errorResponseMsg = workflowException.getErrorMessage() + def encErrorResponseMsg = "" + if (errorResponseMsg != null) { + encErrorResponseMsg = errorResponseMsg + } + + String content = """ + <sdncadapterworkflow:FalloutHandlerRequest xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1" + xmlns:reqtype="http://org.onap/so/request/types/v1" + xmlns:msoservtypes="http://org.onap/so/request/types/v1" + xmlns:structuredtypes="http://org.onap/so/structured/types/v1"> + ${requestInformation} + <sdncadapterworkflow:WorkflowException> + <sdncadapterworkflow:ErrorMessage>${MsoUtils.xmlEscape(encErrorResponseMsg)}</sdncadapterworkflow:ErrorMessage> + <sdncadapterworkflow:ErrorCode>${MsoUtils.xmlEscape(errorResponseCode)}</sdncadapterworkflow:ErrorCode> + </sdncadapterworkflow:WorkflowException> + </sdncadapterworkflow:FalloutHandlerRequest> + """ + content = utils.formatXml(content) + msoLogger.debug(resultVar + ' = ' + System.lineSeparator() + content) + execution.setVariable(resultVar, content) + + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildWorkflowException(execution, 2000, 'Internal Error') + } + } + + /** + * Validates the request, request id and service instance id. If a problem is found, + * a WorkflowException is generated and an MSOWorkflowException event is thrown. This + * method also sets up the log context for the workflow. + * @param execution the execution + * @return the validated request + */ + public String validateInfraRequest(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.validateInfraRequest(' + + 'execution=' + execution.getId() + + ')' + + msoLogger.trace('Entered ' + method) + + String processKey = getProcessKey(execution); + def prefix = execution.getVariable("prefix") + + if (prefix == null) { + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, processKey + " prefix is null") + } + + try { + def request = execution.getVariable(prefix + 'Request') + + if (request == null) { + request = execution.getVariable(processKey + 'Request') + + if (request == null) { + request = execution.getVariable('bpmnRequest') + } + + setVariable(execution, processKey + 'Request', null); + setVariable(execution, 'bpmnRequest', null); + setVariable(execution, prefix + 'Request', request); + } + + if (request == null) { + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, processKey + " request is null") + } + + /* + + def requestId = execution.getVariable("mso-request-id") + + if (requestId == null) { + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, processKey + " request has no mso-request-id") + } + + setVariable(execution, prefix + 'requestId', requestId) + + def serviceInstanceId = execution.getVariable("mso-service-instance-id") + + if (serviceInstanceId == null) { + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, processKey + " request message has no mso-service-instance-id") + } + + utils.logContext(requestId, serviceInstanceId) + */ + msoLogger.debug('Incoming message: ' + System.lineSeparator() + request) + msoLogger.trace('Exited ' + method) + return request + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Invalid Message") + } + } + +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/UpdateVfModuleInfraV2.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/UpdateVfModuleInfraV2.groovy new file mode 100644 index 0000000000..a926030924 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/UpdateVfModuleInfraV2.groovy @@ -0,0 +1,468 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts + + +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.onap.so.bpmn.common.scripts.ExceptionUtil +import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.so.bpmn.core.UrnPropertiesReader +import org.onap.so.client.aai.AAIValidatorImpl +import org.onap.so.client.appc.ApplicationControllerClient +import org.onap.so.logger.MsoLogger + +import groovy.json.JsonOutput +import groovy.json.JsonSlurper + +public class UpdateVfModuleInfraV2 { + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, UpdateVfModuleInfraV2.class); + + ExceptionUtil exceptionUtil = new ExceptionUtil() + + boolean preProcessRequestCheck = true; + boolean sendSynchResponseCheck = true; + boolean checkPserverFlagCheck = true; + boolean vfFlagCheckSetCheck = true; + boolean lockAppCCheck = true; + boolean healthDiagnosticSDNOCheck = true; + boolean healthCheckAppCCheck = true; + boolean stopVfModuleControllerCheck = true; + boolean healthCheckControllerCheck = true; + boolean doUpdateVfModulePrepCheck = true; + boolean completionHandlerPrepCheck = true; + boolean startVfModuleControllerCheck = true; + boolean vFFlagUnsetCheck = true; + boolean unlockAppCCheck = true; + boolean postUpgradeHealthCheckControllerCheck = true; + + + + public void initProcessVariables(DelegateExecution execution) { + execution.setVariable('prefix', 'UPDVfModI_') + execution.setVariable('UPDVfModI_Request', null) + execution.setVariable('UPDVfModI_requestInfo', null) + execution.setVariable('UPDVfModI_requestId', null) + execution.setVariable('UPDVfModI_source', null) + execution.setVariable('UPDVfModI_vnfInputs', null) + execution.setVariable('UPDVfModI_vnfId', null) + execution.setVariable('UPDVFModI_moduleUuid', null) + execution.setVariable('UPDVfModI_vfModuleId', null) + execution.setVariable('UPDVfModI_tenantId', null) + execution.setVariable('UPDVfModI_volumeGroupId', null) + execution.setVariable('UPDVfModI_vnfParams', null) + execution.setVariable('UPDVfModI_updateInfraRequest', null) + execution.setVariable('UpdateVfModuleSuccessIndicator', false) + } + + /** + * Check for missing elements in the received request. + * + * @param execution The flow's execution instance. + */ + public void preProcessRequest(DelegateExecution execution) { + System.out.print("*****************************PreProcessRequest**************************") + + def method = getClass().getSimpleName() + '.preProcessRequest(' + + 'execution=' + execution.getId() + + ')' + + //msoLogger.trace('Entered ' + method) + + initProcessVariables(execution) + + def prefix = "UPDVfModI_" + + def incomingRequest = execution.getVariable('bpmnRequest') + + //msoLogger.debug("Incoming Infra Request: " + incomingRequest) + try { + def jsonSlurper = new JsonSlurper() + def jsonOutput = new JsonOutput() + Map reqMap = jsonSlurper.parseText(incomingRequest) + //msoLogger.debug(" Request is in JSON format.") + + def serviceInstanceId = execution.getVariable('serviceInstanceId') + def vnfId = execution.getVariable('vnfId') + def moduleUuid = execution.getVariable('moduleUuid') + execution.setVariable(prefix + 'moduleUuid',moduleUuid) + execution.setVariable(prefix + 'serviceInstanceId', serviceInstanceId) + execution.setVariable(prefix+'vnfId', vnfId) + execution.setVariable("isVidRequest", "true") + + def vnfName = '' + def asdcServiceModelVersion = '' + def serviceModelInfo = null + def vnfModelInfo = null + + def relatedInstanceList = reqMap.requestDetails?.relatedInstanceList + + if (relatedInstanceList != null) { + relatedInstanceList.each { + if (it.relatedInstance.modelInfo?.modelType == 'service') { + asdcServiceModelVersion = it.relatedInstance.modelInfo?.modelVersion + serviceModelInfo = jsonOutput.toJson(it.relatedInstance.modelInfo) + } + if (it.relatedInstance.modelInfo.modelType == 'vnf') { + vnfName = it.relatedInstance.instanceName ?: '' + vnfModelInfo = jsonOutput.toJson(it.relatedInstance.modelInfo) + } + } + } + + execution.setVariable(prefix + 'vnfName', vnfName) + execution.setVariable(prefix + 'asdcServiceModelVersion', asdcServiceModelVersion) + execution.setVariable(prefix + 'serviceModelInfo', serviceModelInfo) + execution.setVariable(prefix + 'vnfModelInfo', vnfModelInfo) + + def vnfType = execution.getVariable('vnfType') + execution.setVariable(prefix + 'vnfType', vnfType) + def vfModuleId = execution.getVariable('vfModuleId') + execution.setVariable(prefix + 'vfModuleId', vfModuleId) + def volumeGroupId = execution.getVariable('volumeGroupId') + execution.setVariable(prefix + 'volumeGroupId', volumeGroupId) + def userParams = reqMap.requestDetails?.requestParameters?.userParams + + Map<String, String> userParamsMap = [:] + if (userParams != null) { + userParams.each { userParam -> + userParamsMap.put(userParam.name, userParam.value.toString()) + } + } + + //msoLogger.debug('Processed user params: ' + userParamsMap) + + execution.setVariable(prefix + 'vfModuleInputParams', userParamsMap) + + def isBaseVfModule = "false" + if (execution.getVariable('isBaseVfModule') == true) { + isBaseVfModule = "true" + } + + execution.setVariable(prefix + 'isBaseVfModule', isBaseVfModule) + + def requestId = execution.getVariable("mso-request-id") + execution.setVariable(prefix + 'requestId', requestId) + + def vfModuleModelInfo = jsonOutput.toJson(reqMap.requestDetails?.modelInfo) + execution.setVariable(prefix + 'vfModuleModelInfo', vfModuleModelInfo) + + def suppressRollback = reqMap.requestDetails?.requestInfo?.suppressRollback + + + def backoutOnFailure = "" + if(suppressRollback != null){ + if ( suppressRollback == true) { + backoutOnFailure = "false" + } else if ( suppressRollback == false) { + backoutOnFailure = "true" + } + } + + execution.setVariable('disableRollback', suppressRollback) + + def vfModuleName = reqMap.requestDetails?.requestInfo?.instanceName ?: null + execution.setVariable(prefix + 'vfModuleName', vfModuleName) + + def serviceId = reqMap.requestDetails?.requestParameters?.serviceId ?: '' + execution.setVariable(prefix + 'serviceId', serviceId) + + def usePreload = reqMap.requestDetails?.requestParameters?.usePreload + execution.setVariable(prefix + 'usePreload', usePreload) + + def cloudConfiguration = reqMap.requestDetails?.cloudConfiguration + def lcpCloudRegionId = cloudConfiguration.lcpCloudRegionId + execution.setVariable(prefix + 'lcpCloudRegionId', lcpCloudRegionId) + def tenantId = cloudConfiguration.tenantId + execution.setVariable(prefix + 'tenantId', tenantId) + + def globalSubscriberId = reqMap.requestDetails?.subscriberInfo?.globalSubscriberId ?: '' + execution.setVariable(prefix + 'globalSubscriberId', globalSubscriberId) + + execution.setVariable(prefix + 'sdncVersion', '1702') + + execution.setVariable("UpdateVfModuleInfraSuccessIndicator", false) + + + + + def source = reqMap.requestDetails?.requestInfo?.source + execution.setVariable(prefix + "source", source) + + //For Completion Handler & Fallout Handler + String requestInfo = + """<request-info xmlns="http://org.onap/so/infra/vnf-request/v1"> + <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> + <action>UPDATE</action> + <source>${MsoUtils.xmlEscape(source)}</source> + </request-info>""" + + execution.setVariable(prefix + "requestInfo", requestInfo) + + //backoutOnFailure + + //msoLogger.debug('RequestInfo: ' + execution.getVariable(prefix + "requestInfo")) + + //msoLogger.trace('Exited ' + method) + + } + catch(groovy.json.JsonException je) { + //msoLogger.debug(" Request is not in JSON format.") + exceptionUtil.buildAndThrowWorkflowException(execution, 5000, "Invalid request format") + } + catch(Exception e) { + String restFaultMessage = e.getMessage() + //msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, " Exception Encountered - " + "\n" + restFaultMessage, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 5000, restFaultMessage) + } + } + + /** + * Prepare and send the synchronous response for this flow. + * + * @param execution The flow's execution instance. + */ + public void sendSynchResponse(DelegateExecution execution) { + System.out.print("*****************************SendSynchResponse**************************") + + def method = getClass().getSimpleName() + '.sendSynchResponse(' + + 'execution=' + execution.getId() + + ')' + + //msoLogger.trace('Entered ' + method) + + + try { + def requestInfo = execution.getVariable('UPDVfModI_requestInfo') + def requestId = execution.getVariable('UPDVfModI_requestId') + def source = execution.getVariable('UPDVfModI_source') + + def progress = getNodeTextForce(requestInfo, 'progress') + if (progress.isEmpty()) { + progress = '0' + } + def startTime = getNodeTextForce(requestInfo, 'start-time') + if (startTime.isEmpty()) { + startTime = System.currentTimeMillis() + } + // RESTResponse (for API Handler (APIH) Reply Task) + def vfModuleId = execution.getVariable("vfModuleId") + String synchResponse = """{"requestReferences":{"instanceId":"${vfModuleId}","requestId":"${requestId}"}}""".trim() + sendWorkflowResponse(execution, 200, synchResponse) + //msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + //msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in sendResponse(): ' + e.getMessage()) + } + } + + //check to see if the Pserver Flag is locked + public void checkPserverFlag(DelegateExecution execution) { + + System.out.println("*****************************CheckingPserverFlag*************************") + String vnfId = (String)execution.getVariable('vnfId') + String uuid = (String)execution.getVariable('moduleUuid') + AAIValidatorImpl aaiVI = new AAIValidatorImpl() + boolean flag = aaiVI.isPhysicalServerLocked(vnfId, uuid) + } + + //check to see if the VFFlag is locked + public void vfFlagCheck(DelegateExecution execution) { + + System.out.print("*****************************VfFlagCheck*************************") + String vnfId = (String)execution.getVariable('vnfId') + String uuid = (String)execution.getVariable('moduleUuid') + AAIValidatorImpl aaiVI = new AAIValidatorImpl() + boolean flag = aaiVI.isVNFLocked(vnfId, uuid) + + } + //lock the VF Flag + public void vfFlagSet(DelegateExecution execution) { + + System.out.print("*****************************VfFlagSet*************************") + String vnfId = (String)execution.getVariable('vnfId') + String uuid = (String)execution.getVariable('moduleUuid') + AAIValidatorImpl aaiVI = new AAIValidatorImpl() + aaiVI.updateVnfToLocked(vnfId,uuid); + + } + + //Lock AppC + public void lockAppC(DelegateExecution execution) { + + System.out.print("*****************************lockAppC*************************") + def vfModuleId = "" + ApplicationControllerClient aCC = new ApplicationControllerClient(getLCMProperties()) + def status = aCC.runCommand("Lock",vfModuleId) + + + } + //run health check + public void healthCheckAppC(DelegateExecution execution) { + + System.out.print("*****************************healthCheckAppC*************************") + def vfModuleId = "" + ApplicationControllerClient aCC = new ApplicationControllerClient(getLCMProperties()) + def status = aCC.runCommand("HealthCheck",vfModuleId) + + } + //SDNO health diagnostic + public void healthDiagnosticSDNO(DelegateExecution execution) { + + System.out.print("*****************************healthDiagnosticSDNO is currently ignored*************************") + //SDNOValidatorImpl.healthDiagnostic("",""); + + } + //stop VF module controller + public void stopVfModuleController(DelegateExecution execution) { + + System.out.print("*****************************stopVfModuleController*************************") + def vfModuleId = "" + ApplicationControllerClient aCC = new ApplicationControllerClient(getLCMProperties()) + def status = aCC.runCommand("Stop",vfModuleId) + + + } + + public void doUpdateVfModulePrep(DelegateExecution execution) { + + System.out.print("*****************************doUpdateVfModulePrep*************************") + def method = getClass().getSimpleName() + '.prepDoUpdateVfModule(' + + 'execution=' + execution.getId() + + ')' + + //msoLogger.trace('Entered ' + method) + + try { + + //msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + //msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in prepDoUpdateVfModule(): ' + e.getMessage()) + + } + + } + + public void completionHandlerPrep(DelegateExecution execution,String resultVar) { + + System.out.print("*****************************completionHandlerPrep*************************") + def method = getClass().getSimpleName() + '.completionHandlerPrep(' + + 'execution=' + execution.getId() + + ', resultVar=' + resultVar + + ')' + + //msoLogger.trace('Entered ' + method) + + try { + def requestInfo = getVariable(execution, 'UPDVfModI_requestInfo') + + String content = """ + <sdncadapterworkflow:MsoCompletionRequest xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1" + xmlns:reqtype="http://org.onap/so/request/types/v1"> + ${requestInfo} + <sdncadapterworkflow:mso-bpel-name>MSO_ACTIVATE_BPEL</sdncadapterworkflow:mso-bpel-name> + </sdncadapterworkflow:MsoCompletionRequest> + """ + + content = utils.formatXml(content) + //msoLogger.debug(resultVar + ' = ' + System.lineSeparator() + content) + execution.setVariable(resultVar, content) + + //msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + //msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 2000, 'Internal Error') + + } + + } + + public void healthCheckController(DelegateExecution execution) { + + System.out.print("*****************************healthCheckController*************************") + def vfModuleId = "" + ApplicationControllerClient aCC = new ApplicationControllerClient(getLCMProperties()) + def status = aCC.runCommand("HealthCheck",vfModuleId) + + } + + public void startVfModuleController(DelegateExecution execution) { + + System.out.print("*****************************startVfModuleController*************************") + def vfModuleId = "" + ApplicationControllerClient aCC = new ApplicationControllerClient(getLCMProperties()) + def status = aCC.runCommand("Start",vfModuleId) + + } + + public void vFFlagUnset(DelegateExecution execution) { + + System.out.print("*****************************vFFlagUnset*************************") + String vnfId = (String)execution.getVariable('vnfId') + String uuid = (String)execution.getVariable('moduleUuid') + AAIValidatorImpl aaiVI = new AAIValidatorImpl() + aaiVI.updateVnfToUnLocked(vnfId,uuid); + + + } + + public void unlockAppC(DelegateExecution execution) { + + System.out.print("*****************************unlockAppC*************************") + def vfModuleId = "" + ApplicationControllerClient aCC = new ApplicationControllerClient(getLCMProperties()) + def status = aCC.runCommand("Unlock",vfModuleId) + + } + + public void postUpgradeHealthCheckController(DelegateExecution execution) { + + System.out.print("*****************************postUpgradeHealthCheckController*************************") + def vfModuleId = "" + ApplicationControllerClient aCC = new ApplicationControllerClient(getLCMProperties()) + def status = aCC.runCommand("HealthCheck",vfModuleId) + + } + + Properties getLCMProperties() { + Properties properties = new Properties() + + properties.put("topic.read", UrnPropertiesReader.getVariable("appc.client.topic.read.name")) + properties.put("topic.read.timeout", UrnPropertiesReader.getVariable("appc.client.topic.read.timeout")) + properties.put("client.response.timeout", UrnPropertiesReader.getVariable("appc.client.response.timeout")) + properties.put("topic.write", UrnPropertiesReader.getVariable("appc.client.topic.write")) + properties.put("poolMembers", UrnPropertiesReader.getVariable("appc.client.poolMembers")) + properties.put("client.key", UrnPropertiesReader.getVariable("appc.client.key")) + properties.put("client.secret", UrnPropertiesReader.getVariable("appc.client.secret")) + properties.put("client.name", "MSO") + properties.put("service", UrnPropertiesReader.getVariable("appc.client.service")) + return properties + } + +} + diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/UpdateVfModuleVolume.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/UpdateVfModuleVolume.groovy new file mode 100644 index 0000000000..b7f31d7823 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/UpdateVfModuleVolume.groovy @@ -0,0 +1,445 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts + +import org.apache.commons.lang3.* +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.onap.so.bpmn.common.scripts.AaiUtil +import org.onap.so.bpmn.common.scripts.ExceptionUtil +import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.so.bpmn.common.scripts.VfModuleBase +import org.onap.so.bpmn.core.UrnPropertiesReader; +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.logger.MessageEnum +import org.onap.so.logger.MsoLogger +import org.onap.so.rest.APIResponse +import org.springframework.web.util.UriUtils + +class UpdateVfModuleVolume extends VfModuleBase { + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, UpdateVfModuleVolume.class); + + ExceptionUtil exceptionUtil = new ExceptionUtil() + + /** + * Initialize the flow's variables. + * + * @param execution The flow's execution instance. + */ + private void initProcessVariables(DelegateExecution execution) { + execution.setVariable('prefix', 'UPDVfModVol_') + execution.setVariable('UPDVfModVol_Request', null) + execution.setVariable('UPDVfModVol_requestInfo', null) + execution.setVariable('UPDVfModVol_requestId', null) + execution.setVariable('UPDVfModVol_source', null) + execution.setVariable('UPDVfModVol_volumeInputs', null) + execution.setVariable('UPDVfModVol_volumeGroupId', null) + execution.setVariable('UPDVfModVol_vnfType', null) + execution.setVariable('UPDVfModVol_serviceId', null) + execution.setVariable('UPDVfModVol_aicCloudRegion', null) + execution.setVariable('UPDVfModVol_tenantId', null) + execution.setVariable('UPDVfModVol_volumeParams', null) + execution.setVariable('UPDVfModVol_volumeGroupHeatStackId', null) + execution.setVariable('UPDVfModVol_volumeGroupTenantId', null) + execution.setVariable('UpdateVfModuleVolumeSuccessIndicator', false) + } + + /** + * Check for missing elements in the received request. + * + * @param execution The flow's execution instance. + */ + @Override + public void preProcessRequest(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.preProcessRequest(' + + 'execution=' + execution.getId() + + ')' + + msoLogger.trace('Entered ' + method) + + try { + initProcessVariables(execution) + String request = validateRequest(execution) + + def requestInfo = getRequiredNodeXml(execution, request, 'request-info') + execution.setVariable('UPDVfModVol_requestInfo', requestInfo) + execution.setVariable('UPDVfModVol_requestId', getRequiredNodeText(execution, requestInfo, 'request-id')) + execution.setVariable('UPDVfModVol_source', getNodeTextForce(requestInfo, 'source')) + + def volumeInputs = getRequiredNodeXml(execution, request, 'volume-inputs') + execution.setVariable('UPDVfModVol_volumeInputs', volumeInputs) + execution.setVariable('UPDVfModVol_volumeGroupId', getRequiredNodeText(execution, volumeInputs, 'volume-group-id')) + execution.setVariable('UPDVfModVol_vnfType', getRequiredNodeText(execution, volumeInputs, 'vnf-type')) + execution.setVariable('UPDVfModVol_serviceId', getRequiredNodeText(execution, volumeInputs, 'service-id')) + execution.setVariable('UPDVfModVol_aicCloudRegion', getRequiredNodeText(execution, volumeInputs, 'aic-cloud-region')) + execution.setVariable('UPDVfModVol_tenantId', getRequiredNodeText(execution, volumeInputs, 'tenant-id')) + + def volumeParams = utils.getNodeXml(request, 'volume-params') + execution.setVariable('UPDVfModVol_volumeParams', volumeParams) + + msoLogger.trace('Exited ' + method) + msoLogger.debug("UpdateVfModuleVolume request: " + request) + } catch (BpmnError bpmnError) { + throw bpmnError + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in preProcessRequest(): ' + e.getMessage()) + } + } + + /** + * Prepare and send the synchronous response. + * + * @param execution The flow's execution instance. + */ + public void sendSynchResponse(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.sendSynchResponse(' + + 'execution=' + execution.getId() + + ')' + + msoLogger.trace('Entered ' + method) + + try { + def requestInfo = execution.getVariable('UPDVfModVol_requestInfo') + def requestId = execution.getVariable('UPDVfModVol_requestId') + def source = execution.getVariable('UPDVfModVol_source') + def progress = getNodeTextForce(requestInfo, 'progress') + if (progress.isEmpty()) { + progress = '0' + } + def startTime = getNodeTextForce(requestInfo, 'start-time') + if (startTime.isEmpty()) { + startTime = System.currentTimeMillis() + } + def volumeInputs = execution.getVariable('UPDVfModVol_volumeInputs') + + String synchResponse = """ + <volume-request xmlns="http://org.onap/so/infra/vnf-request/v1"> + <request-info> + <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> + <action>UPDATE_VF_MODULE_VOL</action> + <request-status>IN_PROGRESS</request-status> + <progress>${MsoUtils.xmlEscape(progress)}</progress> + <start-time>${MsoUtils.xmlEscape(startTime)}</start-time> + <source>${MsoUtils.xmlEscape(source)}</source> + </request-info> + ${volumeInputs} + </volume-request> + """ + + synchResponse = utils.formatXml(synchResponse) + sendWorkflowResponse(execution, 200, synchResponse) + msoLogger.debug("UpdateVfModuleVolume Synch Response: " + synchResponse) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in sendSynchResponse(): ' + e.getMessage()) + } + } + + /** + * Prepare a Request for querying AAI for Volume Group information using the + * Volume Group Id and Aic Cloud Region. + * + * @param execution The flow's execution instance. + */ + public void queryAAIForVolumeGroup(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.queryAAIForVolumeGroup(' + + 'execution=' + execution.getId() + + ')' + + msoLogger.trace('Entered ' + method) + + try { + def volumeGroupId = execution.getVariable('UPDVfModVol_volumeGroupId') + def aicCloudRegion = execution.getVariable('UPDVfModVol_aicCloudRegion') + def endPoint = UrnPropertiesReader.getVariable("aai.endpoint", execution) + + '/aai/v7/cloud-infrastructure/cloud-regions/cloud-region/att-aic/' + UriUtils.encode(aicCloudRegion, "UTF-8") + + '/volume-groups/volume-group/' + UriUtils.encode(volumeGroupId, "UTF-8") + + msoLogger.debug('Sending GET to AAI endpoint \'' + endPoint + '\'') + msoLogger.debug("UpdateVfModuleVolume sending GET for quering AAI endpoint: " + endPoint) + + AaiUtil aaiUtil = new AaiUtil(this) + APIResponse response = aaiUtil.executeAAIGetCall(execution, endPoint) + def int statusCode = response.getStatusCode() + def responseData = response.getResponseBodyAsString() + msoLogger.debug('Response code:' + statusCode) + msoLogger.debug('Response:' + System.lineSeparator() + responseData) + msoLogger.debug("UpdateVfModuleVolume response data: " + responseData) + + def volumeGroup = responseData + def heatStackId = getNodeTextForce(volumeGroup, 'heat-stack-id') + execution.setVariable('UPDVfModVol_volumeGroupHeatStackId', heatStackId) + if ((statusCode == 200) || (statusCode == 204)) { + def volumeGroupTenantId = getTenantIdFromVolumeGroup(volumeGroup) + if (volumeGroupTenantId == null) { + throw new Exception('Could not find Tenant Id element in Volume Group with Volume Group Id \'' + volumeGroupId + '\'' + + '\', AIC Cloud Region \'' + aicCloudRegion + '\'') + } + execution.setVariable('UPDVfModVol_volumeGroupTenantId', volumeGroupTenantId) + msoLogger.debug('Received Tenant Id \'' + volumeGroupTenantId + '\' from AAI for Volume Group with Volume Group Id \'' + volumeGroupId + '\'' + + '\', AIC Cloud Region \'' + aicCloudRegion + '\'') + } else if (statusCode == 404) { + throw new Exception('Volume Group \'' + volumeGroupId + '\' not found at AAI') + } else { + throw new Exception('Bad status code ' + statusCode + ' received from AAI; Response data: ' + responseData) + } + + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in queryAAIForVolumeGroup(): ' + e.getMessage()) + } + } + + /** + * Prepare a Request for invoking the VnfAdapterRest subflow to do + * a Volume Group update. + * + * @param execution The flow's execution instance. + */ + public void prepVnfAdapterRest(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.prepVnfAdapterRest(' + + 'execution=' + execution.getId() + + ')' + + msoLogger.trace('Entered ' + method) + + try { + def aicCloudRegion = execution.getVariable('UPDVfModVol_aicCloudRegion') + def tenantId = execution.getVariable('UPDVfModVol_tenantId') + def volumeGroupId = execution.getVariable('UPDVfModVol_volumeGroupId') + def volumeGroupHeatStackId = execution.getVariable('UPDVfModVol_volumeGroupHeatStackId') + def vnfType = execution.getVariable('UPDVfModVol_vnfType') + + def volumeParamsXml = execution.getVariable('UPDVfModVol_volumeParams') + def volumeGroupParams = transformParamsToEntries(volumeParamsXml) + + def requestId = execution.getVariable('UPDVfModVol_requestId') + def serviceId = execution.getVariable('UPDVfModVol_serviceId') + + def messageId = execution.getVariable('mso-request-id') + '-' + System.currentTimeMillis() + def notificationUrl = createCallbackURL(execution, "VNFAResponse", messageId) + def useQualifiedHostName = UrnPropertiesReader.getVariable("mso.use.qualified.host",execution) + if ('true'.equals(useQualifiedHostName)) { + notificationUrl = utils.getQualifiedHostNameForCallback(notificationUrl) + } + + String vnfAdapterRestRequest = """ + <updateVolumeGroupRequest> + <cloudSiteId>${MsoUtils.xmlEscape(aicCloudRegion)}</cloudSiteId> + <tenantId>${MsoUtils.xmlEscape(tenantId)}</tenantId> + <volumeGroupId>${MsoUtils.xmlEscape(volumeGroupId)}</volumeGroupId> + <volumeGroupStackId>${MsoUtils.xmlEscape(volumeGroupHeatStackId)}</volumeGroupStackId> + <vnfType>${MsoUtils.xmlEscape(vnfType)}</vnfType> + <vnfVersion></vnfVersion> + <vfModuleType></vfModuleType> + <volumeGroupParams> + ${volumeGroupParams} + </volumeGroupParams> + <skipAAI>true</skipAAI> + <msoRequest> + <requestId>${MsoUtils.xmlEscape(requestId)}</requestId> + <serviceInstanceId>${MsoUtils.xmlEscape(serviceId)}</serviceInstanceId> + </msoRequest> + <messageId>${MsoUtils.xmlEscape(messageId)}</messageId> + <notificationUrl>${MsoUtils.xmlEscape(notificationUrl)}</notificationUrl> + </updateVolumeGroupRequest> + """ + vnfAdapterRestRequest = utils.formatXml(vnfAdapterRestRequest) + execution.setVariable('UPDVfModVol_vnfAdapterRestRequest', vnfAdapterRestRequest) + msoLogger.debug('Request for VNFAdapter Rest:\n' + vnfAdapterRestRequest) + + msoLogger.debug("UpdateVfModuleVolume Request for VNFAdapter Rest: " + vnfAdapterRestRequest) + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in prepVnfAdapterRest(): ' + e.getMessage()) + } + } + + /** + * Prepare a Request for updating the DB for this Infra request. + * + * @param execution The flow's execution instance. + */ + public void prepDbInfraDbRequest(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.prepDbInfraDbRequest(' + + 'execution=' + execution.getId() + + ')' + + msoLogger.trace('Entered ' + method) + + try { + def requestId = execution.getVariable('UPDVfMod_requestId') + + String updateInfraRequest = """ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" + xmlns:req="http://org.onap.so/requestsdb"> + <soapenv:Header/> + <soapenv:Body> + <req:updateInfraRequest> + <requestId>${MsoUtils.xmlEscape(requestId)}</requestId> + <lastModifiedBy>BPEL</lastModifiedBy> + <requestStatus>COMPLETE</requestStatus> + <progress>100</progress> + </req:updateInfraRequest> + </soapenv:Body> + </soapenv:Envelope> + """ + + updateInfraRequest = utils.formatXml(updateInfraRequest) + execution.setVariable('UPDVfModVol_updateInfraRequest', updateInfraRequest) + msoLogger.debug('Request for Update Infra Request:\n' + updateInfraRequest) + + msoLogger.debug("UpdateVfModuleVolume Request for Updating DB for Infra: " + updateInfraRequest) + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildWorkflowException(execution, 1002, 'Error in prepDbInfraDbRequest(): ' + e.getMessage()) + } + } + + /** + * Build a "CompletionHandler" request. + * + * @param execution The flow's execution instance. + */ + public void prepCompletionHandlerRequest(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.prepCompletionHandlerRequest(' + + 'execution=' + execution.getId() + + ')' + + msoLogger.trace('Entered ' + method) + + try { + def requestInfo = execution.getVariable('UPDVfModVol_requestInfo') + + String content = """ + <sdncadapterworkflow:MsoCompletionRequest xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1" + xmlns:reqtype="http://org.onap/so/request/types/v1"> + ${requestInfo} + <sdncadapterworkflow:mso-bpel-name>MSO_ACTIVATE_BPEL</sdncadapterworkflow:mso-bpel-name> + </sdncadapterworkflow:MsoCompletionRequest> + """ + + content = utils.formatXml(content) + msoLogger.debug('Request for Completion Handler:\n' + content) + msoLogger.debug("UpdateVfModuleVolume Completion Handler request: " + content) + execution.setVariable('UPDVfModVol_CompletionHandlerRequest', content) + + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in prepCompletionHandlerRequest(): ' + e.getMessage()) + } + } + + /** + * Build a "FalloutHandler" request. + * + * @param execution The flow's execution instance. + */ + public void prepFalloutHandler(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.prepFalloutHandler(' + + 'execution=' + execution.getId() + + ')' + + msoLogger.trace('Entered ' + method) + + try { + def requestInfo = execution.getVariable('UPDVfModVol_requestInfo') + + def WorkflowException workflowException = execution.getVariable("WorkflowException") + def errorResponseCode = workflowException.getErrorCode() + def errorResponseMsg = workflowException.getErrorMessage() + def encErrorResponseMsg = "" + if (errorResponseMsg != null) { + encErrorResponseMsg = errorResponseMsg + } + + String content = """ + <sdncadapterworkflow:FalloutHandlerRequest xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1" + xmlns:reqtype="http://org.onap/so/request/types/v1" + xmlns:msoservtypes="http://org.onap/so/request/types/v1" + xmlns:structuredtypes="http://org.onap/so/structured/types/v1"> + ${requestInfo} + <sdncadapterworkflow:WorkflowException> + <sdncadapterworkflow:ErrorMessage>${MsoUtils.xmlEscape(encErrorResponseMsg)}</sdncadapterworkflow:ErrorMessage> + <sdncadapterworkflow:ErrorCode>${MsoUtils.xmlEscape(errorResponseCode)}</sdncadapterworkflow:ErrorCode> + </sdncadapterworkflow:WorkflowException> + </sdncadapterworkflow:FalloutHandlerRequest> + """ + content = utils.formatXml(content) + msoLogger.debug('Request for Fallout Handler:\n' + content) + msoLogger.debug("UpdateVfModuleVolume Fallout request: " + content) + execution.setVariable('UPDVfModVol_FalloutHandlerRequest', content) + + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildWorkflowException(execution, 1002, 'Error in prepFalloutHandler(): ' + e.getMessage()) + } + } + + /** + * Create a WorkflowException for the error case where the Tenant Id from + * AAI did not match the Tenant Id in the incoming request. + * + * @param execution The flow's execution instance. + */ + public void handleTenantIdMismatch(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.handleTenantIdMismatch(' + + 'execution=' + execution.getId() + + ')' + + msoLogger.trace('Entered ' + method) + + String processKey = getProcessKey(execution); + def volumeGroupId = execution.getVariable('UPDVfModVol_volumeGroupId') + def aicCloudRegion = execution.getVariable('UPDVfModVol_aicCloudRegion') + def tenantId = execution.getVariable('UPDVfModVol_tenantId') + def volumeGroupTenantId = execution.getVariable('UPDVfModVol_volumeGroupTenantId') + + def String errorMessage = 'TenantId \'' + tenantId + '\' in incoming request does not match Tenant Id \'' + volumeGroupTenantId + + '\' retrieved from AAI for Volume Group Id \'' + volumeGroupId + '\', AIC Cloud Region \'' + aicCloudRegion + '\'' + + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Error in UpdateVfModuleVol: ' + errorMessage, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception"); + + WorkflowException exception = new WorkflowException(processKey, 5000, errorMessage); + execution.setVariable("WorkflowException", exception); + + msoLogger.trace('Exited ' + method) + msoLogger.debug("UpdateVfModuleVolume workflowException in Tenant Mismatch: " + errorMessage) + } +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/UpdateVfModuleVolumeInfraV1.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/UpdateVfModuleVolumeInfraV1.groovy new file mode 100644 index 0000000000..7b2d1b78e4 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/UpdateVfModuleVolumeInfraV1.groovy @@ -0,0 +1,561 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts + +import org.apache.commons.lang3.* +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.onap.so.bpmn.common.scripts.AaiUtil; +import org.onap.so.bpmn.common.scripts.ExceptionUtil; +import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.so.bpmn.common.scripts.VfModuleBase; +import org.onap.so.bpmn.common.scripts.VidUtils; +import org.onap.so.bpmn.core.UrnPropertiesReader +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.logger.MessageEnum +import org.onap.so.logger.MsoLogger +import org.onap.so.rest.APIResponse +import org.springframework.web.util.UriUtils + +import groovy.json.JsonSlurper + +class UpdateVfModuleVolumeInfraV1 extends VfModuleBase { + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, UpdateVfModuleVolumeInfraV1.class); + + /** + * Initialize the flow's variables. + * + * @param execution The flow's execution instance. + */ + private void initProcessVariables(DelegateExecution execution) { + execution.setVariable('prefix', 'UPDVfModVol_') + execution.setVariable('UPDVfModVol_Request', null) + execution.setVariable('UPDVfModVol_requestInfo', null) + execution.setVariable('UPDVfModVol_requestId', null) + execution.setVariable('UPDVfModVol_source', null) + execution.setVariable('UPDVfModVol_volumeInputs', null) + execution.setVariable('UPDVfModVol_volumeGroupId', null) + execution.setVariable('UPDVfModVol_vnfType', null) + execution.setVariable('UPDVfModVol_serviceId', null) + execution.setVariable('UPDVfModVol_aicCloudRegion', null) + execution.setVariable('UPDVfModVol_tenantId', null) + execution.setVariable('UPDVfModVol_volumeParams', null) + execution.setVariable('UPDVfModVol_volumeGroupHeatStackId', null) + execution.setVariable('UPDVfModVol_volumeGroupTenantId', null) + execution.setVariable('UpdateVfModuleVolumeSuccessIndicator', false) + } + + + /** + * Perform initial processing, such as request validation, initialization of variables, etc. + * * @param execution + */ + public void preProcessRequest (DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + preProcessRequest(execution, isDebugEnabled) + } + + public void preProcessRequest(DelegateExecution execution, isDebugLogEnabled) { + + initProcessVariables(execution) + String jsonRequest = validateRequest(execution) + + def request = "" + + try { + def jsonSlurper = new JsonSlurper() + Map reqMap = jsonSlurper.parseText(jsonRequest) + + def serviceInstanceId = execution.getVariable('serviceInstanceId') + def volumeGroupId = execution.getVariable('volumeGroupId') + //def vnfId = execution.getVariable('vnfId') + + def vidUtils = new VidUtils(this) + request = vidUtils.createXmlVolumeRequest(reqMap, 'UPDATE_VF_MODULE_VOL', serviceInstanceId, volumeGroupId) + + execution.setVariable('UPDVfModVol_Request', request) + execution.setVariable("UPDVfModVol_isVidRequest", true) + + //need to get persona-model-id aka model-invariantId to use later to validate vf-module relation in AAI + + def modelInvariantId = reqMap.requestDetails.modelInfo.modelInvariantUuid ?: '' + execution.setVariable('UPDVfModVol_modelInvariantId', modelInvariantId) + + msoLogger.debug("modelInvariantId from request: " + modelInvariantId) + msoLogger.debug("XML request:\n" + request) + } + catch(groovy.json.JsonException je) { + msoLogger.debug(" Request is in XML format.") + // assume request is in XML format - proceed as usual to process XML request + } + + def requestId = execution.getVariable('mso-request-id') + + def requestInfo = getRequiredNodeXml(execution, request, 'request-info') + execution.setVariable('UPDVfModVol_requestInfo', requestInfo) + execution.setVariable('UPDVfModVol_requestId', requestId) + //execution.setVariable('UPDVfModVol_requestId', getRequiredNodeText(execution, requestInfo, 'request-id')) + execution.setVariable('UPDVfModVol_source', getNodeTextForce(requestInfo, 'source')) + + def volumeInputs = getRequiredNodeXml(execution, request, 'volume-inputs') + execution.setVariable('UPDVfModVol_volumeInputs', volumeInputs) + execution.setVariable('UPDVfModVol_volumeGroupId', getRequiredNodeText(execution, volumeInputs, 'volume-group-id')) + execution.setVariable('UPDVfModVol_vnfType', getRequiredNodeText(execution, volumeInputs, 'vnf-type')) + execution.setVariable('UPDVfModVol_vnfVersion', getRequiredNodeText(execution, volumeInputs, 'asdc-service-model-version')) + execution.setVariable('UPDVfModVol_serviceId', utils.getNodeText(volumeInputs, 'service-id')) + execution.setVariable('UPDVfModVol_aicCloudRegion', getRequiredNodeText(execution, volumeInputs, 'aic-cloud-region')) + execution.setVariable('UPDVfModVol_tenantId', getRequiredNodeText(execution, volumeInputs, 'tenant-id')) + //execution.setVariable('UPDVfModVol_modelCustomizationId', getRequiredNodeText(execution, volumeInputs, 'model-customization-id')) + + setBasicDBAuthHeader(execution, isDebugLogEnabled) + + def volumeParams = utils.getNodeXml(request, 'volume-params') + execution.setVariable('UPDVfModVol_volumeParams', volumeParams) + } + + /** + * Prepare and send the synchronous response. + * + * @param execution The flow's execution instance. + */ + public void sendSynchResponse(DelegateExecution execution, isDebugLogEnabled) { + + def requestInfo = execution.getVariable('UPDVfModVol_requestInfo') + def requestId = execution.getVariable('UPDVfModVol_requestId') + def source = execution.getVariable('UPDVfModVol_source') + def progress = getNodeTextForce(requestInfo, 'progress') + if (progress.isEmpty()) { + progress = '0' + } + def startTime = getNodeTextForce(requestInfo, 'start-time') + if (startTime.isEmpty()) { + startTime = System.currentTimeMillis() + } + def volumeInputs = execution.getVariable('UPDVfModVol_volumeInputs') + + String xmlSyncResponse = """ + <volume-request xmlns="http://org.onap/so/infra/vnf-request/v1"> + <request-info> + <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> + <action>UPDATE_VF_MODULE_VOL</action> + <request-status>IN_PROGRESS</request-status> + <progress>${MsoUtils.xmlEscape(progress)}</progress> + <start-time>${MsoUtils.xmlEscape(startTime)}</start-time> + <source>${MsoUtils.xmlEscape(source)}</source> + </request-info> + ${volumeInputs} + </volume-request> + """ + + def syncResponse = '' + def isVidRequest = execution.getVariable('UPDVfModVol_isVidRequest') + + if(isVidRequest) { + def volumeGroupId = execution.getVariable('volumeGroupId') + syncResponse = """{"requestReferences":{"instanceId":"${volumeGroupId}","requestId":"${requestId}"}}""".trim() + } + else { + syncResponse = utils.formatXml(xmlSyncResponse) + } + + msoLogger.debug('Sync response: ' + syncResponse) + execution.setVariable('UPDVfModVol_syncResponseSent', true) + sendWorkflowResponse(execution, 200, syncResponse) + } + + /** + * Prepare a Request for querying AAI for Volume Group information using the + * Volume Group Id and Aic Cloud Region. + * @param execution The flow's execution instance. + */ + public void queryAAIForVolumeGroup(DelegateExecution execution, isDebugLogEnabled) { + + def volumeGroupId = execution.getVariable('UPDVfModVol_volumeGroupId') + def aicCloudRegion = execution.getVariable('UPDVfModVol_aicCloudRegion') + + AaiUtil aaiUtil = new AaiUtil(this) + String aaiEndpoint = aaiUtil.getCloudInfrastructureCloudRegionEndpoint(execution) + String queryAAIVolumeGroupRequest = aaiEndpoint + '/' + URLEncoder.encode(aicCloudRegion, "UTF-8") + "/volume-groups/volume-group/" + UriUtils.encode(volumeGroupId, "UTF-8") + + msoLogger.debug('Query AAI volume group by ID: ' + queryAAIVolumeGroupRequest) + msoLogger.debug('Query AAI volume group by ID: ' + queryAAIVolumeGroupRequest) + + APIResponse response = aaiUtil.executeAAIGetCall(execution, queryAAIVolumeGroupRequest) + + String returnCode = response.getStatusCode() + String aaiResponseAsString = response.getResponseBodyAsString() + + msoLogger.debug("AAI query volume group by id return code: " + returnCode) + msoLogger.debug("AAI query volume group by id response: " + aaiResponseAsString) + + msoLogger.debug("AAI Volume Group return code: " + returnCode) + msoLogger.debug("AAI Volume Group response: " + aaiResponseAsString) + + ExceptionUtil exceptionUtil = new ExceptionUtil() + + if ((returnCode == '200') || (returnCode == '204')) { + + execution.setVariable('UPDVfModVol_aaiVolumeGroupResponse', aaiResponseAsString) + //def heatStackId = getNodeTextForce(aaiResponseAsString, 'heat-stack-id') + //execution.setVariable('UPDVfModVol_volumeGroupHeatStackId', heatStackId) + + def volumeGroupTenantId = getTenantIdFromVolumeGroup(aaiResponseAsString) + if (volumeGroupTenantId == null) { + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Could not find Tenant Id element in Volume Group with Volume Group Id " + volumeGroupId + + ", AIC Cloud Region " + aicCloudRegion) + } + execution.setVariable('UPDVfModVol_volumeGroupTenantId', volumeGroupTenantId) + msoLogger.debug("Received Tenant Id " + volumeGroupTenantId + " from AAI for Volume Group with Volume Group Id " + volumeGroupId + ", AIC Cloud Region " + aicCloudRegion) + + def relatedVfModuleLink = getRelatedVfModuleRelatedLink(aaiResponseAsString) + msoLogger.debug("Related VF Module link: " + relatedVfModuleLink) + execution.setVariable('UPDVfModVol_relatedVfModuleLink', relatedVfModuleLink) + + } + else if (returnCode == '404') { + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Volume Group " + volumeGroupId + " not found at AAI") + } + else { + WorkflowException aWorkflowException = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) + throw new BpmnError("MSOWorkflowException") + } + } + + /** + * Query AAI service instance + * @param execution + * @param isDebugEnabled + */ + public void queryAAIForGenericVnf(DelegateExecution execution, isDebugEnabled) { + + def vnfId = execution.getVariable('vnfId') + + AaiUtil aaiUtil = new AaiUtil(this) + String aaiEndpoint = aaiUtil.getNetworkGenericVnfEndpoint(execution) + def String queryAAIRequest = aaiEndpoint + "/" + UriUtils.encode(vnfId, "UTF-8") + + msoLogger.debug("AAI query generic vnf request: " + queryAAIRequest) + + APIResponse response = aaiUtil.executeAAIGetCall(execution, queryAAIRequest) + + String returnCode = response.getStatusCode() + String aaiResponseAsString = response.getResponseBodyAsString() + + msoLogger.debug("AAI query generic vnf return code: " + returnCode) + msoLogger.debug("AAI query generic vnf response: " + aaiResponseAsString) + + ExceptionUtil exceptionUtil = new ExceptionUtil() + + if (returnCode=='200') { + msoLogger.debug('Generic vnf ' + vnfId + ' found in AAI.') + execution.setVariable('UPDVfModVol_AAIQueryGenericVfnResponse', aaiResponseAsString) + } else { + if (returnCode=='404') { + def message = 'Generic vnf ' + vnfId + ' was not found in AAI. Return code: 404.' + msoLogger.debug(message) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, message) + } else { + WorkflowException aWorkflowException = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) + throw new BpmnError("MSOWorkflowException") + } + } + } + + /** + * Query AAI for VF Module using vf-module-id + * @param execution + * @param isDebugLogEnabled + */ + public void queryAAIForVfModule(DelegateExecution execution, isDebugLogEnabled) { + + AaiUtil aaiUtil = new AaiUtil(this) + String queryAAIVfModuleRequest = execution.getVariable('UPDVfModVol_relatedVfModuleLink') + execution.setVariable('UPDVfModVol_personaModelId', '') + + msoLogger.debug('Query AAI VF Module: ' + queryAAIVfModuleRequest) + msoLogger.debug('Query AAI VF Module: ' + queryAAIVfModuleRequest) + + def aaiUrl = UrnPropertiesReader.getVariable("aai.endpoint", execution) + msoLogger.debug('A&AI URL: ' + aaiUrl) + + def requestEndpoint = aaiUrl + queryAAIVfModuleRequest + msoLogger.debug('A&AI request endpoint: ' + requestEndpoint) + + APIResponse response = aaiUtil.executeAAIGetCall(execution, requestEndpoint) + + String returnCode = response.getStatusCode() + String aaiResponseAsString = response.getResponseBodyAsString() + + msoLogger.debug("AAI query vf-module: " + returnCode) + msoLogger.debug("AAI query vf-module response: " + aaiResponseAsString) + + msoLogger.debug("AAI query vf-module:: " + returnCode) + msoLogger.debug("AAI query vf-module response: " + aaiResponseAsString) + + ExceptionUtil exceptionUtil = new ExceptionUtil() + + if ((returnCode == '200') || (returnCode == '204')) { + def personaModelId = utils.getNodeText(aaiResponseAsString, 'model-invariant-id') + if(personaModelId == null) { + //check old attribute name + personaModelId = utils.getNodeText(aaiResponseAsString, 'persona-model-id') + } + msoLogger.debug("vfModule personaModelId: " + personaModelId) + execution.setVariable('UPDVfModVol_personaModelId', personaModelId) + } + else if (returnCode == '404') { + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "VF Module not found at AAI") + } + else { + WorkflowException aWorkflowException = exceptionUtil.MapAAIExceptionToWorkflowException(aaiResponseAsString, execution) + throw new BpmnError("MSOWorkflowException") + } + } + /** + * + */ + public String getRelatedVfModuleRelatedLink(xml) { + def list = new XmlSlurper().parseText(xml) + def vfModuleRelationship = list.'**'.find { node -> node.'related-to'.text() == 'vf-module' } + return vfModuleRelationship?.'related-link'?.text() ?: '' + } + + /** + * Prepare a Request for invoking the VnfAdapterRest subflow to do + * a Volume Group update. + * + * @param execution The flow's execution instance. + */ + public void prepVnfAdapterRest(DelegateExecution execution, isDebugLogEnabled) { + + def aicCloudRegion = execution.getVariable('UPDVfModVol_aicCloudRegion') + def tenantId = execution.getVariable('UPDVfModVol_tenantId') + def volumeGroupId = execution.getVariable('UPDVfModVol_volumeGroupId') + + def aaiVolumeGroupResponse = execution.getVariable('UPDVfModVol_aaiVolumeGroupResponse') + def volumeGroupHeatStackId = getNodeTextForce(aaiVolumeGroupResponse, 'heat-stack-id') + def volumeGroupName = getNodeTextForce(aaiVolumeGroupResponse, 'volume-group-name') + def modelCustomizationId = getNodeTextForce(aaiVolumeGroupResponse, 'vf-module-model-customization-id') + if(modelCustomizationId == null) { + // Check old attribute name + modelCustomizationId = getNodeTextForce(aaiVolumeGroupResponse, 'vf-module-persona-model-customization-id') + } + + def vnfType = execution.getVariable('UPDVfModVol_vnfType') + def vnfVersion = execution.getVariable('UPDVfModVol_vnfVersion') + + def aaiGenericVnfResponse = execution.getVariable('UPDVfModVol_AAIQueryGenericVfnResponse') + def vnfId = utils.getNodeText(aaiGenericVnfResponse, 'vnf-id') + def vnfName = utils.getNodeText(aaiGenericVnfResponse, 'vnf-name') + + + def volumeParamsXml = execution.getVariable('UPDVfModVol_volumeParams') + def volumeGroupParams = transformVolumeParamsToEntries(volumeParamsXml) + + def requestId = execution.getVariable('UPDVfModVol_requestId') + def serviceId = execution.getVariable('UPDVfModVol_serviceId') + + def messageId = execution.getVariable('mso-request-id') + '-' + System.currentTimeMillis() + def notificationUrl = createCallbackURL(execution, "VNFAResponse", messageId) + def useQualifiedHostName = UrnPropertiesReader.getVariable("mso.use.qualified.host",execution) + if ('true'.equals(useQualifiedHostName)) { + notificationUrl = utils.getQualifiedHostNameForCallback(notificationUrl) + } + + String vnfAdapterRestRequest = """ + <updateVolumeGroupRequest> + <cloudSiteId>${MsoUtils.xmlEscape(aicCloudRegion)}</cloudSiteId> + <tenantId>${MsoUtils.xmlEscape(tenantId)}</tenantId> + <vnfId>${MsoUtils.xmlEscape(vnfId)}</vnfId> + <vnfName>${MsoUtils.xmlEscape(vnfName)}</vnfName> + <volumeGroupId>${MsoUtils.xmlEscape(volumeGroupId)}</volumeGroupId> + <volumeGroupName>${MsoUtils.xmlEscape(volumeGroupName)}</volumeGroupName> + <volumeGroupStackId>${MsoUtils.xmlEscape(volumeGroupHeatStackId)}</volumeGroupStackId> + <vnfType>${MsoUtils.xmlEscape(vnfType)}</vnfType> + <vnfVersion>${MsoUtils.xmlEscape(vnfVersion)}</vnfVersion> + <vfModuleType></vfModuleType> + <modelCustomizationUuid>${MsoUtils.xmlEscape(modelCustomizationId)}</modelCustomizationUuid> + <volumeGroupParams> + <entry> + <key>vnf_id</key> + <value>${MsoUtils.xmlEscape(vnfId)}</value> + </entry> + <entry> + <key>vnf_name</key> + <value>${MsoUtils.xmlEscape(vnfName)}</value> + </entry> + <entry> + <key>vf_module_id</key> + <value>${MsoUtils.xmlEscape(volumeGroupId)}</value> + </entry> + <entry> + <key>vf_module_name</key> + <value>${MsoUtils.xmlEscape(volumeGroupName)}</value> + </entry> + ${volumeGroupParams} + </volumeGroupParams> + <skipAAI>true</skipAAI> + <msoRequest> + <requestId>${MsoUtils.xmlEscape(requestId)}</requestId> + <serviceInstanceId>${MsoUtils.xmlEscape(serviceId)}</serviceInstanceId> + </msoRequest> + <messageId>${MsoUtils.xmlEscape(messageId)}</messageId> + <notificationUrl>${MsoUtils.xmlEscape(notificationUrl)}</notificationUrl> + </updateVolumeGroupRequest> + """ + vnfAdapterRestRequest = utils.formatXml(vnfAdapterRestRequest) + execution.setVariable('UPDVfModVol_vnfAdapterRestRequest', vnfAdapterRestRequest) + msoLogger.debug('Request for VNFAdapter Rest:\n' + vnfAdapterRestRequest) + } + + /** + * Prepare a Request for updating the DB for this Infra request. + * + * @param execution The flow's execution instance. + */ + public void prepDbInfraDbRequest(DelegateExecution execution, isDebugLogEnabled) { + + def requestId = execution.getVariable('UPDVfModVol_requestId') + ExceptionUtil exceptionUtil = new ExceptionUtil(); + + String updateInfraRequest = """ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" + xmlns:req="http://org.onap.so/requestsdb"> + <soapenv:Header/> + <soapenv:Body> + <req:updateInfraRequest> + <requestId>${MsoUtils.xmlEscape(requestId)}</requestId> + <lastModifiedBy>BPEL</lastModifiedBy> + <requestStatus>COMPLETE</requestStatus> + <progress>100</progress> + </req:updateInfraRequest> + </soapenv:Body> + </soapenv:Envelope> + """ + + updateInfraRequest = utils.formatXml(updateInfraRequest) + execution.setVariable('UPDVfModVol_updateInfraRequest', updateInfraRequest) + msoLogger.debug('Request for Update Infra Request:\n' + updateInfraRequest) + } + + /** + * Build a "CompletionHandler" request. + * @param execution The flow's execution instance. + */ + public void prepCompletionHandlerRequest(DelegateExecution execution, requestId, action, source, isDebugLogEnabled) { + + String content = """ + <aetgt:MsoCompletionRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:ns="http://org.onap/so/request/types/v1"> + <request-info xmlns="http://org.onap/so/infra/vnf-request/v1"> + <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> + <action>UPDATE</action> + <source>${MsoUtils.xmlEscape(source)}</source> + </request-info> + <aetgt:mso-bpel-name>BPMN VF Module Volume action: UPDATE</aetgt:mso-bpel-name> + </aetgt:MsoCompletionRequest> + """ + + content = utils.formatXml(content) + msoLogger.debug('Request for Completion Handler:\n' + content) + execution.setVariable('UPDVfModVol_CompletionHandlerRequest', content) + } + + + /** + * Build a "FalloutHandler" request. + * @param execution The flow's execution instance. + */ + public void prepFalloutHandler(DelegateExecution execution, isDebugLogEnabled) { + def requestId = execution.getVariable('UPDVfModVol_requestId') + def source = execution.getVariable('UPDVfModVol_source') + + String requestInfo = """ + <request-info xmlns="http://org.onap/so/infra/vnf-request/v1"> + <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> + <action>UPDATE</action> + <source>${MsoUtils.xmlEscape(source)}</source> + </request-info>""" + + def WorkflowException workflowException = execution.getVariable("WorkflowException") + def errorResponseCode = workflowException.getErrorCode() + def errorResponseMsg = workflowException.getErrorMessage() + def encErrorResponseMsg = "" + if (errorResponseMsg != null) { + encErrorResponseMsg = errorResponseMsg + } + + String content = """ + <sdncadapterworkflow:FalloutHandlerRequest xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1" + xmlns:reqtype="http://org.onap/so/request/types/v1" + xmlns:msoservtypes="http://org.onap/so/request/types/v1" + xmlns:structuredtypes="http://org.onap/so/structured/types/v1"> + ${requestInfo} + <sdncadapterworkflow:WorkflowException> + <sdncadapterworkflow:ErrorMessage>${MsoUtils.xmlEscape(encErrorResponseMsg)}</sdncadapterworkflow:ErrorMessage> + <sdncadapterworkflow:ErrorCode>${MsoUtils.xmlEscape(errorResponseCode)}</sdncadapterworkflow:ErrorCode> + </sdncadapterworkflow:WorkflowException> + </sdncadapterworkflow:FalloutHandlerRequest> + """ + content = utils.formatXml(content) + msoLogger.debug('Request for Fallout Handler:\n' + content) + execution.setVariable('UPDVfModVol_FalloutHandlerRequest', content) + } + + /** + * Create a WorkflowException for the error case where the Tenant Id from + * AAI did not match the Tenant Id in the incoming request. + * @param execution The flow's execution instance. + */ + public void handleTenantIdMismatch(DelegateExecution execution, isDebugLogEnabled) { + + def volumeGroupId = execution.getVariable('UPDVfModVol_volumeGroupId') + def aicCloudRegion = execution.getVariable('UPDVfModVol_aicCloudRegion') + def tenantId = execution.getVariable('UPDVfModVol_tenantId') + def volumeGroupTenantId = execution.getVariable('UPDVfModVol_volumeGroupTenantId') + + def String errorMessage = "TenantId " + tenantId + " in incoming request does not match Tenant Id " + volumeGroupTenantId + + " retrieved from AAI for Volume Group Id " + volumeGroupId + ", AIC Cloud Region " + aicCloudRegion + + ExceptionUtil exceptionUtil = new ExceptionUtil() + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Error in UpdateVfModuleVol: ' + errorMessage, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception"); + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, errorMessage) + } + + /** + * Create a WorkflowException for the error case where the Personal Model Id from + * AAI did not match the model invariant ID in the incoming request. + * @param execution The flow's execution instance. + */ + public void handlePersonaModelIdMismatch(DelegateExecution execution, isDebugLogEnabled) { + + def modelInvariantId = execution.getVariable('UPDVfModVol_modelInvariantId') + def personaModelId = execution.getVariable('UPDVfModVol_personaModelId') + + def String errorMessage = "Model Invariant ID " + modelInvariantId + " in incoming request does not match persona model ID " + personaModelId + + " retrieved from AAI for Volume Group Id " + + ExceptionUtil exceptionUtil = new ExceptionUtil() + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Error in UpdateVfModuleVol: ' + errorMessage, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception"); + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, errorMessage) + } + +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/UpdateVnfInfra.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/UpdateVnfInfra.groovy new file mode 100644 index 0000000000..f251dc46f8 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/UpdateVnfInfra.groovy @@ -0,0 +1,481 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts + +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.onap.appc.client.lcm.model.Action; +import org.onap.so.bpmn.common.scripts.ExceptionUtil +import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.so.bpmn.core.domain.ModelInfo +import org.onap.so.bpmn.core.domain.ServiceDecomposition +import org.onap.so.bpmn.core.domain.VnfResource +import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.client.aai.* +import org.onap.so.logger.MessageEnum +import org.onap.so.logger.MsoLogger + +import groovy.json.JsonOutput +import groovy.json.JsonSlurper + +public class UpdateVnfInfra extends VnfCmBase { + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, UpdateVnfInfra.class); + + ExceptionUtil exceptionUtil = new ExceptionUtil() + JsonUtils jsonUtils = new JsonUtils() + def prefix = "UPDVnfI_" + + /** + * Initialize the flow's variables. + * + * @param execution The flow's execution instance. + */ + public void initProcessVariables(DelegateExecution execution) { + execution.setVariable('prefix', 'UPDVnfI_') + execution.setVariable('Request', null) + execution.setVariable('source', null) + execution.setVariable('vnfInputs', null) + execution.setVariable('tenantId', null) + execution.setVariable('vnfParams', null) + execution.setVariable('controllerType', null) + execution.setVariable('UpdateVnfSuccessIndicator', false) + execution.setVariable('serviceType', null) + execution.setVariable('nfRole', null) + execution.setVariable('currentActivity', 'UPDVnfI') + execution.setVariable('workStep', null) + execution.setVariable('failedActivity', null) + execution.setVariable('errorCode', "0") + execution.setVariable('errorText', null) + execution.setVariable('healthCheckIndex0', 0) + execution.setVariable('healthCheckIndex1', 1) + execution.setVariable("rollbackSetClosedLoopDisabledFlag", false) + execution.setVariable("rollbackVnfStop", false) + execution.setVariable("rollbackVnfLock", false) + execution.setVariable("rollbackQuiesceTraffic", false) + execution.setVariable("rollbackSetVnfInMaintenanceFlag", false) + } + + /** + * Check for missing elements in the received request. + * + * @param execution The flow's execution instance. + */ + public void preProcessRequest(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.preProcessRequest(' + + 'execution=' + execution.getId() + + ')' + initProcessVariables(execution) + + msoLogger.trace('Entered ' + method) + + initProcessVariables(execution) + + def incomingRequest = execution.getVariable('bpmnRequest') + + msoLogger.debug("Incoming Infra Request: " + incomingRequest) + try { + def jsonSlurper = new JsonSlurper() + def jsonOutput = new JsonOutput() + Map reqMap = jsonSlurper.parseText(incomingRequest) + msoLogger.debug(" Request is in JSON format.") + + execution.setVariable("isVidRequest", "true") + execution.setVariable('serviceType', 'Mobility') + execution.setVariable('actionLock', Action.Lock) + execution.setVariable('actionUnlock', Action.Unlock) + execution.setVariable('actionHealthCheck', Action.HealthCheck) + execution.setVariable('actionStart', Action.Start) + execution.setVariable('actionStop', Action.Stop) + + def asdcServiceModelVersion = '' + def serviceModelInfo = null + + def relatedInstanceList = reqMap.requestDetails?.relatedInstanceList + + if (relatedInstanceList != null) { + relatedInstanceList.each { + if (it.relatedInstance.modelInfo?.modelType == 'service') { + msoLogger.debug("PROCESSING SERVICE INFO") + asdcServiceModelVersion = it.relatedInstance.modelInfo?.modelVersion + serviceModelInfo = jsonOutput.toJson(it.relatedInstance.modelInfo) + msoLogger.debug("ServiceModelInfo: " + serviceModelInfo) + def modelInvariant = jsonUtils.getJsonValue(serviceModelInfo, "modelInvariantUuid") + msoLogger.debug("modelInvariant: " + modelInvariant) + } + + } + } + + execution.setVariable('asdcServiceModelVersion', asdcServiceModelVersion) + execution.setVariable('serviceModelInfo', serviceModelInfo) + def vnfModelInfo = jsonOutput.toJson(reqMap.requestDetails?.modelInfo) + execution.setVariable('vnfModelInfo', vnfModelInfo) + def vnfModelInvariantUuid = jsonUtils.getJsonValue(vnfModelInfo, "modelInvariantUuid") + execution.setVariable('vnfModelInvariantUuid', vnfModelInvariantUuid) + msoLogger.debug("vnfModelInvariantUuid: " + vnfModelInvariantUuid) + + def vnfType = execution.getVariable('vnfType') + execution.setVariable('vnfType', vnfType) + + + def controllerType = reqMap.requestDetails?.requestParameters?.controllerType + execution.setVariable('controllerType', controllerType) + + msoLogger.debug('Controller Type: ' + controllerType) + + def userParams = reqMap.requestDetails?.requestParameters?.userParams + + Map<String, String> userParamsMap = [:] + if (userParams != null) { + userParams.each { userParam -> + userParamsMap.put(userParam.name, userParam.value.toString()) + } + } + + msoLogger.debug('Processed user params: ' + userParamsMap) + + execution.setVariable('vfModuleInputParams', userParamsMap) + + def requestId = execution.getVariable("mso-request-id") + execution.setVariable('requestId', requestId) + execution.setVariable('msoRequestId', requestId) + + + def vnfName = reqMap.requestDetails?.requestInfo?.instanceName ?: null + execution.setVariable('vnfName', vnfName) + + def requestorId = reqMap.requestDetails?.requestInfo?.requestorId ?: null + execution.setVariable('requestorId', requestorId) + + def usePreload = reqMap.requestDetails?.requestParameters?.usePreload + execution.setVariable('usePreload', usePreload) + + def cloudConfiguration = reqMap.requestDetails?.cloudConfiguration + def lcpCloudRegionId = cloudConfiguration.lcpCloudRegionId + execution.setVariable('lcpCloudRegionId', lcpCloudRegionId) + def tenantId = cloudConfiguration.tenantId + execution.setVariable('tenantId', tenantId) + + def globalSubscriberId = reqMap.requestDetails?.subscriberInfo?.globalSubscriberId ?: '' + execution.setVariable('globalSubscriberId', globalSubscriberId) + + execution.setVariable('sdncVersion', '1702') + + execution.setVariable("UpdateVnfInfraSuccessIndicator", false) + + + + def source = reqMap.requestDetails?.requestInfo?.source + execution.setVariable("source", source) + + //For Completion Handler & Fallout Handler + String requestInfo = + """<request-info xmlns="http://org.onap/so/infra/vnf-request/v1"> + <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> + <action>UPDATE</action> + <source>${MsoUtils.xmlEscape(source)}</source> + </request-info>""" + + execution.setVariable("requestInfo", requestInfo) + + msoLogger.debug('RequestInfo: ' + execution.getVariable("requestInfo")) + + msoLogger.trace('Exited ' + method) + + } + catch(groovy.json.JsonException je) { + msoLogger.debug(" Request is not in JSON format.") + exceptionUtil.buildAndThrowWorkflowException(execution, 5000, "Invalid request format") + + } + catch(Exception e) { + String restFaultMessage = e.getMessage() + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, " Exception Encountered - " + "\n" + restFaultMessage, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 5000, restFaultMessage) + } + } + + /** + * Prepare and send the sychronous response for this flow. + * + * @param execution The flow's execution instance. + */ + public void sendSynchResponse(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.sendSynchResponse(' + + 'execution=' + execution.getId() + + ')' + + msoLogger.trace('Entered ' + method) + + + try { + def requestInfo = execution.getVariable('requestInfo') + def requestId = execution.getVariable('requestId') + def source = execution.getVariable('source') + def progress = getNodeTextForce(requestInfo, 'progress') + if (progress.isEmpty()) { + progress = '0' + } + def startTime = getNodeTextForce(requestInfo, 'start-time') + if (startTime.isEmpty()) { + startTime = System.currentTimeMillis() + } + + // RESTResponse (for API Handler (APIH) Reply Task) + def vnfId = execution.getVariable("vnfId") + String synchResponse = """{"requestReferences":{"instanceId":"${vnfId}","requestId":"${requestId}"}}""".trim() + + sendWorkflowResponse(execution, 200, synchResponse) + + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in sendResponse(): ' + e.getMessage()) + } + } + + + + /** + * Get VnfResource decomposition object for this VNF. + * + * + * @param execution The flow's execution instance. + */ + public void getVnfResourceDecomposition(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.getVnfResourceDecomposition(' + + 'execution=' + execution.getId() + + ')' + + msoLogger.trace('Entered ' + method) + + try { + ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition") + String vnfModelInvariantUuid = execution.getVariable('vnfModelInvariantUuid') + msoLogger.debug("vnfModelInvariantUuid: " + vnfModelInvariantUuid) + List<VnfResource> vnfResources = serviceDecomposition.getVnfResources() + + for (i in 0..vnfResources.size()-1) { + ModelInfo modelInfo = vnfResources[i].getModelInfo() + String modelInvariantUuidFromDecomposition = modelInfo.getModelInvariantUuid() + msoLogger.debug("modelInvariantUuidFromDecomposition: " + modelInvariantUuidFromDecomposition) + + if (vnfModelInvariantUuid.equals(modelInvariantUuidFromDecomposition)) { + VnfResource vnfResourceDecomposition = vnfResources[i] + execution.setVariable('vnfResourceDecomposition', vnfResourceDecomposition) + def nfRole = vnfResourceDecomposition.getNfRole() + execution.setVariable('nfRole', nfRole) + msoLogger.debug("vnfResourceDecomposition: " + vnfResourceDecomposition.toJsonString()) + break + } + else { + //exception! + } + + } + + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in getVnfResourceDecomposition(): ' + e.getMessage()) + } + } + + /** + * Check if this VNF is already in maintenance in A&AI. + * + * + * @param execution The flow's execution instance. + */ + public void checkIfVnfInMaintInAAI(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.checkIfVnfInMaintInAAI(' + + 'execution=' + execution.getId() + + ')' + + execution.setVariable('errorCode', "0") + execution.setVariable("workStep", "checkIfVnfInMaintInAAI") + execution.setVariable("failedActivity", "AAI") + msoLogger.trace('Entered ' + method) + + try { + def transactionLoggingUuid = UUID.randomUUID().toString() + AAIRestClientImpl client = new AAIRestClientImpl() + AAIValidatorImpl aaiValidator = new AAIValidatorImpl() + aaiValidator.setClient(client) + def vnfId = execution.getVariable("vnfId") + boolean isInMaint = aaiValidator.isVNFLocked(vnfId, transactionLoggingUuid) + msoLogger.debug("isInMaint result: " + isInMaint) + execution.setVariable('isVnfInMaintenance', isInMaint) + + if (isInMaint) { + execution.setVariable("errorCode", "1003") + execution.setVariable("errorText", "VNF is in maintenance in A&AI") + } + + + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + execution.setVariable("errorCode", "1002") + execution.setVariable("errorText", e.getMessage()) + //exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in checkIfVnfInMaintInAAI(): ' + e.getMessage()) + } + } + + + /** + * Check if this VNF's pservers are locked in A&AI. + * + * + * @param execution The flow's execution instance. + */ + public void checkIfPserversInMaintInAAI(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.checkIfPserversInMaintInAAI(' + + 'execution=' + execution.getId() + + ')' + + execution.setVariable('errorCode', "0") + msoLogger.trace('Entered ' + method) + execution.setVariable("workStep", "checkIfPserversInMaintInAAI") + execution.setVariable("failedActivity", "AAI") + + try { + def transactionLoggingUuid = UUID.randomUUID().toString() + AAIRestClientImpl client = new AAIRestClientImpl() + AAIValidatorImpl aaiValidator = new AAIValidatorImpl() + aaiValidator.setClient(client) + def vnfId = execution.getVariable("vnfId") + boolean areLocked = aaiValidator.isPhysicalServerLocked(vnfId, transactionLoggingUuid) + msoLogger.debug("areLocked result: " + areLocked) + execution.setVariable('arePserversLocked', areLocked) + + if (areLocked) { + execution.setVariable("errorCode", "1003") + execution.setVariable("errorText", "pServers are locked in A&AI") + } + + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + execution.setVariable("errorCode", "1002") + execution.setVariable("errorText", e.getMessage()) + //exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in checkIfPserversInMaintInAAI(): ' + e.getMessage()) + } + } + + /** + * Set inMaint flag for this VNF to the specified value in A&AI. + * + * + * @param execution The flow's execution instance. + * @param inMaint The boolean value of the flag to set + */ + public void setVnfInMaintFlagInAAI(DelegateExecution execution, boolean inMaint) { + def method = getClass().getSimpleName() + '.setVnfInMaintFlagInAAI(' + + 'execution=' + execution.getId() + + ')' + + execution.setVariable('errorCode', "0") + msoLogger.trace('Entered ' + method) + if (inMaint) { + execution.setVariable("workStep", "setVnfInMaintFlagInAAI") + } + else { + execution.setVariable("workStep", "unsetVnfInMaintFlagInAAI") + } + execution.setVariable("failedActivity", "AAI") + + try { + def transactionLoggingUuid = UUID.randomUUID().toString() + AAIRestClientImpl client = new AAIRestClientImpl() + AAIUpdatorImpl aaiUpdator = new AAIUpdatorImpl() + aaiUpdator.setClient(client) + def vnfId = execution.getVariable("vnfId") + if (inMaint) { + aaiUpdator.updateVnfToLocked(vnfId, transactionLoggingUuid) + execution.setVariable("rollbackSetVnfInMaintenanceFlag", true) + } + else { + aaiUpdator.updateVnfToUnLocked(vnfId, transactionLoggingUuid) + } + + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + execution.setVariable("errorCode", "1002") + execution.setVariable("errorText", e.getMessage()) + //exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in setVnfInMaintFlagInAAI(): ' + e.getMessage()) + } + } + + + + /** + * Prepare DoUpdateVnfAndModules call. + * + * + * @param execution The flow's execution instance. + */ + public void prepDoUpdateVnfAndModules(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.prepDoUpdateVnfAndModules(' + + 'execution=' + execution.getId() + + ')' + + execution.setVariable('errorCode', "0") + msoLogger.trace('Entered ' + method) + execution.setVariable("workStep", "doUpdateVnfAndModules") + execution.setVariable("failedActivity", "MSO Update VNF") + msoLogger.trace('Exited ' + method) + + } + + + /** + * Handle Abort disposition from RainyDayHandler + * + * @param execution The flow's execution instance. + */ + public void abortProcessing(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.abortProcessing(' + + 'execution=' + execution.getId() + + ')' + + msoLogger.trace('Entered ' + method) + + def errorText = execution.getVariable("errorText") + def errorCode = execution.getVariable("errorCode") + + exceptionUtil.buildAndThrowWorkflowException(execution, errorCode as Integer, errorText) + } + + + + +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/VnfCmBase.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/VnfCmBase.groovy new file mode 100644 index 0000000000..fd9d9cc8a3 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/VnfCmBase.groovy @@ -0,0 +1,835 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts + +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.json.JSONArray +import org.json.JSONObject +import org.onap.appc.client.lcm.model.Action; +import org.onap.appc.client.lcm.model.ActionIdentifiers +import org.onap.appc.client.lcm.model.Flags +import org.onap.appc.client.lcm.model.Status +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor; +import org.onap.so.bpmn.common.scripts.ExceptionUtil +import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.bpmn.core.domain.ModelInfo +import org.onap.so.bpmn.core.domain.ServiceDecomposition +import org.onap.so.bpmn.core.domain.VnfResource +import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.client.aai.* +import org.onap.so.client.aai.entities.AAIResultWrapper +import org.onap.so.client.aai.entities.Relationships +import org.onap.so.client.aai.entities.uri.AAIResourceUri +import org.onap.so.client.aai.entities.uri.AAIUri +import org.onap.so.client.aai.entities.uri.AAIUriFactory +import org.onap.so.client.appc.ApplicationControllerClient; +import org.onap.so.client.appc.ApplicationControllerSupport; +import org.onap.so.logger.MessageEnum +import org.onap.so.logger.MsoLogger + +import groovy.json.JsonSlurper + +public abstract class VnfCmBase extends AbstractServiceTaskProcessor { + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, VnfCmBase.class); + + ExceptionUtil exceptionUtil = new ExceptionUtil() + JsonUtils jsonUtils = new JsonUtils() + def prefix = "VnfIPU_" + + /** + * Initialize the flow's variables. + * + * @param execution The flow's execution instance. + */ + + /** + * Prepare and send the sychronous response for this flow. + * + * @param execution The flow's execution instance. + */ + public void sendSynchResponse(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.sendSynchResponse(' + + 'execution=' + execution.getId() + + ')' + + msoLogger.trace('Entered ' + method) + + + try { + def requestInfo = execution.getVariable('requestInfo') + def requestId = execution.getVariable('requestId') + def source = execution.getVariable('source') + def progress = getNodeTextForce(requestInfo, 'progress') + if (progress.isEmpty()) { + progress = '0' + } + def startTime = getNodeTextForce(requestInfo, 'start-time') + if (startTime.isEmpty()) { + startTime = System.currentTimeMillis() + } + + // RESTResponse (for API Handler (APIH) Reply Task) + def vnfId = execution.getVariable("vnfId") + String synchResponse = """{"requestReferences":{"instanceId":"${vnfId}","requestId":"${requestId}"}}""".trim() + + sendWorkflowResponse(execution, 200, synchResponse) + + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in sendResponse(): ' + e.getMessage()) + } + } + + + + /** + * Get VnfResource decomposition object for this VNF. + * + * + * @param execution The flow's execution instance. + */ + public void getVnfResourceDecomposition(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.getVnfResourceDecomposition(' + + 'execution=' + execution.getId() + + ')' + msoLogger.trace('Entered ' + method) + + try { + ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition") + String vnfModelInvariantUuid = execution.getVariable('vnfModelInvariantUuid') + msoLogger.debug("vnfModelInvariantUuid: " + vnfModelInvariantUuid) + List<VnfResource> vnfResources = serviceDecomposition.getVnfResources() + + for (i in 0..vnfResources.size()-1) { + ModelInfo modelInfo = vnfResources[i].getModelInfo() + String modelInvariantUuidFromDecomposition = modelInfo.getModelInvariantUuid() + msoLogger.debug("modelInvariantUuidFromDecomposition: " + modelInvariantUuidFromDecomposition) + + if (vnfModelInvariantUuid.equals(modelInvariantUuidFromDecomposition)) { + VnfResource vnfResourceDecomposition = vnfResources[i] + execution.setVariable('vnfResourceDecomposition', vnfResourceDecomposition) + def nfRole = vnfResourceDecomposition.getNfRole() + execution.setVariable('nfRole', nfRole) + msoLogger.debug("vnfResourceDecomposition: " + vnfResourceDecomposition.toJsonString()) + break + } + else { + //exception! + } + + } + + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in getVnfResourceDecomposition(): ' + e.getMessage()) + } + } + + /** + * Check if this VNF is already in maintenance in A&AI. + * + * + * @param execution The flow's execution instance. + */ + public void checkIfVnfInMaintInAAI(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.checkIfVnfInMaintInAAI(' + + 'execution=' + execution.getId() + + ')' + + execution.setVariable('errorCode', "0") + execution.setVariable("workStep", "checkIfVnfInMaintInAAI") + execution.setVariable("failedActivity", "AAI") + msoLogger.trace('Entered ' + method) + + try { + def transactionLoggingUuid = UUID.randomUUID().toString() + AAIRestClientImpl client = new AAIRestClientImpl() + AAIValidatorImpl aaiValidator = new AAIValidatorImpl() + aaiValidator.setClient(client) + def vnfId = execution.getVariable("vnfId") + boolean isInMaint = aaiValidator.isVNFLocked(vnfId, transactionLoggingUuid) + msoLogger.debug("isInMaint result: " + isInMaint) + execution.setVariable('isVnfInMaintenance', isInMaint) + + if (isInMaint) { + execution.setVariable("errorCode", "1003") + execution.setVariable("errorText", "VNF is in maintenance in A&AI") + } + + + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + execution.setVariable("errorCode", "1002") + execution.setVariable("errorText", e.getMessage()) + //exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in checkIfVnfInMaintInAAI(): ' + e.getMessage()) + } + } + + /** + * Get VNF info from A&AI. + * + * + * @param execution The flow's execution instance. + */ + public void queryAAIForVnf(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.queryAAIForVnf(' + + 'execution=' + execution.getId() + + ')' + + msoLogger.trace('Entered ' + method) + + try { + def transactionLoggingUuid = UUID.randomUUID().toString() + def vnfId = execution.getVariable("vnfId") + msoLogger.debug("vnfId is: " + vnfId) + def cloudRegionId = execution.getVariable("lcpCloudRegionId") + msoLogger.debug("cloudRegionId is: " + cloudRegionId) + + AAIResourcesClient client = new AAIResourcesClient() + AAIUri genericVnfUri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId) + // Check if this VNF exists + if (!client.exists(genericVnfUri)) { + msoLogger.debug("VNF with vnfId " + vnfId + " does not exist in A&AI") + exceptionUtil.buildAndThrowWorkflowException(execution, 404, "VNF with vnfId " + vnfId + " does not exist in A&AI") + } + + AAIResultWrapper aaiRW = client.get(genericVnfUri) + + Map<String, Object> result = aaiRW.asMap() + + String vnfName = result.get("vnf-name") + msoLogger.debug("vnfName from A&AI is: " + vnfName) + execution.setVariable("vnfName", vnfName) + String nfRole = result.get("nf-role") + msoLogger.debug("nfRole from A&AI is: " + nfRole) + execution.setVariable("nfRole", nfRole) + String vnfHostIpAddress = result.get("ipv4-oam-address") + msoLogger.debug("vnfHostIpAddress from A&AI is: " + vnfHostIpAddress) + execution.setVariable("vnfHostIpAddress", vnfHostIpAddress) + execution.setVariable("vmIdList", null) + if (aaiRW.getRelationships() != null) { + Relationships relationships = aaiRW.getRelationships().get() + if (relationships != null) { + + List<AAIResourceUri> vserverUris = relationships.getRelatedAAIUris(AAIObjectType.VSERVER) + JSONArray vserverIds = new JSONArray() + JSONArray vserverSelfLinks = new JSONArray() + + for (AAIResourceUri j in vserverUris) { + + String vserverId = j.getURIKeys().get('vserver-id') + String vserverJson = client.get(j).getJson() + msoLogger.debug("Retrieved vserverJson from AAI: " + vserverJson) + String vserverSelfLink = jsonUtils.getJsonValue(vserverJson, "vserver-selflink") + + vserverIds.put(vserverId) + vserverSelfLinks.put(vserverSelfLink) + } + + JSONObject vmidsArray = new JSONObject() + JSONObject vserveridsArray = new JSONObject() + vmidsArray.put("vmIds", vserverSelfLinks.toString()) + vserveridsArray.put("vserverIds", vserverIds.toString()) + + msoLogger.debug("vmidsArray is: " + vmidsArray.toString()) + msoLogger.debug("vserveridsArray is: " + vserveridsArray.toString()) + + execution.setVariable("vmIdList", vmidsArray.toString()) + execution.setVariable("vserverIdList", vserveridsArray.toString()) + } + } + + if (cloudRegionId != null) { + AAIUri cloudRegionUri = AAIUriFactory.createResourceUri(AAIObjectType.DEFAULT_CLOUD_REGION, cloudRegionId) + // Check if this client region exists + if (!client.exists(cloudRegionUri)) { + msoLogger.debug("Cloud Region with cloudRegionId " + cloudRegionId + " does not exist in A&AI") + exceptionUtil.buildAndThrowWorkflowException(execution, 404, "Cloud Region with cloudRegionId " + cloudRegionId + " does not exist in A&AI") + } + + AAIResultWrapper aaiRWCloud = client.get(cloudRegionUri) + + Map<String, Object> resultCloud = aaiRWCloud.asMap() + + String aicIdentity = resultCloud.get("identity-url") + msoLogger.debug("aicIdentity from A&AI is: " + aicIdentity) + execution.setVariable("aicIdentity", aicIdentity) + } + // preserve relationships if exist + Optional<Relationships> relationships = aaiRW.getRelationships() + + if(relationships.isPresent()) { + msoLogger.debug("relationships are present") + String rs = relationships.get().getJson() + def jsonSlurper = new JsonSlurper() + def map = jsonSlurper.parseText(rs) + if (map instanceof Map) { + List<Map<String, Object>> relationshipsList = (List<Map<String, Object>>)map.get("relationship"); + for (Map<String, Object> relationship : relationshipsList) { + final String relatedTo = (String)relationship.get("related-to"); + if (relatedTo.equals("platform")) { + List<Map<String, Object>> relationshipDataList = (List<Map<String, Object>>)relationship.get("relationship-data") + msoLogger.debug("Found platform entry") + for (Map<String, Object> relationshipData : relationshipDataList) { + String relationshipKey = (String)relationshipData.get("relationship-key"); + if (relationshipKey.equals("platform.platform-name")) { + String platformName = (String) relationshipData.get("relationship-value") + msoLogger.debug("platform from A&AI is: " + platformName) + execution.setVariable("platform", platformName) + break + } + } + } + if (relatedTo.equals("line-of-business")) { + List<Map<String, Object>> relationshipDataList = (List<Map<String, Object>>)relationship.get("relationship-data") + msoLogger.debug("Found line-of-business entry") + for (Map<String, Object> relationshipData : relationshipDataList) { + String relationshipKey = (String)relationshipData.get("relationship-key"); + if (relationshipKey.equals("line-of-business.line-of-business-name")) { + String lineOfBusinessName = (String) relationshipData.get("relationship-value") + msoLogger.debug("lineOfBusiness from A&AI is: " + lineOfBusinessName) + execution.setVariable("lineOfBusiness", lineOfBusinessName) + break + } + } + } + } + + } + + } + + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in queryAAIForVnf(): ' + e.getMessage()) + } + } + + + + /** + * Check if this VNF's pservers are locked in A&AI. + * + * + * @param execution The flow's execution instance. + */ + public void checkIfPserversInMaintInAAI(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.checkIfPserversInMaintInAAI(' + + 'execution=' + execution.getId() + + ')' + + execution.setVariable('errorCode', "0") + msoLogger.trace('Entered ' + method) + execution.setVariable("workStep", "checkIfPserversInMaintInAAI") + execution.setVariable("failedActivity", "AAI") + + try { + def transactionLoggingUuid = UUID.randomUUID().toString() + AAIRestClientImpl client = new AAIRestClientImpl() + AAIValidatorImpl aaiValidator = new AAIValidatorImpl() + aaiValidator.setClient(client) + def vnfId = execution.getVariable("vnfId") + boolean areLocked = aaiValidator.isPhysicalServerLocked(vnfId, transactionLoggingUuid) + msoLogger.debug("areLocked result: " + areLocked) + execution.setVariable('arePserversLocked', areLocked) + + if (areLocked) { + execution.setVariable("errorCode", "1003") + execution.setVariable("errorText", "pServers are locked in A&AI") + } + + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + execution.setVariable("errorCode", "1002") + execution.setVariable("errorText", e.getMessage()) + //exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in checkIfPserversInMaintInAAI(): ' + e.getMessage()) + } + } + + /** + * Set inMaint flag for this VNF to the specified value in A&AI. + * + * + * @param execution The flow's execution instance. + * @param inMaint The boolean value of the flag to set + */ + public void setVnfInMaintFlagInAAI(DelegateExecution execution, boolean inMaint) { + def method = getClass().getSimpleName() + '.setVnfInMaintFlagInAAI(' + + 'execution=' + execution.getId() + + ')' + + execution.setVariable('errorCode', "0") + msoLogger.trace('Entered ' + method) + if (inMaint) { + execution.setVariable("workStep", "setVnfInMaintFlagInAAI") + } + else { + execution.setVariable("workStep", "unsetVnfInMaintFlagInAAI") + } + execution.setVariable("failedActivity", "AAI") + + try { + def transactionLoggingUuid = UUID.randomUUID().toString() + AAIRestClientImpl client = new AAIRestClientImpl() + AAIUpdatorImpl aaiUpdator = new AAIUpdatorImpl() + aaiUpdator.setClient(client) + def vnfId = execution.getVariable("vnfId") + if (inMaint) { + aaiUpdator.updateVnfToLocked(vnfId, transactionLoggingUuid) + execution.setVariable("rollbackSetVnfInMaintenanceFlag", true) + } + else { + aaiUpdator.updateVnfToUnLocked(vnfId, transactionLoggingUuid) + } + + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + execution.setVariable("errorCode", "1002") + execution.setVariable("errorText", e.getMessage()) + //exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in setVnfInMaintFlagInAAI(): ' + e.getMessage()) + } + } + + /** + * Check if VF Closed Loop Disabled in A&AI. + * + * + * @param execution The flow's execution instance. + */ + public void checkIfClosedLoopDisabledInAAI(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.checkIfClosedLoopDisabledInAAI(' + + 'execution=' + execution.getId() + + ')' + + execution.setVariable('errorCode', "0") + execution.setVariable("workStep", "checkClosedLoopDisabledFlagInAAI") + execution.setVariable("failedActivity", "AAI") + msoLogger.trace('Entered ' + method) + + try { + def transactionLoggingUuid = UUID.randomUUID().toString() + def vnfId = execution.getVariable("vnfId") + msoLogger.debug("vnfId is: " + vnfId) + AAIResourcesClient client = new AAIResourcesClient() + AAIUri genericVnfUri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId) + AAIResultWrapper aaiRW = client.get(genericVnfUri) + Map<String, Object> result = aaiRW.asMap() + boolean isClosedLoopDisabled = result.getOrDefault("is-closed-loop-disabled", false) + + msoLogger.debug("isClosedLoopDisabled result: " + isClosedLoopDisabled) + execution.setVariable('isClosedLoopDisabled', isClosedLoopDisabled) + + if (isClosedLoopDisabled) { + execution.setVariable("errorCode", "1004") + execution.setVariable("errorText", "closedLoop is disabled in A&AI") + } + + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + execution.setVariable("errorCode", "1002") + execution.setVariable("errorText", e.getMessage()) + } + } + + /** + * Set VF Closed Loop Disabled Flag in A&AI. + * + * + * @param execution The flow's execution instance. + */ + public void setClosedLoopDisabledInAAI(DelegateExecution execution, boolean setDisabled) { + def method = getClass().getSimpleName() + '.setClosedLoopDisabledInAAI(' + + 'execution=' + execution.getId() + + ')' + + execution.setVariable('errorCode', "0") + if (setDisabled) { + execution.setVariable("workStep", "setClosedLoopDisabledFlagInAAI") + execution.setVariable("rollbackSetClosedLoopDisabledFlag", true) + } + else { + execution.setVariable("workStep", "unsetClosedLoopDisabledFlagInAAI") + execution.setVariable("rollbackSetClosedLoopDisabledFlag", false) + } + + execution.setVariable("failedActivity", "AAI") + msoLogger.trace('Entered ' + method) + + try { + def transactionLoggingUuid = UUID.randomUUID().toString() + def vnfId = execution.getVariable("vnfId") + AAIResourcesClient client = new AAIResourcesClient() + AAIUri genericVnfUri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId) + + Map<String, Boolean> request = new HashMap<>() + request.put("is-closed-loop-disabled", setDisabled) + client.update(genericVnfUri, request) + msoLogger.debug("set isClosedLoop to: " + setDisabled) + + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + execution.setVariable("errorCode", "1002") + execution.setVariable("errorText", e.getMessage()) + } + } + + + + + /** + * Call APP-C client to execute specified APP-C command for this VNF. + * + * + * @param execution The flow's execution instance. + * @param action The action to take in APP-C. + */ + public void runAppcCommand(DelegateExecution execution, Action action) { + def method = getClass().getSimpleName() + '.runAppcCommand(' + + 'execution=' + execution.getId() + + ')' + + execution.setVariable('errorCode', "0") + msoLogger.trace('Entered ' + method) + + ApplicationControllerClient appcClient = null + + try { + msoLogger.debug("Running APP-C action: " + action.toString()) + String vnfId = execution.getVariable('vnfId') + String msoRequestId = execution.getVariable('requestId') + execution.setVariable('msoRequestId', msoRequestId) + execution.setVariable("failedActivity", "APP-C") + + appcClient = new ApplicationControllerClient() + ApplicationControllerSupport support = new ApplicationControllerSupport() + appcClient.appCSupport=support + org.springframework.test.util.ReflectionTestUtils.setField(support, "lcmModelPackage", "org.onap.appc.client.lcm.model"); + Flags flags = new Flags(); + ActionIdentifiers actionIdentifiers = new ActionIdentifiers(); + actionIdentifiers.setVnfId(vnfId); + Status appcStatus + switch(action) { + case Action.Lock: + execution.setVariable('workStep', "LockVNF") + appcStatus = appcClient.runCommand(Action.Lock,actionIdentifiers,null,msoRequestId) + break + case Action.Unlock: + execution.setVariable('workStep', "UnlockVNF") + appcStatus = appcClient.runCommand(Action.Unlock,actionIdentifiers,null,msoRequestId) + break + case Action.HealthCheck: + def healthCheckIndex = execution.getVariable('healthCheckIndex') + execution.setVariable('workStep', "HealthCheckVNF" + healthCheckIndex) + execution.setVariable('healthCheckIndex', healthCheckIndex + 1) + appcStatus = appcClient.runCommand(Action.HealthCheck,actionIdentifiers,null,msoRequestId) + break + case Action.Start: + execution.setVariable('workStep', "StartVNF") + appcStatus = appcClient.runCommand(Action.Start,actionIdentifiers,null,msoRequestId) + break + case Action.Stop: + execution.setVariable('workStep', "StopVNF") + appcStatus = appcClient.runCommand(Action.Stop,actionIdentifiers,null,msoRequestId) + break + default: + break + } + msoLogger.debug("Completed AppC request") + int appcCode = appcStatus.getCode() + msoLogger.debug("AppC status code is: " + appcCode) + msoLogger.debug("AppC status message is: " + appcStatus.getMessage()) + if (support.getCategoryOf(appcStatus) == ApplicationControllerSupport.StatusCategory.ERROR) { + execution.setVariable("errorCode", Integer.toString(appcCode)) + execution.setVariable("errorText", appcStatus.getMessage()) + } + + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + execution.setVariable("errorCode", "1002") + execution.setVariable("errorText", e.getMessage()) + + } catch (java.lang.NoSuchMethodError e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + execution.setVariable("errorCode", "1002") + execution.setVariable("errorText", e.getMessage()) + + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + execution.setVariable("errorCode", "1002") + execution.setVariable("errorText", e.getMessage()) + + } + } + + /** + * Placeholder for a call to APP-C client to execute specified APP-C command for this VNF. + * + * + * @param execution The flow's execution instance. + * @param action The action to take in APP-C. + */ + public void runAppcCommandPlaceholder(DelegateExecution execution, String action) { + def method = getClass().getSimpleName() + '.runAppcCommandPlaceholder(' + + 'execution=' + execution.getId() + + ')' + + execution.setVariable('errorCode', "0") + msoLogger.trace('Entered ' + method) + execution.setVariable("failedActivity", "APP-C") + execution.setVariable("workStep", action) + } + + + + + + + + /** + * Builds a "CompletionHandler" request and stores it in the specified execution variable. + * + * @param execution the execution + * @param resultVar the execution variable in which the result will be stored + */ + public void completionHandlerPrep(DelegateExecution execution, String resultVar) { + def method = getClass().getSimpleName() + '.completionHandlerPrep(' + + 'execution=' + execution.getId() + + ', resultVar=' + resultVar + + ')' + + msoLogger.trace('Entered ' + method) + + try { + + def requestInfo = execution.getVariable('requestInfo') + + String content = """ + <sdncadapterworkflow:MsoCompletionRequest xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1" + xmlns:reqtype="http://org.onap/so/request/types/v1"> + ${requestInfo} + <sdncadapterworkflow:status-message>Vnf has been updated successfully.</sdncadapterworkflow:status-message> + <sdncadapterworkflow:mso-bpel-name>MSO_ACTIVATE_BPEL</sdncadapterworkflow:mso-bpel-name> + </sdncadapterworkflow:MsoCompletionRequest> + """ + + content = utils.formatXml(content) + msoLogger.debug(resultVar + ' = ' + System.lineSeparator() + content) + execution.setVariable(resultVar, content) + + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 2000, 'Internal Error') + } + } + + /** + * Prepare DoUpdateVnfAndModules call. + * + * + * @param execution The flow's execution instance. + */ + public void prepDoUpdateVnfAndModules(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.prepDoUpdateVnfAndModules(' + + 'execution=' + execution.getId() + + ')' + + execution.setVariable('errorCode', "0") + msoLogger.trace('Entered ' + method) + execution.setVariable("workStep", "doUpdateVnfAndModules") + execution.setVariable("failedActivity", "MSO Update VNF") + msoLogger.trace('Exited ' + method) + + } + + /** + * Builds a "FalloutHandler" request and stores it in the specified execution variable. + * + * @param execution the execution + * @param resultVar the execution variable in which the result will be stored + */ + public void falloutHandlerPrep(DelegateExecution execution, String resultVar) { + def method = getClass().getSimpleName() + '.falloutHandlerPrep(' + + 'execution=' + execution.getId() + + ', resultVar=' + resultVar + + ')' + + msoLogger.trace('Entered ' + method) + + try { + def prefix = execution.getVariable('prefix') + def requestInformation = execution.getVariable("requestInfo") + + def WorkflowException workflowException = execution.getVariable("WorkflowException") + def errorResponseCode = workflowException.getErrorCode() + def errorResponseMsg = workflowException.getErrorMessage() + def encErrorResponseMsg = "" + if (errorResponseMsg != null) { + encErrorResponseMsg = errorResponseMsg + } + + String content = """ + <sdncadapterworkflow:FalloutHandlerRequest xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1" + xmlns:reqtype="http://org.onap/so/request/types/v1" + xmlns:msoservtypes="http://org.onap/so/request/types/v1" + xmlns:structuredtypes="http://org.onap/so/structured/types/v1"> + ${requestInformation} + <sdncadapterworkflow:WorkflowException> + <sdncadapterworkflow:ErrorMessage>${MsoUtils.xmlEscape(encErrorResponseMsg)}</sdncadapterworkflow:ErrorMessage> + <sdncadapterworkflow:ErrorCode>${MsoUtils.xmlEscape(errorResponseCode)}</sdncadapterworkflow:ErrorCode> + </sdncadapterworkflow:WorkflowException> + </sdncadapterworkflow:FalloutHandlerRequest> + """ + content = utils.formatXml(content) + msoLogger.debug(resultVar + ' = ' + System.lineSeparator() + content) + execution.setVariable(resultVar, content) + + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildWorkflowException(execution, 2000, 'Internal Error') + } + } + + /** + * Handle Abort disposition from RainyDayHandler + * + * @param execution The flow's execution instance. + */ + public void abortProcessing(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.abortProcessing(' + + 'execution=' + execution.getId() + + ')' + + msoLogger.trace('Entered ' + method) + + def errorText = execution.getVariable("errorText") + def errorCode = execution.getVariable("errorCode") + + exceptionUtil.buildAndThrowWorkflowException(execution, errorCode as Integer, errorText) + } + + /** + * Increment Retry Count for Current Work Step + * + * @param execution The flow's execution instance. + */ + public void incrementRetryCount(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.incrementRetryCount(' + + 'execution=' + execution.getId() + + ')' + + msoLogger.trace('Entered ' + method) + + String retryCountVariableName = execution.getVariable("workStep") + "RetryCount" + execution.setVariable("retryCountVariableName", retryCountVariableName) + + def retryCountVariable = execution.getVariable(retryCountVariableName) + int retryCount = 0 + + if (retryCountVariable != null) { + retryCount = (int) retryCountVariable + } + + retryCount += 1 + + execution.setVariable(retryCountVariableName, retryCount) + + msoLogger.debug("value of " + retryCountVariableName + " is " + retryCount) + msoLogger.trace('Exited ' + method) + + + } + + + public void preProcessRollback (DelegateExecution execution) { + msoLogger.trace("preProcessRollback ") + try { + + Object workflowException = execution.getVariable("WorkflowException"); + + if (workflowException instanceof WorkflowException) { + msoLogger.debug("Prev workflowException: " + workflowException.getErrorMessage()) + execution.setVariable("prevWorkflowException", workflowException); + //execution.setVariable("WorkflowException", null); + } + } catch (BpmnError e) { + msoLogger.debug("BPMN Error during preProcessRollback") + } catch(Exception ex) { + String msg = "Exception in preProcessRollback. " + ex.getMessage() + msoLogger.debug(msg) + } + msoLogger.trace("Exit preProcessRollback ") + } + + public void postProcessRollback (DelegateExecution execution) { + msoLogger.trace("postProcessRollback ") + String msg = "" + try { + Object workflowException = execution.getVariable("prevWorkflowException"); + if (workflowException instanceof WorkflowException) { + msoLogger.debug("Setting prevException to WorkflowException: ") + execution.setVariable("WorkflowException", workflowException); + } + + } catch (BpmnError b) { + msoLogger.debug("BPMN Error during postProcessRollback") + throw b; + } catch(Exception ex) { + msg = "Exception in postProcessRollback. " + ex.getMessage() + msoLogger.debug(msg) + } + msoLogger.trace("Exit postProcessRollback ") + } + + + +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/VnfConfigUpdate.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/VnfConfigUpdate.groovy new file mode 100644 index 0000000000..8ca2871916 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/VnfConfigUpdate.groovy @@ -0,0 +1,483 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts + +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.onap.appc.client.lcm.model.Action; +import org.onap.so.bpmn.common.scripts.ExceptionUtil +import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.client.aai.* +import org.onap.so.client.aai.entities.AAIResultWrapper +import org.onap.so.client.aai.entities.uri.AAIUri +import org.onap.so.client.aai.entities.uri.AAIUriFactory +import org.onap.so.logger.MessageEnum +import org.onap.so.logger.MsoLogger + +import groovy.json.JsonOutput +import groovy.json.JsonSlurper + +public class VnfConfigUpdate extends VnfCmBase { + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, VnfConfigUpdate.class); + + ExceptionUtil exceptionUtil = new ExceptionUtil() + JsonUtils jsonUtils = new JsonUtils() + def prefix = "VnfIPU_" + + /** + * Initialize the flow's variables. + * + * @param execution The flow's execution instance. + */ + public void initProcessVariables(DelegateExecution execution) { + execution.setVariable('prefix', 'VnfCU_') + execution.setVariable('Request', null) + execution.setVariable('source', null) + execution.setVariable('controllerType', null) + execution.setVariable('UpdateVnfSuccessIndicator', false) + execution.setVariable('serviceType', null) + execution.setVariable('nfRole', null) + execution.setVariable('currentActivity', 'VnfCU') + execution.setVariable('workStep', null) + execution.setVariable('failedActivity', null) + execution.setVariable('errorCode', "0") + execution.setVariable('errorText', null) + execution.setVariable('healthCheckIndex0', 0) + execution.setVariable('healthCheckIndex1', 1) + execution.setVariable('maxRetryCount', 3) + execution.setVariable('retryCount', 0) + execution.setVariable("lcpCloudRegionId", null) + execution.setVariable("rollbackSetClosedLoopDisabledFlag", false) + execution.setVariable("rollbackVnfStop", false) + execution.setVariable("rollbackVnfLock", false) + execution.setVariable("rollbackQuiesceTraffic", false) + execution.setVariable("rollbackSetVnfInMaintenanceFlag", false) + } + + /** + * Check for missing elements in the received request. + * + * @param execution The flow's execution instance. + */ + public void preProcessRequest(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.preProcessRequest(' + + 'execution=' + execution.getId() + + ')' + initProcessVariables(execution) + + msoLogger.trace('Entered ' + method) + + initProcessVariables(execution) + + def incomingRequest = execution.getVariable('bpmnRequest') + + msoLogger.debug("Incoming Infra Request: " + incomingRequest) + try { + def jsonSlurper = new JsonSlurper() + def jsonOutput = new JsonOutput() + Map reqMap = jsonSlurper.parseText(incomingRequest) + msoLogger.debug(" Request is in JSON format.") + + def serviceInstanceId = execution.getVariable('serviceInstanceId') + def vnfId = execution.getVariable('vnfId') + + execution.setVariable('serviceInstanceId', serviceInstanceId) + execution.setVariable('vnfId', vnfId) + execution.setVariable('serviceType', 'Mobility') + execution.setVariable('payload', "") + execution.setVariable('actionHealthCheck', Action.HealthCheck) + execution.setVariable('actionConfigModify', Action.ConfigModify) + + + def controllerType = reqMap.requestDetails?.requestParameters?.controllerType + execution.setVariable('controllerType', controllerType) + + msoLogger.debug('Controller Type: ' + controllerType) + + def payload = reqMap.requestDetails?.requestParameters?.payload + execution.setVariable('payload', payload) + + msoLogger.debug('Processed payload: ' + payload) + + def requestId = execution.getVariable("mso-request-id") + execution.setVariable('requestId', requestId) + execution.setVariable('msoRequestId', requestId) + + def requestorId = reqMap.requestDetails?.requestInfo?.requestorId ?: null + execution.setVariable('requestorId', requestorId) + + execution.setVariable('sdncVersion', '1702') + + execution.setVariable("UpdateVnfInfraSuccessIndicator", false) + + + + def source = reqMap.requestDetails?.requestInfo?.source + execution.setVariable("source", source) + + //For Completion Handler & Fallout Handler + String requestInfo = + """<request-info xmlns="http://org.onap/so/infra/vnf-request/v1"> + <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> + <action>UPDATE</action> + <source>${MsoUtils.xmlEscape(source)}</source> + </request-info>""" + + execution.setVariable("requestInfo", requestInfo) + + msoLogger.debug('RequestInfo: ' + execution.getVariable("requestInfo")) + + msoLogger.trace('Exited ' + method) + + } + catch(groovy.json.JsonException je) { + msoLogger.debug(" Request is not in JSON format.") + exceptionUtil.buildAndThrowWorkflowException(execution, 5000, "Invalid request format") + + } + catch(Exception e) { + String restFaultMessage = e.getMessage() + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, " Exception Encountered - " + "\n" + restFaultMessage, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 5000, restFaultMessage) + } + } + + /** + * Prepare and send the sychronous response for this flow. + * + * @param execution The flow's execution instance. + */ + public void sendSynchResponse(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.sendSynchResponse(' + + 'execution=' + execution.getId() + + ')' + + msoLogger.trace('Entered ' + method) + + + try { + def requestInfo = execution.getVariable('requestInfo') + def requestId = execution.getVariable('requestId') + def source = execution.getVariable('source') + def progress = getNodeTextForce(requestInfo, 'progress') + if (progress.isEmpty()) { + progress = '0' + } + def startTime = getNodeTextForce(requestInfo, 'start-time') + if (startTime.isEmpty()) { + startTime = System.currentTimeMillis() + } + + // RESTResponse (for API Handler (APIH) Reply Task) + def vnfId = execution.getVariable("vnfId") + String synchResponse = """{"requestReferences":{"instanceId":"${vnfId}","requestId":"${requestId}"}}""".trim() + + sendWorkflowResponse(execution, 200, synchResponse) + + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in sendResponse(): ' + e.getMessage()) + } + } + + + /** + * Check if this VNF is already in maintenance in A&AI. + * + * + * @param execution The flow's execution instance. + */ + public void checkIfVnfInMaintInAAI(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.checkIfVnfInMaintInAAI(' + + 'execution=' + execution.getId() + + ')' + + execution.setVariable('errorCode', "0") + execution.setVariable("workStep", "checkIfVnfInMaintInAAI") + execution.setVariable("failedActivity", "AAI") + msoLogger.trace('Entered ' + method) + + try { + def transactionLoggingUuid = UUID.randomUUID().toString() + AAIRestClientImpl client = new AAIRestClientImpl() + AAIValidatorImpl aaiValidator = new AAIValidatorImpl() + aaiValidator.setClient(client) + def vnfId = execution.getVariable("vnfId") + boolean isInMaint = aaiValidator.isVNFLocked(vnfId, transactionLoggingUuid) + msoLogger.debug("isInMaint result: " + isInMaint) + execution.setVariable('isVnfInMaintenance', isInMaint) + + if (isInMaint) { + execution.setVariable("errorCode", "1003") + execution.setVariable("errorText", "VNF is in maintenance in A&AI") + } + + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + execution.setVariable("errorCode", "1002") + execution.setVariable("errorText", e.getMessage()) + //exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in checkIfVnfInMaintInAAI(): ' + e.getMessage()) + } + } + + + /** + * Check if this VNF's pservers are locked in A&AI. + * + * + * @param execution The flow's execution instance. + */ + public void checkIfPserversInMaintInAAI(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.checkIfPserversInMaintInAAI(' + + 'execution=' + execution.getId() + + ')' + + execution.setVariable('errorCode', "0") + msoLogger.trace('Entered ' + method) + execution.setVariable("workStep", "checkIfPserversInMaintInAAI") + execution.setVariable("failedActivity", "AAI") + + try { + def transactionLoggingUuid = UUID.randomUUID().toString() + AAIRestClientImpl client = new AAIRestClientImpl() + AAIValidatorImpl aaiValidator = new AAIValidatorImpl() + aaiValidator.setClient(client) + def vnfId = execution.getVariable("vnfId") + boolean areLocked = aaiValidator.isPhysicalServerLocked(vnfId, transactionLoggingUuid) + msoLogger.debug("areLocked result: " + areLocked) + execution.setVariable('arePserversLocked', areLocked) + + if (areLocked) { + execution.setVariable("errorCode", "1003") + execution.setVariable("errorText", "pServers are locked in A&AI") + } + + + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + execution.setVariable("errorCode", "1002") + execution.setVariable("errorText", e.getMessage()) + //exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in checkIfPserversInMaintInAAI(): ' + e.getMessage()) + } + } + + /** + * Set inMaint flag for this VNF to the specified value in A&AI. + * + * + * @param execution The flow's execution instance. + * @param inMaint The boolean value of the flag to set + */ + public void setVnfInMaintFlagInAAI(DelegateExecution execution, boolean inMaint) { + def method = getClass().getSimpleName() + '.setVnfInMaintFlagInAAI(' + + 'execution=' + execution.getId() + + ')' + + execution.setVariable('errorCode', "0") + msoLogger.trace('Entered ' + method) + if (inMaint) { + execution.setVariable("workStep", "setVnfInMaintFlagInAAI") + execution.setVariable("rollbackSetVnfInMaintenanceFlag", true) + } + else { + execution.setVariable("workStep", "unsetVnfInMaintFlagInAAI") + } + execution.setVariable("failedActivity", "AAI") + + try { + def transactionLoggingUuid = UUID.randomUUID().toString() + AAIRestClientImpl client = new AAIRestClientImpl() + AAIUpdatorImpl aaiUpdator = new AAIUpdatorImpl() + aaiUpdator.setClient(client) + def vnfId = execution.getVariable("vnfId") + if (inMaint) { + aaiUpdator.updateVnfToLocked(vnfId, transactionLoggingUuid) + execution.setVariable("rollbackSetVnfInMaintenanceFlag", true) + } + else { + aaiUpdator.updateVnfToUnLocked(vnfId, transactionLoggingUuid) + } + + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + execution.setVariable("errorCode", "1002") + execution.setVariable("errorText", e.getMessage()) + //exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in setVnfInMaintFlagInAAI(): ' + e.getMessage()) + } + } + + /** + * Check if VF Closed Loop Disabled in A&AI. + * + * + * @param execution The flow's execution instance. + */ + public void checkIfClosedLoopDisabledInAAI(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.checkIfClosedLoopDisabledInAAI(' + + 'execution=' + execution.getId() + + ')' + + execution.setVariable('errorCode', "0") + execution.setVariable("workStep", "checkClosedLoopDisabledFlagInAAI") + execution.setVariable("failedActivity", "AAI") + msoLogger.trace('Entered ' + method) + + try { + def transactionLoggingUuid = UUID.randomUUID().toString() + def vnfId = execution.getVariable("vnfId") + msoLogger.debug("vnfId is: " + vnfId) + AAIResourcesClient client = new AAIResourcesClient() + AAIUri genericVnfUri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId) + AAIResultWrapper aaiRW = client.get(genericVnfUri) + Map<String, Object> result = aaiRW.asMap() + boolean isClosedLoopDisabled = result.getOrDefault("is-closed-loop-disabled", false) + + msoLogger.debug("isClosedLoopDisabled result: " + isClosedLoopDisabled) + execution.setVariable('isClosedLoopDisabled', isClosedLoopDisabled) + + if (isClosedLoopDisabled) { + execution.setVariable("errorCode", "1004") + execution.setVariable("errorText", "closedLoop is disabled in A&AI") + } + + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + execution.setVariable("errorCode", "1002") + execution.setVariable("errorText", e.getMessage()) + //exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in checkIfVnfInMaintInAAI(): ' + e.getMessage()) + } + } + + /** + * Set VF Closed Loop Disabled Flag in A&AI. + * + * + * @param execution The flow's execution instance. + */ + public void setClosedLoopDisabledInAAI(DelegateExecution execution, boolean setDisabled) { + def method = getClass().getSimpleName() + '.setClosedLoopDisabledInAAI(' + + 'execution=' + execution.getId() + + ')' + + execution.setVariable('errorCode', "0") + if (setDisabled) { + execution.setVariable("workStep", "setClosedLoopDisabledFlagInAAI") + execution.setVariable("rollbackSetClosedLoopDisabledFlag", true) + } + else { + execution.setVariable("workStep", "unsetClosedLoopDisabledFlagInAAI") + } + + execution.setVariable("failedActivity", "AAI") + msoLogger.trace('Entered ' + method) + + try { + def transactionLoggingUuid = UUID.randomUUID().toString() + def vnfId = execution.getVariable("vnfId") + AAIResourcesClient client = new AAIResourcesClient() + AAIUri genericVnfUri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId) + + Map<String, Boolean> request = new HashMap<>() + request.put("is-closed-loop-disabled", setDisabled) + client.update(genericVnfUri, request) + msoLogger.debug("set isClosedLoop to: " + setDisabled) + + + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + execution.setVariable("errorCode", "1002") + execution.setVariable("errorText", e.getMessage()) + //exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in checkIfVnfInMaintInAAI(): ' + e.getMessage()) + } + } + + + /** + * Handle Abort disposition from RainyDayHandler + * + * @param execution The flow's execution instance. + */ + public void abortProcessing(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.abortProcessing(' + + 'execution=' + execution.getId() + + ')' + + msoLogger.trace('Entered ' + method) + + def errorText = execution.getVariable("errorText") + def errorCode = execution.getVariable("errorCode") + + exceptionUtil.buildAndThrowWorkflowException(execution, errorCode as Integer, errorText) + } + + /** + * Increment Retry Count for Current Work Step + * + * @param execution The flow's execution instance. + */ + public void incrementRetryCount(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.incrementRetryCount(' + + 'execution=' + execution.getId() + + ')' + + msoLogger.trace('Entered ' + method) + + String retryCountVariableName = execution.getVariable("workStep") + "RetryCount" + execution.setVariable("retryCountVariableName", retryCountVariableName) + + def retryCountVariable = execution.getVariable(retryCountVariableName) + int retryCount = 0 + + if (retryCountVariable != null) { + retryCount = (int) retryCountVariable + } + + retryCount += 1 + + execution.setVariable(retryCountVariableName, retryCount) + + msoLogger.debug("value of " + retryCountVariableName + " is " + retryCount) + msoLogger.trace('Exited ' + method) + + + } + + + +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/VnfInPlaceUpdate.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/VnfInPlaceUpdate.groovy new file mode 100644 index 0000000000..68d5c19b80 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/VnfInPlaceUpdate.groovy @@ -0,0 +1,599 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts + +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.onap.appc.client.lcm.model.Action +import org.onap.appc.client.lcm.model.ActionIdentifiers +import org.onap.appc.client.lcm.model.Flags +import org.onap.appc.client.lcm.model.Status +import org.onap.so.bpmn.common.scripts.ExceptionUtil +import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.client.aai.* +import org.onap.so.client.aai.entities.AAIResultWrapper +import org.onap.so.client.aai.entities.uri.AAIUri +import org.onap.so.client.aai.entities.uri.AAIUriFactory +import org.onap.so.client.appc.ApplicationControllerClient; +import org.onap.so.client.appc.ApplicationControllerSupport; +import org.onap.so.logger.MessageEnum +import org.onap.so.logger.MsoLogger + +import groovy.json.JsonOutput +import groovy.json.JsonSlurper + +public class VnfInPlaceUpdate extends VnfCmBase { + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, VnfInPlaceUpdate.class); + + ExceptionUtil exceptionUtil = new ExceptionUtil() + JsonUtils jsonUtils = new JsonUtils() + def prefix = "VnfIPU_" + + /** + * Initialize the flow's variables. + * + * @param execution The flow's execution instance. + */ + public void initProcessVariables(DelegateExecution execution) { + execution.setVariable('prefix', 'VnfIPU_') + execution.setVariable('Request', null) + execution.setVariable('requestInfo', null) + execution.setVariable('source', null) + execution.setVariable('vnfInputs', null) + execution.setVariable('tenantId', null) + execution.setVariable('vnfParams', null) + execution.setVariable('controllerType', null) + execution.setVariable('UpdateVnfSuccessIndicator', false) + execution.setVariable('serviceType', null) + execution.setVariable('nfRole', null) + execution.setVariable('currentActivity', 'VnfIPU') + execution.setVariable('workStep', null) + execution.setVariable('failedActivity', null) + execution.setVariable('errorCode', "0") + execution.setVariable('errorText', null) + execution.setVariable('healthCheckIndex0', 0) + execution.setVariable('healthCheckIndex1', 1) + execution.setVariable('maxRetryCount', 3) + execution.setVariable("rollbackSetClosedLoopDisabledFlag", false) + execution.setVariable("rollbackVnfStop", false) + execution.setVariable("rollbackVnfLock", false) + execution.setVariable("rollbackQuiesceTraffic", false) + execution.setVariable("rollbackSetVnfInMaintenanceFlag", false) + } + + /** + * Check for missing elements in the received request. + * + * @param execution The flow's execution instance. + */ + public void preProcessRequest(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.preProcessRequest(' + + 'execution=' + execution.getId() + + ')' + initProcessVariables(execution) + + msoLogger.trace('Entered ' + method) + + initProcessVariables(execution) + + def incomingRequest = execution.getVariable('bpmnRequest') + + msoLogger.debug("Incoming Infra Request: " + incomingRequest) + try { + def jsonSlurper = new JsonSlurper() + def jsonOutput = new JsonOutput() + Map reqMap = jsonSlurper.parseText(incomingRequest) + msoLogger.debug(" Request is in JSON format.") + + def serviceInstanceId = execution.getVariable('serviceInstanceId') + def vnfId = execution.getVariable('vnfId') + + execution.setVariable('serviceInstanceId', serviceInstanceId) + execution.setVariable('vnfId', vnfId) + execution.setVariable("isVidRequest", "true") + execution.setVariable('serviceType', 'Mobility') + execution.setVariable('payload', "") + execution.setVariable('actionSnapshot', Action.Snapshot) + execution.setVariable('actionLock', Action.Lock) + execution.setVariable('actionUnlock', Action.Unlock) + execution.setVariable('actionUpgradePreCheck', Action.UpgradePreCheck) + execution.setVariable('actionUpgradePostCheck', Action.UpgradePostCheck) + execution.setVariable('actionQuiesceTraffic', Action.QuiesceTraffic) + execution.setVariable('actionUpgradeBackup', Action.UpgradeBackup) + execution.setVariable('actionUpgradeSoftware', Action.UpgradeSoftware) + execution.setVariable('actionResumeTraffic', Action.ResumeTraffic) + + + def controllerType = reqMap.requestDetails?.requestParameters?.controllerType + execution.setVariable('controllerType', controllerType) + + msoLogger.debug('Controller Type: ' + controllerType) + + def payload = reqMap.requestDetails?.requestParameters?.payload + execution.setVariable('payload', payload) + + msoLogger.debug('Processed payload: ' + payload) + + + def requestId = execution.getVariable("mso-request-id") + execution.setVariable('requestId', requestId) + execution.setVariable('msoRequestId', requestId) + + def requestorId = reqMap.requestDetails?.requestInfo?.requestorId ?: null + execution.setVariable('requestorId', requestorId) + + def cloudConfiguration = reqMap.requestDetails?.cloudConfiguration + def lcpCloudRegionId = cloudConfiguration.lcpCloudRegionId + execution.setVariable('lcpCloudRegionId', lcpCloudRegionId) + def tenantId = cloudConfiguration.tenantId + execution.setVariable('tenantId', tenantId) + + execution.setVariable("UpdateVnfInfraSuccessIndicator", false) + + + + def source = reqMap.requestDetails?.requestInfo?.source + execution.setVariable("source", source) + + //For Completion Handler & Fallout Handler + String requestInfo = + """<request-info xmlns="http://org.onap/so/infra/vnf-request/v1"> + <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> + <action>UPDATE</action> + <source>${MsoUtils.xmlEscape(source)}</source> + </request-info>""" + + execution.setVariable("requestInfo", requestInfo) + + msoLogger.debug('RequestInfo: ' + execution.getVariable("requestInfo")) + + msoLogger.trace('Exited ' + method) + + } + catch(groovy.json.JsonException je) { + msoLogger.debug(" Request is not in JSON format.") + exceptionUtil.buildAndThrowWorkflowException(execution, 5000, "Invalid request format") + } + catch(Exception e) { + String restFaultMessage = e.getMessage() + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, " Exception Encountered - " + "\n" + restFaultMessage, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 5000, restFaultMessage) + } + } + + /** + * Prepare and send the sychronous response for this flow. + * + * @param execution The flow's execution instance. + */ + public void sendSynchResponse(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.sendSynchResponse(' + + 'execution=' + execution.getId() + + ')' + + msoLogger.trace('Entered ' + method) + + + try { + def requestInfo = execution.getVariable('requestInfo') + def requestId = execution.getVariable('requestId') + def source = execution.getVariable('source') + def progress = getNodeTextForce(requestInfo, 'progress') + if (progress.isEmpty()) { + progress = '0' + } + def startTime = getNodeTextForce(requestInfo, 'start-time') + if (startTime.isEmpty()) { + startTime = System.currentTimeMillis() + } + + // RESTResponse (for API Handler (APIH) Reply Task) + def vnfId = execution.getVariable("vnfId") + String synchResponse = """{"requestReferences":{"instanceId":"${vnfId}","requestId":"${requestId}"}}""".trim() + + sendWorkflowResponse(execution, 200, synchResponse) + + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in sendResponse(): ' + e.getMessage()) + } + } + + + /** + * Check if this VNF is already in maintenance in A&AI. + * + * + * @param execution The flow's execution instance. + */ + public void checkIfVnfInMaintInAAI(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.checkIfVnfInMaintInAAI(' + + 'execution=' + execution.getId() + + ')' + + execution.setVariable('errorCode', "0") + execution.setVariable("workStep", "checkIfVnfInMaintInAAI") + execution.setVariable("failedActivity", "AAI") + msoLogger.trace('Entered ' + method) + + try { + def transactionLoggingUuid = UUID.randomUUID().toString() + AAIRestClientImpl client = new AAIRestClientImpl() + AAIValidatorImpl aaiValidator = new AAIValidatorImpl() + aaiValidator.setClient(client) + def vnfId = execution.getVariable("vnfId") + boolean isInMaint = aaiValidator.isVNFLocked(vnfId, transactionLoggingUuid) + msoLogger.debug("isInMaint result: " + isInMaint) + execution.setVariable('isVnfInMaintenance', isInMaint) + + if (isInMaint) { + execution.setVariable("errorCode", "1003") + execution.setVariable("errorText", "VNF is in maintenance in A&AI") + } + + + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + execution.setVariable("errorCode", "1002") + execution.setVariable("errorText", e.getMessage()) + //exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in checkIfVnfInMaintInAAI(): ' + e.getMessage()) + } + } + + + /** + * Check if this VNF's pservers are locked in A&AI. + * + * + * @param execution The flow's execution instance. + */ + public void checkIfPserversInMaintInAAI(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.checkIfPserversInMaintInAAI(' + + 'execution=' + execution.getId() + + ')' + + execution.setVariable('errorCode', "0") + msoLogger.trace('Entered ' + method) + execution.setVariable("workStep", "checkIfPserversInMaintInAAI") + execution.setVariable("failedActivity", "AAI") + + try { + def transactionLoggingUuid = UUID.randomUUID().toString() + AAIRestClientImpl client = new AAIRestClientImpl() + AAIValidatorImpl aaiValidator = new AAIValidatorImpl() + aaiValidator.setClient(client) + def vnfId = execution.getVariable("vnfId") + boolean areLocked = aaiValidator.isPhysicalServerLocked(vnfId, transactionLoggingUuid) + msoLogger.debug("areLocked result: " + areLocked) + execution.setVariable('arePserversLocked', areLocked) + + if (areLocked) { + execution.setVariable("errorCode", "1003") + execution.setVariable("errorText", "pServers are locked in A&AI") + } + + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + execution.setVariable("errorCode", "1002") + execution.setVariable("errorText", e.getMessage()) + //exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in checkIfPserversInMaintInAAI(): ' + e.getMessage()) + } + } + + /** + * Set inMaint flag for this VNF to the specified value in A&AI. + * + * + * @param execution The flow's execution instance. + * @param inMaint The boolean value of the flag to set + */ + public void setVnfInMaintFlagInAAI(DelegateExecution execution, boolean inMaint) { + def method = getClass().getSimpleName() + '.setVnfInMaintFlagInAAI(' + + 'execution=' + execution.getId() + + ')' + + execution.setVariable('errorCode', "0") + msoLogger.trace('Entered ' + method) + if (inMaint) { + execution.setVariable("workStep", "setVnfInMaintFlagInAAI") + } + else { + execution.setVariable("workStep", "unsetVnfInMaintFlagInAAI") + } + execution.setVariable("failedActivity", "AAI") + + try { + def transactionLoggingUuid = UUID.randomUUID().toString() + AAIRestClientImpl client = new AAIRestClientImpl() + AAIUpdatorImpl aaiUpdator = new AAIUpdatorImpl() + aaiUpdator.setClient(client) + def vnfId = execution.getVariable("vnfId") + if (inMaint) { + aaiUpdator.updateVnfToLocked(vnfId, transactionLoggingUuid) + execution.setVariable("rollbackSetVnfInMaintenanceFlag", true) + } + else { + aaiUpdator.updateVnfToUnLocked(vnfId, transactionLoggingUuid) + } + + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + execution.setVariable("errorCode", "1002") + execution.setVariable("errorText", e.getMessage()) + //exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in setVnfInMaintFlagInAAI(): ' + e.getMessage()) + } + } + + /** + * Check if VF Closed Loop Disabled in A&AI. + * + * + * @param execution The flow's execution instance. + */ + public void checkIfClosedLoopDisabledInAAI(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.checkIfClosedLoopDisabledInAAI(' + + 'execution=' + execution.getId() + + ')' + + execution.setVariable('errorCode', "0") + execution.setVariable("workStep", "checkClosedLoopDisabledFlagInAAI") + execution.setVariable("failedActivity", "AAI") + msoLogger.trace('Entered ' + method) + + try { + def transactionLoggingUuid = UUID.randomUUID().toString() + def vnfId = execution.getVariable("vnfId") + msoLogger.debug("vnfId is: " + vnfId) + AAIResourcesClient client = new AAIResourcesClient() + AAIUri genericVnfUri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId) + AAIResultWrapper aaiRW = client.get(genericVnfUri) + Map<String, Object> result = aaiRW.asMap() + boolean isClosedLoopDisabled = result.getOrDefault("is-closed-loop-disabled", false) + + msoLogger.debug("isClosedLoopDisabled result: " + isClosedLoopDisabled) + execution.setVariable('isClosedLoopDisabled', isClosedLoopDisabled) + + if (isClosedLoopDisabled) { + execution.setVariable("errorCode", "1004") + execution.setVariable("errorText", "closedLoop is disabled in A&AI") + } + + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + execution.setVariable("errorCode", "1002") + execution.setVariable("errorText", e.getMessage()) + } + } + + /** + * Set VF Closed Loop Disabled Flag in A&AI. + * + * + * @param execution The flow's execution instance. + */ + public void setClosedLoopDisabledInAAI(DelegateExecution execution, boolean setDisabled) { + def method = getClass().getSimpleName() + '.setClosedLoopDisabledInAAI(' + + 'execution=' + execution.getId() + + ')' + + execution.setVariable('errorCode', "0") + if (setDisabled) { + execution.setVariable("workStep", "setClosedLoopDisabledFlagInAAI") + execution.setVariable("rollbackSetClosedLoopDisabledFlag", true) + } + else { + execution.setVariable("workStep", "unsetClosedLoopDisabledFlagInAAI") + } + + execution.setVariable("failedActivity", "AAI") + msoLogger.trace('Entered ' + method) + + try { + def transactionLoggingUuid = UUID.randomUUID().toString() + def vnfId = execution.getVariable("vnfId") + AAIResourcesClient client = new AAIResourcesClient() + AAIUri genericVnfUri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId) + + Map<String, Boolean> request = new HashMap<>() + request.put("is-closed-loop-disabled", setDisabled) + client.update(genericVnfUri, request) + msoLogger.debug("set isClosedLoop to: " + setDisabled) + + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + execution.setVariable("errorCode", "1002") + execution.setVariable("errorText", e.getMessage()) + } + } + + + + + /** + * Call APP-C client to execute specified APP-C command for this VNF. + * + * + * @param execution The flow's execution instance. + * @param action The action to take in APP-C. + */ + public void runAppcCommand(DelegateExecution execution, Action action) { + def method = getClass().getSimpleName() + '.runAppcCommand(' + + 'execution=' + execution.getId() + + ')' + + execution.setVariable('errorCode', "0") + msoLogger.trace('Entered ' + method) + + ApplicationControllerClient appcClient = null + + try { + msoLogger.debug("Running APP-C action: " + action.toString()) + String vnfId = execution.getVariable('vnfId') + String msoRequestId = execution.getVariable('requestId') + execution.setVariable('msoRequestId', msoRequestId) + execution.setVariable("failedActivity", "APP-C") + + appcClient = new ApplicationControllerClient() + ApplicationControllerSupport support = new ApplicationControllerSupport() + appcClient.appCSupport=support + org.springframework.test.util.ReflectionTestUtils.setField(support, "lcmModelPackage", "org.onap.appc.client.lcm.model"); + Flags flags = new Flags(); + ActionIdentifiers actionIdentifiers = new ActionIdentifiers(); + actionIdentifiers.setVnfId(vnfId); + Status appcStatus + switch(action) { + case Action.Lock: + execution.setVariable('workStep', "LockVNF") + appcStatus = appcClient.runCommand(Action.Lock,actionIdentifiers,null,msoRequestId) + break + case Action.Unlock: + execution.setVariable('workStep', "UnlockVNF") + appcStatus = appcClient.runCommand(Action.Unlock,actionIdentifiers,null,msoRequestId) + break + case Action.HealthCheck: + def healthCheckIndex = execution.getVariable('healthCheckIndex') + execution.setVariable('workStep', "HealthCheckVNF" + healthCheckIndex) + execution.setVariable('healthCheckIndex', healthCheckIndex + 1) + appcStatus = appcClient.runCommand(Action.HealthCheck,actionIdentifiers,null,msoRequestId) + break + case Action.Start: + execution.setVariable('workStep', "StartVNF") + appcStatus = appcClient.runCommand(Action.Start,actionIdentifiers,null,msoRequestId) + break + case Action.Stop: + execution.setVariable('workStep', "StopVNF") + appcStatus = appcClient.runCommand(Action.Stop,actionIdentifiers,null,msoRequestId) + break + default: + break + } + msoLogger.debug("Completed AppC request") + int appcCode = appcStatus.getCode() + msoLogger.debug("AppC status code is: " + appcCode) + msoLogger.debug("AppC status message is: " + appcStatus.getMessage()) + if (support.getCategoryOf(appcStatus) == ApplicationControllerSupport.StatusCategory.ERROR) { + execution.setVariable("errorCode", Integer.toString(appcCode)) + execution.setVariable("errorText", appcStatus.getMessage()) + } + + msoLogger.trace('Exited ' + method) + } catch (BpmnError e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + execution.setVariable("errorCode", "1002") + execution.setVariable("errorText", e.getMessage()) + } catch (java.lang.NoSuchMethodError e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + execution.setVariable("errorCode", "1002") + execution.setVariable("errorText", e.getMessage()) + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + execution.setVariable("errorCode", "1002") + execution.setVariable("errorText", e.getMessage()) + } + } + + /** + * Placeholder for a call to APP-C client to execute specified APP-C command for this VNF. + * + * + * @param execution The flow's execution instance. + * @param action The action to take in APP-C. + */ + public void runAppcCommandPlaceholder(DelegateExecution execution, String action) { + def method = getClass().getSimpleName() + '.runAppcCommandPlaceholder(' + + 'execution=' + execution.getId() + + ')' + + execution.setVariable('errorCode', "0") + msoLogger.trace('Entered ' + method) + execution.setVariable("failedActivity", "APP-C") + execution.setVariable("workStep", action) + } + + + + /** + * Handle Abort disposition from RainyDayHandler + * + * @param execution The flow's execution instance. + */ + public void abortProcessing(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.abortProcessing(' + + 'execution=' + execution.getId() + + ')' + + msoLogger.trace('Entered ' + method) + + def errorText = execution.getVariable("errorText") + def errorCode = execution.getVariable("errorCode") + + exceptionUtil.buildAndThrowWorkflowException(execution, errorCode as Integer, errorText) + } + + /** + * Increment Retry Count for Current Work Step + * + * @param execution The flow's execution instance. + */ + public void incrementRetryCount(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.incrementRetryCount(' + + 'execution=' + execution.getId() + + ')' + + msoLogger.trace('Entered ' + method) + + String retryCountVariableName = execution.getVariable("workStep") + "RetryCount" + execution.setVariable("retryCountVariableName", retryCountVariableName) + + def retryCountVariable = execution.getVariable(retryCountVariableName) + int retryCount = 0 + + if (retryCountVariable != null) { + retryCount = (int) retryCountVariable + } + + retryCount += 1 + + execution.setVariable(retryCountVariableName, retryCount) + + msoLogger.debug("value of " + retryCountVariableName + " is " + retryCount) + msoLogger.trace('Exited ' + method) + } + +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/CreateVcpeResCustService.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/CreateVcpeResCustService.groovy new file mode 100644 index 0000000000..86c5f65e8c --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/CreateVcpeResCustService.groovy @@ -0,0 +1,814 @@ +/* + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.so.bpmn.vcpe.scripts; + +import static org.apache.commons.lang3.StringUtils.* + +import org.apache.commons.lang3.* +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.onap.so.bpmn.common.scripts.CatalogDbUtils +import org.onap.so.bpmn.common.scripts.ExceptionUtil +import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.so.bpmn.common.scripts.VidUtils +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.bpmn.core.domain.* +import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.logger.MessageEnum +import org.onap.so.logger.MsoLogger +import org.springframework.web.util.UriUtils; + +import groovy.json.* + + + +/** + * This groovy class supports the <class>CreateVcpeResCustService.bpmn</class> process. + * + * @author ek1439 + * + */ +public class CreateVcpeResCustService extends AbstractServiceTaskProcessor { + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, CreateVcpeResCustService.class); + + private static final String DebugFlag = "isDebugLogEnabled" + + String Prefix = "CVRCS_" + ExceptionUtil exceptionUtil = new ExceptionUtil() + JsonUtils jsonUtil = new JsonUtils() + VidUtils vidUtils = new VidUtils() + CatalogDbUtils catalogDbUtils = new CatalogDbUtils() + + /** + * This method is executed during the preProcessRequest task of the <class>CreateServiceInstance.bpmn</class> process. + * @param execution + */ + public InitializeProcessVariables(DelegateExecution execution) { + /* Initialize all the process variables in this block */ + + execution.setVariable("createVcpeServiceRequest", "") + execution.setVariable("globalSubscriberId", "") + execution.setVariable("serviceInstanceName", "") + execution.setVariable("msoRequestId", "") + execution.setVariable(Prefix + "VnfsCreatedCount", 0) + execution.setVariable("productFamilyId", "") + execution.setVariable("brgWanMacAddress", "") + execution.setVariable("customerLocation", "") + execution.setVariable("homingService", "") + execution.setVariable("cloudOwner", "") + execution.setVariable("cloudRegionId", "") + execution.setVariable("homingModelIds", "") + + //TODO + execution.setVariable("sdncVersion", "1707") + } + + // ************************************************** + // Pre or Prepare Request Section + // ************************************************** + /** + * This method is executed during the preProcessRequest task of the <class>CreateServiceInstance.bpmn</class> process. + * @param execution + */ + public void preProcessRequest(DelegateExecution execution) { + def isDebugEnabled = execution.getVariable(DebugFlag) + execution.setVariable("prefix", Prefix) + + msoLogger.trace("Inside preProcessRequest CreateVcpeResCustService Request ") + + try { + // initialize flow variables + InitializeProcessVariables(execution) + + //Config Inputs + String aaiDistDelay = execution.getVariable('URN_mso_workflow_aai_distribution_delay') + if (isBlank(aaiDistDelay)) { + msg = "URN_mso_workflow_aai_distribution_delay is null" + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + execution.setVariable("aaiDistDelay", aaiDistDelay) + msoLogger.debug("AAI distribution delay: " + aaiDistDelay) + + // check for incoming json message/input + String createVcpeServiceRequest = execution.getVariable("bpmnRequest") + msoLogger.debug(createVcpeServiceRequest) + execution.setVariable("createVcpeServiceRequest", createVcpeServiceRequest); + println 'createVcpeServiceRequest - ' + createVcpeServiceRequest + + // extract requestId + String requestId = execution.getVariable("mso-request-id") + execution.setVariable("msoRequestId", requestId) + + String serviceInstanceId = execution.getVariable("serviceInstanceId") + + if ((serviceInstanceId == null) || (serviceInstanceId.isEmpty())) { + serviceInstanceId = UUID.randomUUID().toString() + msoLogger.debug(" Generated new Service Instance: " + serviceInstanceId) + } else { + msoLogger.debug("Using provided Service Instance ID: " + serviceInstanceId) + } + + serviceInstanceId = UriUtils.encode(serviceInstanceId, "UTF-8") + execution.setVariable("serviceInstanceId", serviceInstanceId) + utils.log("DEBUG", "Incoming serviceInstanceId is: " + serviceInstanceId, isDebugEnabled) + + String serviceInstanceName = jsonUtil.getJsonValue(createVcpeServiceRequest, "requestDetails.requestInfo.instanceName") + execution.setVariable("serviceInstanceName", serviceInstanceName) + utils.log("DEBUG", "Incoming serviceInstanceName is: " + serviceInstanceName, isDebugEnabled) + + String requestAction = execution.getVariable("requestAction") + execution.setVariable("requestAction", requestAction) + + setBasicDBAuthHeader(execution, isDebugEnabled) + + String source = jsonUtil.getJsonValue(createVcpeServiceRequest, "requestDetails.requestInfo.source") + if ((source == null) || (source.isEmpty())) { + source = "VID" + } + execution.setVariable("source", source) + + // extract globalSubscriberId + String globalSubscriberId = jsonUtil.getJsonValue(createVcpeServiceRequest, "requestDetails.subscriberInfo.globalSubscriberId") + + // verify element global-customer-id is sent from JSON input, throw exception if missing + if ((globalSubscriberId == null) || (globalSubscriberId.isEmpty())) { + String dataErrorMessage = " Element 'globalSubscriberId' is missing. " + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + + } else { + execution.setVariable("globalSubscriberId", globalSubscriberId) + execution.setVariable("globalCustomerId", globalSubscriberId) + } + + // extract subscriptionServiceType + String subscriptionServiceType = jsonUtil.getJsonValue(createVcpeServiceRequest, "requestDetails.requestParameters.subscriptionServiceType") + execution.setVariable("subscriptionServiceType", subscriptionServiceType) + msoLogger.debug("Incoming subscriptionServiceType is: " + subscriptionServiceType) + + String suppressRollback = jsonUtil.getJsonValue(createVcpeServiceRequest, "requestDetails.requestInfo.suppressRollback") + execution.setVariable("disableRollback", suppressRollback) + msoLogger.debug("Incoming Suppress/Disable Rollback is: " + suppressRollback) + + String productFamilyId = jsonUtil.getJsonValue(createVcpeServiceRequest, "requestDetails.requestInfo.productFamilyId") + execution.setVariable("productFamilyId", productFamilyId) + msoLogger.debug("Incoming productFamilyId is: " + productFamilyId) + + String subscriberInfo = jsonUtil.getJsonValue(createVcpeServiceRequest, "requestDetails.subscriberInfo") + execution.setVariable("subscriberInfo", subscriberInfo) + msoLogger.debug("Incoming subscriberInfo is: " + subscriberInfo) + + // extract cloud configuration, split vid_ID into cloudOwner and cloudRegionId + String vimId = jsonUtil.getJsonValue(createVcpeServiceRequest, + "requestDetails.cloudConfiguration.lcpCloudRegionId") + def cloudRegion = vimId.split("_") + def cloudOwner = cloudRegion[0].toString() + def cloudRegionId = cloudRegion[1].toString() + execution.setVariable("cloudOwner", cloudOwner) + utils.log("DEBUG","cloudOwner: " + cloudOwner, isDebugEnabled) + execution.setVariable("cloudRegionId", cloudRegionId) + utils.log("DEBUG","cloudRegionId: " + cloudRegionId, isDebugEnabled) + + /* + * Extracting User Parameters from incoming Request and converting into a Map + */ + def jsonSlurper = new JsonSlurper() + def jsonOutput = new JsonOutput() + + Map reqMap = jsonSlurper.parseText(createVcpeServiceRequest) + + //InputParams + def userParams = reqMap.requestDetails?.requestParameters?.userParams + + Map<String, String> inputMap = [:] + if (userParams) { + userParams.each { + userParam -> + if ("Customer_Location".equals(userParam?.name)) { + execution.setVariable("customerLocation", userParam.value) + userParam.value.each { + param -> + inputMap.put(param.key, param.value) + } + } + if ("Homing_Model_Ids".equals(userParam?.name)) { + utils.log("DEBUG", "Homing_Model_Ids: " + userParam.value.toString() + " ---- Type is:" + + userParam.value.getClass() , isDebugEnabled) + def modelIdLst = [] + userParam.value.each { + param -> + def valueMap = [:] + param.each { + entry -> + valueMap.put(entry.key, entry.value) + } + modelIdLst.add(valueMap) + utils.log("DEBUG", "Param: " + param.toString() + " ---- Type is:" + + param.getClass() , isDebugEnabled) + } + execution.setVariable("homingModelIds", modelIdLst) + } + if ("BRG_WAN_MAC_Address".equals(userParam?.name)) { + execution.setVariable("brgWanMacAddress", userParam.value) + inputMap.put("BRG_WAN_MAC_Address", userParam.value) + } + if ("Homing_Solution".equals(userParam?.name)) { + execution.setVariable("homingService", userParam.value) + inputMap.put("Homing_Solution", userParam.value) + } + } + } + + if (execution.getVariable("homingService") == "") { + // Set Default Homing to OOF if not set + execution.setVariable("homingService", "oof") + } + + msoLogger.debug("User Input Parameters map: " + userParams.toString()) + execution.setVariable("serviceInputParams", inputMap) + + msoLogger.debug("Incoming brgWanMacAddress is: " + execution.getVariable('brgWanMacAddress')) + + //For Completion Handler & Fallout Handler + String requestInfo = + """<request-info xmlns="http://org.onap/so/infra/vnf-request/v1"> + <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> + <action>CREATE</action> + <source>${MsoUtils.xmlEscape(source)}</source> + </request-info>""" + + execution.setVariable(Prefix + "requestInfo", requestInfo) + + msoLogger.trace("Completed preProcessRequest CreateVcpeResCustService Request ") + + } catch (BpmnError e) { + throw e; + + } catch (Exception ex) { + String exceptionMessage = "Bpmn error encountered in CreateVcpeResCustService flow. Unexpected from method preProcessRequest() - " + ex.getMessage() + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + } + } + + public void sendSyncResponse(DelegateExecution execution) { + def isDebugEnabled = execution.getVariable(DebugFlag) + + msoLogger.trace("Inside sendSyncResponse of CreateVcpeResCustService ") + + try { + String serviceInstanceId = execution.getVariable("serviceInstanceId") + String requestId = execution.getVariable("mso-request-id") + + // RESTResponse (for API Handler (APIH) Reply Task) + String syncResponse = """{"requestReferences":{"instanceId":"${serviceInstanceId}","requestId":"${ + requestId + }"}}""".trim() + + msoLogger.debug(" sendSynchResponse: xmlSyncResponse - " + "\n" + syncResponse) + sendWorkflowResponse(execution, 202, syncResponse) + + } catch (Exception ex) { + String exceptionMessage = "Bpmn error encountered in CreateVcpeResCustService flow. Unexpected from method sendSyncResponse() - " + ex.getMessage() + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + } + } + + // ******************************* + // + // ******************************* + public void prepareDecomposeService(DelegateExecution execution) { + def isDebugEnabled = execution.getVariable(DebugFlag) + + try { + msoLogger.trace("Inside prepareDecomposeService of CreateVcpeResCustService ") + + String createVcpeServiceRequest = execution.getVariable("createVcpeServiceRequest") + + //serviceModelInfo JSON string will be used as-is for DoCreateServiceInstance BB + String serviceModelInfo = jsonUtil.getJsonValue(createVcpeServiceRequest, "requestDetails.modelInfo") + execution.setVariable("serviceModelInfo", serviceModelInfo) + + msoLogger.trace("Completed prepareDecomposeService of CreateVcpeResCustService ") + } catch (Exception ex) { + // try error in method block + String exceptionMessage = "Bpmn error encountered in CreateVcpeResCustService flow. Unexpected Error from method prepareDecomposeService() - " + ex.getMessage() + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + } + } + + // ******************************* + // + // ******************************* + public void prepareCreateServiceInstance(DelegateExecution execution) { + def isDebugEnabled = execution.getVariable(DebugFlag) + + try { + msoLogger.trace("Inside prepareCreateServiceInstance of CreateVcpeResCustService ") + + /* + * Service modelInfo is created in earlier step. This flow can use it as-is ... or, extract from DecompositionObject + * ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition") + * ModelInfo modelInfo = serviceDecomposition.getModelInfo() + * + */ + String createVcpeServiceRequest = execution.getVariable("createVcpeServiceRequest") +// String serviceInputParams = jsonUtil.getJsonValue(createVcpeServiceRequest, "requestDetails.requestParameters") +// execution.setVariable("serviceInputParams", serviceInputParams) + + + String serviceInstanceName = jsonUtil.getJsonValue(createVcpeServiceRequest, "requestDetails.requestInfo.instanceName") + execution.setVariable("serviceInstanceName", serviceInstanceName) + + ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition") + execution.setVariable("serviceDecompositionString", serviceDecomposition.toJsonStringNoRootName()) + + msoLogger.trace("Completed prepareCreateServiceInstance of CreateVcpeResCustService ") + } catch (Exception ex) { + // try error in method block + String exceptionMessage = "Bpmn error encountered in CreateVcpeResCustService flow. Unexpected Error from method prepareCreateServiceInstance() - " + ex.getMessage() + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + } + } + + public void postProcessServiceInstanceCreate(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.postProcessServiceInstanceCreate(' + 'execution=' + execution.getId() + ')' + def isDebugLogEnabled = execution.getVariable(DebugFlag) + msoLogger.trace('Entered ' + method) + + String requestId = execution.getVariable("mso-request-id") + String serviceInstanceId = execution.getVariable("serviceInstanceId") + String serviceInstanceName = execution.getVariable("serviceInstanceName") + + try { + + String payload = """ + <soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" xmlns:req="http://org.onap.so/requestsdb"> + <soapenv:Header/> + <soapenv:Body> + <req:updateInfraRequest> + <requestId>${MsoUtils.xmlEscape(requestId)}</requestId> + <lastModifiedBy>BPEL</lastModifiedBy> + <serviceInstanceId>${MsoUtils.xmlEscape(serviceInstanceId)}</serviceInstanceId> + <serviceInstanceName>${MsoUtils.xmlEscape(serviceInstanceName)}</serviceInstanceName> + </req:updateInfraRequest> + </soapenv:Body> + </soapenv:Envelope> + """ + execution.setVariable(Prefix + "setUpdateDbInstancePayload", payload) + msoLogger.debug(Prefix + "setUpdateDbInstancePayload: " + payload) + msoLogger.trace('Exited ' + method) + + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, 'Caught exception in ' + method, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 2000, "Internal Error - Occured in" + method) + } + } + + + public void processDecomposition(DelegateExecution execution) { + def isDebugEnabled = execution.getVariable(DebugFlag) + + msoLogger.trace("Inside processDecomposition() of CreateVcpeResCustService ") + + try { + + ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition") + + // VNFs + List<VnfResource> vnfList = serviceDecomposition.getVnfResources() + filterVnfs(vnfList) + serviceDecomposition.setVnfResources(vnfList) + + execution.setVariable("vnfList", vnfList) + execution.setVariable("vnfListString", vnfList.toString()) + + String vnfModelInfoString = "" + if (vnfList != null && vnfList.size() > 0) { + execution.setVariable(Prefix + "VNFsCount", vnfList.size()) + msoLogger.debug("vnfs to create: " + vnfList.size()) + ModelInfo vnfModelInfo = vnfList[0].getModelInfo() + + vnfModelInfoString = vnfModelInfo.toString() + String vnfModelInfoWithRoot = vnfModelInfo.toString() + vnfModelInfoString = jsonUtil.getJsonValue(vnfModelInfoWithRoot, "modelInfo") + } else { + execution.setVariable(Prefix + "VNFsCount", 0) + msoLogger.debug("no vnfs to create based upon serviceDecomposition content") + } + + execution.setVariable("vnfModelInfo", vnfModelInfoString) + execution.setVariable("vnfModelInfoString", vnfModelInfoString) + msoLogger.debug(" vnfModelInfoString :" + vnfModelInfoString) + + msoLogger.trace("Completed processDecomposition() of CreateVcpeResCustService ") + } catch (Exception ex) { + sendSyncError(execution) + String exceptionMessage = "Bpmn error encountered in CreateVcpeResCustService flow. processDecomposition() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + } + } + + private void filterVnfs(List<VnfResource> vnfList) { + if (vnfList == null) { + return + } + + // remove BRG & TXC from VNF list + + Iterator<VnfResource> it = vnfList.iterator() + while (it.hasNext()) { + VnfResource vr = it.next() + + String role = vr.getNfRole() + if (role == "BRG" || role == "TunnelXConn" || role == "Tunnel XConn") { + it.remove() + } + } + } + + + public void prepareCreateAllottedResourceTXC(DelegateExecution execution) { + def isDebugEnabled = execution.getVariable(DebugFlag) + + try { + msoLogger.trace("Inside prepareCreateAllottedResourceTXC of CreateVcpeResCustService ") + + /* + * Service modelInfo is created in earlier step. This flow can use it as-is ... or, extract from DecompositionObject + * ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition") + * ModelInfo modelInfo = serviceDecomposition.getModelInfo() + * + */ + String createVcpeServiceRequest = execution.getVariable("createVcpeServiceRequest") + ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition") + + //allottedResourceModelInfo + //allottedResourceRole + //The model Info parameters are a JSON structure as defined in the Service Instantiation API. + //It would be sufficient to only include the service model UUID (i.e. the modelVersionId), since this BB will query the full model from the Catalog DB. + List<AllottedResource> allottedResources = serviceDecomposition.getAllottedResources() + if (allottedResources != null) { + Iterator iter = allottedResources.iterator(); + while (iter.hasNext()) { + AllottedResource allottedResource = (AllottedResource) iter.next(); + + msoLogger.debug(" getting model info for AllottedResource # :" + allottedResource.toJsonStringNoRootName()) + msoLogger.debug(" allottedResource.getAllottedResourceType() :" + allottedResource.getAllottedResourceType()) + if ("TunnelXConn".equalsIgnoreCase(allottedResource.getAllottedResourceType()) || "Tunnel XConn".equalsIgnoreCase(allottedResource.getAllottedResourceType())) { + //set create flag to true + execution.setVariable("createTXCAR", true) + ModelInfo allottedResourceModelInfo = allottedResource.getModelInfo() + execution.setVariable("allottedResourceModelInfoTXC", allottedResourceModelInfo.toJsonStringNoRootName()) + execution.setVariable("allottedResourceRoleTXC", allottedResource.getAllottedResourceRole()) + execution.setVariable("allottedResourceTypeTXC", allottedResource.getAllottedResourceType()) + //After decomposition and homing BBs, there should be an allotted resource object in the decomposition that represents the TXC, + //and in its homingSolution section should be found the infraServiceInstanceId (i.e. infraServiceInstanceId in TXC Allotted Resource structure) (which the Homing BB would have populated). + execution.setVariable("parentServiceInstanceIdTXC", allottedResource.getHomingSolution().getServiceInstanceId()) + } + } + } + + //unit test only + String allottedResourceId = execution.getVariable("allottedResourceId") + execution.setVariable("allottedResourceIdTXC", allottedResourceId) + msoLogger.debug("setting allottedResourceId CreateVcpeResCustService " + allottedResourceId) + + msoLogger.trace("Completed prepareCreateAllottedResourceTXC of CreateVcpeResCustService ") + } catch (Exception ex) { + // try error in method block + String exceptionMessage = "Bpmn error encountered in prepareCreateAllottedResourceTXC flow. Unexpected Error from method prepareCreateServiceInstance() - " + ex.getMessage() + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + } + } + + public void prepareCreateAllottedResourceBRG(DelegateExecution execution) { + def isDebugEnabled = execution.getVariable(DebugFlag) + + try { + msoLogger.trace("Inside prepareCreateAllottedResourceBRG of CreateVcpeResCustService ") + + /* + * Service modelInfo is created in earlier step. This flow can use it as-is ... or, extract from DecompositionObject + * ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition") + * ModelInfo modelInfo = serviceDecomposition.getModelInfo() + * + */ + String createVcpeServiceRequest = execution.getVariable("createVcpeServiceRequest") + ServiceDecomposition serviceDecomposition = execution.getVariable("serviceDecomposition") + + //allottedResourceModelInfo + //allottedResourceRole + //The model Info parameters are a JSON structure as defined in the Service Instantiation API. + //It would be sufficient to only include the service model UUID (i.e. the modelVersionId), since this BB will query the full model from the Catalog DB. + List<AllottedResource> allottedResources = serviceDecomposition.getAllottedResources() + if (allottedResources != null) { + Iterator iter = allottedResources.iterator(); + while (iter.hasNext()) { + AllottedResource allottedResource = (AllottedResource) iter.next(); + + msoLogger.debug(" getting model info for AllottedResource # :" + allottedResource.toJsonStringNoRootName()) + msoLogger.debug(" allottedResource.getAllottedResourceType() :" + allottedResource.getAllottedResourceType()) + if ("BRG".equalsIgnoreCase(allottedResource.getAllottedResourceType())) { + //set create flag to true + execution.setVariable("createBRGAR", true) + ModelInfo allottedResourceModelInfo = allottedResource.getModelInfo() + execution.setVariable("allottedResourceModelInfoBRG", allottedResourceModelInfo.toJsonStringNoRootName()) + execution.setVariable("allottedResourceRoleBRG", allottedResource.getAllottedResourceRole()) + execution.setVariable("allottedResourceTypeBRG", allottedResource.getAllottedResourceType()) + //After decomposition and homing BBs, there should be an allotted resource object in the decomposition that represents the BRG, + //and in its homingSolution section should be found the infraServiceInstanceId (i.e. infraServiceInstanceId in BRG Allotted Resource structure) (which the Homing BB would have populated). + execution.setVariable("parentServiceInstanceIdBRG", allottedResource.getHomingSolution().getServiceInstanceId()) + } + } + } + + //unit test only + String allottedResourceId = execution.getVariable("allottedResourceId") + execution.setVariable("allottedResourceIdBRG", allottedResourceId) + msoLogger.debug("setting allottedResourceId CreateVcpeResCustService " + allottedResourceId) + + msoLogger.trace("Completed prepareCreateAllottedResourceBRG of CreateVcpeResCustService ") + } catch (Exception ex) { + // try error in method block + String exceptionMessage = "Bpmn error encountered in prepareCreateAllottedResourceBRG flow. Unexpected Error from method prepareCreateServiceInstance() - " + ex.getMessage() + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + } + } + + // ******************************* + // Generate Network request Section + // ******************************* + public void prepareVnfAndModulesCreate(DelegateExecution execution) { + def isDebugEnabled = execution.getVariable(DebugFlag) + + try { + msoLogger.trace("Inside prepareVnfAndModulesCreate of CreateVcpeResCustService ") + + // String disableRollback = execution.getVariable("disableRollback") + // def backoutOnFailure = "" + // if(disableRollback != null){ + // if ( disableRollback == true) { + // backoutOnFailure = "false" + // } else if ( disableRollback == false) { + // backoutOnFailure = "true" + // } + // } + //failIfExists - optional + + String createVcpeServiceRequest = execution.getVariable("createVcpeServiceRequest") + String productFamilyId = jsonUtil.getJsonValue(createVcpeServiceRequest, "requestDetails.requestInfo.productFamilyId") + execution.setVariable("productFamilyId", productFamilyId) + msoLogger.debug("productFamilyId: " + productFamilyId) + + List<VnfResource> vnfList = execution.getVariable("vnfList") + + Integer vnfsCreatedCount = execution.getVariable(Prefix + "VnfsCreatedCount") + String vnfModelInfoString = null; + + if (vnfList != null && vnfList.size() > 0) { + msoLogger.debug("getting model info for vnf # " + vnfsCreatedCount) + ModelInfo vnfModelInfo1 = vnfList[0].getModelInfo() + msoLogger.debug("got 0 ") + ModelInfo vnfModelInfo = vnfList[vnfsCreatedCount.intValue()].getModelInfo() + vnfModelInfoString = vnfModelInfo.toString() + } else { + //TODO: vnfList does not contain data. Need to investigate why ... . Fro VCPE use model stored + vnfModelInfoString = execution.getVariable("vnfModelInfo") + } + + msoLogger.debug(" vnfModelInfoString :" + vnfModelInfoString) + + // extract cloud configuration + String vimId = jsonUtil.getJsonValue(createVcpeServiceRequest, + "requestDetails.cloudConfiguration.lcpCloudRegionId") + def cloudRegion = vimId.split("_") + execution.setVariable("cloudOwner", cloudRegion[0]) + msoLogger.debug("cloudOwner: "+ cloudRegion[0]) + execution.setVariable("cloudRegionId", cloudRegion[1]) + msoLogger.debug("cloudRegionId: "+ cloudRegion[1]) + execution.setVariable("lcpCloudRegionId", cloudRegion[1]) + msoLogger.debug("lcpCloudRegionId: "+ cloudRegion[1]) + String tenantId = jsonUtil.getJsonValue(createVcpeServiceRequest, + "requestDetails.cloudConfiguration.tenantId") + execution.setVariable("tenantId", tenantId) + msoLogger.debug("tenantId: " + tenantId) + + String sdncVersion = execution.getVariable("sdncVersion") + msoLogger.debug("sdncVersion: " + sdncVersion) + + msoLogger.trace("Completed prepareVnfAndModulesCreate of CreateVcpeResCustService ") + } catch (Exception ex) { + // try error in method block + String exceptionMessage = "Bpmn error encountered in CreateVcpeResCustService flow. Unexpected Error from method prepareVnfAndModulesCreate() - " + ex.getMessage() + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + } + } + + // ******************************* + // Validate Vnf request Section -> increment count + // ******************************* + public void validateVnfCreate(DelegateExecution execution) { + def isDebugEnabled = execution.getVariable(DebugFlag) + + try { + msoLogger.trace("Inside validateVnfCreate of CreateVcpeResCustService ") + + Integer vnfsCreatedCount = execution.getVariable(Prefix + "VnfsCreatedCount") + vnfsCreatedCount++ + + execution.setVariable(Prefix + "VnfsCreatedCount", vnfsCreatedCount) + + msoLogger.debug(" ***** Completed validateVnfCreate of CreateVcpeResCustService ***** " + " vnf # " + vnfsCreatedCount) + } catch (Exception ex) { + // try error in method block + String exceptionMessage = "Bpmn error encountered in CreateVcpeResCustService flow. Unexpected Error from method validateVnfCreate() - " + ex.getMessage() + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + } + } + + // ***************************************** + // Prepare Completion request Section + // ***************************************** + public void postProcessResponse(DelegateExecution execution) { + def isDebugEnabled = execution.getVariable(DebugFlag) + + msoLogger.trace("Inside postProcessResponse of CreateVcpeResCustService ") + + try { + String source = execution.getVariable("source") + String requestId = execution.getVariable("mso-request-id") + String serviceInstanceId = execution.getVariable("serviceInstanceId") + + String msoCompletionRequest = + """<aetgt:MsoCompletionRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:ns="http://org.onap/so/request/types/v1"> + <request-info xmlns="http://org.onap/so/infra/vnf-request/v1"> + <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> + <action>CREATE</action> + <source>${MsoUtils.xmlEscape(source)}</source> + </request-info> + <status-message>Service Instance has been created successfully via macro orchestration</status-message> + <serviceInstanceId>${MsoUtils.xmlEscape(serviceInstanceId)}</serviceInstanceId> + <mso-bpel-name>BPMN macro create</mso-bpel-name> + </aetgt:MsoCompletionRequest>""" + + // Format Response + String xmlMsoCompletionRequest = utils.formatXml(msoCompletionRequest) + + msoLogger.debug(xmlMsoCompletionRequest) + execution.setVariable(Prefix + "Success", true) + execution.setVariable(Prefix + "CompleteMsoProcessRequest", xmlMsoCompletionRequest) + msoLogger.debug(" SUCCESS flow, going to CompleteMsoProcess - " + "\n" + xmlMsoCompletionRequest) + } catch (BpmnError e) { + throw e; + } catch (Exception ex) { + // try error in method block + String exceptionMessage = "Bpmn error encountered in CreateVcpeResCustService flow. Unexpected Error from method postProcessResponse() - " + ex.getMessage() + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + } + } + + public void preProcessRollback(DelegateExecution execution) { + def isDebugEnabled = execution.getVariable(DebugFlag) + msoLogger.trace("preProcessRollback of CreateVcpeResCustService ") + try { + + Object workflowException = execution.getVariable("WorkflowException"); + + if (workflowException instanceof WorkflowException) { + msoLogger.debug("Prev workflowException: " + workflowException.getErrorMessage()) + execution.setVariable("prevWorkflowException", workflowException); + //execution.setVariable("WorkflowException", null); + } + } catch (BpmnError e) { + msoLogger.debug("BPMN Error during preProcessRollback") + } catch (Exception ex) { + String msg = "Exception in preProcessRollback. " + ex.getMessage() + msoLogger.debug(msg) + } + msoLogger.trace("Exit preProcessRollback of CreateVcpeResCustService ") + } + + public void postProcessRollback(DelegateExecution execution) { + def isDebugEnabled = execution.getVariable(DebugFlag) + msoLogger.trace("postProcessRollback of CreateVcpeResCustService ") + String msg = "" + try { + Object workflowException = execution.getVariable("prevWorkflowException"); + if (workflowException instanceof WorkflowException) { + msoLogger.debug("Setting prevException to WorkflowException: ") + execution.setVariable("WorkflowException", workflowException); + } + } catch (BpmnError b) { + msoLogger.debug("BPMN Error during postProcessRollback") + throw b; + } catch (Exception ex) { + msg = "Exception in postProcessRollback. " + ex.getMessage() + msoLogger.debug(msg) + } + msoLogger.trace("Exit postProcessRollback of CreateVcpeResCustService ") + } + + public void prepareFalloutRequest(DelegateExecution execution) { + def isDebugEnabled = execution.getVariable(DebugFlag) + + msoLogger.trace("STARTED CreateVcpeResCustService prepareFalloutRequest Process ") + + try { + WorkflowException wfex = execution.getVariable("WorkflowException") + msoLogger.debug(" Incoming Workflow Exception: " + wfex.toString()) + String requestInfo = execution.getVariable(Prefix + "requestInfo") + msoLogger.debug(" Incoming Request Info: " + requestInfo) + + //TODO. hmmm. there is no way to UPDATE error message. +// String errorMessage = wfex.getErrorMessage() +// boolean successIndicator = execution.getVariable("DCRESI_rolledBack") +// if (successIndicator){ +// errorMessage = errorMessage + ". Rollback successful." +// } else { +// errorMessage = errorMessage + ". Rollback not completed." +// } + + String falloutRequest = exceptionUtil.processMainflowsBPMNException(execution, requestInfo) + + execution.setVariable(Prefix + "falloutRequest", falloutRequest) + + } catch (Exception ex) { + msoLogger.debug("Error Occured in CreateVcpeResCustService prepareFalloutRequest Process " + ex.getMessage()) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in CreateVcpeResCustService prepareFalloutRequest Process") + } + msoLogger.trace("COMPLETED CreateVcpeResCustService prepareFalloutRequest Process ") + } + + + public void sendSyncError(DelegateExecution execution) { + def isDebugEnabled = execution.getVariable(DebugFlag) + execution.setVariable("prefix", Prefix) + + msoLogger.trace("Inside sendSyncError() of CreateVcpeResCustService ") + + try { + String errorMessage = "" + def wfe = execution.getVariable("WorkflowException") + if (wfe instanceof WorkflowException) { + errorMessage = wfe.getErrorMessage() + } else { + errorMessage = "Sending Sync Error." + } + + String buildworkflowException = + """<aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1"> + <aetgt:ErrorMessage>${MsoUtils.xmlEscape(errorMessage)}</aetgt:ErrorMessage> + <aetgt:ErrorCode>7000</aetgt:ErrorCode> + </aetgt:WorkflowException>""" + + msoLogger.debug(buildworkflowException) + sendWorkflowResponse(execution, 500, buildworkflowException) + } catch (Exception ex) { + msoLogger.debug(" Sending Sync Error Activity Failed. " + "\n" + ex.getMessage()) + } + } + + public void processJavaException(DelegateExecution execution) { + def isDebugEnabled = execution.getVariable(DebugFlag) + execution.setVariable("prefix", Prefix) + try { + msoLogger.debug("Caught a Java Exception") + msoLogger.debug("Started processJavaException Method") + msoLogger.debug("Variables List: " + execution.getVariables()) + execution.setVariable(Prefix + "unexpectedError", "Caught a Java Lang Exception") + // Adding this line temporarily until this flows error handling gets updated + exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Caught a Java Lang Exception") + } catch (BpmnError b) { + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Rethrowing MSOWorkflowException", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, ""); + throw b + } catch (Exception e) { + msoLogger.debug("Caught Exception during processJavaException Method: " + e) + execution.setVariable(Prefix + "unexpectedError", "Exception in processJavaException method") + // Adding this line temporarily until this flows error handling gets updated + exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Exception in processJavaException method") + } + msoLogger.debug("Completed processJavaException Method") + } +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DeleteVcpeResCustService.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DeleteVcpeResCustService.groovy new file mode 100644 index 0000000000..85993d6c92 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DeleteVcpeResCustService.groovy @@ -0,0 +1,433 @@ +/* + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.so.bpmn.vcpe.scripts + +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.onap.so.bpmn.common.scripts.AaiUtil +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.onap.so.bpmn.common.scripts.CatalogDbUtils +import org.onap.so.bpmn.common.scripts.ExceptionUtil +import org.onap.so.bpmn.common.scripts.NetworkUtils +import org.onap.so.bpmn.common.scripts.VidUtils +import org.onap.so.bpmn.core.UrnPropertiesReader +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.logger.MessageEnum +import org.onap.so.logger.MsoLogger +import org.onap.so.rest.APIResponse +import org.onap.so.client.aai.AAIResourcesClient +import org.onap.so.client.aai.AAIObjectType +import org.onap.so.client.aai.entities.AAIResultWrapper +import org.onap.so.client.aai.entities.Relationships +import org.onap.so.client.aai.entities.uri.AAIResourceUri +import org.onap.so.client.aai.entities.uri.AAIUriFactory +import javax.ws.rs.NotFoundException +import org.json.JSONObject + +import static org.apache.commons.lang3.StringUtils.isBlank + + +/** + * This groovy class supports the <class>DeleteVcpeResCustService.bpmn</class> process. + * + * @author dm4252 + * + */ +public class DeleteVcpeResCustService extends AbstractServiceTaskProcessor { + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DeleteVcpeResCustService.class); + + private static final String DebugFlag = "isDebugLogEnabled" + + String Prefix = "DVRCS_" + ExceptionUtil exceptionUtil = new ExceptionUtil() + JsonUtils jsonUtil = new JsonUtils() + VidUtils vidUtils = new VidUtils() + CatalogDbUtils catalogDbUtils = new CatalogDbUtils() + NetworkUtils networkUtils = new NetworkUtils() + + /** + * This method is executed during the preProcessRequest task of the <class>DeleteVcpeResCustService.bpmn</class> process. + * @param execution + */ + public InitializeProcessVariables(DelegateExecution execution){ + /* Initialize all the process variables in this block */ + + execution.setVariable("DeleteVcpeResCustServiceRequest", "") + execution.setVariable("msoRequestId", "") + execution.setVariable(Prefix+"vnfsDeletedCount", 0) + execution.setVariable(Prefix+"vnfsCount", 0) + } + + // ************************************************** + // Pre or Prepare Request Section + // ************************************************** + /** + * This method is executed during the preProcessRequest task of the <class>CreateServiceInstance.bpmn</class> process. + * @param execution + */ + public void preProcessRequest (DelegateExecution execution) { + def isDebugEnabled=execution.getVariable(DebugFlag) + execution.setVariable("prefix",Prefix) + + msoLogger.trace("Inside preProcessRequest DeleteVcpeResCustService Request ") + + try { + // initialize flow variables + InitializeProcessVariables(execution) + + // check for incoming json message/input + String DeleteVcpeResCustServiceRequest = execution.getVariable("bpmnRequest") + msoLogger.debug(DeleteVcpeResCustServiceRequest) + execution.setVariable("DeleteVcpeResCustServiceRequest", DeleteVcpeResCustServiceRequest); + println 'DeleteVcpeResCustServiceRequest - ' + DeleteVcpeResCustServiceRequest + + // extract requestId + String requestId = execution.getVariable("mso-request-id") + execution.setVariable("msoRequestId", requestId) + + String serviceInstanceId = execution.getVariable("serviceInstanceId") + if ((serviceInstanceId == null) || (serviceInstanceId.isEmpty())) { + String dataErrorMessage = " Element 'serviceInstanceId' is missing. " + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) + } + + String requestAction = execution.getVariable("requestAction") + execution.setVariable("requestAction", requestAction) + + String source = jsonUtil.getJsonValue(DeleteVcpeResCustServiceRequest, "requestDetails.requestInfo.source") + if ((source == null) || (source.isEmpty())) { + source = "VID" + } + execution.setVariable("source", source) + + // extract globalSubscriberId + String globalSubscriberId = jsonUtil.getJsonValue(DeleteVcpeResCustServiceRequest, "requestDetails.subscriberInfo.globalSubscriberId") + + // global-customer-id is optional on Delete + + execution.setVariable("globalSubscriberId", globalSubscriberId) + execution.setVariable("globalCustomerId", globalSubscriberId) + + String suppressRollback = jsonUtil.getJsonValue(DeleteVcpeResCustServiceRequest, "requestDetails.requestInfo.suppressRollback") + execution.setVariable("disableRollback", suppressRollback) + msoLogger.debug("Incoming Suppress/Disable Rollback is: " + suppressRollback) + + String productFamilyId = jsonUtil.getJsonValue(DeleteVcpeResCustServiceRequest, "requestDetails.requestInfo.productFamilyId") + execution.setVariable("productFamilyId", productFamilyId) + msoLogger.debug("Incoming productFamilyId is: " + productFamilyId) + + // extract subscriptionServiceType + String subscriptionServiceType = jsonUtil.getJsonValue(DeleteVcpeResCustServiceRequest, "requestDetails.requestParameters.subscriptionServiceType") + execution.setVariable("subscriptionServiceType", subscriptionServiceType) + msoLogger.debug("Incoming subscriptionServiceType is: " + subscriptionServiceType) + + // extract cloud configuration + String cloudConfiguration = jsonUtil.getJsonValue(DeleteVcpeResCustServiceRequest, "requestDetails.cloudConfiguration") + execution.setVariable("cloudConfiguration", cloudConfiguration) + msoLogger.debug("cloudConfiguration: "+ cloudConfiguration) + String lcpCloudRegionId = jsonUtil.getJsonValue(cloudConfiguration, "lcpCloudRegionId") + execution.setVariable("lcpCloudRegionId", lcpCloudRegionId) + msoLogger.debug("lcpCloudRegionId: "+ lcpCloudRegionId) + String tenantId = jsonUtil.getJsonValue(cloudConfiguration, "tenantId") + execution.setVariable("tenantId", tenantId) + msoLogger.debug("tenantId: "+ tenantId) + + String sdncVersion = "1707" + execution.setVariable("sdncVersion", sdncVersion) + msoLogger.debug("sdncVersion: "+ sdncVersion) + + //For Completion Handler & Fallout Handler + String requestInfo = + """<request-info xmlns="http://org.onap/so/infra/vnf-request/v1"> + <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> + <action>DELETE</action> + <source>${MsoUtils.xmlEscape(source)}</source> + </request-info>""" + + execution.setVariable(Prefix+"requestInfo", requestInfo) + + msoLogger.trace("Completed preProcessRequest DeleteVcpeResCustServiceRequest Request ") + + } catch (BpmnError e) { + throw e; + } catch (Exception ex){ + String exceptionMessage = "Bpmn error encountered in DeleteVcpeResCustService flow. Unexpected from method preProcessRequest() - " + ex.getMessage() + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + } + } + + public void sendSyncResponse(DelegateExecution execution) { + def isDebugEnabled=execution.getVariable(DebugFlag) + + msoLogger.trace("Inside sendSyncResponse of DeleteVcpeResCustService ") + + try { + String serviceInstanceId = execution.getVariable("serviceInstanceId") + String requestId = execution.getVariable("mso-request-id") + + // RESTResponse (for API Handler (APIH) Reply Task) + String syncResponse ="""{"requestReferences":{"instanceId":"${serviceInstanceId}","requestId":"${requestId}"}}""".trim() + + msoLogger.debug(" sendSynchResponse: xmlSyncResponse - " + "\n" + syncResponse) + sendWorkflowResponse(execution, 202, syncResponse) + } catch (Exception ex) { + String exceptionMessage = "Bpmn error encountered in DeleteVcpeResCustService flow. Unexpected from method preProcessRequest() - " + ex.getMessage() + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + } + } + + /** + * Gets the service instance and its related resources from aai + * + * @author cb645j + */ + public void getServiceInstance(DelegateExecution execution) { + try { + String serviceInstanceId = execution.getVariable('serviceInstanceId') + + AAIResourcesClient resourceClient = new AAIResourcesClient() + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, serviceInstanceId) + + if(resourceClient.exists(uri)){ + AAIResultWrapper wrapper = resourceClient.get(uri, NotFoundException.class) + Optional<Relationships> relationships = wrapper.getRelationships() + + def (TXC_found, TXC_id) = new Tuple(false, null) + def (BRG_found, BRG_id) = new Tuple(false, null) + List relatedVnfIdList = [] + + if(relationships.isPresent()){ + + List<AAIResourceUri> vnfUris = relationships.get().getRelatedAAIUris(AAIObjectType.GENERIC_VNF) + for(AAIResourceUri u:vnfUris){ + Map<String, String> keys = u.getURIKeys() + String vnfId = keys.get("vnf-id") + relatedVnfIdList.add(vnfId) + } + List<AAIResourceUri> arUris = relationships.get().getRelatedAAIUris(AAIObjectType.ALLOTTED_RESOURCE) + for(AAIResourceUri u:arUris){ + String ar = resourceClient.get(u).getJson() + + def type = jsonUtil.getJsonValue(ar, "type") + def id = jsonUtil.getJsonValue(ar, "id") + + if(type == "TunnelXConn" || type == "Tunnel XConn") { + msoLogger.debug("TunnelXConn AR found") + TXC_found = true + TXC_id = id + + }else if(type == "BRG") { + msoLogger.debug("BRG AR found") + BRG_found = true + BRG_id = id + } + + execution.setVariable(Prefix+"TunnelXConn", TXC_found) + execution.setVariable("TXC_allottedResourceId", TXC_id) + msoLogger.debug("TXC_allottedResourceId: " + TXC_id) + + execution.setVariable(Prefix+"BRG", BRG_found) + execution.setVariable("BRG_allottedResourceId", BRG_id) + msoLogger.debug("BRG_allottedResourceId: " + BRG_id) + + } + } + + execution.setVariable(Prefix+"vnfsCount", relatedVnfIdList.size()) + if(relatedVnfIdList.size() > 0) { + execution.setVariable(Prefix+"relatedVnfIdList", relatedVnfIdList) + } + + }else{ + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Service Instance was not found in aai") + } + + }catch(BpmnError e) { + throw e; + }catch(NotFoundException e) { + msoLogger.debug("Service Instance does not exist AAI") + exceptionUtil.buildAndThrowWorkflowException(execution, 404, "Service Instance was not found in aai") + }catch(Exception ex) { + String msg = "Internal Error in getServiceInstance: " + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + } + + + // ******************************* + // + // ******************************* + public void prepareVnfAndModulesDelete (DelegateExecution execution) { + def isDebugEnabled=execution.getVariable(DebugFlag) + msoLogger.trace("Inside prepareVnfAndModulesDelete of DeleteVcpeResCustService ") + + try { + List vnfList = execution.getVariable(Prefix+"relatedVnfIdList") + int vnfsDeletedCount = execution.getVariable(Prefix+"vnfsDeletedCount") + String vnfModelInfoString = "" + String vnfId = "" + if (vnfList.size() > 0 ) { + vnfId = vnfList.get(vnfsDeletedCount.intValue()) + } + + execution.setVariable("vnfId", vnfId) + msoLogger.debug("need to delete vnfId:" + vnfId) + + msoLogger.trace("Completed prepareVnfAndModulesDelete of DeleteVcpeResCustService ") + } catch (Exception ex) { + // try error in method block + String exceptionMessage = "Bpmn error encountered in DeleteVcpeResCustService flow. Unexpected Error from method prepareVnfAndModulesDelete() - " + ex.getMessage() + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + } + } + + // ******************************* + // Validate Vnf request Section -> increment count + // ******************************* + public void validateVnfDelete (DelegateExecution execution) { + def isDebugEnabled=execution.getVariable(DebugFlag) + msoLogger.trace("Inside validateVnfDelete of DeleteVcpeResCustService ") + + try { + int vnfsDeletedCount = execution.getVariable(Prefix+"vnfsDeletedCount") + vnfsDeletedCount++ + + execution.setVariable(Prefix+"vnfsDeletedCount", vnfsDeletedCount) + + msoLogger.debug(" ***** Completed validateVnfDelete of DeleteVcpeResCustService ***** "+" vnf # "+vnfsDeletedCount) + } catch (Exception ex) { + // try error in method block + String exceptionMessage = "Bpmn error encountered in DeleteVcpeResCustService flow. Unexpected Error from method validateVnfDelete() - " + ex.getMessage() + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + } + } + + + // ***************************************** + // Prepare Completion request Section + // ***************************************** + public void postProcessResponse (DelegateExecution execution) { + def isDebugEnabled=execution.getVariable(DebugFlag) + msoLogger.trace("Inside postProcessResponse of DeleteVcpeResCustService ") + + try { + String source = execution.getVariable("source") + String requestId = execution.getVariable("msoRequestId") + + String msoCompletionRequest = + """<aetgt:MsoCompletionRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:ns="http://org.onap/so/request/types/v1"> + <request-info xmlns="http://org.onap/so/infra/vnf-request/v1"> + <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> + <action>DELETE</action> + <source>${MsoUtils.xmlEscape(source)}</source> + </request-info> + <aetgt:status-message>vCPE Res Cust Service Instance has been deleted successfully.</aetgt:status-message> + <aetgt:mso-bpel-name>BPMN Service Instance macro action: DELETE</aetgt:mso-bpel-name> + </aetgt:MsoCompletionRequest>""" + + // Format Response + String xmlMsoCompletionRequest = utils.formatXml(msoCompletionRequest) + + msoLogger.debug(xmlMsoCompletionRequest) + execution.setVariable(Prefix+"Success", true) + execution.setVariable(Prefix+"CompleteMsoProcessRequest", xmlMsoCompletionRequest) + msoLogger.debug(" SUCCESS flow, going to CompleteMsoProcess - " + "\n" + xmlMsoCompletionRequest) + } catch (BpmnError e) { + throw e; + + } catch (Exception ex) { + // try error in method block + String exceptionMessage = "Bpmn error encountered in DeleteServiceInstance flow. Unexpected Error from method postProcessResponse() - " + ex.getMessage() + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + } + } + + public void prepareFalloutRequest(DelegateExecution execution){ + def isDebugEnabled=execution.getVariable(DebugFlag) + msoLogger.trace("STARTED DeleteVcpeResCustService prepareFalloutRequest Process ") + + try { + WorkflowException wfex = execution.getVariable("WorkflowException") + msoLogger.debug(" Incoming Workflow Exception: " + wfex.toString()) + String requestInfo = execution.getVariable(Prefix+"requestInfo") + msoLogger.debug(" Incoming Request Info: " + requestInfo) + + String falloutRequest = exceptionUtil.processMainflowsBPMNException(execution, requestInfo) + + execution.setVariable(Prefix+"falloutRequest", falloutRequest) + } catch (Exception ex) { + msoLogger.debug("Error Occured in DeleteVcpeResCustService prepareFalloutRequest Process " + ex.getMessage()) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Internal Error - Occured in DeleteVcpeResCustService prepareFalloutRequest Process") + } + msoLogger.trace("COMPLETED DeleteVcpeResCustService prepareFalloutRequest Process ") + } + + + public void sendSyncError (DelegateExecution execution) { + def isDebugEnabled=execution.getVariable(DebugFlag) + msoLogger.trace("Inside sendSyncError() of DeleteVcpeResCustService ") + + try { + String errorMessage = "" + if (execution.getVariable("WorkflowException") instanceof WorkflowException) { + WorkflowException wfe = execution.getVariable("WorkflowException") + errorMessage = wfe.getErrorMessage() + } else { + errorMessage = "Sending Sync Error." + } + + String buildworkflowException = + """<aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1"> + <aetgt:ErrorMessage>${MsoUtils.xmlEscape(errorMessage)}</aetgt:ErrorMessage> + <aetgt:ErrorCode>7000</aetgt:ErrorCode> + </aetgt:WorkflowException>""" + + msoLogger.debug(buildworkflowException) + sendWorkflowResponse(execution, 500, buildworkflowException) + } catch (Exception ex) { + msoLogger.debug(" Sending Sync Error Activity Failed. " + "\n" + ex.getMessage()) + } + } + + public void processJavaException(DelegateExecution execution){ + def isDebugEnabled=execution.getVariable(DebugFlag) + execution.setVariable("prefix",Prefix) + try{ + msoLogger.debug("Caught a Java Exception") + msoLogger.debug("Started processJavaException Method") + msoLogger.debug("Variables List: " + execution.getVariables()) + execution.setVariable(Prefix+"unexpectedError", "Caught a Java Lang Exception") // Adding this line temporarily until this flows error handling gets updated + exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Caught a Java Lang Exception") + }catch(BpmnError b){ + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Rethrowing MSOWorkflowException", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, ""); + throw b + }catch(Exception e){ + msoLogger.debug("Caught Exception during processJavaException Method: " + e) + execution.setVariable(Prefix+"unexpectedError", "Exception in processJavaException method") // Adding this line temporarily until this flows error handling gets updated + exceptionUtil.buildAndThrowWorkflowException(execution, 500, "Exception in processJavaException method") + } + msoLogger.debug("Completed processJavaException Method") + } + + +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceBRG.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceBRG.groovy new file mode 100644 index 0000000000..3c08779513 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceBRG.groovy @@ -0,0 +1,745 @@ +/* + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.vcpe.scripts; + +import org.onap.so.bpmn.common.scripts.*; +import org.onap.so.bpmn.common.scripts.AaiUtil +import org.onap.so.bpmn.core.RollbackData +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.bpmn.core.UrnPropertiesReader +import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.rest.APIResponse + +import java.util.UUID; +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.apache.commons.lang3.* +import org.springframework.web.util.UriUtils; +import static org.apache.commons.lang3.StringUtils.* + +import org.onap.so.logger.MessageEnum +import org.onap.so.logger.MsoLogger +import org.onap.so.client.aai.AAIResourcesClient +import org.onap.so.client.aai.AAIObjectType +import org.onap.so.client.aai.entities.AAIResultWrapper +import org.onap.so.client.aai.entities.Relationships +import org.onap.so.client.aai.entities.uri.AAIResourceUri +import org.onap.so.client.aai.entities.uri.AAIUriFactory +import org.json.JSONObject +import javax.ws.rs.NotFoundException +/** + * This groovy class supports the <class>DoCreateAllottedResourceBRG.bpmn</class> process. + * + * @author + * + * Inputs: + * @param - msoRequestId + * @param - isDEbugLogEnabled + * @param - disableRollback + * @param - failExists - O + * @param - serviceInstanceId + * @param - globalCustomerId - O + * @param - subscriptionServiceType - O + * @param - parentServiceInstanceId + * @param - allottedReourceId - O + * @param - allottedResourceModelInfo + * @param - allottedResourceRole + * @param - allottedResourceType + * @param - brgWanMacAddress + * @param - vni + * @param - vgmuxBearerIP + * + * Outputs: + * @param - rollbackData (localRB->null) + * @param - rolledBack (no localRB->null, localRB F->false, localRB S->true) + * @param - WorkflowException - O + * @param - allottedResourceId + * @param - allottedResourceName + * + */ +public class DoCreateAllottedResourceBRG extends AbstractServiceTaskProcessor{ + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoCreateAllottedResourceBRG.class); + + String Prefix="DCARBRG_" + ExceptionUtil exceptionUtil = new ExceptionUtil() + JsonUtils jsonUtil = new JsonUtils() + + public void preProcessRequest (DelegateExecution execution) { + + + String msg = "" + msoLogger.trace("start preProcessRequest") + + try { + execution.setVariable("prefix", Prefix) + + //Config Inputs + String sdncCallbackUrl = UrnPropertiesReader.getVariable("mso.workflow.sdncadapter.callback",execution) + if (isBlank(sdncCallbackUrl)) { + msg = "mso.workflow.sdncadapter.callback is null" + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + execution.setVariable("sdncCallbackUrl", sdncCallbackUrl) + msoLogger.debug("SDNC Callback URL: " + sdncCallbackUrl) + + String sdncReplDelay = UrnPropertiesReader.getVariable("mso.workflow.sdnc.replication.delay",execution) + if (isBlank(sdncReplDelay)) { + msg = "mso.workflow.sdnc.replication.delay is null" + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + execution.setVariable("sdncReplDelay", sdncReplDelay) + msoLogger.debug("SDNC replication delay: " + sdncReplDelay) + + //Request Inputs + if (isBlank(execution.getVariable("serviceInstanceId"))){ + msg = "Input serviceInstanceId is null" + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + if (isBlank(execution.getVariable("parentServiceInstanceId"))) { + msg = "Input parentServiceInstanceId is null" + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + if (isBlank(execution.getVariable("allottedResourceModelInfo"))) { + msg = "Input allottedResourceModelInfo is null" + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + if (isBlank(execution.getVariable("vni"))) { + msg = "Input vni is null" + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + if (isBlank(execution.getVariable("vgmuxBearerIP"))) { + msg = "Input vgmuxBearerIP is null" + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + if (isBlank(execution.getVariable("brgWanMacAddress"))) { + msg = "Input brgWanMacAddress is null" + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + if (isBlank(execution.getVariable("allottedResourceRole"))) { + msg = "Input allottedResourceRole is null" + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + if (isBlank(execution.getVariable("allottedResourceType"))) { + msg = "Input allottedResourceType is null" + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + }catch(BpmnError b){ + msoLogger.debug("Rethrowing MSOWorkflowException") + throw b + } catch (Exception ex){ + msg = "Exception in preProcessRequest " + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.trace("end preProcessRequest") + } + + /** + * Gets the service instance uri from aai + */ + public void getServiceInstance(DelegateExecution execution) { + msoLogger.trace("getServiceInstance ") + try { + String serviceInstanceId = execution.getVariable('serviceInstanceId') + + AAIResourcesClient resourceClient = new AAIResourcesClient() + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.SERVICE_INSTANCE, serviceInstanceId) + + if(resourceClient.exists(uri)){ + execution.setVariable("CSI_resourceLink", uri.build().toString()) + }else{ + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Service instance was not found in aai") + } + + }catch(BpmnError e) { + throw e; + }catch (Exception ex){ + String msg = "Exception in getServiceInstance. " + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.trace("Exit getServiceInstance ") + } + + public void getAaiAR (DelegateExecution execution) { + + + msoLogger.trace("start getAaiAR") + + String arType = execution.getVariable("allottedResourceType") + String arRole = execution.getVariable("allottedResourceRole") + + AllottedResourceUtils arUtils = new AllottedResourceUtils(this) + String orchStatus = arUtils.getAROrchStatus(execution) + + String errorMsg = "" + + if (orchStatus != null) // AR was found + { + if ("true".equals(execution.getVariable("failExists"))) + { + errorMsg = "Allotted resource " + arType + " with Role " + arRole + " already exists" + } + else + { + if ("Active".equals(orchStatus)) + { + execution.setVariable("foundActiveAR", true) + } + else // blanks included + { + errorMsg = "Allotted Resource " + arType + " with Role " + arRole + " already exists in an incomplete state -" + orchStatus + } + } + } + if (!isBlank(errorMsg)) { + msoLogger.debug(errorMsg) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, errorMsg) + } + msoLogger.trace("end getAaiAR") + } + + public void getParentServiceInstance(DelegateExecution execution) { + msoLogger.trace("getParentServiceInstance ") + try { + String serviceInstanceId = execution.getVariable('parentServiceInstanceId') + + AAIResourcesClient resourceClient = new AAIResourcesClient() + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.NODES_QUERY, "").queryParam("search-node-type", "service-instance").queryParam("filter", "service-instance-id:EQUALS:" + serviceInstanceId) + String json = resourceClient.get(uri).getJson() + + JSONObject obj = new JSONObject(json) + if(obj.has("result-data")){ + JSONObject ob = obj.getJSONArray("result-data").getJSONObject(0) + String resourceLink = ob.getString("resource-link") + + String[] split = resourceLink.split("/aai/") + String siRelatedLink = "/aai/" + split[1] + + execution.setVariable("PSI_resourceLink", resourceLink) + }else{ + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, "Service instance was not found in aai") + } + + }catch(BpmnError e) { + throw e; + }catch (Exception ex){ + String msg = "Exception in getParentServiceInstance. " + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.trace("Exit getParentServiceInstance ") + } + + + public void createAaiAR(DelegateExecution execution) { + + + msoLogger.trace("start createAaiAR") + String msg = "" + + String allottedResourceId = execution.getVariable("allottedResourceId") + if (isBlank(allottedResourceId)) + { + allottedResourceId = UUID.randomUUID().toString() + execution.setVariable("allottedResourceId", allottedResourceId) + } + String arUrl = "" + try { + + //AAI PUT + AaiUtil aaiUriUtil = new AaiUtil(this) + String aaiEndpoint = UrnPropertiesReader.getVariable("aai.endpoint", execution) + String siResourceLink= execution.getVariable("PSI_resourceLink") + + String siUri = "" + msoLogger.debug("PSI_resourceLink:" + siResourceLink) + + if(!isBlank(siResourceLink)) { + msoLogger.debug("Incoming PSI Resource Link is: " + siResourceLink) + String[] split = siResourceLink.split("/aai/") + siUri = "/aai/" + split[1] + } + else + { + msg = "Parent Service Link in AAI is null" + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + + arUrl = "${aaiEndpoint}${siUri}" + "/allotted-resources/allotted-resource/" + UriUtils.encode(allottedResourceId,"UTF-8") + execution.setVariable("aaiARPath", arUrl) + msoLogger.debug("GET AllottedResource AAI URL is:\n" + arUrl) + + String namespace = aaiUriUtil.getNamespaceFromUri(execution, arUrl) + + String arType = execution.getVariable("allottedResourceType") + String arRole = execution.getVariable("allottedResourceRole") + String CSI_resourceLink = execution.getVariable("CSI_resourceLink") + String arModelInfo = execution.getVariable("allottedResourceModelInfo") + String modelInvariantId = jsonUtil.getJsonValue(arModelInfo, "modelInvariantUuid") + String modelVersionId = jsonUtil.getJsonValue(arModelInfo, "modelUuid") + String modelCustomizationId = jsonUtil.getJsonValue(arModelInfo, "modelCustomizationUuid") + + if (modelInvariantId == null) { + modelInvariantId = "" + } + if (modelVersionId == null) { + modelVersionId = "" + } + if (modelCustomizationId == null) { + modelCustomizationId = "" + } + + String payload = + """<allotted-resource xmlns="${namespace}"> + <id>${MsoUtils.xmlEscape(allottedResourceId)}</id> + <description></description> + <type>${MsoUtils.xmlEscape(arType)}</type> + <role>${MsoUtils.xmlEscape(arRole)}</role> + <selflink></selflink> + <model-invariant-id>${MsoUtils.xmlEscape(modelInvariantId)}</model-invariant-id> + <model-version-id>${MsoUtils.xmlEscape(modelVersionId)}</model-version-id> + <model-customization-id>${MsoUtils.xmlEscape(modelCustomizationId)}</model-customization-id> + <orchestration-status>PendingCreate</orchestration-status> + <operation-status></operation-status> + <relationship-list> + <relationship> + <related-to>service-instance</related-to> + <related-link>${MsoUtils.xmlEscape(CSI_resourceLink)}</related-link> + </relationship> + </relationship-list> + </allotted-resource>""".trim() + + execution.setVariable("AaiARPayload", payload) + msoLogger.debug(" payload to create AllottedResource in AAI:" + "\n" + payload) + + APIResponse response = aaiUriUtil.executeAAIPutCall(execution, arUrl, payload) + int responseCode = response.getStatusCode() + msoLogger.debug("AllottedResource AAI PUT responseCode:" + responseCode) + + String aaiResponse = response.getResponseBodyAsString() + msoLogger.debug("AllottedResource AAI PUT responseStr:" + aaiResponse) + + //200 OK 201 CREATED 202 ACCEPTED + if(responseCode == 200 || responseCode == 201 || responseCode == 202 ) + { + msoLogger.debug("AAI PUT AllottedResource received a Good Response") + } + else{ + msoLogger.debug("AAI Put AllottedResouce received a Bad Response Code: " + responseCode) + exceptionUtil.MapAAIExceptionToWorkflowExceptionGeneric(execution, aaiResponse, responseCode) + throw new BpmnError("MSOWorkflowException") + } + }catch(BpmnError b){ + msoLogger.debug("Rethrowing MSOWorkflowException") + throw b + } catch (Exception ex) { + msg = "Exception in createAaiAR " + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + + //start rollback set up + RollbackData rollbackData = new RollbackData() + def disableRollback = execution.getVariable("disableRollback") + rollbackData.put(Prefix, "disableRollback", disableRollback.toString()) + rollbackData.put(Prefix, "rollbackAAI", "true") + rollbackData.put(Prefix, "allottedResourceId", allottedResourceId) + rollbackData.put(Prefix, "serviceInstanceId", execution.getVariable("serviceInstanceId")) + rollbackData.put(Prefix, "parentServiceInstanceId", execution.getVariable("parentServiceInstanceId")) + rollbackData.put(Prefix, "aaiARPath", arUrl) + execution.setVariable("rollbackData", rollbackData) + msoLogger.trace("end createAaiAR") + } + + public String buildSDNCRequest(DelegateExecution execution, String action, String sdncRequestId) { + + + String msg = "" + msoLogger.trace("start buildSDNCRequest") + String sdncReq = null + + try { + + String allottedResourceId = execution.getVariable("allottedResourceId") + String serviceInstanceId = execution.getVariable("serviceInstanceId") + String globalCustomerId = execution.getVariable("globalCustomerId") + String subscriptionServiceType = execution.getVariable("subscriptionServiceType") + String parentServiceInstanceId = execution.getVariable("parentServiceInstanceId") + String callbackUrl = execution.getVariable("sdncCallbackUrl") + String requestId = execution.getVariable("msoRequestId") + + String brgWanMacAddress = execution.getVariable("brgWanMacAddress") + String vni = execution.getVariable("vni") + String vgmuxBearerIP = execution.getVariable("vgmuxBearerIP") + + String arModelInfo = execution.getVariable("allottedResourceModelInfo") + String modelInvariantId = jsonUtil.getJsonValue(arModelInfo, "modelInvariantUuid") + String modelVersion = jsonUtil.getJsonValue(arModelInfo, "modelVersion") + String modelUUId = jsonUtil.getJsonValue(arModelInfo, "modelUuid") + String modelCustomizationId = jsonUtil.getJsonValue(arModelInfo, "modelCustomizationUuid") + String modelName = jsonUtil.getJsonValue(arModelInfo, "modelName") + + if (modelInvariantId == null) { + modelInvariantId = "" + } + if (modelVersion == null) { + modelVersion = "" + } + if (modelUUId == null) { + modelUUId = "" + } + if (modelName == null) { + modelName = "" + } + if (modelCustomizationId == null) { + modelCustomizationId = "" + } + + sdncReq = + """<sdncadapterworkflow:SDNCAdapterWorkflowRequest xmlns:ns5="http://org.onap/so/request/types/v1" + xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1" + xmlns:sdncadapter="http://org.onap/workflow/sdnc/adapter/schema/v1"> + <sdncadapter:RequestHeader> + <sdncadapter:RequestId>${MsoUtils.xmlEscape(sdncRequestId)}</sdncadapter:RequestId> + <sdncadapter:SvcInstanceId>${MsoUtils.xmlEscape(serviceInstanceId)}</sdncadapter:SvcInstanceId> + <sdncadapter:SvcAction>${MsoUtils.xmlEscape(action)}</sdncadapter:SvcAction> + <sdncadapter:SvcOperation>brg-topology-operation</sdncadapter:SvcOperation> + <sdncadapter:CallbackUrl>${MsoUtils.xmlEscape(callbackUrl)}</sdncadapter:CallbackUrl> + </sdncadapter:RequestHeader> + <sdncadapterworkflow:SDNCRequestData> + <request-information> + <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> + <request-action>CreateBRGInstance</request-action> + <source>MSO</source> + <notification-url/> + <order-number/> + <order-version/> + </request-information> + <service-information> + <service-id></service-id> + <subscription-service-type>${MsoUtils.xmlEscape(subscriptionServiceType)}</subscription-service-type> + <onap-model-information></onap-model-information> + <service-instance-id>${MsoUtils.xmlEscape(serviceInstanceId)}</service-instance-id> + <subscriber-name/> + <global-customer-id>${MsoUtils.xmlEscape(globalCustomerId)}</global-customer-id> + </service-information> + <allotted-resource-information> + <allotted-resource-id>${MsoUtils.xmlEscape(allottedResourceId)}</allotted-resource-id> + <allotted-resource-type>brg</allotted-resource-type> + <parent-service-instance-id>${MsoUtils.xmlEscape(parentServiceInstanceId)}</parent-service-instance-id> + <onap-model-information> + <model-invariant-uuid>${MsoUtils.xmlEscape(modelInvariantId)}</model-invariant-uuid> + <model-uuid>${MsoUtils.xmlEscape(modelUUId)}</model-uuid> + <model-customization-uuid>${MsoUtils.xmlEscape(modelCustomizationId)}</model-customization-uuid> + <model-version>${MsoUtils.xmlEscape(modelVersion)}</model-version> + <model-name>${MsoUtils.xmlEscape(modelName)}</model-name> + </onap-model-information> + </allotted-resource-information> + <brg-request-input> + <brg-wan-mac-address>${MsoUtils.xmlEscape(brgWanMacAddress)}</brg-wan-mac-address> + <vni>${MsoUtils.xmlEscape(vni)}</vni> + <vgmux-bearer-ip>${MsoUtils.xmlEscape(vgmuxBearerIP)}</vgmux-bearer-ip> + </brg-request-input> + </sdncadapterworkflow:SDNCRequestData> + </sdncadapterworkflow:SDNCAdapterWorkflowRequest>""" + + msoLogger.debug("sdncRequest:\n" + sdncReq) + sdncReq = utils.formatXml(sdncReq) + + } catch(Exception ex) { + msg = "Exception in buildSDNCRequest. " + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.trace("end buildSDNCRequest") + return sdncReq + } + + public void preProcessSDNCAssign(DelegateExecution execution) { + + + String msg = "" + msoLogger.trace("start preProcessSDNCAssign") + + try { + String sdncRequestId = UUID.randomUUID().toString() + String sdncAssignReq = buildSDNCRequest(execution, "assign", sdncRequestId) + execution.setVariable("sdncAssignRequest", sdncAssignReq) + msoLogger.debug("sdncAssignRequest: " + sdncAssignReq) + def sdncRequestId2 = UUID.randomUUID().toString() + String sdncAssignRollbackReq = sdncAssignReq.replace(">assign<", ">unassign<").replace(">CreateBRGInstance<", ">DeleteBRGInstance<").replace(">${sdncRequestId}<", ">${sdncRequestId2}<") + def rollbackData = execution.getVariable("rollbackData") + rollbackData.put(Prefix, "sdncAssignRollbackReq", sdncAssignRollbackReq) + execution.setVariable("rollbackData", rollbackData) + + msoLogger.debug("sdncAssignRollbackReq:\n" + sdncAssignRollbackReq) + msoLogger.debug("rollbackData:\n" + rollbackData.toString()) + + } catch (BpmnError e) { + throw e; + } catch(Exception ex) { + msg = "Exception in preProcessSDNCAssign. " + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.trace("end preProcessSDNCAssign") + } + + public void preProcessSDNCCreate(DelegateExecution execution) { + + + String msg = "" + msoLogger.trace("start preProcessSDNCCreate") + + try { + String sdncRequestId = UUID.randomUUID().toString() + String sdncCreateReq = buildSDNCRequest(execution, "create", sdncRequestId) + execution.setVariable("sdncCreateRequest", sdncCreateReq) + msoLogger.debug("sdncCreateReq: " + sdncCreateReq) + def sdncRequestId2 = UUID.randomUUID().toString() + String sdncCreateRollbackReq = sdncCreateReq.replace(">create<", ">delete<").replace(">CreateBRGInstance<", ">DeleteBRGInstance<").replace(">${sdncRequestId}<", ">${sdncRequestId2}<") + def rollbackData = execution.getVariable("rollbackData") + rollbackData.put(Prefix, "sdncCreateRollbackReq", sdncCreateRollbackReq) + execution.setVariable("rollbackData", rollbackData) + + msoLogger.debug("sdncCreateRollbackReq:\n" + sdncCreateRollbackReq) + msoLogger.debug("rollbackData:\n" + rollbackData.toString()) + + } catch (BpmnError e) { + throw e; + } catch(Exception ex) { + msg = "Exception in preProcessSDNCCreate. " + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.trace("end preProcessSDNCCreate") + } + + public void preProcessSDNCActivate(DelegateExecution execution) { + + + String msg = "" + msoLogger.trace("start preProcessSDNCActivate") + + try { + String sdncRequestId = UUID.randomUUID().toString() + String sdncActivateReq = buildSDNCRequest(execution, "activate", sdncRequestId) + execution.setVariable("sdncActivateRequest", sdncActivateReq) + msoLogger.debug("sdncActivateReq: " + sdncActivateReq) + def sdncRequestId2 = UUID.randomUUID().toString() + String sdncActivateRollbackReq = sdncActivateReq.replace(">activate<", ">deactivate<").replace(">CreateBRGInstance<", ">DeleteBRGInstance<").replace(">${sdncRequestId}<", ">${sdncRequestId2}<") + def rollbackData = execution.getVariable("rollbackData") + rollbackData.put(Prefix, "sdncActivateRollbackReq", sdncActivateRollbackReq) + execution.setVariable("rollbackData", rollbackData) + + msoLogger.debug("sdncActivateRollbackReq:\n" + sdncActivateRollbackReq) + msoLogger.debug("rollbackData:\n" + rollbackData.toString()) + + } catch (BpmnError e) { + throw e; + } catch(Exception ex) { + msg = "Exception in preProcessSDNCActivate. " + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.trace("end preProcessSDNCActivate") + } + + public void validateSDNCResp(DelegateExecution execution, String response, String method){ + + + msoLogger.trace("ValidateSDNCResponse Process") + String msg = "" + + try { + WorkflowException workflowException = execution.getVariable("WorkflowException") + msoLogger.debug("workflowException: " + workflowException) + + boolean successIndicator = execution.getVariable("SDNCA_SuccessIndicator") + msoLogger.debug("SDNCResponse: " + response) + + SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this) + sdncAdapterUtils.validateSDNCResponse(execution, response, workflowException, successIndicator) + + if(execution.getVariable(Prefix + 'sdncResponseSuccess') == true){ + msoLogger.debug("Received a Good Response from SDNC Adapter for " + method + " SDNC Call. Response is: \n" + response) + + if (!"get".equals(method)) + { + def rollbackData = execution.getVariable("rollbackData") + rollbackData.put(Prefix, "rollback" + "SDNC" + method, "true") + execution.setVariable("rollbackData", rollbackData) + } + + }else{ + msoLogger.debug("Received a BAD Response from SDNC Adapter for " + method + " SDNC Call.") + throw new BpmnError("MSOWorkflowException") + } + } catch (BpmnError e) { + throw e; + } catch(Exception ex) { + msg = "Exception in validateSDNCResp. " + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.trace("End ValidateSDNCResp Process") + } + + public void preProcessSDNCGet(DelegateExecution execution){ + + msoLogger.trace("start preProcessSDNCGet") + try{ + + def callbackUrl = execution.getVariable("sdncCallbackUrl") + // serviceOperation (URI for topology GET) will be retrieved from "selflink" from AAI if active AR exists in AAI + // or from "object-path" in SDNC response for assign when AR does not exist in AA + + String serviceOperation = "" + + if (execution.getVariable("foundActiveAR")) { + def aaiQueryResponse = execution.getVariable("aaiARGetResponse") + serviceOperation = utils.getNodeText(aaiQueryResponse, "selflink") + msoLogger.debug("AR service operation/aaiARSelfLink: " + serviceOperation) + } + else + { + String response = execution.getVariable("sdncAssignResponse") + String data = utils.getNodeXml(response, "response-data") + msoLogger.debug("Assign responseData: " + data) + serviceOperation = utils.getNodeText(data, "object-path") + msoLogger.debug("AR service operation:" + serviceOperation) + } + + String serviceInstanceId = execution.getVariable("serviceInstanceId") + String sdncRequestId = UUID.randomUUID().toString() + + //neeed the same url as used by vfmodules + String SDNCGetRequest = + """<sdncadapterworkflow:SDNCAdapterWorkflowRequest xmlns:ns5="http://org.onap/so/request/types/v1" + xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1" + xmlns:sdncadapter="http://org.onap/workflow/sdnc/adapter/schema/v1"> + <sdncadapter:RequestHeader> + <sdncadapter:RequestId>${MsoUtils.xmlEscape(sdncRequestId)}</sdncadapter:RequestId> + <sdncadapter:SvcInstanceId>${MsoUtils.xmlEscape(serviceInstanceId)}</sdncadapter:SvcInstanceId> + <sdncadapter:SvcAction>query</sdncadapter:SvcAction> + <sdncadapter:SvcOperation>${MsoUtils.xmlEscape(serviceOperation)}</sdncadapter:SvcOperation> + <sdncadapter:CallbackUrl>${MsoUtils.xmlEscape(callbackUrl)}</sdncadapter:CallbackUrl> + <sdncadapter:MsoAction>vfmodule</sdncadapter:MsoAction> + </sdncadapter:RequestHeader> + <sdncadapterworkflow:SDNCRequestData></sdncadapterworkflow:SDNCRequestData> + </sdncadapterworkflow:SDNCAdapterWorkflowRequest>""" + + execution.setVariable("sdncGetRequest", SDNCGetRequest) + + }catch(Exception e){ + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception Occurred Processing preProcessSDNCGetRequest.", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during SDNC GET Method:\n" + e.getMessage()) + } + msoLogger.trace("end preProcessSDNCGet") + } + + public void updateAaiAROrchStatus(DelegateExecution execution, String status){ + + msoLogger.trace("start updateAaiAROrchStatus") + String aaiARPath = execution.getVariable("aaiARPath") //set during query (existing AR) or create + AllottedResourceUtils arUtils = new AllottedResourceUtils(this) + String orchStatus = arUtils.updateAROrchStatus(execution, status, aaiARPath) + msoLogger.trace("end updateAaiAROrchStatus") + } + + public void generateOutputs(DelegateExecution execution) + { + + msoLogger.trace("start generateOutputs") + try { + String sdncGetResponse = execution.getVariable("enhancedCallbackRequestData") //unescaped + msoLogger.debug("resp:" + sdncGetResponse) + String arData = utils.getNodeXml(sdncGetResponse, "brg-topology") + arData = utils.removeXmlNamespaces(arData) + + String brga = utils.getNodeXml(arData, "brg-assignments") + String ari = utils.getNodeXml(arData, "allotted-resource-identifiers") + execution.setVariable("allotedResourceName", utils.getNodeText(ari, "allotted-resource-name")) + } catch (BpmnError e) { + msoLogger.debug("BPMN Error in generateOutputs ") + } catch(Exception ex) { + String msg = "Exception in generateOutputs " + ex.getMessage() + msoLogger.debug(msg) + } + msoLogger.trace("end generateOutputs") + + } + + public void preProcessRollback (DelegateExecution execution) { + + msoLogger.trace("start preProcessRollback") + try { + + Object workflowException = execution.getVariable("WorkflowException"); + + if (workflowException instanceof WorkflowException) { + msoLogger.debug("Prev workflowException: " + workflowException.getErrorMessage()) + execution.setVariable("prevWorkflowException", workflowException); + //execution.setVariable("WorkflowException", null); + } + } catch (BpmnError e) { + msoLogger.debug("BPMN Error during preProcessRollback") + } catch(Exception ex) { + String msg = "Exception in preProcessRollback. " + ex.getMessage() + msoLogger.debug(msg) + } + msoLogger.trace("end preProcessRollback") + } + + public void postProcessRollback (DelegateExecution execution) { + + msoLogger.trace("start postProcessRollback") + String msg = "" + try { + Object workflowException = execution.getVariable("prevWorkflowException"); + if (workflowException instanceof WorkflowException) { + msoLogger.debug("Setting prevException to WorkflowException: ") + execution.setVariable("WorkflowException", workflowException); + } + execution.setVariable("rollbackData", null) + } catch (BpmnError b) { + msoLogger.debug("BPMN Error during postProcessRollback") + throw b; + } catch(Exception ex) { + msg = "Exception in postProcessRollback. " + ex.getMessage() + msoLogger.debug(msg) + } + msoLogger.trace("end postProcessRollback") + } + +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceBRGRollback.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceBRGRollback.groovy new file mode 100644 index 0000000000..4d4f11c3e5 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceBRGRollback.groovy @@ -0,0 +1,279 @@ +/* + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.vcpe.scripts; + +import org.onap.so.bpmn.common.scripts.*; +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.bpmn.common.scripts.ExceptionUtil +import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.so.bpmn.common.scripts.AaiUtil +import org.onap.so.bpmn.common.scripts.SDNCAdapterUtils +import org.onap.so.rest.APIResponse + +import java.util.UUID; +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.apache.commons.lang3.* +import org.springframework.web.util.UriUtils; +import static org.apache.commons.lang3.StringUtils.* + +import org.onap.so.logger.MessageEnum +import org.onap.so.logger.MsoLogger + +/** + * This groovy class supports the <class>CreateAllottedResourceBRGRollback.bpmn</class> process. + * + * @author + * + * Inputs: + * @param - msoRequestId + * @param - isDebugLogEnabled + * @param - disableRollback - O + * @param - rollbackData + * + * Outputs: + * @param - rollbackError + * @param - rolledBack (no localRB->null, localRB F->false, localRB S->true) + * + */ +public class DoCreateAllottedResourceBRGRollback extends AbstractServiceTaskProcessor{ + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoCreateAllottedResourceBRGRollback.class); + + String Prefix="DCARBRGRB_" + ExceptionUtil exceptionUtil = new ExceptionUtil() + + public void preProcessRequest (DelegateExecution execution) { + + + String msg = "" + msoLogger.trace("start preProcessRequest") + execution.setVariable("prefix", Prefix) + String rbType = "DCARBRG_" + try { + + def rollbackData = execution.getVariable("rollbackData") + msoLogger.debug("RollbackData:" + rollbackData) + + if (rollbackData != null) { + if (rollbackData.hasType(rbType)) { + + execution.setVariable("serviceInstanceId", rollbackData.get(rbType, "serviceInstanceId")) + execution.setVariable("parentServiceInstanceId", rollbackData.get(rbType, "parentServiceInstanceId")) + execution.setVariable("allottedResourceId", rollbackData.get("SERVICEINSTANCE", "allottedResourceId")) + + + def rollbackAAI = rollbackData.get(rbType, "rollbackAAI") + if ("true".equals(rollbackAAI)) + { + execution.setVariable("rollbackAAI",true) + execution.setVariable("aaiARPath", rollbackData.get(rbType, "aaiARPath")) + + } + def rollbackSDNC = rollbackData.get(rbType, "rollbackSDNCassign") + if ("true".equals(rollbackSDNC)) + { + execution.setVariable("rollbackSDNC", true) + execution.setVariable("deactivateSdnc", rollbackData.get(rbType, "rollbackSDNCactivate")) + execution.setVariable("deleteSdnc", rollbackData.get(rbType, "rollbackSDNCcreate")) + execution.setVariable("unassignSdnc", rollbackData.get(rbType, "rollbackSDNCassign")) + + msoLogger.debug("sdncDeactivate:\n" + execution.getVariable("deactivateSdnc") ) + msoLogger.debug("sdncDelete:\n" + execution.getVariable("deleteSdnc")) + msoLogger.debug("sdncUnassign:\n" + execution.getVariable("unassignSdnc")) + + execution.setVariable("sdncDeactivateRequest", rollbackData.get(rbType, "sdncActivateRollbackReq")) + execution.setVariable("sdncDeleteRequest", rollbackData.get(rbType, "sdncCreateRollbackReq")) + execution.setVariable("sdncUnassignRequest", rollbackData.get(rbType, "sdncAssignRollbackReq")) + } + + if (execution.getVariable("rollbackAAI") != true && execution.getVariable("rollbackSDNC") != true) + { + execution.setVariable("skipRollback", true) + } + } + else { + execution.setVariable("skipRollback", true) + } + } + else { + execution.setVariable("skipRollback", true) + } + if (execution.getVariable("disableRollback").equals("true" )) + { + execution.setVariable("skipRollback", true) + } + + }catch(BpmnError b){ + msoLogger.debug("Rethrowing MSOWorkflowException") + throw b + } catch (Exception ex){ + msg = "Exception in preProcessRequest " + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.trace("end preProcessRequest") + } + + // aaiARPath set during query (existing AR) + public void updateAaiAROrchStatus(DelegateExecution execution, String status){ + + String msg = null; + msoLogger.trace("start updateAaiAROrchStatus") + AllottedResourceUtils arUtils = new AllottedResourceUtils(this) + String aaiARPath = execution.getVariable("aaiARPath") + msoLogger.debug(" aaiARPath:" + aaiARPath) + String ar = null; //need this for getting resourceVersion for delete + if (!isBlank(aaiARPath)) + { + ar = arUtils.getARbyLink(execution, aaiARPath, "") + } + if (isBlank(ar)) + { + msg = "AR not found in AAI at:" + aaiARPath + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + String orchStatus = arUtils.updateAROrchStatus(execution, status, aaiARPath) + msoLogger.trace("end updateAaiAROrchStatus") + } + + public void validateSDNCResp(DelegateExecution execution, String response, String method){ + + + msoLogger.trace("start ValidateSDNCResponse Process") + String msg = "" + + try { + WorkflowException workflowException = execution.getVariable("WorkflowException") + msoLogger.debug("workflowException: " + workflowException) + + boolean successIndicator = execution.getVariable("SDNCA_SuccessIndicator") + msoLogger.debug("SDNCResponse: " + response) + + SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this) + sdncAdapterUtils.validateSDNCResponse(execution, response, workflowException, successIndicator) + + if(execution.getVariable(Prefix + 'sdncResponseSuccess') == true){ + msoLogger.debug("Received a Good Response from SDNC Adapter for " + method + " SDNC Call. Response is: \n" + response) + + }else{ + + msoLogger.debug("Received a BAD Response from SDNC Adapter for " + method + " SDNC Call.") + throw new BpmnError("MSOWorkflowException") + } + } catch (BpmnError e) { + if ("404".contentEquals(e.getErrorCode())) + { + msg = "SDNC rollback " + method + " returned a 404. Proceding with rollback" + msoLogger.debug(msg) + } + else { + throw e; + } + } catch(Exception ex) { + msg = "Exception in validateSDNCResp. " + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.trace("end ValidateSDNCResp Process") + } + + public void deleteAaiAR(DelegateExecution execution){ + + try{ + msoLogger.trace("start deleteAaiAR") + AllottedResourceUtils arUtils = new AllottedResourceUtils(this) + String ar = null //need to get resource-version + String arLink = execution.getVariable("aaiARPath") + if (!isBlank(arLink)) + { + ar = arUtils.getARbyLink(execution, arLink, "") + } + arUtils.deleteAR(execution, arLink + '?resource-version=' + UriUtils.encode(execution.getVariable("aaiARResourceVersion"),"UTF-8")) + } catch (BpmnError e) { + throw e; + }catch(Exception ex){ + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception Occurred Processing preProcessSDNCGetRequest.", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + ex); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during SDNC GET Method:\n" + ex.getMessage()) + } + msoLogger.trace("end deleteAaiAR") + } + + public void postProcessRequest(DelegateExecution execution) { + + msoLogger.trace("start postProcessRequest") + String msg = "" + try { + execution.setVariable("rollbackData", null) + boolean skipRollback = execution.getVariable("skipRollback") + if (skipRollback != true) + { + execution.setVariable("rolledBack", true) + msoLogger.debug("rolledBack") + } + msoLogger.trace("end postProcessRequest") + + } catch (BpmnError e) { + msg = "Bpmn Exception in postProcessRequest. " + msoLogger.debug(msg) + } catch (Exception ex) { + msg = "Exception in postProcessRequest. " + ex.getMessage() + msoLogger.debug(msg) + } + + } + + public void processRollbackException(DelegateExecution execution){ + + msoLogger.trace("start processRollbackException") + try{ + msoLogger.debug("Caught an Exception in DoCreateAllottedResourceRollback") + execution.setVariable("rollbackData", null) + execution.setVariable("rolledBack", false) + execution.setVariable("rollbackError", "Caught exception in AllottedResource Create Rollback") + execution.setVariable("WorkflowException", null) + + }catch(BpmnError b){ + msoLogger.debug("BPMN Error during processRollbackExceptions Method: ") + }catch(Exception e){ + msoLogger.debug("Caught Exception during processRollbackExceptions Method: " + e.getMessage()) + } + + msoLogger.trace("end processRollbackException") + } + + public void processRollbackJavaException(DelegateExecution execution){ + + msoLogger.trace("start processRollbackJavaException") + try{ + execution.setVariable("rollbackData", null) + execution.setVariable("rolledBack", false) + execution.setVariable("rollbackError", "Caught Java exception in AllottedResource Create Rollback") + msoLogger.debug("Caught Exception in processRollbackJavaException") + + }catch(Exception e){ + msoLogger.debug("Caught Exception in processRollbackJavaException " + e.getMessage()) + } + msoLogger.trace("end processRollbackJavaException") + } + +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceTXC.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceTXC.groovy new file mode 100644 index 0000000000..5f9b4b8ecd --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceTXC.groovy @@ -0,0 +1,674 @@ +/* + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.vcpe.scripts; + +import org.onap.so.bpmn.common.scripts.*; +import org.onap.so.bpmn.common.scripts.AaiUtil +import org.onap.so.bpmn.core.RollbackData +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.bpmn.core.UrnPropertiesReader +import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.rest.APIResponse + +import java.util.UUID; +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.apache.commons.lang3.* +import org.springframework.web.util.UriUtils; +import static org.apache.commons.lang3.StringUtils.* + +import org.onap.so.logger.MessageEnum +import org.onap.so.logger.MsoLogger + +/** + * This groovy class supports the <class>DoCreateAllottedResourceTXC.bpmn</class> process. + * + * @author + * + * Inputs: + * @param - msoRequestId + * @param - isDEbugLogEnabled + * @param - disableRollback + * @param - failExists - O + * @param - serviceInstanceId + * @param - globalCustomerId - O + * @param - subscriptionServiceType - O + * @param - parentServiceInstanceId + * @param - allottedReourceId - O + * @param - allottedResourceModelInfo + * @param - allottedResourceRole + * @param - allottedResourceType + * @param - brgWanMacAddress + * + * Outputs: + * @param - rollbackData (localRB->null) + * @param - rolledBack (no localRB->null, localRB F->false, localRB S->true) + * @param - WorkflowException - O + * @param - allottedResourceId + * @param - allottedResourceName + * @param - vni + * @param - vgmuxBearerIP + * @param - vgmuxLanIP + * + */ +public class DoCreateAllottedResourceTXC extends AbstractServiceTaskProcessor{ + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoCreateAllottedResourceTXC.class); + + String Prefix="DCARTXC_" + ExceptionUtil exceptionUtil = new ExceptionUtil() + JsonUtils jsonUtil = new JsonUtils() + + public void preProcessRequest (DelegateExecution execution) { + + + String msg = "" + msoLogger.trace("start preProcessRequest") + + try { + String msoRequestId = execution.getVariable("msoRequestId") + msoLogger.debug(" msoRequestId = " + msoRequestId) + + execution.setVariable("prefix", Prefix) + + //Config Inputs + String sdncCallbackUrl = UrnPropertiesReader.getVariable("mso.workflow.sdncadapter.callback",execution) + if (isBlank(sdncCallbackUrl)) { + msg = "mso.workflow.sdncadapter.callback is null" + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + execution.setVariable("sdncCallbackUrl", sdncCallbackUrl) + msoLogger.debug("SDNC Callback URL: " + sdncCallbackUrl) + + String sdncReplDelay = UrnPropertiesReader.getVariable("mso.workflow.sdnc.replication.delay",execution) + if (isBlank(sdncReplDelay)) { + msg = "mso.workflow.sdnc.replication.delay is null" + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + execution.setVariable("sdncReplDelay", sdncReplDelay) + msoLogger.debug("SDNC replication delay: " + sdncReplDelay) + + //Request Inputs + if (isBlank(execution.getVariable("serviceInstanceId"))){ + msg = "Input serviceInstanceId is null" + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + if (isBlank(execution.getVariable("parentServiceInstanceId"))) { + msg = "Input parentServiceInstanceId is null" + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + if (isBlank(execution.getVariable("allottedResourceModelInfo"))) { + msg = "Input allottedResourceModelInfo is null" + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + if (isBlank(execution.getVariable("brgWanMacAddress"))) { + msg = "Input brgWanMacAddress is null" + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + if (isBlank(execution.getVariable("allottedResourceRole"))) { + msg = "Input allottedResourceRole is null" + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + if (isBlank(execution.getVariable("allottedResourceType"))) { + msg = "Input allottedResourceType is null" + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + }catch(BpmnError b){ + msoLogger.debug("Rethrowing MSOWorkflowException") + throw b + } catch (Exception ex){ + msg = "Exception in preProcessRequest " + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.trace("end preProcessRequest") + } + + public void getAaiAR (DelegateExecution execution) { + + + msoLogger.trace("start getAaiAR") + + String arType = execution.getVariable("allottedResourceType") + String arRole = execution.getVariable("allottedResourceRole") + + AllottedResourceUtils arUtils = new AllottedResourceUtils(this) + String orchStatus = arUtils.getAROrchStatus(execution) + + String errorMsg = "" + + if (orchStatus != null) // AR was found + { + if ("true".equals(execution.getVariable("failExists"))) + { + errorMsg = "Allotted resource " + arType + " with Role " + arRole + " already exists" + } + else + { + if ("Active".equals(orchStatus)) + { + execution.setVariable("foundActiveAR", true) + } + else // blanks included + { + errorMsg = "Allotted Resource " + arType + " with Role " + arRole + " already exists in an incomplete state -" + orchStatus + } + } + } + if (!isBlank(errorMsg)) { + msoLogger.debug(errorMsg) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, errorMsg) + } + msoLogger.trace("end getAaiAR") + } + + public void createAaiAR(DelegateExecution execution) { + + + msoLogger.trace("start createAaiAR") + String msg = "" + + String allottedResourceId = execution.getVariable("allottedResourceId") + if (isBlank(allottedResourceId)) + { + allottedResourceId = UUID.randomUUID().toString() + execution.setVariable("allottedResourceId", allottedResourceId) + } + String arUrl = "" + try { + + //AAI PUT + AaiUtil aaiUriUtil = new AaiUtil(this) + String aaiEndpoint = UrnPropertiesReader.getVariable("aai.endpoint", execution) + String siResourceLink= execution.getVariable("PSI_resourceLink") + + String siUri = "" + msoLogger.debug("PSI_resourceLink:" + siResourceLink) + + if(!isBlank(siResourceLink)) { + msoLogger.debug("Incoming PSI Resource Link is: " + siResourceLink) + String[] split = siResourceLink.split("/aai/") + siUri = "/aai/" + split[1] + } + else + { + msg = "Parent Service Link in AAI is null" + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + + arUrl = "${aaiEndpoint}${siUri}" + "/allotted-resources/allotted-resource/" + UriUtils.encode(allottedResourceId,"UTF-8") + execution.setVariable("aaiARPath", arUrl) + msoLogger.debug("GET AllottedResource AAI URL is:\n" + arUrl) + + String namespace = aaiUriUtil.getNamespaceFromUri(execution, arUrl) + + String arType = execution.getVariable("allottedResourceType") + String arRole = execution.getVariable("allottedResourceRole") + String CSI_resourceLink = execution.getVariable("CSI_resourceLink") + String arModelInfo = execution.getVariable("allottedResourceModelInfo") + msoLogger.debug("arModelInfo is:\n" + arModelInfo) + String modelInvariantId = jsonUtil.getJsonValue(arModelInfo, "modelInvariantUuid") + String modelVersionId = jsonUtil.getJsonValue(arModelInfo, "modelUuid") + String modelCustomizationId = jsonUtil.getJsonValue(arModelInfo, "modelCustomizationUuid") + + if (modelInvariantId == null) { + modelInvariantId = "" + } + if (modelVersionId == null) { + modelVersionId = "" + } + if (modelCustomizationId == null) { + modelCustomizationId = "" + } + + String payload = + """<allotted-resource xmlns="${namespace}"> + <id>${MsoUtils.xmlEscape(allottedResourceId)}</id> + <description></description> + <type>${MsoUtils.xmlEscape(arType)}</type> + <role>${MsoUtils.xmlEscape(arRole)}</role> + <selflink></selflink> + <model-invariant-id>${MsoUtils.xmlEscape(modelInvariantId)}</model-invariant-id> + <model-version-id>${MsoUtils.xmlEscape(modelVersionId)}</model-version-id> + <model-customization-id>${MsoUtils.xmlEscape(modelCustomizationId)}</model-customization-id> + <orchestration-status>PendingCreate</orchestration-status> + <operation-status></operation-status> + <relationship-list> + <relationship> + <related-to>service-instance</related-to> + <related-link>${MsoUtils.xmlEscape(CSI_resourceLink)}</related-link> + </relationship> + </relationship-list> + </allotted-resource>""".trim() + + execution.setVariable("AaiARPayload", payload) + msoLogger.debug(" payload to create AllottedResource in AAI:" + "\n" + payload) + + APIResponse response = aaiUriUtil.executeAAIPutCall(execution, arUrl, payload) + int responseCode = response.getStatusCode() + msoLogger.debug("AllottedResource AAI PUT responseCode:" + responseCode) + + String aaiResponse = response.getResponseBodyAsString() + msoLogger.debug("AllottedResource AAI PUT responseStr:" + aaiResponse) + + //200 OK 201 CREATED 202 ACCEPTED + if(responseCode == 200 || responseCode == 201 || responseCode == 202 ) + { + msoLogger.debug("AAI PUT AllottedResource received a Good Response") + } + else{ + msoLogger.debug("AAI Put AllottedResouce received a Bad Response Code: " + responseCode) + exceptionUtil.MapAAIExceptionToWorkflowExceptionGeneric(execution, aaiResponse, responseCode) + throw new BpmnError("MSOWorkflowException") + } + }catch(BpmnError b){ + msoLogger.debug("Rethrowing MSOWorkflowException") + throw b + } catch (Exception ex) { + msg = "Exception in createAaiAR " + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + + //start rollback set up + RollbackData rollbackData = new RollbackData() + def disableRollback = execution.getVariable("disableRollback") + rollbackData.put(Prefix, "disableRollback", disableRollback.toString()) + rollbackData.put(Prefix, "rollbackAAI", "true") + rollbackData.put(Prefix, "allottedResourceId", allottedResourceId) + rollbackData.put(Prefix, "serviceInstanceId", execution.getVariable("serviceInstanceId")) + rollbackData.put(Prefix, "parentServiceInstanceId", execution.getVariable("parentServiceInstanceId")) + rollbackData.put(Prefix, "aaiARPath", arUrl) + execution.setVariable("rollbackData", rollbackData) + msoLogger.trace("end createAaiAR") + } + + public String buildSDNCRequest(DelegateExecution execution, String action, String sdncRequestId) { + + + String msg = "" + msoLogger.trace("start buildSDNCRequest") + String sdncReq = null + + try { + + String allottedResourceId = execution.getVariable("allottedResourceId") + String serviceInstanceId = execution.getVariable("serviceInstanceId") + String globalCustomerId = execution.getVariable("globalCustomerId") + String subscriptionServiceType = execution.getVariable("subscriptionServiceType") + String parentServiceInstanceId = execution.getVariable("parentServiceInstanceId") + String serviceChainServiceInstanceId = execution.getVariable("serviceChainServiceInstanceId") + String callbackUrl = execution.getVariable("sdncCallbackUrl") + String requestId = execution.getVariable("msoRequestId") + + String brgWanMacAddress = execution.getVariable("brgWanMacAddress") + + String arModelInfo = execution.getVariable("allottedResourceModelInfo") + String modelInvariantId = jsonUtil.getJsonValue(arModelInfo, "modelInvariantUuid") + String modelVersion = jsonUtil.getJsonValue(arModelInfo, "modelVersion") + String modelUUId = jsonUtil.getJsonValue(arModelInfo, "modelUuid") + String modelCustomizationId = jsonUtil.getJsonValue(arModelInfo, "modelCustomizationUuid") + String modelName = jsonUtil.getJsonValue(arModelInfo, "modelName") + + if (modelInvariantId == null) { + modelInvariantId = "" + } + if (modelVersion == null) { + modelVersion = "" + } + if (modelUUId == null) { + modelUUId = "" + } + if (modelName == null) { + modelName = "" + } + if (modelCustomizationId == null) { + modelCustomizationId = "" + } + + sdncReq = + """<sdncadapterworkflow:SDNCAdapterWorkflowRequest xmlns:ns5="http://org.onap/so/request/types/v1" + xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1" + xmlns:sdncadapter="http://org.onap/workflow/sdnc/adapter/schema/v1"> + <sdncadapter:RequestHeader> + <sdncadapter:RequestId>${MsoUtils.xmlEscape(sdncRequestId)}</sdncadapter:RequestId> + <sdncadapter:SvcInstanceId>${MsoUtils.xmlEscape(serviceInstanceId)}</sdncadapter:SvcInstanceId> + <sdncadapter:SvcAction>${MsoUtils.xmlEscape(action)}</sdncadapter:SvcAction> + <sdncadapter:SvcOperation>tunnelxconn-topology-operation</sdncadapter:SvcOperation> + <sdncadapter:CallbackUrl>${MsoUtils.xmlEscape(callbackUrl)}</sdncadapter:CallbackUrl> + </sdncadapter:RequestHeader> + <sdncadapterworkflow:SDNCRequestData> + <request-information> + <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> + <request-action>CreateTunnelXConnInstance</request-action> + <source>MSO</source> + <notification-url/> + <order-number/> + <order-version/> + </request-information> + <service-information> + <service-id></service-id> + <subscription-service-type>${MsoUtils.xmlEscape(subscriptionServiceType)}</subscription-service-type> + <onap-model-information></onap-model-information> + <service-instance-id>${MsoUtils.xmlEscape(serviceInstanceId)}</service-instance-id> + <subscriber-name/> + <global-customer-id>${MsoUtils.xmlEscape(globalCustomerId)}</global-customer-id> + </service-information> + <allotted-resource-information> + <allotted-resource-id>${MsoUtils.xmlEscape(allottedResourceId)}</allotted-resource-id> + <allotted-resource-type>tunnelxconn</allotted-resource-type> + <parent-service-instance-id>${MsoUtils.xmlEscape(parentServiceInstanceId)}</parent-service-instance-id> + <onap-model-information> + <model-invariant-uuid>${MsoUtils.xmlEscape(modelInvariantId)}</model-invariant-uuid> + <model-uuid>${MsoUtils.xmlEscape(modelUUId)}</model-uuid> + <model-customization-uuid>${MsoUtils.xmlEscape(modelCustomizationId)}</model-customization-uuid> + <model-version>${MsoUtils.xmlEscape(modelVersion)}</model-version> + <model-name>${MsoUtils.xmlEscape(modelName)}</model-name> + </onap-model-information> + </allotted-resource-information> + <tunnelxconn-request-input> + <brg-wan-mac-address>${MsoUtils.xmlEscape(brgWanMacAddress)}</brg-wan-mac-address> + </tunnelxconn-request-input> + </sdncadapterworkflow:SDNCRequestData> + </sdncadapterworkflow:SDNCAdapterWorkflowRequest>""" + + msoLogger.debug("sdncRequest:\n" + sdncReq) + sdncReq = utils.formatXml(sdncReq) + + } catch(Exception ex) { + msg = "Exception in buildSDNCRequest. " + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.trace("end buildSDNCRequest") + return sdncReq + } + + public void preProcessSDNCAssign(DelegateExecution execution) { + + + String msg = "" + msoLogger.trace("start preProcessSDNCAssign") + + try { + String sdncRequestId = UUID.randomUUID().toString() + String sdncAssignReq = buildSDNCRequest(execution, "assign", sdncRequestId) + execution.setVariable("sdncAssignRequest", sdncAssignReq) + msoLogger.debug("sdncAssignRequest: " + sdncAssignReq) + def sdncRequestId2 = UUID.randomUUID().toString() + String sdncAssignRollbackReq = sdncAssignReq.replace(">assign<", ">unassign<").replace(">CreateTunnelXConnInstance<", ">DeleteTunnelXConnInstance<").replace(">${sdncRequestId}<", ">${sdncRequestId2}<") + def rollbackData = execution.getVariable("rollbackData") + rollbackData.put(Prefix, "sdncAssignRollbackReq", sdncAssignRollbackReq) + execution.setVariable("rollbackData", rollbackData) + + msoLogger.debug("sdncAssignRollbackReq:\n" + sdncAssignRollbackReq) + msoLogger.debug("rollbackData:\n" + rollbackData.toString()) + + } catch (BpmnError e) { + throw e; + } catch(Exception ex) { + msg = "Exception in preProcessSDNCAssign. " + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.debug("end preProcessSDNCAssign") + } + + public void preProcessSDNCCreate(DelegateExecution execution) { + + + String msg = "" + msoLogger.trace("start preProcessSDNCCreate") + + try { + String sdncRequestId = UUID.randomUUID().toString() + String sdncCreateReq = buildSDNCRequest(execution, "create", sdncRequestId) + execution.setVariable("sdncCreateRequest", sdncCreateReq) + msoLogger.debug("sdncCreateReq: " + sdncCreateReq) + def sdncRequestId2 = UUID.randomUUID().toString() + String sdncCreateRollbackReq = sdncCreateReq.replace(">create<", ">delete<").replace(">CreateTunnelXConnInstance<", ">DeleteTunnelXConnInstance<").replace(">${sdncRequestId}<", ">${sdncRequestId2}<") + def rollbackData = execution.getVariable("rollbackData") + rollbackData.put(Prefix, "sdncCreateRollbackReq", sdncCreateRollbackReq) + execution.setVariable("rollbackData", rollbackData) + + msoLogger.debug("sdncCreateRollbackReq:\n" + sdncCreateRollbackReq) + msoLogger.debug("rollbackData:\n" + rollbackData.toString()) + + } catch (BpmnError e) { + throw e; + } catch(Exception ex) { + msg = "Exception in preProcessSDNCCreate. " + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.trace("end preProcessSDNCCreate") + } + + public void preProcessSDNCActivate(DelegateExecution execution) { + + + String msg = "" + msoLogger.trace("start preProcessSDNCActivate") + + try { + String sdncRequestId = UUID.randomUUID().toString() + String sdncActivateReq = buildSDNCRequest(execution, "activate", sdncRequestId) + execution.setVariable("sdncActivateRequest", sdncActivateReq) + msoLogger.debug("sdncActivateReq: " + sdncActivateReq) + def sdncRequestId2 = UUID.randomUUID().toString() + String sdncActivateRollbackReq = sdncActivateReq.replace(">activate<", ">deactivate<").replace(">CreateTunnelXConnInstance<", ">DeleteTunnelXConnInstance<").replace(">${sdncRequestId}<", ">${sdncRequestId2}<") + def rollbackData = execution.getVariable("rollbackData") + rollbackData.put(Prefix, "sdncActivateRollbackReq", sdncActivateRollbackReq) + execution.setVariable("rollbackData", rollbackData) + + msoLogger.debug("sdncActivateRollbackReq:\n" + sdncActivateRollbackReq) + msoLogger.debug("rollbackData:\n" + rollbackData.toString()) + + } catch (BpmnError e) { + throw e; + } catch(Exception ex) { + msg = "Exception in preProcessSDNCActivate. " + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.trace("end preProcessSDNCActivate") + } + + public void validateSDNCResp(DelegateExecution execution, String response, String method){ + + + msoLogger.trace("start ValidateSDNCResponse Process") + String msg = "" + + try { + WorkflowException workflowException = execution.getVariable("WorkflowException") + msoLogger.debug("workflowException: " + workflowException) + + boolean successIndicator = execution.getVariable("SDNCA_SuccessIndicator") + msoLogger.debug("SDNCResponse: " + response) + + SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this) + sdncAdapterUtils.validateSDNCResponse(execution, response, workflowException, successIndicator) + + if(execution.getVariable(Prefix + 'sdncResponseSuccess') == true){ + msoLogger.debug("Received a Good Response from SDNC Adapter for " + method + " SDNC Call. Response is: \n" + response) + + if (!"get".equals(method)) + { + def rollbackData = execution.getVariable("rollbackData") + rollbackData.put(Prefix, "rollback" + "SDNC" + method, "true") + execution.setVariable("rollbackData", rollbackData) + } + + }else{ + msoLogger.debug("Received a BAD Response from SDNC Adapter for " + method + " SDNC Call.") + throw new BpmnError("MSOWorkflowException") + } + } catch (BpmnError e) { + throw e; + } catch(Exception ex) { + msg = "Exception in validateSDNCResp. " + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.trace("end ValidateSDNCResp Process") + } + + public void preProcessSDNCGet(DelegateExecution execution){ + + msoLogger.trace("start preProcessSDNCGet") + try{ + + def callbackUrl = execution.getVariable("sdncCallbackUrl") + // serviceOperation (URI for topology GET) will be retrieved from "selflink" from AAI if active AR exists in AAI + // or from "object-path" in SDNC response for assign when AR does not exist in AA + + String serviceOperation = "" + + if (execution.getVariable("foundActiveAR")) { + def aaiQueryResponse = execution.getVariable("aaiARGetResponse") + serviceOperation = utils.getNodeText(aaiQueryResponse, "selflink") + msoLogger.debug("AR service operation/aaiARSelfLink: " + serviceOperation) + } + else + { + String response = execution.getVariable("sdncAssignResponse") + String data = utils.getNodeXml(response, "response-data") + msoLogger.debug("Assign responseData: " + data) + serviceOperation = utils.getNodeText(data, "object-path") + msoLogger.debug("AR service operation:" + serviceOperation) + } + + String serviceInstanceId = execution.getVariable("serviceInstanceId") + String sdncRequestId = UUID.randomUUID().toString() + + //neeed the same url as used by vfmodules + String SDNCGetRequest = + """<sdncadapterworkflow:SDNCAdapterWorkflowRequest xmlns:ns5="http://org.onap/so/request/types/v1" + xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1" + xmlns:sdncadapter="http://org.onap/workflow/sdnc/adapter/schema/v1"> + <sdncadapter:RequestHeader> + <sdncadapter:RequestId>${MsoUtils.xmlEscape(sdncRequestId)}</sdncadapter:RequestId> + <sdncadapter:SvcInstanceId>${MsoUtils.xmlEscape(serviceInstanceId)}</sdncadapter:SvcInstanceId> + <sdncadapter:SvcAction>query</sdncadapter:SvcAction> + <sdncadapter:SvcOperation>${MsoUtils.xmlEscape(serviceOperation)}</sdncadapter:SvcOperation> + <sdncadapter:CallbackUrl>${MsoUtils.xmlEscape(callbackUrl)}</sdncadapter:CallbackUrl> + <sdncadapter:MsoAction>vfmodule</sdncadapter:MsoAction> + </sdncadapter:RequestHeader> + <sdncadapterworkflow:SDNCRequestData></sdncadapterworkflow:SDNCRequestData> + </sdncadapterworkflow:SDNCAdapterWorkflowRequest>""" + + execution.setVariable("sdncGetRequest", SDNCGetRequest) + + }catch(Exception e){ + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception Occurred Processing preProcessSDNCGetRequest.", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during SDNC GET Method:\n" + e.getMessage()) + } + msoLogger.trace("end preProcessSDNCGet") + } + + public void updateAaiAROrchStatus(DelegateExecution execution, String status){ + + msoLogger.trace("start updateAaiAROrchStatus") + String aaiARPath = execution.getVariable("aaiARPath") //set during query (existing AR) or create + AllottedResourceUtils arUtils = new AllottedResourceUtils(this) + String orchStatus = arUtils.updateAROrchStatus(execution, status, aaiARPath) + msoLogger.trace("end updateAaiAROrchStatus") + } + + public void generateOutputs(DelegateExecution execution) + { + + msoLogger.trace("start generateOutputs") + try { + String sdncGetResponse = execution.getVariable("enhancedCallbackRequestData") //unescaped + msoLogger.debug("resp:" + sdncGetResponse) + String arData = utils.getNodeXml(sdncGetResponse, "tunnelxconn-topology") + arData = utils.removeXmlNamespaces(arData) + + String txca = utils.getNodeXml(arData, "tunnelxconn-assignments") + execution.setVariable("vni", utils.getNodeText(txca, "vni")) + execution.setVariable("vgmuxBearerIP", utils.getNodeText(txca, "vgmux-bearer-ip")) + execution.setVariable("vgmuxLanIP", utils.getNodeText(txca, "vgmux-lan-ip")) + + String ari = utils.getNodeXml(arData, "allotted-resource-identifiers") + execution.setVariable("allotedResourceName", utils.getNodeText(ari, "allotted-resource-name")) + } catch (BpmnError e) { + msoLogger.debug("BPMN Error in generateOutputs ") + } catch(Exception ex) { + String msg = "Exception in generateOutputs " + ex.getMessage() + msoLogger.debug(msg) + } + msoLogger.trace("end generateOutputs") + + } + + public void preProcessRollback (DelegateExecution execution) { + + msoLogger.trace("start preProcessRollback") + try { + + Object workflowException = execution.getVariable("WorkflowException"); + + if (workflowException instanceof WorkflowException) { + msoLogger.debug("Prev workflowException: " + workflowException.getErrorMessage()) + execution.setVariable("prevWorkflowException", workflowException); + //execution.setVariable("WorkflowException", null); + } + } catch (BpmnError e) { + msoLogger.debug("BPMN Error during preProcessRollback") + } catch(Exception ex) { + String msg = "Exception in preProcessRollback. " + ex.getMessage() + msoLogger.debug(msg) + } + msoLogger.trace("end preProcessRollback") + } + + public void postProcessRollback (DelegateExecution execution) { + + msoLogger.trace("start postProcessRollback") + String msg = "" + try { + Object workflowException = execution.getVariable("prevWorkflowException"); + if (workflowException instanceof WorkflowException) { + msoLogger.debug("Setting prevException to WorkflowException: ") + execution.setVariable("WorkflowException", workflowException); + } + execution.setVariable("rollbackData", null) + } catch (BpmnError b) { + msoLogger.debug("BPMN Error during postProcessRollback") + throw b; + } catch(Exception ex) { + msg = "Exception in postProcessRollback. " + ex.getMessage() + msoLogger.debug(msg) + } + msoLogger.trace("end postProcessRollback") + } + +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceTXCRollback.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceTXCRollback.groovy new file mode 100644 index 0000000000..24b919524f --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceTXCRollback.groovy @@ -0,0 +1,278 @@ +/* + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.vcpe.scripts; + +import org.onap.so.bpmn.common.scripts.*; +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.bpmn.common.scripts.ExceptionUtil +import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.so.bpmn.common.scripts.AaiUtil +import org.onap.so.bpmn.common.scripts.SDNCAdapterUtils +import org.onap.so.rest.APIResponse + +import java.util.UUID; +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.apache.commons.lang3.* +import org.springframework.web.util.UriUtils; +import static org.apache.commons.lang3.StringUtils.* + +import org.onap.so.logger.MessageEnum +import org.onap.so.logger.MsoLogger + +/** + * This groovy class supports the <class>CreateAllottedResourceTXCRollback.bpmn</class> process. + * + * @author + * + * Inputs: + * @param - msoRequestId + * @param - isDebugLogEnabled + * @param - disableRollback - O + * @param - rollbackData + * + * Outputs: + * @param - rollbackError + * @param - rolledBack (no localRB->null, localRB F->false, localRB S->true) + * + */ +public class DoCreateAllottedResourceTXCRollback extends AbstractServiceTaskProcessor{ + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoCreateAllottedResourceTXCRollback.class); + + String Prefix="DCARTXCRB_" + ExceptionUtil exceptionUtil = new ExceptionUtil() + + public void preProcessRequest (DelegateExecution execution) { + + + String msg = "" + msoLogger.trace("start preProcessRequest") + execution.setVariable("prefix", Prefix) + String rbType = "DCARTXC_" + try { + + def rollbackData = execution.getVariable("rollbackData") + msoLogger.debug("RollbackData:" + rollbackData) + + if (rollbackData != null) { + if (rollbackData.hasType(rbType)) { + + execution.setVariable("serviceInstanceId", rollbackData.get(rbType, "serviceInstanceId")) + execution.setVariable("parentServiceInstanceId", rollbackData.get(rbType, "parentServiceInstanceId")) + execution.setVariable("allottedResourceId", rollbackData.get("SERVICEINSTANCE", "allottedResourceId")) + + + def rollbackAAI = rollbackData.get(rbType, "rollbackAAI") + if ("true".equals(rollbackAAI)) + { + execution.setVariable("rollbackAAI",true) + execution.setVariable("aaiARPath", rollbackData.get(rbType, "aaiARPath")) + + } + def rollbackSDNC = rollbackData.get(rbType, "rollbackSDNCassign") + if ("true".equals(rollbackSDNC)) + { + execution.setVariable("rollbackSDNC", true) + execution.setVariable("deactivateSdnc", rollbackData.get(rbType, "rollbackSDNCactivate")) + execution.setVariable("deleteSdnc", rollbackData.get(rbType, "rollbackSDNCcreate")) + execution.setVariable("unassignSdnc", rollbackData.get(rbType, "rollbackSDNCassign")) + + msoLogger.debug("sdncDeactivate:\n" + execution.getVariable("deactivateSdnc") ) + msoLogger.debug("sdncDelete:\n" + execution.getVariable("deleteSdnc")) + msoLogger.debug("sdncUnassign:\n" + execution.getVariable("unassignSdnc")) + + execution.setVariable("sdncDeactivateRequest", rollbackData.get(rbType, "sdncActivateRollbackReq")) + execution.setVariable("sdncDeleteRequest", rollbackData.get(rbType, "sdncCreateRollbackReq")) + execution.setVariable("sdncUnassignRequest", rollbackData.get(rbType, "sdncAssignRollbackReq")) + } + + if (execution.getVariable("rollbackAAI") != true && execution.getVariable("rollbackSDNC") != true) + { + execution.setVariable("skipRollback", true) + } + } + else { + execution.setVariable("skipRollback", true) + } + } + else { + execution.setVariable("skipRollback", true) + } + if (execution.getVariable("disableRollback").equals("true" )) + { + execution.setVariable("skipRollback", true) + } + + }catch(BpmnError b){ + msoLogger.debug("Rethrowing MSOWorkflowException") + throw b + } catch (Exception ex){ + msg = "Exception in preProcessRequest " + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.trace("end preProcessRequest") + } + + // aaiARPath set during query (existing AR) + public void updateAaiAROrchStatus(DelegateExecution execution, String status){ + + String msg = null; + msoLogger.trace("start updateAaiAROrchStatus") + AllottedResourceUtils arUtils = new AllottedResourceUtils(this) + String aaiARPath = execution.getVariable("aaiARPath") + msoLogger.debug(" aaiARPath:" + aaiARPath) + String ar = null; //need this for getting resourceVersion for delete + if (!isBlank(aaiARPath)) + { + ar = arUtils.getARbyLink(execution, aaiARPath, "") + } + if (isBlank(ar)) + { + msg = "AR not found in AAI at:" + aaiARPath + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + String orchStatus = arUtils.updateAROrchStatus(execution, status, aaiARPath) + msoLogger.trace("end updateAaiAROrchStatus") + } + + public void validateSDNCResp(DelegateExecution execution, String response, String method){ + + + msoLogger.trace("start ValidateSDNCResponse Process") + String msg = "" + + try { + WorkflowException workflowException = execution.getVariable("WorkflowException") + msoLogger.debug("workflowException: " + workflowException) + + boolean successIndicator = execution.getVariable("SDNCA_SuccessIndicator") + msoLogger.debug("SDNCResponse: " + response) + + SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this) + sdncAdapterUtils.validateSDNCResponse(execution, response, workflowException, successIndicator) + + if(execution.getVariable(Prefix + 'sdncResponseSuccess') == true){ + msoLogger.debug("Received a Good Response from SDNC Adapter for " + method + " SDNC Call. Response is: \n" + response) + + }else{ + + msoLogger.debug("Received a BAD Response from SDNC Adapter for " + method + " SDNC Call.") + throw new BpmnError("MSOWorkflowException") + } + } catch (BpmnError e) { + if ("404".contentEquals(e.getErrorCode())) + { + msg = "SDNC rollback " + method + " returned a 404. Proceding with rollback" + msoLogger.debug(msg) + } + else { + throw e; + } + } catch(Exception ex) { + msg = "Exception in validateSDNCResp. " + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.trace("Exit ValidateSDNCResp Process") + } + + public void deleteAaiAR(DelegateExecution execution){ + + try{ + msoLogger.trace("start deleteAaiAR") + AllottedResourceUtils arUtils = new AllottedResourceUtils(this) + String ar = null //need to get resource-version + String arLink = execution.getVariable("aaiARPath") + if (!isBlank(arLink)) + { + ar = arUtils.getARbyLink(execution, arLink, "") + } + arUtils.deleteAR(execution, arLink + '?resource-version=' + UriUtils.encode(execution.getVariable("aaiARResourceVersion"),"UTF-8")) + } catch (BpmnError e) { + throw e; + }catch(Exception ex){ + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception Occurred Processing preProcessSDNCGetRequest.", "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + ex); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during SDNC GET Method:\n" + ex.getMessage()) + } + msoLogger.trace("end deleteAaiAR") + } + + public void postProcessRequest(DelegateExecution execution) { + + msoLogger.trace("start postProcessRequest") + String msg = "" + try { + execution.setVariable("rollbackData", null) + boolean skipRollback = execution.getVariable("skipRollback") + if (skipRollback != true) + { + execution.setVariable("rolledBack", true) + msoLogger.debug("rolledBack") + } + msoLogger.trace("end postProcessRequest") + + } catch (BpmnError e) { + msoLogger.debug(msg) + } catch (Exception ex) { + msg = "Exception in postProcessRequest. " + ex.getMessage() + msoLogger.debug(msg) + } + + } + + public void processRollbackException(DelegateExecution execution){ + + msoLogger.trace("start processRollbackException") + try{ + msoLogger.debug("Caught an Exception in DoCreateAllottedResourceRollback") + execution.setVariable("rollbackData", null) + execution.setVariable("rolledBack", false) + execution.setVariable("rollbackError", "Caught exception in AllottedResource Create Rollback") + execution.setVariable("WorkflowException", null) + + }catch(BpmnError b){ + msoLogger.debug("BPMN Error during processRollbackExceptions Method: ") + }catch(Exception e){ + msoLogger.debug("Caught Exception during processRollbackExceptions Method: " + e.getMessage()) + } + + msoLogger.trace("end processRollbackException") + } + + public void processRollbackJavaException(DelegateExecution execution){ + + msoLogger.trace("start processRollbackJavaException") + try{ + execution.setVariable("rollbackData", null) + execution.setVariable("rolledBack", false) + execution.setVariable("rollbackError", "Caught Java exception in AllottedResource Create Rollback") + msoLogger.debug("Caught Exception in processRollbackJavaException") + + }catch(Exception e){ + msoLogger.debug("Caught Exception in processRollbackJavaException " + e.getMessage()) + } + msoLogger.trace("end processRollbackJavaException") + } + +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoDeleteAllottedResourceBRG.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoDeleteAllottedResourceBRG.groovy new file mode 100644 index 0000000000..a5125fea73 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoDeleteAllottedResourceBRG.groovy @@ -0,0 +1,368 @@ +/* + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.vcpe.scripts; + +import org.onap.so.bpmn.common.scripts.*; +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.bpmn.common.scripts.ExceptionUtil +import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.so.bpmn.common.scripts.AaiUtil +import org.onap.so.bpmn.common.scripts.SDNCAdapterUtils +import org.onap.so.rest.APIResponse + +import java.util.UUID; +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.apache.commons.lang3.* +import org.springframework.web.util.UriUtils; +import static org.apache.commons.lang3.StringUtils.* +import org.onap.so.bpmn.core.UrnPropertiesReader; + +import org.onap.so.logger.MessageEnum +import org.onap.so.logger.MsoLogger + +/** + * This groovy class supports the <class>DoDeleteAllottedResourceBRG.bpmn</class> process. + * + * @author + * + * Inputs: + * @param - msoRequestId + * @param - isDebugLogEnabled + * @param - disableRollback - O ignored + * @param - failNotfound - O + * @param - serviceInstanceId + * @param - globalCustomerId - O + * @param - subscriptionServiceType - O + * @param - parentServiceInstanceId + * @param - allottedResourceId + * + * Outputs: + * @param - rollbackData - N/A + * @param - rolledBack - true if no deletions performed + * @param - WorkflowException - O + * @param - wasDeleted - O (ie not silentSuccess) + * + */ +public class DoDeleteAllottedResourceBRG extends AbstractServiceTaskProcessor{ + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoDeleteAllottedResourceBRG.class); + + String Prefix="DDARBRG_" + ExceptionUtil exceptionUtil = new ExceptionUtil() + + public void preProcessRequest (DelegateExecution execution) { + + String msg = "" + msoLogger.trace("start preProcessRequest") + + try { + execution.setVariable("prefix", Prefix) + + //Config Inputs + String sdncCallbackUrl = UrnPropertiesReader.getVariable("mso.workflow.sdncadapter.callback",execution) + if (isBlank(sdncCallbackUrl)) { + msg = "mso.workflow.sdncadapter.callback is null" + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + execution.setVariable("sdncCallbackUrl", sdncCallbackUrl) + msoLogger.debug("SDNC Callback URL: " + sdncCallbackUrl) + + //Request Inputs + if (isBlank(execution.getVariable("serviceInstanceId"))){ + msg = "Input serviceInstanceId is null" + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + if (isBlank(execution.getVariable("allottedResourceId"))){ + msg = "Input allottedResourceId is null" + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + + }catch(BpmnError b){ + msoLogger.debug("Rethrowing MSOWorkflowException") + throw b + } catch (Exception ex){ + msg = "Exception in preProcessRequest " + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.trace("end preProcessRequest") + } + + public void getAaiAR (DelegateExecution execution) { + + msoLogger.trace("start getAaiAR end") + + String allottedResourceId = execution.getVariable("allottedResourceId") + + AllottedResourceUtils arUtils = new AllottedResourceUtils(this) + String ar = arUtils.getARbyId(execution, allottedResourceId) + + String errorMsg = "" + if (isBlank(ar)) // AR was !found + { + errorMsg = "Allotted resource not found in AAI with AllottedResourceId:" + allottedResourceId + } + else + { + String aaiARPath = execution.getVariable("aaiARPath") + String parentServiceInstanceId = arUtils.getPSIFmARLink(execution, aaiARPath) + execution.setVariable("parentServiceInstanceId", parentServiceInstanceId) + } + if (!isBlank(errorMsg)) { + msoLogger.debug(errorMsg) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, errorMsg) + } + msoLogger.trace("end getAaiAR") + + } + + // aaiARPath set during query (existing AR) + public void updateAaiAROrchStatus(DelegateExecution execution, String status){ + msoLogger.trace("start updateAaiAROrchStatus") + AllottedResourceUtils arUtils = new AllottedResourceUtils(this) + String aaiARPath = execution.getVariable("aaiARPath") //set during query (existing AR) + String orchStatus = arUtils.updateAROrchStatus(execution, status, aaiARPath) + msoLogger.trace("end updateAaiAROrchStatus") + } + + public String buildSDNCRequest(DelegateExecution execution, String action, String sdncRequestId) { + + String msg = "" + msoLogger.trace("start buildSDNCRequest") + String sdncReq = null + + try { + + String allottedResourceId = execution.getVariable("allottedResourceId") + String serviceInstanceId = execution.getVariable("serviceInstanceId") + String parentServiceInstanceId = execution.getVariable("parentServiceInstanceId") + String globalCustomerId = execution.getVariable("globalCustomerId") + String subscriptionServiceType = execution.getVariable("subscriptionServiceType") + + String callbackUrl = execution.getVariable("sdncCallbackUrl") + String requestId = execution.getVariable("msoRequestId") + + String serviceChainServiceInstanceId = "" + String sourceNetworkId = "" + String sourceNetworkRole = "" + String allottedResourceRole = "" + + String arModelInfo = "" + String modelInvariantId = "" + String modelVersion = "" + String modelUUId = "" + String modelCustomizationId = "" + String modelName = "" + + + sdncReq = + """<sdncadapterworkflow:SDNCAdapterWorkflowRequest xmlns:ns5="http://org.onap/so/request/types/v1" + xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1" + xmlns:sdncadapter="http://org.onap/workflow/sdnc/adapter/schema/v1"> + <sdncadapter:RequestHeader> + <sdncadapter:RequestId>${MsoUtils.xmlEscape(sdncRequestId)}</sdncadapter:RequestId> + <sdncadapter:SvcInstanceId>${MsoUtils.xmlEscape(serviceInstanceId)}</sdncadapter:SvcInstanceId> + <sdncadapter:SvcAction>${MsoUtils.xmlEscape(action)}</sdncadapter:SvcAction> + <sdncadapter:SvcOperation>brg-topology-operation</sdncadapter:SvcOperation> + <sdncadapter:CallbackUrl>${MsoUtils.xmlEscape(callbackUrl)}</sdncadapter:CallbackUrl> + </sdncadapter:RequestHeader> + <sdncadapterworkflow:SDNCRequestData> + <request-information> + <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> + <request-action>DeleteBRGInstance</request-action> + <source>MSO</source> + <notification-url/> + <order-number/> + <order-version/> + </request-information> + <service-information> + <service-id></service-id> + <subscription-service-type>${MsoUtils.xmlEscape(subscriptionServiceType)}</subscription-service-type> + <onap-model-information></onap-model-information> + <service-instance-id>${MsoUtils.xmlEscape(serviceInstanceId)}</service-instance-id> + <subscriber-name/> + <global-customer-id>${MsoUtils.xmlEscape(globalCustomerId)}</global-customer-id> + </service-information> + <allotted-resource-information> + <allotted-resource-id>${MsoUtils.xmlEscape(allottedResourceId)}</allotted-resource-id> + <allotted-resource-type>brg</allotted-resource-type> + <parent-service-instance-id>${MsoUtils.xmlEscape(parentServiceInstanceId)}</parent-service-instance-id> + <onap-model-information> + <model-invariant-uuid>${MsoUtils.xmlEscape(modelInvariantId)}</model-invariant-uuid> + <model-uuid>${MsoUtils.xmlEscape(modelUUId)}</model-uuid> + <model-customization-uuid>${MsoUtils.xmlEscape(modelCustomizationId)}</model-customization-uuid> + <model-version>${MsoUtils.xmlEscape(modelVersion)}</model-version> + <model-name>${MsoUtils.xmlEscape(modelName)}</model-name> + </onap-model-information> + </allotted-resource-information> + <brg-request-input> + </brg-request-input> + </sdncadapterworkflow:SDNCRequestData> + </sdncadapterworkflow:SDNCAdapterWorkflowRequest>""" + + msoLogger.debug("sdncRequest:\n" + sdncReq) + sdncReq = utils.formatXml(sdncReq) + + } catch(Exception ex) { + msg = "Exception in buildSDNCRequest. " + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.trace("end buildSDNCRequest") + return sdncReq + } + + public void preProcessSDNCUnassign(DelegateExecution execution) { + + String msg = "" + msoLogger.trace("start preProcessSDNCUnassign") + + try { + String sdncRequestId = UUID.randomUUID().toString() + String sdncUnassignReq = buildSDNCRequest(execution, "unassign", sdncRequestId) + execution.setVariable("sdncUnassignRequest", sdncUnassignReq) + msoLogger.debug("sdncUnassignRequest: " + sdncUnassignReq) + } catch (BpmnError e) { + throw e; + } catch(Exception ex) { + msg = "Exception in preProcessSDNCUnassign. " + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.trace("end preProcessSDNCUnassign") + } + + public void preProcessSDNCDelete(DelegateExecution execution) { + + String msg = "" + msoLogger.trace("start preProcessSDNCDelete") + + try { + String sdncRequestId = UUID.randomUUID().toString() + String sdncDeleteReq = buildSDNCRequest(execution, "delete", sdncRequestId) + execution.setVariable("sdncDeleteRequest", sdncDeleteReq) + msoLogger.debug("sdncDeleteReq: " + sdncDeleteReq) + } catch (BpmnError e) { + throw e; + } catch(Exception ex) { + msg = "Exception in preProcessSDNCDelete. " + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.trace("end preProcessSDNCDelete") + } + + public void preProcessSDNCDeactivate(DelegateExecution execution) { + + String msg = "" + msoLogger.trace("start preProcessSDNCDeactivate") + + try { + String sdncRequestId = UUID.randomUUID().toString() + String sdncDeactivateReq = buildSDNCRequest(execution, "deactivate", sdncRequestId) + execution.setVariable("sdncDeactivateRequest", sdncDeactivateReq) + msoLogger.debug("sdncDeactivateReq: " + sdncDeactivateReq) + } catch (BpmnError e) { + throw e; + } catch(Exception ex) { + msg = "Exception in preProcessSDNCDeactivate. " + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.trace("end preProcessSDNCDeactivate") + } + + public void validateSDNCResp(DelegateExecution execution, String response, String method){ + + msoLogger.trace("start ValidateSDNCResponse Process") + String msg = "" + + try { + WorkflowException workflowException = execution.getVariable("WorkflowException") + msoLogger.debug("workflowException: " + workflowException) + + boolean successIndicator = execution.getVariable("SDNCA_SuccessIndicator") + msoLogger.debug("SDNCResponse: " + response) + + SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this) + sdncAdapterUtils.validateSDNCResponse(execution, response, workflowException, successIndicator) + + if(execution.getVariable(Prefix + 'sdncResponseSuccess') == true){ + msoLogger.debug("Received a Good Response from SDNC Adapter for " + method + " SDNC Call. Response is: \n" + response) + + }else{ + String sdncRespCode = execution.getVariable(Prefix + 'sdncRequestDataResponseCode') + msoLogger.debug(method + " AllottedResource received error response from SDNC. ResponseCode:" + sdncRespCode) + if (sdncRespCode.equals("404") && "deactivate".equals(method)) + { + execution.setVariable("ARNotFoundInSDNC", true) + if ("true".equals(execution.getVariable("failNotFound"))) + { + msg = "Allotted Resource Not found in SDNC" + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + else + { + execution.setVariable("wasDeleted", false) + } + } + else + { + throw new BpmnError("MSOWorkflowException") + } + } + } catch (BpmnError e) { + throw e; + } catch(Exception ex) { + msg = "Exception in validateSDNCResp. " + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.trace("end ValidateSDNCResp Process") + } + + public void deleteAaiAR(DelegateExecution execution){ + msoLogger.trace("start deleteAaiAR") + + try{ + AllottedResourceUtils arUtils = new AllottedResourceUtils(this) + String ar = null //need to get resource-version again + String arLink = execution.getVariable("aaiARPath") + if (!isBlank(arLink)) + { + ar = arUtils.getARbyLink(execution, arLink, "") + } + arUtils.deleteAR(execution, arLink + '?resource-version=' + UriUtils.encode(execution.getVariable("aaiARResourceVersion"),"UTF-8")) + } catch (BpmnError e) { + throw e; + }catch(Exception ex){ + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception Occurred Processing preProcessSDNCGetRequest." + ex, "BPMN", MsoLogger.getServiceName(), MsoLogger.ErrorCode.UnknownError, "Exception is:" + ex); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during SDNC GET Method:\n" + ex.getMessage()) + } + msoLogger.trace("end deleteAaiAR") + } + +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoDeleteAllottedResourceTXC.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoDeleteAllottedResourceTXC.groovy new file mode 100644 index 0000000000..7ce606e685 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoDeleteAllottedResourceTXC.groovy @@ -0,0 +1,369 @@ +/* + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.vcpe.scripts; + +import org.onap.so.bpmn.common.scripts.*; +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.bpmn.common.scripts.ExceptionUtil +import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.so.bpmn.common.scripts.AaiUtil +import org.onap.so.bpmn.common.scripts.SDNCAdapterUtils +import org.onap.so.rest.APIResponse + +import java.util.UUID; +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.apache.commons.lang3.* +import org.springframework.web.util.UriUtils; +import static org.apache.commons.lang3.StringUtils.* +import org.onap.so.bpmn.core.UrnPropertiesReader; + +import org.onap.so.logger.MessageEnum +import org.onap.so.logger.MsoLogger + +/** + * This groovy class supports the <class>DoDeleteAllottedResourceTXC.bpmn</class> process. + * + * @author + * + * Inputs: + * @param - msoRequestId + * @param - isDebugLogEnabled + * @param - disableRollback - O ignored + * @param - failNotfound - O + * @param - serviceInstanceId + * @param - globalCustomerId - O + * @param - subscriptionServiceType - O + * @param - parentServiceInstanceId + * @param - allottedResourceId + * + * Outputs: + * @param - rollbackData - N/A + * @param - rolledBack - true if no deletions performed + * @param - WorkflowException - O + * @param - wasDeleted - O (ie not silentSuccess) + * + */ +public class DoDeleteAllottedResourceTXC extends AbstractServiceTaskProcessor{ + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoDeleteAllottedResourceTXC.class); + + String Prefix="DDARTXC_" + ExceptionUtil exceptionUtil = new ExceptionUtil() + + public void preProcessRequest (DelegateExecution execution) { + + String msg = "" + msoLogger.trace("start preProcessRequest") + + try { + execution.setVariable("prefix", Prefix) + + //Config Inputs + String sdncCallbackUrl = UrnPropertiesReader.getVariable("mso.workflow.sdncadapter.callback",execution) + if (isBlank(sdncCallbackUrl)) { + msg = "mso.workflow.sdncadapter.callback is null" + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + execution.setVariable("sdncCallbackUrl", sdncCallbackUrl) + msoLogger.debug("SDNC Callback URL: " + sdncCallbackUrl) + + //Request Inputs + if (isBlank(execution.getVariable("serviceInstanceId"))){ + msg = "Input serviceInstanceId is null" + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + if (isBlank(execution.getVariable("allottedResourceId"))){ + msg = "Input allottedResourceId is null" + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + + }catch(BpmnError b){ + msoLogger.debug("Rethrowing MSOWorkflowException") + throw b + } catch (Exception ex){ + msg = "Exception in preProcessRequest " + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.trace("end preProcessRequest") + } + + public void getAaiAR (DelegateExecution execution) { + + msoLogger.trace("start getAaiAR") + + String allottedResourceId = execution.getVariable("allottedResourceId") + + AllottedResourceUtils arUtils = new AllottedResourceUtils(this) + String ar = arUtils.getARbyId(execution, allottedResourceId) + + String errorMsg = "" + if (isBlank(ar)) // AR was !found + { + errorMsg = "Allotted resource not found in AAI with AllottedResourceId:" + allottedResourceId + } + else + { + String aaiARPath = execution.getVariable("aaiARPath") + String parentServiceInstanceId = arUtils.getPSIFmARLink(execution, aaiARPath) + execution.setVariable("parentServiceInstanceId", parentServiceInstanceId) + } + if (!isBlank(errorMsg)) { + msoLogger.debug(errorMsg) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, errorMsg) + } + msoLogger.trace("end getAaiAR") + + } + + // aaiARPath set during query (existing AR) + public void updateAaiAROrchStatus(DelegateExecution execution, String status){ + msoLogger.trace("start updateAaiAROrchStatus") + AllottedResourceUtils arUtils = new AllottedResourceUtils(this) + String aaiARPath = execution.getVariable("aaiARPath") //set during query (existing AR) + String orchStatus = arUtils.updateAROrchStatus(execution, status, aaiARPath) + msoLogger.trace("end updateAaiAROrchStatus") + } + + public String buildSDNCRequest(DelegateExecution execution, String action, String sdncRequestId) { + + String msg = "" + msoLogger.trace("start buildSDNCRequest") + String sdncReq = null + + try { + + String allottedResourceId = execution.getVariable("allottedResourceId") + String serviceInstanceId = execution.getVariable("serviceInstanceId") + String parentServiceInstanceId = execution.getVariable("parentServiceInstanceId") + String globalCustomerId = execution.getVariable("globalCustomerId") + String subscriptionServiceType = execution.getVariable("subscriptionServiceType") + + String callbackUrl = execution.getVariable("sdncCallbackUrl") + String requestId = execution.getVariable("msoRequestId") + + String serviceChainServiceInstanceId = "" + String sourceNetworkId = "" + String sourceNetworkRole = "" + String allottedResourceRole = "" + + String arModelInfo = "" + String modelInvariantId = "" + String modelVersion = "" + String modelUUId = "" + String modelCustomizationId = "" + String modelName = "" + + + sdncReq = + """<sdncadapterworkflow:SDNCAdapterWorkflowRequest xmlns:ns5="http://org.onap/so/request/types/v1" + xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1" + xmlns:sdncadapter="http://org.onap/workflow/sdnc/adapter/schema/v1"> + <sdncadapter:RequestHeader> + <sdncadapter:RequestId>${MsoUtils.xmlEscape(sdncRequestId)}</sdncadapter:RequestId> + <sdncadapter:SvcInstanceId>${MsoUtils.xmlEscape(serviceInstanceId)}</sdncadapter:SvcInstanceId> + <sdncadapter:SvcAction>${MsoUtils.xmlEscape(action)}</sdncadapter:SvcAction> + <sdncadapter:SvcOperation>tunnelxconn-topology-operation</sdncadapter:SvcOperation> + <sdncadapter:CallbackUrl>${MsoUtils.xmlEscape(callbackUrl)}</sdncadapter:CallbackUrl> + </sdncadapter:RequestHeader> + <sdncadapterworkflow:SDNCRequestData> + <request-information> + <request-id>${MsoUtils.xmlEscape(requestId)}</request-id> + <request-action>DeleteTunnelXConnInstance</request-action> + <source>MSO</source> + <notification-url/> + <order-number/> + <order-version/> + </request-information> + <service-information> + <service-id></service-id> + <subscription-service-type>${MsoUtils.xmlEscape(subscriptionServiceType)}</subscription-service-type> + <onap-model-information></onap-model-information> + <service-instance-id>${MsoUtils.xmlEscape(serviceInstanceId)}</service-instance-id> + <subscriber-name/> + <global-customer-id>${MsoUtils.xmlEscape(globalCustomerId)}</global-customer-id> + </service-information> + <allotted-resource-information> + <allotted-resource-id>${MsoUtils.xmlEscape(allottedResourceId)}</allotted-resource-id> + <allotted-resource-type>tunnelxconn</allotted-resource-type> + <parent-service-instance-id>${MsoUtils.xmlEscape(parentServiceInstanceId)}</parent-service-instance-id> + <onap-model-information> + <model-invariant-uuid>${MsoUtils.xmlEscape(modelInvariantId)}</model-invariant-uuid> + <model-uuid>${MsoUtils.xmlEscape(modelUUId)}</model-uuid> + <model-customization-uuid>${MsoUtils.xmlEscape(modelCustomizationId)}</model-customization-uuid> + <model-version>${MsoUtils.xmlEscape(modelVersion)}</model-version> + <model-name>${MsoUtils.xmlEscape(modelName)}</model-name> + </onap-model-information> + </allotted-resource-information> + <tunnelxconn-request-input> + </tunnelxconn-request-input> + </sdncadapterworkflow:SDNCRequestData> + </sdncadapterworkflow:SDNCAdapterWorkflowRequest>""" + + msoLogger.debug("sdncRequest:\n" + sdncReq) + sdncReq = utils.formatXml(sdncReq) + + } catch(Exception ex) { + msg = "Exception in buildSDNCRequest. " + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.trace("end buildSDNCRequest") + return sdncReq + } + + public void preProcessSDNCUnassign(DelegateExecution execution) { + + String msg = "" + msoLogger.trace("start preProcessSDNCUnassign") + + try { + String sdncRequestId = UUID.randomUUID().toString() + String sdncUnassignReq = buildSDNCRequest(execution, "unassign", sdncRequestId) + execution.setVariable("sdncUnassignRequest", sdncUnassignReq) + msoLogger.debug("sdncUnassignRequest: " + sdncUnassignReq) + } catch (BpmnError e) { + throw e; + } catch(Exception ex) { + msg = "Exception in preProcessSDNCUnassign. " + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.trace("end preProcessSDNCUnassign") + } + + public void preProcessSDNCDelete(DelegateExecution execution) { + + String msg = "" + msoLogger.trace("start preProcessSDNCDelete") + + try { + String sdncRequestId = UUID.randomUUID().toString() + String sdncDeleteReq = buildSDNCRequest(execution, "delete", sdncRequestId) + execution.setVariable("sdncDeleteRequest", sdncDeleteReq) + msoLogger.debug("sdncDeleteReq: " + sdncDeleteReq) + } catch (BpmnError e) { + throw e; + } catch(Exception ex) { + msg = "Exception in preProcessSDNCDelete. " + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.trace("end preProcessSDNCDelete") + } + + public void preProcessSDNCDeactivate(DelegateExecution execution) { + + String msg = "" + msoLogger.trace("start preProcessSDNCDeactivate") + + try { + String sdncRequestId = UUID.randomUUID().toString() + String sdncDeactivateReq = buildSDNCRequest(execution, "deactivate", sdncRequestId) + execution.setVariable("sdncDeactivateRequest", sdncDeactivateReq) + msoLogger.debug("sdncDeactivateReq: " + sdncDeactivateReq) + } catch (BpmnError e) { + throw e; + } catch(Exception ex) { + msg = "Exception in preProcessSDNCDeactivate. " + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.trace("end preProcessSDNCDeactivate") + } + + public void validateSDNCResp(DelegateExecution execution, String response, String method){ + + msoLogger.trace("start ValidateSDNCResponse Process") + String msg = "" + + try { + WorkflowException workflowException = execution.getVariable("WorkflowException") + msoLogger.debug("workflowException: " + workflowException) + + boolean successIndicator = execution.getVariable("SDNCA_SuccessIndicator") + msoLogger.debug("SDNCResponse: " + response) + + SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils(this) + sdncAdapterUtils.validateSDNCResponse(execution, response, workflowException, successIndicator) + + if(execution.getVariable(Prefix + 'sdncResponseSuccess') == true){ + msoLogger.debug("Received a Good Response from SDNC Adapter for " + method + " SDNC Call. Response is: \n" + response) + + }else{ + String sdncRespCode = execution.getVariable(Prefix + 'sdncRequestDataResponseCode') + msoLogger.debug(method + " AllottedResource received error response from SDNC. ResponseCode:" + sdncRespCode) + if (sdncRespCode.equals("404") && "deactivate".equals(method)) + { + execution.setVariable("ARNotFoundInSDNC", true) + if ("true".equals(execution.getVariable("failNotFound"))) + { + msg = "Allotted Resource Not found in SDNC" + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + else + { + execution.setVariable("wasDeleted", false) + } + } + else + { + throw new BpmnError("MSOWorkflowException") + } + } + } catch (BpmnError e) { + throw e; + } catch(Exception ex) { + msg = "Exception in validateSDNCResp. " + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.trace("end Exit ValidateSDNCResp Process") + } + + public void deleteAaiAR(DelegateExecution execution){ + msoLogger.trace("start deleteAaiAR") + + try{ + AllottedResourceUtils arUtils = new AllottedResourceUtils(this) + String ar = null //need to get resource-version again + String arLink = execution.getVariable("aaiARPath") + if (!isBlank(arLink)) + { + ar = arUtils.getARbyLink(execution, arLink, "") + } + arUtils.deleteAR(execution, arLink + '?resource-version=' + UriUtils.encode(execution.getVariable("aaiARResourceVersion"),"UTF-8")) + } catch (BpmnError e) { + throw e; + }catch(Exception ex){ + msoLogger.error(MessageEnum.BPMN_GENERAL_EXCEPTION_ARG, "Exception Occurred Processing preProcessSDNCGetRequest.", "BPMN", MsoLogger.getServiceName(), + MsoLogger.ErrorCode.UnknownError, "Exception is:\n" + ex); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during SDNC GET Method:\n" + ex.getMessage()) + } + msoLogger.trace("end deleteAaiAR") + } + +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/service/ServicePluginFactory.java b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/service/ServicePluginFactory.java new file mode 100644 index 0000000000..bd781756a5 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/java/org/onap/so/bpmn/infrastructure/workflow/service/ServicePluginFactory.java @@ -0,0 +1,422 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2018 Huawei Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.workflow.service; + +import java.io.IOException; +import java.net.SocketTimeoutException; +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Map.Entry; + +import org.apache.http.HttpResponse; +import org.apache.http.ParseException; +import org.apache.http.client.HttpClient; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.client.methods.HttpDelete; +import org.apache.http.client.methods.HttpGet; +import org.apache.http.client.methods.HttpPost; +import org.apache.http.client.methods.HttpPut; +import org.apache.http.client.methods.HttpRequestBase; +import org.apache.http.conn.ConnectTimeoutException; +import org.apache.http.entity.ContentType; +import org.apache.http.entity.StringEntity; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.util.EntityUtils; +import org.camunda.bpm.engine.runtime.Execution; +import org.onap.so.bpmn.core.UrnPropertiesReader; +import org.onap.so.bpmn.core.domain.ServiceDecomposition; +import org.onap.so.bpmn.core.json.JsonUtils; +import org.onap.so.logger.MessageEnum; +import org.onap.so.logger.MsoLogger; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; + +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.fasterxml.jackson.databind.SerializationFeature; + +public class ServicePluginFactory { + + // SOTN calculate route + public static final String OOF_Default_EndPoint = "http://192.168.1.223:8443/oof/sotncalc"; + + public static final String Third_SP_Default_EndPoint = "http://192.168.1.223:8443/sp/resourcemgr/querytps"; + + private static final int DEFAULT_TIME_OUT = 60000; + + static JsonUtils jsonUtil = new JsonUtils(); + + private static MsoLogger LOGGER = MsoLogger.getMsoLogger(MsoLogger.Catalog.RA, ServicePluginFactory.class); + + private static ServicePluginFactory instance; + + + public static synchronized ServicePluginFactory getInstance() { + if (null == instance) { + instance = new ServicePluginFactory(); + } + return instance; + } + + private String getThirdSPEndPoint(){ + return UrnPropertiesReader.getVariable("mso.service-plugin.third-sp-endpoint", Third_SP_Default_EndPoint); + } + + private String getOOFCalcEndPoint(){ + return UrnPropertiesReader.getVariable("mso.service-plugin.oof-calc-endpoint", OOF_Default_EndPoint); + } + + + public String preProcessService(ServiceDecomposition serviceDecomposition, String uuiRequest) { + + // now only for sotn + if (isSOTN(serviceDecomposition, uuiRequest)) { + // We Need to query the terminalpoint of the VPN by site location + // info + return preProcessSOTNService(serviceDecomposition, uuiRequest); + } + return uuiRequest; + } + + public String doServiceHoming(ServiceDecomposition serviceDecomposition, String uuiRequest) { + // now only for sotn + if (isSOTN(serviceDecomposition, uuiRequest)) { + return doSOTNServiceHoming(serviceDecomposition, uuiRequest); + } + return uuiRequest; + } + + private boolean isSOTN(ServiceDecomposition serviceDecomposition, String uuiRequest) { + // there should be a register platform , we check it very simple here. + return uuiRequest.contains("clientSignal") && uuiRequest.contains("vpnType"); + } + + private String preProcessSOTNService(ServiceDecomposition serviceDecomposition, String uuiRequest) { + Map<String, Object> uuiObject = getJsonObject(uuiRequest, Map.class); + Map<String, Object> serviceObject = (Map<String, Object>) uuiObject.get("service"); + Map<String, Object> serviceParametersObject = (Map<String, Object>) serviceObject.get("parameters"); + Map<String, Object> serviceRequestInputs = (Map<String, Object>) serviceParametersObject.get("requestInputs"); + List<Object> resources = (List<Object>) serviceParametersObject.get("resources"); + // This is a logic for demo , it could not be finalized to community. + String srcLocation = ""; + String dstLocation = ""; + String srcClientSignal = ""; + String dstClientSignal = ""; + // support R2 uuiReq and R1 uuiReq + // logic for R2 uuiRequest params in service level + for (Entry<String, Object> entry : serviceRequestInputs.entrySet()) { + if (entry.getKey().toLowerCase().contains("location")) { + if ("".equals(srcLocation)) { + srcLocation = (String) entry.getValue(); + } else if ("".equals(dstLocation)) { + dstLocation = (String) entry.getValue(); + } + } + if (entry.getKey().toLowerCase().contains("clientsignal")) { + if ("".equals(srcClientSignal)) { + srcClientSignal = (String) entry.getValue(); + } else if ("".equals(dstClientSignal)) { + dstClientSignal = (String) entry.getValue(); + } + } + } + + // logic for R1 uuiRequest, params in resource level + for (Object resource : resources) { + Map<String, Object> resourceObject = (Map<String, Object>) resource; + Map<String, Object> resourceParametersObject = (Map<String, Object>) resourceObject.get("parameters"); + Map<String, Object> resourceRequestInputs = (Map<String, Object>) resourceParametersObject + .get("requestInputs"); + for (Entry<String, Object> entry : resourceRequestInputs.entrySet()) { + if (entry.getKey().toLowerCase().contains("location")) { + if ("".equals(srcLocation)) { + srcLocation = (String) entry.getValue(); + } else if ("".equals(dstLocation)) { + dstLocation = (String) entry.getValue(); + } + } + if (entry.getKey().toLowerCase().contains("clientsignal")) { + if ("".equals(srcClientSignal)) { + srcClientSignal = (String) entry.getValue(); + } else if ("".equals(dstClientSignal)) { + dstClientSignal = (String) entry.getValue(); + } + } + } + } + + Map<String, Object> vpnRequestInputs = getVPNResourceRequestInputs(resources); + // here we put client signal to vpn resource inputs + vpnRequestInputs.put("src-client-signal", srcClientSignal); + vpnRequestInputs.put("dst-client-signal", dstClientSignal); + + // Now we need to query terminal points from SP resourcemgr system. + List<Object> locationTerminalPointList = queryTerminalPointsFromServiceProviderSystem(srcLocation, dstLocation); + Map<String, Object> tpInfoMap = (Map<String, Object>) locationTerminalPointList.get(0); + + serviceRequestInputs.put("inner-src-access-provider-id", tpInfoMap.get("access-provider-id")); + serviceRequestInputs.put("inner-src-access-client-id", tpInfoMap.get("access-client-id")); + serviceRequestInputs.put("inner-src-access-topology-id", tpInfoMap.get("access-topology-id")); + serviceRequestInputs.put("inner-src-access-node-id", tpInfoMap.get("access-node-id")); + serviceRequestInputs.put("inner-src-access-ltp-id", tpInfoMap.get("access-ltp-id")); + tpInfoMap = (Map<String, Object>) locationTerminalPointList.get(1); + + serviceRequestInputs.put("inner-dst-access-provider-id", tpInfoMap.get("access-provider-id")); + serviceRequestInputs.put("inner-dst-access-client-id", tpInfoMap.get("access-client-id")); + serviceRequestInputs.put("inner-dst-access-topology-id", tpInfoMap.get("access-topology-id")); + serviceRequestInputs.put("inner-dst-access-node-id", tpInfoMap.get("access-node-id")); + serviceRequestInputs.put("inner-dst-access-ltp-id", tpInfoMap.get("access-ltp-id")); + + String newRequest = getJsonString(uuiObject); + return newRequest; + } + + private List<Object> queryTerminalPointsFromServiceProviderSystem(String srcLocation, String dstLocation) { + Map<String, String> locationSrc = new HashMap<>(); + locationSrc.put("location", srcLocation); + Map<String, String> locationDst = new HashMap<>(); + locationDst.put("location", dstLocation); + List<Map<String, String>> locations = new ArrayList<>(); + locations.add(locationSrc); + locations.add(locationDst); + List<Object> returnList = new ArrayList<>(); + String reqContent = getJsonString(locations); + String url = getThirdSPEndPoint(); + String responseContent = sendRequest(url, "POST", reqContent); + if (null != responseContent) { + returnList = getJsonObject(responseContent, List.class); + } + return returnList; + } + + private Map<String, Object> getVPNResourceRequestInputs(List<Object> resources) { + for (Object resource : resources) { + Map<String, Object> resourceObject = (Map<String, Object>) resource; + Map<String, Object> resourceParametersObject = (Map<String, Object>) resourceObject.get("parameters"); + Map<String, Object> resourceRequestInputs = (Map<String, Object>) resourceParametersObject + .get("requestInputs"); + for (Entry<String, Object> entry : resourceRequestInputs.entrySet()) { + if (entry.getKey().toLowerCase().contains("vpntype")) { + return resourceRequestInputs; + } + } + } + return null; + } + + public static void main(String args[]){ + String str = "restconf/config/GENERIC-RESOURCE-API:services/service/eca7e542-12ba-48de-8544-fac59303b14e/service-data/networks/network/aec07806-1671-4af2-b722-53c8e320a633/network-data/"; + + int index1 = str.indexOf("/network/"); + int index2 = str.indexOf("/network-data"); + + String str1 = str.substring(index1 + "/network/".length(), index2); + System.out.println(str1); + + } + + private String doSOTNServiceHoming(ServiceDecomposition serviceDecomposition, String uuiRequest) { + // query the route for the service. + Map<String, Object> uuiObject = getJsonObject(uuiRequest, Map.class); + Map<String, Object> serviceObject = (Map<String, Object>) uuiObject.get("service"); + Map<String, Object> serviceParametersObject = (Map<String, Object>) serviceObject.get("parameters"); + Map<String, Object> serviceRequestInputs = (Map<String, Object>) serviceParametersObject.get("requestInputs"); + Map<String, Object> oofQueryObject = new HashMap<>(); + List<Object> resources = (List<Object>) serviceParametersObject.get("resources"); + oofQueryObject.put("src-access-provider-id", serviceRequestInputs.get("inner-src-access-provider-id")); + oofQueryObject.put("src-access-client-id", serviceRequestInputs.get("inner-src-access-client-id")); + oofQueryObject.put("src-access-topology-id", serviceRequestInputs.get("inner-src-access-topology-id")); + oofQueryObject.put("src-access-node-id", serviceRequestInputs.get("inner-src-access-node-id")); + oofQueryObject.put("src-access-ltp-id", serviceRequestInputs.get("inner-src-access-ltp-id")); + oofQueryObject.put("dst-access-provider-id", serviceRequestInputs.get("inner-dst-access-provider-id")); + oofQueryObject.put("dst-access-client-id", serviceRequestInputs.get("inner-dst-access-client-id")); + oofQueryObject.put("dst-access-topology-id", serviceRequestInputs.get("inner-dst-access-topology-id")); + oofQueryObject.put("dst-access-node-id", serviceRequestInputs.get("inner-dst-access-node-id")); + oofQueryObject.put("dst-access-ltp-id", serviceRequestInputs.get("inner-dst-access-ltp-id")); + String oofRequestReq = getJsonString(oofQueryObject); + String url = getOOFCalcEndPoint(); + String responseContent = sendRequest(url, "POST", oofRequestReq); + + List<Object> returnList = new ArrayList<>(); + if (null != responseContent) { + returnList = getJsonObject(responseContent, List.class); + } + // in demo we have only one VPN. no cross VPNs, so get first item. + Map<String, Object> returnRoute = getReturnRoute(returnList); + Map<String, Object> vpnRequestInputs = getVPNResourceRequestInputs(resources); + vpnRequestInputs.putAll(returnRoute); + String newRequest = getJsonString(uuiObject); + return newRequest; + } + + private Map<String, Object> getReturnRoute(List<Object> returnList){ + Map<String, Object> returnRoute = new HashMap<>(); + for(Object returnVpn :returnList){ + Map<String, Object> returnVpnInfo = (Map<String, Object>) returnVpn; + String accessTopoId = (String)returnVpnInfo.get("access-topology-id"); + if("100".equals(accessTopoId)){ + returnRoute.putAll(returnVpnInfo); + } + else if("101".equals(accessTopoId)){ + for(String key : returnVpnInfo.keySet()){ + returnRoute.put("domain1-" + key, returnVpnInfo.get(key)); + } + } + else if("102".equals(accessTopoId)){ + for(String key : returnVpnInfo.keySet()){ + returnRoute.put("domain2-" + key, returnVpnInfo.get(key)); + } + } + else{ + for(String key : returnVpnInfo.keySet()){ + returnRoute.put("domain" + accessTopoId +"-" + key, returnVpnInfo.get(key)); + } + } + } + return returnRoute; + } + + private Map<String, Object> getResourceParams(Execution execution, String resourceCustomizationUuid, + String serviceParameters) { + List<String> resourceList = jsonUtil.StringArrayToList(execution, + (String) JsonUtils.getJsonValue(serviceParameters, "resources")); + // Get the right location str for resource. default is an empty array. + String resourceInputsFromUui = ""; + for (String resource : resourceList) { + String resCusUuid = (String) JsonUtils.getJsonValue(resource, "resourceCustomizationUuid"); + if (resourceCustomizationUuid.equals(resCusUuid)) { + String resourceParameters = JsonUtils.getJsonValue(resource, "parameters"); + resourceInputsFromUui = JsonUtils.getJsonValue(resourceParameters, "requestInputs"); + } + } + Map<String, Object> resourceInputsFromUuiMap = getJsonObject(resourceInputsFromUui, Map.class); + return resourceInputsFromUuiMap; + } + + public static <T> T getJsonObject(String jsonstr, Class<T> type) { + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, true); + try { + return mapper.readValue(jsonstr, type); + } catch (IOException e) { + LOGGER.error(MessageEnum.RA_NS_EXC, "", "", MsoLogger.ErrorCode.BusinessProcesssError, + "fail to unMarshal json", e); + } + return null; + } + + public static String getJsonString(Object srcObj) { + ObjectMapper mapper = new ObjectMapper(); + mapper.configure(SerializationFeature.WRAP_ROOT_VALUE, false); + String jsonStr = null; + try { + jsonStr = mapper.writeValueAsString(srcObj); + } catch (JsonProcessingException e) { + LOGGER.debug("SdcToscaParserException", e); + e.printStackTrace(); + } + return jsonStr; + } + + private static String sendRequest(String url, String methodType, String content) { + + String msbUrl = url; + HttpRequestBase method = null; + HttpResponse httpResponse = null; + + try { + int timeout = DEFAULT_TIME_OUT; + + RequestConfig requestConfig = RequestConfig.custom().setSocketTimeout(timeout).setConnectTimeout(timeout) + .setConnectionRequestTimeout(timeout).build(); + + HttpClient client = HttpClientBuilder.create().build(); + + if ("POST".equals(methodType.toUpperCase())) { + HttpPost httpPost = new HttpPost(msbUrl); + httpPost.setConfig(requestConfig); + httpPost.setEntity(new StringEntity(content, ContentType.APPLICATION_JSON)); + method = httpPost; + } else if ("PUT".equals(methodType.toUpperCase())) { + HttpPut httpPut = new HttpPut(msbUrl); + httpPut.setConfig(requestConfig); + httpPut.setEntity(new StringEntity(content, ContentType.APPLICATION_JSON)); + method = httpPut; + } else if ("GET".equals(methodType.toUpperCase())) { + HttpGet httpGet = new HttpGet(msbUrl); + httpGet.setConfig(requestConfig); + method = httpGet; + } else if ("DELETE".equals(methodType.toUpperCase())) { + HttpDelete httpDelete = new HttpDelete(msbUrl); + httpDelete.setConfig(requestConfig); + method = httpDelete; + } + + // now have no auth + // String userCredentials = + // SDNCAdapterProperties.getEncryptedProperty(Constants.SDNC_AUTH_PROP, + // Constants.DEFAULT_SDNC_AUTH, Constants.ENCRYPTION_KEY); + // String authorization = "Basic " + + // DatatypeConverter.printBase64Binary(userCredentials.getBytes()); + // method.setHeader("Authorization", authorization); + + httpResponse = client.execute(method); + String responseContent = null; + if (null != httpResponse && httpResponse.getEntity() != null) { + try { + responseContent = EntityUtils.toString(httpResponse.getEntity(), "UTF-8"); + } catch (ParseException e) { + e.printStackTrace(); + } catch (IOException e) { + e.printStackTrace(); + } + } + if (null != method) { + method.reset(); + } + method = null; + return responseContent; + + } catch (SocketTimeoutException | ConnectTimeoutException e) { + return null; + + } catch (Exception e) { + return null; + + } finally { + if (httpResponse != null) { + try { + EntityUtils.consume(httpResponse.getEntity()); + } catch (Exception e) { + } + } + if (method != null) { + try { + method.reset(); + } catch (Exception e) { + + } + } + } + } +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateCustomE2EServiceInstanceTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateCustomE2EServiceInstanceTest.groovy new file mode 100644 index 0000000000..ae40e9d7c6 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateCustomE2EServiceInstanceTest.groovy @@ -0,0 +1,84 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts + +import com.github.tomakehurst.wiremock.junit.WireMockRule +import org.camunda.bpm.engine.ProcessEngineServices +import org.camunda.bpm.engine.RepositoryService +import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity +import org.camunda.bpm.engine.repository.ProcessDefinition +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.ArgumentCaptor +import org.mockito.Captor +import org.mockito.Mockito +import org.mockito.MockitoAnnotations +import org.mockito.runners.MockitoJUnitRunner + +import static org.junit.Assert.assertNotNull +import static org.mockito.Mockito.* + +@RunWith(MockitoJUnitRunner.class) +class CreateCustomE2EServiceInstanceTest { + + @Rule + public WireMockRule wireMockRule = new WireMockRule(28090); + + @Before + public void init() throws IOException { + MockitoAnnotations.initMocks(this); + } + + @Captor + static ArgumentCaptor<ExecutionEntity> captor = ArgumentCaptor.forClass(ExecutionEntity.class) + + @Test + public void testPrepareInitServiceOperationStatus (){ + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("serviceInstanceId")).thenReturn("12345") + when(mockExecution.getVariable("mso.adapters.openecomp.db.endpoint")).thenReturn("http://localhost:28090/dbadapters/RequestsDbAdapter") + CreateCustomE2EServiceInstance obj = new CreateCustomE2EServiceInstance(); + obj.prepareInitServiceOperationStatus(mockExecution) + Mockito.verify(mockExecution, times(5)).setVariable(captor.capture(), captor.capture()) + def updateVolumeGroupRequest = captor.getValue() + assertNotNull(updateVolumeGroupRequest); + } + + private ExecutionEntity setupMock() { + ProcessDefinition mockProcessDefinition = mock(ProcessDefinition.class) + when(mockProcessDefinition.getKey()).thenReturn("CreateCustomE2EServiceInstance") + RepositoryService mockRepositoryService = mock(RepositoryService.class) + when(mockRepositoryService.getProcessDefinition()).thenReturn(mockProcessDefinition) + when(mockRepositoryService.getProcessDefinition().getKey()).thenReturn("CreateCustomE2EServiceInstance") + when(mockRepositoryService.getProcessDefinition().getId()).thenReturn("100") + ProcessEngineServices mockProcessEngineServices = mock(ProcessEngineServices.class) + when(mockProcessEngineServices.getRepositoryService()).thenReturn(mockRepositoryService) + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + when(mockExecution.getId()).thenReturn("100") + when(mockExecution.getProcessDefinitionId()).thenReturn("CreateCustomE2EServiceInstance") + when(mockExecution.getProcessInstanceId()).thenReturn("CreateCustomE2EServiceInstance") + when(mockExecution.getProcessEngineServices()).thenReturn(mockProcessEngineServices) + when(mockExecution.getProcessEngineServices().getRepositoryService().getProcessDefinition(mockExecution.getProcessDefinitionId())).thenReturn(mockProcessDefinition) + return mockExecution + } +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateGenericAlaCarteServiceInstanceTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateGenericAlaCarteServiceInstanceTest.groovy new file mode 100644 index 0000000000..da0990910a --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateGenericAlaCarteServiceInstanceTest.groovy @@ -0,0 +1,235 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts + +import org.camunda.bpm.engine.ProcessEngineServices +import org.camunda.bpm.engine.RepositoryService +import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity +import org.camunda.bpm.engine.repository.ProcessDefinition +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.mockito.MockitoAnnotations +import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.bpmn.common.scripts.VidUtils + +import static org.junit.Assert.*; +import static org.mockito.Mockito.* + +import com.github.tomakehurst.wiremock.junit.WireMockRule + +class CreateGenericAlaCarteServiceInstanceTest { + + @Rule + public WireMockRule wireMockRule = new WireMockRule(8090); + + String Prefix="CRESI_" + def utils = new MsoUtils() + JsonUtils jsonUtil = new JsonUtils() + VidUtils vidUtils = new VidUtils() + + String createDBRequestError = +"""<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"> + <soapenv:Header/> + <soapenv:Body> + <ns:updateInfraRequest xmlns:ns="http://org.onap.so/requestsdb"> + <requestId>88f65519-9a38-4c4b-8445-9eb4a5a5af56</requestId> + <lastModifiedBy>BPMN</lastModifiedBy> + <statusMessage>Received error from SDN-C: No availability zone available</statusMessage> + <responseBody></responseBody> + <requestStatus>FAILED</requestStatus> + <vnfOutputs><network-id></network-id><network-name></network-names></vnfOutputs> + </ns:updateInfraRequest> + </soapenv:Body> + </soapenv:Envelope>""" + + String falloutHandlerRequest = + """<aetgt:FalloutHandlerRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:ns="http://org.onap/so/request/types/v1" + xmlns:wfsch="http://org.onap/so/workflow/schema/v1"> + <request-info xmlns="http://org.onap/so/infra/vnf-request/v1"> + <request-id>b69c9054-da09-4a2c-adf5-51042b62bfac</request-id> + <action>CREATE</action> + <source>VID</source> + </request-info> + <aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1"> + <aetgt:ErrorMessage>Received error from SDN-C: No availability zone available.</aetgt:ErrorMessage> + <aetgt:ErrorCode>5300</aetgt:ErrorCode> + </aetgt:WorkflowException> + </aetgt:FalloutHandlerRequest>""" + + String completeMsoProcessRequest = + """<aetgt:MsoCompletionRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:ns="http://org.onap/so/request/types/v1" + xmlns="http://org.onap/so/infra/vnf-request/v1"> + <request-info> + <request-id>88f65519-9a38-4c4b-8445-9eb4a5a5af56</request-id> + <action>CREATE</action> + <source>VID</source> + </request-info> + <aetgt:status-message>Network has been created successfully.</aetgt:status-message> + <aetgt:mso-bpel-name>BPMN Network action: CREATE</aetgt:mso-bpel-name> +</aetgt:MsoCompletionRequest>""" + + String jsonIncomingRequest = + """{ + "requestDetails": { + "modelInfo": { + "modelType": "service", + "modelInvariantId": "1de901ed-17af-4b03-bc1f-41659cfa27cb", + "modelVersionId": "ace39141-09ec-4068-b06d-ac6b23bdc6e0", + "modelName": "demoVLB", + "modelVersion": "1.0" + }, + "cloudConfiguration" : { + "lcpCloudRegionId": "RegionOne", + "tenantId": "onap" + }, + "subscriberInfo": { + "globalSubscriberId": "Demonstration", + "subscriberName": "Demonstration" + }, + "requestInfo": { + "instanceName": "sample-instance-2", + "productFamilyId": "a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb", + "source": "VID", + "requestorId":"1234", + "suppressRollback": "false" + }, + "requestParameters": { + "subscriptionServiceType": "vLB" + } + } + }""" + + @Before + public void init() + { + MockitoAnnotations.initMocks(this) + + } + + public void initializeVariables(DelegateExecution mockExecution) { + + //verify(mockExecution).setVariable(Prefix + "Success", false) + + //verify(mockExecution).setVariable(Prefix + "CompleteMsoProcessRequest", "") + //verify(mockExecution).setVariable(Prefix + "FalloutHandlerRequest", "") + //verify(mockExecution).setVariable(Prefix + "isSilentSuccess", false) + + } + + @Test + //@Ignore + public void preProcessRequest() { + + println "************ preProcessRequest() ************* " + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + // Initialize prerequisite variables + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("bpmnRequest")).thenReturn(jsonIncomingRequest) + try{ + + // preProcessRequest(DelegateExecution execution) + CreateGenericALaCarteServiceInstance createGenericALaCarteServiceInstance = new CreateGenericALaCarteServiceInstance() + createGenericALaCarteServiceInstance.preProcessRequest(mockExecution) + + //verify(mockExecution).getVariable("isDebugLogEnabled") + //verify(mockExecution).setVariable("prefix", Prefix) + + initializeVariables(mockExecution) + //verify(mockExecution).setVariable(Prefix + "Success", false) + }catch(Exception e){ + //ignore + } + } + + @Test + //@Ignore + public void sendSyncResponse() { + + println "************ sendSyncResponse ************* " + + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("isAsyncProcess")).thenReturn(true) + when(mockExecution.getVariable("mso-request-id")).thenReturn("e8ebf6a0-f8ea-4dc0-8b99-fe98a87722d6") + when(mockExecution.getVariable("serviceInstanceId")).thenReturn("f70e927b-6087-4974-9ef8-c5e4d5847ca4") + try{ + // preProcessRequest(DelegateExecution execution) + CreateGenericALaCarteServiceInstance createGenericALaCarteServiceInstance = new CreateGenericALaCarteServiceInstance() + createGenericALaCarteServiceInstance.sendSyncResponse(mockExecution) + + //verify(mockExecution).setVariable("prefix", Prefix) + //verify(mockExecution).setVariable("createServiceRestRequest", "202") + }catch(Exception e){ + //ignore + } + } + + @Test + //@Ignore + public void sendSyncError() { + + println "************ sendSyncError ************* " + + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("isAsyncProcess")).thenReturn(true) + when(mockExecution.getVariable("mso-request-id")).thenReturn("e8ebf6a0-f8ea-4dc0-8b99-fe98a87722d6") + when(mockExecution.getVariable("serviceInstanceId")).thenReturn("f70e927b-6087-4974-9ef8-c5e4d5847ca4") + try{ + CreateGenericALaCarteServiceInstance createGenericALaCarteServiceInstance = new CreateGenericALaCarteServiceInstance() + createGenericALaCarteServiceInstance.sendSyncError(mockExecution) + + //verify(mockExecution).setVariable("prefix", Prefix) + //verify(mockExecution).setVariable("createServiceRestRequest", "500") + }catch(Exception e){ + //ignore + } + } + + private ExecutionEntity setupMock() { + + ProcessDefinition mockProcessDefinition = mock(ProcessDefinition.class) + when(mockProcessDefinition.getKey()).thenReturn("CreateGenericALaCarteSeviceInstance") + RepositoryService mockRepositoryService = mock(RepositoryService.class) + when(mockRepositoryService.getProcessDefinition()).thenReturn(mockProcessDefinition) + when(mockRepositoryService.getProcessDefinition().getKey()).thenReturn("CreateGenericALaCarteSeviceInstance") + when(mockRepositoryService.getProcessDefinition().getId()).thenReturn("100") + ProcessEngineServices mockProcessEngineServices = mock(ProcessEngineServices.class) + when(mockProcessEngineServices.getRepositoryService()).thenReturn(mockRepositoryService) + + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + // Initialize prerequisite variables + + when(mockExecution.getId()).thenReturn("100") + when(mockExecution.getProcessDefinitionId()).thenReturn("CreateGenericALaCarteSeviceInstance") + when(mockExecution.getProcessInstanceId()).thenReturn("CreateGenericALaCarteSeviceInstance") + when(mockExecution.getProcessEngineServices()).thenReturn(mockProcessEngineServices) + when(mockExecution.getProcessEngineServices().getRepositoryService().getProcessDefinition(mockExecution.getProcessDefinitionId())).thenReturn(mockProcessDefinition) + + return mockExecution + } +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateNetworkInstanceTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateNetworkInstanceTest.groovy new file mode 100644 index 0000000000..4d5f506599 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateNetworkInstanceTest.groovy @@ -0,0 +1,379 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts + +import org.camunda.bpm.engine.ProcessEngineServices +import org.camunda.bpm.engine.RepositoryService +import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity +import org.camunda.bpm.engine.repository.ProcessDefinition +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.mockito.MockitoAnnotations +import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.so.bpmn.core.WorkflowException + +import static org.junit.Assert.*; +import static org.mockito.Mockito.* + +import com.github.tomakehurst.wiremock.junit.WireMockRule + +class CreateNetworkInstanceTest { + + @Rule + public WireMockRule wireMockRule = new WireMockRule(8090); + + String Prefix="CRENI_" + def utils = new MsoUtils() + + String createDBRequestError = +"""<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"> + <soapenv:Header/> + <soapenv:Body> + <ns:updateInfraRequest xmlns:ns="http://org.onap.so/requestsdb"> + <requestId>88f65519-9a38-4c4b-8445-9eb4a5a5af56</requestId> + <lastModifiedBy>BPMN</lastModifiedBy> + <statusMessage>Received error from SDN-C: No availability zone available</statusMessage> + <responseBody></responseBody> + <requestStatus>FAILED</requestStatus> + <vnfOutputs><network-id></network-id><network-name></network-names></vnfOutputs> + </ns:updateInfraRequest> + </soapenv:Body> + </soapenv:Envelope>""" + + String falloutHandlerRequest = + """<aetgt:FalloutHandlerRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:ns="http://org.onap/so/request/types/v1" + xmlns:wfsch="http://org.onap/so/workflow/schema/v1"> + <request-info xmlns="http://org.onap/so/infra/vnf-request/v1"> + <request-id>b69c9054-da09-4a2c-adf5-51042b62bfac</request-id> + <action>CREATE</action> + <source>VID</source> + </request-info> + <aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1"> + <aetgt:ErrorMessage>Received error from SDN-C: No availability zone available.</aetgt:ErrorMessage> + <aetgt:ErrorCode>5300</aetgt:ErrorCode> + </aetgt:WorkflowException> + </aetgt:FalloutHandlerRequest>""" + + String completeMsoProcessRequest = + """<aetgt:MsoCompletionRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:ns="http://org.onap/so/request/types/v1" + xmlns="http://org.onap/so/infra/vnf-request/v1"> + <request-info> + <request-id>88f65519-9a38-4c4b-8445-9eb4a5a5af56</request-id> + <action>CREATE</action> + <source>VID</source> + </request-info> + <aetgt:status-message>Network has been created successfully.</aetgt:status-message> + <aetgt:mso-bpel-name>BPMN Network action: CREATE</aetgt:mso-bpel-name> +</aetgt:MsoCompletionRequest>""" + + +String jsonIncomingRequest = +"""{ "requestDetails": { + "modelInfo": { + "modelType": "networkTyp", + "modelId": "modelId", + "modelNameVersionId": "modelNameVersionId", + "modelName": "CONTRAIL_EXTERNAL", + "modelVersion": "1" + }, + "cloudConfiguration": { + "lcpCloudRegionId": "RDM2WAGPLCP", + "tenantId": "7dd5365547234ee8937416c65507d266" + }, + "requestInfo": { + "instanceName": "MNS-25180-L-01-dmz_direct_net_1", + "source": "VID", + "callbackUrl": "", + "suppressRollback": true, + "productFamilyId": "a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb" + }, + "relatedInstanceList": [ + { + "relatedInstance": { + "instanceId": "f70e927b-6087-4974-9ef8-c5e4d5847ca4", + "modelInfo": { + "modelType": "serviceT", + "modelId": "modelI", + "modelNameVersionId": "modelNameVersionI", + "modelName": "modleNam", + "modelVersion": "1" + } + } + } + ], + "requestParameters": { + "userParams": [ + { + "name": "someUserParam1", + "value": "someValue1" + } + ] + } + }}""" + + @Before + public void init() + { + MockitoAnnotations.initMocks(this) + } + + public void initializeVariables(DelegateExecution mockExecution) { + + verify(mockExecution).setVariable(Prefix + "Success", false) + + verify(mockExecution).setVariable(Prefix + "CompleteMsoProcessRequest", "") + verify(mockExecution).setVariable(Prefix + "FalloutHandlerRequest", "") + verify(mockExecution).setVariable(Prefix + "isSilentSuccess", false) + + } + + @Test + //@Ignore + public void preProcessRequest() { + + println "************ preProcessRequest() ************* " + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + // Initialize prerequisite variables + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("bpmnRequest")).thenReturn(jsonIncomingRequest) + + + // preProcessRequest(DelegateExecution execution) + CreateNetworkInstance CreateNetworkInstance = new CreateNetworkInstance() + CreateNetworkInstance.preProcessRequest(mockExecution) + + //verify(mockExecution).getVariable("isDebugLogEnabled") + verify(mockExecution).setVariable("prefix", Prefix) + + initializeVariables(mockExecution) + //verify(mockExecution).setVariable(Prefix + "Success", false) + + } + + + @Test + //@Ignore + public void getNetworkModelInfo() { + + println "************ getNetworkModelInfo() ************* " + + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + // Initialize prerequisite variables + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + + // preProcessRequest(DelegateExecution execution) + CreateNetworkInstance CreateNetworkInstance = new CreateNetworkInstance() + CreateNetworkInstance.getNetworkModelInfo(mockExecution) + + //verify(mockExecution).getVariable("isDebugLogEnabled") + verify(mockExecution).setVariable("prefix", Prefix) + + } + + @Test + //@Ignore + public void sendSyncResponse() { + + println "************ sendSyncResponse ************* " + + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("isAsyncProcess")).thenReturn(true) + when(mockExecution.getVariable("mso-request-id")).thenReturn("e8ebf6a0-f8ea-4dc0-8b99-fe98a87722d6") + when(mockExecution.getVariable("serviceInstanceId")).thenReturn("f70e927b-6087-4974-9ef8-c5e4d5847ca4") + + // preProcessRequest(DelegateExecution execution) + CreateNetworkInstance CreateNetworkInstance = new CreateNetworkInstance() + CreateNetworkInstance.sendSyncResponse(mockExecution) + + verify(mockExecution).setVariable("prefix", Prefix) + verify(mockExecution).setVariable("CreateNetworkInstanceResponseCode", "202") + + } + + @Test + //@Ignore + public void sendSyncError() { + + println "************ sendSyncError ************* " + + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("isAsyncProcess")).thenReturn(true) + when(mockExecution.getVariable("mso-request-id")).thenReturn("e8ebf6a0-f8ea-4dc0-8b99-fe98a87722d6") + when(mockExecution.getVariable("serviceInstanceId")).thenReturn("f70e927b-6087-4974-9ef8-c5e4d5847ca4") + + CreateNetworkInstance CreateNetworkInstance = new CreateNetworkInstance() + CreateNetworkInstance.sendSyncError(mockExecution) + + verify(mockExecution).setVariable("prefix", Prefix) + verify(mockExecution).setVariable("CreateNetworkInstanceResponseCode", "500") + + } + + @Test + //@Ignore + public void prepareDBRequestError() { + + println "************ prepareDBRequestError ************* " + + WorkflowException sndcWorkflowException = new WorkflowException("CreateNetworkInstance", 500, "Received error from SDN-C: No availability zone available") + + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + // Initialize prerequisite variables + when(mockExecution.getVariable("WorkflowException")).thenReturn(sndcWorkflowException) + //when(mockExecution.getVariable("msoRequestId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + when(mockExecution.getVariable(Prefix + "requestId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + when(mockExecution.getVariable("networkId")).thenReturn("") + when(mockExecution.getVariable("networkName")).thenReturn("") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("mso.adapters.db.auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") + when(mockExecution.getVariable("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") + + // preProcessRequest(DelegateExecution execution) + CreateNetworkInstance CreateNetworkInstance = new CreateNetworkInstance() + CreateNetworkInstance.prepareDBRequestError(mockExecution) + + verify(mockExecution).setVariable("prefix", Prefix) + verify(mockExecution).setVariable(Prefix + "createDBRequest", createDBRequestError) + + } + + + @Test + //@Ignore + public void prepareCompletion() { + + println "************ postProcessResponse ************* " + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + // Initialize prerequisite variables + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("mso-request-id")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + when(mockExecution.getVariable(Prefix + "dbReturnCode")).thenReturn("200") + + // postProcessResponse(DelegateExecution execution) + CreateNetworkInstance CreateNetworkInstance = new CreateNetworkInstance() + CreateNetworkInstance.prepareCompletion(mockExecution) + + // check the sequence of variable invocation + //MockitoDebuggerImpl preDebugger = new MockitoDebuggerImpl() + //preDebugger.printInvocations(mockExecution) + + verify(mockExecution).setVariable("prefix", Prefix) + verify(mockExecution).setVariable(Prefix + "Success", true) + verify(mockExecution).setVariable(Prefix + "CompleteMsoProcessRequest", completeMsoProcessRequest) + + } + + @Test + //@Ignore + public void buildErrorResponse() { + + println "************ buildErrorResponse ************* " + + + WorkflowException sndcWorkflowException = new WorkflowException("CreateNetworkInstance", 5300, "Received error from SDN-C: No availability zone available.") + + ExecutionEntity mockExecution = setupMock() + // Initialize prerequisite variables + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("mso-request-id")).thenReturn("b69c9054-da09-4a2c-adf5-51042b62bfac") + //when(mockExecution.getVariable("WorkflowException")).thenReturn(sndcWorkflowException) + when(mockExecution.getVariable("WorkflowException")).thenReturn(sndcWorkflowException) + + // buildErrorResponse(DelegateExecution execution) + CreateNetworkInstance CreateNetworkInstance = new CreateNetworkInstance() + CreateNetworkInstance.buildErrorResponse(mockExecution) + + verify(mockExecution, atLeast(1)).setVariable("prefix", "CRENI_") + verify(mockExecution).setVariable(Prefix + "FalloutHandlerRequest", falloutHandlerRequest) + + //MockitoDebuggerImpl debugger = new MockitoDebuggerImpl() + //debugger.printInvocations(mockExecution) + + } + + @Test + //@Ignore + public void postProcessResponse() { + + println "************ postProcessResponse() ************* " + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("CMSO_ResponseCode")).thenReturn("200") + + // postProcessResponse(DelegateExecution execution) + CreateNetworkInstance CreateNetworkInstance = new CreateNetworkInstance() + CreateNetworkInstance.postProcessResponse(mockExecution) + + //verify(mockExecution).getVariable("isDebugLogEnabled") + //verify(mockExecution).setVariable("prefix", Prefix) + + verify(mockExecution).setVariable(Prefix + "Success", true) + + } + + @Test + //@Ignore + public void processRollbackData() { + + println "************ callDBCatalog() ************* " + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + // Initialize prerequisite variables + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + + // preProcessRequest(DelegateExecution execution) + CreateNetworkInstance CreateNetworkInstance = new CreateNetworkInstance() + CreateNetworkInstance.processRollbackData(mockExecution) + +// verify(mockExecution).getVariable("isDebugLogEnabled") + verify(mockExecution).setVariable("prefix", Prefix) + + } + + private ExecutionEntity setupMock() { + + ProcessDefinition mockProcessDefinition = mock(ProcessDefinition.class) + when(mockProcessDefinition.getKey()).thenReturn("CreateNetworkInstance") + RepositoryService mockRepositoryService = mock(RepositoryService.class) + when(mockRepositoryService.getProcessDefinition()).thenReturn(mockProcessDefinition) + when(mockRepositoryService.getProcessDefinition().getKey()).thenReturn("CreateNetworkInstance") + when(mockRepositoryService.getProcessDefinition().getId()).thenReturn("100") + ProcessEngineServices mockProcessEngineServices = mock(ProcessEngineServices.class) + when(mockProcessEngineServices.getRepositoryService()).thenReturn(mockRepositoryService) + + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + // Initialize prerequisite variables + + when(mockExecution.getId()).thenReturn("100") + when(mockExecution.getProcessDefinitionId()).thenReturn("CreateNetworkInstance") + when(mockExecution.getProcessInstanceId()).thenReturn("CreateNetworkInstance") + when(mockExecution.getProcessEngineServices()).thenReturn(mockProcessEngineServices) + when(mockExecution.getProcessEngineServices().getRepositoryService().getProcessDefinition(mockExecution.getProcessDefinitionId())).thenReturn(mockProcessDefinition) + + return mockExecution + } + +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateVfModuleInfraTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateVfModuleInfraTest.groovy new file mode 100644 index 0000000000..77220da94f --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateVfModuleInfraTest.groovy @@ -0,0 +1,96 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts + +import com.github.tomakehurst.wiremock.junit.WireMockRule +import org.camunda.bpm.engine.ProcessEngineServices +import org.camunda.bpm.engine.RepositoryService +import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity +import org.camunda.bpm.engine.repository.ProcessDefinition +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.ArgumentCaptor +import org.mockito.Captor +import org.mockito.Mockito +import org.mockito.MockitoAnnotations +import org.mockito.runners.MockitoJUnitRunner + +import static org.mockito.Mockito.mock +import static org.mockito.Mockito.when + +@RunWith(MockitoJUnitRunner.class) +class CreateVfModuleInfraTest { + + def prefix = "CVFMI_" + def requestInfo = "<requestInfo><request-id>12345</request-id></requestInfo>" + + @Rule + public WireMockRule wireMockRule = new WireMockRule(28090) + + @Captor + static ArgumentCaptor<ExecutionEntity> captor = ArgumentCaptor.forClass(ExecutionEntity.class) + + @Before + void init() throws IOException { + MockitoAnnotations.initMocks(this); + } + + @Test + void testPrepareUpdateInfraRequest() { + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("prefix")).thenReturn(prefix) + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable(prefix + "vnfId")).thenReturn("12345") + when(mockExecution.getVariable(prefix + "requestInfo")).thenReturn(requestInfo) + when(mockExecution.getVariable(prefix + "vfModuleId")).thenReturn("12345") + when(mockExecution.getVariable(prefix + "vfModuleName")).thenReturn("12345") + when(mockExecution.getVariable("mso.adapters.openecomp.db.endpoint")).thenReturn("http://mso.mso.testlab.openecomp.org:8080/dbadapters/RequestsDbAdapter") + + CreateVfModuleInfra obj = new CreateVfModuleInfra() + obj.prepareUpdateInfraRequest(mockExecution) + Mockito.verify(mockExecution).setVariable(prefix + "dbAdapterEndpoint", "http://mso.mso.testlab.openecomp.org:8080/dbadapters/RequestsDbAdapter") + } + + + + private static ExecutionEntity setupMock() { + ProcessDefinition mockProcessDefinition = mock(ProcessDefinition.class) + when(mockProcessDefinition.getKey()).thenReturn("CreateVfModuleInfra") + RepositoryService mockRepositoryService = mock(RepositoryService.class) + when(mockRepositoryService.getProcessDefinition()).thenReturn(mockProcessDefinition) + when(mockRepositoryService.getProcessDefinition().getKey()).thenReturn("CreateVfModuleInfra") + when(mockRepositoryService.getProcessDefinition().getId()).thenReturn("100") + ProcessEngineServices mockProcessEngineServices = mock(ProcessEngineServices.class) + when(mockProcessEngineServices.getRepositoryService()).thenReturn(mockRepositoryService) + + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + // Initialize prerequisite variables + when(mockExecution.getId()).thenReturn("100") + when(mockExecution.getProcessDefinitionId()).thenReturn("CreateVfModuleInfra") + when(mockExecution.getProcessInstanceId()).thenReturn("CreateVfModuleInfra") + when(mockExecution.getProcessEngineServices()).thenReturn(mockProcessEngineServices) + when(mockExecution.getProcessEngineServices().getRepositoryService().getProcessDefinition(mockExecution.getProcessDefinitionId())).thenReturn(mockProcessDefinition) + + return mockExecution + } +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateVfModuleVolumeInfraV1Test.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateVfModuleVolumeInfraV1Test.groovy new file mode 100644 index 0000000000..2b437d875e --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateVfModuleVolumeInfraV1Test.groovy @@ -0,0 +1,208 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts + +import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity +import org.junit.Before +import org.junit.Ignore +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.ArgumentCaptor +import org.mockito.MockitoAnnotations +import org.mockito.runners.MockitoJUnitRunner +import org.onap.so.bpmn.common.scripts.MsoGroovyTest + +import static org.junit.Assert.assertEquals +import static org.mockito.Mockito.* + +@RunWith(MockitoJUnitRunner.class) +class CreateVfModuleVolumeInfraV1Test extends MsoGroovyTest { + + def jsonRequest = """ +{ + "requestDetails": { + "modelInfo": { + "modelType": "volumeGroup", + "modelId": "ff5256d2-5a33-55df-13ab-12abad84e7ff", + "modelNameVersionId": "fe6478e5-ea33-3346-ac12-ab121484a3fe", + "modelName": "vSAMP12::base::module-0", + "modelVersion": "1" + }, + "cloudConfiguration": { + "lcpCloudRegionId": "mdt1", + "tenantId": "88a6ca3ee0394ade9403f075db23167e" + }, + "requestInfo": { + "instanceName": "MSOTESTVOL101a-vSAMP12_base_vol_module-0", + "source": "VID", + "suppressRollback": false + }, + "relatedInstanceList": [ + { + "relatedInstance": { + "instanceId": "{service-instance-id}", + "modelInfo": { + "modelType": "service", + "modelInvariantUuid": "ff5256d1-5a33-55df-13ab-12abad84e7ff", + "modelUuid": "fe6478e4-ea33-3346-ac12-ab121484a3fe", + "modelName": "Test", + "modelVersion": "2.0" + } + } + }, { + "relatedInstance": { + "instanceId": "{vnf-instance-id}", + "modelInfo": { + "modelType": "vnf", + "modelId": "ff5256d1-5a33-55df-13ab-12abad84e7ff", + "modelNameVersionId": "fe6478e4-ea33-3346-ac12-ab121484a3fe", + "modelName": "vSAMP12", + "modelVersion": "1", + "modelInstanceName": "vSAMP12" + } + } + } + ], + "requestParameters": { + "serviceId": "a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb", + "userParams": [ + {"name": "vnfName", "value": "STMTN5MMSC20" }, + {"name": "vnfName2", "value": "US1117MTSNJVBR0246" }, + {"name": "vnfNmInformation", "value": "" }, + {"name": "vnfType", "value": "pcrf-capacity" }, + {"name": "vnfId", "value": "skask" }, + {"name": "vnfStackId", "value": "slowburn" }, + {"name": "vnfStatus", "value": "created" }, + {"name": "aicCloudRegion", "value": "MDTWNJ21" }, + {"name": "availabilityZone", "value": "slcp3-esx-az01" }, + {"name": "oamNetworkName", "value": "VLAN-OAM-1323" }, + {"name": "vmName", "value": "slcp34246vbc246ceb" }, + {"name": "ipagNetworkId", "value": "970cd2b9-7f09-4a12-af47-182ea38ba1f0" }, + {"name": "vpeNetworkId", "value": "545cc2c3-1930-4100-b534-5d82d0e12bb6" } + ] + } + } +} +""" + + def volumeRequestXml = """<volume-request xmlns="http://www.w3.org/2001/XMLSchema"> + <request-info> + <action>CREATE_VF_MODULE_VOL</action> + <source>VID</source> + <service-instance-id/> + </request-info> + <volume-inputs> + <volume-group-id/> + <volume-group-name>MSOTESTVOL101a-vSAMP12_base_vol_module-0</volume-group-name> + <vnf-type>Test/vSAMP12</vnf-type> + <vf-module-model-name>vSAMP12::base::module-0</vf-module-model-name> + <asdc-service-model-version>2.0</asdc-service-model-version> + <aic-cloud-region>mdt1</aic-cloud-region> + <tenant-id>88a6ca3ee0394ade9403f075db23167e</tenant-id> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <backout-on-failure>true</backout-on-failure> + <model-customization-id/> + </volume-inputs> + <volume-params> + <param name="vnf_name">STMTN5MMSC20</param> + <param name="vnf_name2">US1117MTSNJVBR0246</param> + <param name="vnf_nm_information"/> + <param name="vnf_type">pcrf-capacity</param> + <param name="vnf_id">skask</param> + <param name="vnf_stack_id">slowburn</param> + <param name="vnf_status">created</param> + <param name="aic_cloud_region">MDTWNJ21</param> + <param name="availability_zone">slcp3-esx-az01</param> + <param name="oam_network_name">VLAN-OAM-1323</param> + <param name="vm_name">slcp34246vbc246ceb</param> + <param name="ipag_network_id">970cd2b9-7f09-4a12-af47-182ea38ba1f0</param> + <param name="vpe_network_id">545cc2c3-1930-4100-b534-5d82d0e12bb6</param> + </volume-params> +</volume-request>""" + + def completeMsoRequestXml = """<aetgt:MsoCompletionRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:ns="http://org.onap/so/request/types/v1" + xmlns="http://org.onap/so/infra/vnf-request/v1"> + <request-info> + <request-id>1234</request-id> + <action>CREATE</action> + <source>VID</source> + </request-info> + <aetgt:status-message>Volume Group has been created successfully.</aetgt:status-message> + <aetgt:mso-bpel-name>BPMN VF Module Volume action: CREATE</aetgt:mso-bpel-name> +</aetgt:MsoCompletionRequest>""" + + + @Before + public void init() + { + MockitoAnnotations.initMocks(this) + } + + + @Test + @Ignore + public void testPreProcessRequest() { + + ExecutionEntity mockExecution = setupMock('CreateVfModuleVolumeInfraV1') + + when(mockExecution.getVariable("prefix")).thenReturn('CVMVINFRAV1_') + when(mockExecution.getVariable("bpmnRequest")).thenReturn(jsonRequest) + when(mockExecution.getVariable("serviceInstanceId")).thenReturn('') + when(mockExecution.getVariable("vnfId")).thenReturn('test-vnf-id') + when(mockExecution.getVariable("mso-request-id")).thenReturn('1234') + when(mockExecution.getVariable("mso.rollback")).thenReturn('true') + + CreateVfModuleVolumeInfraV1 createVfModuleVolumeInfraV1 = new CreateVfModuleVolumeInfraV1() + createVfModuleVolumeInfraV1.preProcessRequest(mockExecution, 'true') + + // Capture the arguments to setVariable + ArgumentCaptor<String> captor1 = ArgumentCaptor.forClass(String.class); + ArgumentCaptor<String> captor2 = ArgumentCaptor.forClass(String.class); + + verify(mockExecution, times(15)).setVariable(captor1.capture(), captor2.capture()) + + List<String> arg2List = captor2.getAllValues() + String volumeRequestActual = arg2List.get(6) + String isVidRequestActual = arg2List.get(8) + + assertEquals(volumeRequestXml, volumeRequestActual.trim()) + assertEquals('true', isVidRequestActual) + } + + @Test + public void testPostProcessResponse() { + + ExecutionEntity mockExecution = setupMock('CreateVfModuleVolumeInfraV1') + when(mockExecution.getVariable("dbReturnCode")).thenReturn('000') + when(mockExecution.getVariable("CVMVINFRAV1_createDBResponse")).thenReturn('') + when(mockExecution.getVariable("mso-request-id")).thenReturn('1234') + when(mockExecution.getVariable("CVMVINFRAV1_source")).thenReturn('VID') + + CreateVfModuleVolumeInfraV1 createVfModuleVolumeInfraV1 = new CreateVfModuleVolumeInfraV1() + createVfModuleVolumeInfraV1.postProcessResponse(mockExecution, 'true') + + verify(mockExecution).setVariable('CVMVINFRAV1_Success', true) + verify(mockExecution).setVariable('CVMVINFRAV1_CompleteMsoProcessRequest', completeMsoRequestXml) + } + + +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteCustomE2EServiceInstanceTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteCustomE2EServiceInstanceTest.groovy new file mode 100644 index 0000000000..95259e9ec0 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteCustomE2EServiceInstanceTest.groovy @@ -0,0 +1,148 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts + +import com.github.tomakehurst.wiremock.junit.WireMockRule +import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity +import org.junit.Before +import org.junit.BeforeClass +import org.junit.Rule +import org.junit.Test +import org.mockito.MockitoAnnotations +import org.onap.so.bpmn.mock.FileUtil +import org.onap.so.bpmn.vcpe.scripts.GroovyTestBase + +import static org.mockito.Mockito.verify +import static org.mockito.Mockito.when + +class DeleteCustomE2EServiceInstanceTest extends GroovyTestBase { + + private static String request + + @Rule + public WireMockRule wireMockRule = new WireMockRule(GroovyTestBase.PORT) + + String Prefix = "CVRCS_" + String RbType = "DCRENI_" + + @BeforeClass + public static void setUpBeforeClass() { + request = FileUtil.readResourceFile("__files/InfrastructureFlows/DeleteCustomE2EService.json") + } + + @Before + public void init() + { + MockitoAnnotations.initMocks(this) + } + + public DeleteCustomE2EServiceInstanceTest(){ + super("DeleteCustomE2EServiceInstance") + } + @Test + public void preProcessRequestTest () { + ExecutionEntity mex = setupMock() + def map = setupMap(mex) + initPreProcess(mex) + DeleteCustomE2EServiceInstance instance = new DeleteCustomE2EServiceInstance() + mex.setVariable("isDebugLogEnabled","true") + instance.preProcessRequest(mex); + + verify(mex).getVariable(GroovyTestBase.DBGFLAG) + + Map<String,String> userParams = new HashMap<>() + userParams.put("someUserParam","someValue") + + verify(mex).setVariable("prefix", "DELSI_") + verify(mex).setVariable("msoRequestId", "mri") + verify(mex).setVariable("source", "CCD") + verify(mex).setVariable("operationType", "DELETE") + verify(mex).setVariable("globalSubscriberId", "38829939920000") + verify(mex).setVariable("serviceInputParams",userParams) + } + + @Test + public void sendSyncResponseTest() { + ExecutionEntity mex = setupMock() + def map = setupMap(mex) + initPreProcess(mex) + DeleteCustomE2EServiceInstance instance = new DeleteCustomE2EServiceInstance() + instance.sendSyncResponse(mex) + verify(mex).setVariable("DeleteCustomE2EServiceInstanceWorkflowResponseSent", "true") + } + + @Test + public void prepareCompletionRequestTest(){ + ExecutionEntity mex = setupMock() + def map = setupMap(mex) + initPreProcess(mex) + DeleteCustomE2EServiceInstance instance = new DeleteCustomE2EServiceInstance() + instance.prepareCompletionRequest(mex) + String msoComplitionRequest = FileUtil.readResourceFile("__files/GenericFlows/MsoCompletionRequest.xml") + //verify(mex).setVariable("completionRequest", msoComplitionRequest) + } + + @Test + public void sendSyncErrorTest(){ + ExecutionEntity mex = setupMock() + def map = setupMap(mex) + initPreProcess(mex) + DeleteCustomE2EServiceInstance instance = new DeleteCustomE2EServiceInstance() + instance.sendSyncError(mex) + + } + + @Test + public void prepareFalloutRequest(){ + ExecutionEntity mex = setupMock() + def map = setupMap(mex) + initPreProcess(mex) + DeleteCustomE2EServiceInstance instance = new DeleteCustomE2EServiceInstance() + instance.prepareFalloutRequest(mex) + String requestInfo = + """<request-info xmlns="http://org.onap/so/infra/vnf-request/v1"> + <request-id>null</request-id> + <action>DELETE</action> + <source>null</source> + </request-info>""" + //verify(mex).setVariable("falloutRequest", requestInfo) + } + + @Test + public void processJavaExceptionTest(){ + ExecutionEntity mex = setupMock() + def map = setupMap(mex) + initPreProcess(mex) + DeleteCustomE2EServiceInstance instance = new DeleteCustomE2EServiceInstance() + instance.processJavaException() + } + + + private void initPreProcess(ExecutionEntity mex) { + when(mex.getVariable(GroovyTestBase.DBGFLAG)).thenReturn("true") + when(mex.getVariable("bpmnRequest")).thenReturn(request) + when(mex.getVariable("mso-request-id")).thenReturn("mri") + when(mex.getVariable("serviceType")).thenReturn("VoLTE") + when(mex.getVariable("serviceInstanceId")).thenReturn("sii") + when(mex.getVariable("requestAction")).thenReturn("ra") + when(mex.getVariable("operationId")).thenReturn("59960003992") + } +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteGenericAlaCarteServiceInstanceTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteGenericAlaCarteServiceInstanceTest.groovy new file mode 100644 index 0000000000..b459710479 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteGenericAlaCarteServiceInstanceTest.groovy @@ -0,0 +1,125 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts + +import org.camunda.bpm.engine.ProcessEngineServices +import org.camunda.bpm.engine.RepositoryService +import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity +import org.camunda.bpm.engine.repository.ProcessDefinition +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.mockito.MockitoAnnotations +import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.bpmn.core.json.JsonUtils +import org.onap.so.bpmn.common.scripts.VidUtils + +import static org.junit.Assert.*; +import static org.mockito.Mockito.* + +import com.github.tomakehurst.wiremock.junit.WireMockRule + +class DeleteGenericAlaCarteServiceInstanceTest { + + @Rule + public WireMockRule wireMockRule = new WireMockRule(8090); + + String Prefix="DELSI_" + def utils = new MsoUtils() + JsonUtils jsonUtil = new JsonUtils() + VidUtils vidUtils = new VidUtils() + + String jsonIncomingRequest = + """{ + "requestDetails": { + "modelInfo": { + "modelType": "service", + "modelInvariantId": "1de901ed-17af-4b03-bc1f-41659cfa27cb", + "modelVersionId": "ace39141-09ec-4068-b06d-ac6b23bdc6e0", + "modelName": "demoVLB", + "modelVersion": "1.0" + }, + "cloudConfiguration" : { + "lcpCloudRegionId": "RegionOne", + "tenantId": "onap" + }, + "subscriberInfo": { + "globalSubscriberId": "Demonstration", + "subscriberName": "Demonstration" + }, + "requestInfo": { + "instanceName": "sample-instance-2", + "productFamilyId": "a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb", + "source": "VID", + "requestorId":"1234", + "suppressRollback": "false" + }, + "requestParameters": { + "subscriptionServiceType": "vLB" + } + } + }""" + + @Before + public void init() + { + MockitoAnnotations.initMocks(this) + + } + + public void initializeVariables(DelegateExecution mockExecution) { + + verify(mockExecution).setVariable(Prefix + "Success", false) + + verify(mockExecution).setVariable(Prefix + "CompleteMsoProcessRequest", "") + verify(mockExecution).setVariable(Prefix + "FalloutHandlerRequest", "") + verify(mockExecution).setVariable(Prefix + "isSilentSuccess", false) + + } + + @Test + //@Ignore + public void preProcessRequest() { + + println "************ preProcessRequest() ************* " + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + // Initialize prerequisite variables + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("bpmnRequest")).thenReturn(jsonIncomingRequest) + + try { + // preProcessRequest(DelegateExecution execution) + DeleteGenericALaCarteServiceInstance deleteGenericALaCarteServiceInstance = new DeleteGenericALaCarteServiceInstance() + deleteGenericALaCarteServiceInstance.preProcessRequest(mockExecution) + + verify(mockExecution).getVariable("isDebugLogEnabled") + verify(mockExecution).setVariable("prefix", Prefix) + + initializeVariables(mockExecution) + //verify(mockExecution).setVariable(Prefix + "Success", false) + }catch(Exception e){ + //ignore + } + + } +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteNetworkInstanceTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteNetworkInstanceTest.groovy new file mode 100644 index 0000000000..9b7d7ee21f --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteNetworkInstanceTest.groovy @@ -0,0 +1,418 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts + + +import static org.mockito.Mockito.* + +import org.apache.commons.lang3.* +import org.camunda.bpm.engine.ProcessEngineServices +import org.camunda.bpm.engine.RepositoryService +import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity +import org.camunda.bpm.engine.repository.ProcessDefinition +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.MockitoAnnotations +import org.mockito.runners.MockitoJUnitRunner +import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.so.bpmn.core.WorkflowException + +import com.github.tomakehurst.wiremock.junit.WireMockRule + + +@RunWith(MockitoJUnitRunner.class) +class DeleteNetworkInstanceTest { + + @Rule + public WireMockRule wireMockRule = new WireMockRule(8090); + + String Prefix="DELNI_" + def utils = new MsoUtils() + + String falloutHandlerRequest = + """<aetgt:FalloutHandlerRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:ns="http://org.onap/so/request/types/v1" + xmlns:wfsch="http://org.onap/so/workflow/schema/v1"> + <request-info xmlns="http://org.onap/so/infra/vnf-request/v1"> + <request-id>b69c9054-da09-4a2c-adf5-51042b62bfac</request-id> + <action>DELETE</action> + <source>PORTAL</source> + </request-info> + <aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1"> + <aetgt:ErrorMessage>Received error from SDN-C: No availability zone available</aetgt:ErrorMessage> + <aetgt:ErrorCode>5300</aetgt:ErrorCode> + <aetgt:SourceSystemErrorCode>200</aetgt:SourceSystemErrorCode> +</aetgt:WorkflowException> + </aetgt:FalloutHandlerRequest>""" + + String falloutHandlerRequestObj = + """<aetgt:FalloutHandlerRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:ns="http://org.onap/so/request/types/v1" + xmlns:wfsch="http://org.onap/so/workflow/schema/v1"> + <request-info xmlns="http://org.onap/so/infra/vnf-request/v1"> + <request-id>b69c9054-da09-4a2c-adf5-51042b62bfac</request-id> + <action>DELETE</action> + <source>PORTAL</source> + </request-info> + <aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1"> + <aetgt:ErrorMessage>Received error from SDN-C: No availability zone available</aetgt:ErrorMessage> + <aetgt:ErrorCode>7000</aetgt:ErrorCode> + </aetgt:WorkflowException> + </aetgt:FalloutHandlerRequest>""" + + String completeMsoProcessRequest = + """<aetgt:MsoCompletionRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:ns="http://org.onap/so/request/types/v1" + xmlns="http://org.onap/so/infra/vnf-request/v1"> + <request-info> + <request-id>88f65519-9a38-4c4b-8445-9eb4a5a5af56</request-id> + <action>DELETE</action> + <source>VID</source> + </request-info> + <aetgt:status-message>Network has been deleted successfully.</aetgt:status-message> + <aetgt:mso-bpel-name>BPMN Network action: DELETE</aetgt:mso-bpel-name> +</aetgt:MsoCompletionRequest>""" + +String deleteDBRequest = +"""<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" + xmlns:ns="http://org.onap.so/requestsdb"> + <soapenv:Header/> + <soapenv:Body> + <ns:updateInfraRequest> + <requestId>88f65519-9a38-4c4b-8445-9eb4a5a5af56</requestId> + <lastModifiedBy>BPMN</lastModifiedBy> + <statusMessage>Network successfully deleted.</statusMessage> + <responseBody/> + <requestStatus>COMPLETED</requestStatus> + <progress>100</progress> + <vnfOutputs><network-outputs xmlns="http://org.onap/so/infra/vnf-request/v1" xmlns:aetgt="http://org.onap/so/infra/vnf-request/v1" xmlns:rest="http://schemas.activebpel.org/REST/2007/12/01/aeREST.xsd"/></vnfOutputs> + </ns:updateInfraRequest> + </soapenv:Body> +</soapenv:Envelope>""" + +String deleteDBRequestErrorObj = +"""<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"> + <soapenv:Header/> + <soapenv:Body> + <ns:updateInfraRequest xmlns:ns="http://org.onap.so/requestsdb"> + <requestId>88f65519-9a38-4c4b-8445-9eb4a5a5af56</requestId> + <lastModifiedBy>BPMN</lastModifiedBy> + <statusMessage>Received error from SDN-C: No availability zone available</statusMessage> + <responseBody></responseBody> + <requestStatus>FAILED</requestStatus> + <progress></progress> + <vnfOutputs><network-outputs xmlns="http://org.onap/so/infra/vnf-request/v1" xmlns:aetgt="http://org.onap/so/infra/vnf-request/v1" xmlns:rest="http://schemas.activebpel.org/REST/2007/12/01/aeREST.xsd"/></vnfOutputs> + </ns:updateInfraRequest> + </soapenv:Body> + </soapenv:Envelope>""" + +String deleteDBRequestErrorString = +"""<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"> + <soapenv:Header/> + <soapenv:Body> + <ns:updateInfraRequest xmlns:ns="http://org.onap.so/requestsdb"> + <requestId>88f65519-9a38-4c4b-8445-9eb4a5a5af56</requestId> + <lastModifiedBy>BPMN</lastModifiedBy> + <statusMessage>Received error from SDN-C: No availability zone available</statusMessage> + <responseBody></responseBody> + <requestStatus>FAILED</requestStatus> + <progress></progress> + <vnfOutputs><network-outputs xmlns="http://org.onap/so/infra/vnf-request/v1" xmlns:aetgt="http://org.onap/so/infra/vnf-request/v1" xmlns:rest="http://schemas.activebpel.org/REST/2007/12/01/aeREST.xsd"/></vnfOutputs> + </ns:updateInfraRequest> + </soapenv:Body> + </soapenv:Envelope>""" + + String jsonIncomingRequest = + """{ "requestDetails": { + "modelInfo": { + "modelType": "networkTyp", + "modelId": "modelId", + "modelNameVersionId": "modelNameVersionId", + "modelName": "CONTRAIL_EXTERNAL", + "modelVersion": "1" + }, + "cloudConfiguration": { + "lcpCloudRegionId": "RDM2WAGPLCP", + "tenantId": "7dd5365547234ee8937416c65507d266" + }, + "requestInfo": { + "instanceName": "MNS-25180-L-01-dmz_direct_net_1", + "source": "VID", + "callbackUrl": "", + "suppressRollback": true, + "productFamilyId": "a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb" + }, + "relatedInstanceList": [ + { + "relatedInstance": { + "instanceId": "f70e927b-6087-4974-9ef8-c5e4d5847ca4", + "modelInfo": { + "modelType": "serviceT", + "modelId": "modelI", + "modelNameVersionId": "modelNameVersionI", + "modelName": "modleNam", + "modelVersion": "1" + } + } + } + ], + "requestParameters": { + "userParams": [ + { + "name": "someUserParam1", + "value": "someValue1" + } + ] + } + }}""" + +// - - - - - - - - + + + @Before + public void init() + { + MockitoAnnotations.initMocks(this) + } + + @Test + //@Ignore + public void preProcessRequest() { + + println "************ preProcessRequest_Payload ************* " + ExecutionEntity mockExecution = setupMock() + // Initialize prerequisite variables + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("bpmnRequest")).thenReturn(jsonIncomingRequest) + + DeleteNetworkInstance DeleteNetworkInstance = new DeleteNetworkInstance() + DeleteNetworkInstance.preProcessRequest(mockExecution) + + verify(mockExecution).getVariable("isDebugLogEnabled") + verify(mockExecution).setVariable("prefix", Prefix) + + //verify variable initialization + initializeVariables(mockExecution) + + + } + + public void initializeVariables (DelegateExecution mockExecution) { + + + verify(mockExecution).setVariable(Prefix + "Success", false) + + verify(mockExecution).setVariable(Prefix + "CompleteMsoProcessRequest", "") + verify(mockExecution).setVariable(Prefix + "FalloutHandlerRequest", "") + verify(mockExecution).setVariable(Prefix + "isSilentSuccess", false) + + } + + + @Test + //@Ignore + public void getNetworkModelInfo() { + + println "************ getNetworkModelInfo() ************* " + + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + // Initialize prerequisite variables + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + + // preProcessRequest(DelegateExecution execution) + DeleteNetworkInstance DeleteNetworkInstance = new DeleteNetworkInstance() + DeleteNetworkInstance.getNetworkModelInfo(mockExecution) + + verify(mockExecution).getVariable("isDebugLogEnabled") + verify(mockExecution).setVariable("prefix", Prefix) + + } + + @Test + //@Ignore + public void sendSyncResponse() { + + println "************ sendSyncResponse ************* " + + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("isAsyncProcess")).thenReturn(true) + when(mockExecution.getVariable("mso-request-id")).thenReturn("e8ebf6a0-f8ea-4dc0-8b99-fe98a87722d6") + when(mockExecution.getVariable("serviceInstanceId")).thenReturn("f70e927b-6087-4974-9ef8-c5e4d5847ca4") + + // preProcessRequest(DelegateExecution execution) + DeleteNetworkInstance DeleteNetworkInstance = new DeleteNetworkInstance() + DeleteNetworkInstance.sendSyncResponse(mockExecution) + + verify(mockExecution).setVariable("prefix", Prefix) + verify(mockExecution).setVariable("DeleteNetworkInstanceResponseCode", "202") + + } + + + @Test + //@Ignore + public void sendSyncError() { + + println "************ sendSyncError ************* " + + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("isAsyncProcess")).thenReturn(true) + when(mockExecution.getVariable("mso-request-id")).thenReturn("e8ebf6a0-f8ea-4dc0-8b99-fe98a87722d6") + when(mockExecution.getVariable("serviceInstanceId")).thenReturn("f70e927b-6087-4974-9ef8-c5e4d5847ca4") + + DeleteNetworkInstance DeleteNetworkInstance = new DeleteNetworkInstance() + DeleteNetworkInstance.sendSyncError(mockExecution) + + verify(mockExecution).setVariable("prefix", Prefix) + verify(mockExecution).setVariable("DeleteNetworkInstanceResponseCode", "500") + + } + + + @Test + //@Ignore + public void prepareCompletion() { + + println "************ postProcessResponse ************* " + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + // Initialize prerequisite variables + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable(Prefix + "source")).thenReturn("PORTAL") + when(mockExecution.getVariable("mso-request-id")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + + // postProcessResponse(DelegateExecution execution) + DeleteNetworkInstance DeleteNetworkInstance = new DeleteNetworkInstance() + DeleteNetworkInstance.prepareCompletion(mockExecution) + + // check the sequence of variable invocation + //MockitoDebuggerImpl preDebugger = new MockitoDebuggerImpl() + //preDebugger.printInvocations(mockExecution) + + verify(mockExecution).getVariable("isDebugLogEnabled") + verify(mockExecution).setVariable("prefix", Prefix) + verify(mockExecution).setVariable(Prefix + "CompleteMsoProcessRequest", completeMsoProcessRequest) + + } + + + @Test + //@Ignore + public void prepareDBRequestError() { + + println "************ prepareDBRequestError ************* " + + WorkflowException sndcWorkflowExceptionObj = new WorkflowException("CreateNetworkV2", 500, "Received error from SDN-C: No availability zone available") + + ExecutionEntity mockExecution = setupMock() + // Initialize prerequisite variables + when(mockExecution.getVariable(Prefix + "requestId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + when(mockExecution.getVariable("WorkflowException")).thenReturn(sndcWorkflowExceptionObj) + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("mso.adapters.db.auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") + when(mockExecution.getVariable("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") + + // preProcessRequest(DelegateExecution execution) + DeleteNetworkInstance DeleteNetworkInstance = new DeleteNetworkInstance() + DeleteNetworkInstance.prepareDBRequestError(mockExecution) + + verify(mockExecution).setVariable("prefix", Prefix) + verify(mockExecution).setVariable(Prefix + "deleteDBRequest", deleteDBRequestErrorObj) + + } + + + @Test + //@Ignore + public void postProcessResponse() { + + println "************ postProcessResponse ************* " + ExecutionEntity mockExecution = setupMock() + // Initialize prerequisite variables + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("CMSO_ResponseCode")).thenReturn("200") + + // postProcessResponse(DelegateExecution execution) + DeleteNetworkInstance DeleteNetworkInstance = new DeleteNetworkInstance() + DeleteNetworkInstance.postProcessResponse(mockExecution) + + verify(mockExecution).setVariable("prefix", Prefix) + verify(mockExecution).setVariable(Prefix + "Success", true) + + + } + + + @Test + //@Ignore + public void buildErrorResponse_FalloutHandlerRequest() { + + println "************ buildErrorResponse ************* " + + WorkflowException sndcWorkflowExceptionObj = new WorkflowException("DeleteNetworkInstance", 7000, "Received error from SDN-C: No availability zone available") + + ExecutionEntity mockExecution = setupMock() + // Initialize prerequisite variables + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("mso-request-id")).thenReturn("b69c9054-da09-4a2c-adf5-51042b62bfac") + when(mockExecution.getVariable("WorkflowException")).thenReturn(sndcWorkflowExceptionObj) + when(mockExecution.getVariable(Prefix + "source")).thenReturn("PORTAL") + + // buildErrorResponse(DelegateExecution execution) + DeleteNetworkInstance DeleteNetworkInstance = new DeleteNetworkInstance() + DeleteNetworkInstance.buildErrorResponse(mockExecution) + + verify(mockExecution).setVariable("prefix", Prefix) + verify(mockExecution).setVariable(Prefix + "Success", false) + verify(mockExecution).setVariable(Prefix + "FalloutHandlerRequest", falloutHandlerRequestObj) + + } + + + private ExecutionEntity setupMock() { + + ProcessDefinition mockProcessDefinition = mock(ProcessDefinition.class) + when(mockProcessDefinition.getKey()).thenReturn("DeleteNetworkInstance") + RepositoryService mockRepositoryService = mock(RepositoryService.class) + when(mockRepositoryService.getProcessDefinition()).thenReturn(mockProcessDefinition) + when(mockRepositoryService.getProcessDefinition().getKey()).thenReturn("DeleteNetworkInstance") + when(mockRepositoryService.getProcessDefinition().getId()).thenReturn("100") + ProcessEngineServices mockProcessEngineServices = mock(ProcessEngineServices.class) + when(mockProcessEngineServices.getRepositoryService()).thenReturn(mockRepositoryService) + + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + // Initialize prerequisite variables + + when(mockExecution.getId()).thenReturn("100") + when(mockExecution.getProcessDefinitionId()).thenReturn("DeleteNetworkInstance") + when(mockExecution.getProcessInstanceId()).thenReturn("DeleteNetworkInstance") + when(mockExecution.getProcessEngineServices()).thenReturn(mockProcessEngineServices) + when(mockExecution.getProcessEngineServices().getRepositoryService().getProcessDefinition(mockExecution.getProcessDefinitionId())).thenReturn(mockProcessDefinition) + + return mockExecution + + } + +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteVfModuleVolumeInfraV1Test.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteVfModuleVolumeInfraV1Test.groovy new file mode 100644 index 0000000000..0bce32716f --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteVfModuleVolumeInfraV1Test.groovy @@ -0,0 +1,167 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts + +import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.MockitoAnnotations +import org.mockito.runners.MockitoJUnitRunner +import org.onap.so.bpmn.common.scripts.MsoGroovyTest +import org.onap.so.bpmn.core.WorkflowException + +import static org.mockito.Mockito.verify +import static org.mockito.Mockito.when + +@RunWith(MockitoJUnitRunner.class) +class DeleteVfModuleVolumeInfraV1Test extends MsoGroovyTest { + + def deleteVnfAdapterRequestXml = """<deleteVolumeGroupRequest> + <cloudSiteId>RDM2WAGPLCP</cloudSiteId> + <tenantId>fba1bd1e195a404cacb9ce17a9b2b421</tenantId> + <volumeGroupId>78987</volumeGroupId> + <volumeGroupStackId/> + <skipAAI>true</skipAAI> + <msoRequest> + <requestId>TEST-REQUEST-ID-0123</requestId> + <serviceInstanceId>1234</serviceInstanceId> + </msoRequest> + <messageId>ebb9ef7b-a6a5-40e6-953e-f868f1767677</messageId> + <notificationUrl>http://localhost:28080/mso/WorkflowMessage/VNFAResponse/ebb9ef7b-a6a5-40e6-953e-f868f1767677</notificationUrl> +</deleteVolumeGroupRequest>""" + + def dbRequestXml = """<soapenv:Envelope xmlns:req="http://org.onap.so/requestsdb" + xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"> + <soapenv:Header/> + <soapenv:Body> + <req:updateInfraRequest> + <requestId>TEST-REQUEST-ID-0123</requestId> + <lastModifiedBy>BPMN</lastModifiedBy> + <statusMessage>VolumeGroup successfully deleted</statusMessage> + <requestStatus>COMPLETE</requestStatus> + <progress>100</progress> + <vnfOutputs/> + </req:updateInfraRequest> + </soapenv:Body> +</soapenv:Envelope>""" + + def completionRequestXml = """<aetgt:MsoCompletionRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:ns="http://org.onap/so/request/types/v1" + xmlns="http://org.onap/so/infra/vnf-request/v1"> + <request-info> + <request-id>TEST-REQUEST-ID-0123</request-id> + <action>DELETE</action> + <source>VID</source> + </request-info> + <aetgt:status-message>Volume Group has been deleted successfully.</aetgt:status-message> + <aetgt:mso-bpel-name>BPMN VF Module Volume action: DELETE</aetgt:mso-bpel-name> +</aetgt:MsoCompletionRequest>""" + + def falloutHandlerRequestXml = """<aetgt:FalloutHandlerRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:ns="http://org.onap/so/request/types/v1" + xmlns="http://org.onap/so/infra/vnf-request/v1"> + <request-info> + <request-id>TEST-REQUEST-ID-0123</request-id> + <action>DELETE</action> + <source>VID</source> + </request-info> + <aetgt:WorkflowException> + <aetgt:ErrorMessage>Unexpected Error</aetgt:ErrorMessage> + <aetgt:ErrorCode>5000</aetgt:ErrorCode> + </aetgt:WorkflowException> +</aetgt:FalloutHandlerRequest>""" + + @Before + public void init() + { + MockitoAnnotations.initMocks(this) + } + + + @Test + public void testPrepareVnfAdapterDeleteRequest() { + + ExecutionEntity mockExecution = setupMock('DeleteVfModuleVolumeInfraV1') + when(mockExecution.getVariable("DELVfModVol_cloudRegion")).thenReturn('RDM2WAGPLCP') + when(mockExecution.getVariable("DELVfModVol_tenantId")).thenReturn('fba1bd1e195a404cacb9ce17a9b2b421') + when(mockExecution.getVariable("DELVfModVol_volumeGroupId")).thenReturn('78987') + when(mockExecution.getVariable("DELVfModVol_volumeGroupHeatStackId")).thenReturn('') + when(mockExecution.getVariable("DELVfModVol_requestId")).thenReturn('TEST-REQUEST-ID-0123') + when(mockExecution.getVariable("DELVfModVol_serviceId")).thenReturn('1234') + when(mockExecution.getVariable("DELVfModVol_messageId")).thenReturn('ebb9ef7b-a6a5-40e6-953e-f868f1767677') + when(mockExecution.getVariable("mso.workflow.message.endpoint")).thenReturn('http://localhost:28080/mso/WorkflowMessage') + when(mockExecution.getVariable("mso.use.qualified.host")).thenReturn('') + + DeleteVfModuleVolumeInfraV1 myproc = new DeleteVfModuleVolumeInfraV1() + myproc.prepareVnfAdapterDeleteRequest(mockExecution, 'true') + + verify(mockExecution).setVariable("DELVfModVol_deleteVnfARequest", deleteVnfAdapterRequestXml) + + } + + @Test + //@Ignore + public void testPrepareDbRequest() { + + ExecutionEntity mockExecution = setupMock('DeleteVfModuleVolumeInfraV1') + when(mockExecution.getVariable("DELVfModVol_requestId")).thenReturn('TEST-REQUEST-ID-0123') + when(mockExecution.getVariable("DELVfModVol_volumeOutputs")).thenReturn('') + when(mockExecution.getVariable("mso.adapters.db.auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") + when(mockExecution.getVariable("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") + + DeleteVfModuleVolumeInfraV1 myproc = new DeleteVfModuleVolumeInfraV1() + myproc.prepareDBRequest(mockExecution, 'true') + + verify(mockExecution).setVariable("DELVfModVol_updateInfraRequest", dbRequestXml) + } + + @Test + public void testPrepareCompletionHandlerRequest() { + + ExecutionEntity mockExecution = setupMock('DeleteVfModuleVolumeInfraV1') + when(mockExecution.getVariable("mso-request-id")).thenReturn('TEST-REQUEST-ID-0123') + when(mockExecution.getVariable("DELVfModVol_source")).thenReturn('VID') + + DeleteVfModuleVolumeInfraV1 myproc = new DeleteVfModuleVolumeInfraV1() + myproc.prepareCompletionHandlerRequest(mockExecution, 'true') + + verify(mockExecution).setVariable("DELVfModVol_CompleteMsoProcessRequest", completionRequestXml) + } + + @Test + public void testPrepareFalloutHandler() { + + WorkflowException workflowException = new WorkflowException('DeleteVfModuleVolumeInfraV1', 5000, 'Unexpected Error') + + ExecutionEntity mockExecution = setupMock('DeleteVfModuleVolumeInfraV1') + + when(mockExecution.getVariable("DELVfModVol_requestId")).thenReturn('TEST-REQUEST-ID-0123') + when(mockExecution.getVariable("WorkflowException")).thenReturn(workflowException) + when(mockExecution.getVariable("DELVfModVol_source")).thenReturn('VID') + + DeleteVfModuleVolumeInfraV1 myproc = new DeleteVfModuleVolumeInfraV1() + myproc.prepareFalloutHandler(mockExecution, 'true') + + verify(mockExecution).setVariable("DELVfModVol_Success", false) + verify(mockExecution).setVariable("DELVfModVol_FalloutHandlerRequest", falloutHandlerRequestXml) + } +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateE2EServiceInstanceTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateE2EServiceInstanceTest.groovy new file mode 100644 index 0000000000..72f79c80d9 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateE2EServiceInstanceTest.groovy @@ -0,0 +1,103 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts + +import com.github.tomakehurst.wiremock.junit.WireMockRule +import org.camunda.bpm.engine.ProcessEngineServices +import org.camunda.bpm.engine.RepositoryService +import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity +import org.camunda.bpm.engine.repository.ProcessDefinition +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.ArgumentCaptor +import org.mockito.Captor +import org.mockito.Mockito +import org.mockito.MockitoAnnotations +import org.mockito.runners.MockitoJUnitRunner +import org.onap.so.bpmn.common.scripts.utils.XmlComparator + +import static org.mockito.Mockito.* +/** + * @author sushilma + * @since January 10, 2018 + */ +@RunWith(MockitoJUnitRunner.class) +class DoCreateE2EServiceInstanceTest { + + @Rule + public WireMockRule wireMockRule = new WireMockRule(28090); + + @Before + public void init() throws IOException { + MockitoAnnotations.initMocks(this); + } + + @Captor + static ArgumentCaptor<ExecutionEntity> captor = ArgumentCaptor.forClass(ExecutionEntity.class) + + String expectedServiceInstanceData = """ <service-instance xmlns="http://org.openecomp.aai.inventory/v8"> + <service-instance-id>1234</service-instance-id> + <service-instance-name>volte-service</service-instance-name> + <service-type>voLTE type</service-type> + <service-role>voLTE role</service-role> + <orchestration-status>Created</orchestration-status> + <model-invariant-id>c1d4305f-cdbd-4bbe-9069-a2f4978fd89e</model-invariant-id> + <model-version-id>d4df5c27-98a1-4812-a8aa-c17f055b7a3f</model-version-id> + </service-instance>""" + @Test + public void testPreProcessRequest(){ + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("globalSubscriberId")).thenReturn("12345") + when(mockExecution.getVariable("serviceType")).thenReturn("TRANSPORT") + when(mockExecution.getVariable("serviceInstanceId")).thenReturn("1234") + when(mockExecution.getVariable("serviceInstanceName")).thenReturn("volte-service") + when(mockExecution.getVariable("uuiRequest")).thenReturn("""{"service":{"serviceDefId":"c1d4305f-cdbd-4bbe-9069-a2f4978fd89e" , "templateId" : "d4df5c27-98a1-4812-a8aa-c17f055b7a3f"}}""") + when(mockExecution.getVariable("mso.workflow.sdncadapter.callback")).thenReturn("/mso/sdncadapter/") + when(mockExecution.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn("http://org.openecomp.aai.inventory/") + when(mockExecution.getVariable("mso.workflow.default.aai.customer.version")).thenReturn("8") + when(mockExecution.getVariable("mso.workflow.default.aai.v8.customer.uri")).thenReturn('/aai/v8/business/customers/customer') + DoCreateE2EServiceInstance obj = new DoCreateE2EServiceInstance() + obj.preProcessRequest(mockExecution) + Mockito.verify(mockExecution, times(7)).setVariable(captor.capture(), captor.capture()) + XmlComparator.assertXMLEquals(expectedServiceInstanceData, captor.getValue()) + } + + private ExecutionEntity setupMock() { + ProcessDefinition mockProcessDefinition = mock(ProcessDefinition.class) + when(mockProcessDefinition.getKey()).thenReturn("DoCreateE2EServiceInstance") + RepositoryService mockRepositoryService = mock(RepositoryService.class) + when(mockRepositoryService.getProcessDefinition()).thenReturn(mockProcessDefinition) + when(mockRepositoryService.getProcessDefinition().getKey()).thenReturn("DoCreateE2EServiceInstance") + when(mockRepositoryService.getProcessDefinition().getId()).thenReturn("100") + ProcessEngineServices mockProcessEngineServices = mock(ProcessEngineServices.class) + when(mockProcessEngineServices.getRepositoryService()).thenReturn(mockRepositoryService) + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + when(mockExecution.getId()).thenReturn("100") + when(mockExecution.getProcessDefinitionId()).thenReturn("DoCreateE2EServiceInstance") + when(mockExecution.getProcessInstanceId()).thenReturn("DoCreateE2EServiceInstance") + when(mockExecution.getProcessEngineServices()).thenReturn(mockProcessEngineServices) + when(mockExecution.getProcessEngineServices().getRepositoryService().getProcessDefinition(mockExecution.getProcessDefinitionId())).thenReturn(mockProcessDefinition) + return mockExecution + } +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateNetworkInstanceRollbackTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateNetworkInstanceRollbackTest.groovy new file mode 100644 index 0000000000..5ee10bc931 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateNetworkInstanceRollbackTest.groovy @@ -0,0 +1,369 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts + +import static org.mockito.Mockito.* + +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.ProcessEngineServices +import org.camunda.bpm.engine.RepositoryService +import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity +import org.camunda.bpm.engine.impl.pvm.process.ProcessDefinitionImpl +import org.camunda.bpm.engine.repository.ProcessDefinition +import org.camunda.bpm.engine.delegate.DelegateExecution; +import org.mockito.MockitoAnnotations +import org.mockito.runners.MockitoJUnitRunner +import org.mockito.internal.debugging.MockitoDebuggerImpl +import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.so.bpmn.core.WorkflowException +import org.junit.Before +import org.junit.Rule; +import org.junit.Test +import org.junit.Ignore +import org.junit.runner.RunWith + +import static org.onap.so.bpmn.mock.StubResponseNetworkAdapter.MockNetworkAdapterRestRollbackDelete; +import static org.junit.Assert.*; + +import com.github.tomakehurst.wiremock.client.WireMock; +import com.github.tomakehurst.wiremock.junit.WireMockRule; + +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; +import org.apache.commons.lang3.* + + +@RunWith(MockitoJUnitRunner.class) +class DoCreateNetworkInstanceRollbackTest { + + @Rule + public WireMockRule wireMockRule = new WireMockRule(28090); + + def utils = new MsoUtils() + String Prefix="CRENWKIR_" + + + String rollbackNetworkRequest = + """<NetworkAdapter:rollbackNetwork xmlns:NetworkAdapter="http://org.onap.so/network"> + <rollback> + <networkId>MNS-25180-L-01-dmz_direct_net_1/2c88a3a9-69b9-43a7-ada6-1aca577c3641</networkId> + <neutronNetworkId>c4f4e878-cde0-4b15-ae9a-bda857759cea</neutronNetworkId> + <networkStackId/> + <networkType>CONTRAIL_EXTERNAL</networkType> + <networkCreated>true</networkCreated> + <tenantId>7dd5365547234ee8937416c65507d266</tenantId> + <cloudSiteId>RDM2WAGPLCP</cloudSiteId> + <msoRequest> + <requestId>1ef47428-cade-45bd-a103-0751e8b2deb0</requestId> + <serviceInstanceId/> + </msoRequest> + </rollback> +</NetworkAdapter:rollbackNetwork>""" + + String rollbackActivateSDNCRequest = + """<aetgt:SDNCAdapterWorkflowRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:ns5="http://org.onap/so/request/types/v1" + xmlns:sdncadapter="http://org.onap.so/workflow/sdnc/adapter/schema/v1"> + <sdncadapter:RequestHeader> + <sdncadapter:RequestId>88f65519-9a38-4c4b-8445-9eb4a5a5af56</sdncadapter:RequestId> + <sdncadapter:SvcInstanceId>f70e927b-6087-4974-9ef8-c5e4d5847ca4</sdncadapter:SvcInstanceId> + <sdncadapter:SvcAction>rollback</sdncadapter:SvcAction> + <sdncadapter:SvcOperation>network-topology-operation</sdncadapter:SvcOperation> + <sdncadapter:CallbackUrl>sdncCallback</sdncadapter:CallbackUrl> + <sdncadapter:MsoAction>generic-resource</sdncadapter:MsoAction> + </sdncadapter:RequestHeader> + <aetgt:SDNCRequestData> + <request-information> + <request-id>88f65519-9a38-4c4b-8445-9eb4a5a5af56</request-id> + <request-action>CreateNetworkInstance</request-action> + <source>VID</source> + <notification-url/> + <order-number/> + <order-version/> + </request-information> + <service-information> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <service-type>MSO-dev-service-type</service-type> + <service-instance-id>f70e927b-6087-4974-9ef8-c5e4d5847ca4</service-instance-id> + <subscriber-name>MSO_1610_dev</subscriber-name> + </service-information> + <network-information> + <network-id>8abc633a-810b-4ca5-8b3a-09511d13a2ce</network-id> + <network-type>CONTRAIL_EXTERNAL</network-type> + <onap-model-information> + <model-invariant-uuid>invariant-uuid</model-invariant-uuid> + <model-customization-uuid>customization-uuid</model-customization-uuid> + <model-uuid>uuid</model-uuid> + <model-version>version</model-version> + <model-name>CONTRAIL_EXTERNAL</model-name> + </onap-model-information> + </network-information> + <network-request-information> + <network-id>8abc633a-810b-4ca5-8b3a-09511d13a2ce</network-id> + <network-type>CONTRAIL_EXTERNAL</network-type> + <network-name>MNS-25180-L-01-dmz_direct_net_1</network-name> + <tenant>7dd5365547234ee8937416c65507d266</tenant> + <aic-cloud-region>RDM2WAGPLCP</aic-cloud-region> + </network-request-information> + </aetgt:SDNCRequestData> +</aetgt:SDNCAdapterWorkflowRequest>""" + + String rollbackSDNCRequest = + """<aetgt:SDNCAdapterWorkflowRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:ns5="http://org.onap/so/request/types/v1" + xmlns:sdncadapter="http://org.onap.so/workflow/sdnc/adapter/schema/v1"> + <sdncadapter:RequestHeader> + <sdncadapter:RequestId>88f65519-9a38-4c4b-8445-9eb4a5a5af56</sdncadapter:RequestId> + <sdncadapter:SvcInstanceId>f70e927b-6087-4974-9ef8-c5e4d5847ca4</sdncadapter:SvcInstanceId> + <sdncadapter:SvcAction>rollback</sdncadapter:SvcAction> + <sdncadapter:SvcOperation>network-topology-operation</sdncadapter:SvcOperation> + <sdncadapter:CallbackUrl>sdncCallback</sdncadapter:CallbackUrl> + <sdncadapter:MsoAction>generic-resource</sdncadapter:MsoAction> + </sdncadapter:RequestHeader> + <aetgt:SDNCRequestData> + <request-information> + <request-id>88f65519-9a38-4c4b-8445-9eb4a5a5af56</request-id> + <request-action>CreateNetworkInstance</request-action> + <source>VID</source> + <notification-url/> + <order-number/> + <order-version/> + </request-information> + <service-information> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <service-type>MSO-dev-service-type</service-type> + <service-instance-id>f70e927b-6087-4974-9ef8-c5e4d5847ca4</service-instance-id> + <subscriber-name>MSO_1610_dev</subscriber-name> + </service-information> + <network-information> + <network-id>8abc633a-810b-4ca5-8b3a-09511d13a2ce</network-id> + <network-type>CONTRAIL_EXTERNAL</network-type> + <onap-model-information> + <model-invariant-uuid>invariant-uuid</model-invariant-uuid> + <model-customization-uuid>customization-uuid</model-customization-uuid> + <model-uuid>uuid</model-uuid> + <model-version>version</model-version> + <model-name>CONTRAIL_EXTERNAL</model-name> + </onap-model-information> + </network-information> + <network-request-information> + <network-id>8abc633a-810b-4ca5-8b3a-09511d13a2ce</network-id> + <network-type>CONTRAIL_EXTERNAL</network-type> + <network-name>MNS-25180-L-01-dmz_direct_net_1</network-name> + <tenant>7dd5365547234ee8937416c65507d266</tenant> + <aic-cloud-region>RDM2WAGPLCP</aic-cloud-region> + </network-request-information> + </aetgt:SDNCRequestData> +</aetgt:SDNCAdapterWorkflowRequest>""" + +// - - - - - - - - + + + @Before + public void init() + { + MockitoAnnotations.initMocks(this) + + } + + public void initializeVariables (DelegateExecution mockExecution) { + + verify(mockExecution).setVariable(Prefix + "WorkflowException", null) + + verify(mockExecution).setVariable(Prefix + "rollbackNetworkRequest", null) + verify(mockExecution).setVariable(Prefix + "rollbackNetworkResponse", "") + verify(mockExecution).setVariable(Prefix + "rollbackNetworkReturnCode", "") + + verify(mockExecution).setVariable(Prefix + "rollbackSDNCRequest", null) + verify(mockExecution).setVariable(Prefix + "rollbackSDNCResponse", "") + verify(mockExecution).setVariable(Prefix + "rollbackSDNCReturnCode", "") + + verify(mockExecution).setVariable(Prefix + "rollbackActivateSDNCRequest", null) + verify(mockExecution).setVariable(Prefix + "rollbackActivateSDNCResponse", "") + verify(mockExecution).setVariable(Prefix + "rollbackActivateSDNCReturnCode", "") + + verify(mockExecution).setVariable(Prefix + "Success", false) + verify(mockExecution).setVariable(Prefix + "fullRollback", false) + verify(mockExecution).setVariable(Prefix + "networkId", "") + verify(mockExecution).setVariable(Prefix + "urlRollbackPoNetwork", "") + + } + + @Test + //@Ignore + public void preProcessRequest() { + + println "************ preProcessRequest ************* " + + WorkflowException workflowException = new WorkflowException("DoCreateNetworkInstance", 2500, "Received error from Network Adapter: JBWEB000065: HTTP Status 500.") + Map<String, String> rollbackData = new HashMap<String, String>(); + rollbackData.put("rollbackSDNCRequest", rollbackSDNCRequest) + rollbackData.put("rollbackActivateSDNCRequest", rollbackActivateSDNCRequest) + rollbackData.put("rollbackNetworkRequest", rollbackNetworkRequest) + + ExecutionEntity mockExecution = setupMock() + // Initialize prerequisite variables + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("prefix")).thenReturn(Prefix + "") + when(mockExecution.getVariable("WorkflowException")).thenReturn(workflowException) + when(mockExecution.getVariable("rollbackData")).thenReturn(rollbackData) + when(mockExecution.getVariable("sdncVersion")).thenReturn("1702") + + when(mockExecution.getVariable("mso.adapters.po.auth")).thenReturn("3141634BF7E070AA289CF2892C986C0B") + when(mockExecution.getVariable("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") + + when(mockExecution.getVariable("mso.adapters.sdnc.endpoint")).thenReturn("http://localhost:28090/SDNCAdapter") + when(mockExecution.getVariable("mso.adapters.network.rest.endpoint")).thenReturn("http://localhost:28090/networks/NetworkAdapter") + when(mockExecution.getVariable("mso.adapters.sdnc.resource.endpoint")).thenReturn("http://localhost:28090/SDNCAdapterRpc") + + + // preProcessRequest(DelegateExecution execution) + DoCreateNetworkInstanceRollback DoCreateNetworkInstanceRollback = new DoCreateNetworkInstanceRollback() + DoCreateNetworkInstanceRollback.preProcessRequest(mockExecution) + +// verify(mockExecution).getVariable("isDebugLogEnabled") + verify(mockExecution).setVariable("prefix", Prefix) + + //verify variable initialization + initializeVariables(mockExecution) + + } + + @Test + //@Ignore + public void callPONetworkAdapter() { + + MockNetworkAdapterRestRollbackDelete("deleteNetworkResponse_Success.xml","8abc633a-810b-4ca5-8b3a-09511d13a2ce"); + + ExecutionEntity mockExecution = setupMock() + // Initialize prerequisite variables + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("prefix")).thenReturn(Prefix + "") + when(mockExecution.getVariable(Prefix + "rollbackNetworkRequest")).thenReturn( rollbackNetworkRequest) + when(mockExecution.getVariable(Prefix + "rollbackSDNCRequest")).thenReturn(rollbackSDNCRequest) + when(mockExecution.getVariable("mso.adapters.network.rest.endpoint")).thenReturn("http://localhost:28090/networks/NetworkAdapter") + + // preProcessRequest(DelegateExecution execution) + DoCreateNetworkInstanceRollback DoCreateNetworkInstanceRollback = new DoCreateNetworkInstanceRollback() + DoCreateNetworkInstanceRollback.callPONetworkAdapter(mockExecution) + + verify(mockExecution, atLeast(1)).setVariable(Prefix + "urlRollbackPoNetwork", "http://localhost:28090/networks/NetworkAdapter/8abc633a-810b-4ca5-8b3a-09511d13a2ce/rollback") + + } + + @Test + //@Ignore + public void validateRollbackResponses_Good() { + + WorkflowException workflowException = new WorkflowException("DoCreateNetworkInstanceRollback", 2500, "AAI Update Contrail Failed. Error 404.") + WorkflowException expectedWorkflowException = new WorkflowException("DoCreateNetworkInstanceRollback", 2500, "AAI Update Contrail Failed. Error 404. + SNDC activate rollback completed. + PO Network rollback completed. + SNDC assign rollback completed.") + + println "************ validateRollbackResponses_Good() ************* " + ExecutionEntity mockExecution = setupMock() + // Initialize prerequisite variables + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("prefix")).thenReturn(Prefix + "") + when(mockExecution.getVariable(Prefix + "rollbackNetworkRequest")).thenReturn("Good") + when(mockExecution.getVariable(Prefix + "rollbackSDNCRequest")).thenReturn("Good") + when(mockExecution.getVariable(Prefix + "rollbackActivateSDNCRequest")).thenReturn("Good") + when(mockExecution.getVariable(Prefix + "rollbackNetworkReturnCode")).thenReturn("200") + when(mockExecution.getVariable(Prefix + "rollbackNetworkResponse")).thenReturn("GoodResponse") + when(mockExecution.getVariable(Prefix + "rollbackSDNCReturnCode")).thenReturn("200") + when(mockExecution.getVariable(Prefix + "rollbackSDNCResponse")).thenReturn("GoodResponse") + when(mockExecution.getVariable(Prefix + "rollbackActivateSDNCReturnCode")).thenReturn("200") + when(mockExecution.getVariable(Prefix + "rollbackActivateSDNCResponse")).thenReturn("GoodResponse") + when(mockExecution.getVariable(Prefix + "WorkflowException")).thenReturn(workflowException) + when(mockExecution.getVariable(Prefix + "fullRollback")).thenReturn(false) + + DoCreateNetworkInstanceRollback DoCreateNetworkInstanceRollback = new DoCreateNetworkInstanceRollback() + DoCreateNetworkInstanceRollback.validateRollbackResponses(mockExecution) + + // verify set prefix = Prefix + "" + verify(mockExecution, atLeast(1)).setVariable("prefix", Prefix) + verify(mockExecution, atLeast(1)).setVariable("rolledBack", true) + verify(mockExecution, atLeast(1)).setVariable("wasDeleted", true) + verify(mockExecution).setVariable("WorkflowException", refEq(expectedWorkflowException, any(WorkflowException.class))) + //verify(mockExecution).setVariable("WorkflowException", expectedWorkflowException) + } + + @Test + //@Ignore + public void validateRollbackResponses_FullRollback() { + + Map<String, String> rollbackData = new HashMap<String, String>(); + rollbackData.put("rollbackSDNCRequest", rollbackSDNCRequest) + rollbackData.put("rollbackActivateSDNCRequest", rollbackActivateSDNCRequest) + rollbackData.put("rollbackNetworkRequest", rollbackNetworkRequest) + + println "************ validateRollbackResponses_FullRollback() ************* " + ExecutionEntity mockExecution = setupMock() + // Initialize prerequisite variables + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("prefix")).thenReturn(Prefix + "") + when(mockExecution.getVariable(Prefix + "rollbackNetworkRequest")).thenReturn("Good") + when(mockExecution.getVariable(Prefix + "rollbackSDNCRequest")).thenReturn("Good") + when(mockExecution.getVariable(Prefix + "rollbackActivateSDNCRequest")).thenReturn("Good") + when(mockExecution.getVariable(Prefix + "rollbackNetworkReturnCode")).thenReturn("200") + when(mockExecution.getVariable(Prefix + "rollbackNetworkResponse")).thenReturn("GoodResponse") + when(mockExecution.getVariable(Prefix + "rollbackSDNCReturnCode")).thenReturn("200") + when(mockExecution.getVariable(Prefix + "rollbackSDNCResponse")).thenReturn("GoodResponse") + when(mockExecution.getVariable(Prefix + "rollbackActivateSDNCReturnCode")).thenReturn("200") + when(mockExecution.getVariable(Prefix + "rollbackActivateSDNCResponse")).thenReturn("GoodResponse") + when(mockExecution.getVariable(Prefix + "workflowException")).thenReturn(null) + when(mockExecution.getVariable(Prefix + "fullRollback")).thenReturn(true) + when(mockExecution.getVariable("rollbackData")).thenReturn(rollbackData) + + DoCreateNetworkInstanceRollback DoCreateNetworkInstanceRollback = new DoCreateNetworkInstanceRollback() + DoCreateNetworkInstanceRollback.validateRollbackResponses(mockExecution) + + // verify set prefix = Prefix + "" + verify(mockExecution, atLeast(1)).setVariable("prefix", Prefix) + verify(mockExecution, atLeast(1)).setVariable("rollbackSuccessful", true) + verify(mockExecution, atLeast(1)).setVariable("rollbackError", false) + + } + + + private ExecutionEntity setupMock() { + + ProcessDefinition mockProcessDefinition = mock(ProcessDefinition.class) + when(mockProcessDefinition.getKey()).thenReturn("DoCreateNetworkInstanceRollback") + RepositoryService mockRepositoryService = mock(RepositoryService.class) + when(mockRepositoryService.getProcessDefinition()).thenReturn(mockProcessDefinition) + when(mockRepositoryService.getProcessDefinition().getKey()).thenReturn("DoCreateNetworkInstanceRollback") + when(mockRepositoryService.getProcessDefinition().getId()).thenReturn("100") + ProcessEngineServices mockProcessEngineServices = mock(ProcessEngineServices.class) + when(mockProcessEngineServices.getRepositoryService()).thenReturn(mockRepositoryService) + + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + // Initialize prerequisite variables + + when(mockExecution.getId()).thenReturn("100") + when(mockExecution.getProcessDefinitionId()).thenReturn("DoCreateNetworkInstanceRollback") + when(mockExecution.getProcessInstanceId()).thenReturn("DoCreateNetworkInstanceRollback") + when(mockExecution.getProcessEngineServices()).thenReturn(mockProcessEngineServices) + when(mockExecution.getProcessEngineServices().getRepositoryService().getProcessDefinition(mockExecution.getProcessDefinitionId())).thenReturn(mockProcessDefinition) + + return mockExecution + } + +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateNetworkInstanceTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateNetworkInstanceTest.groovy new file mode 100644 index 0000000000..0a1f8f2859 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateNetworkInstanceTest.groovy @@ -0,0 +1,4324 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts + + +import static org.mockito.Mockito.* +import static org.onap.so.bpmn.mock.StubResponseAAI.MockGetNetworkByName; +import static org.onap.so.bpmn.mock.StubResponseAAI.MockGetNetworkByName_404; +import static org.onap.so.bpmn.mock.StubResponseAAI.MockGetNetworkByIdWithDepth; +import static org.onap.so.bpmn.mock.StubResponseAAI.MockGetNetworkCloudRegion; +import static org.onap.so.bpmn.mock.StubResponseAAI.MockGetNetworkCloudRegion_404; +import static org.onap.so.bpmn.mock.StubResponseAAI.MockPutNetworkIdWithDepth; +import static org.onap.so.bpmn.mock.StubResponseAAI.MockGetNetworkPolicy; +import static org.onap.so.bpmn.mock.StubResponseAAI.MockGetNetworkTableReference; +import static org.onap.so.bpmn.mock.StubResponseAAI.MockGetNetworkVpnBinding; +import org.camunda.bpm.engine.ProcessEngineServices +import org.camunda.bpm.engine.RepositoryService +import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity +import org.camunda.bpm.engine.repository.ProcessDefinition +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.junit.Before +import org.junit.Ignore +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.MockitoAnnotations +import org.mockito.runners.MockitoJUnitRunner +import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.so.bpmn.core.WorkflowException + +import com.github.tomakehurst.wiremock.client.WireMock +import com.github.tomakehurst.wiremock.junit.WireMockRule +import org.apache.commons.lang3.* + +@RunWith(MockitoJUnitRunner.class) +class DoCreateNetworkInstanceTest { + + @Rule + public WireMockRule wireMockRule = new WireMockRule(8090); + + def utils = new MsoUtils() + String Prefix="CRENWKI_" + +// ---- Start XML Zone ---- + String xmlIncomingRequest = + """<rest:payload contentType="text/xml" xmlns:rest="http://schemas.activebpel.org/REST/2007/12/01/aeREST.xsd"> + <network-request xmlns:vnfreq="http://org.onap/so/infra/vnf-request/v1"> + <request-info> + <request-id>1ef47428-cade-45bd-a103-0751e8b2deb0</request-id> + <action>CREATE</action> + <source>PORTAL</source> + </request-info> + <network-inputs> + <network-id>bdc5efe8-404a-409b-85f6-0dcc9eebae30</network-id> + <network-name>MNS-25180-L-01-dmz_direct_net_1</network-name> + <network-type>CONTRAIL_EXTERNAL</network-type> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <aic-cloud-region>RDM2WAGPLCP</aic-cloud-region> + <tenant-id>7dd5365547234ee8937416c65507d266</tenant-id> + <physicalNetworkName>dvs-slcp3-01</physicalNetworkName> + <vlans>3008</vlans> + <service-instance-id>MNS-25180-L-01-dmz_direct_net_1</service-instance-id> + <backout-on-failure>true</backout-on-failure> + </network-inputs> + <network-params> + <param xmlns="" name="shared">1</param> + <param xmlns="" name="external">0</param> + </network-params> + </network-request> + </rest:payload>""" + + String expectedXMLNetworkRequest = +"""<rest:payload xmlns:rest="http://schemas.activebpel.org/REST/2007/12/01/aeREST.xsd" + xmlns:vnfreq="http://org.onap/so/infra/vnf-request/v1" + contentType="text/xml"> + <network-request> + <request-info> + <request-id>1ef47428-cade-45bd-a103-0751e8b2deb0</request-id> + <action>CREATE</action> + <source>PORTAL</source> + </request-info> + <network-inputs> + <network-id>bdc5efe8-404a-409b-85f6-0dcc9eebae30</network-id> + <network-name>MNS-25180-L-01-dmz_direct_net_1</network-name> + <network-type>CONTRAIL_EXTERNAL</network-type> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <aic-cloud-region>RDM2WAGPLCP</aic-cloud-region> + <tenant-id>7dd5365547234ee8937416c65507d266</tenant-id> + <physicalNetworkName>dvs-slcp3-01</physicalNetworkName> + <vlans>3008</vlans> + <service-instance-id>MNS-25180-L-01-dmz_direct_net_1</service-instance-id> + <backout-on-failure>true</backout-on-failure> + </network-inputs> + <network-params> + <param name="shared">1</param> + <param name="external">0</param> + </network-params> + </network-request> +</rest:payload>""" + + String expectedXMLNetworkInputs = +"""<network-inputs> + <network-id>bdc5efe8-404a-409b-85f6-0dcc9eebae30</network-id> + <network-name>MNS-25180-L-01-dmz_direct_net_1</network-name> + <network-type>CONTRAIL_EXTERNAL</network-type> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <aic-cloud-region>RDM2WAGPLCP</aic-cloud-region> + <tenant-id>7dd5365547234ee8937416c65507d266</tenant-id> + <physicalNetworkName>dvs-slcp3-01</physicalNetworkName> + <vlans>3008</vlans> + <service-instance-id>MNS-25180-L-01-dmz_direct_net_1</service-instance-id> + <backout-on-failure>true</backout-on-failure> +</network-inputs>""" + + String networkXMLOutputs = +"""""" + +// ---- End XML Zone ---- + +// ---- Start JSON Zone ---- + // JSON format Input + String jsonIncomingRequest = + """{ "requestDetails": { + "modelInfo": { + "modelType": "network", + "modelCustomizationId": "f21df226-8093-48c3-be7e-0408fcda0422", + "modelName": "CONTRAIL_EXTERNAL", + "modelVersion": "1.0" + }, + "cloudConfiguration": { + "lcpCloudRegionId": "RDM2WAGPLCP", + "tenantId": "7dd5365547234ee8937416c65507d266" + }, + "requestInfo": { + "instanceName": "MNS-25180-L-01-dmz_direct_net_1", + "source": "VID", + "callbackUrl": "", + "suppressRollback": true, + "productFamilyId": "a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb" + }, + "relatedInstanceList": [ + { + "relatedInstance": { + "instanceId": "f70e927b-6087-4974-9ef8-c5e4d5847ca4", + "modelInfo": { + "modelType": "serviceT", + "modelId": "modelI", + "modelNameVersionId": "modelNameVersionI", + "modelName": "modleNam", + "modelVersion": "1" + } + } + } + ], + "requestParameters": { + "userParams": [ + { + "name": "someUserParam1", + "value": "someValue1" + } + ] + } + }}""" + + String expectedJSONNetworkRequest = + """<network-request xmlns="http://www.w3.org/2001/XMLSchema"> + <request-info> + <request-id>null</request-id> + <action>CREATE</action> + <source>VID</source> + <service-instance-id>f70e927b-6087-4974-9ef8-c5e4d5847ca4</service-instance-id> + </request-info> + <network-inputs> + <network-id>networkId</network-id> + <network-name>MNS-25180-L-01-dmz_direct_net_1</network-name> + <network-type>CONTRAIL_EXTERNAL</network-type> + <modelCustomizationId>f21df226-8093-48c3-be7e-0408fcda0422</modelCustomizationId> + <aic-cloud-region>RDM2WAGPLCP</aic-cloud-region> + <tenant-id>7dd5365547234ee8937416c65507d266</tenant-id> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <backout-on-failure>false</backout-on-failure> + <sdncVersion>1610</sdncVersion> + </network-inputs> + <network-params> + <param name="some_user_param1">someValue1</param> + </network-params> +</network-request>""" + + String expectedJSONNetworkInputs = +"""<network-inputs xmlns="http://www.w3.org/2001/XMLSchema"> + <network-id>networkId</network-id> + <network-name>MNS-25180-L-01-dmz_direct_net_1</network-name> + <network-type>CONTRAIL_EXTERNAL</network-type> + <modelCustomizationId>f21df226-8093-48c3-be7e-0408fcda0422</modelCustomizationId> + <aic-cloud-region>RDM2WAGPLCP</aic-cloud-region> + <tenant-id>7dd5365547234ee8937416c65507d266</tenant-id> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <backout-on-failure>false</backout-on-failure> + <sdncVersion>1610</sdncVersion> +</network-inputs>""" + + String networkJSONOutputs = +"""<network-outputs> + <network-id>networkId</network-id> + <network-name>MNS-25180-L-01-dmz_direct_net_1</network-name> + </network-outputs>""" + +// ---- End JSON Zone ---- + +// ---- Start vPIR Zone ---- + // expectedNetworkRequest + String expectedvIPRNetworkRequest = + """<network-request xmlns="http://www.w3.org/2001/XMLSchema"> + <request-info> + <request-id>88f65519-9a38-4c4b-8445-9eb4a5a5af56</request-id> + <action>CREATE</action> + <source>VID</source> + <service-instance-id>f70e927b-6087-4974-9ef8-c5e4d5847ca4</service-instance-id> + </request-info> + <network-inputs> + <network-id>networkId</network-id> + <network-name>MNS-25180-L-01-dmz_direct_net_1</network-name> + <network-type>CONTRAIL_EXTERNAL</network-type> + <subscription-service-type>MSO-dev-service-type</subscription-service-type> + <global-customer-id>globalId_45678905678</global-customer-id> + <aic-cloud-region>RDM2WAGPLCP</aic-cloud-region> + <tenant-id>7dd5365547234ee8937416c65507d266</tenant-id> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <backout-on-failure>false</backout-on-failure> + <failIfExist>false</failIfExist> + <networkModelInfo> + <modelName>CONTRAIL_EXTERNAL</modelName> + <modelUuid>sn5256d1-5a33-55df-13ab-12abad84e111</modelUuid> + <modelInvariantUuid>sn5256d1-5a33-55df-13ab-12abad84e764</modelInvariantUuid> + <modelVersion>1</modelVersion> + <modelCustomizationUuid>sn5256d1-5a33-55df-13ab-12abad84e222</modelCustomizationUuid> + </networkModelInfo> + <serviceModelInfo> + <modelName>HNGW Protected OAM</modelName> + <modelUuid>36a3a8ea-49a6-4ac8-b06c-89a54544b9b6</modelUuid> + <modelInvariantUuid>fcc85cb0-ad74-45d7-a5a1-17c8744fdb71</modelInvariantUuid> + <modelVersion>1.0</modelVersion> + <modelCustomizationUuid/> + </serviceModelInfo> + <sdncVersion>1702</sdncVersion> + </network-inputs> + <network-params/> +</network-request>""" + + String expectedvIPRNetworkInputs = +"""<network-inputs xmlns="http://www.w3.org/2001/XMLSchema"> + <network-id>networkId</network-id> + <network-name>MNS-25180-L-01-dmz_direct_net_1</network-name> + <network-type>CONTRAIL_EXTERNAL</network-type> + <subscription-service-type>MSO-dev-service-type</subscription-service-type> + <global-customer-id>globalId_45678905678</global-customer-id> + <aic-cloud-region>RDM2WAGPLCP</aic-cloud-region> + <tenant-id>7dd5365547234ee8937416c65507d266</tenant-id> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <backout-on-failure>false</backout-on-failure> + <failIfExist>false</failIfExist> + <networkModelInfo> + <modelName>CONTRAIL_EXTERNAL</modelName> + <modelUuid>sn5256d1-5a33-55df-13ab-12abad84e111</modelUuid> + <modelInvariantUuid>sn5256d1-5a33-55df-13ab-12abad84e764</modelInvariantUuid> + <modelVersion>1</modelVersion> + <modelCustomizationUuid>sn5256d1-5a33-55df-13ab-12abad84e222</modelCustomizationUuid> + </networkModelInfo> + <serviceModelInfo> + <modelName>HNGW Protected OAM</modelName> + <modelUuid>36a3a8ea-49a6-4ac8-b06c-89a54544b9b6</modelUuid> + <modelInvariantUuid>fcc85cb0-ad74-45d7-a5a1-17c8744fdb71</modelInvariantUuid> + <modelVersion>1.0</modelVersion> + <modelCustomizationUuid/> + </serviceModelInfo> + <sdncVersion>1702</sdncVersion> +</network-inputs>""" + + String networkvIPROutputs = +"""<network-outputs> + <network-id>networkId</network-id> + <network-name>MNS-25180-L-01-dmz_direct_net_1</network-name> + </network-outputs>""" + +// ---- End vPIR Zone ---- + + String vnfRequestFakeRegion = + """<vnfreq:network-request xmlns:vnfreq="http://org.onap/so/infra/vnf-request/v1"> + <vnfreq:request-info> + <vnfreq:request-id>1ef47428-cade-45bd-a103-0751e8b2deb0</vnfreq:request-id> + <vnfreq:action>CREATE</vnfreq:action> + <vnfreq:source>PORTAL</vnfreq:source> + </vnfreq:request-info> + <vnfreq:network-inputs> + <vnfreq:network-name>MNS-25180-L-01-dmz_direct_net_1</vnfreq:network-name> + <vnfreq:network-type>CONTRAIL_EXTERNAL</vnfreq:network-type> + <subscriptionServiceType>MSO-dev-service-type</subscriptionServiceType> + <vnfreq:service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</vnfreq:service-id> + <vnfreq:aic-cloud-region>MDTWNJ21</vnfreq:aic-cloud-region> + <vnfreq:tenant-id>7dd5365547234ee8937416c65507d266</vnfreq:tenant-id> + </vnfreq:network-inputs> + <vnfreq:network-params> + <param name="shared">1</param> + <param name="external">0</param> + </vnfreq:network-params> +</vnfreq:network-request>""" + + // expectedNetworkRequest + String expectedNetworkRequest_Outputs = + """<vnfreq:network-request xmlns:vnfreq="http://org.onap/so/infra/vnf-request/v1"> + <vnfreq:request-info> + <vnfreq:request-id>1ef47428-cade-45bd-a103-0751e8b2deb0</vnfreq:request-id> + <vnfreq:action>CREATE</vnfreq:action> + <vnfreq:source>PORTAL</vnfreq:source> + </vnfreq:request-info> + <vnfreq:network-inputs> + <vnfreq:network-name>MNS-25180-L-01-dmz_direct_net_1</vnfreq:network-name> + <vnfreq:network-type>CONTRAIL_EXTERNAL</vnfreq:network-type> + <subscriptionServiceType>MSO-dev-service-type</subscriptionServiceType> + <vnfreq:service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</vnfreq:service-id> + <vnfreq:aic-cloud-region>RDM2WAGPLCP</vnfreq:aic-cloud-region> + <vnfreq:tenant-id>7dd5365547234ee8937416c65507d266</vnfreq:tenant-id> + </vnfreq:network-inputs> + <vnfreq:network-outputs> + <vnfreq:network-name>MNS-25180-L-01-dmz_direct_net_1</vnfreq:network-name> + <vnfreq:network-id>bdc5efe8-404a-409b-85f6-0dcc9eebae30</vnfreq:network-id> + </vnfreq:network-outputs> + <vnfreq:network-params> + <param name="shared">1</param> + <param name="external">0</param> + </vnfreq:network-params> +</vnfreq:network-request>""" + + + // expectedNetworkRequest + String networkInputs_404 = + """<network-inputs xmlns="http://org.onap/so/infra/vnf-request/v1"> + <network-name>myOwn_Network</network-name> + <network-type>CONTRAIL_EXTERNAL</network-type> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <aic-cloud-region>RDM2WAGPLCP</aic-cloud-region> + <tenant-id>e81d842d3e8b45c5a59f57cd76af3aaf</tenant-id> + </network-inputs>""" + + String networkInputs = + """<network-inputs xmlns="http://org.onap/so/infra/vnf-request/v1"> + <network-id>bdc5efe8-404a-409b-85f6-0dcc9eebae30</network-id> + <network-name>MNS-25180-L-01-dmz_direct_net_1</network-name> + <network-type>CONTRAIL_EXTERNAL</network-type> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <aic-cloud-region>RDM2WAGPLCP</aic-cloud-region> + <tenant-id>e81d842d3e8b45c5a59f57cd76af3aaf</tenant-id> +</network-inputs>""" + + + + String queryAAIResponse = + """<rest:RESTResponse xmlns:rest="http://schemas.activebpel.org/REST/2007/12/01/aeREST.xsd" + statusCode="200"> + <rest:headers> + <rest:header name="Transfer-Encoding" value="chunked"/> + <rest:header name="Date" value="Thu,10 Mar 2016 00:01:18 GMT"/> + <rest:header name="Expires" value="Thu,01 Jan 1970 00:00:00 UTC"/> + <rest:header name="X-AAI-TXID" value="mtcnjv9aaas03-20160310-00:01:18:502-132671"/> + <rest:header name="Content-Type" value="application/xml"/> + <rest:header name="Server" value="Apache-Coyote/1.1"/> + <rest:header name="Cache-Control" value="private"/> + </rest:headers> + <rest:payload contentType="text/xml"> + <l3-network xmlns="http://org.openecomp.aai.inventory/v3"> + <network-id>bdc5efe8-404a-409b-85f6-0dcc9eebae30</network-id> + <network-name>HSL_direct_net_2</network-name> + <network-type>CONTRAIL_EXTERNAL</network-type> + <network-role>dmz_direct</network-role> + <network-technology>contrail</network-technology> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <network-role-instance>0</network-role-instance> + <orchestration-status>pending-create</orchestration-status> + <subnets> + <subnet> + <subnet-id>57e9a1ff-d14f-4071-a828-b19ae98eb2fc</subnet-id> + <gateway-address>107.239.52.1</gateway-address> + <network-start-address>107.239.52.0</network-start-address> + <cidr-mask>24</cidr-mask> + <ip-version>4</ip-version> + <orchestration-status>pending-create</orchestration-status> + <dhcp-enabled>true</dhcp-enabled> + <relationship-list/> + </subnet> + </subnets> + <relationship-list> + <relationship> + <related-to>vpn-binding</related-to> + <related-link>https://aai-app-e2e.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/85f015d0-2e32-4c30-96d2-87a1a27f8017/</related-link> + <relationship-data> + <relationship-key>vpn-binding.vpn-id</relationship-key> + <relationship-value>85f015d0-2e32-4c30-96d2-87a1a27f8017</relationship-value> + </relationship-data> + </relationship> + <relationship> + <related-to>vpn-binding</related-to> + <related-link>https://aai-app-e2e.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/c980a6ef-3b88-49f0-9751-dbad8608d0a6/</related-link> + <relationship-data> + <relationship-key>vpn-binding.vpn-id</relationship-key> + <relationship-value>c980a6ef-3b88-49f0-9751-dbad8608d0a6</relationship-value> + </relationship-data> + </relationship> + <relationship> + <related-to>tenant</related-to> + <related-link>https://aai-app-e2e.test.com:8443/aai/v8/cloud-infrastructure/tenants/tenant/7dd5365547234ee8937416c65507d266/</related-link> + <relationship-data> + <relationship-key>tenant.tenant-id</relationship-key> + <relationship-value>7dd5365547234ee8937416c65507d266</relationship-value> + </relationship-data> + </relationship> + </relationship-list> + </l3-network> + </rest:payload> +</rest:RESTResponse>""" + + String queryIdAIIResponse = + """<rest:RESTResponse xmlns:rest="http://schemas.activebpel.org/REST/2007/12/01/aeREST.xsd" + statusCode="200"> + <rest:headers> + <rest:header name="Transfer-Encoding" value="chunked"/> + <rest:header name="Date" value="Thu,10 Mar 2016 00:01:18 GMT"/> + <rest:header name="Expires" value="Thu,01 Jan 1970 00:00:00 UTC"/> + <rest:header name="X-AAI-TXID" value="mtcnjv9aaas03-20160310-00:01:18:502-132671"/> + <rest:header name="Content-Type" value="application/xml"/> + <rest:header name="Server" value="Apache-Coyote/1.1"/> + <rest:header name="Cache-Control" value="private"/> + </rest:headers> + <rest:payload contentType="text/xml"> + <l3-network xmlns="http://org.openecomp.aai.inventory/v6"> + <network-id>49c86598-f766-46f8-84f8-8d1c1b10f9b4</network-id> + <network-name>MNS-25180-L-01-dmz_direct_net_1</network-name> + <network-type>CONTRAIL_EXTERNAL</network-type> + <network-role>dmz_direct</network-role> + <network-technology>Contrail</network-technology> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <network-role-instance>0</network-role-instance> + <resource-version>l3-version</resource-version> + <orchestration-status>pending-create</orchestration-status> + <physical-network-name>networkName</physical-network-name> + <is-provider-network>false</is-provider-network> + <is-shared-network>true</is-shared-network> + <is-external-network>false</is-external-network> + <subnets> + <subnet> + <subnet-id>57e9a1ff-d14f-4071-a828-b19ae98eb2fc</subnet-id> + <gateway-address>107.239.52.1</gateway-address> + <network-start-address>107.239.52.0</network-start-address> + <cidr-mask>24</cidr-mask> + <ip-version>4</ip-version> + <orchestration-status>pending-create</orchestration-status> + <dhcp-enabled>true</dhcp-enabled> + <subnet-name>subnetName</subnet-name> + <subnet-role>ECOMP</subnet-role> + <ip-assignment-direction>true</ip-assignment-direction> + <host-routes> + <host-route> + <host-route-id>string</host-route-id> + <route-prefix>192.10.16.0/24</route-prefix> + <next-hop>192.10.16.100/24</next-hop> + <next-hop-type>ip-address</next-hop-type> + <resource-version>1505857301954</resource-version> + </host-route> + <host-route> + <host-route-id>string</host-route-id> + <route-prefix>192.110.17.0/24</route-prefix> + <next-hop>192.110.17.110/24</next-hop> + <next-hop-type>ip-address</next-hop-type> + <resource-version>1505857301954</resource-version> + </host-route> + </host-routes> + <relationship-list/> + </subnet> + <subnet> + <subnet-id>57e9a1ff-d14f-4071-a828-b19ae98eb2fc</subnet-id> + <gateway-address>107.239.52.1</gateway-address> + <network-start-address>107.239.52.0</network-start-address> + <cidr-mask>24</cidr-mask> + <ip-version>4</ip-version> + <orchestration-status>pending-create</orchestration-status> + <dhcp-enabled>true</dhcp-enabled> + <subnet-name>subnetName</subnet-name> + <ip-assignment-direction>true</ip-assignment-direction> + <host-routes> + <host-route> + <host-route-id>string</host-route-id> + <route-prefix>192.10.16.0/24</route-prefix> + <next-hop>192.10.16.100/24</next-hop> + <next-hop-type>ip-address</next-hop-type> + <resource-version>1505857301954</resource-version> + </host-route> + </host-routes> + <relationship-list/> + </subnet> + </subnets> + <segmentation-assignments> + <segmentation-id>414</segmentation-id> + <resource-version>4132176</resource-version> + </segmentation-assignments> + <segmentation-assignments> + <segmentation-id>415</segmentation-id> + <resource-version>4132176</resource-version> + </segmentation-assignments> + <ctag-assignments> + <ctag-assignment> + <vlan-id-inner>inner</vlan-id-inner> + <resource-version>ctag-version</resource-version> + <relationship-list> + <relationship> + <related-to>tenant</related-to> + <related-link>https://aai-ext1.test.com:8443/aai/v8/cloud-infrastructure/tenants/tenant/897deadc2b954a6bac6d3c197fb3525e/</related-link> + <relationship-data> + <relationship-key>tenant.tenant-id</relationship-key> + <relationship-value>897deadc2b954a6bac6d3c197fb3525e</relationship-value> + </relationship-data> + <related-to-property> + <property-key>tenant.tenant-name</property-key> + <property-value>MSOTest1</property-value> + </related-to-property> + </relationship> + <relationship> + <related-to>vpn-binding</related-to> + <related-link>https://aai-ext1.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/a290b841-f672-44dd-b9cd-6f8c20d7d8c8/</related-link> + <relationship-data> + <relationship-key>vpn-binding.vpn-id</relationship-key> + <relationship-value>a290b841-f672-44dd-b9cd-6f8c20d7d8c8</relationship-value> + </relationship-data> + <related-to-property> + <property-key>vpn-binding.vpn-name</property-key> + <property-value>oam_protected_net_6_MTN5_msotest2</property-value> + </related-to-property> + </relationship> + <relationship> + <related-to>vpn-binding</related-to> + <related-link>https://aai-ext1.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/24a4b507-853a-4a38-99aa-05fcc54be24d/</related-link> + <relationship-data> + <relationship-key>vpn-binding.vpn-id</relationship-key> + <relationship-value>24a4b507-853a-4a38-99aa-05fcc54be24d</relationship-value> + </relationship-data> + <related-to-property> + <property-key>vpn-binding.vpn-name</property-key> + <property-value>oam_protected_net_6_MTN5_msotest1</property-value> + </related-to-property> + </relationship> + </relationship-list> + </ctag-assignment> + </ctag-assignments> + <relationship-list> + <relationship> + <related-to>vpn-binding</related-to> + <related-link>https://aai-app-e2e.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/85f015d0-2e32-4c30-96d2-87a1a27f8017/</related-link> + <relationship-data> + <relationship-key>vpn-binding.vpn-id</relationship-key> + <relationship-value>85f015d0-2e32-4c30-96d2-87a1a27f8017</relationship-value> + </relationship-data> + </relationship> + <relationship> + <related-to>vpn-binding</related-to> + <related-link>https://aai-app-e2e.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/c980a6ef-3b88-49f0-9751-dbad8608d0a6/</related-link> + <relationship-data> + <relationship-key>vpn-binding.vpn-id</relationship-key> + <relationship-value>c980a6ef-3b88-49f0-9751-dbad8608d0a6</relationship-value> + </relationship-data> + </relationship> + <relationship> + <related-to>tenant</related-to> + <related-link>https://aai-app-e2e.test.com:8443/aai/v8/cloud-infrastructure/tenants/tenant/7dd5365547234ee8937416c65507d266/</related-link> + <relationship-data> + <relationship-key>tenant.tenant-id</relationship-key> + <relationship-value>7dd5365547234ee8937416c65507d266</relationship-value> + </relationship-data> + </relationship> + <relationship> + <related-to>network-policy</related-to> + <related-link>https://aai-app-e2e.test.com:8443/aai/v8/network/network-policies/network-policy/cee6d136-e378-4678-a024-2cd15f0ee0cg</related-link> + <relationship-data> + <relationship-key>network-policy.network-policy-id</relationship-key> + <relationship-value>cee6d136-e378-4678-a024-2cd15f0ee0cg</relationship-value> + </relationship-data> + </relationship> + <relationship> + <related-to>route-table-reference</related-to> + <related-link>https://aai-app-e2e.test.com:8443/aai/v8/network/route-table-references/route-table-reference/refFQDN1</related-link> + <relationship-data> + <relationship-key>route-table-reference.route-table-reference-id</relationship-key> + <relationship-value>cee6d136-e378-4678-a024-2cd15f0ee0hi</relationship-value> + </relationship-data> + </relationship> + <relationship> + <related-to>route-table-reference</related-to> + <related-link>https://aai-app-e2e.test.com:8443/aai/v8/network/route-table-references/route-table-reference/refFQDN2</related-link> + <relationship-data> + <relationship-key>route-table-reference.route-table-reference-id</relationship-key> + <relationship-value>cee6d136-e378-4678-a024-2cd15f0ee0hi</relationship-value> + </relationship-data> + </relationship> + </relationship-list> + </l3-network> + </rest:payload> +</rest:RESTResponse>""" + +String queryIdAIIResponse_AlaCarte = +"""<rest:RESTResponse xmlns:rest="http://schemas.activebpel.org/REST/2007/12/01/aeREST.xsd" + statusCode="200"> + <rest:headers> + <rest:header name="Transfer-Encoding" value="chunked"/> + <rest:header name="Date" value="Thu,10 Mar 2016 00:01:18 GMT"/> + <rest:header name="Expires" value="Thu,01 Jan 1970 00:00:00 UTC"/> + <rest:header name="X-AAI-TXID" value="mtcnjv9aaas03-20160310-00:01:18:502-132671"/> + <rest:header name="Content-Type" value="application/xml"/> + <rest:header name="Server" value="Apache-Coyote/1.1"/> + <rest:header name="Cache-Control" value="private"/> + </rest:headers> + <rest:payload contentType="text/xml"> + <l3-network xmlns="http://org.openecomp.aai.inventory/v6"> + <network-id>49c86598-f766-46f8-84f8-8d1c1b10f9b4</network-id> + <network-name>MNS-25180-L-01-dmz_direct_net_1</network-name> + <network-type>CONTRAIL_EXTERNAL</network-type> + <network-role>dmz_direct</network-role> + <network-technology>Contrail</network-technology> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <network-role-instance>0</network-role-instance> + <resource-version>l3-version</resource-version> + <orchestration-status>pending-create</orchestration-status> + <physical-network-name>networkName</physical-network-name> + <is-provider-network>false</is-provider-network> + <is-shared-network>true</is-shared-network> + <is-external-network>false</is-external-network> + <subnets> + <subnet> + <subnet-id>57e9a1ff-d14f-4071-a828-b19ae98eb2fc</subnet-id> + <gateway-address>107.239.52.1</gateway-address> + <network-start-address>107.239.52.0</network-start-address> + <cidr-mask>24</cidr-mask> + <ip-version>4</ip-version> + <orchestration-status>pending-create</orchestration-status> + <dhcp-enabled>true</dhcp-enabled> + <subnet-name>subnetName</subnet-name> + <relationship-list/> + </subnet> + <subnet> + <subnet-id>57e9a1ff-d14f-4071-a828-b19ae98eb2fc</subnet-id> + <gateway-address>107.239.52.1</gateway-address> + <network-start-address>107.239.52.0</network-start-address> + <cidr-mask>24</cidr-mask> + <ip-version>4</ip-version> + <orchestration-status>pending-create</orchestration-status> + <dhcp-enabled>true</dhcp-enabled> + <subnet-name>subnetName</subnet-name> + <relationship-list/> + </subnet> + </subnets> + <segmentation-assignments> + <segmentation-id>414</segmentation-id> + <resource-version>4132176</resource-version> + </segmentation-assignments> + <segmentation-assignments> + <segmentation-id>415</segmentation-id> + <resource-version>4132176</resource-version> + </segmentation-assignments> + <ctag-assignments> + <ctag-assignment> + <vlan-id-inner>inner</vlan-id-inner> + <resource-version>ctag-version</resource-version> + <relationship-list> + <relationship> + <related-to>tenant</related-to> + <related-link>https://aai-ext1.test.com:8443/aai/v8/cloud-infrastructure/tenants/tenant/897deadc2b954a6bac6d3c197fb3525e/</related-link> + <relationship-data> + <relationship-key>tenant.tenant-id</relationship-key> + <relationship-value>897deadc2b954a6bac6d3c197fb3525e</relationship-value> + </relationship-data> + <related-to-property> + <property-key>tenant.tenant-name</property-key> + <property-value>MSOTest1</property-value> + </related-to-property> + </relationship> + <relationship> + <related-to>vpn-binding</related-to> + <related-link>https://aai-ext1.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/a290b841-f672-44dd-b9cd-6f8c20d7d8c8/</related-link> + <relationship-data> + <relationship-key>vpn-binding.vpn-id</relationship-key> + <relationship-value>a290b841-f672-44dd-b9cd-6f8c20d7d8c8</relationship-value> + </relationship-data> + <related-to-property> + <property-key>vpn-binding.vpn-name</property-key> + <property-value>oam_protected_net_6_MTN5_msotest2</property-value> + </related-to-property> + </relationship> + <relationship> + <related-to>vpn-binding</related-to> + <related-link>https://aai-ext1.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/24a4b507-853a-4a38-99aa-05fcc54be24d/</related-link> + <relationship-data> + <relationship-key>vpn-binding.vpn-id</relationship-key> + <relationship-value>24a4b507-853a-4a38-99aa-05fcc54be24d</relationship-value> + </relationship-data> + <related-to-property> + <property-key>vpn-binding.vpn-name</property-key> + <property-value>oam_protected_net_6_MTN5_msotest1</property-value> + </related-to-property> + </relationship> + </relationship-list> + </ctag-assignment> + </ctag-assignments> + <relationship-list> + <relationship> + <related-to>vpn-binding</related-to> + <related-link>https://aai-app-e2e.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/85f015d0-2e32-4c30-96d2-87a1a27f8017/</related-link> + <relationship-data> + <relationship-key>vpn-binding.vpn-id</relationship-key> + <relationship-value>85f015d0-2e32-4c30-96d2-87a1a27f8017</relationship-value> + </relationship-data> + </relationship> + <relationship> + <related-to>vpn-binding</related-to> + <related-link>https://aai-app-e2e.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/c980a6ef-3b88-49f0-9751-dbad8608d0a6/</related-link> + <relationship-data> + <relationship-key>vpn-binding.vpn-id</relationship-key> + <relationship-value>c980a6ef-3b88-49f0-9751-dbad8608d0a6</relationship-value> + </relationship-data> + </relationship> + <relationship> + <related-to>tenant</related-to> + <related-link>https://aai-app-e2e.test.com:8443/aai/v8/cloud-infrastructure/tenants/tenant/7dd5365547234ee8937416c65507d266/</related-link> + <relationship-data> + <relationship-key>tenant.tenant-id</relationship-key> + <relationship-value>7dd5365547234ee8937416c65507d266</relationship-value> + </relationship-data> + </relationship> + <relationship> + <related-to>network-policy</related-to> + <related-link>https://aai-app-e2e.test.com:8443/aai/v8/network/network-policies/network-policy/cee6d136-e378-4678-a024-2cd15f0ee0cg</related-link> + <relationship-data> + <relationship-key>network-policy.network-policy-id</relationship-key> + <relationship-value>cee6d136-e378-4678-a024-2cd15f0ee0cg</relationship-value> + </relationship-data> + </relationship> + <relationship> + <related-to>route-table-reference</related-to> + <related-link>https://aai-app-e2e.test.com:8443/aai/v8/network/route-table-references/route-table-reference/refFQDN1</related-link> + <relationship-data> + <relationship-key>route-table-reference.route-table-reference-id</relationship-key> + <relationship-value>cee6d136-e378-4678-a024-2cd15f0ee0hi</relationship-value> + </relationship-data> + </relationship> + <relationship> + <related-to>route-table-reference</related-to> + <related-link>https://aai-app-e2e.test.com:8443/aai/v8/network/route-table-references/route-table-reference/refFQDN2</related-link> + <relationship-data> + <relationship-key>route-table-reference.route-table-reference-id</relationship-key> + <relationship-value>cee6d136-e378-4678-a024-2cd15f0ee0hi</relationship-value> + </relationship-data> + </relationship> + </relationship-list> + </l3-network> + </rest:payload> +</rest:RESTResponse>""" + +String queryIdAIIResponse_segmentation = +"""<rest:RESTResponse xmlns:rest="http://schemas.activebpel.org/REST/2007/12/01/aeREST.xsd" + statusCode="200"> + <rest:headers> + <rest:header name="Transfer-Encoding" value="chunked"/> + <rest:header name="Date" value="Thu,10 Mar 2016 00:01:18 GMT"/> + <rest:header name="Expires" value="Thu,01 Jan 1970 00:00:00 UTC"/> + <rest:header name="X-AAI-TXID" value="mtcnjv9aaas03-20160310-00:01:18:502-132671"/> + <rest:header name="Content-Type" value="application/xml"/> + <rest:header name="Server" value="Apache-Coyote/1.1"/> + <rest:header name="Cache-Control" value="private"/> + </rest:headers> + <rest:payload contentType="text/xml"> + <l3-network xmlns="http://org.openecomp.aai.inventory/v6"> + <network-id>49c86598-f766-46f8-84f8-8d1c1b10f9b4</network-id> + <network-name>MNS-25180-L-01-dmz_direct_net_1</network-name> + <network-type>CONTRAIL_EXTERNAL</network-type> + <network-role>dmz_direct</network-role> + <network-technology>Contrail</network-technology> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <network-role-instance>0</network-role-instance> + <resource-version>l3-version</resource-version> + <orchestration-status>pending-create</orchestration-status> + <physical-network-name>networkName</physical-network-name> + <is-provider-network>false</is-provider-network> + <is-shared-network>true</is-shared-network> + <is-external-network>false</is-external-network> + <subnets> + <subnet> + <subnet-id>57e9a1ff-d14f-4071-a828-b19ae98eb2fc</subnet-id> + <gateway-address>107.239.52.1</gateway-address> + <network-start-address>107.239.52.0</network-start-address> + <cidr-mask>24</cidr-mask> + <ip-version>4</ip-version> + <orchestration-status>pending-create</orchestration-status> + <dhcp-enabled>true</dhcp-enabled> + <subnet-name>subnetName</subnet-name> + <relationship-list/> + </subnet> + <subnet> + <subnet-id>57e9a1ff-d14f-4071-a828-b19ae98eb2fc</subnet-id> + <gateway-address>107.239.52.1</gateway-address> + <network-start-address>107.239.52.0</network-start-address> + <cidr-mask>24</cidr-mask> + <ip-version>4</ip-version> + <orchestration-status>pending-create</orchestration-status> + <dhcp-enabled>true</dhcp-enabled> + <subnet-name>subnetName</subnet-name> + <relationship-list/> + </subnet> + </subnets> + <segmentation-assignments> + <segmentation-assignment> + <segmentation-id>1</segmentation-id> + <resource-version>1498507569188</resource-version> + </segmentation-assignment> + </segmentation-assignments> + <ctag-assignments> + <ctag-assignment> + <vlan-id-inner>inner</vlan-id-inner> + <resource-version>ctag-version</resource-version> + <relationship-list> + <relationship> + <related-to>tenant</related-to> + <related-link>https://aai-ext1.test.com:8443/aai/v8/cloud-infrastructure/tenants/tenant/897deadc2b954a6bac6d3c197fb3525e/</related-link> + <relationship-data> + <relationship-key>tenant.tenant-id</relationship-key> + <relationship-value>897deadc2b954a6bac6d3c197fb3525e</relationship-value> + </relationship-data> + <related-to-property> + <property-key>tenant.tenant-name</property-key> + <property-value>MSOTest1</property-value> + </related-to-property> + </relationship> + <relationship> + <related-to>vpn-binding</related-to> + <related-link>https://aai-ext1.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/a290b841-f672-44dd-b9cd-6f8c20d7d8c8/</related-link> + <relationship-data> + <relationship-key>vpn-binding.vpn-id</relationship-key> + <relationship-value>a290b841-f672-44dd-b9cd-6f8c20d7d8c8</relationship-value> + </relationship-data> + <related-to-property> + <property-key>vpn-binding.vpn-name</property-key> + <property-value>oam_protected_net_6_MTN5_msotest2</property-value> + </related-to-property> + </relationship> + <relationship> + <related-to>vpn-binding</related-to> + <related-link>https://aai-ext1.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/24a4b507-853a-4a38-99aa-05fcc54be24d/</related-link> + <relationship-data> + <relationship-key>vpn-binding.vpn-id</relationship-key> + <relationship-value>24a4b507-853a-4a38-99aa-05fcc54be24d</relationship-value> + </relationship-data> + <related-to-property> + <property-key>vpn-binding.vpn-name</property-key> + <property-value>oam_protected_net_6_MTN5_msotest1</property-value> + </related-to-property> + </relationship> + </relationship-list> + </ctag-assignment> + </ctag-assignments> + <relationship-list> + <relationship> + <related-to>vpn-binding</related-to> + <related-link>https://aai-app-e2e.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/85f015d0-2e32-4c30-96d2-87a1a27f8017/</related-link> + <relationship-data> + <relationship-key>vpn-binding.vpn-id</relationship-key> + <relationship-value>85f015d0-2e32-4c30-96d2-87a1a27f8017</relationship-value> + </relationship-data> + </relationship> + <relationship> + <related-to>vpn-binding</related-to> + <related-link>https://aai-app-e2e.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/c980a6ef-3b88-49f0-9751-dbad8608d0a6/</related-link> + <relationship-data> + <relationship-key>vpn-binding.vpn-id</relationship-key> + <relationship-value>c980a6ef-3b88-49f0-9751-dbad8608d0a6</relationship-value> + </relationship-data> + </relationship> + <relationship> + <related-to>tenant</related-to> + <related-link>https://aai-app-e2e.test.com:8443/aai/v8/cloud-infrastructure/tenants/tenant/7dd5365547234ee8937416c65507d266/</related-link> + <relationship-data> + <relationship-key>tenant.tenant-id</relationship-key> + <relationship-value>7dd5365547234ee8937416c65507d266</relationship-value> + </relationship-data> + </relationship> + <relationship> + <related-to>network-policy</related-to> + <related-link>https://aai-app-e2e.test.com:8443/aai/v8/network/network-policies/network-policy/cee6d136-e378-4678-a024-2cd15f0ee0cg</related-link> + <relationship-data> + <relationship-key>network-policy.network-policy-id</relationship-key> + <relationship-value>cee6d136-e378-4678-a024-2cd15f0ee0cg</relationship-value> + </relationship-data> + </relationship> + <relationship> + <related-to>route-table-reference</related-to> + <related-link>https://aai-app-e2e.test.com:8443/aai/v8/network/route-table-references/route-table-reference/refFQDN1</related-link> + <relationship-data> + <relationship-key>route-table-reference.route-table-reference-id</relationship-key> + <relationship-value>cee6d136-e378-4678-a024-2cd15f0ee0hi</relationship-value> + </relationship-data> + </relationship> + <relationship> + <related-to>route-table-reference</related-to> + <related-link>https://aai-app-e2e.test.com:8443/aai/v8/network/route-table-references/route-table-reference/refFQDN2</related-link> + <relationship-data> + <relationship-key>route-table-reference.route-table-reference-id</relationship-key> + <relationship-value>cee6d136-e378-4678-a024-2cd15f0ee0hi</relationship-value> + </relationship-data> + </relationship> + </relationship-list> + </l3-network> + </rest:payload> +</rest:RESTResponse>""" + +String queryIdAIIResponse_Ipv4 = +"""<rest:RESTResponse xmlns:rest="http://schemas.activebpel.org/REST/2007/12/01/aeREST.xsd" + statusCode="200"> + <rest:headers> + <rest:header name="Transfer-Encoding" value="chunked"/> + <rest:header name="Date" value="Thu,10 Mar 2016 00:01:18 GMT"/> + <rest:header name="Expires" value="Thu,01 Jan 1970 00:00:00 UTC"/> + <rest:header name="X-AAI-TXID" value="mtcnjv9aaas03-20160310-00:01:18:502-132671"/> + <rest:header name="Content-Type" value="application/xml"/> + <rest:header name="Server" value="Apache-Coyote/1.1"/> + <rest:header name="Cache-Control" value="private"/> + </rest:headers> + <rest:payload contentType="text/xml"> + <l3-network xmlns="http://org.openecomp.aai.inventory/v6"> + <network-id>49c86598-f766-46f8-84f8-8d1c1b10f9b4</network-id> + <network-name>MNS-25180-L-01-dmz_direct_net_1</network-name> + <network-type>CONTRAIL_EXTERNAL</network-type> + <network-role>dmz_direct</network-role> + <network-technology>Contrail</network-technology> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <network-role-instance>0</network-role-instance> + <resource-version>l3-version</resource-version> + <orchestration-status>pending-create</orchestration-status> + <physical-network-name>networkName</physical-network-name> + <is-provider-network>false</is-provider-network> + <is-shared-network>true</is-shared-network> + <is-external-network>false</is-external-network> + <subnets> + <subnet> + <subnet-id>57e9a1ff-d14f-4071-a828-b19ae98eb2fc</subnet-id> + <gateway-address>107.239.52.1</gateway-address> + <network-start-address>107.239.52.0</network-start-address> + <cidr-mask>24</cidr-mask> + <ip-version>ipv4</ip-version> + <orchestration-status>pending-create</orchestration-status> + <dhcp-enabled>true</dhcp-enabled> + <subnet-name>subnetName</subnet-name> + <relationship-list/> + </subnet> + <subnet> + <subnet-id>57e9a1ff-d14f-4071-a828-b19ae98eb2fc</subnet-id> + <gateway-address>107.239.52.1</gateway-address> + <network-start-address>107.239.52.0</network-start-address> + <cidr-mask>24</cidr-mask> + <ip-version>ipv4</ip-version> + <orchestration-status>pending-create</orchestration-status> + <dhcp-enabled>true</dhcp-enabled> + <subnet-name>subnetName</subnet-name> + <relationship-list/> + </subnet> + </subnets> + <segmentation-assignments> + <segmentation-id>414</segmentation-id> + <resource-version>4132176</resource-version> + </segmentation-assignments> + <segmentation-assignments> + <segmentation-id>415</segmentation-id> + <resource-version>4132176</resource-version> + </segmentation-assignments> + <ctag-assignments> + <ctag-assignment> + <vlan-id-inner>inner</vlan-id-inner> + <resource-version>ctag-version</resource-version> + <relationship-list> + <relationship> + <related-to>tenant</related-to> + <related-link>https://aai-ext1.test.com:8443/aai/v8/cloud-infrastructure/tenants/tenant/897deadc2b954a6bac6d3c197fb3525e/</related-link> + <relationship-data> + <relationship-key>tenant.tenant-id</relationship-key> + <relationship-value>897deadc2b954a6bac6d3c197fb3525e</relationship-value> + </relationship-data> + <related-to-property> + <property-key>tenant.tenant-name</property-key> + <property-value>MSOTest1</property-value> + </related-to-property> + </relationship> + <relationship> + <related-to>vpn-binding</related-to> + <related-link>https://aai-ext1.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/a290b841-f672-44dd-b9cd-6f8c20d7d8c8/</related-link> + <relationship-data> + <relationship-key>vpn-binding.vpn-id</relationship-key> + <relationship-value>a290b841-f672-44dd-b9cd-6f8c20d7d8c8</relationship-value> + </relationship-data> + <related-to-property> + <property-key>vpn-binding.vpn-name</property-key> + <property-value>oam_protected_net_6_MTN5_msotest2</property-value> + </related-to-property> + </relationship> + <relationship> + <related-to>vpn-binding</related-to> + <related-link>https://aai-ext1.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/24a4b507-853a-4a38-99aa-05fcc54be24d/</related-link> + <relationship-data> + <relationship-key>vpn-binding.vpn-id</relationship-key> + <relationship-value>24a4b507-853a-4a38-99aa-05fcc54be24d</relationship-value> + </relationship-data> + <related-to-property> + <property-key>vpn-binding.vpn-name</property-key> + <property-value>oam_protected_net_6_MTN5_msotest1</property-value> + </related-to-property> + </relationship> + </relationship-list> + </ctag-assignment> + </ctag-assignments> + <relationship-list> + <relationship> + <related-to>vpn-binding</related-to> + <related-link>https://aai-app-e2e.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/85f015d0-2e32-4c30-96d2-87a1a27f8017/</related-link> + <relationship-data> + <relationship-key>vpn-binding.vpn-id</relationship-key> + <relationship-value>85f015d0-2e32-4c30-96d2-87a1a27f8017</relationship-value> + </relationship-data> + </relationship> + <relationship> + <related-to>vpn-binding</related-to> + <related-link>https://aai-app-e2e.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/c980a6ef-3b88-49f0-9751-dbad8608d0a6/</related-link> + <relationship-data> + <relationship-key>vpn-binding.vpn-id</relationship-key> + <relationship-value>c980a6ef-3b88-49f0-9751-dbad8608d0a6</relationship-value> + </relationship-data> + </relationship> + <relationship> + <related-to>tenant</related-to> + <related-link>https://aai-app-e2e.test.com:8443/aai/v8/cloud-infrastructure/tenants/tenant/7dd5365547234ee8937416c65507d266/</related-link> + <relationship-data> + <relationship-key>tenant.tenant-id</relationship-key> + <relationship-value>7dd5365547234ee8937416c65507d266</relationship-value> + </relationship-data> + </relationship> + <relationship> + <related-to>network-policy</related-to> + <related-link>https://aai-app-e2e.test.com:8443/aai/v8/network/network-policies/network-policy/cee6d136-e378-4678-a024-2cd15f0ee0cg</related-link> + <relationship-data> + <relationship-key>network-policy.network-policy-id</relationship-key> + <relationship-value>cee6d136-e378-4678-a024-2cd15f0ee0cg</relationship-value> + </relationship-data> + </relationship> + <relationship> + <related-to>route-table-reference</related-to> + <related-link>https://aai-app-e2e.test.com:8443/aai/v8/network/route-table-references/route-table-reference/refFQDN1</related-link> + <relationship-data> + <relationship-key>route-table-reference.route-table-reference-id</relationship-key> + <relationship-value>cee6d136-e378-4678-a024-2cd15f0ee0hi</relationship-value> + </relationship-data> + </relationship> + <relationship> + <related-to>route-table-reference</related-to> + <related-link>https://aai-app-e2e.test.com:8443/aai/v8/network/route-table-references/route-table-reference/refFQDN2</related-link> + <relationship-data> + <relationship-key>route-table-reference.route-table-reference-id</relationship-key> + <relationship-value>cee6d136-e378-4678-a024-2cd15f0ee0hi</relationship-value> + </relationship-data> + </relationship> + </relationship-list> + </l3-network> + </rest:payload> +</rest:RESTResponse>""" + +String queryIdAIIResponse_SRIOV = +"""<?xml version="1.0" encoding="UTF-8"?> +<l3-network xmlns="http://org.openecomp.aai.inventory/v8"> + <network-id>6cb1ae5a-d2db-4eb6-97bf-d52a506a53d8</network-id> + <network-name>MSO_TEST_1702_A_HnportalProviderNetwork.HNPortalPROVIDERNETWORK.SR_IOV_Provider2_1_net_17</network-name> + <network-type>SR_IOV_Provider2_1</network-type> + <network-role>HnportalProviderNetwork.HNPortalPROVIDERNETWORK.SR_IOV_Provider2_1</network-role> + <network-technology>AIC_SR_IOV</network-technology> + <is-bound-to-vpn>false</is-bound-to-vpn> + <service-id/> + <resource-version>1487336177672</resource-version> + <orchestration-status>PendingCreate</orchestration-status> + <persona-model-id>f70d7a32-0ac8-4bd5-a0fb-3c9336540d78</persona-model-id> + <persona-model-version>1.0</persona-model-version> + <physical-network-name>Physnet21</physical-network-name> + <is-provider-network>true</is-provider-network> + <is-shared-network>false</is-shared-network> + <is-external-network>false</is-external-network> + <subnets> + <subnet> + <subnet-id>10437</subnet-id> + <subnet-name>MSO_TEST_1702_A_HnportalProviderNetwork.HNPortalPROVIDERNETWORK.SR_IOV_Provider2_1_net_17_S0</subnet-name> + <gateway-address>192.168.6.1</gateway-address> + <network-start-address>192.168.6.0</network-start-address> + <cidr-mask>26</cidr-mask> + <ip-version>4</ip-version> + <orchestration-status>PendingCreate</orchestration-status> + <dhcp-enabled>true</dhcp-enabled> + <dhcp-start>192.168.6.3</dhcp-start> + <dhcp-end>192.168.6.62</dhcp-end> + <resource-version>1487336177359</resource-version> + </subnet> + </subnets> + <relationship-list> + <relationship> + <related-to>tenant</related-to> + <related-link>https://aai-ext1.test.com:8443/aai/v8/cloud-infrastructure/cloud-regions/cloud-region/att-aic/mtn16/tenants/tenant/6accefef3cb442ff9e644d589fb04107</related-link> + <relationship-data> + <relationship-key>cloud-region.cloud-owner</relationship-key> + <relationship-value>att-aic</relationship-value> + </relationship-data> + <relationship-data> + <relationship-key>cloud-region.cloud-region-id</relationship-key> + <relationship-value>mtn16</relationship-value> + </relationship-data> + <relationship-data> + <relationship-key>tenant.tenant-id</relationship-key> + <relationship-value>6accefef3cb442ff9e644d589fb04107</relationship-value> + </relationship-data> + <related-to-property> + <property-key>tenant.tenant-name</property-key> + <property-value>MSO_TEST_1702_A</property-value> + </related-to-property> + </relationship> + <relationship> + <related-to>cloud-region</related-to> + <related-link>https://aai-ext1.test.com:8443/aai/v8/cloud-infrastructure/cloud-regions/cloud-region/att-aic/mtn16</related-link> + <relationship-data> + <relationship-key>cloud-region.cloud-owner</relationship-key> + <relationship-value>att-aic</relationship-value> + </relationship-data> + <relationship-data> + <relationship-key>cloud-region.cloud-region-id</relationship-key> + <relationship-value>mtn16</relationship-value> + </relationship-data> + <related-to-property> + <property-key>cloud-region.owner-defined-type</property-key> + <property-value>lcp</property-value> + </related-to-property> + </relationship> + <relationship> + <related-to>service-instance</related-to> + <related-link>https://aai-ext1.test.com:8443/aai/v8/business/customers/customer/MSO_1610_ST/service-subscriptions/service-subscription/MSO-dev-service-type/service-instances/service-instance/51d8336b-a993-4afe-a5fc-10b3afbd6560</related-link> + <relationship-data> + <relationship-key>customer.global-customer-id</relationship-key> + <relationship-value>MSO_1610_ST</relationship-value> + </relationship-data> + <relationship-data> + <relationship-key>service-subscription.service-type</relationship-key> + <relationship-value>MSO-dev-service-type</relationship-value> + </relationship-data> + <relationship-data> + <relationship-key>service-instance.service-instance-id</relationship-key> + <relationship-value>51d8336b-a993-4afe-a5fc-10b3afbd6560</relationship-value> + </relationship-data> + <related-to-property> + <property-key>service-instance.service-instance-name</property-key> + <property-value>HnportalProviderNetwork_17</property-value> + </related-to-property> + </relationship> + </relationship-list> +</l3-network>""" + + String queryIdAIIResponseTestScenario01 = + """<?xml version="1.0" encoding="UTF-8"?> +<l3-network xmlns="http://org.openecomp.aai.inventory/v7"> + <network-id>4da55fe4-7a9e-478c-a434-8a98d62265ab</network-id> + <network-name>GN_EVPN_direct_net_0_ST1</network-name> + <network-type>CONTRAIL30_BASIC</network-type> + <network-role>GN_EVPN_direct</network-role> + <network-technology>contrail</network-technology> + <is-bound-to-vpn>false</is-bound-to-vpn> + <service-id>9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <network-role-instance>0</network-role-instance> + <resource-version>1465398611</resource-version> + <orchestration-status>pending-create</orchestration-status> + <physical-network-name>networkName</physical-network-name> + <is-provider-network>false</is-provider-network> + <is-shared-network>true</is-shared-network> + <is-external-network>false</is-external-network> + <subnets> + <subnet> + <subnet-id>cb1a7b47-5428-44c9-89c2-8b17541c3228</subnet-id> + <gateway-address>108.239.40.1</gateway-address> + <network-start-address>108.239.40.0</network-start-address> + <cidr-mask>28</cidr-mask> + <ip-version>4</ip-version> + <orchestration-status>pending-create</orchestration-status> + <dhcp-enabled>true</dhcp-enabled> + <dhcp-start>108.239.40.0</dhcp-start> + <dhcp-end>108.239.40.0</dhcp-end> + <resource-version>1465398611</resource-version> + <subnet-name>subnetName</subnet-name> + <relationship-list /> + </subnet> + <subnet> + <subnet-id>e2cc7c14-90f0-4205-840d-b4e07f04e621</subnet-id> + <gateway-address>2606:ae00:2e01:604::1</gateway-address> + <network-start-address>2606:ae00:2e01:604::</network-start-address> + <cidr-mask>64</cidr-mask> + <ip-version>6</ip-version> + <orchestration-status>pending-create</orchestration-status> + <dhcp-enabled>true</dhcp-enabled> + <dhcp-start>2606:ae00:2e01:604::</dhcp-start> + <dhcp-end>2606:ae00:2e01:604::</dhcp-end> + <resource-version>1465398611</resource-version> + <subnet-name>subnetName</subnet-name> + <relationship-list /> + </subnet> + </subnets> + <ctag-assignments /> + <segmentation-assignments> + <segmentation-id>416</segmentation-id> + <resource-version>4132176</resource-version> + </segmentation-assignments> + <relationship-list> + <relationship> + <related-to>cloud-region</related-to> + <related-link>https://localhost:8443/aai/v8/cloud-infrastructure/cloud-regions/cloud-region/att-aic/AAIAIC25/ + </related-link> + <relationship-data> + <relationship-key>cloud-region.cloud-region-id</relationship-key> + <relationship-value>AAIAIC25</relationship-value> + </relationship-data> + <relationship-data> + <relationship-key>cloud-region.cloud-owner</relationship-key> + <relationship-value>att-aic</relationship-value> + </relationship-data> + <related-to-property> + <property-key>cloud-region.owner-defined-type</property-key> + <property-value></property-value> + </related-to-property> + </relationship> + <relationship> + <related-to>tenant</related-to> + <related-link>https://localhost:8443/aai/v8/cloud-infrastructure/cloud-regions/cloud-region/att-aic/AAIAIC25/tenants/tenant/4ae1d3446a4c48b2bec44b6cfba06d68/</related-link> + <relationship-data> + <relationship-key>tenant.tenant-id</relationship-key> + <relationship-value>4ae1d3446a4c48b2bec44b6cfba06d68 + </relationship-value> + </relationship-data> + <relationship-data> + <relationship-key>cloud-region.cloud-owner</relationship-key> + <relationship-value>att-aic</relationship-value> + </relationship-data> + <relationship-data> + <relationship-key>cloud-region.cloud-region-id</relationship-key> + <relationship-value>AAIAIC25</relationship-value> + </relationship-data> + <related-to-property> + <property-key>tenant.tenant-name</property-key> + <property-value>Ruchira Contrail 3.0 test</property-value> + </related-to-property> + </relationship> + <relationship> + <related-to>vpn-binding</related-to> + <related-link>https://localhost:8443/aai/v8/network/vpn-bindings/vpn-binding/85f015d0-2e32-4c30-96d2-87a1a27f8017/</related-link> + <relationship-data> + <relationship-key>vpn-binding.vpn-id</relationship-key> + <relationship-value>9a7b327d9-287aa00-82c4b0-100001</relationship-value> + </relationship-data> + <related-to-property> + <property-key>vpn-binding.vpn-name</property-key> + <property-value>GN_EVPN_direct_net_0_ST1</property-value> + </related-to-property> + </relationship> + <relationship> + <related-to>route-table-reference</related-to> + <related-link>https://aai-app-e2e.test.com:8443/aai/v8/network/route-table-references/route-table-reference/refFQDN1</related-link> + <relationship-data> + <relationship-key>route-table-reference.route-table-reference-id</relationship-key> + <relationship-value>cee6d136-e378-4678-a024-2cd15f0ee0hi</relationship-value> + </relationship-data> + </relationship> + <relationship> + <related-to>route-table-reference</related-to> + <related-link>https://aai-app-e2e.test.com:8443/aai/v8/network/route-table-references/route-table-reference/refFQDN2</related-link> + <relationship-data> + <relationship-key>route-table-reference.route-table-reference-id</relationship-key> + <relationship-value>cee6d136-e378-4678-a024-2cd15f0ee0hi</relationship-value> + </relationship-data> + </relationship> + </relationship-list> +</l3-network>""" + + String queryIdAIIResponseVpnNotPresent = + """<rest:RESTResponse xmlns:rest="http://schemas.activebpel.org/REST/2007/12/01/aeREST.xsd" + statusCode="200"> + <rest:headers> + <rest:header name="Transfer-Encoding" value="chunked"/> + <rest:header name="Date" value="Thu,10 Mar 2016 00:01:18 GMT"/> + <rest:header name="Expires" value="Thu,01 Jan 1970 00:00:00 UTC"/> + <rest:header name="X-AAI-TXID" value="mtcnjv9aaas03-20160310-00:01:18:502-132671"/> + <rest:header name="Content-Type" value="application/xml"/> + <rest:header name="Server" value="Apache-Coyote/1.1"/> + <rest:header name="Cache-Control" value="private"/> + </rest:headers> + <rest:payload contentType="text/xml"> + <l3-network xmlns="http://org.openecomp.aai.inventory/v8"> + <network-id>49c86598-f766-46f8-84f8-8d1c1b10f9b4</network-id> + <network-name>MNS-25180-L-01-dmz_direct_net_1</network-name> + <network-type>CONTRAIL_EXTERNAL</network-type> + <network-role>dmz_direct</network-role> + <network-technology>contrail</network-technology> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <network-role-instance>0</network-role-instance> + <orchestration-status>pending-create</orchestration-status> + <physical-network-name>networkName</physical-network-name> + <is-provider-network>false</is-provider-network> + <is-shared-network>true</is-shared-network> + <is-external-network>false</is-external-network> + <subnets> + <subnet> + <subnet-id>57e9a1ff-d14f-4071-a828-b19ae98eb2fc</subnet-id> + <gateway-address>107.239.52.1</gateway-address> + <network-start-address>107.239.52.0</network-start-address> + <cidr-mask>24</cidr-mask> + <ip-version>4</ip-version> + <orchestration-status>pending-create</orchestration-status> + <dhcp-enabled>true</dhcp-enabled> + <subnet-name>subnetName</subnet-name> + <relationship-list/> + </subnet> + </subnets> + <relationship-list/> + </l3-network> + </rest:payload> +</rest:RESTResponse>""" + + String queryNameAIIResponse = + """<rest:RESTResponse xmlns:rest="http://schemas.activebpel.org/REST/2007/12/01/aeREST.xsd" + statusCode="200"> + <rest:headers> + <rest:header name="Transfer-Encoding" value="chunked"/> + <rest:header name="Date" value="Thu,10 Mar 2016 00:01:18 GMT"/> + <rest:header name="Expires" value="Thu,01 Jan 1970 00:00:00 UTC"/> + <rest:header name="X-AAI-TXID" value="mtcnjv9aaas03-20160310-00:01:18:502-132671"/> + <rest:header name="Content-Type" value="application/xml"/> + <rest:header name="Server" value="Apache-Coyote/1.1"/> + <rest:header name="Cache-Control" value="private"/> + </rest:headers> + <rest:payload contentType="text/xml"> + <l3-network xmlns="http://org.openecomp.aai.inventory/v6"> + <network-id>49c86598-f766-46f8-84f8-8d1c1b10f9b4</network-id> + <network-name>MNS-25180-L-01-dmz_direct_net_1</network-name> + <network-type>CONTRAIL_EXTERNAL</network-type> + <network-role>dmz_direct</network-role> + <network-technology>contrail</network-technology> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <network-role-instance>0</network-role-instance> + <orchestration-status>pending-create</orchestration-status> + <subnets> + <subnet> + <subnet-id>57e9a1ff-d14f-4071-a828-b19ae98eb2fc</subnet-id> + <gateway-address>107.239.52.1</gateway-address> + <network-start-address>107.239.52.0</network-start-address> + <cidr-mask>24</cidr-mask> + <ip-version>4</ip-version> + <orchestration-status>pending-create</orchestration-status> + <dhcp-enabled>true</dhcp-enabled> + <relationship-list/> + </subnet> + </subnets> + <relationship-list> + <relationship> + <related-to>vpn-binding</related-to> + <related-link>https://aai-app-e2e.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/85f015d0-2e32-4c30-96d2-87a1a27f8017/</related-link> + <relationship-data> + <relationship-key>vpn-binding.vpn-id</relationship-key> + <relationship-value>85f015d0-2e32-4c30-96d2-87a1a27f8017</relationship-value> + </relationship-data> + </relationship> + <relationship> + <related-to>vpn-binding</related-to> + <related-link>https://aai-app-e2e.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/c980a6ef-3b88-49f0-9751-dbad8608d0a6/</related-link> + <relationship-data> + <relationship-key>vpn-binding.vpn-id</relationship-key> + <relationship-value>c980a6ef-3b88-49f0-9751-dbad8608d0a6</relationship-value> + </relationship-data> + </relationship> + <relationship> + <related-to>tenant</related-to> + <related-link>https://aai-app-e2e.test.com:8443/aai/v8/cloud-infrastructure/tenants/tenant/7dd5365547234ee8937416c65507d266/</related-link> + <relationship-data> + <relationship-key>tenant.tenant-id</relationship-key> + <relationship-value>7dd5365547234ee8937416c65507d266</relationship-value> + </relationship-data> + </relationship> + </relationship-list> + </l3-network> + </rest:payload> + </rest:RESTResponse>""" + + String queryNameAIIResponseVpnNotPresent = + """<rest:RESTResponse xmlns:rest="http://schemas.activebpel.org/REST/2007/12/01/aeREST.xsd" + statusCode="200"> + <rest:headers> + <rest:header name="Transfer-Encoding" value="chunked"/> + <rest:header name="Date" value="Thu,10 Mar 2016 00:01:18 GMT"/> + <rest:header name="Expires" value="Thu,01 Jan 1970 00:00:00 UTC"/> + <rest:header name="X-AAI-TXID" value="mtcnjv9aaas03-20160310-00:01:18:502-132671"/> + <rest:header name="Content-Type" value="application/xml"/> + <rest:header name="Server" value="Apache-Coyote/1.1"/> + <rest:header name="Cache-Control" value="private"/> + </rest:headers> + <rest:payload contentType="text/xml"> + <l3-network xmlns="http://org.openecomp.aai.inventory/v6> + <network-id>49c86598-f766-46f8-84f8-8d1c1b10f9b4</network-id> + <network-name>MNS-25180-L-01-dmz_direct_net_1</network-name> + <network-type>CONTRAIL_EXTERNAL</network-type> + <network-role>dmz_direct</network-role> + <network-technology>contrail</network-technology> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <network-role-instance>0</network-role-instance> + <orchestration-status>pending-create</orchestration-status> + <subnets> + <subnet> + <subnet-id>57e9a1ff-d14f-4071-a828-b19ae98eb2fc</subnet-id> + <gateway-address>107.239.52.1</gateway-address> + <network-start-address>107.239.52.0</network-start-address> + <cidr-mask>24</cidr-mask> + <ip-version>4</ip-version> + <orchestration-status>pending-create</orchestration-status> + <dhcp-enabled>true</dhcp-enabled> + <relationship-list/> + </subnet> + </subnets> + </l3-network> + </rest:payload> + </rest:RESTResponse>""" + + String aaiVpnResponseStub = + """<rest:payload xmlns:rest="http://schemas.activebpel.org/REST/2007/12/01/aeREST.xsd" + xmlns="http://org.openecomp.aai.inventory/v8" + contentType="text/xml"> + <vpn-binding> + <global-route-target/> + </vpn-binding> +</rest:payload>""" + + String queryVpnBindingAAIResponse = + """<rest:RESTResponse xmlns:rest="http://schemas.activebpel.org/REST/2007/12/01/aeREST.xsd" + statusCode="200"> + <rest:headers> + <rest:header name="Transfer-Encoding" value="chunked"/> + <rest:header name="Date" value="Mon,14 Mar 2016 20:53:33 GMT"/> + <rest:header name="Expires" value="Thu,01 Jan 1970 00:00:00 UTC"/> + <rest:header name="X-AAI-TXID" + value="localhost-20160314-20:53:33:487-134392"/> + <rest:header name="Content-Type" value="application/xml"/> + <rest:header name="Server" value="Apache-Coyote/1.1"/> + <rest:header name="Cache-Control" value="private"/> + </rest:headers> + <rest:payload contentType="text/xml"> + <vpn-binding xmlns="http://org.openecomp.aai.inventory/v6"> + <vpn-id>9a7b327d9-287aa00-82c4b0-105757</vpn-id> + <vpn-name>GN_EVPN_Test</vpn-name> + <global-route-target>13979:105757</global-route-target> + <relationship-list> + <relationship> + <related-to>l3-network</related-to> + <related-link>https://aai-app-e2e.test.com:8443/aai/v3/network/l3-networks/l3-network/689ec39e-c5fc-4462-8db2-4f760763ad28/</related-link> + <relationship-data> + <relationship-key>l3-network.network-id</relationship-key> + <relationship-value>689ec39e-c5fc-4462-8db2-4f760763ad28</relationship-value> + </relationship-data> + </relationship> + <relationship> + <related-to>l3-network</related-to> + <related-link>https://aai-app-e2e.test.com:8443/aai/v3/network/l3-networks/l3-network/1a49396b-19b3-40a4-8792-aa2fbd0f0704/</related-link> + <relationship-data> + <relationship-key>l3-network.network-id</relationship-key> + <relationship-value>1a49396b-19b3-40a4-8792-aa2fbd0f0704</relationship-value> + </relationship-data> + </relationship> + <relationship> + <related-to>l3-network</related-to> + <related-link>https://aai-app-e2e.test.com:8443/aai/v3/network/l3-networks/l3-network/774f3329-3c83-4771-86c7-9e6207cd50fd/</related-link> + <relationship-data> + <relationship-key>l3-network.network-id</relationship-key> + <relationship-value>774f3329-3c83-4771-86c7-9e6207cd50fd</relationship-value> + </relationship-data> + </relationship> + </relationship-list> + </vpn-binding> + </rest:payload> +</rest:RESTResponse>""" + + String createDBRequestError01 = + """<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"> + <soapenv:Header/> + <soapenv:Body> + <ns:updateInfraRequest xmlns:ns="http://org.onap.so/requestsdb"> + <requestId>88f65519-9a38-4c4b-8445-9eb4a5a5af56</requestId> + <lastModifiedBy>BPMN</lastModifiedBy> + <statusMessage>Received error unexpectedly from SDN-C.</statusMessage> + <responseBody></responseBody> + <requestStatus>FAILED</requestStatus> + <vnfOutputs><network-id></network-id><network-name></network-names></vnfOutputs> + </ns:updateInfraRequest> + </soapenv:Body> + </soapenv:Envelope>""" + + String createDBRequest_Outputs = + """<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" + xmlns:ns="http://org.onap.so/requestsdb"> + <soapenv:Header/> + <soapenv:Body> + <ns:updateInfraRequest> + <requestId>88f65519-9a38-4c4b-8445-9eb4a5a5af56</requestId> + <lastModifiedBy>BPMN</lastModifiedBy> + <statusMessage>Network successfully created.</statusMessage> + <responseBody/> + <requestStatus>COMPLETED</requestStatus> + <progress>100</progress> + <vnfOutputs><network-id>networkId</network-id><network-name>MNS-25180-L-01-dmz_direct_net_1</network-names></vnfOutputs> + <networkId>networkId</networkId> + </ns:updateInfraRequest> + </soapenv:Body> +</soapenv:Envelope>""" + + String createNetworkRequest = + """<createNetworkRequest> + <cloudSiteId>RDM2WAGPLCP</cloudSiteId> + <tenantId>7dd5365547234ee8937416c65507d266</tenantId> + <networkId>49c86598-f766-46f8-84f8-8d1c1b10f9b4</networkId> + <networkName>MNS-25180-L-01-dmz_direct_net_1</networkName> + <networkType>CONTRAIL_EXTERNAL</networkType> + <modelCustomizationUuid>sn5256d1-5a33-55df-13ab-12abad84e222</modelCustomizationUuid> + <networkTechnology>CONTRAIL</networkTechnology> + <providerVlanNetwork> + <physicalNetworkName>networkName</physicalNetworkName> + <vlans>414,415</vlans> + </providerVlanNetwork> + <contrailNetwork> + <shared>true</shared> + <external>false</external> + <routeTargets>13979:105757</routeTargets> + <routeTargets>13979:105757</routeTargets> + <policyFqdns>GN_EVPN_Test</policyFqdns> + <routeTableFqdns>refFQDN1</routeTableFqdns> + <routeTableFqdns>refFQDN2</routeTableFqdns> + </contrailNetwork> + <subnets> + <allocationPools> + <start/> + <end/> + </allocationPools> + <cidr>107.239.52.0/24</cidr> + <enableDHCP>true</enableDHCP> + <gatewayIp>107.239.52.1</gatewayIp> + <ipVersion>4</ipVersion> + <subnetId>57e9a1ff-d14f-4071-a828-b19ae98eb2fc</subnetId> + <subnetName>subnetName</subnetName> + <addrFromStart>true</addrFromStart> + <hostRoutes> + <prefix>192.10.16.0/24</prefix> + <nextHop>192.10.16.100/24</nextHop> + </hostRoutes> + <hostRoutes> + <prefix>192.110.17.0/24</prefix> + <nextHop>192.110.17.110/24</nextHop> + </hostRoutes> + </subnets> + <subnets> + <allocationPools> + <start/> + <end/> + </allocationPools> + <cidr>107.239.52.0/24</cidr> + <enableDHCP>true</enableDHCP> + <gatewayIp>107.239.52.1</gatewayIp> + <ipVersion>4</ipVersion> + <subnetId>57e9a1ff-d14f-4071-a828-b19ae98eb2fc</subnetId> + <subnetName>subnetName</subnetName> + <addrFromStart>true</addrFromStart> + <hostRoutes> + <prefix>192.10.16.0/24</prefix> + <nextHop>192.10.16.100/24</nextHop> + </hostRoutes> + </subnets> + <skipAAI>true</skipAAI> + <backout>true</backout> + <failIfExists>false</failIfExists> + <msoRequest> + <requestId>88f65519-9a38-4c4b-8445-9eb4a5a5af56</requestId> + <serviceInstanceId>f70e927b-6087-4974-9ef8-c5e4d5847ca4</serviceInstanceId> + </msoRequest> + <messageId>messageId_generated</messageId> + <notificationUrl/> +</createNetworkRequest>""" + +String createNetworkRequest_Ipv4 = +"""<createNetworkRequest> + <cloudSiteId>RDM2WAGPLCP</cloudSiteId> + <tenantId>7dd5365547234ee8937416c65507d266</tenantId> + <networkId>49c86598-f766-46f8-84f8-8d1c1b10f9b4</networkId> + <networkName>MNS-25180-L-01-dmz_direct_net_1</networkName> + <networkType>CONTRAIL_EXTERNAL</networkType> + <modelCustomizationUuid>sn5256d1-5a33-55df-13ab-12abad84e222</modelCustomizationUuid> + <networkTechnology>CONTRAIL</networkTechnology> + <providerVlanNetwork> + <physicalNetworkName>networkName</physicalNetworkName> + <vlans>414,415</vlans> + </providerVlanNetwork> + <contrailNetwork> + <shared>true</shared> + <external>false</external> + <routeTargets>13979:105757</routeTargets> + <routeTargets>13979:105757</routeTargets> + <policyFqdns>GN_EVPN_Test</policyFqdns> + <routeTableFqdns>refFQDN1</routeTableFqdns> + <routeTableFqdns>refFQDN2</routeTableFqdns> + </contrailNetwork> + <subnets> + <allocationPools> + <start/> + <end/> + </allocationPools> + <cidr>107.239.52.0/24</cidr> + <enableDHCP>true</enableDHCP> + <gatewayIp>107.239.52.1</gatewayIp> + <ipVersion>4</ipVersion> + <subnetId>57e9a1ff-d14f-4071-a828-b19ae98eb2fc</subnetId> + <subnetName>subnetName</subnetName> + </subnets> + <subnets> + <allocationPools> + <start/> + <end/> + </allocationPools> + <cidr>107.239.52.0/24</cidr> + <enableDHCP>true</enableDHCP> + <gatewayIp>107.239.52.1</gatewayIp> + <ipVersion>4</ipVersion> + <subnetId>57e9a1ff-d14f-4071-a828-b19ae98eb2fc</subnetId> + <subnetName>subnetName</subnetName> + </subnets> + <skipAAI>true</skipAAI> + <backout>true</backout> + <failIfExists>false</failIfExists> + <msoRequest> + <requestId>88f65519-9a38-4c4b-8445-9eb4a5a5af56</requestId> + <serviceInstanceId>f70e927b-6087-4974-9ef8-c5e4d5847ca4</serviceInstanceId> + </msoRequest> + <messageId>messageId_generated</messageId> + <notificationUrl/> +</createNetworkRequest>""" + +String createNetworkRequestAlaCarte = +"""<createNetworkRequest> + <cloudSiteId>RDM2WAGPLCP</cloudSiteId> + <tenantId>7dd5365547234ee8937416c65507d266</tenantId> + <networkId>49c86598-f766-46f8-84f8-8d1c1b10f9b4</networkId> + <networkName>MNS-25180-L-01-dmz_direct_net_1</networkName> + <networkType>CONTRAIL_EXTERNAL</networkType> + <modelCustomizationUuid>f21df226-8093-48c3-be7e-0408fcda0422</modelCustomizationUuid> + <networkTechnology>CONTRAIL</networkTechnology> + <providerVlanNetwork> + <physicalNetworkName>networkName</physicalNetworkName> + <vlans>414,415</vlans> + </providerVlanNetwork> + <contrailNetwork> + <shared>true</shared> + <external>false</external> + <routeTargets>13979:105757</routeTargets> + <routeTargets>13979:105757</routeTargets> + <policyFqdns>GN_EVPN_Test</policyFqdns> + <routeTableFqdns>refFQDN1</routeTableFqdns> + <routeTableFqdns>refFQDN2</routeTableFqdns> + </contrailNetwork> + <subnets> + <allocationPools> + <start/> + <end/> + </allocationPools> + <cidr>107.239.52.0/24</cidr> + <enableDHCP>true</enableDHCP> + <gatewayIp>107.239.52.1</gatewayIp> + <ipVersion>4</ipVersion> + <subnetId>57e9a1ff-d14f-4071-a828-b19ae98eb2fc</subnetId> + <subnetName>subnetName</subnetName> + </subnets> + <subnets> + <allocationPools> + <start/> + <end/> + </allocationPools> + <cidr>107.239.52.0/24</cidr> + <enableDHCP>true</enableDHCP> + <gatewayIp>107.239.52.1</gatewayIp> + <ipVersion>4</ipVersion> + <subnetId>57e9a1ff-d14f-4071-a828-b19ae98eb2fc</subnetId> + <subnetName>subnetName</subnetName> + </subnets> + <skipAAI>true</skipAAI> + <backout>true</backout> + <failIfExists>false</failIfExists> + <networkParams> + <some_user_param1>someValue1</some_user_param1> + </networkParams> + <msoRequest> + <requestId>88f65519-9a38-4c4b-8445-9eb4a5a5af56</requestId> + <serviceInstanceId>f70e927b-6087-4974-9ef8-c5e4d5847ca4</serviceInstanceId> + </msoRequest> + <messageId>messageId_generated</messageId> + <notificationUrl/> +</createNetworkRequest>""" + +String createNetworkRequest_SRIOV = +"""<createNetworkRequest> + <cloudSiteId>RDM2WAGPLCP</cloudSiteId> + <tenantId>7dd5365547234ee8937416c65507d266</tenantId> + <networkId>6cb1ae5a-d2db-4eb6-97bf-d52a506a53d8</networkId> + <networkName>MSO_TEST_1702_A_HnportalProviderNetwork.HNPortalPROVIDERNETWORK.SR_IOV_Provider2_1_net_17</networkName> + <networkType>CONTRAIL_EXTERNAL</networkType> + <modelCustomizationUuid>sn5256d1-5a33-55df-13ab-12abad84e222</modelCustomizationUuid> + <networkTechnology>AIC_SR_IOV</networkTechnology> + <providerVlanNetwork> + <physicalNetworkName>Physnet21</physicalNetworkName> + <vlans/> + </providerVlanNetwork> + <subnets> + <allocationPools> + <start>192.168.6.3</start> + <end>192.168.6.62</end> + </allocationPools> + <cidr>192.168.6.0/26</cidr> + <enableDHCP>true</enableDHCP> + <gatewayIp>192.168.6.1</gatewayIp> + <ipVersion>4</ipVersion> + <subnetId>10437</subnetId> + <subnetName>MSO_TEST_1702_A_HnportalProviderNetwork.HNPortalPROVIDERNETWORK.SR_IOV_Provider2_1_net_17_S0</subnetName> + </subnets> + <skipAAI>true</skipAAI> + <backout>true</backout> + <failIfExists>false</failIfExists> + <msoRequest> + <requestId>88f65519-9a38-4c4b-8445-9eb4a5a5af56</requestId> + <serviceInstanceId>f70e927b-6087-4974-9ef8-c5e4d5847ca4</serviceInstanceId> + </msoRequest> + <messageId>messageId_generated</messageId> + <notificationUrl/> +</createNetworkRequest>""" + + String createNetworkRequest_noPhysicalName = + """<createNetworkRequest> + <cloudSiteId>RDM2WAGPLCP</cloudSiteId> + <tenantId>7dd5365547234ee8937416c65507d266</tenantId> + <networkId>49c86598-f766-46f8-84f8-8d1c1b10f9b4</networkId> + <networkName>MNS-25180-L-01-dmz_direct_net_1</networkName> + <networkType>CONTRAIL_EXTERNAL</networkType> + <networkTechnology>CONTRAIL</networkTechnology> + <providerVlanNetwork> + <physicalNetworkName>networkName</physicalNetworkName> + <vlans>414,415</vlans> + </providerVlanNetwork> + <contrailNetwork> + <shared>true</shared> + <external>false</external> + <routeTargets>13979:105757</routeTargets> + <routeTargets>13979:105757</routeTargets> + <policyFqdns>GN_EVPN_Test</policyFqdns> + </contrailNetwork> + <subnets> + <allocationPools> + <start/> + <end/> + </allocationPools> + <cidr>107.239.52.0/24</cidr> + <enableDHCP>true</enableDHCP> + <gatewayIp>107.239.52.1</gatewayIp> + <ipVersion>4</ipVersion> + <subnetId>57e9a1ff-d14f-4071-a828-b19ae98eb2fc</subnetId> + <subnetName>subnetName</subnetName> + </subnets> + <subnets> + <allocationPools> + <start/> + <end/> + </allocationPools> + <cidr>107.239.52.0/24</cidr> + <enableDHCP>true</enableDHCP> + <gatewayIp>107.239.52.1</gatewayIp> + <ipVersion>4</ipVersion> + <subnetId>57e9a1ff-d14f-4071-a828-b19ae98eb2fc</subnetId> + <subnetName>subnetName</subnetName> + </subnets> + <skipAAI>true</skipAAI> + <backout>true</backout> + <failIfExists>false</failIfExists> + <networkParams> + <dhcp-enabled>true</dhcp-enabled> + <serviceId>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</serviceId> + <cidr-mask>true</cidr-mask> + <backoutOnFailure>true</backoutOnFailure> + <gateway-address>10.10.125.1</gateway-address> + </networkParams> + <msoRequest> + <requestId>88f65519-9a38-4c4b-8445-9eb4a5a5af56</requestId> + <serviceInstanceId>null</serviceInstanceId> + </msoRequest> + <messageId>messageId_generated</messageId> + <notificationUrl/> +</createNetworkRequest>""" + + String createNetworkResponseREST = + """<ns2:createNetworkResponse xmlns:ns2="http://org.onap.so/network"> + <networkId>MNS-25180-L-01-dmz_direct_net_1/2c88a3a9-69b9-43a7-ada6-1aca577c3641</networkId> + <neutronNetworkId>c4f4e878-cde0-4b15-ae9a-bda857759cea</neutronNetworkId> + <networkFqdn>default-domain:MSOTest:GN_EVPN_direct_net_0_ST1</networkFqdn> + <networkStackId></networkStackId> + <networkCreated>true</networkCreated> + <subnetMap> + <entry> + <key>57e9a1ff-d14f-4071-a828-b19ae98eb2fc</key> + <value>bd8e87c6-f4e2-41b8-b0bc-9596aa00cd73</value> + </entry> + <entry> + <key>57e9a1ff-d14f-4071-a828-b19ae98eb2fc</key> + <value>bd8e87c6-f4e2-41b8-b0bc-9596aa00cd73</value> + </entry> + </subnetMap> + <rollback> + <networkId>MNS-25180-L-01-dmz_direct_net_1/2c88a3a9-69b9-43a7-ada6-1aca577c3641</networkId> + <neutronNetworkId>c4f4e878-cde0-4b15-ae9a-bda857759cea</neutronNetworkId> + <networkStackId></networkStackId> + <networkType>CONTRAIL_EXTERNAL</networkType> + <networkCreated>true</networkCreated> + <tenantId>7dd5365547234ee8937416c65507d266</tenantId> + <cloudSiteId>RDM2WAGPLCP</cloudSiteId> + <msoRequest> + <requestId>1ef47428-cade-45bd-a103-0751e8b2deb0</requestId> + <serviceInstanceId></serviceInstanceId> + </msoRequest> + </rollback> + <messageId>messageId_generated</messageId> +</ns2:createNetworkResponse>""" + + String createRollbackNetworkRequest = + """<rollbackNetworkRequest> + <networkRollback> + <networkId>MNS-25180-L-01-dmz_direct_net_1/2c88a3a9-69b9-43a7-ada6-1aca577c3641</networkId> + <neutronNetworkId>c4f4e878-cde0-4b15-ae9a-bda857759cea</neutronNetworkId> + <networkStackId/> + <networkType>CONTRAIL_EXTERNAL</networkType> + <networkCreated>true</networkCreated> + <tenantId>7dd5365547234ee8937416c65507d266</tenantId> + <cloudSiteId>RDM2WAGPLCP</cloudSiteId> + <msoRequest> + <requestId>1ef47428-cade-45bd-a103-0751e8b2deb0</requestId> + <serviceInstanceId/> + </msoRequest> + </networkRollback> +</rollbackNetworkRequest>""" + + String createNetworkResponse = + """<ns2:createNetworkResponse xmlns:ns2="http://org.onap.so/network" + xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> + <networkId>MNS-25180-L-01-dmz_direct_net_1/2c88a3a9-69b9-43a7-ada6-1aca577c3641</networkId> + <neutronNetworkId>c4f4e878-cde0-4b15-ae9a-bda857759cea</neutronNetworkId> + <networkStackId>MNS-25180-L-01-dmz_direct_net_1/2c88a3a9-69b9-43a7-ada6-1aca577c3641</networkStackId> + <networkFqdn>default-domain:MSOTest:GN_EVPN_direct_net_0_ST1</networkFqdn> + <subnetIdMap> + <entry> + <key>57e9a1ff-d14f-4071-a828-b19ae98eb2fc</key> + <value>bd8e87c6-f4e2-41b8-b0bc-9596aa00cd73</value> + </entry> + </subnetIdMap> + <rollback> + <cloudId>RDM2WAGPLCP</cloudId> + <msoRequest> + <requestId>1ef47428-cade-45bd-a103-0751e8b2deb0</requestId> + <serviceInstanceId/> + </msoRequest> + <networkCreated>true</networkCreated> + <networkId>MNS-25180-L-01-dmz_direct_net_1/2c88a3a9-69b9-43a7-ada6-1aca577c3641</networkId> + <networkType>CONTRAIL_EXTERNAL</networkType> + <networkUpdated>false</networkUpdated> + <neutronNetworkId>c4f4e878-cde0-4b15-ae9a-bda857759cea</neutronNetworkId> + <tenantId>7dd5365547234ee8937416c65507d266</tenantId> + </rollback> +</ns2:createNetworkResponse>""" + + String updateContrailAAIPayloadRequest = + """<l3-network xmlns="http://org.openecomp.aai.inventory/v9"> + <network-id>49c86598-f766-46f8-84f8-8d1c1b10f9b4</network-id> + <network-name>MNS-25180-L-01-dmz_direct_net_1</network-name> + <network-type>CONTRAIL_EXTERNAL</network-type> + <network-role>dmz_direct</network-role> + <network-technology>Contrail</network-technology> + <neutron-network-id>c4f4e878-cde0-4b15-ae9a-bda857759cea</neutron-network-id> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <network-role-instance>0</network-role-instance> + <resource-version>l3-version</resource-version> + <orchestration-status>Created</orchestration-status> + <contrail-network-fqdn>default-domain:MSOTest:GN_EVPN_direct_net_0_ST1</contrail-network-fqdn> + <physical-network-name>networkName</physical-network-name> + <is-provider-network>false</is-provider-network> + <is-shared-network>true</is-shared-network> + <is-external-network>false</is-external-network> + <subnets> + <subnet> + <subnet-id>57e9a1ff-d14f-4071-a828-b19ae98eb2fc</subnet-id> + <neutron-subnet-id>bd8e87c6-f4e2-41b8-b0bc-9596aa00cd73</neutron-subnet-id> + <gateway-address>107.239.52.1</gateway-address> + <network-start-address>107.239.52.0</network-start-address> + <cidr-mask>24</cidr-mask> + <ip-version>4</ip-version> + <orchestration-status>Created</orchestration-status> + <dhcp-enabled>true</dhcp-enabled> + <subnet-role>ECOMP</subnet-role> + <resource-version>1505857301954</resource-version> + <subnet-name>subnetName</subnet-name> + <ip-assignment-direction>true</ip-assignment-direction> + <host-routes> + <host-route> + <host-route-id>string</host-route-id> + <route-prefix>192.10.16.0/24</route-prefix> + <next-hop>192.10.16.100/24</next-hop> + <next-hop-type>ip-address</next-hop-type> + <resource-version>1505857301954</resource-version> + </host-route> + <host-route> + <host-route-id>string</host-route-id> + <route-prefix>192.110.17.0/24</route-prefix> + <next-hop>192.110.17.110/24</next-hop> + <next-hop-type>ip-address</next-hop-type> + <resource-version>1505857301954</resource-version> + </host-route> + </host-routes> + </subnet> + <subnet> + <subnet-id>57e9a1ff-d14f-4071-a828-b19ae98eb2fc</subnet-id> + <neutron-subnet-id>bd8e87c6-f4e2-41b8-b0bc-9596aa00cd73</neutron-subnet-id> + <gateway-address>107.239.52.1</gateway-address> + <network-start-address>107.239.52.0</network-start-address> + <cidr-mask>24</cidr-mask> + <ip-version>4</ip-version> + <orchestration-status>Created</orchestration-status> + <dhcp-enabled>true</dhcp-enabled> + <resource-version>1505857301954</resource-version> + <subnet-name>subnetName</subnet-name> + <ip-assignment-direction>true</ip-assignment-direction> + <host-routes> + <host-route> + <host-route-id>string</host-route-id> + <route-prefix>192.10.16.0/24</route-prefix> + <next-hop>192.10.16.100/24</next-hop> + <next-hop-type>ip-address</next-hop-type> + <resource-version>1505857301954</resource-version> + </host-route> + </host-routes> + </subnet> + </subnets> + <segmentation-assignments> + <segmentation-id>414</segmentation-id> + <resource-version>4132176</resource-version> + </segmentation-assignments> + <segmentation-assignments> + <segmentation-id>415</segmentation-id> + <resource-version>4132176</resource-version> + </segmentation-assignments> + <ctag-assignments> + <ctag-assignment> + <vlan-id-inner>inner</vlan-id-inner> + <resource-version>ctag-version</resource-version> + <relationship-list> + <relationship> + <related-to>tenant</related-to> + <related-link>https://aai-ext1.test.com:8443/aai/v8/cloud-infrastructure/tenants/tenant/897deadc2b954a6bac6d3c197fb3525e/</related-link> + <relationship-data> + <relationship-key>tenant.tenant-id</relationship-key> + <relationship-value>897deadc2b954a6bac6d3c197fb3525e</relationship-value> + </relationship-data> + <related-to-property> + <property-key>tenant.tenant-name</property-key> + <property-value>MSOTest1</property-value> + </related-to-property> + </relationship> + <relationship> + <related-to>vpn-binding</related-to> + <related-link>https://aai-ext1.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/a290b841-f672-44dd-b9cd-6f8c20d7d8c8/</related-link> + <relationship-data> + <relationship-key>vpn-binding.vpn-id</relationship-key> + <relationship-value>a290b841-f672-44dd-b9cd-6f8c20d7d8c8</relationship-value> + </relationship-data> + <related-to-property> + <property-key>vpn-binding.vpn-name</property-key> + <property-value>oam_protected_net_6_MTN5_msotest2</property-value> + </related-to-property> + </relationship> + <relationship> + <related-to>vpn-binding</related-to> + <related-link>https://aai-ext1.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/24a4b507-853a-4a38-99aa-05fcc54be24d/</related-link> + <relationship-data> + <relationship-key>vpn-binding.vpn-id</relationship-key> + <relationship-value>24a4b507-853a-4a38-99aa-05fcc54be24d</relationship-value> + </relationship-data> + <related-to-property> + <property-key>vpn-binding.vpn-name</property-key> + <property-value>oam_protected_net_6_MTN5_msotest1</property-value> + </related-to-property> + </relationship> + </relationship-list> + </ctag-assignment> + </ctag-assignments> + <relationship-list> + <relationship> + <related-to>vpn-binding</related-to> + <related-link>https://aai-app-e2e.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/85f015d0-2e32-4c30-96d2-87a1a27f8017/</related-link> + <relationship-data> + <relationship-key>vpn-binding.vpn-id</relationship-key> + <relationship-value>85f015d0-2e32-4c30-96d2-87a1a27f8017</relationship-value> + </relationship-data> + </relationship> + <relationship> + <related-to>vpn-binding</related-to> + <related-link>https://aai-app-e2e.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/c980a6ef-3b88-49f0-9751-dbad8608d0a6/</related-link> + <relationship-data> + <relationship-key>vpn-binding.vpn-id</relationship-key> + <relationship-value>c980a6ef-3b88-49f0-9751-dbad8608d0a6</relationship-value> + </relationship-data> + </relationship> + <relationship> + <related-to>tenant</related-to> + <related-link>https://aai-app-e2e.test.com:8443/aai/v8/cloud-infrastructure/tenants/tenant/7dd5365547234ee8937416c65507d266/</related-link> + <relationship-data> + <relationship-key>tenant.tenant-id</relationship-key> + <relationship-value>7dd5365547234ee8937416c65507d266</relationship-value> + </relationship-data> + </relationship> + <relationship> + <related-to>network-policy</related-to> + <related-link>https://aai-app-e2e.test.com:8443/aai/v8/network/network-policies/network-policy/cee6d136-e378-4678-a024-2cd15f0ee0cg</related-link> + <relationship-data> + <relationship-key>network-policy.network-policy-id</relationship-key> + <relationship-value>cee6d136-e378-4678-a024-2cd15f0ee0cg</relationship-value> + </relationship-data> + </relationship> + <relationship> + <related-to>route-table-reference</related-to> + <related-link>https://aai-app-e2e.test.com:8443/aai/v8/network/route-table-references/route-table-reference/refFQDN1</related-link> + <relationship-data> + <relationship-key>route-table-reference.route-table-reference-id</relationship-key> + <relationship-value>cee6d136-e378-4678-a024-2cd15f0ee0hi</relationship-value> + </relationship-data> + </relationship> + <relationship> + <related-to>route-table-reference</related-to> + <related-link>https://aai-app-e2e.test.com:8443/aai/v8/network/route-table-references/route-table-reference/refFQDN2</related-link> + <relationship-data> + <relationship-key>route-table-reference.route-table-reference-id</relationship-key> + <relationship-value>cee6d136-e378-4678-a024-2cd15f0ee0hi</relationship-value> + </relationship-data> + </relationship> + </relationship-list> +</l3-network>""" + +String updateContrailAAIPayloadRequest_segmentation = +"""<l3-network xmlns="http://org.openecomp.aai.inventory/v9"> + <network-id>49c86598-f766-46f8-84f8-8d1c1b10f9b4</network-id> + <network-name>MNS-25180-L-01-dmz_direct_net_1</network-name> + <network-type>CONTRAIL_EXTERNAL</network-type> + <network-role>dmz_direct</network-role> + <network-technology>Contrail</network-technology> + <neutron-network-id>c4f4e878-cde0-4b15-ae9a-bda857759cea</neutron-network-id> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <network-role-instance>0</network-role-instance> + <resource-version>l3-version</resource-version> + <orchestration-status>Created</orchestration-status> + <contrail-network-fqdn>default-domain:MSOTest:GN_EVPN_direct_net_0_ST1</contrail-network-fqdn> + <physical-network-name>networkName</physical-network-name> + <is-provider-network>false</is-provider-network> + <is-shared-network>true</is-shared-network> + <is-external-network>false</is-external-network> + <subnets> + <subnet> + <subnet-id>57e9a1ff-d14f-4071-a828-b19ae98eb2fc</subnet-id> + <neutron-subnet-id>bd8e87c6-f4e2-41b8-b0bc-9596aa00cd73</neutron-subnet-id> + <gateway-address>107.239.52.1</gateway-address> + <network-start-address>107.239.52.0</network-start-address> + <cidr-mask>24</cidr-mask> + <ip-version>4</ip-version> + <orchestration-status>Created</orchestration-status> + <dhcp-enabled>true</dhcp-enabled> + <subnet-name>subnetName</subnet-name> + </subnet> + <subnet> + <subnet-id>57e9a1ff-d14f-4071-a828-b19ae98eb2fc</subnet-id> + <neutron-subnet-id>bd8e87c6-f4e2-41b8-b0bc-9596aa00cd73</neutron-subnet-id> + <gateway-address>107.239.52.1</gateway-address> + <network-start-address>107.239.52.0</network-start-address> + <cidr-mask>24</cidr-mask> + <ip-version>4</ip-version> + <orchestration-status>Created</orchestration-status> + <dhcp-enabled>true</dhcp-enabled> + <subnet-name>subnetName</subnet-name> + </subnet> + </subnets> + <segmentation-assignments> + <segmentation-assignment> + <segmentation-id>1</segmentation-id> + <resource-version>1498507569188</resource-version> + </segmentation-assignment> + </segmentation-assignments> + <ctag-assignments> + <ctag-assignment> + <vlan-id-inner>inner</vlan-id-inner> + <resource-version>ctag-version</resource-version> + <relationship-list> + <relationship> + <related-to>tenant</related-to> + <related-link>https://aai-ext1.test.com:8443/aai/v8/cloud-infrastructure/tenants/tenant/897deadc2b954a6bac6d3c197fb3525e/</related-link> + <relationship-data> + <relationship-key>tenant.tenant-id</relationship-key> + <relationship-value>897deadc2b954a6bac6d3c197fb3525e</relationship-value> + </relationship-data> + <related-to-property> + <property-key>tenant.tenant-name</property-key> + <property-value>MSOTest1</property-value> + </related-to-property> + </relationship> + <relationship> + <related-to>vpn-binding</related-to> + <related-link>https://aai-ext1.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/a290b841-f672-44dd-b9cd-6f8c20d7d8c8/</related-link> + <relationship-data> + <relationship-key>vpn-binding.vpn-id</relationship-key> + <relationship-value>a290b841-f672-44dd-b9cd-6f8c20d7d8c8</relationship-value> + </relationship-data> + <related-to-property> + <property-key>vpn-binding.vpn-name</property-key> + <property-value>oam_protected_net_6_MTN5_msotest2</property-value> + </related-to-property> + </relationship> + <relationship> + <related-to>vpn-binding</related-to> + <related-link>https://aai-ext1.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/24a4b507-853a-4a38-99aa-05fcc54be24d/</related-link> + <relationship-data> + <relationship-key>vpn-binding.vpn-id</relationship-key> + <relationship-value>24a4b507-853a-4a38-99aa-05fcc54be24d</relationship-value> + </relationship-data> + <related-to-property> + <property-key>vpn-binding.vpn-name</property-key> + <property-value>oam_protected_net_6_MTN5_msotest1</property-value> + </related-to-property> + </relationship> + </relationship-list> + </ctag-assignment> + </ctag-assignments> + <relationship-list> + <relationship> + <related-to>vpn-binding</related-to> + <related-link>https://aai-app-e2e.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/85f015d0-2e32-4c30-96d2-87a1a27f8017/</related-link> + <relationship-data> + <relationship-key>vpn-binding.vpn-id</relationship-key> + <relationship-value>85f015d0-2e32-4c30-96d2-87a1a27f8017</relationship-value> + </relationship-data> + </relationship> + <relationship> + <related-to>vpn-binding</related-to> + <related-link>https://aai-app-e2e.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/c980a6ef-3b88-49f0-9751-dbad8608d0a6/</related-link> + <relationship-data> + <relationship-key>vpn-binding.vpn-id</relationship-key> + <relationship-value>c980a6ef-3b88-49f0-9751-dbad8608d0a6</relationship-value> + </relationship-data> + </relationship> + <relationship> + <related-to>tenant</related-to> + <related-link>https://aai-app-e2e.test.com:8443/aai/v8/cloud-infrastructure/tenants/tenant/7dd5365547234ee8937416c65507d266/</related-link> + <relationship-data> + <relationship-key>tenant.tenant-id</relationship-key> + <relationship-value>7dd5365547234ee8937416c65507d266</relationship-value> + </relationship-data> + </relationship> + <relationship> + <related-to>network-policy</related-to> + <related-link>https://aai-app-e2e.test.com:8443/aai/v8/network/network-policies/network-policy/cee6d136-e378-4678-a024-2cd15f0ee0cg</related-link> + <relationship-data> + <relationship-key>network-policy.network-policy-id</relationship-key> + <relationship-value>cee6d136-e378-4678-a024-2cd15f0ee0cg</relationship-value> + </relationship-data> + </relationship> + <relationship> + <related-to>route-table-reference</related-to> + <related-link>https://aai-app-e2e.test.com:8443/aai/v8/network/route-table-references/route-table-reference/refFQDN1</related-link> + <relationship-data> + <relationship-key>route-table-reference.route-table-reference-id</relationship-key> + <relationship-value>cee6d136-e378-4678-a024-2cd15f0ee0hi</relationship-value> + </relationship-data> + </relationship> + <relationship> + <related-to>route-table-reference</related-to> + <related-link>https://aai-app-e2e.test.com:8443/aai/v8/network/route-table-references/route-table-reference/refFQDN2</related-link> + <relationship-data> + <relationship-key>route-table-reference.route-table-reference-id</relationship-key> + <relationship-value>cee6d136-e378-4678-a024-2cd15f0ee0hi</relationship-value> + </relationship-data> + </relationship> + </relationship-list> +</l3-network>""" + + String updateContrailAAIResponse = + """<rest:RESTResponse xmlns:rest="http://schemas.activebpel.org/REST/2007/12/01/aeREST.xsd" + statusCode="200"> + <rest:headers> + <rest:header name="Date" value="Thu,10 Mar 2016 00:01:18 GMT"/> + <rest:header name="Content-Length" value="0"/> + <rest:header name="Expires" value="Thu,01 Jan 1970 00:00:00 UTC"/> + <rest:header name="X-AAI-TXID" value="mtcnjv9aaas03-20160310-00:01:18:551-132672"/> + <rest:header name="Server" value="Apache-Coyote/1.1"/> + <rest:header name="Cache-Control" value="private"/> + </rest:headers> +</rest:RESTResponse>""" + + String createNetworkErrorResponse = + """<createNetworkError> + <messageId>680bd458-5ec1-4a16-b77c-509022e53450</messageId><category>INTERNAL</category> + <message>400 Bad Request: The server could not comply with the request since it is either malformed or otherwise incorrect., error.type=StackValidationFailed, error.message=Property error: : resources.network.properties: : Unknown Property network_ipam_refs_data</message> + <rolledBack>true</rolledBack> + </createNetworkError>""" + + + String networkException500 = + """<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><soap:Fault><faultcode>soap:VersionMismatch</faultcode><faultstring>"http://org.onap.so/network", the namespace on the "createNetworkContrail" element, is not a valid SOAP version.</faultstring></soap:Fault></soap:Body></soap:Envelope>""" + + String aaiResponse = + """<rest:RESTResponse xmlns:rest="http://schemas.activebpel.org/REST/2007/12/01/aeREST.xsd" + statusCode="200"> + <rest:headers> + <rest:header name="Transfer-Encoding" value="chunked"/> + <rest:header name="Date" value="Sat,30 Jan 2016 20:09:24 GMT"/> + <rest:header name="Expires" value="Thu,01 Jan 1970 00:00:00 UTC"/> + <rest:header name="X-AAI-TXID" + value="localhost-20160130-20:09:24:814-165843"/> + <rest:header name="Content-Type" value="application/xml"/> + <rest:header name="Server" value="Apache-Coyote/1.1"/> + <rest:header name="Cache-Control" value="private"/> + </rest:headers> + <rest:payload contentType="text/xml"> + <l3-network xmlns="http://org.openecomp.aai.inventory/v3"> + <network-id>bdc5efe8-404a-409b-85f6-0dcc9eebae30</network-id> + <network-name>HSL_direct_net_2</network-name> + <network-type>CONTRAIL_BASIC</network-type> + <network-role>HSL_direct</network-role> + <network-technology>contrail</network-technology> + <neutron-network-id>8bbd3edf-b835-4610-96a2-a5cafa029042</neutron-network-id> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <orchestration-status>active</orchestration-status> + <heat-stack-id>HSL_direct_net_2/57594a56-1c92-4a38-9caa-641c1fa3d4b6</heat-stack-id> + <subnets> + <subnet> + <subnet-id>ea5f2a2c-604f-47ff-a9c5-253ee4f0ef0a</subnet-id> + <neutron-subnet-id>5a77fdc2-7789-4649-a1b9-6eaf1db1813a</neutron-subnet-id> + <gateway-address>172.16.34.1</gateway-address> + <network-start-address>172.16.34.0</network-start-address> + <cidr-mask>28</cidr-mask> + <ip-version>4</ip-version> + <orchestration-status>active</orchestration-status> + <dhcp-enabled>true</dhcp-enabled> + <relationship-list/> + </subnet> + </subnets> + <relationship-list> + <relationship> + <related-to>tenant</related-to> + <related-link>https://aai-app-e2e.test.com:8443/aai/v3/cloud-infrastructure/tenants/tenant/e81d842d3e8b45c5a59f57cd76af3aaf/</related-link> + <relationship-data> + <relationship-key>tenant.tenant-id</relationship-key> + <relationship-value>e81d842d3e8b45c5a59f57cd76af3aaf</relationship-value> + </relationship-data> + </relationship> + </relationship-list> + </l3-network> + </rest:payload> + </rest:RESTResponse>""" + + String assignSDNCRequest = + """<aetgt:SDNCAdapterWorkflowRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:ns5="http://org.onap/so/request/types/v1" + xmlns:sdncadapter="http://org.onap.so/workflow/sdnc/adapter/schema/v1"> + <sdncadapter:RequestHeader> + <sdncadapter:RequestId>88f65519-9a38-4c4b-8445-9eb4a5a5af56</sdncadapter:RequestId> + <sdncadapter:SvcInstanceId>f70e927b-6087-4974-9ef8-c5e4d5847ca4</sdncadapter:SvcInstanceId> + <sdncadapter:SvcAction>assign</sdncadapter:SvcAction> + <sdncadapter:SvcOperation>network-topology-operation</sdncadapter:SvcOperation> + <sdncadapter:CallbackUrl>sdncCallback</sdncadapter:CallbackUrl> + </sdncadapter:RequestHeader> + <aetgt:SDNCRequestData> + <request-information> + <request-id>88f65519-9a38-4c4b-8445-9eb4a5a5af56</request-id> + <request-action>NetworkActivateRequest</request-action> + <source>VID</source> + <notification-url/> + <order-number/> + <order-version/> + </request-information> + <service-information> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <service-type>MSO-dev-service-type</service-type> + <service-instance-id>f70e927b-6087-4974-9ef8-c5e4d5847ca4</service-instance-id> + <subscriber-name>MSO_1610_dev</subscriber-name> + </service-information> + <network-request-information> + <network-id>networkId</network-id> + <network-type>CONTRAIL_EXTERNAL</network-type> + <network-name>MNS-25180-L-01-dmz_direct_net_1</network-name> + <tenant>7dd5365547234ee8937416c65507d266</tenant> + <aic-cloud-region>RDM2WAGPLCP</aic-cloud-region> + </network-request-information> + </aetgt:SDNCRequestData> +</aetgt:SDNCAdapterWorkflowRequest>""" + +String assignSDNCRequest_decodeUrlLink = +"""<aetgt:SDNCAdapterWorkflowRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:ns5="http://org.onap/so/request/types/v1" + xmlns:sdncadapter="http://org.onap.so/workflow/sdnc/adapter/schema/v1"> + <sdncadapter:RequestHeader> + <sdncadapter:RequestId>88f65519-9a38-4c4b-8445-9eb4a5a5af56</sdncadapter:RequestId> + <sdncadapter:SvcInstanceId>f70e927b-6087-4974-9ef8-c5e4d5847ca4</sdncadapter:SvcInstanceId> + <sdncadapter:SvcAction>assign</sdncadapter:SvcAction> + <sdncadapter:SvcOperation>network-topology-operation</sdncadapter:SvcOperation> + <sdncadapter:CallbackUrl>sdncCallback</sdncadapter:CallbackUrl> + </sdncadapter:RequestHeader> + <aetgt:SDNCRequestData> + <request-information> + <request-id>88f65519-9a38-4c4b-8445-9eb4a5a5af56</request-id> + <request-action>NetworkActivateRequest</request-action> + <source>VID</source> + <notification-url/> + <order-number/> + <order-version/> + </request-information> + <service-information> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <service-type>VIRTUAL USP</service-type> + <service-instance-id>f70e927b-6087-4974-9ef8-c5e4d5847ca4</service-instance-id> + <subscriber-name>MSO_1610_dev</subscriber-name> + </service-information> + <network-request-information> + <network-id>networkId</network-id> + <network-type>CONTRAIL_EXTERNAL</network-type> + <network-name>MNS-25180-L-01-dmz_direct_net_1</network-name> + <tenant>7dd5365547234ee8937416c65507d266</tenant> + <aic-cloud-region>RDM2WAGPLCP</aic-cloud-region> + </network-request-information> + </aetgt:SDNCRequestData> +</aetgt:SDNCAdapterWorkflowRequest>""" + +String assignRpcSDNCRequest = + """<aetgt:SDNCAdapterWorkflowRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:sdncadapter="http://org.onap.so/workflow/sdnc/adapter/schema/v1"> + <sdncadapter:RequestHeader> + <sdncadapter:RequestId>88f65519-9a38-4c4b-8445-9eb4a5a5af56</sdncadapter:RequestId> + <sdncadapter:SvcInstanceId>f70e927b-6087-4974-9ef8-c5e4d5847ca4</sdncadapter:SvcInstanceId> + <sdncadapter:SvcAction>assign</sdncadapter:SvcAction> + <sdncadapter:SvcOperation>network-topology-operation</sdncadapter:SvcOperation> + <sdncadapter:CallbackUrl>sdncCallback</sdncadapter:CallbackUrl> + <sdncadapter:MsoAction>generic-resource</sdncadapter:MsoAction> + </sdncadapter:RequestHeader> + <aetgt:SDNCRequestData> + <request-information> + <request-id>88f65519-9a38-4c4b-8445-9eb4a5a5af56</request-id> + <request-action>CreateNetworkInstance</request-action> + <source>VID</source> + <notification-url/> + <order-number/> + <order-version/> + </request-information> + <service-information> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <subscription-service-type>MSO-dev-service-type</subscription-service-type> + <onap-model-information> + <model-invariant-uuid>fcc85cb0-ad74-45d7-a5a1-17c8744fdb71</model-invariant-uuid> + <model-uuid>36a3a8ea-49a6-4ac8-b06c-89a54544b9b6</model-uuid> + <model-version>1.0</model-version> + <model-name>HNGW Protected OAM</model-name> + </onap-model-information> + <service-instance-id>f70e927b-6087-4974-9ef8-c5e4d5847ca4</service-instance-id> + <global-customer-id>globalId_45678905678</global-customer-id> + <subscriber-name>MSO_1610_dev</subscriber-name> + </service-information> + <network-information> + <network-id>networkId</network-id> + <network-type>CONTRAIL_EXTERNAL</network-type> + <onap-model-information> + <model-invariant-uuid>sn5256d1-5a33-55df-13ab-12abad84e764</model-invariant-uuid> + <model-customization-uuid>sn5256d1-5a33-55df-13ab-12abad84e222</model-customization-uuid> + <model-uuid>sn5256d1-5a33-55df-13ab-12abad84e111</model-uuid> + <model-version>1</model-version> + <model-name>CONTRAIL_EXTERNAL</model-name> + </onap-model-information> + </network-information> + <network-request-input> + <network-name>MNS-25180-L-01-dmz_direct_net_1</network-name> + <tenant>7dd5365547234ee8937416c65507d266</tenant> + <aic-cloud-region>RDM2WAGPLCP</aic-cloud-region> + <aic-clli/> + <network-input-parameters/> + </network-request-input> + </aetgt:SDNCRequestData> +</aetgt:SDNCAdapterWorkflowRequest>""" + +String activateSDNCRequest = +"""<aetgt:SDNCAdapterWorkflowRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:sdncadapter="http://org.onap.so/workflow/sdnc/adapter/schema/v1"> + <sdncadapter:RequestHeader> + <sdncadapter:RequestId>88f65519-9a38-4c4b-8445-9eb4a5a5af56</sdncadapter:RequestId> + <sdncadapter:SvcInstanceId>f70e927b-6087-4974-9ef8-c5e4d5847ca4</sdncadapter:SvcInstanceId> + <sdncadapter:SvcAction>activate</sdncadapter:SvcAction> + <sdncadapter:SvcOperation>network-topology-operation</sdncadapter:SvcOperation> + <sdncadapter:CallbackUrl>sdncCallback</sdncadapter:CallbackUrl> + <sdncadapter:MsoAction>generic-resource</sdncadapter:MsoAction> + </sdncadapter:RequestHeader> + <aetgt:SDNCRequestData> + <request-information> + <request-id>88f65519-9a38-4c4b-8445-9eb4a5a5af56</request-id> + <request-action>CreateNetworkInstance</request-action> + <source>VID</source> + <notification-url/> + <order-number/> + <order-version/> + </request-information> + <service-information> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <subscription-service-type>MSO-dev-service-type</subscription-service-type> + <onap-model-information> + <model-invariant-uuid>fcc85cb0-ad74-45d7-a5a1-17c8744fdb71</model-invariant-uuid> + <model-uuid>36a3a8ea-49a6-4ac8-b06c-89a54544b9b6</model-uuid> + <model-version>1.0</model-version> + <model-name>HNGW Protected OAM</model-name> + </onap-model-information> + <service-instance-id>f70e927b-6087-4974-9ef8-c5e4d5847ca4</service-instance-id> + <global-customer-id>globalId_45678905678</global-customer-id> + <subscriber-name>MSO_1610_dev</subscriber-name> + </service-information> + <network-information> + <network-id>networkId</network-id> + <network-type>CONTRAIL_EXTERNAL</network-type> + <onap-model-information> + <model-invariant-uuid>sn5256d1-5a33-55df-13ab-12abad84e764</model-invariant-uuid> + <model-customization-uuid>sn5256d1-5a33-55df-13ab-12abad84e222</model-customization-uuid> + <model-uuid>sn5256d1-5a33-55df-13ab-12abad84e111</model-uuid> + <model-version>1</model-version> + <model-name>CONTRAIL_EXTERNAL</model-name> + </onap-model-information> + </network-information> + <network-request-input> + <network-name>MNS-25180-L-01-dmz_direct_net_1</network-name> + <tenant>7dd5365547234ee8937416c65507d266</tenant> + <aic-cloud-region>RDM2WAGPLCP</aic-cloud-region> + <aic-clli/> + <network-input-parameters/> + </network-request-input> + </aetgt:SDNCRequestData> +</aetgt:SDNCAdapterWorkflowRequest>""" + +String assignResponse = +"""<sdncadapterworkflow:SDNCAdapterWorkflowResponse xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1" xmlns:tag0="http://org.onap/workflow/sdnc/adapter/schema/v1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <sdncadapterworkflow:response-data> <tag0:CallbackHeader> <tag0:RequestId>006927ca-f5a3-47fd-880c-dfcbcd81a093</tag0:RequestId> <tag0:ResponseCode>200</tag0:ResponseCode> <tag0:ResponseMessage>OK</tag0:ResponseMessage> </tag0:CallbackHeader> <tag0:RequestData xsi:type="xs:string"><output xmlns="com:att:sdnctl:vnf"><response-code>200</response-code><svc-request-id>006927ca-f5a3-47fd-880c-dfcbcd81a093</svc-request-id><ack-final-indicator>Y</ack-final-indicator><service-information><subscriber-name>notsurewecare</subscriber-name><service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id><service-instance-id>GN_EVPN_direct_net_0_ST_noGW</service-instance-id></service-information><network-information><network-id>8abc633a-810b-4ca5-8b3a-09511d13a2ce</network-id></network-information></output></tag0:RequestData> </sdncadapterworkflow:response-data> </sdncadapterworkflow:SDNCAdapterWorkflowResponse>""" + + String sdncRollbackRequest = + """<aetgt:SDNCAdapterWorkflowRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:ns5="http://org.onap/so/request/types/v1" + xmlns:sdncadapter="http://org.onap.so/workflow/sdnc/adapter/schema/v1"> + <sdncadapter:RequestHeader> + <sdncadapter:RequestId>88f65519-9a38-4c4b-8445-9eb4a5a5af56</sdncadapter:RequestId> + <sdncadapter:SvcInstanceId>f70e927b-6087-4974-9ef8-c5e4d5847ca4</sdncadapter:SvcInstanceId> + <sdncadapter:SvcAction>rollback</sdncadapter:SvcAction> + <sdncadapter:SvcOperation>network-topology-operation</sdncadapter:SvcOperation> + <sdncadapter:CallbackUrl>sdncCallback</sdncadapter:CallbackUrl> + </sdncadapter:RequestHeader> + <aetgt:SDNCRequestData> + <request-information> + <request-id>88f65519-9a38-4c4b-8445-9eb4a5a5af56</request-id> + <request-action>NetworkActivateRequest</request-action> + <source>VID</source> + <notification-url/> + <order-number/> + <order-version/> + </request-information> + <service-information> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <service-type>MSO-dev-service-type</service-type> + <service-instance-id>f70e927b-6087-4974-9ef8-c5e4d5847ca4</service-instance-id> + <subscriber-name>MSO_1610_dev</subscriber-name> + </service-information> + <network-request-information> + <network-id>8abc633a-810b-4ca5-8b3a-09511d13a2ce</network-id> + <network-type>CONTRAIL_EXTERNAL</network-type> + <network-name>MNS-25180-L-01-dmz_direct_net_1</network-name> + <tenant>7dd5365547234ee8937416c65507d266</tenant> + <aic-cloud-region>RDM2WAGPLCP</aic-cloud-region> + </network-request-information> + </aetgt:SDNCRequestData> +</aetgt:SDNCAdapterWorkflowRequest>""" + +String sdncRpcRollbackRequest = +"""<aetgt:SDNCAdapterWorkflowRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:sdncadapter="http://org.onap.so/workflow/sdnc/adapter/schema/v1"> + <sdncadapter:RequestHeader> + <sdncadapter:RequestId>88f65519-9a38-4c4b-8445-9eb4a5a5af56</sdncadapter:RequestId> + <sdncadapter:SvcInstanceId>f70e927b-6087-4974-9ef8-c5e4d5847ca4</sdncadapter:SvcInstanceId> + <sdncadapter:SvcAction>unassign</sdncadapter:SvcAction> + <sdncadapter:SvcOperation>network-topology-operation</sdncadapter:SvcOperation> + <sdncadapter:CallbackUrl>sdncCallback</sdncadapter:CallbackUrl> + <sdncadapter:MsoAction>generic-resource</sdncadapter:MsoAction> + </sdncadapter:RequestHeader> + <aetgt:SDNCRequestData> + <request-information> + <request-id>88f65519-9a38-4c4b-8445-9eb4a5a5af56</request-id> + <request-action>DeleteNetworkInstance</request-action> + <source>VID</source> + <notification-url/> + <order-number/> + <order-version/> + </request-information> + <service-information> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <subscription-service-type>MSO-dev-service-type</subscription-service-type> + <onap-model-information> + <model-invariant-uuid>fcc85cb0-ad74-45d7-a5a1-17c8744fdb71</model-invariant-uuid> + <model-uuid>36a3a8ea-49a6-4ac8-b06c-89a54544b9b6</model-uuid> + <model-version>1.0</model-version> + <model-name>HNGW Protected OAM</model-name> + </onap-model-information> + <service-instance-id>f70e927b-6087-4974-9ef8-c5e4d5847ca4</service-instance-id> + <global-customer-id>globalId_45678905678</global-customer-id> + <subscriber-name>MSO_1610_dev</subscriber-name> + </service-information> + <network-information> + <network-id>8abc633a-810b-4ca5-8b3a-09511d13a2ce</network-id> + <network-type>CONTRAIL_EXTERNAL</network-type> + <onap-model-information> + <model-invariant-uuid>sn5256d1-5a33-55df-13ab-12abad84e764</model-invariant-uuid> + <model-customization-uuid>sn5256d1-5a33-55df-13ab-12abad84e222</model-customization-uuid> + <model-uuid>sn5256d1-5a33-55df-13ab-12abad84e111</model-uuid> + <model-version>1</model-version> + <model-name>CONTRAIL_EXTERNAL</model-name> + </onap-model-information> + </network-information> + <network-request-input> + <network-name>MNS-25180-L-01-dmz_direct_net_1</network-name> + <tenant>7dd5365547234ee8937416c65507d266</tenant> + <aic-cloud-region>RDM2WAGPLCP</aic-cloud-region> + <aic-clli/> + <network-input-parameters/> + </network-request-input> + </aetgt:SDNCRequestData> +</aetgt:SDNCAdapterWorkflowRequest>""" + +String sdncActivateRollbackRequest = +"""<aetgt:SDNCAdapterWorkflowRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:sdncadapter="http://org.onap.so/workflow/sdnc/adapter/schema/v1"> + <sdncadapter:RequestHeader> + <sdncadapter:RequestId>88f65519-9a38-4c4b-8445-9eb4a5a5af56</sdncadapter:RequestId> + <sdncadapter:SvcInstanceId>f70e927b-6087-4974-9ef8-c5e4d5847ca4</sdncadapter:SvcInstanceId> + <sdncadapter:SvcAction>deactivate</sdncadapter:SvcAction> + <sdncadapter:SvcOperation>network-topology-operation</sdncadapter:SvcOperation> + <sdncadapter:CallbackUrl>sdncCallback</sdncadapter:CallbackUrl> + <sdncadapter:MsoAction>generic-resource</sdncadapter:MsoAction> + </sdncadapter:RequestHeader> + <aetgt:SDNCRequestData> + <request-information> + <request-id>88f65519-9a38-4c4b-8445-9eb4a5a5af56</request-id> + <request-action>DeleteNetworkInstance</request-action> + <source>VID</source> + <notification-url/> + <order-number/> + <order-version/> + </request-information> + <service-information> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <subscription-service-type>MSO-dev-service-type</subscription-service-type> + <onap-model-information> + <model-invariant-uuid>fcc85cb0-ad74-45d7-a5a1-17c8744fdb71</model-invariant-uuid> + <model-uuid>36a3a8ea-49a6-4ac8-b06c-89a54544b9b6</model-uuid> + <model-version>1.0</model-version> + <model-name>HNGW Protected OAM</model-name> + </onap-model-information> + <service-instance-id>f70e927b-6087-4974-9ef8-c5e4d5847ca4</service-instance-id> + <global-customer-id>globalId_45678905678</global-customer-id> + <subscriber-name>MSO_1610_dev</subscriber-name> + </service-information> + <network-information> + <network-id>8abc633a-810b-4ca5-8b3a-09511d13a2ce</network-id> + <network-type>CONTRAIL_EXTERNAL</network-type> + <onap-model-information> + <model-invariant-uuid>sn5256d1-5a33-55df-13ab-12abad84e764</model-invariant-uuid> + <model-customization-uuid>sn5256d1-5a33-55df-13ab-12abad84e222</model-customization-uuid> + <model-uuid>sn5256d1-5a33-55df-13ab-12abad84e111</model-uuid> + <model-version>1</model-version> + <model-name>CONTRAIL_EXTERNAL</model-name> + </onap-model-information> + </network-information> + <network-request-input> + <network-name>MNS-25180-L-01-dmz_direct_net_1</network-name> + <tenant>7dd5365547234ee8937416c65507d266</tenant> + <aic-cloud-region>RDM2WAGPLCP</aic-cloud-region> + <aic-clli/> + <network-input-parameters/> + </network-request-input> + </aetgt:SDNCRequestData> +</aetgt:SDNCAdapterWorkflowRequest>""" + + String sdncAdapterWorkflowResponse = + """<aetgt:SDNCAdapterWorkflowResponse xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1"> + <sdncadapterworkflow:response-data> +<tag0:CallbackHeader xmlns:tag0="http://org.onap.so/workflow/sdnc/adapter/schema/v1"> + <tag0:RequestId>745b1b50-e39e-4685-9cc8-c71f0bde8bf0</tag0:RequestId> + <tag0:ResponseCode>200</tag0:ResponseCode> + <tag0:ResponseMessage>OK</tag0:ResponseMessage> +</tag0:CallbackHeader> + <tag0:RequestData xmlns:tag0="http://org.onap/workflow/sdnc/adapter/schema/v1" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:type="xs:string"><output xmlns="com:att:sdnctl:vnf"><svc-request-id>00703dc8-71ff-442d-a4a8-3adc5beef6a9</svc-request-id><response-code>200</response-code><ack-final-indicator>Y</ack-final-indicator><network-information><network-id>49c86598-f766-46f8-84f8-8d1c1b10f9b4</network-id></network-information><service-information><service-type>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-type><service-instance-id>MNS-25180-L-01-dmz_direct_net_1</service-instance-id><subscriber-name>notsurewecare</subscriber-name></service-information></output></tag0:RequestData> + </sdncadapterworkflow:response-data> +</aetgt:SDNCAdapterWorkflowResponse>""" + + + String sdncAdapterWorkflowResponse_Error = + """<sdncadapterworkflow:SDNCAdapterWorkflowResponse xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1" + xmlns:tag0="http://org.onap/workflow/sdnc/adapter/schema/v1" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns="com:att:sdnctl:vnf"> + <sdncadapterworkflow:response-data> + <tag0:RequestData xsi:type="xs:string"> + <output> + <response-code>400</response-code> + <response-message>Error writing to l3-netework</response-message> + <ack-final-indicator>Y</ack-final-indicator> + <svc-request-id>c79240d8-34b5-4853-af69-2021928dba00</svc-request-id> + </output> + </tag0:RequestData> + </sdncadapterworkflow:response-data> +</sdncadapterworkflow:SDNCAdapterWorkflowResponse>""" + + String expected_sdncAdapterWorkflowResponse_Error = + """<sdncadapterworkflow:SDNCAdapterWorkflowResponse xmlns="com:att:sdnctl:vnf" + xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1" + xmlns:tag0="http://org.onap/workflow/sdnc/adapter/schema/v1" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> + <sdncadapterworkflow:response-data> + <tag0:RequestData xsi:type="xs:string"> + <output> + <response-code>400</response-code> + <response-message>Error writing to l3-netework</response-message> + <ack-final-indicator>Y</ack-final-indicator> + <svc-request-id>c79240d8-34b5-4853-af69-2021928dba00</svc-request-id> + </output> + </tag0:RequestData> + </sdncadapterworkflow:response-data> +</sdncadapterworkflow:SDNCAdapterWorkflowResponse>""" + + String sdncAdapterWorkflowFormattedResponse = + """<aetgt:SDNCAdapterWorkflowResponse xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns="com:att:sdnctl:vnf"> + <aetgt:response-data> + <output> + <svc-request-id>00703dc8-71ff-442d-a4a8-3adc5beef6a9</svc-request-id> + <response-code>200</response-code> + <ack-final-indicator>Y</ack-final-indicator> + <network-information> + <network-id>49c86598-f766-46f8-84f8-8d1c1b10f9b4</network-id> + </network-information> + <service-information> + <service-type>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-type> + <service-instance-id>f70e927b-6087-4974-9ef8-c5e4d5847ca4</service-instance-id> + <subscriber-name>notsurewecare</subscriber-name> + </service-information> + </output> + </aetgt:response-data> +</aetgt:SDNCAdapterWorkflowResponse>""" + +String sdncAdapterWorkflowAssignResponse = +"""<sdncadapterworkflow:SDNCAdapterWorkflowResponse xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1" + xmlns:tag0="http://org.onap.so/workflow/sdnc/adapter/schema/v1" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> + <sdncadapterworkflow:response-data> + <tag0:CallbackHeader> + <tag0:RequestId>79ec9006-3695-4fcc-93a8-be6f9e248beb</tag0:RequestId> + <tag0:ResponseCode>200</tag0:ResponseCode> + <tag0:ResponseMessage>OK</tag0:ResponseMessage> + </tag0:CallbackHeader> + <tag0:RequestData xsi:type="xs:string"> + <output xmlns="org:onap:sdnc:northbound:generic-resource"> + <response-message/> + <svc-request-id>79ec9006-3695-4fcc-93a8-be6f9e248beb</svc-request-id> + <service-response-information> + <instance-id>f805ec2b-b4d8-473e-8325-67f110139e5d</instance-id> + </service-response-information> + <response-code>200</response-code> + <network-response-information> + <instance-id>49c86598-f766-46f8-84f8-8d1c1b10f9b4</instance-id> + <object-path>restconf/config/GENERIC-RESOURCE-API:services/service/f805ec2b-b4d8-473e-8325-67f110139e5d/service-data/networks/network/f7e4db56-aab5-4065-8e65-cec1cd1de24f</object-path> + </network-response-information> + <ack-final-indicator>Y</ack-final-indicator> + </output> + </tag0:RequestData> + </sdncadapterworkflow:response-data> +</sdncadapterworkflow:SDNCAdapterWorkflowResponse>""" + + String rollbackNetworkRequest = +"""<NetworkAdapter:rollbackNetwork xmlns:NetworkAdapter="http://org.onap.so/network"> + <rollback> + <networkId>MNS-25180-L-01-dmz_direct_net_1/2c88a3a9-69b9-43a7-ada6-1aca577c3641</networkId> + <neutronNetworkId>c4f4e878-cde0-4b15-ae9a-bda857759cea</neutronNetworkId> + <networkStackId/> + <networkType>CONTRAIL_EXTERNAL</networkType> + <networkCreated>true</networkCreated> + <tenantId>7dd5365547234ee8937416c65507d266</tenantId> + <cloudSiteId>RDM2WAGPLCP</cloudSiteId> + <msoRequest> + <requestId>1ef47428-cade-45bd-a103-0751e8b2deb0</requestId> + <serviceInstanceId/> + </msoRequest> + </rollback> +</NetworkAdapter:rollbackNetwork>""" + + String rollbackActivateSDNCRequest = +"""<aetgt:SDNCAdapterWorkflowRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:ns5="http://org.onap/so/request/types/v1" + xmlns:sdncadapter="http://org.onap.so/workflow/sdnc/adapter/schema/v1"> + <sdncadapter:RequestHeader> + <sdncadapter:RequestId>88f65519-9a38-4c4b-8445-9eb4a5a5af56</sdncadapter:RequestId> + <sdncadapter:SvcInstanceId>f70e927b-6087-4974-9ef8-c5e4d5847ca4</sdncadapter:SvcInstanceId> + <sdncadapter:SvcAction>rollback</sdncadapter:SvcAction> + <sdncadapter:SvcOperation>network-topology-operation</sdncadapter:SvcOperation> + <sdncadapter:CallbackUrl>sdncCallback</sdncadapter:CallbackUrl> + </sdncadapter:RequestHeader> + <aetgt:SDNCRequestData> + <request-information> + <request-id>88f65519-9a38-4c4b-8445-9eb4a5a5af56</request-id> + <request-action>CreateNetworkInstance</request-action> + <source>VID</source> + <notification-url/> + <order-number/> + <order-version/> + </request-information> + <service-information> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <service-type>MSO-dev-service-type</service-type> + <service-instance-id>f70e927b-6087-4974-9ef8-c5e4d5847ca4</service-instance-id> + <subscriber-name>MSO_1610_dev</subscriber-name> + </service-information> + <network-information> + <network-id>8abc633a-810b-4ca5-8b3a-09511d13a2ce</network-id> + <network-type>CONTRAIL_EXTERNAL</network-type> + <onap-model-information> + <model-invariant-uuid>invariant-uuid</model-invariant-uuid> + <model-customization-uuid>customization-uuid</model-customization-uuid> + <model-uuid>uuid</model-uuid> + <model-version>version</model-version> + <model-name>CONTRAIL_EXTERNAL</model-name> + </onap-model-information> + </network-information> + <network-request-information> + <network-id>8abc633a-810b-4ca5-8b3a-09511d13a2ce</network-id> + <network-type>CONTRAIL_EXTERNAL</network-type> + <network-name>MNS-25180-L-01-dmz_direct_net_1</network-name> + <tenant>7dd5365547234ee8937416c65507d266</tenant> + <aic-cloud-region>RDM2WAGPLCP</aic-cloud-region> + </network-request-information> + </aetgt:SDNCRequestData> +</aetgt:SDNCAdapterWorkflowRequest>""" + + String rollbackSDNCRequest = +"""<aetgt:SDNCAdapterWorkflowRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:ns5="http://org.onap/so/request/types/v1" + xmlns:sdncadapter="http://org.onap.so/workflow/sdnc/adapter/schema/v1"> + <sdncadapter:RequestHeader> + <sdncadapter:RequestId>88f65519-9a38-4c4b-8445-9eb4a5a5af56</sdncadapter:RequestId> + <sdncadapter:SvcInstanceId>f70e927b-6087-4974-9ef8-c5e4d5847ca4</sdncadapter:SvcInstanceId> + <sdncadapter:SvcAction>rollback</sdncadapter:SvcAction> + <sdncadapter:SvcOperation>network-topology-operation</sdncadapter:SvcOperation> + <sdncadapter:CallbackUrl>sdncCallback</sdncadapter:CallbackUrl> + </sdncadapter:RequestHeader> + <aetgt:SDNCRequestData> + <request-information> + <request-id>88f65519-9a38-4c4b-8445-9eb4a5a5af56</request-id> + <request-action>CreateNetworkInstance</request-action> + <source>VID</source> + <notification-url/> + <order-number/> + <order-version/> + </request-information> + <service-information> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <service-type>MSO-dev-service-type</service-type> + <service-instance-id>f70e927b-6087-4974-9ef8-c5e4d5847ca4</service-instance-id> + <subscriber-name>MSO_1610_dev</subscriber-name> + </service-information> + <network-information> + <network-id>8abc633a-810b-4ca5-8b3a-09511d13a2ce</network-id> + <network-type>CONTRAIL_EXTERNAL</network-type> + <onap-model-information> + <model-invariant-uuid>invariant-uuid</model-invariant-uuid> + <model-customization-uuid>customization-uuid</model-customization-uuid> + <model-uuid>uuid</model-uuid> + <model-version>version</model-version> + <model-name>CONTRAIL_EXTERNAL</model-name> + </onap-model-information> + </network-information> + <network-request-information> + <network-id>8abc633a-810b-4ca5-8b3a-09511d13a2ce</network-id> + <network-type>CONTRAIL_EXTERNAL</network-type> + <network-name>MNS-25180-L-01-dmz_direct_net_1</network-name> + <tenant>7dd5365547234ee8937416c65507d266</tenant> + <aic-cloud-region>RDM2WAGPLCP</aic-cloud-region> + </network-request-information> + </aetgt:SDNCRequestData> +</aetgt:SDNCAdapterWorkflowRequest>""" + +// - - - - - - - - + + @Before + public void init() + { + MockitoAnnotations.initMocks(this) + } + + public void initializeVariables (DelegateExecution mockExecution) { + + verify(mockExecution).setVariable(Prefix + "networkRequest", "") + verify(mockExecution).setVariable(Prefix + "rollbackEnabled", null) + verify(mockExecution).setVariable(Prefix + "networkInputs", "") + //verify(mockExecution).setVariable(Prefix + "requestId", "") + verify(mockExecution).setVariable(Prefix + "messageId", "") + verify(mockExecution).setVariable(Prefix + "source", "") + verify(mockExecution).setVariable("BasicAuthHeaderValuePO", "") + verify(mockExecution).setVariable("BasicAuthHeaderValueSDNC", "") + verify(mockExecution).setVariable(Prefix + "serviceInstanceId","") + verify(mockExecution).setVariable("GENGS_type","") + verify(mockExecution).setVariable(Prefix + "rsrc_endpoint", null) + verify(mockExecution).setVariable(Prefix + "networkOutputs", "") + verify(mockExecution).setVariable(Prefix + "networkId","") + verify(mockExecution).setVariable(Prefix + "networkName","") + + // AAI query Name + verify(mockExecution).setVariable(Prefix + "queryNameAAIRequest","") + verify(mockExecution).setVariable(Prefix + "queryNameAAIResponse", "") + verify(mockExecution).setVariable(Prefix + "aaiNameReturnCode", "") + verify(mockExecution).setVariable(Prefix + "isAAIqueryNameGood", false) + + // AAI query Cloud Region + verify(mockExecution).setVariable(Prefix + "queryCloudRegionRequest","") + verify(mockExecution).setVariable(Prefix + "queryCloudRegionReturnCode","") + verify(mockExecution).setVariable(Prefix + "queryCloudRegionResponse","") + verify(mockExecution).setVariable(Prefix + "cloudRegionPo","") + verify(mockExecution).setVariable(Prefix + "cloudRegionSdnc","") + verify(mockExecution).setVariable(Prefix + "isCloudRegionGood", false) + + // AAI query Id + verify(mockExecution).setVariable(Prefix + "queryIdAAIRequest","") + verify(mockExecution).setVariable(Prefix + "queryIdAAIResponse", "") + verify(mockExecution).setVariable(Prefix + "aaiIdReturnCode", "") + + // AAI query vpn binding + verify(mockExecution).setVariable(Prefix + "queryVpnBindingAAIRequest","") + verify(mockExecution).setVariable(Prefix + "queryVpnBindingAAIResponse", "") + verify(mockExecution).setVariable(Prefix + "aaiQqueryVpnBindingReturnCode", "") + verify(mockExecution).setVariable(Prefix + "vpnBindings", null) + verify(mockExecution).setVariable(Prefix + "vpnCount", 0) + verify(mockExecution).setVariable(Prefix + "routeCollection", "") + + // AAI query network policy + verify(mockExecution).setVariable(Prefix + "queryNetworkPolicyAAIRequest","") + verify(mockExecution).setVariable(Prefix + "queryNetworkPolicyAAIResponse", "") + verify(mockExecution).setVariable(Prefix + "aaiQqueryNetworkPolicyReturnCode", "") + verify(mockExecution).setVariable(Prefix + "networkPolicyUriList", null) + verify(mockExecution).setVariable(Prefix + "networkPolicyCount", 0) + verify(mockExecution).setVariable(Prefix + "networkCollection", "") + + // AAI query route table reference + verify(mockExecution).setVariable(Prefix + "queryNetworkTableRefAAIRequest","") + verify(mockExecution).setVariable(Prefix + "queryNetworkTableRefAAIResponse", "") + verify(mockExecution).setVariable(Prefix + "aaiQqueryNetworkTableRefReturnCode", "") + verify(mockExecution).setVariable(Prefix + "networkTableRefUriList", null) + verify(mockExecution).setVariable(Prefix + "networkTableRefCount", 0) + verify(mockExecution).setVariable(Prefix + "tableRefCollection", "") + + // AAI requery Id + verify(mockExecution).setVariable(Prefix + "requeryIdAAIRequest","") + verify(mockExecution).setVariable(Prefix + "requeryIdAAIResponse", "") + verify(mockExecution).setVariable(Prefix + "aaiRequeryIdReturnCode", "") + + // AAI update contrail + verify(mockExecution).setVariable(Prefix + "updateContrailAAIUrlRequest","") + verify(mockExecution).setVariable(Prefix + "updateContrailAAIPayloadRequest","") + verify(mockExecution).setVariable(Prefix + "updateContrailAAIResponse", "") + verify(mockExecution).setVariable(Prefix + "aaiUpdateContrailReturnCode", "") + + verify(mockExecution).setVariable(Prefix + "createNetworkRequest", "") + verify(mockExecution).setVariable(Prefix + "createNetworkResponse", "") + verify(mockExecution).setVariable(Prefix + "rollbackNetworkRequest", "") + //verify(mockExecution).setVariable(Prefix + "rollbackNetworkResponse", "") + verify(mockExecution).setVariable(Prefix + "networkReturnCode", "") + //verify(mockExecution).setVariable(Prefix + "rollbackNetworkReturnCode", "") + verify(mockExecution).setVariable(Prefix + "isNetworkRollbackNeeded", false) + + verify(mockExecution).setVariable(Prefix + "assignSDNCRequest", "") + verify(mockExecution).setVariable(Prefix + "assignSDNCResponse", "") + verify(mockExecution).setVariable(Prefix + "rollbackSDNCRequest", "") + //verify(mockExecution).setVariable(Prefix + "rollbackSDNCResponse", "") + verify(mockExecution).setVariable(Prefix + "sdncReturnCode", "") + //verify(mockExecution).setVariable(Prefix + "rollbackSDNCReturnCode", "") + verify(mockExecution).setVariable(Prefix + "isSdncRollbackNeeded", false) + verify(mockExecution).setVariable(Prefix + "sdncResponseSuccess", false) + + verify(mockExecution).setVariable(Prefix + "activateSDNCRequest", "") + verify(mockExecution).setVariable(Prefix + "activateSDNCResponse", "") + verify(mockExecution).setVariable(Prefix + "rollbackActivateSDNCRequest", "") + //verify(mockExecution).setVariable(Prefix + "rollbackActivateSDNCResponse", "") + verify(mockExecution).setVariable(Prefix + "sdncActivateReturnCode", "") + //verify(mockExecution).setVariable(Prefix + "rollbackActivateSDNCReturnCode", "") + verify(mockExecution).setVariable(Prefix + "isSdncActivateRollbackNeeded", false) + verify(mockExecution).setVariable(Prefix + "sdncActivateResponseSuccess", false) + + verify(mockExecution).setVariable(Prefix + "orchestrationStatus", "") + verify(mockExecution).setVariable(Prefix + "isVnfBindingPresent", false) + verify(mockExecution).setVariable(Prefix + "Success", false) + + verify(mockExecution).setVariable(Prefix + "isException", false) + + } + + @Test + //@Ignore + public void preProcessRequest_vIPR_NetworkRequest() { + + println "************ preProcessRequest_Payload ************* " + + def networkModelInfo = """{"modelUuid": "sn5256d1-5a33-55df-13ab-12abad84e111", + "modelName": "CONTRAIL_EXTERNAL", + "modelType": "CONTRAIL_EXTERNAL", + "modelVersion": "1", + "modelCustomizationUuid": "sn5256d1-5a33-55df-13ab-12abad84e222", + "modelInvariantUuid": "sn5256d1-5a33-55df-13ab-12abad84e764" + }""".trim() + + def serviceModelInfo = """{"modelUuid": "36a3a8ea-49a6-4ac8-b06c-89a54544b9b6", + "modelName": "HNGW Protected OAM", + "modelType": "service", + "modelVersion": "1.0", + "modelInvariantUuid": "fcc85cb0-ad74-45d7-a5a1-17c8744fdb71" + }""".trim() + + + ExecutionEntity mockExecution = setupMock() + // Initialize prerequisite variables + + // Pre-defined value, testing Only + when(mockExecution.getVariable("testMessageId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + // Inputs: + when(mockExecution.getVariable("msoRequestId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + when(mockExecution.getVariable("disableRollback")).thenReturn("true") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("serviceInstanceId")).thenReturn("f70e927b-6087-4974-9ef8-c5e4d5847ca4") + when(mockExecution.getVariable("networkId")).thenReturn("networkId") // optional + when(mockExecution.getVariable("networkName")).thenReturn("MNS-25180-L-01-dmz_direct_net_1") // optional + when(mockExecution.getVariable("productFamilyId")).thenReturn("a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb") + when(mockExecution.getVariable("networkModelInfo")).thenReturn("CONTRAIL_EXTERNAL") + when(mockExecution.getVariable("lcpCloudRegionId")).thenReturn("RDM2WAGPLCP") + when(mockExecution.getVariable("tenantId")).thenReturn("7dd5365547234ee8937416c65507d266") + when(mockExecution.getVariable("failIfExists")).thenReturn("false") + when(mockExecution.getVariable("networkModelInfo")).thenReturn(networkModelInfo) + when(mockExecution.getVariable("serviceModelInfo")).thenReturn(serviceModelInfo) + when(mockExecution.getVariable("sdncVersion")).thenReturn("1702") + when(mockExecution.getVariable("action")).thenReturn("CREATE") + when(mockExecution.getVariable("subscriptionServiceType")).thenReturn("MSO-dev-service-type") + when(mockExecution.getVariable("globalSubscriberId")).thenReturn("globalId_45678905678") + + when(mockExecution.getVariable("mso.adapters.po.auth")).thenReturn("3141634BF7E070AA289CF2892C986C0B") + when(mockExecution.getVariable("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") + + when(mockExecution.getVariable("mso.rollback")).thenReturn("true") + when(mockExecution.getVariable("mso.adapters.sdnc.endpoint")).thenReturn("http://localhost:8090/SDNCAdapter") + when(mockExecution.getVariable("mso.adapters.network.rest.endpoint")).thenReturn("http://localhost:8090/networks/NetworkAdapter") + when(mockExecution.getVariable("mso.adapters.sdnc.resource.endpoint")).thenReturn("http://localhost:8090/SDNCAdapterRpc") + + + // preProcessRequest(DelegateExecution execution) + DoCreateNetworkInstance DoCreateNetworkInstance = new DoCreateNetworkInstance() + DoCreateNetworkInstance.preProcessRequest(mockExecution) + +// verify(mockExecution).getVariable("isDebugLogEnabled") + verify(mockExecution).setVariable("prefix", Prefix) + + //verify variable initialization + initializeVariables(mockExecution) + + verify(mockExecution).setVariable("action", "CREATE") + verify(mockExecution).setVariable(Prefix + "networkId","") + verify(mockExecution).setVariable(Prefix + "networkRequest", expectedvIPRNetworkRequest) + verify(mockExecution, atLeast(1)).setVariable(Prefix + "rollbackEnabled", false) + verify(mockExecution).setVariable(Prefix + "networkInputs", expectedvIPRNetworkInputs) + //verify(mockExecution).setVariable(Prefix + "requestId", "88f65519-9a38-4c4b-8445-9eb4a5a5af56") + //verify(mockExecution).setVariable("mso-service-instance-id", "88f65519-9a38-4c4b-8445-9eb4a5a5af56") + verify(mockExecution).setVariable(Prefix + "messageId", "88f65519-9a38-4c4b-8445-9eb4a5a5af56") + verify(mockExecution).setVariable(Prefix + "source", "VID") + verify(mockExecution).setVariable("BasicAuthHeaderValuePO", "Basic cGFzc3dvcmQ=") + verify(mockExecution).setVariable("BasicAuthHeaderValueSDNC", "Basic cGFzc3dvcmQ=") + verify(mockExecution).setVariable(Prefix + "serviceInstanceId","f70e927b-6087-4974-9ef8-c5e4d5847ca4") + verify(mockExecution, atLeast(1)).setVariable("GENGS_type", "service-instance") + //verify(mockExecution, atLeast(1)).setVariable("mso-request-id", "88f65519-9a38-4c4b-8445-9eb4a5a5af56") + //verify(mockExecution, atLeast(1)).setVariable("msoRequestId", "88f65519-9a38-4c4b-8445-9eb4a5a5af56") + //verify(mockExecution).setVariable("mso-service-instance-id","88f65519-9a38-4c4b-8445-9eb4a5a5af56") + verify(mockExecution).setVariable(Prefix + "networkId","") + verify(mockExecution).setVariable(Prefix + "networkOutputs", networkvIPROutputs) + verify(mockExecution).setVariable(Prefix + "networkName","") + + } + + @Test + //@Ignore + public void preProcessRequest_JSON_NetworkRequest() { + + println "************ preProcessRequest_Payload ************* " + ExecutionEntity mockExecution = setupMock() + // Initialize prerequisite variables + + // Pre-defined value, testing Only + when(mockExecution.getVariable("testMessageId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + // Inputs: + // when(mockExecution.getVariable("requestId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + when(mockExecution.getVariable("mso-request-id")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + when(mockExecution.getVariable("serviceInstanceId")).thenReturn("f70e927b-6087-4974-9ef8-c5e4d5847ca4") + when(mockExecution.getVariable("requestAction")).thenReturn("CREATE") + when(mockExecution.getVariable("networkId")).thenReturn("networkId") // optional + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("bpmnRequest")).thenReturn(jsonIncomingRequest) // JSON format + when(mockExecution.getVariable("sdncVersion")).thenReturn("1610") // 1610 default + when(mockExecution.getVariable("disableRollback")).thenReturn(true) + + when(mockExecution.getVariable("mso.adapters.po.auth")).thenReturn("3141634BF7E070AA289CF2892C986C0B") + when(mockExecution.getVariable("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") + + when(mockExecution.getVariable("mso.rollback")).thenReturn("true") + when(mockExecution.getVariable("mso.adapters.sdnc.endpoint")).thenReturn("http://localhost:8090/SDNCAdapter") + when(mockExecution.getVariable("mso.adapters.network.rest.endpoint")).thenReturn("http://localhost:8090/networks/NetworkAdapter") + when(mockExecution.getVariable("mso.adapters.sdnc.resource.endpoint")).thenReturn("http://localhost:8090/SDNCAdapterRpc") + + // preProcessRequest(DelegateExecution execution) + DoCreateNetworkInstance DoCreateNetworkInstance = new DoCreateNetworkInstance() + DoCreateNetworkInstance.preProcessRequest(mockExecution) + +// verify(mockExecution).getVariable("isDebugLogEnabled") + verify(mockExecution).setVariable("prefix", Prefix) + + //verify variable initialization + initializeVariables(mockExecution) + + verify(mockExecution).setVariable("action", "CREATE") + verify(mockExecution).setVariable(Prefix + "networkRequest", expectedJSONNetworkRequest) + verify(mockExecution).setVariable(Prefix + "rollbackEnabled", false) + verify(mockExecution).setVariable(Prefix + "networkInputs", expectedJSONNetworkInputs) + //verify(mockExecution).setVariable(Prefix + "requestId", "88f65519-9a38-4c4b-8445-9eb4a5a5af56") + //verify(mockExecution).setVariable(Prefix + "messageId", "88f65519-9a38-4c4b-8445-9eb4a5a5af56") + verify(mockExecution).setVariable(Prefix + "source", "VID") + verify(mockExecution).setVariable("BasicAuthHeaderValuePO", "Basic cGFzc3dvcmQ=") + verify(mockExecution).setVariable("BasicAuthHeaderValueSDNC", "Basic cGFzc3dvcmQ=") + verify(mockExecution).setVariable(Prefix + "serviceInstanceId","f70e927b-6087-4974-9ef8-c5e4d5847ca4") + verify(mockExecution, atLeast(1)).setVariable("GENGS_type", "service-instance") + //verify(mockExecution, atLeast(1)).setVariable("msoRequestId", "88f65519-9a38-4c4b-8445-9eb4a5a5af56") + //verify(mockExecution).setVariable("mso-service-instance-id","88f65519-9a38-4c4b-8445-9eb4a5a5af56") + verify(mockExecution).setVariable(Prefix + "networkId","") + verify(mockExecution).setVariable(Prefix + "networkOutputs", networkJSONOutputs) + verify(mockExecution).setVariable(Prefix + "networkName","") + + + } + + @Test + //@Ignore + public void preProcessRequest_XML_NetworkRequest() { + + println "************ preProcessRequest_Payload ************* " + ExecutionEntity mockExecution = setupMock() + // Initialize prerequisite variables + + // Pre-defined value, testing Only + when(mockExecution.getVariable("testMessageId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + // Inputs: + // when(mockExecution.getVariable("msoRequestId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + when(mockExecution.getVariable("mso-request-id")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("bpmnRequest")).thenReturn(xmlIncomingRequest) // XML format + + when(mockExecution.getVariable("mso.adapters.po.auth")).thenReturn("3141634BF7E070AA289CF2892C986C0B") + when(mockExecution.getVariable("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") + + when(mockExecution.getVariable("mso.rollback")).thenReturn("true") + when(mockExecution.getVariable("mso.adapters.sdnc.endpoint")).thenReturn("http://localhost:8090/SDNCAdapter") + when(mockExecution.getVariable("mso.adapters.network.rest.endpoint")).thenReturn("http://localhost:8090/networks/NetworkAdapter") + when(mockExecution.getVariable("mso.adapters.sdnc.resource.endpoint")).thenReturn("http://localhost:8090/SDNCAdapterRpc") + + // preProcessRequest(DelegateExecution execution) + DoCreateNetworkInstance DoCreateNetworkInstance = new DoCreateNetworkInstance() + DoCreateNetworkInstance.preProcessRequest(mockExecution) + +// verify(mockExecution).getVariable("isDebugLogEnabled") + verify(mockExecution).setVariable("prefix", Prefix) + + //verify variable initialization + initializeVariables(mockExecution) + + verify(mockExecution).setVariable("action", "CREATE") + verify(mockExecution).setVariable(Prefix + "networkRequest", expectedXMLNetworkRequest) + verify(mockExecution).setVariable(Prefix + "rollbackEnabled", true) + verify(mockExecution).setVariable(Prefix + "networkInputs", expectedXMLNetworkInputs) + //verify(mockExecution).setVariable(Prefix + "requestId", "88f65519-9a38-4c4b-8445-9eb4a5a5af56") + verify(mockExecution).setVariable(Prefix + "messageId", "88f65519-9a38-4c4b-8445-9eb4a5a5af56") + verify(mockExecution).setVariable(Prefix + "source", "PORTAL") + verify(mockExecution).setVariable("BasicAuthHeaderValuePO", "Basic cGFzc3dvcmQ=") + verify(mockExecution).setVariable("BasicAuthHeaderValueSDNC", "Basic cGFzc3dvcmQ=") + verify(mockExecution).setVariable(Prefix + "serviceInstanceId","MNS-25180-L-01-dmz_direct_net_1") + verify(mockExecution, atLeast(1)).setVariable("GENGS_type", "service-instance") + //verify(mockExecution).setVariable("mso-service-instance-id","88f65519-9a38-4c4b-8445-9eb4a5a5af56") + verify(mockExecution, atLeast(1)).setVariable(Prefix + "networkId","") + verify(mockExecution).setVariable(Prefix + "networkOutputs", networkXMLOutputs) + verify(mockExecution).setVariable(Prefix + "networkName","") + + } + + + + @Test + //@Ignore + public void prepareCreateNetworkRequest() { + + println "************ prepareNetworkRequest ************* " + ExecutionEntity mockExecution = setupMock() + // Initialize prerequisite variables + when(mockExecution.getVariable(Prefix + "networkRequest")).thenReturn(expectedvIPRNetworkRequest) + when(mockExecution.getVariable(Prefix + "queryIdAAIResponse")).thenReturn(queryIdAIIResponse) + when(mockExecution.getVariable(Prefix + "cloudRegionPo")).thenReturn("RDM2WAGPLCP") + when(mockExecution.getVariable(Prefix + "messageId")).thenReturn("messageId_generated") + when(mockExecution.getVariable(Prefix + "source")).thenReturn("VID") + //when(mockExecution.getVariable(Prefix + "queryVpnBindingAAIResponse")).thenReturn(queryVpnBindingAAIResponse) + when(mockExecution.getVariable(Prefix + "routeCollection")).thenReturn("<routeTargets>13979:105757</routeTargets><routeTargets>13979:105757</routeTargets>") + when(mockExecution.getVariable(Prefix + "networkCollection")).thenReturn("<policyFqdns>GN_EVPN_Test</policyFqdns>") + when(mockExecution.getVariable(Prefix + "tableRefCollection")).thenReturn("<routeTableFqdns>refFQDN1</routeTableFqdns><routeTableFqdns>refFQDN2</routeTableFqdns>") + when(mockExecution.getVariable(Prefix + "requestId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + //when(mockExecution.getVariable("URN_?????")).thenReturn("") // notificationUrl, //TODO - is this coming from URN? What variable/value to use? + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable(Prefix + "rollbackEnabled")).thenReturn("true") + when(mockExecution.getVariable("mso-request-id")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + + // preProcessRequest(DelegateExecution execution) + DoCreateNetworkInstance DoCreateNetworkInstance = new DoCreateNetworkInstance() + DoCreateNetworkInstance.prepareCreateNetworkRequest(mockExecution) + + // check the sequence of variable invocation + //MockitoDebuggerImpl preDebugger = new MockitoDebuggerImpl() + //preDebugger.printInvocations(mockExecution) + + // verify set prefix = Prefix + "" + verify(mockExecution).setVariable("prefix", Prefix) + + verify(mockExecution).setVariable(Prefix + "createNetworkRequest", createNetworkRequest) + + } + + + @Test + //@Ignore + public void prepareCreateNetworkRequest_Ipv4() { + + println "************ prepareNetworkRequest ************* " + ExecutionEntity mockExecution = setupMock() + // Initialize prerequisite variables + when(mockExecution.getVariable(Prefix + "networkRequest")).thenReturn(expectedvIPRNetworkRequest) + when(mockExecution.getVariable(Prefix + "queryIdAAIResponse")).thenReturn(queryIdAIIResponse_Ipv4) + when(mockExecution.getVariable(Prefix + "cloudRegionPo")).thenReturn("RDM2WAGPLCP") + when(mockExecution.getVariable(Prefix + "messageId")).thenReturn("messageId_generated") + when(mockExecution.getVariable(Prefix + "source")).thenReturn("VID") + //when(mockExecution.getVariable(Prefix + "queryVpnBindingAAIResponse")).thenReturn(queryVpnBindingAAIResponse) + when(mockExecution.getVariable(Prefix + "routeCollection")).thenReturn("<routeTargets>13979:105757</routeTargets><routeTargets>13979:105757</routeTargets>") + when(mockExecution.getVariable(Prefix + "networkCollection")).thenReturn("<policyFqdns>GN_EVPN_Test</policyFqdns>") + when(mockExecution.getVariable(Prefix + "tableRefCollection")).thenReturn("<routeTableFqdns>refFQDN1</routeTableFqdns><routeTableFqdns>refFQDN2</routeTableFqdns>") + when(mockExecution.getVariable(Prefix + "requestId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + //when(mockExecution.getVariable("URN_?????")).thenReturn("") // notificationUrl, //TODO - is this coming from URN? What variable/value to use? + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable(Prefix + "rollbackEnabled")).thenReturn("true") + when(mockExecution.getVariable("mso-request-id")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + + // preProcessRequest(DelegateExecution execution) + DoCreateNetworkInstance DoCreateNetworkInstance = new DoCreateNetworkInstance() + DoCreateNetworkInstance.prepareCreateNetworkRequest(mockExecution) + + // check the sequence of variable invocation + //MockitoDebuggerImpl preDebugger = new MockitoDebuggerImpl() + //preDebugger.printInvocations(mockExecution) + + // verify set prefix = Prefix + "" + verify(mockExecution).setVariable("prefix", Prefix) + + verify(mockExecution).setVariable(Prefix + "createNetworkRequest", createNetworkRequest_Ipv4) + + } + + @Test + //@Ignore + public void prepareCreateNetworkRequest_AlaCarte() { + + println "************ prepareNetworkRequest ************* " + ExecutionEntity mockExecution = setupMock() + // Initialize prerequisite variables + when(mockExecution.getVariable(Prefix + "networkRequest")).thenReturn(expectedJSONNetworkRequest) + when(mockExecution.getVariable(Prefix + "queryIdAAIResponse")).thenReturn(queryIdAIIResponse_AlaCarte) + when(mockExecution.getVariable(Prefix + "cloudRegionPo")).thenReturn("RDM2WAGPLCP") + when(mockExecution.getVariable(Prefix + "messageId")).thenReturn("messageId_generated") + when(mockExecution.getVariable(Prefix + "source")).thenReturn("VID") + //when(mockExecution.getVariable(Prefix + "queryVpnBindingAAIResponse")).thenReturn(queryVpnBindingAAIResponse) + when(mockExecution.getVariable(Prefix + "routeCollection")).thenReturn("<routeTargets>13979:105757</routeTargets><routeTargets>13979:105757</routeTargets>") + when(mockExecution.getVariable(Prefix + "networkCollection")).thenReturn("<policyFqdns>GN_EVPN_Test</policyFqdns>") + when(mockExecution.getVariable(Prefix + "tableRefCollection")).thenReturn("<routeTableFqdns>refFQDN1</routeTableFqdns><routeTableFqdns>refFQDN2</routeTableFqdns>") + when(mockExecution.getVariable(Prefix + "requestId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + //when(mockExecution.getVariable("URN_?????")).thenReturn("") // notificationUrl, //TODO - is this coming from URN? What variable/value to use? + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable(Prefix + "rollbackEnabled")).thenReturn("true") + when(mockExecution.getVariable("mso-request-id")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + + // preProcessRequest(DelegateExecution execution) + DoCreateNetworkInstance DoCreateNetworkInstance = new DoCreateNetworkInstance() + DoCreateNetworkInstance.prepareCreateNetworkRequest(mockExecution) + + // check the sequence of variable invocation + //MockitoDebuggerImpl preDebugger = new MockitoDebuggerImpl() + //preDebugger.printInvocations(mockExecution) + + // verify set prefix = Prefix + "" + verify(mockExecution).setVariable("prefix", Prefix) + + verify(mockExecution).setVariable(Prefix + "createNetworkRequest", createNetworkRequestAlaCarte) + + } + + @Test + //@Ignore + public void prepareCreateNetworkRequest_SRIOV() { + + println "************ prepareNetworkRequest ************* " + ExecutionEntity mockExecution = setupMock() + // Initialize prerequisite variables + when(mockExecution.getVariable(Prefix + "networkRequest")).thenReturn(expectedvIPRNetworkRequest) + when(mockExecution.getVariable(Prefix + "queryIdAAIResponse")).thenReturn(queryIdAIIResponse_SRIOV) + when(mockExecution.getVariable(Prefix + "cloudRegionPo")).thenReturn("RDM2WAGPLCP") + when(mockExecution.getVariable(Prefix + "messageId")).thenReturn("messageId_generated") + when(mockExecution.getVariable(Prefix + "source")).thenReturn("VID") + //when(mockExecution.getVariable(Prefix + "queryVpnBindingAAIResponse")).thenReturn(queryVpnBindingAAIResponse) + when(mockExecution.getVariable(Prefix + "routeCollection")).thenReturn("<routeTargets>13979:105757</routeTargets><routeTargets>13979:105757</routeTargets>") + when(mockExecution.getVariable(Prefix + "networkCollection")).thenReturn("<policyFqdns>GN_EVPN_Test</policyFqdns>") + when(mockExecution.getVariable(Prefix + "tableRefCollection")).thenReturn("<routeTableFqdns>refFQDN1</routeTableFqdns><routeTableFqdns>refFQDN2</routeTableFqdns>") + when(mockExecution.getVariable(Prefix + "requestId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + //when(mockExecution.getVariable("URN_?????")).thenReturn("") // notificationUrl, //TODO - is this coming from URN? What variable/value to use? + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable(Prefix + "rollbackEnabled")).thenReturn("true") + when(mockExecution.getVariable("mso-request-id")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + + // preProcessRequest(DelegateExecution execution) + DoCreateNetworkInstance DoCreateNetworkInstance = new DoCreateNetworkInstance() + DoCreateNetworkInstance.prepareCreateNetworkRequest(mockExecution) + + // check the sequence of variable invocation + //MockitoDebuggerImpl preDebugger = new MockitoDebuggerImpl() + //preDebugger.printInvocations(mockExecution) + + // verify set prefix = Prefix + "" + verify(mockExecution).setVariable("prefix", Prefix) + + verify(mockExecution).setVariable(Prefix + "createNetworkRequest", createNetworkRequest_SRIOV) + + } + + + @Test + //@Ignore + public void prepareSDNCRequest() { + + println "************ prepareSDNCRequest ************* " + + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + // Initialize prerequisite variables + when(mockExecution.getVariable(Prefix + "networkRequest")).thenReturn(expectedvIPRNetworkRequest) + when(mockExecution.getVariable(Prefix + "cloudRegionSdnc")).thenReturn("RDM2WAGPLCP") + when(mockExecution.getVariable(Prefix + "serviceInstanceId")).thenReturn("f70e927b-6087-4974-9ef8-c5e4d5847ca4") + when(mockExecution.getVariable(Prefix + "networkId")).thenReturn("networkId") + when(mockExecution.getVariable("mso-request-id")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + when(mockExecution.getVariable("testMessageId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + when(mockExecution.getVariable("mso.workflow.sdncadapter.callback")).thenReturn("http://localhost:8090/SDNCAdapterCallback") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("GENGSI_siResourceLink")).thenReturn("https://aai-int1.test.com:8443/aai/v8/business/customers/customer/MSO_1610_dev/service-subscriptions/service-subscription/MSO-dev-service-type/service-instances/service-instance/6d4eb22a-82f1-4257-9f80-4176262cfe69/") + + + // preProcessRequest(DelegateExecution execution) + DoCreateNetworkInstance DoCreateNetworkInstance = new DoCreateNetworkInstance() + DoCreateNetworkInstance.prepareSDNCRequest(mockExecution) + + // verify set prefix = Prefix + "" + verify(mockExecution).setVariable("prefix", Prefix) + verify(mockExecution).setVariable(Prefix + "assignSDNCRequest", assignSDNCRequest) + + } + + @Test + //@Ignore + public void prepareSDNCRequest_decodeUrlLink() { + + println "************ prepareSDNCRequest ************* " + + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + // Initialize prerequisite variables + when(mockExecution.getVariable(Prefix + "networkRequest")).thenReturn(expectedvIPRNetworkRequest) + when(mockExecution.getVariable(Prefix + "cloudRegionSdnc")).thenReturn("RDM2WAGPLCP") + when(mockExecution.getVariable(Prefix + "serviceInstanceId")).thenReturn("f70e927b-6087-4974-9ef8-c5e4d5847ca4") + when(mockExecution.getVariable(Prefix + "networkId")).thenReturn("networkId") + when(mockExecution.getVariable("mso-request-id")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + when(mockExecution.getVariable("testMessageId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + when(mockExecution.getVariable("mso.workflow.sdncadapter.callback")).thenReturn("http://localhost:8090/SDNCAdapterCallback") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("GENGSI_siResourceLink")).thenReturn("https://aai-int1.test.com:8443/aai/v8/business/customers/customer/MSO_1610_dev/service-subscriptions/service-subscription/VIRTUAL%20USP/service-instances/service-instance/6d4eb22a-82f1-4257-9f80-4176262cfe69/") + + + // preProcessRequest(DelegateExecution execution) + DoCreateNetworkInstance DoCreateNetworkInstance = new DoCreateNetworkInstance() + DoCreateNetworkInstance.prepareSDNCRequest(mockExecution) + + // verify set prefix = Prefix + "" + verify(mockExecution).setVariable("prefix", Prefix) + verify(mockExecution).setVariable(Prefix + "assignSDNCRequest", assignSDNCRequest_decodeUrlLink) + + } + + @Test + //@Ignore + public void prepareRpcSDNCRequest() { + + println "************ prepareRpcSDNCRequest ************* " + + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + // Initialize prerequisite variables + when(mockExecution.getVariable(Prefix + "networkRequest")).thenReturn(expectedvIPRNetworkRequest) + when(mockExecution.getVariable(Prefix + "cloudRegionSdnc")).thenReturn("RDM2WAGPLCP") + when(mockExecution.getVariable(Prefix + "serviceInstanceId")).thenReturn("f70e927b-6087-4974-9ef8-c5e4d5847ca4") + when(mockExecution.getVariable("mso-request-id")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + when(mockExecution.getVariable("msoRequestId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + when(mockExecution.getVariable("testMessageId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") // test ONLY + when(mockExecution.getVariable(Prefix + "networkId")).thenReturn("networkId") + when(mockExecution.getVariable("mso.workflow.sdncadapter.callback")).thenReturn("http://localhost:8090/SDNCAdapterCallback") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("GENGSI_siResourceLink")).thenReturn("https://aai-int1.test.com:8443/aai/v8/business/customers/customer/MSO_1610_dev/service-subscriptions/service-subscription/MSO-dev-service-type/service-instances/service-instance/6d4eb22a-82f1-4257-9f80-4176262cfe69/") + + // preProcessRequest(DelegateExecution execution) + DoCreateNetworkInstance DoCreateNetworkInstance = new DoCreateNetworkInstance() + DoCreateNetworkInstance.prepareRpcSDNCRequest(mockExecution) + + // verify set prefix = Prefix + "" + verify(mockExecution).setVariable("prefix", Prefix) + verify(mockExecution).setVariable(Prefix + "assignSDNCRequest", assignRpcSDNCRequest) + + } + + @Test + //@Ignore + public void prepareSDNCRollbackRequest() { + + println "************ prepareSDNCRollbackRequest ************* " + + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + // Initialize prerequisite variables + when(mockExecution.getVariable(Prefix + "networkRequest")).thenReturn(expectedvIPRNetworkRequest) + when(mockExecution.getVariable(Prefix + "cloudRegionSdnc")).thenReturn("RDM2WAGPLCP") + when(mockExecution.getVariable(Prefix + "serviceInstanceId")).thenReturn("f70e927b-6087-4974-9ef8-c5e4d5847ca4") + when(mockExecution.getVariable(Prefix + "assignSDNCResponse")).thenReturn(assignResponse) + when(mockExecution.getVariable(Prefix + "networkId")).thenReturn("8abc633a-810b-4ca5-8b3a-09511d13a2ce") + when(mockExecution.getVariable("mso-request-id")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + when(mockExecution.getVariable("testMessageId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + when(mockExecution.getVariable("mso.workflow.sdncadapter.callback")).thenReturn("http://localhost:8090/SDNCAdapterCallback") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("GENGSI_siResourceLink")).thenReturn("https://aai-int1.test.com:8443/aai/v8/business/customers/customer/MSO_1610_dev/service-subscriptions/service-subscription/MSO-dev-service-type/service-instances/service-instance/6d4eb22a-82f1-4257-9f80-4176262cfe69/") + + // preProcessRequest(DelegateExecution execution) + DoCreateNetworkInstance DoCreateNetworkInstance = new DoCreateNetworkInstance() + DoCreateNetworkInstance.prepareSDNCRollbackRequest(mockExecution) + + // verify set prefix = Prefix + "" + verify(mockExecution).setVariable("prefix", Prefix) + verify(mockExecution).setVariable(Prefix + "rollbackSDNCRequest", sdncRollbackRequest) + + } + + @Test + //@Ignore + public void prepareRpcSDNCActivateRequest() { + + println "************ prepareRpcSDNCActivateRequest ************* " + + ExecutionEntity mockExecution = setupMock() + // Initialize prerequisite variables + when(mockExecution.getVariable(Prefix + "networkRequest")).thenReturn(expectedvIPRNetworkRequest) + when(mockExecution.getVariable(Prefix + "cloudRegionSdnc")).thenReturn("RDM2WAGPLCP") + when(mockExecution.getVariable(Prefix + "serviceInstanceId")).thenReturn("f70e927b-6087-4974-9ef8-c5e4d5847ca4") + when(mockExecution.getVariable(Prefix + "networkId")).thenReturn("networkId") + when(mockExecution.getVariable("mso-request-id")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + when(mockExecution.getVariable("msoRequestId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + when(mockExecution.getVariable("testMessageId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") // test ONLY + when(mockExecution.getVariable("mso.workflow.sdncadapter.callback")).thenReturn("http://localhost:8090/SDNCAdapterCallback") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("GENGSI_siResourceLink")).thenReturn("https://aai-int1.test.com:8443/aai/v8/business/customers/customer/MSO_1610_dev/service-subscriptions/service-subscription/MSO-dev-service-type/service-instances/service-instance/6d4eb22a-82f1-4257-9f80-4176262cfe69/") + + // preProcessRequest(DelegateExecution execution) + DoCreateNetworkInstance DoCreateNetworkInstance = new DoCreateNetworkInstance() + DoCreateNetworkInstance.prepareRpcSDNCActivateRequest(mockExecution) + + // verify set prefix = Prefix + "" + verify(mockExecution).setVariable("prefix", Prefix) + verify(mockExecution).setVariable(Prefix + "activateSDNCRequest", activateSDNCRequest) + + } + + + @Test + //@Ignore + public void prepareRpcSDNCRollbackRequest() { + + println "************ prepareRpcSDNCRollbackRequest ************* " + + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + // Initialize prerequisite variables + when(mockExecution.getVariable(Prefix + "networkRequest")).thenReturn(expectedvIPRNetworkRequest) + when(mockExecution.getVariable(Prefix + "cloudRegionSdnc")).thenReturn("RDM2WAGPLCP") + when(mockExecution.getVariable(Prefix + "serviceInstanceId")).thenReturn("f70e927b-6087-4974-9ef8-c5e4d5847ca4") + when(mockExecution.getVariable(Prefix + "assignSDNCResponse")).thenReturn(assignResponse) + when(mockExecution.getVariable(Prefix + "networkId")).thenReturn("8abc633a-810b-4ca5-8b3a-09511d13a2ce") + when(mockExecution.getVariable("mso-request-id")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + when(mockExecution.getVariable("testMessageId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") // test ONLY + when(mockExecution.getVariable("msoRequestId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + when(mockExecution.getVariable("mso.workflow.sdncadapter.callback")).thenReturn("http://localhost:8090/SDNCAdapterCallback") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("GENGSI_siResourceLink")).thenReturn("https://aai-int1.test.com:8443/aai/v8/business/customers/customer/MSO_1610_dev/service-subscriptions/service-subscription/MSO-dev-service-type/service-instances/service-instance/6d4eb22a-82f1-4257-9f80-4176262cfe69/") + + // preProcessRequest(DelegateExecution execution) + DoCreateNetworkInstance DoCreateNetworkInstance = new DoCreateNetworkInstance() + DoCreateNetworkInstance.prepareRpcSDNCRollbackRequest(mockExecution) + + // verify set prefix = Prefix + "" + verify(mockExecution).setVariable("prefix", Prefix) + verify(mockExecution).setVariable(Prefix + "rollbackSDNCRequest", sdncRpcRollbackRequest) + + } + + @Test + //@Ignore + public void prepareRpcSDNCActivateRollback() { + + println "************ prepareRpcSDNCActivateRollback ************* " + + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + // Initialize prerequisite variables + when(mockExecution.getVariable(Prefix + "networkRequest")).thenReturn(expectedvIPRNetworkRequest) + when(mockExecution.getVariable(Prefix + "cloudRegionSdnc")).thenReturn("RDM2WAGPLCP") + when(mockExecution.getVariable(Prefix + "serviceInstanceId")).thenReturn("f70e927b-6087-4974-9ef8-c5e4d5847ca4") + when(mockExecution.getVariable(Prefix + "activateSDNCResponse")).thenReturn(assignResponse) + when(mockExecution.getVariable(Prefix + "networkId")).thenReturn("8abc633a-810b-4ca5-8b3a-09511d13a2ce") + when(mockExecution.getVariable("mso-request-id")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + when(mockExecution.getVariable("msoRequestId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + when(mockExecution.getVariable("testMessageId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") // test ONLY + when(mockExecution.getVariable("mso.workflow.sdncadapter.callback")).thenReturn("http://localhost:8090/SDNCAdapterCallback") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("GENGSI_siResourceLink")).thenReturn("https://aai-int1.test.com:8443/aai/v8/business/customers/customer/MSO_1610_dev/service-subscriptions/service-subscription/MSO-dev-service-type/service-instances/service-instance/6d4eb22a-82f1-4257-9f80-4176262cfe69/") + + // preProcessRequest(DelegateExecution execution) + DoCreateNetworkInstance DoCreateNetworkInstance = new DoCreateNetworkInstance() + DoCreateNetworkInstance.prepareRpcSDNCActivateRollback(mockExecution) + + // verify set prefix = Prefix + "" + verify(mockExecution).setVariable("prefix", Prefix) + //verify(mockExecution).setVariable("mso-request-id", "88f65519-9a38-4c4b-8445-9eb4a5a5af56") + //verify(mockExecution).setVariable(Prefix + "requestId", "88f65519-9a38-4c4b-8445-9eb4a5a5af56") + //verify(mockExecution).setVariable("mso-service-instance-id", "88f65519-9a38-4c4b-8445-9eb4a5a5af56") + verify(mockExecution).setVariable(Prefix + "rollbackActivateSDNCRequest", sdncActivateRollbackRequest) + + } + + @Test + //@Ignore + public void callRESTQueryAAINetworkName_200() { + + println "************ callRESTQueryAAINetworkName ************* " + + WireMock.reset(); + MockGetNetworkByName("MNS-25180-L-01-dmz_direct_net_1", "CreateNetworkV2/createNetwork_queryName_AAIResponse_Success.xml"); + + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable(Prefix + "networkInputs")).thenReturn(networkInputs) + when(mockExecution.getVariable(Prefix + "messageId")).thenReturn("e8ebf6a0-f8ea-4dc0-8b99-fe98a87722d6") + when(mockExecution.getVariable("aai.endpoint")).thenReturn("http://localhost:8090") + // old: when(mockExecution.getVariable("mso.workflow.DoCreateNetworkInstance.aai.network.l3-network.uri")).thenReturn("/aai/v8/network/l3-networks/l3-network") + when(mockExecution.getVariable("mso.workflow.DoCreateNetworkInstance.aai.l3-network.uri")).thenReturn("/aai/v8/network/l3-networks/l3-network") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn('http://org.openecomp.aai.inventory/') + when(mockExecution.getVariable("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") + when(mockExecution.getVariable("aai.auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") + + // preProcessRequest(DelegateExecution execution) + DoCreateNetworkInstance DoCreateNetworkInstance = new DoCreateNetworkInstance() + DoCreateNetworkInstance.callRESTQueryAAINetworkName(mockExecution) + + // check the sequence of variable invocation + //MockitoDebuggerImpl preDebugger = new MockitoDebuggerImpl() + //preDebugger.printInvocations(mockExecution) + + verify(mockExecution).setVariable("prefix", Prefix) + verify(mockExecution).setVariable(Prefix + "queryNameAAIRequest", "http://localhost:8090/aai/v8/network/l3-networks/l3-network?network-name=MNS-25180-L-01-dmz_direct_net_1") + + verify(mockExecution).setVariable(Prefix + "aaiNameReturnCode", "200") + verify(mockExecution).setVariable(Prefix + "orchestrationStatus", "PENDING-CREATE") + + } + + @Test + //@Ignore + public void callRESTQueryAAINetworkName_404() { + + println "************ callRESTQueryAAINetworkName ************* " + + WireMock.reset(); + MockGetNetworkByName_404("CreateNetworkV2/createNetwork_queryName_AAIResponse_Success.xml", "myOwn_Network"); + + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable(Prefix + "networkInputs")).thenReturn(networkInputs_404) + when(mockExecution.getVariable(Prefix + "messageId")).thenReturn("e8ebf6a0-f8ea-4dc0-8b99-fe98a87722d6") + when(mockExecution.getVariable("aai.endpoint")).thenReturn("http://localhost:8090") + // old: when(mockExecution.getVariable("mso.workflow.DoCreateNetworkInstance.aai.network.l3-network.uri")).thenReturn("/aai/v8/network/l3-networks/l3-network") + when(mockExecution.getVariable("mso.workflow.DoCreateNetworkInstance.aai.l3-network.uri")).thenReturn("/aai/v8/network/l3-networks/l3-network") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn('http://org.openecomp.aai.inventory/') + when(mockExecution.getVariable("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") + when(mockExecution.getVariable("aai.auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") + + // preProcessRequest(DelegateExecution execution) + DoCreateNetworkInstance DoCreateNetworkInstance = new DoCreateNetworkInstance() + DoCreateNetworkInstance.callRESTQueryAAINetworkName(mockExecution) + + // check the sequence of variable invocation + //MockitoDebuggerImpl preDebugger = new MockitoDebuggerImpl() + //preDebugger.printInvocations(mockExecution) + + verify(mockExecution, atLeast(1)).setVariable("prefix", Prefix) + verify(mockExecution).setVariable(Prefix + "queryNameAAIRequest", "http://localhost:8090/aai/v8/network/l3-networks/l3-network?network-name=myOwn_Network") + verify(mockExecution).setVariable(Prefix + "aaiNameReturnCode", "404") + + } + + @Test + //@Ignore + public void callRESTQueryAAINetworkId_200() { + + println "************ callRESTQueryAAINetworkId ************* " + + WireMock.reset(); + MockGetNetworkByIdWithDepth("49c86598-f766-46f8-84f8-8d1c1b10f9b4", "CreateNetworkV2/createNetwork_queryNetworkId_AAIResponse_Success.xml", "all"); + + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable(Prefix + "assignSDNCResponse")).thenReturn(sdncAdapterWorkflowAssignResponse) + when(mockExecution.getVariable(Prefix + "messageId")).thenReturn("e8ebf6a0-f8ea-4dc0-8b99-fe98a87722d6") + when(mockExecution.getVariable("aai.endpoint")).thenReturn("http://localhost:8090") + // old: when(mockExecution.getVariable("mso.workflow.DoCreateNetworkInstance.aai.network.l3-network.uri")).thenReturn("/aai/v8/network/l3-networks/l3-network") + when(mockExecution.getVariable("mso.workflow.DoCreateNetworkInstance.aai.l3-network.uri")).thenReturn("/aai/v9/network/l3-networks/l3-network") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("sdncVersion")).thenReturn("1702") + when(mockExecution.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn('http://org.openecomp.aai.inventory/') + when(mockExecution.getVariable("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") + when(mockExecution.getVariable("aai.auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") + + // preProcessRequest(DelegateExecution execution) + DoCreateNetworkInstance DoCreateNetworkInstance = new DoCreateNetworkInstance() + DoCreateNetworkInstance.callRESTQueryAAINetworkId(mockExecution) + + // check the sequence of variable invocation + //MockitoDebuggerImpl preDebugger = new MockitoDebuggerImpl() + //preDebugger.printInvocations(mockExecution) + + verify(mockExecution).setVariable("prefix", Prefix) + verify(mockExecution).setVariable(Prefix + "queryIdAAIRequest", "http://localhost:8090/aai/v9/network/l3-networks/l3-network/49c86598-f766-46f8-84f8-8d1c1b10f9b4"+"?depth=all") + verify(mockExecution).setVariable(Prefix + "aaiIdReturnCode", "200") + + } + + @Test + //@Ignore + public void callRESTQueryAAICloudRegion30_200() { + + println "************ callRESTQueryAAICloudRegion30_200 ************* " + + WireMock.reset(); + MockGetNetworkCloudRegion("CreateNetworkV2/cloudRegion25_AAIResponse_Success.xml", "RDM2WAGPLCP"); + + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("prefix")).thenReturn(Prefix) + when(mockExecution.getVariable(Prefix + "networkInputs")).thenReturn(expectedvIPRNetworkRequest) + when(mockExecution.getVariable("aai.endpoint")).thenReturn("http://localhost:8090") + // old: when(mockExecution.getVariable("mso.workflow.default.aai.cloud-infrastructure.cloud-region.uri")).thenReturn("/aai/v8/cloud-infrastructure/cloud-regions/cloud-region/att-aic") + when(mockExecution.getVariable("mso.workflow.global.default.aai.version")).thenReturn("8") + when(mockExecution.getVariable("mso.workflow.default.aai.v8.cloud-region.uri")).thenReturn("/aai/v8/cloud-infrastructure/cloud-regions/cloud-region/att-aic") + // + when(mockExecution.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn('http://org.openecomp.aai.inventory/') + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") + when(mockExecution.getVariable("aai.auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") + + // preProcessRequest(DelegateExecution execution) + DoCreateNetworkInstance DoCreateNetworkInstance = new DoCreateNetworkInstance() + DoCreateNetworkInstance.callRESTQueryAAICloudRegion(mockExecution) + + // check the sequence of variable invocation + //MockitoDebuggerImpl preDebugger = new MockitoDebuggerImpl() + //preDebugger.printInvocations(mockExecution) + + verify(mockExecution, atLeast(1)).setVariable("prefix", Prefix) + verify(mockExecution, atLeast(2)).setVariable(Prefix + "queryCloudRegionReturnCode", "200") + verify(mockExecution).setVariable(Prefix + "isCloudRegionGood", true) + + } + + @Test + //@Ignore + public void callRESTQueryAAICloudRegion25_200() { + + println "************ callRESTQueryAAICloudRegion25_200 ************* " + + WireMock.reset(); + MockGetNetworkCloudRegion("CreateNetworkV2/cloudRegion25_AAIResponse_Success.xml", "RDM2WAGPLCP"); + + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("prefix")).thenReturn(Prefix) + when(mockExecution.getVariable(Prefix + "networkInputs")).thenReturn(expectedvIPRNetworkRequest) + when(mockExecution.getVariable("aai.endpoint")).thenReturn("http://localhost:8090") + // old: when(mockExecution.getVariable("mso.workflow.default.aai.cloud-infrastructure.cloud-region.uri")).thenReturn("/aai/v8/cloud-infrastructure/cloud-regions/cloud-region/att-aic") + when(mockExecution.getVariable("mso.workflow.global.default.aai.version")).thenReturn("8") + when(mockExecution.getVariable("mso.workflow.default.aai.v8.cloud-region.uri")).thenReturn("/aai/v8/cloud-infrastructure/cloud-regions/cloud-region/att-aic") + // + when(mockExecution.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn('http://org.openecomp.aai.inventory/') + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") + when(mockExecution.getVariable("aai.auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") + + // preProcessRequest(DelegateExecution execution) + DoCreateNetworkInstance DoCreateNetworkInstance = new DoCreateNetworkInstance() + DoCreateNetworkInstance.callRESTQueryAAICloudRegion(mockExecution) + + // check the sequence of variable invocation + //MockitoDebuggerImpl preDebugger = new MockitoDebuggerImpl() + //preDebugger.printInvocations(mockExecution) + + verify(mockExecution, atLeast(1)).setVariable("prefix", Prefix) + verify(mockExecution, atLeast(2)).setVariable(Prefix + "queryCloudRegionReturnCode", "200") + verify(mockExecution).setVariable(Prefix + "isCloudRegionGood", true) + + } + + @Test + //@Ignore + public void callRESTQueryAAICloudRegion_NotFound() { + + println "************ callRESTQueryAAICloudRegionFake ************* " + + WireMock.reset(); + MockGetNetworkCloudRegion_404("MDTWNJ21") + + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("prefix")).thenReturn(Prefix) + when(mockExecution.getVariable(Prefix + "networkInputs")).thenReturn(vnfRequestFakeRegion) + when(mockExecution.getVariable("aai.endpoint")).thenReturn("http://localhost:8090") + //old: when(mockExecution.getVariable("mso.workflow.default.aai.cloud-infrastructure.cloud-region.uri")).thenReturn("/aai/v8/cloud-infrastructure/cloud-regions/cloud-region/att-aic") + when(mockExecution.getVariable("mso.workflow.global.default.aai.version")).thenReturn("8") + when(mockExecution.getVariable("mso.workflow.default.aai.v8.cloud-region.uri")).thenReturn("/aai/v8/cloud-infrastructure/cloud-regions/cloud-region/att-aic") + // + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn('http://org.openecomp.aai.inventory/') + when(mockExecution.getVariable("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") + when(mockExecution.getVariable("aai.auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") + + // preProcessRequest(DelegateExecution execution) + DoCreateNetworkInstance DoCreateNetworkInstance = new DoCreateNetworkInstance() + DoCreateNetworkInstance.callRESTQueryAAICloudRegion(mockExecution) + + // check the sequence of variable invocation + //MockitoDebuggerImpl preDebugger = new MockitoDebuggerImpl() + //preDebugger.printInvocations(mockExecution) + + verify(mockExecution, atLeast(1)).setVariable("prefix", Prefix) + verify(mockExecution, atLeast(1)).setVariable(Prefix + "queryCloudRegionReturnCode", "404") + verify(mockExecution).setVariable(Prefix + "cloudRegionPo", "MDTWNJ21") + verify(mockExecution).setVariable(Prefix + "cloudRegionSdnc", "AAIAIC25") + verify(mockExecution).setVariable(Prefix + "isCloudRegionGood", true) + + } + + @Test + //@Ignore + public void callRESTQueryAAINetworkVpnBinding_200() { + + println "************ callRESTQueryAAINetworkVpnBinding_200 ************* " + + WireMock.reset(); + MockGetNetworkVpnBinding("CreateNetworkV2/createNetwork_queryVpnBinding_AAIResponse_Success.xml", "85f015d0-2e32-4c30-96d2-87a1a27f8017"); + MockGetNetworkVpnBinding("CreateNetworkV2/createNetwork_queryVpnBinding_AAIResponse_Success.xml", "c980a6ef-3b88-49f0-9751-dbad8608d0a6"); + + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable(Prefix + "queryIdAAIResponse")).thenReturn(queryIdAIIResponse) // v6 + when(mockExecution.getVariable(Prefix + "messageId")).thenReturn("e8ebf6a0-f8ea-4dc0-8b99-fe98a87722d6") + when(mockExecution.getVariable("aai.endpoint")).thenReturn("http://localhost:8090") + // old: when(mockExecution.getVariable("mso.workflow.default.aai.network.vpn-binding.uri")).thenReturn("") + // old: when(mockExecution.getVariable("mso.workflow.DoCreateNetworkInstance.aai.network.vpn-binding.uri")).thenReturn("") + when(mockExecution.getVariable("mso.workflow.DoCreateNetworkInstance.aai.vpn-binding.uri")).thenReturn("/aai/v8/network/vpn-bindings/vpn-binding") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn('http://org.openecomp.aai.inventory/') + when(mockExecution.getVariable("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") + when(mockExecution.getVariable("aai.auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") + + // preProcessRequest(DelegateExecution execution) + DoCreateNetworkInstance DoCreateNetworkInstance = new DoCreateNetworkInstance() + DoCreateNetworkInstance.callRESTQueryAAINetworkVpnBinding(mockExecution) + + // check the sequence of variable invocation + //MockitoDebuggerImpl preDebugger = new MockitoDebuggerImpl() + //preDebugger.printInvocations(mockExecution) + + verify(mockExecution).setVariable("prefix", Prefix) + verify(mockExecution).setVariable(Prefix + "vpnCount", 2) + verify(mockExecution).setVariable(Prefix + "vpnBindings", ['/aai/v8/network/vpn-bindings/vpn-binding/85f015d0-2e32-4c30-96d2-87a1a27f8017/', '/aai/v8/network/vpn-bindings/vpn-binding/c980a6ef-3b88-49f0-9751-dbad8608d0a6/']) + // the last vpnBinding value is saved. + verify(mockExecution).setVariable(Prefix + "queryVpnBindingAAIRequest", "http://localhost:8090/aai/v8/network/vpn-bindings/vpn-binding/85f015d0-2e32-4c30-96d2-87a1a27f8017?depth=all") + verify(mockExecution, atLeast(2)).setVariable(Prefix + "aaiQqueryVpnBindingReturnCode", "200") + + } + + @Test + //@Ignore + public void callRESTQueryAAINetworkVpnBindingList_200() { + + println "************ callRESTQueryAAINetworkVpnBinding_200 ************* " + + WireMock.reset(); + MockGetNetworkVpnBinding("CreateNetworkV2/createNetwork_queryVpnBindingList_AAIResponse_Success.xml", "85f015d0-2e32-4c30-96d2-87a1a27f8017"); + MockGetNetworkVpnBinding("CreateNetworkV2/createNetwork_queryVpnBindingList_AAIResponse_Success.xml", "c980a6ef-3b88-49f0-9751-dbad8608d0a6"); + + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable(Prefix + "queryIdAAIResponse")).thenReturn(queryIdAIIResponse) // v6 + when(mockExecution.getVariable(Prefix + "messageId")).thenReturn("e8ebf6a0-f8ea-4dc0-8b99-fe98a87722d6") + when(mockExecution.getVariable("aai.endpoint")).thenReturn("http://localhost:8090") + when(mockExecution.getVariable("mso.workflow.DoCreateNetworkInstance.aai.vpn-binding.uri")).thenReturn("/aai/v8/network/vpn-bindings/vpn-binding") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn('http://org.openecomp.aai.inventory/') + when(mockExecution.getVariable("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") + when(mockExecution.getVariable("aai.auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") + + // preProcessRequest(DelegateExecution execution) + DoCreateNetworkInstance DoCreateNetworkInstance = new DoCreateNetworkInstance() + DoCreateNetworkInstance.callRESTQueryAAINetworkVpnBinding(mockExecution) + + verify(mockExecution).setVariable("prefix", Prefix) + verify(mockExecution).setVariable(Prefix + "vpnCount", 2) + verify(mockExecution).setVariable(Prefix + "vpnBindings", ['/aai/v8/network/vpn-bindings/vpn-binding/85f015d0-2e32-4c30-96d2-87a1a27f8017/', '/aai/v8/network/vpn-bindings/vpn-binding/c980a6ef-3b88-49f0-9751-dbad8608d0a6/']) + // the last vpnBinding value is saved. + verify(mockExecution).setVariable(Prefix + "queryVpnBindingAAIRequest", "http://localhost:8090/aai/v8/network/vpn-bindings/vpn-binding/85f015d0-2e32-4c30-96d2-87a1a27f8017?depth=all") + verify(mockExecution, atLeast(2)).setVariable(Prefix + "aaiQqueryVpnBindingReturnCode", "200") + + } + + @Test + //@Ignore + public void callRESTQueryAAINetworkVpnBinding_TestScenario01_200() { + + println "************ callRESTQueryAAINetworkVpnBinding_200 ************* " + + WireMock.reset(); + MockGetNetworkVpnBinding("CreateNetworkV2/createNetwork_queryVpnBinding_AAIResponse_Success.xml", "85f015d0-2e32-4c30-96d2-87a1a27f8017"); + + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable(Prefix + "queryIdAAIResponse")).thenReturn(queryIdAIIResponseTestScenario01) + when(mockExecution.getVariable(Prefix + "messageId")).thenReturn("e8ebf6a0-f8ea-4dc0-8b99-fe98a87722d6") + when(mockExecution.getVariable("aai.endpoint")).thenReturn("http://localhost:8090") + // old: when(mockExecution.getVariable("mso.workflow.default.aai.network.vpn-binding.uri")).thenReturn("") + // old: when(mockExecution.getVariable("mso.workflow.DoCreateNetworkInstance.aai.network.vpn-binding.uri")).thenReturn("") + when(mockExecution.getVariable("mso.workflow.DoCreateNetworkInstance.aai.vpn-binding.uri")).thenReturn("/aai/v8/network/vpn-bindings/vpn-binding") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn('http://org.openecomp.aai.inventory/') + when(mockExecution.getVariable("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") + when(mockExecution.getVariable("aai.auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") + + // preProcessRequest(DelegateExecution execution) + DoCreateNetworkInstance DoCreateNetworkInstance = new DoCreateNetworkInstance() + DoCreateNetworkInstance.callRESTQueryAAINetworkVpnBinding(mockExecution) + + // check the sequence of variable invocation + //MockitoDebuggerImpl preDebugger = new MockitoDebuggerImpl() + //preDebugger.printInvocations(mockExecution) + + verify(mockExecution).setVariable("prefix", Prefix) + verify(mockExecution).setVariable(Prefix + "vpnCount", 1) + verify(mockExecution).setVariable(Prefix + "vpnBindings", ['/aai/v8/network/vpn-bindings/vpn-binding/85f015d0-2e32-4c30-96d2-87a1a27f8017/']) + // the last vpnBinding value is saved. + verify(mockExecution).setVariable(Prefix + "queryVpnBindingAAIRequest", "http://localhost:8090/aai/v8/network/vpn-bindings/vpn-binding/85f015d0-2e32-4c30-96d2-87a1a27f8017?depth=all") + verify(mockExecution).setVariable(Prefix + "aaiQqueryVpnBindingReturnCode", "200") + + } + + @Test + //@Ignore + public void callRESTQueryAAINetworkVpnBinding_200_URN_Uri() { + + println "************ callRESTQueryAAINetworkVpnBinding_200 ************* " + + WireMock.reset(); + MockGetNetworkVpnBinding("CreateNetworkV2/createNetwork_queryVpnBinding_AAIResponse_Success.xml", "85f015d0-2e32-4c30-96d2-87a1a27f8017"); + MockGetNetworkVpnBinding("CreateNetworkV2/createNetwork_queryVpnBinding_AAIResponse_Success.xml", "c980a6ef-3b88-49f0-9751-dbad8608d0a6"); + + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable(Prefix + "queryIdAAIResponse")).thenReturn(queryIdAIIResponse) + when(mockExecution.getVariable(Prefix + "messageId")).thenReturn("e8ebf6a0-f8ea-4dc0-8b99-fe98a87722d6") + when(mockExecution.getVariable("aai.endpoint")).thenReturn("http://localhost:8090") + //when(mockExecution.getVariable("mso.workflow.DoCreateNetworkInstance.aai.network.vpn-binding.uri")).thenReturn("/aai/v8/network/vpn-bindings/vpn-binding") + //when(mockExecution.getVariable("mso.workflow.default.aai.network.vpn-binding.uri")).thenReturn("/aai/v8/network/vpn-bindings/vpn-binding") + when(mockExecution.getVariable("mso.workflow.global.default.aai.version")).thenReturn("8") + when(mockExecution.getVariable("mso.workflow.default.aai.v8.vpn-binding.uri")).thenReturn("/aai/v8/network/vpn-bindings/vpn-binding") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn('http://org.openecomp.aai.inventory/') + when(mockExecution.getVariable("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") + when(mockExecution.getVariable("aai.auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") + + // preProcessRequest(DelegateExecution execution) + DoCreateNetworkInstance DoCreateNetworkInstance = new DoCreateNetworkInstance() + DoCreateNetworkInstance.callRESTQueryAAINetworkVpnBinding(mockExecution) + + // check the sequence of variable invocation + //MockitoDebuggerImpl preDebugger = new MockitoDebuggerImpl() + //preDebugger.printInvocations(mockExecution) + + verify(mockExecution).setVariable("prefix", Prefix) + verify(mockExecution).setVariable(Prefix + "vpnCount", 2) + verify(mockExecution).setVariable(Prefix + "vpnBindings", ['/aai/v8/network/vpn-bindings/vpn-binding/85f015d0-2e32-4c30-96d2-87a1a27f8017/', '/aai/v8/network/vpn-bindings/vpn-binding/c980a6ef-3b88-49f0-9751-dbad8608d0a6/']) + // the last vpnBinding value is saved. + verify(mockExecution).setVariable(Prefix + "queryVpnBindingAAIRequest", "http://localhost:8090/aai/v8/network/vpn-bindings/vpn-binding/85f015d0-2e32-4c30-96d2-87a1a27f8017?depth=all") + verify(mockExecution, atLeast(2)).setVariable(Prefix + "aaiQqueryVpnBindingReturnCode", "200") + + } + + @Test + //@Ignore + public void callRESTQueryAAINetworkVpnBinding_NotPresent() { + + println "************ callRESTQueryAAINetworkVpnBinding_NotPresent ************* " + + WireMock.reset(); + MockGetNetworkVpnBinding("CreateNetworkV2/createNetwork_queryVpnBinding_AAIResponse_Success.xml", "85f015d0-2e32-4c30-96d2-87a1a27f8017"); + + ExecutionEntity mockExecution = setupMock() + // Initialize prerequisite variables + + when(mockExecution.getVariable(Prefix + "queryIdAAIResponse")).thenReturn(queryIdAIIResponseVpnNotPresent) + when(mockExecution.getVariable(Prefix + "messageId")).thenReturn("e8ebf6a0-f8ea-4dc0-8b99-fe98a87722d6") + when(mockExecution.getVariable("aai.endpoint")).thenReturn("http://localhost:8090") + //when(mockExecution.getVariable("mso.workflow.default.aai.network.l3-network.uri")).thenReturn("/aai/v8/network/l3-networks/l3-network") + when(mockExecution.getVariable("mso.workflow.global.default.aai.version")).thenReturn("8") + when(mockExecution.getVariable("mso.workflow.default.aai.v8.l3-network.uri")).thenReturn("/aai/v8/network/l3-networks/l3-network") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn('http://org.openecomp.aai.inventory/') + when(mockExecution.getVariable("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") + when(mockExecution.getVariable("aai.auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") + + // preProcessRequest(DelegateExecution execution) + DoCreateNetworkInstance DoCreateNetworkInstance = new DoCreateNetworkInstance() + DoCreateNetworkInstance.callRESTQueryAAINetworkVpnBinding(mockExecution) + + // check the sequence of variable invocation + //MockitoDebuggerImpl preDebugger = new MockitoDebuggerImpl() + //preDebugger.printInvocations(mockExecution) + + verify(mockExecution).setVariable("prefix", Prefix) + verify(mockExecution).setVariable(Prefix + "aaiQqueryVpnBindingReturnCode", "200") + verify(mockExecution).setVariable(Prefix + "vpnCount", 0) + verify(mockExecution).setVariable(Prefix + "queryVpnBindingAAIResponse", aaiVpnResponseStub) + + } + + @Test + //@Ignore + public void callRESTQueryAAINetworkPolicy_200() { + + println "************ callRESTQueryAAINetworkPolicy_200 ************* " + + WireMock.reset(); + MockGetNetworkPolicy("CreateNetworkV2/createNetwork_queryNetworkPolicy_AAIResponse_Success.xml", "cee6d136-e378-4678-a024-2cd15f0ee0cg"); + + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable(Prefix + "queryIdAAIResponse")).thenReturn(queryIdAIIResponse) + when(mockExecution.getVariable(Prefix + "messageId")).thenReturn("e8ebf6a0-f8ea-4dc0-8b99-fe98a87722d6") + when(mockExecution.getVariable("aai.endpoint")).thenReturn("http://localhost:8090") + //when(mockExecution.getVariable("mso.workflow.DoCreateNetworkInstance.aai.network-policy.uri")).thenReturn("") + // old: when(mockExecution.getVariable("mso.workflow.default.aai.network-policy.uri")).thenReturn("/aai/v8/network/network-policies/network-policy") + when(mockExecution.getVariable("mso.workflow.global.default.aai.version")).thenReturn("8") + when(mockExecution.getVariable("mso.workflow.default.aai.v8.network-policy.uri")).thenReturn("/aai/v8/network/network-policies/network-policy") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn('http://org.openecomp.aai.inventory/') + when(mockExecution.getVariable("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") + when(mockExecution.getVariable("aai.auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") + + // preProcessRequest(DelegateExecution execution) + DoCreateNetworkInstance DoCreateNetworkInstance = new DoCreateNetworkInstance() + DoCreateNetworkInstance.callRESTQueryAAINetworkPolicy(mockExecution) + + // check the sequence of variable invocation + //MockitoDebuggerImpl preDebugger = new MockitoDebuggerImpl() + //preDebugger.printInvocations(mockExecution) + + verify(mockExecution).setVariable("prefix", Prefix) + verify(mockExecution).setVariable(Prefix + "networkPolicyCount", 1) + verify(mockExecution).setVariable(Prefix + "networkPolicyUriList", ['/aai/v8/network/network-policies/network-policy/cee6d136-e378-4678-a024-2cd15f0ee0cg']) + // the last vpnBinding value is saved. + verify(mockExecution).setVariable(Prefix + "queryNetworkPolicyAAIRequest", "http://localhost:8090/aai/v8/network/network-policies/network-policy/cee6d136-e378-4678-a024-2cd15f0ee0cg?depth=all") + verify(mockExecution).setVariable(Prefix + "aaiQqueryNetworkPolicyReturnCode", "200") + + } + + @Test + //@Ignore + public void callRESTQueryAAINetworkTableRef_200() { + + println "************ callRESTQueryAAINetworkTableRef_200 ************* " + + WireMock.reset(); + MockGetNetworkTableReference("CreateNetworkV2/createNetwork_queryNetworkTableRef1_AAIResponse_Success.xml", "refFQDN1"); + MockGetNetworkTableReference("CreateNetworkV2/createNetwork_queryNetworkTableRef2_AAIResponse_Success.xml", "refFQDN2"); + + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable(Prefix + "queryIdAAIResponse")).thenReturn(queryIdAIIResponse) + when(mockExecution.getVariable(Prefix + "messageId")).thenReturn("e8ebf6a0-f8ea-4dc0-8b99-fe98a87722d6") + when(mockExecution.getVariable("aai.endpoint")).thenReturn("http://localhost:8090") + when(mockExecution.getVariable("mso.workflow.default.aai.network-table-reference.uri")).thenReturn("") + // old: when(mockExecution.getVariable("mso.workflow.DoCreateNetworkInstance.aai.network-table-reference.uri")).thenReturn("") + when(mockExecution.getVariable("mso.workflow.DoCreateNetworkInstance.aai.route-table-reference.uri")).thenReturn("/aai/v8/network/route-table-references/route-table-reference") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn('http://org.openecomp.aai.inventory/') + when(mockExecution.getVariable("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") + when(mockExecution.getVariable("aai.auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") + + // preProcessRequest(DelegateExecution execution) + DoCreateNetworkInstance DoCreateNetworkInstance = new DoCreateNetworkInstance() + DoCreateNetworkInstance.callRESTQueryAAINetworkTableRef(mockExecution) + + // check the sequence of variable invocation + //MockitoDebuggerImpl preDebugger = new MockitoDebuggerImpl() + //preDebugger.printInvocations(mockExecution) + + verify(mockExecution).setVariable("prefix", Prefix) + verify(mockExecution).setVariable(Prefix + "networkTableRefCount", 2) + verify(mockExecution).setVariable(Prefix + "networkTableRefUriList", ['/aai/v8/network/route-table-references/route-table-reference/refFQDN1','/aai/v8/network/route-table-references/route-table-reference/refFQDN2']) + // the last vpnBinding value is saved. + verify(mockExecution).setVariable(Prefix + "queryNetworkTableRefAAIRequest", "http://localhost:8090/aai/v8/network/route-table-references/route-table-reference/refFQDN1?depth=all") + verify(mockExecution, atLeast(2)).setVariable(Prefix + "aaiQqueryNetworkTableRefReturnCode", "200") + + } + + @Test + //@Ignore + public void callRESTReQueryAAINetworkId_200() { + + println "************ callRESTReQueryAAINetworkId ************* " + + WireMock.reset(); + MockGetNetworkByIdWithDepth("49c86598-f766-46f8-84f8-8d1c1b10f9b4", "CreateNetworkV2/createNetwork_queryNetworkId_AAIResponse_Success.xml", "all"); + + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable(Prefix + "networkId")).thenReturn("49c86598-f766-46f8-84f8-8d1c1b10f9b4") + when(mockExecution.getVariable(Prefix + "messageId")).thenReturn("e8ebf6a0-f8ea-4dc0-8b99-fe98a87722d6") + when(mockExecution.getVariable("aai.endpoint")).thenReturn("http://localhost:8090") + //when(mockExecution.getVariable("mso.workflow.default.aai.l3-network.version")).thenReturn("8") + when(mockExecution.getVariable("mso.workflow.DoCreateNetworkInstance.aai.l3-network.uri")).thenReturn("/aai/v9/network/l3-networks/l3-network") + //old: when(mockExecution.getVariable("mso.workflow.DoCreateNetworkInstance.aai.network.l3-network.uri")).thenReturn("/aai/v8/network/l3-networks/l3-network") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("sdncVersion")).thenReturn("1702") + when(mockExecution.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn('http://org.openecomp.aai.inventory/') + when(mockExecution.getVariable("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") + when(mockExecution.getVariable("aai.auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") + + // preProcessRequest(DelegateExecution execution) + DoCreateNetworkInstance DoCreateNetworkInstance = new DoCreateNetworkInstance() + DoCreateNetworkInstance.callRESTReQueryAAINetworkId(mockExecution) + + // check the sequence of variable invocation + //MockitoDebuggerImpl preDebugger = new MockitoDebuggerImpl() + //preDebugger.printInvocations(mockExecution) + + verify(mockExecution).setVariable("prefix", Prefix) + verify(mockExecution).setVariable(Prefix + "requeryIdAAIRequest", "http://localhost:8090/aai/v9/network/l3-networks/l3-network/49c86598-f766-46f8-84f8-8d1c1b10f9b4"+"?depth=all") + verify(mockExecution).setVariable(Prefix + "aaiRequeryIdReturnCode", "200") + + } + + @Test + //@Ignore + public void callRESTUpdateContrailAAINetworkREST_200() { + + println "************ callRESTUpdateContrailAAINetwork ************* " + + WireMock.reset(); + MockPutNetworkIdWithDepth("CreateNetworkV2/createNetwork_updateContrail_AAIResponse_Success.xml", "49c86598-f766-46f8-84f8-8d1c1b10f9b4", "all"); + + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable(Prefix + "networkId")).thenReturn("49c86598-f766-46f8-84f8-8d1c1b10f9b4") + when(mockExecution.getVariable(Prefix + "requeryIdAAIResponse")).thenReturn(queryIdAIIResponse) + when(mockExecution.getVariable(Prefix + "createNetworkResponse")).thenReturn(createNetworkResponseREST) + when(mockExecution.getVariable(Prefix + "messageId")).thenReturn("e8ebf6a0-f8ea-4dc0-8b99-fe98a87722d6") + when(mockExecution.getVariable("aai.endpoint")).thenReturn("http://localhost:8090") + // old: when(mockExecution.getVariable("mso.workflow.DoCreateNetworkInstance.aai.network.l3-network.uri")).thenReturn("/aai/v8/network/l3-networks/l3-network") + when(mockExecution.getVariable("mso.workflow.DoCreateNetworkInstance.aai.l3-network.uri")).thenReturn("/aai/v9/network/l3-networks/l3-network") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable(Prefix + "rollbackEnabled")).thenReturn("false") + when(mockExecution.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn('http://org.openecomp.aai.inventory/') + when(mockExecution.getVariable("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") + when(mockExecution.getVariable("aai.auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") + + // preProcessRequest(DelegateExecution execution) + DoCreateNetworkInstance DoCreateNetworkInstance = new DoCreateNetworkInstance() + DoCreateNetworkInstance.callRESTUpdateContrailAAINetwork(mockExecution) + + // check the sequence of variable invocation + //MockitoDebuggerImpl preDebugger = new MockitoDebuggerImpl() + //preDebugger.printInvocations(mockExecution) + + verify(mockExecution).setVariable("prefix", Prefix) + verify(mockExecution).setVariable(Prefix + "updateContrailAAIUrlRequest", "http://localhost:8090/aai/v9/network/l3-networks/l3-network/49c86598-f766-46f8-84f8-8d1c1b10f9b4"+"?depth=all") + verify(mockExecution).setVariable(Prefix + "updateContrailAAIPayloadRequest", updateContrailAAIPayloadRequest) + verify(mockExecution).setVariable(Prefix + "aaiUpdateContrailReturnCode", "200") + //verify(mockExecution).setVariable(Prefix + "updateContrailAAIResponse", updateContrailAAIResponse) + verify(mockExecution).setVariable(Prefix + "isPONR", true) + + } + + @Test + //@Ignore + public void callRESTUpdateContrailAAINetworkREST_200_segmentation() { + + println "************ callRESTUpdateContrailAAINetwork ************* " + + WireMock.reset(); + MockPutNetworkIdWithDepth("CreateNetworkV2/createNetwork_updateContrail_AAIResponse_Success.xml", "49c86598-f766-46f8-84f8-8d1c1b10f9b4", "all"); + + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable(Prefix + "networkId")).thenReturn("49c86598-f766-46f8-84f8-8d1c1b10f9b4") + when(mockExecution.getVariable(Prefix + "requeryIdAAIResponse")).thenReturn(queryIdAIIResponse_segmentation) + when(mockExecution.getVariable(Prefix + "createNetworkResponse")).thenReturn(createNetworkResponseREST) + when(mockExecution.getVariable(Prefix + "messageId")).thenReturn("e8ebf6a0-f8ea-4dc0-8b99-fe98a87722d6") + when(mockExecution.getVariable("aai.endpoint")).thenReturn("http://localhost:8090") + // old: when(mockExecution.getVariable("mso.workflow.DoCreateNetworkInstance.aai.network.l3-network.uri")).thenReturn("/aai/v8/network/l3-networks/l3-network") + when(mockExecution.getVariable("mso.workflow.DoCreateNetworkInstance.aai.l3-network.uri")).thenReturn("/aai/v9/network/l3-networks/l3-network") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable(Prefix + "rollbackEnabled")).thenReturn("false") + when(mockExecution.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn('http://org.openecomp.aai.inventory/') + when(mockExecution.getVariable("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") + when(mockExecution.getVariable("aai.auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") + + // preProcessRequest(DelegateExecution execution) + DoCreateNetworkInstance DoCreateNetworkInstance = new DoCreateNetworkInstance() + DoCreateNetworkInstance.callRESTUpdateContrailAAINetwork(mockExecution) + + // check the sequence of variable invocation + //MockitoDebuggerImpl preDebugger = new MockitoDebuggerImpl() + //preDebugger.printInvocations(mockExecution) + + verify(mockExecution).setVariable("prefix", Prefix) + verify(mockExecution).setVariable(Prefix + "updateContrailAAIUrlRequest", "http://localhost:8090/aai/v9/network/l3-networks/l3-network/49c86598-f766-46f8-84f8-8d1c1b10f9b4"+"?depth=all") + verify(mockExecution).setVariable(Prefix + "updateContrailAAIPayloadRequest", updateContrailAAIPayloadRequest_segmentation) + verify(mockExecution).setVariable(Prefix + "aaiUpdateContrailReturnCode", "200") + //verify(mockExecution).setVariable(Prefix + "updateContrailAAIResponse", updateContrailAAIResponse) + verify(mockExecution).setVariable(Prefix + "isPONR", true) + + } + + + + @Test + //@Ignore + public void validateCreateNetworkResponseREST() { + + println "************ validateNetworkResponse ************* " + + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + // Initialize prerequisite variables + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable(Prefix + "createNetworkResponse")).thenReturn(createNetworkResponseREST) + when(mockExecution.getVariable(Prefix + "networkReturnCode")).thenReturn('200') + + DoCreateNetworkInstance DoCreateNetworkInstance = new DoCreateNetworkInstance() + DoCreateNetworkInstance.validateCreateNetworkResponse(mockExecution) + + //MockitoDebuggerImpl debugger = new MockitoDebuggerImpl() + //debugger.printInvocations(mockExecution) + + verify(mockExecution).setVariable("prefix", Prefix) + verify(mockExecution).setVariable(Prefix + "createNetworkResponse", createNetworkResponseREST) + verify(mockExecution).setVariable(Prefix + "isNetworkRollbackNeeded", true) + verify(mockExecution).setVariable(Prefix + "rollbackNetworkRequest", createRollbackNetworkRequest) + + } + + @Test + //@Ignore + public void validateCreateNetworkResponseREST_Error() { + + println "************ validateNetworkResponse ************* " + + WorkflowException workflowException = new WorkflowException("DoCreateNetworkInstance", 2500, "Received error from Network Adapter: JBWEB000065: HTTP Status 500.") + + ExecutionEntity mockExecution = setupMock() + // Initialize prerequisite variables + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable(Prefix + "createNetworkResponse")).thenReturn(networkException500) + when(mockExecution.getVariable(Prefix + "networkReturnCode")).thenReturn('500') + + DoCreateNetworkInstance DoCreateNetworkInstance = new DoCreateNetworkInstance() + try { + DoCreateNetworkInstance.validateCreateNetworkResponse(mockExecution) + } catch (Exception ex) { + println " Test End - Handle catch-throw BpmnError()! " + } + + verify(mockExecution).setVariable("prefix", Prefix) + verify(mockExecution, atLeast(1)).setVariable("WorkflowException", refEq(workflowException, any(WorkflowException.class))) + + } + + @Test + //@Ignore + public void validateSDNCResponse() { + + println "************ validateSDNCResponse ************* " + + ExecutionEntity mockExecution = setupMock() + // Initialize prerequisite variables + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable(Prefix + "assignSDNCResponse")).thenReturn(sdncAdapterWorkflowResponse) + when(mockExecution.getVariable("prefix")).thenReturn(Prefix + "") + when(mockExecution.getVariable("SDNCA_SuccessIndicator")).thenReturn(true) + when(mockExecution.getVariable(Prefix + "sdncReturnCode")).thenReturn("200") + when(mockExecution.getVariable(Prefix + "isResponseGood")).thenReturn(true) + + DoCreateNetworkInstance DoCreateNetworkInstance = new DoCreateNetworkInstance() + try { + DoCreateNetworkInstance.validateSDNCResponse(mockExecution) + verify(mockExecution).setVariable(Prefix + "isSdncRollbackNeeded", true) + + } catch (Exception ex) { + println " Graceful Exit - " + ex.getMessage() + } + //MockitoDebuggerImpl debugger = new MockitoDebuggerImpl() + //debugger.printInvocations(mockExecution) + + //verify(mockExecution).setVariable(Prefix + "isSdncRollbackNeeded", true) + + } + + @Test + //@Ignore + public void validateSDNCResponse_Error() { + + println "************ validateSDNCResponse ************* " + + WorkflowException workflowException = new WorkflowException("DoCreateNetworkInstance", 2500, "Received error from SNDC Adapter: HTTP Status 500.") + + //ExecutionEntity mockExecution = mock(ExecutionEntity.class) + ExecutionEntity mockExecution = setupMock() + // Initialize prerequisite variables + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable(Prefix + "assignSDNCResponse")).thenReturn(sdncAdapterWorkflowResponse_Error) + when(mockExecution.getVariable("prefix")).thenReturn(Prefix + "") + when(mockExecution.getVariable("SDNCA_SuccessIndicator")).thenReturn(false) + when(mockExecution.getVariable(Prefix + "sdncReturnCode")).thenReturn("200") + when(mockExecution.getVariable("WorkflowException")).thenReturn(workflowException) + + + DoCreateNetworkInstance DoCreateNetworkInstance = new DoCreateNetworkInstance() + try { + DoCreateNetworkInstance.validateSDNCResponse(mockExecution) + } catch (Exception ex) { + println " Graceful Exit! - " + ex.getMessage() + } + //MockitoDebuggerImpl debugger = new MockitoDebuggerImpl() + //debugger.printInvocations(mockExecution) + + // verify set prefix = Prefix + "" + //verify(mockExecution).setVariable(Prefix + "sdncResponseSuccess", false) + + } + + @Test + //@Ignore + public void validateRpcSDNCActivateResponse() { + + println "************ validateRpcSDNCActivateResponse ************* " + + ExecutionEntity mockExecution = setupMock() + // Initialize prerequisite variables + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable(Prefix + "activateSDNCResponse")).thenReturn(sdncAdapterWorkflowResponse) + when(mockExecution.getVariable("prefix")).thenReturn(Prefix + "") + when(mockExecution.getVariable("SDNCA_SuccessIndicator")).thenReturn(true) + when(mockExecution.getVariable(Prefix + "sdncActivateReturnCode")).thenReturn("200") + + DoCreateNetworkInstance DoCreateNetworkInstance = new DoCreateNetworkInstance() + try { + DoCreateNetworkInstance.validateRpcSDNCActivateResponse(mockExecution) + verify(mockExecution).setVariable(Prefix + "isSdncActivateRollbackNeeded", true) + + } catch (Exception ex) { + println " Graceful Exit - " + ex.getMessage() + } + //MockitoDebuggerImpl debugger = new MockitoDebuggerImpl() + //debugger.printInvocations(mockExecution) + + //verify(mockExecution).setVariable(Prefix + "isSdncRollbackNeeded", true) + + } + + @Test + //@Ignore + public void prepareRollbackData() { + + println "************ prepareRollbackData() ************* " + + + + WorkflowException workflowException = new WorkflowException("DoCreateNetworkInstance", 2500, "Received error from Network Adapter: JBWEB000065: HTTP Status 500.") + + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + // Initialize prerequisite variables + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable(Prefix + "rollbackSDNCRequest")).thenReturn(rollbackSDNCRequest) + when(mockExecution.getVariable(Prefix + "rollbackActivateSDNCRequest")).thenReturn(rollbackActivateSDNCRequest) + when(mockExecution.getVariable(Prefix + "rollbackNetworkRequest")).thenReturn(rollbackNetworkRequest) + when(mockExecution.getVariable("WorkflowException")).thenReturn(workflowException) + + // preProcessRequest(DelegateExecution execution) + DoCreateNetworkInstance DoCreateNetworkInstance = new DoCreateNetworkInstance() + DoCreateNetworkInstance.prepareRollbackData(mockExecution) + +// verify(mockExecution).getVariable("isDebugLogEnabled") + verify(mockExecution).setVariable("prefix", Prefix) + + } + + @Test + public void postProcessResponse() { + + println "************ postProcessResponse() ************* " + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + // Initialize prerequisite variables + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("testProcessKey")).thenReturn("DoCreateNetworkInstanceTest") + when(mockExecution.getVariable(Prefix + "isException")).thenReturn(false) + when(mockExecution.getVariable("sdncVersion")).thenReturn("1702") + when(mockExecution.getVariable(Prefix + "rollbackSDNCRequest")).thenReturn(sdncRpcRollbackRequest) + when(mockExecution.getVariable(Prefix + "rollbackNetworkRequest")).thenReturn(rollbackSDNCRequest) + when(mockExecution.getVariable(Prefix + "rollbackActivateSDNCRequest")).thenReturn(sdncActivateRollbackRequest) + + + // preProcessRequest(DelegateExecution execution) + DoCreateNetworkInstance DoCreateNetworkInstance = new DoCreateNetworkInstance() + DoCreateNetworkInstance.postProcessResponse(mockExecution) + +// verify(mockExecution,atLeastOnce()).getVariable("isDebugLogEnabled") + verify(mockExecution,atLeastOnce()).setVariable("prefix", Prefix) + verify(mockExecution,atLeastOnce()).setVariable(Prefix + "Success", true) + + } + + private ExecutionEntity setupMock() { + + ProcessDefinition mockProcessDefinition = mock(ProcessDefinition.class) + when(mockProcessDefinition.getKey()).thenReturn("DoCreateNetworkInstance") + RepositoryService mockRepositoryService = mock(RepositoryService.class) + when(mockRepositoryService.getProcessDefinition()).thenReturn(mockProcessDefinition) + when(mockRepositoryService.getProcessDefinition().getKey()).thenReturn("DoCreateNetworkInstance") + when(mockRepositoryService.getProcessDefinition().getId()).thenReturn("100") + ProcessEngineServices mockProcessEngineServices = mock(ProcessEngineServices.class) + when(mockProcessEngineServices.getRepositoryService()).thenReturn(mockRepositoryService) + + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + // Initialize prerequisite variables + + when(mockExecution.getId()).thenReturn("100") + when(mockExecution.getProcessDefinitionId()).thenReturn("DoCreateNetworkInstance") + when(mockExecution.getProcessInstanceId()).thenReturn("DoCreateNetworkInstance") + when(mockExecution.getProcessEngineServices()).thenReturn(mockProcessEngineServices) + when(mockExecution.getProcessEngineServices().getRepositoryService().getProcessDefinition(mockExecution.getProcessDefinitionId())).thenReturn(mockProcessDefinition) + + return mockExecution + } +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateServiceInstanceTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateServiceInstanceTest.groovy new file mode 100644 index 0000000000..cc6f89865f --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateServiceInstanceTest.groovy @@ -0,0 +1,135 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts + +import com.github.tomakehurst.wiremock.junit.WireMockRule +import org.camunda.bpm.engine.ProcessEngineServices +import org.camunda.bpm.engine.RepositoryService +import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity +import org.camunda.bpm.engine.repository.ProcessDefinition +import org.junit.Assert +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.ArgumentCaptor +import org.mockito.Captor +import org.mockito.Mockito +import org.mockito.MockitoAnnotations +import org.mockito.runners.MockitoJUnitRunner +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.bpmn.core.domain.ModelInfo +import org.onap.so.bpmn.core.domain.ServiceDecomposition +import org.onap.so.bpmn.core.domain.ServiceInstance +import org.onap.so.bpmn.mock.StubResponseAAI + +import static org.mockito.Mockito.* + +@RunWith(MockitoJUnitRunner.class) +class DoCreateServiceInstanceTest { + def prefix = "DCRESI_" + + @Rule + public WireMockRule wireMockRule = new WireMockRule(28090) + + @Captor + static ArgumentCaptor<ExecutionEntity> captor = ArgumentCaptor.forClass(ExecutionEntity.class) + + @Before + void init() throws IOException { + MockitoAnnotations.initMocks(this); + } + + @Test + void testPreProcessRequest() { + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("prefix")).thenReturn(prefix) + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("msoRequestId")).thenReturn("12345") + when(mockExecution.getVariable("serviceInstanceId")).thenReturn("MIS/1604/0026/SW_INTERNET") + when(mockExecution.getVariable("lcpCloudRegionId")).thenReturn("MDTWNJ21") + when(mockExecution.getVariable("mso-request-id")).thenReturn("testRequestId-1503410089303") + when(mockExecution.getVariable("mso.workflow.sdncadapter.callback")).thenReturn("http://localhost:28080/mso/SDNCAdapterCallbackService") + when(mockExecution.getVariable("globalSubscriberId")).thenReturn("MSO_dev") + when(mockExecution.getVariable("subscriptionServiceType")).thenReturn("MSO-dev-service-type") + when(mockExecution.getVariable("productFamilyId")).thenReturn("RDM2WAGPLCP") + when(mockExecution.getVariable("sdnc.si.svc.types")).thenReturn("PORT-MIRROR,PPROBES") + + ServiceDecomposition decomposition = new ServiceDecomposition() + ModelInfo modelInfo = new ModelInfo() + ServiceInstance instance = new ServiceInstance() + instance.instanceId = "12345" + decomposition.modelInfo = modelInfo + decomposition.serviceInstance = instance + + when(mockExecution.getVariable("serviceDecomposition")).thenReturn(decomposition) + when(mockExecution.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn("http://org.openecomp.aai.inventory/") + when(mockExecution.getVariable("mso.workflow.default.aai.customer.version")).thenReturn("8") + when(mockExecution.getVariable("mso.workflow.default.aai.v8.customer.uri")).thenReturn('/aai/v8/business/customers/customer') + + + DoCreateServiceInstance obj = new DoCreateServiceInstance() + obj.preProcessRequest(mockExecution) + + verify(mockExecution).setVariable("prefix", prefix) + verify(mockExecution).setVariable("sdncCallbackUrl", "http://localhost:28080/mso/SDNCAdapterCallbackService") + } + + + + @Test + void testGetAAICustomerById() { + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("prefix")).thenReturn(prefix) + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("globalSubscriberId")).thenReturn("12345") + when(mockExecution.getVariable("mso.workflow.default.aai.v8.customer.uri")).thenReturn("/aai/v9/business/customers/customer") + when(mockExecution.getVariable("aai.endpoint")).thenReturn("http://localhost:28090") + when(mockExecution.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn("http://org.openecomp.aai.inventory/") + when(mockExecution.getVariable("mso.workflow.custom.DoCreateServiceInstance.aai.version")).thenReturn('8') + StubResponseAAI.MockGetCustomer("12345", "") + DoCreateServiceInstance obj = new DoCreateServiceInstance() + obj.getAAICustomerById(mockExecution) + + verify(mockExecution, times(1)).getVariable("aai.endpoint") + } + + private static ExecutionEntity setupMock() { + ProcessDefinition mockProcessDefinition = mock(ProcessDefinition.class) + when(mockProcessDefinition.getKey()).thenReturn("DoCreateServiceInstance") + RepositoryService mockRepositoryService = mock(RepositoryService.class) + when(mockRepositoryService.getProcessDefinition()).thenReturn(mockProcessDefinition) + when(mockRepositoryService.getProcessDefinition().getKey()).thenReturn("DoCreateServiceInstance") + when(mockRepositoryService.getProcessDefinition().getId()).thenReturn("100") + ProcessEngineServices mockProcessEngineServices = mock(ProcessEngineServices.class) + when(mockProcessEngineServices.getRepositoryService()).thenReturn(mockRepositoryService) + + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + // Initialize prerequisite variables + when(mockExecution.getId()).thenReturn("100") + when(mockExecution.getProcessDefinitionId()).thenReturn("DoCreateServiceInstance") + when(mockExecution.getProcessInstanceId()).thenReturn("DoCreateServiceInstance") + when(mockExecution.getProcessEngineServices()).thenReturn(mockProcessEngineServices) + when(mockExecution.getProcessEngineServices().getRepositoryService().getProcessDefinition(mockExecution.getProcessDefinitionId())).thenReturn(mockProcessDefinition) + + return mockExecution + } +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVFCNetworkServiceInstanceTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVFCNetworkServiceInstanceTest.groovy new file mode 100644 index 0000000000..6d9d5e5356 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVFCNetworkServiceInstanceTest.groovy @@ -0,0 +1,106 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts + +import com.github.tomakehurst.wiremock.junit.WireMockRule +import org.camunda.bpm.engine.ProcessEngineServices +import org.camunda.bpm.engine.RepositoryService +import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity +import org.camunda.bpm.engine.repository.ProcessDefinition +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.ArgumentCaptor +import org.mockito.Captor +import org.mockito.MockitoAnnotations +import org.mockito.runners.MockitoJUnitRunner + +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse +import static com.github.tomakehurst.wiremock.client.WireMock.put +import static com.github.tomakehurst.wiremock.client.WireMock.stubFor +import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching +import static org.mockito.Mockito.mock +import static org.mockito.Mockito.times +import static org.mockito.Mockito.verify +import static org.mockito.Mockito.when + +/** + * @author sushilma + * @since January 10, 2018 + */ +@RunWith(MockitoJUnitRunner.class) +class DoCreateVFCNetworkServiceInstanceTest { + + @Rule + public WireMockRule wireMockRule = new WireMockRule(28090) + @Before + public void init() throws IOException { + MockitoAnnotations.initMocks(this); + } + + @Captor + static ArgumentCaptor<ExecutionEntity> captor = ArgumentCaptor.forClass(ExecutionEntity.class) + + @Test + public void testAddNSRelationship(){ + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("aai.endpoint")).thenReturn("http://localhost:28090") + when(mockExecution.getVariable("nsInstanceId")).thenReturn("NS12345") + when(mockExecution.getVariable("globalSubscriberId")).thenReturn("MSO_dev") + when(mockExecution.getVariable("serviceType")).thenReturn("MSO-dev-service-type") + when(mockExecution.getVariable("serviceId")).thenReturn("SER12345") + when(mockExecution.getVariable("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") + when(mockExecution.getVariable("aai.auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") + MockPutServiceInstance("MSO_dev", "MSO-dev-service-type", "SER12345"); + DoCreateVFCNetworkServiceInstance DoCreateVFCNetworkServiceInstance = new DoCreateVFCNetworkServiceInstance() + DoCreateVFCNetworkServiceInstance.addNSRelationship(mockExecution); + verify(mockExecution, times(1)).getVariable("aai.endpoint") + verify(mockExecution, times(1)).getVariable("mso.msoKey") + verify(mockExecution, times(1)).getVariable("aai.auth") + } + + private ExecutionEntity setupMock() { + ProcessDefinition mockProcessDefinition = mock(ProcessDefinition.class) + when(mockProcessDefinition.getKey()).thenReturn("DoCreateVFCNetworkServiceInstance") + RepositoryService mockRepositoryService = mock(RepositoryService.class) + when(mockRepositoryService.getProcessDefinition()).thenReturn(mockProcessDefinition) + when(mockRepositoryService.getProcessDefinition().getKey()).thenReturn("DoCreateVFCNetworkServiceInstance") + when(mockRepositoryService.getProcessDefinition().getId()).thenReturn("100") + ProcessEngineServices mockProcessEngineServices = mock(ProcessEngineServices.class) + when(mockProcessEngineServices.getRepositoryService()).thenReturn(mockRepositoryService) + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + when(mockExecution.getId()).thenReturn("100") + when(mockExecution.getProcessDefinitionId()).thenReturn("DoCreateVFCNetworkServiceInstance") + when(mockExecution.getProcessInstanceId()).thenReturn("DoCreateVFCNetworkServiceInstance") + when(mockExecution.getProcessEngineServices()).thenReturn(mockProcessEngineServices) + when(mockExecution.getProcessEngineServices().getRepositoryService().getProcessDefinition(mockExecution.getProcessDefinitionId())).thenReturn(mockProcessDefinition) + return mockExecution + } + + public static void MockPutServiceInstance(String globalCustId, String subscriptionType, String serviceInstanceId) { + stubFor(put(urlMatching("/aai/v[0-9]+/business/customers/customer/" + globalCustId + "/service-subscriptions/service-subscription/" + subscriptionType + "/service-instances/service-instance/" + serviceInstanceId+"/relationship-list/relationship")) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml").withBody("") + )); + } +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModuleRollbackTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModuleRollbackTest.groovy new file mode 100644 index 0000000000..c5c6187648 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModuleRollbackTest.groovy @@ -0,0 +1,202 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts + +import com.github.tomakehurst.wiremock.junit.WireMockRule +import org.camunda.bpm.engine.ProcessEngineServices +import org.camunda.bpm.engine.RepositoryService +import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity +import org.camunda.bpm.engine.repository.ProcessDefinition +import org.junit.Assert +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.ArgumentCaptor +import org.mockito.Captor +import org.mockito.Mockito +import org.mockito.MockitoAnnotations +import org.mockito.runners.MockitoJUnitRunner +import org.onap.so.bpmn.common.scripts.utils.XmlComparator +import org.onap.so.bpmn.core.RollbackData +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.bpmn.mock.FileUtil + +import static com.github.tomakehurst.wiremock.client.WireMock.* +import static org.mockito.Mockito.* + +@RunWith(MockitoJUnitRunner.class) +class DoCreateVfModuleRollbackTest { + + def prefix = "DCVFMR_" + + @Rule + public WireMockRule wireMockRule = new WireMockRule(28090) + + @Captor + static ArgumentCaptor<ExecutionEntity> captor = ArgumentCaptor.forClass(ExecutionEntity.class) + + @Before + void init() throws IOException { + MockitoAnnotations.initMocks(this); + } + + @Test + void testPrepSDNCAdapterRequest() { + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("prefix")).thenReturn(prefix) + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable(prefix + "serviceInstanceId")).thenReturn("12345") + when(mockExecution.getVariable("testReqId")).thenReturn("testReqId") + when(mockExecution.getVariable("mso.workflow.sdncadapter.callback")).thenReturn("http://localhost:28080/mso/SDNCAdapterCallbackService") + when(mockExecution.getVariable(prefix + "source")).thenReturn("VID") + when(mockExecution.getVariable(prefix + "tenantId")).thenReturn("fba1bd1e195a404cacb9ce17a9b2b421") + when(mockExecution.getVariable(prefix + "vnfType")).thenReturn("vRRaas") + when(mockExecution.getVariable(prefix + "vnfName")).thenReturn("skask-test") + when(mockExecution.getVariable(prefix + "vnfId")).thenReturn("skask") + when(mockExecution.getVariable(prefix + "vfModuleModelName")).thenReturn("PCRF::module-0-2") + when(mockExecution.getVariable(prefix + "requestId")).thenReturn("testRequestId") + when(mockExecution.getVariable(prefix + "vfModuleId")).thenReturn("cb510af0-5b21-4bc7-86d9-323cb396ce32") + when(mockExecution.getVariable(prefix + "vfModuleName")).thenReturn("PCRF::module-0-2") + when(mockExecution.getVariable(prefix + "serviceId")).thenReturn("12345") + when(mockExecution.getVariable(prefix + "cloudSiteId")).thenReturn("RDM2WAGPLCP") + + when(mockExecution.getVariable(prefix + "rollbackSDNCRequestActivate")).thenReturn("true") + + + DoCreateVfModuleRollback obj = new DoCreateVfModuleRollback() + obj.prepSDNCAdapterRequest(mockExecution) + + Mockito.verify(mockExecution, times(1)).setVariable(captor.capture(), captor.capture()) + String expectedValue = FileUtil.readResourceFile("__files/DoCreateVfModuleRollback/sdncAdapterWorkflowRequest.xml") + XmlComparator.assertXMLEquals(expectedValue, captor.getValue()) + } + + + + @Test + void testBuildSDNCRequest() { + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("prefix")).thenReturn(prefix) + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable(prefix + "serviceInstanceId")).thenReturn("12345") + when(mockExecution.getVariable("testReqId")).thenReturn("testReqId") + when(mockExecution.getVariable("mso.workflow.sdncadapter.callback")).thenReturn("http://localhost:28080/mso/SDNCAdapterCallbackService") + when(mockExecution.getVariable(prefix + "source")).thenReturn("VID") + when(mockExecution.getVariable(prefix + "vnfType")).thenReturn("vRRaas") + when(mockExecution.getVariable(prefix + "vnfName")).thenReturn("skask-test") + when(mockExecution.getVariable(prefix + "vnfId")).thenReturn("skask") + when(mockExecution.getVariable(prefix + "requestId")).thenReturn("testRequestId") + when(mockExecution.getVariable(prefix + "vfModuleId")).thenReturn("cb510af0-5b21-4bc7-86d9-323cb396ce32") + when(mockExecution.getVariable(prefix + "vfModuleName")).thenReturn("PCRF::module-0-2") + when(mockExecution.getVariable(prefix + "serviceId")).thenReturn("12345") + + when(mockExecution.getVariable(prefix + "rollbackSDNCRequestActivate")).thenReturn("true") + + + DoCreateVfModuleRollback obj = new DoCreateVfModuleRollback() + String sdncRequest = obj.buildSDNCRequest(mockExecution, "svcInstId_test", "deactivate") + String expectedValue = FileUtil.readResourceFile("__files/DoCreateVfModuleRollback/deactivateSDNCRequest.xml") + XmlComparator.assertXMLEquals(expectedValue, sdncRequest) + } + + + + @Test + void testPrepVNFAdapterRequest() { + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("prefix")).thenReturn(prefix) + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable(prefix + "serviceInstanceId")).thenReturn("12345") + when(mockExecution.getVariable("testReqId")).thenReturn("testReqId") + when(mockExecution.getVariable("mso.use.qualified.host")).thenReturn("true") + when(mockExecution.getVariable(prefix + "vnfId")).thenReturn("skask") + when(mockExecution.getVariable(prefix + "requestId")).thenReturn("testRequestId") + when(mockExecution.getVariable(prefix + "vfModuleId")).thenReturn("cb510af0-5b21-4bc7-86d9-323cb396ce32") + when(mockExecution.getVariable(prefix + "mso-request-id")).thenReturn("12345") + when(mockExecution.getVariable("mso.workflow.message.endpoint")).thenReturn('http://localhost:18080/mso/WorkflowMessage/') + + + DoCreateVfModuleRollback obj = new DoCreateVfModuleRollback() + String sdncRequest = obj.prepVNFAdapterRequest(mockExecution) + + Mockito.verify(mockExecution, times(1)).setVariable(captor.capture(), captor.capture()) + String expectedValue = FileUtil.readResourceFile("__files/DoCreateVfModuleRollback/vnfAdapterRestV1Request.xml") + XmlComparator.assertXMLEquals(expectedValue, captor.getValue(), "messageId", "notificationUrl") + } + + @Test + void testDeleteNetworkPoliciesFromAAI() { + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("prefix")).thenReturn(prefix) + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("DCVFM_cloudSiteId")).thenReturn("12345") + when(mockExecution.getVariable("mso.workflow.DoCreateVfModuleRollback.aai.network-policy.uri")).thenReturn("/aai/v8/network/network-policies/network-policy") + when(mockExecution.getVariable("mso.workflow.custom.DoCreateVfModuleRollback.aai.version")).thenReturn("8") + when(mockExecution.getVariable("aai.endpoint")).thenReturn("http://localhost:28090") + when(mockExecution.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn("http://org.openecomp.aai.inventory/") + when(mockExecution.getVariable("rollbackData")).thenReturn(new RollbackData()) + List fqdnList = new ArrayList() + fqdnList.add("test") + when(mockExecution.getVariable(prefix + "createdNetworkPolicyFqdnList")).thenReturn(fqdnList) + mockData() + DoCreateVfModuleRollback obj = new DoCreateVfModuleRollback() + obj.deleteNetworkPoliciesFromAAI(mockExecution) + + Mockito.verify(mockExecution).setVariable("prefix", prefix) + Mockito.verify(mockExecution).setVariable(prefix + "networkPolicyFqdnCount", 1) + Mockito.verify(mockExecution).setVariable(prefix + "aaiQueryNetworkPolicyByFqdnReturnCode", 200) + } + + + private static ExecutionEntity setupMock() { + ProcessDefinition mockProcessDefinition = mock(ProcessDefinition.class) + when(mockProcessDefinition.getKey()).thenReturn("DoCreateVfModuleRollback") + RepositoryService mockRepositoryService = mock(RepositoryService.class) + when(mockRepositoryService.getProcessDefinition()).thenReturn(mockProcessDefinition) + when(mockRepositoryService.getProcessDefinition().getKey()).thenReturn("DoCreateVfModuleRollback") + when(mockRepositoryService.getProcessDefinition().getId()).thenReturn("100") + ProcessEngineServices mockProcessEngineServices = mock(ProcessEngineServices.class) + when(mockProcessEngineServices.getRepositoryService()).thenReturn(mockRepositoryService) + + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + // Initialize prerequisite variables + when(mockExecution.getId()).thenReturn("100") + when(mockExecution.getProcessDefinitionId()).thenReturn("DoCreateVfModuleRollback") + when(mockExecution.getProcessInstanceId()).thenReturn("DoCreateVfModuleRollback") + when(mockExecution.getProcessEngineServices()).thenReturn(mockProcessEngineServices) + when(mockExecution.getProcessEngineServices().getRepositoryService().getProcessDefinition(mockExecution.getProcessDefinitionId())).thenReturn(mockProcessDefinition) + + return mockExecution + } + + private static void mockData() { + stubFor(get(urlMatching("/aai/v[0-9]+/network/network-policies/network-policy\\?network-policy-fqdn=.*")) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBodyFile("VfModularity/QueryNetworkPolicy_AAIResponse_Success.xml"))) + stubFor(delete(urlMatching("/aai/v[0-9]+/network/network-policies/network-policy/.*")) + .willReturn(aResponse() + .withStatus(200))); + + } +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModuleTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModuleTest.groovy new file mode 100644 index 0000000000..30e3779b53 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModuleTest.groovy @@ -0,0 +1,229 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts + +import com.github.tomakehurst.wiremock.junit.WireMockRule +import org.camunda.bpm.engine.ProcessEngineServices +import org.camunda.bpm.engine.RepositoryService +import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity +import org.camunda.bpm.engine.repository.ProcessDefinition +import org.junit.Assert +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.ArgumentCaptor +import org.mockito.Captor +import org.mockito.Mockito +import org.mockito.MockitoAnnotations +import org.mockito.runners.MockitoJUnitRunner +import org.onap.so.bpmn.common.scripts.utils.XmlComparator +import org.onap.so.bpmn.core.RollbackData +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.bpmn.mock.FileUtil + +import static com.github.tomakehurst.wiremock.client.WireMock.* +import static org.mockito.Mockito.* + +@RunWith(MockitoJUnitRunner.class) +class DoCreateVfModuleTest { + def prefix = "DCVFM_" + + @Rule + public WireMockRule wireMockRule = new WireMockRule(28090) + + @Captor + static ArgumentCaptor<ExecutionEntity> captor = ArgumentCaptor.forClass(ExecutionEntity.class) + + @Before + void init() throws IOException { + MockitoAnnotations.initMocks(this); + } + + @Test + void testQueryAAIVfModule() { + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("prefix")).thenReturn(prefix) + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("DCVFM_vnfId")).thenReturn("12345") + when(mockExecution.getVariable("mso.workflow.DoCreateVfModule.aai.generic-vnf.uri")).thenReturn("/aai/v9/network/generic-vnfs/generic-vnf") + when(mockExecution.getVariable("aai.endpoint")).thenReturn("http://localhost:28090") + when(mockExecution.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn("http://org.openecomp.aai.inventory/") + + mockData() + DoCreateVfModule obj = new DoCreateVfModule() + obj.queryAAIVfModule(mockExecution) + Mockito.verify(mockExecution).setVariable("DCVFM_queryAAIVfModuleResponseCode", 200) + } + + + @Test + void testQueryAAIVfModuleForStatus() { + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("prefix")).thenReturn(prefix) + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("DCVFM_vnfId")).thenReturn("12345") + when(mockExecution.getVariable("DCVFM_vfModuleName")).thenReturn("module-0") + when(mockExecution.getVariable("mso.workflow.DoCreateVfModule.aai.generic-vnf.uri")).thenReturn("/aai/v9/network/generic-vnfs/generic-vnf") + when(mockExecution.getVariable("aai.endpoint")).thenReturn("http://localhost:28090") + when(mockExecution.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn("http://org.openecomp.aai.inventory/") + + mockData() + DoCreateVfModule obj = new DoCreateVfModule() + obj.queryAAIVfModuleForStatus(mockExecution) + Mockito.verify(mockExecution).setVariable("DCVFM_orchestrationStatus", '') + Mockito.verify(mockExecution).setVariable("DCVFM_queryAAIVfModuleForStatusResponseCode", 200) + } + + + + @Test + void testPreProcessVNFAdapterRequest() { + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("prefix")).thenReturn(prefix) + when(mockExecution.getVariable(prefix + "cloudSiteId")).thenReturn("RDM2WAGPLCP") + when(mockExecution.getVariable(prefix + "vfModuleId")).thenReturn("cb510af0-5b21-4bc7-86d9-323cb396ce32") + when(mockExecution.getVariable("volumeGroupStackId")).thenReturn("12345") + when(mockExecution.getVariable(prefix + "vfModuleName")).thenReturn("PCRF::module-0-2") + when(mockExecution.getVariable("lcpCloudRegionId")).thenReturn("MDTWNJ21") + when(mockExecution.getVariable(prefix + "tenantId")).thenReturn("fba1bd1e195a404cacb9ce17a9b2b421") + when(mockExecution.getVariable(prefix + "vnfType")).thenReturn("vRRaas") + when(mockExecution.getVariable(prefix + "vnfName")).thenReturn("skask-test") + when(mockExecution.getVariable(prefix + "vnfId")).thenReturn("skask") + when(mockExecution.getVariable(prefix + "vfModuleModelName")).thenReturn("PCRF::module-0-2") + when(mockExecution.getVariable(prefix + "vfModuleIndex")).thenReturn("index") + when(mockExecution.getVariable(prefix + "requestId")).thenReturn("testRequestId") + when(mockExecution.getVariable(prefix + "serviceId")).thenReturn("12345") + when(mockExecution.getVariable(prefix + "serviceInstanceId")).thenReturn("MIS/1604/0026/SW_INTERNET") + when(mockExecution.getVariable(prefix + "backoutOnFailure")).thenReturn("12345") + when(mockExecution.getVariable(prefix + "volumeGroupId")).thenReturn("12345") + when(mockExecution.getVariable(prefix + "asdcServiceModelVersion")).thenReturn("1.0") + when(mockExecution.getVariable(prefix + "modelCustomizationUuid")).thenReturn("cb510af0-5b21-4bc7-86d9-323cb396ced3") + when(mockExecution.getVariable("baseVfModuleId")).thenReturn("12345") + when(mockExecution.getVariable(prefix + "baseVfModuleHeatStackId")).thenReturn("12345") + String sdncGetResponse = FileUtil.readResourceFile("__files/DoCreateVfModule/sdncGetResponse.xml"); + when(mockExecution.getVariable(prefix + "getSDNCAdapterResponse")).thenReturn(sdncGetResponse) + Map<String, String> map = new HashMap<String, String>(); + map.put("vrr_image_name", "MDT17"); + map.put("availability_zone_0", "nova"); + map.put("vrr_flavor_name", "ns.c16r32d128.v1"); + when(mockExecution.getVariable("vnfParamsMap")).thenReturn(map) + when(mockExecution.getVariable("mso-request-id")).thenReturn("testRequestId-1503410089303") + when(mockExecution.getVariable("mso.use.qualified.host")).thenReturn("true") + when(mockExecution.getVariable("mso.workflow.message.endpoint")).thenReturn("http://localhost:28080/mso/WorkflowMesssage") + + mockData() + DoCreateVfModule obj = new DoCreateVfModule() + obj.preProcessVNFAdapterRequest(mockExecution) + + String createVnfARequest = FileUtil.readResourceFile("__files/DoCreateVfModule/createVnfARequest.xml") + Mockito.verify(mockExecution, times(1)).setVariable(captor.capture(), captor.capture()) + XmlComparator.assertXMLEquals(createVnfARequest, captor.getValue(), "messageId", "notificationUrl") + } + + @Test + void testQueryCloudRegion() { + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("prefix")).thenReturn(prefix) + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("DCVFM_cloudSiteId")).thenReturn("12345") + when(mockExecution.getVariable("mso.workflow.DoCreateVfModule.aai.cloud-region.uri")).thenReturn("/aai/v8/cloud-infrastructure/cloud-regions/cloud-region") + when(mockExecution.getVariable("aai.endpoint")).thenReturn("http://localhost:28090") + when(mockExecution.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn("http://org.openecomp.aai.inventory/") + + mockData() + DoCreateVfModule obj = new DoCreateVfModule() + obj.queryCloudRegion(mockExecution) + + Mockito.verify(mockExecution).setVariable("prefix", prefix) + Mockito.verify(mockExecution).setVariable(prefix + "queryCloudRegionRequest", "http://localhost:28090/aai/v8/cloud-infrastructure/cloud-regions/cloud-region/12345") + Mockito.verify(mockExecution).setVariable(prefix + "queryCloudRegionReturnCode", "200") + } + + + + @Test + void testCreateNetworkPoliciesInAAI() { + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("prefix")).thenReturn(prefix) + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("DCVFM_cloudSiteId")).thenReturn("12345") + when(mockExecution.getVariable("mso.workflow.DoCreateVfModule.aai.network-policy.uri")).thenReturn("/aai/v8/network/network-policies/network-policy") + when(mockExecution.getVariable("mso.workflow.custom.DoCreateVfModule.aai.version")).thenReturn("8") + when(mockExecution.getVariable("aai.endpoint")).thenReturn("http://localhost:28090") + when(mockExecution.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn("http://org.openecomp.aai.inventory/") + when(mockExecution.getVariable("rollbackData")).thenReturn(new RollbackData()) + List fqdnList = new ArrayList() + fqdnList.add("test") + when(mockExecution.getVariable("DCVFM_contrailNetworkPolicyFqdnList")).thenReturn(fqdnList) + + mockData() + DoCreateVfModule obj = new DoCreateVfModule() + obj.createNetworkPoliciesInAAI(mockExecution) + + Mockito.verify(mockExecution).setVariable("prefix", prefix) + Mockito.verify(mockExecution).setVariable(prefix + "networkPolicyFqdnCount", 1) + Mockito.verify(mockExecution).setVariable(prefix + "aaiQqueryNetworkPolicyByFqdnReturnCode", 200) + } + + + + private static ExecutionEntity setupMock() { + ProcessDefinition mockProcessDefinition = mock(ProcessDefinition.class) + when(mockProcessDefinition.getKey()).thenReturn("DoCreateVfModule") + RepositoryService mockRepositoryService = mock(RepositoryService.class) + when(mockRepositoryService.getProcessDefinition()).thenReturn(mockProcessDefinition) + when(mockRepositoryService.getProcessDefinition().getKey()).thenReturn("DoCreateVfModule") + when(mockRepositoryService.getProcessDefinition().getId()).thenReturn("100") + ProcessEngineServices mockProcessEngineServices = mock(ProcessEngineServices.class) + when(mockProcessEngineServices.getRepositoryService()).thenReturn(mockRepositoryService) + + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + // Initialize prerequisite variables + when(mockExecution.getId()).thenReturn("100") + when(mockExecution.getProcessDefinitionId()).thenReturn("DoCreateVfModule") + when(mockExecution.getProcessInstanceId()).thenReturn("DoCreateVfModule") + when(mockExecution.getProcessEngineServices()).thenReturn(mockProcessEngineServices) + when(mockExecution.getProcessEngineServices().getRepositoryService().getProcessDefinition(mockExecution.getProcessDefinitionId())).thenReturn(mockProcessDefinition) + + return mockExecution + } + + private static void mockData() { + stubFor(get(urlMatching(".*/aai/v[0-9]+/network/generic-vnfs/generic-vnf/12345[?]depth=1")) + .willReturn(aResponse() + .withStatus(200).withHeader("Content-Type", "text/xml") + .withBodyFile("DoCreateVfModule/getGenericVnfResponse.xml"))) + stubFor(get(urlMatching(".*/aai/v[0-9]+/network/generic-vnfs/generic-vnf/12345/vf-modules/vf-module[?]vf-module-name=module-0")) + .willReturn(aResponse() + .withStatus(200).withHeader("Content-Type", "text/xml") + .withBodyFile("DoCreateVfModule/getGenericVnfResponse.xml"))) + stubFor(get(urlMatching(".*/aai/v[0-9]+/cloud-infrastructure/cloud-regions/cloud-region/12345")) + .willReturn(aResponse() + .withStatus(200).withHeader("Content-Type", "text/xml") + .withBodyFile("DoCreateVfModule/cloudRegion_AAIResponse_Success.xml"))) + stubFor(get(urlMatching("/aai/v[0-9]+/network/network-policies/network-policy\\?network-policy-fqdn=.*")) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBodyFile("VfModularity/QueryNetworkPolicy_AAIResponse_Success.xml"))) + } +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModuleVolumeV2Test.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModuleVolumeV2Test.groovy new file mode 100644 index 0000000000..91e7086bd3 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModuleVolumeV2Test.groovy @@ -0,0 +1,135 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts + +import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity +import org.junit.Before +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.ArgumentCaptor +import org.mockito.Captor +import org.mockito.Mockito +import org.mockito.MockitoAnnotations +import org.mockito.runners.MockitoJUnitRunner +import org.onap.so.bpmn.common.scripts.MsoGroovyTest + +import static org.junit.Assert.assertEquals +import static org.junit.Assert.assertNotNull +import static org.mockito.Mockito.times +import static org.mockito.Mockito.when + + +@RunWith(MockitoJUnitRunner.class) +class DoCreateVfModuleVolumeV2Test extends MsoGroovyTest { + + @Captor + static ArgumentCaptor<ExecutionEntity> captor = ArgumentCaptor.forClass(ExecutionEntity.class) + + def String volumeRollbackRequest = """ +<rollbackVolumeGroupRequest> + <volumeGroupRollback> + <volumeGroupId>171907d6-cdf0-4e08-953d-81ee104005a7</volumeGroupId> + <volumeGroupStackId>{{VOLUMEGROUPSTACKID}}</volumeGroupStackId> + <tenantId>c2141e3fcae940fcb4797ec9115e5a7a</tenantId> + <cloudSiteId>mtwnj1a</cloudSiteId> + <volumeGroupCreated>true</volumeGroupCreated> + <msoRequest> + <requestId>230fd6ac-2a39-4be4-9b1e-7b7e1cc039b5</requestId> + <serviceInstanceId>88c871d6-be09-4982-8490-96b1d243fb34</serviceInstanceId> + </msoRequest> + <messageId>9a5a91e8-3b79-463c-81c3-874a78f5b567</messageId> + </volumeGroupRollback> + <skipAAI>true</skipAAI> + <notificationUrl>http://localhost:8080/mso/WorkflowMessage/VNFAResponse/9a5a91e8-3b79-463c-81c3-874a78f5b567</notificationUrl> +</rollbackVolumeGroupRequest> + """ + + def String volumeRollbackRequestWithStackId = """ +<rollbackVolumeGroupRequest> + <volumeGroupRollback> + <volumeGroupId>171907d6-cdf0-4e08-953d-81ee104005a7</volumeGroupId> + <volumeGroupStackId>mdt22avrr_volume01/0f1aaae8-efe3-45ce-83e1-bfad01db58d8</volumeGroupStackId> + <tenantId>c2141e3fcae940fcb4797ec9115e5a7a</tenantId> + <cloudSiteId>mtwnj1a</cloudSiteId> + <volumeGroupCreated>true</volumeGroupCreated> + <msoRequest> + <requestId>230fd6ac-2a39-4be4-9b1e-7b7e1cc039b5</requestId> + <serviceInstanceId>88c871d6-be09-4982-8490-96b1d243fb34</serviceInstanceId> + </msoRequest> + <messageId>9a5a91e8-3b79-463c-81c3-874a78f5b567</messageId> + </volumeGroupRollback> + <skipAAI>true</skipAAI> + <notificationUrl>http://localhost:8080/mso/WorkflowMessage/VNFAResponse/9a5a91e8-3b79-463c-81c3-874a78f5b567</notificationUrl> +</rollbackVolumeGroupRequest> + """ + + + + @Before + public void init() + { + MockitoAnnotations.initMocks(this) + } + + @Test + public void testBuildRollbackVolumeGroupRequestXml() { + DoCreateVfModuleVolumeV2 process = new DoCreateVfModuleVolumeV2() + String xml = process.buildRollbackVolumeGroupRequestXml( + "171907d6-cdf0-4e08-953d-81ee104005a7", // volumeGroupId + "mtwnj1a", // cloudSiteId + "c2141e3fcae940fcb4797ec9115e5a7a", // tenantId + "230fd6ac-2a39-4be4-9b1e-7b7e1cc039b5", // requestId + "88c871d6-be09-4982-8490-96b1d243fb34", // serviceInstanceId + "9a5a91e8-3b79-463c-81c3-874a78f5b567", // messageId + "http://localhost:8080/mso/WorkflowMessage/VNFAResponse/9a5a91e8-3b79-463c-81c3-874a78f5b567") // notificationUrl + + assertEquals(volumeRollbackRequest.replaceAll("\\s", ""), xml.replaceAll("\\s", "")) + } + + + @Test + public void testUpdateRollbackVolumeGroupRequestXml() { + DoCreateVfModuleVolumeV2 process = new DoCreateVfModuleVolumeV2() + String updatedXml = process.updateRollbackVolumeGroupRequestXml(volumeRollbackRequest, "mdt22avrr_volume01/0f1aaae8-efe3-45ce-83e1-bfad01db58d8") + assertEquals(volumeRollbackRequestWithStackId.replaceAll("\\s", ""), updatedXml.replaceAll("\\s", "")) + } + + @Test + public void testPrepareVnfAdapterCreateRequest (){ + ExecutionEntity mockExecution = setupMock('DoCreateVfModuleVolumeV2') + + when(mockExecution.getVariable("prefix")).thenReturn('DCVFMODVOLV2_') + when(mockExecution.getVariable("serviceInstanceId")).thenReturn('') + when(mockExecution.getVariable("vnfId")).thenReturn('test-vnf-id') + when(mockExecution.getVariable("mso-request-id")).thenReturn('1234') + when(mockExecution.getVariable("volumeGroupId")).thenReturn('1234') + when(mockExecution.getVariable("mso.use.qualified.host")).thenReturn("true") + when(mockExecution.getVariable("mso.workflow.message.endpoint")).thenReturn("http://localhost:28080/mso/WorkflowMesssage") + Map vfModuleInputParams = new HashMap() + vfModuleInputParams.put("param1","value1") + when(mockExecution.getVariable("vfModuleInputParams")).thenReturn(vfModuleInputParams) + DoCreateVfModuleVolumeV2 process = new DoCreateVfModuleVolumeV2() + process.prepareVnfAdapterCreateRequest(mockExecution,"true"); + Mockito.verify(mockExecution,times(2)).setVariable(captor.capture(), captor.capture()) + String DCVFMODVOLV2_createVnfARequest = captor.getValue(); + assertNotNull(DCVFMODVOLV2_createVnfARequest) + } +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVnfTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVnfTest.groovy new file mode 100644 index 0000000000..9b421d8b63 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVnfTest.groovy @@ -0,0 +1,106 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts + +import com.github.tomakehurst.wiremock.junit.WireMockRule +import org.camunda.bpm.engine.ProcessEngineServices +import org.camunda.bpm.engine.RepositoryService +import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity +import org.camunda.bpm.engine.repository.ProcessDefinition +import org.junit.Assert +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.ArgumentCaptor +import org.mockito.Captor +import org.mockito.Mockito +import org.mockito.MockitoAnnotations +import org.mockito.runners.MockitoJUnitRunner +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.bpmn.core.domain.VnfResource + +import static org.mockito.Mockito.* + +@RunWith(MockitoJUnitRunner.class) +class DoCreateVnfTest { + def prefix = "DoCVNF_" + + @Rule + public WireMockRule wireMockRule = new WireMockRule(28090) + + @Captor + static ArgumentCaptor<ExecutionEntity> captor = ArgumentCaptor.forClass(ExecutionEntity.class) + + @Before + void init() throws IOException { + MockitoAnnotations.initMocks(this); + } + + @Test + void testPreProcessRequest() { + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("prefix")).thenReturn(prefix) + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("msoRequestId")).thenReturn("12345") + when(mockExecution.getVariable("serviceInstanceId")).thenReturn("MIS/1604/0026/SW_INTERNET") + when(mockExecution.getVariable("vnfType")).thenReturn("vRRaas") + when(mockExecution.getVariable("vnfName")).thenReturn("skask-test") + + when(mockExecution.getVariable("productFamilyId")).thenReturn("RDM2WAGPLCP") + when(mockExecution.getVariable("lcpCloudRegionId")).thenReturn("MDTWNJ21") + + when(mockExecution.getVariable("vnfResourceDecomposition")).thenReturn(new VnfResource()) + when(mockExecution.getVariable("mso-request-id")).thenReturn("testRequestId-1503410089303") + when(mockExecution.getVariable("mso.workflow.sdncadapter.callback")).thenReturn("http://localhost:28080/mso/SDNCAdapterCallbackService") + + + + DoCreateVnf obj = new DoCreateVnf() + obj.preProcessRequest(mockExecution) + + Mockito.verify(mockExecution, times(31)).setVariable(captor.capture(), captor.capture()) + List list = captor.getAllValues() + String str = list.get(51) + Assert.assertEquals("http://localhost:28080/mso/SDNCAdapterCallbackService", str) + } + + private static ExecutionEntity setupMock() { + ProcessDefinition mockProcessDefinition = mock(ProcessDefinition.class) + when(mockProcessDefinition.getKey()).thenReturn("DoCreateVnf") + RepositoryService mockRepositoryService = mock(RepositoryService.class) + when(mockRepositoryService.getProcessDefinition()).thenReturn(mockProcessDefinition) + when(mockRepositoryService.getProcessDefinition().getKey()).thenReturn("DoCreateVnf") + when(mockRepositoryService.getProcessDefinition().getId()).thenReturn("100") + ProcessEngineServices mockProcessEngineServices = mock(ProcessEngineServices.class) + when(mockProcessEngineServices.getRepositoryService()).thenReturn(mockRepositoryService) + + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + // Initialize prerequisite variables + when(mockExecution.getId()).thenReturn("100") + when(mockExecution.getProcessDefinitionId()).thenReturn("DoCreateVnf") + when(mockExecution.getProcessInstanceId()).thenReturn("DoCreateVnf") + when(mockExecution.getProcessEngineServices()).thenReturn(mockProcessEngineServices) + when(mockExecution.getProcessEngineServices().getRepositoryService().getProcessDefinition(mockExecution.getProcessDefinitionId())).thenReturn(mockProcessDefinition) + + return mockExecution + } +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCustomDeleteE2EServiceInstanceTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCustomDeleteE2EServiceInstanceTest.groovy new file mode 100644 index 0000000000..bbbb82b5aa --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCustomDeleteE2EServiceInstanceTest.groovy @@ -0,0 +1,169 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts + +import com.github.tomakehurst.wiremock.junit.WireMockRule +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity +import org.junit.Before +import org.junit.BeforeClass +import org.junit.Ignore +import org.junit.Rule +import org.junit.Test +import org.mockito.MockitoAnnotations +import org.onap.so.bpmn.infrastructure.scripts.DoCustomDeleteE2EServiceInstance +import org.onap.so.bpmn.mock.FileUtil +import org.onap.so.bpmn.vcpe.scripts.GroovyTestBase + +import static org.assertj.core.api.Assertions.assertThatThrownBy +import static org.mockito.Matchers.anyString +import static org.mockito.Mockito.verify +import static org.mockito.Mockito.when +import static org.mockito.Mockito.eq + +class DoCustomDeleteE2EServiceInstanceTest extends GroovyTestBase { + + private static String request + + @Rule + public WireMockRule wireMockRule = new WireMockRule(GroovyTestBase.PORT) + + String Prefix = "CVRCS_" + String RbType = "DCRENI_" + + @BeforeClass + public static void setUpBeforeClass() { + request = FileUtil.readResourceFile("__files/InfrastructureFlows/DeleteCustomE2EService.json") + } + + @Before + public void init() + { + MockitoAnnotations.initMocks(this) + } + public DoCustomDeleteE2EServiceInstanceTest(){ + super("DoCustomDeleteE2EServiceInstance") + } + + @Test + public void preProcessRequestTest(){ + + ExecutionEntity mex = setupMock() + def map = setupMap(mex) + initPreProcess(mex) + + DoCustomDeleteE2EServiceInstance instance = new DoCustomDeleteE2EServiceInstance() + instance.preProcessRequest(mex) + verify(mex).setVariable("sdncCallbackUrl", "/mso/sdncadapter/") + verify(mex).setVariable("siParamsXml", "") + } + + @Test + public void postProcessAAIGETSuccessTest(){ + ExecutionEntity mex = setupMock() + def map = setupMap(mex) + initPreProcess(mex) + when(mex.getVariable("GENGS_SuccessIndicator")).thenReturn(true) + + String aaiGetResponse = FileUtil.readResourceFile("__files/GenericFlows/aaiGetResponse.xml") + when(mex.getVariable("GENGS_service")).thenReturn(aaiGetResponse) + DoCustomDeleteE2EServiceInstance instance = new DoCustomDeleteE2EServiceInstance() + instance.postProcessAAIGET(mex) + + verify(mex).setVariable(eq("serviceRelationShip"), anyString()) + } + + @Test + public void postProcessAAIGETFailureTest(){ + ExecutionEntity mex = setupMock() + def map = setupMap(mex) + initPreProcess(mex) + when(mex.getVariable("GENGS_FoundIndicator")).thenReturn(false) + when(mex.getVariable("GENGS_SuccessIndicator")).thenReturn(false) + + DoCustomDeleteE2EServiceInstance instance = new DoCustomDeleteE2EServiceInstance() + assertThatThrownBy { instance.postProcessAAIGET(mex) } isInstanceOf BpmnError.class + } + + @Test + public void preInitResourcesOperStatusTest(){ + ExecutionEntity mex = setupMock() + def map = setupMap(mex) + initPreProcess(mex) + when(mex.getVariable("serviceRelationShip")).thenReturn("[{\"resourceInstanceId\":\"3333\",\"resourceType\":\"overlay\"},{\"resourceInstanceId\":\"4444\",\"resourceType\":\"underlay\"},{\"resourceInstanceId\":\"1111\",\"resourceType\":\"vIMS\"},{\"resourceInstanceId\":\"222\",\"resourceType\":\"vEPC\"}]") + DoCustomDeleteE2EServiceInstance instance = new DoCustomDeleteE2EServiceInstance() + instance.preInitResourcesOperStatus(mex) + + verify(mex).setVariable(eq("CVFMI_initResOperStatusRequest"), anyString()) + } + + @Test + public void preResourceDeleteTest() { + ExecutionEntity mex = setupMock() + def map = setupMap(mex) + initPreProcess(mex) + when(mex.getVariable("serviceRelationShip")).thenReturn("[{\"resourceInstanceId\":\"3333\",\"resourceType\":\"overlay\"},{\"resourceInstanceId\":\"4444\",\"resourceType\":\"underlay\"},{\"resourceInstanceId\":\"1111\",\"resourceType\":\"vIMS\"},{\"resourceInstanceId\":\"222\",\"resourceType\":\"vEPC\"}]") + DoCustomDeleteE2EServiceInstance instance = new DoCustomDeleteE2EServiceInstance() + instance.preResourceDelete(mex,"overlay") + verify(mex).setVariable("resourceType", "overlay") + } + + @Test + public void postProcessSDNCDeleteTest(){ + ExecutionEntity mex = setupMock() + def map = setupMap(mex) + initPreProcess(mex) + when(mex.getVariable("SDNCA_SuccessIndicator")).thenReturn("true") + when(mex.getVariable("DDELSI_sdncResponseSuccess")).thenReturn("true") + when(mex.getVariable("prefix")).thenReturn("DDELSI_") + DoCustomDeleteE2EServiceInstance instance = new DoCustomDeleteE2EServiceInstance() + String response = FileUtil.readResourceFile("__files/GenericFlows/SDNCDeleteResponse.xml") + String method = "deleteE2E"; + instance.postProcessSDNCDelete(mex, response, method) + // following method doesn't do anything currently -> nothing to check + } + + @Test + public void postProcessAAIDELTest() { + ExecutionEntity mex = setupMock() + def map = setupMap(mex) + initPreProcess(mex) + when(mex.getVariable("GENDS_SuccessIndicator")).thenReturn("true") + DoCustomDeleteE2EServiceInstance instance = new DoCustomDeleteE2EServiceInstance() + instance.postProcessAAIDEL(mex) + } + + private void initPreProcess(ExecutionEntity mex) { + when(mex.getVariable(GroovyTestBase.DBGFLAG)).thenReturn("true") + when(mex.getVariable("bpmnRequest")).thenReturn(request) + when(mex.getVariable("mso-request-id")).thenReturn("mri") + when(mex.getVariable("serviceType")).thenReturn("VoLTE") + when(mex.getVariable("serviceInstanceId")).thenReturn("e151059a-d924-4629-845f-264db19e50b4") + when(mex.getVariable("requestAction")).thenReturn("ra") + when(mex.getVariable("operationId")).thenReturn("59960003992") + when(mex.getVariable("mso.workflow.sdncadapter.callback")).thenReturn("/mso/sdncadapter/") + when(mex.getVariable("GENGS_FoundIndicator")).thenReturn("true") + when(mex.getVariable("GENGS_siResourceLink")).thenReturn("/service-subscription/e2eserviceInstance/delete/service-instances/") + when(mex.getVariable("globalSubscriberId")).thenReturn("4993921112123") + when(mex.getVariable("GENGS_service")).thenReturn("test3434") + when(mex.getVariable("mso.adapters.openecomp.db.endpoint")).thenReturn("http://localhost:8080/mso") + } +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteNetworkInstanceRollbackTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteNetworkInstanceRollbackTest.groovy new file mode 100644 index 0000000000..5e264c0af4 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteNetworkInstanceRollbackTest.groovy @@ -0,0 +1,343 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts + + +import static org.mockito.Mockito.* + +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.ProcessEngineServices +import org.camunda.bpm.engine.RepositoryService +import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity +import org.camunda.bpm.engine.impl.pvm.process.ProcessDefinitionImpl +import org.camunda.bpm.engine.repository.ProcessDefinition +import org.camunda.bpm.engine.delegate.DelegateExecution; +import org.mockito.MockitoAnnotations +import org.mockito.runners.MockitoJUnitRunner +import org.mockito.internal.debugging.MockitoDebuggerImpl +import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.so.bpmn.core.WorkflowException +import org.junit.Before +import org.junit.Rule; +import org.junit.Test +import org.junit.Ignore +import org.junit.runner.RunWith + +import static org.junit.Assert.*; + +import com.github.tomakehurst.wiremock.client.WireMock; +import com.github.tomakehurst.wiremock.junit.WireMockRule; + +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; + +import org.apache.commons.lang3.* + + +@RunWith(MockitoJUnitRunner.class) +class DoDeleteNetworkInstanceRollbackTest { + + @Rule + public WireMockRule wireMockRule = new WireMockRule(8090); + + def utils = new MsoUtils() + String Prefix="DELNWKIR_" + + + String rollbackNetworkRequest = + """<NetworkAdapter:rollbackNetwork xmlns:NetworkAdapter="http://org.onap.so/network"> + <rollback> + <networkId>MNS-25180-L-01-dmz_direct_net_1/2c88a3a9-69b9-43a7-ada6-1aca577c3641</networkId> + <neutronNetworkId>c4f4e878-cde0-4b15-ae9a-bda857759cea</neutronNetworkId> + <networkStackId/> + <networkType>CONTRAIL_EXTERNAL</networkType> + <networkCreated>true</networkCreated> + <tenantId>7dd5365547234ee8937416c65507d266</tenantId> + <cloudSiteId>RDM2WAGPLCP</cloudSiteId> + <msoRequest> + <requestId>1ef47428-cade-45bd-a103-0751e8b2deb0</requestId> + <serviceInstanceId/> + </msoRequest> + </rollback> +</NetworkAdapter:rollbackNetwork>""" + + String rollbackDeActivateSDNCRequest = + """<aetgt:SDNCAdapterWorkflowRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:ns5="http://org.onap/so/request/types/v1" + xmlns:sdncadapter="http://org.onap.so/workflow/sdnc/adapter/schema/v1"> + <sdncadapter:RequestHeader> + <sdncadapter:RequestId>88f65519-9a38-4c4b-8445-9eb4a5a5af56</sdncadapter:RequestId> + <sdncadapter:SvcInstanceId>f70e927b-6087-4974-9ef8-c5e4d5847ca4</sdncadapter:SvcInstanceId> + <sdncadapter:SvcAction>activate</sdncadapter:SvcAction> + <sdncadapter:SvcOperation>network-topology-operation</sdncadapter:SvcOperation> + <sdncadapter:CallbackUrl>sdncCallback</sdncadapter:CallbackUrl> + <sdncadapter:MsoAction>generic-resource</sdncadapter:MsoAction> + </sdncadapter:RequestHeader> + <aetgt:SDNCRequestData> + <request-information> + <request-id>88f65519-9a38-4c4b-8445-9eb4a5a5af56</request-id> + <request-action>CreateNetworkInstance</request-action> + <source>VID</source> + <notification-url/> + <order-number/> + <order-version/> + </request-information> + <service-information> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <service-type>MSO-dev-service-type</service-type> + <service-instance-id>f70e927b-6087-4974-9ef8-c5e4d5847ca4</service-instance-id> + <subscriber-name>MSO_1610_dev</subscriber-name> + </service-information> + <network-information> + <network-id>8abc633a-810b-4ca5-8b3a-09511d13a2ce</network-id> + <network-type>CONTRAIL_EXTERNAL</network-type> + <onap-model-information> + <model-invariant-uuid>invariant-uuid</model-invariant-uuid> + <model-customization-uuid>customization-uuid</model-customization-uuid> + <model-uuid>uuid</model-uuid> + <model-version>version</model-version> + <model-name>CONTRAIL_EXTERNAL</model-name> + </onap-model-information> + </network-information> + <network-request-information> + <network-id>8abc633a-810b-4ca5-8b3a-09511d13a2ce</network-id> + <network-type>CONTRAIL_EXTERNAL</network-type> + <network-name>MNS-25180-L-01-dmz_direct_net_1</network-name> + <tenant>7dd5365547234ee8937416c65507d266</tenant> + <aic-cloud-region>RDM2WAGPLCP</aic-cloud-region> + </network-request-information> + </aetgt:SDNCRequestData> +</aetgt:SDNCAdapterWorkflowRequest>""" + + String rollbackSDNCRequest = + """<aetgt:SDNCAdapterWorkflowRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:ns5="http://org.onap/so/request/types/v1" + xmlns:sdncadapter="http://org.onap.so/workflow/sdnc/adapter/schema/v1"> + <sdncadapter:RequestHeader> + <sdncadapter:RequestId>88f65519-9a38-4c4b-8445-9eb4a5a5af56</sdncadapter:RequestId> + <sdncadapter:SvcInstanceId>f70e927b-6087-4974-9ef8-c5e4d5847ca4</sdncadapter:SvcInstanceId> + <sdncadapter:SvcAction>rollback</sdncadapter:SvcAction> + <sdncadapter:SvcOperation>network-topology-operation</sdncadapter:SvcOperation> + <sdncadapter:CallbackUrl>sdncCallback</sdncadapter:CallbackUrl> + </sdncadapter:RequestHeader> + <aetgt:SDNCRequestData> + <request-information> + <request-id>88f65519-9a38-4c4b-8445-9eb4a5a5af56</request-id> + <request-action>CreateNetworkInstance</request-action> + <source>VID</source> + <notification-url/> + <order-number/> + <order-version/> + </request-information> + <service-information> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <service-type>MSO-dev-service-type</service-type> + <service-instance-id>f70e927b-6087-4974-9ef8-c5e4d5847ca4</service-instance-id> + <subscriber-name>MSO_1610_dev</subscriber-name> + </service-information> + <network-information> + <network-id>8abc633a-810b-4ca5-8b3a-09511d13a2ce</network-id> + <network-type>CONTRAIL_EXTERNAL</network-type> + <onap-model-information> + <model-invariant-uuid>invariant-uuid</model-invariant-uuid> + <model-customization-uuid>customization-uuid</model-customization-uuid> + <model-uuid>uuid</model-uuid> + <model-version>version</model-version> + <model-name>CONTRAIL_EXTERNAL</model-name> + </onap-model-information> + </network-information> + <network-request-information> + <network-id>8abc633a-810b-4ca5-8b3a-09511d13a2ce</network-id> + <network-type>CONTRAIL_EXTERNAL</network-type> + <network-name>MNS-25180-L-01-dmz_direct_net_1</network-name> + <tenant>7dd5365547234ee8937416c65507d266</tenant> + <aic-cloud-region>RDM2WAGPLCP</aic-cloud-region> + </network-request-information> + </aetgt:SDNCRequestData> +</aetgt:SDNCAdapterWorkflowRequest>""" + +// - - - - - - - - + + + @Before + public void init() + { + MockitoAnnotations.initMocks(this) + } + + public void initializeVariables (DelegateExecution mockExecution) { + + verify(mockExecution).setVariable(Prefix + "WorkflowException", null) + + verify(mockExecution).setVariable(Prefix + "rollbackDeactivateSDNCRequest", null) + verify(mockExecution).setVariable(Prefix + "rollbackDeactivateSDNCResponse", "") + verify(mockExecution).setVariable(Prefix + "rollbackDeactivateSDNCReturnCode", "") + + verify(mockExecution).setVariable(Prefix + "rollbackNetworkRequest", null) + verify(mockExecution).setVariable(Prefix + "rollbackNetworkResponse", "") + verify(mockExecution).setVariable(Prefix + "rollbackNetworkReturnCode", "") + + verify(mockExecution).setVariable(Prefix + "Success", false) + verify(mockExecution).setVariable(Prefix + "fullRollback", false) + + } + + @Test + //@Ignore + public void preProcessRequest() { + + println "************ preProcessRequest ************* " + + WorkflowException workflowException = new WorkflowException("DoCreateNetworkInstance", 2500, "Received error from Network Adapter: JBWEB000065: HTTP Status 500.") + Map<String, String> rollbackData = new HashMap<String, String>(); + rollbackData.put("rollbackDeactivateSDNCRequest", rollbackDeActivateSDNCRequest) + rollbackData.put("rollbackNetworkRequest", rollbackNetworkRequest) + rollbackData.put("rollbackSDNCRequest", rollbackSDNCRequest) + + ExecutionEntity mockExecution = setupMock() + // Initialize prerequisite variables + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("prefix")).thenReturn(Prefix + "") + when(mockExecution.getVariable("WorkflowException")).thenReturn(workflowException) + when(mockExecution.getVariable("rollbackData")).thenReturn(rollbackData) + when(mockExecution.getVariable("sdncVersion")).thenReturn("1702") + + when(mockExecution.getVariable("mso.adapters.po.auth")).thenReturn("3141634BF7E070AA289CF2892C986C0B") + when(mockExecution.getVariable("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") + + when(mockExecution.getVariable("mso.adapters.sdnc.endpoint")).thenReturn("http://localhost:8090/SDNCAdapter") + when(mockExecution.getVariable("mso.adapters.network.rest.endpoint")).thenReturn("http://localhost:8090/networks/NetworkAdapter") + when(mockExecution.getVariable("mso.adapters.sdnc.resource.endpoint")).thenReturn("http://localhost:8090/SDNCAdapterRpc") + + + // preProcessRequest(DelegateExecution execution) + DoDeleteNetworkInstanceRollback DoDeleteNetworkInstanceRollback = new DoDeleteNetworkInstanceRollback() + DoDeleteNetworkInstanceRollback.preProcessRequest(mockExecution) + + //verify variable initialization + initializeVariables(mockExecution) + +// verify(mockExecution).getVariable("isDebugLogEnabled") + verify(mockExecution).setVariable("prefix", Prefix) + + } + + + @Test + //@Ignore + public void validateRollbackResponses_Good() { + + WorkflowException workflowException = new WorkflowException("DoDeleteNetworkInstanceRollback", 2500, "AAI Update Contrail Failed. Error 404.") + WorkflowException expectedWorkflowException = new WorkflowException("DoDeleteNetworkInstanceRollback", 2500, "AAI Update Contrail Failed. Error 404. + SNDC deactivate rollback completed. + PO Network rollback completed. + SNDC unassign rollback completed.") + + println "************ validateRollbackResponses_Good() ************* " + ExecutionEntity mockExecution = setupMock() + // Initialize prerequisite variables + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("prefix")).thenReturn(Prefix + "") + + when(mockExecution.getVariable(Prefix + "rollbackDeactivateSDNCRequest")).thenReturn("Good") + when(mockExecution.getVariable(Prefix + "rollbackDeactivateSDNCReturnCode")).thenReturn("200") + when(mockExecution.getVariable(Prefix + "rollbackDeactivateSDNCResponse")).thenReturn("GoodResponse") + when(mockExecution.getVariable(Prefix + "rollbackNetworkRequest")).thenReturn("Good") + when(mockExecution.getVariable(Prefix + "rollbackNetworkReturnCode")).thenReturn("200") + when(mockExecution.getVariable(Prefix + "rollbackNetworkResponse")).thenReturn("GoodResponse") + when(mockExecution.getVariable(Prefix + "rollbackSDNCRequest")).thenReturn("Good") + when(mockExecution.getVariable(Prefix + "rollbackSDNCReturnCode")).thenReturn("200") + when(mockExecution.getVariable(Prefix + "rollbackSDNCResponse")).thenReturn("GoodResponse") + when(mockExecution.getVariable(Prefix + "WorkflowException")).thenReturn(workflowException) + when(mockExecution.getVariable(Prefix + "fullRollback")).thenReturn(false) + + DoDeleteNetworkInstanceRollback DoDeleteNetworkInstanceRollback = new DoDeleteNetworkInstanceRollback() + DoDeleteNetworkInstanceRollback.validateRollbackResponses(mockExecution) + + // verify set prefix = Prefix + "" + verify(mockExecution, atLeast(1)).setVariable("prefix", Prefix) + verify(mockExecution, atLeast(1)).setVariable("rolledBack", true) + verify(mockExecution, atLeast(1)).setVariable("wasDeleted", true) + verify(mockExecution).setVariable("WorkflowException", refEq(expectedWorkflowException, any(WorkflowException.class))) + //verify(mockExecution).setVariable("WorkflowException", expectedWorkflowException) + } + + @Test + //@Ignore + public void validateRollbackResponses_FullRollback() { + + Map<String, String> rollbackData = new HashMap<String, String>(); + rollbackData.put("rollbackDeactivateSDNCRequest", rollbackDeActivateSDNCRequest) + rollbackData.put("rollbackNetworkRequest", rollbackNetworkRequest) + rollbackData.put("rollbackSDNCRequest", rollbackSDNCRequest) + + println "************ validateRollbackResponses_FullRollback() ************* " + ExecutionEntity mockExecution = setupMock() + // Initialize prerequisite variables + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("prefix")).thenReturn(Prefix + "") + + when(mockExecution.getVariable(Prefix + "rollbackDeactivateSDNCRequest")).thenReturn("Good") + when(mockExecution.getVariable(Prefix + "rollbackDeactivateSDNCReturnCode")).thenReturn("200") + when(mockExecution.getVariable(Prefix + "rollbackDeactivateSDNCResponse")).thenReturn("GoodResponse") + when(mockExecution.getVariable(Prefix + "rollbackNetworkRequest")).thenReturn("Good") + when(mockExecution.getVariable(Prefix + "rollbackNetworkReturnCode")).thenReturn("200") + when(mockExecution.getVariable(Prefix + "rollbackNetworkResponse")).thenReturn("GoodResponse") + when(mockExecution.getVariable(Prefix + "rollbackSDNCRequest")).thenReturn("Good") + when(mockExecution.getVariable(Prefix + "rollbackSDNCReturnCode")).thenReturn("200") + when(mockExecution.getVariable(Prefix + "rollbackSDNCResponse")).thenReturn("GoodResponse") + when(mockExecution.getVariable(Prefix + "WorkflowException")).thenReturn(null) + when(mockExecution.getVariable(Prefix + "fullRollback")).thenReturn(true) + when(mockExecution.getVariable("rollbackData")).thenReturn(rollbackData) + + DoDeleteNetworkInstanceRollback DoDeleteNetworkInstanceRollback = new DoDeleteNetworkInstanceRollback() + DoDeleteNetworkInstanceRollback.validateRollbackResponses(mockExecution) + + // verify set prefix = Prefix + "" + verify(mockExecution, atLeast(1)).setVariable("prefix", Prefix) + verify(mockExecution, atLeast(1)).setVariable("rollbackSuccessful", true) + verify(mockExecution, atLeast(1)).setVariable("rollbackError", false) + + } + + + private ExecutionEntity setupMock() { + + ProcessDefinition mockProcessDefinition = mock(ProcessDefinition.class) + when(mockProcessDefinition.getKey()).thenReturn("DoDeleteNetworkInstanceRollback") + RepositoryService mockRepositoryService = mock(RepositoryService.class) + when(mockRepositoryService.getProcessDefinition()).thenReturn(mockProcessDefinition) + when(mockRepositoryService.getProcessDefinition().getKey()).thenReturn("DoDeleteNetworkInstanceRollback") + when(mockRepositoryService.getProcessDefinition().getId()).thenReturn("100") + ProcessEngineServices mockProcessEngineServices = mock(ProcessEngineServices.class) + when(mockProcessEngineServices.getRepositoryService()).thenReturn(mockRepositoryService) + + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + // Initialize prerequisite variables + + when(mockExecution.getId()).thenReturn("100") + when(mockExecution.getProcessDefinitionId()).thenReturn("DoDeleteNetworkInstanceRollback") + when(mockExecution.getProcessInstanceId()).thenReturn("DoDeleteNetworkInstanceRollback") + when(mockExecution.getProcessEngineServices()).thenReturn(mockProcessEngineServices) + when(mockExecution.getProcessEngineServices().getRepositoryService().getProcessDefinition(mockExecution.getProcessDefinitionId())).thenReturn(mockProcessDefinition) + + return mockExecution + } + +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteNetworkInstanceTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteNetworkInstanceTest.groovy new file mode 100644 index 0000000000..1a2d16d9d0 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteNetworkInstanceTest.groovy @@ -0,0 +1,1948 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts + + +import static org.mockito.Mockito.* + +import static org.onap.so.bpmn.mock.StubResponseNetworkAdapter.MockNetworkAdapter; +import static org.onap.so.bpmn.mock.StubResponseAAI.MockGetNetworkByIdWithDepth; +import static org.onap.so.bpmn.mock.StubResponseAAI.MockGetNetworkCloudRegion; +import static org.onap.so.bpmn.mock.StubResponseAAI.MockGetNetworkCloudRegion_404; +import org.camunda.bpm.engine.ProcessEngineServices +import org.camunda.bpm.engine.RepositoryService +import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity +import org.camunda.bpm.engine.repository.ProcessDefinition +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.junit.Before +import org.junit.Ignore +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.MockitoAnnotations +import org.mockito.runners.MockitoJUnitRunner +import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.so.bpmn.core.WorkflowException + +import com.github.tomakehurst.wiremock.client.WireMock +import com.github.tomakehurst.wiremock.junit.WireMockRule +import org.apache.commons.lang3.* + + +@RunWith(MockitoJUnitRunner.class) +class DoDeleteNetworkInstanceTest { + + @Rule + public WireMockRule wireMockRule = new WireMockRule(8090); + + def utils = new MsoUtils() + String Prefix="DELNWKI_" + + String incomingJsonRequest = + """{ "requestDetails": { + "modelInfo": { + "modelType": "network", + "modelCustomizationId": "f21df226-8093-48c3-be7e-0408fcda0422", + "modelName": "CONTRAIL_EXTERNAL", + "modelVersion": "1.0" + }, + "cloudConfiguration": { + "lcpCloudRegionId": "RDM2WAGPLCP", + "tenantId": "7dd5365547234ee8937416c65507d266" + }, + "requestInfo": { + "instanceName": "HSL_direct_net_2", + "source": "VID", + "callbackUrl": "", + "suppressRollback": true, + "productFamilyId": "a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb" + }, + "relatedInstanceList": [ + { + "relatedInstance": { + "instanceId": "f70e927b-6087-4974-9ef8-c5e4d5847ca4", + "modelInfo": { + "modelType": "serviceT", + "modelId": "modelI", + "modelNameVersionId": "modelNameVersionI", + "modelName": "modleNam", + "modelVersion": "1" + } + } + } + ], + "requestParameters": { + "userParams": [] + } + }""" + + String expectedDoDeleteNetworkInstanceRequest = + """{ "requestDetails": { + "modelInfo": { + "modelType": "networkTyp", + "modelId": "modelId", + "modelNameVersionId": "modelNameVersionId", + "modelName": "CONTRAIL_EXTERNAL", + "modelVersion": "1" + }, + "cloudConfiguration": { + "lcpCloudRegionId": "RDM2WAGPLCP", + "tenantId": "7dd5365547234ee8937416c65507d266" + }, + "requestInfo": { + "instanceName": "HSL_direct_net_2", + "source": "VID", + "callbackUrl": "", + "suppressRollback": true, + "productFamilyId": "a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb" + }, + "relatedInstanceList": [ + { + "relatedInstance": { + "instanceId": "f70e927b-6087-4974-9ef8-c5e4d5847ca4", + "modelInfo": { + "modelType": "serviceT", + "modelId": "modelI", + "modelNameVersionId": "modelNameVersionI", + "modelName": "modleNam", + "modelVersion": "1" + } + } + } + ], + "requestParameters": { + "userParams": [] + } + }""" + + // expectedVnfRequest + String expectedNetworkRequest = +"""<network-request xmlns="http://www.w3.org/2001/XMLSchema"> + <request-info> + <request-id>88f65519-9a38-4c4b-8445-9eb4a5a5af56</request-id> + <action>DELETE</action> + <source>VID</source> + <service-instance-id>f70e927b-6087-4974-9ef8-c5e4d5847ca4</service-instance-id> + </request-info> + <network-inputs> + <network-id>bdc5efe8-404a-409b-85f6-0dcc9eebae30</network-id> + <network-name>HSL_direct_net_2</network-name> + <network-type>CONTRAIL_EXTERNAL</network-type> + <modelCustomizationId>f21df226-8093-48c3-be7e-0408fcda0422</modelCustomizationId> + <aic-cloud-region>RDM2WAGPLCP</aic-cloud-region> + <tenant-id>7dd5365547234ee8937416c65507d266</tenant-id> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <backout-on-failure>false</backout-on-failure> + <sdncVersion>1610</sdncVersion> + </network-inputs> + <network-params/> +</network-request>""" + + String expectedVperNetworkRequest = +"""<network-request xmlns="http://www.w3.org/2001/XMLSchema"> + <request-info> + <request-id>88f65519-9a38-4c4b-8445-9eb4a5a5af56</request-id> + <action>DELETE</action> + <source>VID</source> + <service-instance-id>f70e927b-6087-4974-9ef8-c5e4d5847ca4</service-instance-id> + </request-info> + <network-inputs> + <network-id>bdc5efe8-404a-409b-85f6-0dcc9eebae30</network-id> + <network-name>MNS-25180-L-01-dmz_direct_net_1</network-name> + <network-type>CONTRAIL_EXTERNAL</network-type> + <subscription-service-type>MSO-dev-service-type</subscription-service-type> + <global-customer-id>globalId_45678905678</global-customer-id> + <aic-cloud-region>RDM2WAGPLCP</aic-cloud-region> + <tenant-id>7dd5365547234ee8937416c65507d266</tenant-id> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <backout-on-failure>false</backout-on-failure> + <failIfExist>false</failIfExist> + <networkModelInfo> + <modelName>CONTRAIL_EXTERNAL</modelName> + <modelUuid>sn5256d1-5a33-55df-13ab-12abad84e111</modelUuid> + <modelInvariantUuid>sn5256d1-5a33-55df-13ab-12abad84e764</modelInvariantUuid> + <modelVersion>1</modelVersion> + <modelCustomizationUuid>sn5256d1-5a33-55df-13ab-12abad84e222</modelCustomizationUuid> + </networkModelInfo> + <serviceModelInfo> + <modelName/> + <modelUuid/> + <modelInvariantUuid/> + <modelVersion/> + <modelCustomizationUuid/> + </serviceModelInfo> + <sdncVersion>1702</sdncVersion> + </network-inputs> + <network-params/> +</network-request>""" + + String expected_networkInput = + """<network-inputs xmlns="http://www.w3.org/2001/XMLSchema"> + <network-id>bdc5efe8-404a-409b-85f6-0dcc9eebae30</network-id> + <network-name>HSL_direct_net_2</network-name> + <network-type>CONTRAIL_EXTERNAL</network-type> + <modelCustomizationId>f21df226-8093-48c3-be7e-0408fcda0422</modelCustomizationId> + <aic-cloud-region>RDM2WAGPLCP</aic-cloud-region> + <tenant-id>7dd5365547234ee8937416c65507d266</tenant-id> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <backout-on-failure>false</backout-on-failure> + <sdncVersion>1610</sdncVersion> +</network-inputs>""" + + String expectedVper_networkInput = +"""<network-inputs xmlns="http://www.w3.org/2001/XMLSchema"> + <network-id>bdc5efe8-404a-409b-85f6-0dcc9eebae30</network-id> + <network-name>MNS-25180-L-01-dmz_direct_net_1</network-name> + <network-type>CONTRAIL_EXTERNAL</network-type> + <subscription-service-type>MSO-dev-service-type</subscription-service-type> + <global-customer-id>globalId_45678905678</global-customer-id> + <aic-cloud-region>RDM2WAGPLCP</aic-cloud-region> + <tenant-id>7dd5365547234ee8937416c65507d266</tenant-id> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <backout-on-failure>false</backout-on-failure> + <failIfExist>false</failIfExist> + <networkModelInfo> + <modelName>CONTRAIL_EXTERNAL</modelName> + <modelUuid>sn5256d1-5a33-55df-13ab-12abad84e111</modelUuid> + <modelInvariantUuid>sn5256d1-5a33-55df-13ab-12abad84e764</modelInvariantUuid> + <modelVersion>1</modelVersion> + <modelCustomizationUuid>sn5256d1-5a33-55df-13ab-12abad84e222</modelCustomizationUuid> + </networkModelInfo> + <serviceModelInfo> + <modelName/> + <modelUuid/> + <modelInvariantUuid/> + <modelVersion/> + <modelCustomizationUuid/> + </serviceModelInfo> + <sdncVersion>1702</sdncVersion> +</network-inputs>""" + +// emptyRegionVnfRequest +String emptyRegionVnfRequest = +"""<network-request xmlns="http://org.onap/so/infra/vnf-request/v1"> + <request-info> + <request-id>88f65519-9a38-4c4b-8445-9eb4a5a5af56</request-id> + <action>DELETE</action> + <source>PORTAL</source> + </request-info> + <network-inputs> + <network-id>bdc5efe8-404a-409b-85f6-0dcc9eebae30</network-id> + <network-name>HSL_direct_net_2</network-name> + <network-type>CONTRAIL_BASIC</network-type> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <aic-cloud-region/> + <tenant-id>e81d842d3e8b45c5a59f57cd76af3aaf</tenant-id> + </network-inputs> + <network-params> + <param name="shared">0</param> + </network-params> +</network-request>""" + +String vnfRequestCloudRegionNotFound = +"""<network-request xmlns="http://org.onap/so/infra/vnf-request/v1"> + <request-info> + <request-id>88f65519-9a38-4c4b-8445-9eb4a5a5af56</request-id> + <action>DELETE</action> + <source>PORTAL</source> + </request-info> + <network-inputs> + <network-id>bdc5efe8-404a-409b-85f6-0dcc9eebae30</network-id> + <network-name>HSL_direct_net_2</network-name> + <network-type>CONTRAIL_BASIC</network-type> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <aic-cloud-region>MDTWNJ21</aic-cloud-region> + <tenant-id>e81d842d3e8b45c5a59f57cd76af3aaf</tenant-id> + </network-inputs> + <network-params> + <param name="shared">0</param> + </network-params> +</network-request>""" + + String vnfPayload = + """<rest:payload xmlns:rest="http://schemas.activebpel.org/REST/2007/12/01/aeREST.xsd" + contentType="text/xml"> + <network-request xmlns="http://org.onap/so/infra/vnf-request/v1"> + <request-info> + <request-id>88f65519-9a38-4c4b-8445-9eb4a5a5af56</request-id> + <action>DELETE</action> + <source>PORTAL</source> + </request-info> + <network-inputs> + <network-id>bdc5efe8-404a-409b-85f6-0dcc9eebae30</network-id> + <network-name>HSL_direct_net_2</network-name> + <network-type>CONTRAIL_BASIC</network-type> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <aic-cloud-region>RDM2WAGPLCP</aic-cloud-region> + <tenant-id>e81d842d3e8b45c5a59f57cd76af3aaf</tenant-id> + </network-inputs> + <network-params> + <param name="shared">0</param> + </network-params> + </network-request> +</rest:payload>""" + + String vnfPayload_MissingId = +"""<rest:payload xmlns:rest="http://schemas.activebpel.org/REST/2007/12/01/aeREST.xsd" + contentType="text/xml"> + <network-request xmlns="http://org.onap/so/infra/vnf-request/v1"> + <request-info> + <request-id>88f65519-9a38-4c4b-8445-9eb4a5a5af56</request-id> + <action>DELETE</action> + <source>PORTAL</source> + </request-info> + <network-inputs> + <network-id>bdc5efe8-404a-409b-85f6-0dcc9eebae30</network-id> + <network-name/> + <network-type>CONTRAIL_BASIC</network-type> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <aic-cloud-region>RDM2WAGPLCP</aic-cloud-region> + <tenant-id>e81d842d3e8b45c5a59f57cd76af3aaf</tenant-id> + </network-inputs> + <network-params> + <param name="shared">0</param> + </network-params> + </network-request> +</rest:payload>""" + + String vnfRequestRESTPayload = +"""<network-request xmlns="http://org.onap/so/infra/vnf-request/v1"> + <request-info> + <request-id>88f65519-9a38-4c4b-8445-9eb4a5a5af56</request-id> + <action>DELETE</action> + <source>PORTAL</source> + </request-info> + <network-inputs> + <network-id>bdc5efe8-404a-409b-85f6-0dcc9eebae30</network-id> + <network-name>HSL_direct_net_2</network-name> + <network-type>CONTRAIL_BASIC</network-type> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <aic-cloud-region>RDM2WAGPLCP</aic-cloud-region> + <tenant-id>e81d842d3e8b45c5a59f57cd76af3aaf</tenant-id> + </network-inputs> + <network-outputs> + <network-id>id</network-id> + <network-name>name</network-name> + </network-outputs> + <network-params> + <param name="shared">0</param> + </network-params> + </network-request>""" + + +String incomingRequestMissingCloudRegion = +"""{ "requestDetails": { + "modelInfo": { + "modelType": "network", + "modelCustomizationId": "f21df226-8093-48c3-be7e-0408fcda0422", + "modelName": "CONTRAIL_EXTERNAL", + "modelVersion": "1.0" + }, + "cloudConfiguration": { + "tenantId": "7dd5365547234ee8937416c65507d266" + }, + "requestInfo": { + "instanceName": "HSL_direct_net_2", + "source": "VID", + "callbackUrl": "", + "suppressRollback": true, + "productFamilyId": "a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb" + }, + "relatedInstanceList": [ + { + "relatedInstance": { + "instanceId": "f70e927b-6087-4974-9ef8-c5e4d5847ca4", + "modelInfo": { + "modelType": "serviceT", + "modelId": "modelI", + "modelNameVersionId": "modelNameVersionI", + "modelName": "modleNam", + "modelVersion": "1" + } + } + } + ], + "requestParameters": { + "userParams": [] + } + }""" + + String expectedNetworkRequestMissingId = + """<network-request xmlns="http://www.w3.org/2001/XMLSchema"> + <request-info> + <request-id>88f65519-9a38-4c4b-8445-9eb4a5a5af56</request-id> + <action>DELETE</action> + <source>VID</source> + <service-instance-id>f70e927b-6087-4974-9ef8-c5e4d5847ca4</service-instance-id> + </request-info> + <network-inputs> + <network-id/> + <network-name>HSL_direct_net_2</network-name> + <network-type>CONTRAIL_EXTERNAL</network-type> + <modelCustomizationId>f21df226-8093-48c3-be7e-0408fcda0422</modelCustomizationId> + <aic-cloud-region>RDM2WAGPLCP</aic-cloud-region> + <tenant-id>7dd5365547234ee8937416c65507d266</tenant-id> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <backout-on-failure>false</backout-on-failure> + <sdncVersion>1610</sdncVersion> + </network-inputs> + <network-params/> +</network-request>""" + +String expectedNetworkRequestMissingCloudRegion = +"""<network-request xmlns="http://www.w3.org/2001/XMLSchema"> + <request-info> + <request-id>88f65519-9a38-4c4b-8445-9eb4a5a5af56</request-id> + <action>DELETE</action> + <source>VID</source> + <service-instance-id>f70e927b-6087-4974-9ef8-c5e4d5847ca4</service-instance-id> + </request-info> + <network-inputs> + <network-id>bdc5efe8-404a-409b-85f6-0dcc9eebae30</network-id> + <network-name>HSL_direct_net_2</network-name> + <network-type>CONTRAIL_EXTERNAL</network-type> + <modelCustomizationId>f21df226-8093-48c3-be7e-0408fcda0422</modelCustomizationId> + <aic-cloud-region>null</aic-cloud-region> + <tenant-id>7dd5365547234ee8937416c65507d266</tenant-id> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <backout-on-failure>false</backout-on-failure> + <sdncVersion>1610</sdncVersion> + </network-inputs> + <network-params/> +</network-request>""" + + // vnfRESTRequest + String vnfRESTRequest = +"""<rest:RESTResponse xmlns:rest="http://schemas.activebpel.org/REST/2007/12/01/aeREST.xsd" + xmlns="http://www.w3.org/2001/XMLSchema" + statusCode="200"> + <rest:payload contentType="text/xml"> + <network-request> + <request-info> + <action>DELETE</action> + <source>VID</source> + <service-instance-id>f70e927b-6087-4974-9ef8-c5e4d5847ca4</service-instance-id> + </request-info> + <network-inputs> + <network-id>bdc5efe8-404a-409b-85f6-0dcc9eebae30</network-id> + <network-name>HSL_direct_net_2</network-name> + <network-type>CONTRAIL_EXTERNAL</network-type> + <aic-cloud-region>RDM2WAGPLCP</aic-cloud-region> + <tenant-id>7dd5365547234ee8937416c65507d266</tenant-id> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <backout-on-failure>true</backout-on-failure> + </network-inputs> + <network-params> + <userParams/> + </network-params> + </network-request> + </rest:payload> +</rest:RESTResponse>""" + + String networkInputs = + """<network-inputs xmlns="http://org.onap/so/infra/vnf-request/v1"> + <network-id>bdc5efe8-404a-409b-85f6-0dcc9eebae30</network-id> + <network-name>HSL_direct_net_2</network-name> + <network-type>CONTRAIL_BASIC</network-type> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <aic-cloud-region>RDM2WAGPLCP</aic-cloud-region> + <tenant-id>e81d842d3e8b45c5a59f57cd76af3aaf</tenant-id> +</network-inputs>""" + +String networkInputsNoType = +"""<network-inputs xmlns="http://org.onap/so/infra/vnf-request/v1"> + <network-id></network-id> + <network-name></network-name> + <network-type></network-type> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <aic-cloud-region>RDM2WAGPLCP</aic-cloud-region> + <tenant-id>e81d842d3e8b45c5a59f57cd76af3aaf</tenant-id> +</network-inputs>""" + + String networkInputsMissingId = + """<network-inputs xmlns="http://www.w3.org/2001/XMLSchema"> + <network-id/> + <network-name>HSL_direct_net_2</network-name> + <network-type>CONTRAIL_EXTERNAL</network-type> + <modelCustomizationId>f21df226-8093-48c3-be7e-0408fcda0422</modelCustomizationId> + <aic-cloud-region>RDM2WAGPLCP</aic-cloud-region> + <tenant-id>7dd5365547234ee8937416c65507d266</tenant-id> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <backout-on-failure>false</backout-on-failure> + <sdncVersion>1610</sdncVersion> +</network-inputs>""" + +String networkInputsMissingCloudRegion = +"""<network-inputs xmlns="http://www.w3.org/2001/XMLSchema"> + <network-id>bdc5efe8-404a-409b-85f6-0dcc9eebae30</network-id> + <network-name>HSL_direct_net_2</network-name> + <network-type>CONTRAIL_EXTERNAL</network-type> + <modelCustomizationId>f21df226-8093-48c3-be7e-0408fcda0422</modelCustomizationId> + <aic-cloud-region>null</aic-cloud-region> + <tenant-id>7dd5365547234ee8937416c65507d266</tenant-id> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <backout-on-failure>false</backout-on-failure> + <sdncVersion>1610</sdncVersion> +</network-inputs>""" + + String MissingIdFault = "Invalid value or missing network-id element" + String MissingRegionFault = "Invalid value or missing 'aic-cloud-region' element" + + String invalidWorkflowException = """<aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1"> + <aetgt:ErrorMessage>Invalid value of network-id element</aetgt:ErrorMessage> + <aetgt:ErrorCode>2500</aetgt:ErrorCode> + </aetgt:WorkflowException>""" + + + String queryAAIResponse = + """<rest:RESTResponse xmlns:rest="http://schemas.activebpel.org/REST/2007/12/01/aeREST.xsd" + statusCode="200"> + <rest:headers> + <rest:header name="Transfer-Encoding" value="chunked"/> + <rest:header name="Date" value="Sat,30 Jan 2016 20:09:24 GMT"/> + <rest:header name="Expires" value="Thu,01 Jan 1970 00:00:00 UTC"/> + <rest:header name="X-AAI-TXID" + value="localhost-20160130-20:09:24:814-165843"/> + <rest:header name="Content-Type" value="application/xml"/> + <rest:header name="Server" value="Apache-Coyote/1.1"/> + <rest:header name="Cache-Control" value="private"/> + </rest:headers> + <rest:payload contentType="text/xml"> + <l3-network xmlns="http://org.openecomp.aai.inventory/v3"> + <network-id>bdc5efe8-404a-409b-85f6-0dcc9eebae30</network-id> + <network-name>HSL_direct_net_2</network-name> + <network-type>CONTRAIL_BASIC</network-type> + <network-role>HSL_direct</network-role> + <network-technology>contrail</network-technology> + <neutron-network-id>8bbd3edf-b835-4610-96a2-a5cafa029042</neutron-network-id> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <orchestration-status>active</orchestration-status> + <heat-stack-id>HSL_direct_net_2/57594a56-1c92-4a38-9caa-641c1fa3d4b6</heat-stack-id> + <subnets> + <subnet> + <subnet-id>ea5f2a2c-604f-47ff-a9c5-253ee4f0ef0a</subnet-id> + <neutron-subnet-id>5a77fdc2-7789-4649-a1b9-6eaf1db1813a</neutron-subnet-id> + <gateway-address>172.16.34.1</gateway-address> + <network-start-address>172.16.34.0</network-start-address> + <cidr-mask>28</cidr-mask> + <ip-version>4</ip-version> + <orchestration-status>active</orchestration-status> + <dhcp-enabled>true</dhcp-enabled> + <relationship-list/> + </subnet> + </subnets> + <relationship-list> + <relationship> + <related-to>tenant</related-to> + <related-link>https://aai-app-e2e.test.com:8443/aai/v3/cloud-infrastructure/tenants/tenant/e81d842d3e8b45c5a59f57cd76af3aaf/</related-link> + <relationship-data> + <relationship-key>tenant.tenant-id</relationship-key> + <relationship-value>e81d842d3e8b45c5a59f57cd76af3aaf</relationship-value> + </relationship-data> + </relationship> + </relationship-list> + </l3-network> + </rest:payload> +</rest:RESTResponse>""" + + String deleteNetworkRequest = + """<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"> + <soapenv:Header/> + <soapenv:Body> + <NetworkAdapter:deleteNetwork xmlns:NetworkAdapter="http://org.onap.so/network"> + <cloudSiteId>RDM2WAGPLCP</cloudSiteId> + <tenantId>e81d842d3e8b45c5a59f57cd76af3aaf</tenantId> + <networkType>CONTRAIL_BASIC</networkType> + <networkId>HSL_direct_net_2/57594a56-1c92-4a38-9caa-641c1fa3d4b6</networkId> + <request> + <requestId>88f65519-9a38-4c4b-8445-9eb4a5a5af56</requestId> + <serviceInstanceId>0</serviceInstanceId> + </request> + </NetworkAdapter:deleteNetwork> + </soapenv:Body> +</soapenv:Envelope>""" + +String deleteNetworkRESTRequest = +"""<deleteNetworkRequest> + <cloudSiteId>RDM2WAGPLCP</cloudSiteId> + <tenantId>e81d842d3e8b45c5a59f57cd76af3aaf</tenantId> + <networkId>bdc5efe8-404a-409b-85f6-0dcc9eebae30</networkId> + <networkStackId>HSL_direct_net_2/57594a56-1c92-4a38-9caa-641c1fa3d4b6</networkStackId> + <networkType>CONTRAIL_BASIC</networkType> + <modelCustomizationUuid>sn5256d1-5a33-55df-13ab-12abad84e222</modelCustomizationUuid> + <skipAAI>true</skipAAI> + <msoRequest> + <requestId>88f65519-9a38-4c4b-8445-9eb4a5a5af56</requestId> + <serviceInstanceId>f70e927b-6087-4974-9ef8-c5e4d5847ca4</serviceInstanceId> + </msoRequest> + <messageId>messageId_value</messageId> + <notificationUrl/> +</deleteNetworkRequest>""" + +String deleteNetworkRESTRequestAlaCarte = +"""<deleteNetworkRequest> + <cloudSiteId>RDM2WAGPLCP</cloudSiteId> + <tenantId>e81d842d3e8b45c5a59f57cd76af3aaf</tenantId> + <networkId>bdc5efe8-404a-409b-85f6-0dcc9eebae30</networkId> + <networkStackId>HSL_direct_net_2/57594a56-1c92-4a38-9caa-641c1fa3d4b6</networkStackId> + <networkType>CONTRAIL_BASIC</networkType> + <modelCustomizationUuid>f21df226-8093-48c3-be7e-0408fcda0422</modelCustomizationUuid> + <skipAAI>true</skipAAI> + <msoRequest> + <requestId>88f65519-9a38-4c4b-8445-9eb4a5a5af56</requestId> + <serviceInstanceId>f70e927b-6087-4974-9ef8-c5e4d5847ca4</serviceInstanceId> + </msoRequest> + <messageId>messageId_value</messageId> + <notificationUrl/> +</deleteNetworkRequest>""" + + String deleteNetworkResponse_noRollback = +"""<ns2:deleteNetworkResponse xmlns:ns2="http://org.onap.so/network"> + <networkDeleted>true</networkDeleted> +</ns2:deleteNetworkResponse> +""" + + String deleteNetworkResponse = + """<ns2:deleteNetworkResponse xmlns:ns2="http://org.onap.so/network"> + <networkDeleted>true</networkDeleted> + <rollback> + <networkId>MNS-25180-L-01-dmz_direct_net_1/2c88a3a9-69b9-43a7-ada6-1aca577c3641</networkId> + <neutronNetworkId>c4f4e878-cde0-4b15-ae9a-bda857759cea</neutronNetworkId> + <networkStackId></networkStackId> + <networkType>CONTRAIL_EXTERNAL</networkType> + <networkCreated>true</networkCreated> + <tenantId>7dd5365547234ee8937416c65507d266</tenantId> + <cloudSiteId>RDM2WAGPLCP</cloudSiteId> + <msoRequest> + <requestId>1ef47428-cade-45bd-a103-0751e8b2deb0</requestId> + <serviceInstanceId></serviceInstanceId> + </msoRequest> + </rollback> + </ns2:deleteNetworkResponse>""" + + String deleteRollbackNetworkRequest = + """<NetworkAdapter:rollbackNetwork xmlns:NetworkAdapter="http://org.onap.so/network"> + <rollback> + <networkId>MNS-25180-L-01-dmz_direct_net_1/2c88a3a9-69b9-43a7-ada6-1aca577c3641</networkId> + <neutronNetworkId>c4f4e878-cde0-4b15-ae9a-bda857759cea</neutronNetworkId> + <networkStackId/> + <networkType>CONTRAIL_EXTERNAL</networkType> + <networkCreated>true</networkCreated> + <tenantId>7dd5365547234ee8937416c65507d266</tenantId> + <cloudSiteId>RDM2WAGPLCP</cloudSiteId> + <msoRequest> + <requestId>1ef47428-cade-45bd-a103-0751e8b2deb0</requestId> + <serviceInstanceId/> + </msoRequest> + </rollback> +</NetworkAdapter:rollbackNetwork>""" + + String deleteNetworkResponseFalseCompletion = + """<ns2:deleteNetworkResponse xmlns:ns2="http://org.onap.so/network" + xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> + <networkDeleted>false</networkDeleted> + </ns2:deleteNetworkResponse>""" + + String deleteNetworkErrorResponse = + """<?xml version="1.0" encoding="UTF-8" standalone="yes"?> +<deleteNetworkError> +<messageId>680bd458-5ec1-4a16-b77c-509022e53450</messageId><category>INTERNAL</category> +<message>400 Bad Request: The server could not comply with the request since it is either malformed or otherwise incorrect., error.type=StackValidationFailed, error.message=Property error: : resources.network.properties: : Unknown Property network_ipam_refs_data</message> +<rolledBack>true</rolledBack> +</deleteNetworkError> +""" + + String deleteNetworkWorkflowException = + """<aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1"> + <aetgt:ErrorMessage>Received error from Network Adapter: 400 Bad Request: The server could not comply with the request since it is either malformed or otherwise incorrect., error.type=StackValidationFailed, error.message=Property error: : resources.network.properties: : Unknown Property network_ipam_refs_data</aetgt:ErrorMessage> + <aetgt:ErrorCode>7020</aetgt:ErrorCode> + </aetgt:WorkflowException>""" + +String aaiWorkflowException = +"""<aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1"> + <aetgt:ErrorMessage>Bpmn error encountered in DoDeleteNetworkInstance flow. Unexpected Response from AAI Adapter - org.apache.http.conn.HttpHostConnectException: Connect to localhost:8090 [localhost/127.0.0.1, localhost/0:0:0:0:0:0:0:1] failed: Connection refused: connect</aetgt:ErrorMessage> + <aetgt:ErrorCode>2500</aetgt:ErrorCode> + </aetgt:WorkflowException>""" + + String aaiResponse = + """<rest:RESTResponse xmlns:rest="http://schemas.activebpel.org/REST/2007/12/01/aeREST.xsd" + statusCode="200"> + <rest:headers> + <rest:header name="Transfer-Encoding" value="chunked"/> + <rest:header name="Date" value="Sat,30 Jan 2016 20:09:24 GMT"/> + <rest:header name="Expires" value="Thu,01 Jan 1970 00:00:00 UTC"/> + <rest:header name="X-AAI-TXID" + value="localhost-20160130-20:09:24:814-165843"/> + <rest:header name="Content-Type" value="application/xml"/> + <rest:header name="Server" value="Apache-Coyote/1.1"/> + <rest:header name="Cache-Control" value="private"/> + </rest:headers> + <rest:payload contentType="text/xml"> + <l3-network xmlns="http://org.openecomp.aai.inventory/v8"> + <network-id>bdc5efe8-404a-409b-85f6-0dcc9eebae30</network-id> + <network-name>HSL_direct_net_2</network-name> + <network-type>CONTRAIL_BASIC</network-type> + <network-role>HSL_direct</network-role> + <network-technology>contrail</network-technology> + <neutron-network-id>8bbd3edf-b835-4610-96a2-a5cafa029042</neutron-network-id> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <orchestration-status>active</orchestration-status> + <heat-stack-id>HSL_direct_net_2/57594a56-1c92-4a38-9caa-641c1fa3d4b6</heat-stack-id> + <subnets> + <subnet> + <subnet-id>ea5f2a2c-604f-47ff-a9c5-253ee4f0ef0a</subnet-id> + <neutron-subnet-id>5a77fdc2-7789-4649-a1b9-6eaf1db1813a</neutron-subnet-id> + <gateway-address>172.16.34.1</gateway-address> + <network-start-address>172.16.34.0</network-start-address> + <cidr-mask>28</cidr-mask> + <ip-version>4</ip-version> + <orchestration-status>active</orchestration-status> + <dhcp-enabled>true</dhcp-enabled> + <relationship-list/> + </subnet> + </subnets> + <relationship-list> + <relationship> + <related-to>tenant</related-to> + <related-link>https://aai-app-e2e.test.com:8443/aai/v8/cloud-infrastructure/tenants/tenant/e81d842d3e8b45c5a59f57cd76af3aaf/</related-link> + <relationship-data> + <relationship-key>tenant.tenant-id</relationship-key> + <relationship-value>e81d842d3e8b45c5a59f57cd76af3aaf</relationship-value> + </relationship-data> + </relationship> + <relationship> + <related-to>cloud-region</related-to> + <related-link>cloud-infrastructure/cloud-regions/cloud-region/att-aic/RDM2WAGPLCP/</related-link> + <relationship-data> + <relationship-key>cloud-region.cloud-owner</relationship-key> + <relationship-value>att-aic</relationship-value> + </relationship-data> + <relationship-data> + <relationship-key>cloud-region.cloud-region-id</relationship-key> + <relationship-value>RDM2WAGPLCP</relationship-value> + </relationship-data> + </relationship> + </relationship-list> + </l3-network> + </rest:payload> +</rest:RESTResponse>""" + +String aaiResponseWithRelationship = +"""<rest:RESTResponse xmlns:rest="http://schemas.activebpel.org/REST/2007/12/01/aeREST.xsd" + statusCode="200"> + <rest:headers> + <rest:header name="Transfer-Encoding" value="chunked"/> + <rest:header name="Date" value="Sat,30 Jan 2016 20:09:24 GMT"/> + <rest:header name="Expires" value="Thu,01 Jan 1970 00:00:00 UTC"/> + <rest:header name="X-AAI-TXID" + value="localhost-20160130-20:09:24:814-165843"/> + <rest:header name="Content-Type" value="application/xml"/> + <rest:header name="Server" value="Apache-Coyote/1.1"/> + <rest:header name="Cache-Control" value="private"/> + </rest:headers> + <rest:payload contentType="text/xml"> + <l3-network xmlns="http://org.openecomp.aai.inventory/v8"> + <network-id>bdc5efe8-404a-409b-85f6-0dcc9eebae30</network-id> + <network-name>HSL_direct_net_2</network-name> + <network-type>CONTRAIL_BASIC</network-type> + <network-role>HSL_direct</network-role> + <network-technology>contrail</network-technology> + <neutron-network-id>8bbd3edf-b835-4610-96a2-a5cafa029042</neutron-network-id> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <orchestration-status>active</orchestration-status> + <heat-stack-id>HSL_direct_net_2/57594a56-1c92-4a38-9caa-641c1fa3d4b6</heat-stack-id> + <subnets> + <subnet> + <subnet-id>ea5f2a2c-604f-47ff-a9c5-253ee4f0ef0a</subnet-id> + <neutron-subnet-id>5a77fdc2-7789-4649-a1b9-6eaf1db1813a</neutron-subnet-id> + <gateway-address>172.16.34.1</gateway-address> + <network-start-address>172.16.34.0</network-start-address> + <cidr-mask>28</cidr-mask> + <ip-version>4</ip-version> + <orchestration-status>active</orchestration-status> + <dhcp-enabled>true</dhcp-enabled> + <relationship-list/> + </subnet> + </subnets> + <relationship-list> + <relationship> + <related-to>tenant</related-to> + <related-link>https://aai-app-e2e.test.com:8443/aai/v8/cloud-infrastructure/tenants/tenant/e81d842d3e8b45c5a59f57cd76af3aaf/</related-link> + <relationship-data> + <relationship-key>tenant.tenant-id</relationship-key> + <relationship-value>e81d842d3e8b45c5a59f57cd76af3aaf</relationship-value> + </relationship-data> + </relationship> + <relationship> + <related-to>vf-module</related-to> + <related-link>https://aai-app-e2e.ecomp.cci.com:8443/aai/v8/network/generic-vnfs/generic-vnf/105df7e5-0b3b-49f7-a837-4864b62827c4/vf-modules/vf-module/d9217058-95a0-49ee-b9a9-949259e89349/</related-link> + <relationship-data> + <relationship-key>generic-vnf.vnf-id</relationship-key> + <relationship-value>105df7e5-0b3b-49f7-a837-4864b62827c4</relationship-value> + </relationship-data> + <relationship-data> + <relationship-key>vf-module.vf-module-id</relationship-key> + <relationship-value>d9217058-95a0-49ee-b9a9-949259e89349</relationship-value> + </relationship-data> + </relationship> + <relationship> + <related-to>generic-vnf</related-to> + <related-link>https://aai-app-e2e.test.com:8443/aai/v8/network/generic-vnfs/generic-vnf/45f822d9-73ca-4255-9844-7cef401bbf47/</related-link> + <relationship-data> + <relationship-key>generic-vnf.vnf-id</relationship-key> + <relationship-value>45f822d9-73ca-4255-9844-7cef401bbf47</relationship-value> + </relationship-data> + <related-to-property> + <property-key>generic-vnf.vnf-name</property-key> + <property-value>zrdm1scpx05</property-value> + </related-to-property> + </relationship> + </relationship-list> + </l3-network> + </rest:payload> +</rest:RESTResponse>""" + + String deleteSDNCRequest = + """<aetgt:SDNCAdapterWorkflowRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:ns5="http://org.onap/so/request/types/v1" + xmlns:sdncadapter="http://org.onap.so/workflow/sdnc/adapter/schema/v1"> + <sdncadapter:RequestHeader> + <sdncadapter:RequestId>88f65519-9a38-4c4b-8445-9eb4a5a5af56</sdncadapter:RequestId> + <sdncadapter:SvcInstanceId>f70e927b-6087-4974-9ef8-c5e4d5847ca4</sdncadapter:SvcInstanceId> + <sdncadapter:SvcAction>delete</sdncadapter:SvcAction> + <sdncadapter:SvcOperation>network-topology-operation</sdncadapter:SvcOperation> + <sdncadapter:CallbackUrl>sdncCallback</sdncadapter:CallbackUrl> + </sdncadapter:RequestHeader> + <aetgt:SDNCRequestData> + <request-information> + <request-id>88f65519-9a38-4c4b-8445-9eb4a5a5af56</request-id> + <request-action>DisconnectNetworkRequest</request-action> + <source>VID</source> + <notification-url/> + <order-number/> + <order-version/> + </request-information> + <service-information> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <service-type/> + <service-instance-id>f70e927b-6087-4974-9ef8-c5e4d5847ca4</service-instance-id> + <subscriber-name/> + </service-information> + <network-request-information> + <network-id>bdc5efe8-404a-409b-85f6-0dcc9eebae30</network-id> + <network-type>CONTRAIL_BASIC</network-type> + <network-name>HSL_direct_net_2</network-name> + <tenant>7dd5365547234ee8937416c65507d266</tenant> + <aic-cloud-region>RDM2WAGPLCP</aic-cloud-region> + </network-request-information> + </aetgt:SDNCRequestData> +</aetgt:SDNCAdapterWorkflowRequest>""" + + String deleteRpcSDNCRequest = + """<aetgt:SDNCAdapterWorkflowRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:sdncadapter="http://org.onap.so/workflow/sdnc/adapter/schema/v1"> + <sdncadapter:RequestHeader> + <sdncadapter:RequestId>88f65519-9a38-4c4b-8445-9eb4a5a5af56</sdncadapter:RequestId> + <sdncadapter:SvcInstanceId>f70e927b-6087-4974-9ef8-c5e4d5847ca4</sdncadapter:SvcInstanceId> + <sdncadapter:SvcAction>unassign</sdncadapter:SvcAction> + <sdncadapter:SvcOperation>network-topology-operation</sdncadapter:SvcOperation> + <sdncadapter:CallbackUrl>sdncCallback</sdncadapter:CallbackUrl> + <sdncadapter:MsoAction>generic-resource</sdncadapter:MsoAction> + </sdncadapter:RequestHeader> + <aetgt:SDNCRequestData> + <request-information> + <request-id>88f65519-9a38-4c4b-8445-9eb4a5a5af56</request-id> + <request-action>DeleteNetworkInstance</request-action> + <source>VID</source> + <notification-url/> + <order-number/> + <order-version/> + </request-information> + <service-information> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <subscription-service-type>MSO-dev-service-type</subscription-service-type> + <onap-model-information> + <model-invariant-uuid>fcc85cb0-ad74-45d7-a5a1-17c8744fdb71</model-invariant-uuid> + <model-uuid>36a3a8ea-49a6-4ac8-b06c-89a54544b9b6</model-uuid> + <model-version>1.0</model-version> + <model-name>HNGW Protected OAM</model-name> + </onap-model-information> + <service-instance-id>f70e927b-6087-4974-9ef8-c5e4d5847ca4</service-instance-id> + <global-customer-id>globalId_45678905678</global-customer-id> + <subscriber-name/> + </service-information> + <network-information> + <network-id>networkId</network-id> + <network-type>CONTRAIL_EXTERNAL</network-type> + <onap-model-information> + <model-invariant-uuid>sn5256d1-5a33-55df-13ab-12abad84e764</model-invariant-uuid> + <model-customization-uuid>sn5256d1-5a33-55df-13ab-12abad84e222</model-customization-uuid> + <model-uuid>sn5256d1-5a33-55df-13ab-12abad84e111</model-uuid> + <model-version>1</model-version> + <model-name>CONTRAIL_EXTERNAL</model-name> + </onap-model-information> + </network-information> + <network-request-input> + <network-name>MNS-25180-L-01-dmz_direct_net_1</network-name> + <tenant>7dd5365547234ee8937416c65507d266</tenant> + <aic-cloud-region>RDM2WAGPLCP</aic-cloud-region> + <aic-clli/> + <network-input-parameters/> + </network-request-input> + </aetgt:SDNCRequestData> +</aetgt:SDNCAdapterWorkflowRequest>""" + + String sdncAdapaterDeactivateRollback = +"""<aetgt:SDNCAdapterWorkflowRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:sdncadapter="http://org.onap.so/workflow/sdnc/adapter/schema/v1"> + <sdncadapter:RequestHeader> + <sdncadapter:RequestId>88f65519-9a38-4c4b-8445-9eb4a5a5af56</sdncadapter:RequestId> + <sdncadapter:SvcInstanceId>f70e927b-6087-4974-9ef8-c5e4d5847ca4</sdncadapter:SvcInstanceId> + <sdncadapter:SvcAction>activate</sdncadapter:SvcAction> + <sdncadapter:SvcOperation>network-topology-operation</sdncadapter:SvcOperation> + <sdncadapter:CallbackUrl>sdncCallback</sdncadapter:CallbackUrl> + <sdncadapter:MsoAction>generic-resource</sdncadapter:MsoAction> + </sdncadapter:RequestHeader> + <aetgt:SDNCRequestData> + <request-information> + <request-id>88f65519-9a38-4c4b-8445-9eb4a5a5af56</request-id> + <request-action>CreateNetworkInstance</request-action> + <source>VID</source> + <notification-url/> + <order-number/> + <order-version/> + </request-information> + <service-information> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <subscription-service-type>MSO-dev-service-type</subscription-service-type> + <onap-model-information> + <model-invariant-uuid>fcc85cb0-ad74-45d7-a5a1-17c8744fdb71</model-invariant-uuid> + <model-uuid>36a3a8ea-49a6-4ac8-b06c-89a54544b9b6</model-uuid> + <model-version>1.0</model-version> + <model-name>HNGW Protected OAM</model-name> + </onap-model-information> + <service-instance-id>f70e927b-6087-4974-9ef8-c5e4d5847ca4</service-instance-id> + <global-customer-id>globalId_45678905678</global-customer-id> + <subscriber-name/> + </service-information> + <network-information> + <network-id>bdc5efe8-404a-409b-85f6-0dcc9eebae30</network-id> + <network-type>CONTRAIL_EXTERNAL</network-type> + <onap-model-information> + <model-invariant-uuid>sn5256d1-5a33-55df-13ab-12abad84e764</model-invariant-uuid> + <model-customization-uuid>sn5256d1-5a33-55df-13ab-12abad84e222</model-customization-uuid> + <model-uuid>sn5256d1-5a33-55df-13ab-12abad84e111</model-uuid> + <model-version>1</model-version> + <model-name>CONTRAIL_EXTERNAL</model-name> + </onap-model-information> + </network-information> + <network-request-input> + <network-name>MNS-25180-L-01-dmz_direct_net_1</network-name> + <tenant>7dd5365547234ee8937416c65507d266</tenant> + <aic-cloud-region>RDM2WAGPLCP</aic-cloud-region> + <aic-clli/> + <network-input-parameters/> + </network-request-input> + </aetgt:SDNCRequestData> +</aetgt:SDNCAdapterWorkflowRequest>""" + String sdncAdapterWorkflowResponse = + """<aetgt:SDNCAdapterWorkflowResponse xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1"> + <sdncadapterworkflow:response-data> +<tag0:CallbackHeader xmlns:tag0="http://org.onap.so/workflow/sdnc/adapter/schema/v1"> + <tag0:RequestId>745b1b50-e39e-4685-9cc8-c71f0bde8bf0</tag0:RequestId> + <tag0:ResponseCode>200</tag0:ResponseCode> + <tag0:ResponseMessage>OK</tag0:ResponseMessage> +</tag0:CallbackHeader> + <tag0:RequestData xmlns:tag0="http://org.onap.so/workflow/sdnc/adapter/schema/v1"><?xml version="1.0" encoding="UTF-8"?><output xmlns="com:att:sdnctl:vnf"><svc-request-id>19174929-3809-49ca-89eb-17f84a035389</svc-request-id><response-code>200</response-code><ack-final-indicator>Y</ack-final-indicator><network-information><network-id>bdc5efe8-404a-409b-85f6-0dcc9eebae30</network-id></network-information><service-information><service-type>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-type><service-instance-id>HSL_direct_net_2</service-instance-id><subscriber-name>notsurewecare</subscriber-name></service-information></output></tag0:RequestData> + </sdncadapterworkflow:response-data> + </aetgt:SDNCAdapterWorkflowResponse>""" + + String sdncAdapterWorkflowResponse_404 = + """<aetgt:SDNCAdapterWorkflowResponse xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1"> + <sdncadapterworkflow:response-data><?xml version="1.0" encoding="UTF-8"?><output xmlns="com:att:sdnctl:vnf"><svc-request-id>00703dc8-71ff-442d-a4a8-3adc5beef6a9</svc-request-id><response-code>404</response-code><response-message>Service instance not found in config tree</response-message><ack-final-indicator>Y</ack-final-indicator><network-information><network-id>49c86598-f766-46f8-84f8-8d1c1b10f9b4</network-id></network-information><service-information><service-type>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-type><service-instance-id>MNS-25180-L-01-dmz_direct_net_1</service-instance-id><subscriber-name>notsurewecare</subscriber-name></service-information></output></sdncadapterworkflow:response-data> +</aetgt:SDNCAdapterWorkflowResponse>""" + + String expected_sdncAdapterWorkflowFormattedResponse_404 = +"""<aetgt:SDNCAdapterWorkflowResponse xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns="com:att:sdnctl:vnf"> + <aetgt:response-data> + <output> + <svc-request-id>00703dc8-71ff-442d-a4a8-3adc5beef6a9</svc-request-id> + <response-code>404</response-code> + <response-message>Service instance not found in config tree</response-message> + <ack-final-indicator>Y</ack-final-indicator> + <network-information> + <network-id>49c86598-f766-46f8-84f8-8d1c1b10f9b4</network-id> + </network-information> + <service-information> + <service-type>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-type> + <service-instance-id>MNS-25180-L-01-dmz_direct_net_1</service-instance-id> + <subscriber-name>notsurewecare</subscriber-name> + </service-information> + </output> + </aetgt:response-data> +</aetgt:SDNCAdapterWorkflowResponse>""" + + String sdncAdapterWorkflowFormattedResponse = + """<aetgt:SDNCAdapterWorkflowResponse xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns="com:att:sdnctl:vnf"> + <aetgt:response-data> + <output> + <svc-request-id>19174929-3809-49ca-89eb-17f84a035389</svc-request-id> + <response-code>200</response-code> + <ack-final-indicator>Y</ack-final-indicator> + <network-information> + <network-id>bdc5efe8-404a-409b-85f6-0dcc9eebae30</network-id> + </network-information> + <service-information> + <service-type>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-type> + <service-instance-id>HSL_direct_net_2</service-instance-id> + <subscriber-name>notsurewecare</subscriber-name> + </service-information> + </output> + </aetgt:response-data> +</aetgt:SDNCAdapterWorkflowResponse>""" + +String sdncAdapterWorkflowFormattedResponse_404 = +"""<aetgt:SDNCAdapterWorkflowResponse xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns="com:att:sdnctl:vnf"> + <aetgt:response-data> + <output> + <svc-request-id>00703dc8-71ff-442d-a4a8-3adc5beef6a9</svc-request-id> + <response-code>404</response-code> + <response-message>Service instance not found in config tree</response-message> + <ack-final-indicator>Y</ack-final-indicator> + <network-information> + <network-id>49c86598-f766-46f8-84f8-8d1c1b10f9b4</network-id> + </network-information> + <service-information> + <service-type>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-type> + <service-instance-id>MNS-25180-L-01-dmz_direct_net_1</service-instance-id> + <subscriber-name>notsurewecare</subscriber-name> + </service-information> + </output> + </aetgt:response-data> +</aetgt:SDNCAdapterWorkflowResponse>""" + + String invalidRequest = "Invalid value of network-id element" + + + + String sndcWorkflowException = + """<aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1"> + <aetgt:ErrorMessage>Received error from SDN-C: No availability zone available</aetgt:ErrorMessage> + <aetgt:ErrorCode>5300</aetgt:ErrorCode> + <aetgt:SourceSystemErrorCode>200</aetgt:SourceSystemErrorCode> +</aetgt:WorkflowException>""" + + String sndcWorkflowErrorResponse = + """<aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1"> + <aetgt:ErrorMessage>Received error from SDN-C: <aetgt:SDNCAdapterWorkflowResponse xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1"> + <sdncadapterworkflow:response-data><?xml version="1.0" encoding="UTF-8"?><output xmlns="com:att:sdnctl:vnf"><svc-request-id>00703dc8-71ff-442d-a4a8-3adc5beef6a9</svc-request-id><response-code>404</response-code><response-message>Service instance not found in config tree</response-message><ack-final-indicator>Y</ack-final-indicator><network-information><network-id>49c86598-f766-46f8-84f8-8d1c1b10f9b4</network-id></network-information><service-information><service-type>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-type><service-instance-id>MNS-25180-L-01-dmz_direct_net_1</service-instance-id><subscriber-name>notsurewecare</subscriber-name></service-information></output></sdncadapterworkflow:response-data> +</aetgt:SDNCAdapterWorkflowResponse></aetgt:ErrorMessage> + <aetgt:ErrorCode>5300</aetgt:ErrorCode> + </aetgt:WorkflowException>""" + + String unexpectedErrorEncountered = + """<aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1"> + <aetgt:ErrorMessage>bpel error deleting network</aetgt:ErrorMessage> + <aetgt:ErrorCode>5300</aetgt:ErrorCode> + </aetgt:WorkflowException>""" + + + // expectedVnfRequest + String inputViprSDC_NetworkRequest = + """<network-request xmlns="http://www.w3.org/2001/XMLSchema"> + <request-info> + <request-id>88f65519-9a38-4c4b-8445-9eb4a5a5af56</request-id> + <action>DELETE</action> + <source>VID</source> + <service-instance-id>f70e927b-6087-4974-9ef8-c5e4d5847ca4</service-instance-id> + </request-info> + <network-inputs> + <network-id>networkId</network-id> + <network-name>MNS-25180-L-01-dmz_direct_net_1</network-name> + <network-type>CONTRAIL_EXTERNAL</network-type> + <subscription-service-type>MSO-dev-service-type</subscription-service-type> + <global-customer-id>globalId_45678905678</global-customer-id> + <aic-cloud-region>RDM2WAGPLCP</aic-cloud-region> + <tenant-id>7dd5365547234ee8937416c65507d266</tenant-id> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <backout-on-failure>false</backout-on-failure> + <failIfExist>false</failIfExist> + <networkModelInfo> + <modelName>CONTRAIL_EXTERNAL</modelName> + <modelUuid>sn5256d1-5a33-55df-13ab-12abad84e111</modelUuid> + <modelInvariantUuid>sn5256d1-5a33-55df-13ab-12abad84e764</modelInvariantUuid> + <modelVersion>1</modelVersion> + <modelCustomizationUuid>sn5256d1-5a33-55df-13ab-12abad84e222</modelCustomizationUuid> + <modelType>CONTRAIL_EXTERNAL</modelType> + </networkModelInfo> + <serviceModelInfo> + <modelName>HNGW Protected OAM</modelName> + <modelUuid>36a3a8ea-49a6-4ac8-b06c-89a54544b9b6</modelUuid> + <modelInvariantUuid>fcc85cb0-ad74-45d7-a5a1-17c8744fdb71</modelInvariantUuid> + <modelVersion>1.0</modelVersion> + <modelCustomizationUuid/> + <modelType>service</modelType> + </serviceModelInfo> + <sdncVersion>1702</sdncVersion> + </network-inputs> + <network-params/> +</network-request>""" +// - - - - - - - - + + + @Before + public void init() + { + MockitoAnnotations.initMocks(this) + } + + @Test + //@Ignore + public void preProcessRequest_Json() { + + println "************ preProcessRequest_Payload ************* " + ExecutionEntity mockExecution = setupMock() + // Initialize prerequisite variables + when(mockExecution.getVariable("mso-request-id")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + when(mockExecution.getVariable("requestId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + when(mockExecution.getVariable("isBaseVfModule")).thenReturn(true) + when(mockExecution.getVariable("recipeTimeout")).thenReturn(0) + when(mockExecution.getVariable("requestAction")).thenReturn("DELETE") + when(mockExecution.getVariable("networkId")).thenReturn("bdc5efe8-404a-409b-85f6-0dcc9eebae30") + when(mockExecution.getVariable("serviceInstanceId")).thenReturn("f70e927b-6087-4974-9ef8-c5e4d5847ca4") + when(mockExecution.getVariable("vnfId")).thenReturn("") + when(mockExecution.getVariable("volumeGroupId")).thenReturn("") + //when(mockExecution.getVariable("networkId")).thenReturn("") + when(mockExecution.getVariable("serviceType")).thenReturn("MOG") + when(mockExecution.getVariable("networkType")).thenReturn("modelName") + when(mockExecution.getVariable("bpmnRequest")).thenReturn(incomingJsonRequest) + when(mockExecution.getVariable("disableRollback")).thenReturn(true) + when(mockExecution.getVariable("testMessageId")).thenReturn("7df689f9-7b93-430b-9b9e-28140d70cc7ad") + when(mockExecution.getVariable("mso-request-id")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + when(mockExecution.getVariable("mso-service-instance-id")).thenReturn("FH/VLXM/003717//SW_INTERNET") + when(mockExecution.getVariable("mso.adapters.po.auth")).thenReturn("3141634BF7E070AA289CF2892C986C0B") + when(mockExecution.getVariable("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("mso.rollback")).thenReturn("true") + when(mockExecution.getVariable("sdncVersion")).thenReturn("1610") + + DoDeleteNetworkInstance DoDeleteNetworkInstance = new DoDeleteNetworkInstance() + DoDeleteNetworkInstance.preProcessRequest(mockExecution) + + // check the sequence of variable invocation + //MockitoDebuggerImpl preDebugger = new MockitoDebuggerImpl() + //preDebugger.printInvocations(mockExecution) + +// verify(mockExecution).getVariable("isDebugLogEnabled") + verify(mockExecution).setVariable("prefix", Prefix) + + //verify variable initialization + initializeVariables(mockExecution) + + verify(mockExecution).setVariable("action", "DELETE") + verify(mockExecution).setVariable(Prefix + "networkRequest", expectedNetworkRequest) + + verify(mockExecution).setVariable(Prefix + "rollbackEnabled", false) + + verify(mockExecution).setVariable(Prefix + "networkInputs", expected_networkInput) + verify(mockExecution).setVariable(Prefix + "messageId", "7df689f9-7b93-430b-9b9e-28140d70cc7ad") + verify(mockExecution).setVariable(Prefix + "source", "VID") + + // Authentications + verify(mockExecution).setVariable("BasicAuthHeaderValuePO", "Basic cGFzc3dvcmQ=") + verify(mockExecution).setVariable("BasicAuthHeaderValueSDNC", "Basic cGFzc3dvcmQ=") + + + } + + @Test + //@Ignore + public void preProcessRequest_vPER() { + + def networkModelInfo = """{"modelUuid": "sn5256d1-5a33-55df-13ab-12abad84e111", + "modelName": "CONTRAIL_EXTERNAL", + "modelType": "CONTRAIL_EXTERNAL", + "modelVersion": "1", + "modelCustomizationUuid": "sn5256d1-5a33-55df-13ab-12abad84e222", + "modelInvariantUuid": "sn5256d1-5a33-55df-13ab-12abad84e764" + }""".trim() + + println "************ preProcessRequest_Payload ************* " + ExecutionEntity mockExecution = setupMock() + // Initialize prerequisite variables + when(mockExecution.getVariable("testMessageId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + // Inputs: + when(mockExecution.getVariable("msoRequestId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + when(mockExecution.getVariable("disableRollback")).thenReturn("true") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("serviceInstanceId")).thenReturn("f70e927b-6087-4974-9ef8-c5e4d5847ca4") + when(mockExecution.getVariable("networkId")).thenReturn("bdc5efe8-404a-409b-85f6-0dcc9eebae30") // optional + when(mockExecution.getVariable("networkName")).thenReturn("MNS-25180-L-01-dmz_direct_net_1") // optional + when(mockExecution.getVariable("productFamilyId")).thenReturn("a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb") + when(mockExecution.getVariable("networkModelInfo")).thenReturn("CONTRAIL_EXTERNAL") + when(mockExecution.getVariable("lcpCloudRegionId")).thenReturn("RDM2WAGPLCP") + when(mockExecution.getVariable("tenantId")).thenReturn("7dd5365547234ee8937416c65507d266") + when(mockExecution.getVariable("failIfExists")).thenReturn("false") + when(mockExecution.getVariable("networkModelInfo")).thenReturn(networkModelInfo) + when(mockExecution.getVariable("sdncVersion")).thenReturn("1702") + when(mockExecution.getVariable("action")).thenReturn("DELETE") + when(mockExecution.getVariable("subscriptionServiceType")).thenReturn("MSO-dev-service-type") + when(mockExecution.getVariable("globalSubscriberId")).thenReturn("globalId_45678905678") + when(mockExecution.getVariable("testMessageId")).thenReturn("7df689f9-7b93-430b-9b9e-28140d70cc7ad") + + when(mockExecution.getVariable("mso.adapters.po.auth")).thenReturn("3141634BF7E070AA289CF2892C986C0B") + when(mockExecution.getVariable("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") + + DoDeleteNetworkInstance DoDeleteNetworkInstance = new DoDeleteNetworkInstance() + DoDeleteNetworkInstance.preProcessRequest(mockExecution) + + // check the sequence of variable invocation + //MockitoDebuggerImpl preDebugger = new MockitoDebuggerImpl() + //preDebugger.printInvocations(mockExecution) + +// verify(mockExecution).getVariable("isDebugLogEnabled") + verify(mockExecution).setVariable("prefix", Prefix) + + //verify variable initialization + initializeVariables(mockExecution) + + verify(mockExecution).setVariable("action", "DELETE") + verify(mockExecution).setVariable(Prefix + "networkRequest", expectedVperNetworkRequest) + + verify(mockExecution).setVariable(Prefix + "rollbackEnabled", false) + + verify(mockExecution).setVariable(Prefix + "networkInputs", expectedVper_networkInput) + verify(mockExecution).setVariable(Prefix + "messageId", "7df689f9-7b93-430b-9b9e-28140d70cc7ad") + verify(mockExecution).setVariable(Prefix + "source", "VID") + + // Authentications + verify(mockExecution).setVariable("BasicAuthHeaderValuePO", "Basic cGFzc3dvcmQ=") + verify(mockExecution).setVariable("BasicAuthHeaderValueSDNC", "Basic cGFzc3dvcmQ=") + + + } + + public void initializeVariables (DelegateExecution mockExecution) { + + verify(mockExecution).setVariable(Prefix + "networkRequest", "") + verify(mockExecution).setVariable(Prefix + "isSilentSuccess", false) + verify(mockExecution).setVariable(Prefix + "Success", false) + + verify(mockExecution).setVariable(Prefix + "requestId", "") + verify(mockExecution).setVariable(Prefix + "source", "") + verify(mockExecution).setVariable(Prefix + "lcpCloudRegion", "") + verify(mockExecution).setVariable(Prefix + "networkInputs", "") + verify(mockExecution).setVariable(Prefix + "tenantId", "") + + verify(mockExecution).setVariable(Prefix + "queryAAIRequest","") + verify(mockExecution).setVariable(Prefix + "queryAAIResponse", "") + verify(mockExecution).setVariable(Prefix + "aaiReturnCode", "") + verify(mockExecution).setVariable(Prefix + "isAAIGood", false) + verify(mockExecution).setVariable(Prefix + "isVfRelationshipExist", false) + + // AAI query Cloud Region + verify(mockExecution).setVariable(Prefix + "queryCloudRegionRequest","") + verify(mockExecution).setVariable(Prefix + "queryCloudRegionReturnCode","") + verify(mockExecution).setVariable(Prefix + "queryCloudRegionResponse","") + verify(mockExecution).setVariable(Prefix + "cloudRegionPo","") + verify(mockExecution).setVariable(Prefix + "cloudRegionSdnc","") + + verify(mockExecution).setVariable(Prefix + "deleteNetworkRequest", "") + verify(mockExecution).setVariable(Prefix + "deleteNetworkResponse", "") + verify(mockExecution).setVariable(Prefix + "networkReturnCode", "") + verify(mockExecution).setVariable(Prefix + "rollbackNetworkRequest", "") + + verify(mockExecution).setVariable(Prefix + "deleteSDNCRequest", "") + verify(mockExecution).setVariable(Prefix + "deleteSDNCResponse", "") + verify(mockExecution).setVariable(Prefix + "sdncReturnCode", "") + verify(mockExecution).setVariable(Prefix + "sdncResponseSuccess", false) + + verify(mockExecution).setVariable(Prefix + "deactivateSDNCRequest", "") + verify(mockExecution).setVariable(Prefix + "deactivateSDNCResponse", "") + verify(mockExecution).setVariable(Prefix + "deactivateSdncReturnCode", "") + verify(mockExecution).setVariable(Prefix + "isSdncDeactivateRollbackNeeded", "") + + verify(mockExecution).setVariable(Prefix + "rollbackDeactivateSDNCRequest", "") + verify(mockExecution).setVariable(Prefix + "isException", false) + + } + + @Test + //@Ignore + public void preProcessRequest_Json_MissingId() { + + println "************ preProcessRequest_MissingId() ************* " + ExecutionEntity mockExecution = setupMock() + // Initialize prerequisite variables + when(mockExecution.getVariable("mso-request-id")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + when(mockExecution.getVariable("requestId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + when(mockExecution.getVariable("isBaseVfModule")).thenReturn(true) + when(mockExecution.getVariable("recipeTimeout")).thenReturn(0) + when(mockExecution.getVariable("requestAction")).thenReturn("DELETE") + //when(mockExecution.getVariable("networkId")).thenReturn("") // missing Id + when(mockExecution.getVariable("serviceInstanceId")).thenReturn("f70e927b-6087-4974-9ef8-c5e4d5847ca4") + when(mockExecution.getVariable("vnfId")).thenReturn("") + when(mockExecution.getVariable("volumeGroupId")).thenReturn("") + //when(mockExecution.getVariable("networkId")).thenReturn("") + when(mockExecution.getVariable("serviceType")).thenReturn("MOG") + when(mockExecution.getVariable("networkType")).thenReturn("modelName") + when(mockExecution.getVariable("bpmnRequest")).thenReturn(incomingJsonRequest) + when(mockExecution.getVariable("disableRollback")).thenReturn(true) + + when(mockExecution.getVariable("testMessageId")).thenReturn("7df689f9-7b93-430b-9b9e-28140d70cc7ad") + when(mockExecution.getVariable(Prefix + "messageId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + when(mockExecution.getVariable("mso-request-id")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + when(mockExecution.getVariable("mso-service-instance-id")).thenReturn("FH/VLXM/003717//SW_INTERNET") + when(mockExecution.getVariable("mso.adapters.po.auth")).thenReturn("3141634BF7E070AA289CF2892C986C0B") + when(mockExecution.getVariable("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("mso.rollback")).thenReturn("true") + when(mockExecution.getVariable("sdncVersion")).thenReturn("1610") + + // preProcessRequest(DelegateExecution execution) + DoDeleteNetworkInstance DoDeleteNetworkInstance = new DoDeleteNetworkInstance() + try { + DoDeleteNetworkInstance.preProcessRequest(mockExecution) + } catch (Exception ex) { + println " Test End - Handle catch-throw BpmnError()! " + } + + //verify(mockExecution).getVariable("isDebugLogEnabled") + verify(mockExecution).setVariable("prefix", Prefix) + + //verify variable initialization + initializeVariables(mockExecution) + + verify(mockExecution).setVariable("action", "DELETE") + verify(mockExecution).setVariable(Prefix + "networkRequest", expectedNetworkRequestMissingId) + verify(mockExecution).setVariable(Prefix + "rollbackEnabled", false) + + verify(mockExecution).setVariable(Prefix + "networkInputs", networkInputsMissingId) + verify(mockExecution).setVariable(Prefix + "messageId", "7df689f9-7b93-430b-9b9e-28140d70cc7ad") + verify(mockExecution).setVariable(Prefix + "source", "VID") + + } + + @Test + //@Ignore + public void preProcessRequest_Json_MissingCloudRegion() { + + def networkModelInfo = """{"modelVersionId": "sn5256d1-5a33-55df-13ab-12abad84e111", + "modelName": "CONTRAIL_EXTERNAL", + "modelType": "CONTRAIL_EXTERNAL", + "modelVersion": "1", + "modelCustomizationId": "sn5256d1-5a33-55df-13ab-12abad84e222", + "modelInvariantId": "sn5256d1-5a33-55df-13ab-12abad84e764" + }""".trim() + + println "************ preProcessRequest_MissingCloudRegion() ************* " + ExecutionEntity mockExecution = setupMock() + // Initialize prerequisite variables + when(mockExecution.getVariable("networkModelInfo")).thenReturn(networkModelInfo) + when(mockExecution.getVariable("mso-request-id")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + when(mockExecution.getVariable("requestId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + when(mockExecution.getVariable("isBaseVfModule")).thenReturn(true) + when(mockExecution.getVariable("recipeTimeout")).thenReturn(0) + when(mockExecution.getVariable("requestAction")).thenReturn("DELETE") + when(mockExecution.getVariable("networkId")).thenReturn("bdc5efe8-404a-409b-85f6-0dcc9eebae30") + when(mockExecution.getVariable("serviceInstanceId")).thenReturn("f70e927b-6087-4974-9ef8-c5e4d5847ca4") + when(mockExecution.getVariable("vnfId")).thenReturn("") + when(mockExecution.getVariable("volumeGroupId")).thenReturn("") + //when(mockExecution.getVariable("networkId")).thenReturn("") + when(mockExecution.getVariable("serviceType")).thenReturn("MOG") + when(mockExecution.getVariable("networkType")).thenReturn("modelName") + when(mockExecution.getVariable("bpmnRequest")).thenReturn(incomingRequestMissingCloudRegion) + when(mockExecution.getVariable("disableRollback")).thenReturn(true) + + when(mockExecution.getVariable("testMessageId")).thenReturn("7df689f9-7b93-430b-9b9e-28140d70cc7ad") + when(mockExecution.getVariable(Prefix + "messageId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + when(mockExecution.getVariable("mso-request-id")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + when(mockExecution.getVariable("mso-service-instance-id")).thenReturn("FH/VLXM/003717//SW_INTERNET") + when(mockExecution.getVariable("mso.adapters.po.auth")).thenReturn("3141634BF7E070AA289CF2892C986C0B") + when(mockExecution.getVariable("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("mso.rollback")).thenReturn("true") + when(mockExecution.getVariable("sdncVersion")).thenReturn("1610") + + // preProcessRequest(DelegateExecution execution) + DoDeleteNetworkInstance DoDeleteNetworkInstance = new DoDeleteNetworkInstance() + DoDeleteNetworkInstance.preProcessRequest(mockExecution) + + //verify(mockExecution).getVariable("isDebugLogEnabled") + verify(mockExecution).setVariable("prefix", Prefix) + + //verify variable initialization + initializeVariables(mockExecution) + + verify(mockExecution).setVariable("action", "DELETE") + verify(mockExecution).setVariable(Prefix + "networkRequest", expectedNetworkRequestMissingCloudRegion) + verify(mockExecution).setVariable(Prefix + "rollbackEnabled", false) + + verify(mockExecution).setVariable(Prefix + "networkInputs", networkInputsMissingCloudRegion) + verify(mockExecution).setVariable(Prefix + "messageId", "7df689f9-7b93-430b-9b9e-28140d70cc7ad") + verify(mockExecution).setVariable(Prefix + "lcpCloudRegion", null) + + verify(mockExecution).setVariable("BasicAuthHeaderValuePO","Basic cGFzc3dvcmQ=") + verify(mockExecution).setVariable("BasicAuthHeaderValueSDNC", "Basic cGFzc3dvcmQ=") + + } + + + + @Test + //@Ignore + public void prepareNetworkRequest() { + + println "************ prepareNetworkRequest ************* " + ExecutionEntity mockExecution = setupMock() + // Initialize prerequisite variables + when(mockExecution.getVariable(Prefix + "networkRequest")).thenReturn(expectedVperNetworkRequest) + when(mockExecution.getVariable(Prefix + "queryAAIResponse")).thenReturn(queryAAIResponse) + when(mockExecution.getVariable(Prefix + "cloudRegionPo")).thenReturn("RDM2WAGPLCP") + when(mockExecution.getVariable(Prefix + "tenantId")).thenReturn("e81d842d3e8b45c5a59f57cd76af3aaf") + + when(mockExecution.getVariable("serviceInstanceId")).thenReturn("f70e927b-6087-4974-9ef8-c5e4d5847ca4") + when(mockExecution.getVariable("mso.adapters.network.rest.endpoint")).thenReturn("http://localhost:8090/networks/NetworkAdapter") + when(mockExecution.getVariable("msoRequestId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + when(mockExecution.getVariable(Prefix + "messageId")).thenReturn("messageId_value") + //when(mockExecution.getVariable("URN_?????")).thenReturn("") // notificationUrl, //TODO - is this coming from URN? What variable/value to use? + when(mockExecution.getVariable(Prefix + "rollbackEnabled")).thenReturn("true") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + + DoDeleteNetworkInstance DoDeleteNetworkInstance = new DoDeleteNetworkInstance() + DoDeleteNetworkInstance.prepareNetworkRequest(mockExecution) + + verify(mockExecution).setVariable("prefix", Prefix) + verify(mockExecution).setVariable("mso.adapters.network.rest.endpoint", "http://localhost:8090/networks/NetworkAdapter/bdc5efe8-404a-409b-85f6-0dcc9eebae30") + //verify(mockExecution).setVariable(Prefix + "deleteNetworkRequest", deleteNetworkRequest) + verify(mockExecution).setVariable(Prefix + "deleteNetworkRequest", deleteNetworkRESTRequest) + + } + + @Test + //@Ignore + public void prepareNetworkRequest_AlaCarte() { + + println "************ prepareNetworkRequest ************* " + ExecutionEntity mockExecution = setupMock() + // Initialize prerequisite variables + when(mockExecution.getVariable(Prefix + "networkRequest")).thenReturn(expectedNetworkRequest) + when(mockExecution.getVariable(Prefix + "queryAAIResponse")).thenReturn(queryAAIResponse) + when(mockExecution.getVariable(Prefix + "cloudRegionPo")).thenReturn("RDM2WAGPLCP") + when(mockExecution.getVariable(Prefix + "tenantId")).thenReturn("e81d842d3e8b45c5a59f57cd76af3aaf") + + when(mockExecution.getVariable("serviceInstanceId")).thenReturn("f70e927b-6087-4974-9ef8-c5e4d5847ca4") + when(mockExecution.getVariable("mso.adapters.network.rest.endpoint")).thenReturn("http://localhost:8090/networks/NetworkAdapter") + when(mockExecution.getVariable("msoRequestId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + when(mockExecution.getVariable(Prefix + "messageId")).thenReturn("messageId_value") + //when(mockExecution.getVariable("URN_?????")).thenReturn("") // notificationUrl, //TODO - is this coming from URN? What variable/value to use? + when(mockExecution.getVariable(Prefix + "rollbackEnabled")).thenReturn("true") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + + DoDeleteNetworkInstance DoDeleteNetworkInstance = new DoDeleteNetworkInstance() + DoDeleteNetworkInstance.prepareNetworkRequest(mockExecution) + + verify(mockExecution).setVariable("prefix", Prefix) + verify(mockExecution).setVariable("mso.adapters.network.rest.endpoint", "http://localhost:8090/networks/NetworkAdapter/bdc5efe8-404a-409b-85f6-0dcc9eebae30") + //verify(mockExecution).setVariable(Prefix + "deleteNetworkRequest", deleteNetworkRequest) + verify(mockExecution).setVariable("mso-request-id", "88f65519-9a38-4c4b-8445-9eb4a5a5af56") + verify(mockExecution).setVariable(Prefix + "deleteNetworkRequest", deleteNetworkRESTRequestAlaCarte) + + } + + @Test + //@Ignore + public void sendRequestToVnfAdapter() { + + println "************ sendRequestToVnfAdapter ************* " + + WireMock.reset(); + MockNetworkAdapter("bdc5efe8-404a-409b-85f6-0dcc9eebae30", 200, "deleteNetworkResponse_Success.xml"); + + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable(Prefix + "deleteNetworkRequest")).thenReturn(deleteNetworkRESTRequest) + when(mockExecution.getVariable("mso.adapters.network.rest.endpoint")).thenReturn("http://localhost:8090/networks/NetworkAdapter/bdc5efe8-404a-409b-85f6-0dcc9eebae30") + when(mockExecution.getVariable("BasicAuthHeaderValuePO")).thenReturn("3141634BF7E070AA289CF2892C986C0B") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + + DoDeleteNetworkInstance DoDeleteNetworkInstance = new DoDeleteNetworkInstance() + DoDeleteNetworkInstance.sendRequestToVnfAdapter(mockExecution) + + verify(mockExecution).setVariable(Prefix + "networkReturnCode", 200) + //verify(mockExecution).setVariable(Prefix + "deleteNetworkResponse", deleteNetworkResponse_noRollback) + + } + + + @Test + //@Ignore + public void prepareSDNCRequest() { + + println "************ prepareSDNCRequest ************* " + + ExecutionEntity mockExecution = setupMock() + // Initialize prerequisite variables + when(mockExecution.getVariable(Prefix + "networkRequest")).thenReturn(expectedNetworkRequest) + when(mockExecution.getVariable(Prefix + "cloudRegionSdnc")).thenReturn("RDM2WAGPLCP") + when(mockExecution.getVariable(Prefix + "queryAAIResponse")).thenReturn(aaiResponse) + when(mockExecution.getVariable("mso-request-id")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + when(mockExecution.getVariable("testMessageId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + when(mockExecution.getVariable("serviceInstanceId")).thenReturn("f70e927b-6087-4974-9ef8-c5e4d5847ca4") + when(mockExecution.getVariable("mso.workflow.sdncadapter.callback")).thenReturn("http://localhost:8090/SDNCAdapterCallback") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + + DoDeleteNetworkInstance DoDeleteNetworkInstance = new DoDeleteNetworkInstance() + DoDeleteNetworkInstance.prepareSDNCRequest(mockExecution) + + verify(mockExecution).setVariable("prefix", Prefix) + verify(mockExecution).setVariable(Prefix + "deleteSDNCRequest", deleteSDNCRequest) + + } + + @Test + //@Ignore + public void prepareRpcSDNCRequest() { + + println "************ prepareRpcSDNCRequest ************* " + + ExecutionEntity mockExecution = setupMock() + // Initialize prerequisite variables + when(mockExecution.getVariable(Prefix + "networkRequest")).thenReturn(inputViprSDC_NetworkRequest) + when(mockExecution.getVariable(Prefix + "cloudRegionSdnc")).thenReturn("RDM2WAGPLCP") + when(mockExecution.getVariable("mso-request-id")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + when(mockExecution.getVariable("msoRequestId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + when(mockExecution.getVariable("testMessageId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") // test ONLY + when(mockExecution.getVariable("serviceInstanceId")).thenReturn("f70e927b-6087-4974-9ef8-c5e4d5847ca4") + when(mockExecution.getVariable("mso.workflow.sdncadapter.callback")).thenReturn("http://localhost:8090/SDNCAdapterCallback") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + + DoDeleteNetworkInstance DoDeleteNetworkInstance = new DoDeleteNetworkInstance() + DoDeleteNetworkInstance.prepareRpcSDNCRequest(mockExecution) + + verify(mockExecution).setVariable("prefix", Prefix) + verify(mockExecution).setVariable(Prefix + "deleteSDNCRequest", deleteRpcSDNCRequest) + + } + + @Test + //@Ignore + public void prepareRpcSDNCActivateRollback() { + + println "************ prepareRpcSDNCActivateRollback ************* " + + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + // Initialize prerequisite variables + when(mockExecution.getVariable(Prefix + "networkRequest")).thenReturn(inputViprSDC_NetworkRequest) + when(mockExecution.getVariable(Prefix + "cloudRegionSdnc")).thenReturn("RDM2WAGPLCP") + when(mockExecution.getVariable(Prefix + "serviceInstanceId")).thenReturn("f70e927b-6087-4974-9ef8-c5e4d5847ca4") + when(mockExecution.getVariable(Prefix + "networkId")).thenReturn("8abc633a-810b-4ca5-8b3a-09511d13a2ce") + when(mockExecution.getVariable("mso-request-id")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + when(mockExecution.getVariable("msoRequestId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + when(mockExecution.getVariable("testMessageId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") // test ONLY + when(mockExecution.getVariable("mso.workflow.sdncadapter.callback")).thenReturn("http://localhost:8090/SDNCAdapterCallback") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("GENGSI_siResourceLink")).thenReturn(null) + when(mockExecution.getVariable(Prefix + "deactivateSDNCResponse")).thenReturn(sdncAdapterWorkflowFormattedResponse) + + // preProcessRequest(DelegateExecution execution) + DoDeleteNetworkInstance DoDeleteNetworkInstance = new DoDeleteNetworkInstance() + DoDeleteNetworkInstance.prepareRpcSDNCDeactivateRollback(mockExecution) + + // verify set prefix = Prefix + "" + verify(mockExecution).setVariable("prefix", Prefix) + //verify(mockExecution).setVariable("mso-request-id", "88f65519-9a38-4c4b-8445-9eb4a5a5af56") + //verify(mockExecution).setVariable(Prefix + "requestId", "88f65519-9a38-4c4b-8445-9eb4a5a5af56") + //verify(mockExecution).setVariable("mso-service-instance-id", "88f65519-9a38-4c4b-8445-9eb4a5a5af56") + verify(mockExecution).setVariable(Prefix + "rollbackDeactivateSDNCRequest", sdncAdapaterDeactivateRollback) + + } + + + @Test + //@Ignore + public void callRESTQueryAAI_200() { + + println "************ callRESTQueryAAI ************* " + + WireMock.reset(); + MockGetNetworkByIdWithDepth("bdc5efe8-404a-409b-85f6-0dcc9eebae30", "DeleteNetworkV2/deleteNetworkAAIResponse_Success.xml", "all"); + + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable(Prefix + "networkInputs")).thenReturn(expectedNetworkRequest) + when(mockExecution.getVariable(Prefix + "messageId")).thenReturn("e8ebf6a0-f8ea-4dc0-8b99-fe98a87722d6") + when(mockExecution.getVariable("aai.endpoint")).thenReturn("http://localhost:8090") + when(mockExecution.getVariable("mso.workflow.default.aai.network.l3-network.uri")).thenReturn("") + // old: when(mockExecution.getVariable("mso.workflow.DoDeleteNetworkInstance.aai.network.l3-network.uri")).thenReturn("/aai/v8/network/l3-networks/l3-network") + when(mockExecution.getVariable("mso.workflow.DoDeleteNetworkInstance.aai.l3-network.uri")).thenReturn("/aai/v9/network/l3-networks/l3-network") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn('http://org.openecomp.aai.inventory/') + when(mockExecution.getVariable("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") + when(mockExecution.getVariable("aai.auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") + + DoDeleteNetworkInstance DoDeleteNetworkInstance = new DoDeleteNetworkInstance() + DoDeleteNetworkInstance.callRESTQueryAAI(mockExecution) + + verify(mockExecution).setVariable("prefix", Prefix) + verify(mockExecution).setVariable(Prefix + "queryAAIRequest", "http://localhost:8090/aai/v9/network/l3-networks/l3-network/bdc5efe8-404a-409b-85f6-0dcc9eebae30"+"?depth=all") + + verify(mockExecution).setVariable(Prefix + "aaiReturnCode", "200") + //verify(mockExecution).setVariable(Prefix + "queryAAIResponse", aaiResponse) + verify(mockExecution).setVariable(Prefix + "isAAIGood", true) + verify(mockExecution).setVariable(Prefix + "isVfRelationshipExist", false) + + } + + @Test + //@Ignore + public void callRESTQueryAAI_withRelationship_200() { + + println "************ callRESTQueryAAI ************* " + + WireMock.reset(); + MockGetNetworkByIdWithDepth("bdc5efe8-404a-409b-85f6-0dcc9eebae30", "DeleteNetworkV2/deleteNetworkAAIResponse_withRelationship_Success.xml", "all"); + + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable(Prefix + "networkInputs")).thenReturn(expectedNetworkRequest) + when(mockExecution.getVariable(Prefix + "messageId")).thenReturn("e8ebf6a0-f8ea-4dc0-8b99-fe98a87722d6") + when(mockExecution.getVariable("aai.endpoint")).thenReturn("http://localhost:8090") + when(mockExecution.getVariable("mso.workflow.default.aai.network.l3-network.uri")).thenReturn("") + // old: when(mockExecution.getVariable("mso.workflow.DoDeleteNetworkInstance.aai.network.l3-network.uri")).thenReturn("/aai/v8/network/l3-networks/l3-network") + when(mockExecution.getVariable("mso.workflow.DoDeleteNetworkInstance.aai.l3-network.uri")).thenReturn("/aai/v9/network/l3-networks/l3-network") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn('http://org.openecomp.aai.inventory/') + when(mockExecution.getVariable("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") + when(mockExecution.getVariable("aai.auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") + + DoDeleteNetworkInstance DoDeleteNetworkInstance = new DoDeleteNetworkInstance() + DoDeleteNetworkInstance.callRESTQueryAAI(mockExecution) + + verify(mockExecution, atLeast(1)).setVariable("prefix", Prefix) + verify(mockExecution).setVariable(Prefix + "queryAAIRequest", "http://localhost:8090/aai/v9/network/l3-networks/l3-network/bdc5efe8-404a-409b-85f6-0dcc9eebae30"+"?depth=all") + + verify(mockExecution).setVariable(Prefix + "aaiReturnCode", "200") + //verify(mockExecution).setVariable(Prefix + "queryAAIResponse", aaiResponseWithRelationship) + verify(mockExecution).setVariable(Prefix + "isAAIGood", true) + verify(mockExecution).setVariable(Prefix + "isVfRelationshipExist", true) + + } + + @Test + //@Ignore + public void callRESTQueryAAI_200_DefaultUri() { + + println "************ callRESTQueryAAI ************* " + + WireMock.reset(); + MockGetNetworkByIdWithDepth("bdc5efe8-404a-409b-85f6-0dcc9eebae30", "DeleteNetworkV2/deleteNetworkAAIResponse_Success.xml", "all"); + + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable(Prefix + "networkInputs")).thenReturn(expectedNetworkRequest) + when(mockExecution.getVariable(Prefix + "messageId")).thenReturn("e8ebf6a0-f8ea-4dc0-8b99-fe98a87722d6") + when(mockExecution.getVariable("aai.endpoint")).thenReturn("http://localhost:8090") + // old: when(mockExecution.getVariable("mso.workflow.default.aai.network.l3-network.uri")).thenReturn("/aai/v8/network/l3-networks/l3-network") + when(mockExecution.getVariable("mso.workflow.global.default.aai.version")).thenReturn("8") + when(mockExecution.getVariable("mso.workflow.default.aai.v8.l3-network.uri")).thenReturn("/aai/v9/network/l3-networks/l3-network") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn('http://org.openecomp.aai.inventory/') + when(mockExecution.getVariable("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") + when(mockExecution.getVariable("aai.auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") + + DoDeleteNetworkInstance DoDeleteNetworkInstance = new DoDeleteNetworkInstance() + DoDeleteNetworkInstance.callRESTQueryAAI(mockExecution) + + verify(mockExecution).setVariable("prefix", Prefix) + verify(mockExecution).setVariable(Prefix + "queryAAIRequest", "http://localhost:8090/aai/v9/network/l3-networks/l3-network/bdc5efe8-404a-409b-85f6-0dcc9eebae30"+ "?depth=all") + + verify(mockExecution).setVariable(Prefix + "aaiReturnCode", "200") + //verify(mockExecution).setVariable(Prefix + "queryAAIResponse", aaiResponse) + verify(mockExecution).setVariable(Prefix + "isAAIGood", true) + + } + + @Test + //@Ignore + public void callRESTQueryAAICloudRegion30_200() { + + println "************ callRESTQueryAAICloudRegion30_200 ************* " + + WireMock.reset(); + MockGetNetworkCloudRegion("DeleteNetworkV2/cloudRegion30_AAIResponse_Success.xml", "RDM2WAGPLCP"); + + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("prefix")).thenReturn(Prefix) + when(mockExecution.getVariable(Prefix + "networkInputs")).thenReturn(expectedNetworkRequest) + when(mockExecution.getVariable(Prefix + "lcpCloudRegion")).thenReturn("RDM2WAGPLCP") + when(mockExecution.getVariable("aai.endpoint")).thenReturn("http://localhost:8090") + // old: when(mockExecution.getVariable("mso.workflow.default.aai.cloud-infrastructure.cloud-region.uri")).thenReturn("/aai/v8/cloud-infrastructure/cloud-regions/cloud-region/att-aic") + when(mockExecution.getVariable("mso.workflow.global.default.aai.version")).thenReturn("8") + when(mockExecution.getVariable("mso.workflow.default.aai.v8.cloud-region.uri")).thenReturn("/aai/v8/cloud-infrastructure/cloud-regions/cloud-region/att-aic") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn('http://org.openecomp.aai.inventory/') + when(mockExecution.getVariable("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") + when(mockExecution.getVariable("aai.auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") + + DoDeleteNetworkInstance DoDeleteNetworkInstance = new DoDeleteNetworkInstance() + DoDeleteNetworkInstance.callRESTQueryAAICloudRegion(mockExecution) + + verify(mockExecution, atLeast(1)).setVariable("prefix", Prefix) + verify(mockExecution, atLeast(2)).setVariable(Prefix + "queryCloudRegionReturnCode", "200") + + } + + @Test + //@Ignore + public void callRESTQueryAAICloudRegion_NotFound() { + + println "************ callRESTQueryAAICloudRegion_NotFound ************* " + + WireMock.reset(); + MockGetNetworkCloudRegion_404("MDTWNJ21"); + + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("prefix")).thenReturn(Prefix) + when(mockExecution.getVariable(Prefix + "networkInputs")).thenReturn(vnfRequestCloudRegionNotFound) + when(mockExecution.getVariable(Prefix + "lcpCloudRegion")).thenReturn("MDTWNJ21") + when(mockExecution.getVariable("aai.endpoint")).thenReturn("http://localhost:8090") + // old: when(mockExecution.getVariable("mso.workflow.default.aai.cloud-infrastructure.cloud-region.uri")).thenReturn("/aai/v8/cloud-infrastructure/cloud-regions/cloud-region/att-aic") + when(mockExecution.getVariable("mso.workflow.global.default.aai.version")).thenReturn("8") + when(mockExecution.getVariable("mso.workflow.default.aai.v8.cloud-region.uri")).thenReturn("/aai/v8/cloud-infrastructure/cloud-regions/cloud-region/att-aic") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn('http://org.openecomp.aai.inventory/') + when(mockExecution.getVariable("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") + when(mockExecution.getVariable("aai.auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") + + // preProcessRequest(DelegateExecution execution) + DoDeleteNetworkInstance DoDeleteNetworkInstance = new DoDeleteNetworkInstance() + DoDeleteNetworkInstance.callRESTQueryAAICloudRegion(mockExecution) + + verify(mockExecution, atLeast(1)).setVariable("prefix", Prefix) + verify(mockExecution).setVariable(Prefix + "cloudRegionPo", "MDTWNJ21") + verify(mockExecution).setVariable(Prefix + "cloudRegionSdnc", "AAIAIC25") + + } + + @Test + //@Ignore + public void callRESTQueryAAICloudRegion25_200() { + + println "************ callRESTQueryAAICloudRegion25_200 ************* " + + WireMock.reset(); + MockGetNetworkCloudRegion("DeleteNetworkV2/cloudRegion25_AAIResponse_Success.xml", "RDM2WAGPLCP"); + + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("prefix")).thenReturn(Prefix) + when(mockExecution.getVariable(Prefix + "networkInputs")).thenReturn(expectedNetworkRequest) + when(mockExecution.getVariable(Prefix + "lcpCloudRegion")).thenReturn("RDM2WAGPLCP") + when(mockExecution.getVariable("aai.endpoint")).thenReturn("http://localhost:8090") + // old: when(mockExecution.getVariable("mso.workflow.default.aai.cloud-infrastructure.cloud-region.uri")).thenReturn("/aai/v8/cloud-infrastructure/cloud-regions/cloud-region/att-aic") + when(mockExecution.getVariable("mso.workflow.global.default.aai.version")).thenReturn("8") + when(mockExecution.getVariable("mso.workflow.default.aai.v8.cloud-region.uri")).thenReturn("/aai/v8/cloud-infrastructure/cloud-regions/cloud-region/att-aic") + // + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn('http://org.openecomp.aai.inventory/') + when(mockExecution.getVariable("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") + when(mockExecution.getVariable("aai.auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") + + // preProcessRequest(DelegateExecution execution) + DoDeleteNetworkInstance DoDeleteNetworkInstance = new DoDeleteNetworkInstance() + DoDeleteNetworkInstance.callRESTQueryAAICloudRegion(mockExecution) + + verify(mockExecution, atLeast(1)).setVariable("prefix", Prefix) + verify(mockExecution, atLeast(2)).setVariable(Prefix + "queryCloudRegionReturnCode", "200") + + } + + + @Test + //@Ignore + public void validateNetworkResponse() { + + println "************ validateNetworkResponse ************* " + + ExecutionEntity mockExecution = setupMock() + // Initialize prerequisite variables + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable(Prefix + "deleteNetworkResponse")).thenReturn(deleteNetworkResponse) + when(mockExecution.getVariable(Prefix + "networkReturnCode")).thenReturn('200') + + DoDeleteNetworkInstance DoDeleteNetworkInstance = new DoDeleteNetworkInstance() + DoDeleteNetworkInstance.validateNetworkResponse(mockExecution) + + verify(mockExecution).setVariable("prefix", Prefix) + //verify(mockExecution).setVariable(Prefix + "rollbackNetworkRequest", null) + + } + + + @Test + //@Ignore + public void validateSDNCResponse_200() { + + println "************ validateSDNCResponse ************* " + ExecutionEntity mockExecution = setupMock() + // Initialize prerequisite variables + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable(Prefix + "sdncReturnCode")).thenReturn("200") + when(mockExecution.getVariable("SDNCA_SuccessIndicator")).thenReturn(true) + + DoDeleteNetworkInstance DoDeleteNetworkInstance = new DoDeleteNetworkInstance() + try { + DoDeleteNetworkInstance.validateSDNCResponse(mockExecution, sdncAdapterWorkflowResponse) + } catch (Exception ex) { + println " Graceful Exit - " + ex.getMessage() + } + + } + + @Test + //@Ignore + public void validateSDNCResponse_404() { + + println "************ validateSDNCResponse ************* " + + WorkflowException workflowException = new WorkflowException("DoCreateNetworkInstance", 2500, "Received error from SNDC Adapter: HTTP Status 404.") + + ExecutionEntity mockExecution = setupMock() + // Initialize prerequisite variables + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable(Prefix + "sdncReturnCode")).thenReturn("404") + when(mockExecution.getVariable("SDNCA_SuccessIndicator")).thenReturn(false) + when(mockExecution.getVariable("WorkflowException")).thenReturn(workflowException) + + DoDeleteNetworkInstance DoDeleteNetworkInstance = new DoDeleteNetworkInstance() + try { + DoDeleteNetworkInstance.validateSDNCResponse(mockExecution) + } catch (Exception ex) { + println " Graceful Exit - " + ex.getMessage() + } + + } + + @Test + //@Ignore + public void validateRpcSDNCDeactivateResponse() { + + println "************ validateRpcSDNCDeactivateResponse ************* " + + ExecutionEntity mockExecution = setupMock() + // Initialize prerequisite variables + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable(Prefix + "deactivateSDNCResponse")).thenReturn(sdncAdapterWorkflowResponse) + when(mockExecution.getVariable("prefix")).thenReturn(Prefix + "") + when(mockExecution.getVariable("SDNCA_SuccessIndicator")).thenReturn(true) + when(mockExecution.getVariable(Prefix + "deactivateSDNCReturnCode")).thenReturn("200") + + DoDeleteNetworkInstance DoDeleteNetworkInstance = new DoDeleteNetworkInstance() + try { + DoDeleteNetworkInstance.validateRpcSDNCDeactivateResponse(mockExecution) + verify(mockExecution).setVariable(Prefix + "isSdncDeactivateRollbackNeeded", true) + + } catch (Exception ex) { + println " Graceful Exit - " + ex.getMessage() + } + //MockitoDebuggerImpl debugger = new MockitoDebuggerImpl() + //debugger.printInvocations(mockExecution) + + //verify(mockExecution).setVariable(Prefix + "isSdncRollbackNeeded", true) + + } + + @Test + @Ignore + public void postProcessResponse() { + + println "************ postProcessResponse ************* " + ExecutionEntity mockExecution = setupMock() + // Initialize prerequisite variables + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable(Prefix + "source")).thenReturn("PORTAL") + when(mockExecution.getVariable(Prefix + "isException")).thenReturn(false) + + // postProcessResponse(DelegateExecution execution) + DoDeleteNetworkInstance DoDeleteNetworkInstance = new DoDeleteNetworkInstance() + DoDeleteNetworkInstance.postProcessResponse(mockExecution) + + verify(mockExecution).setVariable("prefix", Prefix) + verify(mockExecution).setVariable(Prefix + "Success", true) + + } + + @Test + //@Ignore + public void prepareRollbackData() { + + println "************ prepareRollbackData() ************* " + + + + WorkflowException workflowException = new WorkflowException("DoCreateNetworkInstance", 2500, "Received error from Network Adapter: JBWEB000065: HTTP Status 500.") + + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + // Initialize prerequisite variables + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable(Prefix + "rollbackNetworkRequest")).thenReturn(deleteRollbackNetworkRequest) + //when(mockExecution.getVariable(Prefix + "rollbackNetworkRequest")).thenReturn(null) + //when(mockExecution.getVariable(Prefix + "rollbackNetworkRequest")).thenReturn("") + when(mockExecution.getVariable(Prefix + "rollbackDeactivateSDNCRequest")).thenReturn(sdncAdapaterDeactivateRollback) + when(mockExecution.getVariable("WorkflowException")).thenReturn(workflowException) + + // preProcessRequest(DelegateExecution execution) + DoDeleteNetworkInstance DoDeleteNetworkInstance = new DoDeleteNetworkInstance() + DoDeleteNetworkInstance.prepareRollbackData(mockExecution) + +// verify(mockExecution).getVariable("isDebugLogEnabled") + verify(mockExecution).setVariable("prefix", Prefix) + + } + + + private ExecutionEntity setupMock() { + + ProcessDefinition mockProcessDefinition = mock(ProcessDefinition.class) + when(mockProcessDefinition.getKey()).thenReturn("DoDeleteNetworkInstance") + RepositoryService mockRepositoryService = mock(RepositoryService.class) + when(mockRepositoryService.getProcessDefinition()).thenReturn(mockProcessDefinition) + when(mockRepositoryService.getProcessDefinition().getKey()).thenReturn("DoDeleteNetworkInstance") + when(mockRepositoryService.getProcessDefinition().getId()).thenReturn("100") + ProcessEngineServices mockProcessEngineServices = mock(ProcessEngineServices.class) + when(mockProcessEngineServices.getRepositoryService()).thenReturn(mockRepositoryService) + + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + // Initialize prerequisite variables + + when(mockExecution.getId()).thenReturn("100") + when(mockExecution.getProcessDefinitionId()).thenReturn("DoDeleteNetworkInstance") + when(mockExecution.getProcessInstanceId()).thenReturn("DoDeleteNetworkInstance") + when(mockExecution.getProcessEngineServices()).thenReturn(mockProcessEngineServices) + when(mockExecution.getProcessEngineServices().getRepositoryService().getProcessDefinition(mockExecution.getProcessDefinitionId())).thenReturn(mockProcessDefinition) + + return mockExecution + + } + +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteServiceInstanceTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteServiceInstanceTest.groovy new file mode 100644 index 0000000000..a8bdfb0633 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteServiceInstanceTest.groovy @@ -0,0 +1,127 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts + +import com.github.tomakehurst.wiremock.junit.WireMockRule +import org.camunda.bpm.engine.ProcessEngineServices +import org.camunda.bpm.engine.RepositoryService +import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity +import org.camunda.bpm.engine.repository.ProcessDefinition +import org.junit.Assert +import org.junit.Before +import org.junit.Ignore +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.ArgumentCaptor +import org.mockito.Captor +import org.mockito.Mockito +import org.mockito.MockitoAnnotations +import org.mockito.runners.MockitoJUnitRunner +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.bpmn.mock.FileUtil +import org.onap.so.bpmn.vcpe.scripts.GroovyTestBase + +import static com.github.tomakehurst.wiremock.client.WireMock.* +import static org.mockito.Mockito.* + +@RunWith(MockitoJUnitRunner.class) +class DoDeleteServiceInstanceTest { + + @Rule + public WireMockRule wireMockRule = new WireMockRule(28090) + + @Captor + static ArgumentCaptor<ExecutionEntity> captor = ArgumentCaptor.forClass(ExecutionEntity.class) + + @Before + void init() throws IOException { + MockitoAnnotations.initMocks(this); + } + + @Test + public void preProcessRequestTest() { + + ExecutionEntity mex = setupMock() + when(mex.getVariable(GroovyTestBase.DBGFLAG)).thenReturn("true") + when(mex.getVariable("serviceInstanceId")).thenReturn("e151059a-d924-4629-845f-264db19e50b4") + when(mex.getVariable("mso.workflow.sdncadapter.callback")).thenReturn("/mso/sdncadapter/") + when(mex.getVariable("globalSubscriberId")).thenReturn("4993921112123") + + DoDeleteServiceInstance instance = new DoDeleteServiceInstance() + instance.preProcessRequest(mex) + + Mockito.verify(mex).setVariable("sdncCallbackUrl", "/mso/sdncadapter/") + Mockito.verify(mex).setVariable("siParamsXml", "") + } + + + @Test + public void testPostProcessAAIGET() { + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn('true') + when(mockExecution.getVariable("aai.endpoint")).thenReturn('http://localhost:8090') + when(mockExecution.getVariable("GENGS_FoundIndicator")).thenReturn(true) + when(mockExecution.getVariable("sdnc.si.svc.types")).thenReturn("") + when(mockExecution.getVariable("globalSubscriberId")).thenReturn("globalSubscriberId_test") + when(mockExecution.getVariable("subscriptionServiceType")).thenReturn("subscriptionServiceType_test") + + String aaiGetResponse = FileUtil.readResourceFile("__files/GenericFlows/aaiGetResponse.xml") + when(mockExecution.getVariable("GENGS_service")).thenReturn(aaiGetResponse) + when(mockExecution.getVariable("GENGS_siResourceLink")).thenReturn("/aai/v8/business/customers/customer/MSO_1610_dev/service-subscriptions/service-subscription/MSO-dev-service-type/service-instances/service-instance/") + when(mockExecution.getVariable("mso.workflow.global.default.aai.version")).thenReturn('8') + when(mockExecution.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn('http://org.openecomp.aai.inventory/') + + mockData() + DoDeleteServiceInstance instance = new DoDeleteServiceInstance() + instance.postProcessAAIGET(mockExecution) + + Mockito.verify(mockExecution).setVariable("sendToSDNC", true) + } + + private static ExecutionEntity setupMock() { + ProcessDefinition mockProcessDefinition = mock(ProcessDefinition.class) + when(mockProcessDefinition.getKey()).thenReturn("DoDeleteServiceInstance") + RepositoryService mockRepositoryService = mock(RepositoryService.class) + when(mockRepositoryService.getProcessDefinition()).thenReturn(mockProcessDefinition) + when(mockRepositoryService.getProcessDefinition().getKey()).thenReturn("DoDeleteServiceInstance") + when(mockRepositoryService.getProcessDefinition().getId()).thenReturn("100") + ProcessEngineServices mockProcessEngineServices = mock(ProcessEngineServices.class) + when(mockProcessEngineServices.getRepositoryService()).thenReturn(mockRepositoryService) + + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + // Initialize prerequisite variables + when(mockExecution.getId()).thenReturn("100") + when(mockExecution.getProcessDefinitionId()).thenReturn("DoDeleteServiceInstance") + when(mockExecution.getProcessInstanceId()).thenReturn("DoDeleteServiceInstance") + when(mockExecution.getProcessEngineServices()).thenReturn(mockProcessEngineServices) + when(mockExecution.getProcessEngineServices().getRepositoryService().getProcessDefinition(mockExecution.getProcessDefinitionId())).thenReturn(mockProcessDefinition) + + return mockExecution + } + + private void mockData() { + stubFor(get(urlMatching(".*/aai/v[0-9]+/business/customers/customer/MSO_1610_dev/service-subscriptions/service-subscription/MSO-dev-service-type/service-instances/service-instance/.*")) + .willReturn(aResponse() + .withStatus(200).withHeader("Content-Type", "text/xml") + .withBodyFile(""))) + } +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVfModuleFromVnfTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVfModuleFromVnfTest.groovy new file mode 100644 index 0000000000..fcb0fb0940 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVfModuleFromVnfTest.groovy @@ -0,0 +1,172 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts + +import com.github.tomakehurst.wiremock.junit.WireMockRule +import org.camunda.bpm.engine.ProcessEngineServices +import org.camunda.bpm.engine.RepositoryService +import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity +import org.camunda.bpm.engine.repository.ProcessDefinition +import org.junit.Assert +import org.junit.Before +import org.junit.Ignore +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.ArgumentCaptor +import org.mockito.Captor +import org.mockito.Mockito +import org.mockito.MockitoAnnotations +import org.mockito.runners.MockitoJUnitRunner +import org.onap.so.bpmn.core.WorkflowException + +import static com.github.tomakehurst.wiremock.client.WireMock.* +import static org.mockito.Mockito.* + +@RunWith(MockitoJUnitRunner.class) +class DoDeleteVfModuleFromVnfTest { + + @Rule + public WireMockRule wireMockRule = new WireMockRule(28090); + + @Captor + static ArgumentCaptor<ExecutionEntity> captor = ArgumentCaptor.forClass(ExecutionEntity.class) + + @Before + public void init() throws IOException { + MockitoAnnotations.initMocks(this); + } + + @Test + public void testPreProcessRequest() { + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("msoRequestId")).thenReturn("12345") + when(mockExecution.getVariable("source")).thenReturn("VID") + when(mockExecution.getVariable("serviceInstanceId")).thenReturn("12345") + when(mockExecution.getVariable("vnfId")).thenReturn("12345") + when(mockExecution.getVariable("tenantId")).thenReturn("19123c2924c648eb8e42a3c1f14b7682") + when(mockExecution.getVariable("vfModuleId")).thenReturn("12345") + when(mockExecution.getVariable("lcpCloudRegionId")).thenReturn("12345") + when(mockExecution.getVariable("sdncVersion")).thenReturn("8") + when(mockExecution.getVariable("mso.workflow.sdncadapter.callback")).thenReturn("http://localhost:8090/SDNCAdapterCallback") + + DoDeleteVfModuleFromVnf obj = new DoDeleteVfModuleFromVnf() + obj.preProcessRequest(mockExecution) + + Mockito.verify(mockExecution).setVariable("prefix", "DDVFMV_") + Mockito.verify(mockExecution).setVariable("DDVFMV_contrailNetworkPolicyFqdnList", null) + Mockito.verify(mockExecution).setVariable("mso-request-id", "12345") + Mockito.verify(mockExecution).setVariable("requestId", "12345") + Mockito.verify(mockExecution).setVariable("cloudSiteId", "12345") + Mockito.verify(mockExecution).setVariable("source", "VID") + Mockito.verify(mockExecution).setVariable("isVidRequest", "true") + Mockito.verify(mockExecution).setVariable("srvInstId", "") + Mockito.verify(mockExecution).setVariable("DDVFMV_serviceInstanceIdToSdnc", "12345") + Mockito.verify(mockExecution).setVariable("DDVFMV_sdncVersion", "8") + Mockito.verify(mockExecution).setVariable("sdncCallbackUrl", "http://localhost:8090/SDNCAdapterCallback") + } + + + + @Test + void testDeleteNetworkPoliciesFromAAI() { + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("mso.workflow.DoDeleteVfModuleFromVnf.aai.network-policy.uri")).thenReturn("/aai/v8/network/network-policies/network-policy") + when(mockExecution.getVariable("mso.workflow.custom.DoDeleteVfModuleFromVnf.aai.version")).thenReturn("8") + when(mockExecution.getVariable("aai.endpoint")).thenReturn("http://localhost:28090") + when(mockExecution.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn("http://org.openecomp.aai.inventory/") + List fqdnList = new ArrayList() + fqdnList.add("test") + when(mockExecution.getVariable("DDVFMV_contrailNetworkPolicyFqdnList")).thenReturn(fqdnList) + mockData() + DoDeleteVfModuleFromVnf obj = new DoDeleteVfModuleFromVnf() + obj.deleteNetworkPoliciesFromAAI(mockExecution) + + Mockito.verify(mockExecution).setVariable("prefix", 'DDVFMV_') + Mockito.verify(mockExecution).setVariable("DCVFM_aaiQueryNetworkPolicyByFqdnReturnCode", 200) + } + + + @Test + void testQueryAAIForVfModule() { + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("vnfId")).thenReturn("12345") + when(mockExecution.getVariable("aai.endpoint")).thenReturn("http://localhost:28090") + when(mockExecution.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn("mso.workflow.global.default.aai.namespace") + when(mockExecution.getVariable("mso.workflow.default.aai.generic-vnf.version")).thenReturn("8") + when(mockExecution.getVariable("mso.workflow.default.aai.v8.generic-vnf.uri")).thenReturn("/aai/v8/network/generic-vnfs/generic-vnf") + when(mockExecution.getVariable("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") + when(mockExecution.getVariable("aai.auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") + + mockData() + DoDeleteVfModuleFromVnf obj = new DoDeleteVfModuleFromVnf() + obj.queryAAIForVfModule(mockExecution) + + Mockito.verify(mockExecution, atLeastOnce()).setVariable("DDVMFV_getVnfResponseCode", 200) + } + + + + private ExecutionEntity setupMock() { + + ProcessDefinition mockProcessDefinition = mock(ProcessDefinition.class) + when(mockProcessDefinition.getKey()).thenReturn("DoDeleteVfModuleFromVnf") + RepositoryService mockRepositoryService = mock(RepositoryService.class) + when(mockRepositoryService.getProcessDefinition()).thenReturn(mockProcessDefinition) + when(mockRepositoryService.getProcessDefinition().getKey()).thenReturn("DoDeleteVfModuleFromVnf") + when(mockRepositoryService.getProcessDefinition().getId()).thenReturn("100") + ProcessEngineServices mockProcessEngineServices = mock(ProcessEngineServices.class) + when(mockProcessEngineServices.getRepositoryService()).thenReturn(mockRepositoryService) + + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + // Initialize prerequisite variables + + when(mockExecution.getId()).thenReturn("100") + when(mockExecution.getProcessDefinitionId()).thenReturn("DoDeleteVfModuleFromVnf") + when(mockExecution.getProcessInstanceId()).thenReturn("DoDeleteVfModuleFromVnf") + when(mockExecution.getProcessEngineServices()).thenReturn(mockProcessEngineServices) + when(mockExecution.getProcessEngineServices().getRepositoryService().getProcessDefinition(mockExecution.getProcessDefinitionId())).thenReturn(mockProcessDefinition) + + return mockExecution + + } + + private static void mockData() { + stubFor(get(urlMatching(".*/aai/v[0-9]+/network/generic-vnfs/generic-vnf/12345[?]depth=1")) + .willReturn(aResponse() + .withStatus(200).withHeader("Content-Type", "text/xml") + .withBodyFile("VfModularity/GenerateVfModuleName_AAIResponse_Success.xml"))) + + stubFor(get(urlMatching("/aai/v[0-9]+/network/network-policies/network-policy\\?network-policy-fqdn=.*")) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBodyFile("VfModularity/QueryNetworkPolicy_AAIResponse_Success.xml"))) + + stubFor(delete(urlMatching("/aai/v[0-9]+/network/network-policies/network-policy/.*")) + .willReturn(aResponse() + .withStatus(200))); + + } +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVfModuleTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVfModuleTest.groovy new file mode 100644 index 0000000000..3390b1a6f0 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVfModuleTest.groovy @@ -0,0 +1,163 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts + +import com.github.tomakehurst.wiremock.junit.WireMockRule +import org.camunda.bpm.engine.ProcessEngineServices +import org.camunda.bpm.engine.RepositoryService +import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity +import org.camunda.bpm.engine.repository.ProcessDefinition +import org.junit.Assert +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.ArgumentCaptor +import org.mockito.Captor +import org.mockito.Mockito +import org.mockito.MockitoAnnotations +import org.mockito.runners.MockitoJUnitRunner +import org.onap.so.bpmn.common.scripts.utils.XmlComparator +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.bpmn.mock.FileUtil + +import static com.github.tomakehurst.wiremock.client.WireMock.* +import static org.mockito.Mockito.* + +@RunWith(MockitoJUnitRunner.class) +class DoDeleteVfModuleTest { + + @Rule + public WireMockRule wireMockRule = new WireMockRule(28090); + + @Captor + static ArgumentCaptor<ExecutionEntity> captor = ArgumentCaptor.forClass(ExecutionEntity.class) + + @Before + public void init() throws IOException { + MockitoAnnotations.initMocks(this); + } + + @Test + public void testPrepSDNCAdapterRequest() { + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("testReqId")).thenReturn("testReqId") + when(mockExecution.getVariable("requestId")).thenReturn("12345") + when(mockExecution.getVariable("source")).thenReturn("VID") + when(mockExecution.getVariable("serviceId")).thenReturn("12345") + when(mockExecution.getVariable("vnfId")).thenReturn("12345") + when(mockExecution.getVariable("tenantId")).thenReturn("19123c2924c648eb8e42a3c1f14b7682") + when(mockExecution.getVariable("vfModuleId")).thenReturn("12345") + when(mockExecution.getVariable("DoDVfMod_serviceInstanceIdToSdnc")).thenReturn("123456789") + when(mockExecution.getVariable("vfModuleName")).thenReturn("vfModuleName_test") + when(mockExecution.getVariable("mso.workflow.sdncadapter.callback")).thenReturn("http://localhost:8090/SDNCAdapterCallback") + + DoDeleteVfModule obj = new DoDeleteVfModule() + obj.prepSDNCAdapterRequest(mockExecution, 'release') + + String expectedValue = FileUtil.readResourceFile("__files/DoDeleteVfModule/sdncAdapterWorkflowRequest.xml") + Mockito.verify(mockExecution, times(1)).setVariable(captor.capture(), captor.capture()) + XmlComparator.assertXMLEquals(expectedValue, captor.getValue()) + } + + + @Test + void testDeleteNetworkPoliciesFromAAI() { + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("mso.workflow.DoDeleteVfModule.aai.network-policy.uri")).thenReturn("/aai/v8/network/network-policies/network-policy") + when(mockExecution.getVariable("mso.workflow.custom.DoDeleteVfModule.aai.version")).thenReturn("8") + when(mockExecution.getVariable("aai.endpoint")).thenReturn("http://localhost:28090") + when(mockExecution.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn("http://org.openecomp.aai.inventory/") + List fqdnList = new ArrayList() + fqdnList.add("test") + when(mockExecution.getVariable("DoDVfMod_contrailNetworkPolicyFqdnList")).thenReturn(fqdnList) + mockData() + DoDeleteVfModule obj = new DoDeleteVfModule() + obj.deleteNetworkPoliciesFromAAI(mockExecution) + + Mockito.verify(mockExecution).setVariable("DCVFM_aaiQueryNetworkPolicyByFqdnReturnCode", 200) + } + + + @Test + void testQueryAAIVfModuleForStatus() { + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("DCVFM_vnfId")).thenReturn("12345") + when(mockExecution.getVariable("DCVFM_vfModuleName")).thenReturn("module-0") + when(mockExecution.getVariable("mso.workflow.DoDeleteVfModule.aai.generic-vnf.uri")).thenReturn("/aai/v9/network/generic-vnfs/generic-vnf") + when(mockExecution.getVariable("aai.endpoint")).thenReturn("http://localhost:28090") + when(mockExecution.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn("http://org.openecomp.aai.inventory/") + + mockData() + DoCreateVfModule obj = new DoCreateVfModule() + obj.queryAAIVfModuleForStatus(mockExecution) + + Mockito.verify(mockExecution).setVariable("DCVFM_queryAAIVfModuleForStatusResponseCode", 200) + } + + + + private ExecutionEntity setupMock() { + + ProcessDefinition mockProcessDefinition = mock(ProcessDefinition.class) + when(mockProcessDefinition.getKey()).thenReturn("DoDeleteVfModule") + RepositoryService mockRepositoryService = mock(RepositoryService.class) + when(mockRepositoryService.getProcessDefinition()).thenReturn(mockProcessDefinition) + when(mockRepositoryService.getProcessDefinition().getKey()).thenReturn("DoDeleteVfModule") + when(mockRepositoryService.getProcessDefinition().getId()).thenReturn("100") + ProcessEngineServices mockProcessEngineServices = mock(ProcessEngineServices.class) + when(mockProcessEngineServices.getRepositoryService()).thenReturn(mockRepositoryService) + + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + // Initialize prerequisite variables + + when(mockExecution.getId()).thenReturn("100") + when(mockExecution.getProcessDefinitionId()).thenReturn("DoDeleteVfModule") + when(mockExecution.getProcessInstanceId()).thenReturn("DoDeleteVfModule") + when(mockExecution.getProcessEngineServices()).thenReturn(mockProcessEngineServices) + when(mockExecution.getProcessEngineServices().getRepositoryService().getProcessDefinition(mockExecution.getProcessDefinitionId())).thenReturn(mockProcessDefinition) + + return mockExecution + + } + + private static void mockData() { + stubFor(get(urlMatching("/aai/v[0-9]+/network/network-policies/network-policy\\?network-policy-fqdn=.*")) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBodyFile("VfModularity/QueryNetworkPolicy_AAIResponse_Success.xml"))) + + stubFor(delete(urlMatching("/aai/v[0-9]+/network/network-policies/network-policy/.*")) + .willReturn(aResponse() + .withStatus(200))) + + stubFor(get(urlMatching(".*/aai/v[0-9]+/network/generic-vnfs/generic-vnf/12345/vf-modules/vf-module[?]vf-module-name=module-0")) + .willReturn(aResponse() + .withStatus(200).withHeader("Content-Type", "text/xml") + .withBodyFile("DoDeleteVfModule/getGenericVnfResponse.xml"))) + + } +} + diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVfModuleVolumeV2Test.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVfModuleVolumeV2Test.groovy new file mode 100644 index 0000000000..730be14df0 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVfModuleVolumeV2Test.groovy @@ -0,0 +1,152 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts + +import com.github.tomakehurst.wiremock.junit.WireMockRule +import org.camunda.bpm.engine.ProcessEngineServices +import org.camunda.bpm.engine.RepositoryService +import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity +import org.camunda.bpm.engine.repository.ProcessDefinition +import org.junit.Assert +import org.junit.Before +import org.junit.Ignore +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.ArgumentCaptor +import org.mockito.Captor +import org.mockito.Mockito +import org.mockito.MockitoAnnotations +import org.mockito.runners.MockitoJUnitRunner +import org.onap.so.bpmn.common.scripts.utils.XmlComparator +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.bpmn.mock.FileUtil + +import static com.github.tomakehurst.wiremock.client.WireMock.* +import static org.mockito.Mockito.* + +@RunWith(MockitoJUnitRunner.class) +class DoDeleteVfModuleVolumeV2Test { + @Rule + public WireMockRule wireMockRule = new WireMockRule(28090); + + @Captor + static ArgumentCaptor<ExecutionEntity> captor = ArgumentCaptor.forClass(ExecutionEntity.class) + + @Before + public void init() throws IOException { + MockitoAnnotations.initMocks(this); + } + + @Test + public void testCallRESTQueryAAICloudRegion() { + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("prefix")).thenReturn("DDVMV_") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("lcpCloudRegionId")).thenReturn("12345") + when(mockExecution.getVariable("mso.workflow.DoDeleteVfModuleVolumeV2.aai.cloud-region.uri")).thenReturn("/aai/v8/cloud-infrastructure/cloud-regions/cloud-region") + when(mockExecution.getVariable("aai.endpoint")).thenReturn("http://localhost:28090") + when(mockExecution.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn("http://org.openecomp.aai.inventory/") + + mockData() + DoDeleteVfModuleVolumeV2 obj = new DoDeleteVfModuleVolumeV2() + obj.callRESTQueryAAICloudRegion(mockExecution, "true") + Mockito.verify(mockExecution).setVariable("DDVMV_queryCloudRegionReturnCode", "200") + Mockito.verify(mockExecution).setVariable("DDVMV_aicCloudRegion", "RDM2WAGPLCP") + } + + @Test + public void testCallRESTQueryAAICloudRegionAAiEndpointNull() { + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("prefix")).thenReturn("DDVMV_") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("lcpCloudRegionId")).thenReturn("12345") + when(mockExecution.getVariable("mso.workflow.DoDeleteVfModuleVolumeV2.aai.cloud-region.uri")).thenReturn("/aai/v8/cloud-infrastructure/cloud-regions/cloud-region") + when(mockExecution.getVariable("aai.endpoint")).thenReturn(null) + when(mockExecution.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn("http://org.openecomp.aai.inventory/") + + mockData() + try { + DoDeleteVfModuleVolumeV2 obj = new DoDeleteVfModuleVolumeV2() + obj.callRESTQueryAAICloudRegion(mockExecution, "true") + + } catch (Exception ex) { + println " Test End - Handle catch-throw BpmnError()! " + } + Mockito.verify(mockExecution,atLeastOnce()).setVariable(captor.capture(),captor.capture()) + WorkflowException workflowException = captor.getValue() + Assert.assertEquals(9999, workflowException.getErrorCode()) + } + + @Test + public void testPrepareVnfAdapterDeleteRequest() { + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("prefix")).thenReturn("DDVMV_") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("aicCloudRegion")).thenReturn("RegionOne") + when(mockExecution.getVariable("tenantId")).thenReturn("12345") + when(mockExecution.getVariable("volumeGroupId")).thenReturn("12345") + when(mockExecution.getVariable("volumeGroupHeatStackId")).thenReturn("12345") + when(mockExecution.getVariable("serviceInstanceId")).thenReturn("12345") + when(mockExecution.getVariable("msoRequestId")).thenReturn("12345") + when(mockExecution.getVariable("mso.use.qualified.host")).thenReturn("true") + when(mockExecution.getVariable("mso.workflow.message.endpoint")).thenReturn("http://localhost:18080/mso/WorkflowMessage") + + DoDeleteVfModuleVolumeV2 obj = new DoDeleteVfModuleVolumeV2() + obj.prepareVnfAdapterDeleteRequest(mockExecution, "true") + + Mockito.verify(mockExecution, times(1)).setVariable(captor.capture(), captor.capture()) + String str = FileUtil.readResourceFile("__files/DoCreateVfModuleVolumeV2/vnfAdapterDeleteRequest.xml") + XmlComparator.assertXMLEquals(str, captor.getValue(),"messageId","notificationUrl") + } + + + private ExecutionEntity setupMock() { + + ProcessDefinition mockProcessDefinition = mock(ProcessDefinition.class) + when(mockProcessDefinition.getKey()).thenReturn("DoDeleteVfModuleVolumeV2") + RepositoryService mockRepositoryService = mock(RepositoryService.class) + when(mockRepositoryService.getProcessDefinition()).thenReturn(mockProcessDefinition) + when(mockRepositoryService.getProcessDefinition().getKey()).thenReturn("DoDeleteVfModuleVolumeV2") + when(mockRepositoryService.getProcessDefinition().getId()).thenReturn("100") + ProcessEngineServices mockProcessEngineServices = mock(ProcessEngineServices.class) + when(mockProcessEngineServices.getRepositoryService()).thenReturn(mockRepositoryService) + + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + // Initialize prerequisite variables + + when(mockExecution.getId()).thenReturn("100") + when(mockExecution.getProcessDefinitionId()).thenReturn("DoDeleteVfModuleVolumeV2") + when(mockExecution.getProcessInstanceId()).thenReturn("DoDeleteVfModuleVolumeV2") + when(mockExecution.getProcessEngineServices()).thenReturn(mockProcessEngineServices) + when(mockExecution.getProcessEngineServices().getRepositoryService().getProcessDefinition(mockExecution.getProcessDefinitionId())).thenReturn(mockProcessDefinition) + + return mockExecution + + } + + private void mockData() { + stubFor(get(urlMatching(".*/aai/v[0-9]+/cloud-infrastructure/cloud-regions/cloud-region/12345")) + .willReturn(aResponse() + .withStatus(200).withHeader("Content-Type", "text/xml") + .withBodyFile("DoCreateVfModuleVolumeV2/cloudRegion_AAIResponse_Success.xml"))) + } +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVnfAndModulesTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVnfAndModulesTest.groovy new file mode 100644 index 0000000000..0b95ffc053 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVnfAndModulesTest.groovy @@ -0,0 +1,162 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts + +import com.github.tomakehurst.wiremock.junit.WireMockRule +import org.camunda.bpm.engine.ProcessEngineServices +import org.camunda.bpm.engine.RepositoryService +import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity +import org.camunda.bpm.engine.repository.ProcessDefinition +import org.junit.Assert +import org.junit.Before +import org.junit.Ignore +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.ArgumentCaptor +import org.mockito.Captor +import org.mockito.Mockito +import org.mockito.MockitoAnnotations +import org.mockito.runners.MockitoJUnitRunner +import org.onap.so.bpmn.core.WorkflowException + +import static com.github.tomakehurst.wiremock.client.WireMock.* +import static org.mockito.Mockito.* + +@RunWith(MockitoJUnitRunner.class) +public class DoDeleteVnfAndModulesTest { + + @Rule + public WireMockRule wireMockRule = new WireMockRule(28090); + + @Captor + static ArgumentCaptor<ExecutionEntity> captor = ArgumentCaptor.forClass(ExecutionEntity.class) + + String cloudConfiguration = "{ " + + "\"lcpCloudRegionId\": \"mdt1\"," + + "\"tenantId\": \"88a6ca3ee0394ade9403f075db23167e\"" + "}"; + + @Before + public void init() throws IOException { + MockitoAnnotations.initMocks(this); + } + + @Test + public void testPreProcessRequestTest() { + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("cloudConfiguration")).thenReturn(cloudConfiguration) + when(mockExecution.getVariable("msoRequestId")).thenReturn("12345") + when(mockExecution.getVariable("serviceInstanceId")).thenReturn("serviceInstanceId") + when(mockExecution.getVariable("sdncVersion")).thenReturn("1702") + when(mockExecution.getVariable("productFamilyId")).thenReturn("productFamilyId") + when(mockExecution.getVariable("lcpCloudRegionId")).thenReturn("mdt1") + when(mockExecution.getVariable("tenantId")).thenReturn("19123c2924c648eb8e42a3c1f14b7682") + when(mockExecution.getVariable("globalSubscriberId")).thenReturn("MSO_test") + when(mockExecution.getVariable("mso.workflow.sdncadapter.callback")).thenReturn("http://localhost:8090/SDNCAdapterCallback") + + DoDeleteVnfAndModules obj = new DoDeleteVnfAndModules() + obj.preProcessRequest(mockExecution) + + Mockito.verify(mockExecution).setVariable("prefix", "DDVAM_") + Mockito.verify(mockExecution).setVariable("requestId", "12345") + Mockito.verify(mockExecution).setVariable("mso-request-id", "12345") + Mockito.verify(mockExecution).setVariable("DDVAM_source", "VID") + Mockito.verify(mockExecution).setVariable("DDVAM_isVidRequest", "true") + Mockito.verify(mockExecution).setVariable("DDVAM_sdncVersion", "1702") + Mockito.verify(mockExecution).setVariable("DDVAM_isVidRequest", "true") + Mockito.verify(mockExecution).setVariable("sdncCallbackUrl", "http://localhost:8090/SDNCAdapterCallback") + } + + + + @Test + public void testQueryAAIVfModuleNullEndPoint() { + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("vnfId")).thenReturn("12345") + when(mockExecution.getVariable("mso.workflow.DoDeleteVnfAndModules.aai.generic-vnf.uri")).thenReturn("/aai/v8/network/generic-vnfs/generic-vnf") + when(mockExecution.getVariable("aai.endpoint")).thenReturn(null) + when(mockExecution.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn("http://org.openecomp.aai.inventory/") + + mockData() + try { + DoDeleteVnfAndModules obj = new DoDeleteVnfAndModules() + obj.queryAAIVfModule(mockExecution) + } catch (Exception ex) { + println " Test End - Handle catch-throw BpmnError()! " + } + + Mockito.verify(mockExecution,atLeastOnce()).setVariable(captor.capture(),captor.capture()) + WorkflowException workflowException = captor.getValue() + Assert.assertEquals("AAI GET Failed:null", workflowException.getErrorMessage()) + Assert.assertEquals(1002, workflowException.getErrorCode()) + } + + @Test + public void testQueryAAIVfModule() { + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("vnfId")).thenReturn("12345") + when(mockExecution.getVariable("mso.workflow.DoDeleteVnfAndModules.aai.generic-vnf.uri")).thenReturn("/aai/v8/network/generic-vnfs/generic-vnf") + when(mockExecution.getVariable("aai.endpoint")).thenReturn("http://localhost:28090") + when(mockExecution.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn("http://org.openecomp.aai.inventory/") + + mockData() + DoDeleteVnfAndModules obj = new DoDeleteVnfAndModules() + obj.queryAAIVfModule(mockExecution) + + Mockito.verify(mockExecution).setVariable("DCVFM_queryAAIVfModuleResponseCode", 200) + } + + private ExecutionEntity setupMock() { + + ProcessDefinition mockProcessDefinition = mock(ProcessDefinition.class) + when(mockProcessDefinition.getKey()).thenReturn("DoDeleteVnfAndModules") + RepositoryService mockRepositoryService = mock(RepositoryService.class) + when(mockRepositoryService.getProcessDefinition()).thenReturn(mockProcessDefinition) + when(mockRepositoryService.getProcessDefinition().getKey()).thenReturn("DoDeleteVnfAndModules") + when(mockRepositoryService.getProcessDefinition().getId()).thenReturn("100") + ProcessEngineServices mockProcessEngineServices = mock(ProcessEngineServices.class) + when(mockProcessEngineServices.getRepositoryService()).thenReturn(mockRepositoryService) + + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + // Initialize prerequisite variables + + when(mockExecution.getId()).thenReturn("100") + when(mockExecution.getProcessDefinitionId()).thenReturn("DoDeleteVnfAndModules") + when(mockExecution.getProcessInstanceId()).thenReturn("DoDeleteVnfAndModules") + when(mockExecution.getProcessEngineServices()).thenReturn(mockProcessEngineServices) + when(mockExecution.getProcessEngineServices().getRepositoryService().getProcessDefinition(mockExecution.getProcessDefinitionId())).thenReturn(mockProcessDefinition) + + return mockExecution + + } + + private void mockData() { + + stubFor(get(urlMatching("/aai/v[0-9]+/network/generic-vnfs/generic-vnf/12345[?]depth=1")) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBodyFile("GenericFlows/getGenericVnfResponse_hasRelationships.xml"))); + } +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoScaleE2EServiceInstanceTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoScaleE2EServiceInstanceTest.groovy new file mode 100644 index 0000000000..4e993525f9 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoScaleE2EServiceInstanceTest.groovy @@ -0,0 +1,110 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2018 CMCC All rights reserved. * + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.so.bpmn.infrastructure.scripts + +import com.github.tomakehurst.wiremock.junit.WireMockRule +import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity +import org.junit.Before +import org.junit.BeforeClass +import org.junit.Rule +import org.junit.Test +import org.mockito.MockitoAnnotations +import org.onap.so.bpmn.mock.FileUtil +import org.onap.so.bpmn.vcpe.scripts.GroovyTestBase + +import static org.mockito.Mockito.verify +import static org.mockito.Mockito.when + +class DoScaleE2EServiceInstanceTest extends GroovyTestBase { + + private static String request + + @Rule + public WireMockRule wireMockRule = new WireMockRule(GroovyTestBase.PORT) + + String Prefix = "CVRCS_" + + @BeforeClass + public static void setUpBeforeClass() { + request = FileUtil.readResourceFile("__files/InfrastructureFlows/DoScaleE2EServiceInstance.json") + } + + @Before + public void init() + { + MockitoAnnotations.initMocks(this) + } + public DoScaleE2EServiceInstanceTest(){ + super("DoScaleE2EServiceInstance") + } + + @Test + public void preProcessRequestTest(){ + + ExecutionEntity mex = setupMock() + def map = setupMap(mex) + initPreProcess(mex) + + DoScaleE2EServiceInstance instance = new DoScaleE2EServiceInstance() + instance.preProcessRequest(mex) + verify(mex).setVariable("resourceTemplateUUIDs", "ns111:ns333:") + } + + @Test + public void preInitResourcesOperStatusTest(){ + ExecutionEntity mex = setupMock() + def map = setupMap(mex) + initPreProcess(mex) + DoScaleE2EServiceInstance instance = new DoScaleE2EServiceInstance() + instance.preInitResourcesOperStatus(mex) + + verify(mex).setVariable("serviceInstanceId","e151059a-d924-4629-845f-264db19e50b4") + verify(mex).setVariable("operationId", "59960003992") + verify(mex).setVariable("operationType", "SCALE") + verify(mex).setVariable("URN_mso_openecomp_adapters_db_endpoint","http://mso.mso.testlab.openecomp.org:8080/dbadapters/RequestsDbAdapter") + + String payload = + """<soapenv:Envelope xmlns:ns="http://org.onap.so/requestsdb" + xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"> + <soapenv:Header/> + <soapenv:Body> + <ns:initResourceOperationStatus> + <serviceId>e151059a-d924-4629-845f-264db19e50b4</serviceId> + <operationId>59960003992</operationId> + <operationType>SCALE</operationType> + <resourceTemplateUUIDs>ns111:ns333:</resourceTemplateUUIDs> + </ns:initResourceOperationStatus> + </soapenv:Body> +</soapenv:Envelope>""" + verify(mex).setVariable("CVFMI_initResOperStatusRequest", payload) + } + + private void initPreProcess(ExecutionEntity mex) { + when(mex.getVariable(GroovyTestBase.DBGFLAG)).thenReturn("true") + when(mex.getVariable("bpmnRequest")).thenReturn(request) + when(mex.getVariable("msoRequestId")).thenReturn("mri") + when(mex.getVariable("serviceType")).thenReturn("VoLTE") + when(mex.getVariable("serviceInstanceId")).thenReturn("e151059a-d924-4629-845f-264db19e50b4") + when(mex.getVariable("serviceInstanceName")).thenReturn("ra") + when(mex.getVariable("operationId")).thenReturn("59960003992") + when(mex.getVariable("globalSubscriberId")).thenReturn("4993921112123") + when(mex.getVariable("resourceTemplateUUIDs")).thenReturn("ns111:ns333:") + } +}
\ No newline at end of file diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateNetworkInstanceRollbackTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateNetworkInstanceRollbackTest.groovy new file mode 100644 index 0000000000..0189d065df --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateNetworkInstanceRollbackTest.groovy @@ -0,0 +1,332 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts + +import static org.mockito.Mockito.* + +import org.camunda.bpm.engine.delegate.BpmnError +import org.camunda.bpm.engine.ProcessEngineServices +import org.camunda.bpm.engine.RepositoryService +import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity +import org.camunda.bpm.engine.repository.ProcessDefinition +import org.camunda.bpm.engine.delegate.DelegateExecution; +import org.mockito.MockitoAnnotations +import org.mockito.runners.MockitoJUnitRunner +import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.so.bpmn.core.WorkflowException +import org.junit.Before +import org.junit.Rule; +import org.junit.Test +import org.junit.Ignore +import org.junit.runner.RunWith + +import static org.junit.Assert.*; + +import com.github.tomakehurst.wiremock.client.WireMock; +import com.github.tomakehurst.wiremock.junit.WireMockRule; + +import java.util.HashMap; +import java.util.Map; +import java.util.UUID; +import org.apache.commons.lang3.* + + +@RunWith(MockitoJUnitRunner.class) +class DoUpdateNetworkInstanceRollbackTest { + + @Rule + public WireMockRule wireMockRule = new WireMockRule(28090); + + def utils = new MsoUtils() + String Prefix="UPDNETIR_" + + + String rollbackNetworkRequest = + """<NetworkAdapter:rollbackNetwork xmlns:NetworkAdapter="http://org.onap.so/network"> + <rollback> + <networkId>MNS-25180-L-01-dmz_direct_net_1/2c88a3a9-69b9-43a7-ada6-1aca577c3641</networkId> + <neutronNetworkId>c4f4e878-cde0-4b15-ae9a-bda857759cea</neutronNetworkId> + <networkStackId/> + <networkType>CONTRAIL_EXTERNAL</networkType> + <networkCreated>true</networkCreated> + <tenantId>7dd5365547234ee8937416c65507d266</tenantId> + <cloudSiteId>RDM2WAGPLCP</cloudSiteId> + <msoRequest> + <requestId>1ef47428-cade-45bd-a103-0751e8b2deb0</requestId> + <serviceInstanceId/> + </msoRequest> + </rollback> +</NetworkAdapter:rollbackNetwork>""" + + String rollbackActivateSDNCRequest = + """<aetgt:SDNCAdapterWorkflowRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:ns5="http://org.onap/so/request/types/v1" + xmlns:sdncadapter="http://org.onap.so/workflow/sdnc/adapter/schema/v1"> + <sdncadapter:RequestHeader> + <sdncadapter:RequestId>88f65519-9a38-4c4b-8445-9eb4a5a5af56</sdncadapter:RequestId> + <sdncadapter:SvcInstanceId>f70e927b-6087-4974-9ef8-c5e4d5847ca4</sdncadapter:SvcInstanceId> + <sdncadapter:SvcAction>rollback</sdncadapter:SvcAction> + <sdncadapter:SvcOperation>network-topology-operation</sdncadapter:SvcOperation> + <sdncadapter:CallbackUrl>sdncCallback</sdncadapter:CallbackUrl> + <sdncadapter:MsoAction>generic-resource</sdncadapter:MsoAction> + </sdncadapter:RequestHeader> + <aetgt:SDNCRequestData> + <request-information> + <request-id>88f65519-9a38-4c4b-8445-9eb4a5a5af56</request-id> + <request-action>CreateNetworkInstance</request-action> + <source>VID</source> + <notification-url/> + <order-number/> + <order-version/> + </request-information> + <service-information> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <service-type>MSO-dev-service-type</service-type> + <service-instance-id>f70e927b-6087-4974-9ef8-c5e4d5847ca4</service-instance-id> + <subscriber-name>MSO_1610_dev</subscriber-name> + </service-information> + <network-information> + <network-id>8abc633a-810b-4ca5-8b3a-09511d13a2ce</network-id> + <network-type>CONTRAIL_EXTERNAL</network-type> + <onap-model-information> + <model-invariant-uuid>invariant-uuid</model-invariant-uuid> + <model-customization-uuid>customization-uuid</model-customization-uuid> + <model-uuid>uuid</model-uuid> + <model-version>version</model-version> + <model-name>CONTRAIL_EXTERNAL</model-name> + </onap-model-information> + </network-information> + <network-request-information> + <network-id>8abc633a-810b-4ca5-8b3a-09511d13a2ce</network-id> + <network-type>CONTRAIL_EXTERNAL</network-type> + <network-name>MNS-25180-L-01-dmz_direct_net_1</network-name> + <tenant>7dd5365547234ee8937416c65507d266</tenant> + <aic-cloud-region>RDM2WAGPLCP</aic-cloud-region> + </network-request-information> + </aetgt:SDNCRequestData> +</aetgt:SDNCAdapterWorkflowRequest>""" + + String rollbackSDNCRequest = + """<aetgt:SDNCAdapterWorkflowRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:ns5="http://org.onap/so/request/types/v1" + xmlns:sdncadapter="http://org.onap.so/workflow/sdnc/adapter/schema/v1"> + <sdncadapter:RequestHeader> + <sdncadapter:RequestId>88f65519-9a38-4c4b-8445-9eb4a5a5af56</sdncadapter:RequestId> + <sdncadapter:SvcInstanceId>f70e927b-6087-4974-9ef8-c5e4d5847ca4</sdncadapter:SvcInstanceId> + <sdncadapter:SvcAction>rollback</sdncadapter:SvcAction> + <sdncadapter:SvcOperation>network-topology-operation</sdncadapter:SvcOperation> + <sdncadapter:CallbackUrl>sdncCallback</sdncadapter:CallbackUrl> + <sdncadapter:MsoAction>generic-resource</sdncadapter:MsoAction> + </sdncadapter:RequestHeader> + <aetgt:SDNCRequestData> + <request-information> + <request-id>88f65519-9a38-4c4b-8445-9eb4a5a5af56</request-id> + <request-action>CreateNetworkInstance</request-action> + <source>VID</source> + <notification-url/> + <order-number/> + <order-version/> + </request-information> + <service-information> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <service-type>MSO-dev-service-type</service-type> + <service-instance-id>f70e927b-6087-4974-9ef8-c5e4d5847ca4</service-instance-id> + <subscriber-name>MSO_1610_dev</subscriber-name> + </service-information> + <network-information> + <network-id>8abc633a-810b-4ca5-8b3a-09511d13a2ce</network-id> + <network-type>CONTRAIL_EXTERNAL</network-type> + <onap-model-information> + <model-invariant-uuid>invariant-uuid</model-invariant-uuid> + <model-customization-uuid>customization-uuid</model-customization-uuid> + <model-uuid>uuid</model-uuid> + <model-version>version</model-version> + <model-name>CONTRAIL_EXTERNAL</model-name> + </onap-model-information> + </network-information> + <network-request-information> + <network-id>8abc633a-810b-4ca5-8b3a-09511d13a2ce</network-id> + <network-type>CONTRAIL_EXTERNAL</network-type> + <network-name>MNS-25180-L-01-dmz_direct_net_1</network-name> + <tenant>7dd5365547234ee8937416c65507d266</tenant> + <aic-cloud-region>RDM2WAGPLCP</aic-cloud-region> + </network-request-information> + </aetgt:SDNCRequestData> +</aetgt:SDNCAdapterWorkflowRequest>""" + +// - - - - - - - - + + + @Before + public void init() + { + MockitoAnnotations.initMocks(this) + } + + public void initializeVariables (DelegateExecution mockExecution) { + + verify(mockExecution).setVariable(Prefix + "rollbackNetworkRequest", null) + verify(mockExecution).setVariable(Prefix + "rollbackSDNCRequest", null) + verify(mockExecution).setVariable(Prefix + "WorkflowException", null) + + verify(mockExecution).setVariable(Prefix + "rollbackNetworkRequest", "") + verify(mockExecution).setVariable(Prefix + "rollbackNetworkResponse", "") + verify(mockExecution).setVariable(Prefix + "rollbackNetworkReturnCode", "") + + verify(mockExecution).setVariable(Prefix + "rollbackSDNCRequest", "") + verify(mockExecution).setVariable(Prefix + "rollbackSDNCResponse", "") + verify(mockExecution).setVariable(Prefix + "rollbackSDNCReturnCode", "") + + verify(mockExecution).setVariable(Prefix + "Success", false) + verify(mockExecution).setVariable(Prefix + "fullRollback", false) + + + } + + @Test + //@Ignore + public void preProcessRequest() { + + println "************ preProcessRequest ************* " + + WorkflowException workflowException = new WorkflowException("DoUpdateNetworkInstanceRollback", 2500, "Received error from Network Adapter: JBWEB000065: HTTP Status 500.") + Map<String, String> rollbackData = new HashMap<String, String>(); + rollbackData.put("rollbackSDNCRequest", rollbackSDNCRequest) + rollbackData.put("rollbackNetworkRequest", rollbackNetworkRequest) + + ExecutionEntity mockExecution = setupMock() + // Initialize prerequisite variables + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("prefix")).thenReturn(Prefix + "") + when(mockExecution.getVariable("WorkflowException")).thenReturn(workflowException) + when(mockExecution.getVariable("rollbackData")).thenReturn(rollbackData) + when(mockExecution.getVariable("sdncVersion")).thenReturn("1610") + when(mockExecution.getVariable("mso.adapters.po.auth")).thenReturn("3141634BF7E070AA289CF2892C986C0B") + when(mockExecution.getVariable("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") + + when(mockExecution.getVariable("mso.adapters.sdnc.endpoint")).thenReturn("http://localhost:28090/SDNCAdapter") + when(mockExecution.getVariable("mso.adapters.network.rest.endpoint")).thenReturn("http://localhost:28090/networks/NetworkAdapter") + when(mockExecution.getVariable("mso.adapters.sdnc.resource.endpoint")).thenReturn("http://localhost:28090/SDNCAdapterRpc") + + + // preProcessRequest(DelegateExecution execution) + DoUpdateNetworkInstanceRollback DoUpdateNetworkInstanceRollback = new DoUpdateNetworkInstanceRollback() + DoUpdateNetworkInstanceRollback.preProcessRequest(mockExecution) + +// verify(mockExecution).getVariable("isDebugLogEnabled") + verify(mockExecution).setVariable("prefix", Prefix) + + //verify variable initialization + initializeVariables(mockExecution) + + } + + + @Test + @Ignore + public void validateRollbackResponses_Good() { + + WorkflowException workflowException = new WorkflowException("DoUpdateNetworkInstanceRollback", 2500, "AAI Update Contrail Failed. Error 404.") + WorkflowException expectedWorkflowException = new WorkflowException("DoUpdateNetworkInstanceRollback", 2500, "AAI Update Contrail Failed. Error 404. + SNDC activate rollback completed. + PO Network rollback completed. + SNDC assign rollback completed.") + + println "************ validateRollbackResponses_Good() ************* " + ExecutionEntity mockExecution = setupMock() + // Initialize prerequisite variables + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("prefix")).thenReturn(Prefix + "") + when(mockExecution.getVariable(Prefix + "rollbackNetworkRequest")).thenReturn("Good") + when(mockExecution.getVariable(Prefix + "rollbackSDNCRequest")).thenReturn("Good") + when(mockExecution.getVariable(Prefix + "rollbackNetworkReturnCode")).thenReturn("200") + when(mockExecution.getVariable(Prefix + "rollbackNetworkResponse")).thenReturn("GoodResponse") + when(mockExecution.getVariable(Prefix + "rollbackSDNCReturnCode")).thenReturn("200") + when(mockExecution.getVariable(Prefix + "rollbackSDNCResponse")).thenReturn("GoodResponse") + when(mockExecution.getVariable(Prefix + "WorkflowException")).thenReturn(workflowException) + when(mockExecution.getVariable(Prefix + "fullRollback")).thenReturn(false) + + DoUpdateNetworkInstanceRollback DoUpdateNetworkInstanceRollback = new DoUpdateNetworkInstanceRollback() + DoUpdateNetworkInstanceRollback.validateRollbackResponses(mockExecution) + + // verify set prefix = Prefix + "" + verify(mockExecution, atLeast(1)).setVariable("prefix", Prefix) + verify(mockExecution, atLeast(1)).setVariable("rolledBack", true) + verify(mockExecution, atLeast(1)).setVariable("wasDeleted", true) + verify(mockExecution).setVariable("WorkflowException", refEq(expectedWorkflowException, any(WorkflowException.class))) + //verify(mockExecution).setVariable("WorkflowException", expectedWorkflowException) + } + + @Test + //@Ignore + public void validateRollbackResponses_FullRollback() { + + Map<String, String> rollbackData = new HashMap<String, String>(); + rollbackData.put("rollbackSDNCRequest", rollbackSDNCRequest) + rollbackData.put("rollbackNetworkRequest", rollbackNetworkRequest) + + println "************ validateRollbackResponses_FullRollback() ************* " + ExecutionEntity mockExecution = setupMock() + // Initialize prerequisite variables + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("prefix")).thenReturn(Prefix) + when(mockExecution.getVariable(Prefix + "rollbackNetworkRequest")).thenReturn("Good") + when(mockExecution.getVariable(Prefix + "rollbackSDNCRequest")).thenReturn("Good") + when(mockExecution.getVariable(Prefix + "rollbackNetworkReturnCode")).thenReturn("200") + when(mockExecution.getVariable(Prefix + "rollbackNetworkResponse")).thenReturn("GoodResponse") + when(mockExecution.getVariable(Prefix + "rollbackSDNCReturnCode")).thenReturn("200") + when(mockExecution.getVariable(Prefix + "rollbackSDNCResponse")).thenReturn("GoodResponse") + when(mockExecution.getVariable(Prefix + "WorkflowException")).thenReturn(null) + when(mockExecution.getVariable(Prefix + "fullRollback")).thenReturn(true) + when(mockExecution.getVariable("rollbackData")).thenReturn(rollbackData) + + DoUpdateNetworkInstanceRollback DoUpdateNetworkInstanceRollback = new DoUpdateNetworkInstanceRollback() + DoUpdateNetworkInstanceRollback.validateRollbackResponses(mockExecution) + + // verify set prefix = Prefix + "" + verify(mockExecution, atLeast(1)).setVariable("prefix", Prefix) + verify(mockExecution, atLeast(1)).setVariable("rollbackSuccessful", true) + verify(mockExecution, atLeast(1)).setVariable("rollbackError", false) + + } + + + private ExecutionEntity setupMock() { + + ProcessDefinition mockProcessDefinition = mock(ProcessDefinition.class) + when(mockProcessDefinition.getKey()).thenReturn("DoUpdateNetworkInstanceRollback") + RepositoryService mockRepositoryService = mock(RepositoryService.class) + when(mockRepositoryService.getProcessDefinition()).thenReturn(mockProcessDefinition) + when(mockRepositoryService.getProcessDefinition().getKey()).thenReturn("DoUpdateNetworkInstanceRollback") + when(mockRepositoryService.getProcessDefinition().getId()).thenReturn("100") + ProcessEngineServices mockProcessEngineServices = mock(ProcessEngineServices.class) + when(mockProcessEngineServices.getRepositoryService()).thenReturn(mockRepositoryService) + + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + // Initialize prerequisite variables + + when(mockExecution.getId()).thenReturn("100") + when(mockExecution.getProcessDefinitionId()).thenReturn("DoUpdateNetworkInstanceRollback") + when(mockExecution.getProcessInstanceId()).thenReturn("DoUpdateNetworkInstanceRollback") + when(mockExecution.getProcessEngineServices()).thenReturn(mockProcessEngineServices) + when(mockExecution.getProcessEngineServices().getRepositoryService().getProcessDefinition(mockExecution.getProcessDefinitionId())).thenReturn(mockProcessDefinition) + + return mockExecution + } + +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateNetworkInstanceTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateNetworkInstanceTest.groovy new file mode 100644 index 0000000000..de3db5b5a8 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateNetworkInstanceTest.groovy @@ -0,0 +1,2762 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts + + +import static org.mockito.Mockito.* +import static org.onap.so.bpmn.mock.StubResponseAAI.MockGetNetworkByIdWithDepth; +import static org.onap.so.bpmn.mock.StubResponseAAI.MockGetNetworkCloudRegion; +import static org.onap.so.bpmn.mock.StubResponseAAI.MockGetNetworkCloudRegion_404; +import static org.onap.so.bpmn.mock.StubResponseAAI.MockGetNetworkVpnBinding; +import static org.onap.so.bpmn.mock.StubResponseAAI.MockGetNetworkTableReference; +import static org.onap.so.bpmn.mock.StubResponseAAI.MockGetNetworkPolicy; +import static org.onap.so.bpmn.mock.StubResponseAAI.MockPutNetworkIdWithDepth; +import org.camunda.bpm.engine.ProcessEngineServices +import org.camunda.bpm.engine.RepositoryService +import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity +import org.camunda.bpm.engine.repository.ProcessDefinition +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.MockitoAnnotations +import org.mockito.runners.MockitoJUnitRunner +import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.so.bpmn.core.WorkflowException + +import com.github.tomakehurst.wiremock.client.WireMock +import com.github.tomakehurst.wiremock.junit.WireMockRule +import org.apache.commons.lang3.* + + +@RunWith(MockitoJUnitRunner.class) +class DoUpdateNetworkInstanceTest { + + @Rule + public WireMockRule wireMockRule = new WireMockRule(8090); + + def utils = new MsoUtils() + String Prefix="UPDNETI_" + + String jsonIncomingRequest = + """{ "requestDetails": { + "modelInfo": { + "modelType": "network", + "modelCustomizationId": "f21df226-8093-48c3-be7e-0408fcda0422", + "modelName": "CONTRAIL_EXTERNAL", + "modelVersion": "1.0" + }, + "cloudConfiguration": { + "lcpCloudRegionId": "RDM2WAGPLCP", + "tenantId": "7dd5365547234ee8937416c65507d266" + }, + "requestInfo": { + "instanceName": "MNS-25180-L-01-dmz_direct_net_1", + "source": "VID", + "callbackUrl": "", + "suppressRollback": true, + "productFamilyId": "a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb" + }, + "relatedInstanceList": [ + { + "relatedInstance": { + "instanceId": "f70e927b-6087-4974-9ef8-c5e4d5847ca4", + "modelInfo": { + "modelType": "serviceT", + "modelId": "modelI", + "modelNameVersionId": "modelNameVersionI", + "modelName": "modleNam", + "modelVersion": "1" + } + } + } + ], + "requestParameters": { + "userParams": [ + { + "name": "someUserParam1", + "value": "someValue1" + } + ] + } + }}""" + + + String jsonIncomingRequest_MissingCloudRegion = + """{ "requestDetails": { + "modelInfo": { + "modelType": "network", + "modelCustomizationId": "f21df226-8093-48c3-be7e-0408fcda0422", + "modelName": "CONTRAIL_EXTERNAL", + "modelVersion": "1.0" + }, + "cloudConfiguration": { + "tenantId": "7dd5365547234ee8937416c65507d266" + }, + "requestInfo": { + "instanceName": "MNS-25180-L-01-dmz_direct_net_1", + "source": "VID", + "callbackUrl": "", + "suppressRollback": true, + "productFamilyId": "a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb" + }, + "relatedInstanceList": [ + { + "relatedInstance": { + "instanceId": "f70e927b-6087-4974-9ef8-c5e4d5847ca4", + "modelInfo": { + "modelType": "serviceT", + "modelId": "modelI", + "modelNameVersionId": "modelNameVersionI", + "modelName": "modleNam", + "modelVersion": "1" + } + } + } + ], + "requestParameters": { + "userParams": [] + } + }}""" + + + + String expectedNetworkRequestMissingNetworkId = + """<network-request xmlns="http://www.w3.org/2001/XMLSchema"> + <request-info> + <request-id>88f65519-9a38-4c4b-8445-9eb4a5a5af56</request-id> + <action>UPDATE</action> + <source>VID</source> + <service-instance-id>f70e927b-6087-4974-9ef8-c5e4d5847ca4</service-instance-id> + </request-info> + <network-inputs> + <network-id/> + <network-name>MNS-25180-L-01-dmz_direct_net_1</network-name> + <network-type>CONTRAIL_EXTERNAL</network-type> + <modelCustomizationId>f21df226-8093-48c3-be7e-0408fcda0422</modelCustomizationId> + <aic-cloud-region>RDM2WAGPLCP</aic-cloud-region> + <tenant-id>7dd5365547234ee8937416c65507d266</tenant-id> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <backout-on-failure>false</backout-on-failure> + <sdncVersion>1610</sdncVersion> + </network-inputs> + <network-params> + <param name="some_user_param1">someValue1</param> + </network-params> +</network-request>""" + + +String expectedNetworkRequestMissingCloudRegion = +"""<network-request xmlns="http://www.w3.org/2001/XMLSchema"> + <request-info> + <request-id>88f65519-9a38-4c4b-8445-9eb4a5a5af56</request-id> + <action>UPDATE</action> + <source>VID</source> + <service-instance-id>f70e927b-6087-4974-9ef8-c5e4d5847ca4</service-instance-id> + </request-info> + <network-inputs> + <network-id>networkId</network-id> + <network-name>MNS-25180-L-01-dmz_direct_net_1</network-name> + <network-type>CONTRAIL_EXTERNAL</network-type> + <modelCustomizationId>f21df226-8093-48c3-be7e-0408fcda0422</modelCustomizationId> + <aic-cloud-region>null</aic-cloud-region> + <tenant-id>7dd5365547234ee8937416c65507d266</tenant-id> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <backout-on-failure>false</backout-on-failure> + <sdncVersion>null</sdncVersion> + </network-inputs> + <network-params/> +</network-request>""" + +String expectedNetworkInputMissingCloudRegion = +"""<network-inputs xmlns="http://www.w3.org/2001/XMLSchema"> + <network-id>networkId</network-id> + <network-name>MNS-25180-L-01-dmz_direct_net_1</network-name> + <network-type>CONTRAIL_EXTERNAL</network-type> + <modelCustomizationId>f21df226-8093-48c3-be7e-0408fcda0422</modelCustomizationId> + <aic-cloud-region>null</aic-cloud-region> + <tenant-id>7dd5365547234ee8937416c65507d266</tenant-id> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <backout-on-failure>false</backout-on-failure> + <sdncVersion>null</sdncVersion> +</network-inputs>""" + + String networkInputsMissingName = + """<network-inputs xmlns="http://org.onap/so/infra/vnf-request/v1"> + <network-name/> + <network-type>CONTRAIL_EXTERNAL</network-type> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <aic-cloud-region>RDM2WAGPLCP</aic-cloud-region> + <tenant-id>e81d842d3e8b45c5a59f57cd76af3aaf</tenant-id> + </network-inputs>""" + +String networkInputsMissingCloudRegion = +"""<network-inputs xmlns="http://org.onap/so/infra/vnf-request/v1"> + <network-name>MNS-25180-L-01-dmz_direct_net_1</network-name> + <network-type>CONTRAIL_EXTERNAL</network-type> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <aic-cloud-region/> + <tenant-id>e81d842d3e8b45c5a59f57cd76af3aaf</tenant-id> +</network-inputs>""" + + // expectedNetworkRequest + String expectedNetworkRequest = + """<network-request xmlns="http://www.w3.org/2001/XMLSchema"> + <request-info> + <request-id>88f65519-9a38-4c4b-8445-9eb4a5a5af56</request-id> + <action>UPDATE</action> + <source>VID</source> + <service-instance-id>f70e927b-6087-4974-9ef8-c5e4d5847ca4</service-instance-id> + </request-info> + <network-inputs> + <network-id>49c86598-f766-46f8-84f8-8d1c1b10f9b4</network-id> + <network-name>MNS-25180-L-01-dmz_direct_net_1</network-name> + <network-type>CONTRAIL_EXTERNAL</network-type> + <modelCustomizationId>f21df226-8093-48c3-be7e-0408fcda0422</modelCustomizationId> + <aic-cloud-region>RDM2WAGPLCP</aic-cloud-region> + <tenant-id>7dd5365547234ee8937416c65507d266</tenant-id> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <backout-on-failure>false</backout-on-failure> + <sdncVersion>1610</sdncVersion> + </network-inputs> + <network-params> + <param name="some_user_param1">someValue1</param> + </network-params> +</network-request>""" + +String expectedNetworkInputs = +"""<network-inputs xmlns="http://www.w3.org/2001/XMLSchema"> + <network-id>49c86598-f766-46f8-84f8-8d1c1b10f9b4</network-id> + <network-name>MNS-25180-L-01-dmz_direct_net_1</network-name> + <network-type>CONTRAIL_EXTERNAL</network-type> + <modelCustomizationId>f21df226-8093-48c3-be7e-0408fcda0422</modelCustomizationId> + <aic-cloud-region>RDM2WAGPLCP</aic-cloud-region> + <tenant-id>7dd5365547234ee8937416c65507d266</tenant-id> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <backout-on-failure>false</backout-on-failure> + <sdncVersion>1610</sdncVersion> +</network-inputs>""" + +String expectedVperNetworkRequest = +"""<network-request xmlns="http://www.w3.org/2001/XMLSchema"> + <request-info> + <request-id>88f65519-9a38-4c4b-8445-9eb4a5a5af56</request-id> + <action>UPDATE</action> + <source>VID</source> + <service-instance-id>f70e927b-6087-4974-9ef8-c5e4d5847ca4</service-instance-id> + </request-info> + <network-inputs> + <network-id>49c86598-f766-46f8-84f8-8d1c1b10f9b4</network-id> + <network-name>MNS-25180-L-01-dmz_direct_net_1</network-name> + <network-type>CONTRAIL_EXTERNAL</network-type> + <subscription-service-type>MSO-dev-service-type</subscription-service-type> + <global-customer-id>globalId_45678905678</global-customer-id> + <aic-cloud-region>RDM2WAGPLCP</aic-cloud-region> + <tenant-id>7dd5365547234ee8937416c65507d266</tenant-id> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <backout-on-failure>false</backout-on-failure> + <failIfExist>false</failIfExist> + <networkModelInfo> + <modelName>CONTRAIL_EXTERNAL</modelName> + <modelUuid>sn5256d1-5a33-55df-13ab-12abad84e111</modelUuid> + <modelInvariantUuid>sn5256d1-5a33-55df-13ab-12abad84e764</modelInvariantUuid> + <modelVersion>1</modelVersion> + <modelCustomizationUuid>sn5256d1-5a33-55df-13ab-12abad84e222</modelCustomizationUuid> + </networkModelInfo> + <serviceModelInfo> + <modelName/> + <modelUuid/> + <modelInvariantUuid/> + <modelVersion/> + <modelCustomizationUuid/> + </serviceModelInfo> + <sdncVersion>1702</sdncVersion> + </network-inputs> + <network-params/> +</network-request>""" + +String expectedVperNetworkInputs = +"""<network-inputs xmlns="http://www.w3.org/2001/XMLSchema"> + <network-id>49c86598-f766-46f8-84f8-8d1c1b10f9b4</network-id> + <network-name>MNS-25180-L-01-dmz_direct_net_1</network-name> + <network-type>CONTRAIL_EXTERNAL</network-type> + <subscription-service-type>MSO-dev-service-type</subscription-service-type> + <global-customer-id>globalId_45678905678</global-customer-id> + <aic-cloud-region>RDM2WAGPLCP</aic-cloud-region> + <tenant-id>7dd5365547234ee8937416c65507d266</tenant-id> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <backout-on-failure>false</backout-on-failure> + <failIfExist>false</failIfExist> + <networkModelInfo> + <modelName>CONTRAIL_EXTERNAL</modelName> + <modelUuid>sn5256d1-5a33-55df-13ab-12abad84e111</modelUuid> + <modelInvariantUuid>sn5256d1-5a33-55df-13ab-12abad84e764</modelInvariantUuid> + <modelVersion>1</modelVersion> + <modelCustomizationUuid>sn5256d1-5a33-55df-13ab-12abad84e222</modelCustomizationUuid> + </networkModelInfo> + <serviceModelInfo> + <modelName/> + <modelUuid/> + <modelInvariantUuid/> + <modelVersion/> + <modelCustomizationUuid/> + </serviceModelInfo> + <sdncVersion>1702</sdncVersion> +</network-inputs>""" + +String expectedNetworkInputsMissingNetworkId = +"""<network-inputs xmlns="http://www.w3.org/2001/XMLSchema"> + <network-id/> + <network-name>MNS-25180-L-01-dmz_direct_net_1</network-name> + <network-type>CONTRAIL_EXTERNAL</network-type> + <modelCustomizationId>f21df226-8093-48c3-be7e-0408fcda0422</modelCustomizationId> + <aic-cloud-region>RDM2WAGPLCP</aic-cloud-region> + <tenant-id>7dd5365547234ee8937416c65507d266</tenant-id> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <backout-on-failure>false</backout-on-failure> + <sdncVersion>1610</sdncVersion> +</network-inputs>""" + + + String NetworkRequest_noPhysicalName = + """<vnfreq:network-request xmlns:vnfreq="http://org.onap/so/infra/vnf-request/v1"> + <vnfreq:request-info> + <vnfreq:request-id>1ef47428-cade-45bd-a103-0751e8b2deb0</vnfreq:request-id> + <vnfreq:action>UPDATE</vnfreq:action> + <vnfreq:source>PORTAL</vnfreq:source> + </vnfreq:request-info> + <vnfreq:network-inputs> + <vnfreq:network-name>MNS-25180-L-01-dmz_direct_net_1</vnfreq:network-name> + <vnfreq:network-type>CONTRAIL_EXTERNAL</vnfreq:network-type> + <vnfreq:modelCustomizationId></vnfreq:modelCustomizationId> + <vnfreq:service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</vnfreq:service-id> + <vnfreq:aic-cloud-region>RDM2WAGPLCP</vnfreq:aic-cloud-region> + <vnfreq:tenant-id>7dd5365547234ee8937416c65507d266</vnfreq:tenant-id> + <vnfreq:vlans>3008</vnfreq:vlans> + </vnfreq:network-inputs> + <vnfreq:network-params> + <network-params> + <param name="dhcp-enabled">true</param> + <param name="serviceId">a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</param> + <param name="cidr-mask">true</param> + <param name="backoutOnFailure">true</param> + <param name="gateway-address">10.10.125.1</param> + </network-params> + </vnfreq:network-params> +</vnfreq:network-request>""" + + String vnfRequestFakeRegion = + """<vnfreq:network-request xmlns:vnfreq="http://org.onap/so/infra/vnf-request/v1"> + <vnfreq:request-info> + <vnfreq:request-id>1ef47428-cade-45bd-a103-0751e8b2deb0</vnfreq:request-id> + <vnfreq:action>UPDATE</vnfreq:action> + <vnfreq:source>PORTAL</vnfreq:source> + </vnfreq:request-info> + <vnfreq:network-inputs> + <vnfreq:network-name>MNS-25180-L-01-dmz_direct_net_1</vnfreq:network-name> + <vnfreq:network-type>CONTRAIL_EXTERNAL</vnfreq:network-type> + <vnfreq:service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</vnfreq:service-id> + <vnfreq:aic-cloud-region>MDTWNJ21</vnfreq:aic-cloud-region> + <vnfreq:tenant-id>7dd5365547234ee8937416c65507d266</vnfreq:tenant-id> + </vnfreq:network-inputs> + <vnfreq:network-params> + <param name="shared">1</param> + <param name="external">0</param> + </vnfreq:network-params> +</vnfreq:network-request>""" + + // expectedNetworkRequest + String expectedNetworkRequest_Outputs = + """<vnfreq:network-request xmlns:vnfreq="http://org.onap/so/infra/vnf-request/v1"> + <vnfreq:request-info> + <vnfreq:request-id>1ef47428-cade-45bd-a103-0751e8b2deb0</vnfreq:request-id> + <vnfreq:action>UPDATE</vnfreq:action> + <vnfreq:source>PORTAL</vnfreq:source> + </vnfreq:request-info> + <vnfreq:network-inputs> + <vnfreq:network-name>MNS-25180-L-01-dmz_direct_net_1</vnfreq:network-name> + <vnfreq:network-type>CONTRAIL_EXTERNAL</vnfreq:network-type> + <vnfreq:service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</vnfreq:service-id> + <vnfreq:aic-cloud-region>RDM2WAGPLCP</vnfreq:aic-cloud-region> + <vnfreq:tenant-id>7dd5365547234ee8937416c65507d266</vnfreq:tenant-id> + </vnfreq:network-inputs> + <vnfreq:network-outputs> + <vnfreq:network-name>MNS-25180-L-01-dmz_direct_net_1</vnfreq:network-name> + <vnfreq:network-id>bdc5efe8-404a-409b-85f6-0dcc9eebae30</vnfreq:network-id> + </vnfreq:network-outputs> + <vnfreq:network-params> + <param name="shared">1</param> + <param name="external">0</param> + </vnfreq:network-params> +</vnfreq:network-request>""" + + + String networkInputs = + """<network-inputs xmlns="http://org.onap/so/infra/vnf-request/v1"> + <network-id>bdc5efe8-404a-409b-85f6-0dcc9eebae30</network-id> + <network-name>MNS-25180-L-01-dmz_direct_net_1</network-name> + <network-type>CONTRAIL_EXTERNAL</network-type> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <aic-cloud-region>RDM2WAGPLCP</aic-cloud-region> + <tenant-id>e81d842d3e8b45c5a59f57cd76af3aaf</tenant-id> +</network-inputs>""" + + String networkOutputs = + """<network-outputs> + <network-id>49c86598-f766-46f8-84f8-8d1c1b10f9b4</network-id> + <network-name>MNS-25180-L-01-dmz_direct_net_1</network-name> + </network-outputs>""" + + String queryAAIResponse = + """<rest:RESTResponse xmlns:rest="http://schemas.activebpel.org/REST/2007/12/01/aeREST.xsd" + statusCode="200"> + <rest:headers> + <rest:header name="Transfer-Encoding" value="chunked"/> + <rest:header name="Date" value="Thu,10 Mar 2016 00:01:18 GMT"/> + <rest:header name="Expires" value="Thu,01 Jan 1970 00:00:00 UTC"/> + <rest:header name="X-AAI-TXID" value="mtcnjv9aaas03-20160310-00:01:18:502-132671"/> + <rest:header name="Content-Type" value="application/xml"/> + <rest:header name="Server" value="Apache-Coyote/1.1"/> + <rest:header name="Cache-Control" value="private"/> + </rest:headers> + <rest:payload contentType="text/xml"> + <l3-network xmlns="http://org.openecomp.aai.inventory/v3"> + <network-id>bdc5efe8-404a-409b-85f6-0dcc9eebae30</network-id> + <network-name>MNS-25180-L-01-dmz_direct_net_1</network-name> + <network-type>CONTRAIL_EXTERNAL</network-type> + <network-role>dmz_direct</network-role> + <network-technology>contrail</network-technology> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <network-role-instance>0</network-role-instance> + <orchestration-status>pending-delete</orchestration-status> + <subnets> + <subnet> + <subnet-id>57e9a1ff-d14f-4071-a828-b19ae98eb2fc</subnet-id> + <gateway-address>107.239.52.1</gateway-address> + <network-start-address>107.239.52.0</network-start-address> + <cidr-mask>24</cidr-mask> + <ip-version>4</ip-version> + <orchestration-status>pending-delete</orchestration-status> + <dhcp-enabled>true</dhcp-enabled> + <relationship-list/> + </subnet> + </subnets> + <relationship-list> + <relationship> + <related-to>vpn-binding</related-to> + <related-link>https://aai-app-e2e.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/85f015d0-2e32-4c30-96d2-87a1a27f8017/</related-link> + <relationship-data> + <relationship-key>vpn-binding.vpn-id</relationship-key> + <relationship-value>85f015d0-2e32-4c30-96d2-87a1a27f8017</relationship-value> + </relationship-data> + </relationship> + <relationship> + <related-to>vpn-binding</related-to> + <related-link>https://aai-app-e2e.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/c980a6ef-3b88-49f0-9751-dbad8608d0a6/</related-link> + <relationship-data> + <relationship-key>vpn-binding.vpn-id</relationship-key> + <relationship-value>c980a6ef-3b88-49f0-9751-dbad8608d0a6</relationship-value> + </relationship-data> + </relationship> + <relationship> + <related-to>tenant</related-to> + <related-link>https://aai-app-e2e.test.com:8443/aai/v8/cloud-infrastructure/tenants/tenant/7dd5365547234ee8937416c65507d266/</related-link> + <relationship-data> + <relationship-key>tenant.tenant-id</relationship-key> + <relationship-value>7dd5365547234ee8937416c65507d266</relationship-value> + </relationship-data> + </relationship> + </relationship-list> + </l3-network> + </rest:payload> +</rest:RESTResponse>""" + + String queryIdAIIResponse = + """<rest:RESTResponse xmlns:rest="http://schemas.activebpel.org/REST/2007/12/01/aeREST.xsd" + statusCode="200"> + <rest:headers> + <rest:header name="Transfer-Encoding" value="chunked"/> + <rest:header name="Date" value="Thu,10 Mar 2016 00:01:18 GMT"/> + <rest:header name="Expires" value="Thu,01 Jan 1970 00:00:00 UTC"/> + <rest:header name="X-AAI-TXID" value="mtcnjv9aaas03-20160310-00:01:18:502-132671"/> + <rest:header name="Content-Type" value="application/xml"/> + <rest:header name="Server" value="Apache-Coyote/1.1"/> + <rest:header name="Cache-Control" value="private"/> + </rest:headers> + <rest:payload contentType="text/xml"> + <l3-network xmlns="http://org.openecomp.aai.inventory/v6"> + <network-id>49c86598-f766-46f8-84f8-8d1c1b10f9b4</network-id> + <network-name>MNS-25180-L-01-dmz_direct_net_1</network-name> + <network-type>CONTRAIL_EXTERNAL</network-type> + <network-role>dmz_direct</network-role> + <network-technology>contrail</network-technology> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <network-role-instance>0</network-role-instance> + <resource-version>l3-version</resource-version> + <orchestration-status>pending-delete</orchestration-status> + <heat-stack-id>ST_2Bindings_6006/55288ef0-595c-47d3-819e-cf93aaac6326</heat-stack-id> + <physical-network-name>networkName</physical-network-name> + <is-provider-network>false</is-provider-network> + <is-shared-network>true</is-shared-network> + <is-external-network>false</is-external-network> + <subnets> + <subnet> + <subnet-id>57e9a1ff-d14f-4071-a828-b19ae98eb2fc</subnet-id> + <gateway-address>107.239.52.1</gateway-address> + <network-start-address>107.239.52.0</network-start-address> + <cidr-mask>24</cidr-mask> + <ip-version>4</ip-version> + <orchestration-status>pending-update</orchestration-status> + <dhcp-enabled>true</dhcp-enabled> + <subnet-name>subnetName</subnet-name> + <subnet-role>ECOMP</subnet-role> + <ip-assignment-direction>true</ip-assignment-direction> + <host-routes> + <host-route> + <host-route-id>400d286b-7e44-4514-b9b3-f70f7360ff32</host-route-id> + <route-prefix>172.20.1.0/24</route-prefix> + <next-hop>10.102.200.1</next-hop> + <next-hop-type>ip-address</next-hop-type> + <resource-version>1505857300987</resource-version> + </host-route> + <host-route> + <host-route-id>6f038013-8b15-4eb8-914b-507489fbc8ee</host-route-id> + <route-prefix>10.102.0.0/16</route-prefix> + <next-hop>10.102.200.1</next-hop> + <next-hop-type>ip-address</next-hop-type> + <resource-version>1505857301151</resource-version> + </host-route> + <host-route> + <host-route-id>8811c5f8-f1ed-4fa0-a505-e1be60396e28</host-route-id> + <route-prefix>192.168.2.0/25</route-prefix> + <next-hop>10.102.200.1</next-hop> + <resource-version>1505857301954</resource-version> + </host-route> + </host-routes> + <relationship-list/> + </subnet> + <subnet> + <subnet-id>57e9a1ff-d14f-4071-a828-b19ae98eb2fc</subnet-id> + <gateway-address>107.239.52.1</gateway-address> + <network-start-address>107.239.52.0</network-start-address> + <cidr-mask>24</cidr-mask> + <ip-version>4</ip-version> + <orchestration-status>pending-delete</orchestration-status> + <dhcp-enabled>true</dhcp-enabled> + <subnet-name>subnetName</subnet-name> + <ip-assignment-direction>true</ip-assignment-direction> + <host-routes> + <host-route> + <host-route-id>400d286b-7e44-4514-b9b3-f70f7360ff32</host-route-id> + <route-prefix>172.20.1.0/24</route-prefix> + <next-hop>10.102.200.1</next-hop> + <resource-version>1505857300987</resource-version> + </host-route> + </host-routes> + <relationship-list/> + </subnet> + </subnets> + <segmentation-assignments> + <segmentation-id>414</segmentation-id> + <resource-version>4132176</resource-version> + </segmentation-assignments> + <segmentation-assignments> + <segmentation-id>415</segmentation-id> + <resource-version>4132176</resource-version> + </segmentation-assignments> + <ctag-assignments> + <ctag-assignment> + <vlan-id-inner>inner</vlan-id-inner> + <resource-version>ctag-version</resource-version> + <relationship-list> + <relationship> + <related-to>tenant</related-to> + <related-link>https://aai-ext1.test.com:8443/aai/v8/cloud-infrastructure/tenants/tenant/897deadc2b954a6bac6d3c197fb3525e/</related-link> + <relationship-data> + <relationship-key>tenant.tenant-id</relationship-key> + <relationship-value>897deadc2b954a6bac6d3c197fb3525e</relationship-value> + </relationship-data> + <related-to-property> + <property-key>tenant.tenant-name</property-key> + <property-value>MSOTest1</property-value> + </related-to-property> + </relationship> + <relationship> + <related-to>vpn-binding</related-to> + <related-link>https://aai-ext1.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/a290b841-f672-44dd-b9cd-6f8c20d7d8c8/</related-link> + <relationship-data> + <relationship-key>vpn-binding.vpn-id</relationship-key> + <relationship-value>a290b841-f672-44dd-b9cd-6f8c20d7d8c8</relationship-value> + </relationship-data> + <related-to-property> + <property-key>vpn-binding.vpn-name</property-key> + <property-value>oam_protected_net_6_MTN5_msotest2</property-value> + </related-to-property> + </relationship> + <relationship> + <related-to>vpn-binding</related-to> + <related-link>https://aai-ext1.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/24a4b507-853a-4a38-99aa-05fcc54be24d/</related-link> + <relationship-data> + <relationship-key>vpn-binding.vpn-id</relationship-key> + <relationship-value>24a4b507-853a-4a38-99aa-05fcc54be24d</relationship-value> + </relationship-data> + <related-to-property> + <property-key>vpn-binding.vpn-name</property-key> + <property-value>oam_protected_net_6_MTN5_msotest1</property-value> + </related-to-property> + </relationship> + </relationship-list> + </ctag-assignment> + </ctag-assignments> + <relationship-list> + <relationship> + <related-to>vpn-binding</related-to> + <related-link>https://aai-app-e2e.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/85f015d0-2e32-4c30-96d2-87a1a27f8017/</related-link> + <relationship-data> + <relationship-key>vpn-binding.vpn-id</relationship-key> + <relationship-value>85f015d0-2e32-4c30-96d2-87a1a27f8017</relationship-value> + </relationship-data> + </relationship> + <relationship> + <related-to>vpn-binding</related-to> + <related-link>https://aai-app-e2e.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/c980a6ef-3b88-49f0-9751-dbad8608d0a6/</related-link> + <relationship-data> + <relationship-key>vpn-binding.vpn-id</relationship-key> + <relationship-value>c980a6ef-3b88-49f0-9751-dbad8608d0a6</relationship-value> + </relationship-data> + </relationship> + <relationship> + <related-to>tenant</related-to> + <related-link>https://aai-app-e2e.test.com:8443/aai/v8/cloud-infrastructure/tenants/tenant/7dd5365547234ee8937416c65507d266/</related-link> + <relationship-data> + <relationship-key>tenant.tenant-id</relationship-key> + <relationship-value>7dd5365547234ee8937416c65507d266</relationship-value> + </relationship-data> + </relationship> + <relationship> + <related-to>network-policy</related-to> + <related-link>https://aai-app-e2e.test.com:8443/aai/v8/network/network-policies/network-policy/cee6d136-e378-4678-a024-2cd15f0ee0cg</related-link> + <relationship-data> + <relationship-key>network-policy.network-policy-id</relationship-key> + <relationship-value>cee6d136-e378-4678-a024-2cd15f0ee0cg</relationship-value> + </relationship-data> + </relationship> + <relationship> + <related-to>route-table-reference</related-to> + <related-link>https://aai-app-e2e.test.com:8443/aai/v8/network/route-table-references/route-table-reference/refFQDN1</related-link> + <relationship-data> + <relationship-key>route-table-reference.route-table-reference-id</relationship-key> + <relationship-value>cee6d136-e378-4678-a024-2cd15f0ee0hi</relationship-value> + </relationship-data> + </relationship> + <relationship> + <related-to>route-table-reference</related-to> + <related-link>https://aai-app-e2e.test.com:8443/aai/v8/network/route-table-references/route-table-reference/refFQDN2</related-link> + <relationship-data> + <relationship-key>route-table-reference.route-table-reference-id</relationship-key> + <relationship-value>cee6d136-e378-4678-a024-2cd15f0ee0hi</relationship-value> + </relationship-data> + </relationship> + </relationship-list> + </l3-network> + </rest:payload> +</rest:RESTResponse>""" + + String queryIdAIIResponseTestScenario01 = + """<?xml version="1.0" encoding="UTF-8"?> +<l3-network xmlns="http://org.openecomp.aai.inventory/v7"> + <network-id>4da55fe4-7a9e-478c-a434-8a98d62265ab</network-id> + <network-name>GN_EVPN_direct_net_0_ST1</network-name> + <network-type>CONTRAIL30_BASIC</network-type> + <network-role>GN_EVPN_direct</network-role> + <network-technology>contrail</network-technology> + <is-bound-to-vpn>false</is-bound-to-vpn> + <service-id>9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <network-role-instance>0</network-role-instance> + <resource-version>1465398611</resource-version> + <orchestration-status>pending-delete</orchestration-status> + <physical-network-name>networkName</physical-network-name> + <is-provider-network>false</is-provider-network> + <is-shared-network>true</is-shared-network> + <is-external-network>false</is-external-network> + <subnets> + <subnet> + <subnet-id>cb1a7b47-5428-44c9-89c2-8b17541c3228</subnet-id> + <gateway-address>108.239.40.1</gateway-address> + <network-start-address>108.239.40.0</network-start-address> + <cidr-mask>28</cidr-mask> + <ip-version>4</ip-version> + <orchestration-status>pending-delete</orchestration-status> + <dhcp-enabled>true</dhcp-enabled> + <dhcp-start>108.239.40.0</dhcp-start> + <dhcp-end>108.239.40.0</dhcp-end> + <resource-version>1465398611</resource-version> + <subnet-name>subnetName</subnet-name> + <relationship-list /> + </subnet> + <subnet> + <subnet-id>e2cc7c14-90f0-4205-840d-b4e07f04e621</subnet-id> + <gateway-address>2606:ae00:2e01:604::1</gateway-address> + <network-start-address>2606:ae00:2e01:604::</network-start-address> + <cidr-mask>64</cidr-mask> + <ip-version>6</ip-version> + <orchestration-status>pending-delete</orchestration-status> + <dhcp-enabled>true</dhcp-enabled> + <dhcp-start>2606:ae00:2e01:604::</dhcp-start> + <dhcp-end>2606:ae00:2e01:604::</dhcp-end> + <resource-version>1465398611</resource-version> + <subnet-name>subnetName</subnet-name> + <relationship-list /> + </subnet> + </subnets> + <ctag-assignments /> + <segmentation-assignments> + <segmentation-id>416</segmentation-id> + <resource-version>4132176</resource-version> + </segmentation-assignments> + <relationship-list> + <relationship> + <related-to>cloud-region</related-to> + <related-link>https://localhost:8443/aai/v8/cloud-infrastructure/cloud-regions/cloud-region/att-aic/AAIAIC25/ + </related-link> + <relationship-data> + <relationship-key>cloud-region.cloud-region-id</relationship-key> + <relationship-value>AAIAIC25</relationship-value> + </relationship-data> + <relationship-data> + <relationship-key>cloud-region.cloud-owner</relationship-key> + <relationship-value>att-aic</relationship-value> + </relationship-data> + <related-to-property> + <property-key>cloud-region.owner-defined-type</property-key> + <property-value></property-value> + </related-to-property> + </relationship> + <relationship> + <related-to>tenant</related-to> + <related-link>https://localhost:8443/aai/v8/cloud-infrastructure/cloud-regions/cloud-region/att-aic/AAIAIC25/tenants/tenant/4ae1d3446a4c48b2bec44b6cfba06d68/</related-link> + <relationship-data> + <relationship-key>tenant.tenant-id</relationship-key> + <relationship-value>4ae1d3446a4c48b2bec44b6cfba06d68 + </relationship-value> + </relationship-data> + <relationship-data> + <relationship-key>cloud-region.cloud-owner</relationship-key> + <relationship-value>att-aic</relationship-value> + </relationship-data> + <relationship-data> + <relationship-key>cloud-region.cloud-region-id</relationship-key> + <relationship-value>AAIAIC25</relationship-value> + </relationship-data> + <related-to-property> + <property-key>tenant.tenant-name</property-key> + <property-value>Ruchira Contrail 3.0 test</property-value> + </related-to-property> + </relationship> + <relationship> + <related-to>vpn-binding</related-to> + <related-link>https://localhost:8443/aai/v8/network/vpn-bindings/vpn-binding/85f015d0-2e32-4c30-96d2-87a1a27f8017/</related-link> + <relationship-data> + <relationship-key>vpn-binding.vpn-id</relationship-key> + <relationship-value>9a7b327d9-287aa00-82c4b0-100001</relationship-value> + </relationship-data> + <related-to-property> + <property-key>vpn-binding.vpn-name</property-key> + <property-value>GN_EVPN_direct_net_0_ST1</property-value> + </related-to-property> + </relationship> + <relationship> + <related-to>route-table-reference</related-to> + <relationship-data> + <relationship-key>route-table-reference.route-table-reference-id</relationship-key> + <relationship-value>cee6d136-e378-4678-a024-2cd15f0ee0hi</relationship-value> + </relationship-data> + </relationship> + </relationship-list> +</l3-network>""" + + String queryIdAIIResponseVpnNotPresent = + """<rest:RESTResponse xmlns:rest="http://schemas.activebpel.org/REST/2007/12/01/aeREST.xsd" + statusCode="200"> + <rest:headers> + <rest:header name="Transfer-Encoding" value="chunked"/> + <rest:header name="Date" value="Thu,10 Mar 2016 00:01:18 GMT"/> + <rest:header name="Expires" value="Thu,01 Jan 1970 00:00:00 UTC"/> + <rest:header name="X-AAI-TXID" value="mtcnjv9aaas03-20160310-00:01:18:502-132671"/> + <rest:header name="Content-Type" value="application/xml"/> + <rest:header name="Server" value="Apache-Coyote/1.1"/> + <rest:header name="Cache-Control" value="private"/> + </rest:headers> + <rest:payload contentType="text/xml"> + <l3-network xmlns="http://org.openecomp.aai.inventory/v6"> + <network-id>49c86598-f766-46f8-84f8-8d1c1b10f9b4</network-id> + <network-name>MNS-25180-L-01-dmz_direct_net_1</network-name> + <network-type>CONTRAIL_EXTERNAL</network-type> + <network-role>dmz_direct</network-role> + <network-technology>contrail</network-technology> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <network-role-instance>0</network-role-instance> + <orchestration-status>pending-delete</orchestration-status> + <physical-network-name>networkName</physical-network-name> + <is-provider-network>false</is-provider-network> + <is-shared-network>true</is-shared-network> + <is-external-network>false</is-external-network> + <subnets> + <subnet> + <subnet-id>57e9a1ff-d14f-4071-a828-b19ae98eb2fc</subnet-id> + <gateway-address>107.239.52.1</gateway-address> + <network-start-address>107.239.52.0</network-start-address> + <cidr-mask>24</cidr-mask> + <ip-version>4</ip-version> + <orchestration-status>pending-delete</orchestration-status> + <dhcp-enabled>true</dhcp-enabled> + <subnet-name>subnetName</subnet-name> + <relationship-list/> + </subnet> + </subnets> + <relationship-list/> + </l3-network> + </rest:payload> +</rest:RESTResponse>""" + + String queryNameAIIResponse = + """<rest:RESTResponse xmlns:rest="http://schemas.activebpel.org/REST/2007/12/01/aeREST.xsd" + statusCode="200"> + <rest:headers> + <rest:header name="Transfer-Encoding" value="chunked"/> + <rest:header name="Date" value="Thu,10 Mar 2016 00:01:18 GMT"/> + <rest:header name="Expires" value="Thu,01 Jan 1970 00:00:00 UTC"/> + <rest:header name="X-AAI-TXID" value="mtcnjv9aaas03-20160310-00:01:18:502-132671"/> + <rest:header name="Content-Type" value="application/xml"/> + <rest:header name="Server" value="Apache-Coyote/1.1"/> + <rest:header name="Cache-Control" value="private"/> + </rest:headers> + <rest:payload contentType="text/xml"> + <l3-network xmlns="http://org.openecomp.aai.inventory/v6"> + <network-id>49c86598-f766-46f8-84f8-8d1c1b10f9b4</network-id> + <network-name>MNS-25180-L-01-dmz_direct_net_1</network-name> + <network-type>CONTRAIL_EXTERNAL</network-type> + <network-role>dmz_direct</network-role> + <network-technology>contrail</network-technology> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <network-role-instance>0</network-role-instance> + <orchestration-status>pending-delete</orchestration-status> + <subnets> + <subnet> + <subnet-id>57e9a1ff-d14f-4071-a828-b19ae98eb2fc</subnet-id> + <gateway-address>107.239.52.1</gateway-address> + <network-start-address>107.239.52.0</network-start-address> + <cidr-mask>24</cidr-mask> + <ip-version>4</ip-version> + <orchestration-status>pending-delete</orchestration-status> + <dhcp-enabled>true</dhcp-enabled> + <relationship-list/> + </subnet> + </subnets> + <relationship-list> + <relationship> + <related-to>vpn-binding</related-to> + <related-link>https://aai-app-e2e.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/85f015d0-2e32-4c30-96d2-87a1a27f8017/</related-link> + <relationship-data> + <relationship-key>vpn-binding.vpn-id</relationship-key> + <relationship-value>85f015d0-2e32-4c30-96d2-87a1a27f8017</relationship-value> + </relationship-data> + </relationship> + <relationship> + <related-to>vpn-binding</related-to> + <related-link>https://aai-app-e2e.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/c980a6ef-3b88-49f0-9751-dbad8608d0a6/</related-link> + <relationship-data> + <relationship-key>vpn-binding.vpn-id</relationship-key> + <relationship-value>c980a6ef-3b88-49f0-9751-dbad8608d0a6</relationship-value> + </relationship-data> + </relationship> + <relationship> + <related-to>tenant</related-to> + <related-link>https://aai-app-e2e.test.com:8443/aai/v8/cloud-infrastructure/tenants/tenant/7dd5365547234ee8937416c65507d266/</related-link> + <relationship-data> + <relationship-key>tenant.tenant-id</relationship-key> + <relationship-value>7dd5365547234ee8937416c65507d266</relationship-value> + </relationship-data> + </relationship> + </relationship-list> + </l3-network> + </rest:payload> + </rest:RESTResponse>""" + + String queryNameAIIResponseVpnNotPresent = + """<rest:RESTResponse xmlns:rest="http://schemas.activebpel.org/REST/2007/12/01/aeREST.xsd" + statusCode="200"> + <rest:headers> + <rest:header name="Transfer-Encoding" value="chunked"/> + <rest:header name="Date" value="Thu,10 Mar 2016 00:01:18 GMT"/> + <rest:header name="Expires" value="Thu,01 Jan 1970 00:00:00 UTC"/> + <rest:header name="X-AAI-TXID" value="mtcnjv9aaas03-20160310-00:01:18:502-132671"/> + <rest:header name="Content-Type" value="application/xml"/> + <rest:header name="Server" value="Apache-Coyote/1.1"/> + <rest:header name="Cache-Control" value="private"/> + </rest:headers> + <rest:payload contentType="text/xml"> + <l3-network xmlns="http://org.openecomp.aai.inventory/v6> + <network-id>49c86598-f766-46f8-84f8-8d1c1b10f9b4</network-id> + <network-name>MNS-25180-L-01-dmz_direct_net_1</network-name> + <network-type>CONTRAIL_EXTERNAL</network-type> + <network-role>dmz_direct</network-role> + <network-technology>contrail</network-technology> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <network-role-instance>0</network-role-instance> + <orchestration-status>pending-delete</orchestration-status> + <subnets> + <subnet> + <subnet-id>57e9a1ff-d14f-4071-a828-b19ae98eb2fc</subnet-id> + <gateway-address>107.239.52.1</gateway-address> + <network-start-address>107.239.52.0</network-start-address> + <cidr-mask>24</cidr-mask> + <ip-version>4</ip-version> + <orchestration-status>pending-delete</orchestration-status> + <dhcp-enabled>true</dhcp-enabled> + <relationship-list/> + </subnet> + </subnets> + </l3-network> + </rest:payload> + </rest:RESTResponse>""" + + String aaiVpnResponseStub = + """<rest:payload xmlns:rest="http://schemas.activebpel.org/REST/2007/12/01/aeREST.xsd" + xmlns="http://org.openecomp.aai.inventory/v8" + contentType="text/xml"> + <vpn-binding> + <global-route-target/> + </vpn-binding> +</rest:payload>""" + + String queryVpnBindingAAIResponse = + """<rest:RESTResponse xmlns:rest="http://schemas.activebpel.org/REST/2007/12/01/aeREST.xsd" + statusCode="200"> + <rest:headers> + <rest:header name="Transfer-Encoding" value="chunked"/> + <rest:header name="Date" value="Mon,14 Mar 2016 20:53:33 GMT"/> + <rest:header name="Expires" value="Thu,01 Jan 1970 00:00:00 UTC"/> + <rest:header name="X-AAI-TXID" + value="localhost-20160314-20:53:33:487-134392"/> + <rest:header name="Content-Type" value="application/xml"/> + <rest:header name="Server" value="Apache-Coyote/1.1"/> + <rest:header name="Cache-Control" value="private"/> + </rest:headers> + <rest:payload contentType="text/xml"> + <vpn-binding xmlns="http://org.openecomp.aai.inventory/v6"> + <vpn-id>9a7b327d9-287aa00-82c4b0-105757</vpn-id> + <vpn-name>GN_EVPN_Test</vpn-name> + <global-route-target>13979:105757</global-route-target> + <relationship-list> + <relationship> + <related-to>l3-network</related-to> + <related-link>https://aai-app-e2e.test.com:8443/aai/v3/network/l3-networks/l3-network/689ec39e-c5fc-4462-8db2-4f760763ad28/</related-link> + <relationship-data> + <relationship-key>l3-network.network-id</relationship-key> + <relationship-value>689ec39e-c5fc-4462-8db2-4f760763ad28</relationship-value> + </relationship-data> + </relationship> + <relationship> + <related-to>l3-network</related-to> + <related-link>https://aai-app-e2e.test.com:8443/aai/v3/network/l3-networks/l3-network/1a49396b-19b3-40a4-8792-aa2fbd0f0704/</related-link> + <relationship-data> + <relationship-key>l3-network.network-id</relationship-key> + <relationship-value>1a49396b-19b3-40a4-8792-aa2fbd0f0704</relationship-value> + </relationship-data> + </relationship> + <relationship> + <related-to>l3-network</related-to> + <related-link>https://aai-app-e2e.test.com:8443/aai/v3/network/l3-networks/l3-network/774f3329-3c83-4771-86c7-9e6207cd50fd/</related-link> + <relationship-data> + <relationship-key>l3-network.network-id</relationship-key> + <relationship-value>774f3329-3c83-4771-86c7-9e6207cd50fd</relationship-value> + </relationship-data> + </relationship> + </relationship-list> + </vpn-binding> + </rest:payload> +</rest:RESTResponse>""" + + + String updateNetworkRequest = + """<updateNetworkRequest> + <cloudSiteId>RDM2WAGPLCP</cloudSiteId> + <tenantId>7dd5365547234ee8937416c65507d266</tenantId> + <networkId>49c86598-f766-46f8-84f8-8d1c1b10f9b4</networkId> + <networkStackId>ST_2Bindings_6006/55288ef0-595c-47d3-819e-cf93aaac6326</networkStackId> + <networkName>MNS-25180-L-01-dmz_direct_net_1</networkName> + <networkType>CONTRAIL_EXTERNAL</networkType> + <modelCustomizationUuid>sn5256d1-5a33-55df-13ab-12abad84e222</modelCustomizationUuid> + <networkTypeVersion/> + <networkTechnology>CONTRAIL</networkTechnology> + <providerVlanNetwork> + <physicalNetworkName>networkName</physicalNetworkName> + <vlans>414,415</vlans> + </providerVlanNetwork> + <contrailNetwork> + <shared>true</shared> + <external>false</external> + <routeTargets>13979:105757</routeTargets> + <routeTargets>13979:105757</routeTargets> + <policyFqdns>GN_EVPN_Test</policyFqdns> + <routeTableFqdns>refFQDN1</routeTableFqdns> + <routeTableFqdns>refFQDN2</routeTableFqdns> + </contrailNetwork> + <subnets> + <allocationPools> + <start/> + <end/> + </allocationPools> + <cidr>107.239.52.0/24</cidr> + <enableDHCP>true</enableDHCP> + <gatewayIp>107.239.52.1</gatewayIp> + <ipVersion>4</ipVersion> + <subnetId>57e9a1ff-d14f-4071-a828-b19ae98eb2fc</subnetId> + <subnetName>subnetName</subnetName> + <addrFromStart>true</addrFromStart> + <hostRoutes> + <prefix>172.20.1.0/24</prefix> + <nextHop>10.102.200.1</nextHop> + </hostRoutes> + <hostRoutes> + <prefix>10.102.0.0/16</prefix> + <nextHop>10.102.200.1</nextHop> + </hostRoutes> + <hostRoutes> + <prefix>192.168.2.0/25</prefix> + <nextHop>10.102.200.1</nextHop> + </hostRoutes> + </subnets> + <skipAAI>true</skipAAI> + <backout>true</backout> + <failIfExists>false</failIfExists> + <msoRequest> + <requestId>88f65519-9a38-4c4b-8445-9eb4a5a5af56</requestId> + <serviceInstanceId>f70e927b-6087-4974-9ef8-c5e4d5847ca4</serviceInstanceId> + </msoRequest> + <messageId>messageId_generated</messageId> + <notificationUrl/> +</updateNetworkRequest>""" + +String updateNetworkRequest_noPhysicalName = +"""<updateNetworkRequest> + <cloudSiteId>RDM2WAGPLCP</cloudSiteId> + <tenantId>7dd5365547234ee8937416c65507d266</tenantId> + <networkId>49c86598-f766-46f8-84f8-8d1c1b10f9b4</networkId> + <networkStackId>ST_2Bindings_6006/55288ef0-595c-47d3-819e-cf93aaac6326</networkStackId> + <networkName>MNS-25180-L-01-dmz_direct_net_1</networkName> + <networkType>CONTRAIL_EXTERNAL</networkType> + <modelCustomizationUuid/> + <networkTypeVersion/> + <networkTechnology>CONTRAIL</networkTechnology> + <providerVlanNetwork> + <physicalNetworkName>networkName</physicalNetworkName> + <vlans>414,415</vlans> + </providerVlanNetwork> + <contrailNetwork> + <shared>true</shared> + <external>false</external> + <routeTargets>13979:105757</routeTargets> + <routeTargets>13979:105757</routeTargets> + <policyFqdns>GN_EVPN_Test</policyFqdns> + </contrailNetwork> + <subnets> + <allocationPools> + <start/> + <end/> + </allocationPools> + <cidr>107.239.52.0/24</cidr> + <enableDHCP>true</enableDHCP> + <gatewayIp>107.239.52.1</gatewayIp> + <ipVersion>4</ipVersion> + <subnetId>57e9a1ff-d14f-4071-a828-b19ae98eb2fc</subnetId> + <subnetName>subnetName</subnetName> + <addrFromStart>true</addrFromStart> + <hostRoutes> + <prefix>172.20.1.0/24</prefix> + <nextHop>10.102.200.1</nextHop> + </hostRoutes> + <hostRoutes> + <prefix>10.102.0.0/16</prefix> + <nextHop>10.102.200.1</nextHop> + </hostRoutes> + <hostRoutes> + <prefix>192.168.2.0/25</prefix> + <nextHop>10.102.200.1</nextHop> + </hostRoutes> + </subnets> + <skipAAI>true</skipAAI> + <backout>true</backout> + <failIfExists>false</failIfExists> + <networkParams> + <dhcp-enabled>true</dhcp-enabled> + <serviceId>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</serviceId> + <cidr-mask>true</cidr-mask> + <backoutOnFailure>true</backoutOnFailure> + <gateway-address>10.10.125.1</gateway-address> + </networkParams> + <msoRequest> + <requestId>88f65519-9a38-4c4b-8445-9eb4a5a5af56</requestId> + <serviceInstanceId>null</serviceInstanceId> + </msoRequest> + <messageId>messageId_generated</messageId> + <notificationUrl/> +</updateNetworkRequest>""" + + String updateNetworkResponseREST = + """<ns2:updateNetworkContrailResponse xmlns:ns2="http://org.onap.so/network"> + <networkId>MNS-25180-L-01-dmz_direct_net_1/2c88a3a9-69b9-43a7-ada6-1aca577c3641</networkId> + <neutronNetworkId>c4f4e878-cde0-4b15-ae9a-bda857759cea</neutronNetworkId> + <networkFqdn>default-domain:MSOTest:GN_EVPN_direct_net_0_ST1</networkFqdn> + <networkStackId></networkStackId> + <subnetMap> + <entry> + <key>57e9a1ff-d14f-4071-a828-b19ae98eb2fc</key> + <value>bd8e87c6-f4e2-41b8-b0bc-9596aa00cd73</value> + </entry> + <entry> + <key>57e9a1ff-d14f-4071-a828-b19ae98eb2fc</key> + <value>bd8e87c6-f4e2-41b8-b0bc-9596aa00cd73</value> + </entry> + </subnetMap> + <rollback> + <networkId>MNS-25180-L-01-dmz_direct_net_1/2c88a3a9-69b9-43a7-ada6-1aca577c3641</networkId> + <neutronNetworkId>c4f4e878-cde0-4b15-ae9a-bda857759cea</neutronNetworkId> + <networkStackId></networkStackId> + <networkType>CONTRAIL_EXTERNAL</networkType> + <networkUpdated>true</networkUpdated> + <tenantId>7dd5365547234ee8937416c65507d266</tenantId> + <cloudSiteId>RDM2WAGPLCP</cloudSiteId> + <msoRequest> + <requestId>1ef47428-cade-45bd-a103-0751e8b2deb0</requestId> + <serviceInstanceId></serviceInstanceId> + </msoRequest> + </rollback> + <messageId>messageId_generated</messageId> +</ns2:updateNetworkContrailResponse>""" + + String updateRollbackNetworkRequest = + """<rollbackNetworkRequest> + <networkRollback> + <networkId>MNS-25180-L-01-dmz_direct_net_1/2c88a3a9-69b9-43a7-ada6-1aca577c3641</networkId> + <neutronNetworkId>c4f4e878-cde0-4b15-ae9a-bda857759cea</neutronNetworkId> + <networkStackId/> + <networkType>CONTRAIL_EXTERNAL</networkType> + <networkUpdated>true</networkUpdated> + <tenantId>7dd5365547234ee8937416c65507d266</tenantId> + <cloudSiteId>RDM2WAGPLCP</cloudSiteId> + <msoRequest> + <requestId>1ef47428-cade-45bd-a103-0751e8b2deb0</requestId> + <serviceInstanceId/> + </msoRequest> + </networkRollback> +</rollbackNetworkRequest>""" + + String updateNetworkResponse = + """<ns2:updateNetworkContrailResponse xmlns:ns2="http://org.onap.so/network" + xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"> + <networkId>MNS-25180-L-01-dmz_direct_net_1/2c88a3a9-69b9-43a7-ada6-1aca577c3641</networkId> + <neutronNetworkId>c4f4e878-cde0-4b15-ae9a-bda857759cea</neutronNetworkId> + <networkStackId>MNS-25180-L-01-dmz_direct_net_1/2c88a3a9-69b9-43a7-ada6-1aca577c3641</networkStackId> + <networkFqdn>default-domain:MSOTest:GN_EVPN_direct_net_0_ST1</networkFqdn> + <subnetIdMap> + <entry> + <key>57e9a1ff-d14f-4071-a828-b19ae98eb2fc</key> + <value>bd8e87c6-f4e2-41b8-b0bc-9596aa00cd73</value> + </entry> + </subnetIdMap> + <rollback> + <cloudId>RDM2WAGPLCP</cloudId> + <msoRequest> + <requestId>1ef47428-cade-45bd-a103-0751e8b2deb0</requestId> + <serviceInstanceId/> + </msoRequest> + <networkUpdated>true</networkUpdated> + <networkId>MNS-25180-L-01-dmz_direct_net_1/2c88a3a9-69b9-43a7-ada6-1aca577c3641</networkId> + <networkType>CONTRAIL_EXTERNAL</networkType> + <networkUpdated>false</networkUpdated> + <neutronNetworkId>c4f4e878-cde0-4b15-ae9a-bda857759cea</neutronNetworkId> + <tenantId>7dd5365547234ee8937416c65507d266</tenantId> + </rollback> +</ns2:updateNetworkContrailResponse>""" + + String updateContrailAAIPayloadRequest = + """<l3-network xmlns="http://org.openecomp.aai.inventory/v9"> + <network-id>49c86598-f766-46f8-84f8-8d1c1b10f9b4</network-id> + <network-name>MNS-25180-L-01-dmz_direct_net_1</network-name> + <network-type>CONTRAIL_EXTERNAL</network-type> + <network-role>dmz_direct</network-role> + <network-technology>contrail</network-technology> + <neutron-network-id>c4f4e878-cde0-4b15-ae9a-bda857759cea</neutron-network-id> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <network-role-instance>0</network-role-instance> + <resource-version>l3-version</resource-version> + <orchestration-status>Active</orchestration-status> + <heat-stack-id>ST_2Bindings_6006/55288ef0-595c-47d3-819e-cf93aaac6326</heat-stack-id> + <contrail-network-fqdn>default-domain:MSOTest:GN_EVPN_direct_net_0_ST1</contrail-network-fqdn> + <physical-network-name>networkName</physical-network-name> + <is-provider-network>false</is-provider-network> + <is-shared-network>true</is-shared-network> + <is-external-network>false</is-external-network> + <subnets> + <subnet> + <subnet-id>57e9a1ff-d14f-4071-a828-b19ae98eb2fc</subnet-id> + <neutron-subnet-id>bd8e87c6-f4e2-41b8-b0bc-9596aa00cd73</neutron-subnet-id> + <gateway-address>107.239.52.1</gateway-address> + <network-start-address>107.239.52.0</network-start-address> + <cidr-mask>24</cidr-mask> + <ip-version>4</ip-version> + <orchestration-status>Active</orchestration-status> + <dhcp-enabled>true</dhcp-enabled> + <subnet-role>ECOMP</subnet-role> + <resource-version>1505857300987</resource-version> + <subnet-name>subnetName</subnet-name> + <ip-assignment-direction>true</ip-assignment-direction> + <host-routes> + <host-route> + <host-route-id>400d286b-7e44-4514-b9b3-f70f7360ff32</host-route-id> + <route-prefix>172.20.1.0/24</route-prefix> + <next-hop>10.102.200.1</next-hop> + <next-hop-type>ip-address</next-hop-type> + <resource-version>1505857300987</resource-version> + </host-route> + <host-route> + <host-route-id>6f038013-8b15-4eb8-914b-507489fbc8ee</host-route-id> + <route-prefix>10.102.0.0/16</route-prefix> + <next-hop>10.102.200.1</next-hop> + <next-hop-type>ip-address</next-hop-type> + <resource-version>1505857301151</resource-version> + </host-route> + <host-route> + <host-route-id>8811c5f8-f1ed-4fa0-a505-e1be60396e28</host-route-id> + <route-prefix>192.168.2.0/25</route-prefix> + <next-hop>10.102.200.1</next-hop> + <next-hop-type/> + <resource-version>1505857301954</resource-version> + </host-route> + </host-routes> + </subnet> + </subnets> + <segmentation-assignments> + <segmentation-id>414</segmentation-id> + <resource-version>4132176</resource-version> + </segmentation-assignments> + <segmentation-assignments> + <segmentation-id>415</segmentation-id> + <resource-version>4132176</resource-version> + </segmentation-assignments> + <ctag-assignments> + <ctag-assignment> + <vlan-id-inner>inner</vlan-id-inner> + <resource-version>ctag-version</resource-version> + <relationship-list> + <relationship> + <related-to>tenant</related-to> + <related-link>https://aai-ext1.test.com:8443/aai/v8/cloud-infrastructure/tenants/tenant/897deadc2b954a6bac6d3c197fb3525e/</related-link> + <relationship-data> + <relationship-key>tenant.tenant-id</relationship-key> + <relationship-value>897deadc2b954a6bac6d3c197fb3525e</relationship-value> + </relationship-data> + <related-to-property> + <property-key>tenant.tenant-name</property-key> + <property-value>MSOTest1</property-value> + </related-to-property> + </relationship> + <relationship> + <related-to>vpn-binding</related-to> + <related-link>https://aai-ext1.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/a290b841-f672-44dd-b9cd-6f8c20d7d8c8/</related-link> + <relationship-data> + <relationship-key>vpn-binding.vpn-id</relationship-key> + <relationship-value>a290b841-f672-44dd-b9cd-6f8c20d7d8c8</relationship-value> + </relationship-data> + <related-to-property> + <property-key>vpn-binding.vpn-name</property-key> + <property-value>oam_protected_net_6_MTN5_msotest2</property-value> + </related-to-property> + </relationship> + <relationship> + <related-to>vpn-binding</related-to> + <related-link>https://aai-ext1.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/24a4b507-853a-4a38-99aa-05fcc54be24d/</related-link> + <relationship-data> + <relationship-key>vpn-binding.vpn-id</relationship-key> + <relationship-value>24a4b507-853a-4a38-99aa-05fcc54be24d</relationship-value> + </relationship-data> + <related-to-property> + <property-key>vpn-binding.vpn-name</property-key> + <property-value>oam_protected_net_6_MTN5_msotest1</property-value> + </related-to-property> + </relationship> + </relationship-list> + </ctag-assignment> + </ctag-assignments> + <relationship-list> + <relationship> + <related-to>vpn-binding</related-to> + <related-link>https://aai-app-e2e.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/85f015d0-2e32-4c30-96d2-87a1a27f8017/</related-link> + <relationship-data> + <relationship-key>vpn-binding.vpn-id</relationship-key> + <relationship-value>85f015d0-2e32-4c30-96d2-87a1a27f8017</relationship-value> + </relationship-data> + </relationship> + <relationship> + <related-to>vpn-binding</related-to> + <related-link>https://aai-app-e2e.test.com:8443/aai/v8/network/vpn-bindings/vpn-binding/c980a6ef-3b88-49f0-9751-dbad8608d0a6/</related-link> + <relationship-data> + <relationship-key>vpn-binding.vpn-id</relationship-key> + <relationship-value>c980a6ef-3b88-49f0-9751-dbad8608d0a6</relationship-value> + </relationship-data> + </relationship> + <relationship> + <related-to>tenant</related-to> + <related-link>https://aai-app-e2e.test.com:8443/aai/v8/cloud-infrastructure/tenants/tenant/7dd5365547234ee8937416c65507d266/</related-link> + <relationship-data> + <relationship-key>tenant.tenant-id</relationship-key> + <relationship-value>7dd5365547234ee8937416c65507d266</relationship-value> + </relationship-data> + </relationship> + <relationship> + <related-to>network-policy</related-to> + <related-link>https://aai-app-e2e.test.com:8443/aai/v8/network/network-policies/network-policy/cee6d136-e378-4678-a024-2cd15f0ee0cg</related-link> + <relationship-data> + <relationship-key>network-policy.network-policy-id</relationship-key> + <relationship-value>cee6d136-e378-4678-a024-2cd15f0ee0cg</relationship-value> + </relationship-data> + </relationship> + <relationship> + <related-to>route-table-reference</related-to> + <related-link>https://aai-app-e2e.test.com:8443/aai/v8/network/route-table-references/route-table-reference/refFQDN1</related-link> + <relationship-data> + <relationship-key>route-table-reference.route-table-reference-id</relationship-key> + <relationship-value>cee6d136-e378-4678-a024-2cd15f0ee0hi</relationship-value> + </relationship-data> + </relationship> + <relationship> + <related-to>route-table-reference</related-to> + <related-link>https://aai-app-e2e.test.com:8443/aai/v8/network/route-table-references/route-table-reference/refFQDN2</related-link> + <relationship-data> + <relationship-key>route-table-reference.route-table-reference-id</relationship-key> + <relationship-value>cee6d136-e378-4678-a024-2cd15f0ee0hi</relationship-value> + </relationship-data> + </relationship> + </relationship-list> +</l3-network>""" + + + String updateContrailAAIResponse = + """<rest:RESTResponse xmlns:rest="http://schemas.activebpel.org/REST/2007/12/01/aeREST.xsd" + statusCode="200"> + <rest:headers> + <rest:header name="Date" value="Thu,10 Mar 2016 00:01:18 GMT"/> + <rest:header name="Content-Length" value="0"/> + <rest:header name="Expires" value="Thu,01 Jan 1970 00:00:00 UTC"/> + <rest:header name="X-AAI-TXID" value="mtcnjv9aaas03-20160310-00:01:18:551-132672"/> + <rest:header name="Server" value="Apache-Coyote/1.1"/> + <rest:header name="Cache-Control" value="private"/> + </rest:headers> +</rest:RESTResponse>""" + + String updateNetworkErrorResponse = + """<updateNetworkError> + <messageId>680bd458-5ec1-4a16-b77c-509022e53450</messageId><category>INTERNAL</category> + <message>400 Bad Request: The server could not comply with the request since it is either malformed or otherwise incorrect., error.type=StackValidationFailed, error.message=Property error: : resources.network.properties: : Unknown Property network_ipam_refs_data</message> + <rolledBack>true</rolledBack> + </updateNetworkError>""" + + + String networkException500 = + """<soap:Envelope xmlns:soap="http://schemas.xmlsoap.org/soap/envelope/"><soap:Body><soap:Fault><faultcode>soap:VersionMismatch</faultcode><faultstring>"http://org.onap.so/network", the namespace on the "updateNetworkContrail" element, is not a valid SOAP version.</faultstring></soap:Fault></soap:Body></soap:Envelope>""" + + String aaiResponse = + """<rest:RESTResponse xmlns:rest="http://schemas.activebpel.org/REST/2007/12/01/aeREST.xsd" + statusCode="200"> + <rest:headers> + <rest:header name="Transfer-Encoding" value="chunked"/> + <rest:header name="Date" value="Sat,30 Jan 2016 20:09:24 GMT"/> + <rest:header name="Expires" value="Thu,01 Jan 1970 00:00:00 UTC"/> + <rest:header name="X-AAI-TXID" + value="localhost-20160130-20:09:24:814-165843"/> + <rest:header name="Content-Type" value="application/xml"/> + <rest:header name="Server" value="Apache-Coyote/1.1"/> + <rest:header name="Cache-Control" value="private"/> + </rest:headers> + <rest:payload contentType="text/xml"> + <l3-network xmlns="http://org.openecomp.aai.inventory/v3"> + <network-id>bdc5efe8-404a-409b-85f6-0dcc9eebae30</network-id> + <network-name>MNS-25180-L-01-dmz_direct_net_1</network-name> + <network-type>CONTRAIL_EXTERNAL</network-type> + <network-role>HSL_direct</network-role> + <network-technology>contrail</network-technology> + <neutron-network-id>8bbd3edf-b835-4610-96a2-a5cafa029042</neutron-network-id> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <orchestration-status>active</orchestration-status> + <heat-stack-id>MNS-25180-L-01-dmz_direct_net_1/57594a56-1c92-4a38-9caa-641c1fa3d4b6</heat-stack-id> + <subnets> + <subnet> + <subnet-id>ea5f2a2c-604f-47ff-a9c5-253ee4f0ef0a</subnet-id> + <neutron-subnet-id>5a77fdc2-7789-4649-a1b9-6eaf1db1813a</neutron-subnet-id> + <gateway-address>172.16.34.1</gateway-address> + <network-start-address>172.16.34.0</network-start-address> + <cidr-mask>28</cidr-mask> + <ip-version>4</ip-version> + <orchestration-status>active</orchestration-status> + <dhcp-enabled>true</dhcp-enabled> + <relationship-list/> + </subnet> + </subnets> + <relationship-list> + <relationship> + <related-to>tenant</related-to> + <related-link>https://aai-app-e2e.test.com:8443/aai/v3/cloud-infrastructure/tenants/tenant/e81d842d3e8b45c5a59f57cd76af3aaf/</related-link> + <relationship-data> + <relationship-key>tenant.tenant-id</relationship-key> + <relationship-value>e81d842d3e8b45c5a59f57cd76af3aaf</relationship-value> + </relationship-data> + </relationship> + </relationship-list> + </l3-network> + </rest:payload> + </rest:RESTResponse>""" + + String changeAssignSDNCRequest = + """<aetgt:SDNCAdapterWorkflowRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:ns5="http://org.onap/so/request/types/v1" + xmlns:sdncadapter="http://org.onap.so/workflow/sdnc/adapter/schema/v1"> + <sdncadapter:RequestHeader> + <sdncadapter:RequestId>88f65519-9a38-4c4b-8445-9eb4a5a5af56</sdncadapter:RequestId> + <sdncadapter:SvcInstanceId>f70e927b-6087-4974-9ef8-c5e4d5847ca4</sdncadapter:SvcInstanceId> + <sdncadapter:SvcAction>changeassign</sdncadapter:SvcAction> + <sdncadapter:SvcOperation>network-topology-operation</sdncadapter:SvcOperation> + <sdncadapter:CallbackUrl>sdncCallback</sdncadapter:CallbackUrl> + </sdncadapter:RequestHeader> + <aetgt:SDNCRequestData> + <request-information> + <request-id>88f65519-9a38-4c4b-8445-9eb4a5a5af56</request-id> + <request-action>NetworkActivateRequest</request-action> + <source>VID</source> + <notification-url/> + <order-number/> + <order-version/> + </request-information> + <service-information> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <service-type>MSO-dev-service-type</service-type> + <service-instance-id>f70e927b-6087-4974-9ef8-c5e4d5847ca4</service-instance-id> + <subscriber-name>MSO_1610_dev</subscriber-name> + </service-information> + <network-request-information> + <network-id>49c86598-f766-46f8-84f8-8d1c1b10f9b4</network-id> + <network-type>CONTRAIL_EXTERNAL</network-type> + <network-name>MNS-25180-L-01-dmz_direct_net_1</network-name> + <tenant>7dd5365547234ee8937416c65507d266</tenant> + <aic-cloud-region>RDM2WAGPLCP</aic-cloud-region> + </network-request-information> + </aetgt:SDNCRequestData> +</aetgt:SDNCAdapterWorkflowRequest>""" + +String assignResponse = +"""<sdncadapterworkflow:SDNCAdapterWorkflowResponse xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1" xmlns:tag0="http://org.onap.so/workflow/sdnc/adapter/schema/v1" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <sdncadapterworkflow:response-data> <tag0:CallbackHeader> <tag0:RequestId>006927ca-f5a3-47fd-880c-dfcbcd81a093</tag0:RequestId> <tag0:ResponseCode>200</tag0:ResponseCode> <tag0:ResponseMessage>OK</tag0:ResponseMessage> </tag0:CallbackHeader> <tag0:RequestData xsi:type="xs:string"><output xmlns="com:att:sdnctl:vnf"><response-code>200</response-code><svc-request-id>006927ca-f5a3-47fd-880c-dfcbcd81a093</svc-request-id><ack-final-indicator>Y</ack-final-indicator><service-information><subscriber-name>notsurewecare</subscriber-name><service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id><service-instance-id>GN_EVPN_direct_net_0_ST_noGW</service-instance-id></service-information><network-information><network-id>8abc633a-810b-4ca5-8b3a-09511d13a2ce</network-id></network-information></output></tag0:RequestData> </sdncadapterworkflow:response-data> </sdncadapterworkflow:SDNCAdapterWorkflowResponse>""" + + String sdncRollbackRequest = + """<aetgt:SDNCAdapterWorkflowRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:ns5="http://org.onap/so/request/types/v1" + xmlns:sdncadapter="http://org.onap.so/workflow/sdnc/adapter/schema/v1"> + <sdncadapter:RequestHeader> + <sdncadapter:RequestId>88f65519-9a38-4c4b-8445-9eb4a5a5af56</sdncadapter:RequestId> + <sdncadapter:SvcInstanceId>f70e927b-6087-4974-9ef8-c5e4d5847ca4</sdncadapter:SvcInstanceId> + <sdncadapter:SvcAction>rollback</sdncadapter:SvcAction> + <sdncadapter:SvcOperation>network-topology-operation</sdncadapter:SvcOperation> + <sdncadapter:CallbackUrl>sdncCallback</sdncadapter:CallbackUrl> + </sdncadapter:RequestHeader> + <aetgt:SDNCRequestData> + <request-information> + <request-id>88f65519-9a38-4c4b-8445-9eb4a5a5af56</request-id> + <request-action>NetworkActivateRequest</request-action> + <source>VID</source> + <notification-url/> + <order-number/> + <order-version/> + </request-information> + <service-information> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <service-type>MSO-dev-service-type</service-type> + <service-instance-id>f70e927b-6087-4974-9ef8-c5e4d5847ca4</service-instance-id> + <subscriber-name>MSO_1610_dev</subscriber-name> + </service-information> + <network-request-information> + <network-id>8abc633a-810b-4ca5-8b3a-09511d13a2ce</network-id> + <network-type>CONTRAIL_EXTERNAL</network-type> + <network-name>MNS-25180-L-01-dmz_direct_net_1</network-name> + <tenant>7dd5365547234ee8937416c65507d266</tenant> + <aic-cloud-region>RDM2WAGPLCP</aic-cloud-region> + </network-request-information> + </aetgt:SDNCRequestData> +</aetgt:SDNCAdapterWorkflowRequest>""" + + String sdncAdapterWorkflowResponse = + """<aetgt:SDNCAdapterWorkflowResponse xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1"> + <sdncadapterworkflow:response-data> +<tag0:CallbackHeader xmlns:tag0="http://org.onap.so/workflow/sdnc/adapter/schema/v1"> + <tag0:RequestId>745b1b50-e39e-4685-9cc8-c71f0bde8bf0</tag0:RequestId> + <tag0:ResponseCode>200</tag0:ResponseCode> + <tag0:ResponseMessage>OK</tag0:ResponseMessage> +</tag0:CallbackHeader> + <tag0:RequestData xmlns:tag0="http://org.onap.so/workflow/sdnc/adapter/schema/v1" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xsi:type="xs:string"><output xmlns="com:att:sdnctl:vnf"><svc-request-id>00703dc8-71ff-442d-a4a8-3adc5beef6a9</svc-request-id><response-code>200</response-code><ack-final-indicator>Y</ack-final-indicator><network-information><network-id>49c86598-f766-46f8-84f8-8d1c1b10f9b4</network-id></network-information><service-information><service-type>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-type><service-instance-id>MNS-25180-L-01-dmz_direct_net_1</service-instance-id><subscriber-name>notsurewecare</subscriber-name></service-information></output></tag0:RequestData> + </sdncadapterworkflow:response-data> +</aetgt:SDNCAdapterWorkflowResponse>""" + + + String sdncAdapterWorkflowResponse_Error = + """<sdncadapterworkflow:SDNCAdapterWorkflowResponse xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1" + xmlns:tag0="http://org.onap.so/workflow/sdnc/adapter/schema/v1" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" + xmlns="com:att:sdnctl:vnf"> + <sdncadapterworkflow:response-data> + <tag0:RequestData xsi:type="xs:string"> + <output> + <response-code>400</response-code> + <response-message>Error writing to l3-netework</response-message> + <ack-final-indicator>Y</ack-final-indicator> + <svc-request-id>c79240d8-34b5-4853-af69-2021928dba00</svc-request-id> + </output> + </tag0:RequestData> + </sdncadapterworkflow:response-data> +</sdncadapterworkflow:SDNCAdapterWorkflowResponse>""" + + String expected_sdncAdapterWorkflowResponse_Error = + """<sdncadapterworkflow:SDNCAdapterWorkflowResponse xmlns="com:att:sdnctl:vnf" + xmlns:sdncadapterworkflow="http://org.onap/so/workflow/schema/v1" + xmlns:tag0="http://org.onap.so/workflow/sdnc/adapter/schema/v1" + xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> + <sdncadapterworkflow:response-data> + <tag0:RequestData xsi:type="xs:string"> + <output> + <response-code>400</response-code> + <response-message>Error writing to l3-netework</response-message> + <ack-final-indicator>Y</ack-final-indicator> + <svc-request-id>c79240d8-34b5-4853-af69-2021928dba00</svc-request-id> + </output> + </tag0:RequestData> + </sdncadapterworkflow:response-data> +</sdncadapterworkflow:SDNCAdapterWorkflowResponse>""" + + String sdncAdapterWorkflowFormattedResponse = + """<aetgt:SDNCAdapterWorkflowResponse xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns="com:att:sdnctl:vnf"> + <aetgt:response-data> + <output> + <svc-request-id>00703dc8-71ff-442d-a4a8-3adc5beef6a9</svc-request-id> + <response-code>200</response-code> + <ack-final-indicator>Y</ack-final-indicator> + <network-information> + <network-id>49c86598-f766-46f8-84f8-8d1c1b10f9b4</network-id> + </network-information> + <service-information> + <service-type>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-type> + <service-instance-id>f70e927b-6087-4974-9ef8-c5e4d5847ca4</service-instance-id> + <subscriber-name>notsurewecare</subscriber-name> + </service-information> + </output> + </aetgt:response-data> +</aetgt:SDNCAdapterWorkflowResponse>""" + +String rollbackSDNCRequest = +"""<aetgt:SDNCAdapterWorkflowRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:ns5="http://org.onap/so/request/types/v1" + xmlns:sdncadapter="http://org.onap.so/workflow/sdnc/adapter/schema/v1"> + <sdncadapter:RequestHeader> + <sdncadapter:RequestId>88f65519-9a38-4c4b-8445-9eb4a5a5af56</sdncadapter:RequestId> + <sdncadapter:SvcInstanceId>f70e927b-6087-4974-9ef8-c5e4d5847ca4</sdncadapter:SvcInstanceId> + <sdncadapter:SvcAction>rollback</sdncadapter:SvcAction> + <sdncadapter:SvcOperation>network-topology-operation</sdncadapter:SvcOperation> + <sdncadapter:CallbackUrl>sdncCallback</sdncadapter:CallbackUrl> + </sdncadapter:RequestHeader> + <aetgt:SDNCRequestData> + <request-information> + <request-id>88f65519-9a38-4c4b-8445-9eb4a5a5af56</request-id> + <request-action>CreateNetworkInstance</request-action> + <source>VID</source> + <notification-url/> + <order-number/> + <order-version/> + </request-information> + <service-information> + <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id> + <service-type>MSO-dev-service-type</service-type> + <service-instance-id>f70e927b-6087-4974-9ef8-c5e4d5847ca4</service-instance-id> + <subscriber-name>MSO_1610_dev</subscriber-name> + </service-information> + <network-information> + <network-id>8abc633a-810b-4ca5-8b3a-09511d13a2ce</network-id> + <network-type>CONTRAIL_EXTERNAL</network-type> + <onap-model-information> + <model-invariant-uuid>invariant-uuid</model-invariant-uuid> + <model-customization-uuid>customization-uuid</model-customization-uuid> + <model-uuid>uuid</model-uuid> + <model-version>version</model-version> + <model-name>CONTRAIL_EXTERNAL</model-name> + </onap-model-information> + </network-information> + <network-request-information> + <network-id>8abc633a-810b-4ca5-8b3a-09511d13a2ce</network-id> + <network-type>CONTRAIL_EXTERNAL</network-type> + <network-name>MNS-25180-L-01-dmz_direct_net_1</network-name> + <tenant>7dd5365547234ee8937416c65507d266</tenant> + <aic-cloud-region>RDM2WAGPLCP</aic-cloud-region> + </network-request-information> + </aetgt:SDNCRequestData> +</aetgt:SDNCAdapterWorkflowRequest>""" + +String rollbackNetworkRequest = +"""<NetworkAdapter:rollbackNetwork xmlns:NetworkAdapter="http://org.onap.so/network"> + <rollback> + <networkId>MNS-25180-L-01-dmz_direct_net_1/2c88a3a9-69b9-43a7-ada6-1aca577c3641</networkId> + <neutronNetworkId>c4f4e878-cde0-4b15-ae9a-bda857759cea</neutronNetworkId> + <networkStackId/> + <networkType>CONTRAIL_EXTERNAL</networkType> + <networkCreated>true</networkCreated> + <tenantId>7dd5365547234ee8937416c65507d266</tenantId> + <cloudSiteId>RDM2WAGPLCP</cloudSiteId> + <msoRequest> + <requestId>1ef47428-cade-45bd-a103-0751e8b2deb0</requestId> + <serviceInstanceId/> + </msoRequest> + </rollback> +</NetworkAdapter:rollbackNetwork>""" + +// - - - - - - - - + + + @Before + public void init() + { + MockitoAnnotations.initMocks(this) + } + + public void initializeVariables (DelegateExecution mockExecution) { + + verify(mockExecution).setVariable(Prefix + "messageId", "") + verify(mockExecution).setVariable("BasicAuthHeaderValuePO", "") + verify(mockExecution).setVariable("BasicAuthHeaderValueSDNC", "") + verify(mockExecution).setVariable(Prefix + "networkRequest", "") + verify(mockExecution).setVariable(Prefix + "networkInputs", "") + verify(mockExecution).setVariable(Prefix + "networkOutputs", "") + verify(mockExecution).setVariable(Prefix + "requestId", "") + verify(mockExecution).setVariable(Prefix + "source", "") + verify(mockExecution).setVariable(Prefix + "networkId", "") + + verify(mockExecution).setVariable(Prefix + "isPONR", false) + + // AAI query Cloud Region + verify(mockExecution).setVariable(Prefix + "queryCloudRegionRequest","") + verify(mockExecution).setVariable(Prefix + "queryCloudRegionReturnCode","") + verify(mockExecution).setVariable(Prefix + "queryCloudRegionResponse","") + verify(mockExecution).setVariable(Prefix + "cloudRegionPo","") + verify(mockExecution).setVariable(Prefix + "cloudRegionSdnc","") + verify(mockExecution).setVariable(Prefix + "isCloudRegionGood", false) + + // AAI query Id + verify(mockExecution).setVariable(Prefix + "queryIdAAIRequest","") + verify(mockExecution).setVariable(Prefix + "queryIdAAIResponse", "") + verify(mockExecution).setVariable(Prefix + "aaiIdReturnCode", "") + + // AAI query vpn binding + verify(mockExecution).setVariable(Prefix + "queryVpnBindingAAIRequest","") + verify(mockExecution).setVariable(Prefix + "queryVpnBindingAAIResponse", "") + verify(mockExecution).setVariable(Prefix + "aaiQqueryVpnBindingReturnCode", "") + verify(mockExecution).setVariable(Prefix + "vpnBindings", null) + verify(mockExecution).setVariable(Prefix + "vpnCount", 0) + verify(mockExecution).setVariable(Prefix + "routeCollection", "") + + // AAI query network policy + verify(mockExecution).setVariable(Prefix + "queryNetworkPolicyAAIRequest","") + verify(mockExecution).setVariable(Prefix + "queryNetworkPolicyAAIResponse", "") + verify(mockExecution).setVariable(Prefix + "aaiQqueryNetworkPolicyReturnCode", "") + verify(mockExecution).setVariable(Prefix + "networkPolicyUriList", null) + verify(mockExecution).setVariable(Prefix + "networkPolicyCount", 0) + verify(mockExecution).setVariable(Prefix + "networkCollection", "") + + // AAI query route table reference + verify(mockExecution).setVariable(Prefix + "queryNetworkTableRefAAIRequest","") + verify(mockExecution).setVariable(Prefix + "queryNetworkTableRefAAIResponse", "") + verify(mockExecution).setVariable(Prefix + "aaiQqueryNetworkTableRefReturnCode", "") + verify(mockExecution).setVariable(Prefix + "networkTableRefUriList", null) + verify(mockExecution).setVariable(Prefix + "networkTableRefCount", 0) + verify(mockExecution).setVariable(Prefix + "tableRefCollection", "") + + + // AAI requery Id + verify(mockExecution).setVariable(Prefix + "requeryIdAAIRequest","") + verify(mockExecution).setVariable(Prefix + "requeryIdAAIResponse", "") + verify(mockExecution).setVariable(Prefix + "aaiRequeryIdReturnCode", "") + + // AAI update contrail + verify(mockExecution).setVariable(Prefix + "updateContrailAAIUrlRequest","") + verify(mockExecution).setVariable(Prefix + "updateContrailAAIPayloadRequest","") + verify(mockExecution).setVariable(Prefix + "updateContrailAAIResponse", "") + verify(mockExecution).setVariable(Prefix + "aaiUpdateContrailReturnCode", "") + + verify(mockExecution).setVariable(Prefix + "updateNetworkRequest", "") + verify(mockExecution).setVariable(Prefix + "updateNetworkResponse", "") + verify(mockExecution).setVariable(Prefix + "rollbackNetworkRequest", "") + //verify(mockExecution).setVariable(Prefix + "rollbackNetworkResponse", "") + verify(mockExecution).setVariable(Prefix + "networkReturnCode", "") + //verify(mockExecution).setVariable(Prefix + "rollbackNetworkReturnCode", "") + verify(mockExecution).setVariable(Prefix + "isNetworkRollbackNeeded", false) + + verify(mockExecution).setVariable(Prefix + "changeAssignSDNCRequest", "") + verify(mockExecution).setVariable(Prefix + "changeAssignSDNCResponse", "") + verify(mockExecution).setVariable(Prefix + "rollbackSDNCRequest", "") + //verify(mockExecution).setVariable(Prefix + "rollbackSDNCResponse", "") + verify(mockExecution).setVariable(Prefix + "sdncReturnCode", "") + //verify(mockExecution).setVariable(Prefix + "rollbackSDNCReturnCode", "") + verify(mockExecution).setVariable(Prefix + "isSdncRollbackNeeded", false) + verify(mockExecution).setVariable(Prefix + "sdncResponseSuccess", false) + + verify(mockExecution).setVariable(Prefix + "isVnfBindingPresent", false) + verify(mockExecution).setVariable(Prefix + "Success", false) + verify(mockExecution).setVariable(Prefix + "serviceInstanceId", "") + + verify(mockExecution).setVariable(Prefix + "isException", false) + + } + + @Test + //@Ignore + public void preProcessRequest_NetworkRequest() { + + println "************ preProcessRequest_Payload ************* " + ExecutionEntity mockExecution = setupMock() + // Initialize prerequisite variables + when(mockExecution.getVariable("mso-request-id")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + when(mockExecution.getVariable("requestId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + when(mockExecution.getVariable("isBaseVfModule")).thenReturn(true) + when(mockExecution.getVariable("recipeTimeout")).thenReturn(0) + when(mockExecution.getVariable("requestAction")).thenReturn("UPDATE") + when(mockExecution.getVariable("serviceInstanceId")).thenReturn("f70e927b-6087-4974-9ef8-c5e4d5847ca4") + when(mockExecution.getVariable("vnfId")).thenReturn("") + when(mockExecution.getVariable("volumeGroupId")).thenReturn("") + when(mockExecution.getVariable("networkId")).thenReturn("49c86598-f766-46f8-84f8-8d1c1b10f9b4") + when(mockExecution.getVariable("serviceType")).thenReturn("MOG") + when(mockExecution.getVariable("networkType")).thenReturn("modelName") + when(mockExecution.getVariable("bpmnRequest")).thenReturn(jsonIncomingRequest) + when(mockExecution.getVariable("sdncVersion")).thenReturn("1610") + when(mockExecution.getVariable(Prefix + "messageId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + when(mockExecution.getVariable("mso.adapters.po.auth")).thenReturn("3141634BF7E070AA289CF2892C986C0B") + when(mockExecution.getVariable("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("mso.rollback")).thenReturn("true") + when(mockExecution.getVariable("disableRollback")).thenReturn("true") + + // preProcessRequest(DelegateExecution execution) + DoUpdateNetworkInstance DoUpdateNetworkInstance = new DoUpdateNetworkInstance() + DoUpdateNetworkInstance.preProcessRequest(mockExecution) + +// verify(mockExecution).getVariable("isDebugLogEnabled") + verify(mockExecution).setVariable("prefix", Prefix + "") + + //verify variable initialization + initializeVariables(mockExecution) + + // Authentications + verify(mockExecution).setVariable("action", "UPDATE") + verify(mockExecution).setVariable(Prefix + "networkRequest", expectedNetworkRequest) + verify(mockExecution).setVariable(Prefix + "rollbackEnabled", false) + verify(mockExecution).setVariable(Prefix + "networkInputs", expectedNetworkInputs) + verify(mockExecution).setVariable("BasicAuthHeaderValuePO", "Basic cGFzc3dvcmQ=") + verify(mockExecution).setVariable("BasicAuthHeaderValueSDNC", "Basic cGFzc3dvcmQ=") + verify(mockExecution).setVariable(Prefix + "networkOutputs", "") + + } + + @Test + //@Ignore + public void preProcessRequest_vPERNetworkRequest() { + + def networkModelInfo = """{"modelUuid": "sn5256d1-5a33-55df-13ab-12abad84e111", + "modelName": "CONTRAIL_EXTERNAL", + "modelType": "CONTRAIL_EXTERNAL", + "modelVersion": "1", + "modelCustomizationUuid": "sn5256d1-5a33-55df-13ab-12abad84e222", + "modelInvariantUuid": "sn5256d1-5a33-55df-13ab-12abad84e764" + }""".trim() + + println "************ preProcessRequest_Payload ************* " + ExecutionEntity mockExecution = setupMock() + // Initialize prerequisite variables + when(mockExecution.getVariable("msoRequestId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + when(mockExecution.getVariable("disableRollback")).thenReturn("true") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("serviceInstanceId")).thenReturn("f70e927b-6087-4974-9ef8-c5e4d5847ca4") + when(mockExecution.getVariable("networkId")).thenReturn("49c86598-f766-46f8-84f8-8d1c1b10f9b4") // optional + when(mockExecution.getVariable("networkName")).thenReturn("MNS-25180-L-01-dmz_direct_net_1") // optional + when(mockExecution.getVariable("productFamilyId")).thenReturn("a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb") + when(mockExecution.getVariable("networkModelInfo")).thenReturn("CONTRAIL_EXTERNAL") + when(mockExecution.getVariable("lcpCloudRegionId")).thenReturn("RDM2WAGPLCP") + when(mockExecution.getVariable("tenantId")).thenReturn("7dd5365547234ee8937416c65507d266") + when(mockExecution.getVariable("failIfExists")).thenReturn("false") + when(mockExecution.getVariable("networkModelInfo")).thenReturn(networkModelInfo) + when(mockExecution.getVariable("sdncVersion")).thenReturn("1702") + when(mockExecution.getVariable("action")).thenReturn("UPDATE") + when(mockExecution.getVariable("subscriptionServiceType")).thenReturn("MSO-dev-service-type") + when(mockExecution.getVariable("globalSubscriberId")).thenReturn("globalId_45678905678") + when(mockExecution.getVariable(Prefix + "messageId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + + when(mockExecution.getVariable("mso.adapters.po.auth")).thenReturn("3141634BF7E070AA289CF2892C986C0B") + when(mockExecution.getVariable("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") + + when(mockExecution.getVariable("mso.rollback")).thenReturn("true") + when(mockExecution.getVariable("mso.adapters.sdnc.endpoint")).thenReturn("http://localhost:8090/SDNCAdapter") + when(mockExecution.getVariable("mso.adapters.network.rest.endpoint")).thenReturn("http://localhost:8090/networks/NetworkAdapter") + when(mockExecution.getVariable("mso.adapters.sdnc.resource.endpoint")).thenReturn("http://localhost:8090/SDNCAdapterRpc") + + // preProcessRequest(DelegateExecution execution) + DoUpdateNetworkInstance DoUpdateNetworkInstance = new DoUpdateNetworkInstance() + DoUpdateNetworkInstance.preProcessRequest(mockExecution) + +// verify(mockExecution).getVariable("isDebugLogEnabled") + verify(mockExecution).setVariable("prefix", Prefix + "") + + //verify variable initialization + initializeVariables(mockExecution) + + // Authentications + verify(mockExecution).setVariable("action", "UPDATE") + verify(mockExecution).setVariable(Prefix + "networkRequest", expectedVperNetworkRequest) + verify(mockExecution).setVariable(Prefix + "rollbackEnabled", false) + verify(mockExecution).setVariable(Prefix + "networkInputs", expectedVperNetworkInputs) + verify(mockExecution).setVariable("BasicAuthHeaderValuePO", "Basic cGFzc3dvcmQ=") + verify(mockExecution).setVariable("BasicAuthHeaderValueSDNC", "Basic cGFzc3dvcmQ=") + verify(mockExecution).setVariable(Prefix + "networkOutputs", "") + + } + + @Test + //@Ignore + public void preProcessRequest_MissingNetworkId() { + + println "************ preProcessRequest_MissingName() ************* " + + WorkflowException missingNameWorkflowException = new WorkflowException("DoUpdateNetworkInstance", 2500, "Variable 'network-id' value/element is missing.") + + ExecutionEntity mockExecution = setupMock() + // Initialize prerequisite variables + when(mockExecution.getVariable("mso-request-id")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + when(mockExecution.getVariable("requestId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + when(mockExecution.getVariable("isBaseVfModule")).thenReturn(true) + when(mockExecution.getVariable("recipeTimeout")).thenReturn(0) + when(mockExecution.getVariable("requestAction")).thenReturn("UPDATE") + when(mockExecution.getVariable("serviceInstanceId")).thenReturn("f70e927b-6087-4974-9ef8-c5e4d5847ca4") + when(mockExecution.getVariable("vnfId")).thenReturn("") + when(mockExecution.getVariable("volumeGroupId")).thenReturn("") + //when(mockExecution.getVariable("networkId")).thenReturn("49c86598-f766-46f8-84f8-8d1c1b10f9b4") + when(mockExecution.getVariable("serviceType")).thenReturn("MOG") + when(mockExecution.getVariable("networkType")).thenReturn("modelName") + when(mockExecution.getVariable("bpmnRequest")).thenReturn(jsonIncomingRequest) + when(mockExecution.getVariable("sdncVersion")).thenReturn("1610") + + when(mockExecution.getVariable(Prefix + "messageId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + when(mockExecution.getVariable("mso.adapters.po.auth")).thenReturn("3141634BF7E070AA289CF2892C986C0B") + when(mockExecution.getVariable("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("mso.rollback")).thenReturn("true") + when(mockExecution.getVariable("disableRollback")).thenReturn("true") + + // preProcessRequest(DelegateExecution execution) + DoUpdateNetworkInstance DoUpdateNetworkInstance = new DoUpdateNetworkInstance() + try { + DoUpdateNetworkInstance.preProcessRequest(mockExecution) + } catch (Exception ex) { + println " Test End - Handle catch-throw BpmnError()! " + } + + verify(mockExecution, atLeast(1)).getVariable("isDebugLogEnabled") + verify(mockExecution, atLeast(1)).setVariable("prefix", Prefix + "") + + //verify variable initialization + initializeVariables(mockExecution) + + verify(mockExecution).setVariable("action", "UPDATE") + verify(mockExecution).setVariable(Prefix + "networkRequest", expectedNetworkRequestMissingNetworkId) + verify(mockExecution).setVariable(Prefix + "rollbackEnabled", false) + verify(mockExecution).setVariable(Prefix + "networkInputs", expectedNetworkInputsMissingNetworkId) + verify(mockExecution).setVariable(Prefix + "messageId", "88f65519-9a38-4c4b-8445-9eb4a5a5af56") + verify(mockExecution).setVariable(Prefix + "source", "VID") + verify(mockExecution).setVariable(Prefix + "networkOutputs", "") + + verify(mockExecution).setVariable(eq("WorkflowException"), refEq(missingNameWorkflowException)) + + } + + @Test + //@Ignore + public void preProcessRequest_MissingCloudRegion() { + + println "************ preProcessRequest_MissingCloudRegion() ************* " + + WorkflowException missingCloudRegionWorkflowException = new WorkflowException("DoUpdateNetworkInstance", 2500, "requestDetails has missing 'aic-cloud-region' value/element.") + + ExecutionEntity mockExecution = setupMock() + // Initialize prerequisite variables + when(mockExecution.getVariable("mso-request-id")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + when(mockExecution.getVariable("requestId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + when(mockExecution.getVariable("isBaseVfModule")).thenReturn(true) + when(mockExecution.getVariable("recipeTimeout")).thenReturn(0) + when(mockExecution.getVariable("requestAction")).thenReturn("UPDATE") + when(mockExecution.getVariable("serviceInstanceId")).thenReturn("f70e927b-6087-4974-9ef8-c5e4d5847ca4") + when(mockExecution.getVariable("vnfId")).thenReturn("") + when(mockExecution.getVariable("volumeGroupId")).thenReturn("") + when(mockExecution.getVariable("networkId")).thenReturn("networkId") + when(mockExecution.getVariable("serviceType")).thenReturn("MOG") + when(mockExecution.getVariable("networkType")).thenReturn("modelName") + + when(mockExecution.getVariable("bpmnRequest")).thenReturn(jsonIncomingRequest_MissingCloudRegion) + when(mockExecution.getVariable(Prefix + "messageId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + when(mockExecution.getVariable("mso.adapters.po.auth")).thenReturn("3141634BF7E070AA289CF2892C986C0B") + when(mockExecution.getVariable("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("mso.rollback")).thenReturn("true") + when(mockExecution.getVariable("disableRollback")).thenReturn("true") + + // preProcessRequest(DelegateExecution execution) + DoUpdateNetworkInstance DoUpdateNetworkInstance = new DoUpdateNetworkInstance() + try { + DoUpdateNetworkInstance.preProcessRequest(mockExecution) + } catch (Exception ex) { + println " Test End - Handle catch-throw BpmnError()! " + } + // check the sequence of variable invocation + //MockitoDebuggerImpl preDebugger = new MockitoDebuggerImpl() + //preDebugger.printInvocations(mockExecution) + + verify(mockExecution, atLeast(1)).getVariable("isDebugLogEnabled") + verify(mockExecution, atLeast(1)).setVariable("prefix", Prefix + "") + + //verify variable initialization + initializeVariables(mockExecution) + + verify(mockExecution).setVariable("action", "UPDATE") + verify(mockExecution).setVariable(Prefix + "networkRequest", expectedNetworkRequestMissingCloudRegion) + verify(mockExecution).setVariable(Prefix + "rollbackEnabled", false) + verify(mockExecution).setVariable(Prefix + "networkInputs", expectedNetworkInputMissingCloudRegion) + verify(mockExecution).setVariable(Prefix + "messageId", "88f65519-9a38-4c4b-8445-9eb4a5a5af56") + verify(mockExecution).setVariable(Prefix + "source", "VID") + + verify(mockExecution).setVariable(eq("WorkflowException"), refEq(missingCloudRegionWorkflowException)) + + } + + @Test + //@Ignore + public void prepareUpdateNetworkRequest() { + + println "************ prepareNetworkRequest ************* " + ExecutionEntity mockExecution = setupMock() + // Initialize prerequisite variables + when(mockExecution.getVariable(Prefix + "networkRequest")).thenReturn(expectedVperNetworkRequest) + when(mockExecution.getVariable(Prefix + "requeryIdAAIResponse")).thenReturn(queryIdAIIResponse) + when(mockExecution.getVariable(Prefix + "cloudRegionPo")).thenReturn("RDM2WAGPLCP") + when(mockExecution.getVariable(Prefix + "messageId")).thenReturn("messageId_generated") + when(mockExecution.getVariable(Prefix + "source")).thenReturn("VID") + //when(mockExecution.getVariable(Prefix + "queryVpnBindingAAIResponse")).thenReturn(queryVpnBindingAAIResponse) + when(mockExecution.getVariable(Prefix + "routeCollection")).thenReturn("<routeTargets>13979:105757</routeTargets><routeTargets>13979:105757</routeTargets>") + when(mockExecution.getVariable(Prefix + "networkCollection")).thenReturn("<policyFqdns>GN_EVPN_Test</policyFqdns>") + when(mockExecution.getVariable(Prefix + "tableRefCollection")).thenReturn("<routeTableFqdns>refFQDN1</routeTableFqdns><routeTableFqdns>refFQDN2</routeTableFqdns>") + when(mockExecution.getVariable(Prefix + "requestId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + //when(mockExecution.getVariable("URN_?????")).thenReturn("") // notificationUrl, //TODO - is this coming from URN? What variable/value to use? + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable(Prefix + "rollbackEnabled")).thenReturn("true") + + // preProcessRequest(DelegateExecution execution) + DoUpdateNetworkInstance DoUpdateNetworkInstance = new DoUpdateNetworkInstance() + DoUpdateNetworkInstance.prepareUpdateNetworkRequest(mockExecution) + + // check the sequence of variable invocation + //MockitoDebuggerImpl preDebugger = new MockitoDebuggerImpl() + //preDebugger.printInvocations(mockExecution) + + // verify set prefix = Prefix + "" + verify(mockExecution).setVariable("prefix", Prefix + "") + + verify(mockExecution).setVariable(Prefix + "updateNetworkRequest", updateNetworkRequest) + + } + + + @Test + //@Ignore + public void prepareUpdateNetworkRequest_NoPhysicalname() { + + println "************ prepareNetworkRequest ************* " + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + // Initialize prerequisite variables + when(mockExecution.getVariable(Prefix + "networkRequest")).thenReturn(NetworkRequest_noPhysicalName) + when(mockExecution.getVariable(Prefix + "requeryIdAAIResponse")).thenReturn(queryIdAIIResponse) + when(mockExecution.getVariable(Prefix + "cloudRegionPo")).thenReturn("RDM2WAGPLCP") + when(mockExecution.getVariable(Prefix + "messageId")).thenReturn("messageId_generated") + when(mockExecution.getVariable(Prefix + "source")).thenReturn("VID") + //when(mockExecution.getVariable(Prefix + "queryVpnBindingAAIResponse")).thenReturn(queryVpnBindingAAIResponse) + when(mockExecution.getVariable(Prefix + "routeCollection")).thenReturn("<routeTargets>13979:105757</routeTargets><routeTargets>13979:105757</routeTargets>") + when(mockExecution.getVariable(Prefix + "networkCollection")).thenReturn("<policyFqdns>GN_EVPN_Test</policyFqdns>") + when(mockExecution.getVariable(Prefix + "tableRefCollection")).thenReturn("") + when(mockExecution.getVariable(Prefix + "requestId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + //when(mockExecution.getVariable("URN_?????")).thenReturn("") // notificationUrl, //TODO - is this coming from URN? What variable/value to use? + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable(Prefix + "rollbackEnabled")).thenReturn("true") + + // preProcessRequest(DelegateExecution execution) + DoUpdateNetworkInstance DoUpdateNetworkInstance = new DoUpdateNetworkInstance() + DoUpdateNetworkInstance.prepareUpdateNetworkRequest(mockExecution) + + // check the sequence of variable invocation + //MockitoDebuggerImpl preDebugger = new MockitoDebuggerImpl() + //preDebugger.printInvocations(mockExecution) + + // verify set prefix = Prefix + "" + verify(mockExecution).setVariable("prefix", Prefix + "") + + verify(mockExecution).setVariable(Prefix + "updateNetworkRequest", updateNetworkRequest_noPhysicalName) + + } + + @Test + //@Ignore + public void prepareSDNCRequest() { + + println "************ prepareSDNCRequest ************* " + + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + // Initialize prerequisite variables + when(mockExecution.getVariable(Prefix + "networkRequest")).thenReturn(expectedNetworkRequest) + when(mockExecution.getVariable(Prefix + "cloudRegionSdnc")).thenReturn("RDM2WAGPLCP") + when(mockExecution.getVariable(Prefix + "serviceInstanceId")).thenReturn("f70e927b-6087-4974-9ef8-c5e4d5847ca4") + when(mockExecution.getVariable(Prefix + "queryIdAAIResponse")).thenReturn(aaiResponse) + when(mockExecution.getVariable("mso-request-id")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + when(mockExecution.getVariable("testMessageId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + when(mockExecution.getVariable("mso.workflow.sdncadapter.callback")).thenReturn("http://localhost:8090/SDNCAdapterCallback") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("GENGSI_siResourceLink")).thenReturn("https://aai-int1.test.com:8443/aai/v8/business/customers/customer/MSO_1610_dev/service-subscriptions/service-subscription/MSO-dev-service-type/service-instances/service-instance/6d4eb22a-82f1-4257-9f80-4176262cfe69/") + + + // preProcessRequest(DelegateExecution execution) + DoUpdateNetworkInstance DoUpdateNetworkInstance = new DoUpdateNetworkInstance() + DoUpdateNetworkInstance.prepareSDNCRequest(mockExecution) + + // verify set prefix = Prefix + "" + verify(mockExecution).setVariable("prefix", Prefix + "") + verify(mockExecution).setVariable(Prefix + "changeAssignSDNCRequest", changeAssignSDNCRequest) + + } + + @Test + //@Ignore + public void prepareSDNCRollbackRequest() { + + println "************ prepareSDNCRollbackRequest ************* " + + + + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + // Initialize prerequisite variables + when(mockExecution.getVariable(Prefix + "networkRequest")).thenReturn(expectedNetworkRequest) + when(mockExecution.getVariable(Prefix + "cloudRegionSdnc")).thenReturn("RDM2WAGPLCP") + when(mockExecution.getVariable(Prefix + "serviceInstanceId")).thenReturn("f70e927b-6087-4974-9ef8-c5e4d5847ca4") + when(mockExecution.getVariable(Prefix + "changeAssignSDNCResponse")).thenReturn(assignResponse) + when(mockExecution.getVariable("mso-request-id")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + when(mockExecution.getVariable("testMessageId")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + when(mockExecution.getVariable("mso.workflow.sdncadapter.callback")).thenReturn("http://localhost:8090/SDNCAdapterCallback") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("GENGSI_siResourceLink")).thenReturn("https://aai-int1.test.com:8443/aai/v8/business/customers/customer/MSO_1610_dev/service-subscriptions/service-subscription/MSO-dev-service-type/service-instances/service-instance/6d4eb22a-82f1-4257-9f80-4176262cfe69/") + + // preProcessRequest(DelegateExecution execution) + DoUpdateNetworkInstance DoUpdateNetworkInstance = new DoUpdateNetworkInstance() + DoUpdateNetworkInstance.prepareSDNCRollbackRequest(mockExecution) + + // verify set prefix = Prefix + "" + verify(mockExecution).setVariable("prefix", Prefix + "") + verify(mockExecution).setVariable(Prefix + "WorkflowException", null) + verify(mockExecution).setVariable(Prefix + "rollbackSDNCRequest", sdncRollbackRequest) + + } + + @Test + //@Ignore + public void callRESTQueryAAINetworkId_200() { + + println "************ callRESTQueryAAINetworkId ************* " + + WireMock.reset(); + MockGetNetworkByIdWithDepth("49c86598-f766-46f8-84f8-8d1c1b10f9b4", "UpdateNetworkV2/updateNetwork_queryNetworkId_AAIResponse_Success.xml", "all"); + + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable(Prefix + "networkRequest")).thenReturn(expectedNetworkRequest) + when(mockExecution.getVariable(Prefix + "messageId")).thenReturn("e8ebf6a0-f8ea-4dc0-8b99-fe98a87722d6") + when(mockExecution.getVariable("aai.endpoint")).thenReturn("http://localhost:8090") + when(mockExecution.getVariable("mso.workflow.DoUpdateNetworkInstance.aai.l3-network.uri")).thenReturn("/aai/v9/network/l3-networks/l3-network") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn('http://org.openecomp.aai.inventory/') + when(mockExecution.getVariable("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") + when(mockExecution.getVariable("aai.auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") + + // preProcessRequest(DelegateExecution execution) + DoUpdateNetworkInstance DoUpdateNetworkInstance = new DoUpdateNetworkInstance() + DoUpdateNetworkInstance.callRESTQueryAAINetworkId(mockExecution) + + // check the sequence of variable invocation + //MockitoDebuggerImpl preDebugger = new MockitoDebuggerImpl() + //preDebugger.printInvocations(mockExecution) + + verify(mockExecution).setVariable("prefix", Prefix + "") + verify(mockExecution).setVariable(Prefix + "queryIdAAIRequest", "http://localhost:8090/aai/v9/network/l3-networks/l3-network/49c86598-f766-46f8-84f8-8d1c1b10f9b4"+"?depth=all") + verify(mockExecution).setVariable(Prefix + "aaiIdReturnCode", "200") + + } + + @Test + //@Ignore + public void callRESTQueryAAICloudRegion30_200() { + + println "************ callRESTQueryAAICloudRegion30_200 ************* " + + WireMock.reset(); + MockGetNetworkCloudRegion("CreateNetworkV2/cloudRegion30_AAIResponse_Success.xml", "RDM2WAGPLCP"); + + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("prefix")).thenReturn(Prefix + "") + when(mockExecution.getVariable(Prefix + "networkInputs")).thenReturn(expectedNetworkRequest) + when(mockExecution.getVariable("aai.endpoint")).thenReturn("http://localhost:8090") + when(mockExecution.getVariable("mso.workflow.global.default.aai.version")).thenReturn("8") + when(mockExecution.getVariable("mso.workflow.default.aai.v8.cloud-region.uri")).thenReturn("/aai/v8/cloud-infrastructure/cloud-regions/cloud-region/att-aic") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn('http://org.openecomp.aai.inventory/') + when(mockExecution.getVariable("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") + when(mockExecution.getVariable("aai.auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") + + // preProcessRequest(DelegateExecution execution) + DoUpdateNetworkInstance DoUpdateNetworkInstance = new DoUpdateNetworkInstance() + DoUpdateNetworkInstance.callRESTQueryAAICloudRegion(mockExecution) + + // check the sequence of variable invocation + //MockitoDebuggerImpl preDebugger = new MockitoDebuggerImpl() + //preDebugger.printInvocations(mockExecution) + + verify(mockExecution, atLeast(1)).setVariable("prefix", Prefix + "") + verify(mockExecution, atLeast(2)).setVariable(Prefix + "queryCloudRegionReturnCode", "200") + verify(mockExecution).setVariable(Prefix + "isCloudRegionGood", true) + + } + + @Test + public void callRESTQueryAAICloudRegion25_200() { + + println "************ callRESTQueryAAICloudRegion25_200 ************* " + + WireMock.reset(); + MockGetNetworkCloudRegion("CreateNetworkV2/cloudRegion25_AAIResponse_Success.xml", "RDM2WAGPLCP"); + + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("prefix")).thenReturn(Prefix + "") + when(mockExecution.getVariable(Prefix + "networkInputs")).thenReturn(expectedNetworkRequest) + when(mockExecution.getVariable("aai.endpoint")).thenReturn("http://localhost:8090") + when(mockExecution.getVariable("mso.workflow.global.default.aai.version")).thenReturn("8") + when(mockExecution.getVariable("mso.workflow.default.aai.v8.cloud-region.uri")).thenReturn("/aai/v8/cloud-infrastructure/cloud-regions/cloud-region/att-aic") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn('http://org.openecomp.aai.inventory/') + when(mockExecution.getVariable("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") + when(mockExecution.getVariable("aai.auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") + + // preProcessRequest(DelegateExecution execution) + DoUpdateNetworkInstance DoUpdateNetworkInstance = new DoUpdateNetworkInstance() + DoUpdateNetworkInstance.callRESTQueryAAICloudRegion(mockExecution) + + // check the sequence of variable invocation + //MockitoDebuggerImpl preDebugger = new MockitoDebuggerImpl() + //preDebugger.printInvocations(mockExecution) + + verify(mockExecution, atLeast(1)).setVariable("prefix", Prefix + "") + verify(mockExecution).setVariable(Prefix + "isCloudRegionGood", true) + + } + + @Test + //@Ignore + public void callRESTQueryAAICloudRegion_NotFound() { + + println "************ callRESTQueryAAICloudRegionFake ************* " + + WireMock.reset(); + MockGetNetworkCloudRegion_404("MDTWNJ21"); + + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("prefix")).thenReturn(Prefix + "") + when(mockExecution.getVariable(Prefix + "networkInputs")).thenReturn(vnfRequestFakeRegion) + when(mockExecution.getVariable("aai.endpoint")).thenReturn("http://localhost:8090") + when(mockExecution.getVariable("mso.workflow.global.default.aai.version")).thenReturn("8") + when(mockExecution.getVariable("mso.workflow.default.aai.v8.cloud-region.uri")).thenReturn("/aai/v8/cloud-infrastructure/cloud-regions/cloud-region/att-aic") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn('http://org.openecomp.aai.inventory/') + when(mockExecution.getVariable("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") + when(mockExecution.getVariable("aai.auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") + + // preProcessRequest(DelegateExecution execution) + DoUpdateNetworkInstance DoUpdateNetworkInstance = new DoUpdateNetworkInstance() + DoUpdateNetworkInstance.callRESTQueryAAICloudRegion(mockExecution) + + // check the sequence of variable invocation + //MockitoDebuggerImpl preDebugger = new MockitoDebuggerImpl() + //preDebugger.printInvocations(mockExecution) + + verify(mockExecution, atLeast(1)).setVariable("prefix", Prefix + "") + verify(mockExecution, atLeast(1)).setVariable(Prefix + "queryCloudRegionReturnCode", "404") + verify(mockExecution).setVariable(Prefix + "cloudRegionPo", "MDTWNJ21") + verify(mockExecution).setVariable(Prefix + "cloudRegionSdnc", "AAIAIC25") + verify(mockExecution).setVariable(Prefix + "isCloudRegionGood", true) + + } + + @Test + //@Ignore + public void callRESTQueryAAINetworkVpnBinding_200() { + + println "************ callRESTQueryAAINetworkVpnBinding_200 ************* " + + WireMock.reset(); + MockGetNetworkVpnBinding("UpdateNetworkV2/updateNetwork_queryVpnBinding_AAIResponse_Success.xml", "85f015d0-2e32-4c30-96d2-87a1a27f8017"); + MockGetNetworkVpnBinding("UpdateNetworkV2/updateNetwork_queryVpnBinding_AAIResponse_Success.xml", "c980a6ef-3b88-49f0-9751-dbad8608d0a6"); + + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable(Prefix + "requeryIdAAIResponse")).thenReturn(queryIdAIIResponse) // v6 + when(mockExecution.getVariable(Prefix + "messageId")).thenReturn("e8ebf6a0-f8ea-4dc0-8b99-fe98a87722d6") + when(mockExecution.getVariable("aai.endpoint")).thenReturn("http://localhost:8090") + when(mockExecution.getVariable("mso.workflow.global.default.aai.version")).thenReturn("8") + when(mockExecution.getVariable("mso.workflow.default.aai.v8.vpn-binding.uri")).thenReturn("/aai/v8/network/vpn-bindings/vpn-binding") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn('http://org.openecomp.aai.inventory/') + when(mockExecution.getVariable("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") + when(mockExecution.getVariable("aai.auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") + + // preProcessRequest(DelegateExecution execution) + DoUpdateNetworkInstance DoUpdateNetworkInstance = new DoUpdateNetworkInstance() + DoUpdateNetworkInstance.callRESTQueryAAINetworkVpnBinding(mockExecution) + + // check the sequence of variable invocation + //MockitoDebuggerImpl preDebugger = new MockitoDebuggerImpl() + //preDebugger.printInvocations(mockExecution) + + verify(mockExecution).setVariable("prefix", Prefix + "") + verify(mockExecution).setVariable(Prefix + "vpnCount", 2) + verify(mockExecution).setVariable(Prefix + "vpnBindings", ['/aai/v8/network/vpn-bindings/vpn-binding/85f015d0-2e32-4c30-96d2-87a1a27f8017/', '/aai/v8/network/vpn-bindings/vpn-binding/c980a6ef-3b88-49f0-9751-dbad8608d0a6/']) + // the last vpnBinding value is saved. + verify(mockExecution).setVariable(Prefix + "queryVpnBindingAAIRequest", "http://localhost:8090/aai/v8/network/vpn-bindings/vpn-binding/85f015d0-2e32-4c30-96d2-87a1a27f8017?depth=all") + verify(mockExecution, atLeast(2)).setVariable(Prefix + "aaiQqueryVpnBindingReturnCode", "200") + + } + + @Test + //@Ignore + public void callRESTQueryAAINetworkVpnBindingList_200() { + + println "************ callRESTQueryAAINetworkVpnBinding_200 ************* " + + WireMock.reset(); + MockGetNetworkVpnBinding("UpdateNetworkV2/updateNetwork_queryVpnBindingList_AAIResponse_Success.xml", "85f015d0-2e32-4c30-96d2-87a1a27f8017"); + MockGetNetworkVpnBinding("UpdateNetworkV2/updateNetwork_queryVpnBindingList_AAIResponse_Success.xml", "c980a6ef-3b88-49f0-9751-dbad8608d0a6"); + + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable(Prefix + "requeryIdAAIResponse")).thenReturn(queryIdAIIResponse) // v6 + when(mockExecution.getVariable(Prefix + "messageId")).thenReturn("e8ebf6a0-f8ea-4dc0-8b99-fe98a87722d6") + when(mockExecution.getVariable("aai.endpoint")).thenReturn("http://localhost:8090") + when(mockExecution.getVariable("mso.workflow.global.default.aai.version")).thenReturn("8") + when(mockExecution.getVariable("mso.workflow.default.aai.v8.vpn-binding.uri")).thenReturn("/aai/v8/network/vpn-bindings/vpn-binding") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn('http://org.openecomp.aai.inventory/') + when(mockExecution.getVariable("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") + when(mockExecution.getVariable("aai.auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") + + // preProcessRequest(DelegateExecution execution) + DoUpdateNetworkInstance DoUpdateNetworkInstance = new DoUpdateNetworkInstance() + DoUpdateNetworkInstance.callRESTQueryAAINetworkVpnBinding(mockExecution) + + verify(mockExecution).setVariable("prefix", Prefix + "") + verify(mockExecution).setVariable(Prefix + "vpnCount", 2) + verify(mockExecution).setVariable(Prefix + "vpnBindings", ['/aai/v8/network/vpn-bindings/vpn-binding/85f015d0-2e32-4c30-96d2-87a1a27f8017/', '/aai/v8/network/vpn-bindings/vpn-binding/c980a6ef-3b88-49f0-9751-dbad8608d0a6/']) + // the last vpnBinding value is saved. + verify(mockExecution).setVariable(Prefix + "queryVpnBindingAAIRequest", "http://localhost:8090/aai/v8/network/vpn-bindings/vpn-binding/85f015d0-2e32-4c30-96d2-87a1a27f8017?depth=all") + verify(mockExecution, atLeast(2)).setVariable(Prefix + "aaiQqueryVpnBindingReturnCode", "200") + + } + + + @Test + //@Ignore + public void callRESTQueryAAINetworkVpnBinding_TestScenario01_200() { + + println "************ callRESTQueryAAINetworkVpnBinding_200 ************* " + + WireMock.reset(); + MockGetNetworkVpnBinding("UpdateNetworkV2/updateNetwork_queryVpnBinding_AAIResponse_Success.xml", "85f015d0-2e32-4c30-96d2-87a1a27f8017"); + + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable(Prefix + "requeryIdAAIResponse")).thenReturn(queryIdAIIResponseTestScenario01) + when(mockExecution.getVariable(Prefix + "messageId")).thenReturn("e8ebf6a0-f8ea-4dc0-8b99-fe98a87722d6") + when(mockExecution.getVariable("aai.endpoint")).thenReturn("http://localhost:8090") + when(mockExecution.getVariable("mso.workflow.global.default.aai.version")).thenReturn("8") + when(mockExecution.getVariable("mso.workflow.default.aai.v8.vpn-binding.uri")).thenReturn("/aai/v8/network/vpn-bindings/vpn-binding") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn('http://org.openecomp.aai.inventory/') + when(mockExecution.getVariable("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") + when(mockExecution.getVariable("aai.auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") + + // preProcessRequest(DelegateExecution execution) + DoUpdateNetworkInstance DoUpdateNetworkInstance = new DoUpdateNetworkInstance() + DoUpdateNetworkInstance.callRESTQueryAAINetworkVpnBinding(mockExecution) + + // check the sequence of variable invocation + //MockitoDebuggerImpl preDebugger = new MockitoDebuggerImpl() + //preDebugger.printInvocations(mockExecution) + + verify(mockExecution).setVariable("prefix", Prefix + "") + verify(mockExecution).setVariable(Prefix + "vpnCount", 1) + verify(mockExecution).setVariable(Prefix + "vpnBindings", ['/aai/v8/network/vpn-bindings/vpn-binding/85f015d0-2e32-4c30-96d2-87a1a27f8017/']) + // the last vpnBinding value is saved. + verify(mockExecution).setVariable(Prefix + "queryVpnBindingAAIRequest", "http://localhost:8090/aai/v8/network/vpn-bindings/vpn-binding/85f015d0-2e32-4c30-96d2-87a1a27f8017?depth=all") + verify(mockExecution).setVariable(Prefix + "aaiQqueryVpnBindingReturnCode", "200") + + } + + @Test + //@Ignore + public void callRESTQueryAAINetworkVpnBinding_200_URN_Uri() { + + println "************ callRESTQueryAAINetworkVpnBinding_200 ************* " + + WireMock.reset(); + MockGetNetworkVpnBinding("UpdateNetworkV2/updateNetwork_queryVpnBinding_AAIResponse_Success.xml", "85f015d0-2e32-4c30-96d2-87a1a27f8017"); + MockGetNetworkVpnBinding("UpdateNetworkV2/updateNetwork_queryVpnBinding_AAIResponse_Success.xml", "c980a6ef-3b88-49f0-9751-dbad8608d0a6"); + + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable(Prefix + "requeryIdAAIResponse")).thenReturn(queryIdAIIResponse) + when(mockExecution.getVariable(Prefix + "messageId")).thenReturn("e8ebf6a0-f8ea-4dc0-8b99-fe98a87722d6") + when(mockExecution.getVariable("aai.endpoint")).thenReturn("http://localhost:8090") + when(mockExecution.getVariable("mso.workflow.global.default.aai.version")).thenReturn("8") + when(mockExecution.getVariable("mso.workflow.default.aai.v8.vpn-binding.uri")).thenReturn("/aai/v8/network/vpn-bindings/vpn-binding") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn('http://org.openecomp.aai.inventory/') + when(mockExecution.getVariable("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") + when(mockExecution.getVariable("aai.auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") + + // preProcessRequest(DelegateExecution execution) + DoUpdateNetworkInstance DoUpdateNetworkInstance = new DoUpdateNetworkInstance() + DoUpdateNetworkInstance.callRESTQueryAAINetworkVpnBinding(mockExecution) + + // check the sequence of variable invocation + //MockitoDebuggerImpl preDebugger = new MockitoDebuggerImpl() + //preDebugger.printInvocations(mockExecution) + + verify(mockExecution).setVariable("prefix", Prefix + "") + verify(mockExecution).setVariable(Prefix + "vpnCount", 2) + verify(mockExecution).setVariable(Prefix + "vpnBindings", ['/aai/v8/network/vpn-bindings/vpn-binding/85f015d0-2e32-4c30-96d2-87a1a27f8017/', '/aai/v8/network/vpn-bindings/vpn-binding/c980a6ef-3b88-49f0-9751-dbad8608d0a6/']) + // the last vpnBinding value is saved. + verify(mockExecution).setVariable(Prefix + "queryVpnBindingAAIRequest", "http://localhost:8090/aai/v8/network/vpn-bindings/vpn-binding/85f015d0-2e32-4c30-96d2-87a1a27f8017?depth=all") + verify(mockExecution, atLeast(2)).setVariable(Prefix + "aaiQqueryVpnBindingReturnCode", "200") + + } + + @Test + //@Ignore + public void callRESTQueryAAINetworkVpnBinding_NotPresent() { + + println "************ callRESTQueryAAINetworkVpnBinding_NotPresent ************* " + + WireMock.reset(); + MockGetNetworkVpnBinding("UpdateNetworkV2/updateNetwork_queryVpnBinding_AAIResponse_Success.xml", "85f015d0-2e32-4c30-96d2-87a1a27f8017"); + + ExecutionEntity mockExecution = setupMock() + // Initialize prerequisite variables + + when(mockExecution.getVariable(Prefix + "requeryIdAAIResponse")).thenReturn(queryIdAIIResponseVpnNotPresent) + when(mockExecution.getVariable(Prefix + "messageId")).thenReturn("e8ebf6a0-f8ea-4dc0-8b99-fe98a87722d6") + when(mockExecution.getVariable("aai.endpoint")).thenReturn("http://localhost:8090") + when(mockExecution.getVariable("mso.workflow.global.default.aai.version")).thenReturn("8") + when(mockExecution.getVariable("mso.workflow.default.aai.v8.l3-network.uri")).thenReturn("/aai/v8/network/l3-networks/l3-network") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn('http://org.openecomp.aai.inventory/') + when(mockExecution.getVariable("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") + when(mockExecution.getVariable("aai.auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") + + // preProcessRequest(DelegateExecution execution) + DoUpdateNetworkInstance DoUpdateNetworkInstance = new DoUpdateNetworkInstance() + DoUpdateNetworkInstance.callRESTQueryAAINetworkVpnBinding(mockExecution) + + // check the sequence of variable invocation + //MockitoDebuggerImpl preDebugger = new MockitoDebuggerImpl() + //preDebugger.printInvocations(mockExecution) + + verify(mockExecution).setVariable("prefix", Prefix + "") + verify(mockExecution).setVariable(Prefix + "aaiQqueryVpnBindingReturnCode", "200") + verify(mockExecution).setVariable(Prefix + "vpnCount", 0) + verify(mockExecution).setVariable(Prefix + "queryVpnBindingAAIResponse", aaiVpnResponseStub) + + } + + @Test + //@Ignore + public void callRESTQueryAAINetworkTableRef_200() { + + println "************ callRESTQueryAAINetworkTableRef_200 ************* " + + WireMock.reset(); + MockGetNetworkTableReference("UpdateNetworkV2/updateNetwork_queryNetworkTableRef1_AAIResponse_Success.xml", "refFQDN1"); + MockGetNetworkTableReference("UpdateNetworkV2/updateNetwork_queryNetworkTableRef2_AAIResponse_Success.xml", "refFQDN2"); + + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable(Prefix + "requeryIdAAIResponse")).thenReturn(queryIdAIIResponse) + when(mockExecution.getVariable(Prefix + "messageId")).thenReturn("e8ebf6a0-f8ea-4dc0-8b99-fe98a87722d6") + when(mockExecution.getVariable("aai.endpoint")).thenReturn("http://localhost:8090") + when(mockExecution.getVariable("mso.workflow.default.aai.network-table-reference.uri")).thenReturn("") + when(mockExecution.getVariable("mso.workflow.DoUpdateNetworkInstance.aai.route-table-reference.uri")).thenReturn("/aai/v8/network/route-table-references/route-table-reference") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn('http://org.openecomp.aai.inventory/') + when(mockExecution.getVariable("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") + when(mockExecution.getVariable("aai.auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") + + // preProcessRequest(DelegateExecution execution) + DoUpdateNetworkInstance DoUpdateNetworkInstance = new DoUpdateNetworkInstance() + DoUpdateNetworkInstance.callRESTQueryAAINetworkTableRef(mockExecution) + + // check the sequence of variable invocation + //MockitoDebuggerImpl preDebugger = new MockitoDebuggerImpl() + //preDebugger.printInvocations(mockExecution) + + verify(mockExecution).setVariable("prefix", Prefix + "") + verify(mockExecution).setVariable(Prefix + "networkTableRefCount", 2) + verify(mockExecution).setVariable(Prefix + "networkTableRefUriList", ['/aai/v8/network/route-table-references/route-table-reference/refFQDN1','/aai/v8/network/route-table-references/route-table-reference/refFQDN2']) + // the last vpnBinding value is saved. + verify(mockExecution).setVariable(Prefix + "queryNetworkTableRefAAIRequest", "http://localhost:8090/aai/v8/network/route-table-references/route-table-reference/refFQDN1?depth=all") + verify(mockExecution, atLeast(2)).setVariable(Prefix + "aaiQqueryNetworkTableRefReturnCode", "200") + + } + + @Test + //@Ignore + public void callRESTQueryAAINetworkPolicy_200() { + + println "************ callRESTQueryAAINetworkPolicy_200 ************* " + + WireMock.reset(); + MockGetNetworkPolicy("UpdateNetworkV2/updateNetwork_queryNetworkPolicy_AAIResponse_Success.xml", "cee6d136-e378-4678-a024-2cd15f0ee0cg"); + + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable(Prefix + "requeryIdAAIResponse")).thenReturn(queryIdAIIResponse) + when(mockExecution.getVariable(Prefix + "messageId")).thenReturn("e8ebf6a0-f8ea-4dc0-8b99-fe98a87722d6") + when(mockExecution.getVariable("aai.endpoint")).thenReturn("http://localhost:8090") + when(mockExecution.getVariable("mso.workflow.global.default.aai.version")).thenReturn("8") + when(mockExecution.getVariable("mso.workflow.default.aai.v8.network-policy.uri")).thenReturn("/aai/v8/network/network-policies/network-policy") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn('http://org.openecomp.aai.inventory/') + when(mockExecution.getVariable("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") + when(mockExecution.getVariable("aai.auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") + + // preProcessRequest(DelegateExecution execution) + DoUpdateNetworkInstance DoUpdateNetworkInstance = new DoUpdateNetworkInstance() + DoUpdateNetworkInstance.callRESTQueryAAINetworkPolicy(mockExecution) + + // check the sequence of variable invocation + //MockitoDebuggerImpl preDebugger = new MockitoDebuggerImpl() + //preDebugger.printInvocations(mockExecution) + + verify(mockExecution).setVariable("prefix", Prefix + "") + verify(mockExecution).setVariable(Prefix + "networkPolicyCount", 1) + verify(mockExecution).setVariable(Prefix + "networkPolicyUriList", ['/aai/v8/network/network-policies/network-policy/cee6d136-e378-4678-a024-2cd15f0ee0cg']) + // the last vpnBinding value is saved. + verify(mockExecution).setVariable(Prefix + "queryNetworkPolicyAAIRequest", "http://localhost:8090/aai/v8/network/network-policies/network-policy/cee6d136-e378-4678-a024-2cd15f0ee0cg?depth=all") + verify(mockExecution).setVariable(Prefix + "aaiQqueryNetworkPolicyReturnCode", "200") + + } + + + @Test + //@Ignore + public void callRESTReQueryAAINetworkId_200() { + + println "************ callRESTReQueryAAINetworkId ************* " + + WireMock.reset(); + MockGetNetworkByIdWithDepth("49c86598-f766-46f8-84f8-8d1c1b10f9b4", "UpdateNetworkV2/updateNetwork_queryNetworkId_AAIResponse_Success.xml", "all"); + + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable(Prefix + "networkRequest")).thenReturn(expectedNetworkRequest) + when(mockExecution.getVariable(Prefix + "changeAssignSDNCResponse")).thenReturn(sdncAdapterWorkflowFormattedResponse) + when(mockExecution.getVariable(Prefix + "messageId")).thenReturn("e8ebf6a0-f8ea-4dc0-8b99-fe98a87722d6") + when(mockExecution.getVariable("aai.endpoint")).thenReturn("http://localhost:8090") + when(mockExecution.getVariable("mso.workflow.DoUpdateNetworkInstance.aai.l3-network.uri")).thenReturn("/aai/v9/network/l3-networks/l3-network") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn('http://org.openecomp.aai.inventory/') + when(mockExecution.getVariable("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") + when(mockExecution.getVariable("aai.auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") + + // preProcessRequest(DelegateExecution execution) + DoUpdateNetworkInstance DoUpdateNetworkInstance = new DoUpdateNetworkInstance() + DoUpdateNetworkInstance.callRESTReQueryAAINetworkId(mockExecution) + + // check the sequence of variable invocation + //MockitoDebuggerImpl preDebugger = new MockitoDebuggerImpl() + //preDebugger.printInvocations(mockExecution) + + verify(mockExecution).setVariable("prefix", Prefix + "") + verify(mockExecution).setVariable(Prefix + "requeryIdAAIRequest", "http://localhost:8090/aai/v9/network/l3-networks/l3-network/49c86598-f766-46f8-84f8-8d1c1b10f9b4"+"?depth=all") + verify(mockExecution).setVariable(Prefix + "aaiRequeryIdReturnCode", "200") + + } + + + @Test + //@Ignore + public void callRESTUpdateContrailAAINetworkREST_200() { + + println "************ callRESTUpdateContrailAAINetwork ************* " + + WireMock.reset(); + MockPutNetworkIdWithDepth("UpdateNetworkV2/updateNetwork_updateContrail_AAIResponse_Success.xml", "49c86598-f766-46f8-84f8-8d1c1b10f9b4", "all"); + + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable(Prefix + "networkRequest")).thenReturn(expectedNetworkRequest) + when(mockExecution.getVariable(Prefix + "changeAssignSDNCResponse")).thenReturn(sdncAdapterWorkflowFormattedResponse) + when(mockExecution.getVariable(Prefix + "requeryIdAAIResponse")).thenReturn(queryIdAIIResponse) + when(mockExecution.getVariable(Prefix + "updateNetworkResponse")).thenReturn(updateNetworkResponseREST) + when(mockExecution.getVariable(Prefix + "messageId")).thenReturn("e8ebf6a0-f8ea-4dc0-8b99-fe98a87722d6") + when(mockExecution.getVariable("aai.endpoint")).thenReturn("http://localhost:8090") + when(mockExecution.getVariable("mso.workflow.DoUpdateNetworkInstance.aai.l3-network.uri")).thenReturn("/aai/v9/network/l3-networks/l3-network") + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn('http://org.openecomp.aai.inventory/') + when(mockExecution.getVariable("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") + when(mockExecution.getVariable("aai.auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") + + // preProcessRequest(DelegateExecution execution) + DoUpdateNetworkInstance DoUpdateNetworkInstance = new DoUpdateNetworkInstance() + DoUpdateNetworkInstance.callRESTUpdateContrailAAINetwork(mockExecution) + + // check the sequence of variable invocation + //MockitoDebuggerImpl preDebugger = new MockitoDebuggerImpl() + //preDebugger.printInvocations(mockExecution) + + verify(mockExecution).setVariable("prefix", Prefix + "") + verify(mockExecution).setVariable(Prefix + "updateContrailAAIUrlRequest", "http://localhost:8090/aai/v9/network/l3-networks/l3-network/49c86598-f766-46f8-84f8-8d1c1b10f9b4"+"?depth=all") + verify(mockExecution).setVariable(Prefix + "updateContrailAAIPayloadRequest", updateContrailAAIPayloadRequest) + verify(mockExecution).setVariable(Prefix + "aaiUpdateContrailReturnCode", "200") + //verify(mockExecution).setVariable(Prefix + "updateContrailAAIResponse", updateContrailAAIResponse) + verify(mockExecution).setVariable(Prefix + "isPONR", true) + + } + + + + @Test + //@Ignore + public void validateUpdateNetworkResponseREST() { + + println "************ validateNetworkResponse ************* " + + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + // Initialize prerequisite variables + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable(Prefix + "updateNetworkResponse")).thenReturn(updateNetworkResponseREST) + when(mockExecution.getVariable(Prefix + "networkReturnCode")).thenReturn('200') + + DoUpdateNetworkInstance DoUpdateNetworkInstance = new DoUpdateNetworkInstance() + DoUpdateNetworkInstance.validateUpdateNetworkResponse(mockExecution) + + //MockitoDebuggerImpl debugger = new MockitoDebuggerImpl() + //debugger.printInvocations(mockExecution) + + verify(mockExecution).setVariable("prefix", Prefix + "") + verify(mockExecution).setVariable(Prefix + "updateNetworkResponse", updateNetworkResponseREST) + verify(mockExecution).setVariable(Prefix + "isNetworkRollbackNeeded", true) + verify(mockExecution).setVariable(Prefix + "rollbackNetworkRequest", updateRollbackNetworkRequest) + + } + + @Test + //@Ignore + public void validateUpdateNetworkResponseREST_Error() { + + println "************ validateNetworkResponse ************* " + + WorkflowException workflowException = new WorkflowException("DoUpdateNetworkInstance", 2500, "Received error from Network Adapter: JBWEB000065: HTTP Status 500.") + + ExecutionEntity mockExecution = setupMock() + // Initialize prerequisite variables + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable(Prefix + "updateNetworkResponse")).thenReturn(networkException500) + when(mockExecution.getVariable(Prefix + "networkReturnCode")).thenReturn('500') + + DoUpdateNetworkInstance DoUpdateNetworkInstance = new DoUpdateNetworkInstance() + try { + DoUpdateNetworkInstance.validateUpdateNetworkResponse(mockExecution) + } catch (Exception ex) { + println " Test End - Handle catch-throw BpmnError()! " + } + + verify(mockExecution).setVariable("prefix", Prefix + "") + verify(mockExecution, atLeast(1)).setVariable("WorkflowException", refEq(workflowException, any(WorkflowException.class))) + + } + + @Test + //@Ignore + public void validateSDNCResponse() { + + println "************ validateSDNCResponse ************* " + + ExecutionEntity mockExecution = setupMock() + // Initialize prerequisite variables + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable(Prefix + "changeAssignSDNCResponse")).thenReturn(sdncAdapterWorkflowResponse) + when(mockExecution.getVariable("prefix")).thenReturn(Prefix + "") + when(mockExecution.getVariable("SDNCA_SuccessIndicator")).thenReturn(true) + when(mockExecution.getVariable(Prefix + "sdncReturnCode")).thenReturn("200") + when(mockExecution.getVariable(Prefix + "isResponseGood")).thenReturn(true) + + DoUpdateNetworkInstance DoUpdateNetworkInstance = new DoUpdateNetworkInstance() + try { + DoUpdateNetworkInstance.validateSDNCResponse(mockExecution) + verify(mockExecution).setVariable(Prefix + "isSdncRollbackNeeded", true) + verify(mockExecution).setVariable(Prefix + "rollbackSDNCRequest", "") + + } catch (Exception ex) { + println " Graceful Exit - " + ex.getMessage() + } + //MockitoDebuggerImpl debugger = new MockitoDebuggerImpl() + //debugger.printInvocations(mockExecution) + + //verify(mockExecution).setVariable(Prefix + "isSdncRollbackNeeded", true) + + } + + @Test + //@Ignore + public void validateSDNCResponse_Error() { + + println "************ validateSDNCResponse ************* " + //ExecutionEntity mockExecution = mock(ExecutionEntity.class) + ExecutionEntity mockExecution = setupMock() + // Initialize prerequisite variables + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable(Prefix + "changeAssignSDNCResponse")).thenReturn(sdncAdapterWorkflowResponse_Error) + when(mockExecution.getVariable("prefix")).thenReturn(Prefix + "") + when(mockExecution.getVariable("SDNCA_SuccessIndicator")).thenReturn(false) + when(mockExecution.getVariable(Prefix + "sdncReturnCode")).thenReturn("200") + when(mockExecution.getVariable(Prefix + "isResponseGood")).thenReturn(true) + + DoUpdateNetworkInstance DoUpdateNetworkInstance = new DoUpdateNetworkInstance() + try { + DoUpdateNetworkInstance.validateSDNCResponse(mockExecution) + } catch (Exception ex) { + println " Graceful Exit! - " + ex.getMessage() + } + //MockitoDebuggerImpl debugger = new MockitoDebuggerImpl() + //debugger.printInvocations(mockExecution) + + // verify set prefix = Prefix + "" + //verify(mockExecution).setVariable(Prefix + "sdncResponseSuccess", false) + + } + + @Test + //@Ignore + public void prepareRollbackData() { + + println "************ prepareRollbackData() ************* " + + + + WorkflowException workflowException = new WorkflowException("DoUpdateNetworkInstance", 2500, "Received error from Network Adapter: JBWEB000065: HTTP Status 500.") + + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + // Initialize prerequisite variables + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable(Prefix + "rollbackSDNCRequest")).thenReturn(rollbackSDNCRequest) + when(mockExecution.getVariable(Prefix + "rollbackNetworkRequest")).thenReturn(rollbackNetworkRequest) + when(mockExecution.getVariable("WorkflowException")).thenReturn(workflowException) + + // preProcessRequest(DelegateExecution execution) + DoUpdateNetworkInstance DoUpdateNetworkInstance = new DoUpdateNetworkInstance() + DoUpdateNetworkInstance.prepareRollbackData(mockExecution) + +// verify(mockExecution).getVariable("isDebugLogEnabled") + verify(mockExecution).setVariable("prefix", Prefix) + + } + + @Test + //@Ignore + public void postProcessResponse() { + + println "************ postProcessResponse() ************* " + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + // Initialize prerequisite variables + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable(Prefix + "isException")).thenReturn(false) + when(mockExecution.getVariable("sdncVersion")).thenReturn("1610") + when(mockExecution.getVariable(Prefix + "rollbackSDNCRequest")).thenReturn(rollbackSDNCRequest) + when(mockExecution.getVariable(Prefix + "rollbackNetworkRequest")).thenReturn(rollbackSDNCRequest) + when(mockExecution.getVariable(Prefix + "networkRequest")).thenReturn(expectedNetworkRequest) + when(mockExecution.getVariable("mso-request-id")).thenReturn("requestId") + + // preProcessRequest(DelegateExecution execution) + DoUpdateNetworkInstance DoUpdateNetworkInstance = new DoUpdateNetworkInstance() + DoUpdateNetworkInstance.postProcessResponse(mockExecution) + +// verify(mockExecution, atLeast(3)).getVariable("isDebugLogEnabled") + verify(mockExecution, atLeast(3)).setVariable("prefix", Prefix) + verify(mockExecution).setVariable(Prefix + "Success", true) + + } + + private ExecutionEntity setupMock() { + + ProcessDefinition mockProcessDefinition = mock(ProcessDefinition.class) + when(mockProcessDefinition.getKey()).thenReturn("DoUpdateNetworkInstance") + RepositoryService mockRepositoryService = mock(RepositoryService.class) + when(mockRepositoryService.getProcessDefinition()).thenReturn(mockProcessDefinition) + when(mockRepositoryService.getProcessDefinition().getKey()).thenReturn("DoUpdateNetworkInstance") + when(mockRepositoryService.getProcessDefinition().getId()).thenReturn("100") + ProcessEngineServices mockProcessEngineServices = mock(ProcessEngineServices.class) + when(mockProcessEngineServices.getRepositoryService()).thenReturn(mockRepositoryService) + + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + // Initialize prerequisite variables + + when(mockExecution.getId()).thenReturn("100") + when(mockExecution.getProcessDefinitionId()).thenReturn("DoUpdateNetworkInstance") + when(mockExecution.getProcessInstanceId()).thenReturn("DoUpdateNetworkInstance") + when(mockExecution.getProcessEngineServices()).thenReturn(mockProcessEngineServices) + when(mockExecution.getProcessEngineServices().getRepositoryService().getProcessDefinition(mockExecution.getProcessDefinitionId())).thenReturn(mockProcessDefinition) + + return mockExecution + } + + +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateVfModuleTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateVfModuleTest.groovy new file mode 100644 index 0000000000..beaebceaf7 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateVfModuleTest.groovy @@ -0,0 +1,309 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts + +import com.github.tomakehurst.wiremock.junit.WireMockRule +import org.camunda.bpm.engine.ProcessEngineServices +import org.camunda.bpm.engine.RepositoryService +import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity +import org.camunda.bpm.engine.repository.ProcessDefinition +import org.junit.Assert +import org.junit.Before +import org.junit.Ignore +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.ArgumentCaptor +import org.mockito.Captor +import org.mockito.Mockito +import org.mockito.MockitoAnnotations +import org.mockito.runners.MockitoJUnitRunner +import org.onap.so.bpmn.common.scripts.VfModule +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.bpmn.mock.FileUtil + +import static com.github.tomakehurst.wiremock.client.WireMock.* +import static org.mockito.Mockito.* +import org.onap.so.bpmn.common.scripts.utils.XmlComparator + +@RunWith(MockitoJUnitRunner.class) +class DoUpdateVfModuleTest { + + def prefix = "DOUPVfMod_" + String doUpdateVfModuleRequest = FileUtil.readResourceFile("__files/VfModularity/DoUpdateVfModuleRequest.xml"); + String sdncChangeAssignRequest = FileUtil.readResourceFile("__files/DoUpdateVfModule/sdncChangeAssignRequest.xml") + String sdncTopologyRequest = FileUtil.readResourceFile("__files/DoUpdateVfModule/sdncTopologyRequest.xml") + + @Captor + static ArgumentCaptor<ExecutionEntity> captor = ArgumentCaptor.forClass(ExecutionEntity.class) + + @Rule + public WireMockRule wireMockRule = new WireMockRule(28090); + + @Before + public void init() { + MockitoAnnotations.initMocks(this) + } + + @Test + void testPreProcessRequest() { + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("prefix")).thenReturn(prefix) + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("DoUpdateVfModuleRequest")).thenReturn(doUpdateVfModuleRequest) + when(mockExecution.getVariable("mso.workflow.sdncadapter.callback")).thenReturn("http://localhost:28080/mso/SDNCAdapterCallbackService") + + DoUpdateVfModule obj = new DoUpdateVfModule() + obj.preProcessRequest(mockExecution) + + Mockito.verify(mockExecution, atLeastOnce()).getVariable("mso.workflow.sdncadapter.callback") + } + + + + @Test + void testPrepConfirmVolumeGroupTenant() { + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("prefix")).thenReturn(prefix) + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable(prefix + "aicCloudRegion")).thenReturn("att-aic") + when(mockExecution.getVariable("mso.workflow.default.aai.v8.cloud-region.uri")).thenReturn("/aai/v8/cloud-infrastructure/cloud-regions/cloud-region") + when(mockExecution.getVariable("mso.workflow.default.aai.cloud-region.version")).thenReturn("8") + when(mockExecution.getVariable("aai.endpoint")).thenReturn("http://localhost:28090") + when(mockExecution.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn("http://org.openecomp.aai.inventory/") + + mockData() + DoUpdateVfModule obj = new DoUpdateVfModule() + obj.prepConfirmVolumeGroupTenant(mockExecution) + + Mockito.verify(mockExecution).setVariable(prefix + "queryCloudRegionRequest", "http://localhost:28090/aai/v8/cloud-infrastructure/cloud-regions/cloud-region/att-aic") + Mockito.verify(mockExecution).setVariable(prefix + "queryCloudRegionReturnCode", "200") + Mockito.verify(mockExecution).setVariable(prefix + "cloudRegionForVolume", "AAIAIC25") + Mockito.verify(mockExecution).setVariable(prefix + "isCloudRegionGood", true) + } + + + @Test + void testPrepSDNCTopologyChg() { + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("prefix")).thenReturn(prefix) + when(mockExecution.getVariable(prefix + "requestId")).thenReturn("12345") + when(mockExecution.getVariable("testReqId")).thenReturn("testReqId") + + + when(mockExecution.getVariable(prefix + "cloudSiteId")).thenReturn("RDM2WAGPLCP") + when(mockExecution.getVariable(prefix + "vfModuleId")).thenReturn("cb510af0-5b21-4bc7-86d9-323cb396ce32") + when(mockExecution.getVariable("volumeGroupStackId")).thenReturn("12345") + when(mockExecution.getVariable(prefix + "vfModuleName")).thenReturn("PCRF::module-0-2") + when(mockExecution.getVariable(prefix + "aicCloudRegion")).thenReturn("MDTWNJ21") + when(mockExecution.getVariable(prefix + "usePreload")).thenReturn("Y") + when(mockExecution.getVariable(prefix + "vnfNameFromAAI")).thenReturn("skask-test") + + def node = new Node(null, 'vfModule') + new Node(node, 'vf-module-name', "abc") + VfModule vfModule = new VfModule(node, true); + when(mockExecution.getVariable(prefix + "vfModule")).thenReturn(vfModule) + + when(mockExecution.getVariable(prefix + "tenantId")).thenReturn("fba1bd1e195a404cacb9ce17a9b2b421") + when(mockExecution.getVariable(prefix + "vnfType")).thenReturn("vRRaas") + when(mockExecution.getVariable(prefix + "vnfName")).thenReturn("skask-test") + when(mockExecution.getVariable(prefix + "vnfId")).thenReturn("skask") + when(mockExecution.getVariable(prefix + "vfModuleModelName")).thenReturn("PCRF::module-0-2") + when(mockExecution.getVariable(prefix + "requestId")).thenReturn("testRequestId") + when(mockExecution.getVariable(prefix + "serviceId")).thenReturn("12345") + when(mockExecution.getVariable(prefix + "serviceInstanceId")).thenReturn("MIS/1604/0026/SW_INTERNET") + Map<String, String> map = new HashMap<String, String>(); + map.put("vrr_image_name", "MDT17"); + map.put("availability_zone_0", "nova"); + map.put("vrr_flavor_name", "ns.c16r32d128.v1"); + when(mockExecution.getVariable("vnfParamsMap")).thenReturn(map) + when(mockExecution.getVariable("mso-request-id")).thenReturn("testRequestId-1503410089303") + when(mockExecution.getVariable("mso.workflow.sdncadapter.callback")).thenReturn("http://localhost:8090/SDNCAdapter") + + mockData() + DoUpdateVfModule obj = new DoUpdateVfModule() + obj.prepSDNCTopologyChg(mockExecution) + + Mockito.verify(mockExecution).setVariable(prefix + "vnfName", "skask-test") + + Mockito.verify(mockExecution, times(2)).setVariable(captor.capture(), captor.capture()) + XmlComparator.assertXMLEquals(sdncChangeAssignRequest, captor.getValue()) + } + + + + @Test + void testPrepSDNCTopologyQuery() { + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("prefix")).thenReturn(prefix) + when(mockExecution.getVariable("testReqId")).thenReturn("testReqId") + when(mockExecution.getVariable(prefix + "vfModuleId")).thenReturn("12345") + when(mockExecution.getVariable(prefix + "serviceId")).thenReturn("12345") + when(mockExecution.getVariable(prefix + "serviceInstanceId")).thenReturn("MIS/1604/0026/SW_INTERNET") + when(mockExecution.getVariable("mso.workflow.sdncadapter.callback")).thenReturn("http://localhost:8090/SDNCAdapter") + + mockData() + DoUpdateVfModule obj = new DoUpdateVfModule() + obj.prepSDNCTopologyQuery(mockExecution) + + Mockito.verify(mockExecution, times(1)).setVariable(captor.capture(), captor.capture()) + XmlComparator.assertXMLEquals(sdncTopologyRequest, captor.getValue()) + } + + + + @Test + void testPrepVnfAdapterRest() { + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("prefix")).thenReturn(prefix) + when(mockExecution.getVariable(prefix + "aicCloudRegion")).thenReturn("RDM2WAGPLCP") + when(mockExecution.getVariable(prefix + "vfModuleId")).thenReturn("cb510af0-5b21-4bc7-86d9-323cb396ce32") + when(mockExecution.getVariable(prefix + "volumeGroupStackId")).thenReturn("12345") + when(mockExecution.getVariable(prefix + "vfModuleName")).thenReturn("PCRF::module-0-2") + when(mockExecution.getVariable(prefix + "tenantId")).thenReturn("fba1bd1e195a404cacb9ce17a9b2b421") + when(mockExecution.getVariable(prefix + "vnfType")).thenReturn("vRRaas") + when(mockExecution.getVariable(prefix + "vnfName")).thenReturn("skask-test") + when(mockExecution.getVariable(prefix + "vnfId")).thenReturn("skask") + when(mockExecution.getVariable(prefix + "vfModuleModelName")).thenReturn("PCRF::module-0-2") + when(mockExecution.getVariable(prefix + "vfModuleIndex")).thenReturn("index") + when(mockExecution.getVariable(prefix + "requestId")).thenReturn("testRequestId") + when(mockExecution.getVariable(prefix + "serviceId")).thenReturn("12345") + when(mockExecution.getVariable(prefix + "serviceInstanceId")).thenReturn("MIS/1604/0026/SW_INTERNET") + when(mockExecution.getVariable(prefix + "backoutOnFailure")).thenReturn("12345") + when(mockExecution.getVariable(prefix + "volumeGroupId")).thenReturn("12345") + when(mockExecution.getVariable(prefix + "asdcServiceModelVersion")).thenReturn("1.0") + when(mockExecution.getVariable(prefix + "modelCustomizationUuid")).thenReturn("cb510af0-5b21-4bc7-86d9-323cb396ced3") + when(mockExecution.getVariable(prefix + "baseVfModuleId")).thenReturn("12345") + when(mockExecution.getVariable(prefix + "baseVfModuleHeatStackId")).thenReturn("12345") + + def node = new Node(null, 'vfModule') + new Node(node, 'heat-stack-id', "abc") + VfModule vfModule = new VfModule(node, true); + when(mockExecution.getVariable(prefix + "vfModule")).thenReturn(vfModule) + + String sdncGetResponse = FileUtil.readResourceFile("__files/DoUpdateVfModule/sdncGetResponse.xml"); + when(mockExecution.getVariable(prefix + "sdncTopologyResponse")).thenReturn(sdncGetResponse) + Map<String, String> map = new HashMap<String, String>(); + map.put("vrr_image_name", "MDT17"); + map.put("availability_zone_0", "nova"); + map.put("vrr_flavor_name", "ns.c16r32d128.v1"); + when(mockExecution.getVariable(prefix + "vnfParamsMap")).thenReturn(map) + when(mockExecution.getVariable("mso-request-id")).thenReturn("testRequestId-1503410089303") + when(mockExecution.getVariable("mso.use.qualified.host")).thenReturn("true") + when(mockExecution.getVariable("mso.workflow.message.endpoint")).thenReturn("http://localhost:28080/mso/WorkflowMesssage") + + mockData() + DoUpdateVfModule obj = new DoUpdateVfModule() + obj.prepVnfAdapterRest(mockExecution) + + String createVnfARequest = FileUtil.readResourceFile("__files/DoUpdateVfModule/vnfAdapterRestRequest.xml") + Mockito.verify(mockExecution, times(1)).setVariable(captor.capture(), captor.capture()) + XmlComparator.assertXMLEquals(createVnfARequest, captor.getValue(), "messageId", "notificationUrl") + } + + + + @Test + void testPrepSDNCTopologyAct() { + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("prefix")).thenReturn(prefix) + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable(prefix + "aicCloudRegion")).thenReturn("RDM2WAGPLCP") + when(mockExecution.getVariable("testReqId")).thenReturn("testReqId") + when(mockExecution.getVariable(prefix + "vfModuleId")).thenReturn("cb510af0-5b21-4bc7-86d9-323cb396ce32") + when(mockExecution.getVariable(prefix + "tenantId")).thenReturn("fba1bd1e195a404cacb9ce17a9b2b421") + when(mockExecution.getVariable(prefix + "vnfType")).thenReturn("vRRaas") + when(mockExecution.getVariable(prefix + "vnfName")).thenReturn("skask-test") + when(mockExecution.getVariable(prefix + "vnfId")).thenReturn("skask") + when(mockExecution.getVariable(prefix + "vfModuleModelName")).thenReturn("PCRF::module-0-2") + when(mockExecution.getVariable(prefix + "requestId")).thenReturn("testRequestId") + when(mockExecution.getVariable(prefix + "serviceId")).thenReturn("12345") + when(mockExecution.getVariable(prefix + "serviceInstanceId")).thenReturn("MIS/1604/0026/SW_INTERNET") + when(mockExecution.getVariable(prefix + "usePreload")).thenReturn("Y") + when(mockExecution.getVariable(prefix + "modelCustomizationUuid")).thenReturn("cb510af0-5b21-4bc7-86d9-323cb396ced3") + + def node = new Node(null, 'vfModule') + new Node(node, 'vf-module-name', "abc") + VfModule vfModule = new VfModule(node, true); + when(mockExecution.getVariable(prefix + "vfModule")).thenReturn(vfModule) + + when(mockExecution.getVariable("mso.workflow.sdncadapter.callback")).thenReturn("http://localhost:8090/SDNCAdapter") + + mockData() + DoUpdateVfModule obj = new DoUpdateVfModule() + obj.prepSDNCTopologyAct(mockExecution) + + String createVnfARequest = FileUtil.readResourceFile("__files/DoUpdateVfModule/sdncActivateRequest.xml") + Mockito.verify(mockExecution, times(1)).setVariable(captor.capture(), captor.capture()) + XmlComparator.assertXMLEquals(createVnfARequest, captor.getValue()) + } + + @Test + void testQueryAAIVfModule() { + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("prefix")).thenReturn(prefix) + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable(prefix + "vnfId")).thenReturn("12345") + when(mockExecution.getVariable("mso.workflow.default.aai.generic-vnf.version")).thenReturn("8") + when(mockExecution.getVariable("mso.workflow.default.aai.v8.generic-vnf.uri")).thenReturn("/aai/v8/network/generic-vnfs/generic-vnf") + when(mockExecution.getVariable("aai.endpoint")).thenReturn("http://localhost:28090") + when(mockExecution.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn("http://org.openecomp.aai.inventory/") + + mockData() + DoUpdateVfModule obj = new DoUpdateVfModule() + obj.queryAAIVfModule(mockExecution) + Mockito.verify(mockExecution).setVariable(prefix + "queryAAIVfModuleResponseCode", 200) + } + + + private static ExecutionEntity setupMock() { + ProcessDefinition mockProcessDefinition = mock(ProcessDefinition.class) + when(mockProcessDefinition.getKey()).thenReturn("DoUpdateVfModule") + RepositoryService mockRepositoryService = mock(RepositoryService.class) + when(mockRepositoryService.getProcessDefinition()).thenReturn(mockProcessDefinition) + when(mockRepositoryService.getProcessDefinition().getKey()).thenReturn("DoUpdateVfModule") + when(mockRepositoryService.getProcessDefinition().getId()).thenReturn("100") + ProcessEngineServices mockProcessEngineServices = mock(ProcessEngineServices.class) + when(mockProcessEngineServices.getRepositoryService()).thenReturn(mockRepositoryService) + + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + // Initialize prerequisite variables + when(mockExecution.getId()).thenReturn("100") + when(mockExecution.getProcessDefinitionId()).thenReturn("DoUpdateVfModule") + when(mockExecution.getProcessInstanceId()).thenReturn("DoUpdateVfModule") + when(mockExecution.getProcessEngineServices()).thenReturn(mockProcessEngineServices) + when(mockExecution.getProcessEngineServices().getRepositoryService().getProcessDefinition(mockExecution.getProcessDefinitionId())).thenReturn(mockProcessDefinition) + + return mockExecution + } + + private static void mockData() { + stubFor(get(urlMatching(".*/aai/v[0-9]+/cloud-infrastructure/cloud-regions/cloud-region/att-aic")) + .willReturn(aResponse() + .withStatus(200).withHeader("Content-Type", "text/xml") + .withBodyFile("DoUpdateVfModule/cloudRegion_AAIResponse_Success.xml"))) + + stubFor(get(urlMatching(".*/aai/v[0-9]+/network/generic-vnfs/generic-vnf/12345[?]depth=1")) + .willReturn(aResponse() + .withStatus(200).withHeader("Content-Type", "text/xml") + .withBodyFile("DoUpdateVfModule/getGenericVnfResponse.xml"))) + } +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateVnfAndModulesTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateVnfAndModulesTest.groovy new file mode 100644 index 0000000000..ba54787dc1 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateVnfAndModulesTest.groovy @@ -0,0 +1,126 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts + +import com.github.tomakehurst.wiremock.junit.WireMockRule +import org.camunda.bpm.engine.ProcessEngineServices +import org.camunda.bpm.engine.RepositoryService +import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity +import org.camunda.bpm.engine.repository.ProcessDefinition +import org.junit.Assert +import org.junit.Before +import org.junit.Ignore +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.ArgumentCaptor +import org.mockito.Captor +import org.mockito.Mockito +import org.mockito.MockitoAnnotations +import org.mockito.runners.MockitoJUnitRunner +import org.onap.so.bpmn.core.WorkflowException + +import static com.github.tomakehurst.wiremock.client.WireMock.* +import static org.mockito.Mockito.* + +@RunWith(MockitoJUnitRunner.class) +class DoUpdateVnfAndModulesTest { + + @Captor + static ArgumentCaptor<ExecutionEntity> captor = ArgumentCaptor.forClass(ExecutionEntity.class) + + @Rule + public WireMockRule wireMockRule = new WireMockRule(28090); + + @Before + public void init() { + MockitoAnnotations.initMocks(this) + } + + @Test + void testQueryAAIVfModule() { + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("vnfId")).thenReturn("12345") + when(mockExecution.getVariable("mso.workflow.default.aai.generic-vnf.version")).thenReturn("8") + when(mockExecution.getVariable("mso.workflow.default.aai.v8.generic-vnf.uri")).thenReturn("/aai/v8/network/generic-vnfs/generic-vnf") + when(mockExecution.getVariable("aai.endpoint")).thenReturn("http://localhost:28090") + when(mockExecution.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn("http://org.openecomp.aai.inventory/") + + mockData() + DoUpdateVnfAndModules obj = new DoUpdateVnfAndModules() + obj.queryAAIVfModule(mockExecution) + Mockito.verify(mockExecution).setVariable("DUVAM_queryAAIVfModuleResponseCode", 200) + } + + @Test + @Ignore + void testQueryAAIVfModuleEndpointNull() { + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("vnfId")).thenReturn("12345") + when(mockExecution.getVariable("mso.workflow.default.aai.generic-vnf.version")).thenReturn("8") + when(mockExecution.getVariable("mso.workflow.default.aai.v8.generic-vnf.uri")).thenReturn("/aai/v8/network/generic-vnfs/generic-vnf") + when(mockExecution.getVariable("aai.endpoint")).thenReturn(null) + when(mockExecution.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn("http://org.openecomp.aai.inventory/") + + mockData() + try { + DoUpdateVnfAndModules obj = new DoUpdateVnfAndModules() + obj.queryAAIVfModule(mockExecution) + } catch (Exception ex) { + println " Test End - Handle catch-throw BpmnError()! " + } + Mockito.verify(mockExecution, atLeastOnce()).setVariable(captor.capture(), captor.capture()) + WorkflowException workflowException = captor.getValue() + Assert.assertEquals(1002, workflowException.getErrorCode()) + Assert.assertEquals("AAI GET Failed:org.apache.http.client.ClientProtocolException", workflowException.getErrorMessage()) + } + + private static ExecutionEntity setupMock() { + ProcessDefinition mockProcessDefinition = mock(ProcessDefinition.class) + when(mockProcessDefinition.getKey()).thenReturn("DoUpdateVfModule") + RepositoryService mockRepositoryService = mock(RepositoryService.class) + when(mockRepositoryService.getProcessDefinition()).thenReturn(mockProcessDefinition) + when(mockRepositoryService.getProcessDefinition().getKey()).thenReturn("DoUpdateVfModule") + when(mockRepositoryService.getProcessDefinition().getId()).thenReturn("100") + ProcessEngineServices mockProcessEngineServices = mock(ProcessEngineServices.class) + when(mockProcessEngineServices.getRepositoryService()).thenReturn(mockRepositoryService) + + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + // Initialize prerequisite variables + when(mockExecution.getId()).thenReturn("100") + when(mockExecution.getProcessDefinitionId()).thenReturn("DoUpdateVfModule") + when(mockExecution.getProcessInstanceId()).thenReturn("DoUpdateVfModule") + when(mockExecution.getProcessEngineServices()).thenReturn(mockProcessEngineServices) + when(mockExecution.getProcessEngineServices().getRepositoryService().getProcessDefinition(mockExecution.getProcessDefinitionId())).thenReturn(mockProcessDefinition) + + return mockExecution + } + + private static void mockData() { + stubFor(get(urlMatching(".*/aai/v[0-9]+/network/generic-vnfs/generic-vnf/12345[?]depth=1")) + .willReturn(aResponse() + .withStatus(200).withHeader("Content-Type", "text/xml") + .withBodyFile("DoUpdateVfModule/getGenericVnfResponse.xml"))) + } + +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/ScaleCustomE2EServiceInstanceTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/ScaleCustomE2EServiceInstanceTest.groovy new file mode 100644 index 0000000000..e196a62e1f --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/ScaleCustomE2EServiceInstanceTest.groovy @@ -0,0 +1,195 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2018 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts + +import static org.mockito.Mockito.* + +import org.apache.commons.lang3.* +import org.camunda.bpm.engine.ProcessEngineServices +import org.camunda.bpm.engine.RepositoryService +import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity +import org.camunda.bpm.engine.repository.ProcessDefinition +import org.camunda.bpm.engine.runtime.Execution +import org.junit.Before +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.MockitoAnnotations +import org.mockito.runners.MockitoJUnitRunner +import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.bpmn.common.scripts.ExceptionUtil + + +import com.github.tomakehurst.wiremock.junit.WireMockRule + +@RunWith(MockitoJUnitRunner.class) +class SacleCustomE2EServiceInstanceTest{ + @Rule + public WireMockRule wireMockRule = new WireMockRule(8090); + + String Prefix="CRESI_" + ExceptionUtil exceptionUtil = new ExceptionUtil() + String globalSubscriberId="test_custormer" + String requestDescription = "request description for test" + def utils = new MsoUtils() + + String jsonIncomingRequest = """{"service":{ + "serviceType":"example-service-type", + "globalSubscriberId":"test_custormer", + "resources":[ + { + "resourceInstanceId":"ns111", + "scaleType":"SCALE_NS", + "scaleNsData":{ + "scaleNsByStepsData":{ + "numberOfSteps":"4", + "aspectId":"TIC_EDGE_HW", + "scalingDirection":"UP" + } + } + }, + { + "resourceInstanceId":"ns333", + "scaleType":"SCALE_NS", + "scaleNsData":{ + "scaleNsByStepsData":{ + "numberOfSteps":"4", + "aspectId":"TIC_EDGE_HW", + "scalingDirection":"UP" + } + } + }], + "serviceInstanceName":"XXXX" + }, + "operationId":"0a5b1651-c56e-4263-8c26-c8f8a6ef72d8" + }""" + + String xmlMsoCompletionRequest = """<aetgt:MsoCompletionRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:ns="http://org.onap/so/request/types/v1" + xmlns:w1aaan0="http://org.onap/so/infra/vnf-request/v1"> + <w1aaan0:request-info> + <w1aaan0:request-id>56c881ad-6c9d-4b79-aacc-401e5640b47f</w1aaan0:request-id> + <w1aaan0:action>SCALE</w1aaan0:action> + <w1aaan0:source>null</w1aaan0:source> + </w1aaan0:request-info> + <status-message>Service Instance was scaled successfully.</status-message> + <serviceInstanceId>56c881ad-6c9d-4b79-aacc-401e5640b47f</serviceInstanceId> + <mso-bpel-name>ScaleGenericALaCarteServiceInstance</mso-bpel-name> +</aetgt:MsoCompletionRequest>""" + + String requestInfo = """<request-info xmlns="http://org.onap/so/infra/vnf-request/v1"> + <request-id>56c881ad-6c9d-4b79-aacc-401e5640b47f</request-id> + <action>SCALE</action> + <source>null</source> + </request-info>""" + + String payload ="""<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/" + xmlns:ns="http://org.onap.so/requestsdb"> + <soapenv:Header/> + <soapenv:Body> + <ns:updateServiceOperationStatus xmlns:ns="http://org.onap.so/requestsdb"> + <serviceId>56c881ad-6c9d-4b79-aacc-401e5640b47f</serviceId> + <operationId>0a5b1651-c56e-4263-8c26-c8f8a6ef72d8</operationId> + <operationType>SCALE</operationType> + <userId></userId> + <result>processing</result> + <operationContent>Prepare service scaling</operationContent> + <progress>0</progress> + <reason></reason> + </ns:updateServiceOperationStatus> + </soapenv:Body> + </soapenv:Envelope>""" + + @Before + public void init() + { + MockitoAnnotations.initMocks(this) + } + + @Test + public void preProcessRequestTest() { + println "************ preProcessRequest_Payload ************* " + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + + // Initialize prerequisite variables + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("bpmnRequest")).thenReturn(jsonIncomingRequest) + + when(mockExecution.getVariable("mso-request-id")).thenReturn("56c881ad-6c9d-4b79-aacc-401e5640b47f") + when(mockExecution.getVariable("serviceInstanceId")).thenReturn("56c881ad-6c9d-4b79-aacc-401e5640b47f") + + ScaleCustomE2EServiceInstance scaleCustomE2EServiceInstance = new ScaleCustomE2EServiceInstance() + scaleCustomE2EServiceInstance.preProcessRequest(mockExecution) + + verify(mockExecution).setVariable("globalSubscriberId", globalSubscriberId) + verify(mockExecution).setVariable("prefix", Prefix) + verify(mockExecution).setVariable("requestDescription", requestDescription) + } + + @Test + public void sendSyncResponseTest() { + println "************ sendSyncResponse ************* " + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("operationId")).thenReturn("3338b250-e995-4782-8936-081b66ba4dbf") + when(mockExecution.getVariable("serviceInstanceId")).thenReturn("56c881ad-6c9d-4b79-aacc-401e5640b47f") + + ScaleCustomE2EServiceInstance scaleCustomE2EServiceInstance = new ScaleCustomE2EServiceInstance() + scaleCustomE2EServiceInstance.sendSyncResponse(mockExecution) + + verify(mockExecution).setVariable("sentSyncResponse", true) + } + + @Test + public void prepareCompletionRequestTest() { + println "************ prepareCompletionRequest ************* " + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("msoRequestId")).thenReturn("56c881ad-6c9d-4b79-aacc-401e5640b47f") + when(mockExecution.getVariable("serviceInstanceId")).thenReturn("56c881ad-6c9d-4b79-aacc-401e5640b47f") + + ScaleCustomE2EServiceInstance scaleCustomE2EServiceInstance = new ScaleCustomE2EServiceInstance() + scaleCustomE2EServiceInstance.prepareCompletionRequest(mockExecution) + + verify(mockExecution).setVariable("CompleteMsoProcessRequest", xmlMsoCompletionRequest) + + } + + @Test + public void prepareInitServiceOperationStatusTest() { + println "************ prepareInitServiceOperationStatus ************* " + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + + when(mockExecution.getVariable("serviceInstanceId")).thenReturn("56c881ad-6c9d-4b79-aacc-401e5640b47f") + //when(mockExecution.getVariable("serviceInstanceName")).thenReturn("XXXX") + when(mockExecution.getVariable("operationId")).thenReturn("0a5b1651-c56e-4263-8c26-c8f8a6ef72d8") + + ScaleCustomE2EServiceInstance scaleCustomE2EServiceInstance = new ScaleCustomE2EServiceInstance() + scaleCustomE2EServiceInstance.prepareInitServiceOperationStatus(mockExecution) + + payload = utils.formatXml(payload) + verify(mockExecution).setVariable("CVFMI_updateServiceOperStatusRequest", payload) + } + +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/UpdateNetworkInstanceTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/UpdateNetworkInstanceTest.groovy new file mode 100644 index 0000000000..fd3c1e352f --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/UpdateNetworkInstanceTest.groovy @@ -0,0 +1,358 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts + + +import static org.mockito.Mockito.* + +import org.camunda.bpm.engine.ProcessEngineServices +import org.camunda.bpm.engine.RepositoryService +import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity +import org.camunda.bpm.engine.repository.ProcessDefinition +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.junit.Before +import org.junit.Ignore +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.MockitoAnnotations +import org.mockito.runners.MockitoJUnitRunner +import org.onap.so.bpmn.common.scripts.MsoUtils +import org.onap.so.bpmn.core.WorkflowException + +import com.github.tomakehurst.wiremock.junit.WireMockRule +import org.apache.commons.lang3.* + + +@RunWith(MockitoJUnitRunner.class) +class UpdateNetworkInstanceTest { + + @Rule + public WireMockRule wireMockRule = new WireMockRule(8090); + + String Prefix="UPDNI_" + def utils = new MsoUtils() + + String createDBRequestError = +"""<soapenv:Envelope xmlns:soapenv="http://schemas.xmlsoap.org/soap/envelope/"> + <soapenv:Header/> + <soapenv:Body> + <ns:updateInfraRequest xmlns:ns="http://org.onap.so/requestsdb"> + <requestId>88f65519-9a38-4c4b-8445-9eb4a5a5af56</requestId> + <lastModifiedBy>BPMN</lastModifiedBy> + <statusMessage>Received error from SDN-C: No availability zone available</statusMessage> + <responseBody></responseBody> + <requestStatus>FAILED</requestStatus> + <vnfOutputs><network-id></network-id><network-name></network-names></vnfOutputs> + </ns:updateInfraRequest> + </soapenv:Body> + </soapenv:Envelope>""" + + String falloutHandlerRequest = + """<aetgt:FalloutHandlerRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:ns="http://org.onap/so/request/types/v1" + xmlns:wfsch="http://org.onap/so/workflow/schema/v1"> + <request-info xmlns="http://org.onap/so/infra/vnf-request/v1"> + <request-id>b69c9054-da09-4a2c-adf5-51042b62bfac</request-id> + <action>UPDATE</action> + <source>VID</source> + </request-info> + <aetgt:WorkflowException xmlns:aetgt="http://org.onap/so/workflow/schema/v1"> + <aetgt:ErrorMessage>Received error from SDN-C: No availability zone available.</aetgt:ErrorMessage> + <aetgt:ErrorCode>5300</aetgt:ErrorCode> + </aetgt:WorkflowException> + </aetgt:FalloutHandlerRequest>""" + + String completeMsoProcessRequest = + """<aetgt:MsoCompletionRequest xmlns:aetgt="http://org.onap/so/workflow/schema/v1" + xmlns:ns="http://org.onap/so/request/types/v1" + xmlns="http://org.onap/so/infra/vnf-request/v1"> + <request-info> + <request-id>88f65519-9a38-4c4b-8445-9eb4a5a5af56</request-id> + <action>UPDATE</action> + <source>VID</source> + </request-info> + <aetgt:status-message>Network has been updated successfully.</aetgt:status-message> + <aetgt:mso-bpel-name>BPMN Network action: UPDATE</aetgt:mso-bpel-name> +</aetgt:MsoCompletionRequest>""" + + +String jsonIncomingRequest = +"""{ "requestDetails": { + "modelInfo": { + "modelType": "networkTyp", + "modelId": "modelId", + "modelNameVersionId": "modelNameVersionId", + "modelName": "CONTRAIL_EXTERNAL", + "modelVersion": "1" + }, + "cloudConfiguration": { + "lcpCloudRegionId": "RDM2WAGPLCP", + "tenantId": "7dd5365547234ee8937416c65507d266" + }, + "requestInfo": { + "instanceName": "MNS-25180-L-01-dmz_direct_net_1", + "source": "VID", + "callbackUrl": "", + "suppressRollback": true, + "productFamilyId": "a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb" + }, + "relatedInstanceList": [ + { + "relatedInstance": { + "instanceId": "f70e927b-6087-4974-9ef8-c5e4d5847ca4", + "modelInfo": { + "modelType": "serviceT", + "modelId": "modelI", + "modelNameVersionId": "modelNameVersionI", + "modelName": "modleNam", + "modelVersion": "1" + } + } + } + ], + "requestParameters": { + "userParams": [ + { + "name": "someUserParam1", + "value": "someValue1" + } + ] + } + }}""" + + @Before + public void init() + { + MockitoAnnotations.initMocks(this) + } + + public void initializeVariables(DelegateExecution mockExecution) { + + verify(mockExecution).setVariable(Prefix + "source", "") + verify(mockExecution).setVariable(Prefix + "Success", false) + + verify(mockExecution).setVariable(Prefix + "CompleteMsoProcessRequest", "") + verify(mockExecution).setVariable(Prefix + "FalloutHandlerRequest", "") + + } + + @Test + //@Ignore + public void preProcessRequest() { + + println "************ preProcessRequest() ************* " + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + // Initialize prerequisite variables + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("bpmnRequest")).thenReturn(jsonIncomingRequest) + + when(mockExecution.getVariable("mso.adapters.db.auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") + when(mockExecution.getVariable("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") + + // preProcessRequest(DelegateExecution execution) + UpdateNetworkInstance UpdateNetworkInstance = new UpdateNetworkInstance() + UpdateNetworkInstance.preProcessRequest(mockExecution) + +// verify(mockExecution).getVariable("isDebugLogEnabled") + verify(mockExecution).setVariable("prefix", Prefix) + + initializeVariables(mockExecution) + //verify(mockExecution).setVariable(Prefix + "Success", false) + + } + + + @Test + //@Ignore + public void getNetworkModelInfo() { + + println "************ getNetworkModelInfo() ************* " + + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + // Initialize prerequisite variables + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + + // preProcessRequest(DelegateExecution execution) + UpdateNetworkInstance UpdateNetworkInstance = new UpdateNetworkInstance() + UpdateNetworkInstance.getNetworkModelInfo(mockExecution) + +// verify(mockExecution).getVariable("isDebugLogEnabled") + verify(mockExecution).setVariable("prefix", Prefix) + + } + + @Test + //@Ignore + public void sendSyncResponse() { + + println "************ sendSyncResponse ************* " + + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("isAsyncProcess")).thenReturn(true) + when(mockExecution.getVariable("mso-request-id")).thenReturn("e8ebf6a0-f8ea-4dc0-8b99-fe98a87722d6") + when(mockExecution.getVariable("serviceInstanceId")).thenReturn("f70e927b-6087-4974-9ef8-c5e4d5847ca4") + + // preProcessRequest(DelegateExecution execution) + UpdateNetworkInstance UpdateNetworkInstance = new UpdateNetworkInstance() + UpdateNetworkInstance.sendSyncResponse(mockExecution) + + verify(mockExecution).setVariable("prefix", Prefix) + verify(mockExecution).setVariable("UpdateNetworkInstanceResponseCode", "202") + + } + + @Test + //@Ignore + public void sendSyncError() { + + println "************ sendSyncError ************* " + + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("isAsyncProcess")).thenReturn(true) + when(mockExecution.getVariable("mso-request-id")).thenReturn("e8ebf6a0-f8ea-4dc0-8b99-fe98a87722d6") + when(mockExecution.getVariable("serviceInstanceId")).thenReturn("f70e927b-6087-4974-9ef8-c5e4d5847ca4") + + UpdateNetworkInstance UpdateNetworkInstance = new UpdateNetworkInstance() + UpdateNetworkInstance.sendSyncError(mockExecution) + + verify(mockExecution).setVariable("prefix", Prefix) + verify(mockExecution).setVariable("UpdateNetworkInstanceResponseCode", "500") + + } + + @Test + //@Ignore + public void prepareCompletion() { + + println "************ postProcessResponse ************* " + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + // Initialize prerequisite variables + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("mso-request-id")).thenReturn("88f65519-9a38-4c4b-8445-9eb4a5a5af56") + when(mockExecution.getVariable(Prefix + "dbReturnCode")).thenReturn("200") + + // postProcessResponse(DelegateExecution execution) + UpdateNetworkInstance UpdateNetworkInstance = new UpdateNetworkInstance() + UpdateNetworkInstance.prepareCompletion(mockExecution) + + // check the sequence of variable invocation + //MockitoDebuggerImpl preDebugger = new MockitoDebuggerImpl() + //preDebugger.printInvocations(mockExecution) + + verify(mockExecution).setVariable("prefix", Prefix) + verify(mockExecution).setVariable(Prefix + "Success", true) + verify(mockExecution).setVariable(Prefix + "CompleteMsoProcessRequest", completeMsoProcessRequest) + + } + + @Test + //@Ignore + public void buildErrorResponse() { + + println "************ buildErrorResponse ************* " + + + WorkflowException sndcWorkflowException = new WorkflowException("UpdateNetworkInstance", 5300, "Received error from SDN-C: No availability zone available.") + + ExecutionEntity mockExecution = setupMock() + // Initialize prerequisite variables + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("mso-request-id")).thenReturn("b69c9054-da09-4a2c-adf5-51042b62bfac") + //when(mockExecution.getVariable("WorkflowException")).thenReturn(sndcWorkflowException) + when(mockExecution.getVariable("WorkflowException")).thenReturn(sndcWorkflowException) + + // buildErrorResponse(DelegateExecution execution) + UpdateNetworkInstance UpdateNetworkInstance = new UpdateNetworkInstance() + UpdateNetworkInstance.buildErrorResponse(mockExecution) + + verify(mockExecution, atLeast(1)).setVariable("prefix", Prefix) + verify(mockExecution).setVariable(Prefix + "FalloutHandlerRequest", falloutHandlerRequest) + + //MockitoDebuggerImpl debugger = new MockitoDebuggerImpl() + //debugger.printInvocations(mockExecution) + + } + + @Test + //@Ignore + public void postProcessResponse() { + + println "************ postProcessResponse() ************* " + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("CMSO_ResponseCode")).thenReturn("200") + + // postProcessResponse(DelegateExecution execution) + UpdateNetworkInstance UpdateNetworkInstance = new UpdateNetworkInstance() + UpdateNetworkInstance.postProcessResponse(mockExecution) + + //verify(mockExecution).getVariable("isDebugLogEnabled") + //verify(mockExecution).setVariable("prefix", Prefix) + + verify(mockExecution).setVariable(Prefix + "Success", true) + + } + + @Test + //@Ignore + public void processRollbackData() { + + println "************ callDBCatalog() ************* " + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + // Initialize prerequisite variables + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + + // preProcessRequest(DelegateExecution execution) + UpdateNetworkInstance UpdateNetworkInstance = new UpdateNetworkInstance() + UpdateNetworkInstance.processRollbackData(mockExecution) + +// verify(mockExecution).getVariable("isDebugLogEnabled") + verify(mockExecution).setVariable("prefix", Prefix) + + } + + private ExecutionEntity setupMock() { + + ProcessDefinition mockProcessDefinition = mock(ProcessDefinition.class) + when(mockProcessDefinition.getKey()).thenReturn("UpdateNetworkInstance") + RepositoryService mockRepositoryService = mock(RepositoryService.class) + when(mockRepositoryService.getProcessDefinition()).thenReturn(mockProcessDefinition) + when(mockRepositoryService.getProcessDefinition().getKey()).thenReturn("UpdateNetworkInstance") + when(mockRepositoryService.getProcessDefinition().getId()).thenReturn("100") + ProcessEngineServices mockProcessEngineServices = mock(ProcessEngineServices.class) + when(mockProcessEngineServices.getRepositoryService()).thenReturn(mockRepositoryService) + + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + // Initialize prerequisite variables + + when(mockExecution.getId()).thenReturn("100") + when(mockExecution.getProcessDefinitionId()).thenReturn("UpdateNetworkInstance") + when(mockExecution.getProcessInstanceId()).thenReturn("UpdateNetworkInstance") + when(mockExecution.getProcessEngineServices()).thenReturn(mockProcessEngineServices) + when(mockExecution.getProcessEngineServices().getRepositoryService().getProcessDefinition(mockExecution.getProcessDefinitionId())).thenReturn(mockProcessDefinition) + + return mockExecution + } + +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/UpdateVfModuleVolumeInfraV1Test.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/UpdateVfModuleVolumeInfraV1Test.groovy new file mode 100644 index 0000000000..620b0b787d --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/infrastructure/scripts/UpdateVfModuleVolumeInfraV1Test.groovy @@ -0,0 +1,134 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.scripts + +import com.github.tomakehurst.wiremock.junit.WireMockRule +import org.camunda.bpm.engine.ProcessEngineServices +import org.camunda.bpm.engine.RepositoryService +import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity +import org.camunda.bpm.engine.repository.ProcessDefinition +import org.junit.Assert +import org.junit.Before +import org.junit.Ignore +import org.junit.Rule +import org.junit.Test +import org.junit.runner.RunWith +import org.mockito.ArgumentCaptor +import org.mockito.Captor +import org.mockito.Mockito +import org.mockito.MockitoAnnotations +import org.mockito.runners.MockitoJUnitRunner +import org.onap.so.bpmn.common.scripts.utils.XmlComparator +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.bpmn.mock.FileUtil + +import static com.github.tomakehurst.wiremock.client.WireMock.* +import static org.mockito.Mockito.* + +@RunWith(MockitoJUnitRunner.class) +class UpdateVfModuleVolumeInfraV1Test { + + def prefix = "UPDVfModVol_" + @Captor + static ArgumentCaptor<ExecutionEntity> captor = ArgumentCaptor.forClass(ExecutionEntity.class) + + @Rule + public WireMockRule wireMockRule = new WireMockRule(28090); + + @Before + public void init() + { + MockitoAnnotations.initMocks(this) + } + + @Test + void testQueryAAIForVfModule() { + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("prefix")).thenReturn(prefix) + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable("UPDVfModVol_relatedVfModuleLink")).thenReturn("/aai/v8/network/generic-vnfs/generic-vnf/12345/vf-modules/vf-module/12345") + when(mockExecution.getVariable("aai.endpoint")).thenReturn("http://localhost:28090") + when(mockExecution.getVariable("mso.msoKey")).thenReturn("07a7159d3bf51a0e53be7a8f89699be7") + when(mockExecution.getVariable("aai.auth")).thenReturn("757A94191D685FD2092AC1490730A4FC") + + mockData() + UpdateVfModuleVolumeInfraV1 obj = new UpdateVfModuleVolumeInfraV1() + obj.queryAAIForVfModule(mockExecution, "true") + + Mockito.verify(mockExecution, atLeastOnce()).setVariable("UPDVfModVol_personaModelId", "ff5256d2-5a33-55df-13ab-12abad84e7ff") + } + + @Test + void testPrepVnfAdapterRest() { + ExecutionEntity mockExecution = setupMock() + when(mockExecution.getVariable("prefix")).thenReturn(prefix) + when(mockExecution.getVariable("isDebugLogEnabled")).thenReturn("true") + when(mockExecution.getVariable(prefix + "aicCloudRegion")).thenReturn("RDM2WAGPLCP") + when(mockExecution.getVariable(prefix + "tenantId")).thenReturn("") + when(mockExecution.getVariable(prefix + "aaiVolumeGroupResponse")).thenReturn(FileUtil.readResourceFile("__files/UpdateVfModuleVolumeInfraV1/queryVolumeId_AAIResponse_Success.xml")) + when(mockExecution.getVariable(prefix + "vnfType")).thenReturn("vnf1") + when(mockExecution.getVariable(prefix + "vnfVersion")).thenReturn("1") + when(mockExecution.getVariable(prefix + "AAIQueryGenericVfnResponse")).thenReturn(FileUtil.readResourceFile("__files/GenericFlows/getGenericVnfByNameResponse.xml")) + when(mockExecution.getVariable(prefix + "requestId")).thenReturn("12345") + when(mockExecution.getVariable(prefix + "serviceId")).thenReturn("12345") + when(mockExecution.getVariable("mso-request-id")).thenReturn("12345") + when(mockExecution.getVariable("mso.workflow.message.endpoint")).thenReturn('http://localhost:28080/mso/WorkflowMessage') + when(mockExecution.getVariable("mso.use.qualified.host")).thenReturn("true") + + mockData() + UpdateVfModuleVolumeInfraV1 obj = new UpdateVfModuleVolumeInfraV1() + obj.prepVnfAdapterRest(mockExecution, "true") + + Mockito.verify(mockExecution, times(1)).setVariable(captor.capture(), captor.capture()) + def updateVolumeGroupRequest = captor.getValue() + String expectedValue = FileUtil.readResourceFile("__files/UpdateVfModuleVolumeInfraV1/updateVolumeGroupRequest.xml") + XmlComparator.assertXMLEquals(expectedValue, updateVolumeGroupRequest, "messageId", "notificationUrl") + } + + + private static ExecutionEntity setupMock() { + ProcessDefinition mockProcessDefinition = mock(ProcessDefinition.class) + when(mockProcessDefinition.getKey()).thenReturn("UpdateVfModuleVolumeInfraV1") + RepositoryService mockRepositoryService = mock(RepositoryService.class) + when(mockRepositoryService.getProcessDefinition()).thenReturn(mockProcessDefinition) + when(mockRepositoryService.getProcessDefinition().getKey()).thenReturn("UpdateVfModuleVolumeInfraV1") + when(mockRepositoryService.getProcessDefinition().getId()).thenReturn("100") + ProcessEngineServices mockProcessEngineServices = mock(ProcessEngineServices.class) + when(mockProcessEngineServices.getRepositoryService()).thenReturn(mockRepositoryService) + + ExecutionEntity mockExecution = mock(ExecutionEntity.class) + // Initialize prerequisite variables + when(mockExecution.getId()).thenReturn("100") + when(mockExecution.getProcessDefinitionId()).thenReturn("UpdateVfModuleVolumeInfraV1") + when(mockExecution.getProcessInstanceId()).thenReturn("UpdateVfModuleVolumeInfraV1") + when(mockExecution.getProcessEngineServices()).thenReturn(mockProcessEngineServices) + when(mockExecution.getProcessEngineServices().getRepositoryService().getProcessDefinition(mockExecution.getProcessDefinitionId())).thenReturn(mockProcessDefinition) + + return mockExecution + } + + private static void mockData() { + stubFor(get(urlMatching(".*/aai/v[0-9]+/network/generic-vnfs/generic-vnf/12345/vf-modules/vf-module/.*")) + .willReturn(aResponse() + .withStatus(200).withHeader("Content-Type", "text/xml") + .withBodyFile("UpdateVfModuleVolumeInfraV1/vf_module_aai_response.xml"))) + } +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/vcpe/scripts/CreateVcpeResCustServiceTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/vcpe/scripts/CreateVcpeResCustServiceTest.groovy new file mode 100644 index 0000000000..523c791efc --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/vcpe/scripts/CreateVcpeResCustServiceTest.groovy @@ -0,0 +1,1269 @@ +/* + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.so.bpmn.vcpe.scripts + + +import org.camunda.bpm.engine.ProcessEngineServices +import org.camunda.bpm.engine.RepositoryService +import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity +import org.camunda.bpm.engine.repository.ProcessDefinition +import org.junit.Before +import org.junit.BeforeClass +import org.junit.Rule +import org.junit.Test +import org.junit.Ignore +import org.mockito.MockitoAnnotations +import org.camunda.bpm.engine.delegate.BpmnError +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.bpmn.core.domain.HomingSolution +import org.onap.so.bpmn.mock.FileUtil + +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse +import static com.github.tomakehurst.wiremock.client.WireMock.get +import static com.github.tomakehurst.wiremock.client.WireMock.patch +import static com.github.tomakehurst.wiremock.client.WireMock.put +import static com.github.tomakehurst.wiremock.client.WireMock.stubFor +import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching +import static org.junit.Assert.*; +import static org.mockito.Mockito.* +import static org.onap.so.bpmn.mock.StubResponseAAI.MockGetAllottedResource +import org.onap.so.bpmn.core.domain.ServiceDecomposition +import org.onap.so.bpmn.core.domain.VnfResource +import org.onap.so.bpmn.core.domain.AllottedResource +import org.onap.so.bpmn.core.domain.ModelInfo +import org.onap.so.bpmn.core.domain.HomingSolution +import org.onap.so.bpmn.core.RollbackData +import org.onap.so.bpmn.vcpe.scripts.MapGetter +import org.onap.so.bpmn.vcpe.scripts.MapSetter + +import com.github.tomakehurst.wiremock.junit.WireMockRule + +class CreateVcpeResCustServiceTest extends GroovyTestBase { + + private static String request + + @Rule + public WireMockRule wireMockRule = new WireMockRule(PORT) + + String Prefix = "CVRCS_" + String RbType = "DCRENI_" + + @BeforeClass + public static void setUpBeforeClass() { + request = FileUtil.readResourceFile("__files/VCPE/CreateVcpeResCustService/request.json") + } + + @Before + public void init() + { + MockitoAnnotations.initMocks(this) + } + + public CreateVcpeResCustServiceTest() { + super("CreateVcpeResCustService") + } + + + // ***** preProcessRequest ***** + + @Test + @Ignore // 1802 merge + public void preProcessRequest() { + ExecutionEntity mex = setupMock() + def map = setupMap(mex) + initPreProcess(mex) + + CreateVcpeResCustService CreateVcpeResCustService = new CreateVcpeResCustService() + CreateVcpeResCustService.preProcessRequest(mex) + + verify(mex).getVariable(DBGFLAG) + verify(mex).setVariable("prefix", Prefix) + verify(mex).setVariable("aaiDistDelay", "aaidelay") + verify(mex).setVariable("createVcpeServiceRequest", request) + verify(mex).setVariable("msoRequestId", "mri") + assertEquals("sii", map.get("serviceInstanceId")) + verify(mex).setVariable("requestAction", "ra") + verify(mex).setVariable("source", "VID") + verify(mex).setVariable("globalSubscriberId", CUST) + verify(mex).setVariable("globalCustomerId", CUST) + verify(mex).setVariable("subscriptionServiceType", SVC) + verify(mex).setVariable("disableRollback", "false") + verify(mex).setVariable("productFamilyId", "a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb") + assertTrue(map.containsKey("subscriberInfo")) + + verify(mex).setVariable("brgWanMacAddress", "brgmac") + verify(mex).setVariable("customerLocation", ["customerLatitude":"32.897480", "customerLongitude":"-97.040443", "customerName":"some_company"]) + verify(mex).setVariable("homingService", "sniro") + assertTrue(map.containsKey("serviceInputParams")) + assertTrue(map.containsKey(Prefix+"requestInfo")) + + def reqinfo = map.get(Prefix+"requestInfo") + assertTrue(reqinfo.indexOf("<request-id>mri</") >= 0) + assertTrue(reqinfo.indexOf("<source>VID</") >= 0) + } + + @Test + // @Ignore + public void preProcessRequest_MissingAaiDistDelay() { + ExecutionEntity mex = setupMock() + def map = setupMap(mex) + initPreProcess(mex) + + when(mex.getVariable("URN_mso_workflow_aai_distribution_delay")).thenReturn(null) + + CreateVcpeResCustService CreateVcpeResCustService = new CreateVcpeResCustService() + + assertTrue(doBpmnError( { _ -> CreateVcpeResCustService.preProcessRequest(mex) })) + } + + @Test + @Ignore // 1802 merge + public void preProcessRequest_EmptyParts() { + ExecutionEntity mex = setupMock() + def map = setupMap(mex) + initPreProcess(mex) + + def req = request + .replace('"source"', '"sourceXXX"') + .replace('"BRG_WAN_MAC_Address"', '"BRG_WAN_MAC_AddressXXX"') + .replace('"Customer_Location"', '"Customer_LocationXXX"') + + when(mex.getVariable("bpmnRequest")).thenReturn(req) + when(mex.getVariable("serviceInstanceId")).thenReturn(null) + + CreateVcpeResCustService CreateVcpeResCustService = new CreateVcpeResCustService() + CreateVcpeResCustService.preProcessRequest(mex) + + verify(mex).getVariable(DBGFLAG) + verify(mex).setVariable("prefix", Prefix) + verify(mex).setVariable("createVcpeServiceRequest", req) + verify(mex).setVariable("msoRequestId", "mri") + assertNotNull(map.get("serviceInstanceId")) + assertFalse(map.get("serviceInstanceId").isEmpty()) + verify(mex).setVariable("requestAction", "ra") + verify(mex).setVariable("source", "VID") + verify(mex).setVariable("globalSubscriberId", CUST) + verify(mex).setVariable("globalCustomerId", CUST) + verify(mex).setVariable("subscriptionServiceType", SVC) + verify(mex).setVariable("disableRollback", "false") + verify(mex).setVariable("productFamilyId", "a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb") + assertTrue(map.containsKey("subscriberInfo")) + + assertEquals("", map.get("brgWanMacAddress")) + assertEquals("", map.get("customerLocation")) + assertEquals("oof", map.get("homingService")) + assertTrue(map.containsKey("serviceInputParams")) + assertTrue(map.containsKey(Prefix+"requestInfo")) + + def reqinfo = map.get(Prefix+"requestInfo") + println reqinfo + assertTrue(reqinfo.indexOf("<request-id>mri</") >= 0) + assertTrue(reqinfo.indexOf("<source>VID</") >= 0) + } + + @Test + // @Ignore + public void preProcessRequest_MissingSubscriberId() { + ExecutionEntity mex = setupMock() + def map = setupMap(mex) + initPreProcess(mex) + + def req = request + .replace('"globalSubscriberId"', '"globalSubscriberIdXXX"') + + when(mex.getVariable("bpmnRequest")).thenReturn(req) + when(mex.getVariable("serviceInstanceId")).thenReturn(null) + + CreateVcpeResCustService CreateVcpeResCustService = new CreateVcpeResCustService() + + assertTrue(doBpmnError( { _ -> CreateVcpeResCustService.preProcessRequest(mex) })) + } + + @Test + // @Ignore + public void preProcessRequest_BpmnError() { + ExecutionEntity mex = setupMock() + initPreProcess(mex) + + when(mex.getVariable("bpmnRequest")).thenThrow(new BpmnError("expected exception")) + + CreateVcpeResCustService CreateVcpeResCustService = new CreateVcpeResCustService() + + assertTrue(doBpmnError( { _ -> CreateVcpeResCustService.preProcessRequest(mex) })) + } + + @Test + // @Ignore + public void preProcessRequest_Ex() { + ExecutionEntity mex = setupMock() + initPreProcess(mex) + + when(mex.getVariable("bpmnRequest")).thenThrow(new RuntimeException("expected exception")) + + CreateVcpeResCustService CreateVcpeResCustService = new CreateVcpeResCustService() + + assertTrue(doBpmnError( { _ -> CreateVcpeResCustService.preProcessRequest(mex) })) + } + + // ***** sendSyncResponse ***** + + @Test + // @Ignore + public void sendSyncResponse() { + ExecutionEntity mex = setupMock() + def map = setupMap(mex) + initSendSyncResponse(mex) + + CreateVcpeResCustService CreateVcpeResCustService = new CreateVcpeResCustService() + CreateVcpeResCustService.sendSyncResponse(mex) + + verify(mex, times(2)).getVariable(DBGFLAG) + + verify(mex).setVariable(processName+"WorkflowResponseSent", "true") + + assertEquals("202", map.get(processName+"ResponseCode")) + assertEquals("Success", map.get(processName+"Status")) + + def resp = map.get(processName+"Response") + + assertTrue(resp.indexOf('"instanceId":"sii"') >= 0) + assertTrue(resp.indexOf('"requestId":"mri"') >= 0) + } + + @Test + // @Ignore + public void sendSyncResponse_Ex() { + ExecutionEntity mex = setupMock() + initSendSyncResponse(mex) + + when(mex.getVariable("serviceInstanceId")).thenThrow(new RuntimeException("expected exception")) + + CreateVcpeResCustService CreateVcpeResCustService = new CreateVcpeResCustService() + + assertTrue(doBpmnError( { _ -> CreateVcpeResCustService.sendSyncResponse(mex) })) + } + + + // ***** prepareDecomposeService ***** + + @Test + // @Ignore + public void prepareDecomposeService() { + ExecutionEntity mex = setupMock() + initPrepareDecomposeService(mex) + + CreateVcpeResCustService CreateVcpeResCustService = new CreateVcpeResCustService() + CreateVcpeResCustService.prepareDecomposeService(mex) + + verify(mex).getVariable(DBGFLAG) + verify(mex).setVariable("serviceModelInfo", "mi") + } + + @Test + // @Ignore + public void prepareDecomposeService_Ex() { + ExecutionEntity mex = setupMock() + initPrepareDecomposeService(mex) + + when(mex.getVariable("createVcpeServiceRequest")).thenThrow(new RuntimeException("expected exception")) + + CreateVcpeResCustService CreateVcpeResCustService = new CreateVcpeResCustService() + + assertTrue(doBpmnError( { _ -> CreateVcpeResCustService.prepareDecomposeService(mex) })) + } + + + // ***** prepareCreateServiceInstance ***** + + @Test + // @Ignore + public void prepareCreateServiceInstance() { + ExecutionEntity mex = setupMock() + initPrepareCreateServiceInstance(mex) + + CreateVcpeResCustService CreateVcpeResCustService = new CreateVcpeResCustService() + CreateVcpeResCustService.prepareCreateServiceInstance(mex) + + verify(mex).getVariable(DBGFLAG) + verify(mex).setVariable("serviceInstanceName", "VCPE1") + verify(mex).setVariable("serviceDecompositionString", "mydecomp") + } + + @Test + // @Ignore + public void prepareCreateServiceInstance_Ex() { + ExecutionEntity mex = setupMock() + initPrepareCreateServiceInstance(mex) + + when(mex.getVariable("createVcpeServiceRequest")).thenThrow(new RuntimeException("expected exception")) + + CreateVcpeResCustService CreateVcpeResCustService = new CreateVcpeResCustService() + + assertTrue(doBpmnError( { _ -> CreateVcpeResCustService.prepareCreateServiceInstance(mex) })) + } + + + // ***** postProcessServiceInstanceCreate ***** + + @Test + // @Ignore + public void postProcessServiceInstanceCreate() { + ExecutionEntity mex = setupMock() + def map = setupMap(mex) + initPostProcessServiceInstanceCreate(mex) + + CreateVcpeResCustService CreateVcpeResCustService = new CreateVcpeResCustService() + CreateVcpeResCustService.postProcessServiceInstanceCreate(mex) + + verify(mex).getVariable(DBGFLAG) + + def reqinfo = map.get(Prefix+"setUpdateDbInstancePayload") + + assertTrue(reqinfo.indexOf("<requestId>mri</") >= 0) + assertTrue(reqinfo.indexOf("<serviceInstanceId>sii</") >= 0) + assertTrue(reqinfo.indexOf("<serviceInstanceName>sin</") >= 0) + } + + @Test + // @Ignore + public void postProcessServiceInstanceCreate_BpmnError() { + ExecutionEntity mex = setupMock() + initPostProcessServiceInstanceCreate(mex) + + doThrow(new BpmnError("expected exception")).when(mex).setVariable(endsWith("setUpdateDbInstancePayload"), any()) + + CreateVcpeResCustService CreateVcpeResCustService = new CreateVcpeResCustService() + + assertTrue(doBpmnError( { _ -> CreateVcpeResCustService.postProcessServiceInstanceCreate(mex) })) + } + + @Test + // @Ignore + public void postProcessServiceInstanceCreate_Ex() { + ExecutionEntity mex = setupMock() + initPostProcessServiceInstanceCreate(mex) + + doThrow(new RuntimeException("expected exception")).when(mex).setVariable(endsWith("setUpdateDbInstancePayload"), any()) + + CreateVcpeResCustService CreateVcpeResCustService = new CreateVcpeResCustService() + + assertTrue(doBpmnError( { _ -> CreateVcpeResCustService.postProcessServiceInstanceCreate(mex) })) + } + + + // ***** processDecomposition ***** + + @Test + // @Ignore + public void processDecomposition() { + ExecutionEntity mex = setupMock() + def svcdecomp = initProcessDecomposition(mex) + + CreateVcpeResCustService CreateVcpeResCustService = new CreateVcpeResCustService() + CreateVcpeResCustService.processDecomposition(mex) + + verify(mex).getVariable(DBGFLAG) + + verify(mex).setVariable("vnfList", svcdecomp.getVnfResources()) + verify(mex).setVariable("vnfListString", '[myvnf]') + verify(mex).setVariable(Prefix+"VNFsCount", 1) + + verify(mex).setVariable("vnfModelInfo", "mymodel") + verify(mex).setVariable("vnfModelInfoString", "mymodel") + } + + @Test + // @Ignore + public void processDecomposition_EmptyNet_EmptyVnf() { + ExecutionEntity mex = setupMock() + def svcdecomp = initProcessDecomposition(mex) + + when(svcdecomp.getVnfResources()).thenReturn(new LinkedList<VnfResource>()) + + CreateVcpeResCustService CreateVcpeResCustService = new CreateVcpeResCustService() + CreateVcpeResCustService.processDecomposition(mex) + + verify(mex).getVariable(DBGFLAG) + + verify(mex).setVariable("vnfList", svcdecomp.getVnfResources()) + verify(mex).setVariable("vnfListString", '[]') + verify(mex).setVariable(Prefix+"VNFsCount", 0) + + verify(mex).setVariable("vnfModelInfo", "") + verify(mex).setVariable("vnfModelInfoString", "") + } + + @Test + // @Ignore + public void processDecomposition_Ex() { + ExecutionEntity mex = setupMock() + def svcdecomp = initProcessDecomposition(mex) + + when(svcdecomp.getVnfResources()).thenThrow(new RuntimeException("expected exception")) + + CreateVcpeResCustService CreateVcpeResCustService = new CreateVcpeResCustService() + + assertTrue(doBpmnError( { _ -> CreateVcpeResCustService.processDecomposition(mex) })) + } + + + // ***** filterVnfs ***** + + @Test + // @Ignore + public void filterVnfs() { + ExecutionEntity mex = setupMock() + def svcdecomp = initFilterVnfs(mex) + + CreateVcpeResCustService CreateVcpeResCustService = new CreateVcpeResCustService() + CreateVcpeResCustService.processDecomposition(mex) + + verify(mex).setVariable("vnfListString", '[myvnf3, myvnf5]') + } + + @Test + // @Ignore + public void filterVnfs_Null() { + ExecutionEntity mex = setupMock() + def svcdecomp = initFilterVnfs(mex) + + when(svcdecomp.getVnfResources()).thenReturn(null) + + CreateVcpeResCustService CreateVcpeResCustService = new CreateVcpeResCustService() + CreateVcpeResCustService.processDecomposition(mex) + + // nothing more to check, as long as it didn't throw an exception + } + + + // ***** prepareCreateAllottedResourceTXC ***** + + @Test + // @Ignore + public void prepareCreateAllottedResourceTXC() { + ExecutionEntity mex = setupMock() + initPrepareCreateAllottedResourceTXC(mex) + + CreateVcpeResCustService CreateVcpeResCustService = new CreateVcpeResCustService() + CreateVcpeResCustService.prepareCreateAllottedResourceTXC(mex) + + verify(mex).getVariable(DBGFLAG) + + verify(mex).setVariable("createTXCAR", true) + verify(mex).setVariable("allottedResourceModelInfoTXC", "modelB") + verify(mex).setVariable("allottedResourceRoleTXC", "TXCr") + verify(mex).setVariable("allottedResourceTypeTXC", "Tunnel XConn") + verify(mex).setVariable("parentServiceInstanceIdTXC", "homeB") + } + + @Test + // @Ignore + public void prepareCreateAllottedResourceTXC_NullArList() { + ExecutionEntity mex = setupMock() + def svcdecomp = initPrepareCreateAllottedResourceTXC(mex) + + when(svcdecomp.getAllottedResources()).thenReturn(null) + + CreateVcpeResCustService CreateVcpeResCustService = new CreateVcpeResCustService() + CreateVcpeResCustService.prepareCreateAllottedResourceTXC(mex) + + verify(mex).getVariable(DBGFLAG) + + verify(mex, never()).setVariable("createTXCAR", true) + verify(mex, never()).setVariable("allottedResourceModelInfoTXC", "modelB") + verify(mex, never()).setVariable("allottedResourceRoleTXC", "TXCr") + verify(mex, never()).setVariable("allottedResourceTypeTXC", "Tunnel XConn") + verify(mex, never()).setVariable("parentServiceInstanceIdTXC", "homeB") + } + + @Test + // @Ignore + public void prepareCreateAllottedResourceTXC_Ex() { + ExecutionEntity mex = setupMock() + initPrepareCreateAllottedResourceTXC(mex) + + when(mex.getVariable("createVcpeServiceRequest")).thenThrow(new RuntimeException("expected exception")) + + CreateVcpeResCustService CreateVcpeResCustService = new CreateVcpeResCustService() + + assertTrue(doBpmnError( { _ -> CreateVcpeResCustService.prepareCreateAllottedResourceTXC(mex) })) + } + + + // ***** prepareCreateAllottedResourceBRG ***** + + @Test + // @Ignore + public void prepareCreateAllottedResourceBRG() { + ExecutionEntity mex = setupMock() + initPrepareCreateAllottedResourceBRG(mex) + + CreateVcpeResCustService CreateVcpeResCustService = new CreateVcpeResCustService() + CreateVcpeResCustService.prepareCreateAllottedResourceBRG(mex) + + verify(mex).getVariable(DBGFLAG) + + verify(mex).setVariable("createBRGAR", true) + verify(mex).setVariable("allottedResourceModelInfoBRG", "modelB") + verify(mex).setVariable("allottedResourceRoleBRG", "BRGr") + verify(mex).setVariable("allottedResourceTypeBRG", "BRG") + verify(mex).setVariable("parentServiceInstanceIdBRG", "homeB") + } + + @Test + // @Ignore + public void prepareCreateAllottedResourceBRG_NullArList() { + ExecutionEntity mex = setupMock() + def svcdecomp = initPrepareCreateAllottedResourceBRG(mex) + + when(svcdecomp.getAllottedResources()).thenReturn(null) + + CreateVcpeResCustService CreateVcpeResCustService = new CreateVcpeResCustService() + CreateVcpeResCustService.prepareCreateAllottedResourceBRG(mex) + + verify(mex).getVariable(DBGFLAG) + + verify(mex, never()).setVariable("createBRGAR", true) + verify(mex, never()).setVariable("allottedResourceModelInfoBRG", "modelB") + verify(mex, never()).setVariable("allottedResourceRoleBRG", "BRGr") + verify(mex, never()).setVariable("allottedResourceTypeBRG", "BRG") + verify(mex, never()).setVariable("parentServiceInstanceIdBRG", "homeB") + } + + @Test + // @Ignore + public void prepareCreateAllottedResourceBRG_Ex() { + ExecutionEntity mex = setupMock() + initPrepareCreateAllottedResourceBRG(mex) + + when(mex.getVariable("createVcpeServiceRequest")).thenThrow(new RuntimeException("expected exception")) + + CreateVcpeResCustService CreateVcpeResCustService = new CreateVcpeResCustService() + + assertTrue(doBpmnError( { _ -> CreateVcpeResCustService.prepareCreateAllottedResourceBRG(mex) })) + } + + + // ***** prepareVnfAndModulesCreate ***** + + @Test + // @Ignore + public void prepareVnfAndModulesCreate() { + ExecutionEntity mex = setupMock() + initPrepareVnfAndModulesCreate(mex) + + CreateVcpeResCustService CreateVcpeResCustService = new CreateVcpeResCustService() + CreateVcpeResCustService.prepareVnfAndModulesCreate(mex) + + verify(mex).getVariable(DBGFLAG) + + verify(mex).setVariable("productFamilyId", "a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb") + verify(mex).setVariable("lcpCloudRegionId", "mdt1") + verify(mex).setVariable("tenantId", "8b1df54faa3b49078e3416e21370a3ba") + } + + @Test + // @Ignore + public void prepareVnfAndModulesCreate_EmptyList() { + ExecutionEntity mex = setupMock() + initPrepareVnfAndModulesCreate(mex) + + when(mex.getVariable("vnfList")).thenReturn(new LinkedList<VnfResource>()) + + CreateVcpeResCustService CreateVcpeResCustService = new CreateVcpeResCustService() + CreateVcpeResCustService.prepareVnfAndModulesCreate(mex) + + verify(mex).getVariable(DBGFLAG) + + verify(mex).setVariable("productFamilyId", "a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb") + verify(mex).setVariable("lcpCloudRegionId", "mdt1") + verify(mex).setVariable("tenantId", "8b1df54faa3b49078e3416e21370a3ba") + } + + @Test + // @Ignore + public void prepareVnfAndModulesCreate_NullList() { + ExecutionEntity mex = setupMock() + initPrepareVnfAndModulesCreate(mex) + + when(mex.getVariable("vnfList")).thenReturn(null) + + CreateVcpeResCustService CreateVcpeResCustService = new CreateVcpeResCustService() + CreateVcpeResCustService.prepareVnfAndModulesCreate(mex) + + verify(mex).getVariable(DBGFLAG) + + verify(mex).setVariable("productFamilyId", "a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb") + verify(mex).setVariable("lcpCloudRegionId", "mdt1") + verify(mex).setVariable("tenantId", "8b1df54faa3b49078e3416e21370a3ba") + } + + @Test + // @Ignore + public void prepareVnfAndModulesCreate_Ex() { + ExecutionEntity mex = setupMock() + initPrepareVnfAndModulesCreate(mex) + + when(mex.getVariable("vnfList")).thenThrow(new RuntimeException("expected exception")) + + CreateVcpeResCustService CreateVcpeResCustService = new CreateVcpeResCustService() + + assertTrue(doBpmnError( { _ -> CreateVcpeResCustService.prepareVnfAndModulesCreate(mex) })) + } + + + // ***** validateVnfCreate ***** + + @Test + // @Ignore + public void validateVnfCreate() { + ExecutionEntity mex = setupMock() + initValidateVnfCreate(mex) + + CreateVcpeResCustService CreateVcpeResCustService = new CreateVcpeResCustService() + CreateVcpeResCustService.validateVnfCreate(mex) + + verify(mex).getVariable(DBGFLAG) + + verify(mex).setVariable(Prefix+"VnfsCreatedCount", 3) + } + + @Test + // @Ignore + public void validateVnfCreate_Ex() { + ExecutionEntity mex = setupMock() + initValidateVnfCreate(mex) + + when(mex.getVariable(Prefix+"VnfsCreatedCount")).thenThrow(new RuntimeException("expected exception")) + + CreateVcpeResCustService CreateVcpeResCustService = new CreateVcpeResCustService() + + assertTrue(doBpmnError( { _ -> CreateVcpeResCustService.validateVnfCreate(mex) })) + } + + + // ***** postProcessResponse ***** + + @Test + // @Ignore + public void postProcessResponse() { + ExecutionEntity mex = setupMock() + def map = setupMap(mex) + initPostProcessResponse(mex) + + CreateVcpeResCustService CreateVcpeResCustService = new CreateVcpeResCustService() + CreateVcpeResCustService.postProcessResponse(mex) + + verify(mex).getVariable(DBGFLAG) + + verify(mex).setVariable(Prefix+"Success", true) + + def reqinfo = map.get(Prefix+"CompleteMsoProcessRequest") + + assertTrue(reqinfo.indexOf("request-id>mri</") >= 0) + assertTrue(reqinfo.indexOf("source>mysrc</") >= 0) + assertTrue(reqinfo.indexOf("serviceInstanceId>sii</") >= 0) + } + + @Test + // @Ignore + public void postProcessResponse_BpmnError() { + ExecutionEntity mex = setupMock() + def map = setupMap(mex) + initPostProcessResponse(mex) + + when(mex.getVariable("source")).thenThrow(new BpmnError("expected exception")) + + CreateVcpeResCustService CreateVcpeResCustService = new CreateVcpeResCustService() + + assertTrue(doBpmnError( { _ -> CreateVcpeResCustService.postProcessResponse(mex) })) + } + + @Test + // @Ignore + public void postProcessResponse_Ex() { + ExecutionEntity mex = setupMock() + def map = setupMap(mex) + initPostProcessResponse(mex) + + when(mex.getVariable("source")).thenThrow(new RuntimeException("expected exception")) + + CreateVcpeResCustService CreateVcpeResCustService = new CreateVcpeResCustService() + + assertTrue(doBpmnError( { _ -> CreateVcpeResCustService.postProcessResponse(mex) })) + } + + + // ***** preProcessRollback ***** + + @Test + // @Ignore + public void preProcessRollback() { + ExecutionEntity mex = setupMock() + def wfe = initPreProcessRollback(mex) + + CreateVcpeResCustService CreateVcpeResCustService = new CreateVcpeResCustService() + CreateVcpeResCustService.preProcessRollback(mex) + + verify(mex).getVariable(DBGFLAG) + + verify(mex).setVariable("prevWorkflowException", wfe) + } + + @Test + // @Ignore + public void preProcessRollback_NullWfe() { + ExecutionEntity mex = setupMock() + def map = setupMap(mex) + def wfe = initPreProcessRollback(mex) + + when(mex.getVariable("WorkflowException")).thenReturn(null) + + CreateVcpeResCustService CreateVcpeResCustService = new CreateVcpeResCustService() + CreateVcpeResCustService.preProcessRollback(mex) + + verify(mex).getVariable(DBGFLAG) + + assertFalse(map.containsKey("prevWorkflowException")) + } + + @Test + // @Ignore + public void preProcessRollback_BpmnError() { + ExecutionEntity mex = setupMock() + def map = setupMap(mex) + def wfe = initPreProcessRollback(mex) + + when(mex.getVariable("WorkflowException")).thenThrow(new BpmnError("expected exception")) + + CreateVcpeResCustService CreateVcpeResCustService = new CreateVcpeResCustService() + CreateVcpeResCustService.preProcessRollback(mex) + + verify(mex).getVariable(DBGFLAG) + + assertFalse(map.containsKey("prevWorkflowException")) + } + + @Test + // @Ignore + public void preProcessRollback_Ex() { + ExecutionEntity mex = setupMock() + def map = setupMap(mex) + def wfe = initPreProcessRollback(mex) + + when(mex.getVariable("WorkflowException")).thenThrow(new RuntimeException("expected exception")) + + CreateVcpeResCustService CreateVcpeResCustService = new CreateVcpeResCustService() + CreateVcpeResCustService.preProcessRollback(mex) + + verify(mex).getVariable(DBGFLAG) + + assertFalse(map.containsKey("prevWorkflowException")) + } + + + // ***** postProcessRollback ***** + + @Test + // @Ignore + public void postProcessRollback() { + ExecutionEntity mex = setupMock() + def wfe = initPostProcessRollback(mex) + + CreateVcpeResCustService CreateVcpeResCustService = new CreateVcpeResCustService() + CreateVcpeResCustService.postProcessRollback(mex) + + verify(mex).getVariable(DBGFLAG) + + verify(mex).setVariable("WorkflowException", wfe) + } + + @Test + // @Ignore + public void postProcessRollback_NullWfe() { + ExecutionEntity mex = setupMock() + def map = setupMap(mex) + def wfe = initPostProcessRollback(mex) + + when(mex.getVariable("prevWorkflowException")).thenReturn(null) + + CreateVcpeResCustService CreateVcpeResCustService = new CreateVcpeResCustService() + CreateVcpeResCustService.postProcessRollback(mex) + + verify(mex).getVariable(DBGFLAG) + + assertFalse(map.containsKey("WorkflowException")) + } + + @Test + // @Ignore + public void postProcessRollback_BpmnError() { + ExecutionEntity mex = setupMock() + def map = setupMap(mex) + def wfe = initPostProcessRollback(mex) + + when(mex.getVariable("prevWorkflowException")).thenThrow(new BpmnError("expected exception")) + + CreateVcpeResCustService CreateVcpeResCustService = new CreateVcpeResCustService() + assertTrue(doBpmnError( { _ -> CreateVcpeResCustService.postProcessRollback(mex) })) + } + + @Test + // @Ignore + public void postProcessRollback_Ex() { + ExecutionEntity mex = setupMock() + def map = setupMap(mex) + def wfe = initPostProcessRollback(mex) + + when(mex.getVariable("prevWorkflowException")).thenThrow(new RuntimeException("expected exception")) + + CreateVcpeResCustService CreateVcpeResCustService = new CreateVcpeResCustService() + CreateVcpeResCustService.postProcessRollback(mex) + + verify(mex).getVariable(DBGFLAG) + + assertFalse(map.containsKey("WorkflowException")) + } + + + // ***** prepareFalloutRequest ***** + + @Test + // @Ignore + public void prepareFalloutRequest() { + ExecutionEntity mex = setupMock() + def map = setupMap(mex) + initPrepareFalloutRequest(mex) + + CreateVcpeResCustService CreateVcpeResCustService = new CreateVcpeResCustService() + CreateVcpeResCustService.prepareFalloutRequest(mex) + + verify(mex, times(2)).getVariable(DBGFLAG) + + def fo = map.get(Prefix+"falloutRequest") + + assertTrue(fo.indexOf("<hello>world</") >= 0) + assertTrue(fo.indexOf("ErrorMessage>mymsg</") >= 0) + assertTrue(fo.indexOf("ErrorCode>999</") >= 0) + } + + @Test + // @Ignore + public void prepareFalloutRequest_Ex() { + ExecutionEntity mex = setupMock() + def map = setupMap(mex) + initPrepareFalloutRequest(mex) + + when(mex.getVariable("WorkflowException")).thenThrow(new RuntimeException("expected exception")) + + CreateVcpeResCustService CreateVcpeResCustService = new CreateVcpeResCustService() + + assertTrue(doBpmnError( { _ -> CreateVcpeResCustService.prepareFalloutRequest(mex) })) + } + + // ***** sendSyncError ***** + + @Test + // @Ignore + public void sendSyncError() { + ExecutionEntity mex = setupMock() + def map = setupMap(mex) + initSendSyncError(mex) + + CreateVcpeResCustService CreateVcpeResCustService = new CreateVcpeResCustService() + CreateVcpeResCustService.sendSyncError(mex) + + verify(mex, times(2)).getVariable(DBGFLAG) + + verify(mex).setVariable(processName+"WorkflowResponseSent", "true") + + assertEquals("500", map.get(processName+"ResponseCode")) + assertEquals("Fail", map.get(processName+"Status")) + + def resp = map.get(processName+"Response") + + assertTrue(resp.indexOf("ErrorMessage>mymsg</") >= 0) + + verify(mex).setVariable("WorkflowResponse", resp) + } + + @Test + // @Ignore + public void sendSyncError_NotWfe() { + ExecutionEntity mex = setupMock() + def map = setupMap(mex) + initSendSyncError(mex) + + when(mex.getVariable("WorkflowException")).thenReturn("not a WFE") + + CreateVcpeResCustService CreateVcpeResCustService = new CreateVcpeResCustService() + CreateVcpeResCustService.sendSyncError(mex) + + verify(mex, times(2)).getVariable(DBGFLAG) + + verify(mex).setVariable(processName+"WorkflowResponseSent", "true") + + assertEquals("500", map.get(processName+"ResponseCode")) + assertEquals("Fail", map.get(processName+"Status")) + + def resp = map.get(processName+"Response") + + assertTrue(resp.indexOf("ErrorMessage>Sending Sync Error.</") >= 0) + + verify(mex).setVariable("WorkflowResponse", resp) + } + + @Test + // @Ignore + public void sendSyncError_NullWfe() { + ExecutionEntity mex = setupMock() + def map = setupMap(mex) + initSendSyncError(mex) + + when(mex.getVariable("WorkflowException")).thenReturn(null) + + CreateVcpeResCustService CreateVcpeResCustService = new CreateVcpeResCustService() + CreateVcpeResCustService.sendSyncError(mex) + + verify(mex, times(2)).getVariable(DBGFLAG) + + verify(mex).setVariable(processName+"WorkflowResponseSent", "true") + + assertEquals("500", map.get(processName+"ResponseCode")) + assertEquals("Fail", map.get(processName+"Status")) + + def resp = map.get(processName+"Response") + + assertTrue(resp.indexOf("ErrorMessage>Sending Sync Error.</") >= 0) + + verify(mex).setVariable("WorkflowResponse", resp) + } + + @Test + // @Ignore + public void sendSyncError_Ex() { + ExecutionEntity mex = setupMock() + def map = setupMap(mex) + initSendSyncError(mex) + + when(mex.getVariable("WorkflowException")).thenThrow(new RuntimeException("expected exception")) + + CreateVcpeResCustService CreateVcpeResCustService = new CreateVcpeResCustService() + + CreateVcpeResCustService.sendSyncError(mex) + + assertFalse(map.containsKey(processName+"ResponseCode")) + } + + + // ***** processJavaException ***** + + @Test + // @Ignore + public void processJavaException() { + ExecutionEntity mex = setupMock() + def map = setupMap(mex) + initProcessJavaException(mex) + + CreateVcpeResCustService CreateVcpeResCustService = new CreateVcpeResCustService() + + assertTrue(doBpmnError( { _ -> CreateVcpeResCustService.processJavaException(mex) })) + + verify(mex, times(2)).getVariable(DBGFLAG) + + verify(mex).setVariable("prefix", Prefix) + + def wfe = map.get("WorkflowException") + + assertEquals("Caught a Java Lang Exception", wfe.getErrorMessage()) + } + + @Test + // @Ignore + public void processJavaException_BpmnError() { + ExecutionEntity mex = setupMock() + def map = setupMap(mex) + initProcessJavaException(mex) + + when(mex.getVariables()).thenThrow(new BpmnError("expected exception")) + + CreateVcpeResCustService CreateVcpeResCustService = new CreateVcpeResCustService() + + assertTrue(doBpmnError( { _ -> CreateVcpeResCustService.processJavaException(mex) })) + + assertFalse(map.containsKey("WorkflowException")) + } + + @Test + // @Ignore + public void processJavaException_Ex() { + ExecutionEntity mex = setupMock() + def map = setupMap(mex) + initProcessJavaException(mex) + + when(mex.getVariables()).thenThrow(new RuntimeException("expected exception")) + + CreateVcpeResCustService CreateVcpeResCustService = new CreateVcpeResCustService() + + assertTrue(doBpmnError( { _ -> CreateVcpeResCustService.processJavaException(mex) })) + + def wfe = map.get("WorkflowException") + + assertEquals("Exception in processJavaException method", wfe.getErrorMessage()) + } + + + private void initPreProcess(ExecutionEntity mex) { + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("bpmnRequest")).thenReturn(request) + when(mex.getVariable("URN_mso_workflow_aai_distribution_delay")).thenReturn("aaidelay") + when(mex.getVariable("mso-request-id")).thenReturn("mri") + when(mex.getVariable("serviceInstanceId")).thenReturn("sii") + when(mex.getVariable("requestAction")).thenReturn("ra") + } + + private initSendSyncResponse(ExecutionEntity mex) { + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("mso-request-id")).thenReturn("mri") + when(mex.getVariable("serviceInstanceId")).thenReturn("sii") + } + + private void initPrepareDecomposeService(ExecutionEntity mex) { + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("createVcpeServiceRequest")).thenReturn('{"requestDetails":{"modelInfo":"mi"}}') + } + + private void initPrepareCreateServiceInstance(ExecutionEntity mex) { + ServiceDecomposition svcdecomp = mock(ServiceDecomposition.class) + + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("createVcpeServiceRequest")).thenReturn(request) + when(mex.getVariable("serviceDecomposition")).thenReturn(svcdecomp) + + when(svcdecomp.toJsonStringNoRootName()).thenReturn("mydecomp") + } + + private void initPostProcessServiceInstanceCreate(ExecutionEntity mex) { + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("mso-request-id")).thenReturn("mri") + when(mex.getVariable("serviceInstanceId")).thenReturn("sii") + when(mex.getVariable("serviceInstanceName")).thenReturn("sin") + } + + private ServiceDecomposition initProcessDecomposition(ExecutionEntity mex) { + List<VnfResource> vnflst = new LinkedList<>() + vnflst.add(makeVnf("", "")) + vnflst.add(makeVnf("2", "BRG")) + vnflst.add(makeVnf("3", "BRG")) + + ServiceDecomposition svcdecomp = mock(ServiceDecomposition.class) + when(svcdecomp.getVnfResources()).thenReturn(vnflst) + + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("serviceDecomposition")).thenReturn(svcdecomp) + when(mex.getVariable("serviceInstanceId")).thenReturn("sii") + when(mex.getVariable("serviceInstanceName")).thenReturn("sin") + + return svcdecomp + } + + private ServiceDecomposition initFilterVnfs(ExecutionEntity mex) { + List<VnfResource> vnflst = new LinkedList<>() + vnflst.add(makeVnf("", "BRG")) + vnflst.add(makeVnf("2", "Tunnel XConn")) + vnflst.add(makeVnf("3", "")) + vnflst.add(makeVnf("4", "BRG")) + vnflst.add(makeVnf("5", "other")) + + ServiceDecomposition svcdecomp = mock(ServiceDecomposition.class) + when(svcdecomp.getVnfResources()).thenReturn(vnflst) + + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("serviceDecomposition")).thenReturn(svcdecomp) + when(mex.getVariable("serviceInstanceId")).thenReturn("sii") + when(mex.getVariable("serviceInstanceName")).thenReturn("sin") + + return svcdecomp + } + + private initAwaitAaiDistribution(ExecutionEntity mex) { + when(mex.getVariable(DBGFLAG)).thenReturn("true") + } + + private ServiceDecomposition initPrepareCreateAllottedResourceTXC(ExecutionEntity mex) { + ServiceDecomposition svcdecomp = mock(ServiceDecomposition.class) + List<AllottedResource> arlst = new LinkedList<>() + + arlst.add(makeArBRG("A")) + arlst.add(makeArTXC("B")) + arlst.add(makeArBRG("C")) + + when(svcdecomp.getAllottedResources()).thenReturn(arlst) + + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("createVcpeServiceRequest")).thenReturn(request) + when(mex.getVariable("serviceDecomposition")).thenReturn(svcdecomp) + when(mex.getVariable("allottedResourceId")).thenReturn(ARID) + + return svcdecomp + } + + private ServiceDecomposition initPrepareCreateAllottedResourceBRG(ExecutionEntity mex) { + ServiceDecomposition svcdecomp = mock(ServiceDecomposition.class) + List<AllottedResource> arlst = new LinkedList<>() + + arlst.add(makeArTXC("A")) + arlst.add(makeArBRG("B")) + arlst.add(makeArTXC("C")) + + when(svcdecomp.getAllottedResources()).thenReturn(arlst) + + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("createVcpeServiceRequest")).thenReturn(request) + when(mex.getVariable("serviceDecomposition")).thenReturn(svcdecomp) + when(mex.getVariable("allottedResourceId")).thenReturn(ARID) + + return svcdecomp + } + + private AllottedResource makeArTXC(String id) { + AllottedResource ar = mock(AllottedResource.class) + ModelInfo mod = mock(ModelInfo.class) + HomingSolution home = mock(HomingSolution.class) + + when(ar.toJsonStringNoRootName()).thenReturn("json"+id) + when(ar.getAllottedResourceType()).thenReturn("Tunnel XConn") + when(ar.getModelInfo()).thenReturn(mod) + when(ar.getAllottedResourceRole()).thenReturn("TXCr") + when(ar.getHomingSolution()).thenReturn(home) + + when(mod.toJsonStringNoRootName()).thenReturn("model"+id) + + when(home.getServiceInstanceId()).thenReturn("home"+id) + + return ar + } + + private AllottedResource makeArBRG(String id) { + AllottedResource ar = mock(AllottedResource.class) + ModelInfo mod = mock(ModelInfo.class) + HomingSolution home = mock(HomingSolution.class) + + when(ar.toJsonStringNoRootName()).thenReturn("json"+id) + when(ar.getAllottedResourceType()).thenReturn("BRG") + when(ar.getModelInfo()).thenReturn(mod) + when(ar.getAllottedResourceRole()).thenReturn("BRGr") + when(ar.getHomingSolution()).thenReturn(home) + + when(mod.toJsonStringNoRootName()).thenReturn("model"+id) + + when(home.getServiceInstanceId()).thenReturn("home"+id) + + return ar + } + + private initPrepareVnfAndModulesCreate(ExecutionEntity mex) { + + List<VnfResource> vnflst = new LinkedList<>() + + vnflst.add(makeVnf("A", "BRG")) + vnflst.add(makeVnf("B", "")) + vnflst.add(makeVnf("C", "")) + vnflst.add(makeVnf("D", "Tunnel XConn")) + + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("createVcpeServiceRequest")).thenReturn(request) + when(mex.getVariable("vnfList")).thenReturn(vnflst) + when(mex.getVariable(Prefix+"VnfsCreatedCount")).thenReturn(2) + when(mex.getVariable("vnfModelInfo")).thenReturn("nomodel") + when(mex.getVariable("sdncVersion")).thenReturn("myvers") + } + + private VnfResource makeVnf(String id, String role) { + ModelInfo mod = mock(ModelInfo.class) + VnfResource vnf = mock(VnfResource.class) + + when(mod.toString()).thenReturn('{"modelInfo":"mymodel'+id+'"}') + + when(vnf.toString()).thenReturn("myvnf"+id) + when(vnf.getModelInfo()).thenReturn(mod) + when(vnf.getNfRole()).thenReturn(role) + + return vnf + } + + private initValidateVnfCreate(ExecutionEntity mex) { + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable(Prefix+"VnfsCreatedCount")).thenReturn(2) + } + + private initPostProcessResponse(ExecutionEntity mex) { + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("source")).thenReturn("mysrc") + when(mex.getVariable("mso-request-id")).thenReturn("mri") + when(mex.getVariable("serviceInstanceId")).thenReturn("sii") + } + + private WorkflowException initPreProcessRollback(ExecutionEntity mex) { + WorkflowException wfe = mock(WorkflowException.class) + + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("WorkflowException")).thenReturn(wfe) + + return wfe + } + + private WorkflowException initPostProcessRollback(ExecutionEntity mex) { + WorkflowException wfe = mock(WorkflowException.class) + + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("prevWorkflowException")).thenReturn(wfe) + + return wfe + } + + private initPrepareFalloutRequest(ExecutionEntity mex) { + WorkflowException wfe = mock(WorkflowException.class) + + when(wfe.getErrorMessage()).thenReturn("mymsg") + when(wfe.getErrorCode()).thenReturn(999) + + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("WorkflowException")).thenReturn(wfe) + when(mex.getVariable(Prefix+"requestInfo")).thenReturn("<hello>world</hello>") + + return wfe + } + + private initSendSyncError(ExecutionEntity mex) { + WorkflowException wfe = mock(WorkflowException.class) + + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("mso-request-id")).thenReturn("mri") + when(mex.getVariable("WorkflowException")).thenReturn(wfe) + + when(wfe.getErrorMessage()).thenReturn("mymsg") + } + + private initProcessJavaException(ExecutionEntity mex) { + when(mex.getVariable(DBGFLAG)).thenReturn("true") + } + +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/vcpe/scripts/DeleteVcpeResCustServiceTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/vcpe/scripts/DeleteVcpeResCustServiceTest.groovy new file mode 100644 index 0000000000..b7c754938a --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/vcpe/scripts/DeleteVcpeResCustServiceTest.groovy @@ -0,0 +1,773 @@ +/* + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ +package org.onap.so.bpmn.vcpe.scripts + + +import org.camunda.bpm.engine.ProcessEngineServices +import org.camunda.bpm.engine.RepositoryService +import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity +import org.camunda.bpm.engine.repository.ProcessDefinition +import org.junit.Before +import org.junit.BeforeClass +import org.junit.Rule +import org.junit.Test +import org.junit.Ignore +import org.mockito.MockitoAnnotations +import org.camunda.bpm.engine.delegate.BpmnError +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.bpmn.mock.FileUtil + +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse +import static com.github.tomakehurst.wiremock.client.WireMock.get +import static com.github.tomakehurst.wiremock.client.WireMock.patch +import static com.github.tomakehurst.wiremock.client.WireMock.put +import static com.github.tomakehurst.wiremock.client.WireMock.stubFor +import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching +import static org.junit.Assert.*; +import static org.mockito.Mockito.* +import static org.onap.so.bpmn.mock.StubResponseAAI.MockGetAllottedResource +import org.onap.so.bpmn.core.domain.ServiceDecomposition +import org.onap.so.bpmn.core.domain.VnfResource +import org.onap.so.bpmn.core.domain.AllottedResource +import org.onap.so.bpmn.core.domain.ModelInfo + +import org.onap.so.bpmn.core.RollbackData +import org.onap.so.bpmn.vcpe.scripts.MapGetter +import org.onap.so.bpmn.vcpe.scripts.MapSetter + +import com.github.tomakehurst.wiremock.junit.WireMockRule + +class DeleteVcpeResCustServiceTest extends GroovyTestBase { + + private static String request + + @Rule + public WireMockRule wireMockRule = new WireMockRule(PORT) + + String Prefix = "DVRCS_" + String RbType = "DCRENI_" + + @BeforeClass + public static void setUpBeforeClass() { + request = FileUtil.readResourceFile("__files/VCPE/DeleteVcpeResCustService/request.json") + } + + @Before + public void init() + { + MockitoAnnotations.initMocks(this) + } + + public DeleteVcpeResCustServiceTest() { + super("DeleteVcpeResCustService") + } + + + // ***** preProcessRequest ***** + + @Test +// @Ignore + public void preProcessRequest() { + ExecutionEntity mex = setupMock() + def map = setupMap(mex) + initPreProcess(mex) + + DeleteVcpeResCustService DeleteVcpeResCustService = new DeleteVcpeResCustService() + DeleteVcpeResCustService.preProcessRequest(mex) + + verify(mex).getVariable(DBGFLAG) + + assertEquals(Prefix, map.get("prefix")) + assertEquals(request, map.get("DeleteVcpeResCustServiceRequest")) + assertEquals("mri", map.get("msoRequestId")) + assertEquals("ra", map.get("requestAction")) + assertEquals("VID", map.get("source")) + assertEquals(CUST, map.get("globalSubscriberId")) + assertEquals(CUST, map.get("globalCustomerId")) + assertEquals("false", map.get("disableRollback")) + assertEquals("a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb", map.get("productFamilyId")) + assertEquals(SVC, map.get("subscriptionServiceType")) + + assertEquals("mdt1", map.get("lcpCloudRegionId")) + assertEquals("8b1df54faa3b49078e3416e21370a3ba", map.get("tenantId")) + assertEquals("1707", map.get("sdncVersion")) + assertEquals("service-instance", map.get("GENGS_type")) + assertEquals("""{"tenantId":"8b1df54faa3b49078e3416e21370a3ba","lcpCloudRegionId":"mdt1"}""", map.get("cloudConfiguration")) + assertTrue(map.containsKey(Prefix+"requestInfo")) + + def reqinfo = map.get(Prefix+"requestInfo") + assertTrue(reqinfo.indexOf("<request-id>mri</") >= 0) + assertTrue(reqinfo.indexOf("<source>VID</") >= 0) + } + + @Test +// @Ignore + public void preProcessRequest_EmptyParts() { + ExecutionEntity mex = setupMock() + def map = setupMap(mex) + initPreProcess(mex) + + def req = request + .replace('"source"', '"sourceXXX"') + + when(mex.getVariable("bpmnRequest")).thenReturn(req) + + DeleteVcpeResCustService DeleteVcpeResCustService = new DeleteVcpeResCustService() + DeleteVcpeResCustService.preProcessRequest(mex) + + verify(mex).getVariable(DBGFLAG) + verify(mex).setVariable("prefix", Prefix) + verify(mex).setVariable("DeleteVcpeResCustServiceRequest", req) + verify(mex).setVariable("msoRequestId", "mri") + verify(mex).setVariable("requestAction", "ra") + verify(mex).setVariable("source", "VID") + verify(mex).setVariable("globalSubscriberId", CUST) + verify(mex).setVariable("globalCustomerId", CUST) + verify(mex).setVariable("disableRollback", "false") + verify(mex).setVariable("productFamilyId", "a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb") + verify(mex).setVariable("subscriptionServiceType", SVC) + + verify(mex).setVariable("lcpCloudRegionId", "mdt1") + verify(mex).setVariable("tenantId", "8b1df54faa3b49078e3416e21370a3ba") + assertEquals("""{"tenantId":"8b1df54faa3b49078e3416e21370a3ba","lcpCloudRegionId":"mdt1"}""", map.get("cloudConfiguration")) + verify(mex).setVariable("sdncVersion", "1707") + verify(mex).setVariable("GENGS_type", "service-instance") + assertTrue(map.containsKey(Prefix+"requestInfo")) + + def reqinfo = map.get(Prefix+"requestInfo") + println reqinfo + assertTrue(reqinfo.indexOf("<request-id>mri</") >= 0) + assertTrue(reqinfo.indexOf("<source>VID</") >= 0) + } + + @Test +// @Ignore + public void preProcessRequest_MissingServiceInstanceId() { + ExecutionEntity mex = setupMock() + initPreProcess(mex) + + when(mex.getVariable("serviceInstanceId")).thenReturn(null) + + DeleteVcpeResCustService DeleteVcpeResCustService = new DeleteVcpeResCustService() + + assertTrue(doBpmnError( { _ -> DeleteVcpeResCustService.preProcessRequest(mex) })) + } + + @Test +// @Ignore + public void preProcessRequest_BpmnError() { + ExecutionEntity mex = setupMock() + initPreProcess(mex) + + when(mex.getVariable("bpmnRequest")).thenThrow(new BpmnError("expected exception")) + + DeleteVcpeResCustService DeleteVcpeResCustService = new DeleteVcpeResCustService() + + assertTrue(doBpmnError( { _ -> DeleteVcpeResCustService.preProcessRequest(mex) })) + } + + @Test +// @Ignore + public void preProcessRequest_Ex() { + ExecutionEntity mex = setupMock() + initPreProcess(mex) + + when(mex.getVariable("bpmnRequest")).thenThrow(new RuntimeException("expected exception")) + + DeleteVcpeResCustService DeleteVcpeResCustService = new DeleteVcpeResCustService() + + assertTrue(doBpmnError( { _ -> DeleteVcpeResCustService.preProcessRequest(mex) })) + } + + private void initPreProcess(ExecutionEntity mex) { + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("bpmnRequest")).thenReturn(request) + when(mex.getVariable("mso-request-id")).thenReturn("mri") + when(mex.getVariable("serviceInstanceId")).thenReturn("sii") + when(mex.getVariable("requestAction")).thenReturn("ra") + } + + // ***** sendSyncResponse ***** + + @Test +// @Ignore + public void sendSyncResponse() { + ExecutionEntity mex = setupMock() + def map = setupMap(mex) + initSendSyncResponse(mex) + + DeleteVcpeResCustService DeleteVcpeResCustService = new DeleteVcpeResCustService() + DeleteVcpeResCustService.sendSyncResponse(mex) + + verify(mex, times(2)).getVariable(DBGFLAG) + + verify(mex).setVariable(processName+"WorkflowResponseSent", "true") + + assertEquals("202", map.get(processName+"ResponseCode")) + assertEquals("Success", map.get(processName+"Status")) + + def resp = map.get(processName+"Response") + + assertTrue(resp.indexOf('"instanceId":"sii"') >= 0) + assertTrue(resp.indexOf('"requestId":"mri"') >= 0) + } + + @Test +// @Ignore + public void sendSyncResponse_Ex() { + ExecutionEntity mex = setupMock() + initSendSyncResponse(mex) + + when(mex.getVariable("serviceInstanceId")).thenThrow(new RuntimeException("expected exception")) + + DeleteVcpeResCustService DeleteVcpeResCustService = new DeleteVcpeResCustService() + + assertTrue(doBpmnError( { _ -> DeleteVcpeResCustService.sendSyncResponse(mex) })) + } + + private initSendSyncResponse(ExecutionEntity mex) { + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("mso-request-id")).thenReturn("mri") + when(mex.getVariable("serviceInstanceId")).thenReturn("sii") + } + + // ***** prepareServiceDelete ***** + + @Test +// @Ignore + public void prepareServiceDelete() { + ExecutionEntity mex = setupMock() + def map = setupMap(mex) + initPrepareServiceDelete(mex) + + myMockGetAr("/aai/v11/anytxc", 200, "arGetTXCById.xml"); + myMockGetAr("/aai/v11/anybrg", 200, "arGetBRGById.xml"); + myMockGetAr("/aai/v11/other", 200, "arGetOtherById.xml"); + + DeleteVcpeResCustService DeleteVcpeResCustService = new DeleteVcpeResCustService() + DeleteVcpeResCustService.prepareServiceDelete(mex) + + verify(mex).setVariable(Prefix+"TunnelXConn", true) + assertEquals("ar-txcA", map.get("TXC_allottedResourceId")) + + verify(mex).setVariable(Prefix+"BRG", true) + assertEquals("ar-brgB", map.get("BRG_allottedResourceId")) + + verify(mex).setVariable(Prefix+"vnfsCount", 2) + assertNotNull(map.get(Prefix+"relatedVnfIdList")) + assertEquals("[vnfX, vnfY]", map.get(Prefix+"relatedVnfIdList").toString()) + + verify(mex, never()).setVariable(processName+"WorkflowResponseSent", "true") + } + + @Test +// @Ignore + public void prepareServiceDelete_NotFound() { + ExecutionEntity mex = setupMock() + initPrepareServiceDelete(mex) + + when(mex.getVariable("GENGS_FoundIndicator")).thenReturn(false) + + DeleteVcpeResCustService DeleteVcpeResCustService = new DeleteVcpeResCustService() + + assertTrue(doBpmnError({ _ -> DeleteVcpeResCustService.prepareServiceDelete(mex) })) + + verify(mex, never()).setVariable(processName+"WorkflowResponseSent", "true") + } + + @Test +// @Ignore + public void prepareServiceDelete_Empty() { + ExecutionEntity mex = setupMock() + def map = setupMap(mex) + initPrepareServiceDelete(mex) + + when(mex.getVariable("GENGS_service")).thenReturn("<empty></empty>") + + DeleteVcpeResCustService DeleteVcpeResCustService = new DeleteVcpeResCustService() + DeleteVcpeResCustService.prepareServiceDelete(mex) + + verify(mex).getVariable(DBGFLAG) + + verify(mex).setVariable(Prefix+"TunnelXConn", false) + assertNull(map.get("TXC_allottedResourceId")) + + verify(mex).setVariable(Prefix+"BRG", false) + assertNull(map.get("BRG_allottedResourceId")) + + assertEquals(0, map.get(Prefix+"vnfsCount")) + assertFalse(map.containsKey(Prefix+"relatedVnfIdList")) + + verify(mex, never()).setVariable(processName+"WorkflowResponseSent", "true") + } + + @Test +// @Ignore + public void prepareServiceDelete_BpmnError() { + ExecutionEntity mex = setupMock() + initPrepareServiceDelete(mex) + + when(mex.getVariable("GENGS_FoundIndicator")).thenThrow(new BpmnError("expected exception")) + + DeleteVcpeResCustService DeleteVcpeResCustService = new DeleteVcpeResCustService() + + assertTrue(doBpmnError({ _ -> DeleteVcpeResCustService.prepareServiceDelete(mex) })) + + verify(mex, never()).setVariable(processName+"WorkflowResponseSent", "true") + } + + @Test +// @Ignore + public void prepareServiceDelete_Ex() { + ExecutionEntity mex = setupMock() + initPrepareServiceDelete(mex) + + when(mex.getVariable("GENGS_FoundIndicator")).thenThrow(new RuntimeException("expected exception")) + + DeleteVcpeResCustService DeleteVcpeResCustService = new DeleteVcpeResCustService() + + assertTrue(doBpmnError({ _ -> DeleteVcpeResCustService.prepareServiceDelete(mex) })) + + verify(mex).setVariable(processName+"WorkflowResponseSent", "true") + } + + private initPrepareServiceDelete(ExecutionEntity mex) { + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("serviceInstanceId")).thenReturn("sii") + when(mex.getVariable("GENGS_FoundIndicator")).thenReturn(true) + when(mex.getVariable("mso-request-id")).thenReturn("mri") + when(mex.getVariable("DeleteVcpeResCustServiceRequest")).thenReturn(request) + when(mex.getVariable("URN_aai_endpoint")).thenReturn(aaiUriPfx) + when(mex.getVariable("GENGS_service")).thenReturn(FileUtil.readResourceFile("__files/VCPE/DeleteVcpeResCustService/serviceToDelete.xml")) + } + + // ***** getAaiAr ***** + + @Test +// @Ignore + public void getAaiAr() { + myMockGetAr("/myurl/ar1", 200, "arGetBRGById.xml"); + + ExecutionEntity mex = setupMock() + initGetAaiAr(mex) + + DeleteVcpeResCustService DeleteVcpeResCustService = new DeleteVcpeResCustService() + def (type, id) = DeleteVcpeResCustService.getAaiAr(mex, "/myurl/ar1") + + assertEquals("BRG", type) + assertEquals("ar-brgB", id) + } + + @Test +// @Ignore + public void getAaiAr_401() { + myMockGetAr("/myurl/ar1", 401, "arGetBRGById.xml"); + + ExecutionEntity mex = setupMock() + initGetAaiAr(mex) + + DeleteVcpeResCustService DeleteVcpeResCustService = new DeleteVcpeResCustService() + def (type, id) = DeleteVcpeResCustService.getAaiAr(mex, "/myurl/ar1") + + assertEquals(null, type) + assertEquals(null, id) + } + + @Test +// @Ignore + public void getAaiAr_EmptyResponse() { + myMockGetAr("/myurl/ar1", 200, "empty.txt"); + + ExecutionEntity mex = setupMock() + initGetAaiAr(mex) + + DeleteVcpeResCustService DeleteVcpeResCustService = new DeleteVcpeResCustService() + def (type, id) = DeleteVcpeResCustService.getAaiAr(mex, "/myurl/ar1") + + assertEquals(null, type) + assertEquals(null, id) + } + + private void initGetAaiAr(ExecutionEntity mex) { + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("URN_aai_endpoint")).thenReturn(aaiUriPfx) + } + + // ***** prepareVnfAndModulesDelete ***** + + @Test +// @Ignore + public void prepareVnfAndModulesDelete() { + ExecutionEntity mex = setupMock() + initPrepareVnfAndModulesDelete(mex) + + DeleteVcpeResCustService DeleteVcpeResCustService = new DeleteVcpeResCustService() + DeleteVcpeResCustService.prepareVnfAndModulesDelete(mex) + + verify(mex).getVariable(DBGFLAG) + + verify(mex).setVariable("vnfId", "vnfB") + } + + @Test +// @Ignore + public void prepareVnfAndModulesDelete_Empty() { + ExecutionEntity mex = setupMock() + initPrepareVnfAndModulesDelete(mex) + + when(mex.getVariable(Prefix+"relatedVnfIdList")).thenReturn(new LinkedList()) + + DeleteVcpeResCustService DeleteVcpeResCustService = new DeleteVcpeResCustService() + DeleteVcpeResCustService.prepareVnfAndModulesDelete(mex) + + verify(mex).getVariable(DBGFLAG) + + verify(mex).setVariable("vnfId", "") + } + + @Test +// @Ignore + public void prepareVnfAndModulesDelete_Ex() { + ExecutionEntity mex = setupMock() + initPrepareVnfAndModulesDelete(mex) + + when(mex.getVariable(Prefix+"relatedVnfIdList")).thenThrow(new RuntimeException("expected exception")) + + DeleteVcpeResCustService DeleteVcpeResCustService = new DeleteVcpeResCustService() + + assertTrue(doBpmnError({ _ -> DeleteVcpeResCustService.prepareVnfAndModulesDelete(mex) })) + } + + private initPrepareVnfAndModulesDelete(ExecutionEntity mex) { + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable(Prefix+"relatedVnfIdList")).thenReturn(Arrays.asList("vnfA", "vnfB", "vnfC")) + when(mex.getVariable(Prefix+"vnfsDeletedCount")).thenReturn(1) + } + + // ***** validateVnfDelete ***** + + @Test +// @Ignore + public void validateVnfDelete() { + ExecutionEntity mex = setupMock() + initValidateVnfDelete(mex) + + DeleteVcpeResCustService DeleteVcpeResCustService = new DeleteVcpeResCustService() + DeleteVcpeResCustService.validateVnfDelete(mex) + + verify(mex).getVariable(DBGFLAG) + + verify(mex).setVariable(Prefix+"vnfsDeletedCount", 3) + } + + @Test +// @Ignore + public void validateVnfDelete_Ex() { + ExecutionEntity mex = setupMock() + initValidateVnfDelete(mex) + + when(mex.getVariable(Prefix+"vnfsDeletedCount")).thenThrow(new RuntimeException("expected exception")) + + DeleteVcpeResCustService DeleteVcpeResCustService = new DeleteVcpeResCustService() + + assertTrue(doBpmnError({ _ -> DeleteVcpeResCustService.validateVnfDelete(mex) })) + } + + private initValidateVnfDelete(ExecutionEntity mex) { + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable(Prefix+"vnfsDeletedCount")).thenReturn(2) + } + + // ***** postProcessResponse ***** + + @Test +// @Ignore + public void postProcessResponse() { + ExecutionEntity mex = setupMock() + def map = setupMap(mex) + initPostProcessResponse(mex) + + DeleteVcpeResCustService DeleteVcpeResCustService = new DeleteVcpeResCustService() + DeleteVcpeResCustService.postProcessResponse(mex) + + verify(mex).getVariable(DBGFLAG) + + assertEquals(true, map.get(Prefix+"Success")) + + def req = map.get(Prefix+"CompleteMsoProcessRequest") + + assertTrue(req.indexOf("<request-id>mri</") >= 0) + assertTrue(req.indexOf("<source>mysrc</") >= 0) + } + + @Test +// @Ignore + public void postProcessResponse_BpmnError() { + ExecutionEntity mex = setupMock() + initPostProcessResponse(mex) + + when(mex.getVariable("source")).thenThrow(new BpmnError("expected exception")) + + DeleteVcpeResCustService DeleteVcpeResCustService = new DeleteVcpeResCustService() + + assertTrue(doBpmnError( { _ -> DeleteVcpeResCustService.postProcessResponse(mex) })) + } + + @Test +// @Ignore + public void postProcessResponse_Ex() { + ExecutionEntity mex = setupMock() + initPostProcessResponse(mex) + + when(mex.getVariable("source")).thenThrow(new RuntimeException("expected exception")) + + DeleteVcpeResCustService DeleteVcpeResCustService = new DeleteVcpeResCustService() + + assertTrue(doBpmnError( { _ -> DeleteVcpeResCustService.postProcessResponse(mex) })) + } + + private initPostProcessResponse(ExecutionEntity mex) { + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("source")).thenReturn("mysrc") + when(mex.getVariable("msoRequestId")).thenReturn("mri") + } + + + // ***** prepareFalloutRequest ***** + + @Test +// @Ignore + public void prepareFalloutRequest() { + ExecutionEntity mex = setupMock() + def map = setupMap(mex) + initPrepareFalloutRequest(mex) + + DeleteVcpeResCustService DeleteVcpeResCustService = new DeleteVcpeResCustService() + DeleteVcpeResCustService.prepareFalloutRequest(mex) + + verify(mex, times(2)).getVariable(DBGFLAG) + + def fo = map.get(Prefix+"falloutRequest") + + assertTrue(fo.indexOf("<hello>world</") >= 0) + assertTrue(fo.indexOf("ErrorMessage>mymsg</") >= 0) + assertTrue(fo.indexOf("ErrorCode>999</") >= 0) + } + + @Test +// @Ignore + public void prepareFalloutRequest_Ex() { + ExecutionEntity mex = setupMock() + def map = setupMap(mex) + initPrepareFalloutRequest(mex) + + when(mex.getVariable("WorkflowException")).thenThrow(new RuntimeException("expected exception")) + + DeleteVcpeResCustService DeleteVcpeResCustService = new DeleteVcpeResCustService() + + assertTrue(doBpmnError( { _ -> DeleteVcpeResCustService.prepareFalloutRequest(mex) })) + } + + private initPrepareFalloutRequest(ExecutionEntity mex) { + WorkflowException wfe = mock(WorkflowException.class) + + when(wfe.getErrorMessage()).thenReturn("mymsg") + when(wfe.getErrorCode()).thenReturn(999) + + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("WorkflowException")).thenReturn(wfe) + when(mex.getVariable(Prefix+"requestInfo")).thenReturn("<hello>world</hello>") + + return wfe + } + + // ***** sendSyncError ***** + + @Test +// @Ignore + public void sendSyncError() { + ExecutionEntity mex = setupMock() + def map = setupMap(mex) + initSendSyncError(mex) + + DeleteVcpeResCustService DeleteVcpeResCustService = new DeleteVcpeResCustService() + DeleteVcpeResCustService.sendSyncError(mex) + + verify(mex, times(2)).getVariable(DBGFLAG) + + verify(mex).setVariable(processName+"WorkflowResponseSent", "true") + + assertEquals("500", map.get(processName+"ResponseCode")) + assertEquals("Fail", map.get(processName+"Status")) + + def resp = map.get(processName+"Response") + + assertTrue(resp.indexOf("ErrorMessage>mymsg</") >= 0) + + verify(mex).setVariable("WorkflowResponse", resp) + } + + @Test +// @Ignore + public void sendSyncError_NotWfe() { + ExecutionEntity mex = setupMock() + def map = setupMap(mex) + initSendSyncError(mex) + + when(mex.getVariable("WorkflowException")).thenReturn("not a WFE") + + DeleteVcpeResCustService DeleteVcpeResCustService = new DeleteVcpeResCustService() + DeleteVcpeResCustService.sendSyncError(mex) + + verify(mex, times(2)).getVariable(DBGFLAG) + + verify(mex).setVariable(processName+"WorkflowResponseSent", "true") + + assertEquals("500", map.get(processName+"ResponseCode")) + assertEquals("Fail", map.get(processName+"Status")) + + def resp = map.get(processName+"Response") + + assertTrue(resp.indexOf("ErrorMessage>Sending Sync Error.</") >= 0) + + verify(mex).setVariable("WorkflowResponse", resp) + } + + @Test +// @Ignore + public void sendSyncError_NullWfe() { + ExecutionEntity mex = setupMock() + def map = setupMap(mex) + initSendSyncError(mex) + + when(mex.getVariable("WorkflowException")).thenReturn(null) + + DeleteVcpeResCustService DeleteVcpeResCustService = new DeleteVcpeResCustService() + DeleteVcpeResCustService.sendSyncError(mex) + + verify(mex, times(2)).getVariable(DBGFLAG) + + verify(mex).setVariable(processName+"WorkflowResponseSent", "true") + + assertEquals("500", map.get(processName+"ResponseCode")) + assertEquals("Fail", map.get(processName+"Status")) + + def resp = map.get(processName+"Response") + + assertTrue(resp.indexOf("ErrorMessage>Sending Sync Error.</") >= 0) + + verify(mex).setVariable("WorkflowResponse", resp) + } + + @Test +// @Ignore + public void sendSyncError_Ex() { + ExecutionEntity mex = setupMock() + def map = setupMap(mex) + initSendSyncError(mex) + + when(mex.getVariable("WorkflowException")).thenThrow(new RuntimeException("expected exception")) + + DeleteVcpeResCustService DeleteVcpeResCustService = new DeleteVcpeResCustService() + + DeleteVcpeResCustService.sendSyncError(mex) + + assertFalse(map.containsKey(processName+"ResponseCode")) + } + + private initSendSyncError(ExecutionEntity mex) { + WorkflowException wfe = mock(WorkflowException.class) + + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("mso-request-id")).thenReturn("mri") + when(mex.getVariable("WorkflowException")).thenReturn(wfe) + + when(wfe.getErrorMessage()).thenReturn("mymsg") + } + + + // ***** processJavaException ***** + + @Test +// @Ignore + public void processJavaException() { + ExecutionEntity mex = setupMock() + def map = setupMap(mex) + initProcessJavaException(mex) + + DeleteVcpeResCustService DeleteVcpeResCustService = new DeleteVcpeResCustService() + + assertTrue(doBpmnError( { _ -> DeleteVcpeResCustService.processJavaException(mex) })) + + verify(mex, times(2)).getVariable(DBGFLAG) + + verify(mex).setVariable("prefix", Prefix) + + def wfe = map.get("WorkflowException") + + assertEquals("Caught a Java Lang Exception", wfe.getErrorMessage()) + } + + @Test +// @Ignore + public void processJavaException_BpmnError() { + ExecutionEntity mex = setupMock() + def map = setupMap(mex) + initProcessJavaException(mex) + + when(mex.getVariables()).thenThrow(new BpmnError("expected exception")) + + DeleteVcpeResCustService DeleteVcpeResCustService = new DeleteVcpeResCustService() + + assertTrue(doBpmnError( { _ -> DeleteVcpeResCustService.processJavaException(mex) })) + + assertFalse(map.containsKey("WorkflowException")) + } + + @Test +// @Ignore + public void processJavaException_Ex() { + ExecutionEntity mex = setupMock() + def map = setupMap(mex) + initProcessJavaException(mex) + + when(mex.getVariables()).thenThrow(new RuntimeException("expected exception")) + + DeleteVcpeResCustService DeleteVcpeResCustService = new DeleteVcpeResCustService() + + assertTrue(doBpmnError( { _ -> DeleteVcpeResCustService.processJavaException(mex) })) + + def wfe = map.get("WorkflowException") + + assertEquals("Exception in processJavaException method", wfe.getErrorMessage()) + } + + private initProcessJavaException(ExecutionEntity mex) { + when(mex.getVariable(DBGFLAG)).thenReturn("true") + } + + private void myMockGetAr(String url, int status, String fileResp) { + stubFor(get(urlMatching(url)) + .willReturn(aResponse() + .withStatus(status) + .withHeader("Content-Type", "text/xml") + .withBodyFile("VCPE/DeleteVcpeResCustService/" + fileResp))); + } +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceBRGRollbackTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceBRGRollbackTest.groovy new file mode 100644 index 0000000000..1e8842e68f --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceBRGRollbackTest.groovy @@ -0,0 +1,654 @@ +/* + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.vcpe.scripts + + +import org.camunda.bpm.engine.ProcessEngineServices +import org.camunda.bpm.engine.RepositoryService +import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity +import org.camunda.bpm.engine.repository.ProcessDefinition +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.junit.Before +import org.junit.BeforeClass +import org.junit.Rule +import org.junit.Test +import org.junit.Ignore +import org.mockito.MockitoAnnotations +import org.camunda.bpm.engine.delegate.BpmnError +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.bpmn.mock.FileUtil + +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse +import static com.github.tomakehurst.wiremock.client.WireMock.get +import static com.github.tomakehurst.wiremock.client.WireMock.stubFor +import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching +import static org.junit.Assert.*; +import static org.mockito.Mockito.* +import static org.onap.so.bpmn.mock.StubResponseAAI.MockDeleteAllottedResource +import static org.onap.so.bpmn.mock.StubResponseAAI.MockGetAllottedResource +import static org.onap.so.bpmn.mock.StubResponseAAI.MockPatchAllottedResource + +import org.onap.so.bpmn.core.RollbackData + +import com.github.tomakehurst.wiremock.junit.WireMockRule + +class DoCreateAllottedResourceBRGRollbackTest extends GroovyTestBase { + + @Rule + public WireMockRule wireMockRule = new WireMockRule(PORT) + + String Prefix = "DCARBRGRB_" + String RbType = "DCARBRG_" + + @BeforeClass + public static void setUpBeforeClass() { + super.setUpBeforeClass() + } + + @Before + public void init() + { + MockitoAnnotations.initMocks(this) + } + + public DoCreateAllottedResourceBRGRollbackTest() { + super("DoCreateAllottedResourceBRGRollback") + } + + + // ***** preProcessRequest ***** + + @Test +// @Ignore + public void preProcessRequest() { + ExecutionEntity mex = setupMock() + initPreProcess(mex) + + DoCreateAllottedResourceBRGRollback DoCreateAllottedResourceBRGRollback = new DoCreateAllottedResourceBRGRollback() + DoCreateAllottedResourceBRGRollback.preProcessRequest(mex) + + ////verify(mex).getVariable(DBGFLAG) + verify(mex).setVariable("prefix", Prefix) + verify(mex).setVariable("serviceInstanceId", "sii") + verify(mex).setVariable("parentServiceInstanceId", "psii") + verify(mex).setVariable("allottedResourceId", "myid") + verify(mex).setVariable("rollbackAAI", true) + verify(mex).setVariable("aaiARPath", "mypath") + verify(mex).setVariable("rollbackSDNC", true) + verify(mex).setVariable("deactivateSdnc", "myactivate") + verify(mex).setVariable("deleteSdnc", "mycreate") + verify(mex).setVariable("unassignSdnc", "true") + verify(mex).setVariable("sdncDeactivateRequest", "activatereq") + verify(mex).setVariable("sdncDeleteRequest", "createreq") + verify(mex).setVariable("sdncUnassignRequest", "assignreq") + + verify(mex, never()).setVariable("skipRollback", true) + } + + @Test +// @Ignore + public void preProcessRequest_RollbackDisabled() { + ExecutionEntity mex = setupMock() + initPreProcess(mex) + + when(mex.getVariable("disableRollback")).thenReturn("true") + + DoCreateAllottedResourceBRGRollback DoCreateAllottedResourceBRGRollback = new DoCreateAllottedResourceBRGRollback() + DoCreateAllottedResourceBRGRollback.preProcessRequest(mex) + + ////verify(mex).getVariable(DBGFLAG) + verify(mex).setVariable("prefix", Prefix) + verify(mex).setVariable("serviceInstanceId", "sii") + verify(mex).setVariable("parentServiceInstanceId", "psii") + verify(mex).setVariable("allottedResourceId", "myid") + verify(mex).setVariable("rollbackAAI", true) + verify(mex).setVariable("aaiARPath", "mypath") + verify(mex).setVariable("rollbackSDNC", true) + verify(mex).setVariable("deactivateSdnc", "myactivate") + verify(mex).setVariable("deleteSdnc", "mycreate") + verify(mex).setVariable("unassignSdnc", "true") + verify(mex).setVariable("sdncDeactivateRequest", "activatereq") + verify(mex).setVariable("sdncDeleteRequest", "createreq") + verify(mex).setVariable("sdncUnassignRequest", "assignreq") + + verify(mex).setVariable("skipRollback", true) + } + + @Test +// @Ignore + public void preProcessRequest_NoAAI() { + ExecutionEntity mex = setupMock() + def data = initPreProcess(mex) + + when(mex.getVariable("rollbackAAI")).thenReturn(false) + data.put(RbType, "rollbackAAI", "false") + + DoCreateAllottedResourceBRGRollback DoCreateAllottedResourceBRGRollback = new DoCreateAllottedResourceBRGRollback() + DoCreateAllottedResourceBRGRollback.preProcessRequest(mex) + + //verify(mex).getVariable(DBGFLAG) + verify(mex).setVariable("prefix", Prefix) + verify(mex).setVariable("serviceInstanceId", "sii") + verify(mex).setVariable("parentServiceInstanceId", "psii") + verify(mex).setVariable("allottedResourceId", "myid") + verify(mex, never()).setVariable("rollbackAAI", true) + verify(mex, never()).setVariable("aaiARPath", "mypath") + verify(mex).setVariable("rollbackSDNC", true) + verify(mex).setVariable("deactivateSdnc", "myactivate") + verify(mex).setVariable("deleteSdnc", "mycreate") + verify(mex).setVariable("unassignSdnc", "true") + verify(mex).setVariable("sdncDeactivateRequest", "activatereq") + verify(mex).setVariable("sdncDeleteRequest", "createreq") + verify(mex).setVariable("sdncUnassignRequest", "assignreq") + + verify(mex, never()).setVariable("skipRollback", true) + } + + @Test +// @Ignore + public void preProcessRequest_NoAssign() { + ExecutionEntity mex = setupMock() + def data = initPreProcess(mex) + + when(mex.getVariable("rollbackSDNC")).thenReturn(false) + data.put(RbType, "rollbackSDNCassign", "false") + + DoCreateAllottedResourceBRGRollback DoCreateAllottedResourceBRGRollback = new DoCreateAllottedResourceBRGRollback() + DoCreateAllottedResourceBRGRollback.preProcessRequest(mex) + + //verify(mex).getVariable(DBGFLAG) + verify(mex).setVariable("prefix", Prefix) + verify(mex).setVariable("serviceInstanceId", "sii") + verify(mex).setVariable("parentServiceInstanceId", "psii") + verify(mex).setVariable("allottedResourceId", "myid") + verify(mex).setVariable("rollbackAAI", true) + verify(mex).setVariable("aaiARPath", "mypath") + verify(mex, never()).setVariable("rollbackSDNC", true) + verify(mex, never()).setVariable("deactivateSdnc", "myactivate") + verify(mex, never()).setVariable("deleteSdnc", "mycreate") + verify(mex, never()).setVariable("unassignSdnc", "true") + verify(mex, never()).setVariable("sdncDeactivateRequest", "activatereq") + verify(mex, never()).setVariable("sdncDeleteRequest", "createreq") + verify(mex, never()).setVariable("sdncUnassignRequest", "assignreq") + + verify(mex, never()).setVariable("skipRollback", true) + } + + @Test +// @Ignore + public void preProcessRequest_NoAAI_NoAssign() { + ExecutionEntity mex = setupMock() + initPreProcess(mex) + + when(mex.getVariable("rollbackAAI")).thenReturn(false) + when(mex.getVariable("rollbackSDNC")).thenReturn(false) + + DoCreateAllottedResourceBRGRollback DoCreateAllottedResourceBRGRollback = new DoCreateAllottedResourceBRGRollback() + DoCreateAllottedResourceBRGRollback.preProcessRequest(mex) + + verify(mex).setVariable("skipRollback", true) + } + + @Test +// @Ignore + public void preProcessRequest_NoRbStructure() { + ExecutionEntity mex = setupMock() + initPreProcess(mex) + + when(mex.getVariable("rollbackData")).thenReturn(new RollbackData()) + + DoCreateAllottedResourceBRGRollback DoCreateAllottedResourceBRGRollback = new DoCreateAllottedResourceBRGRollback() + DoCreateAllottedResourceBRGRollback.preProcessRequest(mex) + + verify(mex).setVariable("skipRollback", true) + } + + @Test +// @Ignore + public void preProcessRequest_NullRb() { + ExecutionEntity mex = setupMock() + initPreProcess(mex) + + when(mex.getVariable("rollbackData")).thenReturn(null) + + DoCreateAllottedResourceBRGRollback DoCreateAllottedResourceBRGRollback = new DoCreateAllottedResourceBRGRollback() + DoCreateAllottedResourceBRGRollback.preProcessRequest(mex) + + verify(mex).setVariable("skipRollback", true) + } + + @Test +// @Ignore + public void preProcessRequest_BpmnError() { + ExecutionEntity mex = setupMock() + initPreProcess(mex) + + when(mex.getVariable("rollbackData")).thenThrow(new BpmnError("expected exception")) + + DoCreateAllottedResourceBRGRollback DoCreateAllottedResourceBRGRollback = new DoCreateAllottedResourceBRGRollback() + + assertTrue(doBpmnError( { _ -> DoCreateAllottedResourceBRGRollback.preProcessRequest(mex) })) + } + + @Test +// @Ignore + public void preProcessRequest_Ex() { + ExecutionEntity mex = setupMock() + initPreProcess(mex) + + when(mex.getVariable("rollbackData")).thenThrow(new RuntimeException("expected exception")) + + DoCreateAllottedResourceBRGRollback DoCreateAllottedResourceBRGRollback = new DoCreateAllottedResourceBRGRollback() + + assertTrue(doBpmnError( { _ -> DoCreateAllottedResourceBRGRollback.preProcessRequest(mex) })) + } + + @Test + @Ignore + public void updateAaiAROrchStatus() { + ExecutionEntity mex = setupMock() + initUpdateAaiAROrchStatus(mex) + + MockGetAllottedResource(CUST, SVC, INST, ARID, "VCPE/DoCreateAllottedResourceBRGRollback/arGetById.xml") + MockPatchAllottedResource(CUST, SVC, INST, ARID) + + DoCreateAllottedResourceBRGRollback DoCreateAllottedResourceBRGRollback = new DoCreateAllottedResourceBRGRollback() + DoCreateAllottedResourceBRGRollback.updateAaiAROrchStatus(mex, "success") + } + + @Test +// @Ignore + public void updateAaiAROrchStatus_EmptyResponse() { + ExecutionEntity mex = setupMock() + initUpdateAaiAROrchStatus(mex) + + wireMockRule + .stubFor(get(urlMatching("/aai/v[0-9]+/.*")) + .willReturn(aResponse() + .withStatus(200))) + + DoCreateAllottedResourceBRGRollback DoCreateAllottedResourceBRGRollback = new DoCreateAllottedResourceBRGRollback() + + assertTrue(doBpmnError( { _ -> DoCreateAllottedResourceBRGRollback.updateAaiAROrchStatus(mex, "success") })) + } + + @Test +// @Ignore + public void updateAaiAROrchStatus_NoArPath() { + ExecutionEntity mex = setupMock() + initUpdateAaiAROrchStatus(mex) + + MockGetAllottedResource(CUST, SVC, INST, ARID, "VCPE/DoCreateAllottedResourceBRGRollback/arGetById.xml") + MockPatchAllottedResource(CUST, SVC, INST, ARID) + + when(mex.getVariable("aaiARPath")).thenReturn(null) + + DoCreateAllottedResourceBRGRollback DoCreateAllottedResourceBRGRollback = new DoCreateAllottedResourceBRGRollback() + + assertTrue(doBpmnError( { _ -> DoCreateAllottedResourceBRGRollback.updateAaiAROrchStatus(mex, "success") })) + } + + + // ***** validateSDNCResp ***** + + @Test +// @Ignore + public void validateSDNCResp() { + ExecutionEntity mex = setupMock() + initValidateSDNCResp(mex) + def resp = initValidateSDNCResp_Resp() + + when(mex.getVariable(Prefix+"sdncResponseSuccess")).thenReturn(true) + + DoCreateAllottedResourceBRGRollback DoCreateAllottedResourceBRGRollback = new DoCreateAllottedResourceBRGRollback() + + DoCreateAllottedResourceBRGRollback.validateSDNCResp(mex, resp, "create") + + verify(mex).getVariable("WorkflowException") + verify(mex).getVariable("SDNCA_SuccessIndicator") + } + + @Test +// @Ignore + public void validateSDNCResp_Unsuccessful() { + ExecutionEntity mex = setupMock() + initValidateSDNCResp(mex) + def resp = initValidateSDNCResp_Resp() + + when(mex.getVariable(Prefix+"sdncResponseSuccess")).thenReturn(false) + + DoCreateAllottedResourceBRGRollback DoCreateAllottedResourceBRGRollback = new DoCreateAllottedResourceBRGRollback() + + assertTrue(doBpmnError( { _ -> DoCreateAllottedResourceBRGRollback.validateSDNCResp(mex, resp, "create") })) + } + + @Test +// @Ignore + public void validateSDNCResp_BpmnError404() { + ExecutionEntity mex = setupMock() + initValidateSDNCResp(mex) + def resp = initValidateSDNCResp_Resp() + when(mex.getVariable(Prefix+"sdncResponseSuccess")).thenReturn(true) + + when(mex.getVariable("WorkflowException")).thenThrow(new BpmnError("404", "expected exception")) + + DoCreateAllottedResourceBRGRollback DoCreateAllottedResourceBRGRollback = new DoCreateAllottedResourceBRGRollback() + + DoCreateAllottedResourceBRGRollback.validateSDNCResp(mex, resp, "create") + } + + @Test +// @Ignore + public void validateSDNCResp_BpmnError() { + ExecutionEntity mex = setupMock() + initValidateSDNCResp(mex) + def resp = initValidateSDNCResp_Resp() + when(mex.getVariable(Prefix+"sdncResponseSuccess")).thenReturn(true) + + when(mex.getVariable("WorkflowException")).thenThrow(new BpmnError("expected exception")) + + DoCreateAllottedResourceBRGRollback DoCreateAllottedResourceBRGRollback = new DoCreateAllottedResourceBRGRollback() + + assertTrue(doBpmnError( { _ -> DoCreateAllottedResourceBRGRollback.validateSDNCResp(mex, resp, "create") })) + } + + @Test +// @Ignore + public void validateSDNCResp_Ex() { + ExecutionEntity mex = setupMock() + initValidateSDNCResp(mex) + def resp = initValidateSDNCResp_Resp() + when(mex.getVariable(Prefix+"sdncResponseSuccess")).thenReturn(true) + + when(mex.getVariable("WorkflowException")).thenThrow(new RuntimeException("expected exception")) + + DoCreateAllottedResourceBRGRollback DoCreateAllottedResourceBRGRollback = new DoCreateAllottedResourceBRGRollback() + + assertTrue(doBpmnError( { _ -> DoCreateAllottedResourceBRGRollback.validateSDNCResp(mex, resp, "create") })) + } + + @Test + @Ignore + public void deleteAaiAR() { + ExecutionEntity mex = setupMock() + initDeleteAaiAR(mex) + + MockGetAllottedResource(CUST, SVC, INST, ARID, "VCPE/DoCreateAllottedResourceBRGRollback/arGetById.xml") + MockDeleteAllottedResource(CUST, SVC, INST, ARID, VERS) + + DoCreateAllottedResourceBRGRollback DoCreateAllottedResourceBRGRollback = new DoCreateAllottedResourceBRGRollback() + DoCreateAllottedResourceBRGRollback.deleteAaiAR(mex) + } + + @Test +// @Ignore + public void deleteAaiAR_NoArPath() { + ExecutionEntity mex = setupMock() + initDeleteAaiAR(mex) + + MockGetAllottedResource(CUST, SVC, INST, ARID, "VCPE/DoCreateAllottedResourceBRGRollback/arGetById.xml") + MockDeleteAllottedResource(CUST, SVC, INST, ARID, VERS) + + when(mex.getVariable("aaiARPath")).thenReturn("") + + DoCreateAllottedResourceBRGRollback DoCreateAllottedResourceBRGRollback = new DoCreateAllottedResourceBRGRollback() + + assertTrue(doBpmnError( { _ -> DoCreateAllottedResourceBRGRollback.deleteAaiAR(mex) })) + } + + @Test +// @Ignore + public void deleteAaiAR_BpmnError() { + ExecutionEntity mex = setupMock() + initDeleteAaiAR(mex) + + MockGetAllottedResource(CUST, SVC, INST, ARID, "VCPE/DoCreateAllottedResourceBRGRollback/arGetById.xml") + MockDeleteAllottedResource(CUST, SVC, INST, ARID, VERS) + + when(mex.getVariable("aaiARPath")).thenThrow(new BpmnError("expected exception")) + + DoCreateAllottedResourceBRGRollback DoCreateAllottedResourceBRGRollback = new DoCreateAllottedResourceBRGRollback() + + assertTrue(doBpmnError( { _ -> DoCreateAllottedResourceBRGRollback.deleteAaiAR(mex) })) + } + + @Test +// @Ignore + public void deleteAaiAR_Ex() { + ExecutionEntity mex = setupMock() + initDeleteAaiAR(mex) + + MockGetAllottedResource(CUST, SVC, INST, ARID, "VCPE/DoCreateAllottedResourceBRGRollback/arGetById.xml") + MockDeleteAllottedResource(CUST, SVC, INST, ARID, VERS) + + when(mex.getVariable("aaiARPath")).thenThrow(new RuntimeException("expected exception")) + + DoCreateAllottedResourceBRGRollback DoCreateAllottedResourceBRGRollback = new DoCreateAllottedResourceBRGRollback() + + assertTrue(doBpmnError( { _ -> DoCreateAllottedResourceBRGRollback.deleteAaiAR(mex) })) + } + + @Test +// @Ignore + public void postProcessRequest() { + ExecutionEntity mex = setupMock() + initPostProcessRequest(mex) + + DoCreateAllottedResourceBRGRollback DoCreateAllottedResourceBRGRollback = new DoCreateAllottedResourceBRGRollback() + DoCreateAllottedResourceBRGRollback.postProcessRequest(mex) + + //verify(mex).getVariable(DBGFLAG) + verify(mex).setVariable("rollbackData", null) + verify(mex).setVariable("rolledBack", true) + } + + @Test +// @Ignore + public void postProcessRequest_RolledBack() { + ExecutionEntity mex = setupMock() + initPostProcessRequest(mex) + + when(mex.getVariable("skipRollback")).thenReturn(true) + + DoCreateAllottedResourceBRGRollback DoCreateAllottedResourceBRGRollback = new DoCreateAllottedResourceBRGRollback() + DoCreateAllottedResourceBRGRollback.postProcessRequest(mex) + + //verify(mex).getVariable(DBGFLAG) + verify(mex).setVariable("rollbackData", null) + verify(mex, never()).setVariable("rolledBack", true) + } + + @Test +// @Ignore + public void postProcessRequest_BpmnError() { + ExecutionEntity mex = setupMock() + initPostProcessRequest(mex) + + when(mex.getVariable("skipRollback")).thenThrow(new BpmnError("expected exception")) + + DoCreateAllottedResourceBRGRollback DoCreateAllottedResourceBRGRollback = new DoCreateAllottedResourceBRGRollback() + DoCreateAllottedResourceBRGRollback.postProcessRequest(mex) + + //verify(mex).getVariable(DBGFLAG) + verify(mex).setVariable("rollbackData", null) + verify(mex, never()).setVariable("rolledBack", true) + } + + @Test +// @Ignore + public void postProcessRequest_Ex() { + ExecutionEntity mex = setupMock() + initPostProcessRequest(mex) + + when(mex.getVariable("skipRollback")).thenThrow(new RuntimeException("expected exception")) + + DoCreateAllottedResourceBRGRollback DoCreateAllottedResourceBRGRollback = new DoCreateAllottedResourceBRGRollback() + DoCreateAllottedResourceBRGRollback.postProcessRequest(mex) + + //verify(mex).getVariable(DBGFLAG) + verify(mex).setVariable("rollbackData", null) + verify(mex, never()).setVariable("rolledBack", true) + } + + @Test +// @Ignore + public void processRollbackException() { + ExecutionEntity mex = setupMock() + initProcessRollbackException(mex) + + DoCreateAllottedResourceBRGRollback DoCreateAllottedResourceBRGRollback = new DoCreateAllottedResourceBRGRollback() + DoCreateAllottedResourceBRGRollback.processRollbackException(mex) + + //verify(mex).getVariable(DBGFLAG) + verify(mex).setVariable("rollbackData", null) + verify(mex).setVariable("rolledBack", false) + verify(mex).setVariable("rollbackError", "Caught exception in AllottedResource Create Rollback") + verify(mex).setVariable("WorkflowException", null) + } + + @Test +// @Ignore + public void processRollbackException_BpmnError() { + ExecutionEntity mex = setupMock() + initProcessRollbackException(mex) + + doThrow(new BpmnError("expected exception")).when(mex).setVariable("rollbackData", null) + + DoCreateAllottedResourceBRGRollback DoCreateAllottedResourceBRGRollback = new DoCreateAllottedResourceBRGRollback() + DoCreateAllottedResourceBRGRollback.processRollbackException(mex) + } + + @Test +// @Ignore + public void processRollbackException_Ex() { + ExecutionEntity mex = setupMock() + initProcessRollbackException(mex) + + doThrow(new RuntimeException("expected exception")).when(mex).setVariable("rollbackData", null) + + DoCreateAllottedResourceBRGRollback DoCreateAllottedResourceBRGRollback = new DoCreateAllottedResourceBRGRollback() + DoCreateAllottedResourceBRGRollback.processRollbackException(mex) + } + + @Test +// @Ignore + public void processRollbackJavaException() { + ExecutionEntity mex = setupMock() + initProcessRollbackException(mex) + + DoCreateAllottedResourceBRGRollback DoCreateAllottedResourceBRGRollback = new DoCreateAllottedResourceBRGRollback() + DoCreateAllottedResourceBRGRollback.processRollbackJavaException(mex) + + //verify(mex).getVariable(DBGFLAG) + verify(mex).setVariable("rollbackData", null) + verify(mex).setVariable("rolledBack", false) + verify(mex).setVariable("rollbackError", "Caught Java exception in AllottedResource Create Rollback") + verify(mex, never()).setVariable("WorkflowException", null) + } + + @Test +// @Ignore + public void processRollbackJavaException_BpmnError() { + ExecutionEntity mex = setupMock() + initProcessRollbackException(mex) + + doThrow(new BpmnError("expected exception")).when(mex).setVariable("rollbackData", null) + + DoCreateAllottedResourceBRGRollback DoCreateAllottedResourceBRGRollback = new DoCreateAllottedResourceBRGRollback() + DoCreateAllottedResourceBRGRollback.processRollbackJavaException(mex) + } + + @Test +// @Ignore + public void processRollbackJavaException_Ex() { + ExecutionEntity mex = setupMock() + initProcessRollbackException(mex) + + doThrow(new RuntimeException("expected exception")).when(mex).setVariable("rollbackData", null) + + DoCreateAllottedResourceBRGRollback DoCreateAllottedResourceBRGRollback = new DoCreateAllottedResourceBRGRollback() + DoCreateAllottedResourceBRGRollback.processRollbackJavaException(mex) + } + + private RollbackData initPreProcess(ExecutionEntity mex) { + def data = new RollbackData() + + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("rollbackData")).thenReturn(data) + when(mex.getVariable("rollbackAAI")).thenReturn(true) + when(mex.getVariable("rollbackSDNC")).thenReturn(true) + when(mex.getVariable("disableRollback")).thenReturn("false") + + data.put("SERVICEINSTANCE", "allottedResourceId", "myid") + + data.put(RbType, "serviceInstanceId", "sii") + data.put(RbType, "parentServiceInstanceId", "psii") + + data.put(RbType, "rollbackAAI", "true") + data.put(RbType, "aaiARPath", "mypath") + + data.put(RbType, "rollbackSDNCassign", "true") + data.put(RbType, "rollbackSDNCactivate", "myactivate") + data.put(RbType, "rollbackSDNCcreate", "mycreate") + data.put(RbType, "sdncActivateRollbackReq", "activatereq") + data.put(RbType, "sdncCreateRollbackReq", "createreq") + data.put(RbType, "sdncAssignRollbackReq", "assignreq") + + return data + } + + private initUpdateAaiAROrchStatus(ExecutionEntity mex) { + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("aaiARPath")).thenReturn(aaiUriPfx + "/aai/v9/business/customers/customer/"+CUST+"/service-subscriptions/service-subscription/"+SVC+"/service-instances/service-instance/"+INST+"/allotted-resources/allotted-resource/"+ARID) + when(mex.getVariable("aai.endpoint")).thenReturn(aaiUriPfx) + } + + private initValidateSDNCResp(ExecutionEntity mex) { + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("prefix")).thenReturn(Prefix) + when(mex.getVariable("SDNCA_SuccessIndicator")).thenReturn(true) + } + + private String initValidateSDNCResp_Resp() { + return "<response-data><response-code>200</response-code></response-data>" + } + + private initDeleteAaiAR(ExecutionEntity mex) { + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("aaiARResourceVersion")).thenReturn(VERS) + when(mex.getVariable("aaiARPath")).thenReturn(aaiUriPfx + "/aai/v9/business/customers/customer/"+CUST+"/service-subscriptions/service-subscription/"+SVC+"/service-instances/service-instance/"+INST+"/allotted-resources/allotted-resource/"+ARID) + when(mex.getVariable("aai.endpoint")).thenReturn(aaiUriPfx) + } + + private initPostProcessRequest(ExecutionEntity mex) { + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("skipRollback")).thenReturn(false) + } + + private initProcessRollbackException(ExecutionEntity mex) { + when(mex.getVariable(DBGFLAG)).thenReturn("true") + } + + private initProcessRollbackJavaException(ExecutionEntity mex) { + when(mex.getVariable(DBGFLAG)).thenReturn("true") + } + +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceBRGTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceBRGTest.groovy new file mode 100644 index 0000000000..543bb1db05 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceBRGTest.groovy @@ -0,0 +1,999 @@ +/* + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.vcpe.scripts + + +import org.camunda.bpm.engine.ProcessEngineServices +import org.camunda.bpm.engine.RepositoryService +import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity +import org.camunda.bpm.engine.repository.ProcessDefinition +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.junit.Before +import org.junit.BeforeClass +import org.junit.Rule +import org.junit.Test +import org.junit.Ignore +import org.mockito.MockitoAnnotations +import org.camunda.bpm.engine.delegate.BpmnError +import org.onap.so.bpmn.core.UrnPropertiesReader +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.bpmn.mock.FileUtil + +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse +import static com.github.tomakehurst.wiremock.client.WireMock.put +import static com.github.tomakehurst.wiremock.client.WireMock.stubFor +import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching +import static org.junit.Assert.*; +import static org.mockito.Mockito.* +import static org.onap.so.bpmn.mock.StubResponseAAI.MockGetAllottedResource +import static org.onap.so.bpmn.mock.StubResponseAAI.MockPatchAllottedResource +import static org.onap.so.bpmn.mock.StubResponseAAI.MockPutAllottedResource +import static org.onap.so.bpmn.mock.StubResponseAAI.MockPutAllottedResource_500 + +import org.onap.so.bpmn.core.RollbackData +import org.onap.so.bpmn.vcpe.scripts.MapSetter + +import com.github.tomakehurst.wiremock.junit.WireMockRule + +class DoCreateAllottedResourceBRGTest extends GroovyTestBase { + + @Rule + public WireMockRule wireMockRule = new WireMockRule(PORT) + + String Prefix = "DCARBRG_" + + @BeforeClass + public static void setUpBeforeClass() { + super.setUpBeforeClass() + } + + @Before + public void init() + { + MockitoAnnotations.initMocks(this) + } + + public DoCreateAllottedResourceBRGTest() { + super("DoCreateAllottedResourceBRG") + } + + + // ***** preProcessRequest ***** + + @Test +// @Ignore + public void preProcessRequest() { + ExecutionEntity mex = setupMock() + initPreProcess(mex) + + DoCreateAllottedResourceBRG DoCreateAllottedResourceBRG = new DoCreateAllottedResourceBRG() + DoCreateAllottedResourceBRG.preProcessRequest(mex) + + //verify(mex).getVariable(DBGFLAG) + verify(mex).setVariable("prefix", Prefix) + + assertTrue(checkMissingPreProcessRequest("mso.workflow.sdncadapter.callback")) + assertTrue(checkMissingPreProcessRequest("mso.workflow.sdnc.replication.delay")) + assertTrue(checkMissingPreProcessRequest("serviceInstanceId")) + assertTrue(checkMissingPreProcessRequest("parentServiceInstanceId")) + assertTrue(checkMissingPreProcessRequest("allottedResourceModelInfo")) + assertTrue(checkMissingPreProcessRequest("vni")) + assertTrue(checkMissingPreProcessRequest("vgmuxBearerIP")) + assertTrue(checkMissingPreProcessRequest("brgWanMacAddress")) + assertTrue(checkMissingPreProcessRequest("allottedResourceRole")) + assertTrue(checkMissingPreProcessRequest("allottedResourceType")) + } + + + // ***** getAaiAR ***** + + @Test + @Ignore + public void getAaiAR() { + MockGetAllottedResource(CUST, SVC, INST, ARID, "VCPE/DoCreateAllottedResourceBRG/getArBrg.xml") + + ExecutionEntity mex = setupMock() + initGetAaiAR(mex) + + DoCreateAllottedResourceBRG DoCreateAllottedResourceBRG = new DoCreateAllottedResourceBRG() + DoCreateAllottedResourceBRG.getAaiAR(mex) + + verify(mex).setVariable("foundActiveAR", true) + } + + @Test +// @Ignore + public void getAaiAR_Duplicate() { + MockGetAllottedResource(CUST, SVC, INST, ARID, "VCPE/DoCreateAllottedResourceBRG/getArBrg.xml") + + ExecutionEntity mex = setupMock() + initGetAaiAR(mex) + + // fail if duplicate + when(mex.getVariable("failExists")).thenReturn("true") + + DoCreateAllottedResourceBRG DoCreateAllottedResourceBRG = new DoCreateAllottedResourceBRG() + + assertTrue(doBpmnError( { _ -> DoCreateAllottedResourceBRG.getAaiAR(mex) })) + } + + @Test +// @Ignore + public void getAaiAR_NotActive() { + MockGetAllottedResource(CUST, SVC, INST, ARID, "VCPE/DoCreateAllottedResourceBRG/getArBrg.xml") + + ExecutionEntity mex = setupMock() + initGetAaiAR(mex) + + // not active + when(mex.getVariable("aaiAROrchStatus")).thenReturn("not-active") + + DoCreateAllottedResourceBRG DoCreateAllottedResourceBRG = new DoCreateAllottedResourceBRG() + + assertTrue(doBpmnError( { _ -> DoCreateAllottedResourceBRG.getAaiAR(mex) })) + } + + @Test + @Ignore + public void getAaiAR_NoStatus() { + MockGetAllottedResource(CUST, SVC, INST, ARID, "VCPE/DoCreateAllottedResourceBRG/getArBrg.xml") + + ExecutionEntity mex = setupMock() + initGetAaiAR(mex) + + when(mex.getVariable("aaiAROrchStatus")).thenReturn(null) + + DoCreateAllottedResourceBRG DoCreateAllottedResourceBRG = new DoCreateAllottedResourceBRG() + DoCreateAllottedResourceBRG.getAaiAR(mex) + + verify(mex, never()).setVariable("foundActiveAR", true) + } + + + // ***** createAaiAR ***** + + @Test + @Ignore + public void createAaiAR() { + ExecutionEntity mex = setupMock() + def map = setupMap(mex) + initCreateAaiAr(mex) + + MockPutAllottedResource(CUST, SVC, INST, ARID) + + DoCreateAllottedResourceBRG DoCreateAllottedResourceBRG = new DoCreateAllottedResourceBRG() + DoCreateAllottedResourceBRG.createAaiAR(mex) + + def data = map.get("rollbackData") + assertNotNull(data) + assertTrue(data instanceof RollbackData) + + assertEquals("45", data.get(Prefix, "disableRollback")) + assertEquals("true", data.get(Prefix, "rollbackAAI")) + assertEquals(ARID, data.get(Prefix, "allottedResourceId")) + assertEquals("sii", data.get(Prefix, "serviceInstanceId")) + assertEquals("psii", data.get(Prefix, "parentServiceInstanceId")) + assertEquals(mex.getVariable("PSI_resourceLink")+"/allotted-resources/allotted-resource/"+ARID, data.get(Prefix, "aaiARPath")) + } + + @Test + @Ignore + public void createAaiAR_NoArid_NoModelUuids() { + ExecutionEntity mex = setupMock() + def map = setupMap(mex) + initCreateAaiAr(mex) + + // no allottedResourceId - will be generated + + when(mex.getVariable("allottedResourceId")).thenReturn(null) + + wireMockRule + .stubFor(put(urlMatching("/aai/.*/allotted-resource/.*")) + .willReturn(aResponse() + .withStatus(200))) + + DoCreateAllottedResourceBRG DoCreateAllottedResourceBRG = new DoCreateAllottedResourceBRG() + DoCreateAllottedResourceBRG.createAaiAR(mex) + + def arid = map.get("allottedResourceId") + assertNotNull(arid) + assertFalse(arid.isEmpty()) + + def data = map.get("rollbackData") + assertNotNull(data) + assertTrue(data instanceof RollbackData) + + assertEquals(arid, data.get(Prefix, "allottedResourceId")) + } + + @Test +// @Ignore + public void createAaiAR_MissingPsiLink() { + ExecutionEntity mex = setupMock() + initCreateAaiAr(mex) + + when(mex.getVariable("PSI_resourceLink")).thenReturn(null) + + MockPutAllottedResource(CUST, SVC, INST, ARID) + + DoCreateAllottedResourceBRG DoCreateAllottedResourceBRG = new DoCreateAllottedResourceBRG() + + assertTrue(doBpmnError({ _ -> DoCreateAllottedResourceBRG.createAaiAR(mex) })) + } + + @Test +// @Ignore + public void createAaiAR_HttpFailed() { + ExecutionEntity mex = setupMock() + initCreateAaiAr(mex) + + MockPutAllottedResource_500(CUST, SVC, INST, ARID) + + DoCreateAllottedResourceBRG DoCreateAllottedResourceBRG = new DoCreateAllottedResourceBRG() + + assertTrue(doBpmnError({ _ -> DoCreateAllottedResourceBRG.createAaiAR(mex) })) + } + + @Test +// @Ignore + public void createAaiAR_BpmnError() { + ExecutionEntity mex = setupMock() + initCreateAaiAr(mex) + + when(mex.getVariable("aai.endpoint")).thenThrow(new BpmnError("expected exception")) + + MockPutAllottedResource(CUST, SVC, INST, ARID) + + DoCreateAllottedResourceBRG DoCreateAllottedResourceBRG = new DoCreateAllottedResourceBRG() + + assertTrue(doBpmnError({ _ -> DoCreateAllottedResourceBRG.createAaiAR(mex) })) + } + + @Test +// @Ignore + public void createAaiAR_Ex() { + ExecutionEntity mex = setupMock() + initCreateAaiAr(mex) + + when(mex.getVariable("aai.endpoint")).thenThrow(new RuntimeException("expected exception")) + + MockPutAllottedResource(CUST, SVC, INST, ARID) + + DoCreateAllottedResourceBRG DoCreateAllottedResourceBRG = new DoCreateAllottedResourceBRG() + + assertTrue(doBpmnError({ _ -> DoCreateAllottedResourceBRG.createAaiAR(mex) })) + } + + + // ***** buildSDNCRequest ***** + + @Test +// @Ignore + public void buildSDNCRequest() { + ExecutionEntity mex = setupMock() + initBuildSDNCRequest(mex) + + DoCreateAllottedResourceBRG DoCreateAllottedResourceBRG = new DoCreateAllottedResourceBRG() + + String result = DoCreateAllottedResourceBRG.buildSDNCRequest(mex, "myact", "myreq") + + assertTrue(result.indexOf("<sdncadapter:RequestId>myreq</") >= 0) + assertTrue(result.indexOf("<sdncadapter:SvcAction>myact</") >= 0) + assertTrue(result.indexOf("<allotted-resource-id>ari</") >= 0) + assertTrue(result.indexOf("<sdncadapter:SvcInstanceId>sii</") >= 0) + assertTrue(result.indexOf("<service-instance-id>sii</") >= 0) + assertTrue(result.indexOf("<parent-service-instance-id>psii</") >= 0) + assertTrue(result.indexOf("<subscription-service-type>sst</") >= 0) + assertTrue(result.indexOf("<global-customer-id>gci</") >= 0) + assertTrue(result.indexOf("<sdncadapter:CallbackUrl>scu</") >= 0) + assertTrue(result.indexOf("<request-id>mri</") >= 0) + assertTrue(result.indexOf("<brg-wan-mac-address>bwma</") >= 0) + assertTrue(result.indexOf("<vni>myvni</") >= 0) + assertTrue(result.indexOf("<vgmux-bearer-ip>vbi</") >= 0) + assertTrue(result.indexOf("<model-invariant-uuid>miu</") >= 0) + assertTrue(result.indexOf("<model-uuid>mu</") >= 0) + assertTrue(result.indexOf("<model-customization-uuid>mcu</") >= 0) + assertTrue(result.indexOf("<model-version>mv</") >= 0) + assertTrue(result.indexOf("<model-name>mn</") >= 0) + } + + @Test +// @Ignore + public void buildSDNCRequest_EmptyModelInfo() { + ExecutionEntity mex = setupMock() + initBuildSDNCRequest(mex) + + when(mex.getVariable("allottedResourceModelInfo")).thenReturn("{}") + + DoCreateAllottedResourceBRG DoCreateAllottedResourceBRG = new DoCreateAllottedResourceBRG() + + String result = DoCreateAllottedResourceBRG.buildSDNCRequest(mex, "myact", "myreq") + + assertTrue(result.indexOf("<sdncadapter:RequestId>myreq</") >= 0) + assertTrue(result.indexOf("<sdncadapter:SvcAction>myact</") >= 0) + assertTrue(result.indexOf("<allotted-resource-id>ari</") >= 0) + assertTrue(result.indexOf("<sdncadapter:SvcInstanceId>sii</") >= 0) + assertTrue(result.indexOf("<service-instance-id>sii</") >= 0) + assertTrue(result.indexOf("<parent-service-instance-id>psii</") >= 0) + assertTrue(result.indexOf("<subscription-service-type>sst</") >= 0) + assertTrue(result.indexOf("<global-customer-id>gci</") >= 0) + assertTrue(result.indexOf("<sdncadapter:CallbackUrl>scu</") >= 0) + assertTrue(result.indexOf("<request-id>mri</") >= 0) + assertTrue(result.indexOf("<brg-wan-mac-address>bwma</") >= 0) + assertTrue(result.indexOf("<vni>myvni</") >= 0) + assertTrue(result.indexOf("<vgmux-bearer-ip>vbi</") >= 0) + assertTrue(result.indexOf("<model-invariant-uuid/>") >= 0) + assertTrue(result.indexOf("<model-uuid/>") >= 0) + assertTrue(result.indexOf("<model-customization-uuid/>") >= 0) + assertTrue(result.indexOf("<model-version/>") >= 0) + assertTrue(result.indexOf("<model-name/>") >= 0) + } + + @Test +// @Ignore + public void buildSDNCRequest_Ex() { + ExecutionEntity mex = setupMock() + initBuildSDNCRequest(mex) + + when(mex.getVariable("allottedResourceId")).thenThrow(new RuntimeException("expected exception")) + + DoCreateAllottedResourceBRG DoCreateAllottedResourceBRG = new DoCreateAllottedResourceBRG() + + assertTrue(doBpmnError({ _ -> DoCreateAllottedResourceBRG.buildSDNCRequest(mex, "myact", "myreq") })) + } + + + // ***** preProcessSDNCAssign ***** + + @Test +// @Ignore + public void preProcessSDNCAssign() { + ExecutionEntity mex = setupMock() + def map = setupMap(mex) + def data = initPreProcessSDNC(mex) + + DoCreateAllottedResourceBRG DoCreateAllottedResourceBRG = new DoCreateAllottedResourceBRG() + DoCreateAllottedResourceBRG.preProcessSDNCAssign(mex) + + def req = map.get("sdncAssignRequest") + assertNotNull(req) + + assertEquals(data, map.get("rollbackData")) + + def rbreq = data.get(Prefix, "sdncAssignRollbackReq") + + assertTrue(req.indexOf("<sdncadapter:SvcAction>assign</") >= 0) + assertTrue(req.indexOf("<request-action>CreateBRGInstance</") >= 0) + assertTrue(req.indexOf("<sdncadapter:RequestId>") >= 0) + + assertTrue(rbreq.indexOf("<sdncadapter:SvcAction>unassign</") >= 0) + assertTrue(rbreq.indexOf("<request-action>DeleteBRGInstance</") >= 0) + assertTrue(rbreq.indexOf("<sdncadapter:RequestId>") >= 0) + } + + @Test +// @Ignore + public void preProcessSDNCAssign_BpmnError() { + ExecutionEntity mex = setupMock() + initPreProcessSDNC(mex) + + when(mex.getVariable("rollbackData")).thenThrow(new BpmnError("expected exception")) + + DoCreateAllottedResourceBRG DoCreateAllottedResourceBRG = new DoCreateAllottedResourceBRG() + + assertTrue(doBpmnError({ _ -> DoCreateAllottedResourceBRG.preProcessSDNCAssign(mex) })) + } + + @Test +// @Ignore + public void preProcessSDNCAssign_Ex() { + ExecutionEntity mex = setupMock() + initPreProcessSDNC(mex) + + when(mex.getVariable("rollbackData")).thenThrow(new RuntimeException("expected exception")) + + DoCreateAllottedResourceBRG DoCreateAllottedResourceBRG = new DoCreateAllottedResourceBRG() + + assertTrue(doBpmnError({ _ -> DoCreateAllottedResourceBRG.preProcessSDNCAssign(mex) })) + } + + + // ***** preProcessSDNCCreate ***** + + @Test +// @Ignore + public void preProcessSDNCCreate() { + ExecutionEntity mex = setupMock() + def map = setupMap(mex) + def data = initPreProcessSDNC(mex) + + DoCreateAllottedResourceBRG DoCreateAllottedResourceBRG = new DoCreateAllottedResourceBRG() + DoCreateAllottedResourceBRG.preProcessSDNCCreate(mex) + + def req = map.get("sdncCreateRequest") + assertNotNull(req) + + assertEquals(data, map.get("rollbackData")) + + def rbreq = data.get(Prefix, "sdncCreateRollbackReq") + + assertTrue(req.indexOf("<sdncadapter:SvcAction>create</") >= 0) + assertTrue(req.indexOf("<request-action>CreateBRGInstance</") >= 0) + assertTrue(req.indexOf("<sdncadapter:RequestId>") >= 0) + + assertTrue(rbreq.indexOf("<sdncadapter:SvcAction>delete</") >= 0) + assertTrue(rbreq.indexOf("<request-action>DeleteBRGInstance</") >= 0) + assertTrue(rbreq.indexOf("<sdncadapter:RequestId>") >= 0) + + } + + @Test +// @Ignore + public void preProcessSDNCCreate_BpmnError() { + ExecutionEntity mex = setupMock() + initPreProcessSDNC(mex) + + when(mex.getVariable("rollbackData")).thenThrow(new BpmnError("expected exception")) + + DoCreateAllottedResourceBRG DoCreateAllottedResourceBRG = new DoCreateAllottedResourceBRG() + + assertTrue(doBpmnError({ _ -> DoCreateAllottedResourceBRG.preProcessSDNCCreate(mex) })) + } + + @Test +// @Ignore + public void preProcessSDNCCreate_Ex() { + ExecutionEntity mex = setupMock() + initPreProcessSDNC(mex) + + when(mex.getVariable("rollbackData")).thenThrow(new RuntimeException("expected exception")) + + DoCreateAllottedResourceBRG DoCreateAllottedResourceBRG = new DoCreateAllottedResourceBRG() + + assertTrue(doBpmnError({ _ -> DoCreateAllottedResourceBRG.preProcessSDNCCreate(mex) })) + } + + + // ***** preProcessSDNCActivate ***** + + @Test +// @Ignore + public void preProcessSDNCActivate() { + ExecutionEntity mex = setupMock() + def map = setupMap(mex) + def data = initPreProcessSDNC(mex) + + DoCreateAllottedResourceBRG DoCreateAllottedResourceBRG = new DoCreateAllottedResourceBRG() + DoCreateAllottedResourceBRG.preProcessSDNCActivate(mex) + + def req = map.get("sdncActivateRequest") + assertNotNull(req) + + assertEquals(data, map.get("rollbackData")) + + def rbreq = data.get(Prefix, "sdncActivateRollbackReq") + + assertTrue(req.indexOf("<sdncadapter:SvcAction>activate</") >= 0) + assertTrue(req.indexOf("<request-action>CreateBRGInstance</") >= 0) + assertTrue(req.indexOf("<sdncadapter:RequestId>") >= 0) + + assertTrue(rbreq.indexOf("<sdncadapter:SvcAction>deactivate</") >= 0) + assertTrue(rbreq.indexOf("<request-action>DeleteBRGInstance</") >= 0) + assertTrue(rbreq.indexOf("<sdncadapter:RequestId>") >= 0) + + } + + @Test +// @Ignore + public void preProcessSDNCActivate_BpmnError() { + ExecutionEntity mex = setupMock() + initPreProcessSDNC(mex) + + when(mex.getVariable("rollbackData")).thenThrow(new BpmnError("expected exception")) + + DoCreateAllottedResourceBRG DoCreateAllottedResourceBRG = new DoCreateAllottedResourceBRG() + + assertTrue(doBpmnError({ _ -> DoCreateAllottedResourceBRG.preProcessSDNCActivate(mex) })) + } + + @Test +// @Ignore + public void preProcessSDNCActivate_Ex() { + ExecutionEntity mex = setupMock() + initPreProcessSDNC(mex) + + when(mex.getVariable("rollbackData")).thenThrow(new RuntimeException("expected exception")) + + DoCreateAllottedResourceBRG DoCreateAllottedResourceBRG = new DoCreateAllottedResourceBRG() + + assertTrue(doBpmnError({ _ -> DoCreateAllottedResourceBRG.preProcessSDNCActivate(mex) })) + } + + + // ***** validateSDNCResp ***** + + @Test +// @Ignore + public void validateSDNCResp() { + ExecutionEntity mex = setupMock() + def map = setupMap(mex) + def data = initValidateSDNCResp(mex) + def resp = initValidateSDNCResp_Resp() + + when(mex.getVariable(Prefix+"sdncResponseSuccess")).thenReturn(true) + + DoCreateAllottedResourceBRG DoCreateAllottedResourceBRG = new DoCreateAllottedResourceBRG() + + DoCreateAllottedResourceBRG.validateSDNCResp(mex, resp, "create") + + verify(mex).getVariable("WorkflowException") + verify(mex).getVariable("SDNCA_SuccessIndicator") + verify(mex).getVariable("rollbackData") + + assertEquals(data, map.get("rollbackData")) + + assertEquals("true", data.get(Prefix, "rollback" + "SDNCcreate")) + + } + + @Test +// @Ignore + public void validateSDNCResp_Get() { + ExecutionEntity mex = setupMock() + def data = initValidateSDNCResp(mex) + def resp = initValidateSDNCResp_Resp() + + when(mex.getVariable(Prefix+"sdncResponseSuccess")).thenReturn(true) + + DoCreateAllottedResourceBRG DoCreateAllottedResourceBRG = new DoCreateAllottedResourceBRG() + + DoCreateAllottedResourceBRG.validateSDNCResp(mex, resp, "get") + + verify(mex).getVariable("WorkflowException") + verify(mex).getVariable("SDNCA_SuccessIndicator") + + verify(mex, never()).getVariable("rollbackData") + } + + @Test +// @Ignore + public void validateSDNCResp_Unsuccessful() { + ExecutionEntity mex = setupMock() + initValidateSDNCResp(mex) + def resp = initValidateSDNCResp_Resp() + + // unsuccessful + when(mex.getVariable(Prefix+"sdncResponseSuccess")).thenReturn(false) + + DoCreateAllottedResourceBRG DoCreateAllottedResourceBRG = new DoCreateAllottedResourceBRG() + + assertTrue(doBpmnError({ _ -> DoCreateAllottedResourceBRG.validateSDNCResp(mex, resp, "create") })) + } + + @Test +// @Ignore + public void validateSDNCResp_BpmnError() { + ExecutionEntity mex = setupMock() + initValidateSDNCResp(mex) + def resp = initValidateSDNCResp_Resp() + + when(mex.getVariable("WorkflowException")).thenThrow(new BpmnError("expected exception")) + + DoCreateAllottedResourceBRG DoCreateAllottedResourceBRG = new DoCreateAllottedResourceBRG() + + assertTrue(doBpmnError({ _ -> DoCreateAllottedResourceBRG.validateSDNCResp(mex, resp, "create") })) + } + + @Test +// @Ignore + public void validateSDNCResp_Ex() { + ExecutionEntity mex = setupMock() + initValidateSDNCResp(mex) + def resp = initValidateSDNCResp_Resp() + + when(mex.getVariable("WorkflowException")).thenThrow(new RuntimeException("expected exception")) + + DoCreateAllottedResourceBRG DoCreateAllottedResourceBRG = new DoCreateAllottedResourceBRG() + + assertTrue(doBpmnError({ _ -> DoCreateAllottedResourceBRG.validateSDNCResp(mex, resp, "create") })) + } + + + // ***** preProcessSDNCGet ***** + + @Test +// @Ignore + public void preProcessSDNCGet_FoundAR() { + ExecutionEntity mex = setupMock() + def map = setupMap(mex) + initPreProcessSDNCGet(mex) + + DoCreateAllottedResourceBRG DoCreateAllottedResourceBRG = new DoCreateAllottedResourceBRG() + DoCreateAllottedResourceBRG.preProcessSDNCGet(mex) + + String req = map.get("sdncGetRequest") + + assertTrue(req.indexOf("<sdncadapter:RequestId>") >= 0) + assertTrue(req.indexOf("<sdncadapter:SvcInstanceId>sii</") >= 0) + assertTrue(req.indexOf("<sdncadapter:SvcOperation>arlink</") >= 0) + assertTrue(req.indexOf("<sdncadapter:CallbackUrl>myurl</") >= 0) + + } + + @Test +// @Ignore + public void preProcessSDNCGet_NotFoundAR() { + ExecutionEntity mex = setupMock() + def map = setupMap(mex) + initPreProcessSDNCGet(mex) + + when(mex.getVariable("foundActiveAR")).thenReturn(false) + + DoCreateAllottedResourceBRG DoCreateAllottedResourceBRG = new DoCreateAllottedResourceBRG() + DoCreateAllottedResourceBRG.preProcessSDNCGet(mex) + + String req = map.get("sdncGetRequest") + + assertTrue(req.indexOf("<sdncadapter:RequestId>") >= 0) + assertTrue(req.indexOf("<sdncadapter:SvcInstanceId>sii</") >= 0) + assertTrue(req.indexOf("<sdncadapter:SvcOperation>assignlink</") >= 0) + assertTrue(req.indexOf("<sdncadapter:CallbackUrl>myurl</") >= 0) + + } + + @Test +// @Ignore + public void preProcessSDNCGet_Ex() { + ExecutionEntity mex = setupMock() + initPreProcessSDNCGet(mex) + + when(mex.getVariable("foundActiveAR")).thenThrow(new RuntimeException("expected exception")) + + DoCreateAllottedResourceBRG DoCreateAllottedResourceBRG = new DoCreateAllottedResourceBRG() + + assertTrue(doBpmnError({ _ -> DoCreateAllottedResourceBRG.preProcessSDNCGet(mex) })) + } + + + // ***** updateAaiAROrchStatus ***** + + @Test + @Ignore + public void updateAaiAROrchStatus() { + MockPatchAllottedResource(CUST, SVC, INST, ARID) + + ExecutionEntity mex = setupMock() + initUpdateAaiAROrchStatus(mex) + + DoCreateAllottedResourceBRG DoCreateAllottedResourceBRG = new DoCreateAllottedResourceBRG() + DoCreateAllottedResourceBRG.updateAaiAROrchStatus(mex, "success") + } + + + // ***** generateOutputs ***** + + @Test +// @Ignore + public void generateOutputs() { + ExecutionEntity mex = setupMock() + def brgtop = FileUtil.readResourceFile("__files/VCPE/DoCreateAllottedResourceBRG/SDNCTopologyQueryCallback.xml") + + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("enhancedCallbackRequestData")).thenReturn(brgtop) + + DoCreateAllottedResourceBRG DoCreateAllottedResourceBRG = new DoCreateAllottedResourceBRG() + DoCreateAllottedResourceBRG.generateOutputs(mex) + + verify(mex).setVariable("allotedResourceName", "namefromrequest") + + } + + @Test +// @Ignore + public void generateOutputs_BadXml() { + ExecutionEntity mex = setupMock() + + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("enhancedCallbackRequestData")).thenReturn("invalid xml") + + DoCreateAllottedResourceBRG DoCreateAllottedResourceBRG = new DoCreateAllottedResourceBRG() + DoCreateAllottedResourceBRG.generateOutputs(mex) + + verify(mex, never()).setVariable(anyString(), anyString()) + + } + + @Test +// @Ignore + public void generateOutputs_BpmnError() { + ExecutionEntity mex = setupMock() + + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("enhancedCallbackRequestData")).thenThrow(new BpmnError("expected exception")) + + DoCreateAllottedResourceBRG DoCreateAllottedResourceBRG = new DoCreateAllottedResourceBRG() + + DoCreateAllottedResourceBRG.generateOutputs(mex) + verify(mex, never()).setVariable(anyString(), anyString()) + + } + + @Test +// @Ignore + public void generateOutputs_Ex() { + ExecutionEntity mex = setupMock() + + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("enhancedCallbackRequestData")).thenThrow(new RuntimeException("expected exception")) + + DoCreateAllottedResourceBRG DoCreateAllottedResourceBRG = new DoCreateAllottedResourceBRG() + + DoCreateAllottedResourceBRG.generateOutputs(mex) + verify(mex, never()).setVariable(anyString(), anyString()) + + } + + + // ***** preProcessRollback ***** + + @Test +// @Ignore + public void preProcessRollback() { + ExecutionEntity mex = setupMock() + WorkflowException wfe = mock(WorkflowException.class) + + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("WorkflowException")).thenReturn(wfe) + + DoCreateAllottedResourceBRG DoCreateAllottedResourceBRG = new DoCreateAllottedResourceBRG() + DoCreateAllottedResourceBRG.preProcessRollback(mex) + + verify(mex).setVariable("prevWorkflowException", wfe) + + } + + @Test +// @Ignore + public void preProcessRollback_NotWFE() { + ExecutionEntity mex = setupMock() + + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("WorkflowException")).thenReturn("I'm not a WFE") + + DoCreateAllottedResourceBRG DoCreateAllottedResourceBRG = new DoCreateAllottedResourceBRG() + DoCreateAllottedResourceBRG.preProcessRollback(mex) + +// verify(mex, never()).setVariable("prevWorkflowException", any()) + + } + + @Test +// @Ignore + public void preProcessRollback_BpmnError() { + ExecutionEntity mex = setupMock() + + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("WorkflowException")).thenThrow(new BpmnError("expected exception")) + + DoCreateAllottedResourceBRG DoCreateAllottedResourceBRG = new DoCreateAllottedResourceBRG() + + DoCreateAllottedResourceBRG.preProcessRollback(mex) + + } + + @Test +// @Ignore + public void preProcessRollback_Ex() { + ExecutionEntity mex = setupMock() + + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("WorkflowException")).thenThrow(new RuntimeException("expected exception")) + + DoCreateAllottedResourceBRG DoCreateAllottedResourceBRG = new DoCreateAllottedResourceBRG() + + DoCreateAllottedResourceBRG.preProcessRollback(mex) + + } + + + // ***** postProcessRollback ***** + + @Test +// @Ignore + public void postProcessRollback() { + ExecutionEntity mex = setupMock() + WorkflowException wfe = mock(WorkflowException.class) + + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("prevWorkflowException")).thenReturn(wfe) + + DoCreateAllottedResourceBRG DoCreateAllottedResourceBRG = new DoCreateAllottedResourceBRG() + DoCreateAllottedResourceBRG.postProcessRollback(mex) + + verify(mex).setVariable("WorkflowException", wfe) + verify(mex).setVariable("rollbackData", null) + + } + + @Test +// @Ignore + public void postProcessRollback_NotWFE() { + ExecutionEntity mex = setupMock() + + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("prevWorkflowException")).thenReturn("I'm not a WFE") + + DoCreateAllottedResourceBRG DoCreateAllottedResourceBRG = new DoCreateAllottedResourceBRG() + DoCreateAllottedResourceBRG.postProcessRollback(mex) + +// verify(mex, never()).setVariable("WorkflowException", any()) + verify(mex).setVariable("rollbackData", null) + + } + + @Test +// @Ignore + public void postProcessRollback_BpmnError() { + ExecutionEntity mex = setupMock() + + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("prevWorkflowException")).thenThrow(new BpmnError("expected exception")) + + DoCreateAllottedResourceBRG DoCreateAllottedResourceBRG = new DoCreateAllottedResourceBRG() + + assertTrue(doBpmnError({ _ -> DoCreateAllottedResourceBRG.postProcessRollback(mex) })) + verify(mex, never()).setVariable("rollbackData", null) + + } + + @Test +// @Ignore + public void postProcessRollback_Ex() { + ExecutionEntity mex = setupMock() + + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("prevWorkflowException")).thenThrow(new RuntimeException("expected exception")) + + DoCreateAllottedResourceBRG DoCreateAllottedResourceBRG = new DoCreateAllottedResourceBRG() + + DoCreateAllottedResourceBRG.postProcessRollback(mex) + verify(mex, never()).setVariable("rollbackData", null) + + } + + private boolean checkMissingPreProcessRequest(String fieldnm) { + ExecutionEntity mex = setupMock() + initPreProcess(mex) + + DoCreateAllottedResourceBRG DoCreateAllottedResourceBRG = new DoCreateAllottedResourceBRG() + + when(mex.getVariable(fieldnm)).thenReturn("") + + return doBpmnError( { _ -> DoCreateAllottedResourceBRG.preProcessRequest(mex) }) + } + + private void initPreProcess(ExecutionEntity mex) { + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("mso.workflow.sdncadapter.callback")).thenReturn("sdncurn") + when(mex.getVariable("mso.workflow.sdnc.replication.delay")).thenReturn("sdncdelay") + when(mex.getVariable("serviceInstanceId")).thenReturn("sii") + when(mex.getVariable("parentServiceInstanceId")).thenReturn("psii") + when(mex.getVariable("allottedResourceModelInfo")).thenReturn("armi") + when(mex.getVariable("vni")).thenReturn("myvni") + when(mex.getVariable("vgmuxBearerIP")).thenReturn("vbi") + when(mex.getVariable("brgWanMacAddress")).thenReturn("bwma") + when(mex.getVariable("allottedResourceRole")).thenReturn("arr") + when(mex.getVariable("allottedResourceType")).thenReturn("art") + } + + private void initGetAaiAR(ExecutionEntity mex) { + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("allottedResourceType")).thenReturn("BRGt") + when(mex.getVariable("allottedResourceRole")).thenReturn("BRGr") + when(mex.getVariable("CSI_service")).thenReturn(FileUtil.readResourceFile("__files/VCPE/DoCreateAllottedResourceBRG/getAR.xml")) + when(mex.getVariable("aai.endpoint")).thenReturn(aaiUriPfx) + when(mex.getVariable("aaiAROrchStatus")).thenReturn("Active") + } + + private initCreateAaiAr(ExecutionEntity mex) { + when(mex.getVariable("disableRollback")).thenReturn(45) + when(mex.getVariable("serviceInstanceId")).thenReturn("sii") + when(mex.getVariable("parentServiceInstanceId")).thenReturn("psii") + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("allottedResourceId")).thenReturn(ARID) + when(mex.getVariable("aai.endpoint")).thenReturn(aaiUriPfx) + when(mex.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn(UrnPropertiesReader.getVariable("mso.workflow.global.default.aai.namespace")) + when(mex.getVariable("PSI_resourceLink")).thenReturn(aaiUriPfx + "/aai/v9/business/customers/customer/"+CUST+"/service-subscriptions/service-subscription/"+SVC+"/service-instances/service-instance/"+INST) + when(mex.getVariable("allottedResourceType")).thenReturn("BRGt") + when(mex.getVariable("allottedResourceRole")).thenReturn("BRGr") + when(mex.getVariable("CSI_resourceLink")).thenReturn(aaiUriPfx+"/aai/v9/mycsi") + when(mex.getVariable("allottedResourceModelInfo")).thenReturn(""" + { + "modelInvariantUuid":"modelinvuuid", + "modelUuid":"modeluuid", + "modelCustomizationUuid":"modelcustuuid" + } + """) + } + + private initBuildSDNCRequest(ExecutionEntity mex) { + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("allottedResourceId")).thenReturn("ari") + when(mex.getVariable("serviceInstanceId")).thenReturn("sii") + when(mex.getVariable("parentServiceInstanceId")).thenReturn("psii") + when(mex.getVariable("subscriptionServiceType")).thenReturn("sst") + when(mex.getVariable("globalCustomerId")).thenReturn("gci") + when(mex.getVariable("sdncCallbackUrl")).thenReturn("scu") + when(mex.getVariable("msoRequestId")).thenReturn("mri") + when(mex.getVariable("brgWanMacAddress")).thenReturn("bwma") + when(mex.getVariable("vni")).thenReturn("myvni") + when(mex.getVariable("vgmuxBearerIP")).thenReturn("vbi") + when(mex.getVariable("allottedResourceModelInfo")).thenReturn(""" + { + "modelInvariantUuid":"miu", + "modelUuid":"mu", + "modelCustomizationUuid":"mcu", + "modelVersion":"mv", + "modelName":"mn" + } + """) + } + + private RollbackData initPreProcessSDNC(ExecutionEntity mex) { + def data = new RollbackData() + + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("rollbackData")).thenReturn(data) + + return data + } + + private initPreProcessSDNCGet(ExecutionEntity mex) { + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("sdncCallbackUrl")).thenReturn("myurl") + when(mex.getVariable("foundActiveAR")).thenReturn(true) + when(mex.getVariable("aaiARGetResponse")).thenReturn("<selflink>arlink</selflink>") + when(mex.getVariable("sdncAssignResponse")).thenReturn("<response-data><object-path>assignlink</object-path></response-data>") + when(mex.getVariable("serviceInstanceId")).thenReturn("sii") + when(mex.getVariable("sdncCallbackUrl")).thenReturn("myurl") + } + + private RollbackData initValidateSDNCResp(ExecutionEntity mex) { + def data = new RollbackData() + + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("prefix")).thenReturn(Prefix) + when(mex.getVariable("SDNCA_SuccessIndicator")).thenReturn(true) + when(mex.getVariable("rollbackData")).thenReturn(data) + + return data + } + + private String initValidateSDNCResp_Resp() { + return "<response-data><response-code>200</response-code></response-data>" + } + + private initUpdateAaiAROrchStatus(ExecutionEntity mex) { + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("aaiARPath")).thenReturn(aaiUriPfx + "/aai/v9/business/customers/customer/"+CUST+"/service-subscriptions/service-subscription/"+SVC+"/service-instances/service-instance/"+INST+"/allotted-resources/allotted-resource/"+ARID) + } + +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceTXCRollbackTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceTXCRollbackTest.groovy new file mode 100644 index 0000000000..66cfdb635d --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceTXCRollbackTest.groovy @@ -0,0 +1,654 @@ +/* + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.vcpe.scripts + + +import org.camunda.bpm.engine.ProcessEngineServices +import org.camunda.bpm.engine.RepositoryService +import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity +import org.camunda.bpm.engine.repository.ProcessDefinition +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.junit.Before +import org.junit.BeforeClass +import org.junit.Rule +import org.junit.Test +import org.junit.Ignore +import org.mockito.MockitoAnnotations +import org.camunda.bpm.engine.delegate.BpmnError +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.bpmn.mock.FileUtil + +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse +import static com.github.tomakehurst.wiremock.client.WireMock.get +import static com.github.tomakehurst.wiremock.client.WireMock.stubFor +import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching +import static org.junit.Assert.*; +import static org.mockito.Mockito.* +import static org.onap.so.bpmn.mock.StubResponseAAI.MockDeleteAllottedResource +import static org.onap.so.bpmn.mock.StubResponseAAI.MockGetAllottedResource +import static org.onap.so.bpmn.mock.StubResponseAAI.MockPatchAllottedResource + +import org.onap.so.bpmn.core.RollbackData + +import com.github.tomakehurst.wiremock.junit.WireMockRule + +class DoCreateAllottedResourceTXCRollbackTest extends GroovyTestBase { + + @Rule + public WireMockRule wireMockRule = new WireMockRule(PORT) + + String Prefix = "DCARTXCRB_" + String RbType = "DCARTXC_" + + @BeforeClass + public static void setUpBeforeClass() { + super.setUpBeforeClass() + } + + @Before + public void init() + { + MockitoAnnotations.initMocks(this) + } + + public DoCreateAllottedResourceTXCRollbackTest() { + super("DoCreateAllottedResourceTXCRollback") + } + + + // ***** preProcessRequest ***** + + @Test +// @Ignore + public void preProcessRequest() { + ExecutionEntity mex = setupMock() + initPreProcess(mex) + + DoCreateAllottedResourceTXCRollback DoCreateAllottedResourceTXCRollback = new DoCreateAllottedResourceTXCRollback() + DoCreateAllottedResourceTXCRollback.preProcessRequest(mex) + + //verify(mex).getVariable(DBGFLAG) + verify(mex).setVariable("prefix", Prefix) + verify(mex).setVariable("serviceInstanceId", "sii") + verify(mex).setVariable("parentServiceInstanceId", "psii") + verify(mex).setVariable("allottedResourceId", "myid") + verify(mex).setVariable("rollbackAAI", true) + verify(mex).setVariable("aaiARPath", "mypath") + verify(mex).setVariable("rollbackSDNC", true) + verify(mex).setVariable("deactivateSdnc", "myactivate") + verify(mex).setVariable("deleteSdnc", "mycreate") + verify(mex).setVariable("unassignSdnc", "true") + verify(mex).setVariable("sdncDeactivateRequest", "activatereq") + verify(mex).setVariable("sdncDeleteRequest", "createreq") + verify(mex).setVariable("sdncUnassignRequest", "assignreq") + + verify(mex, never()).setVariable("skipRollback", true) + } + + @Test +// @Ignore + public void preProcessRequest_RollbackDisabled() { + ExecutionEntity mex = setupMock() + initPreProcess(mex) + + when(mex.getVariable("disableRollback")).thenReturn("true") + + DoCreateAllottedResourceTXCRollback DoCreateAllottedResourceTXCRollback = new DoCreateAllottedResourceTXCRollback() + DoCreateAllottedResourceTXCRollback.preProcessRequest(mex) + + //verify(mex).getVariable(DBGFLAG) + verify(mex).setVariable("prefix", Prefix) + verify(mex).setVariable("serviceInstanceId", "sii") + verify(mex).setVariable("parentServiceInstanceId", "psii") + verify(mex).setVariable("allottedResourceId", "myid") + verify(mex).setVariable("rollbackAAI", true) + verify(mex).setVariable("aaiARPath", "mypath") + verify(mex).setVariable("rollbackSDNC", true) + verify(mex).setVariable("deactivateSdnc", "myactivate") + verify(mex).setVariable("deleteSdnc", "mycreate") + verify(mex).setVariable("unassignSdnc", "true") + verify(mex).setVariable("sdncDeactivateRequest", "activatereq") + verify(mex).setVariable("sdncDeleteRequest", "createreq") + verify(mex).setVariable("sdncUnassignRequest", "assignreq") + + verify(mex).setVariable("skipRollback", true) + } + + @Test +// @Ignore + public void preProcessRequest_NoAAI() { + ExecutionEntity mex = setupMock() + def data = initPreProcess(mex) + + when(mex.getVariable("rollbackAAI")).thenReturn(false) + data.put(RbType, "rollbackAAI", "false") + + DoCreateAllottedResourceTXCRollback DoCreateAllottedResourceTXCRollback = new DoCreateAllottedResourceTXCRollback() + DoCreateAllottedResourceTXCRollback.preProcessRequest(mex) + + //verify(mex).getVariable(DBGFLAG) + verify(mex).setVariable("prefix", Prefix) + verify(mex).setVariable("serviceInstanceId", "sii") + verify(mex).setVariable("parentServiceInstanceId", "psii") + verify(mex).setVariable("allottedResourceId", "myid") + verify(mex, never()).setVariable("rollbackAAI", true) + verify(mex, never()).setVariable("aaiARPath", "mypath") + verify(mex).setVariable("rollbackSDNC", true) + verify(mex).setVariable("deactivateSdnc", "myactivate") + verify(mex).setVariable("deleteSdnc", "mycreate") + verify(mex).setVariable("unassignSdnc", "true") + verify(mex).setVariable("sdncDeactivateRequest", "activatereq") + verify(mex).setVariable("sdncDeleteRequest", "createreq") + verify(mex).setVariable("sdncUnassignRequest", "assignreq") + + verify(mex, never()).setVariable("skipRollback", true) + } + + @Test +// @Ignore + public void preProcessRequest_NoAssign() { + ExecutionEntity mex = setupMock() + def data = initPreProcess(mex) + + when(mex.getVariable("rollbackSDNC")).thenReturn(false) + data.put(RbType, "rollbackSDNCassign", "false") + + DoCreateAllottedResourceTXCRollback DoCreateAllottedResourceTXCRollback = new DoCreateAllottedResourceTXCRollback() + DoCreateAllottedResourceTXCRollback.preProcessRequest(mex) + + //verify(mex).getVariable(DBGFLAG) + verify(mex).setVariable("prefix", Prefix) + verify(mex).setVariable("serviceInstanceId", "sii") + verify(mex).setVariable("parentServiceInstanceId", "psii") + verify(mex).setVariable("allottedResourceId", "myid") + verify(mex).setVariable("rollbackAAI", true) + verify(mex).setVariable("aaiARPath", "mypath") + verify(mex, never()).setVariable("rollbackSDNC", true) + verify(mex, never()).setVariable("deactivateSdnc", "myactivate") + verify(mex, never()).setVariable("deleteSdnc", "mycreate") + verify(mex, never()).setVariable("unassignSdnc", "true") + verify(mex, never()).setVariable("sdncDeactivateRequest", "activatereq") + verify(mex, never()).setVariable("sdncDeleteRequest", "createreq") + verify(mex, never()).setVariable("sdncUnassignRequest", "assignreq") + + verify(mex, never()).setVariable("skipRollback", true) + } + + @Test +// @Ignore + public void preProcessRequest_NoAAI_NoAssign() { + ExecutionEntity mex = setupMock() + initPreProcess(mex) + + when(mex.getVariable("rollbackAAI")).thenReturn(false) + when(mex.getVariable("rollbackSDNC")).thenReturn(false) + + DoCreateAllottedResourceTXCRollback DoCreateAllottedResourceTXCRollback = new DoCreateAllottedResourceTXCRollback() + DoCreateAllottedResourceTXCRollback.preProcessRequest(mex) + + verify(mex).setVariable("skipRollback", true) + } + + @Test +// @Ignore + public void preProcessRequest_NoRbStructure() { + ExecutionEntity mex = setupMock() + initPreProcess(mex) + + when(mex.getVariable("rollbackData")).thenReturn(new RollbackData()) + + DoCreateAllottedResourceTXCRollback DoCreateAllottedResourceTXCRollback = new DoCreateAllottedResourceTXCRollback() + DoCreateAllottedResourceTXCRollback.preProcessRequest(mex) + + verify(mex).setVariable("skipRollback", true) + } + + @Test +// @Ignore + public void preProcessRequest_NullRb() { + ExecutionEntity mex = setupMock() + initPreProcess(mex) + + when(mex.getVariable("rollbackData")).thenReturn(null) + + DoCreateAllottedResourceTXCRollback DoCreateAllottedResourceTXCRollback = new DoCreateAllottedResourceTXCRollback() + DoCreateAllottedResourceTXCRollback.preProcessRequest(mex) + + verify(mex).setVariable("skipRollback", true) + } + + @Test +// @Ignore + public void preProcessRequest_BpmnError() { + ExecutionEntity mex = setupMock() + initPreProcess(mex) + + when(mex.getVariable("rollbackData")).thenThrow(new BpmnError("expected exception")) + + DoCreateAllottedResourceTXCRollback DoCreateAllottedResourceTXCRollback = new DoCreateAllottedResourceTXCRollback() + + assertTrue(doBpmnError( { _ -> DoCreateAllottedResourceTXCRollback.preProcessRequest(mex) })) + } + + @Test +// @Ignore + public void preProcessRequest_Ex() { + ExecutionEntity mex = setupMock() + initPreProcess(mex) + + when(mex.getVariable("rollbackData")).thenThrow(new RuntimeException("expected exception")) + + DoCreateAllottedResourceTXCRollback DoCreateAllottedResourceTXCRollback = new DoCreateAllottedResourceTXCRollback() + + assertTrue(doBpmnError( { _ -> DoCreateAllottedResourceTXCRollback.preProcessRequest(mex) })) + } + + @Test + @Ignore + public void updateAaiAROrchStatus() { + ExecutionEntity mex = setupMock() + initUpdateAaiAROrchStatus(mex) + + MockGetAllottedResource(CUST, SVC, INST, ARID, "VCPE/DoCreateAllottedResourceTXCRollback/arGetById.xml") + MockPatchAllottedResource(CUST, SVC, INST, ARID) + + DoCreateAllottedResourceTXCRollback DoCreateAllottedResourceTXCRollback = new DoCreateAllottedResourceTXCRollback() + DoCreateAllottedResourceTXCRollback.updateAaiAROrchStatus(mex, "success") + } + + @Test +// @Ignore + public void updateAaiAROrchStatus_EmptyResponse() { + ExecutionEntity mex = setupMock() + initUpdateAaiAROrchStatus(mex) + + wireMockRule + .stubFor(get(urlMatching("/aai/v[0-9]+/.*")) + .willReturn(aResponse() + .withStatus(200))) + + DoCreateAllottedResourceTXCRollback DoCreateAllottedResourceTXCRollback = new DoCreateAllottedResourceTXCRollback() + + assertTrue(doBpmnError( { _ -> DoCreateAllottedResourceTXCRollback.updateAaiAROrchStatus(mex, "success") })) + } + + @Test +// @Ignore + public void updateAaiAROrchStatus_NoArPath() { + ExecutionEntity mex = setupMock() + initUpdateAaiAROrchStatus(mex) + + MockGetAllottedResource(CUST, SVC, INST, ARID, "VCPE/DoCreateAllottedResourceTXCRollback/arGetById.xml") + MockPatchAllottedResource(CUST, SVC, INST, ARID) + + when(mex.getVariable("aaiARPath")).thenReturn(null) + + DoCreateAllottedResourceTXCRollback DoCreateAllottedResourceTXCRollback = new DoCreateAllottedResourceTXCRollback() + + assertTrue(doBpmnError( { _ -> DoCreateAllottedResourceTXCRollback.updateAaiAROrchStatus(mex, "success") })) + } + + + // ***** validateSDNCResp ***** + + @Test +// @Ignore + public void validateSDNCResp() { + ExecutionEntity mex = setupMock() + initValidateSDNCResp(mex) + def resp = initValidateSDNCResp_Resp() + + when(mex.getVariable(Prefix+"sdncResponseSuccess")).thenReturn(true) + + DoCreateAllottedResourceTXCRollback DoCreateAllottedResourceTXCRollback = new DoCreateAllottedResourceTXCRollback() + + DoCreateAllottedResourceTXCRollback.validateSDNCResp(mex, resp, "create") + + verify(mex).getVariable("WorkflowException") + verify(mex).getVariable("SDNCA_SuccessIndicator") + } + + @Test +// @Ignore + public void validateSDNCResp_Unsuccessful() { + ExecutionEntity mex = setupMock() + initValidateSDNCResp(mex) + def resp = initValidateSDNCResp_Resp() + + when(mex.getVariable(Prefix+"sdncResponseSuccess")).thenReturn(false) + + DoCreateAllottedResourceTXCRollback DoCreateAllottedResourceTXCRollback = new DoCreateAllottedResourceTXCRollback() + + assertTrue(doBpmnError( { _ -> DoCreateAllottedResourceTXCRollback.validateSDNCResp(mex, resp, "create") })) + } + + @Test +// @Ignore + public void validateSDNCResp_BpmnError404() { + ExecutionEntity mex = setupMock() + initValidateSDNCResp(mex) + def resp = initValidateSDNCResp_Resp() + when(mex.getVariable(Prefix+"sdncResponseSuccess")).thenReturn(true) + + when(mex.getVariable("WorkflowException")).thenThrow(new BpmnError("404", "expected exception")) + + DoCreateAllottedResourceTXCRollback DoCreateAllottedResourceTXCRollback = new DoCreateAllottedResourceTXCRollback() + + DoCreateAllottedResourceTXCRollback.validateSDNCResp(mex, resp, "create") + } + + @Test +// @Ignore + public void validateSDNCResp_BpmnError() { + ExecutionEntity mex = setupMock() + initValidateSDNCResp(mex) + def resp = initValidateSDNCResp_Resp() + when(mex.getVariable(Prefix+"sdncResponseSuccess")).thenReturn(true) + + when(mex.getVariable("WorkflowException")).thenThrow(new BpmnError("expected exception")) + + DoCreateAllottedResourceTXCRollback DoCreateAllottedResourceTXCRollback = new DoCreateAllottedResourceTXCRollback() + + assertTrue(doBpmnError( { _ -> DoCreateAllottedResourceTXCRollback.validateSDNCResp(mex, resp, "create") })) + } + + @Test +// @Ignore + public void validateSDNCResp_Ex() { + ExecutionEntity mex = setupMock() + initValidateSDNCResp(mex) + def resp = initValidateSDNCResp_Resp() + when(mex.getVariable(Prefix+"sdncResponseSuccess")).thenReturn(true) + + when(mex.getVariable("WorkflowException")).thenThrow(new RuntimeException("expected exception")) + + DoCreateAllottedResourceTXCRollback DoCreateAllottedResourceTXCRollback = new DoCreateAllottedResourceTXCRollback() + + assertTrue(doBpmnError( { _ -> DoCreateAllottedResourceTXCRollback.validateSDNCResp(mex, resp, "create") })) + } + + @Test + @Ignore + public void deleteAaiAR() { + ExecutionEntity mex = setupMock() + initDeleteAaiAR(mex) + + MockGetAllottedResource(CUST, SVC, INST, ARID, "VCPE/DoCreateAllottedResourceTXCRollback/arGetById.xml") + MockDeleteAllottedResource(CUST, SVC, INST, ARID, VERS) + + DoCreateAllottedResourceTXCRollback DoCreateAllottedResourceTXCRollback = new DoCreateAllottedResourceTXCRollback() + DoCreateAllottedResourceTXCRollback.deleteAaiAR(mex) + } + + @Test +// @Ignore + public void deleteAaiAR_NoArPath() { + ExecutionEntity mex = setupMock() + initDeleteAaiAR(mex) + + MockGetAllottedResource(CUST, SVC, INST, ARID, "VCPE/DoCreateAllottedResourceTXCRollback/arGetById.xml") + MockDeleteAllottedResource(CUST, SVC, INST, ARID, VERS) + + when(mex.getVariable("aaiARPath")).thenReturn("") + + DoCreateAllottedResourceTXCRollback DoCreateAllottedResourceTXCRollback = new DoCreateAllottedResourceTXCRollback() + + assertTrue(doBpmnError( { _ -> DoCreateAllottedResourceTXCRollback.deleteAaiAR(mex) })) + } + + @Test +// @Ignore + public void deleteAaiAR_BpmnError() { + ExecutionEntity mex = setupMock() + initDeleteAaiAR(mex) + + MockGetAllottedResource(CUST, SVC, INST, ARID, "VCPE/DoCreateAllottedResourceTXCRollback/arGetById.xml") + MockDeleteAllottedResource(CUST, SVC, INST, ARID, VERS) + + when(mex.getVariable("aaiARPath")).thenThrow(new BpmnError("expected exception")) + + DoCreateAllottedResourceTXCRollback DoCreateAllottedResourceTXCRollback = new DoCreateAllottedResourceTXCRollback() + + assertTrue(doBpmnError( { _ -> DoCreateAllottedResourceTXCRollback.deleteAaiAR(mex) })) + } + + @Test +// @Ignore + public void deleteAaiAR_Ex() { + ExecutionEntity mex = setupMock() + initDeleteAaiAR(mex) + + MockGetAllottedResource(CUST, SVC, INST, ARID, "VCPE/DoCreateAllottedResourceTXCRollback/arGetById.xml") + MockDeleteAllottedResource(CUST, SVC, INST, ARID, VERS) + + when(mex.getVariable("aaiARPath")).thenThrow(new RuntimeException("expected exception")) + + DoCreateAllottedResourceTXCRollback DoCreateAllottedResourceTXCRollback = new DoCreateAllottedResourceTXCRollback() + + assertTrue(doBpmnError( { _ -> DoCreateAllottedResourceTXCRollback.deleteAaiAR(mex) })) + } + + @Test +// @Ignore + public void postProcessRequest() { + ExecutionEntity mex = setupMock() + initPostProcessRequest(mex) + + DoCreateAllottedResourceTXCRollback DoCreateAllottedResourceTXCRollback = new DoCreateAllottedResourceTXCRollback() + DoCreateAllottedResourceTXCRollback.postProcessRequest(mex) + + //verify(mex).getVariable(DBGFLAG) + verify(mex).setVariable("rollbackData", null) + verify(mex).setVariable("rolledBack", true) + } + + @Test +// @Ignore + public void postProcessRequest_RolledBack() { + ExecutionEntity mex = setupMock() + initPostProcessRequest(mex) + + when(mex.getVariable("skipRollback")).thenReturn(true) + + DoCreateAllottedResourceTXCRollback DoCreateAllottedResourceTXCRollback = new DoCreateAllottedResourceTXCRollback() + DoCreateAllottedResourceTXCRollback.postProcessRequest(mex) + + //verify(mex).getVariable(DBGFLAG) + verify(mex).setVariable("rollbackData", null) + verify(mex, never()).setVariable("rolledBack", true) + } + + @Test +// @Ignore + public void postProcessRequest_BpmnError() { + ExecutionEntity mex = setupMock() + initPostProcessRequest(mex) + + when(mex.getVariable("skipRollback")).thenThrow(new BpmnError("expected exception")) + + DoCreateAllottedResourceTXCRollback DoCreateAllottedResourceTXCRollback = new DoCreateAllottedResourceTXCRollback() + DoCreateAllottedResourceTXCRollback.postProcessRequest(mex) + + //verify(mex).getVariable(DBGFLAG) + verify(mex).setVariable("rollbackData", null) + verify(mex, never()).setVariable("rolledBack", true) + } + + @Test +// @Ignore + public void postProcessRequest_Ex() { + ExecutionEntity mex = setupMock() + initPostProcessRequest(mex) + + when(mex.getVariable("skipRollback")).thenThrow(new RuntimeException("expected exception")) + + DoCreateAllottedResourceTXCRollback DoCreateAllottedResourceTXCRollback = new DoCreateAllottedResourceTXCRollback() + DoCreateAllottedResourceTXCRollback.postProcessRequest(mex) + + //verify(mex).getVariable(DBGFLAG) + verify(mex).setVariable("rollbackData", null) + verify(mex, never()).setVariable("rolledBack", true) + } + + @Test +// @Ignore + public void processRollbackException() { + ExecutionEntity mex = setupMock() + initProcessRollbackException(mex) + + DoCreateAllottedResourceTXCRollback DoCreateAllottedResourceTXCRollback = new DoCreateAllottedResourceTXCRollback() + DoCreateAllottedResourceTXCRollback.processRollbackException(mex) + + //verify(mex).getVariable(DBGFLAG) + verify(mex).setVariable("rollbackData", null) + verify(mex).setVariable("rolledBack", false) + verify(mex).setVariable("rollbackError", "Caught exception in AllottedResource Create Rollback") + verify(mex).setVariable("WorkflowException", null) + } + + @Test +// @Ignore + public void processRollbackException_BpmnError() { + ExecutionEntity mex = setupMock() + initProcessRollbackException(mex) + + doThrow(new BpmnError("expected exception")).when(mex).setVariable("rollbackData", null) + + DoCreateAllottedResourceTXCRollback DoCreateAllottedResourceTXCRollback = new DoCreateAllottedResourceTXCRollback() + DoCreateAllottedResourceTXCRollback.processRollbackException(mex) + } + + @Test +// @Ignore + public void processRollbackException_Ex() { + ExecutionEntity mex = setupMock() + initProcessRollbackException(mex) + + doThrow(new RuntimeException("expected exception")).when(mex).setVariable("rollbackData", null) + + DoCreateAllottedResourceTXCRollback DoCreateAllottedResourceTXCRollback = new DoCreateAllottedResourceTXCRollback() + DoCreateAllottedResourceTXCRollback.processRollbackException(mex) + } + + @Test +// @Ignore + public void processRollbackJavaException() { + ExecutionEntity mex = setupMock() + initProcessRollbackException(mex) + + DoCreateAllottedResourceTXCRollback DoCreateAllottedResourceTXCRollback = new DoCreateAllottedResourceTXCRollback() + DoCreateAllottedResourceTXCRollback.processRollbackJavaException(mex) + + //verify(mex).getVariable(DBGFLAG) + verify(mex).setVariable("rollbackData", null) + verify(mex).setVariable("rolledBack", false) + verify(mex).setVariable("rollbackError", "Caught Java exception in AllottedResource Create Rollback") + verify(mex, never()).setVariable("WorkflowException", null) + } + + @Test +// @Ignore + public void processRollbackJavaException_BpmnError() { + ExecutionEntity mex = setupMock() + initProcessRollbackException(mex) + + doThrow(new BpmnError("expected exception")).when(mex).setVariable("rollbackData", null) + + DoCreateAllottedResourceTXCRollback DoCreateAllottedResourceTXCRollback = new DoCreateAllottedResourceTXCRollback() + DoCreateAllottedResourceTXCRollback.processRollbackJavaException(mex) + } + + @Test +// @Ignore + public void processRollbackJavaException_Ex() { + ExecutionEntity mex = setupMock() + initProcessRollbackException(mex) + + doThrow(new RuntimeException("expected exception")).when(mex).setVariable("rollbackData", null) + + DoCreateAllottedResourceTXCRollback DoCreateAllottedResourceTXCRollback = new DoCreateAllottedResourceTXCRollback() + DoCreateAllottedResourceTXCRollback.processRollbackJavaException(mex) + } + + private RollbackData initPreProcess(ExecutionEntity mex) { + def data = new RollbackData() + + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("rollbackData")).thenReturn(data) + when(mex.getVariable("rollbackAAI")).thenReturn(true) + when(mex.getVariable("rollbackSDNC")).thenReturn(true) + when(mex.getVariable("disableRollback")).thenReturn("false") + + data.put("SERVICEINSTANCE", "allottedResourceId", "myid") + + data.put(RbType, "serviceInstanceId", "sii") + data.put(RbType, "parentServiceInstanceId", "psii") + + data.put(RbType, "rollbackAAI", "true") + data.put(RbType, "aaiARPath", "mypath") + + data.put(RbType, "rollbackSDNCassign", "true") + data.put(RbType, "rollbackSDNCactivate", "myactivate") + data.put(RbType, "rollbackSDNCcreate", "mycreate") + data.put(RbType, "sdncActivateRollbackReq", "activatereq") + data.put(RbType, "sdncCreateRollbackReq", "createreq") + data.put(RbType, "sdncAssignRollbackReq", "assignreq") + + return data + } + + private initUpdateAaiAROrchStatus(ExecutionEntity mex) { + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("aaiARPath")).thenReturn(aaiUriPfx + "/aai/v9/business/customers/customer/"+CUST+"/service-subscriptions/service-subscription/"+SVC+"/service-instances/service-instance/"+INST+"/allotted-resources/allotted-resource/"+ARID) + when(mex.getVariable("aai.endpoint")).thenReturn(aaiUriPfx) + } + + private initValidateSDNCResp(ExecutionEntity mex) { + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("prefix")).thenReturn(Prefix) + when(mex.getVariable("SDNCA_SuccessIndicator")).thenReturn(true) + } + + private String initValidateSDNCResp_Resp() { + return "<response-data><response-code>200</response-code></response-data>" + } + + private initDeleteAaiAR(ExecutionEntity mex) { + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("aaiARResourceVersion")).thenReturn(VERS) + when(mex.getVariable("aaiARPath")).thenReturn(aaiUriPfx + "/aai/v9/business/customers/customer/"+CUST+"/service-subscriptions/service-subscription/"+SVC+"/service-instances/service-instance/"+INST+"/allotted-resources/allotted-resource/"+ARID) + when(mex.getVariable("aai.endpoint")).thenReturn(aaiUriPfx) + } + + private initPostProcessRequest(ExecutionEntity mex) { + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("skipRollback")).thenReturn(false) + } + + private initProcessRollbackException(ExecutionEntity mex) { + when(mex.getVariable(DBGFLAG)).thenReturn("true") + } + + private initProcessRollbackJavaException(ExecutionEntity mex) { + when(mex.getVariable(DBGFLAG)).thenReturn("true") + } + +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceTXCTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceTXCTest.groovy new file mode 100644 index 0000000000..fa40c17e63 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceTXCTest.groovy @@ -0,0 +1,957 @@ +/* + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.vcpe.scripts + + +import org.camunda.bpm.engine.ProcessEngineServices +import org.camunda.bpm.engine.RepositoryService +import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity +import org.camunda.bpm.engine.repository.ProcessDefinition +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.junit.Before +import org.junit.BeforeClass +import org.junit.Rule +import org.junit.Test +import org.junit.Ignore +import org.mockito.MockitoAnnotations +import org.camunda.bpm.engine.delegate.BpmnError +import org.onap.so.bpmn.core.UrnPropertiesReader +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.bpmn.mock.FileUtil +import org.springframework.beans.factory.config.YamlPropertiesFactoryBean +import org.springframework.core.io.ClassPathResource +import org.springframework.core.io.FileSystemResource +import org.springframework.core.io.Resource + +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse +import static com.github.tomakehurst.wiremock.client.WireMock.put +import static com.github.tomakehurst.wiremock.client.WireMock.stubFor +import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching +import static org.junit.Assert.*; +import static org.mockito.Mockito.* +import static org.onap.so.bpmn.mock.StubResponseAAI.MockGetAllottedResource +import static org.onap.so.bpmn.mock.StubResponseAAI.MockPatchAllottedResource +import static org.onap.so.bpmn.mock.StubResponseAAI.MockPutAllottedResource +import static org.onap.so.bpmn.mock.StubResponseAAI.MockPutAllottedResource_500 + +import java.util.Map + +import org.onap.so.bpmn.core.RollbackData +import org.onap.so.bpmn.vcpe.scripts.MapSetter + +import com.github.tomakehurst.wiremock.junit.WireMockRule + +class DoCreateAllottedResourceTXCTest extends GroovyTestBase { + + @Rule + public WireMockRule wireMockRule = new WireMockRule(PORT) + + String Prefix = "DCARTXC_" + + @BeforeClass + public static void setUpBeforeClass() { + aaiUriPfx = UrnPropertiesReader.getVariable("aai.endpoint") + } + + @Before + public void init() + { + MockitoAnnotations.initMocks(this) + } + + public DoCreateAllottedResourceTXCTest() { + super("DoCreateAllottedResourceTXC") + } + + + // ***** preProcessRequest ***** + + @Test + // @Ignore + public void preProcessRequest() { + ExecutionEntity mex = setupMock() + initPreProcess(mex) + + DoCreateAllottedResourceTXC DoCreateAllottedResourceTXC = new DoCreateAllottedResourceTXC() + DoCreateAllottedResourceTXC.preProcessRequest(mex) + + //verify(mex).getVariable(DBGFLAG) + verify(mex).setVariable("prefix", Prefix) + + assertTrue(checkMissingPreProcessRequest("mso.workflow.sdncadapter.callback")) + assertTrue(checkMissingPreProcessRequest("mso.workflow.sdnc.replication.delay")) + assertTrue(checkMissingPreProcessRequest("serviceInstanceId")) + assertTrue(checkMissingPreProcessRequest("parentServiceInstanceId")) + assertTrue(checkMissingPreProcessRequest("allottedResourceModelInfo")) + assertTrue(checkMissingPreProcessRequest("brgWanMacAddress")) + assertTrue(checkMissingPreProcessRequest("allottedResourceRole")) + assertTrue(checkMissingPreProcessRequest("allottedResourceType")) + } + + + // ***** getAaiAR ***** + + @Test + @Ignore + public void getAaiAR() { + MockGetAllottedResource(CUST, SVC, INST, ARID, "VCPE/DoCreateAllottedResourceTXC/getArTxc.xml") + + ExecutionEntity mex = setupMock() + initGetAaiAR(mex) + + DoCreateAllottedResourceTXC DoCreateAllottedResourceTXC = new DoCreateAllottedResourceTXC() + DoCreateAllottedResourceTXC.getAaiAR(mex) + + verify(mex).setVariable("foundActiveAR", true) + } + + @Test + // @Ignore + public void getAaiAR_Duplicate() { + MockGetAllottedResource(CUST, SVC, INST, ARID, "VCPE/DoCreateAllottedResourceTXC/getArTxc.xml") + + ExecutionEntity mex = setupMock() + initGetAaiAR(mex) + + // fail if duplicate + when(mex.getVariable("failExists")).thenReturn("true") + + DoCreateAllottedResourceTXC DoCreateAllottedResourceTXC = new DoCreateAllottedResourceTXC() + + assertTrue(doBpmnError( { _ -> DoCreateAllottedResourceTXC.getAaiAR(mex) })) + } + + @Test + // @Ignore + public void getAaiAR_NotActive() { + MockGetAllottedResource(CUST, SVC, INST, ARID, "VCPE/DoCreateAllottedResourceTXC/getArTxc.xml") + + ExecutionEntity mex = setupMock() + initGetAaiAR(mex) + + // not active + when(mex.getVariable("aaiAROrchStatus")).thenReturn("not-active") + + DoCreateAllottedResourceTXC DoCreateAllottedResourceTXC = new DoCreateAllottedResourceTXC() + + assertTrue(doBpmnError( { _ -> DoCreateAllottedResourceTXC.getAaiAR(mex) })) + } + + @Test + @Ignore + public void getAaiAR_NoStatus() { + MockGetAllottedResource(CUST, SVC, INST, ARID, "VCPE/DoCreateAllottedResourceTXC/getArTxc.xml") + + ExecutionEntity mex = setupMock() + initGetAaiAR(mex) + + when(mex.getVariable("aaiAROrchStatus")).thenReturn(null) + + DoCreateAllottedResourceTXC DoCreateAllottedResourceTXC = new DoCreateAllottedResourceTXC() + DoCreateAllottedResourceTXC.getAaiAR(mex) + + verify(mex, never()).setVariable("foundActiveAR", true) + } + + + // ***** createAaiAR ***** + + @Test + @Ignore + public void createAaiAR() { + ExecutionEntity mex = setupMock() + def map = setupMap(mex) + initCreateAaiAr(mex) + + MockPutAllottedResource(CUST, SVC, INST, ARID) + + DoCreateAllottedResourceTXC DoCreateAllottedResourceTXC = new DoCreateAllottedResourceTXC() + DoCreateAllottedResourceTXC.createAaiAR(mex) + + def data = map.get("rollbackData") + assertNotNull(data) + assertTrue(data instanceof RollbackData) + + assertEquals("45", data.get(Prefix, "disableRollback")) + assertEquals("true", data.get(Prefix, "rollbackAAI")) + assertEquals(ARID, data.get(Prefix, "allottedResourceId")) + assertEquals("sii", data.get(Prefix, "serviceInstanceId")) + assertEquals("psii", data.get(Prefix, "parentServiceInstanceId")) + assertEquals(mex.getVariable("PSI_resourceLink")+"/allotted-resources/allotted-resource/"+ARID, data.get(Prefix, "aaiARPath")) + } + + @Test + @Ignore + public void createAaiAR_NoArid_NoModelUuids() { + ExecutionEntity mex = setupMock() + def map = setupMap(mex) + initCreateAaiAr(mex) + + // no allottedResourceId - will be generated + + when(mex.getVariable("allottedResourceId")).thenReturn(null) + + wireMockRule + .stubFor(put(urlMatching("/aai/.*/allotted-resource/.*")) + .willReturn(aResponse() + .withStatus(200))) + + DoCreateAllottedResourceTXC DoCreateAllottedResourceTXC = new DoCreateAllottedResourceTXC() + DoCreateAllottedResourceTXC.createAaiAR(mex) + + def arid = map.get("allottedResourceId") + assertNotNull(arid) + assertFalse(arid.isEmpty()) + + def data = map.get("rollbackData") + assertNotNull(data) + assertTrue(data instanceof RollbackData) + + assertEquals(arid, data.get(Prefix, "allottedResourceId")) + } + + @Test + // @Ignore + public void createAaiAR_MissingPsiLink() { + ExecutionEntity mex = setupMock() + initCreateAaiAr(mex) + + when(mex.getVariable("PSI_resourceLink")).thenReturn(null) + + MockPutAllottedResource(CUST, SVC, INST, ARID) + + DoCreateAllottedResourceTXC DoCreateAllottedResourceTXC = new DoCreateAllottedResourceTXC() + + assertTrue(doBpmnError({ _ -> DoCreateAllottedResourceTXC.createAaiAR(mex) })) + } + + @Test + // @Ignore + public void createAaiAR_HttpFailed() { + ExecutionEntity mex = setupMock() + initCreateAaiAr(mex) + + MockPutAllottedResource_500(CUST, SVC, INST, ARID) + + DoCreateAllottedResourceTXC DoCreateAllottedResourceTXC = new DoCreateAllottedResourceTXC() + + assertTrue(doBpmnError({ _ -> DoCreateAllottedResourceTXC.createAaiAR(mex) })) + } + + @Test + // @Ignore + public void createAaiAR_BpmnError() { + ExecutionEntity mex = setupMock() + initCreateAaiAr(mex) + + when(mex.getVariable("aai.endpoint")).thenThrow(new BpmnError("expected exception")) + + MockPutAllottedResource(CUST, SVC, INST, ARID) + + DoCreateAllottedResourceTXC DoCreateAllottedResourceTXC = new DoCreateAllottedResourceTXC() + + assertTrue(doBpmnError({ _ -> DoCreateAllottedResourceTXC.createAaiAR(mex) })) + } + + @Test + // @Ignore + public void createAaiAR_Ex() { + ExecutionEntity mex = setupMock() + initCreateAaiAr(mex) + + when(mex.getVariable("aai.endpoint")).thenThrow(new RuntimeException("expected exception")) + + MockPutAllottedResource(CUST, SVC, INST, ARID) + + DoCreateAllottedResourceTXC DoCreateAllottedResourceTXC = new DoCreateAllottedResourceTXC() + + assertTrue(doBpmnError({ _ -> DoCreateAllottedResourceTXC.createAaiAR(mex) })) + } + + + // ***** buildSDNCRequest ***** + + @Test + // @Ignore + public void buildSDNCRequest() { + ExecutionEntity mex = setupMock() + initBuildSDNCRequest(mex) + + DoCreateAllottedResourceTXC DoCreateAllottedResourceTXC = new DoCreateAllottedResourceTXC() + + String result = DoCreateAllottedResourceTXC.buildSDNCRequest(mex, "myact", "myreq") + + assertTrue(result.indexOf("<sdncadapter:RequestId>myreq</") >= 0) + assertTrue(result.indexOf("<sdncadapter:SvcAction>myact</") >= 0) + assertTrue(result.indexOf("<allotted-resource-id>ari</") >= 0) + assertTrue(result.indexOf("<sdncadapter:SvcInstanceId>sii</") >= 0) + assertTrue(result.indexOf("<service-instance-id>sii</") >= 0) + assertTrue(result.indexOf("<parent-service-instance-id>psii</") >= 0) + assertTrue(result.indexOf("<subscription-service-type>sst</") >= 0) + assertTrue(result.indexOf("<global-customer-id>gci</") >= 0) + assertTrue(result.indexOf("<sdncadapter:CallbackUrl>scu</") >= 0) + assertTrue(result.indexOf("<request-id>mri</") >= 0) + assertTrue(result.indexOf("<model-invariant-uuid/>") >= 0) + assertTrue(result.indexOf("<model-uuid/>") >= 0) + assertTrue(result.indexOf("<model-customization-uuid/>") >= 0) + assertTrue(result.indexOf("<model-version/>") >= 0) + assertTrue(result.indexOf("<model-name/>") >= 0) + } + + @Test + // @Ignore + public void buildSDNCRequest_Ex() { + ExecutionEntity mex = setupMock() + initBuildSDNCRequest(mex) + + when(mex.getVariable("allottedResourceId")).thenThrow(new RuntimeException("expected exception")) + + DoCreateAllottedResourceTXC DoCreateAllottedResourceTXC = new DoCreateAllottedResourceTXC() + + assertTrue(doBpmnError({ _ -> DoCreateAllottedResourceTXC.buildSDNCRequest(mex, "myact", "myreq") })) + } + + + // ***** preProcessSDNCAssign ***** + + @Test + // @Ignore + public void preProcessSDNCAssign() { + ExecutionEntity mex = setupMock() + def map = setupMap(mex) + def data = initPreProcessSDNC(mex) + + DoCreateAllottedResourceTXC DoCreateAllottedResourceTXC = new DoCreateAllottedResourceTXC() + DoCreateAllottedResourceTXC.preProcessSDNCAssign(mex) + + def req = map.get("sdncAssignRequest") + assertNotNull(req) + + assertEquals(data, map.get("rollbackData")) + + def rbreq = data.get(Prefix, "sdncAssignRollbackReq") + + assertTrue(req.indexOf("<sdncadapter:SvcAction>assign</") >= 0) + assertTrue(req.indexOf("<request-action>CreateTunnelXConnInstance</") >= 0) + assertTrue(req.indexOf("<sdncadapter:RequestId>") >= 0) + + assertTrue(rbreq.indexOf("<sdncadapter:SvcAction>unassign</") >= 0) + assertTrue(rbreq.indexOf("<request-action>DeleteTunnelXConnInstance</") >= 0) + assertTrue(rbreq.indexOf("<sdncadapter:RequestId>") >= 0) + } + + @Test + // @Ignore + public void preProcessSDNCAssign_BpmnError() { + ExecutionEntity mex = setupMock() + initPreProcessSDNC(mex) + + when(mex.getVariable("rollbackData")).thenThrow(new BpmnError("expected exception")) + + DoCreateAllottedResourceTXC DoCreateAllottedResourceTXC = new DoCreateAllottedResourceTXC() + + assertTrue(doBpmnError({ _ -> DoCreateAllottedResourceTXC.preProcessSDNCAssign(mex) })) + } + + @Test + // @Ignore + public void preProcessSDNCAssign_Ex() { + ExecutionEntity mex = setupMock() + initPreProcessSDNC(mex) + + when(mex.getVariable("rollbackData")).thenThrow(new RuntimeException("expected exception")) + + DoCreateAllottedResourceTXC DoCreateAllottedResourceTXC = new DoCreateAllottedResourceTXC() + + assertTrue(doBpmnError({ _ -> DoCreateAllottedResourceTXC.preProcessSDNCAssign(mex) })) + } + + + // ***** preProcessSDNCCreate ***** + + @Test + // @Ignore + public void preProcessSDNCCreate() { + ExecutionEntity mex = setupMock() + def map = setupMap(mex) + def data = initPreProcessSDNC(mex) + + DoCreateAllottedResourceTXC DoCreateAllottedResourceTXC = new DoCreateAllottedResourceTXC() + DoCreateAllottedResourceTXC.preProcessSDNCCreate(mex) + + def req = map.get("sdncCreateRequest") + assertNotNull(req) + + assertEquals(data, map.get("rollbackData")) + + def rbreq = data.get(Prefix, "sdncCreateRollbackReq") + + assertTrue(req.indexOf("<sdncadapter:SvcAction>create</") >= 0) + assertTrue(req.indexOf("<request-action>CreateTunnelXConnInstance</") >= 0) + assertTrue(req.indexOf("<sdncadapter:RequestId>") >= 0) + + assertTrue(rbreq.indexOf("<sdncadapter:SvcAction>delete</") >= 0) + assertTrue(rbreq.indexOf("<request-action>DeleteTunnelXConnInstance</") >= 0) + assertTrue(rbreq.indexOf("<sdncadapter:RequestId>") >= 0) + + } + + @Test + // @Ignore + public void preProcessSDNCCreate_BpmnError() { + ExecutionEntity mex = setupMock() + initPreProcessSDNC(mex) + + when(mex.getVariable("rollbackData")).thenThrow(new BpmnError("expected exception")) + + DoCreateAllottedResourceTXC DoCreateAllottedResourceTXC = new DoCreateAllottedResourceTXC() + + assertTrue(doBpmnError({ _ -> DoCreateAllottedResourceTXC.preProcessSDNCCreate(mex) })) + } + + @Test + // @Ignore + public void preProcessSDNCCreate_Ex() { + ExecutionEntity mex = setupMock() + initPreProcessSDNC(mex) + + when(mex.getVariable("rollbackData")).thenThrow(new RuntimeException("expected exception")) + + DoCreateAllottedResourceTXC DoCreateAllottedResourceTXC = new DoCreateAllottedResourceTXC() + + assertTrue(doBpmnError({ _ -> DoCreateAllottedResourceTXC.preProcessSDNCCreate(mex) })) + } + + + // ***** preProcessSDNCActivate ***** + + @Test + // @Ignore + public void preProcessSDNCActivate() { + ExecutionEntity mex = setupMock() + def map = setupMap(mex) + def data = initPreProcessSDNC(mex) + + DoCreateAllottedResourceTXC DoCreateAllottedResourceTXC = new DoCreateAllottedResourceTXC() + DoCreateAllottedResourceTXC.preProcessSDNCActivate(mex) + + def req = map.get("sdncActivateRequest") + assertNotNull(req) + + assertEquals(data, map.get("rollbackData")) + + def rbreq = data.get(Prefix, "sdncActivateRollbackReq") + + assertTrue(req.indexOf("<sdncadapter:SvcAction>activate</") >= 0) + assertTrue(req.indexOf("<request-action>CreateTunnelXConnInstance</") >= 0) + assertTrue(req.indexOf("<sdncadapter:RequestId>") >= 0) + + assertTrue(rbreq.indexOf("<sdncadapter:SvcAction>deactivate</") >= 0) + assertTrue(rbreq.indexOf("<request-action>DeleteTunnelXConnInstance</") >= 0) + assertTrue(rbreq.indexOf("<sdncadapter:RequestId>") >= 0) + + } + + @Test + // @Ignore + public void preProcessSDNCActivate_BpmnError() { + ExecutionEntity mex = setupMock() + initPreProcessSDNC(mex) + + when(mex.getVariable("rollbackData")).thenThrow(new BpmnError("expected exception")) + + DoCreateAllottedResourceTXC DoCreateAllottedResourceTXC = new DoCreateAllottedResourceTXC() + + assertTrue(doBpmnError({ _ -> DoCreateAllottedResourceTXC.preProcessSDNCActivate(mex) })) + } + + @Test + // @Ignore + public void preProcessSDNCActivate_Ex() { + ExecutionEntity mex = setupMock() + initPreProcessSDNC(mex) + + when(mex.getVariable("rollbackData")).thenThrow(new RuntimeException("expected exception")) + + DoCreateAllottedResourceTXC DoCreateAllottedResourceTXC = new DoCreateAllottedResourceTXC() + + assertTrue(doBpmnError({ _ -> DoCreateAllottedResourceTXC.preProcessSDNCActivate(mex) })) + } + + + // ***** validateSDNCResp ***** + + @Test + // @Ignore + public void validateSDNCResp() { + ExecutionEntity mex = setupMock() + def map = setupMap(mex) + def data = initValidateSDNCResp(mex) + def resp = initValidateSDNCResp_Resp() + + when(mex.getVariable(Prefix+"sdncResponseSuccess")).thenReturn(true) + + DoCreateAllottedResourceTXC DoCreateAllottedResourceTXC = new DoCreateAllottedResourceTXC() + + DoCreateAllottedResourceTXC.validateSDNCResp(mex, resp, "create") + + verify(mex).getVariable("WorkflowException") + verify(mex).getVariable("SDNCA_SuccessIndicator") + verify(mex).getVariable("rollbackData") + + assertEquals(data, map.get("rollbackData")) + + assertEquals("true", data.get(Prefix, "rollback" + "SDNCcreate")) + + } + + @Test + // @Ignore + public void validateSDNCResp_Get() { + ExecutionEntity mex = setupMock() + def data = initValidateSDNCResp(mex) + def resp = initValidateSDNCResp_Resp() + + when(mex.getVariable(Prefix+"sdncResponseSuccess")).thenReturn(true) + + DoCreateAllottedResourceTXC DoCreateAllottedResourceTXC = new DoCreateAllottedResourceTXC() + + DoCreateAllottedResourceTXC.validateSDNCResp(mex, resp, "get") + + verify(mex).getVariable("WorkflowException") + verify(mex).getVariable("SDNCA_SuccessIndicator") + + verify(mex, never()).getVariable("rollbackData") + } + + @Test + // @Ignore + public void validateSDNCResp_Unsuccessful() { + ExecutionEntity mex = setupMock() + initValidateSDNCResp(mex) + def resp = initValidateSDNCResp_Resp() + + // unsuccessful + when(mex.getVariable(Prefix+"sdncResponseSuccess")).thenReturn(false) + + DoCreateAllottedResourceTXC DoCreateAllottedResourceTXC = new DoCreateAllottedResourceTXC() + + assertTrue(doBpmnError({ _ -> DoCreateAllottedResourceTXC.validateSDNCResp(mex, resp, "create") })) + } + + @Test + // @Ignore + public void validateSDNCResp_BpmnError() { + ExecutionEntity mex = setupMock() + initValidateSDNCResp(mex) + def resp = initValidateSDNCResp_Resp() + + when(mex.getVariable("WorkflowException")).thenThrow(new BpmnError("expected exception")) + + DoCreateAllottedResourceTXC DoCreateAllottedResourceTXC = new DoCreateAllottedResourceTXC() + + assertTrue(doBpmnError({ _ -> DoCreateAllottedResourceTXC.validateSDNCResp(mex, resp, "create") })) + } + + @Test + // @Ignore + public void validateSDNCResp_Ex() { + ExecutionEntity mex = setupMock() + initValidateSDNCResp(mex) + def resp = initValidateSDNCResp_Resp() + + when(mex.getVariable("WorkflowException")).thenThrow(new RuntimeException("expected exception")) + + DoCreateAllottedResourceTXC DoCreateAllottedResourceTXC = new DoCreateAllottedResourceTXC() + + assertTrue(doBpmnError({ _ -> DoCreateAllottedResourceTXC.validateSDNCResp(mex, resp, "create") })) + } + + + // ***** preProcessSDNCGet ***** + + @Test + // @Ignore + public void preProcessSDNCGet_FoundAR() { + ExecutionEntity mex = setupMock() + def map = setupMap(mex) + initPreProcessSDNCGet(mex) + + DoCreateAllottedResourceTXC DoCreateAllottedResourceTXC = new DoCreateAllottedResourceTXC() + DoCreateAllottedResourceTXC.preProcessSDNCGet(mex) + + String req = map.get("sdncGetRequest") + + assertTrue(req.indexOf("<sdncadapter:RequestId>") >= 0) + assertTrue(req.indexOf("<sdncadapter:SvcInstanceId>sii</") >= 0) + assertTrue(req.indexOf("<sdncadapter:SvcOperation>arlink</") >= 0) + assertTrue(req.indexOf("<sdncadapter:CallbackUrl>myurl</") >= 0) + + } + + @Test + // @Ignore + public void preProcessSDNCGet_NotFoundAR() { + ExecutionEntity mex = setupMock() + def map = setupMap(mex) + initPreProcessSDNCGet(mex) + + when(mex.getVariable("foundActiveAR")).thenReturn(false) + + DoCreateAllottedResourceTXC DoCreateAllottedResourceTXC = new DoCreateAllottedResourceTXC() + DoCreateAllottedResourceTXC.preProcessSDNCGet(mex) + + String req = map.get("sdncGetRequest") + + assertTrue(req.indexOf("<sdncadapter:RequestId>") >= 0) + assertTrue(req.indexOf("<sdncadapter:SvcInstanceId>sii</") >= 0) + assertTrue(req.indexOf("<sdncadapter:SvcOperation>assignlink</") >= 0) + assertTrue(req.indexOf("<sdncadapter:CallbackUrl>myurl</") >= 0) + + } + + @Test + // @Ignore + public void preProcessSDNCGet_Ex() { + ExecutionEntity mex = setupMock() + initPreProcessSDNCGet(mex) + + when(mex.getVariable("foundActiveAR")).thenThrow(new RuntimeException("expected exception")) + + DoCreateAllottedResourceTXC DoCreateAllottedResourceTXC = new DoCreateAllottedResourceTXC() + + assertTrue(doBpmnError({ _ -> DoCreateAllottedResourceTXC.preProcessSDNCGet(mex) })) + } + + + // ***** updateAaiAROrchStatus ***** + + @Test + @Ignore + public void updateAaiAROrchStatus() { + MockPatchAllottedResource(CUST, SVC, INST, ARID) + + ExecutionEntity mex = setupMock() + initUpdateAaiAROrchStatus(mex) + + DoCreateAllottedResourceTXC DoCreateAllottedResourceTXC = new DoCreateAllottedResourceTXC() + DoCreateAllottedResourceTXC.updateAaiAROrchStatus(mex, "success") + } + + + // ***** generateOutputs ***** + + @Test + // @Ignore + public void generateOutputs() { + ExecutionEntity mex = setupMock() + def txctop = FileUtil.readResourceFile("__files/VCPE/DoCreateAllottedResourceTXC/SDNCTopologyQueryCallback.xml") + + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("enhancedCallbackRequestData")).thenReturn(txctop) + + DoCreateAllottedResourceTXC DoCreateAllottedResourceTXC = new DoCreateAllottedResourceTXC() + DoCreateAllottedResourceTXC.generateOutputs(mex) + + verify(mex).setVariable("allotedResourceName", "namefromrequest") + verify(mex).setVariable("vni", "my-vni") + verify(mex).setVariable("vgmuxBearerIP", "my-bearer-ip") + verify(mex).setVariable("vgmuxLanIP", "my-lan-ip") + + } + + @Test + // @Ignore + public void generateOutputs_BadXml() { + ExecutionEntity mex = setupMock() + + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("enhancedCallbackRequestData")).thenReturn("invalid xml") + + DoCreateAllottedResourceTXC DoCreateAllottedResourceTXC = new DoCreateAllottedResourceTXC() + DoCreateAllottedResourceTXC.generateOutputs(mex) + + verify(mex, never()).setVariable(anyString(), anyString()) + + } + + @Test + // @Ignore + public void generateOutputs_BpmnError() { + ExecutionEntity mex = setupMock() + + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("enhancedCallbackRequestData")).thenThrow(new BpmnError("expected exception")) + + DoCreateAllottedResourceTXC DoCreateAllottedResourceTXC = new DoCreateAllottedResourceTXC() + + DoCreateAllottedResourceTXC.generateOutputs(mex) + verify(mex, never()).setVariable(anyString(), anyString()) + + } + + @Test + // @Ignore + public void generateOutputs_Ex() { + ExecutionEntity mex = setupMock() + + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("enhancedCallbackRequestData")).thenThrow(new RuntimeException("expected exception")) + + DoCreateAllottedResourceTXC DoCreateAllottedResourceTXC = new DoCreateAllottedResourceTXC() + + DoCreateAllottedResourceTXC.generateOutputs(mex) + verify(mex, never()).setVariable(anyString(), anyString()) + + } + + + // ***** preProcessRollback ***** + + @Test + // @Ignore + public void preProcessRollback() { + ExecutionEntity mex = setupMock() + WorkflowException wfe = mock(WorkflowException.class) + + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("WorkflowException")).thenReturn(wfe) + + DoCreateAllottedResourceTXC DoCreateAllottedResourceTXC = new DoCreateAllottedResourceTXC() + DoCreateAllottedResourceTXC.preProcessRollback(mex) + + verify(mex).setVariable("prevWorkflowException", wfe) + + } + + @Test + // @Ignore + public void preProcessRollback_NotWFE() { + ExecutionEntity mex = setupMock() + + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("WorkflowException")).thenReturn("I'm not a WFE") + + DoCreateAllottedResourceTXC DoCreateAllottedResourceTXC = new DoCreateAllottedResourceTXC() + DoCreateAllottedResourceTXC.preProcessRollback(mex) + +// verify(mex, never()).setVariable("prevWorkflowException", any()) + + } + + @Test + // @Ignore + public void preProcessRollback_BpmnError() { + ExecutionEntity mex = setupMock() + + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("WorkflowException")).thenThrow(new BpmnError("expected exception")) + + DoCreateAllottedResourceTXC DoCreateAllottedResourceTXC = new DoCreateAllottedResourceTXC() + + DoCreateAllottedResourceTXC.preProcessRollback(mex) + + } + + @Test + // @Ignore + public void preProcessRollback_Ex() { + ExecutionEntity mex = setupMock() + + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("WorkflowException")).thenThrow(new RuntimeException("expected exception")) + + DoCreateAllottedResourceTXC DoCreateAllottedResourceTXC = new DoCreateAllottedResourceTXC() + + DoCreateAllottedResourceTXC.preProcessRollback(mex) + + } + + + // ***** postProcessRollback ***** + + @Test + // @Ignore + public void postProcessRollback() { + ExecutionEntity mex = setupMock() + WorkflowException wfe = mock(WorkflowException.class) + + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("prevWorkflowException")).thenReturn(wfe) + + DoCreateAllottedResourceTXC DoCreateAllottedResourceTXC = new DoCreateAllottedResourceTXC() + DoCreateAllottedResourceTXC.postProcessRollback(mex) + + verify(mex).setVariable("WorkflowException", wfe) + verify(mex).setVariable("rollbackData", null) + + } + + @Test + // @Ignore + public void postProcessRollback_NotWFE() { + ExecutionEntity mex = setupMock() + + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("prevWorkflowException")).thenReturn("I'm not a WFE") + + DoCreateAllottedResourceTXC DoCreateAllottedResourceTXC = new DoCreateAllottedResourceTXC() + DoCreateAllottedResourceTXC.postProcessRollback(mex) + +// verify(mex, never()).setVariable("WorkflowException", any()) + verify(mex).setVariable("rollbackData", null) + + } + + @Test + // @Ignore + public void postProcessRollback_BpmnError() { + ExecutionEntity mex = setupMock() + + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("prevWorkflowException")).thenThrow(new BpmnError("expected exception")) + + DoCreateAllottedResourceTXC DoCreateAllottedResourceTXC = new DoCreateAllottedResourceTXC() + + assertTrue(doBpmnError({ _ -> DoCreateAllottedResourceTXC.postProcessRollback(mex) })) + verify(mex, never()).setVariable("rollbackData", null) + + } + + @Test + // @Ignore + public void postProcessRollback_Ex() { + ExecutionEntity mex = setupMock() + + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("prevWorkflowException")).thenThrow(new RuntimeException("expected exception")) + + DoCreateAllottedResourceTXC DoCreateAllottedResourceTXC = new DoCreateAllottedResourceTXC() + + DoCreateAllottedResourceTXC.postProcessRollback(mex) + verify(mex, never()).setVariable("rollbackData", null) + + } + + private boolean checkMissingPreProcessRequest(String fieldnm) { + ExecutionEntity mex = setupMock() + initPreProcess(mex) + + DoCreateAllottedResourceTXC DoCreateAllottedResourceTXC = new DoCreateAllottedResourceTXC() + + when(mex.getVariable(fieldnm)).thenReturn("") + + return doBpmnError( { _ -> DoCreateAllottedResourceTXC.preProcessRequest(mex) }) + } + + private void initPreProcess(ExecutionEntity mex) { + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("mso.workflow.sdncadapter.callback")).thenReturn("sdncurn") + when(mex.getVariable("mso.workflow.sdnc.replication.delay")).thenReturn("sdncdelay") + when(mex.getVariable("serviceInstanceId")).thenReturn("sii") + when(mex.getVariable("parentServiceInstanceId")).thenReturn("psii") + when(mex.getVariable("allottedResourceModelInfo")).thenReturn("armi") + when(mex.getVariable("brgWanMacAddress")).thenReturn("bwma") + when(mex.getVariable("allottedResourceRole")).thenReturn("arr") + when(mex.getVariable("allottedResourceType")).thenReturn("art") + } + + private void initGetAaiAR(ExecutionEntity mex) { + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("allottedResourceType")).thenReturn("TXCt") + when(mex.getVariable("allottedResourceRole")).thenReturn("TXCr") + when(mex.getVariable("CSI_service")).thenReturn(FileUtil.readResourceFile("__files/VCPE/DoCreateAllottedResourceTXC/getAR.xml")) + when(mex.getVariable("aai.endpoint")).thenReturn(aaiUriPfx) + when(mex.getVariable("aaiAROrchStatus")).thenReturn("Active") + } + + private initCreateAaiAr(ExecutionEntity mex) { + when(mex.getVariable("disableRollback")).thenReturn(45) + when(mex.getVariable("serviceInstanceId")).thenReturn("sii") + when(mex.getVariable("parentServiceInstanceId")).thenReturn("psii") + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("allottedResourceId")).thenReturn(ARID) + when(mex.getVariable("aai.endpoint")).thenReturn(aaiUriPfx) + when(mex.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn(UrnPropertiesReader.getVariable("mso.workflow.global.default.aai.namespace")) + when(mex.getVariable("PSI_resourceLink")).thenReturn(aaiUriPfx + "/aai/v9/business/customers/customer/"+CUST+"/service-subscriptions/service-subscription/"+SVC+"/service-instances/service-instance/"+INST) + when(mex.getVariable("allottedResourceType")).thenReturn("TXCt") + when(mex.getVariable("allottedResourceRole")).thenReturn("TXCr") + when(mex.getVariable("CSI_resourceLink")).thenReturn(aaiUriPfx+"/aai/v9/mycsi") + when(mex.getVariable("allottedResourceModelInfo")).thenReturn(""" + { + "modelInvariantUuid":"modelinvuuid", + "modelUuid":"modeluuid", + "modelCustomizationUuid":"modelcustuuid" + } + """) + } + + private initBuildSDNCRequest(ExecutionEntity mex) { + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("allottedResourceId")).thenReturn("ari") + when(mex.getVariable("serviceInstanceId")).thenReturn("sii") + when(mex.getVariable("parentServiceInstanceId")).thenReturn("psii") + when(mex.getVariable("subscriptionServiceType")).thenReturn("sst") + when(mex.getVariable("globalCustomerId")).thenReturn("gci") + when(mex.getVariable("sdncCallbackUrl")).thenReturn("scu") + when(mex.getVariable("msoRequestId")).thenReturn("mri") + } + + private RollbackData initPreProcessSDNC(ExecutionEntity mex) { + def data = new RollbackData() + + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("rollbackData")).thenReturn(data) + + return data + } + + private initPreProcessSDNCGet(ExecutionEntity mex) { + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("sdncCallbackUrl")).thenReturn("myurl") + when(mex.getVariable("foundActiveAR")).thenReturn(true) + when(mex.getVariable("aaiARGetResponse")).thenReturn("<selflink>arlink</selflink>") + when(mex.getVariable("sdncAssignResponse")).thenReturn("<response-data><object-path>assignlink</object-path></response-data>") + when(mex.getVariable("serviceInstanceId")).thenReturn("sii") + when(mex.getVariable("sdncCallbackUrl")).thenReturn("myurl") + } + + private RollbackData initValidateSDNCResp(ExecutionEntity mex) { + def data = new RollbackData() + + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("prefix")).thenReturn(Prefix) + when(mex.getVariable("SDNCA_SuccessIndicator")).thenReturn(true) + when(mex.getVariable("rollbackData")).thenReturn(data) + + return data + } + + private String initValidateSDNCResp_Resp() { + return "<response-data><response-code>200</response-code></response-data>" + } + + private initUpdateAaiAROrchStatus(ExecutionEntity mex) { + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("aaiARPath")).thenReturn(aaiUriPfx + "/aai/v9/business/customers/customer/"+CUST+"/service-subscriptions/service-subscription/"+SVC+"/service-instances/service-instance/"+INST+"/allotted-resources/allotted-resource/"+ARID) + } + +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/vcpe/scripts/DoDeleteAllottedResourceBRGTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/vcpe/scripts/DoDeleteAllottedResourceBRGTest.groovy new file mode 100644 index 0000000000..e8004d3d2b --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/vcpe/scripts/DoDeleteAllottedResourceBRGTest.groovy @@ -0,0 +1,606 @@ +/* + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.vcpe.scripts + + +import org.camunda.bpm.engine.ProcessEngineServices +import org.camunda.bpm.engine.RepositoryService +import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity +import org.camunda.bpm.engine.repository.ProcessDefinition +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.junit.Before +import org.junit.BeforeClass +import org.junit.Rule +import org.junit.Test +import org.junit.Ignore +import org.mockito.MockitoAnnotations +import org.camunda.bpm.engine.delegate.BpmnError +import org.onap.so.bpmn.core.UrnPropertiesReader +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.bpmn.mock.FileUtil + +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse +import static com.github.tomakehurst.wiremock.client.WireMock.delete +import static com.github.tomakehurst.wiremock.client.WireMock.get +import static com.github.tomakehurst.wiremock.client.WireMock.patch +import static com.github.tomakehurst.wiremock.client.WireMock.put +import static com.github.tomakehurst.wiremock.client.WireMock.stubFor +import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching +import static org.junit.Assert.*; +import static org.mockito.Mockito.* +import static org.onap.so.bpmn.mock.StubResponseAAI.MockDeleteAllottedResource +import static org.onap.so.bpmn.mock.StubResponseAAI.MockGetAllottedResource +import static org.onap.so.bpmn.mock.StubResponseAAI.MockPatchAllottedResource +import static org.onap.so.bpmn.mock.StubResponseAAI.MockQueryAllottedResourceById + +import java.util.Map + +import org.onap.so.bpmn.core.RollbackData +import org.onap.so.bpmn.vcpe.scripts.MapSetter + +import com.github.tomakehurst.wiremock.junit.WireMockRule + +class DoDeleteAllottedResourceBRGTest extends GroovyTestBase { + + @Rule + public WireMockRule wireMockRule = new WireMockRule(PORT) + + String Prefix = "DDARBRG_" + + @BeforeClass + public static void setUpBeforeClass() { + super.setUpBeforeClass() + } + + @Before + public void init() + { + MockitoAnnotations.initMocks(this) + } + + public DoDeleteAllottedResourceBRGTest() { + super("DoDeleteAllottedResourceBRG") + } + + + // ***** preProcessRequest ***** + + @Test +// @Ignore + public void preProcessRequest() { + ExecutionEntity mex = setupMock() + initPreProcess(mex) + + DoDeleteAllottedResourceBRG DoDeleteAllottedResourceBRG = new DoDeleteAllottedResourceBRG() + DoDeleteAllottedResourceBRG.preProcessRequest(mex) + + //verify(mex).getVariable(DBGFLAG) + verify(mex).setVariable("prefix", Prefix) + verify(mex).setVariable("sdncCallbackUrl", "sdncurn") + + assertTrue(checkMissingPreProcessRequest("mso.workflow.sdncadapter.callback")) + assertTrue(checkMissingPreProcessRequest("serviceInstanceId")) + assertTrue(checkMissingPreProcessRequest("allottedResourceId")) + } + + @Test +// @Ignore + public void preProcessRequest_BpmnError() { + ExecutionEntity mex = setupMock() + initPreProcess(mex) + + when(mex.getVariable("serviceInstanceId")).thenThrow(new BpmnError("expected exception")) + + DoDeleteAllottedResourceBRG DoDeleteAllottedResourceBRG = new DoDeleteAllottedResourceBRG() + + assertTrue(doBpmnError( { _ -> DoDeleteAllottedResourceBRG.preProcessRequest(mex) })) + } + + @Test +// @Ignore + public void preProcessRequest_Ex() { + ExecutionEntity mex = setupMock() + initPreProcess(mex) + + when(mex.getVariable("serviceInstanceId")).thenThrow(new RuntimeException("expected exception")) + + DoDeleteAllottedResourceBRG DoDeleteAllottedResourceBRG = new DoDeleteAllottedResourceBRG() + + assertTrue(doBpmnError( { _ -> DoDeleteAllottedResourceBRG.preProcessRequest(mex) })) + } + + + // ***** getAaiAR ***** + + @Test + @Ignore + public void getAaiAR() { + MockQueryAllottedResourceById(ARID, "GenericFlows/getARUrlById.xml") + MockGetAllottedResource(CUST, SVC, INST, ARID, "VCPE/DoDeleteAllottedResourceBRG/arGetById.xml") + + ExecutionEntity mex = setupMock() + initGetAaiAR(mex) + + DoDeleteAllottedResourceBRG DoDeleteAllottedResourceBRG = new DoDeleteAllottedResourceBRG() + DoDeleteAllottedResourceBRG.getAaiAR(mex) + + verify(mex).setVariable("parentServiceInstanceId", INST) + } + + @Test +// @Ignore + public void getAaiAR_EmptyResponse() { + + // note: empty result-link + wireMockRule + .stubFor(get(urlMatching("/aai/.*/search/.*")) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBody("<result-data></result-data>"))) + + MockGetAllottedResource(CUST, SVC, INST, ARID, "VCPE/DoDeleteAllottedResourceBRG/arGetById.xml") + + ExecutionEntity mex = setupMock() + initGetAaiAR(mex) + + DoDeleteAllottedResourceBRG DoDeleteAllottedResourceBRG = new DoDeleteAllottedResourceBRG() + + assertTrue(doBpmnError( { _ -> DoDeleteAllottedResourceBRG.getAaiAR(mex) })) + } + + + // ***** updateAaiAROrchStatus ***** + + @Test + @Ignore + public void updateAaiAROrchStatus() { + ExecutionEntity mex = setupMock() + initUpdateAaiAROrchStatus(mex) + + MockPatchAllottedResource(CUST, SVC, INST, ARID) + + DoDeleteAllottedResourceBRG DoDeleteAllottedResourceBRG = new DoDeleteAllottedResourceBRG() + DoDeleteAllottedResourceBRG.updateAaiAROrchStatus(mex, "success") + } + + + // ***** buildSDNCRequest ***** + + @Test +// @Ignore + public void buildSDNCRequest() { + ExecutionEntity mex = setupMock() + initBuildSDNCRequest(mex) + + DoDeleteAllottedResourceBRG DoDeleteAllottedResourceBRG = new DoDeleteAllottedResourceBRG() + + String result = DoDeleteAllottedResourceBRG.buildSDNCRequest(mex, "myact", "myreq") + + assertTrue(result.indexOf("<sdncadapter:RequestId>myreq</") >= 0) + assertTrue(result.indexOf("<sdncadapter:SvcAction>myact</") >= 0) + assertTrue(result.indexOf("<allotted-resource-id>ari</") >= 0) + assertTrue(result.indexOf("<sdncadapter:SvcInstanceId>sii</") >= 0) + assertTrue(result.indexOf("<service-instance-id>sii</") >= 0) + assertTrue(result.indexOf("<parent-service-instance-id>psii</") >= 0) + assertTrue(result.indexOf("<subscription-service-type>sst</") >= 0) + assertTrue(result.indexOf("<global-customer-id>gci</") >= 0) + assertTrue(result.indexOf("<sdncadapter:CallbackUrl>scu</") >= 0) + assertTrue(result.indexOf("<request-id>mri</") >= 0) + assertTrue(result.indexOf("<model-invariant-uuid/>") >= 0) + assertTrue(result.indexOf("<model-uuid/>") >= 0) + assertTrue(result.indexOf("<model-customization-uuid/>") >= 0) + assertTrue(result.indexOf("<model-version/>") >= 0) + assertTrue(result.indexOf("<model-name/>") >= 0) + } + + @Test +// @Ignore + public void buildSDNCRequest_Ex() { + ExecutionEntity mex = setupMock() + initBuildSDNCRequest(mex) + + when(mex.getVariable("allottedResourceId")).thenThrow(new RuntimeException("expected exception")) + + DoDeleteAllottedResourceBRG DoDeleteAllottedResourceBRG = new DoDeleteAllottedResourceBRG() + + assertTrue(doBpmnError({ _ -> DoDeleteAllottedResourceBRG.buildSDNCRequest(mex, "myact", "myreq") })) + } + + + // ***** preProcessSDNCUnassign ***** + + @Test +// @Ignore + public void preProcessSDNCUnassign() { + ExecutionEntity mex = setupMock() + def map = setupMap(mex) + initPreProcessSDNC(mex) + + DoDeleteAllottedResourceBRG DoDeleteAllottedResourceBRG = new DoDeleteAllottedResourceBRG() + DoDeleteAllottedResourceBRG.preProcessSDNCUnassign(mex) + + def req = map.get("sdncUnassignRequest") + + assertTrue(req.indexOf("<sdncadapter:SvcAction>unassign</") >= 0) + assertTrue(req.indexOf("<request-action>DeleteBRGInstance</") >= 0) + assertTrue(req.indexOf("<sdncadapter:RequestId>") >= 0) + } + + @Test +// @Ignore + public void preProcessSDNCUnassign_BpmnError() { + ExecutionEntity mex = setupMock() + initPreProcessSDNC(mex) + + when(mex.getVariable("allottedResourceId")).thenThrow(new BpmnError("expected exception")) + + DoDeleteAllottedResourceBRG DoDeleteAllottedResourceBRG = new DoDeleteAllottedResourceBRG() + + assertTrue(doBpmnError({ _ -> DoDeleteAllottedResourceBRG.preProcessSDNCUnassign(mex) })) + } + + @Test +// @Ignore + public void preProcessSDNCUnassign_Ex() { + ExecutionEntity mex = setupMock() + initPreProcessSDNC(mex) + + when(mex.getVariable("allottedResourceId")).thenThrow(new RuntimeException("expected exception")) + + DoDeleteAllottedResourceBRG DoDeleteAllottedResourceBRG = new DoDeleteAllottedResourceBRG() + + assertTrue(doBpmnError({ _ -> DoDeleteAllottedResourceBRG.preProcessSDNCUnassign(mex) })) + } + + + // ***** preProcessSDNCDelete ***** + + @Test +// @Ignore + public void preProcessSDNCDelete() { + ExecutionEntity mex = setupMock() + def map = setupMap(mex) + initPreProcessSDNC(mex) + + DoDeleteAllottedResourceBRG DoDeleteAllottedResourceBRG = new DoDeleteAllottedResourceBRG() + DoDeleteAllottedResourceBRG.preProcessSDNCDelete(mex) + + def req = map.get("sdncDeleteRequest") + + assertTrue(req.indexOf("<sdncadapter:SvcAction>delete</") >= 0) + assertTrue(req.indexOf("<request-action>DeleteBRGInstance</") >= 0) + assertTrue(req.indexOf("<sdncadapter:RequestId>") >= 0) + } + + @Test +// @Ignore + public void preProcessSDNCDelete_BpmnError() { + ExecutionEntity mex = setupMock() + initPreProcessSDNC(mex) + + when(mex.getVariable("allottedResourceId")).thenThrow(new BpmnError("expected exception")) + + DoDeleteAllottedResourceBRG DoDeleteAllottedResourceBRG = new DoDeleteAllottedResourceBRG() + + assertTrue(doBpmnError({ _ -> DoDeleteAllottedResourceBRG.preProcessSDNCDelete(mex) })) + } + + @Test +// @Ignore + public void preProcessSDNCDelete_Ex() { + ExecutionEntity mex = setupMock() + initPreProcessSDNC(mex) + + when(mex.getVariable("allottedResourceId")).thenThrow(new RuntimeException("expected exception")) + + DoDeleteAllottedResourceBRG DoDeleteAllottedResourceBRG = new DoDeleteAllottedResourceBRG() + + assertTrue(doBpmnError({ _ -> DoDeleteAllottedResourceBRG.preProcessSDNCDelete(mex) })) + } + + + // ***** preProcessSDNCDeactivate ***** + + @Test +// @Ignore + public void preProcessSDNCDeactivate() { + ExecutionEntity mex = setupMock() + def map = setupMap(mex) + initPreProcessSDNC(mex) + + DoDeleteAllottedResourceBRG DoDeleteAllottedResourceBRG = new DoDeleteAllottedResourceBRG() + DoDeleteAllottedResourceBRG.preProcessSDNCDeactivate(mex) + + def req = map.get("sdncDeactivateRequest") + + assertTrue(req.indexOf("<sdncadapter:SvcAction>deactivate</") >= 0) + assertTrue(req.indexOf("<request-action>DeleteBRGInstance</") >= 0) + assertTrue(req.indexOf("<sdncadapter:RequestId>") >= 0) + } + + @Test +// @Ignore + public void preProcessSDNCDeactivate_BpmnError() { + ExecutionEntity mex = setupMock() + initPreProcessSDNC(mex) + + when(mex.getVariable("allottedResourceId")).thenThrow(new BpmnError("expected exception")) + + DoDeleteAllottedResourceBRG DoDeleteAllottedResourceBRG = new DoDeleteAllottedResourceBRG() + + assertTrue(doBpmnError({ _ -> DoDeleteAllottedResourceBRG.preProcessSDNCDeactivate(mex) })) + } + + @Test +// @Ignore + public void preProcessSDNCDeactivate_Ex() { + ExecutionEntity mex = setupMock() + initPreProcessSDNC(mex) + + when(mex.getVariable("allottedResourceId")).thenThrow(new RuntimeException("expected exception")) + + DoDeleteAllottedResourceBRG DoDeleteAllottedResourceBRG = new DoDeleteAllottedResourceBRG() + + assertTrue(doBpmnError({ _ -> DoDeleteAllottedResourceBRG.preProcessSDNCDeactivate(mex) })) + } + + + // ***** validateSDNCResp ***** + + @Test +// @Ignore + public void validateSDNCResp() { + ExecutionEntity mex = setupMock() + def data = initValidateSDNCResp(mex) + def resp = initValidateSDNCResp_Resp(200) + + when(mex.getVariable(Prefix+"sdncResponseSuccess")).thenReturn(true) + + DoDeleteAllottedResourceBRG DoDeleteAllottedResourceBRG = new DoDeleteAllottedResourceBRG() + + DoDeleteAllottedResourceBRG.validateSDNCResp(mex, resp, "create") + + verify(mex).getVariable("WorkflowException") + verify(mex).getVariable("SDNCA_SuccessIndicator") + verify(mex).getVariable(Prefix+"sdncResponseSuccess") + + verify(mex, never()).getVariable(Prefix + "sdncRequestDataResponseCode") + verify(mex, never()).setVariable("wasDeleted", false) + } + + @Test +// @Ignore + public void validateSDNCResp_Fail404_Deactivate_FailNotFound() { + ExecutionEntity mex = setupMock() + def data = initValidateSDNCResp(mex) + + def resp = initValidateSDNCResp_Resp(404) + when(mex.getVariable(Prefix+"sdncRequestDataResponseCode")).thenReturn("404") + when(mex.getVariable("failNotFound")).thenReturn("true") + + DoDeleteAllottedResourceBRG DoDeleteAllottedResourceBRG = new DoDeleteAllottedResourceBRG() + + assertTrue(doBpmnError( { _ -> DoDeleteAllottedResourceBRG.validateSDNCResp(mex, resp, "deactivate")})) + } + + @Test +// @Ignore + public void validateSDNCResp_Fail404_Deactivate() { + ExecutionEntity mex = setupMock() + def data = initValidateSDNCResp(mex) + + def resp = initValidateSDNCResp_Resp(404) + when(mex.getVariable(Prefix+"sdncRequestDataResponseCode")).thenReturn("404") + + DoDeleteAllottedResourceBRG DoDeleteAllottedResourceBRG = new DoDeleteAllottedResourceBRG() + + DoDeleteAllottedResourceBRG.validateSDNCResp(mex, resp, "deactivate") + + verify(mex).setVariable("ARNotFoundInSDNC", true) + verify(mex).setVariable("wasDeleted", false) + } + + @Test +// @Ignore + public void validateSDNCResp_Fail404() { + ExecutionEntity mex = setupMock() + def data = initValidateSDNCResp(mex) + + def resp = initValidateSDNCResp_Resp(404) + when(mex.getVariable(Prefix+"sdncRequestDataResponseCode")).thenReturn("404") + + DoDeleteAllottedResourceBRG DoDeleteAllottedResourceBRG = new DoDeleteAllottedResourceBRG() + + assertTrue(doBpmnError( { _ -> DoDeleteAllottedResourceBRG.validateSDNCResp(mex, resp, "create")})) + } + + @Test +// @Ignore + public void validateSDNCResp_Deactivate() { + ExecutionEntity mex = setupMock() + def data = initValidateSDNCResp(mex) + def resp = initValidateSDNCResp_Resp(200) + + DoDeleteAllottedResourceBRG DoDeleteAllottedResourceBRG = new DoDeleteAllottedResourceBRG() + + assertTrue(doBpmnError( { _ -> DoDeleteAllottedResourceBRG.validateSDNCResp(mex, resp, "deactivate")})) + } + + @Test +// @Ignore + public void validateSDNCResp_BpmnError() { + ExecutionEntity mex = setupMock() + initValidateSDNCResp(mex) + def resp = initValidateSDNCResp_Resp(200) + + when(mex.getVariable("WorkflowException")).thenThrow(new BpmnError("expected exception")) + + DoDeleteAllottedResourceBRG DoDeleteAllottedResourceBRG = new DoDeleteAllottedResourceBRG() + + assertTrue(doBpmnError({ _ -> DoDeleteAllottedResourceBRG.validateSDNCResp(mex, resp, "create") })) + } + + @Test +// @Ignore + public void validateSDNCResp_Ex() { + ExecutionEntity mex = setupMock() + initValidateSDNCResp(mex) + def resp = initValidateSDNCResp_Resp(200) + + when(mex.getVariable("WorkflowException")).thenThrow(new RuntimeException("expected exception")) + + DoDeleteAllottedResourceBRG DoDeleteAllottedResourceBRG = new DoDeleteAllottedResourceBRG() + + assertTrue(doBpmnError({ _ -> DoDeleteAllottedResourceBRG.validateSDNCResp(mex, resp, "create") })) + } + + @Test + @Ignore + public void deleteAaiAR() { + ExecutionEntity mex = setupMock() + initDeleteAaiAR(mex) + + MockGetAllottedResource(CUST, SVC, INST, ARID, "VCPE/DoDeleteAllottedResourceBRG/arGetById.xml") + MockDeleteAllottedResource(CUST, SVC, INST, ARID, VERS) + + DoDeleteAllottedResourceBRG DoDeleteAllottedResourceBRG = new DoDeleteAllottedResourceBRG() + DoDeleteAllottedResourceBRG.deleteAaiAR(mex) + } + + @Test +// @Ignore + public void deleteAaiAR_NoArPath() { + ExecutionEntity mex = setupMock() + initDeleteAaiAR(mex) + + MockGetAllottedResource(CUST, SVC, INST, ARID, "VCPE/DoDeleteAllottedResourceBRG/arGetById.xml") + MockDeleteAllottedResource(CUST, SVC, INST, ARID, VERS) + + when(mex.getVariable("aaiARPath")).thenReturn("") + + DoDeleteAllottedResourceBRG DoDeleteAllottedResourceBRG = new DoDeleteAllottedResourceBRG() + + assertTrue(doBpmnError( { _ -> DoDeleteAllottedResourceBRG.deleteAaiAR(mex) })) + } + + @Test +// @Ignore + public void deleteAaiAR_BpmnError() { + ExecutionEntity mex = setupMock() + initDeleteAaiAR(mex) + + MockGetAllottedResource(CUST, SVC, INST, ARID, "VCPE/DoDeleteAllottedResourceBRG/arGetById.xml") + MockDeleteAllottedResource(CUST, SVC, INST, ARID, VERS) + + when(mex.getVariable("aaiARPath")).thenThrow(new BpmnError("expected exception")) + + DoDeleteAllottedResourceBRG DoDeleteAllottedResourceBRG = new DoDeleteAllottedResourceBRG() + + assertTrue(doBpmnError( { _ -> DoDeleteAllottedResourceBRG.deleteAaiAR(mex) })) + } + + @Test +// @Ignore + public void deleteAaiAR_Ex() { + ExecutionEntity mex = setupMock() + initDeleteAaiAR(mex) + + MockGetAllottedResource(CUST, SVC, INST, ARID, "VCPE/DoDeleteAllottedResourceBRG/arGetById.xml") + MockDeleteAllottedResource(CUST, SVC, INST, ARID, VERS) + + when(mex.getVariable("aaiARPath")).thenThrow(new RuntimeException("expected exception")) + + DoDeleteAllottedResourceBRG DoDeleteAllottedResourceBRG = new DoDeleteAllottedResourceBRG() + + assertTrue(doBpmnError( { _ -> DoDeleteAllottedResourceBRG.deleteAaiAR(mex) })) + } + + private boolean checkMissingPreProcessRequest(String fieldnm) { + ExecutionEntity mex = setupMock() + initPreProcess(mex) + + DoDeleteAllottedResourceBRG DoDeleteAllottedResourceBRG = new DoDeleteAllottedResourceBRG() + + when(mex.getVariable(fieldnm)).thenReturn("") + + return doBpmnError( { _ -> DoDeleteAllottedResourceBRG.preProcessRequest(mex) }) + } + + private void initPreProcess(ExecutionEntity mex) { + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("mso.workflow.sdncadapter.callback")).thenReturn("sdncurn") + when(mex.getVariable("serviceInstanceId")).thenReturn("sii") + when(mex.getVariable("allottedResourceId")).thenReturn("ari") + } + + private void initGetAaiAR(ExecutionEntity mex) { + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("allottedResourceType")).thenReturn("BRG") + when(mex.getVariable("allottedResourceRole")).thenReturn("BRG") + when(mex.getVariable("allottedResourceId")).thenReturn(ARID) + when(mex.getVariable("CSI_service")).thenReturn(FileUtil.readResourceFile("__files/VCPE/DoDeleteAllottedResourceBRG/getAR.xml")) + when(mex.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn(UrnPropertiesReader.getVariable("mso.workflow.global.default.aai.namespace")) + when(mex.getVariable("mso.workflow.global.default.aai.version")).thenReturn(UrnPropertiesReader.getVariable("mso.workflow.global.default.aai.version")) + when(mex.getVariable("mso.workflow.default.aai.v8.nodes.query.uri")).thenReturn(UrnPropertiesReader.getVariable("mso.workflow.default.aai.v8.nodes-query.uri")) + when(mex.getVariable("aai.endpoint")).thenReturn(aaiUriPfx) + when(mex.getVariable("aaiARPath")).thenReturn(aaiUriPfx + "/aai/v9/business/customers/customer/"+CUST+"/service-subscriptions/service-subscription/"+SVC+"/service-instances/service-instance/"+INST+"/allotted-resources/allotted-resource/"+ARID) + when(mex.getVariable("aaiAROrchStatus")).thenReturn("Active") + } + + private initUpdateAaiAROrchStatus(ExecutionEntity mex) { + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("aaiARPath")).thenReturn(aaiUriPfx + "/aai/v9/business/customers/customer/"+CUST+"/service-subscriptions/service-subscription/"+SVC+"/service-instances/service-instance/"+INST+"/allotted-resources/allotted-resource/"+ARID) + } + + private initBuildSDNCRequest(ExecutionEntity mex) { + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("allottedResourceId")).thenReturn("ari") + when(mex.getVariable("serviceInstanceId")).thenReturn("sii") + when(mex.getVariable("parentServiceInstanceId")).thenReturn("psii") + when(mex.getVariable("subscriptionServiceType")).thenReturn("sst") + when(mex.getVariable("globalCustomerId")).thenReturn("gci") + when(mex.getVariable("sdncCallbackUrl")).thenReturn("scu") + when(mex.getVariable("msoRequestId")).thenReturn("mri") + } + + private initPreProcessSDNC(ExecutionEntity mex) { + when(mex.getVariable(DBGFLAG)).thenReturn("true") + } + + private initValidateSDNCResp(ExecutionEntity mex) { + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("prefix")).thenReturn(Prefix) + when(mex.getVariable("SDNCA_SuccessIndicator")).thenReturn(true) + } + + private String initValidateSDNCResp_Resp(int code) { + return "<response-data><response-code>${code}</response-code></response-data>" + } + + private initDeleteAaiAR(ExecutionEntity mex) { + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("aaiARPath")).thenReturn(aaiUriPfx + "/aai/v9/business/customers/customer/"+CUST+"/service-subscriptions/service-subscription/"+SVC+"/service-instances/service-instance/"+INST+"/allotted-resources/allotted-resource/"+ARID) + when(mex.getVariable("aaiARResourceVersion")).thenReturn("myvers") + when(mex.getVariable("aai.endpoint")).thenReturn(aaiUriPfx) + } + +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/vcpe/scripts/DoDeleteAllottedResourceTXCTest.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/vcpe/scripts/DoDeleteAllottedResourceTXCTest.groovy new file mode 100644 index 0000000000..6719be17a1 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/vcpe/scripts/DoDeleteAllottedResourceTXCTest.groovy @@ -0,0 +1,607 @@ +/* + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.vcpe.scripts + + +import org.camunda.bpm.engine.ProcessEngineServices +import org.camunda.bpm.engine.RepositoryService +import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity +import org.camunda.bpm.engine.repository.ProcessDefinition +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.junit.Before +import org.junit.BeforeClass +import org.junit.Rule +import org.junit.Test +import org.junit.Ignore +import org.mockito.MockitoAnnotations +import org.camunda.bpm.engine.delegate.BpmnError +import org.onap.so.bpmn.core.UrnPropertiesReader +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.bpmn.mock.FileUtil + +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse +import static com.github.tomakehurst.wiremock.client.WireMock.delete +import static com.github.tomakehurst.wiremock.client.WireMock.get +import static com.github.tomakehurst.wiremock.client.WireMock.patch +import static com.github.tomakehurst.wiremock.client.WireMock.put +import static com.github.tomakehurst.wiremock.client.WireMock.stubFor +import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching +import static org.junit.Assert.*; +import static org.mockito.Mockito.* +import static org.onap.so.bpmn.mock.StubResponseAAI.MockDeleteAllottedResource +import static org.onap.so.bpmn.mock.StubResponseAAI.MockGetAllottedResource +import static org.onap.so.bpmn.mock.StubResponseAAI.MockPatchAllottedResource +import static org.onap.so.bpmn.mock.StubResponseAAI.MockQueryAllottedResourceById + + +import java.util.Map + +import org.onap.so.bpmn.core.RollbackData +import org.onap.so.bpmn.vcpe.scripts.MapSetter + +import com.github.tomakehurst.wiremock.junit.WireMockRule + +class DoDeleteAllottedResourceTXCTest extends GroovyTestBase { + + @Rule + public WireMockRule wireMockRule = new WireMockRule(PORT) + + String Prefix = "DDARTXC_" + + @BeforeClass + public static void setUpBeforeClass() { + super.setUpBeforeClass() + } + + @Before + public void init() + { + MockitoAnnotations.initMocks(this) + } + + public DoDeleteAllottedResourceTXCTest() { + super("DoDeleteAllottedResourceTXC") + } + + + // ***** preProcessRequest ***** + + @Test +// @Ignore + public void preProcessRequest() { + ExecutionEntity mex = setupMock() + initPreProcess(mex) + + DoDeleteAllottedResourceTXC DoDeleteAllottedResourceTXC = new DoDeleteAllottedResourceTXC() + DoDeleteAllottedResourceTXC.preProcessRequest(mex) + + //verify(mex).getVariable(DBGFLAG) + verify(mex).setVariable("prefix", Prefix) + verify(mex).setVariable("sdncCallbackUrl", "sdncurn") + + assertTrue(checkMissingPreProcessRequest("mso.workflow.sdncadapter.callback")) + assertTrue(checkMissingPreProcessRequest("serviceInstanceId")) + assertTrue(checkMissingPreProcessRequest("allottedResourceId")) + } + + @Test +// @Ignore + public void preProcessRequest_BpmnError() { + ExecutionEntity mex = setupMock() + initPreProcess(mex) + + when(mex.getVariable("serviceInstanceId")).thenThrow(new BpmnError("expected exception")) + + DoDeleteAllottedResourceTXC DoDeleteAllottedResourceTXC = new DoDeleteAllottedResourceTXC() + + assertTrue(doBpmnError( { _ -> DoDeleteAllottedResourceTXC.preProcessRequest(mex) })) + } + + @Test +// @Ignore + public void preProcessRequest_Ex() { + ExecutionEntity mex = setupMock() + initPreProcess(mex) + + when(mex.getVariable("serviceInstanceId")).thenThrow(new RuntimeException("expected exception")) + + DoDeleteAllottedResourceTXC DoDeleteAllottedResourceTXC = new DoDeleteAllottedResourceTXC() + + assertTrue(doBpmnError( { _ -> DoDeleteAllottedResourceTXC.preProcessRequest(mex) })) + } + + + // ***** getAaiAR ***** + + @Test + @Ignore + public void getAaiAR() { + MockQueryAllottedResourceById(ARID, "GenericFlows/getARUrlById.xml") + MockGetAllottedResource(CUST, SVC, INST, ARID, "VCPE/DoDeleteAllottedResourceTXC/arGetById.xml") + + ExecutionEntity mex = setupMock() + initGetAaiAR(mex) + + DoDeleteAllottedResourceTXC DoDeleteAllottedResourceTXC = new DoDeleteAllottedResourceTXC() + DoDeleteAllottedResourceTXC.getAaiAR(mex) + + verify(mex).setVariable("parentServiceInstanceId", INST) + } + + @Test +// @Ignore + public void getAaiAR_EmptyResponse() { + + // note: empty result-link + wireMockRule + .stubFor(get(urlMatching("/aai/.*/search/.*")) + .willReturn(aResponse() + .withStatus(200) + .withHeader("Content-Type", "text/xml") + .withBody("<result-data></result-data>"))) + + MockGetAllottedResource(CUST, SVC, INST, ARID, "VCPE/DoDeleteAllottedResourceTXC/arGetById.xml") + + ExecutionEntity mex = setupMock() + initGetAaiAR(mex) + + DoDeleteAllottedResourceTXC DoDeleteAllottedResourceTXC = new DoDeleteAllottedResourceTXC() + + assertTrue(doBpmnError( { _ -> DoDeleteAllottedResourceTXC.getAaiAR(mex) })) + } + + + // ***** updateAaiAROrchStatus ***** + + @Test + @Ignore + public void updateAaiAROrchStatus() { + ExecutionEntity mex = setupMock() + initUpdateAaiAROrchStatus(mex) + + MockPatchAllottedResource(CUST, SVC, INST, ARID) + + DoDeleteAllottedResourceTXC DoDeleteAllottedResourceTXC = new DoDeleteAllottedResourceTXC() + DoDeleteAllottedResourceTXC.updateAaiAROrchStatus(mex, "success") + } + + + // ***** buildSDNCRequest ***** + + @Test +// @Ignore + public void buildSDNCRequest() { + ExecutionEntity mex = setupMock() + initBuildSDNCRequest(mex) + + DoDeleteAllottedResourceTXC DoDeleteAllottedResourceTXC = new DoDeleteAllottedResourceTXC() + + String result = DoDeleteAllottedResourceTXC.buildSDNCRequest(mex, "myact", "myreq") + + assertTrue(result.indexOf("<sdncadapter:RequestId>myreq</") >= 0) + assertTrue(result.indexOf("<sdncadapter:SvcAction>myact</") >= 0) + assertTrue(result.indexOf("<allotted-resource-id>ari</") >= 0) + assertTrue(result.indexOf("<sdncadapter:SvcInstanceId>sii</") >= 0) + assertTrue(result.indexOf("<service-instance-id>sii</") >= 0) + assertTrue(result.indexOf("<parent-service-instance-id>psii</") >= 0) + assertTrue(result.indexOf("<subscription-service-type>sst</") >= 0) + assertTrue(result.indexOf("<global-customer-id>gci</") >= 0) + assertTrue(result.indexOf("<sdncadapter:CallbackUrl>scu</") >= 0) + assertTrue(result.indexOf("<request-id>mri</") >= 0) + assertTrue(result.indexOf("<model-invariant-uuid/>") >= 0) + assertTrue(result.indexOf("<model-uuid/>") >= 0) + assertTrue(result.indexOf("<model-customization-uuid/>") >= 0) + assertTrue(result.indexOf("<model-version/>") >= 0) + assertTrue(result.indexOf("<model-name/>") >= 0) + } + + @Test +// @Ignore + public void buildSDNCRequest_Ex() { + ExecutionEntity mex = setupMock() + initBuildSDNCRequest(mex) + + when(mex.getVariable("allottedResourceId")).thenThrow(new RuntimeException("expected exception")) + + DoDeleteAllottedResourceTXC DoDeleteAllottedResourceTXC = new DoDeleteAllottedResourceTXC() + + assertTrue(doBpmnError({ _ -> DoDeleteAllottedResourceTXC.buildSDNCRequest(mex, "myact", "myreq") })) + } + + + // ***** preProcessSDNCUnassign ***** + + @Test +// @Ignore + public void preProcessSDNCUnassign() { + ExecutionEntity mex = setupMock() + def map = setupMap(mex) + initPreProcessSDNC(mex) + + DoDeleteAllottedResourceTXC DoDeleteAllottedResourceTXC = new DoDeleteAllottedResourceTXC() + DoDeleteAllottedResourceTXC.preProcessSDNCUnassign(mex) + + def req = map.get("sdncUnassignRequest") + + assertTrue(req.indexOf("<sdncadapter:SvcAction>unassign</") >= 0) + assertTrue(req.indexOf("<request-action>DeleteTunnelXConnInstance</") >= 0) + assertTrue(req.indexOf("<sdncadapter:RequestId>") >= 0) + } + + @Test +// @Ignore + public void preProcessSDNCUnassign_BpmnError() { + ExecutionEntity mex = setupMock() + initPreProcessSDNC(mex) + + when(mex.getVariable("allottedResourceId")).thenThrow(new BpmnError("expected exception")) + + DoDeleteAllottedResourceTXC DoDeleteAllottedResourceTXC = new DoDeleteAllottedResourceTXC() + + assertTrue(doBpmnError({ _ -> DoDeleteAllottedResourceTXC.preProcessSDNCUnassign(mex) })) + } + + @Test +// @Ignore + public void preProcessSDNCUnassign_Ex() { + ExecutionEntity mex = setupMock() + initPreProcessSDNC(mex) + + when(mex.getVariable("allottedResourceId")).thenThrow(new RuntimeException("expected exception")) + + DoDeleteAllottedResourceTXC DoDeleteAllottedResourceTXC = new DoDeleteAllottedResourceTXC() + + assertTrue(doBpmnError({ _ -> DoDeleteAllottedResourceTXC.preProcessSDNCUnassign(mex) })) + } + + + // ***** preProcessSDNCDelete ***** + + @Test +// @Ignore + public void preProcessSDNCDelete() { + ExecutionEntity mex = setupMock() + def map = setupMap(mex) + initPreProcessSDNC(mex) + + DoDeleteAllottedResourceTXC DoDeleteAllottedResourceTXC = new DoDeleteAllottedResourceTXC() + DoDeleteAllottedResourceTXC.preProcessSDNCDelete(mex) + + def req = map.get("sdncDeleteRequest") + + assertTrue(req.indexOf("<sdncadapter:SvcAction>delete</") >= 0) + assertTrue(req.indexOf("<request-action>DeleteTunnelXConnInstance</") >= 0) + assertTrue(req.indexOf("<sdncadapter:RequestId>") >= 0) + } + + @Test +// @Ignore + public void preProcessSDNCDelete_BpmnError() { + ExecutionEntity mex = setupMock() + initPreProcessSDNC(mex) + + when(mex.getVariable("allottedResourceId")).thenThrow(new BpmnError("expected exception")) + + DoDeleteAllottedResourceTXC DoDeleteAllottedResourceTXC = new DoDeleteAllottedResourceTXC() + + assertTrue(doBpmnError({ _ -> DoDeleteAllottedResourceTXC.preProcessSDNCDelete(mex) })) + } + + @Test +// @Ignore + public void preProcessSDNCDelete_Ex() { + ExecutionEntity mex = setupMock() + initPreProcessSDNC(mex) + + when(mex.getVariable("allottedResourceId")).thenThrow(new RuntimeException("expected exception")) + + DoDeleteAllottedResourceTXC DoDeleteAllottedResourceTXC = new DoDeleteAllottedResourceTXC() + + assertTrue(doBpmnError({ _ -> DoDeleteAllottedResourceTXC.preProcessSDNCDelete(mex) })) + } + + + // ***** preProcessSDNCDeactivate ***** + + @Test +// @Ignore + public void preProcessSDNCDeactivate() { + ExecutionEntity mex = setupMock() + def map = setupMap(mex) + initPreProcessSDNC(mex) + + DoDeleteAllottedResourceTXC DoDeleteAllottedResourceTXC = new DoDeleteAllottedResourceTXC() + DoDeleteAllottedResourceTXC.preProcessSDNCDeactivate(mex) + + def req = map.get("sdncDeactivateRequest") + + assertTrue(req.indexOf("<sdncadapter:SvcAction>deactivate</") >= 0) + assertTrue(req.indexOf("<request-action>DeleteTunnelXConnInstance</") >= 0) + assertTrue(req.indexOf("<sdncadapter:RequestId>") >= 0) + } + + @Test +// @Ignore + public void preProcessSDNCDeactivate_BpmnError() { + ExecutionEntity mex = setupMock() + initPreProcessSDNC(mex) + + when(mex.getVariable("allottedResourceId")).thenThrow(new BpmnError("expected exception")) + + DoDeleteAllottedResourceTXC DoDeleteAllottedResourceTXC = new DoDeleteAllottedResourceTXC() + + assertTrue(doBpmnError({ _ -> DoDeleteAllottedResourceTXC.preProcessSDNCDeactivate(mex) })) + } + + @Test +// @Ignore + public void preProcessSDNCDeactivate_Ex() { + ExecutionEntity mex = setupMock() + initPreProcessSDNC(mex) + + when(mex.getVariable("allottedResourceId")).thenThrow(new RuntimeException("expected exception")) + + DoDeleteAllottedResourceTXC DoDeleteAllottedResourceTXC = new DoDeleteAllottedResourceTXC() + + assertTrue(doBpmnError({ _ -> DoDeleteAllottedResourceTXC.preProcessSDNCDeactivate(mex) })) + } + + + // ***** validateSDNCResp ***** + + @Test +// @Ignore + public void validateSDNCResp() { + ExecutionEntity mex = setupMock() + def data = initValidateSDNCResp(mex) + def resp = initValidateSDNCResp_Resp(200) + + when(mex.getVariable(Prefix+"sdncResponseSuccess")).thenReturn(true) + + DoDeleteAllottedResourceTXC DoDeleteAllottedResourceTXC = new DoDeleteAllottedResourceTXC() + + DoDeleteAllottedResourceTXC.validateSDNCResp(mex, resp, "create") + + verify(mex).getVariable("WorkflowException") + verify(mex).getVariable("SDNCA_SuccessIndicator") + verify(mex).getVariable(Prefix+"sdncResponseSuccess") + + verify(mex, never()).getVariable(Prefix + "sdncRequestDataResponseCode") + verify(mex, never()).setVariable("wasDeleted", false) + } + + @Test +// @Ignore + public void validateSDNCResp_Fail404_Deactivate_FailNotFound() { + ExecutionEntity mex = setupMock() + def data = initValidateSDNCResp(mex) + + def resp = initValidateSDNCResp_Resp(404) + when(mex.getVariable(Prefix+"sdncRequestDataResponseCode")).thenReturn("404") + when(mex.getVariable("failNotFound")).thenReturn("true") + + DoDeleteAllottedResourceTXC DoDeleteAllottedResourceTXC = new DoDeleteAllottedResourceTXC() + + assertTrue(doBpmnError( { _ -> DoDeleteAllottedResourceTXC.validateSDNCResp(mex, resp, "deactivate")})) + } + + @Test +// @Ignore + public void validateSDNCResp_Fail404_Deactivate() { + ExecutionEntity mex = setupMock() + def data = initValidateSDNCResp(mex) + + def resp = initValidateSDNCResp_Resp(404) + when(mex.getVariable(Prefix+"sdncRequestDataResponseCode")).thenReturn("404") + + DoDeleteAllottedResourceTXC DoDeleteAllottedResourceTXC = new DoDeleteAllottedResourceTXC() + + DoDeleteAllottedResourceTXC.validateSDNCResp(mex, resp, "deactivate") + + verify(mex).setVariable("ARNotFoundInSDNC", true) + verify(mex).setVariable("wasDeleted", false) + } + + @Test +// @Ignore + public void validateSDNCResp_Fail404() { + ExecutionEntity mex = setupMock() + def data = initValidateSDNCResp(mex) + + def resp = initValidateSDNCResp_Resp(404) + when(mex.getVariable(Prefix+"sdncRequestDataResponseCode")).thenReturn("404") + + DoDeleteAllottedResourceTXC DoDeleteAllottedResourceTXC = new DoDeleteAllottedResourceTXC() + + assertTrue(doBpmnError( { _ -> DoDeleteAllottedResourceTXC.validateSDNCResp(mex, resp, "create")})) + } + + @Test +// @Ignore + public void validateSDNCResp_Deactivate() { + ExecutionEntity mex = setupMock() + def data = initValidateSDNCResp(mex) + def resp = initValidateSDNCResp_Resp(200) + + DoDeleteAllottedResourceTXC DoDeleteAllottedResourceTXC = new DoDeleteAllottedResourceTXC() + + assertTrue(doBpmnError( { _ -> DoDeleteAllottedResourceTXC.validateSDNCResp(mex, resp, "deactivate")})) + } + + @Test +// @Ignore + public void validateSDNCResp_BpmnError() { + ExecutionEntity mex = setupMock() + initValidateSDNCResp(mex) + def resp = initValidateSDNCResp_Resp(200) + + when(mex.getVariable("WorkflowException")).thenThrow(new BpmnError("expected exception")) + + DoDeleteAllottedResourceTXC DoDeleteAllottedResourceTXC = new DoDeleteAllottedResourceTXC() + + assertTrue(doBpmnError({ _ -> DoDeleteAllottedResourceTXC.validateSDNCResp(mex, resp, "create") })) + } + + @Test +// @Ignore + public void validateSDNCResp_Ex() { + ExecutionEntity mex = setupMock() + initValidateSDNCResp(mex) + def resp = initValidateSDNCResp_Resp(200) + + when(mex.getVariable("WorkflowException")).thenThrow(new RuntimeException("expected exception")) + + DoDeleteAllottedResourceTXC DoDeleteAllottedResourceTXC = new DoDeleteAllottedResourceTXC() + + assertTrue(doBpmnError({ _ -> DoDeleteAllottedResourceTXC.validateSDNCResp(mex, resp, "create") })) + } + + @Test + @Ignore + public void deleteAaiAR() { + ExecutionEntity mex = setupMock() + initDeleteAaiAR(mex) + + MockGetAllottedResource(CUST, SVC, INST, ARID, "VCPE/DoDeleteAllottedResourceTXC/arGetById.xml") + MockDeleteAllottedResource(CUST, SVC, INST, ARID, VERS) + + DoDeleteAllottedResourceTXC DoDeleteAllottedResourceTXC = new DoDeleteAllottedResourceTXC() + DoDeleteAllottedResourceTXC.deleteAaiAR(mex) + } + + @Test +// @Ignore + public void deleteAaiAR_NoArPath() { + ExecutionEntity mex = setupMock() + initDeleteAaiAR(mex) + + MockGetAllottedResource(CUST, SVC, INST, ARID, "VCPE/DoDeleteAllottedResourceTXC/arGetById.xml") + MockDeleteAllottedResource(CUST, SVC, INST, ARID, VERS) + + when(mex.getVariable("aaiARPath")).thenReturn("") + + DoDeleteAllottedResourceTXC DoDeleteAllottedResourceTXC = new DoDeleteAllottedResourceTXC() + + assertTrue(doBpmnError( { _ -> DoDeleteAllottedResourceTXC.deleteAaiAR(mex) })) + } + + @Test +// @Ignore + public void deleteAaiAR_BpmnError() { + ExecutionEntity mex = setupMock() + initDeleteAaiAR(mex) + + MockGetAllottedResource(CUST, SVC, INST, ARID, "VCPE/DoDeleteAllottedResourceTXC/arGetById.xml") + MockDeleteAllottedResource(CUST, SVC, INST, ARID, VERS) + + when(mex.getVariable("aaiARPath")).thenThrow(new BpmnError("expected exception")) + + DoDeleteAllottedResourceTXC DoDeleteAllottedResourceTXC = new DoDeleteAllottedResourceTXC() + + assertTrue(doBpmnError( { _ -> DoDeleteAllottedResourceTXC.deleteAaiAR(mex) })) + } + + @Test +// @Ignore + public void deleteAaiAR_Ex() { + ExecutionEntity mex = setupMock() + initDeleteAaiAR(mex) + + MockGetAllottedResource(CUST, SVC, INST, ARID, "VCPE/DoDeleteAllottedResourceTXC/arGetById.xml") + MockDeleteAllottedResource(CUST, SVC, INST, ARID, VERS) + + when(mex.getVariable("aaiARPath")).thenThrow(new RuntimeException("expected exception")) + + DoDeleteAllottedResourceTXC DoDeleteAllottedResourceTXC = new DoDeleteAllottedResourceTXC() + + assertTrue(doBpmnError( { _ -> DoDeleteAllottedResourceTXC.deleteAaiAR(mex) })) + } + + private boolean checkMissingPreProcessRequest(String fieldnm) { + ExecutionEntity mex = setupMock() + initPreProcess(mex) + + DoDeleteAllottedResourceTXC DoDeleteAllottedResourceTXC = new DoDeleteAllottedResourceTXC() + + when(mex.getVariable(fieldnm)).thenReturn("") + + return doBpmnError( { _ -> DoDeleteAllottedResourceTXC.preProcessRequest(mex) }) + } + + private void initPreProcess(ExecutionEntity mex) { + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("mso.workflow.sdncadapter.callback")).thenReturn("sdncurn") + when(mex.getVariable("serviceInstanceId")).thenReturn("sii") + when(mex.getVariable("allottedResourceId")).thenReturn("ari") + } + + private void initGetAaiAR(ExecutionEntity mex) { + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("allottedResourceType")).thenReturn("TXC") + when(mex.getVariable("allottedResourceRole")).thenReturn("TXC") + when(mex.getVariable("allottedResourceId")).thenReturn(ARID) + when(mex.getVariable("CSI_service")).thenReturn(FileUtil.readResourceFile("__files/VCPE/DoDeleteAllottedResourceTXC/getAR.xml")) + when(mex.getVariable("mso.workflow.global.default.aai.namespace")).thenReturn(UrnPropertiesReader.getVariable("mso.workflow.global.default.aai.namespace")) + when(mex.getVariable("mso.workflow.global.default.aai.version")).thenReturn(UrnPropertiesReader.getVariable("mso.workflow.global.default.aai.version")) + when(mex.getVariable("mso.workflow.default.aai.v8.nodes.query.uri")).thenReturn(UrnPropertiesReader.getVariable("mso.workflow.default.aai.v8.nodes-query.uri")) + when(mex.getVariable("aai.endpoint")).thenReturn(aaiUriPfx) + when(mex.getVariable("aaiARPath")).thenReturn(aaiUriPfx + "/aai/v9/business/customers/customer/"+CUST+"/service-subscriptions/service-subscription/"+SVC+"/service-instances/service-instance/"+INST+"/allotted-resources/allotted-resource/"+ARID) + when(mex.getVariable("aaiAROrchStatus")).thenReturn("Active") + } + + private initUpdateAaiAROrchStatus(ExecutionEntity mex) { + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("aaiARPath")).thenReturn(aaiUriPfx + "/aai/v9/business/customers/customer/"+CUST+"/service-subscriptions/service-subscription/"+SVC+"/service-instances/service-instance/"+INST+"/allotted-resources/allotted-resource/"+ARID) + } + + private initBuildSDNCRequest(ExecutionEntity mex) { + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("allottedResourceId")).thenReturn("ari") + when(mex.getVariable("serviceInstanceId")).thenReturn("sii") + when(mex.getVariable("parentServiceInstanceId")).thenReturn("psii") + when(mex.getVariable("subscriptionServiceType")).thenReturn("sst") + when(mex.getVariable("globalCustomerId")).thenReturn("gci") + when(mex.getVariable("sdncCallbackUrl")).thenReturn("scu") + when(mex.getVariable("msoRequestId")).thenReturn("mri") + } + + private initPreProcessSDNC(ExecutionEntity mex) { + when(mex.getVariable(DBGFLAG)).thenReturn("true") + } + + private initValidateSDNCResp(ExecutionEntity mex) { + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("prefix")).thenReturn(Prefix) + when(mex.getVariable("SDNCA_SuccessIndicator")).thenReturn(true) + } + + private String initValidateSDNCResp_Resp(int code) { + return "<response-data><response-code>${code}</response-code></response-data>" + } + + private initDeleteAaiAR(ExecutionEntity mex) { + when(mex.getVariable(DBGFLAG)).thenReturn("true") + when(mex.getVariable("aaiARPath")).thenReturn(aaiUriPfx + "/aai/v9/business/customers/customer/"+CUST+"/service-subscriptions/service-subscription/"+SVC+"/service-instances/service-instance/"+INST+"/allotted-resources/allotted-resource/"+ARID) + when(mex.getVariable("aaiARResourceVersion")).thenReturn("myvers") + when(mex.getVariable("aai.endpoint")).thenReturn(aaiUriPfx) + } + +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/vcpe/scripts/GroovyTestBase.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/vcpe/scripts/GroovyTestBase.groovy new file mode 100644 index 0000000000..764e6244d4 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/vcpe/scripts/GroovyTestBase.groovy @@ -0,0 +1,124 @@ +/* + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.vcpe.scripts + + +import org.camunda.bpm.engine.ProcessEngineServices +import org.camunda.bpm.engine.RepositoryService +import org.camunda.bpm.engine.impl.persistence.entity.ExecutionEntity +import org.camunda.bpm.engine.repository.ProcessDefinition +import org.camunda.bpm.engine.delegate.DelegateExecution +import org.junit.Before +import org.junit.BeforeClass +import org.junit.Rule +import org.junit.Test +import org.junit.Ignore +import org.mockito.MockitoAnnotations +import org.camunda.bpm.engine.delegate.BpmnError +import org.onap.so.bpmn.core.UrnPropertiesReader +import org.onap.so.bpmn.core.WorkflowException +import org.onap.so.bpmn.mock.FileUtil +import org.springframework.beans.factory.config.YamlPropertiesFactoryBean +import org.springframework.core.io.ClassPathResource +import org.springframework.core.io.Resource + +import static com.github.tomakehurst.wiremock.client.WireMock.aResponse +import static com.github.tomakehurst.wiremock.client.WireMock.get +import static com.github.tomakehurst.wiremock.client.WireMock.patch +import static com.github.tomakehurst.wiremock.client.WireMock.put +import static com.github.tomakehurst.wiremock.client.WireMock.stubFor +import static com.github.tomakehurst.wiremock.client.WireMock.urlMatching +import static org.junit.Assert.*; +import static org.mockito.Mockito.* +import static org.onap.so.bpmn.mock.StubResponseAAI.MockGetAllottedResource +import org.onap.so.bpmn.core.RollbackData +import org.onap.so.bpmn.vcpe.scripts.MapSetter + +import com.github.tomakehurst.wiremock.junit.WireMockRule + +class GroovyTestBase { + + static final int PORT = 28090 + static final String LOCAL_URI = "http://localhost:" + PORT + + static final String CUST = "SDN-ETHERNET-INTERNET" + static final String SVC = "123456789" + static final String INST = "MIS%252F1604%252F0026%252FSW_INTERNET" + static final String ARID = "arId-1" + static final String VERS = "myvers" + + static final String DBGFLAG = "isDebugLogEnabled" + + static String aaiUriPfx + + String processName + + public static void setUpBeforeClass() { + aaiUriPfx = UrnPropertiesReader.getVariable("aai.endpoint") + } + + public GroovyTestBase(String processName) { + this.processName = processName + } + + public boolean doBpmnError(def func) { + + try { + func() + return false; + + } catch(BpmnError e) { + return true; + } + } + + public ExecutionEntity setupMock() { + + ProcessDefinition mockProcessDefinition = mock(ProcessDefinition.class) + when(mockProcessDefinition.getKey()).thenReturn(processName) + RepositoryService mockRepositoryService = mock(RepositoryService.class) + when(mockRepositoryService.getProcessDefinition()).thenReturn(mockProcessDefinition) + when(mockRepositoryService.getProcessDefinition().getKey()).thenReturn(processName) + when(mockRepositoryService.getProcessDefinition().getId()).thenReturn("100") + ProcessEngineServices mockProcessEngineServices = mock(ProcessEngineServices.class) + when(mockProcessEngineServices.getRepositoryService()).thenReturn(mockRepositoryService) + + ExecutionEntity mex = mock(ExecutionEntity.class) + + when(mex.getId()).thenReturn("100") + when(mex.getProcessDefinitionId()).thenReturn(processName) + when(mex.getProcessInstanceId()).thenReturn(processName) + when(mex.getProcessEngineServices()).thenReturn(mockProcessEngineServices) + when(mex.getProcessEngineServices().getRepositoryService().getProcessDefinition(mex.getProcessDefinitionId())).thenReturn(mockProcessDefinition) + + when(mex.getVariable("isAsyncProcess")).thenReturn("true") + when(mex.getVariable(processName+"WorkflowResponseSent")).thenReturn("false") + + return mex + } + + public Map<String,Object> setupMap(ExecutionEntity mex) { + MapSetter mapset = new MapSetter(); + doAnswer(mapset).when(mex).setVariable(any(), any()) + return mapset.getMap(); + } + +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/vcpe/scripts/MapGetter.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/vcpe/scripts/MapGetter.groovy new file mode 100644 index 0000000000..fa5dcec4bc --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/vcpe/scripts/MapGetter.groovy @@ -0,0 +1,49 @@ +/* + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.vcpe.scripts; + +import java.util.HashMap; +import java.util.Map; + +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; + +class MapGetter implements Answer<Object> { + final Map<String,Object> map; + + public MapGetter() { + map = new HashMap<>(); + } + + public MapGetter(Map<String,Object> map) { + this.map = map; + } + + public Map<String, Object> getMap() { + return map; + } + + @Override + public Object answer(InvocationOnMock invocation) throws Throwable { + return map.get(invocation.getArgumentAt(0, String.class)); + } + +} diff --git a/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/vcpe/scripts/MapSetter.groovy b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/vcpe/scripts/MapSetter.groovy new file mode 100644 index 0000000000..7b50c616ea --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/test/groovy/org/onap/so/bpmn/vcpe/scripts/MapSetter.groovy @@ -0,0 +1,50 @@ +/* + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.vcpe.scripts; + +import java.util.HashMap; +import java.util.Map; + +import org.mockito.invocation.InvocationOnMock; +import org.mockito.stubbing.Answer; + +class MapSetter implements Answer<Void> { + final Map<String,Object> map; + + public MapSetter() { + map = new HashMap<>(); + } + + public MapSetter(Map<String,Object> map) { + this.map = map; + } + + public Map<String, Object> getMap() { + return map; + } + + @Override + public Void answer(InvocationOnMock invocation) throws Throwable { + map.put(invocation.getArgumentAt(0, String.class), invocation.getArgumentAt(1, Object.class)); + return null; + } + +} |