diff options
Diffstat (limited to 'adapters')
56 files changed, 682 insertions, 1123 deletions
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/utils/MsoCloudifyUtils.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/utils/MsoCloudifyUtils.java index f1c42bb4a5..d7bc22aa7c 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/utils/MsoCloudifyUtils.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/cloudify/utils/MsoCloudifyUtils.java @@ -419,7 +419,11 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin { logger.debug("pollTimeout remaining: " + pollTimeout); execution = queryExecution.execute(); - status = execution.getStatus(); + if (execution != null) { + status = execution.getStatus(); + } else { + status = TERMINATED; + } } // Broke the loop. Check again for a terminal state @@ -562,7 +566,7 @@ public class MsoCloudifyUtils extends MsoCommonUtils implements VduPlugin { Executions executions = listExecutions.execute(); // If no executions, does this give NOT_FOUND or empty set? - if (executions.getItems().isEmpty()) { + if (executions == null || executions.getItems().isEmpty()) { return new DeploymentInfoBuilder().withId(deployment.getId()) .withDeploymentInputs(deployment.getInputs()).build(); } else { 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 b5a97f7559..75a8ca0593 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 @@ -89,6 +89,10 @@ import com.woorea.openstack.heat.model.Stacks; @Component public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin { + private static final String CREATE_FAILED = "CREATE_FAILED"; + + private static final String DELETE_FAILED = "DELETE_FAILED"; + private static final String CREATE_COMPLETE = "CREATE_COMPLETE"; private static final String DELETE_COMPLETE = "DELETE_COMPLETE"; @@ -133,42 +137,7 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin { private static final ObjectMapper JSON_MAPPER = new ObjectMapper(); - /** - * keep this old method signature here to maintain backwards compatibility. keep others as well. this method does - * not include environment, files, or heatFiles - */ - public StackInfo createStack(String cloudSiteId, String cloudOwner, String tenantId, String stackName, - String heatTemplate, Map<String, ?> stackInputs, boolean pollForCompletion, int timeoutMinutes) - throws MsoException { - // Just call the new method with the environment & files variable set to null - return this.createStack(cloudSiteId, cloudOwner, tenantId, stackName, null, heatTemplate, stackInputs, - pollForCompletion, timeoutMinutes, null, null, null, true); - } - - // This method has environment, but not files or heatFiles - public StackInfo createStack(String cloudSiteId, String cloudOwner, String tenantId, String stackName, - String heatTemplate, Map<String, ?> stackInputs, boolean pollForCompletion, int timeoutMinutes, - String environment) throws MsoException { - // Just call the new method with the files/heatFiles variables set to null - return this.createStack(cloudSiteId, cloudOwner, tenantId, stackName, null, heatTemplate, stackInputs, - pollForCompletion, timeoutMinutes, environment, null, null, true); - } - - // This method has environment and files, but not heatFiles. - public StackInfo createStack(String cloudSiteId, String cloudOwner, String tenantId, String stackName, - String heatTemplate, Map<String, ?> stackInputs, boolean pollForCompletion, int timeoutMinutes, - String environment, Map<String, Object> files) throws MsoException { - return this.createStack(cloudSiteId, cloudOwner, tenantId, stackName, null, heatTemplate, stackInputs, - pollForCompletion, timeoutMinutes, environment, files, null, true); - } - // This method has environment, files, heatfiles - public StackInfo createStack(String cloudSiteId, String cloudOwner, String tenantId, String stackName, - String heatTemplate, Map<String, ?> stackInputs, boolean pollForCompletion, int timeoutMinutes, - String environment, Map<String, Object> files, Map<String, Object> heatFiles) throws MsoException { - return this.createStack(cloudSiteId, cloudOwner, tenantId, stackName, null, heatTemplate, stackInputs, - pollForCompletion, timeoutMinutes, environment, files, heatFiles, true); - } /** * Create a new Stack in the specified cloud location and tenant. The Heat template and parameter map are passed in @@ -211,20 +180,50 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin { @SuppressWarnings("unchecked") public StackInfo createStack(String cloudSiteId, String cloudOwner, String tenantId, String stackName, VduModelInfo vduModel, String heatTemplate, Map<String, ?> stackInputs, boolean pollForCompletion, - int timeoutMinutes, String environment, Map<String, Object> files, Map<String, Object> heatFiles, - boolean backout) throws MsoException { - + int timeoutMinutes, String environment, Map<String, Object> nestedTemplates, Map<String, Object> heatFiles, + boolean backout, boolean failIfExists) throws MsoException { stripMultiCloudInputs(stackInputs); - CreateStackParam createStack = - createStackParam(stackName, heatTemplate, stackInputs, timeoutMinutes, environment, files, heatFiles); - Stack currentStack = createStack(createStack, cloudSiteId, tenantId); - currentStack.setStackName(stackName); - if (pollForCompletion) { - currentStack = + CreateStackParam createStack = createStackParam(stackName, heatTemplate, stackInputs, timeoutMinutes, + environment, nestedTemplates, heatFiles); + Stack currentStack = queryHeatStack(stackName, cloudSiteId, tenantId); + if (currentStack != null) { + logger.debug("Existing Stack found with Status: {} ", currentStack.getStackStatus()); + if (CREATE_COMPLETE.equals(currentStack.getStackStatus())) { + new StackInfoMapper(currentStack).map(); + } else if (CREATE_IN_PROGRESS.equals(currentStack.getStackStatus())) { + currentStack = processCreateStack(cloudSiteId, tenantId, timeoutMinutes, backout, currentStack, + createStack, true); + } else if (CREATE_FAILED.equals(currentStack.getStackStatus()) + || DELETE_FAILED.equals(currentStack.getStackStatus())) { + try { 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"); + currentStack = createStack(createStack, cloudSiteId, tenantId); + currentStack.setStackName(stackName); + if (pollForCompletion) { + currentStack = processCreateStack(cloudSiteId, tenantId, timeoutMinutes, backout, + currentStack, createStack, true); + } else { + currentStack = queryHeatStack(currentStack.getStackName() + "/" + currentStack.getId(), + cloudSiteId, tenantId); + } + } else { + throw e; + } + } + } } else { - currentStack = - queryHeatStack(currentStack.getStackName() + "/" + currentStack.getId(), cloudSiteId, tenantId); + currentStack = createStack(createStack, cloudSiteId, tenantId); + currentStack.setStackName(stackName); + if (pollForCompletion) { + currentStack = processCreateStack(cloudSiteId, tenantId, timeoutMinutes, backout, currentStack, + createStack, true); + } else { + currentStack = + queryHeatStack(currentStack.getStackName() + "/" + currentStack.getId(), cloudSiteId, tenantId); + } } return new StackInfoMapper(currentStack).map(); } @@ -270,7 +269,8 @@ 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); + latestStack = + pollStackForStatus(timeoutMinutes, heatStack, CREATE_IN_PROGRESS, cloudSiteId, tenantId, false); } catch (MsoException me) { logger.error("Exception in Create Stack", me); } @@ -280,47 +280,54 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin { protected Stack postProcessStackCreate(Stack stack, boolean backout, int timeoutMinutes, boolean cleanUpKeyPair, String cloudSiteId, String tenantId, CreateStackParam stackCreate) throws MsoException { + boolean stackCreationFailed = false; + boolean stackRollbackFailed = false; if (stack == null) { throw new StackCreationException("Unknown Error in Stack Creation"); - } - - logger.info("Performing post processing backout: {} cleanUpKeyPair: {}, stack {}", backout, cleanUpKeyPair, - stack); - if (!CREATE_COMPLETE.equals(stack.getStackStatus())) { - if (cleanUpKeyPair && !Strings.isNullOrEmpty(stack.getStackStatusReason()) - && isKeyPairFailure(stack.getStackStatusReason())) { - return handleKeyPairConflict(cloudSiteId, tenantId, stackCreate, timeoutMinutes, backout, stack); - } - if (!backout) { - logger.info("Status is not CREATE_COMPLETE, stack deletion suppressed"); - throw new StackCreationException("Stack rollback suppressed, stack not deleted"); - } else { - logger.info("Status is not CREATE_COMPLETE, stack deletion will be executed"); - String errorMessage = "Stack Creation Failed Openstack Status: " + stack.getStackStatus() - + " Status Reason: " + stack.getStackStatusReason(); - try { - Stack deletedStack = handleUnknownCreateStackFailure(stack, timeoutMinutes, cloudSiteId, tenantId); - errorMessage = errorMessage + " , Rollback of Stack Creation completed with status: " - + deletedStack.getStackStatus() + " Status Reason: " + deletedStack.getStackStatusReason(); - } catch (StackRollbackException se) { - logger.error("Sync Error Deleting Stack during rollback process", se); - errorMessage = errorMessage + se.getMessage(); - } catch (MsoException e) { - logger.error("Sync Error Deleting Stack during rollback", e); - - errorMessage = - errorMessage + " , Rollback of Stack Creation failed with sync error: " + e.getMessage(); + } else { + logger.info("Performing post processing backout: {} cleanUpKeyPair: {}, stack {}", backout, cleanUpKeyPair, + stack); + if (!CREATE_COMPLETE.equals(stack.getStackStatus())) { + if (cleanUpKeyPair && !Strings.isNullOrEmpty(stack.getStackStatusReason()) + && isKeyPairFailure(stack.getStackStatusReason())) { + return handleKeyPairConflict(cloudSiteId, tenantId, stackCreate, timeoutMinutes, backout, stack); + } + if (!backout) { + logger.info("Status is not CREATE_COMPLETE, stack deletion suppressed"); + stackCreationFailed = true; + throw new StackCreationException("Stack rollback suppressed, stack not deleted", + stackCreationFailed, stackRollbackFailed); + } else { + logger.info("Status is not CREATE_COMPLETE, stack deletion will be executed"); + stackCreationFailed = true; + String errorMessage = "Stack Creation Failed Openstack Status: " + stack.getStackStatus() + + " Status Reason: " + stack.getStackStatusReason(); + try { + Stack deletedStack = + handleUnknownCreateStackFailure(stack, timeoutMinutes, cloudSiteId, tenantId); + errorMessage = errorMessage + " , Rollback of Stack Creation completed with status: " + + deletedStack.getStackStatus() + " Status Reason: " + + deletedStack.getStackStatusReason(); + } catch (MsoException e) { + stackRollbackFailed = true; + logger.error("Sync Error Deleting Stack during rollback", e); + if (e instanceof StackRollbackException) { + errorMessage = errorMessage + e.getMessage(); + } else { + errorMessage = errorMessage + " , Rollback of Stack Creation failed with sync error: " + + e.getMessage(); + } + } + throw new StackCreationException(errorMessage, stackCreationFailed, stackRollbackFailed); } - throw new StackCreationException(errorMessage); + } else { + return stack; } - } else { - return stack; } - } protected Stack pollStackForStatus(int timeoutMinutes, Stack stack, String stackStatus, String cloudSiteId, - String tenantId) throws MsoException { + String tenantId, boolean notFoundIsSuccess) throws MsoException { int pollingFrequency = Integer.parseInt(this.environment.getProperty(createPollIntervalProp, CREATE_POLL_INTERVAL_DEFAULT)); int pollingMultiplier = @@ -329,9 +336,10 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin { Heat heatClient = getHeatClient(cloudSiteId, tenantId); while (true) { Stack latestStack = queryHeatStack(heatClient, stack.getStackName() + "/" + stack.getId()); - if (latestStack != null) { + if (latestStack == null && notFoundIsSuccess) { + return null; + } else if (latestStack != null) { statusHandler.updateStackStatus(latestStack); - logger.debug("Polling: {} ({})", latestStack.getStackStatus(), latestStack.getStackName()); if (stackStatus.equals(latestStack.getStackStatus())) { if (numberOfPollingAttempts <= 0) { logger.error("Polling of stack timed out with Status: {}", latestStack.getStackStatus()); @@ -342,9 +350,6 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin { } else { return latestStack; } - } else { - logger.error("latestStack is null"); - return null; } } } @@ -381,17 +386,26 @@ 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())) { - OpenStackRequest<Void> request = getHeatClient(cloudSiteId, tenantId).getStacks() - .deleteByName(stack.getStackName() + "/" + stack.getId()); - executeAndRecordOpenstackRequest(request); - Stack currentStack = pollStackForStatus(timeoutMinutes, stack, DELETE_IN_PROGRESS, cloudSiteId, tenantId); - postProcessStackDelete(currentStack); - return currentStack; + return deleteStack(stack, timeoutMinutes, cloudSiteId, tenantId); } else { throw new StackCreationException("Cannot Find Stack Name or Id"); } } + private Stack deleteStack(Stack stack, int timeoutMinutes, String cloudSiteId, String tenantId) + throws MsoException { + OpenStackRequest<Void> 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) { + return currentStack; + } else { + postProcessStackDelete(currentStack); + } + return currentStack; + } + protected void postProcessStackDelete(Stack stack) throws MsoException { logger.info("Performing post processing on delete stack {}", stack); if (stack != null && !Strings.isNullOrEmpty(stack.getStackStatus())) { @@ -453,7 +467,6 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin { // Query the Stack. // An MsoException will propagate transparently to the caller. Stack heatStack = queryHeatStack(heatClient, stackName); - if (heatStack == null) { // Stack does not exist. Return a StackInfo with status NOTFOUND return new StackInfo(stackName, HeatStatus.NOTFOUND); @@ -484,114 +497,16 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin { * @throws MsoCloudSiteNotFound */ public StackInfo deleteStack(String tenantId, String cloudOwner, String cloudSiteId, String stackName, - boolean pollForCompletion) throws MsoException { - Heat heatClient = null; - try { - heatClient = getHeatClient(cloudSiteId, tenantId); - } catch (MsoTenantNotFound e) { - logger.debug("Tenant with id " + tenantId + "not found.", e); - return new StackInfo(stackName, HeatStatus.NOTFOUND); - } catch (MsoException me) { - logger.error("{} {} Openstack Exception on Token request: ", MessageEnum.RA_CONNECTION_EXCEPTION, - ErrorCode.AvailabilityError.getValue(), me); - me.addContext(DELETE_STACK); - throw me; - } - - // OK if stack not found, perform a query first - Stack heatStack = queryHeatStack(heatClient, stackName); - if (heatStack == null || DELETE_COMPLETE.equals(heatStack.getStackStatus())) { - // Not found. Return a StackInfo with status NOTFOUND - return new StackInfo(stackName, HeatStatus.NOTFOUND); - } - - // Use canonical name "<stack name>/<stack-id>" to delete. - // Otherwise, deletion by name returns a 302 redirect. - // NOTE: This is specific to the v1 Orchestration API. - String canonicalName = heatStack.getStackName() + "/" + heatStack.getId(); - - try { - OpenStackRequest<Void> request = null; - if (null != heatClient) { - request = heatClient.getStacks().deleteByName(canonicalName); - } else { - logger.debug("Heat Client is NULL"); - } - executeAndRecordOpenstackRequest(request); - } catch (OpenStackResponseException e) { - if (e.getStatus() == 404) { - // Not found. We are OK with this. Return a StackInfo with status NOTFOUND - return new StackInfo(stackName, HeatStatus.NOTFOUND); - } else { - // Convert the OpenStackResponseException to an MsoOpenstackException - throw heatExceptionToMsoException(e, DELETE_STACK); - } - } catch (OpenStackConnectException e) { - // Error connecting to Openstack instance. Convert to an MsoException - throw heatExceptionToMsoException(e, DELETE_STACK); - } catch (RuntimeException e) { - // Catch-all - throw runtimeExceptionToMsoException(e, DELETE_STACK); - } - - // Requery the stack for current status. - // It will probably still exist with "DELETE_IN_PROGRESS" status. - heatStack = queryHeatStack(heatClient, canonicalName); - statusHandler.updateStackStatus(heatStack); - if (pollForCompletion) { - int pollInterval = Integer - .parseInt(this.environment.getProperty(deletePollIntervalProp, "" + DELETE_POLL_INTERVAL_DEFAULT)); - int pollTimeout = Integer - .parseInt(this.environment.getProperty(deletePollTimeoutProp, "" + DELETE_POLL_INTERVAL_DEFAULT)); - statusHandler.updateStackStatus(heatStack); - // When querying by canonical name, Openstack returns DELETE_COMPLETE status - // instead of "404" (which would result from query by stack name). - while (heatStack != null && !DELETE_COMPLETE.equals(heatStack.getStackStatus())) { - logger.debug("Stack status: {}", heatStack.getStackStatus()); - - if ("DELETE_FAILED".equals(heatStack.getStackStatus())) { - // Throw a 'special case' of MsoOpenstackException to report the Heat status - String error = "Stack delete error (" + heatStack.getStackStatus() + "): " - + heatStack.getStackStatusReason(); - MsoOpenstackException me = new MsoOpenstackException(0, "", error); - me.addContext(DELETE_STACK); - - // Alarm this condition, stack deletion failed - - - throw me; - } - - if (pollTimeout <= 0) { - logger.error("{} Cloud site: {} Tenant: {} Stack: {} Stack status: {} {} Delete Stack Timeout", - MessageEnum.RA_DELETE_STACK_TIMEOUT, cloudSiteId, tenantId, stackName, - heatStack.getStackStatus(), ErrorCode.AvailabilityError.getValue()); - - // Throw a 'special case' of MsoOpenstackException to report the Heat status - MsoOpenstackException me = new MsoOpenstackException(0, "", "Stack Deletion Timeout"); - me.addContext(DELETE_STACK); - - // Alarm this condition, stack deletion failed - - - throw me; - } - - sleep(pollInterval * 1000L); - - pollTimeout -= pollInterval; - logger.debug("pollTimeout remaining: {}", pollTimeout); - - heatStack = queryHeatStack(heatClient, canonicalName); - } - - // The stack is gone when this point is reached + boolean pollForCompletion, int timeoutMinutes) throws MsoException { + Stack currentStack = queryHeatStack(stackName, cloudSiteId, tenantId); + if (currentStack == null || DELETE_COMPLETE.equals(currentStack.getStackStatus())) { return new StackInfo(stackName, HeatStatus.NOTFOUND); + } else { + currentStack = deleteStack(currentStack, timeoutMinutes, cloudSiteId, tenantId); + StackInfo stackInfo = new StackInfoMapper(currentStack).map(); + stackInfo.setName(stackName); + return stackInfo; } - // Return the current status (if not polling, the delete may still be in progress) - StackInfo stackInfo = new StackInfoMapper(heatStack).map(); - stackInfo.setName(stackName); - return stackInfo; } /** @@ -734,7 +649,7 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin { if (!inputs.containsKey(key)) { Object obj = otherStackOutputs.get(key); if (obj instanceof String) { - inputs.put(key, (String) otherStackOutputs.get(key)); + inputs.put(key, otherStackOutputs.get(key)); } else if (obj instanceof JsonNode) { // This is a bit of mess - but I think it's the least impacting // let's convert it BACK to a string - then it will get converted back later @@ -1115,11 +1030,11 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin { } try { - StackInfo stackInfo = - createStack(cloudSiteId, cloudOwner, tenantId, instanceName, vduModel, heatTemplate, inputs, true, // poll - // for - // completion - vduModel.getTimeoutMinutes(), heatEnvironment, nestedTemplates, files, rollbackOnFailure); + StackInfo stackInfo = createStack(cloudSiteId, cloudOwner, tenantId, instanceName, vduModel, heatTemplate, + inputs, true, // poll + // for + // completion + vduModel.getTimeoutMinutes(), heatEnvironment, nestedTemplates, files, rollbackOnFailure, false); // Populate a vduInstance from the StackInfo return stackInfoToVduInstance(stackInfo); @@ -1160,7 +1075,7 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin { try { // Delete the Heat stack - StackInfo stackInfo = deleteStack(tenantId, cloudOwner, cloudSiteId, instanceId, true); + StackInfo stackInfo = deleteStack(tenantId, cloudOwner, cloudSiteId, instanceId, true, timeoutMinutes); // Populate a VduInstance based on the deleted Cloudify Deployment object VduInstance vduInstance = stackInfoToVduInstance(stackInfo); diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoMulticloudUtils.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoMulticloudUtils.java index c75aa9a67e..3eb3fe188d 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoMulticloudUtils.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoMulticloudUtils.java @@ -51,7 +51,7 @@ import org.onap.so.openstack.exceptions.MsoAdapterException; import org.onap.so.openstack.exceptions.MsoException; import org.onap.so.openstack.exceptions.MsoOpenstackException; import org.onap.so.openstack.mappers.StackInfoMapper; -import org.onap.so.utils.TargetEntity; +import org.onap.logging.filter.base.ONAPComponents; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -135,7 +135,7 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin { public StackInfo createStack(String cloudSiteId, String cloudOwner, String tenantId, String stackName, VduModelInfo vduModel, String heatTemplate, Map<String, ?> stackInputs, boolean pollForCompletion, int timeoutMinutes, String environment, Map<String, Object> files, Map<String, Object> heatFiles, - boolean backout) throws MsoException { + boolean backout, boolean failIfExists) throws MsoException { logger.trace("Started MsoMulticloudUtils.createStack"); @@ -821,7 +821,7 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin { private RestClient getMulticloudClient(String endpoint, String tenantId) { HttpClient client = null; try { - client = httpClientFactory.newJsonClient(new URL(endpoint), TargetEntity.MULTICLOUD); + client = httpClientFactory.newJsonClient(new URL(endpoint), ONAPComponents.MULTICLOUD); if (tenantId != null && !tenantId.isEmpty()) { client.addAdditionalHeader("Project", tenantId); } @@ -881,11 +881,11 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin { } try { - StackInfo stackInfo = - createStack(cloudSiteId, cloudOwner, tenantId, instanceName, vduModel, heatTemplate, inputs, true, // poll - // for - // completion - vduModel.getTimeoutMinutes(), heatEnvironment, nestedTemplates, files, rollbackOnFailure); + StackInfo stackInfo = createStack(cloudSiteId, cloudOwner, tenantId, instanceName, vduModel, heatTemplate, + inputs, true, // poll + // for + // completion + vduModel.getTimeoutMinutes(), heatEnvironment, nestedTemplates, files, rollbackOnFailure, false); // Populate a vduInstance from the StackInfo return stackInfoToVduInstance(stackInfo); } catch (Exception e) { @@ -957,6 +957,7 @@ public class MsoMulticloudUtils extends MsoHeatUtils implements VduPlugin { /* * Convert the local DeploymentInfo object (Cloudify-specific) to a generic VduInstance object */ + @Override protected VduInstance stackInfoToVduInstance(StackInfo stackInfo) { VduInstance vduInstance = new VduInstance(); diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/StackCreationException.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/StackCreationException.java index e3936e31f7..ab9c8a6dee 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/StackCreationException.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/StackCreationException.java @@ -24,8 +24,22 @@ import org.onap.so.openstack.exceptions.MsoException; public class StackCreationException extends MsoException { + /** + * + */ + private static final long serialVersionUID = 6221508301589330950L; + + boolean stackCreationFailed = false; + boolean stackRollbackFailed = false; + public StackCreationException(String error) { super(error); } + public StackCreationException(String error, boolean stackCreationFailed, boolean stackRollbackFailed) { + super(error); + this.stackRollbackFailed = stackRollbackFailed; + this.stackCreationFailed = stackCreationFailed; + } + } diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatUtilsITTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatUtilsITTest.java index 7e783aa7a4..86b1413291 100644 --- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatUtilsITTest.java +++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatUtilsITTest.java @@ -133,7 +133,7 @@ public class MsoHeatUtilsITTest extends BaseTest { @Test public void deleteVduTest() throws Exception { VduInstance expected = new VduInstance(); - expected.setVduInstanceId("instanceId"); + expected.setVduInstanceId("name/stackId"); expected.setVduInstanceName("instanceId"); VduStatus status = new VduStatus(); status.setState(VduStateType.DELETED); @@ -209,8 +209,8 @@ public class MsoHeatUtilsITTest extends BaseTest { StubOpenStack.mockOpenStackResponseAccess(wireMockServer, wireMockPort); StubOpenStack.mockOpenStackPostStack_200(wireMockServer, "OpenstackResponse_Stack_Created.json"); StubOpenStack.mockOpenStackGet(wireMockServer, "TEST-stack/stackId"); - StackInfo stackInfo = heatUtils.createStack(cloudSite.getId(), "CloudOwner", "tenantId", "TEST-stack", - "TEST-heat", new HashMap<>(), false, 1, "TEST-env", new HashMap<>(), new HashMap<>()); + StackInfo stackInfo = heatUtils.createStack(cloudSite.getId(), "CloudOwner", "tenantId", "TEST-stack", null, + "TEST-heat", new HashMap<>(), false, 1, "TEST-env", new HashMap<>(), new HashMap<>(), false, false); assertNotNull(stackInfo); } 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 e68364eab8..92cf96ed16 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 @@ -124,7 +124,7 @@ public class MsoHeatUtilsTest extends MsoHeatUtils { latestStack.setStackStatusReason("Stack Finished"); doReturn(latestStack).when(heatUtils).queryHeatStack(isA(Heat.class), eq("stackName/id")); doReturn(heatClient).when(heatUtils).getHeatClient(cloudSiteId, tenantId); - Stack actual = heatUtils.pollStackForStatus(1, stack, "CREATE_IN_PROGRESS", cloudSiteId, tenantId); + Stack actual = heatUtils.pollStackForStatus(1, stack, "CREATE_IN_PROGRESS", cloudSiteId, tenantId, false); Mockito.verify(stackStatusHandler, times(1)).updateStackStatus(latestStack); Mockito.verify(heatUtils, times(1)).queryHeatStack(isA(Heat.class), eq("stackName/id")); assertEquals(true, actual != null); @@ -141,7 +141,7 @@ public class MsoHeatUtilsTest extends MsoHeatUtils { doNothing().when(stackStatusHandler).updateStackStatus(stack); doReturn(stack).when(heatUtils).queryHeatStack(isA(Heat.class), eq("stackName/id")); doReturn(heatClient).when(heatUtils).getHeatClient(cloudSiteId, tenantId); - Stack actual = heatUtils.pollStackForStatus(1, stack, "CREATE_IN_PROGRESS", cloudSiteId, tenantId); + Stack actual = heatUtils.pollStackForStatus(1, stack, "CREATE_IN_PROGRESS", cloudSiteId, tenantId, false); Mockito.verify(stackStatusHandler, times(1)).updateStackStatus(stack); Mockito.verify(heatUtils, times(1)).queryHeatStack(isA(Heat.class), eq("stackName/id")); assertEquals(true, actual != null); @@ -259,11 +259,12 @@ public class MsoHeatUtilsTest extends MsoHeatUtils { doReturn(stackResource).when(heatClient).getStacks(); doReturn(mockDeleteStack).when(stackResource).deleteByName("stackName/id"); doReturn(deletedStack).when(heatUtils).pollStackForStatus(120, stack, "DELETE_IN_PROGRESS", cloudSiteId, - tenantId); + tenantId, true); 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(1)).pollStackForStatus(120, stack, "DELETE_IN_PROGRESS", cloudSiteId, tenantId, + true); Mockito.verify(heatUtils, times(1)).postProcessStackDelete(deletedStack); } @@ -357,12 +358,13 @@ public class MsoHeatUtilsTest extends MsoHeatUtils { createStackParam.setStackName("stackName"); doReturn(createdStack).when(heatUtils).pollStackForStatus(120, stack, "CREATE_IN_PROGRESS", cloudSiteId, - tenantId); + tenantId, false); doReturn(createdStack).when(heatUtils).postProcessStackCreate(createdStack, true, 120, true, cloudSiteId, tenantId, createStackParam); heatUtils.processCreateStack(cloudSiteId, tenantId, 120, true, stack, createStackParam, true); - Mockito.verify(heatUtils, times(1)).pollStackForStatus(120, stack, "CREATE_IN_PROGRESS", cloudSiteId, tenantId); + Mockito.verify(heatUtils, times(1)).pollStackForStatus(120, stack, "CREATE_IN_PROGRESS", cloudSiteId, tenantId, + false); Mockito.verify(heatUtils, times(1)).postProcessStackCreate(createdStack, true, 120, true, cloudSiteId, tenantId, createStackParam); } @@ -387,11 +389,12 @@ public class MsoHeatUtilsTest extends MsoHeatUtils { createStackParam.setStackName("stackName"); doThrow(new StackCreationException("Error")).when(heatUtils).pollStackForStatus(120, stack, - "CREATE_IN_PROGRESS", cloudSiteId, tenantId); + "CREATE_IN_PROGRESS", cloudSiteId, tenantId, false); exceptionRule.expect(MsoException.class); exceptionRule.expectMessage("Error"); heatUtils.processCreateStack(cloudSiteId, tenantId, 120, true, stack, createStackParam, true); - Mockito.verify(heatUtils, times(1)).pollStackForStatus(120, stack, "CREATE_IN_PROGRESS", cloudSiteId, tenantId); + Mockito.verify(heatUtils, times(1)).pollStackForStatus(120, stack, "CREATE_IN_PROGRESS", cloudSiteId, tenantId, + false); Mockito.verify(heatUtils, times(1)).postProcessStackCreate(stack, true, 120, true, cloudSiteId, tenantId, createStackParam); } @@ -527,12 +530,13 @@ public class MsoHeatUtilsTest extends MsoHeatUtils { createStackParam.setStackName("stackName"); doThrow(new StackCreationException("Error")).when(heatUtils).pollStackForStatus(120, stack, - "CREATE_IN_PROGRESS", cloudSiteId, tenantId); + "CREATE_IN_PROGRESS", cloudSiteId, tenantId, false); exceptionRule.expect(MsoException.class); exceptionRule.expectMessage("Error"); heatUtils.processCreateStack(cloudSiteId, tenantId, 120, false, stack, createStackParam, true); - Mockito.verify(heatUtils, times(1)).pollStackForStatus(120, stack, "CREATE_IN_PROGRESS", cloudSiteId, tenantId); + Mockito.verify(heatUtils, times(1)).pollStackForStatus(120, stack, "CREATE_IN_PROGRESS", cloudSiteId, tenantId, + false); Mockito.verify(heatUtils, times(0)).handleUnknownCreateStackFailure(stack, 120, cloudSiteId, tenantId); } diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoMulticloudUtilsTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoMulticloudUtilsTest.java index 995db522e9..44a9bc3e10 100644 --- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoMulticloudUtilsTest.java +++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoMulticloudUtilsTest.java @@ -24,8 +24,8 @@ import static com.github.tomakehurst.wiremock.client.WireMock.aResponse; import static com.github.tomakehurst.wiremock.client.WireMock.delete; import static com.github.tomakehurst.wiremock.client.WireMock.get; import static com.github.tomakehurst.wiremock.client.WireMock.post; -import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static com.github.tomakehurst.wiremock.client.WireMock.urlEqualTo; +import static com.github.tomakehurst.wiremock.client.WireMock.urlPathEqualTo; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; @@ -95,9 +95,9 @@ public class MsoMulticloudUtilsTest extends BaseTest { wireMockServer.stubFor(get(urlEqualTo(MULTICLOUD_GET_PATH)).inScenario("CREATE").whenScenarioStateIs("UPDATING") .willReturn(aResponse().withHeader("Content-Type", "application/json") .withBodyFile("MulticloudGetUpdateResponse.json").withStatus(HttpStatus.SC_OK))); - StackInfo result = - multicloudUtils.createStack("MTN14", "CloudOwner", "TEST-tenant", "TEST-stack", new VduModelInfo(), - "TEST-heat", new HashMap<>(), true, 200, "TEST-env", new HashMap<>(), new HashMap<>(), false); + StackInfo result = multicloudUtils.createStack("MTN14", "CloudOwner", "TEST-tenant", "TEST-stack", + new VduModelInfo(), "TEST-heat", new HashMap<>(), true, 200, "TEST-env", new HashMap<>(), + new HashMap<>(), false, false); wireMockServer.resetScenarios(); assertNotNull(result); assertEquals("TEST-stack", result.getName()); @@ -155,7 +155,8 @@ public class MsoMulticloudUtilsTest extends BaseTest { cloudSite.setIdentityService(new CloudIdentity()); when(cloudConfigMock.getCloudSite("MTN13")).thenReturn(Optional.of(cloudSite)); multicloudUtilsMock.createStack("MNT14", "CloudOwner", "TEST-tenant", "TEST-stack", new VduModelInfo(), - "TEST-heat", new HashMap<>(), false, 200, "TEST-env", new HashMap<>(), new HashMap<>(), false); + "TEST-heat", new HashMap<>(), false, 200, "TEST-env", new HashMap<>(), new HashMap<>(), false, + false); } catch (MsoException e) { assertEquals("0 : Multicloud client could not be initialized", e.toString()); return; @@ -169,7 +170,8 @@ public class MsoMulticloudUtilsTest extends BaseTest { wireMockServer.stubFor(post(urlPathEqualTo(MULTICLOUD_CREATE_PATH)).willReturn( aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_BAD_REQUEST))); multicloudUtils.createStack("MTN14", "CloudOwner", "TEST-tenant", "TEST-stack", new VduModelInfo(), - "TEST-heat", new HashMap<>(), false, 200, "TEST-env", new HashMap<>(), new HashMap<>(), false); + "TEST-heat", new HashMap<>(), false, 200, "TEST-env", new HashMap<>(), new HashMap<>(), false, + false); } catch (MsoException e) { assertEquals("0 : Bad Request", e.toString()); return; @@ -181,9 +183,9 @@ public class MsoMulticloudUtilsTest extends BaseTest { public void createStackEmptyResponseEntity() throws MsoException { wireMockServer.stubFor(post(urlPathEqualTo(MULTICLOUD_CREATE_PATH)).willReturn( aResponse().withHeader("Content-Type", "application/json").withStatus(HttpStatus.SC_CREATED))); - StackInfo result = - multicloudUtils.createStack("MTN14", "CloudOwner", "TEST-tenant", "TEST-stack", new VduModelInfo(), - "TEST-heat", new HashMap<>(), false, 200, "TEST-env", new HashMap<>(), new HashMap<>(), false); + StackInfo result = multicloudUtils.createStack("MTN14", "CloudOwner", "TEST-tenant", "TEST-stack", + new VduModelInfo(), "TEST-heat", new HashMap<>(), false, 200, "TEST-env", new HashMap<>(), + new HashMap<>(), false, false); assertNotNull(result); assertEquals("TEST-stack/", result.getName()); } diff --git a/adapters/mso-adapter-utils/src/test/resources/__files/OpenstackResponse_Stack_DeleteComplete.json b/adapters/mso-adapter-utils/src/test/resources/__files/OpenstackResponse_Stack_DeleteComplete.json index a26a551f7d..ea05b64e08 100644 --- a/adapters/mso-adapter-utils/src/test/resources/__files/OpenstackResponse_Stack_DeleteComplete.json +++ b/adapters/mso-adapter-utils/src/test/resources/__files/OpenstackResponse_Stack_DeleteComplete.json @@ -3,7 +3,7 @@ "description": null, "links": null, "stack_status_reason": null, - "stack_name": null, + "stack_name": "name", "updated_time": null, "creation_time": null, "stack_status": "DELETE_COMPLETE", diff --git a/adapters/mso-catalog-db-adapter/pom.xml b/adapters/mso-catalog-db-adapter/pom.xml index 9ec98cf96c..9745935925 100644 --- a/adapters/mso-catalog-db-adapter/pom.xml +++ b/adapters/mso-catalog-db-adapter/pom.xml @@ -14,6 +14,7 @@ <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding> <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding> <java.version>1.8</java.version> + <swagger.version>2.0.8</swagger.version> </properties> <build> <plugins> @@ -84,40 +85,6 @@ </plugins> <pluginManagement> <plugins> - <!--This plugin's configuration is used to store Eclipse m2e settings - only. It has no influence on the Maven build itself. --> - <plugin> - <groupId>org.eclipse.m2e</groupId> - <artifactId>lifecycle-mapping</artifactId> - <version>1.0.0</version> - <configuration> - <lifecycleMappingMetadata> - <pluginExecutions> - <pluginExecution> - <pluginExecutionFilter> - <groupId> - org.jvnet.jax-ws-commons - </groupId> - <artifactId> - jaxws-maven-plugin - </artifactId> - <versionRange> - [2.3,) - </versionRange> - <goals> - <goal>wsgen</goal> - </goals> - </pluginExecutionFilter> - <action> - <ignore> - </ignore> - </action> - </pluginExecution> - </pluginExecutions> - </lifecycleMappingMetadata> - </configuration> - </plugin> - <plugin> <groupId>org.jacoco</groupId> <artifactId>jacoco-maven-plugin</artifactId> @@ -143,10 +110,22 @@ <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> + + <dependency> + <groupId>com.fasterxml.jackson.dataformat</groupId> + <artifactId>jackson-dataformat-yaml</artifactId> + <version>2.9.9</version> + </dependency> + + <dependency> + <groupId>io.swagger.core.v3</groupId> + <artifactId>swagger-annotations</artifactId> + <version>${swagger.version}</version> + </dependency> <dependency> - <groupId>io.swagger</groupId> - <artifactId>swagger-jersey2-jaxrs</artifactId> - <version>1.5.16</version> + <groupId>io.swagger.core.v3</groupId> + <artifactId>swagger-jaxrs2</artifactId> + <version>2.0.6</version> </dependency> <dependency> <groupId>org.mariadb.jdbc</groupId> diff --git a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/CatalogDBApplication.java b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/CatalogDBApplication.java index aa19aed515..6fb65ca87e 100644 --- a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/CatalogDBApplication.java +++ b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/CatalogDBApplication.java @@ -28,7 +28,7 @@ import org.springframework.scheduling.annotation.EnableScheduling; @SpringBootApplication(scanBasePackages = {"org.onap.so.adapters.catalogdb", "org.onap.so.db.catalog.client", "org.onap.so.logging.jaxrs.filter", "org.onap.so.logging.spring.interceptor", "org.onap.so.client", - "org.onap.so.configuration", "org.onap.so.db"}) + "org.onap.so.configuration", "org.onap.so.db", "org.onap.logging.filter"}) @EnableJpaRepositories("org.onap.so.db.catalog.data.repository") @EntityScan("org.onap.so.db.catalog.beans") @EnableScheduling diff --git a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/JerseyConfiguration.java b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/JerseyConfiguration.java index b43447f5c4..359c8cd46e 100644 --- a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/JerseyConfiguration.java +++ b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/JerseyConfiguration.java @@ -20,17 +20,25 @@ package org.onap.so.adapters.catalogdb; +import java.util.stream.Collectors; +import java.util.stream.Stream; import javax.annotation.PostConstruct; import javax.ws.rs.ApplicationPath; import org.glassfish.jersey.server.ResourceConfig; +import org.onap.logging.filter.base.Constants; +import org.onap.logging.filter.base.ONAPComponents; import org.onap.so.adapters.catalogdb.rest.CatalogDbAdapterRest; import org.onap.so.adapters.catalogdb.rest.ServiceRestImpl; import org.onap.so.adapters.catalogdb.rest.VnfRestImpl; -import org.onap.so.logging.jaxrs.filter.JaxRsFilterLogging; +import org.onap.so.logging.jaxrs.filter.SOAuditLogContainerFilter; import org.springframework.context.annotation.Configuration; -import io.swagger.jaxrs.config.BeanConfig; -import io.swagger.jaxrs.listing.ApiListingResource; -import io.swagger.jaxrs.listing.SwaggerSerializers; +import io.swagger.v3.jaxrs2.integration.JaxrsOpenApiContextBuilder; +import io.swagger.v3.jaxrs2.integration.resources.AcceptHeaderOpenApiResource; +import io.swagger.v3.jaxrs2.integration.resources.OpenApiResource; +import io.swagger.v3.oas.integration.OpenApiConfigurationException; +import io.swagger.v3.oas.integration.SwaggerConfiguration; +import io.swagger.v3.oas.models.OpenAPI; +import io.swagger.v3.oas.models.info.Info; @Configuration @ApplicationPath("/ecomp/mso/catalog") @@ -38,19 +46,27 @@ public class JerseyConfiguration extends ResourceConfig { @PostConstruct public void setUp() { + System.setProperty(Constants.Property.PARTNER_NAME, ONAPComponents.CATALOG_DB.toString()); register(CatalogDbAdapterRest.class); - register(ApiListingResource.class); - register(SwaggerSerializers.class); - register(JaxRsFilterLogging.class); + register(SOAuditLogContainerFilter.class); + register(OpenApiResource.class); + register(AcceptHeaderOpenApiResource.class); register(ServiceRestImpl.class); register(VnfRestImpl.class); - BeanConfig beanConfig = new BeanConfig(); - beanConfig.setVersion("1.0.2"); - beanConfig.setSchemes(new String[] {"https"}); - beanConfig.setBasePath("/ecomp/mso/catalog"); - beanConfig.setResourcePackage("org.onap.so.adapters.catalogdb.rest"); - beanConfig.setPrettyPrint(true); - beanConfig.setScan(true); + + OpenAPI oas = new OpenAPI(); + Info info = new Info(); + info.title("Swagger catalog-db-adapter bootstrap code"); + info.setVersion("1.0.2"); + + SwaggerConfiguration oasConfig = new SwaggerConfiguration().openAPI(oas).prettyPrint(true) + .resourcePackages(Stream.of("org.onap.so.adapters.catalogdb.rest").collect(Collectors.toSet())); + + try { + new JaxrsOpenApiContextBuilder().application(this).openApiConfiguration(oasConfig).buildContext(true); + } catch (OpenApiConfigurationException e) { + throw new RuntimeException(e.getMessage(), e); + } } } diff --git a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/WebMvcConfig.java b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/WebMvcConfig.java index 4dabb58f7d..cd3b2a377b 100644 --- a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/WebMvcConfig.java +++ b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/WebMvcConfig.java @@ -21,22 +21,32 @@ package org.onap.so.adapters.catalogdb; -import org.onap.so.logging.spring.interceptor.LoggingInterceptor; +import org.onap.logging.filter.spring.LoggingInterceptor; +import org.onap.logging.filter.spring.StatusLoggingInterceptor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.handler.MappedInterceptor; @Configuration +@ComponentScan(basePackages = {"org.onap.logging.filter"}) public class WebMvcConfig extends WebMvcConfigurerAdapter { @Autowired - LoggingInterceptor loggingInterceptor; + private LoggingInterceptor loggingInterceptor; + + @Autowired + private StatusLoggingInterceptor statusLoggingInterceptor; @Bean public MappedInterceptor mappedLoggingInterceptor() { return new MappedInterceptor(new String[] {"/**"}, loggingInterceptor); } + @Bean + public MappedInterceptor mappedStatusLoggingInterceptor() { + return new MappedInterceptor(new String[] {"/**"}, statusLoggingInterceptor); + } } diff --git a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/rest/ServiceRestImpl.java b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/rest/ServiceRestImpl.java index 6f556edfa1..bc4d0064d0 100644 --- a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/rest/ServiceRestImpl.java +++ b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/rest/ServiceRestImpl.java @@ -34,11 +34,17 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; import com.google.common.base.Strings; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; -import io.swagger.annotations.ApiParam; +import io.swagger.v3.oas.annotations.OpenAPIDefinition; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.Parameter; +import io.swagger.v3.oas.annotations.info.Info; +import io.swagger.v3.oas.annotations.media.ArraySchema; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; -@Api(value = "/v1", tags = "model") + +@OpenAPIDefinition(info = @Info(title = "/v1", description = "model")) @Path("/v1/services") @Component public class ServiceRestImpl { @@ -63,14 +69,15 @@ public class ServiceRestImpl { } @GET - @ApiOperation(value = "Find Service Models", response = Service.class, responseContainer = "List") + @Operation(description = "Find Service Models", responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Service.class))))) @Produces({MediaType.APPLICATION_JSON}) @Transactional(readOnly = true) public List<Service> queryServices( - @ApiParam(value = "modelName", required = false) @QueryParam("modelName") String modelName, - @ApiParam(value = "distributionStatus", + @Parameter(description = "modelName", required = false) @QueryParam("modelName") String modelName, + @Parameter(description = "distributionStatus", required = false) @QueryParam("distributionStatus") String distributionStatus, - @ApiParam(value = "depth", required = false) @QueryParam("depth") int depth) { + @Parameter(description = "depth", required = false) @QueryParam("depth") int depth) { List<Service> services = new ArrayList<>(); List<org.onap.so.db.catalog.beans.Service> serviceFromDB = new ArrayList<>(); if (!Strings.isNullOrEmpty(modelName) && !Strings.isNullOrEmpty(distributionStatus)) { diff --git a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/rest/VnfRestImpl.java b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/rest/VnfRestImpl.java index 4353526872..9202fd21d4 100644 --- a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/rest/VnfRestImpl.java +++ b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/rest/VnfRestImpl.java @@ -34,14 +34,20 @@ import javax.ws.rs.core.Response; import org.onap.so.db.catalog.beans.VnfResourceCustomization; import org.onap.so.db.catalog.data.repository.ServiceRepository; import org.onap.so.db.catalog.data.repository.VnfCustomizationRepository; +import org.onap.so.rest.catalog.beans.Service; import org.onap.so.rest.catalog.beans.Vnf; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; -import io.swagger.annotations.Api; -import io.swagger.annotations.ApiOperation; +import io.swagger.v3.oas.annotations.OpenAPIDefinition; +import io.swagger.v3.oas.annotations.Operation; +import io.swagger.v3.oas.annotations.info.Info; +import io.swagger.v3.oas.annotations.media.ArraySchema; +import io.swagger.v3.oas.annotations.media.Content; +import io.swagger.v3.oas.annotations.media.Schema; +import io.swagger.v3.oas.annotations.responses.ApiResponse; -@Api(value = "/v1/services/{modelUUID}/vnfs", tags = "model") +@OpenAPIDefinition(info = @Info(title = "/v1/services/{modelUUID}/vnfs", description = "model")) @Path("/v1/services/{modelUUID}/vnfs") @Component public class VnfRestImpl { @@ -59,7 +65,8 @@ public class VnfRestImpl { private VnfCustomizationRepository vnfCustRepo; @GET - @ApiOperation(value = "Find a VNF model contained within a service", response = Vnf.class) + @Operation(description = "Find a VNF model contained within a service", responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Vnf.class))))) @Path("/{modelCustomizationUUID}") @Produces({MediaType.APPLICATION_JSON}) @Transactional(readOnly = true) @@ -72,7 +79,7 @@ public class VnfRestImpl { List<VnfResourceCustomization> vnfCustom = service.getVnfCustomizations().stream() .filter(vnfCust -> vnfCust.getModelCustomizationUUID().equals(modelCustomizationUUID)) .collect(Collectors.toList()); - if (vnfCustom.isEmpty() || vnfCustom == null) { + if (vnfCustom.isEmpty()) { return null; } else if (vnfCustom.size() > 1) { throw new RuntimeException( @@ -82,7 +89,8 @@ public class VnfRestImpl { } @PUT - @ApiOperation(value = "Update a VNF model contained within a service", response = Vnf.class) + @Operation(description = "Update a VNF model contained within a service", responses = @ApiResponse( + content = @Content(array = @ArraySchema(schema = @Schema(implementation = Vnf.class))))) @Path("/{modelCustomizationUUID}") @Produces({MediaType.APPLICATION_JSON}) @Transactional @@ -92,7 +100,7 @@ public class VnfRestImpl { List<VnfResourceCustomization> vnfCustom = service.getVnfCustomizations().stream() .filter(vnfCust -> vnfCust.getModelCustomizationUUID().equals(modelCustomizationUUID)) .collect(Collectors.toList()); - if (vnfCustom.isEmpty() || vnfCustom == null) { + if (vnfCustom.isEmpty()) { throw new RuntimeException("No Vnf Found"); } else if (vnfCustom.size() > 1) { throw new RuntimeException( diff --git a/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V7.0__AddActivatedForOrchestrationStatus.sql b/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V7.0__AddActivatedForOrchestrationStatus.sql new file mode 100644 index 0000000000..30b5010c7c --- /dev/null +++ b/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V7.0__AddActivatedForOrchestrationStatus.sql @@ -0,0 +1,47 @@ +INSERT INTO orchestration_status_state_transition_directive(RESOURCE_TYPE, ORCHESTRATION_STATUS, TARGET_ACTION, FLOW_DIRECTIVE) +VALUES + +('CONFIGURATION', 'ACTIVATED', 'UNASSIGN', 'FAIL'), +('CONFIGURATION', 'ACTIVATED', 'ASSIGN', 'SILENT_SUCCESS'), +('CONFIGURATION', 'ACTIVATED', 'ACTIVATE', 'SILENT_SUCCESS'), +('CONFIGURATION', 'ACTIVATED', 'DEACTIVATE', 'CONTINUE'), + +('NETWORK', 'ACTIVATED', 'ASSIGN', 'SILENT_SUCCESS'), +('NETWORK', 'ACTIVATED', 'UNASSIGN', 'FAIL'), +('NETWORK', 'ACTIVATED', 'ACTIVATE', 'SILENT_SUCCESS'), +('NETWORK', 'ACTIVATED', 'DEACTIVATE', 'CONTINUE'), +('NETWORK', 'ACTIVATED', 'CREATE', 'SILENT_SUCCESS'), +('NETWORK', 'ACTIVATED', 'DELETE', 'FAIL'), +('NETWORK', 'ACTIVATED', 'UPDATE', 'CONTINUE'), +('NETWORK_COLLECTION', 'ACTIVATED', 'CREATE', 'FAIL'), +('NETWORK_COLLECTION', 'ACTIVATED', 'DELETE', 'CONTINUE'), +('NETWORK_COLLECTION', 'ACTIVATED', 'ACTIVATE', 'SILENT_SUCCESS'), + +('NO_VALIDATE', 'ACTIVATED', 'CUSTOM', 'CONTINUE'), + +('SERVICE', 'ACTIVATED', 'ASSIGN', 'SILENT_SUCCESS'), +('SERVICE', 'ACTIVATED', 'UNASSIGN', 'FAIL'), +('SERVICE', 'ACTIVATED', 'ACTIVATE', 'SILENT_SUCCESS'), +('SERVICE', 'ACTIVATED', 'DEACTIVATE', 'CONTINUE'), +('SERVICE', 'ACTIVATED', 'CHANGE_MODEL', 'CONTINUE'), + +('VF_MODULE', 'ACTIVATED', 'ASSIGN', 'SILENT_SUCCESS'), +('VF_MODULE', 'ACTIVATED', 'UNASSIGN', 'FAIL'), +('VF_MODULE', 'ACTIVATED', 'ACTIVATE', 'SILENT_SUCCESS'), +('VF_MODULE', 'ACTIVATED', 'DEACTIVATE', 'CONTINUE'), +('VF_MODULE', 'ACTIVATED', 'CHANGE_MODEL', 'CONTINUE'), +('VF_MODULE', 'ACTIVATED', 'CREATE', 'SILENT_SUCCESS'), +('VF_MODULE', 'ACTIVATED', 'DELETE', 'FAIL'), + +('VNF', 'ACTIVATED', 'ASSIGN', 'SILENT_SUCCESS'), +('VNF', 'ACTIVATED', 'UNASSIGN', 'FAIL'), +('VNF', 'ACTIVATED', 'ACTIVATE', 'SILENT_SUCCESS'), +('VNF', 'ACTIVATED', 'DEACTIVATE', 'CONTINUE'), +('VNF', 'ACTIVATED', 'CHANGE_MODEL', 'CONTINUE'), + +('VOLUME_GROUP', 'ACTIVATED', 'ASSIGN', 'SILENT_SUCCESS'), +('VOLUME_GROUP', 'ACTIVATED', 'UNASSIGN', 'FAIL'), +('VOLUME_GROUP', 'ACTIVATED', 'ACTIVATE', 'SILENT_SUCCESS'), +('VOLUME_GROUP', 'ACTIVATED', 'DEACTIVATE', 'CONTINUE'), +('VOLUME_GROUP', 'ACTIVATED', 'CREATE', 'SILENT_SUCCESS'), +('VOLUME_GROUP', 'ACTIVATED', 'DELETE', 'FAIL');
\ No newline at end of file diff --git a/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/CatalogDBRestTest.java b/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/CatalogDBRestTest.java index 145ba50583..e1cca8901e 100644 --- a/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/CatalogDBRestTest.java +++ b/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/CatalogDBRestTest.java @@ -22,13 +22,13 @@ package org.onap.so.adapters.catalogdb.catalogrest; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; -import static org.onap.so.logger.MdcConstants.ENDTIME; -import static org.onap.so.logger.MdcConstants.INVOCATION_ID; -import static org.onap.so.logger.MdcConstants.PARTNERNAME; -import static org.onap.so.logger.MdcConstants.RESPONSECODE; -import static org.onap.so.logger.MdcConstants.RESPONSEDESC; -import static org.onap.so.logger.MdcConstants.SERVICE_NAME; -import static org.onap.so.logger.MdcConstants.STATUSCODE; +import static org.onap.logging.ref.slf4j.ONAPLogConstants.MDCs.INVOCATION_ID; +import static org.onap.logging.ref.slf4j.ONAPLogConstants.MDCs.LOG_TIMESTAMP; +import static org.onap.logging.ref.slf4j.ONAPLogConstants.MDCs.PARTNER_NAME; +import static org.onap.logging.ref.slf4j.ONAPLogConstants.MDCs.RESPONSE_CODE; +import static org.onap.logging.ref.slf4j.ONAPLogConstants.MDCs.RESPONSE_DESCRIPTION; +import static org.onap.logging.ref.slf4j.ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE; +import static org.onap.logging.ref.slf4j.ONAPLogConstants.MDCs.SERVICE_NAME; import java.io.IOException; import java.util.Map; import javax.ws.rs.core.MediaType; @@ -815,27 +815,27 @@ public class CatalogDBRestTest extends CatalogDbAdapterBaseTest { for (ILoggingEvent logEvent : TestAppender.events) - if (logEvent.getLoggerName().equals("org.onap.so.logging.jaxrs.filter.jersey.JaxRsFilterLogging") + if (logEvent.getLoggerName().equals("org.onap.so.logging.jaxrs.filter.SOAuditLogContainerFilter") && logEvent.getMarker().getName().equals("ENTRY")) { Map<String, String> mdc = logEvent.getMDCPropertyMap(); assertNotNull(mdc.get(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP)); assertNotNull(mdc.get(ONAPLogConstants.MDCs.REQUEST_ID)); assertNotNull(mdc.get(INVOCATION_ID)); - assertEquals("UNKNOWN", mdc.get(PARTNERNAME)); + assertEquals("UNKNOWN", mdc.get(PARTNER_NAME)); assertEquals("v2/vfModules", mdc.get(SERVICE_NAME)); - assertEquals("INPROGRESS", mdc.get(STATUSCODE)); - } else if (logEvent.getLoggerName().equals("org.onap.so.logging.jaxrs.filter.jersey.JaxRsFilterLogging") + assertEquals("INPROGRESS", mdc.get(RESPONSE_STATUS_CODE)); + } else if (logEvent.getLoggerName().equals("org.onap.so.logging.jaxrs.filter.SOAuditLogContainerFilter") && logEvent.getMarker().getName().equals("EXIT")) { Map<String, String> mdc = logEvent.getMDCPropertyMap(); assertNotNull(mdc.get(ONAPLogConstants.MDCs.ENTRY_TIMESTAMP)); - assertNotNull(mdc.get(ENDTIME)); + assertNotNull(mdc.get(LOG_TIMESTAMP)); assertNotNull(mdc.get(ONAPLogConstants.MDCs.REQUEST_ID)); assertNotNull(mdc.get(INVOCATION_ID)); - assertEquals("500", mdc.get(RESPONSECODE)); - assertEquals("UNKNOWN", mdc.get(PARTNERNAME)); + assertEquals("500", mdc.get(RESPONSE_CODE)); + assertEquals("UNKNOWN", mdc.get(PARTNER_NAME)); assertEquals("v2/vfModules", mdc.get(SERVICE_NAME)); - assertEquals("ERROR", mdc.get(STATUSCODE)); - assertNotNull(mdc.get(RESPONSEDESC)); + assertEquals("ERROR", mdc.get(RESPONSE_STATUS_CODE)); + assertNotNull(mdc.get(RESPONSE_DESCRIPTION)); } } diff --git a/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/db/catalog/client/CatalogDbClientTest.java b/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/db/catalog/client/CatalogDbClientTest.java index f82c7acd38..707a2a45af 100644 --- a/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/db/catalog/client/CatalogDbClientTest.java +++ b/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/db/catalog/client/CatalogDbClientTest.java @@ -22,6 +22,7 @@ package org.onap.so.db.catalog.client; import static org.junit.Assert.assertEquals; +import static org.junit.Assert.assertNotEquals; import static org.junit.Assert.assertFalse; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; @@ -733,4 +734,12 @@ public class CatalogDbClientTest extends CatalogDbAdapterBaseTest { assertNull(workflow); } + @Test + public void getCloudSites() { + List<CloudSite> cloudSites = client.getCloudSites(); + assertNotNull(cloudSites); + assertNotEquals(0, cloudSites.size()); + } + + } 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 index 8edce124ec..0c05df959f 100644 --- 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 @@ -22,19 +22,18 @@ package org.onap.so.adapters.audit; import java.util.Optional; -import org.camunda.bpm.client.task.ExternalTask; -import org.onap.logging.ref.slf4j.ONAPLogConstants; import org.onap.so.objects.audit.AAIObjectAudit; import org.onap.so.objects.audit.AAIObjectAuditList; +import org.onap.so.utils.ExternalTaskUtils; +import org.onap.logging.filter.base.ONAPComponents; import org.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.slf4j.MDC; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; @Component -public abstract class AbstractAuditService { +public abstract class AbstractAuditService extends ExternalTaskUtils { private static final Logger logger = LoggerFactory.getLogger(AbstractAuditService.class); @@ -81,23 +80,4 @@ public abstract class AbstractAuditService { return false; } } - - protected String[] getRetrySequence() { - return env.getProperty("mso.workflow.topics.retrySequence", String[].class); - } - - protected void setupMDC(ExternalTask externalTask) { - logger.info(ONAPLogConstants.Markers.ENTRY, "Entering"); - 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()); - } - - protected long calculateRetryDelay(int currentRetries) { - int retrySequence = getRetrySequence().length - currentRetries; - long retryMultiplier = Long.parseLong(env.getProperty("mso.workflow.topics.retryMultiplier", "6000")); - return Integer.parseInt(getRetrySequence()[retrySequence]) * retryMultiplier; - } } 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 index 1e5b6de857..54ffc597f4 100644 --- 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 @@ -30,11 +30,11 @@ 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 @@ -46,16 +46,16 @@ public class AuditCreateStackService extends AbstractAuditService { public HeatStackAudit heatStackAudit; @Autowired - public Environment environment; + private AuditMDCSetup mdcSetup; protected void executeExternalTask(ExternalTask externalTask, ExternalTaskService externalTaskService) { - setupMDC(externalTask); + mdcSetup.setupMDC(externalTask); AuditInventory auditInventory = externalTask.getVariable("auditInventory"); Map<String, Object> variables = new HashMap<>(); boolean success = false; try { - logger.info("Executing External Task Audit Inventory, Retry Number: {} \n {}", auditInventory, - externalTask.getRetries()); + Integer retryCount = externalTask.getRetries(); + logger.info("Executing External Task Audit Inventory, Retry Number: {} \n {}", auditInventory, retryCount); Optional<AAIObjectAuditList> auditListOpt = heatStackAudit.auditHeatStack(auditInventory.getCloudRegion(), auditInventory.getCloudOwner(), auditInventory.getTenantId(), auditInventory.getHeatStackName()); if (auditListOpt.isPresent()) { @@ -69,29 +69,35 @@ public class AuditCreateStackService extends AbstractAuditService { logger.error("Error during audit of stack", e); } variables.put("auditIsSuccessful", success); + mdcSetup.setElapsedTime(); + String externalTaskId = externalTask.getId(); if (success) { externalTaskService.complete(externalTask, variables); - logger.debug("The External Task Id: {} Successful", externalTask.getId()); + mdcSetup.setResponseCode(ONAPLogConstants.ResponseStatus.COMPLETE.toString()); + logger.debug("The External Task Id: {} Successful", externalTaskId); logger.info(ONAPLogConstants.Markers.EXIT, "Exiting"); + mdcSetup.clearClientMDCs(); } else { - if (externalTask.getRetries() == null) { + Integer retryCount = externalTask.getRetries(); + if (retryCount == null) { logger.debug("The External Task Id: {} Failed, Setting Retries to Default Start Value: {}", - externalTask.getId(), getRetrySequence().length); + 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 (externalTask.getRetries() != null && externalTask.getRetries() - 1 == 0) { - logger.debug("The External Task Id: {} Failed, All Retries Exhausted", externalTask.getId()); + } else if (retryCount != null && retryCount - 1 == 0) { 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: ", - externalTask.getId(), externalTask.getRetries() - 1, - calculateRetryDelay(externalTask.getRetries())); + 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, externalTask.getRetries() - 1, - calculateRetryDelay(externalTask.getRetries())); + UNABLE_TO_FIND_ALL_V_SERVERS_AND_L_INTERACES_IN_A_AI, retryCount - 1, + calculateRetryDelay(retryCount)); } - logger.debug("The External Task Id: {} Failed", externalTask.getId()); + logger.debug("The External Task Id: {} Failed", externalTaskId); } } 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 index 0aa4f9bdc3..9a4f154347 100644 --- 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 @@ -28,6 +28,7 @@ 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; @@ -44,6 +45,9 @@ public class AuditDeleteStackService extends AbstractAuditService { protected HeatStackAudit heatStackAudit; @Autowired + private AuditMDCSetup mdcSetup; + + @Autowired protected AuditVServer auditVservers; @Autowired @@ -53,12 +57,13 @@ public class AuditDeleteStackService extends AbstractAuditService { protected Environment env; protected void executeExternalTask(ExternalTask externalTask, ExternalTaskService externalTaskService) { - setupMDC(externalTask); + mdcSetup.setupMDC(externalTask); AuditInventory auditInventory = externalTask.getVariable("auditInventory"); Map<String, Object> variables = new HashMap<>(); boolean success = false; try { - logger.info("Executing External Task Delete Audit Inventory. Retry Number: {}", externalTask.getRetries()); + Integer retryCount = externalTask.getRetries(); + logger.info("Executing External Task Delete Audit Inventory. Retry Number: {}", retryCount); Optional<AAIObjectAuditList> auditListOpt = auditDataService.getStackDataFromRequestDb(auditInventory); if (auditListOpt.isPresent()) { auditVservers.auditVservers(auditListOpt.get()); @@ -77,29 +82,35 @@ public class AuditDeleteStackService extends AbstractAuditService { logger.error("Error during audit of stack", e); } variables.put("auditIsSuccessful", success); + mdcSetup.setElapsedTime(); + String externalTaskId = externalTask.getId(); if (success) { externalTaskService.complete(externalTask, variables); - logger.debug("The External Task Id: {} Successful", externalTask.getId()); + mdcSetup.setResponseCode(ONAPLogConstants.ResponseStatus.COMPLETE.toString()); + logger.debug("The External Task Id: {} Successful", externalTaskId); logger.info(ONAPLogConstants.Markers.EXIT, "Exiting"); + mdcSetup.clearClientMDCs(); } else { - if (externalTask.getRetries() == null) { + Integer retryCount = externalTask.getRetries(); + if (retryCount == null) { logger.debug("The External Task Id: {} Failed, Setting Retries to Default Start Value: {}", - externalTask.getId(), getRetrySequence().length); + 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 (externalTask.getRetries() != null && externalTask.getRetries() - 1 == 0) { - logger.debug("The External Task Id: {} Failed, All Retries Exhausted", externalTask.getId()); + } else if (retryCount != null && retryCount - 1 == 0) { 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: ", - externalTask.getId(), externalTask.getRetries() - 1, - calculateRetryDelay(externalTask.getRetries())); + 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, externalTask.getRetries() - 1, - calculateRetryDelay(externalTask.getRetries())); + UNABLE_TO_FIND_ALL_V_SERVERS_AND_L_INTERACES_IN_A_AI, retryCount - 1, + calculateRetryDelay(retryCount)); } - logger.debug("The External Task Id: {} Failed", externalTask.getId()); + 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 index 2ef7d5b325..dc672ff017 100644 --- 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 @@ -7,6 +7,7 @@ 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; @@ -22,47 +23,56 @@ public class AuditQueryStackService extends AbstractAuditService { protected HeatStackAudit heatStackAudit; @Autowired + private AuditMDCSetup mdcSetup; + + @Autowired protected AuditDataService auditDataService; protected void executeExternalTask(ExternalTask externalTask, ExternalTaskService externalTaskService) { - setupMDC(externalTask); + mdcSetup.setupMDC(externalTask); AuditInventory auditInventory = externalTask.getVariable("auditInventory"); boolean success = false; Map<String, Object> variables = new HashMap<>(); try { + Integer retryCount = externalTask.getRetries(); logger.info("Executing External Task Query Audit Inventory. Audit Inventory: {} \n Retry Number: {}", - auditInventory.toString(), externalTask.getRetries()); + auditInventory.toString(), retryCount); Optional<AAIObjectAuditList> 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); - logger.debug("The External Task {} was Successful", externalTask.getId()); + mdcSetup.setResponseCode(ONAPLogConstants.ResponseStatus.COMPLETE.toString()); + logger.debug("The External Task {} was Successful", externalTaskId); logger.info(ONAPLogConstants.Markers.EXIT, "Exiting"); + mdcSetup.clearClientMDCs(); } else { - if (externalTask.getRetries() == null) { + if (retryCount == null) { logger.debug("The External Task {} Failed. Setting Retries to Default Start Value: {}", - externalTask.getId(), getRetrySequence().length); + 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 (externalTask.getRetries() != null && externalTask.getRetries() - 1 == 0) { - logger.debug("The External Task {} Failed. All Retries Exhausted", externalTask.getId()); + } else if (retryCount != null && retryCount - 1 == 0) { 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: ", - externalTask.getId(), externalTask.getRetries() - 1, - calculateRetryDelay(externalTask.getRetries())); + externalTaskId, retryCount - 1, calculateRetryDelay(retryCount)); externalTaskService.handleFailure(externalTask, UNABLE_TO_FIND_V_SERVERS_IN_OPENSTACK, - UNABLE_TO_FIND_V_SERVERS_IN_OPENSTACK, externalTask.getRetries() - 1, - calculateRetryDelay(externalTask.getRetries())); + UNABLE_TO_FIND_V_SERVERS_IN_OPENSTACK, retryCount - 1, calculateRetryDelay(retryCount)); } - logger.debug("The External Task {} Failed", externalTask.getId()); + 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 index 6a42456715..fb7e925d88 100644 --- 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 @@ -20,13 +20,9 @@ package org.onap.so.adapters.audit; -import java.security.GeneralSecurityException; import javax.annotation.PostConstruct; import org.camunda.bpm.client.ExternalTaskClient; -import org.camunda.bpm.client.backoff.ExponentialBackoffStrategy; -import org.camunda.bpm.client.interceptor.ClientRequestInterceptor; -import org.camunda.bpm.client.interceptor.auth.BasicAuthProvider; -import org.onap.so.utils.CryptoUtils; +import org.onap.so.utils.ExternalTaskServiceUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -56,10 +52,13 @@ public class AuditStackService { @Autowired private AuditQueryStackService auditQueryStack; + @Autowired + private ExternalTaskServiceUtils externalTaskServiceUtils; + @PostConstruct - public void auditAddAAIInventory() { - for (int i = 0; i < getMaxClients(); i++) { - ExternalTaskClient client = createExternalTaskClient(); + 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(); @@ -67,9 +66,9 @@ public class AuditStackService { } @PostConstruct - public void auditDeleteAAIInventory() { - for (int i = 0; i < getMaxClients(); i++) { - ExternalTaskClient client = createExternalTaskClient(); + 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(); @@ -77,35 +76,13 @@ public class AuditStackService { } @PostConstruct - public void auditQueryInventory() { - for (int i = 0; i < getMaxClients(); i++) { - ExternalTaskClient client = createExternalTaskClient(); + 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(); } } - protected ExternalTaskClient createExternalTaskClient() { - ClientRequestInterceptor interceptor = createClientRequestInterceptor(); - return ExternalTaskClient.create().baseUrl(env.getRequiredProperty("mso.workflow.endpoint")).maxTasks(1) - .addInterceptor(interceptor).asyncResponseTimeout(120000) - .backoffStrategy(new ExponentialBackoffStrategy(0, 0, 0)).build(); - } - - protected ClientRequestInterceptor createClientRequestInterceptor() { - String auth = ""; - try { - auth = CryptoUtils.decrypt(env.getRequiredProperty("mso.auth"), env.getRequiredProperty("mso.msoKey")); - } catch (IllegalStateException | GeneralSecurityException e) { - logger.error("Error Decrypting Password", e); - } - return new BasicAuthProvider(env.getRequiredProperty("mso.config.cadi.aafId"), auth); - } - - protected int getMaxClients() { - return Integer.parseInt(env.getProperty("workflow.topics.maxClients", DEFAULT_MAX_CLIENTS_FOR_TOPIC)); - } - - } 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 index 49a9e7e171..c1cc7428ee 100644 --- 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 @@ -20,13 +20,9 @@ package org.onap.so.adapters.inventory.create; -import java.security.GeneralSecurityException; import javax.annotation.PostConstruct; import org.camunda.bpm.client.ExternalTaskClient; -import org.camunda.bpm.client.backoff.ExponentialBackoffStrategy; -import org.camunda.bpm.client.interceptor.ClientRequestInterceptor; -import org.camunda.bpm.client.interceptor.auth.BasicAuthProvider; -import org.onap.so.utils.CryptoUtils; +import org.onap.so.utils.ExternalTaskServiceUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -46,19 +42,13 @@ public class CreateInventoryService { @Autowired private CreateInventoryTask createInventory; + @Autowired + private ExternalTaskServiceUtils externalTaskServiceUtils; + @PostConstruct - public void auditAAIInventory() { - String auth = ""; - try { - auth = CryptoUtils.decrypt(env.getRequiredProperty("mso.auth"), env.getRequiredProperty("mso.msoKey")); - } catch (IllegalStateException | GeneralSecurityException e) { - logger.error("Error Decrypting Password", e); - } - ClientRequestInterceptor interceptor = - new BasicAuthProvider(env.getRequiredProperty("mso.config.cadi.aafId"), auth); - ExternalTaskClient client = ExternalTaskClient.create() - .baseUrl(env.getRequiredProperty("mso.workflow.endpoint")).maxTasks(1).addInterceptor(interceptor) - .asyncResponseTimeout(120000).backoffStrategy(new ExponentialBackoffStrategy(0, 0, 0)).build(); + 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 index a6c61704ad..3d2d1d2aa3 100644 --- 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 @@ -26,16 +26,16 @@ 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.slf4j.Logger; import org.slf4j.LoggerFactory; -import org.slf4j.MDC; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; @Component -public class CreateInventoryTask { +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"; @@ -47,24 +47,28 @@ public class CreateInventoryTask { CreateAAIInventory createInventory; @Autowired - public Environment env; + private AuditMDCSetup mdcSetup; protected void executeExternalTask(ExternalTask externalTask, ExternalTaskService externalTaskService) { - setupMDC(externalTask); + 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, - externalTask.getRetries()); + retryCount); createInventory.createInventory(auditInventory); } catch (InventoryException e) { logger.error("Error during inventory of stack", e); @@ -74,58 +78,39 @@ public class CreateInventoryTask { logger.error("Error during inventory of stack", e); success = false; } + mdcSetup.setElapsedTime(); if (success) { externalTaskService.complete(externalTask); - logger.debug("The External Task Id: {} Successful", externalTask.getId()); + 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) { - logger.debug("The External Task Id: {} Failed, Retry not needed", externalTask.getId()); + 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 (externalTask.getRetries() == null) { + if (retryCount == null) { logger.debug("The External Task Id: {} Failed, Setting Retries to Default Start Value: {}", - externalTask.getId(), getRetrySequence().length); + 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 (externalTask.getRetries() != null && externalTask.getRetries() - 1 == 0) { - logger.debug("The External Task Id: {} Failed, All Retries Exhausted", externalTask.getId()); + } 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: ", - externalTask.getId(), externalTask.getRetries() - 1, - calculateRetryDelay(externalTask.getRetries())); + externalTaskId, retryCount - 1, calculateRetryDelay(retryCount)); externalTaskService.handleFailure(externalTask, UNABLE_TO_WRITE_ALL_INVENTORY_TO_A_AI, - UNABLE_TO_WRITE_ALL_INVENTORY_TO_A_AI, externalTask.getRetries() - 1, - calculateRetryDelay(externalTask.getRetries())); + UNABLE_TO_WRITE_ALL_INVENTORY_TO_A_AI, retryCount - 1, calculateRetryDelay(retryCount)); } - logger.debug("The External Task Id: {} Failed", externalTask.getId()); + logger.debug("The External Task Id: {} Failed", externalTaskId); } } else { - logger.debug("The External Task Id: {} Failed, No Audit Results Written", externalTask.getId()); + logger.debug("The External Task Id: {} Failed, No Audit Results Written", externalTaskId); externalTaskService.handleBpmnError(externalTask, AAI_INVENTORY_FAILURE); } } - - private void setupMDC(ExternalTask externalTask) { - try { - logger.info(ONAPLogConstants.Markers.ENTRY, "Entering"); - MDC.put(ONAPLogConstants.MDCs.SERVICE_NAME, externalTask.getTopicName()); - String msoRequestId = externalTask.getVariable("mso-request-id"); - if (msoRequestId != null && !msoRequestId.isEmpty()) - MDC.put(ONAPLogConstants.MDCs.REQUEST_ID, msoRequestId); - } catch (Exception e) { - logger.error("Error in setting up MDC", e); - } - } - - protected long calculateRetryDelay(int currentRetries) { - int retrySequence = getRetrySequence().length - currentRetries; - long retryMultiplier = Long.parseLong(env.getProperty("mso.workflow.topics.retryMultiplier", "6000")); - return Integer.parseInt(getRetrySequence()[retrySequence]) * retryMultiplier; - } - - public String[] getRetrySequence() { - return env.getProperty("mso.workflow.topics.retrySequence", String[].class); - } } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/MsoNetworkAdapterImpl.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/MsoNetworkAdapterImpl.java index 013c7f8a84..52b97da61a 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/MsoNetworkAdapterImpl.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/MsoNetworkAdapterImpl.java @@ -24,8 +24,6 @@ package org.onap.so.adapters.network; -import com.fasterxml.jackson.databind.JsonNode; -import com.fasterxml.jackson.databind.ObjectMapper; import java.util.ArrayList; import java.util.HashMap; import java.util.List; @@ -33,7 +31,6 @@ import java.util.Map; import java.util.Optional; import javax.jws.WebService; import javax.xml.ws.Holder; -import org.onap.so.logger.LoggingAnchor; import org.onap.so.adapters.network.beans.ContrailPolicyRef; import org.onap.so.adapters.network.beans.ContrailPolicyRefSeq; import org.onap.so.adapters.network.beans.ContrailSubnet; @@ -51,6 +48,7 @@ import org.onap.so.db.catalog.data.repository.NetworkResourceRepository; import org.onap.so.db.catalog.utils.MavenLikeVersioning; import org.onap.so.entity.MsoRequest; import org.onap.so.logger.ErrorCode; +import org.onap.so.logger.LoggingAnchor; import org.onap.so.logger.MessageEnum; import org.onap.so.openstack.beans.HeatStatus; import org.onap.so.openstack.beans.NetworkInfo; @@ -74,6 +72,8 @@ import org.springframework.beans.factory.annotation.Autowired; import org.springframework.core.env.Environment; import org.springframework.stereotype.Component; import org.springframework.transaction.annotation.Transactional; +import com.fasterxml.jackson.databind.JsonNode; +import com.fasterxml.jackson.databind.ObjectMapper; @Component @Transactional @@ -427,7 +427,8 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter { if (backout == null) backout = true; heatStack = heat.createStack(cloudSiteId, CLOUD_OWNER, tenantId, networkName, null, template, - stackParams, true, heatTemplate.getTimeoutMinutes(), null, null, null, backout.booleanValue()); + stackParams, true, heatTemplate.getTimeoutMinutes(), null, null, null, backout.booleanValue(), + failIfExists); } catch (MsoException me) { me.addContext(CREATE_NETWORK_CONTEXT); logger.error("{} {} Exception creating network type {} in {}/{} ", MessageEnum.RA_CREATE_NETWORK_EXC, @@ -1015,13 +1016,7 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter { @Override public void deleteNetwork(String cloudSiteId, String tenantId, String networkType, String modelCustomizationUuid, String networkId, MsoRequest msoRequest, Holder<Boolean> networkDeleted) throws NetworkException { - logger.debug("*** DELETE Network adapter with Network: {} in {}/{}", networkId, cloudSiteId, tenantId); - - // Will capture execution time for metrics - long startTime = System.currentTimeMillis(); - - if (commonUtils.isNullOrEmpty(cloudSiteId) || commonUtils.isNullOrEmpty(tenantId) || commonUtils.isNullOrEmpty(networkId)) { String error = "Missing mandatory parameter cloudSiteId, tenantId or networkId"; @@ -1043,20 +1038,15 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter { networkResource = nrc.getNetworkResource(); } } + String mode = ""; if (networkResource != null) { - logger.debug(LOG_DEBUG_MSG, networkResource); - + logger.debug(LOG_DEBUG_MSG, networkResource.toString()); mode = networkResource.getOrchestrationMode(); } if (NEUTRON_MODE.equals(mode)) { - - // Use MsoNeutronUtils for all NEUTRON commands - long deleteNetworkStarttime = System.currentTimeMillis(); try { - // The deleteNetwork function in MsoNeutronUtils returns success if the network - // was not found. So don't bother to query first. boolean deleted = neutron.deleteNetwork(networkId, tenantId, cloudSiteId); networkDeleted.value = deleted; } catch (MsoException me) { @@ -1065,21 +1055,10 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter { ErrorCode.DataError.getValue(), networkId, cloudSiteId, tenantId, me); throw new NetworkException(me); } - } else { // DEFAULT to ("HEAT".equals (mode)) - long deleteStackStarttime = System.currentTimeMillis(); - + } else { try { - // The deleteStack function in MsoHeatUtils returns NOTFOUND if the stack was not found or if the stack - // was deleted. - // So query first to report back if stack WAS deleted or just NOTOFUND - StackInfo heatStack = null; - heatStack = heat.queryStack(cloudSiteId, CLOUD_OWNER, tenantId, networkId); - if (heatStack != null && heatStack.getStatus() != HeatStatus.NOTFOUND) { - heat.deleteStack(tenantId, CLOUD_OWNER, cloudSiteId, networkId, true); - networkDeleted.value = true; - } else { - networkDeleted.value = false; - } + heat.deleteStack(tenantId, CLOUD_OWNER, cloudSiteId, networkId, true, 120); + networkDeleted.value = true; } catch (MsoException me) { me.addContext("DeleteNetwork"); logger.error("{} {} Delete Network (heat): {} in {}/{} ", MessageEnum.RA_DELETE_NETWORK_EXC, @@ -1087,10 +1066,6 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter { throw new NetworkException(me); } } - - - // On success, nothing is returned. - return; } /** @@ -1103,9 +1078,6 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter { */ @Override public void rollbackNetwork(NetworkRollback rollback) throws NetworkException { - // Will capture execution time for metrics - long startTime = System.currentTimeMillis(); - if (rollback == null) { logger.error("{} {} rollback is null", MessageEnum.RA_ROLLBACK_NULL, ErrorCode.DataError.getValue()); return; @@ -1119,8 +1091,6 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter { String modelCustomizationUuid = rollback.getModelCustomizationUuid(); logger.debug("*** ROLLBACK Network {} in {}/{}", networkId, cloudSiteId, tenantId); - - // Retrieve the Network Resource definition NetworkResource networkResource = null; if (commonUtils.isNullOrEmpty(modelCustomizationUuid)) { @@ -1138,13 +1108,8 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter { } if (rollback.getNetworkCreated()) { - // Rolling back a newly created network, so delete it. if (NEUTRON_MODE.equals(mode)) { - // Use MsoNeutronUtils for all NEUTRON commands - long deleteNetworkStarttime = System.currentTimeMillis(); try { - // The deleteNetwork function in MsoNeutronUtils returns success if the network - // was not found. So don't bother to query first. neutron.deleteNetwork(networkId, tenantId, cloudSiteId); } catch (MsoException me) { me.addContext("RollbackNetwork"); @@ -1153,12 +1118,9 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter { cloudSiteId, tenantId, me); throw new NetworkException(me); } - } else { // DEFAULT to if ("HEAT".equals (mode)) - long deleteStackStarttime = System.currentTimeMillis(); + } else { try { - // The deleteStack function in MsoHeatUtils returns success if the stack - // was not found. So don't bother to query first. - heat.deleteStack(tenantId, CLOUD_OWNER, cloudSiteId, networkId, true); + heat.deleteStack(tenantId, CLOUD_OWNER, cloudSiteId, networkId, true, 120); } catch (MsoException me) { me.addContext("RollbackNetwork"); logger.error("{} {} Exception - Rollback Network (heat): {} in {}/{} ", @@ -1168,8 +1130,6 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter { } } } - - return; } private String validateNetworkParams(NetworkType neutronNetworkType, String networkName, String physicalNetwork, diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/openstack/MsoOpenstackAdaptersApplication.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/openstack/MsoOpenstackAdaptersApplication.java index 436836491d..d9a83e6a9a 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/openstack/MsoOpenstackAdaptersApplication.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/openstack/MsoOpenstackAdaptersApplication.java @@ -21,7 +21,7 @@ package org.onap.so.adapters.openstack; import java.util.concurrent.Executor; -import org.onap.so.logging.jaxrs.filter.MDCTaskDecorator; +import org.onap.logging.filter.spring.MDCTaskDecorator; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; 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 af2fa24ff9..2c78e593a1 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 @@ -36,7 +36,6 @@ import java.util.Optional; import java.util.concurrent.TimeUnit; import javax.jws.WebService; import javax.xml.ws.Holder; -import org.onap.so.logger.LoggingAnchor; import org.apache.commons.collections.CollectionUtils; import org.onap.so.adapters.valet.GenericValetResponse; import org.onap.so.adapters.valet.ValetClient; @@ -47,7 +46,6 @@ import org.onap.so.adapters.valet.beans.ValetDeleteResponse; import org.onap.so.adapters.valet.beans.ValetRollbackResponse; import org.onap.so.adapters.valet.beans.ValetStatus; import org.onap.so.adapters.valet.beans.ValetUpdateResponse; -import org.onap.so.adapters.vnf.exceptions.VnfAlreadyExists; import org.onap.so.adapters.vnf.exceptions.VnfException; import org.onap.so.adapters.vnf.exceptions.VnfNotFound; import org.onap.so.client.aai.AAIResourcesClient; @@ -68,6 +66,7 @@ import org.onap.so.entity.MsoRequest; import org.onap.so.heatbridge.HeatBridgeApi; import org.onap.so.heatbridge.HeatBridgeImpl; import org.onap.so.logger.ErrorCode; +import org.onap.so.logger.LoggingAnchor; import org.onap.so.logger.MessageEnum; import org.onap.so.openstack.beans.HeatStatus; import org.onap.so.openstack.beans.StackInfo; @@ -80,6 +79,10 @@ import org.onap.so.openstack.exceptions.MsoHeatNotFoundException; import org.onap.so.openstack.utils.MsoHeatEnvironmentEntry; import org.onap.so.openstack.utils.MsoHeatUtils; import org.onap.so.openstack.utils.MsoHeatUtilsWithUpdate; +import org.openstack4j.model.compute.Flavor; +import org.openstack4j.model.compute.Image; +import org.openstack4j.model.compute.Server; +import org.openstack4j.model.heat.Resource; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -89,10 +92,6 @@ import org.springframework.transaction.annotation.Transactional; import com.fasterxml.jackson.core.JsonParseException; import com.fasterxml.jackson.databind.JsonNode; import com.fasterxml.jackson.databind.ObjectMapper; -import org.openstack4j.model.compute.Flavor; -import org.openstack4j.model.compute.Image; -import org.openstack4j.model.compute.Server; -import org.openstack4j.model.heat.Resource; @WebService(serviceName = "VnfAdapter", endpointInterface = "org.onap.so.adapters.vnf.MsoVnfAdapter", targetNamespace = "http://org.onap.so/vnf") @@ -133,7 +132,7 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { @Autowired private MsoHeatUtilsWithUpdate heatU; @Autowired - private MsoHeatUtils heat; + private MsoHeatUtils msoHeatUtils; @Autowired private ValetClient vci; @@ -264,7 +263,7 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { StackInfo heatStack; try { - heatStack = heat.queryStack(cloudSiteId, cloudOwner, tenantId, vnfName); + heatStack = msoHeatUtils.queryStack(cloudSiteId, cloudOwner, tenantId, vnfName); } catch (MsoException me) { me.addContext("QueryVNF"); // Failed to query the Stack due to an openstack exception. @@ -317,7 +316,7 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { logger.debug("Deleting VNF {} in {}", vnfName, cloudSiteId + "/" + tenantId); try { - heat.deleteStack(tenantId, cloudOwner, cloudSiteId, vnfName, true); + msoHeatUtils.deleteStack(tenantId, cloudOwner, cloudSiteId, vnfName, true, 118); } catch (MsoException me) { me.addContext(DELETE_VNF); // Failed to query the Stack due to an openstack exception. @@ -360,7 +359,7 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { // of NOTFOUND (on success) or FAILED (on error). Also, MsoOpenstackException // could be thrown. try { - heat.deleteStack(tenantId, cloudOwner, cloudSiteId, vnfId, true); + msoHeatUtils.deleteStack(tenantId, cloudOwner, cloudSiteId, vnfId, true, 118); } catch (MsoException me) { // Failed to rollback the Stack due to an openstack exception. // Convert to a generic VnfException @@ -638,96 +637,13 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { callHeatbridge(baseVfHeatStackId); } - StackInfo heatStack = null; - try { - if (heat != null) { - heatStack = heat.queryStack(cloudSiteId, cloudOwner, tenantId, vfModuleName); - } else { - throw new MsoHeatNotFoundException(); - } - } catch (MsoException me) { - String error = "Create VF Module: Query " + vfModuleName + " in " + cloudOwner + "/" + cloudSiteId + "/" - + tenantId + ": " + me; - logger.error(LoggingAnchor.NINE, MessageEnum.RA_QUERY_VNF_ERR.toString(), vfModuleName, cloudOwner, - cloudSiteId, tenantId, OPENSTACK, QUERY_STACK, ErrorCode.DataError.getValue(), - "Exception - " + QUERY_STACK, me); - logger.debug(error); - // Failed to query the Stack due to an openstack exception. - // Convert to a generic VnfException - me.addContext(CREATE_VFM_MODULE); - throw new VnfException(me); - } - // more precise handling/messaging if the stack already exists - if (heatStack != null && heatStack.getStatus() != HeatStatus.NOTFOUND) { - // INIT, CREATED, NOTFOUND, FAILED, BUILDING, DELETING, UNKNOWN, UPDATING, UPDATED - HeatStatus status = heatStack.getStatus(); - if (status == HeatStatus.INIT || status == HeatStatus.BUILDING || status == HeatStatus.DELETING - || status == HeatStatus.UPDATING) { - // fail - it's in progress - return meaningful error - String error = CREATE_VF_STACK + " " + vfModuleName + " already exists and has status " - + status.toString() + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId - + "; please wait for it to complete, or fix manually."; - logger.error(LoggingAnchor.NINE, MessageEnum.RA_VNF_ALREADY_EXIST.toString(), vfModuleName, cloudOwner, - cloudSiteId, tenantId, OPENSTACK, QUERY_STACK, ErrorCode.DataError.getValue(), - STACK + " " + vfModuleName + " already exists"); - logger.debug(error); - throw new VnfAlreadyExists(vfModuleName, cloudOwner, cloudSiteId, tenantId, - heatStack.getCanonicalName()); - } - if (status == HeatStatus.FAILED) { - // fail - it exists and is in a FAILED state - String error = CREATE_VF_STACK + " " + vfModuleName + " already exists and is in FAILED state in " - + cloudOwner + "/" + cloudSiteId + "/" + tenantId + "; requires manual intervention."; - logger.error(LoggingAnchor.NINE, MessageEnum.RA_VNF_ALREADY_EXIST.toString(), vfModuleName, cloudOwner, - cloudSiteId, tenantId, OPENSTACK, QUERY_STACK, ErrorCode.DataError.getValue(), - STACK + " " + vfModuleName + " already exists and is " + "in FAILED state"); - logger.debug(error); - throw new VnfAlreadyExists(vfModuleName, cloudOwner, cloudSiteId, tenantId, - heatStack.getCanonicalName()); - } - if (status == HeatStatus.UNKNOWN || status == HeatStatus.UPDATED) { - // fail - it exists and is in a FAILED state - String error = CREATE_VF_STACK + " " + vfModuleName + " already exists and has status " - + status.toString() + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId - + "; requires manual intervention."; - logger.error(LoggingAnchor.NINE, MessageEnum.RA_VNF_ALREADY_EXIST.toString(), vfModuleName, cloudOwner, - cloudSiteId, tenantId, OPENSTACK, QUERY_STACK, ErrorCode.DataError.getValue(), - STACK + " " + vfModuleName + " already exists and is " + "in UPDATED or UNKNOWN state"); - logger.debug(error); - throw new VnfAlreadyExists(vfModuleName, cloudOwner, cloudSiteId, tenantId, - heatStack.getCanonicalName()); - } - if (status == HeatStatus.CREATED) { - // fail - it exists - if (failIfExists != null && failIfExists) { - String error = CREATE_VF_STACK + " " + vfModuleName + " already exists in " + cloudOwner + "/" - + cloudSiteId + "/" + tenantId; - logger.error(LoggingAnchor.NINE, MessageEnum.RA_VNF_ALREADY_EXIST.toString(), vfModuleName, - cloudOwner, cloudSiteId, tenantId, OPENSTACK, QUERY_STACK, ErrorCode.DataError.getValue(), - STACK + " " + vfModuleName + " already exists"); - logger.debug(error); - throw new VnfAlreadyExists(vfModuleName, cloudOwner, cloudSiteId, tenantId, - heatStack.getCanonicalName()); - } else { - logger.debug("Found Existing stack, status={}", heatStack.getStatus()); - // Populate the outputs from the existing stack. - vnfId.value = heatStack.getCanonicalName(); - outputs.value = copyStringOutputs(heatStack.getOutputs()); - rollback.value = vfRollback; // Default rollback - no updates performed - } - } - return; - - } - // handle a nestedStackId if sent- this one would be for the volume - so applies to both Vf and Vnf StackInfo nestedHeatStack = null; - Map<String, Object> nestedVolumeOutputs = null; if (nestedStackId != null) { try { logger.debug("Querying for nestedStackId = {}", nestedStackId); - nestedHeatStack = heat.queryStack(cloudSiteId, cloudOwner, tenantId, nestedStackId); + nestedHeatStack = msoHeatUtils.queryStack(cloudSiteId, cloudOwner, tenantId, nestedStackId); } catch (MsoException me) { // Failed to query the Stack due to an openstack exception. // Convert to a generic VnfException @@ -761,7 +677,7 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { if (nestedBaseStackId != null) { try { logger.debug("Querying for nestedBaseStackId = {}", nestedBaseStackId); - nestedBaseHeatStack = heat.queryStack(cloudSiteId, cloudOwner, tenantId, nestedBaseStackId); + nestedBaseHeatStack = msoHeatUtils.queryStack(cloudSiteId, cloudOwner, tenantId, nestedBaseStackId); } catch (MsoException me) { // Failed to query the Stack due to an openstack exception. // Convert to a generic VnfException @@ -790,7 +706,6 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { } try { - // Retrieve the VF VfModule vf = null; VnfResource vnfResource = null; VfModuleCustomization vfmc = null; @@ -985,7 +900,7 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { logger.debug("Contents of nestedTemplates - to be added to files: on stack:"); for (HeatTemplate entry : nestedTemplates) { nestedTemplatesChecked.put(entry.getTemplateName(), entry.getTemplateBody()); - logger.debug(entry.getTemplateName() + " -> " + entry.getTemplateBody()); + logger.debug("Adding Nested Template", entry.getTemplateName()); } } else { logger.debug("No nested templates found - nothing to do here"); @@ -1107,13 +1022,13 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { // Step 1 - convert what we got as inputs (Map<String, String>) to a // Map<String, Object> - where the object matches the param type identified in the template // This will also not copy over params that aren't identified in the template - goldenInputs = heat.convertInputMap(inputs, heatTemplate); + goldenInputs = msoHeatUtils.convertInputMap(inputs, heatTemplate); // Step 2 - now simply add the outputs as we received them - no need to convert to string logger.debug("Now add in the base stack outputs if applicable"); - heat.copyBaseOutputsToInputs(goldenInputs, baseStackOutputs, parameterNames, aliasToParam); + msoHeatUtils.copyBaseOutputsToInputs(goldenInputs, baseStackOutputs, parameterNames, aliasToParam); // Step 3 - add the volume inputs if any logger.debug("Now add in the volume stack outputs if applicable"); - heat.copyBaseOutputsToInputs(goldenInputs, nestedVolumeOutputs, parameterNames, aliasToParam); + msoHeatUtils.copyBaseOutputsToInputs(goldenInputs, nestedVolumeOutputs, parameterNames, aliasToParam); for (HeatTemplateParam parm : heatTemplate.getParameters()) { logger.debug("Parameter:'" + parm.getParamName() + "', isRequired=" + parm.isRequired() + ", alias=" @@ -1186,15 +1101,16 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { // Have the tenant. Now deploy the stack itself // Ignore MsoTenantNotFound and MsoStackAlreadyExists exceptions // because we already checked for those. + + StackInfo heatStack = null; try { if (backout == null) { backout = true; } - if (heat != null) { - - heatStack = heat.createStack(cloudSiteId, cloudOwner, tenantId, vfModuleName, null, template, - goldenInputs, true, heatTemplate.getTimeoutMinutes(), newEnvironmentString, - nestedTemplatesChecked, heatFilesObjects, backout.booleanValue()); + if (msoHeatUtils != null) { + heatStack = msoHeatUtils.createStack(cloudSiteId, cloudOwner, tenantId, vfModuleName, null, + template, goldenInputs, true, heatTemplate.getTimeoutMinutes(), newEnvironmentString, + nestedTemplatesChecked, heatFilesObjects, backout.booleanValue(), failIfExists); } else { throw new MsoHeatNotFoundException(); } @@ -1251,15 +1167,9 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { @Override public void deleteVfModule(String cloudSiteId, String cloudOwner, String tenantId, String vnfName, MsoRequest msoRequest, Holder<Map<String, String>> outputs) throws VnfException { - - logger.debug("Deleting VF {} in ", vnfName, cloudOwner + "/" + cloudSiteId + "/" + tenantId); - // Will capture execution time for metrics - - // 1702 capture the output parameters on a delete - // so we'll need to query first Map<String, Object> stackOutputs; try { - stackOutputs = heat.queryStackForOutputs(cloudSiteId, cloudOwner, tenantId, vnfName); + stackOutputs = msoHeatUtils.queryStackForOutputs(cloudSiteId, cloudOwner, tenantId, vnfName); } catch (MsoException me) { // Failed to query the Stack due to an openstack exception. // Convert to a generic VnfException @@ -1286,7 +1196,7 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { } try { - heat.deleteStack(tenantId, cloudOwner, cloudSiteId, vnfName, true); + msoHeatUtils.deleteStack(tenantId, cloudOwner, cloudSiteId, vnfName, true, 118); } catch (MsoException me) { me.addContext(DELETE_VNF); // Failed to query the Stack due to an openstack exception. @@ -1321,9 +1231,6 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { logger.error("Exception encountered while sending Confirm to Valet ", e); } } - - // On success, nothing is returned. - return; } @Override @@ -1417,7 +1324,7 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { StackInfo heatStack; logger.debug("UpdateVfModule - querying for {}", vfModuleName); try { - heatStack = heat.queryStack(cloudSiteId, cloudOwner, tenantId, vfModuleName); + heatStack = msoHeatUtils.queryStack(cloudSiteId, cloudOwner, tenantId, vfModuleName); } catch (MsoException me) { // Failed to query the Stack due to an openstack exception. // Convert to a generic VnfException @@ -1452,7 +1359,7 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { if (nestedStackId != null) { try { logger.debug("Querying for nestedStackId = {}", nestedStackId); - nestedHeatStack = heat.queryStack(cloudSiteId, cloudOwner, tenantId, nestedStackId); + nestedHeatStack = msoHeatUtils.queryStack(cloudSiteId, cloudOwner, tenantId, nestedStackId); } catch (MsoException me) { // Failed to query the Stack due to an openstack exception. // Convert to a generic VnfException @@ -1475,7 +1382,7 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { } else { logger.debug("Found nested heat stack - copying values to inputs *later*"); nestedVolumeOutputs = nestedHeatStack.getOutputs(); - heat.copyStringOutputsToInputs(inputs, nestedHeatStack.getOutputs(), false); + msoHeatUtils.copyStringOutputsToInputs(inputs, nestedHeatStack.getOutputs(), false); } } // handle a nestedBaseStackId if sent - this is the stack ID of the base. @@ -1484,7 +1391,7 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { if (nestedBaseStackId != null) { try { logger.debug("Querying for nestedBaseStackId = {}", nestedBaseStackId); - nestedBaseHeatStack = heat.queryStack(cloudSiteId, cloudOwner, tenantId, nestedBaseStackId); + nestedBaseHeatStack = msoHeatUtils.queryStack(cloudSiteId, cloudOwner, tenantId, nestedBaseStackId); } catch (MsoException me) { // Failed to query the Stack due to an openstack exception. // Convert to a generic VnfException @@ -1507,14 +1414,10 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { } else { logger.debug("Found nested base heat stack - copying values to inputs *later*"); baseStackOutputs = nestedBaseHeatStack.getOutputs(); - heat.copyStringOutputsToInputs(inputs, nestedBaseHeatStack.getOutputs(), false); + msoHeatUtils.copyStringOutputsToInputs(inputs, nestedBaseHeatStack.getOutputs(), false); } } - // Ready to deploy the new VNF - - - // Retrieve the VF definition VnfResource vnfResource = null; VfModule vf = null; @@ -1924,9 +1827,8 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { parsedVfModuleName = "unknown"; } sendResponseToValet = this.valetUpdateRequest(cloudSiteId, cloudOwner, tenantId, heatFilesObjects, - nestedTemplatesChecked, parsedVfModuleName, false, heatTemplate, newEnvironmentString, - (HashMap<String, Object>) goldenInputs, msoRequest, inputs, failRequestOnValetFailure, - valetModifiedParamsHolder); + nestedTemplatesChecked, parsedVfModuleName, false, heatTemplate, newEnvironmentString, goldenInputs, + msoRequest, inputs, failRequestOnValetFailure, valetModifiedParamsHolder); if (sendResponseToValet) { goldenInputs = valetModifiedParamsHolder.value; } @@ -2064,7 +1966,7 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { boolean valetSucceeded = false; String valetErrorMessage = "more detail not available"; try { - String keystoneUrl = heat.getCloudSiteKeystoneUrl(cloudSiteId); + String keystoneUrl = msoHeatUtils.getCloudSiteKeystoneUrl(cloudSiteId); Map<String, Object> files = this.combineGetFilesAndNestedTemplates(heatFilesObjects, nestedTemplatesChecked); HeatRequest heatRequest = new HeatRequest(vfModuleName, backout, heatTemplate.getTimeoutMinutes(), @@ -2126,7 +2028,7 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { boolean valetSucceeded = false; String valetErrorMessage = "more detail not available"; try { - String keystoneUrl = heat.getCloudSiteKeystoneUrl(cloudSiteId); + String keystoneUrl = msoHeatUtils.getCloudSiteKeystoneUrl(cloudSiteId); Map<String, Object> files = this.combineGetFilesAndNestedTemplates(heatFilesObjects, nestedTemplatesChecked); HeatRequest heatRequest = new HeatRequest(vfModuleName, false, heatTemplate.getTimeoutMinutes(), 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 77c9b1e2f5..89eb6a161d 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 @@ -105,7 +105,6 @@ public class VolumeAdapterRestV2 { @ApiResponse(code = 500, message = "create vnfVolume failed, examine entity object for details")}) public Response createVNFVolumes(@ApiParam(value = "mode", required = true) @QueryParam("mode") String mode, @ApiParam(value = "CreateVolumeGroupRequest", required = true) final CreateVolumeGroupRequest req) { - logger.debug("createVNFVolumes enter: {}", req.toJsonString()); CreateVNFVolumesTask task = new CreateVNFVolumesTask(req, mode); if (req.isSynchronous()) { // This is a synchronous request diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/helpers/AaiHelper.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/helpers/AaiHelper.java index 137aaa9f41..d8a876016f 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/helpers/AaiHelper.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/heatbridge/helpers/AaiHelper.java @@ -84,11 +84,13 @@ public class AaiHelper { relationships.add(vfModuleRelationship); // vserver to image relationship - Relationship imageRel = buildRelationship(HeatBridgeConstants.AAI_IMAGE, - ImmutableMap.<String, String>builder().put(HeatBridgeConstants.AAI_CLOUD_OWNER, cloudOwner) - .put(HeatBridgeConstants.AAI_CLOUD_REGION_ID, cloudRegionId) - .put(HeatBridgeConstants.AAI_IMAGE_ID, server.getImage().getId()).build()); - relationships.add(imageRel); + if (server.getImage() != null) { + Relationship imageRel = buildRelationship(HeatBridgeConstants.AAI_IMAGE, + ImmutableMap.<String, String>builder().put(HeatBridgeConstants.AAI_CLOUD_OWNER, cloudOwner) + .put(HeatBridgeConstants.AAI_CLOUD_REGION_ID, cloudRegionId) + .put(HeatBridgeConstants.AAI_IMAGE_ID, server.getImage().getId()).build()); + relationships.add(imageRel); + } // vserver to flavor relationship Relationship flavorRel = buildRelationship(HeatBridgeConstants.AAI_FLAVOR, 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 index 3432e4a8b6..cff4d5f994 100644 --- 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 @@ -37,6 +37,7 @@ 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; @@ -67,6 +68,9 @@ public class AuditStackServiceDataTest extends AuditCreateStackService { @Mock private AuditDataService auditDataService; + @Mock + private AuditMDCSetup mdcSetup; + private ObjectMapper objectMapper = new ObjectMapper(); private AuditInventory auditInventory = new AuditInventory(); @@ -170,47 +174,6 @@ public class AuditStackServiceDataTest extends AuditCreateStackService { } @Test - public void retry_sequence_calculation_Test() { - long firstRetry = auditStackService.calculateRetryDelay(8); - assertEquals(6000L, firstRetry); - long secondRetry = auditStackService.calculateRetryDelay(7); - assertEquals(6000L, secondRetry); - long thirdRetry = auditStackService.calculateRetryDelay(6); - assertEquals(12000L, thirdRetry); - long fourthRetry = auditStackService.calculateRetryDelay(5); - assertEquals(18000L, fourthRetry); - long fifthRetry = auditStackService.calculateRetryDelay(4); - assertEquals(30000L, fifthRetry); - long sixRetry = auditStackService.calculateRetryDelay(3); - assertEquals(48000L, sixRetry); - long seventhRetry = auditStackService.calculateRetryDelay(2); - assertEquals(78000L, seventhRetry); - long eigthRetry = auditStackService.calculateRetryDelay(1); - assertEquals(120000L, eigthRetry); - } - - @Test - public void retry_sequence_Test() { - long firstRetry = auditStackService.calculateRetryDelay(8); - assertEquals(6000L, firstRetry); - long secondRetry = auditStackService.calculateRetryDelay(7); - assertEquals(6000L, secondRetry); - long thirdRetry = auditStackService.calculateRetryDelay(6); - assertEquals(12000L, thirdRetry); - long fourthRetry = auditStackService.calculateRetryDelay(5); - assertEquals(18000L, fourthRetry); - long fifthRetry = auditStackService.calculateRetryDelay(4); - assertEquals(30000L, fifthRetry); - long sixRetry = auditStackService.calculateRetryDelay(3); - assertEquals(48000L, sixRetry); - long seventhRetry = auditStackService.calculateRetryDelay(2); - assertEquals(78000L, seventhRetry); - long eigthRetry = auditStackService.calculateRetryDelay(1); - assertEquals(120000L, eigthRetry); - } - - - @Test public void determineAuditResult_Test() throws Exception { boolean actual = auditStackService.didCreateAuditFail(auditListOptSuccess); assertEquals(false, actual); diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/audit/AuditStackServiceTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/audit/AuditStackServiceTest.java deleted file mode 100644 index c9aef950f7..0000000000 --- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/audit/AuditStackServiceTest.java +++ /dev/null @@ -1,91 +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.junit.Assert.assertNotNull; -import org.camunda.bpm.client.ExternalTaskClient; -import org.camunda.bpm.client.interceptor.ClientRequestInterceptor; -import org.camunda.bpm.client.interceptor.auth.BasicAuthProvider; -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.Spy; -import org.mockito.junit.MockitoJUnitRunner; -import org.onap.so.utils.CryptoUtils; -import org.springframework.core.env.Environment; - -@RunWith(MockitoJUnitRunner.class) -public class AuditStackServiceTest { - - @Spy - @InjectMocks - AuditStackService auditStackService; - - @Mock - Environment mockEnvironment; - - - @Before - public void before() { - Mockito.doReturn("5").when(mockEnvironment).getProperty("workflow.topics.maxClients", "10"); - Mockito.doReturn("6B466C603A260F3655DBF91E53CE54667041C01406D10E8CAF9CC24D8FA5388D06F90BFE4C852052B436") - .when(mockEnvironment).getRequiredProperty("mso.auth"); - Mockito.doReturn("07a7159d3bf51a0e53be7a8f89699be7").when(mockEnvironment).getRequiredProperty("mso.msoKey"); - Mockito.doReturn("something").when(mockEnvironment).getRequiredProperty("mso.config.cadi.aafId"); - Mockito.doReturn("host.com").when(mockEnvironment).getRequiredProperty("mso.workflow.endpoint"); - } - - @Test - public void testGetMaxClients() throws Exception { - int actual = auditStackService.getMaxClients(); - assertEquals(5, actual); - } - - @Test - public void testCreateClientRequestInterceptor() throws Exception { - String auth = CryptoUtils.decrypt( - "6B466C603A260F3655DBF91E53CE54667041C01406D10E8CAF9CC24D8FA5388D06F90BFE4C852052B436", - "07a7159d3bf51a0e53be7a8f89699be7"); - ClientRequestInterceptor expected = new BasicAuthProvider("something", auth); - ClientRequestInterceptor actual = auditStackService.createClientRequestInterceptor(); - assertThat(actual, sameBeanAs(expected)); - - } - - @Test - public void testCreateExternalTaskClient() throws Exception { - String auth = CryptoUtils.decrypt( - "6B466C603A260F3655DBF91E53CE54667041C01406D10E8CAF9CC24D8FA5388D06F90BFE4C852052B436", - "07a7159d3bf51a0e53be7a8f89699be7"); - ClientRequestInterceptor inter = new BasicAuthProvider("something", auth); - Mockito.doReturn(inter).when(auditStackService).createClientRequestInterceptor(); - ExternalTaskClient actual = auditStackService.createExternalTaskClient(); - assertNotNull(actual); - Mockito.verify(auditStackService, Mockito.times(1)).createClientRequestInterceptor(); - - } -} 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 index 8dc9d7fe5c..c4fa9ee2c5 100644 --- 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 @@ -31,6 +31,7 @@ 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; @@ -46,6 +47,9 @@ public class CreateInventoryTaskTest { @Mock ExternalTaskService externalTaskService; + @Mock + private AuditMDCSetup mdcSetup; + @InjectMocks CreateInventoryTask inventoryTask; diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/network/NetworkAdapterRestTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/network/NetworkAdapterRestTest.java index 1f4c205e7a..412abeab3b 100644 --- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/network/NetworkAdapterRestTest.java +++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/network/NetworkAdapterRestTest.java @@ -194,9 +194,7 @@ public class NetworkAdapterRestTest extends BaseRestTestUtils { public void testRollbackNetwork() throws IOException { RollbackNetworkRequest request = new RollbackNetworkRequest(); - MsoRequest msoReq = new MsoRequest(); - msoReq.setRequestId(MSO_REQUEST_ID); msoReq.setServiceInstanceId(MSO_SERVICE_INSTANCE_ID); diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/MsoVnfAdapterImplTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/MsoVnfAdapterImplTest.java index 651e2c9a73..0d972bb4d2 100644 --- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/MsoVnfAdapterImplTest.java +++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/vnf/MsoVnfAdapterImplTest.java @@ -40,7 +40,6 @@ import org.junit.Ignore; import org.junit.Rule; import org.junit.Test; import org.junit.rules.ExpectedException; -import org.onap.so.adapters.vnf.exceptions.VnfAlreadyExists; import org.onap.so.adapters.vnf.exceptions.VnfException; import org.onap.so.adapters.vnf.exceptions.VnfNotFound; import org.onap.so.db.catalog.beans.HeatEnvironment; @@ -50,15 +49,15 @@ import org.onap.so.db.catalog.beans.VfModule; import org.onap.so.db.catalog.beans.VfModuleCustomization; import org.onap.so.db.catalog.beans.VnfResource; import org.onap.so.entity.MsoRequest; -import org.onap.so.openstack.beans.HeatStatus; -import org.onap.so.openstack.beans.StackInfo; import org.onap.so.openstack.beans.VnfRollback; import org.onap.so.openstack.exceptions.MsoException; import org.onap.so.openstack.utils.MsoHeatUtils; import org.springframework.beans.factory.annotation.Autowired; +import com.github.tomakehurst.wiremock.stubbing.Scenario; public class MsoVnfAdapterImplTest extends BaseRestTestUtils { + @Rule public ExpectedException expectedException = ExpectedException.none(); @@ -71,17 +70,7 @@ public class MsoVnfAdapterImplTest extends BaseRestTestUtils { String vnfName = "DEV-VF-1802-it3-pwt3-v6-vSAMP10a-addon2-Replace-1001/stackId"; @Test - @Ignore - public void healthCheckVNFTest() { - MsoVnfAdapterImpl instance = new MsoVnfAdapterImpl(); - instance.healthCheck(); - } - - @Test public void createVnfTest() throws Exception { - StackInfo info = new StackInfo(); - info.setStatus(HeatStatus.CREATED); - mockOpenStackResponseAccess(wireMockServer, wireMockPort); mockOpenStackGetStackVfModule_200(wireMockServer); @@ -90,105 +79,57 @@ public class MsoVnfAdapterImplTest extends BaseRestTestUtils { Map<String, Object> map = new HashMap<>(); map.put("key1", "value1"); instance.createVfModule("mtn13", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", "", vnfName, "", - "VFMOD", "volumeGroupHeatStackId|1", "baseVfHeatStackId", "88a6ca3ee0394ade9403f075db23167e", map, - Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, msoRequest, new Holder<>(), - new Holder<Map<String, String>>(), new Holder<VnfRollback>()); + "VFMOD", null, null, "b4ea86b4-253f-11e7-93ae-92361f002671", map, Boolean.TRUE, Boolean.TRUE, + Boolean.FALSE, msoRequest, new Holder<>(), new Holder<Map<String, String>>(), + new Holder<VnfRollback>()); } @Test - public void createVnfTest_HeatStatusUpdating() throws Exception { - expectedException.expect(VnfAlreadyExists.class); + public void createVnfTest_HeatStatusFailed() throws Exception { mockOpenStackResponseAccess(wireMockServer, wireMockPort); - wireMockServer.stubFor(get( urlPathEqualTo("/mockPublicUrl/stacks/DEV-VF-1802-it3-pwt3-v6-vSAMP10a-addon2-Replace-1001/stackId")) .willReturn(aResponse().withHeader("Content-Type", "application/json") - .withBodyFile("OpenstackResponse_Stack_Updating_VfModule.json") - .withStatus(HttpStatus.SC_OK))); - - MsoRequest msoRequest = getMsoRequest(); - - Map<String, Object> map = new HashMap<>(); - map.put("key1", "value1"); - instance.createVfModule("mtn13", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", "", vnfName, "", - "VFMOD", "volumeGroupHeatStackId|1", "baseVfHeatStackId", "88a6ca3ee0394ade9403f075db23167e", map, - Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, msoRequest, new Holder<>(), - new Holder<Map<String, String>>(), new Holder<VnfRollback>()); - } - - @Test - public void createVnfTest_HeatStatusUpdated() throws Exception { - expectedException.expect(VnfAlreadyExists.class); - mockOpenStackResponseAccess(wireMockServer, wireMockPort); + .withBodyFile("OpenstackResponse_Stack_Failed_VfModule.json") + .withStatus(HttpStatus.SC_OK)) + .inScenario("HeatStatusFailure").whenScenarioStateIs(Scenario.STARTED) + .willSetStateTo("HeatStackFailed")); wireMockServer.stubFor(get( urlPathEqualTo("/mockPublicUrl/stacks/DEV-VF-1802-it3-pwt3-v6-vSAMP10a-addon2-Replace-1001/stackId")) .willReturn(aResponse().withHeader("Content-Type", "application/json") - .withBodyFile("OpenstackResponse_StackId.json").withStatus(HttpStatus.SC_OK))); + .withBodyFile("OpenstackResponse_Stack_Created_VfModule.json") + .withStatus(HttpStatus.SC_OK)) + .inScenario("HeatStatusFailure").whenScenarioStateIs("HeatStackFailed") + .willSetStateTo("HeatStackSuccess")); MsoRequest msoRequest = getMsoRequest(); Map<String, Object> map = new HashMap<>(); map.put("key1", "value1"); instance.createVfModule("mtn13", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", "", vnfName, "", - "VFMOD", "volumeGroupHeatStackId|1", "baseVfHeatStackId", "88a6ca3ee0394ade9403f075db23167e", map, - Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, msoRequest, new Holder<>(), - new Holder<Map<String, String>>(), new Holder<VnfRollback>()); + "VFMOD", null, null, "b4ea86b4-253f-11e7-93ae-92361f002671", map, Boolean.FALSE, Boolean.TRUE, + Boolean.FALSE, msoRequest, new Holder<>(), new Holder<Map<String, String>>(), + new Holder<VnfRollback>()); } - @Test - public void createVnfTest_HeatStatusFailed() throws Exception { - expectedException.expect(VnfAlreadyExists.class); - mockOpenStackResponseAccess(wireMockServer, wireMockPort); - - wireMockServer.stubFor(get( - urlPathEqualTo("/mockPublicUrl/stacks/DEV-VF-1802-it3-pwt3-v6-vSAMP10a-addon2-Replace-1001/stackId")) - .willReturn(aResponse().withHeader("Content-Type", "application/json") - .withBodyFile("OpenstackResponse_Stack_Failed_VfModule.json") - .withStatus(HttpStatus.SC_OK))); - - MsoRequest msoRequest = getMsoRequest(); - Map<String, Object> map = new HashMap<>(); - map.put("key1", "value1"); - instance.createVfModule("mtn13", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", "", vnfName, "", - "VFMOD", "volumeGroupHeatStackId|1", "baseVfHeatStackId", "88a6ca3ee0394ade9403f075db23167e", map, - Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, msoRequest, new Holder<>(), - new Holder<Map<String, String>>(), new Holder<VnfRollback>()); - } @Test public void createVnfTest_HeatStatusCreated() throws Exception { - expectedException.expect(VnfAlreadyExists.class); mockOpenStackResponseAccess(wireMockServer, wireMockPort); - mockOpenStackGetStackVfModule_200(wireMockServer); - MsoRequest msoRequest = getMsoRequest(); - Map<String, Object> map = new HashMap<>(); map.put("key1", "value1"); instance.createVfModule("mtn13", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", "", vnfName, "", - "VFMOD", "volumeGroupHeatStackId|1", "baseVfHeatStackId", "88a6ca3ee0394ade9403f075db23167e", map, - Boolean.TRUE, Boolean.TRUE, Boolean.FALSE, msoRequest, new Holder<>(), - new Holder<Map<String, String>>(), new Holder<VnfRollback>()); + "VFMOD", null, null, "b4ea86b4-253f-11e7-93ae-92361f002671", map, Boolean.TRUE, Boolean.TRUE, + Boolean.FALSE, msoRequest, new Holder<>(), new Holder<Map<String, String>>(), + new Holder<VnfRollback>()); } @Test - public void createVnfTest_ExceptionInGettingHeat() throws Exception { - expectedException.expect(VnfException.class); - MsoRequest msoRequest = getMsoRequest(); - - Map<String, Object> map = new HashMap<>(); - map.put("key1", "value1"); - instance.createVfModule("mtn13", "CloudOwner", "88a6ca3ee0394ade9403f075db23167e", "vnf", "1", "", vnfName, "", - "VFMOD", "volumeGroupHeatStackId|1", "baseVfHeatStackId", "88a6ca3ee0394ade9403f075db23167e", map, - Boolean.FALSE, Boolean.TRUE, Boolean.FALSE, msoRequest, new Holder<>(), - new Holder<Map<String, String>>(), new Holder<VnfRollback>()); - } - - @Test public void createVnfTest_NestedHeatStatusNotFound() throws Exception { expectedException.expect(VnfException.class); mockOpenStackResponseAccess(wireMockServer, wireMockPort); diff --git a/adapters/mso-openstack-adapters/src/test/resources/application-test.yaml b/adapters/mso-openstack-adapters/src/test/resources/application-test.yaml index 7cc7697129..20fd812ab9 100644 --- a/adapters/mso-openstack-adapters/src/test/resources/application-test.yaml +++ b/adapters/mso-openstack-adapters/src/test/resources/application-test.yaml @@ -1,5 +1,3 @@ -# will be used as entry in DB to say SITE OFF/ON for healthcheck -# MSO Properties go here org: onap: so: @@ -41,7 +39,7 @@ org: default_keystone_reg_ex: "/[vV][0-9]" default_tenant_description: ECOMP Tenant default_region_type: single - default_user_role: admin + default_user_role: adminev default_success_status_string: Success default_no_regions_status_string: no regions default_orm_request_path: /v1/orm/customers/ diff --git a/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/application/MSORequestDBApplication.java b/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/application/MSORequestDBApplication.java index 85c05decb1..3a14b2ff84 100644 --- a/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/application/MSORequestDBApplication.java +++ b/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/application/MSORequestDBApplication.java @@ -24,6 +24,8 @@ package org.onap.so.adapters.requestsdb.application; import java.time.Duration; import javax.sql.DataSource; +import org.onap.logging.filter.base.Constants; +import org.onap.logging.filter.base.ONAPComponents; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Bean; @@ -39,8 +41,7 @@ import net.javacrumbs.shedlock.spring.ScheduledLockConfigurationBuilder; * @since Version 1.0 * */ - -@SpringBootApplication(scanBasePackages = {"org.onap.so"}) +@SpringBootApplication(scanBasePackages = {"org.onap.so", "org.onap.logging.filter"}) @EnableScheduling @EnableMBeanExport(registration = RegistrationPolicy.IGNORE_EXISTING) public class MSORequestDBApplication { @@ -54,6 +55,7 @@ public class MSORequestDBApplication { } public static void main(String... args) { + System.setProperty(Constants.Property.PARTNER_NAME, ONAPComponents.REQUEST_DB.toString()); SpringApplication.run(MSORequestDBApplication.class, args); java.security.Security.setProperty("networkaddress.cache.ttl", "10"); setLogsDir(); diff --git a/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/application/WebMvcConfig.java b/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/application/WebMvcConfig.java index 579afe9243..9135d31ac3 100644 --- a/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/application/WebMvcConfig.java +++ b/adapters/mso-requests-db-adapter/src/main/java/org/onap/so/adapters/requestsdb/application/WebMvcConfig.java @@ -21,22 +21,32 @@ package org.onap.so.adapters.requestsdb.application; -import org.onap.so.logging.spring.interceptor.LoggingInterceptor; +import org.onap.logging.filter.spring.LoggingInterceptor; +import org.onap.logging.filter.spring.StatusLoggingInterceptor; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.ComponentScan; import org.springframework.context.annotation.Configuration; import org.springframework.web.servlet.config.annotation.WebMvcConfigurerAdapter; import org.springframework.web.servlet.handler.MappedInterceptor; @Configuration +@ComponentScan(basePackages = {"org.onap.logging.filter"}) public class WebMvcConfig extends WebMvcConfigurerAdapter { @Autowired - LoggingInterceptor loggingInterceptor; + private LoggingInterceptor loggingInterceptor; + + @Autowired + private StatusLoggingInterceptor statusLoggingInterceptor; @Bean public MappedInterceptor mappedLoggingInterceptor() { return new MappedInterceptor(new String[] {"/**"}, loggingInterceptor); } + @Bean + public MappedInterceptor mappedStatusLoggingInterceptor() { + return new MappedInterceptor(new String[] {"/**"}, statusLoggingInterceptor); + } } diff --git a/adapters/mso-requests-db-adapter/src/main/resources/db/migration/V6.4.1__Rename_Infra_active_requests_AIC_CLOUD_REGION_Column.sql b/adapters/mso-requests-db-adapter/src/main/resources/db/migration/V6.4.1__Rename_Infra_active_requests_AIC_CLOUD_REGION_Column.sql new file mode 100644 index 0000000000..eac9a65f65 --- /dev/null +++ b/adapters/mso-requests-db-adapter/src/main/resources/db/migration/V6.4.1__Rename_Infra_active_requests_AIC_CLOUD_REGION_Column.sql @@ -0,0 +1,12 @@ +use requestdb; + +DROP INDEX `infra_active_requests__aic_cloud_region_idx` on `infra_active_requests`; + +ALTER TABLE + `infra_active_requests` CHANGE AIC_CLOUD_REGION CLOUD_REGION varchar(50) DEFAULT NULL; + +ALTER TABLE + `archived_infra_requests` CHANGE AIC_CLOUD_REGION CLOUD_REGION VARCHAR(50) NULL DEFAULT NULL; + +ALTER TABLE `infra_active_requests` + ADD INDEX IF NOT EXISTS `infra_active_requests__cloud_region_idx` (`CLOUD_REGION` ASC); diff --git a/adapters/mso-requests-db-adapter/src/main/resources/db/migration/V6.5__Drop_Table_Active_Requests.sql b/adapters/mso-requests-db-adapter/src/main/resources/db/migration/V6.5__Drop_Table_Active_Requests.sql new file mode 100644 index 0000000000..c3d385ccc2 --- /dev/null +++ b/adapters/mso-requests-db-adapter/src/main/resources/db/migration/V6.5__Drop_Table_Active_Requests.sql @@ -0,0 +1,4 @@ + +use requestdb; + +DROP TABLE IF EXISTS active_requests;
\ No newline at end of file diff --git a/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/adapters/MSORequestDBImplTest.java b/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/adapters/MSORequestDBImplTest.java index e53b957210..fa2acbc0ca 100644 --- a/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/adapters/MSORequestDBImplTest.java +++ b/adapters/mso-requests-db-adapter/src/test/java/org/onap/so/adapters/requestsdb/adapters/MSORequestDBImplTest.java @@ -449,7 +449,7 @@ public class MSORequestDBImplTest extends RequestsAdapterBase { assertNotNull(mdc.get(ONAPLogConstants.MDCs.INSTANCE_UUID)); assertNotNull(mdc.get(ONAPLogConstants.MDCs.REQUEST_ID)); assertNotNull(mdc.get(ONAPLogConstants.MDCs.INVOCATION_ID)); - assertEquals("", mdc.get(ONAPLogConstants.MDCs.PARTNER_NAME)); + assertEquals("UNKNOWN", mdc.get(ONAPLogConstants.MDCs.PARTNER_NAME)); assertEquals("/services/RequestsDbAdapter", mdc.get(ONAPLogConstants.MDCs.SERVICE_NAME)); assertEquals("INPROGRESS", mdc.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE)); } else if (logEvent.getLoggerName().equals("org.onap.so.logging.cxf.interceptor.SOAPLoggingOutInterceptor") @@ -458,9 +458,9 @@ public class MSORequestDBImplTest extends RequestsAdapterBase { assertNotNull(mdc.get(ONAPLogConstants.MDCs.REQUEST_ID)); assertNotNull(mdc.get(ONAPLogConstants.MDCs.INVOCATION_ID)); assertEquals(null, mdc.get(ONAPLogConstants.MDCs.RESPONSE_CODE)); - assertEquals("", mdc.get(ONAPLogConstants.MDCs.PARTNER_NAME)); + assertEquals("UNKNOWN", mdc.get(ONAPLogConstants.MDCs.PARTNER_NAME)); assertEquals("/services/RequestsDbAdapter", mdc.get(ONAPLogConstants.MDCs.SERVICE_NAME)); - assertEquals("COMPLETED", mdc.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE)); + assertEquals("COMPLETE", mdc.get(ONAPLogConstants.MDCs.RESPONSE_STATUS_CODE)); } } diff --git a/adapters/mso-requests-db-adapter/src/test/resources/db/migration/afterMigrate.sql b/adapters/mso-requests-db-adapter/src/test/resources/db/migration/afterMigrate.sql index 9c2ea6d3bf..65fac11d41 100644 --- a/adapters/mso-requests-db-adapter/src/test/resources/db/migration/afterMigrate.sql +++ b/adapters/mso-requests-db-adapter/src/test/resources/db/migration/afterMigrate.sql @@ -4,7 +4,7 @@ insert into operation_status(service_id, operation_id, service_name, user_id, re ('serviceid', 'operationid', 'servicename', 'userid', 'result', 'operationcontent', 'progress', 'reason', '2016-11-24 13:19:10', '2016-11-24 13:19:10'); -insert into infra_active_requests(request_id, client_request_id, action, request_status, status_message, progress, start_time, end_time, source, vnf_id, vnf_name, vnf_type, service_type, aic_node_clli, tenant_id, prov_status, vnf_params, vnf_outputs, request_body, response_body, last_modified_by, modify_time, request_type, volume_group_id, volume_group_name, vf_module_id, vf_module_name, vf_module_model_name, aai_service_id, aic_cloud_region, callback_url, correlator, network_id, network_name, network_type, request_scope, request_action, service_instance_id, service_instance_name, requestor_id, configuration_id, configuration_name, operational_env_id, operational_env_name, request_url) values +insert into infra_active_requests(request_id, client_request_id, action, request_status, status_message, progress, start_time, end_time, source, vnf_id, vnf_name, vnf_type, service_type, aic_node_clli, tenant_id, prov_status, vnf_params, vnf_outputs, request_body, response_body, last_modified_by, modify_time, request_type, volume_group_id, volume_group_name, vf_module_id, vf_module_name, vf_module_model_name, aai_service_id, cloud_region, callback_url, correlator, network_id, network_name, network_type, request_scope, request_action, service_instance_id, service_instance_name, requestor_id, configuration_id, configuration_name, operational_env_id, operational_env_name, request_url) values ('00032ab7-3fb3-42e5-965d-8ea592502017', '00032ab7-3fb3-42e5-965d-8ea592502016', 'deleteInstance', 'COMPLETE', 'Vf Module has been deleted successfully.', '100', '2016-12-22 18:59:54', '2016-12-22 19:00:28', 'VID', 'b92f60c8-8de3-46c1-8dc1-e4390ac2b005', null, null, null, null, '6accefef3cb442ff9e644d589fb04107', null, null, null, '{"requestDetails":{"modelInfo":{"modelType":"vfModule","modelName":"vSAMP10aDEV::base::module-0"},"requestInfo":{"source":"VID"},"cloudConfiguration":{"tenantId":"6accefef3cb442ff9e644d589fb04107","lcpCloudRegionId":"mtn6"}}}', null, 'BPMN', '2016-12-22 19:00:28', null, null, null, 'c7d527b1-7a91-49fd-b97d-1c8c0f4a7992', null, 'vSAMP10aDEV::base::module-0', null, 'mtn6', null, null, null, null, null, 'vfModule', 'deleteInstance', 'e3b5744d-2ad1-4cdd-8390-c999a38829bc', null, null, null, null, null, null, 'http://localhost:8080/onap/so/infra/serviceInstantiation/v7/serviceInstances'), ('00093944-bf16-4373-ab9a-3adfe730ff2d', null, 'createInstance', 'FAILED', 'Error: Locked instance - This service (MSODEV_1707_SI_vSAMP10a_011-4) already has a request being worked with a status of IN_PROGRESS (RequestId - 278e83b1-4f9f-450e-9e7d-3700a6ed22f4). The existing request must finish or be cleaned up before proceeding.', '100', '2017-07-11 18:33:26', '2017-07-11 18:33:26', 'VID', null, null, null, null, null, '19123c2924c648eb8e42a3c1f14b7682', null, null, null, '{"requestDetails":{"modelInfo":{"modelInvariantId":"9647dfc4-2083-11e7-93ae-92361f002671","modelType":"service","modelName":"MSOTADevInfra_vSAMP10a_Service","modelVersion":"1.0","modelVersionId":"5df8b6de-2083-11e7-93ae-92361f002671"},"requestInfo":{"source":"VID","instanceName":"MSODEV_1707_SI_vSAMP10a_011-4","suppressRollback":false,"requestorId":"xxxxxx"},"subscriberInfo":{"globalSubscriberId":"MSO_1610_dev","subscriberName":"MSO_1610_dev"},"cloudConfiguration":{"tenantId":"19123c2924c648eb8e42a3c1f14b7682","lcpCloudRegionId":"mtn6"},"requestParameters":{"subscriptionServiceType":"MSO-dev-service-type","userParams":[{"name":"someUserParam","value":"someValue"}],"aLaCarte":true,"autoBuildVfModules":false,"cascadeDelete":false,"usePreload":true,"alaCarteSet":true,"alaCarte":true}}}', null, 'APIH', '2016-12-22 19:00:28', null, null, null, null, null, null, null, 'mtn6', null, null, null, null, null, 'service', 'createInstance', null, 'MSODEV_1707_SI_vSAMP10a_011-4', 'xxxxxx', null, null, null, null, 'http://localhost:8080/onap/so/infra/serviceInstantiation/v7/serviceInstances'), ('001619d2-a297-4a4b-a9f5-e2823c88458f', '001619d2-a297-4a4b-a9f5-e2823c88458f', 'CREATE_VF_MODULE', 'COMPLETE', 'COMPLETED', '100', '2016-07-01 14:11:42', '2017-05-02 16:03:34', 'PORTAL', null, 'test-vscp', 'elena_test21', null, null, '381b9ff6c75e4625b7a4182f90fc68d3', null, null, null, '<?xml version=\"1.0\" encoding=\"UTF-8\" standalone=\"yes\"?>\n<vnf-request xmlns=\"http://org.onap.so/mso/infra/vnf-request/v1\">\n <request-info>\n <request-id>001619d2-a297-4a4b-a9f5-e2823c88458f</request-id>\n <action>CREATE_VF_MODULE</action>\n <source>PORTAL</source>\n </request-info>\n <vnf-inputs>\n <vnf-name>test-vscp</vnf-name>\n <vf-module-name>moduleName</vf-module-name>\n <vnf-type>elena_test21</vnf-type>\n <vf-module-model-name>moduleModelName</vf-module-model-name>\n <asdc-service-model-version>1.0</asdc-service-model-version>\n <service-id>a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb</service-id>\n <aic-cloud-region>mtn9</aic-cloud-region>\n <tenant-id>381b9ff6c75e4625b7a4182f90fc68d3</tenant-id>\n <persona-model-id></persona-model-id>\n <persona-model-version></persona-model-version>\n <is-base-vf-module>false</is-base-vf-module>\n </vnf-inputs>\n <vnf-params xmlns:tns=\"http://org.onap.so/mso/infra/vnf-request/v1\"/>\n</vnf-request>\n', 'NONE', 'RDBTEST', '2016-07-01 14:11:42', 'VNF', null, null, null, 'MODULENAME1', 'moduleModelName', 'a9a77d5a-123e-4ca2-9eb9-0b015d2ee0fb', 'mtn9', null, null, null, null, null, 'vfModule', 'createInstance', null, null, null, null, null, null, null, 'http://localhost:8080/onap/so/infra/serviceInstantiation/v7/serviceInstances'), diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/CXFConfiguration.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/CXFConfiguration.java index 6149f7ed25..dd1da98dd8 100644 --- a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/CXFConfiguration.java +++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/CXFConfiguration.java @@ -32,7 +32,7 @@ import org.apache.cxf.transport.servlet.CXFServlet; import org.onap.so.adapters.sdnc.sdncrest.SNIROResponse; import org.onap.so.logging.cxf.interceptor.SOAPLoggingInInterceptor; import org.onap.so.logging.cxf.interceptor.SOAPLoggingOutInterceptor; -import org.onap.so.logging.jaxrs.filter.JaxRsFilterLogging; +import org.onap.so.logging.jaxrs.filter.SOAuditLogContainerFilter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.web.servlet.ServletRegistrationBean; import org.springframework.context.annotation.Bean; @@ -51,7 +51,7 @@ public class CXFConfiguration { private Bus bus; @Autowired - private JaxRsFilterLogging jaxRsFilterLogging; + private SOAuditLogContainerFilter soAuditLogContainerFilter; @Autowired private SDNCAdapterPortType sdncAdapterPortImpl; @@ -70,7 +70,7 @@ public class CXFConfiguration { endpoint.setServiceBeans(Arrays.<Object>asList(sniroResponse)); endpoint.setAddress("/rest"); endpoint.setFeatures(Arrays.asList(createSwaggerFeature(), new LoggingFeature())); - endpoint.setProviders(Arrays.asList(new JacksonJsonProvider(mapper), jaxRsFilterLogging)); + endpoint.setProviders(Arrays.asList(new JacksonJsonProvider(mapper), soAuditLogContainerFilter)); return endpoint.create(); } diff --git a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/SDNCAdapterApplication.java b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/SDNCAdapterApplication.java index 55023088bc..fc6d0a6fc9 100644 --- a/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/SDNCAdapterApplication.java +++ b/adapters/mso-sdnc-adapter/src/main/java/org/onap/so/adapters/sdnc/SDNCAdapterApplication.java @@ -23,7 +23,7 @@ package org.onap.so.adapters.sdnc; import java.util.concurrent.Executor; -import org.onap.so.logging.jaxrs.filter.MDCTaskDecorator; +import org.onap.logging.filter.spring.MDCTaskDecorator; import org.springframework.beans.factory.annotation.Value; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; diff --git a/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/CXFConfiguration.java b/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/CXFConfiguration.java index 5ea68f08a2..dd875c573e 100644 --- a/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/CXFConfiguration.java +++ b/adapters/mso-vfc-adapter/src/main/java/org/onap/so/adapters/vfc/CXFConfiguration.java @@ -28,7 +28,7 @@ import org.apache.cxf.jaxrs.JAXRSServerFactoryBean; import org.apache.cxf.jaxrs.swagger.Swagger2Feature; import org.apache.cxf.transport.servlet.CXFServlet; import org.onap.so.adapters.vfc.rest.VfcAdapterRest; -import org.onap.so.logging.jaxrs.filter.JaxRsFilterLogging; +import org.onap.so.logging.jaxrs.filter.SOAuditLogContainerFilter; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.web.servlet.ServletRegistrationBean; import org.springframework.context.annotation.Bean; @@ -47,7 +47,7 @@ public class CXFConfiguration { private VfcAdapterRest vfcAdapterRest; @Autowired - private JaxRsFilterLogging jaxRsFilterLogging; + private SOAuditLogContainerFilter soAuditLogContainerFilter; @Autowired private ObjectMapper mapper; @@ -64,7 +64,7 @@ public class CXFConfiguration { endpoint.setServiceBeans(Arrays.<Object>asList(vfcAdapterRest)); endpoint.setAddress("/"); endpoint.setFeatures(Arrays.asList(createSwaggerFeature(), new LoggingFeature())); - endpoint.setProviders(Arrays.asList(new JacksonJsonProvider(mapper), jaxRsFilterLogging)); + endpoint.setProviders(Arrays.asList(new JacksonJsonProvider(mapper), soAuditLogContainerFilter)); return endpoint.create(); } diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/Readme.txt b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/Readme.txt index 66876311db..aaad60320d 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/Readme.txt +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/Readme.txt @@ -1,5 +1,9 @@ The following describes how to configure authentication for the VNFM adapter.
+TLS should always be configured to ensure secure communication between the VNFM-adapter <-> BPMN infra and VNFM-adapter <-> VNFM
+If two-way TLS is configured then there is no need for any further authentication (i.e. no need for token or basic auth).
+If two-way TLS is NOT configured then authentication is REQUIRED. Oauth token based authentication must be used for requests, while for notifications either oauth tokens or basic auth can be used.
+
==========================================
To confgure TLS
@@ -12,8 +16,8 @@ The following parameters can be set to configure the certificate for the VNFM ad server:
ssl:
key-alias: so@so.onap.org
- key--store-password: 'I,re7WWEJR$e]x370wRgx?qE'
- key-store: classpath:org.onap.so.p12
+ key--store-password: 'ywsqCy:EEo#j}HJHM7z^Rk[L'
+ key-store: classpath:so-vnfm-adapter.p12
key-store-type: PKCS12
The values shown above relate to the certificate included in the VNFM adapter jar which has been generated from AAF. If a different certificate is to be used then these values should be changed accordingly.
@@ -21,8 +25,8 @@ The following paramters can be set to configure the trust store for the VNFM ada http:
client:
ssl:
- trust-store: org.onap.so.trust.jks
- trust-store-password: NyRD](z:EJJNIt?},QgM3o7H
+ trust-store: classpath:org.onap.so.trust.jks
+ trust-store-password: ',sx#.C*W)]wVgJC6ccFHI#:H'
The values shown above relate to the trust store included in the VNFM adapter jar which has been generated from AAI. If a different trust store is to be used then these values should be changed accordingly.
Ensure the value for the below parameter uses https instead of http
diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/aai/AaiHelper.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/aai/AaiHelper.java index 110bbabdb2..fc9efef947 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/aai/AaiHelper.java +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/aai/AaiHelper.java @@ -31,14 +31,10 @@ import org.onap.aai.domain.yang.EsrVnfmList; import org.onap.aai.domain.yang.GenericVnf; import org.onap.aai.domain.yang.Relationship; import org.onap.aai.domain.yang.RelationshipData; -import org.onap.aai.domain.yang.RelationshipList; import org.onap.aai.domain.yang.Vserver; import org.onap.so.adapters.vnfmadapter.extclients.vnfm.lcn.model.LcnVnfLcmOperationOccurrenceNotificationAffectedVnfcs; import org.onap.so.adapters.vnfmadapter.rest.exceptions.TenantNotFoundException; import org.onap.so.adapters.vnfmadapter.rest.exceptions.VnfmNotFoundException; -import org.onap.so.client.aai.AAIObjectType; -import org.onap.so.client.aai.AAIVersion; -import org.onap.so.client.aai.entities.uri.AAIUriFactory; import org.onap.vnfmadapter.v1.model.Tenant; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -61,38 +57,6 @@ public class AaiHelper { } /** - * Add a relationship to the given generic VNF to the given VNFM. - * - * @param vnf the generic VNF - * @param vnfmId the ID of the VNFM - */ - public void addRelationshipFromGenericVnfToVnfm(final GenericVnf vnf, final String vnfmId) { - if (vnf.getRelationshipList() == null) { - vnf.setRelationshipList(new RelationshipList()); - } - final RelationshipList vnfmRelationshiplist = vnf.getRelationshipList(); - vnfmRelationshiplist.getRelationship().add(createRelationshipToVnfm(vnfmId)); - - } - - private Relationship createRelationshipToVnfm(final String vnfmId) { - final Relationship relationship = new Relationship(); - relationship.setRelatedTo("esr-vnfm"); - relationship.setRelationshipLabel("tosca.relationships.DependsOn"); - relationship.setRelatedLink("/aai/" + AAIVersion.LATEST - + AAIUriFactory.createResourceUri(AAIObjectType.VNFM, vnfmId).build().toString()); - relationship.getRelationshipData().add(createRelationshipData("esr-vnfm.vnfm-id", vnfmId)); - return relationship; - } - - private RelationshipData createRelationshipData(final String key, final String value) { - final RelationshipData data = new RelationshipData(); - data.setRelationshipKey(key); - data.setRelationshipValue(value); - return data; - } - - /** * Get the VNFM assigned for use for the given generic VNF. * * @param vnf the generic VNF @@ -242,30 +206,6 @@ public class AaiHelper { return vserver; } - /** - * Add a relationship to the given vserver to the given VNF. - * - * @param vnf the vserver - * @param vnfmId the ID of the VNF - */ - public void addRelationshipFromVserverVnfToGenericVnf(final Vserver vserver, final String vnfId) { - if (vserver.getRelationshipList() == null) { - vserver.setRelationshipList(new RelationshipList()); - } - final RelationshipList vserverRelationshiplist = vserver.getRelationshipList(); - vserverRelationshiplist.getRelationship().add(createRelationshipToGenericVnf(vnfId)); - } - - private Relationship createRelationshipToGenericVnf(final String vnfId) { - final Relationship relationship = new Relationship(); - relationship.setRelatedTo("generic-vnf"); - relationship.setRelationshipLabel("tosca.relationships.HostedOn"); - relationship.setRelatedLink("/aai/" + AAIVersion.LATEST - + AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId).build().toString()); - relationship.getRelationshipData().add(createRelationshipData("generic-vnf.vnf-id", vnfId)); - return relationship; - } - public void setOamIpAddressSource(final String vnfId, final OamIpAddressSource oamIpAddressSource) { mapOfVnfIdToOamIpAddressHolder.put(vnfId, oamIpAddressSource); } @@ -274,32 +214,4 @@ public class AaiHelper { return mapOfVnfIdToOamIpAddressHolder.get(vnfId); } - /** - * Add a relationship to the given tenant to the given VNF. - * - * @param vnf the generic vnf - * @param tenant the Tenant - */ - - public void addRelationshipFromGenericVnfToTenant(final GenericVnf vnf, final Tenant tenant) { - if (vnf.getRelationshipList() == null) { - vnf.setRelationshipList(new RelationshipList()); - } - final RelationshipList vnfmRelationshiplist = vnf.getRelationshipList(); - vnfmRelationshiplist.getRelationship().add(createRelationshipToTenant(tenant)); - } - - private Relationship createRelationshipToTenant(final Tenant tenant) { - final Relationship relationship = new Relationship(); - relationship.setRelatedTo("tenant"); - relationship.setRelatedLink("/aai/" + AAIVersion.LATEST + AAIUriFactory.createResourceUri(AAIObjectType.TENANT, - tenant.getCloudOwner(), tenant.getRegionName(), tenant.getTenantId()).build().toString()); - relationship.getRelationshipData() - .add(createRelationshipData("cloud-region.cloud-owner", tenant.getCloudOwner())); - relationship.getRelationshipData() - .add(createRelationshipData("cloud-region.cloud-region-id", tenant.getRegionName())); - relationship.getRelationshipData().add(createRelationshipData("tenant.tenant-id", tenant.getTenantId())); - return relationship; - } - } diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/aai/AaiServiceProvider.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/aai/AaiServiceProvider.java index 7021c02511..d19190d88e 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/aai/AaiServiceProvider.java +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/aai/AaiServiceProvider.java @@ -72,12 +72,22 @@ public interface AaiServiceProvider { EsrVnfm invokeGetVnfm(final String vnfmId); /** - * Invoke a PUT request for a generic vnf. + * Invoke a PATCH request for a generic vnf. * * @param vnf the generic vnf * @return */ - void invokePutGenericVnf(GenericVnf vnf); + void invokePatchGenericVnf(GenericVnf vnf); + + /** + * Invoke a PUT request for a relationship from a generic vnf to a VNFM. + * + * @param vnf the generic vnf + * @param vnfmId the ID of the VNFM + * @return + */ + void invokePutGenericVnfToVnfmRelationship(GenericVnf vnf, final String vnfmId); + /** * Invoke a PUT request for a vserver. @@ -92,6 +102,19 @@ public interface AaiServiceProvider { final Vserver vserver); /** + * Invoke a PUT request for a relationship from a vserver to a generic vnf. + * + * @param cloudOwner the cloud owner + * @param cloudRegion the cloud region the vserver is deployed on + * @param tenantId the ID of the tenant the vserver is deployed on + * @param vserver the vserver + * @param vnfId the ID of the generic vnf + * @return + */ + void invokePutVserverToVnfRelationship(final String cloudOwner, final String cloudRegion, final String tenantId, + final Vserver vserver, final String vnfId); + + /** * Invoke a DELETE request for a vserver. * * @param cloudOwner the cloud owner diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/aai/AaiServiceProviderImpl.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/aai/AaiServiceProviderImpl.java index 019a08af78..6dc6020834 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/aai/AaiServiceProviderImpl.java +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/aai/AaiServiceProviderImpl.java @@ -98,12 +98,18 @@ public class AaiServiceProviderImpl implements AaiServiceProvider { } @Override - public void invokePutGenericVnf(final GenericVnf vnf) { + public void invokePatchGenericVnf(final GenericVnf vnf) { aaiClientProvider.getAaiClient() .update(AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnf.getVnfId()), vnf); } @Override + public void invokePutGenericVnfToVnfmRelationship(final GenericVnf vnf, final String vnfmId) { + aaiClientProvider.getAaiClient().connect(AAIUriFactory.createResourceUri(AAIObjectType.VNFM, vnfmId), + AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnf.getVnfId())); + } + + @Override public void invokePutVserver(final String cloudOwner, final String cloudRegion, final String tenant, final Vserver vserver) { aaiClientProvider.getAaiClient().create(AAIUriFactory.createResourceUri(AAIObjectType.VSERVER, cloudOwner, @@ -111,6 +117,16 @@ public class AaiServiceProviderImpl implements AaiServiceProvider { } @Override + public void invokePutVserverToVnfRelationship(final String cloudOwner, final String cloudRegion, + final String tenant, final Vserver vserver, final String vnfId) { + aaiClientProvider.getAaiClient() + .connect( + AAIUriFactory.createResourceUri(AAIObjectType.VSERVER, cloudOwner, cloudRegion, tenant, + vserver.getVserverId()), + AAIUriFactory.createResourceUri(AAIObjectType.GENERIC_VNF, vnfId)); + } + + @Override public void invokeDeleteVserver(final String cloudOwner, final String cloudRegion, final String tenant, final String vserverId) { aaiClientProvider.getAaiClient().delete( diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/vnfm/VnfmServiceProviderConfiguration.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/vnfm/VnfmServiceProviderConfiguration.java index 93312cfa64..ae9316cfdf 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/vnfm/VnfmServiceProviderConfiguration.java +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/vnfm/VnfmServiceProviderConfiguration.java @@ -30,6 +30,7 @@ import java.security.NoSuchAlgorithmException; import java.security.UnrecoverableKeyException; import java.security.cert.CertificateException; import java.util.Iterator; +import java.util.ListIterator; import java.util.Map; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; @@ -41,8 +42,10 @@ import org.apache.http.impl.client.HttpClients; import org.apache.http.ssl.SSLContextBuilder; import org.onap.aai.domain.yang.EsrSystemInfo; import org.onap.aai.domain.yang.EsrVnfm; +import org.onap.logging.filter.spring.SpringClientPayloadFilter; import org.onap.so.adapters.vnfmadapter.extclients.vnfm.lcn.JSON; import org.onap.so.configuration.rest.BasicHttpHeadersProvider; +import org.onap.so.logging.jaxrs.filter.SOSpringClientFilter; import org.onap.so.rest.service.HttpRestServiceProvider; import org.onap.so.rest.service.HttpRestServiceProviderImpl; import org.slf4j.Logger; @@ -53,6 +56,7 @@ import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Configuration; import org.springframework.core.io.Resource; import org.springframework.http.client.BufferingClientHttpRequestFactory; +import org.springframework.http.client.ClientHttpRequestInterceptor; import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.http.converter.HttpMessageConverter; import org.springframework.http.converter.json.GsonHttpMessageConverter; @@ -167,4 +171,14 @@ public class VnfmServiceProviderConfiguration { } } + private void removeSpringClientFilter(final RestTemplate restTemplate) { + ListIterator<ClientHttpRequestInterceptor> interceptorIterator = restTemplate.getInterceptors().listIterator(); + while (interceptorIterator.hasNext()) { + ClientHttpRequestInterceptor interceptor = interceptorIterator.next(); + if (interceptor instanceof SOSpringClientFilter || interceptor instanceof SpringClientPayloadFilter) { + interceptorIterator.remove(); + } + } + } + } diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/lifecycle/LifecycleManager.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/lifecycle/LifecycleManager.java index 0aad91e5be..461c15a512 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/lifecycle/LifecycleManager.java +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/lifecycle/LifecycleManager.java @@ -81,21 +81,25 @@ public class LifecycleManager { * @return the response to the request */ public CreateVnfResponse createVnf(final String vnfIdInAai, final CreateVnfRequest request) { - final GenericVnf genericVnf = getGenericVnfFromAai(vnfIdInAai); + GenericVnf genericVnf = getGenericVnfFromAai(vnfIdInAai); EsrVnfm vnfm = aaiHelper.getAssignedVnfm(genericVnf); checkIfVnfAlreadyExistsInVnfm(vnfm, genericVnf); if (vnfm == null) { vnfm = aaiHelper.selectVnfm(genericVnf); - aaiHelper.addRelationshipFromGenericVnfToVnfm(genericVnf, vnfm.getVnfmId()); + aaiServiceProvider.invokePutGenericVnfToVnfmRelationship(genericVnf, vnfm.getVnfmId()); } - aaiHelper.addRelationshipFromGenericVnfToTenant(genericVnf, request.getTenant()); final InlineResponse201 vnfmResponse = sendCreateRequestToVnfm(request, genericVnf, vnfIdInAai, vnfm); logger.info("Create response: {}", vnfmResponse); genericVnf.setSelflink(getSelfLink(vnfmResponse, vnfm)); - aaiServiceProvider.invokePutGenericVnf(genericVnf); + + GenericVnf genericVnfPatch = new GenericVnf(); + genericVnfPatch.setVnfId(genericVnf.getVnfId()); + genericVnfPatch.setSelflink(genericVnf.getSelflink()); + aaiServiceProvider.invokePatchGenericVnf(genericVnfPatch); + final String vnfIdInVnfm = vnfmResponse.getId(); final OamIpAddressSource oamIpAddressSource = extractOamIpAddressSource(request); diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/notificationhandling/NotificationHandler.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/notificationhandling/NotificationHandler.java index eb912c8775..7a6bbfe0d9 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/notificationhandling/NotificationHandler.java +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/notificationhandling/NotificationHandler.java @@ -97,10 +97,12 @@ public class NotificationHandler implements Runnable { private void handleVnfInstantiateCompleted() { final GenericVnf genericVnf = aaiServiceProvider .invokeQueryGenericVnf(vnfInstance.getLinks().getSelf().getHref()).getGenericVnf().get(0); - setOamIpAddress(genericVnf, vnfInstance); - genericVnf.setOrchestrationStatus("Created"); - aaiServiceProvider.invokePutGenericVnf(genericVnf); + final GenericVnf genericVnfPatch = new GenericVnf(); + genericVnfPatch.setVnfId(genericVnf.getVnfId()); + setOamIpAddress(genericVnfPatch, vnfInstance); + genericVnfPatch.setOrchestrationStatus("Created"); + aaiServiceProvider.invokePatchGenericVnf(genericVnfPatch); addVservers(vnfLcmOperationOccurrenceNotification, genericVnf.getVnfId(), vnfInstance.getVimConnectionInfo()); @@ -162,9 +164,12 @@ public class NotificationHandler implements Runnable { jobManager.notificationProcessedForOperation(vnfLcmOperationOccurrenceNotification.getVnfLcmOpOccId(), deleteSuccessful); jobManager.vnfDeleted(vnfLcmOperationOccurrenceNotification.getVnfLcmOpOccId()); - genericVnf.setOrchestrationStatus("Assigned"); - genericVnf.setSelflink(""); - aaiServiceProvider.invokePutGenericVnf(genericVnf); + + final GenericVnf genericVnfPatch = new GenericVnf(); + genericVnfPatch.setVnfId(genericVnf.getVnfId()); + genericVnfPatch.setOrchestrationStatus("Assigned"); + genericVnfPatch.setSelflink(""); + aaiServiceProvider.invokePatchGenericVnf(genericVnfPatch); } } @@ -180,10 +185,11 @@ public class NotificationHandler implements Runnable { getVimConnectionInfo(vimConnectionIdToVimConnectionInfo, vnfc); if (ChangeTypeEnum.ADDED.equals(vnfc.getChangeType())) { final Vserver vserver = aaiHelper.createVserver(vnfc); - aaiHelper.addRelationshipFromVserverVnfToGenericVnf(vserver, vnfId); - aaiServiceProvider.invokePutVserver(getCloudOwner(vimConnectionInfo), getCloudRegion(vimConnectionInfo), getTenant(vimConnectionInfo), vserver); + + aaiServiceProvider.invokePutVserverToVnfRelationship(getCloudOwner(vimConnectionInfo), + getCloudRegion(vimConnectionInfo), getTenant(vimConnectionInfo), vserver, vnfId); } } } diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/resources/application.yaml b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/resources/application.yaml index 4434d2edd9..951d4a3bb9 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/resources/application.yaml +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/resources/application.yaml @@ -23,22 +23,11 @@ spring: http: converters: preferred-json-mapper: gson - -http: - client: - ssl: - trust-store: classpath:org.onap.so.trust.jks - trust-store-password: ',sx#.C*W)]wVgJC6ccFHI#:H' server: port: 9092 tomcat: max-threads: 50 - ssl: - key-alias: so@so.onap.org - key--store-password: 'ywsqCy:EEo#j}HJHM7z^Rk[L' - key-store: classpath:so-vnfm-adapter.p12 - key-store-type: PKCS12 mso: key: 07a7159d3bf51a0e53be7a8f89699be7 @@ -55,7 +44,7 @@ sdc: endpoint: http://sdc.onap/1234A vnfmadapter: - endpoint: https://so-vnfm-adapter.onap:9092 + endpoint: http://so-vnfm-adapter.onap:9092 #Actuator management: diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/test/java/org/onap/so/adapters/vnfmadapter/rest/Sol003LcnControllerTest.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/test/java/org/onap/so/adapters/vnfmadapter/rest/Sol003LcnControllerTest.java index 89a2c102f4..f83e9c94d2 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/test/java/org/onap/so/adapters/vnfmadapter/rest/Sol003LcnControllerTest.java +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/test/java/org/onap/so/adapters/vnfmadapter/rest/Sol003LcnControllerTest.java @@ -212,12 +212,16 @@ public class Sol003LcnControllerTest { final Vserver vserver = (Vserver) bodyArgument2.getAllValues().get(0); assertEquals("myVnfc1", vserver.getVserverId()); - final Relationship relationship = vserver.getRelationshipList().getRelationship().get(0); - assertEquals("generic-vnf", relationship.getRelatedTo()); - assertEquals("tosca.relationships.HostedOn", relationship.getRelationshipLabel()); - assertEquals("/aai/v15/network/generic-vnfs/generic-vnf/myTestVnfId", relationship.getRelatedLink()); - assertEquals("generic-vnf.vnf-id", relationship.getRelationshipData().get(0).getRelationshipKey()); - assertEquals("myTestVnfId", relationship.getRelationshipData().get(0).getRelationshipValue()); + + final ArgumentCaptor<AAIResourceUri> uriArgument1Connect = ArgumentCaptor.forClass(AAIResourceUri.class); + final ArgumentCaptor<AAIResourceUri> uriArgument2Connect = ArgumentCaptor.forClass(AAIResourceUri.class); + verify(aaiResourcesClient, timeout(1000)).connect(uriArgument1Connect.capture(), uriArgument2Connect.capture()); + assertEquals( + "/cloud-infrastructure/cloud-regions/cloud-region/" + CLOUD_OWNER + "/" + REGION + "/tenants/tenant/" + + TENANT_ID + "/vservers/vserver/myVnfc1", + uriArgument1Connect.getAllValues().get(0).build().toString()); + assertEquals("/network/generic-vnfs/generic-vnf/myTestVnfId", + uriArgument2Connect.getAllValues().get(0).build().toString()); } @Test diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/test/java/org/onap/so/adapters/vnfmadapter/rest/VnfmAdapterControllerTest.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/test/java/org/onap/so/adapters/vnfmadapter/rest/VnfmAdapterControllerTest.java index fe55907420..297f74433e 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/test/java/org/onap/so/adapters/vnfmadapter/rest/VnfmAdapterControllerTest.java +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/test/java/org/onap/so/adapters/vnfmadapter/rest/VnfmAdapterControllerTest.java @@ -25,6 +25,7 @@ import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertNull; import static org.mockito.ArgumentMatchers.eq; import static org.mockito.Mockito.doReturn; +import static org.mockito.Mockito.timeout; import static org.mockito.Mockito.verify; import static org.onap.so.client.RestTemplateConfig.CONFIGURABLE_REST_TEMPLATE; import static org.springframework.test.web.client.match.MockRestRequestMatchers.content; @@ -175,20 +176,14 @@ public class VnfmAdapterControllerTest { assertEquals("/network/generic-vnfs/generic-vnf/myTestVnfId", uriArgument.getValue().build().toString()); assertEquals("myTestVnfId", genericVnfArgument.getValue().getVnfId()); - assertEquals(2, genericVnfArgument.getValue().getRelationshipList().getRelationship().size()); - final Relationship vnfmRelationship = - genericVnfArgument.getValue().getRelationshipList().getRelationship().get(0); - assertEquals("esr-vnfm", vnfmRelationship.getRelatedTo()); - assertEquals("tosca.relationships.DependsOn", vnfmRelationship.getRelationshipLabel()); - assertEquals("/aai/v15/external-system/esr-vnfm-list/esr-vnfm/vnfm2", vnfmRelationship.getRelatedLink()); - - final Relationship tenantRelationship = - genericVnfArgument.getValue().getRelationshipList().getRelationship().get(1); - assertEquals("tenant", tenantRelationship.getRelatedTo()); - assertEquals( - "/aai/v15/cloud-infrastructure/cloud-regions/cloud-region/myTestCloudOwner/myTestRegion/tenants/tenant/myTestTenantId", - tenantRelationship.getRelatedLink()); + final ArgumentCaptor<AAIResourceUri> uriArgument1Connect = ArgumentCaptor.forClass(AAIResourceUri.class); + final ArgumentCaptor<AAIResourceUri> uriArgument2Connect = ArgumentCaptor.forClass(AAIResourceUri.class); + verify(aaiResourcesClient, timeout(1000)).connect(uriArgument1Connect.capture(), uriArgument2Connect.capture()); + assertEquals("/external-system/esr-vnfm-list/esr-vnfm/vnfm2", + uriArgument1Connect.getAllValues().get(0).build().toString()); + assertEquals("/network/generic-vnfs/generic-vnf/myTestVnfId", + uriArgument2Connect.getAllValues().get(0).build().toString()); // check the job status diff --git a/adapters/mso-workflow-message-adapter/src/test/java/org/onap/so/adapters/workflowmessage/BPRestCallbackTest.java b/adapters/mso-workflow-message-adapter/src/test/java/org/onap/so/adapters/workflowmessage/BPRestCallbackTest.java deleted file mode 100644 index 21917c3d2c..0000000000 --- a/adapters/mso-workflow-message-adapter/src/test/java/org/onap/so/adapters/workflowmessage/BPRestCallbackTest.java +++ /dev/null @@ -1,42 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2018 Huawei Technologies Co., Ltd. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.workflowmessage; - -import org.apache.http.entity.ContentType; -import org.junit.Test; -import org.mockito.Mock; - -import static junit.framework.Assert.assertFalse; - -public class BPRestCallbackTest { - - @Mock - ContentType contentType; - - @Test - public void testSendExceptionCase() { - - BPRestCallback test = new BPRestCallback(); - test.send("workflowMessageUrl/", "messageType", "correlator", contentType,"message"); - assertFalse(test.send("workflowMessageUrl/", "messageType", "correlator", contentType,"message")); - - } - } diff --git a/adapters/mso-workflow-message-adapter/src/test/java/org/onap/so/adapters/workflowmessage/WMAdapterRestTest.java b/adapters/mso-workflow-message-adapter/src/test/java/org/onap/so/adapters/workflowmessage/WMAdapterRestTest.java deleted file mode 100644 index 08728fa339..0000000000 --- a/adapters/mso-workflow-message-adapter/src/test/java/org/onap/so/adapters/workflowmessage/WMAdapterRestTest.java +++ /dev/null @@ -1,45 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2018 Huawei Technologies Co., Ltd. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - *l - * 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.workflowmessage; - -import org.junit.Assert; -import org.junit.Test; - -public class WMAdapterRestTest { - - @Test(expected = ClassFormatError.class) - public void testHealthCheckException() throws Exception { - - WMAdapterRest test = new WMAdapterRest(); - test.healthcheck("34388737-cdad-4d96-ae6f-39d08024b495"); - Assert.assertFalse(true); - - } - - @Test(expected = ClassFormatError.class) - public void testReceiveWorkflowMsgException() throws Exception { - WMAdapterRest test = new WMAdapterRest(); - test.receiveWorkflowMessage("contentTypeHeader", "messageType", "correlator", "content"); - Assert.assertFalse(true); - - } -} - |