From 4529f2a4fca2c1846408f274d6feb1cd32f5a847 Mon Sep 17 00:00:00 2001 From: tragait Date: Tue, 7 Jul 2020 12:00:52 +0100 Subject: [SO] create generic pnf healthcheck workflow This commit implements workflow for pnf health check and its respective test cases. Issue-ID: SO-3018 Signed-off-by: tragait Change-Id: Idffcbf78809c33dd7a059bc87962716d0a9cd81c Signed-off-by: tragait --- .../scripts/GenericPnfTaskProcessor.groovy | 127 +++++++++++ .../resources/process/GenericPnfHealthCheck.bpmn | 203 ++++++++++++++++++ .../process/PNFSoftwareUpgradeTest.java | 1 - .../infrastructure/process/PnfHealthCheckTest.java | 234 +++++++++++++++++++++ .../test/resources/request/PnfHealthCheckTest.json | 50 +++++ .../resources/response/PnfHealthCheckTest.json | 26 +++ .../response/PnfHealthCheckTest_catalogdb.json | 39 ++++ .../flowspecific/tasks/GenericPnfDispatcher.java | 174 +++++++++++++++ 8 files changed, 853 insertions(+), 1 deletion(-) create mode 100644 bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/GenericPnfTaskProcessor.groovy create mode 100644 bpmn/so-bpmn-infrastructure-flows/src/main/resources/process/GenericPnfHealthCheck.bpmn create mode 100644 bpmn/so-bpmn-infrastructure-flows/src/test/java/org/onap/so/bpmn/infrastructure/process/PnfHealthCheckTest.java create mode 100644 bpmn/so-bpmn-infrastructure-flows/src/test/resources/request/PnfHealthCheckTest.json create mode 100644 bpmn/so-bpmn-infrastructure-flows/src/test/resources/response/PnfHealthCheckTest.json create mode 100644 bpmn/so-bpmn-infrastructure-flows/src/test/resources/response/PnfHealthCheckTest_catalogdb.json create mode 100644 bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/GenericPnfDispatcher.java (limited to 'bpmn') diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/GenericPnfTaskProcessor.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/GenericPnfTaskProcessor.groovy new file mode 100644 index 0000000000..727a7508c4 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/GenericPnfTaskProcessor.groovy @@ -0,0 +1,127 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2020 Nordix Foundation. + * ================================================================================ + * 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + + +package org.onap.so.bpmn.infrastructure.scripts + +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.workflow.context.WorkflowContext +import org.onap.so.bpmn.common.workflow.context.WorkflowContextHolder +import org.onap.so.bpmn.core.WorkflowException +import org.slf4j.Logger +import org.slf4j.LoggerFactory + +import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames.PNF_CORRELATION_ID +import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames.REQUEST_ID + +class GenericPnfTaskProcessor extends AbstractServiceTaskProcessor { + private static final Logger logger = LoggerFactory.getLogger(GenericPnfTaskProcessor.class) + + ExceptionUtil exceptionUtil = new ExceptionUtil() + String prefix = "Generic_" + + @Override + void preProcessRequest(DelegateExecution execution) { + } + + void sendResponse(DelegateExecution execution) { + def requestId = execution.getVariable(REQUEST_ID) + def instanceId = execution.getVariable(PNF_CORRELATION_ID) + logger.debug("Send response for requestId: {}, instanceId: {}", requestId, instanceId) + + String response = """{"requestReferences":{"requestId":"${requestId}", "instanceId":"${instanceId}"}}""".trim() + sendWorkflowResponse(execution, 200, response) + } + + static WorkflowContext getWorkflowContext(DelegateExecution execution) { + String requestId = execution.getVariable(REQUEST_ID) + return WorkflowContextHolder.getInstance().getWorkflowContext(requestId) + } + + void prepareCompletion(DelegateExecution execution) { + try { + String requestId = execution.getVariable(REQUEST_ID) + logger.debug("Prepare Completion of PNF for requestId: {}", requestId) + + String msoCompletionRequest = + """ + + ${MsoUtils.xmlEscape(requestId)} + UPDATE + VID + + Activity is successful. + ${execution.getProcessDefinitionId()} + """ + String xmlMsoCompletionRequest = utils.formatXml(msoCompletionRequest) + + execution.setVariable(prefix + "CompleteMsoProcessRequest", xmlMsoCompletionRequest) + + logger.debug("CompleteMsoProcessRequest of PNF - " + "\n" + xmlMsoCompletionRequest) + } catch (Exception e) { + String msg = "Prepare Completion error for PNF - " + e.getMessage() + logger.error(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) + } + } + + void prepareFalloutHandler(DelegateExecution execution) { + WorkflowContext workflowContext = getWorkflowContext(execution) + if (workflowContext == null) { + logger.debug("Error occurred before sending response to API handler, and send it now") + sendResponse(execution) + } + + try { + String requestId = execution.getVariable(REQUEST_ID) + logger.debug("Prepare FalloutHandler of PNF for requestId: {}", requestId) + + WorkflowException workflowException = execution.getVariable("WorkflowException") + String errorCode = String.valueOf(workflowException.getErrorCode()) + String errorMessage = workflowException.getErrorMessage() + String falloutHandlerRequest = + """ + + ${MsoUtils.xmlEscape(requestId)} + UPDATE + VID + + + ${MsoUtils.xmlEscape(errorMessage)} + ${MsoUtils.xmlEscape(errorCode)} + + """ + String xmlFalloutHandlerRequest = utils.formatXml(falloutHandlerRequest) + + execution.setVariable(prefix + "FalloutHandlerRequest", xmlFalloutHandlerRequest) + + logger.debug("FalloutHandlerRequest of PNF - " + "\n" + xmlFalloutHandlerRequest) + } catch (Exception e) { + String msg = "Prepare FalloutHandler error for PNF - " + e.getMessage() + logger.error(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) + } + } +} diff --git a/bpmn/so-bpmn-infrastructure-flows/src/main/resources/process/GenericPnfHealthCheck.bpmn b/bpmn/so-bpmn-infrastructure-flows/src/main/resources/process/GenericPnfHealthCheck.bpmn new file mode 100644 index 0000000000..1722137056 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-flows/src/main/resources/process/GenericPnfHealthCheck.bpmn @@ -0,0 +1,203 @@ + + + + + SequenceFlow_1ng4b6l + + + SequenceFlow_1ng4b6l + SequenceFlow_12ejx4m + + + + SequenceFlow_0tle5zb + + + + + SequenceFlow_0j26xlx + SequenceFlow_0piri91 + Flow_015z1h4 + + + SequenceFlow_0piri91 + + + + + SequenceFlow_12ejx4m + Flow_12uv2m0 + import org.onap.so.bpmn.infrastructure.scripts.* +def taskProcessor = new GenericPnfTaskProcessor() +taskProcessor.sendResponse(execution) + + + Flow_015z1h4 + SequenceFlow_0ipc3nt + import org.onap.so.bpmn.infrastructure.scripts.* +def taskProcessor = new GenericPnfTaskProcessor() +taskProcessor.prepareCompletion(execution) + + + + + + + SequenceFlow_0ipc3nt + SequenceFlow_0tle5zb + + + + + SequenceFlow_05haut5 + + + + SequenceFlow_05haut5 + SequenceFlow_09y0mpc + import org.onap.so.bpmn.infrastructure.scripts.* +def pnfSwUpgrade = new PNFSoftwareUpgrade() +pnfSwUpgrade.prepareFalloutHandler(execution) + + + + + + SequenceFlow_09y0mpc + SequenceFlow_1tcjlty + + + SequenceFlow_1tcjlty + + + + + + + + + + healthCheck + pnf + async + + + Flow_12uv2m0 + SequenceFlow_0j26xlx + + + + #{execution.getVariable("ControllerStatus").equals("Success")} + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/bpmn/so-bpmn-infrastructure-flows/src/test/java/org/onap/so/bpmn/infrastructure/process/PNFSoftwareUpgradeTest.java b/bpmn/so-bpmn-infrastructure-flows/src/test/java/org/onap/so/bpmn/infrastructure/process/PNFSoftwareUpgradeTest.java index 22cf72b262..0bf14d7443 100644 --- a/bpmn/so-bpmn-infrastructure-flows/src/test/java/org/onap/so/bpmn/infrastructure/process/PNFSoftwareUpgradeTest.java +++ b/bpmn/so-bpmn-infrastructure-flows/src/test/java/org/onap/so/bpmn/infrastructure/process/PNFSoftwareUpgradeTest.java @@ -1,7 +1,6 @@ /*- * ============LICENSE_START======================================================= * Copyright (C) 2020 Nordix Foundation. - * Modifications Copyright (C) 2020 Huawei Technologies Co., Ltd. * ================================================================================ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. diff --git a/bpmn/so-bpmn-infrastructure-flows/src/test/java/org/onap/so/bpmn/infrastructure/process/PnfHealthCheckTest.java b/bpmn/so-bpmn-infrastructure-flows/src/test/java/org/onap/so/bpmn/infrastructure/process/PnfHealthCheckTest.java new file mode 100644 index 0000000000..2423ad8465 --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-flows/src/test/java/org/onap/so/bpmn/infrastructure/process/PnfHealthCheckTest.java @@ -0,0 +1,234 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2020 Nordix Foundation. + * ================================================================================ + * 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.process; + +import com.google.protobuf.Struct; +import org.camunda.bpm.engine.runtime.ProcessInstance; +import org.junit.Before; +import org.junit.Test; +import org.onap.aaiclient.client.aai.AAIVersion; +import org.onap.ccsdk.cds.controllerblueprints.common.api.ActionIdentifiers; +import org.onap.ccsdk.cds.controllerblueprints.common.api.CommonHeader; +import org.onap.ccsdk.cds.controllerblueprints.processing.api.ExecutionServiceInput; +import org.onap.so.BaseBPMNTest; +import org.onap.so.GrpcNettyServer; +import org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames; +import org.onap.so.bpmn.mock.FileUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.UUID; +import static com.github.tomakehurst.wiremock.client.WireMock.*; +import static org.assertj.core.api.Assertions.fail; +import static org.camunda.bpm.engine.test.assertions.bpmn.BpmnAwareAssertions.assertThat; + +/** + * Basic Integration test for GenericPnfHealthCheck.bpmn workflow. + */ +public class PnfHealthCheckTest extends BaseBPMNTest { + + private final Logger logger = LoggerFactory.getLogger(getClass()); + + private static final long WORKFLOW_WAIT_TIME = 1000L; + + private static final String TEST_PROCESSINSTANCE_KEY = "GenericPnfHealthCheck"; + private static final AAIVersion VERSION = AAIVersion.LATEST; + private static final Map executionVariables = new HashMap<>(); + private static final String REQUEST_ID = "50ae41ad-049c-4fe2-9950-539f111120f5"; + private static final String ACTION_NAME = "healthCheck"; + private final String CLASS_NAME = getClass().getSimpleName(); + private String requestObject; + private String responseObject; + + @Autowired + private GrpcNettyServer grpcNettyServer; + + @Before + public void setUp() { + executionVariables.clear(); + grpcNettyServer.getDetailedMessages().clear(); + + requestObject = FileUtil.readResourceFile("request/" + CLASS_NAME + ".json"); + responseObject = FileUtil.readResourceFile("response/" + CLASS_NAME + ".json"); + + executionVariables.put("bpmnRequest", requestObject); + executionVariables.put("requestId", REQUEST_ID); + + /** + * This variable indicates that the flow was invoked asynchronously. It's injected by {@link WorkflowProcessor}. + */ + executionVariables.put("isAsyncProcess", "true"); + executionVariables.put(ExecutionVariableNames.PRC_CUSTOMIZATION_UUID, "38dc9a92-214c-11e7-93ae-92361f002680"); + + /** + * Temporary solution to add pnfCorrelationId to context. this value is getting from the request to SO api + * handler and then convert to CamundaInput + */ + executionVariables.put(ExecutionVariableNames.PNF_CORRELATION_ID, "PNFDemo"); + } + + + @Test + public void workflow_validInput_expectedOutput() throws InterruptedException { + + mockCatalogDb(); + mockRequestDb(); + mockAai(); + + final String msoRequestId = UUID.randomUUID().toString(); + executionVariables.put(ExecutionVariableNames.MSO_REQUEST_ID, msoRequestId); + + final String testBusinessKey = UUID.randomUUID().toString(); + logger.info("Test the process instance: {} with business key: {}", TEST_PROCESSINSTANCE_KEY, testBusinessKey); + + ProcessInstance pi = + runtimeService.startProcessInstanceByKey(TEST_PROCESSINSTANCE_KEY, testBusinessKey, executionVariables); + + int waitCount = 10; + while (!isProcessInstanceEnded() && waitCount >= 0) { + Thread.sleep(WORKFLOW_WAIT_TIME); + waitCount--; + } + + // Layout is to reflect the bpmn visual layout + assertThat(pi).isEnded().hasPassedInOrder("pnfHealthCheck_startEvent", "ServiceTask_042uz7m", + "ScriptTask_10klpg9", "ServiceTask_0slpaht", "ExclusiveGateway_0x6h0yi", "ScriptTask_1igtc83", + "CallActivity_0o1mi8u", "pnfHealthCheck_endEvent"); + + List detailedMessages = grpcNettyServer.getDetailedMessages(); + logger.debug("Size of detailedMessage is {}", detailedMessages.size()); + assertThat(detailedMessages.size() == 1).isTrue(); + int count = 0; + try { + for (ExecutionServiceInput eSI : detailedMessages) { + if (ACTION_NAME.equals(eSI.getActionIdentifiers().getActionName()) + && eSI.getCommonHeader().getRequestId().equals(msoRequestId)) { + checkWithActionName(eSI, ACTION_NAME); + count++; + } + } + } catch (Exception e) { + e.printStackTrace(); + fail("PNFHealthCheck request exception", e); + } + assertThat(count == 1).isTrue(); + } + + private boolean isProcessInstanceEnded() { + return runtimeService.createProcessInstanceQuery().processDefinitionKey(TEST_PROCESSINSTANCE_KEY) + .singleResult() == null; + } + + private void checkWithActionName(ExecutionServiceInput executionServiceInput, String action) { + + logger.info("Checking the " + action + " request"); + ActionIdentifiers actionIdentifiers = executionServiceInput.getActionIdentifiers(); + + /** + * the fields of actionIdentifiers should match the one in the response/PnfHealthCheck_catalogdb.json. + */ + assertThat(actionIdentifiers.getBlueprintName()).isEqualTo("test_pnf_health_check_restconf"); + assertThat(actionIdentifiers.getBlueprintVersion()).isEqualTo("1.0.0"); + assertThat(actionIdentifiers.getActionName()).isEqualTo(action); + assertThat(actionIdentifiers.getMode()).isEqualTo("async"); + + CommonHeader commonHeader = executionServiceInput.getCommonHeader(); + assertThat(commonHeader.getOriginatorId()).isEqualTo("SO"); + + Struct payload = executionServiceInput.getPayload(); + Struct requeststruct = payload.getFieldsOrThrow(action + "-request").getStructValue(); + + assertThat(requeststruct.getFieldsOrThrow("resolution-key").getStringValue()).isEqualTo("PNFDemo"); + Struct propertiesStruct = requeststruct.getFieldsOrThrow(action + "-properties").getStructValue(); + + assertThat(propertiesStruct.getFieldsOrThrow("pnf-name").getStringValue()).isEqualTo("PNFDemo"); + assertThat(propertiesStruct.getFieldsOrThrow("service-model-uuid").getStringValue()) + .isEqualTo("32daaac6-5017-4e1e-96c8-6a27dfbe1421"); + assertThat(propertiesStruct.getFieldsOrThrow("pnf-customization-uuid").getStringValue()) + .isEqualTo("38dc9a92-214c-11e7-93ae-92361f002680"); + } + + private void mockAai() { + + String aaiPnfEntry = + "{ \n" + " \"pnf-name\":\"PNFDemo\",\n" + " \"pnf-id\":\"testtest\",\n" + " \"in-maint\":true,\n" + + " \"resource-version\":\"1541720264047\",\n" + " \"swVersion\":\"demo-1.1\",\n" + + " \"ipaddress-v4-oam\":\"1.1.1.1\",\n" + " \"ipaddress-v6-oam\":\"::/128\"\n" + "}"; + + /** + * PUT the PNF correlation ID to AAI. + */ + wireMockServer.stubFor(put(urlEqualTo("/aai/" + VERSION + "/network/pnfs/pnf/PNFDemo"))); + + /** + * Get the PNF entry from AAI. + */ + wireMockServer.stubFor( + get(urlEqualTo("/aai/" + VERSION + "/network/pnfs/pnf/PNFDemo")).willReturn(okJson(aaiPnfEntry))); + + /** + * Post the pnf to AAI + */ + wireMockServer.stubFor(post(urlEqualTo("/aai/" + VERSION + "/network/pnfs/pnf/PNFDemo"))); + } + + private void mockRequestDb() { + /** + * Update Request DB + */ + wireMockServer.stubFor(put(urlEqualTo("/infraActiveRequests/" + REQUEST_ID))); + + } + + /** + * Mock the catalobdb rest interface. + */ + private void mockCatalogDb() { + + String catalogdbClientResponse = FileUtil.readResourceFile("response/" + CLASS_NAME + "_catalogdb.json"); + + + /** + * Return valid json for the model UUID in the request file. + */ + wireMockServer + .stubFor(get(urlEqualTo("/v2/serviceResources?serviceModelUuid=32daaac6-5017-4e1e-96c8-6a27dfbe1421")) + .willReturn(okJson(responseObject))); + + /** + * Return valid json for the service model InvariantUUID as specified in the request file. + */ + wireMockServer.stubFor( + get(urlEqualTo("/v2/serviceResources?serviceModelInvariantUuid=339b7a2f-9524-4dbf-9eee-f2e05521df3f")) + .willReturn(okJson(responseObject))); + + /** + * Return valid spring data rest json for the service model UUID as specified in the request file. + */ + wireMockServer.stubFor(get(urlEqualTo( + "/pnfResourceCustomization/search/findPnfResourceCustomizationByModelUuid?SERVICE_MODEL_UUID=32daaac6-5017-4e1e-96c8-6a27dfbe1421")) + .willReturn(okJson(catalogdbClientResponse))); + } + +} diff --git a/bpmn/so-bpmn-infrastructure-flows/src/test/resources/request/PnfHealthCheckTest.json b/bpmn/so-bpmn-infrastructure-flows/src/test/resources/request/PnfHealthCheckTest.json new file mode 100644 index 0000000000..7cfe9f5c9c --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-flows/src/test/resources/request/PnfHealthCheckTest.json @@ -0,0 +1,50 @@ +{ + "requestDetails":{ + "requestInfo":{ + "source":"VID", + "suppressRollback":false, + "requestorId":"demo", + "productFamilyId":"SWUPid" + }, + "modelInfo":{ + "modelType":"service", + "modelInvariantUuid":"339b7a2f-9524-4dbf-9eee-f2e05521df3f", + "modelInvariantId":"339b7a2f-9524-4dbf-9eee-f2e05521df3f", + "modelUuid":"32daaac6-5017-4e1e-96c8-6a27dfbe1421", + "modelName":"PNF_int_service_2", + "modelVersion":"1.0" + }, + "requestParameters":{ + "userParams":[ + { + "name":"aic_zone", + "value":"nova" + }, + { + "name":"pnfId", + "value":"PNFDemo" + }, + { + "name":"pnfName", + "value":"PNFDemo" + } + ], + "subscriptionServiceType":"SWUP", + "aLaCarte":false + }, + "cloudConfiguration":{ + "lcpCloudRegionId":"regionOne", + "tenantId":"09a63533072f4a579d5c99c3b8fe94c6" + }, + "subscriberInfo":{ + "globalSubscriberId":"ADemoCustomerInEric" + }, + "project":{ + "projectName":"Project-Demonstration" + }, + "owningEntity":{ + "owningEntityId":"5eae949c-1c50-4780-b8b5-7cbeb08856b4", + "owningEntityName":"OE-Demonstration" + } + } +} \ No newline at end of file diff --git a/bpmn/so-bpmn-infrastructure-flows/src/test/resources/response/PnfHealthCheckTest.json b/bpmn/so-bpmn-infrastructure-flows/src/test/resources/response/PnfHealthCheckTest.json new file mode 100644 index 0000000000..32539844ba --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-flows/src/test/resources/response/PnfHealthCheckTest.json @@ -0,0 +1,26 @@ +{ + "serviceResources":{ + "modelInfo":{ + "modelInvariantId":"439b7a2f-9524-4dbf-9eee-f2e05521df3f", + "modelUuid":"42daaac6-5017-4e1e-96c8-6a27dfbe1421", + "modelName":"PNF_int_service_2", + "modelVersion":"1.0" + }, + "serviceType":"NA", + "environmentContext":"Luna", + "serviceRole":"NA", + "workloadContext":"Oxygen", + "serviceVnfs":[ + + ], + "serviceNetworks":[ + + ], + "serviceAllottedResources":[ + + ], + "configResource":[ + + ] + } +} \ No newline at end of file diff --git a/bpmn/so-bpmn-infrastructure-flows/src/test/resources/response/PnfHealthCheckTest_catalogdb.json b/bpmn/so-bpmn-infrastructure-flows/src/test/resources/response/PnfHealthCheckTest_catalogdb.json new file mode 100644 index 0000000000..fc9399d7cb --- /dev/null +++ b/bpmn/so-bpmn-infrastructure-flows/src/test/resources/response/PnfHealthCheckTest_catalogdb.json @@ -0,0 +1,39 @@ +{ + "_embedded": { + "pnfResourceCustomization": [ + { + "modelCustomizationUUID": "38dc9a92-214c-11e7-93ae-92361f002680", + "modelInstanceName": "PNF routing", + "created": "2019-03-08 12:00:29.000", + "nfFunction": "routing", + "nfType": "routing", + "nfRole": "routing", + "nfNamingCode": "routing", + "multiStageDesign": null, + "resourceInput": null, + "blueprintName": "test_pnf_health_check_restconf", + "blueprintVersion": "1.0.0", + "skipPostInstConf": false, + "softwareVersion": "1.0.0", + "creationTimestamp": "2019-03-08T12:00:29.000+0000", + "controllerActor": "cds", + "_links": { + "self": { + "href": "http://localhost:41023/pnfResourceCustomization/38dc9a92-214c-11e7-93ae-92361f002680" + }, + "pnfResourceCustomization": { + "href": "http://localhost:41023/pnfResourceCustomization/38dc9a92-214c-11e7-93ae-92361f002680" + }, + "pnfResources": { + "href": "http://localhost:41023/pnfResourceCustomization/38dc9a92-214c-11e7-93ae-92361f002680/pnfResources" + } + } + } + ] + }, + "_links": { + "self": { + "href": "http://localhost:41023/pnfResourceCustomization/search/findPnfResourceCustomizationByModelUuid?SERVICE_MODEL_UUID=4df8b6de-2083-11e7-93ae-92361f002676" + } + } +} \ No newline at end of file diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/GenericPnfDispatcher.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/GenericPnfDispatcher.java new file mode 100644 index 0000000000..72a8590ad5 --- /dev/null +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/flowspecific/tasks/GenericPnfDispatcher.java @@ -0,0 +1,174 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2020 Nordix Foundation. + * ================================================================================ + * 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ + +package org.onap.so.bpmn.infrastructure.flowspecific.tasks; + +import com.fasterxml.jackson.databind.ObjectMapper; +import org.camunda.bpm.engine.delegate.DelegateExecution; +import org.camunda.bpm.engine.delegate.JavaDelegate; +import org.onap.aai.domain.yang.Pnf; +import org.onap.so.bpmn.core.json.JsonUtils; +import org.onap.so.bpmn.infrastructure.pnf.management.PnfManagement; +import org.onap.so.client.exception.ExceptionBuilder; +import org.onap.so.db.catalog.beans.PnfResourceCustomization; +import org.onap.so.db.catalog.client.CatalogDbClient; +import org.onap.so.serviceinstancebeans.RequestDetails; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import java.io.IOException; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import static org.onap.so.bpmn.infrastructure.pnf.delegate.ExecutionVariableNames.*; + +/** + * This implementation of {@link JavaDelegate} is used to populate the execution object for pnf actions + */ +@Component +public class GenericPnfDispatcher implements JavaDelegate { + + private final Logger logger = LoggerFactory.getLogger(getClass()); + private static final String SERVICE_INSTANCE_NAME = "serviceInstanceName"; + private static final String BPMN_REQUEST = "bpmnRequest"; + private static final String RESOURCE_CUSTOMIZATION_UUID_PARAM = "resource_customization_uuid"; + private static final String PNF_NAME = "pnfName"; + + // ERROR CODE for variable not found in the delegation Context + private static final int ERROR_CODE = 601; + + @Autowired + private PnfManagement pnfManagement; + + @Autowired + private ExceptionBuilder exceptionUtil; + + @Autowired + private CatalogDbClient catalogDbClient; + + @Autowired + private ObjectMapper mapper; + + @Override + public void execute(DelegateExecution delegateExecution) throws Exception { + logger.debug("Running execute block for activity id: {}, name: {}", delegateExecution.getCurrentActivityId(), + delegateExecution.getCurrentActivityName()); + + RequestDetails bpmnRequestDetails = requestVerification(delegateExecution); + + final String serviceInstanceName = bpmnRequestDetails.getRequestInfo().getInstanceName(); + final String pnfName; + if (delegateExecution.getVariable(PNF_NAME) == null + || String.valueOf(delegateExecution.getVariable(PNF_NAME)).trim().isEmpty()) { + pnfName = bpmnRequestDetails.getRequestParameters().getUserParamValue(PNF_NAME); + } else { + pnfName = String.valueOf(delegateExecution.getVariable(PNF_NAME)); + } + final String serviceModelUuid = bpmnRequestDetails.getModelInfo().getModelUuid(); + final List> userParams = bpmnRequestDetails.getRequestParameters().getUserParams(); + final Pnf pnf = getPnfByPnfName(delegateExecution, pnfName); + final List pnfCustomizations = + getPnfResourceCustomizations(delegateExecution, serviceModelUuid); + final PnfResourceCustomization pnfResourceCustomization = pnfCustomizations.get(0); + final String payload = bpmnRequestDetails.getRequestParameters().getPayload(); + + populateExecution(delegateExecution, bpmnRequestDetails, pnfResourceCustomization, pnf, serviceInstanceName, + pnfName, serviceModelUuid, userParams, payload); + + logger.trace("Completed dispatcher request for PNF."); + } + + private RequestDetails requestVerification(DelegateExecution delegateExecution) throws IOException { + RequestDetails bpmnRequestDetails = mapper.readValue( + JsonUtils.getJsonValue(String.valueOf(delegateExecution.getVariable(BPMN_REQUEST)), "requestDetails"), + RequestDetails.class); + + throwIfNull(delegateExecution, bpmnRequestDetails.getModelInfo(), SERVICE_MODEL_INFO); + throwIfNull(delegateExecution, bpmnRequestDetails.getRequestInfo(), "RequestInfo"); + throwIfNull(delegateExecution, bpmnRequestDetails.getRequestParameters(), "RequestParameters"); + throwIfNull(delegateExecution, bpmnRequestDetails.getRequestParameters().getUserParams(), "UserParams"); + + return bpmnRequestDetails; + } + + private void populateExecution(DelegateExecution delegateExecution, RequestDetails bpmnRequestDetails, + PnfResourceCustomization pnfResourceCustomization, Pnf pnf, String serviceInstanceName, String pnfName, + String serviceModelUuid, List> userParams, String payload) { + + delegateExecution.setVariable(SERVICE_MODEL_INFO, bpmnRequestDetails.getModelInfo()); + delegateExecution.setVariable(SERVICE_INSTANCE_NAME, serviceInstanceName); + delegateExecution.setVariable(PNF_CORRELATION_ID, pnfName); + delegateExecution.setVariable(MODEL_UUID, serviceModelUuid); + delegateExecution.setVariable(PNF_UUID, pnf.getPnfId()); + delegateExecution.setVariable(PRC_BLUEPRINT_NAME, pnfResourceCustomization.getBlueprintName()); + delegateExecution.setVariable(PRC_BLUEPRINT_VERSION, pnfResourceCustomization.getBlueprintVersion()); + delegateExecution.setVariable(PRC_CUSTOMIZATION_UUID, pnfResourceCustomization.getModelCustomizationUUID()); + delegateExecution.setVariable(RESOURCE_CUSTOMIZATION_UUID_PARAM, + pnfResourceCustomization.getModelCustomizationUUID()); + delegateExecution.setVariable(PRC_INSTANCE_NAME, pnfResourceCustomization.getModelInstanceName()); + delegateExecution.setVariable(PRC_CONTROLLER_ACTOR, pnfResourceCustomization.getControllerActor()); + + for (Map param : userParams) { + if (param.containsKey("name") && param.containsKey("value")) { + delegateExecution.setVariable(param.get("name").toString(), param.get("value").toString()); + } + } + + delegateExecution.setVariable(REQUEST_PAYLOAD, payload); + } + + private Pnf getPnfByPnfName(DelegateExecution delegateExecution, String pnfName) { + Optional pnfOptional = Optional.empty(); + try { + pnfOptional = pnfManagement.getEntryFor(pnfName); + } catch (IOException e) { + throwExceptionWithWarn(delegateExecution, "Unable to fetch from AAI" + e.getMessage()); + } + if (!pnfOptional.isPresent()) { + throwExceptionWithWarn(delegateExecution, "AAI entry for PNF: " + pnfName + " does not exist"); + } + return pnfOptional.get(); + } + + private List getPnfResourceCustomizations(DelegateExecution delegateExecution, + String serviceModelUuid) { + List pnfCustomizations = + catalogDbClient.getPnfResourceCustomizationByModelUuid(serviceModelUuid); + + if (pnfCustomizations == null || pnfCustomizations.isEmpty()) { + throwExceptionWithWarn(delegateExecution, + "Unable to find the PNF resource customizations of model service UUID: " + serviceModelUuid); + } + return pnfCustomizations; + } + + private void throwIfNull(DelegateExecution delegateExecution, Object obj, String param) { + if (obj == null) { + throwExceptionWithWarn(delegateExecution, + "Unable to find the parameter: " + param + " in the execution context"); + } + } + + private void throwExceptionWithWarn(DelegateExecution delegateExecution, String exceptionMsg) { + logger.warn(exceptionMsg); + exceptionUtil.buildAndThrowWorkflowException(delegateExecution, ERROR_CODE, exceptionMsg); + } +} -- cgit 1.2.3-korg