From cd4e5b408603a13dabc58f832e4aae4194e81995 Mon Sep 17 00:00:00 2001 From: "Boslet, Cory" Date: Wed, 25 Mar 2020 16:04:41 -0400 Subject: convert openstack to external tasks Use external tasks to communicate with openstack adapter Will be more resilient to failures Refactored all flows to use external tasks not REST calls Rollback is now an external task Ensured backwards compatibility Issue-ID: SO-2767 Signed-off-by: Benjamin, Max (mb388a) Change-Id: I8afdb89c688d756aed0f25f7d9a7fb898142554d --- .../openstack/utils/MsoHeatEnvironmentEntry.java | 3 +- .../org/onap/so/openstack/utils/MsoHeatUtils.java | 52 +- .../onap/so/openstack/utils/MsoHeatUtilsTest.java | 10 +- .../onap/so/adapters/vnfrest/VfModuleRollback.java | 6 +- .../org/onap/so/adapters/audit/AbstractAudit.java | 39 - .../so/adapters/audit/AbstractAuditService.java | 88 -- .../so/adapters/audit/AuditCreateStackService.java | 111 --- .../onap/so/adapters/audit/AuditDataService.java | 77 -- .../so/adapters/audit/AuditDeleteStackService.java | 121 --- .../so/adapters/audit/AuditQueryStackService.java | 85 -- .../onap/so/adapters/audit/AuditStackService.java | 91 -- .../org/onap/so/adapters/audit/AuditVServer.java | 171 ---- .../org/onap/so/adapters/audit/HeatStackAudit.java | 327 ------- .../inventory/create/CreateAAIInventory.java | 73 -- .../inventory/create/CreateInventoryService.java | 52 -- .../inventory/create/CreateInventoryTask.java | 121 --- .../inventory/create/InventoryException.java | 34 - .../org/onap/so/adapters/tasks/TaskServices.java | 132 +++ .../so/adapters/tasks/audit/AbstractAudit.java | 39 + .../adapters/tasks/audit/AbstractAuditService.java | 87 ++ .../tasks/audit/AuditCreateStackService.java | 111 +++ .../so/adapters/tasks/audit/AuditDataService.java | 77 ++ .../tasks/audit/AuditDeleteStackService.java | 122 +++ .../tasks/audit/AuditQueryStackService.java | 85 ++ .../onap/so/adapters/tasks/audit/AuditVServer.java | 171 ++++ .../so/adapters/tasks/audit/HeatStackAudit.java | 327 +++++++ .../tasks/inventory/CreateAAIInventory.java | 73 ++ .../tasks/inventory/CreateInventoryTask.java | 122 +++ .../tasks/inventory/InventoryException.java | 34 + .../adapters/tasks/orchestration/PollService.java | 191 ++++ .../tasks/orchestration/RollbackService.java | 92 ++ .../adapters/tasks/orchestration/StackService.java | 207 +++++ .../onap/so/adapters/vnf/MsoVnfAdapterImpl.java | 53 +- .../org/onap/so/adapters/vnf/VnfAdapterRest.java | 1 + .../org/onap/so/adapters/vnf/VnfAdapterRestV2.java | 8 +- .../onap/so/adapters/vnf/VolumeAdapterRestV2.java | 47 +- .../so/adapters/audit/AuditDataServiceTest.java | 101 --- .../adapters/audit/AuditStackServiceDataTest.java | 187 ---- .../onap/so/adapters/audit/AuditVServerTest.java | 432 --------- .../onap/so/adapters/audit/HeatStackAuditTest.java | 296 ------- .../inventory/create/CreateAAIInventoryTest.java | 122 --- .../inventory/create/CreateInventoryTaskTest.java | 80 -- .../adapters/tasks/audit/AuditDataServiceTest.java | 102 +++ .../tasks/audit/AuditStackServiceDataTest.java | 191 ++++ .../so/adapters/tasks/audit/AuditVServerTest.java | 433 +++++++++ .../adapters/tasks/audit/HeatStackAuditTest.java | 298 +++++++ .../tasks/inventory/CreateAAIInventoryTest.java | 123 +++ .../tasks/inventory/CreateInventoryTaskTest.java | 83 ++ .../tasks/orchestration/PollServiceTest.java | 82 ++ .../tasks/orchestration/RollbackServiceTest.java | 82 ++ .../tasks/orchestration/StackServiceTest.java | 113 +++ .../__files/vnfAdapterTaskRequestCreate.xml | 66 ++ .../service/ApplicationControllerTask.java | 2 +- .../service/ApplicationControllerTaskTest.java | 2 +- .../so/bpmn/common/scripts/VnfAdapterRestV1.groovy | 676 +++++++------- .../onap/so/client/exception/ExceptionBuilder.java | 56 +- .../main/resources/subprocess/VnfAdapterTask.bpmn | 336 +++++++ .../MSOInfrastructureApplication.java | 4 +- .../subprocess/BuildingBlock/VnfAdapter.bpmn | 57 +- .../bpmn/subprocess/VnfAdapterTest.java | 8 +- .../scripts/DoCreateVfModuleRollback.groovy | 851 +++++++++--------- .../infrastructure/scripts/DoDeleteVfModule.groovy | 978 ++++++++++----------- .../scripts/DoDeleteVfModuleFromVnf.groovy | 854 +++++++++--------- .../process/DeleteVfModuleVolumeInfraV1.bpmn | 9 +- .../process/UpdateVfModuleVolumeInfraV1.bpmn | 9 +- .../resources/subprocess/DoCreateVfModule.bpmn | 6 +- .../subprocess/DoCreateVfModuleRollback.bpmn | 15 +- .../subprocess/DoCreateVfModuleVolumeRollback.bpmn | 7 +- .../subprocess/DoCreateVfModuleVolumeV2.bpmn | 7 +- .../resources/subprocess/DoDeleteVfModule.bpmn | 15 +- .../subprocess/DoDeleteVfModuleFromVnf.bpmn | 15 +- .../subprocess/DoDeleteVfModuleVolumeV2.bpmn | 68 +- .../resources/subprocess/DoUpdateVfModule.bpmn | 15 +- .../adapter/vnf/tasks/VnfAdapterImpl.java | 6 +- .../adapter/vnf/tasks/VnfAdapterImplTest.java | 42 +- .../mapper/NetworkAdapterObjectMapperTest.java | 4 +- .../vnf/mapper/VnfAdapterObjectMapperTest.java | 4 +- .../NetworkMapper/createNetworkRequest.json | 2 +- .../vnfAdapterCreateVfModuleAddonRequest.json | 4 +- ...terCreateVfModuleRequestWithCloudResources.json | 4 +- ...dapterCreateVfModuleWithVolumeGroupRequest.json | 4 +- .../so/externaltasks/logging/AuditMDCSetup.java | 56 -- .../org/onap/so/logging/tasks/AuditMDCSetup.java | 57 ++ .../onap/so/utils/ExternalTaskServiceUtils.java | 7 +- .../java/org/onap/so/utils/ExternalTaskUtils.java | 6 +- .../externaltasks/logging/AuditMDCSetupTest.java | 93 -- .../org/onap/so/logging/tasks/MDCSetupTest.java | 92 ++ .../org/onap/so/utils/ExternalTaskUtilsTest.java | 5 + .../openstack/QueryStackByIdDoubleFailure.java | 52 +- .../scenarios/openstack/QueryStackByIdFailure.java | 16 +- .../openstack/macro/QueryStackByIdMacro1.java | 32 + .../openstack/macro/QueryStackByIdMacro2.java | 15 + .../openstack/macro/QueryStackByIdMacro3.java | 16 + 93 files changed, 6024 insertions(+), 4714 deletions(-) delete mode 100644 adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AbstractAudit.java delete mode 100644 adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AbstractAuditService.java delete mode 100644 adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditCreateStackService.java delete mode 100644 adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditDataService.java delete mode 100644 adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditDeleteStackService.java delete mode 100644 adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditQueryStackService.java delete mode 100644 adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditStackService.java delete mode 100644 adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditVServer.java delete mode 100644 adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/HeatStackAudit.java delete mode 100644 adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/CreateAAIInventory.java delete mode 100644 adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/CreateInventoryService.java delete mode 100644 adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/CreateInventoryTask.java delete mode 100644 adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/InventoryException.java create mode 100644 adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/TaskServices.java create mode 100644 adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/audit/AbstractAudit.java create mode 100644 adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/audit/AbstractAuditService.java create mode 100644 adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/audit/AuditCreateStackService.java create mode 100644 adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/audit/AuditDataService.java create mode 100644 adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/audit/AuditDeleteStackService.java create mode 100644 adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/audit/AuditQueryStackService.java create mode 100644 adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/audit/AuditVServer.java create mode 100644 adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/audit/HeatStackAudit.java create mode 100644 adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/inventory/CreateAAIInventory.java create mode 100644 adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/inventory/CreateInventoryTask.java create mode 100644 adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/inventory/InventoryException.java create mode 100644 adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/orchestration/PollService.java create mode 100644 adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/orchestration/RollbackService.java create mode 100644 adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/orchestration/StackService.java delete mode 100644 adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/audit/AuditDataServiceTest.java delete mode 100644 adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/audit/AuditStackServiceDataTest.java delete mode 100644 adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/audit/AuditVServerTest.java delete mode 100644 adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/audit/HeatStackAuditTest.java delete mode 100644 adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/inventory/create/CreateAAIInventoryTest.java delete mode 100644 adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/inventory/create/CreateInventoryTaskTest.java create mode 100644 adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tasks/audit/AuditDataServiceTest.java create mode 100644 adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tasks/audit/AuditStackServiceDataTest.java create mode 100644 adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tasks/audit/AuditVServerTest.java create mode 100644 adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tasks/audit/HeatStackAuditTest.java create mode 100644 adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tasks/inventory/CreateAAIInventoryTest.java create mode 100644 adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tasks/inventory/CreateInventoryTaskTest.java create mode 100644 adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tasks/orchestration/PollServiceTest.java create mode 100644 adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tasks/orchestration/RollbackServiceTest.java create mode 100644 adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tasks/orchestration/StackServiceTest.java create mode 100644 adapters/mso-openstack-adapters/src/test/resources/__files/vnfAdapterTaskRequestCreate.xml create mode 100644 bpmn/MSOCommonBPMN/src/main/resources/subprocess/VnfAdapterTask.bpmn delete mode 100644 common/src/main/java/org/onap/so/externaltasks/logging/AuditMDCSetup.java create mode 100644 common/src/main/java/org/onap/so/logging/tasks/AuditMDCSetup.java delete mode 100644 common/src/test/java/org/onap/so/externaltasks/logging/AuditMDCSetupTest.java create mode 100644 common/src/test/java/org/onap/so/logging/tasks/MDCSetupTest.java diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatEnvironmentEntry.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatEnvironmentEntry.java index 47ba076e0e..1f6ff1408c 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatEnvironmentEntry.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatEnvironmentEntry.java @@ -58,7 +58,8 @@ public class MsoHeatEnvironmentEntry { return; byte[] b = this.rawEntry.toString().getBytes(); MsoYamlEditorWithEnvt yaml = new MsoYamlEditorWithEnvt(b); - StringBuilder sb = null; + this.parameters = yaml.getParameterListFromEnvt(); + StringBuilder sb = this.getResourceRegistryRawEntry(); if (yaml != null) { this.parameters = yaml.getParameterListFromEnvt(); // this.resources = yaml.getResourceListFromEnvt(); diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatUtils.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatUtils.java index 97ba7828c0..62d9f068f9 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatUtils.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatUtils.java @@ -132,7 +132,6 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin { private static final ObjectMapper JSON_MAPPER = new ObjectMapper(); - /** * Create a new Stack in the specified cloud location and tenant. The Heat template and parameter map are passed in * as arguments, along with the cloud access credentials. It is expected that parameters have been validated and @@ -190,7 +189,10 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin { } else if (CREATE_FAILED.equals(currentStack.getStackStatus()) || DELETE_FAILED.equals(currentStack.getStackStatus())) { try { - processCreateStack(cloudSiteId, tenantId, timeoutMinutes, backout, currentStack, createStack, true); + if (pollForCompletion) { + processCreateStack(cloudSiteId, tenantId, timeoutMinutes, backout, currentStack, createStack, + true); + } } catch (MsoException e) { if (e instanceof StackCreationException) { logger.warn("Error during Stack will attempt to recreate stack"); @@ -199,9 +201,6 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin { if (pollForCompletion) { currentStack = processCreateStack(cloudSiteId, tenantId, timeoutMinutes, backout, currentStack, createStack, true); - } else { - currentStack = queryHeatStack(currentStack.getStackName() + "/" + currentStack.getId(), - cloudSiteId, tenantId); } } else { throw e; @@ -214,9 +213,6 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin { if (pollForCompletion) { currentStack = processCreateStack(cloudSiteId, tenantId, timeoutMinutes, backout, currentStack, createStack, true); - } else { - currentStack = - queryHeatStack(currentStack.getStackName() + "/" + currentStack.getId(), cloudSiteId, tenantId); } operationPerformed = true; } @@ -266,6 +262,7 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin { Stack heatStack, CreateStackParam stackCreate, boolean keyPairCleanUp) throws MsoException { Stack latestStack = null; try { + latestStack = pollStackForStatus(timeoutMinutes, heatStack, CREATE_IN_PROGRESS, cloudSiteId, tenantId, false); } catch (MsoException me) { @@ -275,7 +272,7 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin { stackCreate); } - protected Stack postProcessStackCreate(Stack stack, boolean backout, int timeoutMinutes, boolean cleanUpKeyPair, + public Stack postProcessStackCreate(Stack stack, boolean backout, int timeoutMinutes, boolean cleanUpKeyPair, String cloudSiteId, String tenantId, CreateStackParam stackCreate) throws MsoException { boolean stackCreationFailed = false; boolean stackRollbackFailed = false; @@ -325,7 +322,7 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin { } } - protected Stack pollStackForStatus(int timeoutMinutes, Stack stack, String stackStatus, String cloudSiteId, + public Stack pollStackForStatus(int timeoutMinutes, Stack stack, String stackStatus, String cloudSiteId, String tenantId, boolean notFoundIsSuccess) throws MsoException { int pollingFrequency = Integer.parseInt(this.environment.getProperty(createPollIntervalProp, CREATE_POLL_INTERVAL_DEFAULT)); @@ -334,7 +331,11 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin { int numberOfPollingAttempts = Math.floorDiv((timeoutMinutes * pollingMultiplier), pollingFrequency); Heat heatClient = getHeatClient(cloudSiteId, tenantId); while (true) { - Stack latestStack = queryHeatStack(heatClient, stack.getStackName() + "/" + stack.getId()); + String stackName = stack.getStackName() + "/" + stack.getId(); + if (stack.getId() == null) { + stackName = stack.getStackName(); + } + Stack latestStack = queryHeatStack(heatClient, stackName); if (latestStack == null && notFoundIsSuccess) { return null; } else if (latestStack != null) { @@ -385,27 +386,33 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin { protected Stack handleUnknownCreateStackFailure(Stack stack, int timeoutMinutes, String cloudSiteId, String tenantId) throws MsoException { if (stack != null && !Strings.isNullOrEmpty(stack.getStackName()) && !Strings.isNullOrEmpty(stack.getId())) { - return deleteStack(stack, timeoutMinutes, cloudSiteId, tenantId); + return deleteStack(stack, timeoutMinutes, cloudSiteId, tenantId, false); } else { throw new StackCreationException("Cannot Find Stack Name or Id"); } } - private Stack deleteStack(Stack stack, int timeoutMinutes, String cloudSiteId, String tenantId) - throws MsoException { + private Stack deleteStack(Stack stack, int timeoutMinutes, String cloudSiteId, String tenantId, + boolean pollForCompletion) throws MsoException { OpenStackRequest request = getHeatClient(cloudSiteId, tenantId).getStacks() .deleteByName(stack.getStackName() + "/" + stack.getId()); executeAndRecordOpenstackRequest(request); - Stack currentStack = pollStackForStatus(timeoutMinutes, stack, DELETE_IN_PROGRESS, cloudSiteId, tenantId, true); - if (currentStack == null) { + logger.debug("Completed Executing executeAndRecordOpenstackRequest"); + if (pollForCompletion == true) { + Stack currentStack = + pollStackForStatus(timeoutMinutes, stack, DELETE_IN_PROGRESS, cloudSiteId, tenantId, true); + if (currentStack == null) { + return currentStack; + } + postProcessStackDelete(currentStack); return currentStack; } else { - postProcessStackDelete(currentStack); + logger.debug("Returning the stack"); + return stack; } - return currentStack; } - protected void postProcessStackDelete(Stack stack) throws MsoException { + public void postProcessStackDelete(Stack stack) throws MsoException { logger.info("Performing post processing on delete stack {}", stack); if (stack != null && !Strings.isNullOrEmpty(stack.getStackStatus())) { if (!DELETE_COMPLETE.equals(stack.getStackStatus())) @@ -503,10 +510,13 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin { stackInfo = new StackInfo(stackName, HeatStatus.NOTFOUND); stackInfo.setOperationPerformed(false); } else { - currentStack = deleteStack(currentStack, timeoutMinutes, cloudSiteId, tenantId); + currentStack = deleteStack(currentStack, timeoutMinutes, cloudSiteId, tenantId, pollForCompletion); stackInfo = new StackInfoMapper(currentStack).map(); stackInfo.setName(stackName); stackInfo.setOperationPerformed(true); + if (currentStack != null) { + stackInfo.setCanonicalName(currentStack.getStackName() + "/" + currentStack.getId()); + } } return stackInfo; } @@ -632,7 +642,7 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin { return queryHeatStack(getHeatClient(cloudSiteId, tenantId), stackName); } - + // TODO enhancement - just have this return the stack then we dont have to query again in deleteStack public Map queryStackForOutputs(String cloudSiteId, String cloudOwner, String tenantId, String stackName) throws MsoException { logger.debug("MsoHeatUtils.queryStackForOutputs)"); diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatUtilsTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatUtilsTest.java index 0f9f7a273e..4938bff748 100644 --- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatUtilsTest.java +++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatUtilsTest.java @@ -7,9 +7,9 @@ * 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. @@ -264,9 +264,9 @@ public class MsoHeatUtilsTest extends MsoHeatUtils { heatUtils.handleUnknownCreateStackFailure(stack, 120, cloudSiteId, tenantId); Mockito.verify(heatUtils, times(1)).executeAndRecordOpenstackRequest(mockDeleteStack); - Mockito.verify(heatUtils, times(1)).pollStackForStatus(120, stack, "DELETE_IN_PROGRESS", cloudSiteId, tenantId, + Mockito.verify(heatUtils, times(0)).pollStackForStatus(120, stack, "DELETE_IN_PROGRESS", cloudSiteId, tenantId, true); - Mockito.verify(heatUtils, times(1)).postProcessStackDelete(deletedStack); + Mockito.verify(heatUtils, times(0)).postProcessStackDelete(deletedStack); } @@ -324,8 +324,6 @@ public class MsoHeatUtilsTest extends MsoHeatUtils { CreateStackParam createStackParam = new CreateStackParam(); createStackParam.setStackName("stackName"); - // doReturn(mockResources).when(heatUtils).queryStackResources(cloudSiteId, tenantId, "stackName", 2); - // doNothing().when(novaClient).deleteKeyPair(cloudSiteId, tenantId, "KeypairName"); doReturn(null).when(heatUtils).handleUnknownCreateStackFailure(stack, 120, cloudSiteId, tenantId); doReturn(createdStack).when(heatUtils).createStack(createStackParam, cloudSiteId, tenantId); doReturn(createdStack).when(heatUtils).processCreateStack(cloudSiteId, tenantId, 120, true, createdStack, diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/VfModuleRollback.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/VfModuleRollback.java index 5f93765688..5f4d9d3eab 100644 --- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/VfModuleRollback.java +++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/VfModuleRollback.java @@ -44,15 +44,15 @@ public class VfModuleRollback { public VfModuleRollback(VnfRollback vrb, String vfModuleId, String vfModuleStackId, String messageId) { this.vnfId = vrb.getVnfId(); - this.vfModuleId = vfModuleId; - this.vfModuleStackId = vfModuleStackId; this.vfModuleCreated = vrb.getVnfCreated(); this.tenantId = vrb.getTenantId(); this.cloudOwner = vrb.getCloudOwner(); this.cloudSiteId = vrb.getCloudSiteId(); this.msoRequest = vrb.getMsoRequest(); - this.messageId = messageId; this.mode = vrb.getMode(); + this.vfModuleId = vfModuleId; + this.vfModuleStackId = vfModuleStackId; + this.messageId = messageId; } public VfModuleRollback(String vnfId, String vfModuleId, String vfModuleStackId, boolean vfModuleCreated, diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AbstractAudit.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AbstractAudit.java deleted file mode 100644 index ad28f0daeb..0000000000 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AbstractAudit.java +++ /dev/null @@ -1,39 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2019 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.adapters.audit; - -import org.onap.so.client.aai.AAIResourcesClient; - -public class AbstractAudit { - - private AAIResourcesClient aaiClient; - - protected AAIResourcesClient getAaiClient() { - if (aaiClient == null) - return new AAIResourcesClient(); - else - return aaiClient; - } - - protected void setAaiClient(AAIResourcesClient aaiResource) { - aaiClient = aaiResource; - } -} diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AbstractAuditService.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AbstractAuditService.java deleted file mode 100644 index ddd9fb1b5e..0000000000 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AbstractAuditService.java +++ /dev/null @@ -1,88 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2019 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.adapters.audit; - -import java.util.Optional; -import org.onap.so.objects.audit.AAIObjectAudit; -import org.onap.so.objects.audit.AAIObjectAuditList; -import org.onap.so.utils.ExternalTaskUtils; -import org.onap.so.utils.RetrySequenceLevel; -import org.onap.logging.filter.base.ONAPComponents; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.core.env.Environment; -import org.springframework.stereotype.Component; - -@Component -public abstract class AbstractAuditService extends ExternalTaskUtils { - - private static final Logger logger = LoggerFactory.getLogger(AbstractAuditService.class); - - - - protected static final String UNABLE_TO_FIND_ALL_V_SERVERS_AND_L_INTERACES_IN_A_AI = - "Unable to find all VServers and L-Interaces in A&AI"; - - protected static final String UNABLE_TO_FIND_V_SERVERS_IN_OPENSTACK = "Unable to find VServers in Openstack"; - - @Autowired - public Environment env; - - public AbstractAuditService() { - super(RetrySequenceLevel.LONG); - } - - /** - * @param auditHeatStackFailed - * @param auditList - * @return - */ - protected boolean didCreateAuditFail(Optional auditList) { - if (auditList.get().getAuditList() != null && !auditList.get().getAuditList().isEmpty()) { - if (logger.isInfoEnabled()) { - logger.info("Audit Results: {}", auditList.get().toString()); - } - return auditList.get().getAuditList().stream().filter(auditObject -> !auditObject.isDoesObjectExist()) - .findFirst().map(v -> true).orElse(false); - } else { - return false; - } - } - - /** - * @param auditHeatStackFailed - * @param auditList - * @return - */ - protected boolean didDeleteAuditFail(AAIObjectAuditList auditList) { - if (auditList.getAuditList() != null && !auditList.getAuditList().isEmpty()) { - if (logger.isInfoEnabled()) { - logger.info("Audit Results: {}", auditList.toString()); - } - return auditList.getAuditList().stream().filter(AAIObjectAudit::isDoesObjectExist).findFirst() - .map(v -> true).orElse(false); - } else { - return false; - } - } -} diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditCreateStackService.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditCreateStackService.java deleted file mode 100644 index 8291fa9882..0000000000 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditCreateStackService.java +++ /dev/null @@ -1,111 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Modifications Copyright (c) 2019 Samsung - * ================================================================================ - * 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.adapters.audit; - -import java.util.HashMap; -import java.util.Map; -import java.util.Optional; -import org.camunda.bpm.client.task.ExternalTask; -import org.camunda.bpm.client.task.ExternalTaskService; -import org.onap.logging.ref.slf4j.ONAPLogConstants; -import org.onap.so.audit.beans.AuditInventory; -import org.onap.so.client.graphinventory.GraphInventoryCommonObjectMapperProvider; -import org.onap.so.externaltasks.logging.AuditMDCSetup; -import org.onap.so.objects.audit.AAIObjectAuditList; -import org.onap.so.utils.RetrySequenceLevel; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -@Component -public class AuditCreateStackService extends AbstractAuditService { - - private static final Logger logger = LoggerFactory.getLogger(AuditCreateStackService.class); - - @Autowired - public HeatStackAudit heatStackAudit; - - @Autowired - private AuditMDCSetup mdcSetup; - - public AuditCreateStackService() { - super(); - } - - protected void executeExternalTask(ExternalTask externalTask, ExternalTaskService externalTaskService) { - mdcSetup.setupMDC(externalTask); - AuditInventory auditInventory = externalTask.getVariable("auditInventory"); - Map variables = new HashMap<>(); - boolean success = false; - try { - Integer retryCount = externalTask.getRetries(); - logger.info("Executing External Task Audit Inventory, Retry Number: {} \n {}", auditInventory, retryCount); - Optional auditListOpt = heatStackAudit.auditHeatStack(auditInventory.getCloudRegion(), - auditInventory.getCloudOwner(), auditInventory.getTenantId(), auditInventory.getHeatStackName()); - if (auditListOpt.isPresent()) { - auditListOpt.get().setAuditType("create"); - auditListOpt.get().setHeatStackName(auditInventory.getHeatStackName()); - GraphInventoryCommonObjectMapperProvider objectMapper = new GraphInventoryCommonObjectMapperProvider(); - variables.put("auditInventoryResult", objectMapper.getMapper().writeValueAsString(auditListOpt.get())); - success = !didCreateAuditFail(auditListOpt); - } - } catch (Exception e) { - logger.error("Error during audit of stack", e); - } - variables.put("auditIsSuccessful", success); - mdcSetup.setElapsedTime(); - String externalTaskId = externalTask.getId(); - if (success) { - externalTaskService.complete(externalTask, variables); - mdcSetup.setResponseCode(ONAPLogConstants.ResponseStatus.COMPLETE.toString()); - logger.debug("The External Task Id: {} Successful", externalTaskId); - logger.info(ONAPLogConstants.Markers.EXIT, "Exiting"); - mdcSetup.clearClientMDCs(); - } else { - Integer retryCount = externalTask.getRetries(); - if (retryCount == null) { - logger.debug("The External Task Id: {} Failed, Setting Retries to Default Start Value: {}", - externalTaskId, getRetrySequence().length); - externalTaskService.handleFailure(externalTask, UNABLE_TO_FIND_ALL_V_SERVERS_AND_L_INTERACES_IN_A_AI, - UNABLE_TO_FIND_ALL_V_SERVERS_AND_L_INTERACES_IN_A_AI, getRetrySequence().length, 10000); - } else if (retryCount == 1) { - externalTaskService.complete(externalTask, variables); - mdcSetup.setResponseCode(ONAPLogConstants.ResponseStatus.ERROR.toString()); - logger.debug("The External Task Id: {} Failed, All Retries Exhausted", externalTaskId); - logger.info(ONAPLogConstants.Markers.EXIT, "Exiting"); - mdcSetup.clearClientMDCs(); - } else { - logger.debug("The External Task Id: {} Failed, Decrementing Retries: {} , Retry Delay: ", - externalTaskId, retryCount - 1, calculateRetryDelay(retryCount)); - externalTaskService.handleFailure(externalTask, UNABLE_TO_FIND_ALL_V_SERVERS_AND_L_INTERACES_IN_A_AI, - UNABLE_TO_FIND_ALL_V_SERVERS_AND_L_INTERACES_IN_A_AI, retryCount - 1, - calculateRetryDelay(retryCount)); - } - logger.debug("The External Task Id: {} Failed", externalTaskId); - } - } - - - -} diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditDataService.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditDataService.java deleted file mode 100644 index 1c707fe795..0000000000 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditDataService.java +++ /dev/null @@ -1,77 +0,0 @@ -package org.onap.so.adapters.audit; - -import java.io.IOException; -import java.util.List; -import java.util.Optional; -import org.onap.so.audit.beans.AuditInventory; -import org.onap.so.client.graphinventory.GraphInventoryCommonObjectMapperProvider; -import org.onap.so.db.request.beans.RequestProcessingData; -import org.onap.so.db.request.client.RequestsDbClient; -import org.onap.so.objects.audit.AAIObjectAuditList; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonMappingException; - -@Component -public class AuditDataService { - - @Autowired - private RequestsDbClient requestsDbClient; - - /** - * Checks to see if an entry already exist for the given heat stack and writes audit stack data to the request - * database if it doesn't. - * - * @throws JsonProcessingException - */ - public void writeStackDataToRequestDb(AuditInventory auditInventory, AAIObjectAuditList auditList) - throws JsonProcessingException { - List requestProcessingDataList = - requestsDbClient.getRequestProcessingDataByGroupingIdAndNameAndTag(auditInventory.getVfModuleId(), - auditInventory.getHeatStackName(), "AuditStackData"); - if (requestProcessingDataList.isEmpty()) { - GraphInventoryCommonObjectMapperProvider objectMapper = new GraphInventoryCommonObjectMapperProvider(); - String auditListString = objectMapper.getMapper().writeValueAsString(auditList);; - - RequestProcessingData requestProcessingData = new RequestProcessingData(); - requestProcessingData.setSoRequestId(auditInventory.getMsoRequestId()); - requestProcessingData.setGroupingId(auditInventory.getVfModuleId()); - requestProcessingData.setName(auditInventory.getHeatStackName()); - requestProcessingData.setTag("AuditStackData"); - requestProcessingData.setValue(auditListString); - - requestsDbClient.saveRequestProcessingData(requestProcessingData); - } - } - - /** - * Retrieves audit stack data from the request database. - * - * @throws IOException - * @throws JsonMappingException - * @throws JsonParseException - */ - public Optional getStackDataFromRequestDb(AuditInventory auditInventory) - throws JsonParseException, JsonMappingException, IOException { - - List requestProcessingDataList = - requestsDbClient.getRequestProcessingDataByGroupingIdAndNameAndTag(auditInventory.getVfModuleId(), - auditInventory.getHeatStackName(), "AuditStackData"); - if (!requestProcessingDataList.isEmpty()) { - RequestProcessingData requestProcessingData = requestProcessingDataList.get(0); - String auditListString = requestProcessingData.getValue(); - - GraphInventoryCommonObjectMapperProvider objectMapper = new GraphInventoryCommonObjectMapperProvider(); - AAIObjectAuditList auditList = - objectMapper.getMapper().readValue(auditListString, AAIObjectAuditList.class); - - return Optional.of(auditList); - } else { - return Optional.empty(); - } - } - - -} diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditDeleteStackService.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditDeleteStackService.java deleted file mode 100644 index cf077915c9..0000000000 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditDeleteStackService.java +++ /dev/null @@ -1,121 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017-2019 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.adapters.audit; - -import java.util.HashMap; -import java.util.Map; -import java.util.Optional; -import org.camunda.bpm.client.task.ExternalTask; -import org.camunda.bpm.client.task.ExternalTaskService; -import org.onap.logging.ref.slf4j.ONAPLogConstants; -import org.onap.so.audit.beans.AuditInventory; -import org.onap.so.client.graphinventory.GraphInventoryCommonObjectMapperProvider; -import org.onap.so.externaltasks.logging.AuditMDCSetup; -import org.onap.so.objects.audit.AAIObjectAuditList; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.core.env.Environment; -import org.springframework.stereotype.Component; - -@Component -public class AuditDeleteStackService extends AbstractAuditService { - - private static final Logger logger = LoggerFactory.getLogger(AuditDeleteStackService.class); - - @Autowired - protected HeatStackAudit heatStackAudit; - - @Autowired - private AuditMDCSetup mdcSetup; - - @Autowired - protected AuditVServer auditVservers; - - @Autowired - protected AuditDataService auditDataService; - - @Autowired - protected Environment env; - - public AuditDeleteStackService() { - super(); - } - - protected void executeExternalTask(ExternalTask externalTask, ExternalTaskService externalTaskService) { - mdcSetup.setupMDC(externalTask); - AuditInventory auditInventory = externalTask.getVariable("auditInventory"); - Map variables = new HashMap<>(); - boolean success = false; - try { - Integer retryCount = externalTask.getRetries(); - logger.info("Executing External Task Delete Audit Inventory. Retry Number: {}", retryCount); - Optional auditListOpt = auditDataService.getStackDataFromRequestDb(auditInventory); - if (auditListOpt.isPresent()) { - auditVservers.auditVservers(auditListOpt.get()); - } else { - logger.debug("Auditing Vservers based on vf module relationships"); - auditListOpt = auditVservers.auditVserversThroughRelationships(auditInventory.getGenericVnfId(), - auditInventory.getHeatStackName()); - } - auditListOpt.get().setHeatStackName(auditInventory.getHeatStackName()); - auditListOpt.get().setAuditType("delete"); - GraphInventoryCommonObjectMapperProvider objectMapper = new GraphInventoryCommonObjectMapperProvider(); - variables.put("auditInventoryResult", objectMapper.getMapper().writeValueAsString(auditListOpt.get())); - success = !didDeleteAuditFail(auditListOpt.get()); - - } catch (Exception e) { - logger.error("Error during audit of stack", e); - } - variables.put("auditIsSuccessful", success); - mdcSetup.setElapsedTime(); - String externalTaskId = externalTask.getId(); - if (success) { - externalTaskService.complete(externalTask, variables); - mdcSetup.setResponseCode(ONAPLogConstants.ResponseStatus.COMPLETE.toString()); - logger.debug("The External Task Id: {} Successful", externalTaskId); - logger.info(ONAPLogConstants.Markers.EXIT, "Exiting"); - mdcSetup.clearClientMDCs(); - } else { - Integer retryCount = externalTask.getRetries(); - if (retryCount == null) { - logger.debug("The External Task Id: {} Failed, Setting Retries to Default Start Value: {}", - externalTaskId, getRetrySequence().length); - externalTaskService.handleFailure(externalTask, UNABLE_TO_FIND_ALL_V_SERVERS_AND_L_INTERACES_IN_A_AI, - UNABLE_TO_FIND_ALL_V_SERVERS_AND_L_INTERACES_IN_A_AI, getRetrySequence().length, 10000); - } else if (retryCount == 1) { - externalTaskService.complete(externalTask, variables); - mdcSetup.setResponseCode(ONAPLogConstants.ResponseStatus.ERROR.toString()); - logger.debug("The External Task Id: {} Failed, All Retries Exhausted", externalTaskId); - logger.info(ONAPLogConstants.Markers.EXIT, "Exiting"); - mdcSetup.clearClientMDCs(); - } else { - logger.debug("The External Task Id: {} Failed, Decrementing Retries: {} , Retry Delay: ", - externalTaskId, retryCount - 1, calculateRetryDelay(retryCount)); - externalTaskService.handleFailure(externalTask, UNABLE_TO_FIND_ALL_V_SERVERS_AND_L_INTERACES_IN_A_AI, - UNABLE_TO_FIND_ALL_V_SERVERS_AND_L_INTERACES_IN_A_AI, retryCount - 1, - calculateRetryDelay(retryCount)); - } - logger.debug("The External Task Id: {} Failed", externalTaskId); - } - } - -} diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditQueryStackService.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditQueryStackService.java deleted file mode 100644 index 1c69a3e5e7..0000000000 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditQueryStackService.java +++ /dev/null @@ -1,85 +0,0 @@ -package org.onap.so.adapters.audit; - -import java.util.HashMap; -import java.util.Map; -import java.util.Optional; -import org.camunda.bpm.client.task.ExternalTask; -import org.camunda.bpm.client.task.ExternalTaskService; -import org.onap.logging.ref.slf4j.ONAPLogConstants; -import org.onap.so.audit.beans.AuditInventory; -import org.onap.so.externaltasks.logging.AuditMDCSetup; -import org.onap.so.objects.audit.AAIObjectAuditList; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -@Component -public class AuditQueryStackService extends AbstractAuditService { - - private static final Logger logger = LoggerFactory.getLogger(AuditQueryStackService.class); - - @Autowired - protected HeatStackAudit heatStackAudit; - - @Autowired - private AuditMDCSetup mdcSetup; - - @Autowired - protected AuditDataService auditDataService; - - public AuditQueryStackService() { - super(); - } - - protected void executeExternalTask(ExternalTask externalTask, ExternalTaskService externalTaskService) { - mdcSetup.setupMDC(externalTask); - AuditInventory auditInventory = externalTask.getVariable("auditInventory"); - boolean success = false; - Map variables = new HashMap<>(); - try { - Integer retryCount = externalTask.getRetries(); - logger.info("Executing External Task Query Audit Inventory. Audit Inventory: {} \n Retry Number: {}", - auditInventory.toString(), retryCount); - - Optional auditList = heatStackAudit.queryHeatStack(auditInventory.getCloudOwner(), - auditInventory.getCloudRegion(), auditInventory.getTenantId(), auditInventory.getHeatStackName()); - - if (auditList.isPresent()) { - mdcSetup.setResponseCode(ONAPLogConstants.ResponseStatus.COMPLETE.toString()); - success = true; - auditDataService.writeStackDataToRequestDb(auditInventory, auditList.get()); - } - mdcSetup.setElapsedTime(); - String externalTaskId = externalTask.getId(); - if (success) { - externalTaskService.complete(externalTask, variables); - mdcSetup.setResponseCode(ONAPLogConstants.ResponseStatus.COMPLETE.toString()); - logger.debug("The External Task {} was Successful", externalTaskId); - logger.info(ONAPLogConstants.Markers.EXIT, "Exiting"); - mdcSetup.clearClientMDCs(); - } else { - if (retryCount == null) { - logger.debug("The External Task {} Failed. Setting Retries to Default Start Value: {}", - externalTaskId, getRetrySequence().length); - externalTaskService.handleFailure(externalTask, UNABLE_TO_FIND_V_SERVERS_IN_OPENSTACK, - UNABLE_TO_FIND_V_SERVERS_IN_OPENSTACK, getRetrySequence().length, 10000); - } else if (retryCount == 1) { - externalTaskService.complete(externalTask, variables); - mdcSetup.setResponseCode(ONAPLogConstants.ResponseStatus.ERROR.toString()); - logger.debug("The External Task {} Failed. All Retries Exhausted", externalTaskId); - logger.info(ONAPLogConstants.Markers.EXIT, "Exiting"); - mdcSetup.clearClientMDCs(); - } else { - logger.debug("The External Task {} Failed. Decrementing Retries to {} , Retry Delay: ", - externalTaskId, retryCount - 1, calculateRetryDelay(retryCount)); - externalTaskService.handleFailure(externalTask, UNABLE_TO_FIND_V_SERVERS_IN_OPENSTACK, - UNABLE_TO_FIND_V_SERVERS_IN_OPENSTACK, retryCount - 1, calculateRetryDelay(retryCount)); - } - logger.debug("The External Task {} Failed", externalTaskId); - } - } catch (Exception e) { - logger.error("Error during audit query of stack", e); - } - } -} diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditStackService.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditStackService.java deleted file mode 100644 index 7cc7c02f23..0000000000 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditStackService.java +++ /dev/null @@ -1,91 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2019 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.adapters.audit; - -import javax.annotation.PostConstruct; -import org.camunda.bpm.client.ExternalTaskClient; -import org.onap.so.utils.ExternalTaskServiceUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Profile; -import org.springframework.core.env.Environment; -import org.springframework.stereotype.Component; - -@Component -@Profile("!test") -public class AuditStackService { - - private static final String MSO_AUDIT_LOCK_TIME = "mso.audit.lock-time"; - - private static final Logger logger = LoggerFactory.getLogger(AuditStackService.class); - - private static final String DEFAULT_AUDIT_LOCK_TIME = "60000"; - - private static final String DEFAULT_MAX_CLIENTS_FOR_TOPIC = "10"; - - - @Autowired - public Environment env; - - @Autowired - private AuditCreateStackService auditCreateStack; - - @Autowired - private AuditDeleteStackService auditDeleteStack; - - @Autowired - private AuditQueryStackService auditQueryStack; - - @Autowired - private ExternalTaskServiceUtils externalTaskServiceUtils; - - @PostConstruct - public void auditAddAAIInventory() throws Exception { - for (int i = 0; i < externalTaskServiceUtils.getMaxClients(); i++) { - ExternalTaskClient client = externalTaskServiceUtils.createExternalTaskClient(); - client.subscribe("InventoryAddAudit") - .lockDuration(Long.parseLong(env.getProperty(MSO_AUDIT_LOCK_TIME, DEFAULT_AUDIT_LOCK_TIME))) - .handler(auditCreateStack::executeExternalTask).open(); - } - } - - @PostConstruct - public void auditDeleteAAIInventory() throws Exception { - for (int i = 0; i < externalTaskServiceUtils.getMaxClients(); i++) { - ExternalTaskClient client = externalTaskServiceUtils.createExternalTaskClient(); - client.subscribe("InventoryDeleteAudit") - .lockDuration(Long.parseLong(env.getProperty(MSO_AUDIT_LOCK_TIME, DEFAULT_AUDIT_LOCK_TIME))) - .handler(auditDeleteStack::executeExternalTask).open(); - } - } - - @PostConstruct - public void auditQueryInventory() throws Exception { - for (int i = 0; i < externalTaskServiceUtils.getMaxClients(); i++) { - ExternalTaskClient client = externalTaskServiceUtils.createExternalTaskClient(); - client.subscribe("InventoryQueryAudit") - .lockDuration(Long.parseLong(env.getProperty(MSO_AUDIT_LOCK_TIME, DEFAULT_AUDIT_LOCK_TIME))) - .handler(auditQueryStack::executeExternalTask).open(); - } - } - -} diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditVServer.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditVServer.java deleted file mode 100644 index 585e001f1a..0000000000 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditVServer.java +++ /dev/null @@ -1,171 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2019 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.adapters.audit; - -import java.util.List; -import java.util.Optional; -import java.util.Set; -import org.onap.aai.domain.yang.LInterface; -import org.onap.aai.domain.yang.VfModule; -import org.onap.aai.domain.yang.VfModules; -import org.onap.aai.domain.yang.Vserver; -import org.onap.so.client.aai.AAIObjectPlurals; -import org.onap.so.client.aai.AAIObjectType; -import org.onap.so.client.aai.entities.AAIResultWrapper; -import org.onap.so.client.aai.entities.uri.AAIPluralResourceUri; -import org.onap.so.client.aai.entities.uri.AAIResourceUri; -import org.onap.so.client.aai.entities.uri.AAIUriFactory; -import org.onap.so.client.graphinventory.GraphInventoryCommonObjectMapperProvider; -import org.onap.so.objects.audit.AAIObjectAudit; -import org.onap.so.objects.audit.AAIObjectAuditList; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.BeanUtils; -import org.springframework.stereotype.Component; -import com.fasterxml.jackson.core.JsonProcessingException; - -@Component -public class AuditVServer extends AbstractAudit { - private static final Logger logger = LoggerFactory.getLogger(AuditVServer.class); - - public void auditVservers(AAIObjectAuditList aaiObjectAuditList) { - - aaiObjectAuditList.getAuditList().forEach(aaiObjectAudit -> { - boolean vserverExist = getAaiClient().exists(AAIUriFactory - .createResourceFromExistingURI(AAIObjectType.VSERVER, aaiObjectAudit.getResourceURI())); - aaiObjectAudit.setDoesObjectExist(vserverExist); - }); - } - - public Optional auditVserversThroughRelationships(String genericVnfId, String vfModuleName) { - AAIObjectAuditList auditList = new AAIObjectAuditList(); - AAIPluralResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectPlurals.VF_MODULE, genericVnfId) - .queryParam("vf-module-name", vfModuleName); - Optional wrapper = getAaiClient().getFirstWrapper(VfModules.class, VfModule.class, uri); - if (wrapper.isPresent() && wrapper.get().getRelationships().isPresent()) { - List relatedVservers = - wrapper.get().getRelationships().get().getRelatedUris(AAIObjectType.VSERVER); - if (!relatedVservers.isEmpty()) { - relatedVservers.forEach(vserverUri -> { - Optional vserver = getAaiClient().get(vserverUri).asBean(Vserver.class); - Vserver vServerShallow = new Vserver(); - BeanUtils.copyProperties(vserver, vServerShallow); - AAIObjectAudit vServerAudit = new AAIObjectAudit(); - vServerAudit.setAaiObject(vServerShallow); - vServerAudit.setAaiObjectType(AAIObjectType.VSERVER.typeName()); - vServerAudit.setDoesObjectExist(true); - auditList.getAuditList().add(vServerAudit); - }); - } - } - return Optional.of(auditList); - } - - public Optional auditVservers(Set vServersToAudit, String tenantId, String cloudOwner, - String cloudRegion) { - if (vServersToAudit == null || vServersToAudit.isEmpty()) { - return Optional.empty(); - } - GraphInventoryCommonObjectMapperProvider objectMapper = new GraphInventoryCommonObjectMapperProvider(); - vServersToAudit.stream().forEach(vserver -> { - try { - logger.debug("Vserver to Audit: {}", objectMapper.getMapper().writeValueAsString(vserver)); - } catch (JsonProcessingException e) { - logger.error("Json parse exception: ", e); - } - - }); - AAIObjectAuditList auditList = new AAIObjectAuditList(); - vServersToAudit.stream().forEach(vServer -> auditList.getAuditList() - .addAll(doesVServerExistInAAI(vServer, tenantId, cloudOwner, cloudRegion).getAuditList())); - return Optional.of(auditList); - } - - private AAIObjectAuditList doesVServerExistInAAI(Vserver vServer, String tenantId, String cloudOwner, - String cloudRegion) { - AAIObjectAuditList auditList = new AAIObjectAuditList(); - AAIObjectAudit vServerAudit = new AAIObjectAudit(); - AAIResourceUri vserverURI = AAIUriFactory.createResourceUri(AAIObjectType.VSERVER, cloudOwner, cloudRegion, - tenantId, vServer.getVserverId()); - Vserver vServerShallow = new Vserver(); - BeanUtils.copyProperties(vServer, vServerShallow, "LInterfaces"); - boolean vServerExists = getAaiClient().exists(vserverURI); - logger.info("v-server {} exists: {}", vServer.getVserverId(), vServerExists); - vServerAudit.setAaiObject(vServerShallow); - vServerAudit.setDoesObjectExist(vServerExists); - vServerAudit.setResourceURI(vserverURI.build()); - vServerAudit.setAaiObjectType(AAIObjectType.VSERVER.typeName()); - auditList.getAuditList().add(vServerAudit); - if (vServer.getLInterfaces() != null) { - vServer.getLInterfaces().getLInterface().stream().forEach(lInterface -> auditList.getAuditList().addAll( - doesLinterfaceExistinAAI(lInterface, vServer.getVserverId(), tenantId, cloudOwner, cloudRegion) - .getAuditList())); - } - return auditList; - } - - private AAIObjectAuditList doesLinterfaceExistinAAI(LInterface lInterface, String vServerId, String tenantId, - String cloudOwner, String cloudRegion) { - AAIObjectAuditList auditList = new AAIObjectAuditList(); - AAIObjectAudit lInterfaceAudit = new AAIObjectAudit(); - AAIResourceUri linterfaceURI = AAIUriFactory.createResourceUri(AAIObjectType.L_INTERFACE, cloudOwner, - cloudRegion, tenantId, vServerId, lInterface.getInterfaceName()); - Optional queriedLInterface = getAaiClient().get(LInterface.class, linterfaceURI); - if (queriedLInterface.isPresent()) { - lInterfaceAudit.setDoesObjectExist(true); - lInterface.setInterfaceName(lInterface.getInterfaceName()); - } - lInterfaceAudit.setAaiObject(lInterface); - lInterfaceAudit.setResourceURI(linterfaceURI.build()); - lInterfaceAudit.setAaiObjectType(AAIObjectType.L_INTERFACE.typeName()); - auditList.getAuditList().add(lInterfaceAudit); - logger.info("l-interface id:{} name: {} exists: {} ", lInterface.getInterfaceId(), - lInterface.getInterfaceName(), lInterfaceAudit.isDoesObjectExist()); - - if (lInterface.getLInterfaces() != null) { - lInterface.getLInterfaces().getLInterface().stream() - .forEach(subInterface -> auditList.getAuditList().add(doesSubInterfaceExistinAAI(subInterface, - lInterface.getInterfaceName(), vServerId, tenantId, cloudOwner, cloudRegion))); - } - logger.debug("l-interface {} does not contain any sub-iterfaces, skipping audit of sub-interfaces", - lInterface.getInterfaceId()); - - return auditList; - } - - private AAIObjectAudit doesSubInterfaceExistinAAI(LInterface subInterface, String linterfaceName, String vServerId, - String tenantId, String cloudOwner, String cloudRegion) { - logger.info("checking if sub-l-interface {} , linterfaceName: {} vserverId: {} exists", - subInterface.getInterfaceName(), linterfaceName, vServerId); - AAIObjectAudit subInterfaceAudit = new AAIObjectAudit(); - - - AAIResourceUri subInterfaceURI = AAIUriFactory.createResourceUri(AAIObjectType.SUB_L_INTERFACE, cloudOwner, - cloudRegion, tenantId, vServerId, linterfaceName, subInterface.getInterfaceName()); - subInterfaceAudit.setResourceURI(subInterfaceURI.build()); - boolean doesExist = getAaiClient().exists(subInterfaceURI); - logger.info("sub-l-interface-id:{} exists: {}", subInterface.getInterfaceId(), doesExist); - subInterfaceAudit.setAaiObject(subInterface); - subInterfaceAudit.setDoesObjectExist(doesExist); - subInterfaceAudit.setAaiObjectType(AAIObjectType.SUB_L_INTERFACE.typeName()); - return subInterfaceAudit; - } -} diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/HeatStackAudit.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/HeatStackAudit.java deleted file mode 100644 index ffa76cf8ee..0000000000 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/HeatStackAudit.java +++ /dev/null @@ -1,327 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * - * Modifications Copyright (C) 2019 IBM. - * ================================================================================ - * 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.adapters.audit; - -import java.net.URI; -import java.util.Arrays; -import java.util.HashSet; -import java.util.List; -import java.util.Optional; -import java.util.Set; -import java.util.regex.Matcher; -import java.util.regex.Pattern; -import java.util.stream.Collectors; -import java.util.stream.Stream; -import org.onap.aai.domain.yang.LInterface; -import org.onap.aai.domain.yang.LInterfaces; -import org.onap.aai.domain.yang.Vlan; -import org.onap.aai.domain.yang.Vlans; -import org.onap.aai.domain.yang.Vserver; -import org.onap.so.client.aai.AAIObjectType; -import org.onap.so.client.aai.entities.uri.AAIUriFactory; -import org.onap.so.objects.audit.AAIObjectAudit; -import org.onap.so.objects.audit.AAIObjectAuditList; -import org.onap.so.openstack.utils.MsoHeatUtils; -import org.onap.so.openstack.utils.MsoNeutronUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.BeanUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; -import com.woorea.openstack.heat.model.Link; -import com.woorea.openstack.heat.model.Resource; -import com.woorea.openstack.heat.model.Resources; -import com.woorea.openstack.heat.model.Stack; -import com.woorea.openstack.quantum.model.Port; - -@Component -public class HeatStackAudit { - - private static final String RESOURCES = "/resources"; - - protected static final Logger logger = LoggerFactory.getLogger(HeatStackAudit.class); - - private static final String EXCEPTION_MSG = "Error finding Path from Self Link"; - - @Autowired - protected MsoHeatUtils heat; - - @Autowired - protected MsoNeutronUtils neutron; - - @Autowired - protected AuditVServer auditVservers; - - public Optional queryHeatStack(String cloudOwner, String cloudRegion, String tenantId, - String heatStackName) { - try { - logger.debug("Fetching Top Level Stack Information"); - Resources resources = heat.queryStackResources(cloudRegion, tenantId, heatStackName, 3); - List novaResources = resources.getList().stream() - .filter(p -> "OS::Nova::Server".equals(p.getType())).collect(Collectors.toList()); - if (novaResources.isEmpty()) - return Optional.of(new AAIObjectAuditList()); - else { - Set vserversToAudit = createVserverSet(novaResources); - AAIObjectAuditList aaiObjectAuditList = new AAIObjectAuditList(); - vserversToAudit.stream().forEach(vServer -> aaiObjectAuditList.getAuditList() - .add(createAAIObjectAudit(cloudOwner, cloudRegion, tenantId, vServer))); - return Optional.of(aaiObjectAuditList); - } - } catch (Exception e) { - logger.error("Error during query stack resources", e); - return Optional.of(new AAIObjectAuditList()); - } - } - - public Optional auditHeatStack(String cloudRegion, String cloudOwner, String tenantId, - String heatStackName) { - try { - logger.debug("Fetching Top Level Stack Information"); - Resources resources = heat.queryStackResources(cloudRegion, tenantId, heatStackName, 3); - List novaResources = resources.getList().stream() - .filter(p -> "OS::Nova::Server".equals(p.getType())).collect(Collectors.toList()); - List resourceGroups = resources.getList().stream() - .filter(p -> "OS::Heat::ResourceGroup".equals(p.getType()) && p.getName().contains("subinterfaces")) - .collect(Collectors.toList()); - List> neutronPortDetails = retrieveNeutronPortDetails(resources, cloudRegion, tenantId); - if (novaResources.isEmpty()) - return Optional.of(new AAIObjectAuditList()); - else { - Set vserversToAudit = createVserverSet(resources, novaResources, neutronPortDetails); - Set vserversWithSubInterfaces = - processSubInterfaces(cloudRegion, tenantId, resourceGroups, vserversToAudit); - return auditVservers.auditVservers(vserversWithSubInterfaces, tenantId, cloudOwner, cloudRegion); - } - } catch (Exception e) { - logger.error("Error during auditing stack resources", e); - return Optional.empty(); - } - } - - protected Set processSubInterfaces(String cloudRegion, String tenantId, List resourceGroups, - Set vServersToAudit) throws Exception { - for (Resource resourceGroup : resourceGroups) { - processResourceGroups(cloudRegion, tenantId, vServersToAudit, resourceGroup); - } - return vServersToAudit; - } - - protected void processResourceGroups(String cloudRegion, String tenantId, Set vServersWithLInterface, - Resource resourceGroup) throws Exception { - Optional stackLink = - resourceGroup.getLinks().stream().filter(link -> "nested".equals(link.getRel())).findAny(); - if (stackLink.isPresent()) { - try { - Optional path = extractResourcePathFromHref(stackLink.get().getHref()); - if (path.isPresent()) { - logger.debug("Fetching nested Resource Stack Information"); - Resources nestedResourceGroupResources = - heat.executeHeatClientRequest(path.get(), cloudRegion, tenantId, Resources.class); - processNestedResourceGroup(cloudRegion, tenantId, vServersWithLInterface, - nestedResourceGroupResources); - } else - throw new Exception(EXCEPTION_MSG); - } catch (Exception e) { - logger.error("Error Parsing Link to obtain Path", e); - throw new Exception(EXCEPTION_MSG); - } - } - } - - protected void processNestedResourceGroup(String cloudRegion, String tenantId, Set vServersWithLInterface, - Resources nestedResourceGroupResources) throws Exception { - for (Resource resourceGroupNested : nestedResourceGroupResources) { - Optional subInterfaceStackLink = - resourceGroupNested.getLinks().stream().filter(link -> "nested".equals(link.getRel())).findAny(); - if (subInterfaceStackLink.isPresent()) { - addSubInterface(cloudRegion, tenantId, vServersWithLInterface, subInterfaceStackLink.get()); - } - } - } - - protected void addSubInterface(String cloudRegion, String tenantId, Set vServersWithLInterface, - Link subInterfaceStackLink) throws Exception { - Optional resourcePath = extractResourcePathFromHref(subInterfaceStackLink.getHref()); - Optional stackPath = extractStackPathFromHref(subInterfaceStackLink.getHref()); - if (resourcePath.isPresent() && stackPath.isPresent()) { - logger.debug("Fetching nested Sub-Interface Stack Information"); - Stack subinterfaceStack = - heat.executeHeatClientRequest(stackPath.get(), cloudRegion, tenantId, Stack.class); - Resources subinterfaceResources = - heat.executeHeatClientRequest(resourcePath.get(), cloudRegion, tenantId, Resources.class); - if (subinterfaceStack != null) { - addSubInterfaceToVserver(vServersWithLInterface, subinterfaceStack, subinterfaceResources); - } - } else - throw new Exception(EXCEPTION_MSG); - - } - - protected void addSubInterfaceToVserver(Set vServersWithLInterface, Stack subinterfaceStack, - Resources subinterfaceResources) throws Exception { - String parentNeutronPortId = (String) subinterfaceStack.getParameters().get("port_interface"); - logger.debug("Parent neutron Port: {} on SubInterface: {}", parentNeutronPortId, subinterfaceStack.getId()); - for (Vserver auditVserver : vServersWithLInterface) - for (LInterface lInterface : auditVserver.getLInterfaces().getLInterface()) - - if (parentNeutronPortId.equals(lInterface.getInterfaceId())) { - logger.debug("Found Parent Port on VServer: {} on Port: {}", auditVserver.getVserverId(), - lInterface.getInterfaceId()); - Resource contrailVm = subinterfaceResources.getList().stream() - .filter(resource -> "OS::ContrailV2::VirtualMachineInterface".equals(resource.getType())) - .findAny().orElse(null); - if (contrailVm == null) { - throw new Exception("Cannnot find Contrail Virtual Machine Interface on Stack: " - + subinterfaceStack.getId()); - } - LInterface subInterface = new LInterface(); - subInterface.setInterfaceId(contrailVm.getPhysicalResourceId()); - subInterface.setIsPortMirrored(false); - subInterface.setInMaint(false); - subInterface.setIsIpUnnumbered(false); - String macAddr = (String) subinterfaceStack.getParameters().get("mac_address"); - subInterface.setMacaddr(macAddr); - - String namePrefix = (String) subinterfaceStack.getParameters().get("subinterface_name_prefix"); - Integer vlanIndex = Integer.parseInt((String) subinterfaceStack.getParameters().get("counter")); - String vlanTagList = (String) subinterfaceStack.getParameters().get("vlan_tag"); - List subInterfaceVlanTagList = Arrays.asList(vlanTagList.split(",")); - subInterface.setInterfaceName(namePrefix + "_" + subInterfaceVlanTagList.get(vlanIndex)); - subInterface.setVlans(new Vlans()); - Vlan vlan = new Vlan(); - vlan.setInMaint(false); - vlan.setIsIpUnnumbered(false); - vlan.setVlanIdInner(Long.parseLong(subInterfaceVlanTagList.get(vlanIndex))); - vlan.setVlanInterface(namePrefix + "_" + subInterfaceVlanTagList.get(vlanIndex)); - subInterface.getVlans().getVlan().add(vlan); - if (lInterface.getLInterfaces() == null) - lInterface.setLInterfaces(new LInterfaces()); - - lInterface.getLInterfaces().getLInterface().add(subInterface); - } else - logger.debug("Did Not Find Parent Port on VServer: {} Parent Port: SubInterface: {}", - auditVserver.getVserverId(), lInterface.getInterfaceId(), subinterfaceStack.getId()); - } - - protected Set createVserverSet(Resources resources, List novaResources, - List> neutronPortDetails) { - Set vserversToAudit = new HashSet<>(); - for (Resource novaResource : novaResources) { - Vserver auditVserver = new Vserver(); - auditVserver.setLInterfaces(new LInterfaces()); - auditVserver.setVserverId(novaResource.getPhysicalResourceId()); - Stream filteredNeutronPorts = filterNeutronPorts(novaResource, neutronPortDetails); - filteredNeutronPorts.forEach(port -> { - LInterface lInterface = new LInterface(); - lInterface.setInterfaceId(port.getId()); - lInterface.setInterfaceName(port.getName()); - auditVserver.getLInterfaces().getLInterface().add(lInterface); - }); - vserversToAudit.add(auditVserver); - } - return vserversToAudit; - } - - protected Set createVserverSet(List novaResources) { - Set vserversToAudit = new HashSet<>(); - for (Resource novaResource : novaResources) { - Vserver auditVserver = new Vserver(); - auditVserver.setLInterfaces(new LInterfaces()); - auditVserver.setVserverId(novaResource.getPhysicalResourceId()); - vserversToAudit.add(auditVserver); - } - return vserversToAudit; - } - - protected AAIObjectAudit createAAIObjectAudit(String cloudOwner, String cloudRegion, String tenantId, - Vserver vServer) { - AAIObjectAudit aaiObjectAudit = new AAIObjectAudit(); - Vserver vServerShallow = new Vserver(); - BeanUtils.copyProperties(vServer, vServerShallow); - aaiObjectAudit.setAaiObject(vServerShallow); - aaiObjectAudit.setAaiObjectType(AAIObjectType.VSERVER.typeName()); - aaiObjectAudit.setResourceURI(AAIUriFactory - .createResourceUri(AAIObjectType.VSERVER, cloudOwner, cloudRegion, tenantId, vServer.getVserverId()) - .build()); - - return aaiObjectAudit; - } - - /** - * @param novaResource Single openstack resource that is of type Nova - * @param neutronPorts List of Neutron ports created within the stack - * @return Filtered list of neutron ports taht relate to the nova server in openstack - */ - protected Stream filterNeutronPorts(Resource novaResource, List> neutronPorts) { - List filteredNeutronPorts = - neutronPorts.stream().filter(Optional::isPresent).map(Optional::get).collect(Collectors.toList()); - return filteredNeutronPorts.stream() - .filter(port -> port.getDeviceId().equalsIgnoreCase(novaResource.getPhysicalResourceId())); - } - - /** - * @param resources Resource stream created by the stack in openstack - * @param cloudSiteId Unique site id to identify which openstack we talk to - * @param tenantId The tenant within the cloud we are talking to where resouces exist - * @return List of optional neutron ports found within the cloud site and tenant - */ - protected List> retrieveNeutronPortDetails(Resources resources, String cloudSiteId, - String tenantId) { - return resources.getList().parallelStream().filter(resource -> "OS::Neutron::Port".equals(resource.getType())) - .map(resource -> neutron.getNeutronPort(resource.getPhysicalResourceId(), tenantId, cloudSiteId)) - .collect(Collectors.toList()); - - } - - protected Optional extractResourcePathFromHref(String href) { - try { - Optional stackPath = extractStackPathFromHref(href); - if (stackPath.isPresent()) { - return Optional.of(stackPath.get() + RESOURCES); - } else - return Optional.empty(); - } catch (Exception e) { - logger.error("Error parsing URI", e); - } - return Optional.empty(); - } - - protected Optional extractStackPathFromHref(String href) { - try { - URI uri = new URI(href); - Pattern p = Pattern.compile("/stacks.*"); - Matcher m = p.matcher(uri.getPath()); - if (m.find()) { - return Optional.of(m.group()); - } else - return Optional.empty(); - } catch (Exception e) { - logger.error("Error parsing URI", e); - } - return Optional.empty(); - } - - -} - diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/CreateAAIInventory.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/CreateAAIInventory.java deleted file mode 100644 index 69e16986da..0000000000 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/CreateAAIInventory.java +++ /dev/null @@ -1,73 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2019 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.adapters.inventory.create; - -import java.util.Optional; -import java.util.stream.Stream; -import org.onap.so.client.aai.AAIObjectType; -import org.onap.so.client.aai.AAIResourcesClient; -import org.onap.so.client.aai.entities.uri.AAIUriFactory; -import org.onap.so.objects.audit.AAIObjectAudit; -import org.onap.so.objects.audit.AAIObjectAuditList; -import org.springframework.stereotype.Component; - -@Component -public class CreateAAIInventory { - - private AAIResourcesClient aaiClient; - - public void createInventory(AAIObjectAuditList auditList) throws InventoryException { - if (didAuditFailVserverLInterfaces(auditList)) { - throw new InventoryException("Audit failed for VServer or LInterface cannot write Sub-Interfaces"); - } - auditList.getAuditList().parallelStream() - .filter(auditObject -> !auditObject.isDoesObjectExist() - && AAIObjectType.SUB_L_INTERFACE.typeName().equals(auditObject.getAaiObjectType())) - .forEach(auditObject -> getAaiClient().createIfNotExists(AAIUriFactory.createResourceFromExistingURI( - AAIObjectType.fromTypeName(auditObject.getAaiObjectType()), auditObject.getResourceURI()), - Optional.of(auditObject.getAaiObject()))); - } - - - /** - * @param auditHeatStackFailed - * @param auditList - * @return - */ - protected boolean didAuditFailVserverLInterfaces(AAIObjectAuditList auditList) { - Stream issue = auditList.getAuditList().stream() - .filter(auditObject -> auditObject.getAaiObjectType().equals(AAIObjectType.VSERVER.typeName()) - || auditObject.getAaiObjectType().equals(AAIObjectType.L_INTERFACE.typeName())); - - return issue.filter(auditObject -> !auditObject.isDoesObjectExist()).findFirst().map(v -> true).orElse(false); - } - - protected AAIResourcesClient getAaiClient() { - if (aaiClient == null) - return new AAIResourcesClient(); - else - return aaiClient; - } - - protected void setAaiClient(AAIResourcesClient aaiResource) { - aaiClient = aaiResource; - } -} diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/CreateInventoryService.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/CreateInventoryService.java deleted file mode 100644 index 4ab4d14dac..0000000000 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/CreateInventoryService.java +++ /dev/null @@ -1,52 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2019 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.adapters.inventory.create; - -import javax.annotation.PostConstruct; -import org.camunda.bpm.client.ExternalTaskClient; -import org.onap.so.utils.ExternalTaskServiceUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Profile; -import org.springframework.core.env.Environment; -import org.springframework.stereotype.Component; - -@Component -@Profile("!test") -public class CreateInventoryService { - - @Autowired - public Environment env; - - @Autowired - private CreateInventoryTask createInventory; - - @Autowired - private ExternalTaskServiceUtils externalTaskServiceUtils; - - @PostConstruct - public void auditAAIInventory() throws Exception { - ExternalTaskClient client = externalTaskServiceUtils.createExternalTaskClient(); - client.subscribe("InventoryCreate") - .lockDuration(Long.parseLong(env.getProperty("mso.audit.lock-time", "60000"))) - .handler(createInventory::executeExternalTask).open(); - } - -} diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/CreateInventoryTask.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/CreateInventoryTask.java deleted file mode 100644 index e02258c619..0000000000 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/CreateInventoryTask.java +++ /dev/null @@ -1,121 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. - * - * Copyright (C) 2019 IBM - * ================================================================================ - * 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.adapters.inventory.create; - -import org.camunda.bpm.client.task.ExternalTask; -import org.camunda.bpm.client.task.ExternalTaskService; -import org.onap.logging.ref.slf4j.ONAPLogConstants; -import org.onap.so.client.graphinventory.GraphInventoryCommonObjectMapperProvider; -import org.onap.so.externaltasks.logging.AuditMDCSetup; -import org.onap.so.objects.audit.AAIObjectAuditList; -import org.onap.so.utils.ExternalTaskUtils; -import org.onap.so.utils.RetrySequenceLevel; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.stereotype.Component; - -@Component -public class CreateInventoryTask extends ExternalTaskUtils { - - private static final String UNABLE_TO_WRITE_ALL_INVENTORY_TO_A_AI = "Unable to write all inventory to A&AI"; - - private static final Logger logger = LoggerFactory.getLogger(CreateInventoryTask.class); - - private static final String AAI_INVENTORY_FAILURE = "AAIInventoryFailure"; - - @Autowired - CreateAAIInventory createInventory; - - @Autowired - private AuditMDCSetup mdcSetup; - - public CreateInventoryTask() { - super(RetrySequenceLevel.SHORT); - } - - protected void executeExternalTask(ExternalTask externalTask, ExternalTaskService externalTaskService) { - mdcSetup.setupMDC(externalTask); - boolean success = true; - boolean inventoryException = false; - String auditInventoryString = externalTask.getVariable("auditInventoryResult"); - AAIObjectAuditList auditInventory = null; - String externalTaskId = externalTask.getId(); - try { - GraphInventoryCommonObjectMapperProvider objectMapper = new GraphInventoryCommonObjectMapperProvider(); - auditInventory = objectMapper.getMapper().readValue(auditInventoryString, AAIObjectAuditList.class); - } catch (Exception e) { - mdcSetup.setResponseCode(ONAPLogConstants.ResponseStatus.ERROR.toString()); - logger.error("Error Parsing Audit Results", e); - } - mdcSetup.setElapsedTime(); - if (auditInventory != null) { - Integer retryCount = externalTask.getRetries(); - try { - logger.info("Executing External Task Create Inventory, Retry Number: {} \n {}", auditInventory, - retryCount); - createInventory.createInventory(auditInventory); - } catch (InventoryException e) { - logger.error("Error during inventory of stack", e); - success = false; - inventoryException = true; - } catch (Exception e) { - logger.error("Error during inventory of stack", e); - success = false; - } - mdcSetup.setElapsedTime(); - if (success) { - externalTaskService.complete(externalTask); - mdcSetup.setResponseCode(ONAPLogConstants.ResponseStatus.COMPLETE.toString()); - logger.debug("The External Task Id: {} Successful", externalTaskId); - logger.info(ONAPLogConstants.Markers.EXIT, "Exiting"); - mdcSetup.clearClientMDCs(); - } else if (inventoryException) { - mdcSetup.setResponseCode(ONAPLogConstants.ResponseStatus.ERROR.toString()); - logger.debug("The External Task Id: {} Failed, Retry not needed", externalTaskId); - externalTaskService.handleBpmnError(externalTask, AAI_INVENTORY_FAILURE); - } else { - if (retryCount == null) { - logger.debug("The External Task Id: {} Failed, Setting Retries to Default Start Value: {}", - externalTaskId, getRetrySequence().length); - externalTaskService.handleFailure(externalTask, UNABLE_TO_WRITE_ALL_INVENTORY_TO_A_AI, - UNABLE_TO_WRITE_ALL_INVENTORY_TO_A_AI, getRetrySequence().length, 10000); - } else if (retryCount != null && retryCount - 1 == 0) { - externalTaskService.handleBpmnError(externalTask, AAI_INVENTORY_FAILURE); - mdcSetup.setResponseCode(ONAPLogConstants.ResponseStatus.ERROR.toString()); - logger.debug("The External Task Id: {} Failed, All Retries Exhausted", externalTaskId); - logger.info(ONAPLogConstants.Markers.EXIT, "Exiting"); - } else { - logger.debug("The External Task Id: {} Failed, Decrementing Retries: {} , Retry Delay: ", - externalTaskId, retryCount - 1, calculateRetryDelay(retryCount)); - externalTaskService.handleFailure(externalTask, UNABLE_TO_WRITE_ALL_INVENTORY_TO_A_AI, - UNABLE_TO_WRITE_ALL_INVENTORY_TO_A_AI, retryCount - 1, calculateRetryDelay(retryCount)); - } - logger.debug("The External Task Id: {} Failed", externalTaskId); - } - } else { - logger.debug("The External Task Id: {} Failed, No Audit Results Written", externalTaskId); - externalTaskService.handleBpmnError(externalTask, AAI_INVENTORY_FAILURE); - } - } -} diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/InventoryException.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/InventoryException.java deleted file mode 100644 index ed31c1c67e..0000000000 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/InventoryException.java +++ /dev/null @@ -1,34 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 - 2019 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.adapters.inventory.create; - -public class InventoryException extends Exception { - - /** - * - */ - private static final long serialVersionUID = 912652713891488731L; - - public InventoryException(String errorMessage) { - super(errorMessage); - } - -} diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/TaskServices.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/TaskServices.java new file mode 100644 index 0000000000..d282046b3f --- /dev/null +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/TaskServices.java @@ -0,0 +1,132 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2019 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.adapters.tasks; + +import javax.annotation.PostConstruct; +import org.camunda.bpm.client.ExternalTaskClient; +import org.onap.so.utils.ExternalTaskServiceUtils; +import org.onap.so.adapters.tasks.audit.AuditCreateStackService; +import org.onap.so.adapters.tasks.audit.AuditDeleteStackService; +import org.onap.so.adapters.tasks.audit.AuditQueryStackService; +import org.onap.so.adapters.tasks.inventory.CreateInventoryTask; +import org.onap.so.adapters.tasks.orchestration.PollService; +import org.onap.so.adapters.tasks.orchestration.RollbackService; +import org.onap.so.adapters.tasks.orchestration.StackService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Profile; +import org.springframework.stereotype.Component; + +@Component +@Profile("!test") +public class TaskServices { + + private static final Logger logger = LoggerFactory.getLogger(TaskServices.class); + + @Autowired + private ExternalTaskServiceUtils externalTaskServiceUtils; + + @Autowired + private AuditCreateStackService auditCreateStack; + + @Autowired + private AuditDeleteStackService auditDeleteStack; + + @Autowired + private AuditQueryStackService auditQueryStack; + + @Autowired + private CreateInventoryTask createInventory; + + @Autowired + private StackService stackService; + + @Autowired + private PollService pollService; + + @Autowired + private RollbackService rollbackService; + + @PostConstruct + public void auditAddAAIInventory() throws Exception { + for (int i = 0; i < externalTaskServiceUtils.getMaxClients(); i++) { + ExternalTaskClient client = externalTaskServiceUtils.createExternalTaskClient(); + client.subscribe("InventoryAddAudit").lockDuration(externalTaskServiceUtils.getLockDuration()) + .handler(auditCreateStack::executeExternalTask).open(); + } + } + + @PostConstruct + public void auditDeleteAAIInventory() throws Exception { + for (int i = 0; i < externalTaskServiceUtils.getMaxClients(); i++) { + ExternalTaskClient client = externalTaskServiceUtils.createExternalTaskClient(); + client.subscribe("InventoryDeleteAudit").lockDuration(externalTaskServiceUtils.getLockDuration()) + .handler(auditDeleteStack::executeExternalTask).open(); + } + } + + @PostConstruct + public void auditQueryInventory() throws Exception { + for (int i = 0; i < externalTaskServiceUtils.getMaxClients(); i++) { + ExternalTaskClient client = externalTaskServiceUtils.createExternalTaskClient(); + client.subscribe("InventoryQueryAudit").lockDuration(externalTaskServiceUtils.getLockDuration()) + .handler(auditQueryStack::executeExternalTask).open(); + } + } + + @PostConstruct + public void auditAAIInventory() throws Exception { + for (int i = 0; i < externalTaskServiceUtils.getMaxClients(); i++) { + ExternalTaskClient client = externalTaskServiceUtils.createExternalTaskClient(); + client.subscribe("InventoryCreate").lockDuration(externalTaskServiceUtils.getLockDuration()) + .handler(createInventory::executeExternalTask).open(); + } + } + + @PostConstruct + public void openstackInvoker() throws Exception { + for (int i = 0; i < externalTaskServiceUtils.getMaxClients(); i++) { + ExternalTaskClient client = externalTaskServiceUtils.createExternalTaskClient(); + client.subscribe("OpenstackAdapterInvoke").lockDuration(externalTaskServiceUtils.getLockDuration()) + .handler(stackService::executeExternalTask).open(); + } + } + + @PostConstruct + public void openstackPoller() throws Exception { + for (int i = 0; i < externalTaskServiceUtils.getMaxClients(); i++) { + ExternalTaskClient client = externalTaskServiceUtils.createExternalTaskClient(); + client.subscribe("OpenstackAdapterPolling").lockDuration(externalTaskServiceUtils.getLockDuration()) + .handler(pollService::executeExternalTask).open(); + } + } + + @PostConstruct + public void openstackRollback() throws Exception { + for (int i = 0; i < externalTaskServiceUtils.getMaxClients(); i++) { + ExternalTaskClient client = externalTaskServiceUtils.createExternalTaskClient(); + client.subscribe("OpenstackAdapterRollback").lockDuration(externalTaskServiceUtils.getLockDuration()) + .handler(rollbackService::executeExternalTask).open(); + } + } + +} diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/audit/AbstractAudit.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/audit/AbstractAudit.java new file mode 100644 index 0000000000..7622c1ba28 --- /dev/null +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/audit/AbstractAudit.java @@ -0,0 +1,39 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2019 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.adapters.tasks.audit; + +import org.onap.so.client.aai.AAIResourcesClient; + +public class AbstractAudit { + + private AAIResourcesClient aaiClient; + + protected AAIResourcesClient getAaiClient() { + if (aaiClient == null) + return new AAIResourcesClient(); + else + return aaiClient; + } + + protected void setAaiClient(AAIResourcesClient aaiResource) { + aaiClient = aaiResource; + } +} diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/audit/AbstractAuditService.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/audit/AbstractAuditService.java new file mode 100644 index 0000000000..2f7155bffc --- /dev/null +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/audit/AbstractAuditService.java @@ -0,0 +1,87 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2019 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.adapters.tasks.audit; + +import java.util.Optional; +import org.onap.so.objects.audit.AAIObjectAudit; +import org.onap.so.objects.audit.AAIObjectAuditList; +import org.onap.so.utils.ExternalTaskUtils; +import org.onap.so.utils.RetrySequenceLevel; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Component; + +@Component +public abstract class AbstractAuditService extends ExternalTaskUtils { + + private static final Logger logger = LoggerFactory.getLogger(AbstractAuditService.class); + + + + protected static final String UNABLE_TO_FIND_ALL_V_SERVERS_AND_L_INTERACES_IN_A_AI = + "Unable to find all VServers and L-Interaces in A&AI"; + + protected static final String UNABLE_TO_FIND_V_SERVERS_IN_OPENSTACK = "Unable to find VServers in Openstack"; + + @Autowired + public Environment env; + + public AbstractAuditService() { + super(RetrySequenceLevel.LONG); + } + + /** + * @param auditHeatStackFailed + * @param auditList + * @return + */ + protected boolean didCreateAuditFail(Optional auditList) { + if (auditList.get().getAuditList() != null && !auditList.get().getAuditList().isEmpty()) { + if (logger.isInfoEnabled()) { + logger.info("Audit Results: {}", auditList.get().toString()); + } + return auditList.get().getAuditList().stream().filter(auditObject -> !auditObject.isDoesObjectExist()) + .findFirst().map(v -> true).orElse(false); + } else { + return false; + } + } + + /** + * @param auditHeatStackFailed + * @param auditList + * @return + */ + protected boolean didDeleteAuditFail(AAIObjectAuditList auditList) { + if (auditList.getAuditList() != null && !auditList.getAuditList().isEmpty()) { + if (logger.isInfoEnabled()) { + logger.info("Audit Results: {}", auditList.toString()); + } + return auditList.getAuditList().stream().filter(AAIObjectAudit::isDoesObjectExist).findFirst() + .map(v -> true).orElse(false); + } else { + return false; + } + } +} diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/audit/AuditCreateStackService.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/audit/AuditCreateStackService.java new file mode 100644 index 0000000000..874823a7cd --- /dev/null +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/audit/AuditCreateStackService.java @@ -0,0 +1,111 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Modifications Copyright (c) 2019 Samsung + * ================================================================================ + * 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.adapters.tasks.audit; + +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import org.camunda.bpm.client.task.ExternalTask; +import org.camunda.bpm.client.task.ExternalTaskService; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.onap.so.audit.beans.AuditInventory; +import org.onap.so.client.graphinventory.GraphInventoryCommonObjectMapperProvider; +import org.onap.so.logging.tasks.AuditMDCSetup; +import org.onap.so.objects.audit.AAIObjectAuditList; +import org.onap.so.utils.RetrySequenceLevel; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class AuditCreateStackService extends AbstractAuditService { + + private static final Logger logger = LoggerFactory.getLogger(AuditCreateStackService.class); + + @Autowired + public HeatStackAudit heatStackAudit; + + @Autowired + public AuditMDCSetup mdcSetup; + + public AuditCreateStackService() { + super(); + } + + public void executeExternalTask(ExternalTask externalTask, ExternalTaskService externalTaskService) { + mdcSetup.setupMDC(externalTask); + AuditInventory auditInventory = externalTask.getVariable("auditInventory"); + Map variables = new HashMap<>(); + boolean success = false; + try { + Integer retryCount = externalTask.getRetries(); + logger.info("Executing External Task Audit Inventory, Retry Number: {} \n {}", auditInventory, retryCount); + Optional auditListOpt = heatStackAudit.auditHeatStack(auditInventory.getCloudRegion(), + auditInventory.getCloudOwner(), auditInventory.getTenantId(), auditInventory.getHeatStackName()); + if (auditListOpt.isPresent()) { + auditListOpt.get().setAuditType("create"); + auditListOpt.get().setHeatStackName(auditInventory.getHeatStackName()); + GraphInventoryCommonObjectMapperProvider objectMapper = new GraphInventoryCommonObjectMapperProvider(); + variables.put("auditInventoryResult", objectMapper.getMapper().writeValueAsString(auditListOpt.get())); + success = !didCreateAuditFail(auditListOpt); + } + } catch (Exception e) { + logger.error("Error during audit of stack", e); + } + variables.put("auditIsSuccessful", success); + mdcSetup.setElapsedTime(); + String externalTaskId = externalTask.getId(); + if (success) { + externalTaskService.complete(externalTask, variables); + mdcSetup.setResponseCode(ONAPLogConstants.ResponseStatus.COMPLETE.toString()); + logger.debug("The External Task Id: {} Successful", externalTaskId); + logger.info(ONAPLogConstants.Markers.EXIT, "Exiting"); + mdcSetup.clearClientMDCs(); + } else { + Integer retryCount = externalTask.getRetries(); + if (retryCount == null) { + logger.debug("The External Task Id: {} Failed, Setting Retries to Default Start Value: {}", + externalTaskId, getRetrySequence().length); + externalTaskService.handleFailure(externalTask, UNABLE_TO_FIND_ALL_V_SERVERS_AND_L_INTERACES_IN_A_AI, + UNABLE_TO_FIND_ALL_V_SERVERS_AND_L_INTERACES_IN_A_AI, getRetrySequence().length, 10000); + } else if (retryCount == 1) { + externalTaskService.complete(externalTask, variables); + mdcSetup.setResponseCode(ONAPLogConstants.ResponseStatus.ERROR.toString()); + logger.debug("The External Task Id: {} Failed, All Retries Exhausted", externalTaskId); + logger.info(ONAPLogConstants.Markers.EXIT, "Exiting"); + mdcSetup.clearClientMDCs(); + } else { + logger.debug("The External Task Id: {} Failed, Decrementing Retries: {} , Retry Delay: ", + externalTaskId, retryCount - 1, calculateRetryDelay(retryCount)); + externalTaskService.handleFailure(externalTask, UNABLE_TO_FIND_ALL_V_SERVERS_AND_L_INTERACES_IN_A_AI, + UNABLE_TO_FIND_ALL_V_SERVERS_AND_L_INTERACES_IN_A_AI, retryCount - 1, + calculateRetryDelay(retryCount)); + } + logger.debug("The External Task Id: {} Failed", externalTaskId); + } + } + + + +} diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/audit/AuditDataService.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/audit/AuditDataService.java new file mode 100644 index 0000000000..2c76acdb1b --- /dev/null +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/audit/AuditDataService.java @@ -0,0 +1,77 @@ +package org.onap.so.adapters.tasks.audit; + +import java.io.IOException; +import java.util.List; +import java.util.Optional; +import org.onap.so.audit.beans.AuditInventory; +import org.onap.so.client.graphinventory.GraphInventoryCommonObjectMapperProvider; +import org.onap.so.db.request.beans.RequestProcessingData; +import org.onap.so.db.request.client.RequestsDbClient; +import org.onap.so.objects.audit.AAIObjectAuditList; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonMappingException; + +@Component +public class AuditDataService { + + @Autowired + private RequestsDbClient requestsDbClient; + + /** + * Checks to see if an entry already exist for the given heat stack and writes audit stack data to the request + * database if it doesn't. + * + * @throws JsonProcessingException + */ + public void writeStackDataToRequestDb(AuditInventory auditInventory, AAIObjectAuditList auditList) + throws JsonProcessingException { + List requestProcessingDataList = + requestsDbClient.getRequestProcessingDataByGroupingIdAndNameAndTag(auditInventory.getVfModuleId(), + auditInventory.getHeatStackName(), "AuditStackData"); + if (requestProcessingDataList.isEmpty()) { + GraphInventoryCommonObjectMapperProvider objectMapper = new GraphInventoryCommonObjectMapperProvider(); + String auditListString = objectMapper.getMapper().writeValueAsString(auditList);; + + RequestProcessingData requestProcessingData = new RequestProcessingData(); + requestProcessingData.setSoRequestId(auditInventory.getMsoRequestId()); + requestProcessingData.setGroupingId(auditInventory.getVfModuleId()); + requestProcessingData.setName(auditInventory.getHeatStackName()); + requestProcessingData.setTag("AuditStackData"); + requestProcessingData.setValue(auditListString); + + requestsDbClient.saveRequestProcessingData(requestProcessingData); + } + } + + /** + * Retrieves audit stack data from the request database. + * + * @throws IOException + * @throws JsonMappingException + * @throws JsonParseException + */ + public Optional getStackDataFromRequestDb(AuditInventory auditInventory) + throws JsonParseException, JsonMappingException, IOException { + + List requestProcessingDataList = + requestsDbClient.getRequestProcessingDataByGroupingIdAndNameAndTag(auditInventory.getVfModuleId(), + auditInventory.getHeatStackName(), "AuditStackData"); + if (!requestProcessingDataList.isEmpty()) { + RequestProcessingData requestProcessingData = requestProcessingDataList.get(0); + String auditListString = requestProcessingData.getValue(); + + GraphInventoryCommonObjectMapperProvider objectMapper = new GraphInventoryCommonObjectMapperProvider(); + AAIObjectAuditList auditList = + objectMapper.getMapper().readValue(auditListString, AAIObjectAuditList.class); + + return Optional.of(auditList); + } else { + return Optional.empty(); + } + } + + +} diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/audit/AuditDeleteStackService.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/audit/AuditDeleteStackService.java new file mode 100644 index 0000000000..55cde4d174 --- /dev/null +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/audit/AuditDeleteStackService.java @@ -0,0 +1,122 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017-2019 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.adapters.tasks.audit; + +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import org.camunda.bpm.client.task.ExternalTask; +import org.camunda.bpm.client.task.ExternalTaskService; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.onap.so.audit.beans.AuditInventory; +import org.onap.so.client.graphinventory.GraphInventoryCommonObjectMapperProvider; +import org.onap.so.logging.tasks.AuditMDCSetup; +import org.onap.so.objects.audit.AAIObjectAuditList; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.core.env.Environment; +import org.springframework.stereotype.Component; + +@Component +public class AuditDeleteStackService extends AbstractAuditService { + + private static final Logger logger = LoggerFactory.getLogger(AuditDeleteStackService.class); + + @Autowired + protected HeatStackAudit heatStackAudit; + + @Autowired + protected AuditVServer auditVservers; + + @Autowired + protected AuditDataService auditDataService; + + @Autowired + protected Environment env; + + @Autowired + public AuditMDCSetup mdcSetup; + + public AuditDeleteStackService() { + super(); + } + + public void executeExternalTask(ExternalTask externalTask, ExternalTaskService externalTaskService) { + + mdcSetup.setupMDC(externalTask); + AuditInventory auditInventory = externalTask.getVariable("auditInventory"); + Map variables = new HashMap<>(); + boolean success = false; + try { + Integer retryCount = externalTask.getRetries(); + logger.info("Executing External Task Delete Audit Inventory. Retry Number: {}", retryCount); + Optional auditListOpt = auditDataService.getStackDataFromRequestDb(auditInventory); + if (auditListOpt.isPresent()) { + auditVservers.auditVservers(auditListOpt.get()); + } else { + logger.debug("Auditing Vservers based on vf module relationships"); + auditListOpt = auditVservers.auditVserversThroughRelationships(auditInventory.getGenericVnfId(), + auditInventory.getHeatStackName()); + } + auditListOpt.get().setHeatStackName(auditInventory.getHeatStackName()); + auditListOpt.get().setAuditType("delete"); + GraphInventoryCommonObjectMapperProvider objectMapper = new GraphInventoryCommonObjectMapperProvider(); + variables.put("auditInventoryResult", objectMapper.getMapper().writeValueAsString(auditListOpt.get())); + success = !didDeleteAuditFail(auditListOpt.get()); + + } catch (Exception e) { + logger.error("Error during audit of stack", e); + } + variables.put("auditIsSuccessful", success); + mdcSetup.setElapsedTime(); + String externalTaskId = externalTask.getId(); + if (success) { + externalTaskService.complete(externalTask, variables); + mdcSetup.setResponseCode(ONAPLogConstants.ResponseStatus.COMPLETE.toString()); + logger.debug("The External Task Id: {} Successful", externalTaskId); + logger.info(ONAPLogConstants.Markers.EXIT, "Exiting"); + mdcSetup.clearClientMDCs(); + } else { + Integer retryCount = externalTask.getRetries(); + if (retryCount == null) { + logger.debug("The External Task Id: {} Failed, Setting Retries to Default Start Value: {}", + externalTaskId, getRetrySequence().length); + externalTaskService.handleFailure(externalTask, UNABLE_TO_FIND_ALL_V_SERVERS_AND_L_INTERACES_IN_A_AI, + UNABLE_TO_FIND_ALL_V_SERVERS_AND_L_INTERACES_IN_A_AI, getRetrySequence().length, 10000); + } else if (retryCount == 1) { + externalTaskService.complete(externalTask, variables); + mdcSetup.setResponseCode(ONAPLogConstants.ResponseStatus.ERROR.toString()); + logger.debug("The External Task Id: {} Failed, All Retries Exhausted", externalTaskId); + logger.info(ONAPLogConstants.Markers.EXIT, "Exiting"); + mdcSetup.clearClientMDCs(); + } else { + logger.debug("The External Task Id: {} Failed, Decrementing Retries: {} , Retry Delay: ", + externalTaskId, retryCount - 1, calculateRetryDelay(retryCount)); + externalTaskService.handleFailure(externalTask, UNABLE_TO_FIND_ALL_V_SERVERS_AND_L_INTERACES_IN_A_AI, + UNABLE_TO_FIND_ALL_V_SERVERS_AND_L_INTERACES_IN_A_AI, retryCount - 1, + calculateRetryDelay(retryCount)); + } + logger.debug("The External Task Id: {} Failed", externalTaskId); + } + } + +} diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/audit/AuditQueryStackService.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/audit/AuditQueryStackService.java new file mode 100644 index 0000000000..ebef4425eb --- /dev/null +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/audit/AuditQueryStackService.java @@ -0,0 +1,85 @@ +package org.onap.so.adapters.tasks.audit; + +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import org.camunda.bpm.client.task.ExternalTask; +import org.camunda.bpm.client.task.ExternalTaskService; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.onap.so.audit.beans.AuditInventory; +import org.onap.so.logging.tasks.AuditMDCSetup; +import org.onap.so.objects.audit.AAIObjectAuditList; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class AuditQueryStackService extends AbstractAuditService { + + private static final Logger logger = LoggerFactory.getLogger(AuditQueryStackService.class); + + @Autowired + protected HeatStackAudit heatStackAudit; + + @Autowired + protected AuditDataService auditDataService; + + @Autowired + public AuditMDCSetup mdcSetup; + + public AuditQueryStackService() { + super(); + } + + public void executeExternalTask(ExternalTask externalTask, ExternalTaskService externalTaskService) { + mdcSetup.setupMDC(externalTask); + AuditInventory auditInventory = externalTask.getVariable("auditInventory"); + boolean success = false; + Map variables = new HashMap<>(); + try { + Integer retryCount = externalTask.getRetries(); + logger.info("Executing External Task Query Audit Inventory. Audit Inventory: {} \n Retry Number: {}", + auditInventory.toString(), retryCount); + + Optional auditList = heatStackAudit.queryHeatStack(auditInventory.getCloudOwner(), + auditInventory.getCloudRegion(), auditInventory.getTenantId(), auditInventory.getHeatStackName()); + + if (auditList.isPresent()) { + mdcSetup.setResponseCode(ONAPLogConstants.ResponseStatus.COMPLETE.toString()); + success = true; + auditDataService.writeStackDataToRequestDb(auditInventory, auditList.get()); + } + mdcSetup.setElapsedTime(); + String externalTaskId = externalTask.getId(); + if (success) { + externalTaskService.complete(externalTask, variables); + mdcSetup.setResponseCode(ONAPLogConstants.ResponseStatus.COMPLETE.toString()); + logger.debug("The External Task {} was Successful", externalTaskId); + logger.info(ONAPLogConstants.Markers.EXIT, "Exiting"); + mdcSetup.clearClientMDCs(); + } else { + if (retryCount == null) { + logger.debug("The External Task {} Failed. Setting Retries to Default Start Value: {}", + externalTaskId, getRetrySequence().length); + externalTaskService.handleFailure(externalTask, UNABLE_TO_FIND_V_SERVERS_IN_OPENSTACK, + UNABLE_TO_FIND_V_SERVERS_IN_OPENSTACK, getRetrySequence().length, 10000); + } else if (retryCount == 1) { + externalTaskService.complete(externalTask, variables); + mdcSetup.setResponseCode(ONAPLogConstants.ResponseStatus.ERROR.toString()); + logger.debug("The External Task {} Failed. All Retries Exhausted", externalTaskId); + logger.info(ONAPLogConstants.Markers.EXIT, "Exiting"); + mdcSetup.clearClientMDCs(); + } else { + logger.debug("The External Task {} Failed. Decrementing Retries to {} , Retry Delay: ", + externalTaskId, retryCount - 1, calculateRetryDelay(retryCount)); + externalTaskService.handleFailure(externalTask, UNABLE_TO_FIND_V_SERVERS_IN_OPENSTACK, + UNABLE_TO_FIND_V_SERVERS_IN_OPENSTACK, retryCount - 1, calculateRetryDelay(retryCount)); + } + logger.debug("The External Task {} Failed", externalTaskId); + } + } catch (Exception e) { + logger.error("Error during audit query of stack", e); + } + } +} diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/audit/AuditVServer.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/audit/AuditVServer.java new file mode 100644 index 0000000000..63853c34fa --- /dev/null +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/audit/AuditVServer.java @@ -0,0 +1,171 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2019 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.adapters.tasks.audit; + +import java.util.List; +import java.util.Optional; +import java.util.Set; +import org.onap.aai.domain.yang.LInterface; +import org.onap.aai.domain.yang.VfModule; +import org.onap.aai.domain.yang.VfModules; +import org.onap.aai.domain.yang.Vserver; +import org.onap.so.client.aai.AAIObjectPlurals; +import org.onap.so.client.aai.AAIObjectType; +import org.onap.so.client.aai.entities.AAIResultWrapper; +import org.onap.so.client.aai.entities.uri.AAIPluralResourceUri; +import org.onap.so.client.aai.entities.uri.AAIResourceUri; +import org.onap.so.client.aai.entities.uri.AAIUriFactory; +import org.onap.so.client.graphinventory.GraphInventoryCommonObjectMapperProvider; +import org.onap.so.objects.audit.AAIObjectAudit; +import org.onap.so.objects.audit.AAIObjectAuditList; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.BeanUtils; +import org.springframework.stereotype.Component; +import com.fasterxml.jackson.core.JsonProcessingException; + +@Component +public class AuditVServer extends AbstractAudit { + private static final Logger logger = LoggerFactory.getLogger(AuditVServer.class); + + public void auditVservers(AAIObjectAuditList aaiObjectAuditList) { + + aaiObjectAuditList.getAuditList().forEach(aaiObjectAudit -> { + boolean vserverExist = getAaiClient().exists(AAIUriFactory + .createResourceFromExistingURI(AAIObjectType.VSERVER, aaiObjectAudit.getResourceURI())); + aaiObjectAudit.setDoesObjectExist(vserverExist); + }); + } + + public Optional auditVserversThroughRelationships(String genericVnfId, String vfModuleName) { + AAIObjectAuditList auditList = new AAIObjectAuditList(); + AAIPluralResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectPlurals.VF_MODULE, genericVnfId) + .queryParam("vf-module-name", vfModuleName); + Optional wrapper = getAaiClient().getFirstWrapper(VfModules.class, VfModule.class, uri); + if (wrapper.isPresent() && wrapper.get().getRelationships().isPresent()) { + List relatedVservers = + wrapper.get().getRelationships().get().getRelatedUris(AAIObjectType.VSERVER); + if (!relatedVservers.isEmpty()) { + relatedVservers.forEach(vserverUri -> { + Optional vserver = getAaiClient().get(vserverUri).asBean(Vserver.class); + Vserver vServerShallow = new Vserver(); + BeanUtils.copyProperties(vserver, vServerShallow); + AAIObjectAudit vServerAudit = new AAIObjectAudit(); + vServerAudit.setAaiObject(vServerShallow); + vServerAudit.setAaiObjectType(AAIObjectType.VSERVER.typeName()); + vServerAudit.setDoesObjectExist(true); + auditList.getAuditList().add(vServerAudit); + }); + } + } + return Optional.of(auditList); + } + + public Optional auditVservers(Set vServersToAudit, String tenantId, String cloudOwner, + String cloudRegion) { + if (vServersToAudit == null || vServersToAudit.isEmpty()) { + return Optional.empty(); + } + GraphInventoryCommonObjectMapperProvider objectMapper = new GraphInventoryCommonObjectMapperProvider(); + vServersToAudit.stream().forEach(vserver -> { + try { + logger.debug("Vserver to Audit: {}", objectMapper.getMapper().writeValueAsString(vserver)); + } catch (JsonProcessingException e) { + logger.error("Json parse exception: ", e); + } + + }); + AAIObjectAuditList auditList = new AAIObjectAuditList(); + vServersToAudit.stream().forEach(vServer -> auditList.getAuditList() + .addAll(doesVServerExistInAAI(vServer, tenantId, cloudOwner, cloudRegion).getAuditList())); + return Optional.of(auditList); + } + + private AAIObjectAuditList doesVServerExistInAAI(Vserver vServer, String tenantId, String cloudOwner, + String cloudRegion) { + AAIObjectAuditList auditList = new AAIObjectAuditList(); + AAIObjectAudit vServerAudit = new AAIObjectAudit(); + AAIResourceUri vserverURI = AAIUriFactory.createResourceUri(AAIObjectType.VSERVER, cloudOwner, cloudRegion, + tenantId, vServer.getVserverId()); + Vserver vServerShallow = new Vserver(); + BeanUtils.copyProperties(vServer, vServerShallow, "LInterfaces"); + boolean vServerExists = getAaiClient().exists(vserverURI); + logger.info("v-server {} exists: {}", vServer.getVserverId(), vServerExists); + vServerAudit.setAaiObject(vServerShallow); + vServerAudit.setDoesObjectExist(vServerExists); + vServerAudit.setResourceURI(vserverURI.build()); + vServerAudit.setAaiObjectType(AAIObjectType.VSERVER.typeName()); + auditList.getAuditList().add(vServerAudit); + if (vServer.getLInterfaces() != null) { + vServer.getLInterfaces().getLInterface().stream().forEach(lInterface -> auditList.getAuditList().addAll( + doesLinterfaceExistinAAI(lInterface, vServer.getVserverId(), tenantId, cloudOwner, cloudRegion) + .getAuditList())); + } + return auditList; + } + + private AAIObjectAuditList doesLinterfaceExistinAAI(LInterface lInterface, String vServerId, String tenantId, + String cloudOwner, String cloudRegion) { + AAIObjectAuditList auditList = new AAIObjectAuditList(); + AAIObjectAudit lInterfaceAudit = new AAIObjectAudit(); + AAIResourceUri linterfaceURI = AAIUriFactory.createResourceUri(AAIObjectType.L_INTERFACE, cloudOwner, + cloudRegion, tenantId, vServerId, lInterface.getInterfaceName()); + Optional queriedLInterface = getAaiClient().get(LInterface.class, linterfaceURI); + if (queriedLInterface.isPresent()) { + lInterfaceAudit.setDoesObjectExist(true); + lInterface.setInterfaceName(lInterface.getInterfaceName()); + } + lInterfaceAudit.setAaiObject(lInterface); + lInterfaceAudit.setResourceURI(linterfaceURI.build()); + lInterfaceAudit.setAaiObjectType(AAIObjectType.L_INTERFACE.typeName()); + auditList.getAuditList().add(lInterfaceAudit); + logger.info("l-interface id:{} name: {} exists: {} ", lInterface.getInterfaceId(), + lInterface.getInterfaceName(), lInterfaceAudit.isDoesObjectExist()); + + if (lInterface.getLInterfaces() != null) { + lInterface.getLInterfaces().getLInterface().stream() + .forEach(subInterface -> auditList.getAuditList().add(doesSubInterfaceExistinAAI(subInterface, + lInterface.getInterfaceName(), vServerId, tenantId, cloudOwner, cloudRegion))); + } + logger.debug("l-interface {} does not contain any sub-iterfaces, skipping audit of sub-interfaces", + lInterface.getInterfaceId()); + + return auditList; + } + + private AAIObjectAudit doesSubInterfaceExistinAAI(LInterface subInterface, String linterfaceName, String vServerId, + String tenantId, String cloudOwner, String cloudRegion) { + logger.info("checking if sub-l-interface {} , linterfaceName: {} vserverId: {} exists", + subInterface.getInterfaceName(), linterfaceName, vServerId); + AAIObjectAudit subInterfaceAudit = new AAIObjectAudit(); + + + AAIResourceUri subInterfaceURI = AAIUriFactory.createResourceUri(AAIObjectType.SUB_L_INTERFACE, cloudOwner, + cloudRegion, tenantId, vServerId, linterfaceName, subInterface.getInterfaceName()); + subInterfaceAudit.setResourceURI(subInterfaceURI.build()); + boolean doesExist = getAaiClient().exists(subInterfaceURI); + logger.info("sub-l-interface-id:{} exists: {}", subInterface.getInterfaceId(), doesExist); + subInterfaceAudit.setAaiObject(subInterface); + subInterfaceAudit.setDoesObjectExist(doesExist); + subInterfaceAudit.setAaiObjectType(AAIObjectType.SUB_L_INTERFACE.typeName()); + return subInterfaceAudit; + } +} diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/audit/HeatStackAudit.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/audit/HeatStackAudit.java new file mode 100644 index 0000000000..1554881193 --- /dev/null +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/audit/HeatStackAudit.java @@ -0,0 +1,327 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * + * Modifications Copyright (C) 2019 IBM. + * ================================================================================ + * 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.adapters.tasks.audit; + +import java.net.URI; +import java.util.Arrays; +import java.util.HashSet; +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.regex.Matcher; +import java.util.regex.Pattern; +import java.util.stream.Collectors; +import java.util.stream.Stream; +import org.onap.aai.domain.yang.LInterface; +import org.onap.aai.domain.yang.LInterfaces; +import org.onap.aai.domain.yang.Vlan; +import org.onap.aai.domain.yang.Vlans; +import org.onap.aai.domain.yang.Vserver; +import org.onap.so.client.aai.AAIObjectType; +import org.onap.so.client.aai.entities.uri.AAIUriFactory; +import org.onap.so.objects.audit.AAIObjectAudit; +import org.onap.so.objects.audit.AAIObjectAuditList; +import org.onap.so.openstack.utils.MsoHeatUtils; +import org.onap.so.openstack.utils.MsoNeutronUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.BeanUtils; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import com.woorea.openstack.heat.model.Link; +import com.woorea.openstack.heat.model.Resource; +import com.woorea.openstack.heat.model.Resources; +import com.woorea.openstack.heat.model.Stack; +import com.woorea.openstack.quantum.model.Port; + +@Component +public class HeatStackAudit { + + private static final String RESOURCES = "/resources"; + + protected static final Logger logger = LoggerFactory.getLogger(HeatStackAudit.class); + + private static final String EXCEPTION_MSG = "Error finding Path from Self Link"; + + @Autowired + protected MsoHeatUtils heat; + + @Autowired + protected MsoNeutronUtils neutron; + + @Autowired + protected AuditVServer auditVservers; + + public Optional queryHeatStack(String cloudOwner, String cloudRegion, String tenantId, + String heatStackName) { + try { + logger.debug("Fetching Top Level Stack Information"); + Resources resources = heat.queryStackResources(cloudRegion, tenantId, heatStackName, 3); + List novaResources = resources.getList().stream() + .filter(p -> "OS::Nova::Server".equals(p.getType())).collect(Collectors.toList()); + if (novaResources.isEmpty()) + return Optional.of(new AAIObjectAuditList()); + else { + Set vserversToAudit = createVserverSet(novaResources); + AAIObjectAuditList aaiObjectAuditList = new AAIObjectAuditList(); + vserversToAudit.stream().forEach(vServer -> aaiObjectAuditList.getAuditList() + .add(createAAIObjectAudit(cloudOwner, cloudRegion, tenantId, vServer))); + return Optional.of(aaiObjectAuditList); + } + } catch (Exception e) { + logger.error("Error during query stack resources", e); + return Optional.of(new AAIObjectAuditList()); + } + } + + public Optional auditHeatStack(String cloudRegion, String cloudOwner, String tenantId, + String heatStackName) { + try { + logger.debug("Fetching Top Level Stack Information"); + Resources resources = heat.queryStackResources(cloudRegion, tenantId, heatStackName, 3); + List novaResources = resources.getList().stream() + .filter(p -> "OS::Nova::Server".equals(p.getType())).collect(Collectors.toList()); + List resourceGroups = resources.getList().stream() + .filter(p -> "OS::Heat::ResourceGroup".equals(p.getType()) && p.getName().contains("subinterfaces")) + .collect(Collectors.toList()); + List> neutronPortDetails = retrieveNeutronPortDetails(resources, cloudRegion, tenantId); + if (novaResources.isEmpty()) + return Optional.of(new AAIObjectAuditList()); + else { + Set vserversToAudit = createVserverSet(resources, novaResources, neutronPortDetails); + Set vserversWithSubInterfaces = + processSubInterfaces(cloudRegion, tenantId, resourceGroups, vserversToAudit); + return auditVservers.auditVservers(vserversWithSubInterfaces, tenantId, cloudOwner, cloudRegion); + } + } catch (Exception e) { + logger.error("Error during auditing stack resources", e); + return Optional.empty(); + } + } + + protected Set processSubInterfaces(String cloudRegion, String tenantId, List resourceGroups, + Set vServersToAudit) throws Exception { + for (Resource resourceGroup : resourceGroups) { + processResourceGroups(cloudRegion, tenantId, vServersToAudit, resourceGroup); + } + return vServersToAudit; + } + + protected void processResourceGroups(String cloudRegion, String tenantId, Set vServersWithLInterface, + Resource resourceGroup) throws Exception { + Optional stackLink = + resourceGroup.getLinks().stream().filter(link -> "nested".equals(link.getRel())).findAny(); + if (stackLink.isPresent()) { + try { + Optional path = extractResourcePathFromHref(stackLink.get().getHref()); + if (path.isPresent()) { + logger.debug("Fetching nested Resource Stack Information"); + Resources nestedResourceGroupResources = + heat.executeHeatClientRequest(path.get(), cloudRegion, tenantId, Resources.class); + processNestedResourceGroup(cloudRegion, tenantId, vServersWithLInterface, + nestedResourceGroupResources); + } else + throw new Exception(EXCEPTION_MSG); + } catch (Exception e) { + logger.error("Error Parsing Link to obtain Path", e); + throw new Exception(EXCEPTION_MSG); + } + } + } + + protected void processNestedResourceGroup(String cloudRegion, String tenantId, Set vServersWithLInterface, + Resources nestedResourceGroupResources) throws Exception { + for (Resource resourceGroupNested : nestedResourceGroupResources) { + Optional subInterfaceStackLink = + resourceGroupNested.getLinks().stream().filter(link -> "nested".equals(link.getRel())).findAny(); + if (subInterfaceStackLink.isPresent()) { + addSubInterface(cloudRegion, tenantId, vServersWithLInterface, subInterfaceStackLink.get()); + } + } + } + + protected void addSubInterface(String cloudRegion, String tenantId, Set vServersWithLInterface, + Link subInterfaceStackLink) throws Exception { + Optional resourcePath = extractResourcePathFromHref(subInterfaceStackLink.getHref()); + Optional stackPath = extractStackPathFromHref(subInterfaceStackLink.getHref()); + if (resourcePath.isPresent() && stackPath.isPresent()) { + logger.debug("Fetching nested Sub-Interface Stack Information"); + Stack subinterfaceStack = + heat.executeHeatClientRequest(stackPath.get(), cloudRegion, tenantId, Stack.class); + Resources subinterfaceResources = + heat.executeHeatClientRequest(resourcePath.get(), cloudRegion, tenantId, Resources.class); + if (subinterfaceStack != null) { + addSubInterfaceToVserver(vServersWithLInterface, subinterfaceStack, subinterfaceResources); + } + } else + throw new Exception(EXCEPTION_MSG); + + } + + protected void addSubInterfaceToVserver(Set vServersWithLInterface, Stack subinterfaceStack, + Resources subinterfaceResources) throws Exception { + String parentNeutronPortId = (String) subinterfaceStack.getParameters().get("port_interface"); + logger.debug("Parent neutron Port: {} on SubInterface: {}", parentNeutronPortId, subinterfaceStack.getId()); + for (Vserver auditVserver : vServersWithLInterface) + for (LInterface lInterface : auditVserver.getLInterfaces().getLInterface()) + + if (parentNeutronPortId.equals(lInterface.getInterfaceId())) { + logger.debug("Found Parent Port on VServer: {} on Port: {}", auditVserver.getVserverId(), + lInterface.getInterfaceId()); + Resource contrailVm = subinterfaceResources.getList().stream() + .filter(resource -> "OS::ContrailV2::VirtualMachineInterface".equals(resource.getType())) + .findAny().orElse(null); + if (contrailVm == null) { + throw new Exception("Cannnot find Contrail Virtual Machine Interface on Stack: " + + subinterfaceStack.getId()); + } + LInterface subInterface = new LInterface(); + subInterface.setInterfaceId(contrailVm.getPhysicalResourceId()); + subInterface.setIsPortMirrored(false); + subInterface.setInMaint(false); + subInterface.setIsIpUnnumbered(false); + String macAddr = (String) subinterfaceStack.getParameters().get("mac_address"); + subInterface.setMacaddr(macAddr); + + String namePrefix = (String) subinterfaceStack.getParameters().get("subinterface_name_prefix"); + Integer vlanIndex = Integer.parseInt((String) subinterfaceStack.getParameters().get("counter")); + String vlanTagList = (String) subinterfaceStack.getParameters().get("vlan_tag"); + List subInterfaceVlanTagList = Arrays.asList(vlanTagList.split(",")); + subInterface.setInterfaceName(namePrefix + "_" + subInterfaceVlanTagList.get(vlanIndex)); + subInterface.setVlans(new Vlans()); + Vlan vlan = new Vlan(); + vlan.setInMaint(false); + vlan.setIsIpUnnumbered(false); + vlan.setVlanIdInner(Long.parseLong(subInterfaceVlanTagList.get(vlanIndex))); + vlan.setVlanInterface(namePrefix + "_" + subInterfaceVlanTagList.get(vlanIndex)); + subInterface.getVlans().getVlan().add(vlan); + if (lInterface.getLInterfaces() == null) + lInterface.setLInterfaces(new LInterfaces()); + + lInterface.getLInterfaces().getLInterface().add(subInterface); + } else + logger.debug("Did Not Find Parent Port on VServer: {} Parent Port: SubInterface: {}", + auditVserver.getVserverId(), lInterface.getInterfaceId(), subinterfaceStack.getId()); + } + + protected Set createVserverSet(Resources resources, List novaResources, + List> neutronPortDetails) { + Set vserversToAudit = new HashSet<>(); + for (Resource novaResource : novaResources) { + Vserver auditVserver = new Vserver(); + auditVserver.setLInterfaces(new LInterfaces()); + auditVserver.setVserverId(novaResource.getPhysicalResourceId()); + Stream filteredNeutronPorts = filterNeutronPorts(novaResource, neutronPortDetails); + filteredNeutronPorts.forEach(port -> { + LInterface lInterface = new LInterface(); + lInterface.setInterfaceId(port.getId()); + lInterface.setInterfaceName(port.getName()); + auditVserver.getLInterfaces().getLInterface().add(lInterface); + }); + vserversToAudit.add(auditVserver); + } + return vserversToAudit; + } + + protected Set createVserverSet(List novaResources) { + Set vserversToAudit = new HashSet<>(); + for (Resource novaResource : novaResources) { + Vserver auditVserver = new Vserver(); + auditVserver.setLInterfaces(new LInterfaces()); + auditVserver.setVserverId(novaResource.getPhysicalResourceId()); + vserversToAudit.add(auditVserver); + } + return vserversToAudit; + } + + protected AAIObjectAudit createAAIObjectAudit(String cloudOwner, String cloudRegion, String tenantId, + Vserver vServer) { + AAIObjectAudit aaiObjectAudit = new AAIObjectAudit(); + Vserver vServerShallow = new Vserver(); + BeanUtils.copyProperties(vServer, vServerShallow); + aaiObjectAudit.setAaiObject(vServerShallow); + aaiObjectAudit.setAaiObjectType(AAIObjectType.VSERVER.typeName()); + aaiObjectAudit.setResourceURI(AAIUriFactory + .createResourceUri(AAIObjectType.VSERVER, cloudOwner, cloudRegion, tenantId, vServer.getVserverId()) + .build()); + + return aaiObjectAudit; + } + + /** + * @param novaResource Single openstack resource that is of type Nova + * @param neutronPorts List of Neutron ports created within the stack + * @return Filtered list of neutron ports taht relate to the nova server in openstack + */ + protected Stream filterNeutronPorts(Resource novaResource, List> neutronPorts) { + List filteredNeutronPorts = + neutronPorts.stream().filter(Optional::isPresent).map(Optional::get).collect(Collectors.toList()); + return filteredNeutronPorts.stream() + .filter(port -> port.getDeviceId().equalsIgnoreCase(novaResource.getPhysicalResourceId())); + } + + /** + * @param resources Resource stream created by the stack in openstack + * @param cloudSiteId Unique site id to identify which openstack we talk to + * @param tenantId The tenant within the cloud we are talking to where resouces exist + * @return List of optional neutron ports found within the cloud site and tenant + */ + protected List> retrieveNeutronPortDetails(Resources resources, String cloudSiteId, + String tenantId) { + return resources.getList().parallelStream().filter(resource -> "OS::Neutron::Port".equals(resource.getType())) + .map(resource -> neutron.getNeutronPort(resource.getPhysicalResourceId(), tenantId, cloudSiteId)) + .collect(Collectors.toList()); + + } + + protected Optional extractResourcePathFromHref(String href) { + try { + Optional stackPath = extractStackPathFromHref(href); + if (stackPath.isPresent()) { + return Optional.of(stackPath.get() + RESOURCES); + } else + return Optional.empty(); + } catch (Exception e) { + logger.error("Error parsing URI", e); + } + return Optional.empty(); + } + + protected Optional extractStackPathFromHref(String href) { + try { + URI uri = new URI(href); + Pattern p = Pattern.compile("/stacks.*"); + Matcher m = p.matcher(uri.getPath()); + if (m.find()) { + return Optional.of(m.group()); + } else + return Optional.empty(); + } catch (Exception e) { + logger.error("Error parsing URI", e); + } + return Optional.empty(); + } + + +} + diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/inventory/CreateAAIInventory.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/inventory/CreateAAIInventory.java new file mode 100644 index 0000000000..a3cb99e3af --- /dev/null +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/inventory/CreateAAIInventory.java @@ -0,0 +1,73 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2019 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.adapters.tasks.inventory; + +import java.util.Optional; +import java.util.stream.Stream; +import org.onap.so.client.aai.AAIObjectType; +import org.onap.so.client.aai.AAIResourcesClient; +import org.onap.so.client.aai.entities.uri.AAIUriFactory; +import org.onap.so.objects.audit.AAIObjectAudit; +import org.onap.so.objects.audit.AAIObjectAuditList; +import org.springframework.stereotype.Component; + +@Component +public class CreateAAIInventory { + + private AAIResourcesClient aaiClient; + + public void createInventory(AAIObjectAuditList auditList) throws InventoryException { + if (didAuditFailVserverLInterfaces(auditList)) { + throw new InventoryException("Audit failed for VServer or LInterface cannot write Sub-Interfaces"); + } + auditList.getAuditList().parallelStream() + .filter(auditObject -> !auditObject.isDoesObjectExist() + && AAIObjectType.SUB_L_INTERFACE.typeName().equals(auditObject.getAaiObjectType())) + .forEach(auditObject -> getAaiClient().createIfNotExists(AAIUriFactory.createResourceFromExistingURI( + AAIObjectType.fromTypeName(auditObject.getAaiObjectType()), auditObject.getResourceURI()), + Optional.of(auditObject.getAaiObject()))); + } + + + /** + * @param auditHeatStackFailed + * @param auditList + * @return + */ + protected boolean didAuditFailVserverLInterfaces(AAIObjectAuditList auditList) { + Stream issue = auditList.getAuditList().stream() + .filter(auditObject -> auditObject.getAaiObjectType().equals(AAIObjectType.VSERVER.typeName()) + || auditObject.getAaiObjectType().equals(AAIObjectType.L_INTERFACE.typeName())); + + return issue.filter(auditObject -> !auditObject.isDoesObjectExist()).findFirst().map(v -> true).orElse(false); + } + + protected AAIResourcesClient getAaiClient() { + if (aaiClient == null) + return new AAIResourcesClient(); + else + return aaiClient; + } + + protected void setAaiClient(AAIResourcesClient aaiResource) { + aaiClient = aaiResource; + } +} diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/inventory/CreateInventoryTask.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/inventory/CreateInventoryTask.java new file mode 100644 index 0000000000..04dcd9ff61 --- /dev/null +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/inventory/CreateInventoryTask.java @@ -0,0 +1,122 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. + * + * Copyright (C) 2019 IBM + * ================================================================================ + * 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.adapters.tasks.inventory; + +import org.camunda.bpm.client.task.ExternalTask; +import org.camunda.bpm.client.task.ExternalTaskService; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.onap.so.client.graphinventory.GraphInventoryCommonObjectMapperProvider; +import org.onap.so.logging.tasks.AuditMDCSetup; +import org.onap.so.objects.audit.AAIObjectAuditList; +import org.onap.so.utils.ExternalTaskUtils; +import org.onap.so.utils.RetrySequenceLevel; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class CreateInventoryTask extends ExternalTaskUtils { + + private static final String UNABLE_TO_WRITE_ALL_INVENTORY_TO_A_AI = "Unable to write all inventory to A&AI"; + + private static final Logger logger = LoggerFactory.getLogger(CreateInventoryTask.class); + + private static final String AAI_INVENTORY_FAILURE = "AAIInventoryFailure"; + + @Autowired + CreateAAIInventory createInventory; + + @Autowired + public AuditMDCSetup mdcSetup; + + public CreateInventoryTask() { + super(RetrySequenceLevel.SHORT); + } + + + public void executeExternalTask(ExternalTask externalTask, ExternalTaskService externalTaskService) { + mdcSetup.setupMDC(externalTask); + boolean success = true; + boolean inventoryException = false; + String auditInventoryString = externalTask.getVariable("auditInventoryResult"); + AAIObjectAuditList auditInventory = null; + String externalTaskId = externalTask.getId(); + try { + GraphInventoryCommonObjectMapperProvider objectMapper = new GraphInventoryCommonObjectMapperProvider(); + auditInventory = objectMapper.getMapper().readValue(auditInventoryString, AAIObjectAuditList.class); + } catch (Exception e) { + mdcSetup.setResponseCode(ONAPLogConstants.ResponseStatus.ERROR.toString()); + logger.error("Error Parsing Audit Results", e); + } + mdcSetup.setElapsedTime(); + if (auditInventory != null) { + Integer retryCount = externalTask.getRetries(); + try { + logger.info("Executing External Task Create Inventory, Retry Number: {} \n {}", auditInventory, + retryCount); + createInventory.createInventory(auditInventory); + } catch (InventoryException e) { + logger.error("Error during inventory of stack", e); + success = false; + inventoryException = true; + } catch (Exception e) { + logger.error("Error during inventory of stack", e); + success = false; + } + mdcSetup.setElapsedTime(); + if (success) { + externalTaskService.complete(externalTask); + mdcSetup.setResponseCode(ONAPLogConstants.ResponseStatus.COMPLETE.toString()); + logger.debug("The External Task Id: {} Successful", externalTaskId); + logger.info(ONAPLogConstants.Markers.EXIT, "Exiting"); + mdcSetup.clearClientMDCs(); + } else if (inventoryException) { + mdcSetup.setResponseCode(ONAPLogConstants.ResponseStatus.ERROR.toString()); + logger.debug("The External Task Id: {} Failed, Retry not needed", externalTaskId); + externalTaskService.handleBpmnError(externalTask, AAI_INVENTORY_FAILURE); + } else { + if (retryCount == null) { + logger.debug("The External Task Id: {} Failed, Setting Retries to Default Start Value: {}", + externalTaskId, getRetrySequence().length); + externalTaskService.handleFailure(externalTask, UNABLE_TO_WRITE_ALL_INVENTORY_TO_A_AI, + UNABLE_TO_WRITE_ALL_INVENTORY_TO_A_AI, getRetrySequence().length, 10000); + } else if (retryCount != null && retryCount - 1 == 0) { + externalTaskService.handleBpmnError(externalTask, AAI_INVENTORY_FAILURE); + mdcSetup.setResponseCode(ONAPLogConstants.ResponseStatus.ERROR.toString()); + logger.debug("The External Task Id: {} Failed, All Retries Exhausted", externalTaskId); + logger.info(ONAPLogConstants.Markers.EXIT, "Exiting"); + } else { + logger.debug("The External Task Id: {} Failed, Decrementing Retries: {} , Retry Delay: ", + externalTaskId, retryCount - 1, calculateRetryDelay(retryCount)); + externalTaskService.handleFailure(externalTask, UNABLE_TO_WRITE_ALL_INVENTORY_TO_A_AI, + UNABLE_TO_WRITE_ALL_INVENTORY_TO_A_AI, retryCount - 1, calculateRetryDelay(retryCount)); + } + logger.debug("The External Task Id: {} Failed", externalTaskId); + } + } else { + logger.debug("The External Task Id: {} Failed, No Audit Results Written", externalTaskId); + externalTaskService.handleBpmnError(externalTask, AAI_INVENTORY_FAILURE); + } + } +} diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/inventory/InventoryException.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/inventory/InventoryException.java new file mode 100644 index 0000000000..7df3822961 --- /dev/null +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/inventory/InventoryException.java @@ -0,0 +1,34 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 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.adapters.tasks.inventory; + +public class InventoryException extends Exception { + + /** + * + */ + private static final long serialVersionUID = 912652713891488731L; + + public InventoryException(String errorMessage) { + super(errorMessage); + } + +} diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/orchestration/PollService.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/orchestration/PollService.java new file mode 100644 index 0000000000..6e181c4696 --- /dev/null +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/orchestration/PollService.java @@ -0,0 +1,191 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Modifications Copyright (c) 2019 Samsung + * ================================================================================ + * 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.adapters.tasks.orchestration; + +import java.io.ByteArrayInputStream; +import java.io.StringReader; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import javax.xml.bind.JAXB; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import org.apache.commons.lang3.mutable.MutableBoolean; +import org.camunda.bpm.client.task.ExternalTask; +import org.camunda.bpm.client.task.ExternalTaskService; +import org.onap.so.adapters.vnfrest.CreateVfModuleRequest; +import org.onap.so.adapters.vnfrest.CreateVolumeGroupRequest; +import org.onap.so.adapters.vnfrest.DeleteVfModuleRequest; +import org.onap.so.adapters.vnfrest.DeleteVolumeGroupRequest; +import org.onap.so.logging.tasks.AuditMDCSetup; +import org.onap.so.openstack.exceptions.MsoException; +import org.onap.so.openstack.utils.MsoHeatUtils; +import org.onap.so.utils.ExternalTaskUtils; +import org.onap.so.utils.RetrySequenceLevel; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import com.woorea.openstack.heat.model.Stack; + +@Component +public class PollService extends ExternalTaskUtils { + + private static final Logger logger = LoggerFactory.getLogger(PollService.class); + + @Autowired + private MsoHeatUtils msoHeatUtils; + + @Autowired + private AuditMDCSetup mdcSetup; + + public PollService() { + super(RetrySequenceLevel.SHORT); + } + + public void executeExternalTask(ExternalTask externalTask, ExternalTaskService externalTaskService) { + mdcSetup.setupMDC(externalTask); + logger.trace("Executing External Task Poll Service"); + Map variables = new HashMap<>(); + MutableBoolean success = new MutableBoolean(); + String errorMessage = null; + try { + String xmlRequest = externalTask.getVariable("vnfAdapterTaskRequest"); + if (xmlRequest != null) { + Optional requestType = findRequestType(xmlRequest); + if ("createVolumeGroupRequest".equals(requestType.get())) { + determineCreateVolumeGroupStatus(xmlRequest, externalTask, success); + } else if ("createVfModuleRequest".equals(requestType.get())) { + determineCreateVfModuleStatus(xmlRequest, externalTask, success); + } else if ("deleteVfModuleRequest".equals(requestType.get())) { + logger.debug("Executing External Task Poll Service for Delete Vf Module"); + DeleteVfModuleRequest req = + JAXB.unmarshal(new StringReader(xmlRequest), DeleteVfModuleRequest.class); + pollDeleteResource(req.getCloudSiteId(), req.getTenantId(), externalTask, success); + } else if ("deleteVolumeGroupRequest".equals(requestType.get())) { + logger.debug("Executing External Task Poll Service for Delete Volume Group"); + DeleteVolumeGroupRequest req = + JAXB.unmarshal(new StringReader(xmlRequest), DeleteVolumeGroupRequest.class); + pollDeleteResource(req.getCloudSiteId(), req.getTenantId(), externalTask, success); + } + } + } catch (Exception e) { + logger.error("Error during External Task Poll Service", e); + errorMessage = e.getMessage(); + } + + variables.put("OpenstackPollSuccess", success.booleanValue()); + variables.put("openstackAdapterErrorMessage", errorMessage); + if (success.isTrue()) { + externalTaskService.complete(externalTask, variables); + logger.debug("The External Task Id: {} Successful", externalTask.getId()); + } else { + if (externalTask.getRetries() == null) { + logger.debug("The External Task Id: {} Failed, Setting Retries to Default Start Value: {}", + externalTask.getId(), getRetrySequence().length); + externalTaskService.handleFailure(externalTask, "errorMessage", "errorDetails", + getRetrySequence().length, 10000); + } else if (externalTask.getRetries() != null && externalTask.getRetries() - 1 == 0) { + logger.debug("The External Task Id: {} Failed, All Retries Exhausted", externalTask.getId()); + externalTaskService.complete(externalTask, variables); + } else { + logger.debug("The External Task Id: {} Failed, Decrementing Retries: {} , Retry Delay: {}", + externalTask.getId(), externalTask.getRetries() - 1, + calculateRetryDelay(externalTask.getRetries())); + externalTaskService.handleFailure(externalTask, "errorMessage", "errorDetails", + externalTask.getRetries() - 1, calculateRetryDelay(externalTask.getRetries())); + } + } + } + + private void determineCreateVolumeGroupStatus(String xmlRequest, ExternalTask externalTask, MutableBoolean success) + throws MsoException { + CreateVolumeGroupRequest req = JAXB.unmarshal(new StringReader(xmlRequest), CreateVolumeGroupRequest.class); + boolean pollRollbackStatus = externalTask.getVariable("PollRollbackStatus"); + if (pollRollbackStatus) { + logger.debug("Executing External Task Poll Service for Rollback Create Volume Group"); + pollDeleteResource(req.getCloudSiteId(), req.getTenantId(), externalTask, success); + } else { + pollCreateResource(req.getCloudSiteId(), req.getTenantId(), externalTask, success); + } + } + + private void determineCreateVfModuleStatus(String xmlRequest, ExternalTask externalTask, MutableBoolean success) + throws MsoException { + CreateVfModuleRequest req = JAXB.unmarshal(new StringReader(xmlRequest), CreateVfModuleRequest.class); + boolean pollRollbackStatus = externalTask.getVariable("PollRollbackStatus"); + if (pollRollbackStatus) { + logger.debug("Executing External Task Poll Service for Rollback Create Vf Module"); + pollDeleteResource(req.getCloudSiteId(), req.getTenantId(), externalTask, success); + } else { + logger.debug("Executing External Task Poll Service for Create Vf Module"); + pollCreateResource(req.getCloudSiteId(), req.getTenantId(), externalTask, success); + } + } + + private void pollCreateResource(String cloudSiteId, String tenantId, ExternalTask externalTask, + MutableBoolean success) throws MsoException { + Stack currentStack = createCurrentStack(externalTask.getVariable("stackId")); + Stack stack = + msoHeatUtils.pollStackForStatus(1, currentStack, "CREATE_IN_PROGRESS", cloudSiteId, tenantId, false); + msoHeatUtils.postProcessStackCreate(stack, false, 0, false, cloudSiteId, tenantId, null); + success.setTrue(); + } + + private void pollDeleteResource(String cloudSiteId, String tenantId, ExternalTask externalTask, + MutableBoolean success) throws MsoException { + Stack currentStack = createCurrentStack(externalTask.getVariable("stackId")); + Stack stack = + msoHeatUtils.pollStackForStatus(1, currentStack, "DELETE_IN_PROGRESS", cloudSiteId, tenantId, true); + if (stack != null) { // if stack is null it was not found and no need to do post process + msoHeatUtils.postProcessStackDelete(stack); + } + success.setTrue(); + } + + protected Optional findRequestType(String xmlString) { + try { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + org.w3c.dom.Document doc; + doc = builder.parse(new ByteArrayInputStream(xmlString.getBytes("UTF-8"))); + return Optional.of(doc.getDocumentElement().getNodeName()); + } catch (Exception e) { + logger.error("Error Finding Request Type", e); + return Optional.empty(); + } + } + + private Stack createCurrentStack(String canonicalStackId) { + Stack currentStack = new Stack(); + String stackName = canonicalStackId; + if (canonicalStackId.contains("/")) { + String[] stacks = canonicalStackId.split("/"); + stackName = stacks[0]; + currentStack.setId(stacks[1]); + } + currentStack.setStackName(stackName); + return currentStack; + } + +} diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/orchestration/RollbackService.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/orchestration/RollbackService.java new file mode 100644 index 0000000000..c302293169 --- /dev/null +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/orchestration/RollbackService.java @@ -0,0 +1,92 @@ +package org.onap.so.adapters.tasks.orchestration; + +import java.io.ByteArrayInputStream; +import java.io.StringReader; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import javax.xml.bind.JAXB; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.ws.Holder; +import org.camunda.bpm.client.task.ExternalTask; +import org.camunda.bpm.client.task.ExternalTaskService; +import org.onap.so.adapters.vnf.MsoVnfAdapterImpl; +import org.onap.so.adapters.vnfrest.CreateVfModuleRequest; +import org.onap.so.adapters.vnfrest.CreateVolumeGroupRequest; +import org.onap.so.logging.tasks.AuditMDCSetup; +import org.onap.so.utils.ExternalTaskUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class RollbackService extends ExternalTaskUtils { + + private static final Logger logger = LoggerFactory.getLogger(RollbackService.class); + + @Autowired + private MsoVnfAdapterImpl vnfAdapterImpl; + + @Autowired + private AuditMDCSetup mdcSetup; + + public void executeExternalTask(ExternalTask externalTask, ExternalTaskService externalTaskService) { + mdcSetup.setupMDC(externalTask); + logger.trace("Executing External Task Rollback Service"); + Map variables = new HashMap<>(); + boolean success = false; + boolean pollRollbackStatus = false; + try { + String xmlRequest = externalTask.getVariable("vnfAdapterTaskRequest"); + if (xmlRequest != null) { + Optional requestType = findRequestType(xmlRequest); + if ("createVolumeGroupRequest".equals(requestType.get())) { + logger.debug("Executing External Task Rollback Service for Create Volume Group"); + CreateVolumeGroupRequest req = + JAXB.unmarshal(new StringReader(xmlRequest), CreateVolumeGroupRequest.class); + vnfAdapterImpl.deleteVnf(req.getCloudSiteId(), req.getCloudOwner(), req.getTenantId(), + req.getVolumeGroupName(), req.getMsoRequest(), false); + pollRollbackStatus = true; + success = true; + } else if ("createVfModuleRequest".equals(requestType.get())) { + logger.debug("Executing External Task Rollback Service for Create Vf Module"); + CreateVfModuleRequest req = + JAXB.unmarshal(new StringReader(xmlRequest), CreateVfModuleRequest.class); + vnfAdapterImpl.deleteVfModule(req.getCloudSiteId(), req.getCloudOwner(), req.getTenantId(), + req.getVfModuleName(), req.getVnfId(), req.getVfModuleId(), req.getModelCustomizationUuid(), + req.getMsoRequest(), new Holder<>()); + pollRollbackStatus = true; + success = true; + } + } + } catch (Exception e) { + logger.error("Error during External Task Rollback Service", e); + } + variables.put("OpenstackRollbackSuccess", success); + variables.put("rollbackPerformed", true); + variables.put("PollRollbackStatus", pollRollbackStatus); + if (success) { + externalTaskService.complete(externalTask, variables); + logger.debug("The External Task Id: {} Successful", externalTask.getId()); + } else { + logger.debug("The External Task Id: {} Failed. Not Retrying", externalTask.getId()); + externalTaskService.complete(externalTask, variables); + } + } + + protected Optional findRequestType(String xmlString) { + try { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + org.w3c.dom.Document doc; + doc = builder.parse(new ByteArrayInputStream(xmlString.getBytes("UTF-8"))); + return Optional.of(doc.getDocumentElement().getNodeName()); + } catch (Exception e) { + logger.error("Error Finding Request Type", e); + return Optional.empty(); + } + } + +} diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/orchestration/StackService.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/orchestration/StackService.java new file mode 100644 index 0000000000..34952a056b --- /dev/null +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/orchestration/StackService.java @@ -0,0 +1,207 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Modifications Copyright (c) 2019 Samsung + * ================================================================================ + * 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.adapters.tasks.orchestration; + +import java.io.ByteArrayInputStream; +import java.io.StringReader; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import javax.xml.bind.JAXB; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.ws.Holder; +import org.apache.commons.lang3.mutable.MutableBoolean; +import org.camunda.bpm.client.task.ExternalTask; +import org.camunda.bpm.client.task.ExternalTaskService; +import org.onap.so.adapters.vnf.MsoVnfAdapterImpl; +import org.onap.so.adapters.vnf.exceptions.VnfException; +import org.onap.so.adapters.vnfrest.CreateVfModuleRequest; +import org.onap.so.adapters.vnfrest.CreateVfModuleResponse; +import org.onap.so.adapters.vnfrest.CreateVolumeGroupRequest; +import org.onap.so.adapters.vnfrest.CreateVolumeGroupResponse; +import org.onap.so.adapters.vnfrest.DeleteVfModuleRequest; +import org.onap.so.adapters.vnfrest.DeleteVfModuleResponse; +import org.onap.so.adapters.vnfrest.DeleteVolumeGroupRequest; +import org.onap.so.adapters.vnfrest.DeleteVolumeGroupResponse; +import org.onap.so.adapters.vnfrest.VfModuleRollback; +import org.onap.so.adapters.vnfrest.VolumeGroupRollback; +import org.onap.so.logging.tasks.AuditMDCSetup; +import org.onap.so.openstack.beans.VnfRollback; +import org.onap.so.utils.ExternalTaskUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class StackService extends ExternalTaskUtils { + + private static final Logger logger = LoggerFactory.getLogger(StackService.class); + + @Autowired + private MsoVnfAdapterImpl vnfAdapterImpl; + + @Autowired + private AuditMDCSetup mdcSetup; + + public void executeExternalTask(ExternalTask externalTask, ExternalTaskService externalTaskService) { + Map variables = new HashMap<>(); + mdcSetup.setupMDC(externalTask); + String xmlRequest = externalTask.getVariable("vnfAdapterTaskRequest"); + logger.debug("Executing External Task Stack Service. {}", xmlRequest); + MutableBoolean success = new MutableBoolean(); + MutableBoolean backout = new MutableBoolean(); + String response = ""; + Holder canonicalStackId = new Holder<>(); + String errorMessage = ""; + try { + if (xmlRequest != null) { + Holder> outputs = new Holder<>(); + Holder vnfRollback = new Holder<>(); + Optional requestType = findRequestType(xmlRequest); + if ("createVolumeGroupRequest".equals(requestType.get())) { + logger.debug("Executing External Task Stack Service For Create Volume Group"); + response = createVolumeGroup(xmlRequest, outputs, vnfRollback, canonicalStackId, backout, success); + } else if ("createVfModuleRequest".equals(requestType.get())) { + logger.debug("Executing External Task Stack Service For Create Vf Module"); + response = createVfModule(xmlRequest, outputs, vnfRollback, canonicalStackId, backout, success); + } else if ("deleteVfModuleRequest".equals(requestType.get())) { + logger.debug("Executing External Task Stack Service For Delete Vf Module"); + response = deleteVfModule(xmlRequest, outputs, vnfRollback, canonicalStackId, backout, success); + } else if ("deleteVolumeGroupRequest".equals(requestType.get())) { + logger.debug("Executing External Task Stack Service For Delete Volume Group"); + response = deleteVolumeGroup(xmlRequest, outputs, vnfRollback, canonicalStackId, backout, success); + } + } + } catch (Exception e) { + logger.error("Error during External Task Stack Service", e); + errorMessage = e.getMessage(); + } + variables.put("backout", backout.booleanValue()); + variables.put("WorkflowResponse", response); + variables.put("OpenstackInvokeSuccess", success.booleanValue()); + variables.put("stackId", canonicalStackId.value); + variables.put("openstackAdapterErrorMessage", errorMessage); + variables.put("PollRollbackStatus", false); + variables.put("rollbackPerformed", false); + variables.put("OpenstackRollbackSuccess", false); + variables.put("OpenstackPollSuccess", false); + + if (success.isTrue()) { + externalTaskService.complete(externalTask, variables); + logger.debug("The External Task Id: {} Successful", externalTask.getId()); + } else { + logger.debug("The External Task Id: {} Failed. Not Retrying", externalTask.getId()); + externalTaskService.complete(externalTask, variables); + } + } + + private String createVolumeGroup(String xmlRequest, Holder> outputs, + Holder vnfRollback, Holder canonicalStackId, MutableBoolean backout, + MutableBoolean success) throws VnfException { + Holder stackId = new Holder<>(); + CreateVolumeGroupRequest req = JAXB.unmarshal(new StringReader(xmlRequest), CreateVolumeGroupRequest.class); + String completeVnfVfModuleType = req.getVnfType() + "::" + req.getVfModuleType(); + vnfAdapterImpl.createVfModule(req.getCloudSiteId(), req.getCloudOwner(), req.getTenantId(), + completeVnfVfModuleType, req.getVnfVersion(), "", req.getVolumeGroupName(), "", "VOLUME", null, null, + req.getModelCustomizationUuid(), req.getVolumeGroupParams(), false, true, req.getEnableBridge(), + req.getMsoRequest(), stackId, outputs, vnfRollback); + success.setTrue(); + backout.setValue(!req.getSuppressBackout()); + VolumeGroupRollback rb = new VolumeGroupRollback(req.getVolumeGroupId(), stackId.value, + vnfRollback.value.getVnfCreated(), req.getTenantId(), req.getCloudOwner(), req.getCloudSiteId(), + req.getMsoRequest(), req.getMessageId()); + canonicalStackId.value = stackId.value; + CreateVolumeGroupResponse createResponse = new CreateVolumeGroupResponse(req.getVolumeGroupId(), stackId.value, + vnfRollback.value.getVnfCreated(), outputs.value, rb, req.getMessageId()); + return createResponse.toXmlString(); + } + + private String createVfModule(String xmlRequest, Holder> outputs, + Holder vnfRollback, Holder canonicalStackId, MutableBoolean backout, + MutableBoolean success) throws VnfException { + Holder stackId = new Holder<>(); + CreateVfModuleRequest req = JAXB.unmarshal(new StringReader(xmlRequest), CreateVfModuleRequest.class); + String completeVnfVfModuleType = req.getVnfType() + "::" + req.getVfModuleType(); + vnfAdapterImpl.createVfModule(req.getCloudSiteId(), req.getCloudOwner(), req.getTenantId(), + completeVnfVfModuleType, req.getVnfVersion(), req.getVnfId(), req.getVfModuleName(), + req.getVfModuleId(), req.getRequestType(), req.getVolumeGroupStackId(), req.getBaseVfModuleStackId(), + req.getModelCustomizationUuid(), req.getVfModuleParams(), false, false, req.getEnableBridge(), + req.getMsoRequest(), stackId, outputs, vnfRollback); + success.setTrue(); + backout.setValue(req.getBackout()); + canonicalStackId.value = stackId.value; + VfModuleRollback modRollback = + new VfModuleRollback(vnfRollback.value, req.getVfModuleId(), stackId.value, req.getMessageId()); + CreateVfModuleResponse createResponse = new CreateVfModuleResponse(req.getVnfId(), req.getVfModuleId(), + stackId.value, Boolean.TRUE, outputs.value, modRollback, req.getMessageId()); + return createResponse.toXmlString(); + } + + private String deleteVfModule(String xmlRequest, Holder> outputs, + Holder vnfRollback, Holder canonicalStackId, MutableBoolean backout, + MutableBoolean success) throws VnfException { + backout.setFalse(); + DeleteVfModuleRequest req = JAXB.unmarshal(new StringReader(xmlRequest), DeleteVfModuleRequest.class); + vnfAdapterImpl.deleteVfModule(req.getCloudSiteId(), req.getCloudOwner(), req.getTenantId(), + req.getVfModuleStackId(), req.getVnfId(), req.getVfModuleId(), req.getModelCustomizationUuid(), + req.getMsoRequest(), outputs); + success.setTrue(); + if (outputs != null && outputs.value != null) { + canonicalStackId.value = outputs.value.get("canonicalStackId"); + } else { + canonicalStackId.value = req.getVfModuleStackId(); + } + DeleteVfModuleResponse deleteResponse = new DeleteVfModuleResponse(req.getVnfId(), req.getVfModuleId(), + Boolean.TRUE, req.getMessageId(), outputs.value); + return deleteResponse.toXmlString(); + } + + private String deleteVolumeGroup(String xmlRequest, Holder> outputs, + Holder vnfRollback, Holder canonicalStackId, MutableBoolean backout, + MutableBoolean success) throws VnfException { + backout.setFalse(); + DeleteVolumeGroupRequest req = JAXB.unmarshal(new StringReader(xmlRequest), DeleteVolumeGroupRequest.class); + + vnfAdapterImpl.deleteVnf(req.getCloudSiteId(), req.getCloudOwner(), req.getTenantId(), + req.getVolumeGroupStackId(), req.getMsoRequest(), false); + success.setTrue(); + canonicalStackId.value = req.getVolumeGroupStackId(); + DeleteVolumeGroupResponse deleteResponse = new DeleteVolumeGroupResponse(true, req.getMessageId()); + return deleteResponse.toXmlString(); + } + + protected Optional findRequestType(String xmlString) { + try { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + org.w3c.dom.Document doc; + doc = builder.parse(new ByteArrayInputStream(xmlString.getBytes("UTF-8"))); + return Optional.of(doc.getDocumentElement().getNodeName()); + } catch (Exception e) { + logger.error("Error Finding Request Type", e); + return Optional.empty(); + } + } +} diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfAdapterImpl.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfAdapterImpl.java index 60c5a0ca2a..3a2d3bc5eb 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfAdapterImpl.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfAdapterImpl.java @@ -322,6 +322,42 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { return; } + /** + * This is the "Delete VNF" web service implementation. It will delete a VNF by name or ID in the specified cloud + * and tenant. + * + * The method has no outputs. + * + * @param cloudSiteId CLLI code of the cloud site in which to delete + * @param cloudOwner cloud owner of the cloud region in which to delete + * @param tenantId Openstack tenant identifier + * @param vnfName VNF Name or Openstack ID + * @param msoRequest Request tracking information for logs + */ + public void deleteVnf(String cloudSiteId, String cloudOwner, String tenantId, String vnfName, MsoRequest msoRequest, + boolean pollStackStatus) throws VnfException { + + logger.debug("Deleting VNF {} in {}", vnfName, cloudSiteId + "/" + tenantId); + + try { + msoHeatUtils.deleteStack(tenantId, cloudOwner, cloudSiteId, vnfName, pollStackStatus, 118); + } catch (MsoException me) { + me.addContext(DELETE_VNF); + // Failed to query the Stack due to an openstack exception. + // Convert to a generic VnfException + String error = + "Delete VNF: " + vnfName + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me; + logger.error(LoggingAnchor.NINE, MessageEnum.RA_DELETE_VNF_ERR.toString(), vnfName, cloudOwner, cloudSiteId, + tenantId, OPENSTACK, DELETE_VNF, ErrorCode.DataError.getValue(), "Exception - " + DELETE_VNF, me); + logger.debug(error); + throw new VnfException(me); + } + + // On success, nothing is returned. + return; + } + + /** * This web service endpoint will rollback a previous Create VNF operation. A rollback object is returned to the * client in a successful creation response. The client can pass that object as-is back to the rollbackVnf operation @@ -536,6 +572,7 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { Map inputs, Boolean failIfExists, Boolean backout, Boolean enableBridge, MsoRequest msoRequest, Holder vnfId, Holder> outputs, Holder rollback) throws VnfException { + boolean pollForCompletion = false; String vfModuleName = vnfName; String vfModuleType = vnfType; String vfVersion = vnfVersion; @@ -1050,8 +1087,9 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { } if (msoHeatUtils != null) { heatStack = msoHeatUtils.createStack(cloudSiteId, cloudOwner, tenantId, vfModuleName, null, - template, goldenInputs, true, heatTemplate.getTimeoutMinutes(), newEnvironmentString, - nestedTemplatesChecked, heatFilesObjects, backout.booleanValue(), failIfExists); + template, goldenInputs, pollForCompletion, heatTemplate.getTimeoutMinutes(), + newEnvironmentString, nestedTemplatesChecked, heatFilesObjects, backout.booleanValue(), + failIfExists); if (msoRequest.getRequestId() != null) { msoHeatUtils.updateResourceStatus(msoRequest.getRequestId(), heatStack.isOperationPerformed() ? VF_EXIST_STATUS_MESSAGE : VF_CREATED_STATUS_MESSAGE); @@ -1135,10 +1173,15 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { } try { - StackInfo stackInfo = - msoHeatUtils.deleteStack(tenantId, cloudOwner, cloudSiteId, vnfName, true, timeoutMinutes); + StackInfo currentStack = + msoHeatUtils.deleteStack(tenantId, cloudOwner, cloudSiteId, vnfName, false, timeoutMinutes); + if (currentStack != null && outputs != null && outputs.value != null) { + logger.debug("Adding canonical stack id to outputs " + currentStack.getCanonicalName()); + outputs.value.put("canonicalStackId", currentStack.getCanonicalName()); + } msoHeatUtils.updateResourceStatus(msoRequest.getRequestId(), - stackInfo.isOperationPerformed() ? VF_DELETED_STATUS_MESSAGE : VF_NOT_EXIST_STATUS_MESSAGE); + currentStack.isOperationPerformed() ? VF_DELETED_STATUS_MESSAGE : VF_NOT_EXIST_STATUS_MESSAGE); + } catch (MsoException me) { me.addContext(DELETE_VNF); // Failed to query the Stack due to an openstack exception. diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VnfAdapterRest.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VnfAdapterRest.java index 0836f69ba7..5b78d2f066 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VnfAdapterRest.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VnfAdapterRest.java @@ -78,6 +78,7 @@ import io.swagger.annotations.ApiResponses; * can be produced/consumed. Set Accept: and Content-Type: headers appropriately. XML is the default. For testing, call * with cloudSiteId = ___TESTING___ To test exceptions, also set tenantId = ___TESTING___ */ +@Deprecated @Path("/v1/vnfs") @Api(value = "/v1/vnfs", description = "root of vnf adapters restful web service") @Transactional diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VnfAdapterRestV2.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VnfAdapterRestV2.java index 18ed9872a0..63b4c5d0f3 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VnfAdapterRestV2.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VnfAdapterRestV2.java @@ -39,7 +39,6 @@ import javax.ws.rs.core.GenericEntity; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.xml.ws.Holder; -import org.onap.so.logger.LoggingAnchor; import org.apache.http.HttpStatus; import org.onap.logging.ref.slf4j.ONAPLogConstants; import org.onap.so.adapters.vnf.exceptions.VnfException; @@ -56,6 +55,7 @@ import org.onap.so.adapters.vnfrest.VfModuleExceptionResponse; import org.onap.so.adapters.vnfrest.VfModuleRollback; import org.onap.so.entity.MsoRequest; import org.onap.logging.filter.base.ErrorCode; +import org.onap.so.logger.LoggingAnchor; import org.onap.so.logger.MessageEnum; import org.onap.so.openstack.beans.VnfRollback; import org.onap.so.openstack.beans.VnfStatus; @@ -78,6 +78,7 @@ import io.swagger.annotations.ApiResponses; * * V2 incorporates run-time selection of sub-orchestrator implementation (Heat or Cloudify) based on the target cloud. */ +@Deprecated @Path("/v2/vnfs") @Api(value = "/v2/vnfs", description = "root of vnf adapters restful web service v2") @Component @@ -189,10 +190,7 @@ public class VnfAdapterRestV2 { } String cloudsite = req.getCloudSiteId(); Holder> outputs = new Holder<>(); - if (cloudsite != null && !cloudsite.equals(TESTING_KEYWORD)) { - // vnfAdapter.deleteVnf (req.getCloudSiteId(), req.getTenantId(), req.getVfModuleStackId(), - // req.getMsoRequest()); - // Support different Adapter Implementations + if (cloudsite != null) { MsoVnfAdapter adapter = vnfAdapterRestUtils.getVnfAdapterImpl(mode, cloudsite); adapter.deleteVfModule(req.getCloudSiteId(), req.getCloudOwner(), req.getTenantId(), req.getVfModuleStackId(), req.getVnfId(), req.getVfModuleId(), diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VolumeAdapterRestV2.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VolumeAdapterRestV2.java index cfddbba34e..a424fa92fd 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VolumeAdapterRestV2.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VolumeAdapterRestV2.java @@ -174,33 +174,26 @@ public class VolumeAdapterRestV2 { logger.debug("in createVfModuleVolumes - completeVnfVfModuleType={}", completeVnfVfModuleType); String cloudsiteId = req.getCloudSiteId(); - if (cloudsiteId != null && cloudsiteId.equals(TESTING_KEYWORD)) { - String tenant = req.getTenantId(); - if (tenant != null && tenant.equals(TESTING_KEYWORD)) { - throw new VnfException("testing."); - } - stackId.value = "479D3D8B-6360-47BC-AB75-21CC91981484"; - outputs.value = testMap(); - } else { - // Support different Adapter Implementations - MsoVnfAdapter vnfAdapter = vnfAdapterRestUtils.getVnfAdapterImpl(mode, cloudsiteId); - vnfAdapter.createVfModule(req.getCloudSiteId(), // cloudSiteId, - req.getCloudOwner(), // cloudOwner, - req.getTenantId(), // tenantId, - completeVnfVfModuleType, // vnfType, - req.getVnfVersion(), // vnfVersion, - "", // genericVnfId - req.getVolumeGroupName(), // vnfName, - "", // vfModuleId - "VOLUME", // requestType, - null, // volumeGroupHeatStackId, - null, // baseVfHeatStackId, - req.getModelCustomizationUuid(), req.getVolumeGroupParams(), // inputs, - req.getFailIfExists(), // failIfExists, - req.getSuppressBackout(), // backout, - req.getEnableBridge(), req.getMsoRequest(), // msoRequest, - stackId, outputs, vnfRollback); - } + + // Support different Adapter Implementations + MsoVnfAdapter vnfAdapter = vnfAdapterRestUtils.getVnfAdapterImpl(mode, cloudsiteId); + vnfAdapter.createVfModule(req.getCloudSiteId(), // cloudSiteId, + req.getCloudOwner(), // cloudOwner, + req.getTenantId(), // tenantId, + completeVnfVfModuleType, // vnfType, + req.getVnfVersion(), // vnfVersion, + "", // genericVnfId + req.getVolumeGroupName(), // vnfName, + "", // vfModuleId + "VOLUME", // requestType, + null, // volumeGroupHeatStackId, + null, // baseVfHeatStackId, + req.getModelCustomizationUuid(), req.getVolumeGroupParams(), // inputs, + req.getFailIfExists(), // failIfExists, + req.getSuppressBackout(), // backout, + req.getEnableBridge(), req.getMsoRequest(), // msoRequest, + stackId, outputs, vnfRollback); + VolumeGroupRollback rb = new VolumeGroupRollback(req.getVolumeGroupId(), stackId.value, vnfRollback.value.getVnfCreated(), req.getTenantId(), req.getCloudOwner(), req.getCloudSiteId(), diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/audit/AuditDataServiceTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/audit/AuditDataServiceTest.java deleted file mode 100644 index d3380a6a33..0000000000 --- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/audit/AuditDataServiceTest.java +++ /dev/null @@ -1,101 +0,0 @@ -package org.onap.so.adapters.audit; - -import static org.junit.Assert.assertEquals; -import static org.mockito.ArgumentMatchers.any; -import static org.mockito.Mockito.when; -import java.util.ArrayList; -import java.util.List; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; -import org.onap.aai.domain.yang.Vserver; -import org.onap.so.audit.beans.AuditInventory; -import org.onap.so.client.graphinventory.GraphInventoryCommonObjectMapperProvider; -import org.onap.so.db.request.beans.RequestProcessingData; -import org.onap.so.db.request.client.RequestsDbClient; -import org.onap.so.objects.audit.AAIObjectAudit; -import org.onap.so.objects.audit.AAIObjectAuditList; -import com.fasterxml.jackson.core.JsonProcessingException; - -@RunWith(MockitoJUnitRunner.Silent.class) -public class AuditDataServiceTest { - - @InjectMocks - AuditDataService auditDataService = new AuditDataService(); - - @Mock - protected RequestsDbClient requestsDbClient; - - AuditInventory auditInventory = new AuditInventory(); - - @Before - public void before() throws JsonProcessingException { - auditInventory.setCloudOwner("testCloudOwner"); - auditInventory.setCloudRegion("testLcpCloudRegionId"); - auditInventory.setHeatStackName("testVfModuleName1"); - auditInventory.setVfModuleId("testVnfModuleId"); - auditInventory.setTenantId("testTenantId"); - auditInventory.setGenericVnfId("testVnfId1"); - } - - @Test - public void testWriteStackDataToRequestDb() throws Exception { - Mockito.doReturn(new ArrayList()).when(requestsDbClient) - .getRequestProcessingDataByGroupingIdAndNameAndTag(Mockito.any(), Mockito.any(), Mockito.any()); - Mockito.doNothing().when(requestsDbClient).saveRequestProcessingData(Mockito.any()); - - AAIObjectAuditList auditList = new AAIObjectAuditList(); - auditList.setHeatStackName("testHeatStackName"); - AAIObjectAudit audit = new AAIObjectAudit(); - Vserver vserver = new Vserver(); - vserver.setVserverId("testVserverId"); - audit.setAaiObject(vserver); - auditList.getAuditList().add(audit); - - GraphInventoryCommonObjectMapperProvider objectMapper = new GraphInventoryCommonObjectMapperProvider(); - String auditListString = objectMapper.getMapper().writeValueAsString(auditList);; - - RequestProcessingData requestProcessingData = new RequestProcessingData(); - requestProcessingData.setSoRequestId(auditInventory.getMsoRequestId()); - requestProcessingData.setGroupingId(auditInventory.getVfModuleId()); - requestProcessingData.setName(auditInventory.getHeatStackName()); - requestProcessingData.setTag("AuditStackData"); - requestProcessingData.setValue(auditListString); - - auditDataService.writeStackDataToRequestDb(auditInventory, auditList); - Mockito.verify(requestsDbClient, Mockito.times(1)).saveRequestProcessingData(requestProcessingData); - } - - @Test - public void testGetStackDataToRequestDb() throws Exception { - AAIObjectAuditList auditList = new AAIObjectAuditList(); - auditList.setHeatStackName("testHeatStackName"); - AAIObjectAudit audit = new AAIObjectAudit(); - Vserver vserver = new Vserver(); - vserver.setVserverId("testVserverId"); - audit.setAaiObject(vserver); - auditList.getAuditList().add(audit); - GraphInventoryCommonObjectMapperProvider objectMapper = new GraphInventoryCommonObjectMapperProvider(); - String auditListString = objectMapper.getMapper().writeValueAsString(audit); - - List list = new ArrayList(); - RequestProcessingData requestProcessingData = new RequestProcessingData(); - requestProcessingData.setId(234321432); - requestProcessingData.setGroupingId("testVfModuleId"); - requestProcessingData.setName("heatStackName"); - requestProcessingData.setTag("AuditStackData"); - requestProcessingData.setValue(auditListString); - list.add(requestProcessingData); - - Mockito.doReturn(list).when(requestsDbClient).getRequestProcessingDataByGroupingIdAndNameAndTag(Mockito.any(), - Mockito.any(), Mockito.any()); - auditDataService.getStackDataFromRequestDb(auditInventory); - Mockito.verify(requestsDbClient, Mockito.times(1)).getRequestProcessingDataByGroupingIdAndNameAndTag( - "testVnfModuleId", "testVfModuleName1", "AuditStackData"); - } - -} diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/audit/AuditStackServiceDataTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/audit/AuditStackServiceDataTest.java deleted file mode 100644 index cff4d5f994..0000000000 --- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/audit/AuditStackServiceDataTest.java +++ /dev/null @@ -1,187 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017-2019 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.adapters.audit; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.mockito.Mockito.doReturn; -import java.io.File; -import java.io.IOException; -import java.util.Map; -import java.util.Optional; -import org.camunda.bpm.client.task.ExternalTask; -import org.camunda.bpm.client.task.ExternalTaskService; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; -import org.onap.so.audit.beans.AuditInventory; -import org.onap.so.externaltasks.logging.AuditMDCSetup; -import org.onap.so.objects.audit.AAIObjectAuditList; -import org.springframework.core.env.Environment; -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.core.JsonProcessingException; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.ObjectMapper; - -public class AuditStackServiceDataTest extends AuditCreateStackService { - - @InjectMocks - private AuditCreateStackService auditStackService = new AuditCreateStackService(); - - @InjectMocks - private AuditQueryStackService auditQueryStackService = new AuditQueryStackService(); - - @Mock - private HeatStackAudit heatStackAuditMock; - - @Mock - private Environment mockEnv; - - @Mock - private ExternalTask mockExternalTask; - - @Mock - private ExternalTaskService mockExternalTaskService; - - @Mock - private AuditDataService auditDataService; - - @Mock - private AuditMDCSetup mdcSetup; - - private ObjectMapper objectMapper = new ObjectMapper(); - - private AuditInventory auditInventory = new AuditInventory(); - - Optional auditListOptSuccess; - - Optional auditListOptFailure; - - @Before - public void setup() throws JsonParseException, JsonMappingException, IOException { - auditInventory.setCloudOwner("cloudOwner"); - auditInventory.setCloudRegion("cloudRegion"); - auditInventory.setTenantId("tenantId"); - auditInventory.setHeatStackName("stackName"); - MockitoAnnotations.initMocks(this); - - AAIObjectAuditList auditListSuccess = objectMapper - .readValue(new File("src/test/resources/ExpectedVServerFound.json"), AAIObjectAuditList.class); - auditListOptSuccess = Optional.of(auditListSuccess); - - AAIObjectAuditList auditListFailure = objectMapper.readValue( - new File("src/test/resources/Vserver2_Found_VServer1_Not_Found.json"), AAIObjectAuditList.class); - auditListOptFailure = Optional.of(auditListFailure); - String[] retrySequence = new String[8]; - retrySequence[0] = "1"; - retrySequence[1] = "1"; - retrySequence[2] = "2"; - retrySequence[3] = "3"; - retrySequence[4] = "5"; - retrySequence[5] = "8"; - retrySequence[6] = "13"; - retrySequence[7] = "20"; - doReturn(auditInventory).when(mockExternalTask).getVariable("auditInventory"); - doReturn("6000").when(mockEnv).getProperty("mso.workflow.topics.retryMultiplier", "6000"); - doReturn(retrySequence).when(mockEnv).getProperty("mso.workflow.topics.retrySequence", String[].class); - doReturn("aasdfasdf").when(mockExternalTask).getId(); - } - - @Test - public void execute_external_task_audit_success_Test() { - doReturn(auditListOptSuccess).when(heatStackAuditMock).auditHeatStack("cloudRegion", "cloudOwner", "tenantId", - "stackName"); - auditStackService.executeExternalTask(mockExternalTask, mockExternalTaskService); - ArgumentCaptor captor = ArgumentCaptor.forClass(Map.class); - ArgumentCaptor taskCaptor = ArgumentCaptor.forClass(ExternalTask.class); - Mockito.verify(mockExternalTaskService).complete(taskCaptor.capture(), captor.capture()); - Map actualMap = captor.getValue(); - assertEquals(true, actualMap.get("auditIsSuccessful")); - assertNotNull(actualMap.get("auditInventoryResult")); - } - - @Test - public void executeExternalTaskQueryAuditTest() throws JsonProcessingException { - doReturn(auditListOptSuccess).when(heatStackAuditMock).queryHeatStack("cloudOwner", "cloudRegion", "tenantId", - "stackName"); - Mockito.doNothing().when(auditDataService).writeStackDataToRequestDb(Mockito.any(AuditInventory.class), - Mockito.any(AAIObjectAuditList.class)); - auditQueryStackService.executeExternalTask(mockExternalTask, mockExternalTaskService); - ArgumentCaptor captor = ArgumentCaptor.forClass(Map.class); - ArgumentCaptor taskCaptor = ArgumentCaptor.forClass(ExternalTask.class); - Mockito.verify(mockExternalTaskService).complete(taskCaptor.capture(), captor.capture()); - Mockito.verify(auditDataService).writeStackDataToRequestDb(Mockito.any(AuditInventory.class), - Mockito.any(AAIObjectAuditList.class)); - } - - @Test - public void execute_external_task_audit_first_failure_Test() { - doReturn(auditListOptFailure).when(heatStackAuditMock).auditHeatStack("cloudRegion", "cloudOwner", "tenantId", - "stackName"); - doReturn(null).when(mockExternalTask).getRetries(); - auditStackService.executeExternalTask(mockExternalTask, mockExternalTaskService); - Mockito.verify(mockExternalTaskService).handleFailure(mockExternalTask, - "Unable to find all VServers and L-Interaces in A&AI", - "Unable to find all VServers and L-Interaces in A&AI", 8, 10000L); - } - - @Test - public void execute_external_task_audit_intermediate_failure_Test() { - doReturn(auditListOptFailure).when(heatStackAuditMock).auditHeatStack("cloudRegion", "cloudOwner", "tenantId", - "stackName"); - doReturn(6).when(mockExternalTask).getRetries(); - auditStackService.executeExternalTask(mockExternalTask, mockExternalTaskService); - Mockito.verify(mockExternalTaskService).handleFailure(mockExternalTask, - "Unable to find all VServers and L-Interaces in A&AI", - "Unable to find all VServers and L-Interaces in A&AI", 5, 12000L); - - } - - @Test - public void execute_external_task_audit_final_failure_Test() { - doReturn(auditListOptFailure).when(heatStackAuditMock).auditHeatStack("cloudRegion", "cloudOwner", "tenantId", - "stackName"); - doReturn(1).when(mockExternalTask).getRetries(); - auditStackService.executeExternalTask(mockExternalTask, mockExternalTaskService); - ArgumentCaptor captor = ArgumentCaptor.forClass(Map.class); - ArgumentCaptor taskCaptor = ArgumentCaptor.forClass(ExternalTask.class); - Mockito.verify(mockExternalTaskService).complete(taskCaptor.capture(), captor.capture()); - Map actualMap = captor.getValue(); - assertEquals(false, actualMap.get("auditIsSuccessful")); - assertNotNull(actualMap.get("auditInventoryResult")); - } - - @Test - public void determineAuditResult_Test() throws Exception { - boolean actual = auditStackService.didCreateAuditFail(auditListOptSuccess); - assertEquals(false, actual); - } - - @Test - public void determineAuditResult_Failure_Test() throws Exception { - boolean actual = auditStackService.didCreateAuditFail(auditListOptFailure); - assertEquals(true, actual); - } -} diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/audit/AuditVServerTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/audit/AuditVServerTest.java deleted file mode 100644 index 8e71ec46b0..0000000000 --- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/audit/AuditVServerTest.java +++ /dev/null @@ -1,432 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017-2019 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 perservice2sions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.audit; - -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.doReturn; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.util.HashSet; -import java.util.Optional; -import java.util.Set; -import org.junit.Assert; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.junit.MockitoJUnitRunner; -import org.onap.aai.domain.yang.LInterface; -import org.onap.aai.domain.yang.LInterfaces; -import org.onap.aai.domain.yang.VfModule; -import org.onap.aai.domain.yang.VfModules; -import org.onap.aai.domain.yang.Vserver; -import org.onap.so.client.aai.AAIObjectPlurals; -import org.onap.so.client.aai.AAIObjectType; -import org.onap.so.client.aai.AAIResourcesClient; -import org.onap.so.client.aai.entities.AAIResultWrapper; -import org.onap.so.client.aai.entities.uri.AAIResourceUri; -import org.onap.so.client.aai.entities.uri.AAIUriFactory; -import org.onap.so.objects.audit.AAIObjectAudit; -import org.onap.so.objects.audit.AAIObjectAuditList; -import org.skyscreamer.jsonassert.JSONAssert; -import com.fasterxml.jackson.annotation.JsonInclude.Include; -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.ObjectMapper; - -@RunWith(MockitoJUnitRunner.Silent.class) -public class AuditVServerTest extends AuditVServer { - - private ObjectMapper objectMapper = new ObjectMapper(); - - @InjectMocks - private AuditVServer auditNova = new AuditVServer(); - - @Mock - private AAIResourcesClient aaiResourcesMock; - - private String cloudOwner = "cloudOwner"; - private String cloudRegion = "cloudRegion"; - private String tenantId = "tenantId"; - - private AAIResourceUri vserverURI = AAIUriFactory.createResourceUri(AAIObjectType.VSERVER, cloudOwner, cloudRegion, - tenantId, "3a4c2ca5-27b3-4ecc-98c5-06804867c4db"); - - private AAIResourceUri vserverURI2 = AAIUriFactory.createResourceUri(AAIObjectType.VSERVER, cloudOwner, cloudRegion, - tenantId, "3a4c2ca5-27b3-4ecc-98c5-06804867c4dz"); - - private AAIResourceUri ssc_1_trusted_port_0_uri = AAIUriFactory.createResourceUri(AAIObjectType.L_INTERFACE, - cloudOwner, cloudRegion, tenantId, "3a4c2ca5-27b3-4ecc-98c5-06804867c4db", "ssc_1_trusted_port_0"); - - private AAIResourceUri ssc_1_service1_port_0_uri = AAIUriFactory.createResourceUri(AAIObjectType.L_INTERFACE, - cloudOwner, cloudRegion, tenantId, "3a4c2ca5-27b3-4ecc-98c5-06804867c4db", "ssc_1_service1_port_0"); - - private AAIResourceUri ssc_1_mgmt_port_1_uri = AAIUriFactory.createResourceUri(AAIObjectType.L_INTERFACE, - cloudOwner, cloudRegion, tenantId, "3a4c2ca5-27b3-4ecc-98c5-06804867c4db", "ssc_1_mgmt_port_1"); - - private AAIResourceUri ssc_1_mgmt_port_0_uri = AAIUriFactory.createResourceUri(AAIObjectType.L_INTERFACE, - cloudOwner, cloudRegion, tenantId, "3a4c2ca5-27b3-4ecc-98c5-06804867c4db", "ssc_1_mgmt_port_0"); - - private AAIResourceUri ssc_1_service2_port_0_uri = AAIUriFactory.createResourceUri(AAIObjectType.L_INTERFACE, - cloudOwner, cloudRegion, tenantId, "3a4c2ca5-27b3-4ecc-98c5-06804867c4db", "ssc_1_service2_port_0"); - - private AAIResourceUri ssc_1_int_ha_port_0_uri = AAIUriFactory.createResourceUri(AAIObjectType.L_INTERFACE, - cloudOwner, cloudRegion, tenantId, "3a4c2ca5-27b3-4ecc-98c5-06804867c4db", "ssc_1_int_ha_port_0"); - - private AAIResourceUri test_port_1_uri = AAIUriFactory.createResourceUri(AAIObjectType.L_INTERFACE, cloudOwner, - cloudRegion, tenantId, "3a4c2ca5-27b3-4ecc-98c5-06804867c4dz", "test_port_1"); - - private AAIResourceUri test_port_2_uri = AAIUriFactory.createResourceUri(AAIObjectType.L_INTERFACE, cloudOwner, - cloudRegion, tenantId, "3a4c2ca5-27b3-4ecc-98c5-06804867c4dz", "test_port_2"); - - private AAIResourceUri service2_sub_1_uri = - AAIUriFactory.createResourceUri(AAIObjectType.SUB_L_INTERFACE, cloudOwner, cloudRegion, tenantId, - "3a4c2ca5-27b3-4ecc-98c5-06804867c4db", "ssc_1_service2_port_0", "service2_sub_interface_1"); - - private AAIResourceUri service1_sub_0_uri = - AAIUriFactory.createResourceUri(AAIObjectType.SUB_L_INTERFACE, cloudOwner, cloudRegion, tenantId, - "3a4c2ca5-27b3-4ecc-98c5-06804867c4db", "ssc_1_service1_port_0", "service1_sub_interface_1"); - - private AAIResourceUri service1_sub_1_uri = - AAIUriFactory.createResourceUri(AAIObjectType.SUB_L_INTERFACE, cloudOwner, cloudRegion, tenantId, - "3a4c2ca5-27b3-4ecc-98c5-06804867c4db", "ssc_1_service1_port_0", "service1_sub_interface_2"); - - - - private Set vserversToAudit = new HashSet<>(); - - LInterface test_port_1 = new LInterface(); - LInterface test_port_2 = new LInterface(); - LInterface ssc_1_int_ha_port_0 = new LInterface(); - LInterface service2_sub_interface_1 = new LInterface(); - LInterface ssc_1_service2_port_0 = new LInterface(); - LInterface ssc_1_mgmt_port_0 = new LInterface(); - LInterface ssc_1_mgmt_port_1 = new LInterface(); - LInterface service1_sub_interface_2 = new LInterface(); - LInterface service1_sub_interface_1 = new LInterface(); - LInterface ssc_1_service1_port_0 = new LInterface(); - LInterface ssc_1_trusted_port_0 = new LInterface(); - - - - @Before - public void setup() { - objectMapper.setSerializationInclusion(Include.NON_NULL); - auditNova.setAaiClient(aaiResourcesMock); - - Vserver vServer1 = new Vserver(); - vServer1.setVserverId("3a4c2ca5-27b3-4ecc-98c5-06804867c4db"); - LInterfaces vServer1Linterfaces = new LInterfaces(); - vServer1.setLInterfaces(vServer1Linterfaces); - - ssc_1_trusted_port_0.setInterfaceId("dec8bdc7-5718-41dc-bfbb-561ff6eeb81c"); - ssc_1_trusted_port_0.setInterfaceName("ssc_1_trusted_port_0"); - vServer1.getLInterfaces().getLInterface().add(ssc_1_trusted_port_0); - - - ssc_1_service1_port_0.setInterfaceId("1c56a24b-5f03-435a-850d-31cd4252de56"); - ssc_1_service1_port_0.setInterfaceName("ssc_1_service1_port_0"); - vServer1.getLInterfaces().getLInterface().add(ssc_1_service1_port_0); - ssc_1_service1_port_0.setLInterfaces(new LInterfaces()); - - - service1_sub_interface_1.setInterfaceId("0d9cd813-2ae1-46c0-9ebb-48081f6cffbb"); - service1_sub_interface_1.setInterfaceName("service1_sub_interface_1"); - ssc_1_service1_port_0.getLInterfaces().getLInterface().add(service1_sub_interface_1); - - - service1_sub_interface_2.setInterfaceId("b7019dd0-2ee9-4447-bdef-ac25676b205a"); - service1_sub_interface_2.setInterfaceName("service1_sub_interface_2"); - ssc_1_service1_port_0.getLInterfaces().getLInterface().add(service1_sub_interface_2); - - - ssc_1_mgmt_port_1.setInterfaceId("12afcd28-929f-4d80-8a5a-0833bfd5e20b"); - ssc_1_mgmt_port_1.setInterfaceName("ssc_1_mgmt_port_1"); - vServer1.getLInterfaces().getLInterface().add(ssc_1_mgmt_port_1); - - ssc_1_mgmt_port_0.setInterfaceId("80baec42-ffae-425f-ad8c-3f7b2c24bfff"); - ssc_1_mgmt_port_0.setInterfaceName("ssc_1_mgmt_port_0"); - vServer1.getLInterfaces().getLInterface().add(ssc_1_mgmt_port_0); - - - ssc_1_service2_port_0.setLInterfaces(new LInterfaces()); - ssc_1_service2_port_0.setInterfaceId("13eddf95-4cf3-45f2-823a-2d890a6549b4"); - ssc_1_service2_port_0.setInterfaceName("ssc_1_service2_port_0"); - vServer1.getLInterfaces().getLInterface().add(ssc_1_service2_port_0); - - - service2_sub_interface_1.setInterfaceId("f711be16-2654-4a09-b89d-0511fda20e81"); - service2_sub_interface_1.setInterfaceName("service2_sub_interface_1"); - ssc_1_service2_port_0.getLInterfaces().getLInterface().add(service2_sub_interface_1); - - - ssc_1_int_ha_port_0.setInterfaceId("9cab2903-70f7-44fd-b681-491d6ae2adb8"); - ssc_1_int_ha_port_0.setInterfaceName("ssc_1_int_ha_port_0"); - vServer1.getLInterfaces().getLInterface().add(ssc_1_int_ha_port_0); - - Vserver vServer2 = new Vserver(); - vServer2.setVserverId("3a4c2ca5-27b3-4ecc-98c5-06804867c4dz"); - LInterfaces vServer2Linterfaces = new LInterfaces(); - vServer2.setLInterfaces(vServer2Linterfaces); - - test_port_1.setInterfaceId("9cab2903-70f7-44fd-b681-491d6ae2adz1"); - test_port_1.setInterfaceName("test_port_1"); - - - test_port_2.setInterfaceId("9cab2903-70f7-44fd-b681-491d6ae2adz2"); - test_port_2.setInterfaceName("test_port_2"); - - vServer2.getLInterfaces().getLInterface().add(test_port_1); - vServer2.getLInterfaces().getLInterface().add(test_port_2); - - vserversToAudit.add(vServer1); - vserversToAudit.add(vServer2); - } - - @Test - public void audit_Vserver_Empty_HashSet() throws JsonParseException, JsonMappingException, IOException { - Optional actual = - auditNova.auditVservers(new HashSet(), tenantId, cloudOwner, cloudRegion); - assertEquals(Optional.empty(), actual); - } - - @Test - public void audit_Vserver_Found_Test() throws JsonParseException, JsonMappingException, IOException { - doReturn(true).when(aaiResourcesMock).exists(vserverURI); - doReturn(true).when(aaiResourcesMock).exists(vserverURI2); - doReturn(Optional.of(ssc_1_trusted_port_0)).when(aaiResourcesMock).get(LInterface.class, - ssc_1_trusted_port_0_uri); - doReturn(Optional.of(ssc_1_service1_port_0)).when(aaiResourcesMock).get(LInterface.class, - ssc_1_service1_port_0_uri); - doReturn(Optional.of(ssc_1_mgmt_port_1)).when(aaiResourcesMock).get(LInterface.class, ssc_1_mgmt_port_1_uri); - doReturn(Optional.of(ssc_1_mgmt_port_0)).when(aaiResourcesMock).get(LInterface.class, ssc_1_mgmt_port_0_uri); - doReturn(Optional.of(ssc_1_service2_port_0)).when(aaiResourcesMock).get(LInterface.class, - ssc_1_service2_port_0_uri); - doReturn(Optional.of(service2_sub_interface_1)).when(aaiResourcesMock).get(LInterface.class, - service1_sub_1_uri); - doReturn(Optional.of(ssc_1_int_ha_port_0)).when(aaiResourcesMock).get(LInterface.class, - ssc_1_int_ha_port_0_uri); - doReturn(Optional.of(test_port_1)).when(aaiResourcesMock).get(LInterface.class, test_port_1_uri); - doReturn(Optional.of(test_port_2)).when(aaiResourcesMock).get(LInterface.class, test_port_2_uri); - - doReturn(true).when(aaiResourcesMock).exists(service2_sub_1_uri); - doReturn(true).when(aaiResourcesMock).exists(service1_sub_0_uri); - doReturn(true).when(aaiResourcesMock).exists(service1_sub_1_uri); - - Optional actual = - auditNova.auditVservers(vserversToAudit, tenantId, cloudOwner, cloudRegion); - String actualString = objectMapper.writeValueAsString(actual.get()); - String expected = getJson("ExpectedVServerFound.json"); - JSONAssert.assertEquals(expected, actualString, false); - } - - @Test - public void audit_Vserver_Found_Test_Network_Not_Found() - throws JsonParseException, JsonMappingException, IOException { - doReturn(true).when(aaiResourcesMock).exists(vserverURI); - doReturn(true).when(aaiResourcesMock).exists(vserverURI2); - doReturn(Optional.of(ssc_1_trusted_port_0)).when(aaiResourcesMock).get(LInterface.class, - ssc_1_trusted_port_0_uri); - doReturn(Optional.of(ssc_1_service1_port_0)).when(aaiResourcesMock).get(LInterface.class, - ssc_1_service1_port_0_uri); - doReturn(Optional.of(ssc_1_mgmt_port_1)).when(aaiResourcesMock).get(LInterface.class, ssc_1_mgmt_port_1_uri); - doReturn(Optional.empty()).when(aaiResourcesMock).get(LInterface.class, ssc_1_mgmt_port_0_uri); - doReturn(Optional.of(ssc_1_service2_port_0)).when(aaiResourcesMock).get(LInterface.class, - ssc_1_service2_port_0_uri); - doReturn(Optional.of(ssc_1_int_ha_port_0)).when(aaiResourcesMock).get(LInterface.class, - ssc_1_int_ha_port_0_uri); - doReturn(Optional.of(test_port_1)).when(aaiResourcesMock).get(LInterface.class, test_port_1_uri); - doReturn(Optional.of(test_port_2)).when(aaiResourcesMock).get(LInterface.class, test_port_2_uri); - - doReturn(true).when(aaiResourcesMock).exists(service2_sub_1_uri); - doReturn(true).when(aaiResourcesMock).exists(service1_sub_0_uri); - doReturn(true).when(aaiResourcesMock).exists(service1_sub_1_uri); - - Optional actual = - auditNova.auditVservers(vserversToAudit, tenantId, cloudOwner, cloudRegion); - String actualString = objectMapper.writeValueAsString(actual.get()); - String expected = getJson("VServer_Found_network_Not_Found.json"); - JSONAssert.assertEquals(expected, actualString, false); - } - - @Test - public void audit_Vserver_Found_Test_Network_Not_Found_Second_Server() - throws JsonParseException, JsonMappingException, IOException { - doReturn(true).when(aaiResourcesMock).exists(vserverURI); - doReturn(true).when(aaiResourcesMock).exists(vserverURI2); - doReturn(Optional.of(ssc_1_trusted_port_0)).when(aaiResourcesMock).get(LInterface.class, - ssc_1_trusted_port_0_uri); - doReturn(Optional.of(ssc_1_service1_port_0)).when(aaiResourcesMock).get(LInterface.class, - ssc_1_service1_port_0_uri); - doReturn(Optional.of(ssc_1_mgmt_port_1)).when(aaiResourcesMock).get(LInterface.class, ssc_1_mgmt_port_1_uri); - doReturn(Optional.of(ssc_1_mgmt_port_0)).when(aaiResourcesMock).get(LInterface.class, ssc_1_mgmt_port_0_uri); - doReturn(Optional.of(ssc_1_service2_port_0)).when(aaiResourcesMock).get(LInterface.class, - ssc_1_service2_port_0_uri); - doReturn(Optional.of(ssc_1_int_ha_port_0)).when(aaiResourcesMock).get(LInterface.class, - ssc_1_int_ha_port_0_uri); - doReturn(Optional.of(test_port_1)).when(aaiResourcesMock).get(LInterface.class, test_port_1_uri); - doReturn(Optional.empty()).when(aaiResourcesMock).get(LInterface.class, test_port_2_uri); - doReturn(true).when(aaiResourcesMock).exists(service2_sub_1_uri); - doReturn(true).when(aaiResourcesMock).exists(service1_sub_0_uri); - doReturn(true).when(aaiResourcesMock).exists(service1_sub_1_uri); - Optional actual = - auditNova.auditVservers(vserversToAudit, tenantId, cloudOwner, cloudRegion); - String actualString = objectMapper.writeValueAsString(actual.get()); - String expected = getJson("VServer_Found_Network_Sec_Server_Not_Found.json"); - JSONAssert.assertEquals(expected, actualString, false); - } - - @Test - public void audit_Vserver_Not_Found_Test() throws JsonParseException, JsonMappingException, IOException { - doReturn(false).when(aaiResourcesMock).exists(vserverURI); - doReturn(false).when(aaiResourcesMock).exists(vserverURI2); - Optional actual = - auditNova.auditVservers(vserversToAudit, tenantId, cloudOwner, cloudRegion); - String actualString = objectMapper.writeValueAsString(actual.get()); - String expected = getJson("Vservers_Not_Found.json"); - JSONAssert.assertEquals(expected, actualString, false); - } - - @Test - public void audit_Vserver_first_Not_Found_Test() throws JsonParseException, JsonMappingException, IOException { - doReturn(false).when(aaiResourcesMock).exists(vserverURI); - doReturn(true).when(aaiResourcesMock).exists(vserverURI2); - doReturn(Optional.of(test_port_1)).when(aaiResourcesMock).get(LInterface.class, test_port_1_uri); - doReturn(Optional.of(test_port_2)).when(aaiResourcesMock).get(LInterface.class, test_port_2_uri); - Optional actual = - auditNova.auditVservers(vserversToAudit, tenantId, cloudOwner, cloudRegion); - String actualString = objectMapper.writeValueAsString(actual.get()); - String expected = getJson("Vserver2_Found_VServer1_Not_Found.json"); - JSONAssert.assertEquals(expected, actualString, false); - } - - - @Test - public void doesSubInterfaceExistinAAI_Test() { - AAIResourceUri subInterfaceURI = AAIUriFactory.createResourceUri(AAIObjectType.SUB_L_INTERFACE, cloudOwner, - cloudRegion, tenantId, "vserverId", "l-interface", "sub-interface"); - - assertEquals( - "/cloud-infrastructure/cloud-regions/cloud-region/cloudOwner/cloudRegion/tenants/tenant/tenantId/vservers/vserver/vserverId/l-interfaces/l-interface/l-interface/l-interfaces/l-interface/sub-interface", - subInterfaceURI.build().toString()); - } - - @Test - public void audit_Vserver_Second_Not_Found_Test() throws JsonParseException, JsonMappingException, IOException { - doReturn(true).when(aaiResourcesMock).exists(vserverURI); - doReturn(Optional.of(ssc_1_trusted_port_0)).when(aaiResourcesMock).get(LInterface.class, - ssc_1_trusted_port_0_uri); - doReturn(Optional.of(ssc_1_service1_port_0)).when(aaiResourcesMock).get(LInterface.class, - ssc_1_service1_port_0_uri); - doReturn(Optional.of(ssc_1_mgmt_port_1)).when(aaiResourcesMock).get(LInterface.class, ssc_1_mgmt_port_1_uri); - doReturn(Optional.of(ssc_1_mgmt_port_0)).when(aaiResourcesMock).get(LInterface.class, ssc_1_mgmt_port_0_uri); - doReturn(Optional.of(ssc_1_service2_port_0)).when(aaiResourcesMock).get(LInterface.class, - ssc_1_service2_port_0_uri); - doReturn(Optional.of(ssc_1_int_ha_port_0)).when(aaiResourcesMock).get(LInterface.class, - ssc_1_int_ha_port_0_uri); - doReturn(Optional.empty()).when(aaiResourcesMock).get(LInterface.class, test_port_1_uri); - doReturn(Optional.empty()).when(aaiResourcesMock).get(LInterface.class, test_port_2_uri); - doReturn(true).when(aaiResourcesMock).exists(service2_sub_1_uri); - doReturn(true).when(aaiResourcesMock).exists(service1_sub_0_uri); - doReturn(true).when(aaiResourcesMock).exists(service1_sub_1_uri); - - doReturn(false).when(aaiResourcesMock).exists(vserverURI2); - Optional actual = - auditNova.auditVservers(vserversToAudit, tenantId, cloudOwner, cloudRegion); - String actualString = objectMapper.writeValueAsString(actual.get()); - String expected = getJson("VServer_Found_Sec_Server_Not_Found2.json"); - - JSONAssert.assertEquals(expected, actualString, false); - } - - @Test - public void testAuditVserversWithList() { - - AAIObjectAuditList auditList = new AAIObjectAuditList(); - AAIObjectAudit obj1 = new AAIObjectAudit(); - Vserver vserver = new Vserver(); - vserver.setVserverId("testVserverId"); - obj1.setAaiObject(vserver); - obj1.setResourceURI(AAIUriFactory - .createResourceUri(AAIObjectType.VSERVER, cloudOwner, cloudRegion, tenantId, "testVserverId").build()); - auditList.getAuditList().add(obj1); - - doReturn(false).when(aaiResourcesMock).exists(AAIUriFactory.createResourceUri(AAIObjectType.VSERVER, cloudOwner, - cloudRegion, tenantId, "testVserverId")); - - auditNova.auditVservers(auditList); - - Mockito.verify(aaiResourcesMock).exists(AAIUriFactory.createResourceUri(AAIObjectType.VSERVER, cloudOwner, - cloudRegion, tenantId, "testVserverId")); - - Assert.assertEquals(false, auditList.getAuditList().get(0).isDoesObjectExist()); - } - - @Test - public void testAuditVserversThroughRelationships() { - - VfModule vfModule = new VfModule(); - vfModule.setVfModuleId("id"); - - AAIResultWrapper wrapper = new AAIResultWrapper(vfModule); - - doReturn(Optional.of(wrapper)).when(aaiResourcesMock).getFirstWrapper(VfModules.class, VfModule.class, - AAIUriFactory.createResourceUri(AAIObjectPlurals.VF_MODULE, "genericVnfId").queryParam("vf-module-name", - "vfModuleName")); - - Optional auditList = - auditNova.auditVserversThroughRelationships("genericVnfId", "vfModuleName"); - - Assert.assertTrue(auditList.get().getAuditList().isEmpty()); - } - - @Test - public void testAuditVserversThroughRelationships_exists() throws IOException { - - String vfModule = getJson("vfModule.json"); - - AAIResultWrapper wrapper = new AAIResultWrapper(vfModule); - AAIResultWrapper vserverWrapper = new AAIResultWrapper(new Vserver()); - - doReturn(Optional.of(wrapper)).when(aaiResourcesMock).getFirstWrapper(VfModules.class, VfModule.class, - AAIUriFactory.createResourceUri(AAIObjectPlurals.VF_MODULE, "genericVnfId").queryParam("vf-module-name", - "vfModuleName")); - - doReturn(vserverWrapper).when(aaiResourcesMock).get(AAIUriFactory.createResourceUri(AAIObjectType.VSERVER, - "cloud-owner", "cloud-region-id", "tenant-id", "VUSCHGA1")); - - Optional auditList = - auditNova.auditVserversThroughRelationships("genericVnfId", "vfModuleName"); - - Assert.assertFalse(auditList.get().getAuditList().isEmpty()); - } - - - private String getJson(String filename) throws IOException { - return new String(Files.readAllBytes(Paths.get("src/test/resources/" + filename))); - } - - - -} diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/audit/HeatStackAuditTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/audit/HeatStackAuditTest.java deleted file mode 100644 index c995064ab2..0000000000 --- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/audit/HeatStackAuditTest.java +++ /dev/null @@ -1,296 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017-2019 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.adapters.audit; - -import static com.shazam.shazamcrest.MatcherAssert.assertThat; -import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; -import static org.junit.Assert.assertEquals; -import static org.mockito.Mockito.doReturn; -import java.io.File; -import java.io.IOException; -import java.nio.file.Files; -import java.nio.file.Paths; -import java.util.ArrayList; -import java.util.HashSet; -import java.util.List; -import java.util.Optional; -import java.util.Set; -import java.util.stream.Collectors; -import org.junit.Before; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.junit.MockitoJUnitRunner; -import org.onap.aai.domain.yang.LInterface; -import org.onap.aai.domain.yang.LInterfaces; -import org.onap.aai.domain.yang.Vserver; -import org.onap.so.objects.audit.AAIObjectAuditList; -import org.onap.so.openstack.utils.MsoHeatUtils; -import org.onap.so.openstack.utils.MsoNeutronUtils; -import org.skyscreamer.jsonassert.JSONAssert; -import com.fasterxml.jackson.annotation.JsonInclude.Include; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.ObjectMapper; -import com.woorea.openstack.heat.model.Resource; -import com.woorea.openstack.heat.model.Resources; -import com.woorea.openstack.heat.model.Stack; -import com.woorea.openstack.quantum.model.Port; - - -@RunWith(MockitoJUnitRunner.Silent.class) -public class HeatStackAuditTest extends HeatStackAudit { - - @InjectMocks - private HeatStackAudit heatStackAudit = new HeatStackAudit(); - - @Mock - private MsoHeatUtils msoHeatUtilsMock; - - @Mock - private MsoNeutronUtils neutronUtilsMock; - - @Mock - private AuditVServer auditVserver; - - private static final String cloudRegion = "cloudRegion"; - private static final String tenantId = "tenantId"; - - private Resources resources = new Resources(); - - private ObjectMapper objectMapper = - new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) - .setSerializationInclusion(Include.NON_NULL); - - private ObjectMapper stackObjectMapper = new ObjectMapper() - .configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true).setSerializationInclusion(Include.NON_NULL); - - private List> portList = new ArrayList<>(); - - @Before - public void setup() throws Exception { - resources = objectMapper.readValue(new File("src/test/resources/GetResources.json"), Resources.class); - Port neutronPort1 = stackObjectMapper.readValue(new File("src/test/resources/NeutronPort1.json"), Port.class); - doReturn(Optional.of(neutronPort1)).when(neutronUtilsMock) - .getNeutronPort("7ee06d9d-3d18-411c-9d3e-aec930f70413", cloudRegion, tenantId); - Port neutronPort2 = stackObjectMapper.readValue(new File("src/test/resources/NeutronPort2.json"), Port.class); - doReturn(Optional.of(neutronPort2)).when(neutronUtilsMock) - .getNeutronPort("27391d94-33af-474a-927d-d409249e8fd3", cloudRegion, tenantId); - Port neutronPort3 = stackObjectMapper.readValue(new File("src/test/resources/NeutronPort3.json"), Port.class); - doReturn(Optional.of(neutronPort3)).when(neutronUtilsMock) - .getNeutronPort("fdeedf37-c01e-4ab0-bdd6-8d5fc4913943", cloudRegion, tenantId); - Port neutronPort4 = stackObjectMapper.readValue(new File("src/test/resources/NeutronPort4.json"), Port.class); - doReturn(Optional.of(neutronPort4)).when(neutronUtilsMock) - .getNeutronPort("8d93f63e-e972-48c7-ad98-b2122da47315", cloudRegion, tenantId); - Port neutronPort5 = stackObjectMapper.readValue(new File("src/test/resources/NeutronPort5.json"), Port.class); - doReturn(Optional.of(neutronPort5)).when(neutronUtilsMock) - .getNeutronPort("0594a2f2-7ea4-42eb-abc2-48ea49677fca", cloudRegion, tenantId); - Port neutronPort6 = stackObjectMapper.readValue(new File("src/test/resources/NeutronPort6.json"), Port.class); - doReturn(Optional.of(neutronPort6)).when(neutronUtilsMock) - .getNeutronPort("00bb8407-650e-48b5-b919-33b88d6f8fe3", cloudRegion, tenantId); - - - portList.add(Optional.empty()); - portList.add(Optional.of(neutronPort1)); - portList.add(Optional.of(neutronPort2)); - portList.add(Optional.of(neutronPort3)); - portList.add(Optional.of(neutronPort4)); - portList.add(Optional.of(neutronPort5)); - portList.add(Optional.of(neutronPort6)); - } - - @Test - public void extract_proper_path_Test() { - Optional actualResult = extractStackPathFromHref( - "https://orchestration.com:8004/v1/stacks/test_stack/f711be16-2654-4a09-b89d-0511fda20e81"); - assertEquals("/stacks/test_stack/f711be16-2654-4a09-b89d-0511fda20e81", actualResult.get()); - } - - @Test - public void extract_proper_resources_path_Test() { - Optional actualResult = extractResourcePathFromHref( - "https://orchestration.com:8004/v1/stacks/test_stack/f711be16-2654-4a09-b89d-0511fda20e81"); - assertEquals("/stacks/test_stack/f711be16-2654-4a09-b89d-0511fda20e81/resources", actualResult.get()); - } - - @Test - public void extract_invalid_uri_Test() { - Optional actualResult = extractStackPathFromHref( - "orchestrn.com:8004/v18b44d60a6f94bdcb2738f9e//stacks/test_stack/f711be16-2654-4a09-b89d-0511fda20e81"); - assertEquals(false, actualResult.isPresent()); - } - - @Test - public void createVserverSet_Test() throws Exception { - List novaResources = resources.getList().stream().filter(p -> "OS::Nova::Server".equals(p.getType())) - .collect(Collectors.toList()); - - List resourceGroups = resources.getList().stream() - .filter(p -> "OS::Heat::ResourceGroup".equals(p.getType())).collect(Collectors.toList()); - - Resources service1QueryResponse = objectMapper - .readValue(new File("src/test/resources/Service1ResourceGroupResponse.json"), Resources.class); - doReturn(service1QueryResponse).when(msoHeatUtilsMock).executeHeatClientRequest( - "/stacks/tsbc0005vm002ssc001-ssc_1_subint_service1_port_0_subinterfaces-dtmxjmny7yjz/31d0647a-6043-49a4-81b6-ccab29380672/resources", - cloudRegion, tenantId, Resources.class); - - Resources service2QueryResponse = objectMapper - .readValue(new File("src/test/resources/Service2ResourceGroupResponse.json"), Resources.class); - doReturn(service2QueryResponse).when(msoHeatUtilsMock).executeHeatClientRequest( - "/stacks/tsbc0005vm002ssc001-ssc_1_subint_service2_port_0_subinterfaces-hlzdigtimzst/447a9b41-714e-434b-b1d0-6cce8d9f0f0c/resources", - cloudRegion, tenantId, Resources.class); - - - Stack service2StackQuerySubInt = - stackObjectMapper.readValue(new File("src/test/resources/Service2SubInterface0.json"), Stack.class); - doReturn(service2StackQuerySubInt).when(msoHeatUtilsMock).executeHeatClientRequest( - "/stacks/tsbc0005vm002ssc001-ssc_1_subint_service2_port_0_subinterfaces-hlzdigtimzst-0-upfi5nhurk7y/f711be16-2654-4a09-b89d-0511fda20e81", - cloudRegion, tenantId, Stack.class); - Resources service2ResourceQuerySubInt = objectMapper - .readValue(new File("src/test/resources/Service2SubInterface1Resources.json"), Resources.class); - doReturn(service2ResourceQuerySubInt).when(msoHeatUtilsMock).executeHeatClientRequest( - "/stacks/tsbc0005vm002ssc001-ssc_1_subint_service2_port_0_subinterfaces-hlzdigtimzst-0-upfi5nhurk7y/f711be16-2654-4a09-b89d-0511fda20e81/resources", - cloudRegion, tenantId, Resources.class); - - Stack service1StackQuerySubInt1 = - stackObjectMapper.readValue(new File("src/test/resources/Service1SubInterface0.json"), Stack.class); - doReturn(service1StackQuerySubInt1).when(msoHeatUtilsMock).executeHeatClientRequest( - "/stacks/tsbc0005vm002ssc001-ssc_1_subint_service1_port_0_subinterfaces-dtmxjmny7yjz-1-fmn5laetg5cs/0d9cd813-2ae1-46c0-9ebb-48081f6cffbb", - cloudRegion, tenantId, Stack.class); - Resources service1ResourceQuerySubInt1 = objectMapper - .readValue(new File("src/test/resources/Service1SubInterface0Resources.json"), Resources.class); - doReturn(service1ResourceQuerySubInt1).when(msoHeatUtilsMock).executeHeatClientRequest( - "/stacks/tsbc0005vm002ssc001-ssc_1_subint_service1_port_0_subinterfaces-dtmxjmny7yjz-1-fmn5laetg5cs/0d9cd813-2ae1-46c0-9ebb-48081f6cffbb/resources", - cloudRegion, tenantId, Resources.class); - - - Stack service1StackQuerySubInt2 = - stackObjectMapper.readValue(new File("src/test/resources/Service1SubInterface1.json"), Stack.class); - doReturn(service1StackQuerySubInt2).when(msoHeatUtilsMock).executeHeatClientRequest( - "/stacks/tsbc0005vm002ssc001-ssc_1_subint_service1_port_0_subinterfaces-dtmxjmny7yjz-0-yghihziaf36m/b7019dd0-2ee9-4447-bdef-ac25676b205a", - cloudRegion, tenantId, Stack.class); - Resources service1ResourceQuerySubInt2 = objectMapper - .readValue(new File("src/test/resources/Service1SubInterface1Resources.json"), Resources.class); - doReturn(service1ResourceQuerySubInt2).when(msoHeatUtilsMock).executeHeatClientRequest( - "/stacks/tsbc0005vm002ssc001-ssc_1_subint_service1_port_0_subinterfaces-dtmxjmny7yjz-0-yghihziaf36m/b7019dd0-2ee9-4447-bdef-ac25676b205a/resources", - cloudRegion, tenantId, Resources.class); - - Stack service1StackQuerySubInt3 = - stackObjectMapper.readValue(new File("src/test/resources/Service1SubInterface2.json"), Stack.class); - doReturn(service1StackQuerySubInt3).when(msoHeatUtilsMock).executeHeatClientRequest( - "/stacks/tsbc0005vm002ssc001-ssc_1_subint_service1_port_0_subinterfaces-dtmxjmny7yjz-2-y3ndsavmsymv/bd0fc728-cbde-4301-a581-db56f494675c", - cloudRegion, tenantId, Stack.class); - Resources service1ResourceQuerySubInt3 = objectMapper - .readValue(new File("src/test/resources/Service1SubInterface2Resources.json"), Resources.class); - doReturn(service1ResourceQuerySubInt3).when(msoHeatUtilsMock).executeHeatClientRequest( - "/stacks/tsbc0005vm002ssc001-ssc_1_subint_service1_port_0_subinterfaces-dtmxjmny7yjz-2-y3ndsavmsymv/bd0fc728-cbde-4301-a581-db56f494675c/resources", - cloudRegion, tenantId, Resources.class); - - Set vServersToAudit = heatStackAudit.createVserverSet(resources, novaResources, portList); - Set vserversWithSubInterfaces = - heatStackAudit.processSubInterfaces(cloudRegion, tenantId, resourceGroups, vServersToAudit); - - String actualValue = objectMapper.writeValueAsString(vserversWithSubInterfaces); - String expectedValue = getJson("ExpectedVserversToAudit.json"); - JSONAssert.assertEquals(expectedValue, actualValue, false); - } - - @Test - public void auditHeatStackNoServers_Test() throws Exception { - Resources getResource = objectMapper - .readValue(new File("src/test/resources/Service1ResourceGroupResponse.json"), Resources.class); - doReturn(getResource).when(msoHeatUtilsMock).queryStackResources(cloudRegion, tenantId, "heatStackName", 3); - - Optional actual = - heatStackAudit.auditHeatStack(cloudRegion, "cloudOwner", tenantId, "heatStackName"); - assertEquals(true, actual.get().getAuditList().isEmpty()); - } - - @Test - public void auditHeatStackNestedServers_Test() throws Exception { - Resources getResource = - objectMapper.readValue(new File("src/test/resources/GetNestedResources.json"), Resources.class); - List novaResources = getResource.getList().stream() - .filter(p -> "OS::Nova::Server".equals(p.getType())).collect(Collectors.toList()); - List resourceGroups = getResource.getList().stream() - .filter(p -> "OS::Heat::ResourceGroup".equals(p.getType())).collect(Collectors.toList()); - - doReturn(getResource).when(msoHeatUtilsMock).queryStackResources(cloudRegion, tenantId, "heatStackName", 3); - Set vServersToAudit = heatStackAudit.createVserverSet(resources, novaResources, portList); - Set vserversWithSubInterfaces = - heatStackAudit.processSubInterfaces(cloudRegion, tenantId, resourceGroups, vServersToAudit); - String actualValue = objectMapper.writeValueAsString(vserversWithSubInterfaces); - String expectedValue = getJson("NestedExpectedValue.json"); - JSONAssert.assertEquals(expectedValue, actualValue, false); - } - - - @Test - public void findInterfaceInformation_Test() { - List novaResources = resources.getList().stream().filter(p -> "OS::Nova::Server".equals(p.getType())) - .collect(Collectors.toList()); - Set expectedVservers = new HashSet<>(); - Vserver vServer1 = new Vserver(); - vServer1.setVserverId("92272b67-d23f-42ca-87fa-7b06a9ec81f3"); - LInterfaces vServer1Linterfaces = new LInterfaces(); - vServer1.setLInterfaces(vServer1Linterfaces); - - LInterface ssc_1_trusted_port_0 = new LInterface(); - ssc_1_trusted_port_0.setInterfaceId("7ee06d9d-3d18-411c-9d3e-aec930f70413"); - ssc_1_trusted_port_0.setInterfaceName("ibcx0026v_ibcx0026vm003_untrusted_port"); - vServer1.getLInterfaces().getLInterface().add(ssc_1_trusted_port_0); - - LInterface ssc_1_svc2_port_0 = new LInterface(); - ssc_1_svc2_port_0.setInterfaceId("27391d94-33af-474a-927d-d409249e8fd3"); - ssc_1_svc2_port_0.setInterfaceName("ibcx0026v_ibcx0026vm003_untrusted_port"); - vServer1.getLInterfaces().getLInterface().add(ssc_1_svc2_port_0); - - LInterface ssc_1_mgmt_port_1 = new LInterface(); - ssc_1_mgmt_port_1.setInterfaceId("fdeedf37-c01e-4ab0-bdd6-8d5fc4913943"); - ssc_1_mgmt_port_1.setInterfaceName("ibcx0026v_ibcx0026vm003_untrusted_port"); - vServer1.getLInterfaces().getLInterface().add(ssc_1_mgmt_port_1); - - LInterface ssc_1_mgmt_port_0 = new LInterface(); - ssc_1_mgmt_port_0.setInterfaceId("8d93f63e-e972-48c7-ad98-b2122da47315"); - ssc_1_mgmt_port_0.setInterfaceName("ibcx0026v_ibcx0026vm003_untrusted_port"); - vServer1.getLInterfaces().getLInterface().add(ssc_1_mgmt_port_0); - - LInterface ssc_1_svc1_port_0 = new LInterface(); - ssc_1_svc1_port_0.setInterfaceId("0594a2f2-7ea4-42eb-abc2-48ea49677fca"); - ssc_1_svc1_port_0.setInterfaceName("ibcx0026v_ibcx0026vm003_untrusted_port"); - vServer1.getLInterfaces().getLInterface().add(ssc_1_svc1_port_0); - - LInterface ssc_1_int_ha_port_0 = new LInterface(); - ssc_1_int_ha_port_0.setInterfaceId("00bb8407-650e-48b5-b919-33b88d6f8fe3"); - ssc_1_int_ha_port_0.setInterfaceName("ibcx0026v_ibcx0026vm003_untrusted_port"); - vServer1.getLInterfaces().getLInterface().add(ssc_1_int_ha_port_0); - - expectedVservers.add(vServer1); - - Set actualVservers = heatStackAudit.createVserverSet(resources, novaResources, portList); - - assertThat(actualVservers, sameBeanAs(expectedVservers)); - } - - private String getJson(String filename) throws IOException { - return new String(Files.readAllBytes(Paths.get("src/test/resources/" + filename))); - } -} diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/inventory/create/CreateAAIInventoryTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/inventory/create/CreateAAIInventoryTest.java deleted file mode 100644 index 8226f4fed8..0000000000 --- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/inventory/create/CreateAAIInventoryTest.java +++ /dev/null @@ -1,122 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017-2019 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.adapters.inventory.create; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertTrue; -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.times; -import java.io.File; -import java.io.IOException; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import org.camunda.bpm.client.task.ExternalTask; -import org.hamcrest.Matchers; -import org.junit.Before; -import org.junit.Test; -import org.mockito.ArgumentCaptor; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; -import org.onap.so.audit.beans.AuditInventory; -import org.onap.so.client.aai.AAIObjectType; -import org.onap.so.client.aai.AAIResourcesClient; -import org.onap.so.client.aai.entities.uri.AAIResourceUri; -import org.onap.so.client.aai.entities.uri.AAIUriFactory; -import org.onap.so.objects.audit.AAIObjectAuditList; -import com.fasterxml.jackson.core.JsonParseException; -import com.fasterxml.jackson.databind.JsonMappingException; -import com.fasterxml.jackson.databind.ObjectMapper; - -public class CreateAAIInventoryTest extends CreateAAIInventory { - - @InjectMocks - private CreateAAIInventory createAAIInventory = new CreateAAIInventory(); - - @Mock - private ExternalTask mockExternalTask; - - @Mock - private AAIResourcesClient mockClient; - - private ObjectMapper objectMapper = new ObjectMapper(); - - private AuditInventory auditInventory = new AuditInventory(); - - AAIObjectAuditList auditListSuccess; - - AAIObjectAuditList auditListFailure; - - AAIObjectAuditList missingSubInterfaces; - - @Before - public void setup() throws JsonParseException, JsonMappingException, IOException { - auditInventory.setCloudOwner("cloudOwner"); - auditInventory.setCloudRegion("cloudRegion"); - auditInventory.setTenantId("tenantId"); - auditInventory.setHeatStackName("stackName"); - MockitoAnnotations.initMocks(this); - auditListSuccess = objectMapper.readValue(new File("src/test/resources/ExpectedVServerFound.json"), - AAIObjectAuditList.class); - auditListFailure = objectMapper.readValue(new File("src/test/resources/Vserver2_Found_VServer1_Not_Found.json"), - AAIObjectAuditList.class); - missingSubInterfaces = objectMapper.readValue(new File("src/test/resources/AuditResultsMissSub.json"), - AAIObjectAuditList.class); - doReturn(auditInventory).when(mockExternalTask).getVariable("auditInventory"); - } - - @Test - public void determineAuditResult_Test() throws Exception { - boolean actual = createAAIInventory.didAuditFailVserverLInterfaces(auditListSuccess); - assertEquals(false, actual); - } - - @Test - public void determineAuditResult_Failure_Test() throws Exception { - boolean actual = createAAIInventory.didAuditFailVserverLInterfaces(auditListFailure); - assertEquals(true, actual); - } - - @Test - public void missing_Sub_Interfaces_Test() throws Exception { - AAIResourceUri aaiURI2 = AAIUriFactory.createResourceUri(AAIObjectType.SUB_L_INTERFACE, "cloudOwner", - "regionOne", "0422ffb57ba042c0800a29dc85ca70f8", "92272b67-d23f-42ca-87fa-7b06a9ec81f3", - "tsbc0005v_tsbc0005vm002_svc1_port_0", "tsbc0005v_tsbc0005vm002_subint_untrusted_svc1_81"); - AAIResourceUri aaiURI1 = AAIUriFactory.createResourceUri(AAIObjectType.SUB_L_INTERFACE, "cloudOwner", - "regionOne", "0422ffb57ba042c0800a29dc85ca70f8", "92272b67-d23f-42ca-87fa-7b06a9ec81f3", - "tsbc0005v_tsbc0005vm002_svc2_port_0", "tsbc0005v_tsbc0005vm002_subint_untrusted_svc2_103"); - ArgumentCaptor captor = ArgumentCaptor.forClass(Optional.class); - ArgumentCaptor uriCaptor = ArgumentCaptor.forClass(AAIResourceUri.class); - - createAAIInventory.setAaiClient(mockClient); - createAAIInventory.createInventory(missingSubInterfaces); - Mockito.verify(mockClient, times(2)).createIfNotExists(uriCaptor.capture(), captor.capture()); - - List capturedURI = uriCaptor.getAllValues(); - assertTrue(capturedURI.stream().anyMatch(item -> aaiURI1.build().toString().equals(item.build().toString()))); - assertTrue(capturedURI.stream().anyMatch(item -> aaiURI2.build().toString().equals(item.build().toString()))); - - - - } -} diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/inventory/create/CreateInventoryTaskTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/inventory/create/CreateInventoryTaskTest.java deleted file mode 100644 index c4fa9ee2c5..0000000000 --- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/inventory/create/CreateInventoryTaskTest.java +++ /dev/null @@ -1,80 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2017 - 2019 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.adapters.inventory.create; - -import static org.mockito.Mockito.doReturn; -import static org.mockito.Mockito.times; -import org.camunda.bpm.client.task.ExternalTask; -import org.camunda.bpm.client.task.ExternalTaskService; -import org.junit.Before; -import org.junit.Test; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Mockito; -import org.mockito.MockitoAnnotations; -import org.onap.so.client.graphinventory.GraphInventoryCommonObjectMapperProvider; -import org.onap.so.externaltasks.logging.AuditMDCSetup; -import org.onap.so.objects.audit.AAIObjectAudit; -import org.onap.so.objects.audit.AAIObjectAuditList; -import com.fasterxml.jackson.core.JsonProcessingException; - -public class CreateInventoryTaskTest { - - @Mock - ExternalTask externalTask; - - @Mock - CreateAAIInventory createAAIInventory; - - @Mock - ExternalTaskService externalTaskService; - - @Mock - private AuditMDCSetup mdcSetup; - - @InjectMocks - CreateInventoryTask inventoryTask; - - @Before - public void setup() { - MockitoAnnotations.initMocks(this); - } - - @Test - public void test_Runtime_Parse_Exception() { - doReturn(null).when(externalTask).getVariable("auditInventoryResult"); - inventoryTask.executeExternalTask(externalTask, externalTaskService); - Mockito.verify(externalTaskService, times(1)).handleBpmnError(externalTask, "AAIInventoryFailure"); - } - - @Test - public void testExecuteExternalTask_InventoryException() throws InventoryException, JsonProcessingException { - AAIObjectAuditList object = new AAIObjectAuditList(); - AAIObjectAudit e = new AAIObjectAudit(); - e.setDoesObjectExist(true); - object.getAuditList().add(e); - GraphInventoryCommonObjectMapperProvider objectMapper = new GraphInventoryCommonObjectMapperProvider(); - doReturn(objectMapper.getMapper().writeValueAsString(e)).when(externalTask).getVariable("auditInventoryResult"); - Mockito.doThrow(InventoryException.class).when(createAAIInventory).createInventory(Mockito.any()); - inventoryTask.executeExternalTask(externalTask, externalTaskService); - Mockito.verify(externalTaskService, times(1)).handleBpmnError(externalTask, "AAIInventoryFailure"); - } -} diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tasks/audit/AuditDataServiceTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tasks/audit/AuditDataServiceTest.java new file mode 100644 index 0000000000..d5f8f865a8 --- /dev/null +++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tasks/audit/AuditDataServiceTest.java @@ -0,0 +1,102 @@ +package org.onap.so.adapters.tasks.audit; + +import static org.junit.Assert.assertEquals; +import static org.mockito.ArgumentMatchers.any; +import static org.mockito.Mockito.when; +import java.util.ArrayList; +import java.util.List; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.aai.domain.yang.Vserver; +import org.onap.so.adapters.tasks.audit.AuditDataService; +import org.onap.so.audit.beans.AuditInventory; +import org.onap.so.client.graphinventory.GraphInventoryCommonObjectMapperProvider; +import org.onap.so.db.request.beans.RequestProcessingData; +import org.onap.so.db.request.client.RequestsDbClient; +import org.onap.so.objects.audit.AAIObjectAudit; +import org.onap.so.objects.audit.AAIObjectAuditList; +import com.fasterxml.jackson.core.JsonProcessingException; + +@RunWith(MockitoJUnitRunner.Silent.class) +public class AuditDataServiceTest { + + @InjectMocks + AuditDataService auditDataService = new AuditDataService(); + + @Mock + protected RequestsDbClient requestsDbClient; + + AuditInventory auditInventory = new AuditInventory(); + + @Before + public void before() throws JsonProcessingException { + auditInventory.setCloudOwner("testCloudOwner"); + auditInventory.setCloudRegion("testLcpCloudRegionId"); + auditInventory.setHeatStackName("testVfModuleName1"); + auditInventory.setVfModuleId("testVnfModuleId"); + auditInventory.setTenantId("testTenantId"); + auditInventory.setGenericVnfId("testVnfId1"); + } + + @Test + public void testWriteStackDataToRequestDb() throws Exception { + Mockito.doReturn(new ArrayList()).when(requestsDbClient) + .getRequestProcessingDataByGroupingIdAndNameAndTag(Mockito.any(), Mockito.any(), Mockito.any()); + Mockito.doNothing().when(requestsDbClient).saveRequestProcessingData(Mockito.any()); + + AAIObjectAuditList auditList = new AAIObjectAuditList(); + auditList.setHeatStackName("testHeatStackName"); + AAIObjectAudit audit = new AAIObjectAudit(); + Vserver vserver = new Vserver(); + vserver.setVserverId("testVserverId"); + audit.setAaiObject(vserver); + auditList.getAuditList().add(audit); + + GraphInventoryCommonObjectMapperProvider objectMapper = new GraphInventoryCommonObjectMapperProvider(); + String auditListString = objectMapper.getMapper().writeValueAsString(auditList);; + + RequestProcessingData requestProcessingData = new RequestProcessingData(); + requestProcessingData.setSoRequestId(auditInventory.getMsoRequestId()); + requestProcessingData.setGroupingId(auditInventory.getVfModuleId()); + requestProcessingData.setName(auditInventory.getHeatStackName()); + requestProcessingData.setTag("AuditStackData"); + requestProcessingData.setValue(auditListString); + + auditDataService.writeStackDataToRequestDb(auditInventory, auditList); + Mockito.verify(requestsDbClient, Mockito.times(1)).saveRequestProcessingData(requestProcessingData); + } + + @Test + public void testGetStackDataToRequestDb() throws Exception { + AAIObjectAuditList auditList = new AAIObjectAuditList(); + auditList.setHeatStackName("testHeatStackName"); + AAIObjectAudit audit = new AAIObjectAudit(); + Vserver vserver = new Vserver(); + vserver.setVserverId("testVserverId"); + audit.setAaiObject(vserver); + auditList.getAuditList().add(audit); + GraphInventoryCommonObjectMapperProvider objectMapper = new GraphInventoryCommonObjectMapperProvider(); + String auditListString = objectMapper.getMapper().writeValueAsString(audit); + + List list = new ArrayList(); + RequestProcessingData requestProcessingData = new RequestProcessingData(); + requestProcessingData.setId(234321432); + requestProcessingData.setGroupingId("testVfModuleId"); + requestProcessingData.setName("heatStackName"); + requestProcessingData.setTag("AuditStackData"); + requestProcessingData.setValue(auditListString); + list.add(requestProcessingData); + + Mockito.doReturn(list).when(requestsDbClient).getRequestProcessingDataByGroupingIdAndNameAndTag(Mockito.any(), + Mockito.any(), Mockito.any()); + auditDataService.getStackDataFromRequestDb(auditInventory); + Mockito.verify(requestsDbClient, Mockito.times(1)).getRequestProcessingDataByGroupingIdAndNameAndTag( + "testVnfModuleId", "testVfModuleName1", "AuditStackData"); + } + +} diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tasks/audit/AuditStackServiceDataTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tasks/audit/AuditStackServiceDataTest.java new file mode 100644 index 0000000000..a10ab4b7df --- /dev/null +++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tasks/audit/AuditStackServiceDataTest.java @@ -0,0 +1,191 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017-2019 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.adapters.tasks.audit; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.mockito.Mockito.doReturn; +import java.io.File; +import java.io.IOException; +import java.util.Map; +import java.util.Optional; +import org.camunda.bpm.client.task.ExternalTask; +import org.camunda.bpm.client.task.ExternalTaskService; +import org.junit.Before; +import org.junit.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.onap.so.adapters.tasks.audit.AuditCreateStackService; +import org.onap.so.adapters.tasks.audit.AuditDataService; +import org.onap.so.adapters.tasks.audit.AuditQueryStackService; +import org.onap.so.adapters.tasks.audit.HeatStackAudit; +import org.onap.so.audit.beans.AuditInventory; +import org.onap.so.logging.tasks.AuditMDCSetup; +import org.onap.so.objects.audit.AAIObjectAuditList; +import org.springframework.core.env.Environment; +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.core.JsonProcessingException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class AuditStackServiceDataTest extends AuditCreateStackService { + + @InjectMocks + private AuditCreateStackService auditStackService = new AuditCreateStackService(); + + @InjectMocks + private AuditQueryStackService auditQueryStackService = new AuditQueryStackService(); + + @Mock + private HeatStackAudit heatStackAuditMock; + + @Mock + private Environment mockEnv; + + @Mock + private ExternalTask mockExternalTask; + + @Mock + private ExternalTaskService mockExternalTaskService; + + @Mock + private AuditDataService auditDataService; + + @Mock + private AuditMDCSetup mdcSetup; + + private ObjectMapper objectMapper = new ObjectMapper(); + + private AuditInventory auditInventory = new AuditInventory(); + + Optional auditListOptSuccess; + + Optional auditListOptFailure; + + @Before + public void setup() throws JsonParseException, JsonMappingException, IOException { + auditInventory.setCloudOwner("cloudOwner"); + auditInventory.setCloudRegion("cloudRegion"); + auditInventory.setTenantId("tenantId"); + auditInventory.setHeatStackName("stackName"); + MockitoAnnotations.initMocks(this); + + AAIObjectAuditList auditListSuccess = objectMapper + .readValue(new File("src/test/resources/ExpectedVServerFound.json"), AAIObjectAuditList.class); + auditListOptSuccess = Optional.of(auditListSuccess); + + AAIObjectAuditList auditListFailure = objectMapper.readValue( + new File("src/test/resources/Vserver2_Found_VServer1_Not_Found.json"), AAIObjectAuditList.class); + auditListOptFailure = Optional.of(auditListFailure); + String[] retrySequence = new String[8]; + retrySequence[0] = "1"; + retrySequence[1] = "1"; + retrySequence[2] = "2"; + retrySequence[3] = "3"; + retrySequence[4] = "5"; + retrySequence[5] = "8"; + retrySequence[6] = "13"; + retrySequence[7] = "20"; + doReturn(auditInventory).when(mockExternalTask).getVariable("auditInventory"); + doReturn("6000").when(mockEnv).getProperty("mso.workflow.topics.retryMultiplier", "6000"); + doReturn(retrySequence).when(mockEnv).getProperty("mso.workflow.topics.retrySequence", String[].class); + doReturn("aasdfasdf").when(mockExternalTask).getId(); + } + + @Test + public void execute_external_task_audit_success_Test() { + doReturn(auditListOptSuccess).when(heatStackAuditMock).auditHeatStack("cloudRegion", "cloudOwner", "tenantId", + "stackName"); + auditStackService.executeExternalTask(mockExternalTask, mockExternalTaskService); + ArgumentCaptor captor = ArgumentCaptor.forClass(Map.class); + ArgumentCaptor taskCaptor = ArgumentCaptor.forClass(ExternalTask.class); + Mockito.verify(mockExternalTaskService).complete(taskCaptor.capture(), captor.capture()); + Map actualMap = captor.getValue(); + assertEquals(true, actualMap.get("auditIsSuccessful")); + assertNotNull(actualMap.get("auditInventoryResult")); + } + + @Test + public void executeExternalTaskQueryAuditTest() throws JsonProcessingException { + doReturn(auditListOptSuccess).when(heatStackAuditMock).queryHeatStack("cloudOwner", "cloudRegion", "tenantId", + "stackName"); + Mockito.doNothing().when(auditDataService).writeStackDataToRequestDb(Mockito.any(AuditInventory.class), + Mockito.any(AAIObjectAuditList.class)); + auditQueryStackService.executeExternalTask(mockExternalTask, mockExternalTaskService); + ArgumentCaptor captor = ArgumentCaptor.forClass(Map.class); + ArgumentCaptor taskCaptor = ArgumentCaptor.forClass(ExternalTask.class); + Mockito.verify(mockExternalTaskService).complete(taskCaptor.capture(), captor.capture()); + Mockito.verify(auditDataService).writeStackDataToRequestDb(Mockito.any(AuditInventory.class), + Mockito.any(AAIObjectAuditList.class)); + } + + @Test + public void execute_external_task_audit_first_failure_Test() { + doReturn(auditListOptFailure).when(heatStackAuditMock).auditHeatStack("cloudRegion", "cloudOwner", "tenantId", + "stackName"); + doReturn(null).when(mockExternalTask).getRetries(); + auditStackService.executeExternalTask(mockExternalTask, mockExternalTaskService); + Mockito.verify(mockExternalTaskService).handleFailure(mockExternalTask, + "Unable to find all VServers and L-Interaces in A&AI", + "Unable to find all VServers and L-Interaces in A&AI", 8, 10000L); + } + + @Test + public void execute_external_task_audit_intermediate_failure_Test() { + doReturn(auditListOptFailure).when(heatStackAuditMock).auditHeatStack("cloudRegion", "cloudOwner", "tenantId", + "stackName"); + doReturn(6).when(mockExternalTask).getRetries(); + auditStackService.executeExternalTask(mockExternalTask, mockExternalTaskService); + Mockito.verify(mockExternalTaskService).handleFailure(mockExternalTask, + "Unable to find all VServers and L-Interaces in A&AI", + "Unable to find all VServers and L-Interaces in A&AI", 5, 12000L); + + } + + @Test + public void execute_external_task_audit_final_failure_Test() { + doReturn(auditListOptFailure).when(heatStackAuditMock).auditHeatStack("cloudRegion", "cloudOwner", "tenantId", + "stackName"); + doReturn(1).when(mockExternalTask).getRetries(); + auditStackService.executeExternalTask(mockExternalTask, mockExternalTaskService); + ArgumentCaptor captor = ArgumentCaptor.forClass(Map.class); + ArgumentCaptor taskCaptor = ArgumentCaptor.forClass(ExternalTask.class); + Mockito.verify(mockExternalTaskService).complete(taskCaptor.capture(), captor.capture()); + Map actualMap = captor.getValue(); + assertEquals(false, actualMap.get("auditIsSuccessful")); + assertNotNull(actualMap.get("auditInventoryResult")); + } + + @Test + public void determineAuditResult_Test() throws Exception { + boolean actual = auditStackService.didCreateAuditFail(auditListOptSuccess); + assertEquals(false, actual); + } + + @Test + public void determineAuditResult_Failure_Test() throws Exception { + boolean actual = auditStackService.didCreateAuditFail(auditListOptFailure); + assertEquals(true, actual); + } +} diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tasks/audit/AuditVServerTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tasks/audit/AuditVServerTest.java new file mode 100644 index 0000000000..af4afd41a1 --- /dev/null +++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tasks/audit/AuditVServerTest.java @@ -0,0 +1,433 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017-2019 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 perservice2sions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.tasks.audit; + +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.doReturn; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.HashSet; +import java.util.Optional; +import java.util.Set; +import org.junit.Assert; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.aai.domain.yang.LInterface; +import org.onap.aai.domain.yang.LInterfaces; +import org.onap.aai.domain.yang.VfModule; +import org.onap.aai.domain.yang.VfModules; +import org.onap.aai.domain.yang.Vserver; +import org.onap.so.adapters.tasks.audit.AuditVServer; +import org.onap.so.client.aai.AAIObjectPlurals; +import org.onap.so.client.aai.AAIObjectType; +import org.onap.so.client.aai.AAIResourcesClient; +import org.onap.so.client.aai.entities.AAIResultWrapper; +import org.onap.so.client.aai.entities.uri.AAIResourceUri; +import org.onap.so.client.aai.entities.uri.AAIUriFactory; +import org.onap.so.objects.audit.AAIObjectAudit; +import org.onap.so.objects.audit.AAIObjectAuditList; +import org.skyscreamer.jsonassert.JSONAssert; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +@RunWith(MockitoJUnitRunner.Silent.class) +public class AuditVServerTest extends AuditVServer { + + private ObjectMapper objectMapper = new ObjectMapper(); + + @InjectMocks + private AuditVServer auditNova = new AuditVServer(); + + @Mock + private AAIResourcesClient aaiResourcesMock; + + private String cloudOwner = "cloudOwner"; + private String cloudRegion = "cloudRegion"; + private String tenantId = "tenantId"; + + private AAIResourceUri vserverURI = AAIUriFactory.createResourceUri(AAIObjectType.VSERVER, cloudOwner, cloudRegion, + tenantId, "3a4c2ca5-27b3-4ecc-98c5-06804867c4db"); + + private AAIResourceUri vserverURI2 = AAIUriFactory.createResourceUri(AAIObjectType.VSERVER, cloudOwner, cloudRegion, + tenantId, "3a4c2ca5-27b3-4ecc-98c5-06804867c4dz"); + + private AAIResourceUri ssc_1_trusted_port_0_uri = AAIUriFactory.createResourceUri(AAIObjectType.L_INTERFACE, + cloudOwner, cloudRegion, tenantId, "3a4c2ca5-27b3-4ecc-98c5-06804867c4db", "ssc_1_trusted_port_0"); + + private AAIResourceUri ssc_1_service1_port_0_uri = AAIUriFactory.createResourceUri(AAIObjectType.L_INTERFACE, + cloudOwner, cloudRegion, tenantId, "3a4c2ca5-27b3-4ecc-98c5-06804867c4db", "ssc_1_service1_port_0"); + + private AAIResourceUri ssc_1_mgmt_port_1_uri = AAIUriFactory.createResourceUri(AAIObjectType.L_INTERFACE, + cloudOwner, cloudRegion, tenantId, "3a4c2ca5-27b3-4ecc-98c5-06804867c4db", "ssc_1_mgmt_port_1"); + + private AAIResourceUri ssc_1_mgmt_port_0_uri = AAIUriFactory.createResourceUri(AAIObjectType.L_INTERFACE, + cloudOwner, cloudRegion, tenantId, "3a4c2ca5-27b3-4ecc-98c5-06804867c4db", "ssc_1_mgmt_port_0"); + + private AAIResourceUri ssc_1_service2_port_0_uri = AAIUriFactory.createResourceUri(AAIObjectType.L_INTERFACE, + cloudOwner, cloudRegion, tenantId, "3a4c2ca5-27b3-4ecc-98c5-06804867c4db", "ssc_1_service2_port_0"); + + private AAIResourceUri ssc_1_int_ha_port_0_uri = AAIUriFactory.createResourceUri(AAIObjectType.L_INTERFACE, + cloudOwner, cloudRegion, tenantId, "3a4c2ca5-27b3-4ecc-98c5-06804867c4db", "ssc_1_int_ha_port_0"); + + private AAIResourceUri test_port_1_uri = AAIUriFactory.createResourceUri(AAIObjectType.L_INTERFACE, cloudOwner, + cloudRegion, tenantId, "3a4c2ca5-27b3-4ecc-98c5-06804867c4dz", "test_port_1"); + + private AAIResourceUri test_port_2_uri = AAIUriFactory.createResourceUri(AAIObjectType.L_INTERFACE, cloudOwner, + cloudRegion, tenantId, "3a4c2ca5-27b3-4ecc-98c5-06804867c4dz", "test_port_2"); + + private AAIResourceUri service2_sub_1_uri = + AAIUriFactory.createResourceUri(AAIObjectType.SUB_L_INTERFACE, cloudOwner, cloudRegion, tenantId, + "3a4c2ca5-27b3-4ecc-98c5-06804867c4db", "ssc_1_service2_port_0", "service2_sub_interface_1"); + + private AAIResourceUri service1_sub_0_uri = + AAIUriFactory.createResourceUri(AAIObjectType.SUB_L_INTERFACE, cloudOwner, cloudRegion, tenantId, + "3a4c2ca5-27b3-4ecc-98c5-06804867c4db", "ssc_1_service1_port_0", "service1_sub_interface_1"); + + private AAIResourceUri service1_sub_1_uri = + AAIUriFactory.createResourceUri(AAIObjectType.SUB_L_INTERFACE, cloudOwner, cloudRegion, tenantId, + "3a4c2ca5-27b3-4ecc-98c5-06804867c4db", "ssc_1_service1_port_0", "service1_sub_interface_2"); + + + + private Set vserversToAudit = new HashSet<>(); + + LInterface test_port_1 = new LInterface(); + LInterface test_port_2 = new LInterface(); + LInterface ssc_1_int_ha_port_0 = new LInterface(); + LInterface service2_sub_interface_1 = new LInterface(); + LInterface ssc_1_service2_port_0 = new LInterface(); + LInterface ssc_1_mgmt_port_0 = new LInterface(); + LInterface ssc_1_mgmt_port_1 = new LInterface(); + LInterface service1_sub_interface_2 = new LInterface(); + LInterface service1_sub_interface_1 = new LInterface(); + LInterface ssc_1_service1_port_0 = new LInterface(); + LInterface ssc_1_trusted_port_0 = new LInterface(); + + + + @Before + public void setup() { + objectMapper.setSerializationInclusion(Include.NON_NULL); + auditNova.setAaiClient(aaiResourcesMock); + + Vserver vServer1 = new Vserver(); + vServer1.setVserverId("3a4c2ca5-27b3-4ecc-98c5-06804867c4db"); + LInterfaces vServer1Linterfaces = new LInterfaces(); + vServer1.setLInterfaces(vServer1Linterfaces); + + ssc_1_trusted_port_0.setInterfaceId("dec8bdc7-5718-41dc-bfbb-561ff6eeb81c"); + ssc_1_trusted_port_0.setInterfaceName("ssc_1_trusted_port_0"); + vServer1.getLInterfaces().getLInterface().add(ssc_1_trusted_port_0); + + + ssc_1_service1_port_0.setInterfaceId("1c56a24b-5f03-435a-850d-31cd4252de56"); + ssc_1_service1_port_0.setInterfaceName("ssc_1_service1_port_0"); + vServer1.getLInterfaces().getLInterface().add(ssc_1_service1_port_0); + ssc_1_service1_port_0.setLInterfaces(new LInterfaces()); + + + service1_sub_interface_1.setInterfaceId("0d9cd813-2ae1-46c0-9ebb-48081f6cffbb"); + service1_sub_interface_1.setInterfaceName("service1_sub_interface_1"); + ssc_1_service1_port_0.getLInterfaces().getLInterface().add(service1_sub_interface_1); + + + service1_sub_interface_2.setInterfaceId("b7019dd0-2ee9-4447-bdef-ac25676b205a"); + service1_sub_interface_2.setInterfaceName("service1_sub_interface_2"); + ssc_1_service1_port_0.getLInterfaces().getLInterface().add(service1_sub_interface_2); + + + ssc_1_mgmt_port_1.setInterfaceId("12afcd28-929f-4d80-8a5a-0833bfd5e20b"); + ssc_1_mgmt_port_1.setInterfaceName("ssc_1_mgmt_port_1"); + vServer1.getLInterfaces().getLInterface().add(ssc_1_mgmt_port_1); + + ssc_1_mgmt_port_0.setInterfaceId("80baec42-ffae-425f-ad8c-3f7b2c24bfff"); + ssc_1_mgmt_port_0.setInterfaceName("ssc_1_mgmt_port_0"); + vServer1.getLInterfaces().getLInterface().add(ssc_1_mgmt_port_0); + + + ssc_1_service2_port_0.setLInterfaces(new LInterfaces()); + ssc_1_service2_port_0.setInterfaceId("13eddf95-4cf3-45f2-823a-2d890a6549b4"); + ssc_1_service2_port_0.setInterfaceName("ssc_1_service2_port_0"); + vServer1.getLInterfaces().getLInterface().add(ssc_1_service2_port_0); + + + service2_sub_interface_1.setInterfaceId("f711be16-2654-4a09-b89d-0511fda20e81"); + service2_sub_interface_1.setInterfaceName("service2_sub_interface_1"); + ssc_1_service2_port_0.getLInterfaces().getLInterface().add(service2_sub_interface_1); + + + ssc_1_int_ha_port_0.setInterfaceId("9cab2903-70f7-44fd-b681-491d6ae2adb8"); + ssc_1_int_ha_port_0.setInterfaceName("ssc_1_int_ha_port_0"); + vServer1.getLInterfaces().getLInterface().add(ssc_1_int_ha_port_0); + + Vserver vServer2 = new Vserver(); + vServer2.setVserverId("3a4c2ca5-27b3-4ecc-98c5-06804867c4dz"); + LInterfaces vServer2Linterfaces = new LInterfaces(); + vServer2.setLInterfaces(vServer2Linterfaces); + + test_port_1.setInterfaceId("9cab2903-70f7-44fd-b681-491d6ae2adz1"); + test_port_1.setInterfaceName("test_port_1"); + + + test_port_2.setInterfaceId("9cab2903-70f7-44fd-b681-491d6ae2adz2"); + test_port_2.setInterfaceName("test_port_2"); + + vServer2.getLInterfaces().getLInterface().add(test_port_1); + vServer2.getLInterfaces().getLInterface().add(test_port_2); + + vserversToAudit.add(vServer1); + vserversToAudit.add(vServer2); + } + + @Test + public void audit_Vserver_Empty_HashSet() throws JsonParseException, JsonMappingException, IOException { + Optional actual = + auditNova.auditVservers(new HashSet(), tenantId, cloudOwner, cloudRegion); + assertEquals(Optional.empty(), actual); + } + + @Test + public void audit_Vserver_Found_Test() throws JsonParseException, JsonMappingException, IOException { + doReturn(true).when(aaiResourcesMock).exists(vserverURI); + doReturn(true).when(aaiResourcesMock).exists(vserverURI2); + doReturn(Optional.of(ssc_1_trusted_port_0)).when(aaiResourcesMock).get(LInterface.class, + ssc_1_trusted_port_0_uri); + doReturn(Optional.of(ssc_1_service1_port_0)).when(aaiResourcesMock).get(LInterface.class, + ssc_1_service1_port_0_uri); + doReturn(Optional.of(ssc_1_mgmt_port_1)).when(aaiResourcesMock).get(LInterface.class, ssc_1_mgmt_port_1_uri); + doReturn(Optional.of(ssc_1_mgmt_port_0)).when(aaiResourcesMock).get(LInterface.class, ssc_1_mgmt_port_0_uri); + doReturn(Optional.of(ssc_1_service2_port_0)).when(aaiResourcesMock).get(LInterface.class, + ssc_1_service2_port_0_uri); + doReturn(Optional.of(service2_sub_interface_1)).when(aaiResourcesMock).get(LInterface.class, + service1_sub_1_uri); + doReturn(Optional.of(ssc_1_int_ha_port_0)).when(aaiResourcesMock).get(LInterface.class, + ssc_1_int_ha_port_0_uri); + doReturn(Optional.of(test_port_1)).when(aaiResourcesMock).get(LInterface.class, test_port_1_uri); + doReturn(Optional.of(test_port_2)).when(aaiResourcesMock).get(LInterface.class, test_port_2_uri); + + doReturn(true).when(aaiResourcesMock).exists(service2_sub_1_uri); + doReturn(true).when(aaiResourcesMock).exists(service1_sub_0_uri); + doReturn(true).when(aaiResourcesMock).exists(service1_sub_1_uri); + + Optional actual = + auditNova.auditVservers(vserversToAudit, tenantId, cloudOwner, cloudRegion); + String actualString = objectMapper.writeValueAsString(actual.get()); + String expected = getJson("ExpectedVServerFound.json"); + JSONAssert.assertEquals(expected, actualString, false); + } + + @Test + public void audit_Vserver_Found_Test_Network_Not_Found() + throws JsonParseException, JsonMappingException, IOException { + doReturn(true).when(aaiResourcesMock).exists(vserverURI); + doReturn(true).when(aaiResourcesMock).exists(vserverURI2); + doReturn(Optional.of(ssc_1_trusted_port_0)).when(aaiResourcesMock).get(LInterface.class, + ssc_1_trusted_port_0_uri); + doReturn(Optional.of(ssc_1_service1_port_0)).when(aaiResourcesMock).get(LInterface.class, + ssc_1_service1_port_0_uri); + doReturn(Optional.of(ssc_1_mgmt_port_1)).when(aaiResourcesMock).get(LInterface.class, ssc_1_mgmt_port_1_uri); + doReturn(Optional.empty()).when(aaiResourcesMock).get(LInterface.class, ssc_1_mgmt_port_0_uri); + doReturn(Optional.of(ssc_1_service2_port_0)).when(aaiResourcesMock).get(LInterface.class, + ssc_1_service2_port_0_uri); + doReturn(Optional.of(ssc_1_int_ha_port_0)).when(aaiResourcesMock).get(LInterface.class, + ssc_1_int_ha_port_0_uri); + doReturn(Optional.of(test_port_1)).when(aaiResourcesMock).get(LInterface.class, test_port_1_uri); + doReturn(Optional.of(test_port_2)).when(aaiResourcesMock).get(LInterface.class, test_port_2_uri); + + doReturn(true).when(aaiResourcesMock).exists(service2_sub_1_uri); + doReturn(true).when(aaiResourcesMock).exists(service1_sub_0_uri); + doReturn(true).when(aaiResourcesMock).exists(service1_sub_1_uri); + + Optional actual = + auditNova.auditVservers(vserversToAudit, tenantId, cloudOwner, cloudRegion); + String actualString = objectMapper.writeValueAsString(actual.get()); + String expected = getJson("VServer_Found_network_Not_Found.json"); + JSONAssert.assertEquals(expected, actualString, false); + } + + @Test + public void audit_Vserver_Found_Test_Network_Not_Found_Second_Server() + throws JsonParseException, JsonMappingException, IOException { + doReturn(true).when(aaiResourcesMock).exists(vserverURI); + doReturn(true).when(aaiResourcesMock).exists(vserverURI2); + doReturn(Optional.of(ssc_1_trusted_port_0)).when(aaiResourcesMock).get(LInterface.class, + ssc_1_trusted_port_0_uri); + doReturn(Optional.of(ssc_1_service1_port_0)).when(aaiResourcesMock).get(LInterface.class, + ssc_1_service1_port_0_uri); + doReturn(Optional.of(ssc_1_mgmt_port_1)).when(aaiResourcesMock).get(LInterface.class, ssc_1_mgmt_port_1_uri); + doReturn(Optional.of(ssc_1_mgmt_port_0)).when(aaiResourcesMock).get(LInterface.class, ssc_1_mgmt_port_0_uri); + doReturn(Optional.of(ssc_1_service2_port_0)).when(aaiResourcesMock).get(LInterface.class, + ssc_1_service2_port_0_uri); + doReturn(Optional.of(ssc_1_int_ha_port_0)).when(aaiResourcesMock).get(LInterface.class, + ssc_1_int_ha_port_0_uri); + doReturn(Optional.of(test_port_1)).when(aaiResourcesMock).get(LInterface.class, test_port_1_uri); + doReturn(Optional.empty()).when(aaiResourcesMock).get(LInterface.class, test_port_2_uri); + doReturn(true).when(aaiResourcesMock).exists(service2_sub_1_uri); + doReturn(true).when(aaiResourcesMock).exists(service1_sub_0_uri); + doReturn(true).when(aaiResourcesMock).exists(service1_sub_1_uri); + Optional actual = + auditNova.auditVservers(vserversToAudit, tenantId, cloudOwner, cloudRegion); + String actualString = objectMapper.writeValueAsString(actual.get()); + String expected = getJson("VServer_Found_Network_Sec_Server_Not_Found.json"); + JSONAssert.assertEquals(expected, actualString, false); + } + + @Test + public void audit_Vserver_Not_Found_Test() throws JsonParseException, JsonMappingException, IOException { + doReturn(false).when(aaiResourcesMock).exists(vserverURI); + doReturn(false).when(aaiResourcesMock).exists(vserverURI2); + Optional actual = + auditNova.auditVservers(vserversToAudit, tenantId, cloudOwner, cloudRegion); + String actualString = objectMapper.writeValueAsString(actual.get()); + String expected = getJson("Vservers_Not_Found.json"); + JSONAssert.assertEquals(expected, actualString, false); + } + + @Test + public void audit_Vserver_first_Not_Found_Test() throws JsonParseException, JsonMappingException, IOException { + doReturn(false).when(aaiResourcesMock).exists(vserverURI); + doReturn(true).when(aaiResourcesMock).exists(vserverURI2); + doReturn(Optional.of(test_port_1)).when(aaiResourcesMock).get(LInterface.class, test_port_1_uri); + doReturn(Optional.of(test_port_2)).when(aaiResourcesMock).get(LInterface.class, test_port_2_uri); + Optional actual = + auditNova.auditVservers(vserversToAudit, tenantId, cloudOwner, cloudRegion); + String actualString = objectMapper.writeValueAsString(actual.get()); + String expected = getJson("Vserver2_Found_VServer1_Not_Found.json"); + JSONAssert.assertEquals(expected, actualString, false); + } + + + @Test + public void doesSubInterfaceExistinAAI_Test() { + AAIResourceUri subInterfaceURI = AAIUriFactory.createResourceUri(AAIObjectType.SUB_L_INTERFACE, cloudOwner, + cloudRegion, tenantId, "vserverId", "l-interface", "sub-interface"); + + assertEquals( + "/cloud-infrastructure/cloud-regions/cloud-region/cloudOwner/cloudRegion/tenants/tenant/tenantId/vservers/vserver/vserverId/l-interfaces/l-interface/l-interface/l-interfaces/l-interface/sub-interface", + subInterfaceURI.build().toString()); + } + + @Test + public void audit_Vserver_Second_Not_Found_Test() throws JsonParseException, JsonMappingException, IOException { + doReturn(true).when(aaiResourcesMock).exists(vserverURI); + doReturn(Optional.of(ssc_1_trusted_port_0)).when(aaiResourcesMock).get(LInterface.class, + ssc_1_trusted_port_0_uri); + doReturn(Optional.of(ssc_1_service1_port_0)).when(aaiResourcesMock).get(LInterface.class, + ssc_1_service1_port_0_uri); + doReturn(Optional.of(ssc_1_mgmt_port_1)).when(aaiResourcesMock).get(LInterface.class, ssc_1_mgmt_port_1_uri); + doReturn(Optional.of(ssc_1_mgmt_port_0)).when(aaiResourcesMock).get(LInterface.class, ssc_1_mgmt_port_0_uri); + doReturn(Optional.of(ssc_1_service2_port_0)).when(aaiResourcesMock).get(LInterface.class, + ssc_1_service2_port_0_uri); + doReturn(Optional.of(ssc_1_int_ha_port_0)).when(aaiResourcesMock).get(LInterface.class, + ssc_1_int_ha_port_0_uri); + doReturn(Optional.empty()).when(aaiResourcesMock).get(LInterface.class, test_port_1_uri); + doReturn(Optional.empty()).when(aaiResourcesMock).get(LInterface.class, test_port_2_uri); + doReturn(true).when(aaiResourcesMock).exists(service2_sub_1_uri); + doReturn(true).when(aaiResourcesMock).exists(service1_sub_0_uri); + doReturn(true).when(aaiResourcesMock).exists(service1_sub_1_uri); + + doReturn(false).when(aaiResourcesMock).exists(vserverURI2); + Optional actual = + auditNova.auditVservers(vserversToAudit, tenantId, cloudOwner, cloudRegion); + String actualString = objectMapper.writeValueAsString(actual.get()); + String expected = getJson("VServer_Found_Sec_Server_Not_Found2.json"); + + JSONAssert.assertEquals(expected, actualString, false); + } + + @Test + public void testAuditVserversWithList() { + + AAIObjectAuditList auditList = new AAIObjectAuditList(); + AAIObjectAudit obj1 = new AAIObjectAudit(); + Vserver vserver = new Vserver(); + vserver.setVserverId("testVserverId"); + obj1.setAaiObject(vserver); + obj1.setResourceURI(AAIUriFactory + .createResourceUri(AAIObjectType.VSERVER, cloudOwner, cloudRegion, tenantId, "testVserverId").build()); + auditList.getAuditList().add(obj1); + + doReturn(false).when(aaiResourcesMock).exists(AAIUriFactory.createResourceUri(AAIObjectType.VSERVER, cloudOwner, + cloudRegion, tenantId, "testVserverId")); + + auditNova.auditVservers(auditList); + + Mockito.verify(aaiResourcesMock).exists(AAIUriFactory.createResourceUri(AAIObjectType.VSERVER, cloudOwner, + cloudRegion, tenantId, "testVserverId")); + + Assert.assertEquals(false, auditList.getAuditList().get(0).isDoesObjectExist()); + } + + @Test + public void testAuditVserversThroughRelationships() { + + VfModule vfModule = new VfModule(); + vfModule.setVfModuleId("id"); + + AAIResultWrapper wrapper = new AAIResultWrapper(vfModule); + + doReturn(Optional.of(wrapper)).when(aaiResourcesMock).getFirstWrapper(VfModules.class, VfModule.class, + AAIUriFactory.createResourceUri(AAIObjectPlurals.VF_MODULE, "genericVnfId").queryParam("vf-module-name", + "vfModuleName")); + + Optional auditList = + auditNova.auditVserversThroughRelationships("genericVnfId", "vfModuleName"); + + Assert.assertTrue(auditList.get().getAuditList().isEmpty()); + } + + @Test + public void testAuditVserversThroughRelationships_exists() throws IOException { + + String vfModule = getJson("vfModule.json"); + + AAIResultWrapper wrapper = new AAIResultWrapper(vfModule); + AAIResultWrapper vserverWrapper = new AAIResultWrapper(new Vserver()); + + doReturn(Optional.of(wrapper)).when(aaiResourcesMock).getFirstWrapper(VfModules.class, VfModule.class, + AAIUriFactory.createResourceUri(AAIObjectPlurals.VF_MODULE, "genericVnfId").queryParam("vf-module-name", + "vfModuleName")); + + doReturn(vserverWrapper).when(aaiResourcesMock).get(AAIUriFactory.createResourceUri(AAIObjectType.VSERVER, + "cloud-owner", "cloud-region-id", "tenant-id", "VUSCHGA1")); + + Optional auditList = + auditNova.auditVserversThroughRelationships("genericVnfId", "vfModuleName"); + + Assert.assertFalse(auditList.get().getAuditList().isEmpty()); + } + + + private String getJson(String filename) throws IOException { + return new String(Files.readAllBytes(Paths.get("src/test/resources/" + filename))); + } + + + +} diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tasks/audit/HeatStackAuditTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tasks/audit/HeatStackAuditTest.java new file mode 100644 index 0000000000..d1d0d96042 --- /dev/null +++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tasks/audit/HeatStackAuditTest.java @@ -0,0 +1,298 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017-2019 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.adapters.tasks.audit; + +import static com.shazam.shazamcrest.MatcherAssert.assertThat; +import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; +import static org.junit.Assert.assertEquals; +import static org.mockito.Mockito.doReturn; +import java.io.File; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.ArrayList; +import java.util.HashSet; +import java.util.List; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; +import org.junit.Before; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.aai.domain.yang.LInterface; +import org.onap.aai.domain.yang.LInterfaces; +import org.onap.aai.domain.yang.Vserver; +import org.onap.so.adapters.tasks.audit.AuditVServer; +import org.onap.so.adapters.tasks.audit.HeatStackAudit; +import org.onap.so.objects.audit.AAIObjectAuditList; +import org.onap.so.openstack.utils.MsoHeatUtils; +import org.onap.so.openstack.utils.MsoNeutronUtils; +import org.skyscreamer.jsonassert.JSONAssert; +import com.fasterxml.jackson.annotation.JsonInclude.Include; +import com.fasterxml.jackson.databind.DeserializationFeature; +import com.fasterxml.jackson.databind.ObjectMapper; +import com.woorea.openstack.heat.model.Resource; +import com.woorea.openstack.heat.model.Resources; +import com.woorea.openstack.heat.model.Stack; +import com.woorea.openstack.quantum.model.Port; + + +@RunWith(MockitoJUnitRunner.Silent.class) +public class HeatStackAuditTest extends HeatStackAudit { + + @InjectMocks + private HeatStackAudit heatStackAudit = new HeatStackAudit(); + + @Mock + private MsoHeatUtils msoHeatUtilsMock; + + @Mock + private MsoNeutronUtils neutronUtilsMock; + + @Mock + private AuditVServer auditVserver; + + private static final String cloudRegion = "cloudRegion"; + private static final String tenantId = "tenantId"; + + private Resources resources = new Resources(); + + private ObjectMapper objectMapper = + new ObjectMapper().configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false) + .setSerializationInclusion(Include.NON_NULL); + + private ObjectMapper stackObjectMapper = new ObjectMapper() + .configure(DeserializationFeature.UNWRAP_ROOT_VALUE, true).setSerializationInclusion(Include.NON_NULL); + + private List> portList = new ArrayList<>(); + + @Before + public void setup() throws Exception { + resources = objectMapper.readValue(new File("src/test/resources/GetResources.json"), Resources.class); + Port neutronPort1 = stackObjectMapper.readValue(new File("src/test/resources/NeutronPort1.json"), Port.class); + doReturn(Optional.of(neutronPort1)).when(neutronUtilsMock) + .getNeutronPort("7ee06d9d-3d18-411c-9d3e-aec930f70413", cloudRegion, tenantId); + Port neutronPort2 = stackObjectMapper.readValue(new File("src/test/resources/NeutronPort2.json"), Port.class); + doReturn(Optional.of(neutronPort2)).when(neutronUtilsMock) + .getNeutronPort("27391d94-33af-474a-927d-d409249e8fd3", cloudRegion, tenantId); + Port neutronPort3 = stackObjectMapper.readValue(new File("src/test/resources/NeutronPort3.json"), Port.class); + doReturn(Optional.of(neutronPort3)).when(neutronUtilsMock) + .getNeutronPort("fdeedf37-c01e-4ab0-bdd6-8d5fc4913943", cloudRegion, tenantId); + Port neutronPort4 = stackObjectMapper.readValue(new File("src/test/resources/NeutronPort4.json"), Port.class); + doReturn(Optional.of(neutronPort4)).when(neutronUtilsMock) + .getNeutronPort("8d93f63e-e972-48c7-ad98-b2122da47315", cloudRegion, tenantId); + Port neutronPort5 = stackObjectMapper.readValue(new File("src/test/resources/NeutronPort5.json"), Port.class); + doReturn(Optional.of(neutronPort5)).when(neutronUtilsMock) + .getNeutronPort("0594a2f2-7ea4-42eb-abc2-48ea49677fca", cloudRegion, tenantId); + Port neutronPort6 = stackObjectMapper.readValue(new File("src/test/resources/NeutronPort6.json"), Port.class); + doReturn(Optional.of(neutronPort6)).when(neutronUtilsMock) + .getNeutronPort("00bb8407-650e-48b5-b919-33b88d6f8fe3", cloudRegion, tenantId); + + + portList.add(Optional.empty()); + portList.add(Optional.of(neutronPort1)); + portList.add(Optional.of(neutronPort2)); + portList.add(Optional.of(neutronPort3)); + portList.add(Optional.of(neutronPort4)); + portList.add(Optional.of(neutronPort5)); + portList.add(Optional.of(neutronPort6)); + } + + @Test + public void extract_proper_path_Test() { + Optional actualResult = extractStackPathFromHref( + "https://orchestration.com:8004/v1/stacks/test_stack/f711be16-2654-4a09-b89d-0511fda20e81"); + assertEquals("/stacks/test_stack/f711be16-2654-4a09-b89d-0511fda20e81", actualResult.get()); + } + + @Test + public void extract_proper_resources_path_Test() { + Optional actualResult = extractResourcePathFromHref( + "https://orchestration.com:8004/v1/stacks/test_stack/f711be16-2654-4a09-b89d-0511fda20e81"); + assertEquals("/stacks/test_stack/f711be16-2654-4a09-b89d-0511fda20e81/resources", actualResult.get()); + } + + @Test + public void extract_invalid_uri_Test() { + Optional actualResult = extractStackPathFromHref( + "orchestrn.com:8004/v18b44d60a6f94bdcb2738f9e//stacks/test_stack/f711be16-2654-4a09-b89d-0511fda20e81"); + assertEquals(false, actualResult.isPresent()); + } + + @Test + public void createVserverSet_Test() throws Exception { + List novaResources = resources.getList().stream().filter(p -> "OS::Nova::Server".equals(p.getType())) + .collect(Collectors.toList()); + + List resourceGroups = resources.getList().stream() + .filter(p -> "OS::Heat::ResourceGroup".equals(p.getType())).collect(Collectors.toList()); + + Resources service1QueryResponse = objectMapper + .readValue(new File("src/test/resources/Service1ResourceGroupResponse.json"), Resources.class); + doReturn(service1QueryResponse).when(msoHeatUtilsMock).executeHeatClientRequest( + "/stacks/tsbc0005vm002ssc001-ssc_1_subint_service1_port_0_subinterfaces-dtmxjmny7yjz/31d0647a-6043-49a4-81b6-ccab29380672/resources", + cloudRegion, tenantId, Resources.class); + + Resources service2QueryResponse = objectMapper + .readValue(new File("src/test/resources/Service2ResourceGroupResponse.json"), Resources.class); + doReturn(service2QueryResponse).when(msoHeatUtilsMock).executeHeatClientRequest( + "/stacks/tsbc0005vm002ssc001-ssc_1_subint_service2_port_0_subinterfaces-hlzdigtimzst/447a9b41-714e-434b-b1d0-6cce8d9f0f0c/resources", + cloudRegion, tenantId, Resources.class); + + + Stack service2StackQuerySubInt = + stackObjectMapper.readValue(new File("src/test/resources/Service2SubInterface0.json"), Stack.class); + doReturn(service2StackQuerySubInt).when(msoHeatUtilsMock).executeHeatClientRequest( + "/stacks/tsbc0005vm002ssc001-ssc_1_subint_service2_port_0_subinterfaces-hlzdigtimzst-0-upfi5nhurk7y/f711be16-2654-4a09-b89d-0511fda20e81", + cloudRegion, tenantId, Stack.class); + Resources service2ResourceQuerySubInt = objectMapper + .readValue(new File("src/test/resources/Service2SubInterface1Resources.json"), Resources.class); + doReturn(service2ResourceQuerySubInt).when(msoHeatUtilsMock).executeHeatClientRequest( + "/stacks/tsbc0005vm002ssc001-ssc_1_subint_service2_port_0_subinterfaces-hlzdigtimzst-0-upfi5nhurk7y/f711be16-2654-4a09-b89d-0511fda20e81/resources", + cloudRegion, tenantId, Resources.class); + + Stack service1StackQuerySubInt1 = + stackObjectMapper.readValue(new File("src/test/resources/Service1SubInterface0.json"), Stack.class); + doReturn(service1StackQuerySubInt1).when(msoHeatUtilsMock).executeHeatClientRequest( + "/stacks/tsbc0005vm002ssc001-ssc_1_subint_service1_port_0_subinterfaces-dtmxjmny7yjz-1-fmn5laetg5cs/0d9cd813-2ae1-46c0-9ebb-48081f6cffbb", + cloudRegion, tenantId, Stack.class); + Resources service1ResourceQuerySubInt1 = objectMapper + .readValue(new File("src/test/resources/Service1SubInterface0Resources.json"), Resources.class); + doReturn(service1ResourceQuerySubInt1).when(msoHeatUtilsMock).executeHeatClientRequest( + "/stacks/tsbc0005vm002ssc001-ssc_1_subint_service1_port_0_subinterfaces-dtmxjmny7yjz-1-fmn5laetg5cs/0d9cd813-2ae1-46c0-9ebb-48081f6cffbb/resources", + cloudRegion, tenantId, Resources.class); + + + Stack service1StackQuerySubInt2 = + stackObjectMapper.readValue(new File("src/test/resources/Service1SubInterface1.json"), Stack.class); + doReturn(service1StackQuerySubInt2).when(msoHeatUtilsMock).executeHeatClientRequest( + "/stacks/tsbc0005vm002ssc001-ssc_1_subint_service1_port_0_subinterfaces-dtmxjmny7yjz-0-yghihziaf36m/b7019dd0-2ee9-4447-bdef-ac25676b205a", + cloudRegion, tenantId, Stack.class); + Resources service1ResourceQuerySubInt2 = objectMapper + .readValue(new File("src/test/resources/Service1SubInterface1Resources.json"), Resources.class); + doReturn(service1ResourceQuerySubInt2).when(msoHeatUtilsMock).executeHeatClientRequest( + "/stacks/tsbc0005vm002ssc001-ssc_1_subint_service1_port_0_subinterfaces-dtmxjmny7yjz-0-yghihziaf36m/b7019dd0-2ee9-4447-bdef-ac25676b205a/resources", + cloudRegion, tenantId, Resources.class); + + Stack service1StackQuerySubInt3 = + stackObjectMapper.readValue(new File("src/test/resources/Service1SubInterface2.json"), Stack.class); + doReturn(service1StackQuerySubInt3).when(msoHeatUtilsMock).executeHeatClientRequest( + "/stacks/tsbc0005vm002ssc001-ssc_1_subint_service1_port_0_subinterfaces-dtmxjmny7yjz-2-y3ndsavmsymv/bd0fc728-cbde-4301-a581-db56f494675c", + cloudRegion, tenantId, Stack.class); + Resources service1ResourceQuerySubInt3 = objectMapper + .readValue(new File("src/test/resources/Service1SubInterface2Resources.json"), Resources.class); + doReturn(service1ResourceQuerySubInt3).when(msoHeatUtilsMock).executeHeatClientRequest( + "/stacks/tsbc0005vm002ssc001-ssc_1_subint_service1_port_0_subinterfaces-dtmxjmny7yjz-2-y3ndsavmsymv/bd0fc728-cbde-4301-a581-db56f494675c/resources", + cloudRegion, tenantId, Resources.class); + + Set vServersToAudit = heatStackAudit.createVserverSet(resources, novaResources, portList); + Set vserversWithSubInterfaces = + heatStackAudit.processSubInterfaces(cloudRegion, tenantId, resourceGroups, vServersToAudit); + + String actualValue = objectMapper.writeValueAsString(vserversWithSubInterfaces); + String expectedValue = getJson("ExpectedVserversToAudit.json"); + JSONAssert.assertEquals(expectedValue, actualValue, false); + } + + @Test + public void auditHeatStackNoServers_Test() throws Exception { + Resources getResource = objectMapper + .readValue(new File("src/test/resources/Service1ResourceGroupResponse.json"), Resources.class); + doReturn(getResource).when(msoHeatUtilsMock).queryStackResources(cloudRegion, tenantId, "heatStackName", 3); + + Optional actual = + heatStackAudit.auditHeatStack(cloudRegion, "cloudOwner", tenantId, "heatStackName"); + assertEquals(true, actual.get().getAuditList().isEmpty()); + } + + @Test + public void auditHeatStackNestedServers_Test() throws Exception { + Resources getResource = + objectMapper.readValue(new File("src/test/resources/GetNestedResources.json"), Resources.class); + List novaResources = getResource.getList().stream() + .filter(p -> "OS::Nova::Server".equals(p.getType())).collect(Collectors.toList()); + List resourceGroups = getResource.getList().stream() + .filter(p -> "OS::Heat::ResourceGroup".equals(p.getType())).collect(Collectors.toList()); + + doReturn(getResource).when(msoHeatUtilsMock).queryStackResources(cloudRegion, tenantId, "heatStackName", 3); + Set vServersToAudit = heatStackAudit.createVserverSet(resources, novaResources, portList); + Set vserversWithSubInterfaces = + heatStackAudit.processSubInterfaces(cloudRegion, tenantId, resourceGroups, vServersToAudit); + String actualValue = objectMapper.writeValueAsString(vserversWithSubInterfaces); + String expectedValue = getJson("NestedExpectedValue.json"); + JSONAssert.assertEquals(expectedValue, actualValue, false); + } + + + @Test + public void findInterfaceInformation_Test() { + List novaResources = resources.getList().stream().filter(p -> "OS::Nova::Server".equals(p.getType())) + .collect(Collectors.toList()); + Set expectedVservers = new HashSet<>(); + Vserver vServer1 = new Vserver(); + vServer1.setVserverId("92272b67-d23f-42ca-87fa-7b06a9ec81f3"); + LInterfaces vServer1Linterfaces = new LInterfaces(); + vServer1.setLInterfaces(vServer1Linterfaces); + + LInterface ssc_1_trusted_port_0 = new LInterface(); + ssc_1_trusted_port_0.setInterfaceId("7ee06d9d-3d18-411c-9d3e-aec930f70413"); + ssc_1_trusted_port_0.setInterfaceName("ibcx0026v_ibcx0026vm003_untrusted_port"); + vServer1.getLInterfaces().getLInterface().add(ssc_1_trusted_port_0); + + LInterface ssc_1_svc2_port_0 = new LInterface(); + ssc_1_svc2_port_0.setInterfaceId("27391d94-33af-474a-927d-d409249e8fd3"); + ssc_1_svc2_port_0.setInterfaceName("ibcx0026v_ibcx0026vm003_untrusted_port"); + vServer1.getLInterfaces().getLInterface().add(ssc_1_svc2_port_0); + + LInterface ssc_1_mgmt_port_1 = new LInterface(); + ssc_1_mgmt_port_1.setInterfaceId("fdeedf37-c01e-4ab0-bdd6-8d5fc4913943"); + ssc_1_mgmt_port_1.setInterfaceName("ibcx0026v_ibcx0026vm003_untrusted_port"); + vServer1.getLInterfaces().getLInterface().add(ssc_1_mgmt_port_1); + + LInterface ssc_1_mgmt_port_0 = new LInterface(); + ssc_1_mgmt_port_0.setInterfaceId("8d93f63e-e972-48c7-ad98-b2122da47315"); + ssc_1_mgmt_port_0.setInterfaceName("ibcx0026v_ibcx0026vm003_untrusted_port"); + vServer1.getLInterfaces().getLInterface().add(ssc_1_mgmt_port_0); + + LInterface ssc_1_svc1_port_0 = new LInterface(); + ssc_1_svc1_port_0.setInterfaceId("0594a2f2-7ea4-42eb-abc2-48ea49677fca"); + ssc_1_svc1_port_0.setInterfaceName("ibcx0026v_ibcx0026vm003_untrusted_port"); + vServer1.getLInterfaces().getLInterface().add(ssc_1_svc1_port_0); + + LInterface ssc_1_int_ha_port_0 = new LInterface(); + ssc_1_int_ha_port_0.setInterfaceId("00bb8407-650e-48b5-b919-33b88d6f8fe3"); + ssc_1_int_ha_port_0.setInterfaceName("ibcx0026v_ibcx0026vm003_untrusted_port"); + vServer1.getLInterfaces().getLInterface().add(ssc_1_int_ha_port_0); + + expectedVservers.add(vServer1); + + Set actualVservers = heatStackAudit.createVserverSet(resources, novaResources, portList); + + assertThat(actualVservers, sameBeanAs(expectedVservers)); + } + + private String getJson(String filename) throws IOException { + return new String(Files.readAllBytes(Paths.get("src/test/resources/" + filename))); + } +} diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tasks/inventory/CreateAAIInventoryTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tasks/inventory/CreateAAIInventoryTest.java new file mode 100644 index 0000000000..e822f65072 --- /dev/null +++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tasks/inventory/CreateAAIInventoryTest.java @@ -0,0 +1,123 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017-2019 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.adapters.tasks.inventory; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertTrue; +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.times; +import java.io.File; +import java.io.IOException; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import org.camunda.bpm.client.task.ExternalTask; +import org.hamcrest.Matchers; +import org.junit.Before; +import org.junit.Test; +import org.mockito.ArgumentCaptor; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.onap.so.adapters.tasks.inventory.CreateAAIInventory; +import org.onap.so.audit.beans.AuditInventory; +import org.onap.so.client.aai.AAIObjectType; +import org.onap.so.client.aai.AAIResourcesClient; +import org.onap.so.client.aai.entities.uri.AAIResourceUri; +import org.onap.so.client.aai.entities.uri.AAIUriFactory; +import org.onap.so.objects.audit.AAIObjectAuditList; +import com.fasterxml.jackson.core.JsonParseException; +import com.fasterxml.jackson.databind.JsonMappingException; +import com.fasterxml.jackson.databind.ObjectMapper; + +public class CreateAAIInventoryTest extends CreateAAIInventory { + + @InjectMocks + private CreateAAIInventory createAAIInventory = new CreateAAIInventory(); + + @Mock + private ExternalTask mockExternalTask; + + @Mock + private AAIResourcesClient mockClient; + + private ObjectMapper objectMapper = new ObjectMapper(); + + private AuditInventory auditInventory = new AuditInventory(); + + AAIObjectAuditList auditListSuccess; + + AAIObjectAuditList auditListFailure; + + AAIObjectAuditList missingSubInterfaces; + + @Before + public void setup() throws JsonParseException, JsonMappingException, IOException { + auditInventory.setCloudOwner("cloudOwner"); + auditInventory.setCloudRegion("cloudRegion"); + auditInventory.setTenantId("tenantId"); + auditInventory.setHeatStackName("stackName"); + MockitoAnnotations.initMocks(this); + auditListSuccess = objectMapper.readValue(new File("src/test/resources/ExpectedVServerFound.json"), + AAIObjectAuditList.class); + auditListFailure = objectMapper.readValue(new File("src/test/resources/Vserver2_Found_VServer1_Not_Found.json"), + AAIObjectAuditList.class); + missingSubInterfaces = objectMapper.readValue(new File("src/test/resources/AuditResultsMissSub.json"), + AAIObjectAuditList.class); + doReturn(auditInventory).when(mockExternalTask).getVariable("auditInventory"); + } + + @Test + public void determineAuditResult_Test() throws Exception { + boolean actual = createAAIInventory.didAuditFailVserverLInterfaces(auditListSuccess); + assertEquals(false, actual); + } + + @Test + public void determineAuditResult_Failure_Test() throws Exception { + boolean actual = createAAIInventory.didAuditFailVserverLInterfaces(auditListFailure); + assertEquals(true, actual); + } + + @Test + public void missing_Sub_Interfaces_Test() throws Exception { + AAIResourceUri aaiURI2 = AAIUriFactory.createResourceUri(AAIObjectType.SUB_L_INTERFACE, "cloudOwner", + "regionOne", "0422ffb57ba042c0800a29dc85ca70f8", "92272b67-d23f-42ca-87fa-7b06a9ec81f3", + "tsbc0005v_tsbc0005vm002_svc1_port_0", "tsbc0005v_tsbc0005vm002_subint_untrusted_svc1_81"); + AAIResourceUri aaiURI1 = AAIUriFactory.createResourceUri(AAIObjectType.SUB_L_INTERFACE, "cloudOwner", + "regionOne", "0422ffb57ba042c0800a29dc85ca70f8", "92272b67-d23f-42ca-87fa-7b06a9ec81f3", + "tsbc0005v_tsbc0005vm002_svc2_port_0", "tsbc0005v_tsbc0005vm002_subint_untrusted_svc2_103"); + ArgumentCaptor captor = ArgumentCaptor.forClass(Optional.class); + ArgumentCaptor uriCaptor = ArgumentCaptor.forClass(AAIResourceUri.class); + + createAAIInventory.setAaiClient(mockClient); + createAAIInventory.createInventory(missingSubInterfaces); + Mockito.verify(mockClient, times(2)).createIfNotExists(uriCaptor.capture(), captor.capture()); + + List capturedURI = uriCaptor.getAllValues(); + assertTrue(capturedURI.stream().anyMatch(item -> aaiURI1.build().toString().equals(item.build().toString()))); + assertTrue(capturedURI.stream().anyMatch(item -> aaiURI2.build().toString().equals(item.build().toString()))); + + + + } +} diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tasks/inventory/CreateInventoryTaskTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tasks/inventory/CreateInventoryTaskTest.java new file mode 100644 index 0000000000..fc2baefcd5 --- /dev/null +++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tasks/inventory/CreateInventoryTaskTest.java @@ -0,0 +1,83 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017 - 2019 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.adapters.tasks.inventory; + +import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.times; +import org.camunda.bpm.client.task.ExternalTask; +import org.camunda.bpm.client.task.ExternalTaskService; +import org.junit.Before; +import org.junit.Test; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.MockitoAnnotations; +import org.onap.so.adapters.tasks.inventory.CreateAAIInventory; +import org.onap.so.adapters.tasks.inventory.CreateInventoryTask; +import org.onap.so.adapters.tasks.inventory.InventoryException; +import org.onap.so.client.graphinventory.GraphInventoryCommonObjectMapperProvider; +import org.onap.so.logging.tasks.AuditMDCSetup; +import org.onap.so.objects.audit.AAIObjectAudit; +import org.onap.so.objects.audit.AAIObjectAuditList; +import com.fasterxml.jackson.core.JsonProcessingException; + +public class CreateInventoryTaskTest { + + @Mock + ExternalTask externalTask; + + @Mock + CreateAAIInventory createAAIInventory; + + @Mock + ExternalTaskService externalTaskService; + + @InjectMocks + CreateInventoryTask inventoryTask; + + @Mock + private AuditMDCSetup mdcSetup; + + @Before + public void setup() { + MockitoAnnotations.initMocks(this); + } + + @Test + public void test_Runtime_Parse_Exception() { + doReturn(null).when(externalTask).getVariable("auditInventoryResult"); + inventoryTask.executeExternalTask(externalTask, externalTaskService); + Mockito.verify(externalTaskService, times(1)).handleBpmnError(externalTask, "AAIInventoryFailure"); + } + + @Test + public void testExecuteExternalTask_InventoryException() throws InventoryException, JsonProcessingException { + AAIObjectAuditList object = new AAIObjectAuditList(); + AAIObjectAudit e = new AAIObjectAudit(); + e.setDoesObjectExist(true); + object.getAuditList().add(e); + GraphInventoryCommonObjectMapperProvider objectMapper = new GraphInventoryCommonObjectMapperProvider(); + doReturn(objectMapper.getMapper().writeValueAsString(e)).when(externalTask).getVariable("auditInventoryResult"); + Mockito.doThrow(InventoryException.class).when(createAAIInventory).createInventory(Mockito.any()); + inventoryTask.executeExternalTask(externalTask, externalTaskService); + Mockito.verify(externalTaskService, times(1)).handleBpmnError(externalTask, "AAIInventoryFailure"); + } +} diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tasks/orchestration/PollServiceTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tasks/orchestration/PollServiceTest.java new file mode 100644 index 0000000000..b5b0f5a8ef --- /dev/null +++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tasks/orchestration/PollServiceTest.java @@ -0,0 +1,82 @@ +package org.onap.so.adapters.tasks.orchestration; + +import org.camunda.bpm.client.task.ExternalTask; +import org.camunda.bpm.client.task.ExternalTaskService; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.eq; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.so.adapters.tasks.orchestration.PollService; +import org.onap.so.logging.tasks.AuditMDCSetup; +import org.onap.so.openstack.exceptions.MsoException; +import org.onap.so.openstack.utils.MsoHeatUtils; +import com.woorea.openstack.heat.model.Stack; + +@RunWith(MockitoJUnitRunner.class) +public class PollServiceTest { + + private String RESOURCE_PATH = "src/test/resources/__files/"; + + @Mock + private ExternalTask mockExternalTask; + + @Mock + private ExternalTaskService mockExternalTaskService; + + @Mock + private MsoHeatUtils msoHeatUtils; + + @Mock + private AuditMDCSetup mdcSetup; + + @InjectMocks + private PollService pollService; + + @Test + public void testExecuteExternalTask() throws MsoException, IOException { + String xmlString = + new String(Files.readAllBytes(Paths.get(RESOURCE_PATH + "/vnfAdapterTaskRequestCreate.xml"))); + + Mockito.when(mockExternalTask.getVariable("vnfAdapterTaskRequest")).thenReturn(xmlString); + Mockito.when(mockExternalTask.getVariable("PollRollbackStatus")).thenReturn(false); + Mockito.when(mockExternalTask.getVariable("stackId")).thenReturn("stackId/stack123"); + Mockito.when(msoHeatUtils.pollStackForStatus(eq(1), any(Stack.class), eq("CREATE_IN_PROGRESS"), eq("regionOne"), + eq("0422ffb57ba042c0800a29dc85ca70f8"), eq(false))).thenReturn(new Stack()); + // Mockito.doNothing().when(msoHeatUtils).postProcessStackCreate(Mockito.any(), Mockito.any(), Mockito.any(), + // Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any()); + + pollService.executeExternalTask(mockExternalTask, mockExternalTaskService); + + Mockito.verify(msoHeatUtils).pollStackForStatus(eq(1), any(Stack.class), eq("CREATE_IN_PROGRESS"), + eq("regionOne"), eq("0422ffb57ba042c0800a29dc85ca70f8"), eq(false)); + + } + + @Test + public void testExecuteExternalTask_rollback() throws MsoException, IOException { + String xmlString = + new String(Files.readAllBytes(Paths.get(RESOURCE_PATH + "/vnfAdapterTaskRequestCreate.xml"))); + + Mockito.when(mockExternalTask.getVariable("vnfAdapterTaskRequest")).thenReturn(xmlString); + Mockito.when(mockExternalTask.getVariable("PollRollbackStatus")).thenReturn(true); + Mockito.when(mockExternalTask.getVariable("stackId")).thenReturn("stackId/stack123"); + Mockito.when(msoHeatUtils.pollStackForStatus(eq(1), any(), eq("DELETE_IN_PROGRESS"), eq("regionOne"), + eq("0422ffb57ba042c0800a29dc85ca70f8"), eq(true))).thenReturn(new Stack()); + Mockito.doNothing().when(msoHeatUtils).postProcessStackDelete(Mockito.any()); + + + pollService.executeExternalTask(mockExternalTask, mockExternalTaskService); + + Mockito.verify(msoHeatUtils).pollStackForStatus(eq(1), any(), eq("DELETE_IN_PROGRESS"), eq("regionOne"), + eq("0422ffb57ba042c0800a29dc85ca70f8"), eq(true)); + + } + +} diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tasks/orchestration/RollbackServiceTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tasks/orchestration/RollbackServiceTest.java new file mode 100644 index 0000000000..f7613909ec --- /dev/null +++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tasks/orchestration/RollbackServiceTest.java @@ -0,0 +1,82 @@ +package org.onap.so.adapters.tasks.orchestration; + +import static org.junit.Assert.assertEquals; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import javax.xml.ws.Holder; +import org.camunda.bpm.client.task.ExternalTask; +import org.camunda.bpm.client.task.ExternalTaskService; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.so.adapters.tasks.orchestration.RollbackService; +import org.onap.so.adapters.vnf.MsoVnfAdapterImpl; +import org.onap.so.adapters.vnf.exceptions.VnfException; +import org.onap.so.entity.MsoRequest; +import org.onap.so.logging.tasks.AuditMDCSetup; +import org.onap.so.openstack.beans.VnfRollback; +import org.onap.so.openstack.exceptions.MsoException; +import org.onap.so.openstack.utils.MsoHeatUtils; +import com.woorea.openstack.heat.model.Stack; + +@RunWith(MockitoJUnitRunner.class) +public class RollbackServiceTest { + + private String RESOURCE_PATH = "src/test/resources/__files/"; + + @Mock + private ExternalTask mockExternalTask; + + @Mock + private ExternalTaskService mockExternalTaskService; + + @Mock + private MsoVnfAdapterImpl vnfAdapterImpl; + + @Mock + private MsoHeatUtils msoHeatUtils; + + @Mock + private AuditMDCSetup mdcSetup; + + @InjectMocks + private RollbackService rollbackService; + + + @Test + public void findRequestTypeTest() throws IOException { + String payload = new String(Files.readAllBytes(Paths.get(RESOURCE_PATH + "/vnfAdapterTaskRequestCreate.xml"))); + + Optional actual = rollbackService.findRequestType(payload); + + assertEquals("createVfModuleRequest", actual.get()); + } + + @Test + public void testExecuteExternalTask() throws VnfException, MsoException, IOException { + String payload = new String(Files.readAllBytes(Paths.get(RESOURCE_PATH + "/vnfAdapterTaskRequestCreate.xml"))); + + Stack stack = new Stack(); + stack.setId("heatId"); + Mockito.when(mockExternalTask.getVariable("vnfAdapterTaskRequest")).thenReturn(payload); + Mockito.doNothing().when(vnfAdapterImpl).deleteVfModule(Mockito.any(), Mockito.any(), Mockito.any(), + Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any()); + Mockito.doNothing().when(mockExternalTaskService).complete(Mockito.any(), Mockito.any()); + + rollbackService.executeExternalTask(mockExternalTask, mockExternalTaskService); + + Mockito.verify(vnfAdapterImpl, Mockito.times(1)).deleteVfModule(Mockito.eq("regionOne"), + Mockito.eq("CloudOwner"), Mockito.eq("0422ffb57ba042c0800a29dc85ca70f8"), Mockito.eq("dummy_id"), + Mockito.any(String.class), Mockito.any(String.class), Mockito.any(), Mockito.any(), Mockito.any()); + Mockito.verify(mockExternalTaskService).complete(Mockito.eq(mockExternalTask), Mockito.any()); + + } + +} diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tasks/orchestration/StackServiceTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tasks/orchestration/StackServiceTest.java new file mode 100644 index 0000000000..2f583b30a2 --- /dev/null +++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tasks/orchestration/StackServiceTest.java @@ -0,0 +1,113 @@ +package org.onap.so.adapters.tasks.orchestration; + +import static org.junit.Assert.assertEquals; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import javax.xml.ws.Holder; +import org.camunda.bpm.client.task.ExternalTask; +import org.camunda.bpm.client.task.ExternalTaskService; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.so.adapters.tasks.orchestration.StackService; +import org.onap.so.adapters.vnf.MsoVnfAdapterImpl; +import org.onap.so.entity.MsoRequest; +import org.onap.so.logging.tasks.AuditMDCSetup; +import org.onap.so.openstack.beans.VnfRollback; +import org.onap.so.openstack.exceptions.MsoException; +import org.onap.so.openstack.utils.MsoHeatUtils; +import com.woorea.openstack.heat.model.Stack; +import org.onap.so.adapters.vnf.exceptions.VnfException; + +@RunWith(MockitoJUnitRunner.class) +public class StackServiceTest { + + private String RESOURCE_PATH = "src/test/resources/__files/"; + + @Mock + private ExternalTask mockExternalTask; + + @Mock + private ExternalTaskService mockExternalTaskService; + + @Mock + private MsoVnfAdapterImpl vnfAdapterImpl; + + @Mock + private MsoHeatUtils msoHeatUtils; + + @Mock + private AuditMDCSetup mdcSetup; + + @InjectMocks + private StackService stackService; + + @Test + public void findRequestTypeTest() throws IOException { + String payload = new String(Files.readAllBytes(Paths.get(RESOURCE_PATH + "/vnfAdapterTaskRequestCreate.xml"))); + + Optional actual = stackService.findRequestType(payload); + + assertEquals("createVfModuleRequest", actual.get()); + } + + @Test + public void testExecuteExternalTask() throws VnfException, MsoException, IOException { + String payload = new String(Files.readAllBytes(Paths.get(RESOURCE_PATH + "/vnfAdapterTaskRequestCreate.xml"))); + + Stack stack = new Stack(); + stack.setId("heatId"); + Mockito.when(mockExternalTask.getVariable("vnfAdapterTaskRequest")).thenReturn(payload); + Mockito.doNothing().when(vnfAdapterImpl).createVfModule(Mockito.any(), Mockito.any(), Mockito.any(), + Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), + Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), + Mockito.any(), Mockito.any(), Mockito.any()); + Mockito.doNothing().when(mockExternalTaskService).complete(Mockito.any(), Mockito.any()); + + stackService.executeExternalTask(mockExternalTask, mockExternalTaskService); + + Map paramsMap = new HashMap(); + paramsMap.put("vf_module_id", "985a468b-328b-4c2b-ad0e-b8f1e19501c4"); + paramsMap.put("vnf_id", "6640feba-55f6-4946-9694-4d9558c8870a"); + paramsMap.put("vnf_name", "Robot_VNF_For_Volume_Group"); + paramsMap.put("availability_zone_0", "AZ-MN02"); + paramsMap.put("environment_context", "General_Revenue-Bearing"); + paramsMap.put("user_directives", "{}"); + paramsMap.put("workload_context", ""); + paramsMap.put("vf_module_name", "dummy_id"); + paramsMap.put("vf_module_index", "0"); + paramsMap.put("sdnc_directives", + "{ \"attributes\": [ {\"attribute_name\": \"availability_zone_0\", \"attribute_value\": \"AZ-MN02\"}] }"); + + Map variables = new HashMap<>(); + variables.put("backout", true); + variables.put("WorkflowResponse", ""); + variables.put("OpenstackInvokeSuccess", true); + variables.put("stackId", null); + variables.put("openstackAdapterErrorMessage", null); + variables.put("PollRollbackStatus", false); + variables.put("rollbackPerformed", false); + variables.put("OpenstackRollbackSuccess", false); + variables.put("OpenstackPollSuccess", false); + + Mockito.verify(vnfAdapterImpl, Mockito.times(1)).createVfModule(Mockito.eq("regionOne"), + Mockito.eq("CloudOwner"), Mockito.eq("0422ffb57ba042c0800a29dc85ca70f8"), + Mockito.eq( + "Vf zrdm5bpxmc02092017-Service/Vf zrdm5bpxmc02092017-VF 0::VfZrdm5bpxmc02092017Vf..pxmc_base..module-0"), + Mockito.eq("1.0"), Mockito.eq("6640feba-55f6-4946-9694-4d9558c8870a"), Mockito.eq("dummy_id"), + Mockito.eq("985a468b-328b-4c2b-ad0e-b8f1e19501c4"), Mockito.eq(null), Mockito.eq(null), + Mockito.eq(null), Mockito.eq("074c64d0-7e13-4bcc-8bdb-ea922331102d"), Mockito.eq(paramsMap), + Mockito.eq(false), Mockito.eq(false), Mockito.eq(null), Mockito.any(), Mockito.any(), Mockito.any(), + Mockito.any()); + Mockito.verify(mockExternalTaskService).complete(Mockito.eq(mockExternalTask), Mockito.eq(variables)); + + } + +} diff --git a/adapters/mso-openstack-adapters/src/test/resources/__files/vnfAdapterTaskRequestCreate.xml b/adapters/mso-openstack-adapters/src/test/resources/__files/vnfAdapterTaskRequestCreate.xml new file mode 100644 index 0000000000..c7c880ed92 --- /dev/null +++ b/adapters/mso-openstack-adapters/src/test/resources/__files/vnfAdapterTaskRequestCreate.xml @@ -0,0 +1,66 @@ + + + 7f4557c8-c3b9-4743-8b88-9539f9ed7bea + http://mso-bpmn-infra-svc:9200/mso/WorkflowMessage/VNFAResponse/7f4557c8-c3b9-4743-8b88-9539f9ed7bea + + true + regionOne + CloudOwner + 0422ffb57ba042c0800a29dc85ca70f8 + 6640feba-55f6-4946-9694-4d9558c8870a + Vf zrdm5bpxmc02092017-Service/Vf zrdm5bpxmc02092017-VF 0 + 1.0 + 985a468b-328b-4c2b-ad0e-b8f1e19501c4 + dummy_id + VfZrdm5bpxmc02092017Vf..pxmc_base..module-0 + 985a468b-328b-4c2b-ad0e-b8f1e19501c4 + 074c64d0-7e13-4bcc-8bdb-ea922331102d + false + true + + + vf_module_id + 985a468b-328b-4c2b-ad0e-b8f1e19501c4 + + + vnf_id + 6640feba-55f6-4946-9694-4d9558c8870a + + + vnf_name + Robot_VNF_For_Volume_Group + + + availability_zone_0 + AZ-MN02 + + + environment_context + General_Revenue-Bearing + + + user_directives + {} + + + workload_context + + + + vf_module_name + dummy_id + + + vf_module_index + 0 + + + sdnc_directives + { "attributes": [ {"attribute_name": "availability_zone_0", "attribute_value": "AZ-MN02"}] } + + + + 049abdd8-0e19-48b8-bd87-b18f8d49048c + 7dc4c4eb-b1d7-4aef-94d1-24e925d1210c + + diff --git a/adapters/so-appc-orchestrator/src/main/java/org/onap/so/adapters/appc/orchestrator/service/ApplicationControllerTask.java b/adapters/so-appc-orchestrator/src/main/java/org/onap/so/adapters/appc/orchestrator/service/ApplicationControllerTask.java index db70a6b5cb..2b5e4b2553 100644 --- a/adapters/so-appc-orchestrator/src/main/java/org/onap/so/adapters/appc/orchestrator/service/ApplicationControllerTask.java +++ b/adapters/so-appc-orchestrator/src/main/java/org/onap/so/adapters/appc/orchestrator/service/ApplicationControllerTask.java @@ -6,7 +6,7 @@ import org.onap.so.adapters.appc.orchestrator.client.ApplicationControllerCallba import org.onap.so.adapters.appc.orchestrator.client.ApplicationControllerSupport; import org.onap.so.adapters.appc.orchestrator.client.StatusCategory; import org.onap.so.appc.orchestrator.service.beans.ApplicationControllerTaskRequest; -import org.onap.so.externaltasks.logging.AuditMDCSetup; +import org.onap.so.logging.tasks.AuditMDCSetup; import org.onap.so.utils.ExternalTaskUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/adapters/so-appc-orchestrator/src/test/java/org/onap/so/adapters/appc/orchestrator/service/ApplicationControllerTaskTest.java b/adapters/so-appc-orchestrator/src/test/java/org/onap/so/adapters/appc/orchestrator/service/ApplicationControllerTaskTest.java index 228ee90107..179bdabc6b 100644 --- a/adapters/so-appc-orchestrator/src/test/java/org/onap/so/adapters/appc/orchestrator/service/ApplicationControllerTaskTest.java +++ b/adapters/so-appc-orchestrator/src/test/java/org/onap/so/adapters/appc/orchestrator/service/ApplicationControllerTaskTest.java @@ -31,9 +31,9 @@ import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; -import org.onap.so.externaltasks.logging.AuditMDCSetup; import org.onap.so.adapters.appc.orchestrator.client.ApplicationControllerCallback; import org.onap.so.appc.orchestrator.service.beans.ApplicationControllerTaskRequest; +import org.onap.so.logging.tasks.AuditMDCSetup; import org.onap.appc.client.lcm.model.Status; public class ApplicationControllerTaskTest extends ApplicationControllerTask { diff --git a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/VnfAdapterRestV1.groovy b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/VnfAdapterRestV1.groovy index a6aacc7ea5..e8f842471c 100644 --- a/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/VnfAdapterRestV1.groovy +++ b/bpmn/MSOCommonBPMN/src/main/groovy/org/onap/so/bpmn/common/scripts/VnfAdapterRestV1.groovy @@ -40,419 +40,419 @@ import java.util.UUID import org.onap.so.utils.Components - +@Deprecated //Use vnfAdapterRestV2 class VnfAdapterRestV1 extends AbstractServiceTaskProcessor { private static final Logger logger = LoggerFactory.getLogger( VnfAdapterRestV1.class); - ExceptionUtil exceptionUtil = new ExceptionUtil() + ExceptionUtil exceptionUtil = new ExceptionUtil() - // VNF Response Processing - public void preProcessRequest (DelegateExecution execution) { - def method = getClass().getSimpleName() + '.preProcessRequest(' + - 'execution=' + execution.getId() + - ')' - logger.trace('Entered ' + method) + // VNF Response Processing + public void preProcessRequest (DelegateExecution execution) { + def method = getClass().getSimpleName() + '.preProcessRequest(' + + 'execution=' + execution.getId() + + ')' + logger.trace('Entered ' + method) - def prefix="VNFREST_" - execution.setVariable("prefix", prefix) - setSuccessIndicator(execution, false) + def prefix="VNFREST_" + execution.setVariable("prefix", prefix) + setSuccessIndicator(execution, false) - try { - String request = validateRequest(execution, "mso-request-id") + try { + String request = validateRequest(execution, "mso-request-id") - // Get the request type (the name of the root element) from the request + // Get the request type (the name of the root element) from the request - Node root = new XmlParser().parseText(request) - String requestType = root.name() - execution.setVariable(prefix + 'requestType', requestType) - logger.debug(getProcessKey(execution) + ': ' + prefix + 'requestType = ' + requestType) + Node root = new XmlParser().parseText(request) + String requestType = root.name() + execution.setVariable(prefix + 'requestType', requestType) + logger.debug(getProcessKey(execution) + ': ' + prefix + 'requestType = ' + requestType) - logger.debug('VnfAdapterRestV1, request: ' + request) - // Get the messageId from the request + logger.debug('VnfAdapterRestV1, request: ' + request) + // Get the messageId from the request - String messageId = getChildText(root, 'messageId') + String messageId = getChildText(root, 'messageId') - if ('rollbackVolumeGroupRequest'.equals(requestType)) { - messageId = getMessageIdForVolumeGroupRollback(root) - } + if ('rollbackVolumeGroupRequest'.equals(requestType)) { + messageId = getMessageIdForVolumeGroupRollback(root) + } - if (messageId == null || messageId.isEmpty()) { - String msg = getProcessKey(execution) + ': no messageId in ' + requestType - logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", - ErrorCode.UnknownError.getValue()); + if (messageId == null || messageId.isEmpty()) { + String msg = getProcessKey(execution) + ': no messageId in ' + requestType + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", + ErrorCode.UnknownError.getValue()); exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg, ONAPComponents.SO) - } + } - execution.setVariable('VNFAResponse_CORRELATOR', messageId) - logger.debug(getProcessKey(execution) + ': VNFAResponse_CORRELATOR = ' + messageId) + execution.setVariable('VNFAResponse_CORRELATOR', messageId) + logger.debug(getProcessKey(execution) + ': VNFAResponse_CORRELATOR = ' + messageId) - // Get the notificationUrl from the request + // Get the notificationUrl from the request - String notificationUrl = getChildText(root, 'notificationUrl') + String notificationUrl = getChildText(root, 'notificationUrl') - if (notificationUrl == null || notificationUrl.isEmpty()) { - String msg = getProcessKey(execution) + ': no notificationUrl in ' + requestType - logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", - ErrorCode.UnknownError.getValue()); + if (notificationUrl == null || notificationUrl.isEmpty()) { + String msg = getProcessKey(execution) + ': no notificationUrl in ' + requestType + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", + ErrorCode.UnknownError.getValue()); exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg, ONAPComponents.SO) - } + } - execution.setVariable(prefix + 'notificationUrl', notificationUrl) - logger.debug(getProcessKey(execution) + ': ' + prefix + 'notificationUrl = ' + notificationUrl) + execution.setVariable(prefix + 'notificationUrl', notificationUrl) + logger.debug(getProcessKey(execution) + ': ' + prefix + 'notificationUrl = ' + notificationUrl) - // Determine the VnfAdapter endpoint + // Determine the VnfAdapter endpoint - String vnfAdapterEndpoint = UrnPropertiesReader.getVariable("mso.adapters.vnf.rest.endpoint", execution) + String vnfAdapterEndpoint = UrnPropertiesReader.getVariable("mso.adapters.vnf.rest.endpoint", execution) - if (vnfAdapterEndpoint == null || vnfAdapterEndpoint.isEmpty()) { - String msg = getProcessKey(execution) + ': mso:adapters:vnf:rest:endpoint URN mapping is not defined' - logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", - ErrorCode.UnknownError.getValue()); + if (vnfAdapterEndpoint == null || vnfAdapterEndpoint.isEmpty()) { + String msg = getProcessKey(execution) + ': mso:adapters:vnf:rest:endpoint URN mapping is not defined' + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", + ErrorCode.UnknownError.getValue()); exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg, ONAPComponents.SO) - } + } - while (vnfAdapterEndpoint.endsWith('/')) { - vnfAdapterEndpoint = vnfAdapterEndpoint.substring(0, vnfAdapterEndpoint.length()-1) - } + while (vnfAdapterEndpoint.endsWith('/')) { + vnfAdapterEndpoint = vnfAdapterEndpoint.substring(0, vnfAdapterEndpoint.length()-1) + } - String vnfAdapterMethod = null - String vnfAdapterUrl = null - String vnfAdapterRequest = request + String vnfAdapterMethod = null + String vnfAdapterUrl = null + String vnfAdapterRequest = request - if ('createVfModuleRequest'.equals(requestType)) { - String vnfId = getChildText(root, 'vnfId') + if ('createVfModuleRequest'.equals(requestType)) { + String vnfId = getChildText(root, 'vnfId') - if (vnfId == null || vnfId.isEmpty()) { - String msg = getProcessKey(execution) + ': no vnfId in ' + requestType - logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", - ErrorCode.UnknownError.getValue()); + if (vnfId == null || vnfId.isEmpty()) { + String msg = getProcessKey(execution) + ': no vnfId in ' + requestType + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", + ErrorCode.UnknownError.getValue()); exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg, ONAPComponents.SO) - } + } - vnfAdapterMethod = 'POST' - vnfAdapterUrl = vnfAdapterEndpoint + '/' + URLEncoder.encode(vnfId, 'UTF-8') + '/vf-modules' + vnfAdapterMethod = 'POST' + vnfAdapterUrl = vnfAdapterEndpoint + '/' + URLEncoder.encode(vnfId, 'UTF-8') + '/vf-modules' - } else if ('updateVfModuleRequest'.equals(requestType)) { - String vnfId = getChildText(root, 'vnfId') + } else if ('updateVfModuleRequest'.equals(requestType)) { + String vnfId = getChildText(root, 'vnfId') - if (vnfId == null || vnfId.isEmpty()) { - String msg = getProcessKey(execution) + ': no vnfId in ' + requestType - logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", - ErrorCode.UnknownError.getValue()); + if (vnfId == null || vnfId.isEmpty()) { + String msg = getProcessKey(execution) + ': no vnfId in ' + requestType + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", + ErrorCode.UnknownError.getValue()); exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg, ONAPComponents.SO) - } + } - String vfModuleId = getChildText(root, 'vfModuleId') + String vfModuleId = getChildText(root, 'vfModuleId') - if (vfModuleId == null || vfModuleId.isEmpty()) { - String msg = getProcessKey(execution) + ': no vfModuleId in ' + requestType - logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", - ErrorCode.UnknownError.getValue()); + if (vfModuleId == null || vfModuleId.isEmpty()) { + String msg = getProcessKey(execution) + ': no vfModuleId in ' + requestType + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", + ErrorCode.UnknownError.getValue()); exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg, ONAPComponents.SO) - } + } - vnfAdapterMethod = 'PUT' - vnfAdapterUrl = vnfAdapterEndpoint + '/' + URLEncoder.encode(vnfId, 'UTF-8') + - '/vf-modules/' + URLEncoder.encode(vfModuleId, 'UTF-8') + vnfAdapterMethod = 'PUT' + vnfAdapterUrl = vnfAdapterEndpoint + '/' + URLEncoder.encode(vnfId, 'UTF-8') + + '/vf-modules/' + URLEncoder.encode(vfModuleId, 'UTF-8') - } else if ('deleteVfModuleRequest'.equals(requestType)) { - String vnfId = getChildText(root, 'vnfId') + } else if ('deleteVfModuleRequest'.equals(requestType)) { + String vnfId = getChildText(root, 'vnfId') - if (vnfId == null || vnfId.isEmpty()) { - String msg = getProcessKey(execution) + ': no vnfId in ' + requestType - logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", - ErrorCode.UnknownError.getValue()); + if (vnfId == null || vnfId.isEmpty()) { + String msg = getProcessKey(execution) + ': no vnfId in ' + requestType + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", + ErrorCode.UnknownError.getValue()); exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg, ONAPComponents.SO) - } + } - String vfModuleId = getChildText(root, 'vfModuleId') + String vfModuleId = getChildText(root, 'vfModuleId') - if (vfModuleId == null || vfModuleId.isEmpty()) { - String msg = getProcessKey(execution) + ': no vfModuleId in ' + requestType - logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", - ErrorCode.UnknownError.getValue()); + if (vfModuleId == null || vfModuleId.isEmpty()) { + String msg = getProcessKey(execution) + ': no vfModuleId in ' + requestType + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", + ErrorCode.UnknownError.getValue()); exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg, ONAPComponents.SO) - } + } - vnfAdapterMethod = 'DELETE' - vnfAdapterUrl = vnfAdapterEndpoint + '/' + URLEncoder.encode(vnfId, 'UTF-8') + - '/vf-modules/' + URLEncoder.encode(vfModuleId, 'UTF-8') + vnfAdapterMethod = 'DELETE' + vnfAdapterUrl = vnfAdapterEndpoint + '/' + URLEncoder.encode(vnfId, 'UTF-8') + + '/vf-modules/' + URLEncoder.encode(vfModuleId, 'UTF-8') - } else if ('rollbackVfModuleRequest'.equals(requestType)) { - Node vfModuleRollbackNode = getChild(root, 'vfModuleRollback') + } else if ('rollbackVfModuleRequest'.equals(requestType)) { + Node vfModuleRollbackNode = getChild(root, 'vfModuleRollback') - if (vfModuleRollbackNode == null) { - String msg = getProcessKey(execution) + ': no vfModuleRollback in ' + requestType - logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", - ErrorCode.UnknownError.getValue()); + if (vfModuleRollbackNode == null) { + String msg = getProcessKey(execution) + ': no vfModuleRollback in ' + requestType + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", + ErrorCode.UnknownError.getValue()); exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg, ONAPComponents.SO) - } + } - String vnfId = getChildText(vfModuleRollbackNode, 'vnfId') + String vnfId = getChildText(vfModuleRollbackNode, 'vnfId') - if (vnfId == null || vnfId.isEmpty()) { - String msg = getProcessKey(execution) + ': no vnfId in ' + requestType - logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", - ErrorCode.UnknownError.getValue()); + if (vnfId == null || vnfId.isEmpty()) { + String msg = getProcessKey(execution) + ': no vnfId in ' + requestType + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", + ErrorCode.UnknownError.getValue()); exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg, ONAPComponents.SO) - } + } - String vfModuleId = getChildText(vfModuleRollbackNode, 'vfModuleId') + String vfModuleId = getChildText(vfModuleRollbackNode, 'vfModuleId') - if (vfModuleId == null || vfModuleId.isEmpty()) { - String msg = getProcessKey(execution) + ': no vfModuleId in ' + requestType - logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", - ErrorCode.UnknownError.getValue()); + if (vfModuleId == null || vfModuleId.isEmpty()) { + String msg = getProcessKey(execution) + ': no vfModuleId in ' + requestType + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", + ErrorCode.UnknownError.getValue()); exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg, ONAPComponents.SO) - } - - vnfAdapterMethod = 'DELETE' - vnfAdapterUrl = vnfAdapterEndpoint + '/' + URLEncoder.encode(vnfId, 'UTF-8') + - '/vf-modules/' + URLEncoder.encode(vfModuleId, 'UTF-8') + '/rollback' - - } else if ('createVolumeGroupRequest'.equals(requestType)) { - vnfAdapterMethod = 'POST' - if (vnfAdapterEndpoint.endsWith('v1/vnfs')) { - vnfAdapterEndpoint = vnfAdapterEndpoint.substring(0, (vnfAdapterEndpoint.length()-'/vnfs'.length())) - } - vnfAdapterUrl = vnfAdapterEndpoint + '/volume-groups' - - } else if ('updateVolumeGroupRequest'.equals(requestType)) { - String volumeGroupId = getChildText(root, 'volumeGroupId') - - if (volumeGroupId == null || volumeGroupId.isEmpty()) { - String msg = getProcessKey(execution) + ': no volumeGroupId in ' + requestType - logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", - ErrorCode.UnknownError.getValue()); + } + + vnfAdapterMethod = 'DELETE' + vnfAdapterUrl = vnfAdapterEndpoint + '/' + URLEncoder.encode(vnfId, 'UTF-8') + + '/vf-modules/' + URLEncoder.encode(vfModuleId, 'UTF-8') + '/rollback' + + } else if ('createVolumeGroupRequest'.equals(requestType)) { + vnfAdapterMethod = 'POST' + if (vnfAdapterEndpoint.endsWith('v1/vnfs')) { + vnfAdapterEndpoint = vnfAdapterEndpoint.substring(0, (vnfAdapterEndpoint.length()-'/vnfs'.length())) + } + vnfAdapterUrl = vnfAdapterEndpoint + '/volume-groups' + + } else if ('updateVolumeGroupRequest'.equals(requestType)) { + String volumeGroupId = getChildText(root, 'volumeGroupId') + + if (volumeGroupId == null || volumeGroupId.isEmpty()) { + String msg = getProcessKey(execution) + ': no volumeGroupId in ' + requestType + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", + ErrorCode.UnknownError.getValue()); exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg, ONAPComponents.SO) - } + } - vnfAdapterMethod = 'PUT' - if (vnfAdapterEndpoint.endsWith('v1/vnfs')) { - vnfAdapterEndpoint = vnfAdapterEndpoint.substring(0, (vnfAdapterEndpoint.length()-'/vnfs'.length())) - } - vnfAdapterUrl = vnfAdapterEndpoint + '/volume-groups/' + URLEncoder.encode(volumeGroupId, 'UTF-8') + vnfAdapterMethod = 'PUT' + if (vnfAdapterEndpoint.endsWith('v1/vnfs')) { + vnfAdapterEndpoint = vnfAdapterEndpoint.substring(0, (vnfAdapterEndpoint.length()-'/vnfs'.length())) + } + vnfAdapterUrl = vnfAdapterEndpoint + '/volume-groups/' + URLEncoder.encode(volumeGroupId, 'UTF-8') - } else if ('deleteVolumeGroupRequest'.equals(requestType)) { - String volumeGroupId = getChildText(root, 'volumeGroupId') + } else if ('deleteVolumeGroupRequest'.equals(requestType)) { + String volumeGroupId = getChildText(root, 'volumeGroupId') - if (volumeGroupId == null || volumeGroupId.isEmpty()) { - String msg = getProcessKey(execution) + ': no volumeGroupId in ' + requestType - logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", - ErrorCode.UnknownError.getValue()); + if (volumeGroupId == null || volumeGroupId.isEmpty()) { + String msg = getProcessKey(execution) + ': no volumeGroupId in ' + requestType + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", + ErrorCode.UnknownError.getValue()); exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg, ONAPComponents.SO) - } + } - vnfAdapterMethod = 'DELETE' - if (vnfAdapterEndpoint.endsWith('v1/vnfs')) { - vnfAdapterEndpoint = vnfAdapterEndpoint.substring(0, (vnfAdapterEndpoint.length()-'/vnfs'.length())) - } - vnfAdapterUrl = vnfAdapterEndpoint + '/volume-groups/' + URLEncoder.encode(volumeGroupId, 'UTF-8') + vnfAdapterMethod = 'DELETE' + if (vnfAdapterEndpoint.endsWith('v1/vnfs')) { + vnfAdapterEndpoint = vnfAdapterEndpoint.substring(0, (vnfAdapterEndpoint.length()-'/vnfs'.length())) + } + vnfAdapterUrl = vnfAdapterEndpoint + '/volume-groups/' + URLEncoder.encode(volumeGroupId, 'UTF-8') - } else if ('rollbackVolumeGroupRequest'.equals(requestType)) { - String volumeGroupId = getVolumeGroupIdFromRollbackRequest(root) + } else if ('rollbackVolumeGroupRequest'.equals(requestType)) { + String volumeGroupId = getVolumeGroupIdFromRollbackRequest(root) - if (volumeGroupId == null || volumeGroupId.isEmpty()) { - String msg = getProcessKey(execution) + ': no volumeGroupId in ' + requestType - logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", - ErrorCode.UnknownError.getValue()); + if (volumeGroupId == null || volumeGroupId.isEmpty()) { + String msg = getProcessKey(execution) + ': no volumeGroupId in ' + requestType + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", + ErrorCode.UnknownError.getValue()); exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg, ONAPComponents.SO) - } - - vnfAdapterMethod = 'DELETE' - if (vnfAdapterEndpoint.endsWith('v1/vnfs')) { - vnfAdapterEndpoint = vnfAdapterEndpoint.substring(0, (vnfAdapterEndpoint.length()-'/vnfs'.length())) - } - vnfAdapterUrl = vnfAdapterEndpoint + '/volume-groups/' + URLEncoder.encode(volumeGroupId, 'UTF-8') + '/rollback' - - } else { - String msg = getProcessKey(execution) + ': Unsupported request type: ' + requestType - logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", - ErrorCode.UnknownError.getValue()); + } + + vnfAdapterMethod = 'DELETE' + if (vnfAdapterEndpoint.endsWith('v1/vnfs')) { + vnfAdapterEndpoint = vnfAdapterEndpoint.substring(0, (vnfAdapterEndpoint.length()-'/vnfs'.length())) + } + vnfAdapterUrl = vnfAdapterEndpoint + '/volume-groups/' + URLEncoder.encode(volumeGroupId, 'UTF-8') + '/rollback' + + } else { + String msg = getProcessKey(execution) + ': Unsupported request type: ' + requestType + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", + ErrorCode.UnknownError.getValue()); exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg, ONAPComponents.SO) - } - - execution.setVariable(prefix + 'vnfAdapterMethod', vnfAdapterMethod) - logger.debug(getProcessKey(execution) + ': ' + prefix + 'vnfAdapterMethod = ' + vnfAdapterMethod) - execution.setVariable(prefix + 'vnfAdapterUrl', vnfAdapterUrl) - logger.debug(getProcessKey(execution) + ': ' + prefix + 'vnfAdapterUrl = ' + vnfAdapterUrl) - execution.setVariable(prefix + 'vnfAdapterRequest', vnfAdapterRequest) - logger.debug(getProcessKey(execution) + ': ' + prefix + 'vnfAdapterRequest = \n' + vnfAdapterRequest) - - // Get the Basic Auth credentials for the VnfAdapter - - String basicAuthValue = UrnPropertiesReader.getVariable("mso.adapters.po.auth", execution) - - if (basicAuthValue == null || basicAuthValue.isEmpty()) { - logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), - getProcessKey(execution) + ": mso:adapters:po:auth URN mapping is not defined", "BPMN", - ErrorCode.UnknownError.getValue()); - } else { - try { - def encodedString = utils.getBasicAuth(basicAuthValue, UrnPropertiesReader.getVariable("mso.msoKey", execution)) - execution.setVariable(prefix + 'basicAuthHeaderValue', encodedString) - } catch (IOException ex) { - logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), - getProcessKey(execution) + ": Unable to encode BasicAuth credentials for VnfAdapter", - "BPMN", ErrorCode.UnknownError.getValue(), ex); - } - } - - } catch (BpmnError e) { - logger.debug(" Rethrowing MSOWorkflowException") - throw e - } catch (Exception e) { - String msg = 'Caught exception in ' + method + ": " + e - logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", - ErrorCode.UnknownError.getValue()); - logger.debug(msg) + } + + execution.setVariable(prefix + 'vnfAdapterMethod', vnfAdapterMethod) + logger.debug(getProcessKey(execution) + ': ' + prefix + 'vnfAdapterMethod = ' + vnfAdapterMethod) + execution.setVariable(prefix + 'vnfAdapterUrl', vnfAdapterUrl) + logger.debug(getProcessKey(execution) + ': ' + prefix + 'vnfAdapterUrl = ' + vnfAdapterUrl) + execution.setVariable(prefix + 'vnfAdapterRequest', vnfAdapterRequest) + logger.debug(getProcessKey(execution) + ': ' + prefix + 'vnfAdapterRequest = \n' + vnfAdapterRequest) + + // Get the Basic Auth credentials for the VnfAdapter + + String basicAuthValue = UrnPropertiesReader.getVariable("mso.adapters.po.auth", execution) + + if (basicAuthValue == null || basicAuthValue.isEmpty()) { + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + getProcessKey(execution) + ": mso:adapters:po:auth URN mapping is not defined", "BPMN", + ErrorCode.UnknownError.getValue()); + } else { + try { + def encodedString = utils.getBasicAuth(basicAuthValue, UrnPropertiesReader.getVariable("mso.msoKey", execution)) + execution.setVariable(prefix + 'basicAuthHeaderValue', encodedString) + } catch (IOException ex) { + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + getProcessKey(execution) + ": Unable to encode BasicAuth credentials for VnfAdapter", + "BPMN", ErrorCode.UnknownError.getValue(), ex); + } + } + + } catch (BpmnError e) { + logger.debug(" Rethrowing MSOWorkflowException") + throw e + } catch (Exception e) { + String msg = 'Caught exception in ' + method + ": " + e + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", + ErrorCode.UnknownError.getValue()); + logger.debug(msg) exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg, ONAPComponents.SO) - } - } + } + } - public String getVolumeGroupIdFromRollbackRequest(Node root) { - return root.'volumeGroupRollback'.'volumeGroupId'.text() - } + public String getVolumeGroupIdFromRollbackRequest(Node root) { + return root.'volumeGroupRollback'.'volumeGroupId'.text() + } - public String getMessageIdForVolumeGroupRollback(Node root) { - return root.'volumeGroupRollback'.'messageId'.text() - } + public String getMessageIdForVolumeGroupRollback(Node root) { + return root.'volumeGroupRollback'.'messageId'.text() + } - /** - * 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() + - ')' - logger.trace('Entered ' + method) + /** + * 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() + + ')' + logger.trace('Entered ' + method) - String prefix = execution.getVariable('prefix') + String prefix = execution.getVariable('prefix') - try { - String vnfAdapterMethod = execution.getVariable(prefix + 'vnfAdapterMethod') - String vnfAdapterUrl = execution.getVariable(prefix + 'vnfAdapterUrl') - String vnfAdapterRequest = execution.getVariable(prefix + 'vnfAdapterRequest') + try { + String vnfAdapterMethod = execution.getVariable(prefix + 'vnfAdapterMethod') + String vnfAdapterUrl = execution.getVariable(prefix + 'vnfAdapterUrl') + String vnfAdapterRequest = execution.getVariable(prefix + 'vnfAdapterRequest') - URL url = new URL(vnfAdapterUrl); + URL url = new URL(vnfAdapterUrl); HttpClient httpClient = new HttpClientFactory().newXmlClient(url, ONAPComponents.VNF_ADAPTER) - httpClient.addAdditionalHeader("Authorization", execution.getVariable(prefix + "basicAuthHeaderValue")) - - httpClient.addAdditionalHeader("X-ONAP-RequestID", execution.getVariable("mso-request-id")) - httpClient.addAdditionalHeader("X-ONAP-InvocationID", UUID.randomUUID().toString()) - httpClient.addAdditionalHeader("X-ONAP-PartnerName", "SO-VNFAdapter") - Response response; - - if ("GET".equals(vnfAdapterMethod)) { - response = httpClient.get() - } else if ("PUT".equals(vnfAdapterMethod)) { - response = httpClient.put(vnfAdapterRequest) - } else if ("POST".equals(vnfAdapterMethod)) { - response = httpClient.post(vnfAdapterRequest) - } else if ("DELETE".equals(vnfAdapterMethod)) { - response = httpClient.delete(vnfAdapterRequest) - } else { - String msg = 'Unsupported HTTP method "' + vnfAdapterMethod + '" in ' + method + ": " + e - logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", - ErrorCode.UnknownError.getValue()); + httpClient.addAdditionalHeader("Authorization", execution.getVariable(prefix + "basicAuthHeaderValue")) + + httpClient.addAdditionalHeader("X-ONAP-RequestID", execution.getVariable("mso-request-id")) + httpClient.addAdditionalHeader("X-ONAP-InvocationID", UUID.randomUUID().toString()) + httpClient.addAdditionalHeader("X-ONAP-PartnerName", "SO-VNFAdapter") + Response response; + + if ("GET".equals(vnfAdapterMethod)) { + response = httpClient.get() + } else if ("PUT".equals(vnfAdapterMethod)) { + response = httpClient.put(vnfAdapterRequest) + } else if ("POST".equals(vnfAdapterMethod)) { + response = httpClient.post(vnfAdapterRequest) + } else if ("DELETE".equals(vnfAdapterMethod)) { + response = httpClient.delete(vnfAdapterRequest) + } else { + String msg = 'Unsupported HTTP method "' + vnfAdapterMethod + '" in ' + method + ": " + e + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", + ErrorCode.UnknownError.getValue()); exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg, ONAPComponents.SO) - } - - execution.setVariable(prefix + "vnfAdapterStatusCode", response.getStatus()) - if(response.hasEntity()){ - execution.setVariable(prefix + "vnfAdapterResponse", response.readEntity(String.class)) - } - } catch (BpmnError e) { - throw e - } catch (Exception e) { - String msg = 'Caught exception in ' + method + ": " + e - logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", - ErrorCode.UnknownError.getValue()); + } + + execution.setVariable(prefix + "vnfAdapterStatusCode", response.getStatus()) + if(response.hasEntity()){ + execution.setVariable(prefix + "vnfAdapterResponse", response.readEntity(String.class)) + } + } catch (BpmnError e) { + throw e + } catch (Exception e) { + String msg = 'Caught exception in ' + method + ": " + e + logger.error(LoggingAnchor.FOUR, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", + ErrorCode.UnknownError.getValue()); exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg, ONAPComponents.SO) - } - } - - public void processCallback(DelegateExecution execution){ - def method = getClass().getSimpleName() + '.processCallback(' + - 'execution=' + execution.getId() + - ')' - logger.trace('Entered ' + method) - - String callback = execution.getVariable('VNFAResponse_MESSAGE') - - try { - logger.debug(getProcessKey(execution) + ": received callback:\n" + callback) - - // The XML callback is available to the calling flow in any case, - // even if a WorkflowException is generated. - execution.setVariable(getProcessKey(execution) + 'Response', callback) - // TODO: Should deprecate use of processKey+Response variable for the response. Will use "WorkflowResponse" instead. - execution.setVariable("WorkflowResponse", callback) - - callback = utils.removeXmlPreamble(callback) - - Node root = new XmlParser().parseText(callback) - if (root.name().endsWith('Exception')) { - vnfAdapterWorkflowException(execution, callback) - } - } catch (Exception e) { - logger.debug("Error encountered within VnfAdapterRest ProcessCallback method: {}", e.getMessage(), e) + } + } + + public void processCallback(DelegateExecution execution){ + def method = getClass().getSimpleName() + '.processCallback(' + + 'execution=' + execution.getId() + + ')' + logger.trace('Entered ' + method) + + String callback = execution.getVariable('VNFAResponse_MESSAGE') + + try { + logger.debug(getProcessKey(execution) + ": received callback:\n" + callback) + + // The XML callback is available to the calling flow in any case, + // even if a WorkflowException is generated. + execution.setVariable(getProcessKey(execution) + 'Response', callback) + // TODO: Should deprecate use of processKey+Response variable for the response. Will use "WorkflowResponse" instead. + execution.setVariable("WorkflowResponse", callback) + + callback = utils.removeXmlPreamble(callback) + + Node root = new XmlParser().parseText(callback) + if (root.name().endsWith('Exception')) { + vnfAdapterWorkflowException(execution, callback) + } + } catch (Exception e) { + logger.debug("Error encountered within VnfAdapterRest ProcessCallback method: {}", e.getMessage(), e) exceptionUtil.buildAndThrowWorkflowException(execution, 7020, "Error encountered within VnfAdapterRest ProcessCallback method", ONAPComponents.SO) - } - } - - /** - * Tries to parse the response as XML to extract the information to create - * a WorkflowException. If the response cannot be parsed, a more generic - * WorkflowException is created. - */ - public void vnfAdapterWorkflowException(DelegateExecution execution, Object response) { - try { - Node root = new XmlParser().parseText(response) - String category = getChildText(root, "category") - category = category == null || category.isEmpty() ? "" : " category='" + category + "'" - String message = getChildText(root, "message") - message = message == null || message.isEmpty() ? "" : " message='" + message + "'" - String rolledBack = getChildText(root, "rolledBack") - rolledBack = rolledBack == null || rolledBack.isEmpty() ? "" : " rolledBack='" + rolledBack + "'" - exceptionUtil.buildWorkflowException(execution, 7020, "Received " + root.name() + + } + } + + /** + * Tries to parse the response as XML to extract the information to create + * a WorkflowException. If the response cannot be parsed, a more generic + * WorkflowException is created. + */ + public void vnfAdapterWorkflowException(DelegateExecution execution, Object response) { + try { + Node root = new XmlParser().parseText(response) + String category = getChildText(root, "category") + category = category == null || category.isEmpty() ? "" : " category='" + category + "'" + String message = getChildText(root, "message") + message = message == null || message.isEmpty() ? "" : " message='" + message + "'" + String rolledBack = getChildText(root, "rolledBack") + rolledBack = rolledBack == null || rolledBack.isEmpty() ? "" : " rolledBack='" + rolledBack + "'" + exceptionUtil.buildWorkflowException(execution, 7020, "Received " + root.name() + " from VnfAdapter:" + category + message + rolledBack, Components.OPENSTACK); - } catch (Exception e) { - response = response == null || String.valueOf(response).isEmpty() ? "NONE" : response + } catch (Exception e) { + response = response == null || String.valueOf(response).isEmpty() ? "NONE" : response exceptionUtil.buildWorkflowException(execution, 7020, "Received error from VnfAdapter: " + response, Components.OPENSTACK) - } - } - - /** - * Gets the named child of the specified node. - * @param node the node - * @param name the child name - * @return the child node, or null if no such child exists - */ - private Node getChild(Node node, String name) { - for (Node child : node.children()) { - if (child.name() == name) { - return child - } - } - return null - } - - /** - * Gets the text of the named child of the specified node. - * @param node the node - * @param name the child name - * @return the child node text, or null if no such child exists - */ - private String getChildText(Node node, String name) { - Node child = getChild(node, name) - return child == null ? null : child.text() - } - - public Logger getLogger() { - return logger; - } + } + } + + /** + * Gets the named child of the specified node. + * @param node the node + * @param name the child name + * @return the child node, or null if no such child exists + */ + private Node getChild(Node node, String name) { + for (Node child : node.children()) { + if (child.name() == name) { + return child + } + } + return null + } + + /** + * Gets the text of the named child of the specified node. + * @param node the node + * @param name the child name + * @return the child node text, or null if no such child exists + */ + private String getChildText(Node node, String name) { + Node child = getChild(node, name) + return child == null ? null : child.text() + } + + public Logger getLogger() { + return logger; + } } diff --git a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/exception/ExceptionBuilder.java b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/exception/ExceptionBuilder.java index 2e9d4b0117..30fd2c8770 100644 --- a/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/exception/ExceptionBuilder.java +++ b/bpmn/MSOCommonBPMN/src/main/java/org/onap/so/client/exception/ExceptionBuilder.java @@ -45,6 +45,7 @@ import org.onap.so.logger.LoggingAnchor; import org.onap.so.logger.MessageEnum; import org.onap.so.objects.audit.AAIObjectAudit; import org.onap.so.objects.audit.AAIObjectAuditList; +import org.onap.so.utils.Components; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Component; @@ -207,26 +208,26 @@ public class ExceptionBuilder { } public void buildAndThrowWorkflowException(DelegateExecution execution, int errorCode, String errorMessage) { + + buildWorkflowException(execution, errorCode, errorMessage); + logger.info("Throwing MSOWorkflowException"); + throw new BpmnError("MSOWorkflowException"); + } + + public void buildWorkflowException(DelegateExecution execution, int errorCode, String errorMessage) { String processKey = getProcessKey(execution); - logger.info("Building a WorkflowException for Subflow"); + logger.info("Building a WorkflowException"); WorkflowException exception = new WorkflowException(processKey, errorCode, errorMessage); execution.setVariable("WorkflowException", exception); execution.setVariable("WorkflowExceptionErrorMessage", errorMessage); logger.info("Outgoing WorkflowException is {}", exception); - logger.info("Throwing MSOWorkflowException"); - throw new BpmnError("MSOWorkflowException"); } public void buildAndThrowWorkflowException(DelegateExecution execution, int errorCode, String errorMessage, ONAPComponentsList extSystemErrorSource) { - String processKey = getProcessKey(execution); - logger.info("Building a WorkflowException for Subflow"); - WorkflowException exception = new WorkflowException(processKey, errorCode, errorMessage, extSystemErrorSource); - execution.setVariable("WorkflowException", exception); - execution.setVariable("WorkflowExceptionErrorMessage", errorMessage); - logger.info("Outgoing WorkflowException is {}", exception); + buildWorkflowException(execution, errorCode, errorMessage, extSystemErrorSource); logger.info("Throwing MSOWorkflowException"); throw new BpmnError("MSOWorkflowException"); } @@ -313,7 +314,7 @@ public class ExceptionBuilder { execution.setVariable("WorkflowException", exception); execution.setVariable("WorkflowExceptionErrorMessage", errorMessage.toString()); logger.info("Outgoing WorkflowException is {}", exception); - logger.info("Throwing MSOWorkflowException"); + logger.info("Throwing AAIInventoryFailure"); throw new BpmnError("AAIInventoryFailure"); } @@ -323,9 +324,42 @@ public class ExceptionBuilder { execution.setVariable("WorkflowException", exception); execution.setVariable("WorkflowExceptionErrorMessage", errorMessage); logger.info("Outgoing WorkflowException is {}", exception); - logger.info("Throwing MSOWorkflowException"); + logger.info("Throwing AAIInventoryFailure"); throw new BpmnError("AAIInventoryFailure"); } } + public void processVnfAdapterException(DelegateExecution execution) { + StringBuilder workflowExceptionMessage = new StringBuilder(); + logger.debug("Processing Vnf Adapter Exception"); + try { + String errorMessage = (String) execution.getVariable("openstackAdapterErrorMessage"); + boolean openstackRollbackPollSuccess = (boolean) execution.getVariable("OpenstackPollSuccess"); + boolean rollbackPerformed = (boolean) execution.getVariable("rollbackPerformed"); + boolean openstackRollbackSuccess = (boolean) execution.getVariable("OpenstackRollbackSuccess"); + boolean pollRollbackStatus = (boolean) execution.getVariable("PollRollbackStatus"); + + workflowExceptionMessage.append("Exception occured during vnf adapter: " + errorMessage + "."); + + boolean rollbackCompleted = false; + if (rollbackPerformed) { + if (openstackRollbackSuccess && !pollRollbackStatus) { + rollbackCompleted = true; + } else if (openstackRollbackSuccess && pollRollbackStatus) { + if (openstackRollbackPollSuccess) { + rollbackCompleted = true; + } + } + workflowExceptionMessage + .append(" The resource was rollbacked in openstack: " + rollbackCompleted + "."); + } + } catch (Exception e) { + logger.debug("Error while Processing Vnf Adapter Exception", e); + } + buildWorkflowException(execution, 500, workflowExceptionMessage.toString(), Components.OPENSTACK); + throw new BpmnError("MSOWorkflowException"); + + + } + } diff --git a/bpmn/MSOCommonBPMN/src/main/resources/subprocess/VnfAdapterTask.bpmn b/bpmn/MSOCommonBPMN/src/main/resources/subprocess/VnfAdapterTask.bpmn new file mode 100644 index 0000000000..69b68e534e --- /dev/null +++ b/bpmn/MSOCommonBPMN/src/main/resources/subprocess/VnfAdapterTask.bpmn @@ -0,0 +1,336 @@ + + + + + SequenceFlow_13uy51h + + + SequenceFlow_9 + + + + SequenceFlow_9 + SequenceFlow_1ff2y8j + + + + SequenceFlow_1p39f4r + SequenceFlow_0ecut35 + + + + SequenceFlow_0ecut35 + SequenceFlow_13uy51h + SequenceFlow_0o8wnkx + + + + + + + + + SequenceFlow_1ff2y8j + SequenceFlow_1p39f4r + SequenceFlow_007m32h + + + + + + + + + + SequenceFlow_02rhau9 + + + + SequenceFlow_0y1by9x + SequenceFlow_006myq9 + + + + SequenceFlow_006myq9 + SequenceFlow_1ubla93 + SequenceFlow_1piwh1c + + + + + SequenceFlow_1ubla93 + SequenceFlow_1nku4uk + + + SequenceFlow_1piwh1c + SequenceFlow_1nku4uk + SequenceFlow_1yx80cq + + + SequenceFlow_1yx80cq + SequenceFlow_1az3a2q + SequenceFlow_0bnzfqb + + + + + + + + + + SequenceFlow_0bnzfqb + + + + SequenceFlow_02rhau9 + SequenceFlow_0y1by9x + SequenceFlow_1az3a2q + + + + + + + + + + + + SequenceFlow_007m32h + + + + SequenceFlow_0o8wnkx + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + + diff --git a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/infrastructure/MSOInfrastructureApplication.java b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/infrastructure/MSOInfrastructureApplication.java index 506088eb15..477dce1072 100644 --- a/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/infrastructure/MSOInfrastructureApplication.java +++ b/bpmn/mso-infrastructure-bpmn/src/main/java/org/onap/so/bpmn/infrastructure/MSOInfrastructureApplication.java @@ -9,9 +9,9 @@ * 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. diff --git a/bpmn/so-bpmn-building-blocks/src/main/resources/subprocess/BuildingBlock/VnfAdapter.bpmn b/bpmn/so-bpmn-building-blocks/src/main/resources/subprocess/BuildingBlock/VnfAdapter.bpmn index 30a95eb81f..e139e94660 100644 --- a/bpmn/so-bpmn-building-blocks/src/main/resources/subprocess/BuildingBlock/VnfAdapter.bpmn +++ b/bpmn/so-bpmn-building-blocks/src/main/resources/subprocess/BuildingBlock/VnfAdapter.bpmn @@ -27,92 +27,91 @@ SequenceFlow_1ivhukd - + - - - + + SequenceFlow_0qaaf5k SequenceFlow_0j1zvis - - + + - + - + - - + + - + - + - + - + - - - - + + + + - + - + - + - - + + - - + + - - + + - - + + diff --git a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VnfAdapterTest.java b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VnfAdapterTest.java index 8ad4e0f07f..4dbf4d46ff 100644 --- a/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VnfAdapterTest.java +++ b/bpmn/so-bpmn-building-blocks/src/test/java/org/onap/so/bpmn/infrastructure/bpmn/subprocess/VnfAdapterTest.java @@ -7,9 +7,9 @@ * 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. @@ -32,11 +32,11 @@ import org.onap.so.bpmn.common.BuildingBlockExecution; public class VnfAdapterTest extends BaseBPMNTest { @Test public void vnfAdapterCreatedTest() { - mockSubprocess("vnfAdapterRestV1", "Mocked vnfAdapterRestV1", "GenericStub"); + mockSubprocess("vnfAdapterTask", "Mocked vnfAdapterTask", "GenericStub"); ProcessInstance pi = runtimeService.startProcessInstanceByKey("VnfAdapter", variables); assertThat(pi).isNotNull(); - assertThat(pi).isStarted().hasPassedInOrder("VnfAdapter_Start", "PreProcessRequest", "Call_vnfAdapterRestV1", + assertThat(pi).isStarted().hasPassedInOrder("VnfAdapter_Start", "PreProcessRequest", "Call_vnfAdapterTask", "PostProcessResponse", "VnfAdapter_End"); assertThat(pi).isEnded(); } diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModuleRollback.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModuleRollback.groovy index a77f6f0628..a505aa1a34 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModuleRollback.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoCreateVfModuleRollback.groovy @@ -50,164 +50,164 @@ import javax.ws.rs.NotFoundException public class DoCreateVfModuleRollback extends AbstractServiceTaskProcessor{ private static final Logger logger = LoggerFactory.getLogger( 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") - logger.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 cloudOwner = rollbackData.get("VFMODULE", "cloudowner") - execution.setVariable("DCVFMR_cloudOwner", cloudOwner) - 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) - logger.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 = """ + 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") + logger.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 cloudOwner = rollbackData.get("VFMODULE", "cloudowner") + execution.setVariable("DCVFMR_cloudOwner", cloudOwner) + 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) + logger.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 = """ ${MsoUtils.xmlEscape(vnfId)} ${MsoUtils.xmlEscape(vfModuleId)} pending-delete """ as String - logger.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() - logger.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 = """ @@ -245,76 +245,76 @@ public class DoCreateVfModuleRollback extends AbstractServiceTaskProcessor{ """ - logger.debug("sdncAdapterWorkflowRequest: " + request) - execution.setVariable("sdncAdapterWorkflowRequest", request) - } - - public void preProcessSDNCDeactivateRequest(DelegateExecution execution){ - - execution.setVariable("prefix", Prefix) - logger.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) - logger.debug("Outgoing DeactivateSDNCRequest is: \n" + deactivateSDNCRequest) - - }catch(Exception e){ - logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), - "Exception Occured Processing preProcessSDNCDeactivateRequest.", "BPMN", - ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); - exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during preProcessSDNCDeactivateRequest Method:\n" + e.getMessage()) - } - logger.trace("COMPLETED preProcessSDNCDeactivateRequest") - } - - public void preProcessSDNCUnassignRequest(DelegateExecution execution) { - def method = getClass().getSimpleName() + '.preProcessSDNCUnassignRequest(' + - 'execution=' + execution.getId() + - ')' - def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') - logger.trace('Entered ' + method) - execution.setVariable("prefix", Prefix) - logger.trace("STARTED preProcessSDNCUnassignRequest Process") - try{ - String serviceInstanceId = execution.getVariable("DCVFMR_serviceInstanceId") - - String unassignSDNCRequest = buildSDNCRequest(execution, serviceInstanceId, "unassign") - - execution.setVariable("DCVFMR_unassignSDNCRequest", unassignSDNCRequest) - logger.debug("Outgoing UnassignSDNCRequest is: \n" + unassignSDNCRequest) - - }catch(Exception e){ - logger.debug("Exception Occured Processing preProcessSDNCUnassignRequest. Exception is:\n" + e) - exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during preProcessSDNCUnassignRequest Method:\n" + e.getMessage()) - } - logger.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 = - """ @@ -351,32 +351,32 @@ public class DoCreateVfModuleRollback extends AbstractServiceTaskProcessor{ """ - logger.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 cloudOwner = execution.getVariable("DCVFMR_cloudOwner") - 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 = """ + logger.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 cloudOwner = execution.getVariable("DCVFMR_cloudOwner") + 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 = """ ${MsoUtils.xmlEscape(aicCloudRegion)} ${MsoUtils.xmlEscape(cloudOwner)} @@ -394,117 +394,116 @@ public class DoCreateVfModuleRollback extends AbstractServiceTaskProcessor{ """ as String - logger.debug("vnfAdapterRestV1Request: " + request) - execution.setVariable("vnfAdapterRestV1Request", request) - } + execution.setVariable("vnfAdapterTaskRequest", request) + } - // parse the incoming DELETE_VF_MODULE request - // and formulate the outgoing UpdateAAIVfModuleRequest request - public void prepUpdateAAIVfModule(DelegateExecution execution) { + // 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 = """ + String vnfId = execution.getVariable("DCVFMR_vnfId") + String vfModuleId = execution.getVariable("DCVFMR_vfModuleId") + // formulate the request for UpdateAAIVfModule + String request = """ ${MsoUtils.xmlEscape(vnfId)} ${MsoUtils.xmlEscape(vfModuleId)} DELETE deleted """ as String - logger.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 = """ + logger.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 = """ ${MsoUtils.xmlEscape(vnfId)} ${MsoUtils.xmlEscape(vfModuleId)} Assigned """ as String - logger.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 = """ + logger.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 = """ ${MsoUtils.xmlEscape(vnfId)} ${MsoUtils.xmlEscape(vfModuleId)} """ as String - logger.debug("DeleteAAIVfModuleRequest :" + request) - execution.setVariable("DeleteAAIVfModuleRequest", request) - } + logger.debug("DeleteAAIVfModuleRequest :" + request) + execution.setVariable("DeleteAAIVfModuleRequest", request) + } - // generates a WorkflowException if - // - - public void handleDoDeleteVfModuleFailure(DelegateExecution execution) { + // generates a WorkflowException if + // - + public void handleDoDeleteVfModuleFailure(DelegateExecution execution) { - logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), - "AAI error occurred deleting the Generic Vnf" + execution.getVariable("DoDVfMod_deleteGenericVnfResponse"), - "BPMN", ErrorCode.UnknownError.getValue()); - String processKey = getProcessKey(execution); - exceptionUtil.buildWorkflowException(execution, 5000, "Failure in DoDeleteVfModule") + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + "AAI error occurred deleting the Generic Vnf" + execution.getVariable("DoDVfMod_deleteGenericVnfResponse"), + "BPMN", ErrorCode.UnknownError.getValue()); + String processKey = getProcessKey(execution); + exceptionUtil.buildWorkflowException(execution, 5000, "Failure in DoDeleteVfModule") - } + } - public void sdncValidateResponse(DelegateExecution execution, String response){ + public void sdncValidateResponse(DelegateExecution execution, String response){ - execution.setVariable("prefix",Prefix) + execution.setVariable("prefix",Prefix) - WorkflowException workflowException = execution.getVariable("WorkflowException") - boolean successIndicator = execution.getVariable("SDNCA_SuccessIndicator") + WorkflowException workflowException = execution.getVariable("WorkflowException") + boolean successIndicator = execution.getVariable("SDNCA_SuccessIndicator") - SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils() - sdncAdapterUtils.validateSDNCResponse(execution, response, workflowException, successIndicator) + SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils() + sdncAdapterUtils.validateSDNCResponse(execution, response, workflowException, successIndicator) - if(execution.getVariable(Prefix + 'sdncResponseSuccess') == true){ - logger.debug("Successfully Validated SDNC Response") - }else{ - throw new BpmnError("MSOWorkflowException") - } - } + if(execution.getVariable(Prefix + 'sdncResponseSuccess') == true){ + logger.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') - logger.trace('Entered ' + method) - execution.setVariable("prefix", Prefix) - logger.trace("STARTED deleteNetworkPoliciesFromAAI") + public void deleteNetworkPoliciesFromAAI(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.deleteNetworkPoliciesFromAAI(' + + 'execution=' + execution.getId() + + ')' + def isDebugLogEnabled = execution.getVariable('isDebugLogEnabled') + logger.trace('Entered ' + method) + execution.setVariable("prefix", Prefix) + logger.trace("STARTED deleteNetworkPoliciesFromAAI") - try { - // get variables - List fqdnList = execution.getVariable(Prefix + "createdNetworkPolicyFqdnList") - if (fqdnList == null) { - logger.debug("No network policies to delete") - return - } - int fqdnCount = fqdnList.size() + try { + // get variables + List fqdnList = execution.getVariable(Prefix + "createdNetworkPolicyFqdnList") + if (fqdnList == null) { + logger.debug("No network policies to delete") + return + } + int fqdnCount = fqdnList.size() - execution.setVariable(Prefix + "networkPolicyFqdnCount", fqdnCount) - logger.debug("networkPolicyFqdnCount - " + fqdnCount) + execution.setVariable(Prefix + "networkPolicyFqdnCount", fqdnCount) + logger.debug("networkPolicyFqdnCount - " + fqdnCount) - AaiUtil aaiUriUtil = new AaiUtil(this) + AaiUtil aaiUriUtil = new AaiUtil(this) - if (fqdnCount > 0) { - // AII loop call over contrail network policy fqdn list - for (i in 0..fqdnCount-1) { + 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] + int counting = i+1 + String fqdn = fqdnList[i] try { // Query AAI for this network policy FQDN @@ -517,10 +516,10 @@ public class DoCreateVfModuleRollback extends AbstractServiceTaskProcessor{ NetworkPolicy networkPolicy = networkPolicies.get().getNetworkPolicy().get(0) try{ - AAIResourceUri delUri = AAIUriFactory.createResourceUri(AAIObjectType.NETWORK_POLICY, networkPolicy.getNetworkPolicyId()) - getAAIClient().delete(delUri) - execution.setVariable(Prefix + "aaiDeleteNetworkPolicyReturnCode", 200) - logger.debug("AAI delete network policy Response Code, NetworkPolicy #" + counting + " : " + 200) + AAIResourceUri delUri = AAIUriFactory.createResourceUri(AAIObjectType.NETWORK_POLICY, networkPolicy.getNetworkPolicyId()) + getAAIClient().delete(delUri) + execution.setVariable(Prefix + "aaiDeleteNetworkPolicyReturnCode", 200) + logger.debug("AAI delete network policy Response Code, NetworkPolicy #" + counting + " : " + 200) logger.debug("The return code from deleting network policy is: " + 200) // This network policy was deleted from AAI successfully logger.debug(" DelAAINetworkPolicy Success REST Response, , NetworkPolicy #" + counting + " : ") @@ -548,113 +547,113 @@ public class DoCreateVfModuleRollback extends AbstractServiceTaskProcessor{ logger.debug(dataErrorMessage) exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) } - } // end loop + } // end loop - } else { - logger.debug("No contrail network policies to query/create") + } else { + logger.debug("No contrail network policies to query/create") - } + } - } catch (BpmnError e) { - throw e; + } catch (BpmnError e) { + throw e; - } catch (Exception ex) { - String exceptionMessage = "Bpmn error encountered in DoCreateVfModuleRollback flow. deleteNetworkPoliciesFromAAI() - " + ex.getMessage() - logger.debug(exceptionMessage) - exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) - } + } catch (Exception ex) { + String exceptionMessage = "Bpmn error encountered in DoCreateVfModuleRollback flow. deleteNetworkPoliciesFromAAI() - " + ex.getMessage() + logger.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') - logger.trace('Entered ' + method) + /** + * 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') + logger.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 = '' + 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 = '' + 'DELETE' + '' - } + if (oamManagementV4Address != null) { + ipv4OamAddressElement = '' + 'DELETE' + '' + } - if (oamManagementV6Address != null) { - managementV6AddressElement = '' + 'DELETE' + '' - } + if (oamManagementV6Address != null) { + managementV6AddressElement = '' + 'DELETE' + '' + } - String updateAAIGenericVnfRequest = """ + String updateAAIGenericVnfRequest = """ ${MsoUtils.xmlEscape(vnfId)} ${ipv4OamAddressElement} ${managementV6AddressElement} """ - updateAAIGenericVnfRequest = utils.formatXml(updateAAIGenericVnfRequest) - execution.setVariable(Prefix + 'updateAAIGenericVnfRequest', updateAAIGenericVnfRequest) - logger.debug('Request for UpdateAAIGenericVnf:\n' + updateAAIGenericVnfRequest) - - - logger.trace('Exited ' + method) - } catch (BpmnError e) { - throw e; - } catch (Exception e) { - logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), - 'Caught exception in ' + method, "BPMN", - ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); - exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in preProcessUpdateAAIGenericVnf((): ' + e.getMessage()) - } - } - - public void setSuccessfulRollbackStatus (DelegateExecution execution){ - - execution.setVariable("prefix", Prefix) - logger.trace("STARTED setSuccessfulRollbackStatus") - - try{ - // Set rolledBack to true, rollbackError to null - execution.setVariable("rolledBack", true) - execution.setVariable("rollbackError", null) - - }catch(Exception e){ - logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), - "Exception Occured Processing setSuccessfulRollbackStatus.", "BPMN", - ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); - exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during setSuccessfulRollbackStatus Method:\n" + e.getMessage()) - } - logger.trace("COMPLETED setSuccessfulRollbackStatus") - } - - public void setFailedRollbackStatus (DelegateExecution execution){ - - execution.setVariable("prefix", Prefix) - logger.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){ - logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), - "Exception Occured Processing setFailedRollbackStatus.", "BPMN", - ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); - exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during setFailedRollbackStatus Method:\n" + e.getMessage()) - } - logger.trace("COMPLETED setFailedRollbackStatus") - } + updateAAIGenericVnfRequest = utils.formatXml(updateAAIGenericVnfRequest) + execution.setVariable(Prefix + 'updateAAIGenericVnfRequest', updateAAIGenericVnfRequest) + logger.debug('Request for UpdateAAIGenericVnf:\n' + updateAAIGenericVnfRequest) + + + logger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + 'Caught exception in ' + method, "BPMN", + ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in preProcessUpdateAAIGenericVnf((): ' + e.getMessage()) + } + } + + public void setSuccessfulRollbackStatus (DelegateExecution execution){ + + execution.setVariable("prefix", Prefix) + logger.trace("STARTED setSuccessfulRollbackStatus") + + try{ + // Set rolledBack to true, rollbackError to null + execution.setVariable("rolledBack", true) + execution.setVariable("rollbackError", null) + + }catch(Exception e){ + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + "Exception Occured Processing setSuccessfulRollbackStatus.", "BPMN", + ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during setSuccessfulRollbackStatus Method:\n" + e.getMessage()) + } + logger.trace("COMPLETED setSuccessfulRollbackStatus") + } + + public void setFailedRollbackStatus (DelegateExecution execution){ + + execution.setVariable("prefix", Prefix) + logger.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){ + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + "Exception Occured Processing setFailedRollbackStatus.", "BPMN", + ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during setFailedRollbackStatus Method:\n" + e.getMessage()) + } + logger.trace("COMPLETED setFailedRollbackStatus") + } } diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVfModule.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVfModule.groovy index 002e283790..e776eaf422 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVfModule.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVfModule.groovy @@ -55,187 +55,185 @@ 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 -* -*/ + * 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 Logger logger = LoggerFactory.getLogger( 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) - String cloudOwner = jsonUtil.getJsonValue(cloudConfiguration, "cloudOwner") - execution.setVariable("cloudOwner", cloudOwner) - // 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 { - - logger.debug("DoDeleteVfModule Request: " + xml) - - logger.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) - String cloudOwner = utils.getNodeText(xml, "cloud-owner") - execution.setVariable("cloudOwner", cloudOwner) - } - - // formulate the request for PrepareUpdateAAIVfModule - String request = """ + 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) + String cloudOwner = jsonUtil.getJsonValue(cloudConfiguration, "cloudOwner") + execution.setVariable("cloudOwner", cloudOwner) + // 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 { + + logger.debug("DoDeleteVfModule Request: " + xml) + + logger.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) + String cloudOwner = utils.getNodeText(xml, "cloud-owner") + execution.setVariable("cloudOwner", cloudOwner) + } + + // formulate the request for PrepareUpdateAAIVfModule + String request = """ ${MsoUtils.xmlEscape(vnfId)} ${MsoUtils.xmlEscape(vfModuleId)} pending-delete """ as String - logger.debug("PrepareUpdateAAIVfModuleRequest :" + request) - logger.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) { - org.onap.aai.domain.yang.VfModule vfModuleFromAAI = execution.getVariable("vfModuleFromAAI") - vfModuleName = vfModuleFromAAI.getVfModuleName() - } - } - String vfModuleModelName = execution.getVariable("vfModuleModelName") - String cloudSiteId = execution.getVariable("cloudSiteId") - boolean retainResources = execution.getVariable("retainResources") - String requestSubActionString = "" - if (retainResources) { - requestSubActionString = "RetainResource" - } - String request = """ @@ -274,33 +272,33 @@ public class DoDeleteVfModule extends AbstractServiceTaskProcessor{ """ - logger.debug("sdncAdapterWorkflowRequest: " + request) - logger.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 cloudOwner = execution.getVariable("cloudOwner") - 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 = """ + logger.debug("sdncAdapterWorkflowRequest: " + request) + logger.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 cloudOwner = execution.getVariable("cloudOwner") + 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 = """ ${MsoUtils.xmlEscape(aicCloudRegion)} ${MsoUtils.xmlEscape(cloudOwner)} @@ -318,303 +316,301 @@ public class DoDeleteVfModule extends AbstractServiceTaskProcessor{ """ as String - logger.debug("vnfAdapterRestV1Request: " + request) - logger.debug("deleteVfModuleRequest: " + request) - execution.setVariable("vnfAdapterRestV1Request", request) - } + logger.debug("deleteVfModuleRequest: " + request) + execution.setVariable("vnfAdapterTaskRequest", request) + } - // parse the incoming DELETE_VF_MODULE request - // and formulate the outgoing UpdateAAIVfModuleRequest request - public void prepUpdateAAIVfModule(DelegateExecution execution) { + // 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 = """ + def vnfId = execution.getVariable("vnfId") + def vfModuleId = execution.getVariable("vfModuleId") + // formulate the request for UpdateAAIVfModule + String request = """ ${MsoUtils.xmlEscape(vnfId)} ${MsoUtils.xmlEscape(vfModuleId)} DELETE deleted """ as String - logger.debug("UpdateAAIVfModuleRequest :" + request) - logger.debug("UpdateAAIVfModuleRequest: " + request) - execution.setVariable("UpdateAAIVfModuleRequest", request) - } + logger.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) { + // 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 = """ + def vnfId = execution.getVariable("vnfId") + def vfModuleId = execution.getVariable("vfModuleId") + // formulate the request for UpdateAAIVfModule + String request = """ ${MsoUtils.xmlEscape(vnfId)} ${MsoUtils.xmlEscape(vfModuleId)} """ as String - logger.debug("DeleteAAIVfModuleRequest :" + request) - logger.debug("DeleteAAIVfModuleRequest: " + request) - execution.setVariable("DeleteAAIVfModuleRequest", request) - } - - // generates a WorkflowException if - // - - public void handleDoDeleteVfModuleFailure(DelegateExecution execution) { - logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), - "AAI error occurred deleting the Generic Vnf: " + execution.getVariable("DoDVfMod_deleteGenericVnfResponse"), - "BPMN", ErrorCode.UnknownError.getValue(), "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() - sdncAdapterUtils.validateSDNCResponse(execution, response, workflowException, successIndicator) - - if(execution.getVariable(Prefix + 'sdncResponseSuccess') == true){ - logger.debug("Successfully Validated SDNC Response") - }else{ - throw new BpmnError("MSOWorkflowException") - } - } - - public void postProcessVNFAdapterRequest(DelegateExecution execution) { - def method = getClass().getSimpleName() + '.postProcessVNFAdapterRequest(' + - 'execution=' + execution.getId() + - ')' - - logger.trace('Entered ' + method) - execution.setVariable("prefix",Prefix) - try{ - logger.trace("STARTED postProcessVNFAdapterRequest Process") - - String vnfResponse = execution.getVariable("DoDVfMod_doDeleteVfModuleResponse") - logger.debug("VNF Adapter Response is: " + vnfResponse) - logger.debug("deleteVnfAResponse is: \n" + vnfResponse) - - if(vnfResponse != null){ - - if(vnfResponse.contains("deleteVfModuleResponse")){ - logger.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() - logger.debug("Obtained contrailNetworkPolicyFqdn: " + contrailNetworkPolicyFqdn) - contrailNetworkPolicyFqdnList.add(contrailNetworkPolicyFqdn) - } - else if (key.equals("oam_management_v4_address")) { - String oamManagementV4Address = element.getElementsByTagNameNS("*", "value").item(0).getTextContent() - logger.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() - logger.debug("Obtained oamManagementV6Address: " + oamManagementV6Address) - execution.setVariable(Prefix + "oamManagementV6Address", oamManagementV6Address) - } - - } - } - if (!contrailNetworkPolicyFqdnList.isEmpty()) { - logger.debug("Setting the fqdn list") - execution.setVariable("DoDVfMod_contrailNetworkPolicyFqdnList", contrailNetworkPolicyFqdnList) - } - } - }else{ - logger.debug("Received a BAD Response from VNF Adapter for DELETE_VF_MODULE Call.") - exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "VNF Adapter Error") - } - }else{ - logger.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){ - logger.debug("Internal Error Occured in PostProcess Method") - exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Internal Error Occured in PostProcess Method") - } - logger.trace("COMPLETED postProcessVnfAdapterResponse Process") - } - - public void deleteNetworkPoliciesFromAAI(DelegateExecution execution) { - def method = getClass().getSimpleName() + '.deleteNetworkPoliciesFromAAI(' + - 'execution=' + execution.getId() + - ')' - - logger.trace('Entered ' + method) - execution.setVariable("prefix", Prefix) - logger.trace("STARTED deleteNetworkPoliciesFromAAI ") - - try { - // get variables - List fqdnList = execution.getVariable("DoDVfMod_contrailNetworkPolicyFqdnList") - if (fqdnList == null) { - logger.debug("No network policies to delete") - return - } - int fqdnCount = fqdnList.size() - - execution.setVariable("DoDVfMod_networkPolicyFqdnCount", fqdnCount) - logger.debug("DoDVfMod_networkPolicyFqdnCount - " + fqdnCount) - - if (fqdnCount > 0) { - // AII loop call over contrail network policy fqdn list - for (i in 0..fqdnCount-1) { - String fqdn = fqdnList[i] - // Query AAI for this network policy FQDN + logger.debug("DeleteAAIVfModuleRequest :" + request) + logger.debug("DeleteAAIVfModuleRequest: " + request) + execution.setVariable("DeleteAAIVfModuleRequest", request) + } + + // generates a WorkflowException if + // - + public void handleDoDeleteVfModuleFailure(DelegateExecution execution) { + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + "AAI error occurred deleting the Generic Vnf: " + execution.getVariable("DoDVfMod_deleteGenericVnfResponse"), + "BPMN", ErrorCode.UnknownError.getValue(), "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() + sdncAdapterUtils.validateSDNCResponse(execution, response, workflowException, successIndicator) + + if(execution.getVariable(Prefix + 'sdncResponseSuccess') == true){ + logger.debug("Successfully Validated SDNC Response") + }else{ + throw new BpmnError("MSOWorkflowException") + } + } + + public void postProcessVNFAdapterRequest(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.postProcessVNFAdapterRequest(' + + 'execution=' + execution.getId() + + ')' + + logger.trace('Entered ' + method) + execution.setVariable("prefix",Prefix) + try{ + logger.trace("STARTED postProcessVNFAdapterRequest Process") + + String vnfResponse = execution.getVariable("DoDVfMod_doDeleteVfModuleResponse") + logger.debug("VNF Adapter Response is: " + vnfResponse) + logger.debug("deleteVnfAResponse is: \n" + vnfResponse) + + if(vnfResponse != null){ + + if(vnfResponse.contains("deleteVfModuleResponse")){ + logger.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() + logger.debug("Obtained contrailNetworkPolicyFqdn: " + contrailNetworkPolicyFqdn) + contrailNetworkPolicyFqdnList.add(contrailNetworkPolicyFqdn) + } + else if (key.equals("oam_management_v4_address")) { + String oamManagementV4Address = element.getElementsByTagNameNS("*", "value").item(0).getTextContent() + logger.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() + logger.debug("Obtained oamManagementV6Address: " + oamManagementV6Address) + execution.setVariable(Prefix + "oamManagementV6Address", oamManagementV6Address) + } + + } + } + if (!contrailNetworkPolicyFqdnList.isEmpty()) { + logger.debug("Setting the fqdn list") + execution.setVariable("DoDVfMod_contrailNetworkPolicyFqdnList", contrailNetworkPolicyFqdnList) + } + } + }else{ + logger.debug("Received a BAD Response from VNF Adapter for DELETE_VF_MODULE Call.") + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "VNF Adapter Error") + } + }else{ + logger.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){ + logger.debug("Internal Error Occured in PostProcess Method") + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Internal Error Occured in PostProcess Method") + } + logger.trace("COMPLETED postProcessVnfAdapterResponse Process") + } + + public void deleteNetworkPoliciesFromAAI(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.deleteNetworkPoliciesFromAAI(' + + 'execution=' + execution.getId() + + ')' + + logger.trace('Entered ' + method) + execution.setVariable("prefix", Prefix) + logger.trace("STARTED deleteNetworkPoliciesFromAAI ") + + try { + // get variables + List fqdnList = execution.getVariable("DoDVfMod_contrailNetworkPolicyFqdnList") + if (fqdnList == null) { + logger.debug("No network policies to delete") + return + } + int fqdnCount = fqdnList.size() + + execution.setVariable("DoDVfMod_networkPolicyFqdnCount", fqdnCount) + logger.debug("DoDVfMod_networkPolicyFqdnCount - " + fqdnCount) + + if (fqdnCount > 0) { + // AII loop call over contrail network policy fqdn list + for (i in 0..fqdnCount-1) { + String fqdn = fqdnList[i] + // Query AAI for this network policy FQDN AAIPluralResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectPlurals.NETWORK_POLICY) - uri.queryParam("network-policy-fqdn", fqdn) - try { - Optional networkPolicies = getAAIClient().get(NetworkPolicies.class, uri) - if (networkPolicies.isPresent() && !networkPolicies.get().getNetworkPolicy().isEmpty()) { - // This network policy FQDN exists in AAI - need to delete it now - NetworkPolicy networkPolicy = networkPolicies.get().getNetworkPolicy().get(0) - execution.setVariable("DCVFM_aaiQueryNetworkPolicyByFqdnReturnCode", 200) - // Retrieve the network policy id for this FQDN - def networkPolicyId = networkPolicy.getNetworkPolicyId() - logger.debug("Deleting network-policy with network-policy-id " + networkPolicyId) - try { - AAIResourceUri delUri = AAIUriFactory.createResourceUri(AAIObjectType.NETWORK_POLICY, networkPolicyId) - getAAIClient().delete(delUri) - execution.setVariable("DoDVfMod_aaiDeleteNetworkPolicyReturnCode", 200) - } catch (Exception e) { - execution.setVariable("DoDVfMod_aaiDeleteNetworkPolicyReturnCode", 500) - String delErrorMessage = "Unable to delete network-policy to AAI deleteNetworkPoliciesFromAAI - " + e.getMessage() - logger.debug(delErrorMessage) - exceptionUtil.buildAndThrowWorkflowException(execution, 2500, delErrorMessage) - } - } else { - execution.setVariable("DCVFM_aaiQueryNetworkPolicyByFqdnReturnCode", 404) - // This network policy FQDN is not in AAI. No need to delete. - logger.debug("The return code is: " + 404) - logger.debug("This network policy FQDN is not in AAI: " + fqdn) - logger.debug("Network policy FQDN is not in AAI") - } - }catch(Exception e ) { - // aai all errors - String dataErrorMessage = "Unexpected Response from deleteNetworkPoliciesFromAAI - " + e.getMessage() - logger.debug(dataErrorMessage) - } - } // end loop - } else { - logger.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() - logger.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() + - ')' - - logger.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 = '' + 'DELETE' + '' - } - - if (oamManagementV6Address != null) { - managementV6AddressElement = '' + 'DELETE' + '' - } - - - String updateAAIGenericVnfRequest = """ + uri.queryParam("network-policy-fqdn", fqdn) + try { + Optional networkPolicies = getAAIClient().get(NetworkPolicies.class, uri) + if (networkPolicies.isPresent() && !networkPolicies.get().getNetworkPolicy().isEmpty()) { + // This network policy FQDN exists in AAI - need to delete it now + NetworkPolicy networkPolicy = networkPolicies.get().getNetworkPolicy().get(0) + execution.setVariable("DCVFM_aaiQueryNetworkPolicyByFqdnReturnCode", 200) + // Retrieve the network policy id for this FQDN + def networkPolicyId = networkPolicy.getNetworkPolicyId() + logger.debug("Deleting network-policy with network-policy-id " + networkPolicyId) + try { + AAIResourceUri delUri = AAIUriFactory.createResourceUri(AAIObjectType.NETWORK_POLICY, networkPolicyId) + getAAIClient().delete(delUri) + execution.setVariable("DoDVfMod_aaiDeleteNetworkPolicyReturnCode", 200) + } catch (Exception e) { + execution.setVariable("DoDVfMod_aaiDeleteNetworkPolicyReturnCode", 500) + String delErrorMessage = "Unable to delete network-policy to AAI deleteNetworkPoliciesFromAAI - " + e.getMessage() + logger.debug(delErrorMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 2500, delErrorMessage) + } + } else { + execution.setVariable("DCVFM_aaiQueryNetworkPolicyByFqdnReturnCode", 404) + // This network policy FQDN is not in AAI. No need to delete. + logger.debug("The return code is: " + 404) + logger.debug("This network policy FQDN is not in AAI: " + fqdn) + logger.debug("Network policy FQDN is not in AAI") + } + }catch(Exception e ) { + // aai all errors + String dataErrorMessage = "Unexpected Response from deleteNetworkPoliciesFromAAI - " + e.getMessage() + logger.debug(dataErrorMessage) + } + } // end loop + } else { + logger.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() + logger.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() + + ')' + + logger.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 = '' + 'DELETE' + '' + } + + if (oamManagementV6Address != null) { + managementV6AddressElement = '' + 'DELETE' + '' + } + + + String updateAAIGenericVnfRequest = """ ${MsoUtils.xmlEscape(vnfId)} ${ipv4OamAddressElement} ${managementV6AddressElement} """ - updateAAIGenericVnfRequest = utils.formatXml(updateAAIGenericVnfRequest) - execution.setVariable(Prefix + 'updateAAIGenericVnfRequest', updateAAIGenericVnfRequest) - logger.debug("updateAAIGenericVnfRequest : " + updateAAIGenericVnfRequest) - logger.debug('Request for UpdateAAIGenericVnf:\n' + updateAAIGenericVnfRequest) - - - logger.trace('Exited ' + method) - } catch (BpmnError e) { - throw e; - } catch (Exception e) { - logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), - 'Caught exception in ' + method, "BPMN", - ErrorCode.UnknownError.getValue(), "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() + - ')' - logger.trace('Entered ' + method) - - execution.setVariable(Prefix + 'orchestrationStatus', '') - - try { - def vnfId = execution.getVariable('vnfId') - def vfModuleId = execution.getVariable('vfModuleId') - - AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, vnfId, vfModuleId) - - try { + updateAAIGenericVnfRequest = utils.formatXml(updateAAIGenericVnfRequest) + execution.setVariable(Prefix + 'updateAAIGenericVnfRequest', updateAAIGenericVnfRequest) + logger.debug("updateAAIGenericVnfRequest : " + updateAAIGenericVnfRequest) + logger.debug('Request for UpdateAAIGenericVnf:\n' + updateAAIGenericVnfRequest) + + + logger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + 'Caught exception in ' + method, "BPMN", + ErrorCode.UnknownError.getValue(), "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() + + ')' + logger.trace('Entered ' + method) + + execution.setVariable(Prefix + 'orchestrationStatus', '') + + try { + def vnfId = execution.getVariable('vnfId') + def vfModuleId = execution.getVariable('vfModuleId') + + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.VF_MODULE, vnfId, vfModuleId) + + try { Optional vfModule = getAAIClient().get(org.onap.aai.domain.yang.VfModule.class, uri); - // Retrieve VF Module info and its orchestration status; if not found, do nothing + // Retrieve VF Module info and its orchestration status; if not found, do nothing if (vfModule.isPresent()) { execution.setVariable(Prefix + 'queryAAIVfModuleForStatusResponseCode', 200) execution.setVariable(Prefix + 'queryAAIVfModuleForStatusResponse', vfModule.get()) @@ -622,20 +618,20 @@ public class DoDeleteVfModule extends AbstractServiceTaskProcessor{ execution.setVariable(Prefix + "orchestrationStatus", orchestrationStatus) logger.debug("Received orchestration status from A&AI: " + orchestrationStatus) } - } catch (Exception ex) { - logger.debug('Exception occurred while executing AAI GET: {}', ex.getMessage(), ex) - exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'AAI GET Failed:' + ex.getMessage()) - } - logger.trace('Exited ' + method) - } catch (BpmnError e) { - throw e; - } catch (Exception e) { - logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), - 'Caught exception in ' + method, "BPMN", - ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); - exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in queryAAIVfModuleForStatus(): ' + e.getMessage()) - } - } + } catch (Exception ex) { + logger.debug('Exception occurred while executing AAI GET: {}', ex.getMessage(), ex) + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'AAI GET Failed:' + ex.getMessage()) + } + logger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + 'Caught exception in ' + method, "BPMN", + ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in queryAAIVfModuleForStatus(): ' + e.getMessage()) + } + } diff --git a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVfModuleFromVnf.groovy b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVfModuleFromVnf.groovy index 34a210364a..350de4a03d 100644 --- a/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVfModuleFromVnf.groovy +++ b/bpmn/so-bpmn-infrastructure-common/src/main/groovy/org/onap/so/bpmn/infrastructure/scripts/DoDeleteVfModuleFromVnf.groovy @@ -9,9 +9,9 @@ * 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. @@ -53,244 +53,244 @@ import org.slf4j.LoggerFactory public class DoDeleteVfModuleFromVnf extends VfModuleBase { private static final Logger logger = LoggerFactory.getLogger( 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) - logger.debug("msoRequestId: " + requestId) - String tenantId = execution.getVariable("tenantId") - logger.debug("tenantId: " + tenantId) - String cloudSiteId = execution.getVariable("lcpCloudRegionId") - execution.setVariable("cloudSiteId", cloudSiteId) - logger.debug("cloudSiteId: " + cloudSiteId) - String cloudOwner = execution.getVariable("cloudOwner") - execution.setVariable("cloudOwner", cloudOwner) - logger.debug("cloudOwner: " + cloudOwner) - // 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") - logger.debug("serviceInstanceId: " + serviceInstanceId) - String vnfId = execution.getVariable("vnfId") - logger.debug("vnfId: " + vnfId) - String vfModuleId = execution.getVariable("vfModuleId") - logger.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) - logger.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' - logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", - ErrorCode.UnknownError.getValue(), "Exception"); - exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) - } - execution.setVariable("sdncCallbackUrl", sdncCallbackUrl) - logger.debug("SDNC Callback URL: " + sdncCallbackUrl) - logger.debug("SDNC Callback URL is: " + sdncCallbackUrl) - - }catch(BpmnError b){ - throw b - }catch(Exception e){ - logger.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() + - ')' - - logger.trace('Entered ' + method) - - try { - def vnfId = execution.getVariable('vnfId') - - AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId).depth(Depth.ONE) - try { - Optional genericVnf = getAAIClient().get(GenericVnf.class,uri) - - if(genericVnf.isPresent()){ - execution.setVariable('DDVMFV_getVnfResponseCode', 200) - execution.setVariable('DDVMFV_getVnfResponse', genericVnf.get()) - }else{ - execution.setVariable('DDVMFV_getVnfResponseCode', 404) - execution.setVariable('DDVMFV_getVnfResponse', "Generic Vnf not found!") - } - } catch (Exception ex) { - logger.debug('Exception occurred while executing AAI GET: {}', ex.getMessage(), ex) - execution.setVariable('DDVMFV_getVnfResponseCode', 500) - execution.setVariable('DDVFMV_getVnfResponse', 'AAI GET Failed:' + ex.getMessage()) - } - logger.trace('Exited ' + method) - } catch (BpmnError e) { - throw e; - } catch (Exception e) { - logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), - 'Caught exception in ' + method, "BPMN", - ErrorCode.UnknownError.getValue(), "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') - logger.trace('Entered ' + method) - - try { - GenericVnf genericVnf = execution.getVariable('DDVMFV_getVnfResponse') - def vnfId = execution.getVariable('_vnfId') - def vfModuleId = execution.getVariable('vfModuleId') + 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) + logger.debug("msoRequestId: " + requestId) + String tenantId = execution.getVariable("tenantId") + logger.debug("tenantId: " + tenantId) + String cloudSiteId = execution.getVariable("lcpCloudRegionId") + execution.setVariable("cloudSiteId", cloudSiteId) + logger.debug("cloudSiteId: " + cloudSiteId) + String cloudOwner = execution.getVariable("cloudOwner") + execution.setVariable("cloudOwner", cloudOwner) + logger.debug("cloudOwner: " + cloudOwner) + // 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") + logger.debug("serviceInstanceId: " + serviceInstanceId) + String vnfId = execution.getVariable("vnfId") + logger.debug("vnfId: " + vnfId) + String vfModuleId = execution.getVariable("vfModuleId") + logger.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) + logger.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' + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), msg, "BPMN", + ErrorCode.UnknownError.getValue(), "Exception"); + exceptionUtil.buildAndThrowWorkflowException(execution, 2000, msg) + } + execution.setVariable("sdncCallbackUrl", sdncCallbackUrl) + logger.debug("SDNC Callback URL: " + sdncCallbackUrl) + logger.debug("SDNC Callback URL is: " + sdncCallbackUrl) + + }catch(BpmnError b){ + throw b + }catch(Exception e){ + logger.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() + + ')' + + logger.trace('Entered ' + method) + + try { + def vnfId = execution.getVariable('vnfId') + + AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId).depth(Depth.ONE) + try { + Optional genericVnf = getAAIClient().get(GenericVnf.class,uri) + + if(genericVnf.isPresent()){ + execution.setVariable('DDVMFV_getVnfResponseCode', 200) + execution.setVariable('DDVMFV_getVnfResponse', genericVnf.get()) + }else{ + execution.setVariable('DDVMFV_getVnfResponseCode', 404) + execution.setVariable('DDVMFV_getVnfResponse', "Generic Vnf not found!") + } + } catch (Exception ex) { + logger.debug('Exception occurred while executing AAI GET: {}', ex.getMessage(), ex) + execution.setVariable('DDVMFV_getVnfResponseCode', 500) + execution.setVariable('DDVFMV_getVnfResponse', 'AAI GET Failed:' + ex.getMessage()) + } + logger.trace('Exited ' + method) + } catch (BpmnError e) { + throw e; + } catch (Exception e) { + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + 'Caught exception in ' + method, "BPMN", + ErrorCode.UnknownError.getValue(), "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') + logger.trace('Entered ' + method) + + try { + GenericVnf genericVnf = execution.getVariable('DDVMFV_getVnfResponse') + def vnfId = execution.getVariable('_vnfId') + def vfModuleId = execution.getVariable('vfModuleId') Optional vfModule = Optional.empty() if(genericVnf.getVfModules()!=null && ! genericVnf.getVfModules().getVfModule().isEmpty()) { vfModule = genericVnf.getVfModules().getVfModule().stream().filter { v -> v.getVfModuleId().equals(vfModuleId) }.findFirst() } - if (!vfModule.isPresent()) { - String msg = 'VF Module \'' + vfModuleId + '\' does not exist in Generic VNF \'' + vnfId + '\'' - logger.debug(msg) - exceptionUtil.buildAndThrowWorkflowException(execution, 1002, msg) - } else { + if (!vfModule.isPresent()) { + String msg = 'VF Module \'' + vfModuleId + '\' does not exist in Generic VNF \'' + vnfId + '\'' + logger.debug(msg) + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, msg) + } else { Boolean isOnlyVfModule = (genericVnf.getVfModules().getVfModule().size() == 1) - if (isDebugLogEnabled) { - logger.debug('VF Module \'' + vfModuleId + '\': isBaseVfModule=' + vfModule.get().isIsBaseVfModule() + ', isOnlyVfModule=' + isOnlyVfModule) - } - if (vfModule.get().isIsBaseVfModule() && !isOnlyVfModule) { + if (isDebugLogEnabled) { + logger.debug('VF Module \'' + vfModuleId + '\': isBaseVfModule=' + vfModule.get().isIsBaseVfModule() + ', isOnlyVfModule=' + isOnlyVfModule) + } + if (vfModule.get().isIsBaseVfModule() && !isOnlyVfModule) { 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 + '\'' logger.debug(msg) exceptionUtil.buildAndThrowWorkflowException(execution, 1002,msg) - } - def heatStackId = vfModule.get().getHeatStackId() - execution.setVariable('DDVMFV_heatStackId', heatStackId) - logger.debug('VF Module heatStackId retrieved from AAI: ' + heatStackId) - } - logger.trace('Exited ' + method) - } catch (BpmnError e) { - throw e; - } catch (Exception e) { - logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), - 'Caught exception in ' + method, "BPMN", - ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); - exceptionUtil.buildAndThrowWorkflowException(execution, 1002, 'Error in validateVfModule(): ' + e.getMessage()) - } - } - - - public void preProcessSDNCDeactivateRequest(DelegateExecution execution){ - - execution.setVariable("prefix", Prefix) - logger.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) - logger.debug("Outgoing DeactivateSDNCRequest is: \n" + deactivateSDNCRequest) - - - }catch(Exception e){ - logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), - "Exception Occured Processing preProcessSDNCDeactivateRequest. Exception is:\n" + e, "BPMN", - ErrorCode.UnknownError.getValue(), "Exception is:\n" + e); - exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occurred during preProcessSDNCDeactivateRequest Method:\n" + e.getMessage()) - } - logger.trace("COMPLETED preProcessSDNCDeactivateRequest ") - } - - public void preProcessSDNCUnassignRequest(DelegateExecution execution) { - def method = getClass().getSimpleName() + '.preProcessSDNCUnassignRequest(' + - 'execution=' + execution.getId() + - ')' - - logger.trace('Entered ' + method) - execution.setVariable("prefix", Prefix) - logger.trace("STARTED preProcessSDNCUnassignRequest Process ") - try{ - String serviceInstanceId = execution.getVariable("serviceInstanceId") - - String unassignSDNCRequest = buildSDNCRequest(execution, serviceInstanceId, "unassign") - - execution.setVariable("DDVMFV_unassignSDNCRequest", unassignSDNCRequest) - logger.debug("Outgoing UnassignSDNCRequest is: \n" + unassignSDNCRequest) - - - }catch(Exception e){ - logger.debug("Exception Occured Processing preProcessSDNCUnassignRequest. Exception is:\n" + e) - exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Error Occured during preProcessSDNCUnassignRequest Method:\n" + e.getMessage()) - } - logger.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 = - """ @@ -312,73 +312,73 @@ public class DoDeleteVfModuleFromVnf extends VfModuleBase { - + ${MsoUtils.xmlEscape(serviceInstanceId)} ${MsoUtils.xmlEscape(vnfId)} - + ${MsoUtils.xmlEscape(vfModuleId)} - + """ - - logger.debug("sdncRequest: " + sdncRequest) - return sdncRequest - } - - public void validateSDNCResponse(DelegateExecution execution, String response, String method){ - - execution.setVariable("prefix",Prefix) - logger.trace("STARTED ValidateSDNCResponse Process") - - WorkflowException workflowException = execution.getVariable("WorkflowException") - boolean successIndicator = execution.getVariable("SDNCA_SuccessIndicator") - - logger.debug("workflowException: " + workflowException) - - SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils() - sdncAdapterUtils.validateSDNCResponse(execution, response, workflowException, successIndicator) - - logger.debug("SDNCResponse: " + response) - - String sdncResponse = response - if(execution.getVariable(Prefix + 'sdncResponseSuccess') == true){ - logger.debug("Received a Good Response from SDNC Adapter for " + method + " SDNC Call. Response is: \n" + sdncResponse) - }else{ - logger.debug("Received a BAD Response from SDNC Adapter for " + method + " SDNC Call.") - throw new BpmnError("MSOWorkflowException") - } - logger.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 cloudOwner = execution.getVariable("cloudOwner") - 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 = """ + + logger.debug("sdncRequest: " + sdncRequest) + return sdncRequest + } + + public void validateSDNCResponse(DelegateExecution execution, String response, String method){ + + execution.setVariable("prefix",Prefix) + logger.trace("STARTED ValidateSDNCResponse Process") + + WorkflowException workflowException = execution.getVariable("WorkflowException") + boolean successIndicator = execution.getVariable("SDNCA_SuccessIndicator") + + logger.debug("workflowException: " + workflowException) + + SDNCAdapterUtils sdncAdapterUtils = new SDNCAdapterUtils() + sdncAdapterUtils.validateSDNCResponse(execution, response, workflowException, successIndicator) + + logger.debug("SDNCResponse: " + response) + + String sdncResponse = response + if(execution.getVariable(Prefix + 'sdncResponseSuccess') == true){ + logger.debug("Received a Good Response from SDNC Adapter for " + method + " SDNC Call. Response is: \n" + sdncResponse) + }else{ + logger.debug("Received a BAD Response from SDNC Adapter for " + method + " SDNC Call.") + throw new BpmnError("MSOWorkflowException") + } + logger.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 cloudOwner = execution.getVariable("cloudOwner") + 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 = """ ${MsoUtils.xmlEscape(aicCloudRegion)} ${MsoUtils.xmlEscape(cloudOwner)} @@ -396,126 +396,126 @@ public class DoDeleteVfModuleFromVnf extends VfModuleBase { """ as String - logger.debug("vnfAdapterRestV1Request: " + request) - logger.debug("deleteVfModuleRequest: " + request) - execution.setVariable("vnfAdapterRestV1Request", request) - } - - - // generates a WorkflowException if - // - - public void handleDoDeleteVfModuleFailure(DelegateExecution execution) { - logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), - "AAI error occurred deleting the Generic Vnf: " + execution.getVariable("DDVFMV_deleteGenericVnfResponse"), - "BPMN", ErrorCode.UnknownError.getValue(), "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() + - ')' - - logger.trace('Entered ' + method) - execution.setVariable("prefix",Prefix) - try{ - logger.trace("STARTED postProcessVNFAdapterRequest Process") - - String vnfResponse = execution.getVariable("DDVMFV_doDeleteVfModuleResponse") - logger.debug("VNF Adapter Response is: " + vnfResponse) - logger.debug("deleteVnfAResponse is: \n" + vnfResponse) - - if(vnfResponse != null){ - - if(vnfResponse.contains("deleteVfModuleResponse")){ - logger.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") - logger.debug("Obtained contrailNetworkPolicyFqdn: " + contrailNetworkPolicyFqdn) - contrailNetworkPolicyFqdnList.add(contrailNetworkPolicyFqdn) - } - else if (key.equals("oam_management_v4_address")) { - String oamManagementV4Address = utils.getChildNodeText(node, "value") - logger.debug("Obtained oamManagementV4Address: " + oamManagementV4Address) - execution.setVariable(Prefix + "oamManagementV4Address", oamManagementV4Address) - } - else if (key.equals("oam_management_v6_address")) { - String oamManagementV6Address = utils.getChildNodeText(node, "value") - logger.debug("Obtained oamManagementV6Address: " + oamManagementV6Address) - execution.setVariable(Prefix + "oamManagementV6Address", oamManagementV6Address) - } - } - if (!contrailNetworkPolicyFqdnList.isEmpty()) { - logger.debug("Setting the fqdn list") - execution.setVariable("DDVFMV_contrailNetworkPolicyFqdnList", contrailNetworkPolicyFqdnList) - } - } - }else{ - logger.debug("Received a BAD Response from VNF Adapter for DELETE_VF_MODULE Call.") - exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "VNF Adapter Error") - } - }else{ - logger.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){ - logger.debug("Internal Error Occured in PostProcess Method") - exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Internal Error Occured in PostProcess Method") - } - logger.trace("COMPLETED postProcessVnfAdapterResponse Process") - } - - public void deleteNetworkPoliciesFromAAI(DelegateExecution execution) { - def method = getClass().getSimpleName() + '.deleteNetworkPoliciesFromAAI(' + - 'execution=' + execution.getId() + - ')' - - logger.trace('Entered ' + method) - execution.setVariable("prefix", Prefix) - logger.trace("STARTED deleteNetworkPoliciesFromAAI ") - - try { - // get variables - List fqdnList = execution.getVariable("DDVFMV_contrailNetworkPolicyFqdnList") - if (fqdnList == null) { - logger.debug("No network policies to delete") - return - } - int fqdnCount = fqdnList.size() - - execution.setVariable("DDVFMV_networkPolicyFqdnCount", fqdnCount) - logger.debug("DDVFMV_networkPolicyFqdnCount - " + fqdnCount) - - AaiUtil aaiUriUtil = new AaiUtil(this) - - 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 + + logger.debug("deleteVfModuleRequest: " + request) + execution.setVariable("vnfAdapterTaskRequest", request) + } + + + // generates a WorkflowException if + // - + public void handleDoDeleteVfModuleFailure(DelegateExecution execution) { + logger.error(LoggingAnchor.FIVE, MessageEnum.BPMN_GENERAL_EXCEPTION_ARG.toString(), + "AAI error occurred deleting the Generic Vnf: " + execution.getVariable("DDVFMV_deleteGenericVnfResponse"), + "BPMN", ErrorCode.UnknownError.getValue(), "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() + + ')' + + logger.trace('Entered ' + method) + execution.setVariable("prefix",Prefix) + try{ + logger.trace("STARTED postProcessVNFAdapterRequest Process") + + String vnfResponse = execution.getVariable("DDVMFV_doDeleteVfModuleResponse") + logger.debug("VNF Adapter Response is: " + vnfResponse) + logger.debug("deleteVnfAResponse is: \n" + vnfResponse) + + if(vnfResponse != null){ + + if(vnfResponse.contains("deleteVfModuleResponse")){ + logger.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") + logger.debug("Obtained contrailNetworkPolicyFqdn: " + contrailNetworkPolicyFqdn) + contrailNetworkPolicyFqdnList.add(contrailNetworkPolicyFqdn) + } + else if (key.equals("oam_management_v4_address")) { + String oamManagementV4Address = utils.getChildNodeText(node, "value") + logger.debug("Obtained oamManagementV4Address: " + oamManagementV4Address) + execution.setVariable(Prefix + "oamManagementV4Address", oamManagementV4Address) + } + else if (key.equals("oam_management_v6_address")) { + String oamManagementV6Address = utils.getChildNodeText(node, "value") + logger.debug("Obtained oamManagementV6Address: " + oamManagementV6Address) + execution.setVariable(Prefix + "oamManagementV6Address", oamManagementV6Address) + } + } + if (!contrailNetworkPolicyFqdnList.isEmpty()) { + logger.debug("Setting the fqdn list") + execution.setVariable("DDVFMV_contrailNetworkPolicyFqdnList", contrailNetworkPolicyFqdnList) + } + } + }else{ + logger.debug("Received a BAD Response from VNF Adapter for DELETE_VF_MODULE Call.") + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "VNF Adapter Error") + } + }else{ + logger.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){ + logger.debug("Internal Error Occured in PostProcess Method") + exceptionUtil.buildAndThrowWorkflowException(execution, 1002, "Internal Error Occured in PostProcess Method") + } + logger.trace("COMPLETED postProcessVnfAdapterResponse Process") + } + + public void deleteNetworkPoliciesFromAAI(DelegateExecution execution) { + def method = getClass().getSimpleName() + '.deleteNetworkPoliciesFromAAI(' + + 'execution=' + execution.getId() + + ')' + + logger.trace('Entered ' + method) + execution.setVariable("prefix", Prefix) + logger.trace("STARTED deleteNetworkPoliciesFromAAI ") + + try { + // get variables + List fqdnList = execution.getVariable("DDVFMV_contrailNetworkPolicyFqdnList") + if (fqdnList == null) { + logger.debug("No network policies to delete") + return + } + int fqdnCount = fqdnList.size() + + execution.setVariable("DDVFMV_networkPolicyFqdnCount", fqdnCount) + logger.debug("DDVFMV_networkPolicyFqdnCount - " + fqdnCount) + + AaiUtil aaiUriUtil = new AaiUtil(this) + + 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 AAIPluralResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectPlurals.NETWORK_POLICY) - uri.queryParam("network-policy-fqdn", fqdn) + uri.queryParam("network-policy-fqdn", fqdn) try { Optional networkPolicies = getAAIClient().get(NetworkPolicies.class, uri) @@ -555,35 +555,35 @@ public class DoDeleteVfModuleFromVnf extends VfModuleBase { exceptionUtil.buildAndThrowWorkflowException(execution, 2500, dataErrorMessage) } } // end loop - } else { - logger.debug("No contrail network policies to query/create") + } else { + logger.debug("No contrail network policies to query/create") - } + } + + } catch (BpmnError e) { + throw e; - } catch (BpmnError e) { - throw e; + } catch (Exception ex) { + String exceptionMessage = "Bpmn error encountered in DoDeletVfModule flow. deleteNetworkPoliciesFromAAI() - " + ex.getMessage() + logger.debug(exceptionMessage) + exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) + } - } catch (Exception ex) { - String exceptionMessage = "Bpmn error encountered in DoDeletVfModule flow. deleteNetworkPoliciesFromAAI() - " + ex.getMessage() - logger.debug(exceptionMessage) - exceptionUtil.buildAndThrowWorkflowException(execution, 7000, exceptionMessage) - } + } - } - - // and formulate the outgoing DeleteAAIVfModuleRequest request - public void prepDeleteAAIVfModule(DelegateExecution execution) { + // 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 = """ + def vnfId = execution.getVariable("vnfId") + def vfModuleId = execution.getVariable("vfModuleId") + // formulate the request for UpdateAAIVfModule + String request = """ ${MsoUtils.xmlEscape(vnfId)} ${MsoUtils.xmlEscape(vfModuleId)} """ as String - logger.debug("DeleteAAIVfModuleRequest :" + request) - - execution.setVariable("DeleteAAIVfModuleRequest", request) - } + logger.debug("DeleteAAIVfModuleRequest :" + request) + + execution.setVariable("DeleteAAIVfModuleRequest", request) + } } diff --git a/bpmn/so-bpmn-infrastructure-flows/src/main/resources/process/DeleteVfModuleVolumeInfraV1.bpmn b/bpmn/so-bpmn-infrastructure-flows/src/main/resources/process/DeleteVfModuleVolumeInfraV1.bpmn index b7ce608090..2e5d2e30b1 100644 --- a/bpmn/so-bpmn-infrastructure-flows/src/main/resources/process/DeleteVfModuleVolumeInfraV1.bpmn +++ b/bpmn/so-bpmn-infrastructure-flows/src/main/resources/process/DeleteVfModuleVolumeInfraV1.bpmn @@ -1,5 +1,5 @@ - + SequenceFlow_1 @@ -51,13 +51,12 @@ deleteVfMod.executeMethod('prepareVnfAdapterDeleteRequest', execution, isDebugLo - + - - + + - diff --git a/bpmn/so-bpmn-infrastructure-flows/src/main/resources/process/UpdateVfModuleVolumeInfraV1.bpmn b/bpmn/so-bpmn-infrastructure-flows/src/main/resources/process/UpdateVfModuleVolumeInfraV1.bpmn index 078d72a1d8..ce346e13b3 100644 --- a/bpmn/so-bpmn-infrastructure-flows/src/main/resources/process/UpdateVfModuleVolumeInfraV1.bpmn +++ b/bpmn/so-bpmn-infrastructure-flows/src/main/resources/process/UpdateVfModuleVolumeInfraV1.bpmn @@ -1,5 +1,5 @@ - + SequenceFlow_1 @@ -56,14 +56,13 @@ def uvmv = new UpdateVfModuleVolumeInfraV1() uvmv.executeMethod('prepCompletionHandlerRequest', execution, UPDVfModVol_requestId, 'UPDATE', UPDVfModVol_source, isDebugLogEnabled)]]> - + - - + - + SequenceFlow_21 SequenceFlow_19 diff --git a/bpmn/so-bpmn-infrastructure-flows/src/main/resources/subprocess/DoCreateVfModule.bpmn b/bpmn/so-bpmn-infrastructure-flows/src/main/resources/subprocess/DoCreateVfModule.bpmn index c16061edb2..0d1b970c62 100644 --- a/bpmn/so-bpmn-infrastructure-flows/src/main/resources/subprocess/DoCreateVfModule.bpmn +++ b/bpmn/so-bpmn-infrastructure-flows/src/main/resources/subprocess/DoCreateVfModule.bpmn @@ -224,10 +224,10 @@ doCreateVfModule.prepareCreateAAIVfModuleVolumeGroupRequest(execution)]]> - + - - + + diff --git a/bpmn/so-bpmn-infrastructure-flows/src/main/resources/subprocess/DoCreateVfModuleRollback.bpmn b/bpmn/so-bpmn-infrastructure-flows/src/main/resources/subprocess/DoCreateVfModuleRollback.bpmn index 2508b31f01..e9675b89f8 100644 --- a/bpmn/so-bpmn-infrastructure-flows/src/main/resources/subprocess/DoCreateVfModuleRollback.bpmn +++ b/bpmn/so-bpmn-infrastructure-flows/src/main/resources/subprocess/DoCreateVfModuleRollback.bpmn @@ -1,5 +1,5 @@ - + SequenceFlow_1 @@ -38,13 +38,12 @@ def dcvfmr = new DoCreateVfModuleRollback() dcvfmr.prepVNFAdapterRequest(execution)]]> - - + + - - - + + @@ -375,7 +374,7 @@ dcvfmr.setSuccessfulRollbackStatus(execution)]]> def dcvfmr = new DoCreateVfModuleRollback() dcvfmr.prepUpdateAAIVfModuleToAssigned(execution)]]> - + @@ -403,7 +402,7 @@ dcvfmr.prepUpdateAAIVfModuleToAssigned(execution)]]> - + diff --git a/bpmn/so-bpmn-infrastructure-flows/src/main/resources/subprocess/DoCreateVfModuleVolumeRollback.bpmn b/bpmn/so-bpmn-infrastructure-flows/src/main/resources/subprocess/DoCreateVfModuleVolumeRollback.bpmn index a762b7ecd7..6f3dceda84 100644 --- a/bpmn/so-bpmn-infrastructure-flows/src/main/resources/subprocess/DoCreateVfModuleVolumeRollback.bpmn +++ b/bpmn/so-bpmn-infrastructure-flows/src/main/resources/subprocess/DoCreateVfModuleVolumeRollback.bpmn @@ -1,5 +1,5 @@ - + @@ -33,10 +33,9 @@ doCreateVfModuleVolumeRollback.processJavaException(execution)]]> SequenceFlow_0h7k68j SequenceFlow_10dawse - + - - + diff --git a/bpmn/so-bpmn-infrastructure-flows/src/main/resources/subprocess/DoCreateVfModuleVolumeV2.bpmn b/bpmn/so-bpmn-infrastructure-flows/src/main/resources/subprocess/DoCreateVfModuleVolumeV2.bpmn index 26a4112d59..58ea0c4951 100644 --- a/bpmn/so-bpmn-infrastructure-flows/src/main/resources/subprocess/DoCreateVfModuleVolumeV2.bpmn +++ b/bpmn/so-bpmn-infrastructure-flows/src/main/resources/subprocess/DoCreateVfModuleVolumeV2.bpmn @@ -63,15 +63,14 @@ def doCreateVfModuleVolumeV2 = new DoCreateVfModuleVolumeV2() doCreateVfModuleVolumeV2.executeMethod('callRESTCreateAAIVolGrpName', execution, isDebugLogEnabled)]]> - + - + - + - SequenceFlow_10 diff --git a/bpmn/so-bpmn-infrastructure-flows/src/main/resources/subprocess/DoDeleteVfModule.bpmn b/bpmn/so-bpmn-infrastructure-flows/src/main/resources/subprocess/DoDeleteVfModule.bpmn index 848796c0b6..6026fc84b3 100644 --- a/bpmn/so-bpmn-infrastructure-flows/src/main/resources/subprocess/DoDeleteVfModule.bpmn +++ b/bpmn/so-bpmn-infrastructure-flows/src/main/resources/subprocess/DoDeleteVfModule.bpmn @@ -1,5 +1,5 @@ - + SequenceFlow_0fp1wqz @@ -30,7 +30,7 @@ dvm.prepUpdateAAIVfModule(execution)]]> SequenceFlow_029ioyr SequenceFlow_14xn858 - + @@ -60,12 +60,11 @@ def dvm = new DoDeleteVfModule() dvm.prepSDNCAdapterRequest(execution, "delete")]]> - + - - - + + @@ -182,7 +181,7 @@ doDeleteVfModule.prepUpdateAAIGenericVnf(execution)]]> def dvm = new DoDeleteVfModule() dvm.queryAAIVfModuleForStatus(execution)]]> - + @@ -221,7 +220,7 @@ dvm.queryAAIVfModuleForStatus(execution)]]> - + diff --git a/bpmn/so-bpmn-infrastructure-flows/src/main/resources/subprocess/DoDeleteVfModuleFromVnf.bpmn b/bpmn/so-bpmn-infrastructure-flows/src/main/resources/subprocess/DoDeleteVfModuleFromVnf.bpmn index b7a1373fe9..918964f8f8 100644 --- a/bpmn/so-bpmn-infrastructure-flows/src/main/resources/subprocess/DoDeleteVfModuleFromVnf.bpmn +++ b/bpmn/so-bpmn-infrastructure-flows/src/main/resources/subprocess/DoDeleteVfModuleFromVnf.bpmn @@ -1,7 +1,7 @@ - + - + @@ -31,12 +31,11 @@ def ddvmfv = new DoDeleteVfModuleFromVnf() ddvmfv.preProcessSDNCUnassignRequest(execution)]]> - + - - - + + @@ -83,7 +82,7 @@ ddvmfv.postProcessVNFAdapterRequest(execution)]]> - + @@ -187,7 +186,7 @@ ddvmfv.prepDeleteAAIVfModule(execution)]]> - + diff --git a/bpmn/so-bpmn-infrastructure-flows/src/main/resources/subprocess/DoDeleteVfModuleVolumeV2.bpmn b/bpmn/so-bpmn-infrastructure-flows/src/main/resources/subprocess/DoDeleteVfModuleVolumeV2.bpmn index 4409f2a0dc..e7706c20e6 100644 --- a/bpmn/so-bpmn-infrastructure-flows/src/main/resources/subprocess/DoDeleteVfModuleVolumeV2.bpmn +++ b/bpmn/so-bpmn-infrastructure-flows/src/main/resources/subprocess/DoDeleteVfModuleVolumeV2.bpmn @@ -1,5 +1,5 @@ - + SequenceFlow_1gvfdp4 @@ -25,21 +25,20 @@ deleteVfMod.executeMethod('callRESTQueryAAIForVolumeGroup', execution, isDebugLo def deleteVfMod = new DoDeleteVfModuleVolumeV2() deleteVfMod.executeMethod('prepareVnfAdapterDeleteRequest', execution, isDebugLogEnabled)]]> - + - + - - + SequenceFlow_1tgngf7 - SequenceFlow_1x3luyj + SequenceFlow_04zsr0f - SequenceFlow_0cy0y9t + SequenceFlow_04zsr0f SequenceFlow_13c3cv2 - - SequenceFlow_1x3luyj - SequenceFlow_0cy0y9t - SequenceFlow_1rgd8dg - - - - #{VNFREST_SuccessIndicator == true} - - - SequenceFlow_1rgd8dg - - - SequenceFlow_13c3cv2 SequenceFlow_1sgtwr2 @@ -84,6 +69,7 @@ deleteVfMod.executeMethod('postProcess', execution, isDebugLogEnabled)]]> + @@ -153,39 +139,6 @@ deleteVfMod.executeMethod('postProcess', execution, isDebugLogEnabled)]]> - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - @@ -203,6 +156,13 @@ deleteVfMod.executeMethod('postProcess', execution, isDebugLogEnabled)]]> + + + + + + + diff --git a/bpmn/so-bpmn-infrastructure-flows/src/main/resources/subprocess/DoUpdateVfModule.bpmn b/bpmn/so-bpmn-infrastructure-flows/src/main/resources/subprocess/DoUpdateVfModule.bpmn index 46e7ddcbe6..cfda2ad73c 100644 --- a/bpmn/so-bpmn-infrastructure-flows/src/main/resources/subprocess/DoUpdateVfModule.bpmn +++ b/bpmn/so-bpmn-infrastructure-flows/src/main/resources/subprocess/DoUpdateVfModule.bpmn @@ -1,5 +1,5 @@ - + @@ -121,8 +121,7 @@ duvm.prepUpdateAAIGenericVnf(execution)]]> SequenceFlow_9 - + SequenceFlow_13 SequenceFlow_14 SequenceFlow_18 @@ -157,14 +156,13 @@ duvm.prepSDNCTopologyChg(execution)]]> SequenceFlow_12 SequenceFlow_3 - + - + - - + SequenceFlow_21 SequenceFlow_24 @@ -248,8 +246,7 @@ def duvm = new DoUpdateVfModule() duvm.prepConfirmVolumeGroupTenant(execution)]]> - + SequenceFlow_29 SequenceFlow_10 SequenceFlow_16 diff --git a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterImpl.java b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterImpl.java index 8b78560521..97d78b5ee8 100644 --- a/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterImpl.java +++ b/bpmn/so-bpmn-tasks/src/main/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterImpl.java @@ -9,9 +9,9 @@ * 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. @@ -91,7 +91,7 @@ public class VnfAdapterImpl { public void postProcessVnfAdapter(BuildingBlockExecution execution) { try { - String vnfAdapterResponse = execution.getVariable("vnfAdapterRestV1Response"); + String vnfAdapterResponse = execution.getVariable("WorkflowResponse"); if (!StringUtils.isEmpty(vnfAdapterResponse)) { Object vnfRestResponse = unMarshal(vnfAdapterResponse); if (vnfRestResponse instanceof CreateVfModuleResponse) { diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterImplTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterImplTest.java index 97a9388f8d..16e8c2de7d 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterImplTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/bpmn/infrastructure/adapter/vnf/tasks/VnfAdapterImplTest.java @@ -7,9 +7,9 @@ * 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. @@ -103,7 +103,7 @@ public class VnfAdapterImplTest extends BaseTaskTest { @Test public void postProcessVnfAdapter_CreateResponseTest() { - execution.setVariable("vnfAdapterRestV1Response", VNF_ADAPTER_REST_CREATE_RESPONSE); + execution.setVariable("WorkflowResponse", VNF_ADAPTER_REST_CREATE_RESPONSE); vnfAdapterImpl.postProcessVnfAdapter(execution); assertEquals(TEST_VFMODULE_HEATSTACK_ID, vfModule.getHeatStackId()); assertEquals(TEST_CONTRAIL_SERVICE_INSTANCE_FQDN, vfModule.getContrailServiceInstanceFqdn()); @@ -119,20 +119,20 @@ public class VnfAdapterImplTest extends BaseTaskTest { @Test public void postProcessVnfAdapter_CreateResponseTest_EmptyCreateVfModuleResponseTag() { expectedException.expect(BpmnError.class); - execution.setVariable("vnfAdapterRestV1Response", ""); + execution.setVariable("WorkflowResponse", ""); vnfAdapterImpl.postProcessVnfAdapter(execution); } @Test public void postProcessVnfAdapter_CreateResponseTest_EmptyVfModuleStackIdTag() { - execution.setVariable("vnfAdapterRestV1Response", ""); + execution.setVariable("WorkflowResponse", ""); vnfAdapterImpl.postProcessVnfAdapter(execution); assertNull(vfModule.getHeatStackId()); } @Test public void postProcessVnfAdapter_CreateResponseTest_EmptyHeatStackId() { - execution.setVariable("vnfAdapterRestV1Response", + execution.setVariable("WorkflowResponse", ""); vnfAdapterImpl.postProcessVnfAdapter(execution); assertNull(vfModule.getHeatStackId()); @@ -140,7 +140,7 @@ public class VnfAdapterImplTest extends BaseTaskTest { @Test public void postProcessVnfAdapter_CreateResponseTest_EmptyVfModuleOutputs() { - execution.setVariable("vnfAdapterRestV1Response", + execution.setVariable("WorkflowResponse", ""); vnfAdapterImpl.postProcessVnfAdapter(execution); assertNull(vfModule.getHeatStackId()); @@ -156,7 +156,7 @@ public class VnfAdapterImplTest extends BaseTaskTest { @Test public void postProcessVnfAdapter_DeleteResponseTest() { vfModule.setHeatStackId(TEST_VFMODULE_HEATSTACK_ID); - execution.setVariable("vnfAdapterRestV1Response", VNF_ADAPTER_REST_DELETE_RESPONSE); + execution.setVariable("WorkflowResponse", VNF_ADAPTER_REST_DELETE_RESPONSE); vnfAdapterImpl.postProcessVnfAdapter(execution); assertNull(vfModule.getHeatStackId()); assertEquals(vfModule.getContrailServiceInstanceFqdn(), ""); @@ -170,7 +170,7 @@ public class VnfAdapterImplTest extends BaseTaskTest { @Test public void postProcessVnfAdapter_DeleteResponseTest_EmptyVfModuleOutputs() { - execution.setVariable("vnfAdapterRestV1Response", + execution.setVariable("WorkflowResponse", ""); vnfAdapterImpl.postProcessVnfAdapter(execution); assertNull(vfModule.getHeatStackId()); @@ -183,14 +183,14 @@ public class VnfAdapterImplTest extends BaseTaskTest { @Test public void postProcessVnfAdapter_ResponseNullTest() { - execution.setVariable("vnfAdapterRestV1Response", null); + execution.setVariable("WorkflowResponse", null); vnfAdapterImpl.postProcessVnfAdapter(execution); assertNull(vfModule.getHeatStackId()); } @Test public void postProcessVnfAdapter_ResponseEmptyTest() { - execution.setVariable("vnfAdapterRestV1Response", ""); + execution.setVariable("WorkflowResponse", ""); vnfAdapterImpl.postProcessVnfAdapter(execution); assertNull(vfModule.getHeatStackId()); } @@ -198,7 +198,7 @@ public class VnfAdapterImplTest extends BaseTaskTest { @Test public void postProcessVnfAdapter_DeleteResponseTest_VfModuleDeletedFalse() { vfModule.setHeatStackId(TEST_VFMODULE_HEATSTACK_ID); - execution.setVariable("vnfAdapterRestV1Response", + execution.setVariable("WorkflowResponse", "false"); vnfAdapterImpl.postProcessVnfAdapter(execution); assertEquals(TEST_VFMODULE_HEATSTACK_ID, vfModule.getHeatStackId()); @@ -207,14 +207,14 @@ public class VnfAdapterImplTest extends BaseTaskTest { @Test public void postProcessVnfAdapter_DeleteResponseTest_EmptyDeleteVfModuleResponseTag() { expectedException.expect(BpmnError.class); - execution.setVariable("vnfAdapterRestV1Response", ""); + execution.setVariable("WorkflowResponse", ""); vnfAdapterImpl.postProcessVnfAdapter(execution); } @Test public void postProcessVnfAdapter_DeleteResponseTest_EmptyVfModuleDeletedTag() { vfModule.setHeatStackId(TEST_VFMODULE_HEATSTACK_ID); - execution.setVariable("vnfAdapterRestV1Response", ""); + execution.setVariable("WorkflowResponse", ""); vnfAdapterImpl.postProcessVnfAdapter(execution); assertEquals(TEST_VFMODULE_HEATSTACK_ID, vfModule.getHeatStackId()); } @@ -230,7 +230,7 @@ public class VnfAdapterImplTest extends BaseTaskTest { @Test public void postProcessVnfAdapter_CreateVolumeResponseTest() { - execution.setVariable("vnfAdapterRestV1Response", VNF_ADAPTER_VOLUME_CREATE_RESPONSE); + execution.setVariable("WorkflowResponse", VNF_ADAPTER_VOLUME_CREATE_RESPONSE); vnfAdapterImpl.postProcessVnfAdapter(execution); assertEquals(TEST_VOLUME_HEATSTACK_ID, volumeGroup.getHeatStackId()); } @@ -238,7 +238,7 @@ public class VnfAdapterImplTest extends BaseTaskTest { @Test public void postProcessVnfAdapter_CreateVolumeEmptyResponseTest() { expectedException.expect(BpmnError.class); - execution.setVariable("vnfAdapterRestV1Response", ""); + execution.setVariable("WorkflowResponse", ""); vnfAdapterImpl.postProcessVnfAdapter(execution); assertNull(volumeGroup.getHeatStackId()); } @@ -246,7 +246,7 @@ public class VnfAdapterImplTest extends BaseTaskTest { @Test public void postProcessVnfAdapter_DeleteResponseTest_DeleteVolumeGroup() { volumeGroup.setHeatStackId(TEST_VOLUME_HEATSTACK_ID); - execution.setVariable("vnfAdapterRestV1Response", VNF_ADAPTER_VOLUME_DELETE_RESPONSE); + execution.setVariable("WorkflowResponse", VNF_ADAPTER_VOLUME_DELETE_RESPONSE); vnfAdapterImpl.postProcessVnfAdapter(execution); assertNull(volumeGroup.getHeatStackId()); } @@ -255,7 +255,7 @@ public class VnfAdapterImplTest extends BaseTaskTest { @Test public void postProcessVnfAdapter_DeleteResponseTest_VolumeGroupDeletedFalse() { volumeGroup.setHeatStackId(TEST_VOLUME_HEATSTACK_ID); - execution.setVariable("vnfAdapterRestV1Response", + execution.setVariable("WorkflowResponse", "false"); vnfAdapterImpl.postProcessVnfAdapter(execution); assertEquals(TEST_VOLUME_HEATSTACK_ID, volumeGroup.getHeatStackId()); @@ -264,14 +264,14 @@ public class VnfAdapterImplTest extends BaseTaskTest { @Test public void postProcessVnfAdapter_DeleteResponseTest_EmptyDeleteVolumeGroupResponseTag() { expectedException.expect(BpmnError.class); - execution.setVariable("vnfAdapterRestV1Response", ""); + execution.setVariable("WorkflowResponse", ""); vnfAdapterImpl.postProcessVnfAdapter(execution); } @Test public void postProcessVnfAdapter_DeleteResponseTest_EmptyVolumeGroupDeletedTag() { volumeGroup.setHeatStackId(TEST_VOLUME_HEATSTACK_ID); - execution.setVariable("vnfAdapterRestV1Response", ""); + execution.setVariable("WorkflowResponse", ""); vnfAdapterImpl.postProcessVnfAdapter(execution); assertEquals(TEST_VOLUME_HEATSTACK_ID, volumeGroup.getHeatStackId()); } @@ -281,7 +281,7 @@ public class VnfAdapterImplTest extends BaseTaskTest { doThrow(RuntimeException.class).when(extractPojosForBB).extractByKey(any(), ArgumentMatchers.eq(ResourceKey.VF_MODULE_ID)); - execution.setVariable("vnfAdapterRestV1Response", VNF_ADAPTER_REST_CREATE_RESPONSE); + execution.setVariable("WorkflowResponse", VNF_ADAPTER_REST_CREATE_RESPONSE); expectedException.expect(BpmnError.class); vnfAdapterImpl.postProcessVnfAdapter(execution); diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/adapter/network/mapper/NetworkAdapterObjectMapperTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/adapter/network/mapper/NetworkAdapterObjectMapperTest.java index 109dc55294..ccd4376a10 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/adapter/network/mapper/NetworkAdapterObjectMapperTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/adapter/network/mapper/NetworkAdapterObjectMapperTest.java @@ -7,9 +7,9 @@ * 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. diff --git a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/adapter/vnf/mapper/VnfAdapterObjectMapperTest.java b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/adapter/vnf/mapper/VnfAdapterObjectMapperTest.java index a482da5158..9dfc245f68 100644 --- a/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/adapter/vnf/mapper/VnfAdapterObjectMapperTest.java +++ b/bpmn/so-bpmn-tasks/src/test/java/org/onap/so/client/adapter/vnf/mapper/VnfAdapterObjectMapperTest.java @@ -7,9 +7,9 @@ * 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. diff --git a/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/NetworkMapper/createNetworkRequest.json b/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/NetworkMapper/createNetworkRequest.json index 19d42dddb9..4c97dbc53c 100644 --- a/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/NetworkMapper/createNetworkRequest.json +++ b/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/NetworkMapper/createNetworkRequest.json @@ -19,7 +19,7 @@ "allocationPools": [{ "start": "107.244.64.2", "end": "107.244.64.16" - }] + }] } ], "providerVlanNetwork": { diff --git a/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/VnfAndVfModuleMapper/vnfAdapterCreateVfModuleAddonRequest.json b/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/VnfAndVfModuleMapper/vnfAdapterCreateVfModuleAddonRequest.json index b57c8341f1..3ba5627b38 100644 --- a/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/VnfAndVfModuleMapper/vnfAdapterCreateVfModuleAddonRequest.json +++ b/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/VnfAndVfModuleMapper/vnfAdapterCreateVfModuleAddonRequest.json @@ -14,13 +14,13 @@ "backout": false, "failIfExists": false, "enableBridge": true, - "msoRequest": + "msoRequest": { "requestId": "requestId", "serviceInstanceId": "serviceInstanceId" }, - "vfModuleParams": + "vfModuleParams": { "vnf_id": "vnfId", "vnf_name": "vnfName", diff --git a/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/VnfAndVfModuleMapper/vnfAdapterCreateVfModuleRequestWithCloudResources.json b/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/VnfAndVfModuleMapper/vnfAdapterCreateVfModuleRequestWithCloudResources.json index da826b8a89..3fbf026176 100644 --- a/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/VnfAndVfModuleMapper/vnfAdapterCreateVfModuleRequestWithCloudResources.json +++ b/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/VnfAndVfModuleMapper/vnfAdapterCreateVfModuleRequestWithCloudResources.json @@ -12,13 +12,13 @@ "backout": false, "failIfExists": false, "enableBridge": true, - "msoRequest": + "msoRequest": { "requestId": "requestId", "serviceInstanceId": "serviceInstanceId" }, - "vfModuleParams": + "vfModuleParams": { "environment_context": "environmentContext", "key1": "value1", diff --git a/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/VnfAndVfModuleMapper/vnfAdapterCreateVfModuleWithVolumeGroupRequest.json b/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/VnfAndVfModuleMapper/vnfAdapterCreateVfModuleWithVolumeGroupRequest.json index 54f6e403ed..9f554490bd 100644 --- a/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/VnfAndVfModuleMapper/vnfAdapterCreateVfModuleWithVolumeGroupRequest.json +++ b/bpmn/so-bpmn-tasks/src/test/resources/__files/BuildingBlocks/VnfAndVfModuleMapper/vnfAdapterCreateVfModuleWithVolumeGroupRequest.json @@ -14,13 +14,13 @@ "backout": false, "failIfExists": false, "enableBridge": true, - "msoRequest": + "msoRequest": { "requestId": "requestId", "serviceInstanceId": "serviceInstanceId" }, - "vfModuleParams": + "vfModuleParams": { "vnf_id": "vnfId", "vnf_name": "vnfName", diff --git a/common/src/main/java/org/onap/so/externaltasks/logging/AuditMDCSetup.java b/common/src/main/java/org/onap/so/externaltasks/logging/AuditMDCSetup.java deleted file mode 100644 index 9f71e61e1f..0000000000 --- a/common/src/main/java/org/onap/so/externaltasks/logging/AuditMDCSetup.java +++ /dev/null @@ -1,56 +0,0 @@ -package org.onap.so.externaltasks.logging; - -import java.time.ZoneOffset; -import java.time.ZonedDateTime; -import java.time.format.DateTimeFormatter; -import org.camunda.bpm.client.task.ExternalTask; -import org.onap.logging.filter.base.MDCSetup; -import org.onap.logging.filter.base.ONAPComponents; -import org.onap.logging.ref.slf4j.ONAPLogConstants; -import org.onap.so.logger.MdcConstants; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.slf4j.MDC; -import org.springframework.stereotype.Component; - -@Component -public class AuditMDCSetup { - - private static final Logger logger = LoggerFactory.getLogger(AuditMDCSetup.class); - - private MDCSetup mdcSetup = new MDCSetup(); - - public void setupMDC(ExternalTask externalTask) { - MDC.put(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP, - ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ISO_INSTANT)); - String msoRequestId = externalTask.getVariable("mso-request-id"); - if (msoRequestId != null && !msoRequestId.isEmpty()) { - MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, msoRequestId); - } - MDC.put(ONAPLogConstants.MDCs.SERVICE_NAME, externalTask.getTopicName()); - MDC.put(ONAPLogConstants.MDCs.PARTNER_NAME, ONAPComponents.OPENSTACK_ADAPTER.toString()); - setResponseCode(ONAPLogConstants.ResponseStatus.INPROGRESS.toString()); - setElapsedTime(); - mdcSetup.setServerFQDN(); - logger.info(ONAPLogConstants.Markers.ENTRY, "Entering"); - } - - public void setElapsedTime() { - DateTimeFormatter timeFormatter = DateTimeFormatter.ISO_ZONED_DATE_TIME; - MDC.put(ONAPLogConstants.MDCs.ELAPSED_TIME, Long.toString(System.currentTimeMillis() - ZonedDateTime - .parse(MDC.get(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP), timeFormatter).toInstant().toEpochMilli())); - } - - public void setResponseCode(String code) { - MDC.put(MdcConstants.OPENSTACK_STATUS_CODE, code); - MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, code); - } - - public void clearClientMDCs() { - MDC.remove(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE); - MDC.remove(MdcConstants.OPENSTACK_STATUS_CODE); - MDC.remove(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP); - MDC.remove(ONAPLogConstants.MDCs.ELAPSED_TIME); - MDC.remove(ONAPLogConstants.MDCs.PARTNER_NAME); - } -} diff --git a/common/src/main/java/org/onap/so/logging/tasks/AuditMDCSetup.java b/common/src/main/java/org/onap/so/logging/tasks/AuditMDCSetup.java new file mode 100644 index 0000000000..8d98307a43 --- /dev/null +++ b/common/src/main/java/org/onap/so/logging/tasks/AuditMDCSetup.java @@ -0,0 +1,57 @@ +package org.onap.so.logging.tasks; + +import java.time.ZoneOffset; +import java.time.ZonedDateTime; +import java.time.format.DateTimeFormatter; +import org.camunda.bpm.client.task.ExternalTask; +import org.onap.logging.filter.base.MDCSetup; +import org.onap.logging.filter.base.ONAPComponents; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.onap.so.logger.MdcConstants; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.slf4j.MDC; +import org.springframework.stereotype.Component; + +@Component +public class AuditMDCSetup { + + private static final Logger logger = LoggerFactory.getLogger(AuditMDCSetup.class); + + private MDCSetup mdcSetup = new MDCSetup(); + + public void setupMDC(ExternalTask externalTask) { + MDC.put(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP, + ZonedDateTime.now(ZoneOffset.UTC).format(DateTimeFormatter.ISO_INSTANT)); + String msoRequestId = externalTask.getVariable("mso-request-id"); + if (msoRequestId != null && !msoRequestId.isEmpty()) { + MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, msoRequestId); + } + MDC.put(ONAPLogConstants.MDCs.SERVICE_NAME, externalTask.getTopicName()); + MDC.put(ONAPLogConstants.MDCs.PARTNER_NAME, ONAPComponents.OPENSTACK_ADAPTER.toString()); + setResponseCode(ONAPLogConstants.ResponseStatus.INPROGRESS.toString()); + setElapsedTime(); + mdcSetup.setServerFQDN(); + logger.info(ONAPLogConstants.Markers.ENTRY, "Entering"); + } + + public void setElapsedTime() { + DateTimeFormatter timeFormatter = DateTimeFormatter.ISO_ZONED_DATE_TIME; + MDC.put(ONAPLogConstants.MDCs.ELAPSED_TIME, Long.toString(System.currentTimeMillis() - ZonedDateTime + .parse(MDC.get(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP), timeFormatter).toInstant().toEpochMilli())); + } + + public void setResponseCode(String code) { + MDC.put(MdcConstants.OPENSTACK_STATUS_CODE, code); + MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, code); + } + + public void clearClientMDCs() { + MDC.remove(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE); + MDC.remove(MdcConstants.OPENSTACK_STATUS_CODE); + MDC.remove(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP); + MDC.remove(ONAPLogConstants.MDCs.ELAPSED_TIME); + MDC.remove(ONAPLogConstants.MDCs.PARTNER_NAME); + } + +} diff --git a/common/src/main/java/org/onap/so/utils/ExternalTaskServiceUtils.java b/common/src/main/java/org/onap/so/utils/ExternalTaskServiceUtils.java index 035ad1dc81..840a978a61 100644 --- a/common/src/main/java/org/onap/so/utils/ExternalTaskServiceUtils.java +++ b/common/src/main/java/org/onap/so/utils/ExternalTaskServiceUtils.java @@ -51,7 +51,12 @@ public class ExternalTaskServiceUtils { } public int getMaxClients() { - return Integer.parseInt(env.getProperty("workflow.topics.maxClients", "3")); + return Integer.parseInt(env.getProperty("workflow.topics.maxClients", "10")); + } + + public Long getLockDuration() { + Long lockDuration = Long.parseLong(env.getProperty("mso.audit.lock-time", "60000")); + return lockDuration; } @ScheduledLogging diff --git a/common/src/main/java/org/onap/so/utils/ExternalTaskUtils.java b/common/src/main/java/org/onap/so/utils/ExternalTaskUtils.java index 9488187003..d414135570 100644 --- a/common/src/main/java/org/onap/so/utils/ExternalTaskUtils.java +++ b/common/src/main/java/org/onap/so/utils/ExternalTaskUtils.java @@ -9,11 +9,11 @@ import org.springframework.stereotype.Component; @Component public abstract class ExternalTaskUtils { + private static final Logger logger = LoggerFactory.getLogger(ExternalTaskUtils.class); + @Autowired Environment env; - private static final Logger logger = LoggerFactory.getLogger(ExternalTaskUtils.class); - private final RetrySequenceLevel retrySequenceLevel; public ExternalTaskUtils() { @@ -49,7 +49,7 @@ public abstract class ExternalTaskUtils { return seqInter; case LONG: String[] seqLong = {"1", "1", "2", "3", "5", "8", "13", "20"}; - if (env.getProperty("mso.workflow.topics.retrySequence") != null) { + if (env.getProperty("mso.workflow.topics.retrySequence.long") != null) { seqLong = env.getProperty("mso.workflow.topics.retrySequence", String[].class); } return seqLong; diff --git a/common/src/test/java/org/onap/so/externaltasks/logging/AuditMDCSetupTest.java b/common/src/test/java/org/onap/so/externaltasks/logging/AuditMDCSetupTest.java deleted file mode 100644 index c4609f0336..0000000000 --- a/common/src/test/java/org/onap/so/externaltasks/logging/AuditMDCSetupTest.java +++ /dev/null @@ -1,93 +0,0 @@ -package org.onap.so.externaltasks.logging; - -import static org.junit.Assert.assertEquals; -import static org.junit.Assert.assertNotNull; -import static org.junit.Assert.assertNull; -import static org.mockito.Mockito.doReturn; -import org.camunda.bpm.client.task.ExternalTask; -import org.junit.After; -import org.junit.Test; -import org.junit.runner.RunWith; -import org.mockito.InjectMocks; -import org.mockito.Mock; -import org.mockito.Spy; -import org.mockito.junit.MockitoJUnitRunner; -import org.onap.logging.filter.base.MDCSetup; -import org.onap.logging.ref.slf4j.ONAPLogConstants; -import org.onap.so.logger.MdcConstants; -import org.slf4j.MDC; - -@RunWith(MockitoJUnitRunner.class) -public class AuditMDCSetupTest { - - @Mock - private ExternalTask externalTask; - - @Mock - private MDCSetup mdcSet; - - @Spy - @InjectMocks - private AuditMDCSetup mdcSetup; - - private String requestId = "9bb86b8d-a02f-4a0b-81a9-2eb963850009"; - private String serviceName = "testServiceName"; - - @After - public void tearDown() { - MDC.clear(); - } - - @Test - public void setupMDCTest() { - doReturn(requestId).when(externalTask).getVariable("mso-request-id"); - doReturn(serviceName).when(externalTask).getTopicName(); - - mdcSetup.setupMDC(externalTask); - - assertNotNull(MDC.get(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP)); - assertEquals(requestId, MDC.get(ONAPLogConstants.MDCs.REQUEST_ID)); - assertEquals(serviceName, MDC.get(ONAPLogConstants.MDCs.SERVICE_NAME)); - assertEquals("SO.OPENSTACK_ADAPTER", MDC.get(ONAPLogConstants.MDCs.PARTNER_NAME)); - assertEquals(ONAPLogConstants.ResponseStatus.INPROGRESS.toString(), - MDC.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE)); - } - - @Test - public void setElapsedTimeTest() { - MDC.put(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP, "2019-06-18T02:09:06.024Z"); - - mdcSetup.setElapsedTime(); - - assertNotNull(MDC.get(ONAPLogConstants.MDCs.ELAPSED_TIME)); - } - - @Test - public void setResponseCodeTest() { - mdcSetup.setResponseCode(ONAPLogConstants.ResponseStatus.INPROGRESS.toString()); - - assertEquals(ONAPLogConstants.ResponseStatus.INPROGRESS.toString(), - MDC.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE)); - assertEquals(ONAPLogConstants.ResponseStatus.INPROGRESS.toString(), - MDC.get(MdcConstants.OPENSTACK_STATUS_CODE)); - } - - @Test - public void clearClientMDCsTest() { - MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, ONAPLogConstants.ResponseStatus.INPROGRESS.toString()); - MDC.put(MdcConstants.OPENSTACK_STATUS_CODE, ONAPLogConstants.ResponseStatus.INPROGRESS.toString()); - MDC.put(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP, "2019-06-18T02:09:06.024Z"); - MDC.put(ONAPLogConstants.MDCs.ELAPSED_TIME, "318"); - MDC.put(ONAPLogConstants.MDCs.PARTNER_NAME, "SO.OPENSTACK_ADAPTER"); - - mdcSetup.clearClientMDCs(); - - assertNull(MDC.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE)); - assertNull(MDC.get(MdcConstants.OPENSTACK_STATUS_CODE)); - assertNull(MDC.get(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP)); - assertNull(MDC.get(ONAPLogConstants.MDCs.ELAPSED_TIME)); - assertNull(MDC.get(ONAPLogConstants.MDCs.PARTNER_NAME)); - - } - -} diff --git a/common/src/test/java/org/onap/so/logging/tasks/MDCSetupTest.java b/common/src/test/java/org/onap/so/logging/tasks/MDCSetupTest.java new file mode 100644 index 0000000000..929db79910 --- /dev/null +++ b/common/src/test/java/org/onap/so/logging/tasks/MDCSetupTest.java @@ -0,0 +1,92 @@ +package org.onap.so.logging.tasks; + +import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotNull; +import static org.junit.Assert.assertNull; +import static org.mockito.Mockito.doReturn; +import org.camunda.bpm.client.task.ExternalTask; +import org.junit.After; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Spy; +import org.onap.logging.ref.slf4j.ONAPLogConstants; +import org.onap.so.logger.MdcConstants; +import org.slf4j.MDC; +import org.mockito.junit.MockitoJUnitRunner; + +@RunWith(MockitoJUnitRunner.class) +public class MDCSetupTest { + + @Mock + private org.onap.logging.filter.base.MDCSetup mdcSet; + + @Mock + private ExternalTask externalTask; + + private String requestId = "9bb86b8d-a02f-4a0b-81a9-2eb963850009"; + private String serviceName = "testServiceName"; + + @Spy + @InjectMocks + AuditMDCSetup setup = new AuditMDCSetup(); + + @After + public void tearDown() { + MDC.clear(); + } + + @Test + public void setupMDCTest() { + doReturn(requestId).when(externalTask).getVariable("mso-request-id"); + doReturn(serviceName).when(externalTask).getTopicName(); + + setup.setupMDC(externalTask); + + assertNotNull(MDC.get(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP)); + assertEquals(requestId, MDC.get(ONAPLogConstants.MDCs.REQUEST_ID)); + assertEquals(serviceName, MDC.get(ONAPLogConstants.MDCs.SERVICE_NAME)); + assertEquals("SO.OPENSTACK_ADAPTER", MDC.get(ONAPLogConstants.MDCs.PARTNER_NAME)); + assertEquals(ONAPLogConstants.ResponseStatus.INPROGRESS.toString(), + MDC.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE)); + } + + @Test + public void setElapsedTimeTest() { + MDC.put(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP, "2019-06-18T02:09:06.024Z"); + + setup.setElapsedTime(); + + assertNotNull(MDC.get(ONAPLogConstants.MDCs.ELAPSED_TIME)); + } + + @Test + public void setResponseCodeTest() { + setup.setResponseCode(ONAPLogConstants.ResponseStatus.INPROGRESS.toString()); + + assertEquals(ONAPLogConstants.ResponseStatus.INPROGRESS.toString(), + MDC.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE)); + assertEquals(ONAPLogConstants.ResponseStatus.INPROGRESS.toString(), + MDC.get(MdcConstants.OPENSTACK_STATUS_CODE)); + } + + @Test + public void clearClientMDCsTest() { + MDC.put(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE, ONAPLogConstants.ResponseStatus.INPROGRESS.toString()); + MDC.put(MdcConstants.OPENSTACK_STATUS_CODE, ONAPLogConstants.ResponseStatus.INPROGRESS.toString()); + MDC.put(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP, "2019-06-18T02:09:06.024Z"); + MDC.put(ONAPLogConstants.MDCs.ELAPSED_TIME, "318"); + MDC.put(ONAPLogConstants.MDCs.PARTNER_NAME, "SO.OPENSTACK_ADAPTER"); + + setup.clearClientMDCs(); + + assertNull(MDC.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE)); + assertNull(MDC.get(MdcConstants.OPENSTACK_STATUS_CODE)); + assertNull(MDC.get(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP)); + assertNull(MDC.get(ONAPLogConstants.MDCs.ELAPSED_TIME)); + assertNull(MDC.get(ONAPLogConstants.MDCs.PARTNER_NAME)); + + } + +} diff --git a/common/src/test/java/org/onap/so/utils/ExternalTaskUtilsTest.java b/common/src/test/java/org/onap/so/utils/ExternalTaskUtilsTest.java index e27caa6458..6c2dbb666c 100644 --- a/common/src/test/java/org/onap/so/utils/ExternalTaskUtilsTest.java +++ b/common/src/test/java/org/onap/so/utils/ExternalTaskUtilsTest.java @@ -1,17 +1,22 @@ package org.onap.so.utils; import static org.junit.Assert.assertEquals; +import org.camunda.bpm.client.task.ExternalTask; import org.junit.Test; import org.junit.runner.RunWith; import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; +import org.mockito.Spy; import org.mockito.junit.MockitoJUnitRunner; import org.springframework.core.env.Environment; @RunWith(MockitoJUnitRunner.class) public class ExternalTaskUtilsTest { + @Mock + private ExternalTask externalTask; + @Mock private Environment mockenv; diff --git a/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/QueryStackByIdDoubleFailure.java b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/QueryStackByIdDoubleFailure.java index 2311c4c44e..2fa8725d56 100644 --- a/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/QueryStackByIdDoubleFailure.java +++ b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/QueryStackByIdDoubleFailure.java @@ -17,10 +17,11 @@ public class QueryStackByIdDoubleFailure extends AbstractSimulatorScenario { @Override public void run(ScenarioDesigner scenario) { - // Get to see if stack exists + // Create Poll Service + scenario.scenarioEndpoint().getEndpointConfiguration().setTimeout(300000L); scenario.http().receive().get().extractFromHeader(DynamicEndpointUriResolver.REQUEST_PATH_HEADER_NAME, "correlationId"); - scenario.echo("${correlationId}"); + scenario.echo("${correlationId}"); // step 2 scenario.correlation().start().onHeader(DynamicEndpointUriResolver.REQUEST_PATH_HEADER_NAME, "${correlationId}"); @@ -30,20 +31,63 @@ public class QueryStackByIdDoubleFailure extends AbstractSimulatorScenario { scenario.variable("tenantId", "872f331350c54e59991a8de2cbffb40c"); scenario.variable("vServerId", "d29f3151-592d-4011-9356-ad047794e236"); scenario.variable("stack_failure_message", "The Flavor ID (nd.c6r16d20) could not be found."); + scenario.http().send().response(HttpStatus.OK) // step 4 + .payload(new ClassPathResource("openstack/gr_api/Stack_Failure.json")); + + // Create Poll Retry + scenario.http().receive().get(); // step 5 + scenario.http().send().response(HttpStatus.OK) + .payload(new ClassPathResource("openstack/gr_api/Stack_Failure.json")); + + // Rollback Delete of the stack + scenario.http().receive().delete(); // step 7 + scenario.action(new DeleteVServers()); + scenario.http().send().response(HttpStatus.NO_CONTENT); + + // Rollback Poll + scenario.http().receive().get(); // step 10 scenario.http().send().response(HttpStatus.OK) .payload(new ClassPathResource("openstack/gr_api/Stack_Failure.json")); + // Rollback Poll Retry + scenario.http().receive().get(); + scenario.http().send().response(HttpStatus.OK) + .payload(new ClassPathResource("openstack/gr_api/Stack_Failure.json")); + + // Create Poll + scenario.http().receive().get(); // step 14 + scenario.http().send().response(HttpStatus.OK) + .payload(new ClassPathResource("openstack/gr_api/Stack_Failure.json")); - // Delete of the stack + // Create Poll Retry + scenario.http().receive().get(); + scenario.http().send().response(HttpStatus.OK) + .payload(new ClassPathResource("openstack/gr_api/Stack_Failure.json")); + + // Rollback Delete scenario.http().receive().delete(); scenario.action(new DeleteVServers()); scenario.http().send().response(HttpStatus.NO_CONTENT); - // Poll Deletion of stack for status + // Rollback Poll + scenario.http().receive().get(); // step 18 + scenario.http().send().response(HttpStatus.OK) + .payload(new ClassPathResource("openstack/gr_api/Stack_Failure.json")); + + // Rollback Poll Retry scenario.http().receive().get(); scenario.http().send().response(HttpStatus.OK) .payload(new ClassPathResource("openstack/gr_api/Stack_Failure.json")); + // Delete + scenario.http().receive().delete(); + scenario.http().send().response(HttpStatus.NO_CONTENT); + + // Delete Poll + scenario.http().receive().get(); + scenario.http().send().response(HttpStatus.OK) + .payload(new ClassPathResource("openstack/gr_api/Stack_Deleted.json")); + } } diff --git a/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/QueryStackByIdFailure.java b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/QueryStackByIdFailure.java index 4d0d578831..7f995f2930 100644 --- a/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/QueryStackByIdFailure.java +++ b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/QueryStackByIdFailure.java @@ -3,8 +3,6 @@ package org.onap.so.simulator.scenarios.openstack; import org.springframework.core.io.ClassPathResource; import org.springframework.http.HttpStatus; import org.springframework.web.bind.annotation.RequestMapping; -import org.springframework.web.bind.annotation.RequestMethod; -import org.onap.so.simulator.actions.aai.DeleteVServers; import com.consol.citrus.endpoint.resolver.DynamicEndpointUriResolver; import com.consol.citrus.simulator.scenario.AbstractSimulatorScenario; import com.consol.citrus.simulator.scenario.Scenario; @@ -17,7 +15,9 @@ public class QueryStackByIdFailure extends AbstractSimulatorScenario { @Override public void run(ScenarioDesigner scenario) { - // Get to see if stack exists + scenario.scenarioEndpoint().getEndpointConfiguration().setTimeout(300000L); + + // Create Poll scenario.http().receive().get().extractFromHeader(DynamicEndpointUriResolver.REQUEST_PATH_HEADER_NAME, "correlationId"); scenario.echo("${correlationId}"); @@ -33,13 +33,13 @@ public class QueryStackByIdFailure extends AbstractSimulatorScenario { scenario.http().send().response(HttpStatus.OK) .payload(new ClassPathResource("openstack/gr_api/Stack_Failure.json")); + // Create Poll Retry + scenario.http().receive().get(); + scenario.http().send().response(HttpStatus.OK) + .payload(new ClassPathResource("openstack/gr_api/Stack_Failure.json")); - // Delete of the stack - scenario.http().receive().delete(); - scenario.action(new DeleteVServers()); - scenario.http().send().response(HttpStatus.NO_CONTENT); - // Poll Deletion of stack for status + // Rollback Poll scenario.http().receive().get(); scenario.http().send().response(HttpStatus.OK) .payload(new ClassPathResource("openstack/gr_api/Stack_Deleted.json")); diff --git a/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/macro/QueryStackByIdMacro1.java b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/macro/QueryStackByIdMacro1.java index ba6a1a1185..c8c81ebecf 100644 --- a/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/macro/QueryStackByIdMacro1.java +++ b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/macro/QueryStackByIdMacro1.java @@ -9,6 +9,10 @@ import com.consol.citrus.simulator.scenario.AbstractSimulatorScenario; import com.consol.citrus.simulator.scenario.Scenario; import com.consol.citrus.simulator.scenario.ScenarioDesigner; +/** + * This scenario is used by the following test cases: Resume Service Instance Macro 3 Modules 1 To Complete + * + */ @Scenario("Openstack-QueryStackByID-Macro1") @RequestMapping(value = "/sim/mockPublicUrl/stacks/macro_module_1/*", method = RequestMethod.GET) public class QueryStackByIdMacro1 extends AbstractSimulatorScenario { @@ -16,6 +20,9 @@ public class QueryStackByIdMacro1 extends AbstractSimulatorScenario { @Override public void run(ScenarioDesigner scenario) { + scenario.scenarioEndpoint().getEndpointConfiguration().setTimeout(300000L); + + // Poll scenario.http().receive().get().extractFromHeader(DynamicEndpointUriResolver.REQUEST_PATH_HEADER_NAME, "correlationId"); scenario.echo("${correlationId}"); @@ -27,8 +34,33 @@ public class QueryStackByIdMacro1 extends AbstractSimulatorScenario { scenario.http().send().response(HttpStatus.OK) .payload(new ClassPathResource("openstack/gr_api/Stack_Created.json")); + // Create (module_2) + scenario.http().receive().get(); + scenario.http().send().response(HttpStatus.OK) + .payload(new ClassPathResource("openstack/gr_api/Stack_Created.json")); + + // Create (module_3) + scenario.http().receive().get(); + scenario.http().send().response(HttpStatus.OK) + .payload(new ClassPathResource("openstack/gr_api/Stack_Created.json")); + + // Create (module_2 recreate) + scenario.http().receive().get(); + scenario.http().send().response(HttpStatus.OK) + .payload(new ClassPathResource("openstack/gr_api/Stack_Created.json")); + + // Delete + scenario.http().receive().get(); + scenario.http().send().response(HttpStatus.OK) + .payload(new ClassPathResource("openstack/gr_api/Stack_Deleted.json")); + + // Delete scenario.http().receive().get(); + scenario.http().send().response(HttpStatus.OK) + .payload(new ClassPathResource("openstack/gr_api/Stack_Deleted.json")); + // Poll + scenario.http().receive().get(); scenario.http().send().response(HttpStatus.OK) .payload(new ClassPathResource("openstack/gr_api/Stack_Deleted.json")); } diff --git a/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/macro/QueryStackByIdMacro2.java b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/macro/QueryStackByIdMacro2.java index efd420486d..aca5fe8194 100644 --- a/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/macro/QueryStackByIdMacro2.java +++ b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/macro/QueryStackByIdMacro2.java @@ -9,6 +9,10 @@ import com.consol.citrus.simulator.scenario.AbstractSimulatorScenario; import com.consol.citrus.simulator.scenario.Scenario; import com.consol.citrus.simulator.scenario.ScenarioDesigner; +/** + * This scenario is used by the following test cases: Resume Service Instance Macro 3 Modules 1 To Complete + * + */ @Scenario("Openstack-QueryStackByID-Macro2") @RequestMapping(value = "/sim/mockPublicUrl/stacks/macro_module_2/*", method = RequestMethod.GET) public class QueryStackByIdMacro2 extends AbstractSimulatorScenario { @@ -16,6 +20,9 @@ public class QueryStackByIdMacro2 extends AbstractSimulatorScenario { @Override public void run(ScenarioDesigner scenario) { + scenario.scenarioEndpoint().getEndpointConfiguration().setTimeout(300000L); + + // Poll scenario.http().receive().get().extractFromHeader(DynamicEndpointUriResolver.REQUEST_PATH_HEADER_NAME, "correlationId"); scenario.echo("${correlationId}"); @@ -27,11 +34,19 @@ public class QueryStackByIdMacro2 extends AbstractSimulatorScenario { scenario.http().send().response(HttpStatus.OK) .payload(new ClassPathResource("openstack/gr_api/Stack_Created.json")); + // Delete scenario.http().receive().get(); + scenario.http().send().response(HttpStatus.OK) + .payload(new ClassPathResource("openstack/gr_api/Stack_Created.json")); + scenario.http().receive().get(); scenario.http().send().response(HttpStatus.OK) .payload(new ClassPathResource("openstack/gr_api/Stack_Deleted.json")); + // Poll + scenario.http().receive().get(); + scenario.http().send().response(HttpStatus.OK) + .payload(new ClassPathResource("openstack/gr_api/Stack_Deleted.json")); } } diff --git a/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/macro/QueryStackByIdMacro3.java b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/macro/QueryStackByIdMacro3.java index 4d3ba8697a..9fc6fafdb3 100644 --- a/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/macro/QueryStackByIdMacro3.java +++ b/so-simulator/src/main/java/org/onap/so/simulator/scenarios/openstack/macro/QueryStackByIdMacro3.java @@ -9,6 +9,10 @@ import com.consol.citrus.simulator.scenario.AbstractSimulatorScenario; import com.consol.citrus.simulator.scenario.Scenario; import com.consol.citrus.simulator.scenario.ScenarioDesigner; +/** + * This scenario is used by the following test cases: Resume Service Instance Macro 3 Modules 1 To Complete + * + */ @Scenario("Openstack-QueryStackByID-Macro3") @RequestMapping(value = "/sim/mockPublicUrl/stacks/macro_module_3/*", method = RequestMethod.GET) public class QueryStackByIdMacro3 extends AbstractSimulatorScenario { @@ -16,6 +20,8 @@ public class QueryStackByIdMacro3 extends AbstractSimulatorScenario { @Override public void run(ScenarioDesigner scenario) { + scenario.scenarioEndpoint().getEndpointConfiguration().setTimeout(300000L); + scenario.http().receive().get().extractFromHeader(DynamicEndpointUriResolver.REQUEST_PATH_HEADER_NAME, "correlationId"); scenario.echo("${correlationId}"); @@ -24,11 +30,21 @@ public class QueryStackByIdMacro3 extends AbstractSimulatorScenario { scenario.variable("stackName", "macro_module_3"); + // Poll + scenario.http().send().response(HttpStatus.OK) + .payload(new ClassPathResource("openstack/gr_api/Stack_Created.json")); + + // Delete + scenario.http().receive().get(); scenario.http().send().response(HttpStatus.OK) .payload(new ClassPathResource("openstack/gr_api/Stack_Created.json")); scenario.http().receive().get(); + scenario.http().send().response(HttpStatus.OK) + .payload(new ClassPathResource("openstack/gr_api/Stack_Deleted.json")); + // Poll + scenario.http().receive().get(); scenario.http().send().response(HttpStatus.OK) .payload(new ClassPathResource("openstack/gr_api/Stack_Deleted.json")); -- cgit 1.2.3-korg