diff options
author | Benjamin, Max (mb388a) <mb388a@us.att.com> | 2018-07-30 15:56:09 -0400 |
---|---|---|
committer | Benjamin, Max (mb388a) <mb388a@us.att.com> | 2018-07-31 11:09:25 -0400 |
commit | 5a6a6de6f1a26a1897e4917a0df613e25a24eb70 (patch) | |
tree | 59a968f27b4b603aacc9d5e7b51fb598aeec5321 /bpmn/so-bpmn-infrastructure-flows/src/main/groovy | |
parent | b6dc38501f3b746426b42d9de4cc883d894149e8 (diff) |
Containerization feature of SO
Change-Id: I95381232eeefcd247a66a5cec370a8ce1c288e18
Issue-ID: SO-670
Signed-off-by: Benjamin, Max (mb388a) <mb388a@us.att.com>
Diffstat (limited to 'bpmn/so-bpmn-infrastructure-flows/src/main/groovy')
81 files changed, 39064 insertions, 0 deletions
diff --git a/bpmn/so-bpmn-infrastructure-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CompareModelofE2EServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-flows/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-flows/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-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateCustomE2EServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-flows/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-flows/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-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateGenericALaCarteServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-flows/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-flows/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-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateNetworkInstance.groovy b/bpmn/so-bpmn-infrastructure-flows/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-flows/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-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateSDNCNetworkResource.groovy b/bpmn/so-bpmn-infrastructure-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateSDNCNetworkResource.groovy new file mode 100644 index 0000000000..1c0975f8c4 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateSDNCNetworkResource.groovy @@ -0,0 +1,327 @@ +/*- + * ============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 netowrkInputParametersJson) { + List<Map<String, Object>> paramList = new ArrayList(); + JSONObject jsonObject = new JSONObject(netowrkInputParametersJson); + 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 netowrkInputParametersJson = jsonUtil.getJsonValue(resourceInputPrameters, "requestInputs") + //here convert json string to xml string + String netowrkInputParameters = XML.toString(new JSONObject(customizeResourceParam(netowrkInputParametersJson))) + // 1. prepare assign topology via SDNC Adapter SUBFLOW call + String sndcTopologyCreateRequest = + """<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(sndcTopologyCreateRequest) + 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-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateVFCNSResource.groovy b/bpmn/so-bpmn-infrastructure-flows/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-flows/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-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateVfModuleInfra.groovy b/bpmn/so-bpmn-infrastructure-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateVfModuleInfra.groovy new file mode 100644 index 0000000000..308c93540f --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateVfModuleInfra.groovy @@ -0,0 +1,620 @@ +/*- + * ============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 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-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateVfModuleVolumeInfraV1.groovy b/bpmn/so-bpmn-infrastructure-flows/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-flows/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-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/CreateVnfInfra.groovy b/bpmn/so-bpmn-infrastructure-flows/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-flows/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-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteCustomE2EServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-flows/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-flows/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-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteGenericALaCarteServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-flows/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-flows/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-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteNetworkInstance.groovy b/bpmn/so-bpmn-infrastructure-flows/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-flows/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-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteSDNCNetworkResource.groovy b/bpmn/so-bpmn-infrastructure-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteSDNCNetworkResource.groovy new file mode 100644 index 0000000000..ab5500602f --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteSDNCNetworkResource.groovy @@ -0,0 +1,308 @@ +/*- + * ============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.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 { + + String Prefix="DELSDNCRES_" + + ExceptionUtil exceptionUtil = new ExceptionUtil() + + JsonUtils jsonUtil = new JsonUtils() + + SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils() + + public void preProcessRequest(DelegateExecution execution){ + def isDebugEnabled = execution.getVariable("isDebugLogEnabled") + utils.log("INFO"," ***** Started preProcessRequest *****", 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) + 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() + utils.log("DEBUG", msg, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + } + + /** + * Pre Process the BPMN Flow Request + * Inclouds: + * generate the nsOperationKey + * generate the nsParameters + */ + public void prepareSDNCRequest (DelegateExecution execution) { + def isDebugEnabled = execution.getVariable("isDebugLogEnabled") + utils.log("INFO"," ***** Started prepareSDNCRequest *****", isDebugEnabled) + + 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 = + """<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(sndcTopologyDeleteRequest) + utils.logAudit(sndcTopologyDeleteRequesAsString) + execution.setVariable("sdncAdapterWorkflowRequest", sndcTopologyDeleteRequesAsString) + utils.log("INFO","sdncAdapterWorkflowRequest - " + "\n" + sndcTopologyDeleteRequesAsString, isDebugEnabled) + + } catch (Exception ex) { + String exceptionMessage = " Bpmn error encountered in DeleteSDNCCNetworkResource flow. prepareSDNCRequest() - " + ex.getMessage() + utils.log("DEBUG", exceptionMessage, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + + } + utils.log("INFO"," ***** Exit prepareSDNCRequest *****", 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 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){ + def isDebugEnabled = execution.getVariable("isDebugLogEnabled") + utils.log("INFO"," ***** Started prepareSDNCRequest *****", isDebugEnabled) + String responseCode = execution.getVariable(Prefix + "sdncDeleteReturnCode") + String responseObj = execution.getVariable(Prefix + "SuccessIndicator") + + utils.log("INFO","response from sdnc, response code :" + responseCode + " response object :" + responseObj, isDebugEnabled) + utils.log("INFO"," ***** Exit prepareSDNCRequest *****", 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-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteVFCNSResource.groovy b/bpmn/so-bpmn-infrastructure-flows/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-flows/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-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteVfModuleInfra.groovy b/bpmn/so-bpmn-infrastructure-flows/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-flows/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-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteVfModuleVolumeInfraV1.groovy b/bpmn/so-bpmn-infrastructure-flows/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-flows/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-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DeleteVnfInfra.groovy b/bpmn/so-bpmn-infrastructure-flows/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-flows/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-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCompareModelVersions.groovy b/bpmn/so-bpmn-infrastructure-flows/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-flows/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-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCompareModelofE2EServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCompareModelofE2EServiceInstance.groovy new file mode 100644 index 0000000000..eceba5abe3 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCompareModelofE2EServiceInstance.groovy @@ -0,0 +1,260 @@ +/*- + * ============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.CompareModelsResult +import org.onap.so.bpmn.core.domain.ResourceModelInfo +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.resource.ResourceRequestBuilder +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.Map +import java.util.UUID; +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.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.w3c.dom.Document +import org.w3c.dom.Element +import org.w3c.dom.Node +import org.w3c.dom.NodeList +import org.xml.sax.InputSource +/** + * 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) + } + + 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, Id:" + serviceInstanceId + utils.log("INFO", msg, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + else + { + utils.log("INFO", "SI Data" + siData, isDebugEnabled) + + // 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 = utils.getNodeText(siData, "model-invariant-id") + def modelVersionId = utils.getNodeText(siData, "model-version-id") + + // Set Original Template info + execution.setVariable("model-invariant-id-original", modelInvariantId) + execution.setVariable("model-version-id-original", modelVersionId) + } + } + }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) + } + msoLogger.trace("Exit postProcessAAIGET ") + } + + 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-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateE2EServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateE2EServiceInstance.groovy new file mode 100644 index 0000000000..bb48671e73 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateE2EServiceInstance.groovy @@ -0,0 +1,451 @@ +/*- + * ============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.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.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 ") + } + + 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 ") + } + + 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-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateE2EServiceInstanceRollback.groovy b/bpmn/so-bpmn-infrastructure-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateE2EServiceInstanceRollback.groovy new file mode 100644 index 0000000000..05a0ea86d3 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-flows/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.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-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateNetworkInstance.groovy b/bpmn/so-bpmn-infrastructure-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateNetworkInstance.groovy new file mode 100644 index 0000000000..4bbaef8ecb --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateNetworkInstance.groovy @@ -0,0 +1,1680 @@ +/*- + * ============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 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) + + } + + } + + 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-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateNetworkInstanceRollback.groovy b/bpmn/so-bpmn-infrastructure-flows/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-flows/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-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateResources.groovy b/bpmn/so-bpmn-infrastructure-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateResources.groovy new file mode 100644 index 0000000000..f7c5c1b83d --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateResources.groovy @@ -0,0 +1,279 @@ +/*- + * ============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()); + + 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) + 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-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateServiceInstance.groovy new file mode 100644 index 0000000000..93a260a544 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateServiceInstance.groovy @@ -0,0 +1,795 @@ +/*- + * ============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") + } + + //TODO: Will be able to replace with call to GenericGetService + 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 postProcessAAIGET(DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + msoLogger.trace("postProcessAAIGET") + String msg = "" + + try { + String serviceInstanceName = execution.getVariable("serviceInstanceName") + boolean succInAAI = execution.getVariable("GENGS_SuccessIndicator") + if(!succInAAI){ + msoLogger.debug("Error getting Service-instance from AAI", + serviceInstanceName) + WorkflowException workflowException = execution.getVariable("WorkflowException") + if(workflowException != null){ + exceptionUtil.buildAndThrowWorkflowException(execution, workflowException.getErrorCode(), workflowException.getErrorMessage()) + } + else + { + msg = "Failure in postProcessAAIGET GENGS_SuccessIndicator:" + succInAAI + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg) + } + } + else + { + boolean foundInAAI = execution.getVariable("GENGS_FoundIndicator") + if(foundInAAI){ + msoLogger.debug("Found Service-instance in AAI") + msg = "ServiceInstance already exists in AAI:" + serviceInstanceName + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg) + } + } + } catch (BpmnError e) { + throw e; + } catch (Exception ex) { + msg = "Exception in DoCreateServiceInstance.postProcessAAIGET. " + ex.getMessage() + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.trace("Exit postProcessAAIGET") + } + + 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-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateServiceInstanceRollback.groovy b/bpmn/so-bpmn-infrastructure-flows/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-flows/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-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateServiceInstanceRollbackV2.groovy b/bpmn/so-bpmn-infrastructure-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateServiceInstanceRollbackV2.groovy new file mode 100644 index 0000000000..6e1a5dcb55 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateServiceInstanceRollbackV2.groovy @@ -0,0 +1,72 @@ +/*- + * ============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.camunda.bpm.engine.runtime.Execution +import org.onap.so.bpmn.common.scripts.AbstractServiceTaskProcessor +import org.onap.so.bpmn.core.domain.ServiceDecomposition +import org.onap.so.client.orchestration.AAIServiceInstanceResources +import org.onap.so.logger.MsoLogger + + +public class DoCreateServiceInstanceRollbackV2 extends AbstractServiceTaskProcessor{ + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoCreateServiceInstanceRollbackV2.class); + + @Override + public void preProcessRequest(DelegateExecution execution) { + + } + + public void aaiServiceInstanceRollback (DelegateExecution execution) { + def aaiServiceInstanceRollback = execution.getVariable("aaiServiceInstanceRollback") + if(aaiServiceInstanceRollback){ + msoLogger.trace("Started aaiServiceInstanceRollback") + try{ + ServiceDecomposition serviceDecomp = execution.getVariable("ServiceDecomposition") + AAIServiceInstanceResources aaiO = new AAIServiceInstanceResources() + aaiO.deleteServiceInstance(serviceDecomp) + }catch (Exception ex) { + String msg = "Error Response from AAI for aaiServiceInstanceRollback" + execution.setVariable("rollbackError", msg) + msoLogger.debug(msg) + throw new BpmnError("MSOWorkflowException") + } + msoLogger.trace("Completed aaiServiceInstanceRollback") + }else{ + msoLogger.trace("SKIPPING A&AI ROLLBACK") + } + } + + public void rollbackError (DelegateExecution execution) { + msoLogger.trace("rollbackError") + try{ + msoLogger.debug("Caught an Exception in DoCreateServiceInstanceRollbackV2") + }catch(BpmnError b){ + msoLogger.debug("BPMN Error during rollbackError: " + b.getMessage()) + }catch(Exception e){ + msoLogger.debug("Caught Exception during rollbackError: " + e.getMessage()) + } + msoLogger.debug(" Exit processRollbackException") + } + +} diff --git a/bpmn/so-bpmn-infrastructure-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateServiceInstanceV2.groovy b/bpmn/so-bpmn-infrastructure-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateServiceInstanceV2.groovy new file mode 100644 index 0000000000..8af8e6ba1b --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateServiceInstanceV2.groovy @@ -0,0 +1,104 @@ +/*- + * ============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.core.domain.ServiceDecomposition +import org.onap.so.client.orchestration.AAIServiceInstanceResources +import org.onap.so.client.orchestration.SDNCServiceInstanceResources +import org.onap.so.logger.MsoLogger +import org.onap.so.logger.MessageEnum + +import groovy.json.* + +/** + * This groovy class supports the <class>DoCreateServiceInstanceV2.bpmn</class> process. + * +*/ + +public class DoCreateServiceInstanceV2 extends AbstractServiceTaskProcessor { + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoCreateServiceInstanceV2.class); + AAIServiceInstanceResources aaiO = new AAIServiceInstanceResources() + SDNCServiceInstanceResources sdncO = new SDNCServiceInstanceResources() + + @Override + public void preProcessRequest(DelegateExecution execution) { + } + + public void createServiceInstance(DelegateExecution execution) { + execution.setVariable("callSDNC",true) + if(execution.getVariable("serviceType").equalsIgnoreCase("PORT-MIRROR")== false){ + if(execution.getVariable("sdncVersion").equals("1610")){ + execution.setVariable("callSDNC",false); + } + } + ServiceDecomposition serviceDecomp = (ServiceDecomposition) execution.getVariable("serviceDecomposition") + try{ + aaiO.createServiceInstance(serviceDecomp) + } catch (BpmnError e) { + throw e + } + } + + public void createProject(DelegateExecution execution) { + ServiceDecomposition serviceDecomp = (ServiceDecomposition) execution.getVariable("serviceDecomposition") + if (serviceDecomp.getServiceInstance() != null && serviceDecomp.getProject() != null) { + try{ + aaiO.createProjectandConnectServiceInstance(serviceDecomp) + } catch (BpmnError e) { + throw e + } + } + } + + public void createOwningEntity(DelegateExecution execution) { + ServiceDecomposition serviceDecomp = (ServiceDecomposition) execution.getVariable("serviceDecomposition") + if (serviceDecomp.getServiceInstance() != null && serviceDecomp.getOwningEntity() != null) { + try{ + aaiO.createOwningEntityandConnectServiceInstance(serviceDecomp) + } catch (BpmnError e) { + throw e + } + } + } + + public void sdncAssignRequest(DelegateExecution execution) { + ServiceDecomposition serviceDecomp = (ServiceDecomposition) execution.getVariable("serviceDecomposition") + if (serviceDecomp != null) { + try { + sdncO.sendSyncResponse(serviceDecomp) + } catch (BpmnError e) { + throw e + } + } + + } + + public void rollback(DelegateExecution execution) { + //TODO + } + +} diff --git a/bpmn/so-bpmn-infrastructure-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVFCNetworkServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-flows/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-flows/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-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModule.groovy b/bpmn/so-bpmn-infrastructure-flows/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-flows/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-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModuleRollback.groovy b/bpmn/so-bpmn-infrastructure-flows/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-flows/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-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModuleVolumeRollback.groovy b/bpmn/so-bpmn-infrastructure-flows/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-flows/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-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModuleVolumeV2.groovy b/bpmn/so-bpmn-infrastructure-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModuleVolumeV2.groovy new file mode 100644 index 0000000000..f734ffb3ff --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModuleVolumeV2.groovy @@ -0,0 +1,616 @@ +/*- + * ============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 + +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) + } + + + /** + * validate getServiceInstance response + * @param execution + * @param isDebugEnabled + */ + public void validateGetServiceInstanceCall(DelegateExecution execution, isDebugEnabled) { + def found = execution.getVariable('GENGS_FoundIndicator') + def success = execution.getVariable('GENGS_SuccessIndicator') + def serviceInstanceId = execution.getVariable('serviceInstanceId') + msoLogger.debug("getServiceInstance success: " + success) + msoLogger.debug("getServiceInstance found: " + found) + if(!found || !success) { + String errorMessage = "Service instance id not found in AAI: ${serviceInstanceId}." + msoLogger.debug(errorMessage) + (new ExceptionUtil()).buildAndThrowWorkflowException(execution, 2500, errorMessage) + } + + } + + /** + * 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-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVnf.groovy b/bpmn/so-bpmn-infrastructure-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVnf.groovy new file mode 100644 index 0000000000..46a502e124 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVnf.groovy @@ -0,0 +1,618 @@ +/*- + * ============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 + + +/** + * 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") + } + + 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-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVnfAndModules.groovy b/bpmn/so-bpmn-infrastructure-flows/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-flows/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-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVnfAndModulesRollback.groovy b/bpmn/so-bpmn-infrastructure-flows/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-flows/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-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCustomDeleteE2EServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-flows/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-flows/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-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCustomDeleteE2EServiceInstanceV2.groovy b/bpmn/so-bpmn-infrastructure-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCustomDeleteE2EServiceInstanceV2.groovy new file mode 100644 index 0000000000..20a7f43de7 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCustomDeleteE2EServiceInstanceV2.groovy @@ -0,0 +1,1132 @@ +/*- + * ============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 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) + } + + + + public void postProcessAAIGET(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.postProcessAAIGET(' +'execution=' + execution.getId() +')' + msoLogger.info("Entered " + method) + + String msg = "" + + try { + String serviceInstanceId = execution.getVariable("serviceInstanceId") + msoLogger.info("serviceInstanceId: "+serviceInstanceId) + + boolean foundInAAI = execution.getVariable("GENGS_FoundIndicator") + msoLogger.info("foundInAAI: "+foundInAAI) + + 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{ + 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 = "Bpmn error encountered in " + method + "--" + ex.getMessage() + msoLogger.info(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.info("Exited " + method) + } + + 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") + + // confirm if ServiceInstance was found + if ( !execution.getVariable("GENGS_FoundIndicator") ) + { + String exceptionMessage = "Bpmn error encountered in DeleteMobileAPNCustService flow. Service Instance was not found in AAI by id: " + serviceInstanceId + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + } + + execution.setVariable(Prefix+"resourceList", "") + execution.setVariable(Prefix+"resourceCount", 0) + execution.setVariable(Prefix+"nextResource", 0) + execution.setVariable(Prefix+"resourceFinish", true) + + // get SI extracted by GenericGetService + String serviceInstanceAaiRecord = execution.getVariable("GENGS_service"); + msoLogger.info("serviceInstanceAaiRecord: " +serviceInstanceAaiRecord) + + String aaiJsonRecord = jsonUtil.xml2json(serviceInstanceAaiRecord) + + 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-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteE2EServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteE2EServiceInstance.groovy new file mode 100644 index 0000000000..54dfae3760 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteE2EServiceInstance.groovy @@ -0,0 +1,439 @@ +/*- + * ============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) + //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) + } + } + } + } + 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) + } + + 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-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteNetworkInstance.groovy b/bpmn/so-bpmn-infrastructure-flows/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-flows/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-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteNetworkInstanceRollback.groovy b/bpmn/so-bpmn-infrastructure-flows/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-flows/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-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteResources.groovy b/bpmn/so-bpmn-infrastructure-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteResources.groovy new file mode 100644 index 0000000000..f6dd0cad16 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteResources.groovy @@ -0,0 +1,317 @@ +/*- + * ============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.json.JSONArray; + +import static org.apache.commons.lang3.StringUtils.*; +import groovy.xml.XmlUtil +import groovy.json.* + +import org.onap.so.bpmn.core.domain.ModelInfo +import org.onap.so.bpmn.core.domain.Resource +import org.onap.so.bpmn.core.domain.ServiceInstance +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.SDNCAdapterUtils +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 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.camunda.bpm.engine.runtime.Execution +import org.json.JSONObject; +import org.apache.commons.lang3.* +import org.apache.commons.codec.binary.Base64; +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 com.fasterxml.jackson.jaxrs.json.annotation.JSONP.Def; +import org.onap.so.logger.MessageEnum +import org.onap.so.logger.MsoLogger + +/** + * This groovy class supports the <class>DoDeleteResources.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 DoDeleteResources extends AbstractServiceTaskProcessor { + private static final MsoLogger msoLogger = MsoLogger.getMsoLogger(MsoLogger.Catalog.BPEL, DoDeleteResources.class); + + String Prefix="DDELR_" + ExceptionUtil exceptionUtil = new ExceptionUtil() + JsonUtils jsonUtil = new JsonUtils() + + public void preProcessRequest (DelegateExecution execution) { + msoLogger.trace("preProcessRequest ") + String msg = "" + + List<ServiceInstance> realNSRessources = new ArrayList<ServiceInstance>() + + // related ns from AAI + String serviceRelationShip = execution.getVariable("serviceRelationShip") + def jsonSlurper = new JsonSlurper() + def jsonOutput = new JsonOutput() + List<String> nsSequence = new ArrayList<String>() + List relationShipList = jsonSlurper.parseText(serviceRelationShip) + if (relationShipList != null) { + relationShipList.each { + String resourceType = it.resourceType + nsSequence.add(resourceType) + } + } + + execution.setVariable("currentNSIndex", 0) + execution.setVariable("nsSequence", nsSequence) + execution.setVariable("realNSRessources", realNSRessources) + msoLogger.info("nsSequence: " + nsSequence) + + msoLogger.trace("Exit preProcessRequest ") + } + + public void getCurrentNS(execution){ + msoLogger.trace("Start getCurrentNS Process ") + + 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) + + msoLogger.trace("COMPLETED getCurrentNS Process ") + } + + public void postProcessAAIGET(DelegateExecution execution) { + msoLogger.trace("postProcessAAIGET2 ") + String msg = "" + + try { + String nsResourceName = execution.getVariable("GENGS_serviceInstanceName") + boolean succInAAI = execution.getVariable("GENGS_SuccessIndicator") + if(!succInAAI){ + msoLogger.info("Error getting Service-instance from AAI in postProcessAAIGET", + nsResourceName) + 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){ + String aaiService = execution.getVariable("GENGS_service") + if (!isBlank(aaiService)) { + String svcId = utils.getNodeText(aaiService, "service-instance-id") + //String mn = utils.getNodeText(aaiService, "model-name") + String mIuuid = utils.getNodeText(aaiService, "model-invariant-id") + String muuid = utils.getNodeText(aaiService, "model-version-id") + String mCuuid = utils.getNodeText(aaiService, "model-customization-uuid") + ServiceInstance rc = new ServiceInstance() + ModelInfo modelInfo = new ModelInfo() + //modelInfo.setModelName(mn) + modelInfo.setModelUuid(muuid) + modelInfo.setModelInvariantUuid(mIuuid) + modelInfo.getModelCustomizationUuid(mCuuid) + rc.setModelInfo(modelInfo) + rc.setInstanceId(svcId) + rc.setInstanceName(nsResourceName) + + List<ServiceInstance> realNSRessources = execution.getVariable("realNSRessources") + realNSRessources.add(rc) + execution.setVariable("realNSRessources", realNSRessources) + + msoLogger.info("Found Service-instance in AAI.serviceInstanceName:" + execution.getVariable("serviceInstanceName")) + } + } + } + } catch (BpmnError e) { + throw e; + } catch (Exception ex) { + msg = "Exception in DoDeleteResources.postProcessAAIGET " + ex.getMessage() + msoLogger.info(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + msoLogger.trace("Exit postProcessAAIGET ") + } + + public void parseNextNS(execution){ + msoLogger.trace("Start parseNextNS Process ") + def currentIndex = execution.getVariable("currentNSIndex") + def nextIndex = currentIndex + 1 + execution.setVariable("currentNSIndex", nextIndex) + List<String> nsSequence = execution.getVariable("nsSequence") + if(nextIndex >= nsSequence.size()){ + execution.setVariable("allNsFinished", "true") + }else{ + execution.setVariable("allNsFinished", "false") + } + msoLogger.trace("COMPLETED parseNextNS 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>() + + // get delete resource list and order list + List<Resource> delResourceList = execution.getVariable("delResourceList") + // existing resource list + List<ServiceInstance> existResourceList = execution.getVariable("realNSRessources") + + for(ServiceInstance rc_e : existResourceList){ + + String muuid = rc_e.getModelInfo().getModelUuid() + String mIuuid = rc_e.getModelInfo().getModelInvariantUuid() + String mCuuid = rc_e.getModelInfo().getModelCustomizationUuid() + rcType = rc_e.getInstanceName() + + for(Resource rc_d : delResourceList){ + + if(rc_d.getModelInfo().getModelUuid() == muuid + && rc_d.getModelInfo().getModelInvariantUuid() == mIuuid + && rc_d.getModelInfo().getModelCustomizationUuid() == mCuuid) { + + if(StringUtils.containsIgnoreCase(rcType, "overlay") + || StringUtils.containsIgnoreCase(rcType, "underlay")){ + wanResources.add(rcType) + }else{ + nsResources.add(rcType) + } + + } + } + + } + + 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 ") + } + + /** + * prepare delete parameters + */ + public void preResourceDelete(execution, resourceName){ + + msoLogger.trace("STARTED preResourceDelete Process ") + + List<ServiceInstance> existResourceList = execution.getVariable("realNSRessources") + + for(ServiceInstance rc_e : existResourceList){ + + if(StringUtils.containsIgnoreCase(rc_e.getInstanceName(), resourceName)) { + + String resourceInstanceUUID = rc_e.getInstanceId() + String resourceTemplateUUID = rc_e.getModelInfo().getModelUuid() + execution.setVariable("resourceInstanceId", resourceInstanceUUID) + execution.setVariable("resourceTemplateId", resourceTemplateUUID) + execution.setVariable("resourceType", resourceName) + msoLogger.info("Delete Resource Info resourceTemplate Id :" + resourceTemplateUUID + " resourceInstanceId: " + resourceInstanceUUID + " resourceType: " + resourceName) + } + } + + msoLogger.trace("END preResourceDelete 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 ") + } + + /** + * post config request. + */ + public void postConfigRequest(execution){ + //to do + } + +} +
\ No newline at end of file diff --git a/bpmn/so-bpmn-infrastructure-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteResourcesV1.groovy b/bpmn/so-bpmn-infrastructure-flows/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-flows/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-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteServiceInstance.groovy new file mode 100644 index 0000000000..198144ad34 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteServiceInstance.groovy @@ -0,0 +1,472 @@ +/*- + * ============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 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.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.logger.MsoLogger +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 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>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 + " ") + } + + 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 == true){ + msoLogger.debug("Found Service-instance in AAI") + + //Extract GlobalSubscriberId + String siRelatedLink = execution.getVariable("GENGS_siResourceLink") + if (isBlank(siRelatedLink)) + { + msg = "Could not retrive ServiceInstance data from AAI to delete id:" + serviceInstanceId + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + else + { + msoLogger.debug("Found Service-instance in AAI. link: " + siRelatedLink) + String globalSubscriberId = execution.getVariable("globalSubscriberId") + if(isBlank(globalSubscriberId)){ + int custStart = siRelatedLink.indexOf("customer/") + int custEnd = siRelatedLink.indexOf("/service-subscriptions") + globalSubscriberId = siRelatedLink.substring(custStart + 9, custEnd) + execution.setVariable("globalSubscriberId", globalSubscriberId) + } + + //Extract Service Type if not provided on request + String subscriptionServiceType = execution.getVariable("subscriptionServiceType") + if(isBlank(subscriptionServiceType)){ + int serviceStart = siRelatedLink.indexOf("service-subscription/") + int serviceEnd = siRelatedLink.indexOf("/service-instances/") + String serviceTypeEncoded = siRelatedLink.substring(serviceStart + 21, serviceEnd) + subscriptionServiceType = UriUtils.decode(serviceTypeEncoded, "UTF-8") + execution.setVariable("subscriptionServiceType", subscriptionServiceType) + } + + if (isBlank(globalSubscriberId) || isBlank(subscriptionServiceType)) + { + msg = "Could not retrive global-customer-id & subscription-service-type from AAI to delete id:" + serviceInstanceId + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + } + + String siData = execution.getVariable("GENGS_service") + msoLogger.debug("SI Data") + if (isBlank(siData)) + { + msg = "Could not retrive ServiceInstance data from AAI to delete id:" + serviceInstanceId + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + else + { + msoLogger.debug("SI Data" + siData) + serviceType = utils.getNodeText(siData,"service-type") + execution.setVariable("serviceType", serviceType) + execution.setVariable("serviceRole", utils.getNodeText(siData,"service-role")) + String orchestrationStatus = utils.getNodeText(siData,"orchestration-status") + + //Confirm there are no related service instances (vnf/network or volume) + if (utils.nodeExists(siData, "relationship-list")) { + msoLogger.debug("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) + + NodeList nodeList = serviceXml.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("generic-vnf") || e.equals("l3-network") || e.equals("allotted-resource") ){ + msoLogger.debug("ServiceInstance still has relationship(s) to generic-vnfs, l3-networks or allotted-resources") + execution.setVariable("siInUse", true) + //there are relationship dependencies to this Service Instance + msg = " Stopped deleting Service Instance, it has dependencies. Service instance id: " + serviceInstanceId + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg) + }else{ + msoLogger.debug("Relationship NOT related to OpenStack") + } + } + } + } + + if ("TRANSPORT".equalsIgnoreCase(serviceType)) + { + if ("PendingDelete".equals(orchestrationStatus)) + { + execution.setVariable("skipDeactivate", true) + } + else + { + msg = "ServiceInstance of type TRANSPORT must in PendingDelete status to allow Delete. Orchestration-status:" + orchestrationStatus + msoLogger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + + } + + //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) + } + } + + msoLogger.debug("isSdncService: " + isSdncService) + msoLogger.debug("Send To SDNC: " + execution.getVariable("sendToSDNC")) + msoLogger.debug("Service Type: " + execution.getVariable("serviceType")) + + } + }else{ + boolean succInAAI = execution.getVariable("GENGS_SuccessIndicator") + if(succInAAI != true){ + msoLogger.debug("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.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, msg) + } + } + + msoLogger.debug("Service-instance NOT found in AAI. Silent Success") + } + } catch (BpmnError e) { + throw e; + } catch (Exception ex) { + msg = "Exception in DoDeleteServiceInstance.postProcessAAIGET. " + ex.getMessage() + msoLogger.debug(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("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-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVFCNetworkServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-flows/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-flows/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-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVfModule.groovy b/bpmn/so-bpmn-infrastructure-flows/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-flows/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-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVfModuleFromVnf.groovy b/bpmn/so-bpmn-infrastructure-flows/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-flows/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-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVfModuleVolumeV2.groovy b/bpmn/so-bpmn-infrastructure-flows/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-flows/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-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVnf.groovy b/bpmn/so-bpmn-infrastructure-flows/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-flows/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-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVnfAndModules.groovy b/bpmn/so-bpmn-infrastructure-flows/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-flows/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-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoScaleE2EServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-flows/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-flows/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-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoScaleVFCNetworkServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-flows/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-flows/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-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateE2EServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateE2EServiceInstance.groovy new file mode 100644 index 0000000000..5fb6a9df9a --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateE2EServiceInstance.groovy @@ -0,0 +1,451 @@ +/*- + * ============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 preProcessAAIGET(DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + } + + public void postProcessAAIGET(DelegateExecution execution) { + def isDebugEnabled=execution.getVariable("isDebugLogEnabled") + utils.log("INFO"," ***** postProcessAAIGET ***** ", isDebugEnabled) + String msg = "" + + try { + String serviceInstanceName = execution.getVariable("serviceInstanceName") + boolean succInAAI = execution.getVariable("GENGS_SuccessIndicator") + if(!succInAAI){ + utils.log("INFO","Error getting Service-instance from AAI in postProcessAAIGET", + serviceInstanceName, 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) + } + } + else + { + boolean foundInAAI = execution.getVariable("GENGS_FoundIndicator") + if(foundInAAI){ + String aaiService = execution.getVariable("GENGS_service") + if (!isBlank(aaiService) && (utils.nodeExists(aaiService, "resource-version"))) { + execution.setVariable("serviceInstanceVersion", utils.getNodeText(aaiService, "resource-version")) + utils.log("INFO","Found Service-instance in AAI.serviceInstanceName:" + execution.getVariable("serviceInstanceName"), isDebugEnabled) + } + } + } + } catch (BpmnError e) { + throw e; + } catch (Exception ex) { + msg = "Exception in DoUpdateE2EServiceInstance.postProcessAAIGET " + ex.getMessage() + utils.log("INFO", msg, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, msg) + } + utils.log("INFO"," *** Exit postProcessAAIGET *** ", 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-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateE2EServiceInstanceRollback.groovy b/bpmn/so-bpmn-infrastructure-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateE2EServiceInstanceRollback.groovy new file mode 100644 index 0000000000..a2d94baaed --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateE2EServiceInstanceRollback.groovy @@ -0,0 +1,345 @@ +/*- + * ============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 groovy.json.* + + +/** + * 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 preProcessAAIGET(DelegateExecution execution) { + } + + 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 in postProcessAAIGET", + 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){ + String aaiService = execution.getVariable("GENGS_service") + if (!isBlank(aaiService) && (utils.nodeExists(aaiService, "resource-version"))) { + execution.setVariable("serviceInstanceVersion_n", utils.getNodeText(aaiService, "resource-version")) + msoLogger.info("Found Service-instance in AAI.serviceInstanceName:" + execution.getVariable("serviceInstanceName")) + } + } + } + } 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 ") + } + + 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-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateNetworkInstance.groovy b/bpmn/so-bpmn-infrastructure-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateNetworkInstance.groovy new file mode 100644 index 0000000000..7272f421fc --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateNetworkInstance.groovy @@ -0,0 +1,1408 @@ +/*- + * ============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 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) + + 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' + 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) + + } + } + + 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-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateNetworkInstanceRollback.groovy b/bpmn/so-bpmn-infrastructure-flows/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-flows/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-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateVfModule.groovy b/bpmn/so-bpmn-infrastructure-flows/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-flows/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-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoUpdateVnfAndModules.groovy b/bpmn/so-bpmn-infrastructure-flows/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-flows/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-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/HealchCheckActivate.groovy b/bpmn/so-bpmn-infrastructure-flows/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-flows/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-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/ReplaceVnfInfra.groovy b/bpmn/so-bpmn-infrastructure-flows/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-flows/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-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/RollbackVnf.groovy b/bpmn/so-bpmn-infrastructure-flows/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-flows/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-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/ScaleCustomE2EServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-flows/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-flows/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-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/UpdateCustomE2EServiceInstance.groovy b/bpmn/so-bpmn-infrastructure-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/UpdateCustomE2EServiceInstance.groovy new file mode 100644 index 0000000000..538f882c2b --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/UpdateCustomE2EServiceInstance.groovy @@ -0,0 +1,570 @@ +/*- + * ============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.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.json.JsonUtils +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) + } + + + 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, Id:" + serviceInstanceId + utils.log("INFO", msg, isDebugEnabled) + exceptionUtil.buildAndThrowWorkflowException(execution, 500, msg) + } + + utils.log("INFO", "SI Data" + siData, isDebugEnabled) + + // serviceInstanceName + String serviceInstanceName = execution.getVariable("serviceInstanceName") + if(isBlank(serviceInstanceName) && utils.nodeExists(siData, "service-instance-name")) { + serviceInstanceName = utils.getNodeText(siData, "service-instance-name") + execution.setVariable("serviceInstanceName", serviceInstanceName) + } + + // 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 = utils.getNodeText(siData, "model-invariant-id") + def modelVersionId = utils.getNodeText(siData, "model-version-id") + + // Set Original Template info + execution.setVariable("model-invariant-id-original", modelInvariantId) + execution.setVariable("model-version-id-original", modelVersionId) + } + + //get related service instances (vnf/network or volume) for delete + 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()) + } + }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.getNodeText(relation, "related-to") + + def rl = utils.getNodeText(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) + } + } + + 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 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-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/UpdateNetworkInstance.groovy b/bpmn/so-bpmn-infrastructure-flows/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-flows/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-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/UpdateVfModule.groovy b/bpmn/so-bpmn-infrastructure-flows/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-flows/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-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/UpdateVfModuleInfra.groovy b/bpmn/so-bpmn-infrastructure-flows/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-flows/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-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/UpdateVfModuleInfraV2.groovy b/bpmn/so-bpmn-infrastructure-flows/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-flows/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-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/UpdateVfModuleVolume.groovy b/bpmn/so-bpmn-infrastructure-flows/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-flows/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-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/UpdateVfModuleVolumeInfraV1.groovy b/bpmn/so-bpmn-infrastructure-flows/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-flows/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-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/UpdateVnfInfra.groovy b/bpmn/so-bpmn-infrastructure-flows/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-flows/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-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/VnfCmBase.groovy b/bpmn/so-bpmn-infrastructure-flows/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-flows/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-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/VnfConfigUpdate.groovy b/bpmn/so-bpmn-infrastructure-flows/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-flows/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-flows/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/VnfInPlaceUpdate.groovy b/bpmn/so-bpmn-infrastructure-flows/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-flows/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-flows/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/CreateVcpeResCustService.groovy b/bpmn/so-bpmn-infrastructure-flows/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-flows/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-flows/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DeleteVcpeResCustService.groovy b/bpmn/so-bpmn-infrastructure-flows/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DeleteVcpeResCustService.groovy new file mode 100644 index 0000000000..eaf3631441 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-flows/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DeleteVcpeResCustService.groovy @@ -0,0 +1,461 @@ +/* + * ============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 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) + + //Setting for Generic Sub Flows + execution.setVariable("GENGS_type", "service-instance") + + 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) + } + } + + public void prepareServiceDelete(DelegateExecution execution) { + def isDebugEnabled=execution.getVariable(DebugFlag) + msoLogger.trace("Inside prepareServiceDelete() of DeleteVcpeResCustService ") + + try { + + String serviceInstanceId = execution.getVariable("serviceInstanceId") + + // confirm if ServiceInstance was found + if ( !execution.getVariable("GENGS_FoundIndicator") ) + { + String exceptionMessage = "Bpmn error encountered in DeleteVcpeResCustService flow. Service Instance was not found in AAI by id: " + serviceInstanceId + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + } + + // get variable within incoming json + String DeleteVcpeResCustServiceRequest = execution.getVariable("DeleteVcpeResCustServiceRequest"); + + // get SI extracted by GenericGetService + String serviceInstanceAaiRecord = execution.getVariable("GENGS_service"); + + msoLogger.debug("serviceInstanceAaiRecord: "+serviceInstanceAaiRecord) + serviceInstanceAaiRecord = utils.removeXmlNamespaces(serviceInstanceAaiRecord) + + def (TXC_found, TXC_id) = new Tuple(false, null) + def (BRG_found, BRG_id) = new Tuple(false, null) + List relatedVnfIdList = [] + + for(Node rel: utils.getMultNodeObjects(serviceInstanceAaiRecord, "relationship")) { + def relto = utils.getChildNodeText(rel, "related-to") + def relink = utils.getChildNodeText(rel, "related-link") + msoLogger.debug("check: "+relto+" link: "+relink) + + if(isBlank(relto) || isBlank(relink)) { + + } else if(relto == "generic-vnf") { + def id = relink.substring(relink.indexOf("/generic-vnf/")+13) + if(id.endsWith("/")) { + id = id.substring(0, id.length()-1) + } + + relatedVnfIdList.add(id) + + } else if(relto == "allotted-resource") { + def (type, id) = getAaiAr(execution, relink) + + if(isBlank(type) || isBlank(id)) { + + } else 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) + + int vnfsCount = relatedVnfIdList.size() + execution.setVariable(Prefix+"vnfsCount", vnfsCount) + msoLogger.debug(" "+Prefix+"vnfsCount : " + vnfsCount) + if(vnfsCount > 0) { + execution.setVariable(Prefix+"relatedVnfIdList", relatedVnfIdList) + } + + msoLogger.trace("Completed prepareServiceDelete() of DeleteVcpeResCustService ") + } catch (BpmnError e){ + throw e; + } catch (Exception ex) { + sendSyncError(execution) + String exceptionMessage = "Bpmn error encountered in DeleteVcpeResCustService flow. prepareServiceDelete() - " + ex.getMessage() + msoLogger.debug(exceptionMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + } + } + + private getAaiAr(DelegateExecution execution, String relink) { + def isDebugEnabled = execution.getVariable(DebugFlag) + AaiUtil aaiUtil = new AaiUtil(this) + String aaiEndpoint = UrnPropertiesReader.getVariable("aai.endpoint",execution) + 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 new Tuple2(null, null) + } + + def type = utils.getNodeText(aaiResponse, "type") + def id = utils.getNodeText(aaiResponse, "id") + + return new Tuple2(type, id) + } + + + // ******************************* + // + // ******************************* + 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-flows/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceBRG.groovy b/bpmn/so-bpmn-infrastructure-flows/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceBRG.groovy new file mode 100644 index 0000000000..8a8aa2b2ad --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-flows/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceBRG.groovy @@ -0,0 +1,678 @@ +/* + * ============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>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") + } + + 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") + 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-flows/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceBRGRollback.groovy b/bpmn/so-bpmn-infrastructure-flows/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-flows/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-flows/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceTXC.groovy b/bpmn/so-bpmn-infrastructure-flows/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-flows/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-flows/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoCreateAllottedResourceTXCRollback.groovy b/bpmn/so-bpmn-infrastructure-flows/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-flows/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-flows/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoDeleteAllottedResourceBRG.groovy b/bpmn/so-bpmn-infrastructure-flows/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-flows/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-flows/src/main/groovy/org/onap/so/bpmn/vcpe/scripts/DoDeleteAllottedResourceTXC.groovy b/bpmn/so-bpmn-infrastructure-flows/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-flows/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") + } + +} |