diff options
Diffstat (limited to 'adapters')
74 files changed, 1940 insertions, 530 deletions
diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatEnvironmentEntry.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatEnvironmentEntry.java index 47ba076e0e..1f6ff1408c 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatEnvironmentEntry.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatEnvironmentEntry.java @@ -58,7 +58,8 @@ public class MsoHeatEnvironmentEntry { return; byte[] b = this.rawEntry.toString().getBytes(); MsoYamlEditorWithEnvt yaml = new MsoYamlEditorWithEnvt(b); - StringBuilder sb = null; + this.parameters = yaml.getParameterListFromEnvt(); + StringBuilder sb = this.getResourceRegistryRawEntry(); if (yaml != null) { this.parameters = yaml.getParameterListFromEnvt(); // this.resources = yaml.getResourceListFromEnvt(); diff --git a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatUtils.java b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatUtils.java index f5464645d6..62d9f068f9 100644 --- a/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatUtils.java +++ b/adapters/mso-adapter-utils/src/main/java/org/onap/so/openstack/utils/MsoHeatUtils.java @@ -33,6 +33,7 @@ import java.util.Map.Entry; import java.util.Set; import java.util.regex.Matcher; import java.util.regex.Pattern; +import org.onap.logging.filter.base.ErrorCode; import org.onap.logging.ref.slf4j.ONAPLogConstants; import org.onap.so.adapters.vdu.CloudInfo; import org.onap.so.adapters.vdu.PluginAction; @@ -45,14 +46,11 @@ import org.onap.so.adapters.vdu.VduPlugin; import org.onap.so.adapters.vdu.VduStateType; import org.onap.so.adapters.vdu.VduStatus; import org.onap.so.cloud.authentication.KeystoneAuthHolder; -import org.onap.so.db.catalog.beans.CloudIdentity; -import org.onap.so.db.catalog.beans.CloudSite; import org.onap.so.db.catalog.beans.HeatTemplate; import org.onap.so.db.catalog.beans.HeatTemplateParam; import org.onap.so.db.request.beans.CloudApiRequests; import org.onap.so.db.request.beans.InfraActiveRequests; import org.onap.so.db.request.client.RequestsDbClient; -import org.onap.logging.filter.base.ErrorCode; import org.onap.so.logger.MessageEnum; import org.onap.so.openstack.beans.CreateStackRequest; import org.onap.so.openstack.beans.HeatStatus; @@ -134,7 +132,6 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin { private static final ObjectMapper JSON_MAPPER = new ObjectMapper(); - /** * Create a new Stack in the specified cloud location and tenant. The Heat template and parameter map are passed in * as arguments, along with the cloud access credentials. It is expected that parameters have been validated and @@ -192,7 +189,10 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin { } else if (CREATE_FAILED.equals(currentStack.getStackStatus()) || DELETE_FAILED.equals(currentStack.getStackStatus())) { try { - processCreateStack(cloudSiteId, tenantId, timeoutMinutes, backout, currentStack, createStack, true); + if (pollForCompletion) { + processCreateStack(cloudSiteId, tenantId, timeoutMinutes, backout, currentStack, createStack, + true); + } } catch (MsoException e) { if (e instanceof StackCreationException) { logger.warn("Error during Stack will attempt to recreate stack"); @@ -201,9 +201,6 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin { if (pollForCompletion) { currentStack = processCreateStack(cloudSiteId, tenantId, timeoutMinutes, backout, currentStack, createStack, true); - } else { - currentStack = queryHeatStack(currentStack.getStackName() + "/" + currentStack.getId(), - cloudSiteId, tenantId); } } else { throw e; @@ -216,9 +213,6 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin { if (pollForCompletion) { currentStack = processCreateStack(cloudSiteId, tenantId, timeoutMinutes, backout, currentStack, createStack, true); - } else { - currentStack = - queryHeatStack(currentStack.getStackName() + "/" + currentStack.getId(), cloudSiteId, tenantId); } operationPerformed = true; } @@ -268,6 +262,7 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin { Stack heatStack, CreateStackParam stackCreate, boolean keyPairCleanUp) throws MsoException { Stack latestStack = null; try { + latestStack = pollStackForStatus(timeoutMinutes, heatStack, CREATE_IN_PROGRESS, cloudSiteId, tenantId, false); } catch (MsoException me) { @@ -277,7 +272,7 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin { stackCreate); } - protected Stack postProcessStackCreate(Stack stack, boolean backout, int timeoutMinutes, boolean cleanUpKeyPair, + public Stack postProcessStackCreate(Stack stack, boolean backout, int timeoutMinutes, boolean cleanUpKeyPair, String cloudSiteId, String tenantId, CreateStackParam stackCreate) throws MsoException { boolean stackCreationFailed = false; boolean stackRollbackFailed = false; @@ -327,7 +322,7 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin { } } - protected Stack pollStackForStatus(int timeoutMinutes, Stack stack, String stackStatus, String cloudSiteId, + public Stack pollStackForStatus(int timeoutMinutes, Stack stack, String stackStatus, String cloudSiteId, String tenantId, boolean notFoundIsSuccess) throws MsoException { int pollingFrequency = Integer.parseInt(this.environment.getProperty(createPollIntervalProp, CREATE_POLL_INTERVAL_DEFAULT)); @@ -336,7 +331,11 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin { int numberOfPollingAttempts = Math.floorDiv((timeoutMinutes * pollingMultiplier), pollingFrequency); Heat heatClient = getHeatClient(cloudSiteId, tenantId); while (true) { - Stack latestStack = queryHeatStack(heatClient, stack.getStackName() + "/" + stack.getId()); + String stackName = stack.getStackName() + "/" + stack.getId(); + if (stack.getId() == null) { + stackName = stack.getStackName(); + } + Stack latestStack = queryHeatStack(heatClient, stackName); if (latestStack == null && notFoundIsSuccess) { return null; } else if (latestStack != null) { @@ -387,27 +386,33 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin { protected Stack handleUnknownCreateStackFailure(Stack stack, int timeoutMinutes, String cloudSiteId, String tenantId) throws MsoException { if (stack != null && !Strings.isNullOrEmpty(stack.getStackName()) && !Strings.isNullOrEmpty(stack.getId())) { - return deleteStack(stack, timeoutMinutes, cloudSiteId, tenantId); + return deleteStack(stack, timeoutMinutes, cloudSiteId, tenantId, false); } else { throw new StackCreationException("Cannot Find Stack Name or Id"); } } - private Stack deleteStack(Stack stack, int timeoutMinutes, String cloudSiteId, String tenantId) - throws MsoException { + private Stack deleteStack(Stack stack, int timeoutMinutes, String cloudSiteId, String tenantId, + boolean pollForCompletion) throws MsoException { OpenStackRequest<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) { + logger.debug("Completed Executing executeAndRecordOpenstackRequest"); + if (pollForCompletion == true) { + Stack currentStack = + pollStackForStatus(timeoutMinutes, stack, DELETE_IN_PROGRESS, cloudSiteId, tenantId, true); + if (currentStack == null) { + return currentStack; + } + postProcessStackDelete(currentStack); return currentStack; } else { - postProcessStackDelete(currentStack); + logger.debug("Returning the stack"); + return stack; } - return currentStack; } - protected void postProcessStackDelete(Stack stack) throws MsoException { + public void postProcessStackDelete(Stack stack) throws MsoException { logger.info("Performing post processing on delete stack {}", stack); if (stack != null && !Strings.isNullOrEmpty(stack.getStackStatus())) { if (!DELETE_COMPLETE.equals(stack.getStackStatus())) @@ -505,10 +510,13 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin { stackInfo = new StackInfo(stackName, HeatStatus.NOTFOUND); stackInfo.setOperationPerformed(false); } else { - currentStack = deleteStack(currentStack, timeoutMinutes, cloudSiteId, tenantId); + currentStack = deleteStack(currentStack, timeoutMinutes, cloudSiteId, tenantId, pollForCompletion); stackInfo = new StackInfoMapper(currentStack).map(); stackInfo.setName(stackName); stackInfo.setOperationPerformed(true); + if (currentStack != null) { + stackInfo.setCanonicalName(currentStack.getStackName() + "/" + currentStack.getId()); + } } return stackInfo; } @@ -634,7 +642,7 @@ public class MsoHeatUtils extends MsoCommonUtils implements VduPlugin { return queryHeatStack(getHeatClient(cloudSiteId, tenantId), stackName); } - + // TODO enhancement - just have this return the stack then we dont have to query again in deleteStack public Map<String, Object> queryStackForOutputs(String cloudSiteId, String cloudOwner, String tenantId, String stackName) throws MsoException { logger.debug("MsoHeatUtils.queryStackForOutputs)"); diff --git a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatUtilsTest.java b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatUtilsTest.java index 0f9f7a273e..4938bff748 100644 --- a/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatUtilsTest.java +++ b/adapters/mso-adapter-utils/src/test/java/org/onap/so/openstack/utils/MsoHeatUtilsTest.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -264,9 +264,9 @@ public class MsoHeatUtilsTest extends MsoHeatUtils { heatUtils.handleUnknownCreateStackFailure(stack, 120, cloudSiteId, tenantId); Mockito.verify(heatUtils, times(1)).executeAndRecordOpenstackRequest(mockDeleteStack); - Mockito.verify(heatUtils, times(1)).pollStackForStatus(120, stack, "DELETE_IN_PROGRESS", cloudSiteId, tenantId, + Mockito.verify(heatUtils, times(0)).pollStackForStatus(120, stack, "DELETE_IN_PROGRESS", cloudSiteId, tenantId, true); - Mockito.verify(heatUtils, times(1)).postProcessStackDelete(deletedStack); + Mockito.verify(heatUtils, times(0)).postProcessStackDelete(deletedStack); } @@ -324,8 +324,6 @@ public class MsoHeatUtilsTest extends MsoHeatUtils { CreateStackParam createStackParam = new CreateStackParam(); createStackParam.setStackName("stackName"); - // doReturn(mockResources).when(heatUtils).queryStackResources(cloudSiteId, tenantId, "stackName", 2); - // doNothing().when(novaClient).deleteKeyPair(cloudSiteId, tenantId, "KeypairName"); doReturn(null).when(heatUtils).handleUnknownCreateStackFailure(stack, 120, cloudSiteId, tenantId); doReturn(createdStack).when(heatUtils).createStack(createStackParam, cloudSiteId, tenantId); doReturn(createdStack).when(heatUtils).processCreateStack(cloudSiteId, tenantId, 120, true, createdStack, diff --git a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/VfModuleRollback.java b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/VfModuleRollback.java index 5f93765688..5f4d9d3eab 100644 --- a/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/VfModuleRollback.java +++ b/adapters/mso-adapters-rest-interface/src/main/java/org/onap/so/adapters/vnfrest/VfModuleRollback.java @@ -44,15 +44,15 @@ public class VfModuleRollback { public VfModuleRollback(VnfRollback vrb, String vfModuleId, String vfModuleStackId, String messageId) { this.vnfId = vrb.getVnfId(); - this.vfModuleId = vfModuleId; - this.vfModuleStackId = vfModuleStackId; this.vfModuleCreated = vrb.getVnfCreated(); this.tenantId = vrb.getTenantId(); this.cloudOwner = vrb.getCloudOwner(); this.cloudSiteId = vrb.getCloudSiteId(); this.msoRequest = vrb.getMsoRequest(); - this.messageId = messageId; this.mode = vrb.getMode(); + this.vfModuleId = vfModuleId; + this.vfModuleStackId = vfModuleStackId; + this.messageId = messageId; } public VfModuleRollback(String vnfId, String vfModuleId, String vfModuleStackId, boolean vfModuleCreated, diff --git a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryServiceInfo.java b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryServiceInfo.java index 6c1c81c6ef..195ada37f7 100644 --- a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryServiceInfo.java +++ b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryServiceInfo.java @@ -24,8 +24,11 @@ import org.onap.so.db.catalog.beans.Service; import org.onap.so.db.catalog.beans.ServiceInfo; import org.slf4j.Logger; import org.slf4j.LoggerFactory; +import org.springframework.util.CollectionUtils; import javax.xml.bind.annotation.XmlRootElement; +import java.util.Collections; import java.util.HashMap; +import java.util.List; import java.util.Map; @XmlRootElement(name = "serviceInfo") @@ -45,8 +48,10 @@ public class QueryServiceInfo extends CatalogQuery { this.serviceInfo = new ServiceInfo(); } - public QueryServiceInfo(ServiceInfo serviceInfo) { - this.serviceInfo = serviceInfo; + public QueryServiceInfo(List<ServiceInfo> serviceInfos) { + if (!CollectionUtils.isEmpty(serviceInfos)) { + this.serviceInfo = serviceInfos.get(0); + } } public ServiceInfo getServiceInfo() { diff --git a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryServiceMacroHolder.java b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryServiceMacroHolder.java index d5aa472c8d..305d52a997 100644 --- a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryServiceMacroHolder.java +++ b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/catalogrest/QueryServiceMacroHolder.java @@ -94,7 +94,7 @@ public class QueryServiceMacroHolder extends CatalogQuery { subitem = new QueryAllottedResourceCustomization(service.getAllottedCustomizations()).JSON2(true, true); valueMap.put("_SERVICEALLOTTEDRESOURCES_", subitem.replaceAll(LINE_BEGINNING, "\t")); - subitem = new QueryServiceInfo(serviceMacroHolder.getServiceInfo()).JSON2(true, true); + subitem = new QueryServiceInfo(service.getServiceInfos()).JSON2(true, true); valueMap.put("_SERVICEINFO_", subitem.replaceAll(LINE_BEGINNING, "\t")); subitem = new QueryServiceProxyCustomization(service.getServiceProxyCustomizations()).JSON2(true, true); diff --git a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/rest/CatalogDbAdapterRest.java b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/rest/CatalogDbAdapterRest.java index fca1d3a45e..98abf15645 100644 --- a/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/rest/CatalogDbAdapterRest.java +++ b/adapters/mso-catalog-db-adapter/src/main/java/org/onap/so/adapters/catalogdb/rest/CatalogDbAdapterRest.java @@ -102,9 +102,6 @@ public class CatalogDbAdapterRest { @Autowired private InstanceGroupRepository instanceGroupRepository; - @Autowired - private ServiceInfoRepository serviceInfoRepository; - private static final String NO_MATCHING_PARAMETERS = "no matching parameters"; public Response respond(String version, int respStatus, boolean isArray, CatalogQuery qryResp) { @@ -307,8 +304,6 @@ public class CatalogDbAdapterRest { respStatus = HttpStatus.SC_NOT_FOUND; qryResp = new QueryServiceMacroHolder(); } else { - ServiceInfo serviceInfo = serviceInfoRepository.findByService(ret.getService()); - ret.setServiceInfo(serviceInfo); qryResp = new QueryServiceMacroHolder(ret); logger.debug("serviceMacroHolder qryResp= {}", qryResp); } diff --git a/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/R__MacroData.sql b/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/R__MacroData.sql index e5daf24d6c..b70d409cd8 100644 --- a/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/R__MacroData.sql +++ b/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/R__MacroData.sql @@ -30,7 +30,8 @@ INSERT INTO northbound_request_ref_lookup(MACRO_ACTION, ACTION, REQUEST_SCOPE, I ('NetworkCollection-Macro-Create', 'createInstance', 'NetworkCollection', false,true, '7','7', 'DEFAULT', '*'), ('NetworkCollection-Macro-Delete', 'deleteInstance', 'NetworkCollection', false,true, '7','7', 'DEFAULT', '*'), ('VFModule-ScaleOut', 'scaleOut', 'VfModule', true, true, '7','7', 'DEFAULT', '*'), -('VNF-InPlaceUpdate', 'inPlaceSoftwareUpdate', 'Vnf', true, true, '7','7', 'DEFAULT', '*'); +('VNF-InPlaceUpdate', 'inPlaceSoftwareUpdate', 'Vnf', true, true, '7','7', 'DEFAULT', '*'), +('VNF-Config-Update', 'applyUpdatedConfig', 'Vnf', true, true, '7','7', 'DEFAULT', '*'); INSERT INTO orchestration_flow_reference(COMPOSITE_ACTION, SEQ_NO, FLOW_NAME, FLOW_VERSION, NB_REQ_REF_LOOKUP_ID) VALUES @@ -198,9 +199,16 @@ INSERT INTO orchestration_flow_reference(COMPOSITE_ACTION, SEQ_NO, FLOW_NAME, FL ('VNF-InPlaceUpdate', '15', 'VNFResumeTrafficActivity', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-InPlaceUpdate' and CLOUD_OWNER = 'DEFAULT')), ('VNF-InPlaceUpdate', '16', 'VNFUnlockActivity', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-InPlaceUpdate' and CLOUD_OWNER = 'DEFAULT')), ('VNF-InPlaceUpdate', '17', 'VNFUnsetInMaintFlagActivity', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-InPlaceUpdate' and CLOUD_OWNER = 'DEFAULT')), -('VNF-InPlaceUpdate', '18', 'VNFUnsetClosedLoopDisabledFlagActivity', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-InPlaceUpdate' and CLOUD_OWNER = 'DEFAULT')); - - +('VNF-InPlaceUpdate', '18', 'VNFUnsetClosedLoopDisabledFlagActivity', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-InPlaceUpdate' and CLOUD_OWNER = 'DEFAULT')), +('VNF-Config-Update', '1', 'VNFCheckPserversLockedFlagActivity', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-Config-Update' and CLOUD_OWNER = 'DEFAULT')), +('VNF-Config-Update', '2', 'VNFCheckInMaintFlagActivity', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-Config-Update' and CLOUD_OWNER = 'DEFAULT')), +('VNF-Config-Update', '3', 'VNFSetInMaintFlagActivity', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-Config-Update' and CLOUD_OWNER = 'DEFAULT')), +('VNF-Config-Update', '4', 'VNFSetClosedLoopDisabledFlagActivity', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-Config-Update' and CLOUD_OWNER = 'DEFAULT')), +('VNF-Config-Update', '5', 'VNFHealthCheckActivity', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-Config-Update' and CLOUD_OWNER = 'DEFAULT')), +('VNF-Config-Update', '6', 'VNFConfigModifyActivity', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-Config-Update' and CLOUD_OWNER = 'DEFAULT')), +('VNF-Config-Update', '7', 'VNFHealthCheckActivity', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-Config-Update' and CLOUD_OWNER = 'DEFAULT')), +('VNF-Config-Update', '8', 'VNFUnsetInMaintFlagActivity', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-Config-Update' and CLOUD_OWNER = 'DEFAULT')), +('VNF-Config-Update', '9', 'VNFUnsetClosedLoopDisabledFlagActivity', 1.0,(SELECT id from northbound_request_ref_lookup WHERE MACRO_ACTION = 'VNF-Config-Update' and CLOUD_OWNER = 'DEFAULT')); INSERT INTO rainy_day_handler_macro (FLOW_NAME, SERVICE_TYPE, VNF_TYPE, ERROR_CODE, WORK_STEP, POLICY) VALUES @@ -860,7 +868,8 @@ VALUES ('VNFUpgradePostCheckActivity', 'NO_VALIDATE', 'CUSTOM'), ('VNFUpgradePreCheckActivity', 'NO_VALIDATE', 'CUSTOM'), ('VNFUpgradeSoftwareActivity', 'NO_VALIDATE', 'CUSTOM'), -('VnfInPlaceSoftwareUpdate', 'NO_VALIDATE', 'CUSTOM'); +('VnfInPlaceSoftwareUpdate', 'NO_VALIDATE', 'CUSTOM'), +('VNFConfigModifyActivity', 'NO_VALIDATE', 'CUSTOM'); UPDATE northbound_request_ref_lookup SET SERVICE_TYPE = '*' WHERE SERVICE_TYPE IS NULL; @@ -881,6 +890,10 @@ UPDATE vnf_recipe SET ORCHESTRATION_URI = '/mso/async/services/WorkflowActionBB' WHERE NF_ROLE = 'GR-API-DEFAULT' AND ACTION = 'inPlaceSoftwareUpdate'; +UPDATE vnf_recipe +SET ORCHESTRATION_URI = '/mso/async/services/WorkflowActionBB' +WHERE NF_ROLE = 'GR-API-DEFAULT' AND ACTION = 'applyUpdatedConfig'; + INSERT INTO rainy_day_handler_macro (FLOW_NAME, SERVICE_TYPE, VNF_TYPE, ERROR_CODE, WORK_STEP, POLICY, SECONDARY_POLICY, REG_EX_ERROR_MESSAGE, SERVICE_ROLE) VALUES ('VNFCheckPserversLockedFlagActivity','*','*','*','*','Manual','Abort','*', '*'), diff --git a/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V7.5.1__AddServiceArtifact.sql b/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V7.5.1__AddServiceArtifact.sql new file mode 100644 index 0000000000..60a9482707 --- /dev/null +++ b/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V7.5.1__AddServiceArtifact.sql @@ -0,0 +1,17 @@ +use catalogdb; + + +ALTER TABLE `service_info` + ADD COLUMN IF NOT EXISTS SERVICE_MODEL_UUID varchar (200) + NOT NULL; + + +ALTER TABLE `service_artifact` DROP FOREIGN KEY `fk_service_artifact_service_info1`; + +ALTER TABLE `service_info` + ADD CONSTRAINT `fk_service_info_service1` FOREIGN KEY (`SERVICE_MODEL_UUID`) REFERENCES `service` (`MODEL_UUID`) ON DELETE CASCADE ON UPDATE CASCADE; + +ALTER TABLE `service_artifact` + ADD CONSTRAINT `fk_service_artifact_service1` FOREIGN KEY (`SERVICE_MODEL_UUID`) REFERENCES `service` (`MODEL_UUID`) ON DELETE CASCADE ON UPDATE CASCADE; + +DROP TABLE IF EXISTS `service_to_service_info`; diff --git a/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V8.5__AddCloudOwner.sql b/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V8.5__AddCloudOwner.sql new file mode 100644 index 0000000000..92502e2696 --- /dev/null +++ b/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V8.5__AddCloudOwner.sql @@ -0,0 +1,13 @@ +use catalogdb; + + +ALTER TABLE cloud_sites + ADD COLUMN IF NOT EXISTS CLOUD_OWNER varchar(255); + + +CREATE TABLE IF NOT EXISTS `network_technology_reference` ( + `ID` INT(11) NOT NULL AUTO_INCREMENT, + `NETWORK_TECHNOLOGY` varchar(200) NOT NULL , + `CLOUD_OWNER` varchar(200) NOT NULL, + PRIMARY KEY (`ID`) +) ENGINE=InnoDB DEFAULT CHARSET=latin1;
\ No newline at end of file diff --git a/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V8.6__Update_Service_Function.sql b/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V8.6__Update_Service_Function.sql new file mode 100644 index 0000000000..51be8be664 --- /dev/null +++ b/adapters/mso-catalog-db-adapter/src/main/resources/db/migration/V8.6__Update_Service_Function.sql @@ -0,0 +1,4 @@ +use catalogdb; + +ALTER TABLE service + ADD COLUMN IF NOT EXISTS service_function varchar(200) DEFAULT NULL;
\ No newline at end of file diff --git a/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/NetworkCollectionCatalogDbQueryTest.java b/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/NetworkCollectionCatalogDbQueryTest.java index 440270e047..0ffc213a4e 100644 --- a/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/NetworkCollectionCatalogDbQueryTest.java +++ b/adapters/mso-catalog-db-adapter/src/test/java/org/onap/so/adapters/catalogdb/catalogrest/NetworkCollectionCatalogDbQueryTest.java @@ -30,13 +30,13 @@ import java.util.List; import javax.transaction.Transactional; import org.junit.Before; import org.junit.Test; -import org.junit.runner.RunWith; -import org.onap.so.adapters.catalogdb.CatalogDBApplication; import org.onap.so.adapters.catalogdb.CatalogDbAdapterBaseTest; import org.onap.so.db.catalog.beans.BuildingBlockDetail; import org.onap.so.db.catalog.beans.CollectionNetworkResourceCustomization; import org.onap.so.db.catalog.beans.CollectionResourceCustomization; import org.onap.so.db.catalog.beans.CollectionResourceInstanceGroupCustomization; +import org.onap.so.db.catalog.beans.CvnfcConfigurationCustomization; +import org.onap.so.db.catalog.beans.CvnfcCustomization; import org.onap.so.db.catalog.beans.InstanceGroup; import org.onap.so.db.catalog.beans.NetworkCollectionResourceCustomization; import org.onap.so.db.catalog.client.CatalogDbClientPortChanger; @@ -44,9 +44,6 @@ import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.web.server.LocalServerPort; -import org.springframework.boot.test.context.SpringBootTest; -import org.springframework.test.context.ActiveProfiles; -import org.springframework.test.context.junit4.SpringRunner; public class NetworkCollectionCatalogDbQueryTest extends CatalogDbAdapterBaseTest { @@ -149,4 +146,16 @@ public class NetworkCollectionCatalogDbQueryTest extends CatalogDbAdapterBaseTes assertNotNull(collectionNetworkCust); logger.debug(collectionNetworkCust.getModelCustomizationUUID()); } + + @Test + public void getCvnfcCustomization() { + client.getServiceByID(serviceUUID); + String vfId = "cb82ffd8-252a-11e7-93ae-92361f002671"; + String vnfId = "68dc9a92-214c-11e7-93ae-92361f002671"; + + CvnfcConfigurationCustomization fabricConfig = + client.getCvnfcCustomization(serviceUUID, vnfId, vfId, "dadc2c8c-2bab-11e9-b210-d663bd873d95"); + assertEquals("386c9aa7-9318-48ee-a6d1-1bf0f85de385", fabricConfig.getModelCustomizationUUID()); + } + } diff --git a/adapters/mso-catalog-db-adapter/src/test/resources/db/migration/afterMigrate.sql b/adapters/mso-catalog-db-adapter/src/test/resources/db/migration/afterMigrate.sql index 32c51293c2..8fd171bf64 100644 --- a/adapters/mso-catalog-db-adapter/src/test/resources/db/migration/afterMigrate.sql +++ b/adapters/mso-catalog-db-adapter/src/test/resources/db/migration/afterMigrate.sql @@ -213,8 +213,30 @@ VALUES ( '1', 'testNfcFunction', 'testNfcNamingCode', '2018-07-17 14:05:08', + '9bcce658-9b37-11e8-98d0-529269fb1459',1), + ( '2', + 'dadc2c8c-2bab-11e9-b210-d663bd873d95', + 'testModelInstanceName', + 'b25735fe-9b37-11e8-98d0-529269fb1459', + 'ba7e6ef0-9b37-11e8-98d0-529269fb1459', + 'testModelVersion', + 'testModelName', + 'testToscaNodeType', + 'testCvnfcCustomzationDescription', + 'testNfcFunction', + 'testNfcNamingCode', + '2018-07-17 14:05:08', '9bcce658-9b37-11e8-98d0-529269fb1459',1); + + +INSERT IGNORE INTO `configuration` (`MODEL_UUID`, `MODEL_INVARIANT_UUID`, `MODEL_VERSION`, `MODEL_NAME`, `TOSCA_NODE_TYPE`, `DESCRIPTION`, `CREATION_TIMESTAMP`) VALUES + ('d2195b0e-307a-4d30-b82f-9c82001d965e', '2f0a4b7a-dfdb-4f82-a2ab-b65d1ddd5e8e', '13.0', 'Fabric Configuration', 'org.openecomp.nodes.FabricConfiguration', 'A fabric Configuration object', '2019-06-04 20:12:20'); + +INSERT IGNORE INTO `cvnfc_configuration_customization` (`MODEL_CUSTOMIZATION_UUID`, `MODEL_INSTANCE_NAME`, `CONFIGURATION_TYPE`, `CONFIGURATION_ROLE`, `CONFIGURATION_FUNCTION`, `POLICY_NAME`, `CREATION_TIMESTAMP`, `CONFIGURATION_MODEL_UUID`, `CVNFC_CUSTOMIZATION_ID`) VALUES + ('386c9aa7-9318-48ee-a6d1-1bf0f85de385', 'Fabric Configuration 0', '5G', 'Fabric Config', 'Network Cloud', 'Config_MS_fabric_configuration_FRWL.1.xml', '2019-06-04 20:12:20', 'd2195b0e-307a-4d30-b82f-9c82001d965e', '2'); + + insert into service(model_uuid, model_name, model_invariant_uuid, model_version, description, creation_timestamp, tosca_csar_artifact_uuid, service_type, service_role, environment_context, workload_context) values ('5df8b6de-2083-11e7-93ae-92361f002676', 'PNF_routing_service', '9647dfc4-2083-11e7-93ae-92361f002676', '1.0', 'PNF service', '2019-03-08 12:00:29', null, 'NA', 'NA', 'Luna', 'Oxygen'); @@ -231,4 +253,4 @@ insert into workflow(artifact_uuid, artifact_name, name, operation_name, version ('5b0c4322-643d-4c9f-b184-4516049e99b1', 'testingWorkflow.bpmn', 'testingWorkflow', 'create', 1, 'Test Workflow', null, 'vnf', 'sdc'); insert into vnf_resource_to_workflow(vnf_resource_model_uuid, workflow_id) values -('ff2ae348-214a-11e7-93ae-92361f002671', '1'); +('ff2ae348-214a-11e7-93ae-92361f002671', '1');
\ No newline at end of file diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditStackService.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditStackService.java deleted file mode 100644 index 7cc7c02f23..0000000000 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditStackService.java +++ /dev/null @@ -1,91 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.audit; - -import javax.annotation.PostConstruct; -import org.camunda.bpm.client.ExternalTaskClient; -import org.onap.so.utils.ExternalTaskServiceUtils; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Profile; -import org.springframework.core.env.Environment; -import org.springframework.stereotype.Component; - -@Component -@Profile("!test") -public class AuditStackService { - - private static final String MSO_AUDIT_LOCK_TIME = "mso.audit.lock-time"; - - private static final Logger logger = LoggerFactory.getLogger(AuditStackService.class); - - private static final String DEFAULT_AUDIT_LOCK_TIME = "60000"; - - private static final String DEFAULT_MAX_CLIENTS_FOR_TOPIC = "10"; - - - @Autowired - public Environment env; - - @Autowired - private AuditCreateStackService auditCreateStack; - - @Autowired - private AuditDeleteStackService auditDeleteStack; - - @Autowired - private AuditQueryStackService auditQueryStack; - - @Autowired - private ExternalTaskServiceUtils externalTaskServiceUtils; - - @PostConstruct - public void auditAddAAIInventory() throws Exception { - for (int i = 0; i < externalTaskServiceUtils.getMaxClients(); i++) { - ExternalTaskClient client = externalTaskServiceUtils.createExternalTaskClient(); - client.subscribe("InventoryAddAudit") - .lockDuration(Long.parseLong(env.getProperty(MSO_AUDIT_LOCK_TIME, DEFAULT_AUDIT_LOCK_TIME))) - .handler(auditCreateStack::executeExternalTask).open(); - } - } - - @PostConstruct - public void auditDeleteAAIInventory() throws Exception { - for (int i = 0; i < externalTaskServiceUtils.getMaxClients(); i++) { - ExternalTaskClient client = externalTaskServiceUtils.createExternalTaskClient(); - client.subscribe("InventoryDeleteAudit") - .lockDuration(Long.parseLong(env.getProperty(MSO_AUDIT_LOCK_TIME, DEFAULT_AUDIT_LOCK_TIME))) - .handler(auditDeleteStack::executeExternalTask).open(); - } - } - - @PostConstruct - public void auditQueryInventory() throws Exception { - for (int i = 0; i < externalTaskServiceUtils.getMaxClients(); i++) { - ExternalTaskClient client = externalTaskServiceUtils.createExternalTaskClient(); - client.subscribe("InventoryQueryAudit") - .lockDuration(Long.parseLong(env.getProperty(MSO_AUDIT_LOCK_TIME, DEFAULT_AUDIT_LOCK_TIME))) - .handler(auditQueryStack::executeExternalTask).open(); - } - } - -} diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/cloudregion/CloudRegionRestV1.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/cloudregion/CloudRegionRestV1.java index 780480507b..6cf42e1433 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/cloudregion/CloudRegionRestV1.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/cloudregion/CloudRegionRestV1.java @@ -56,7 +56,6 @@ public class CloudRegionRestV1 { private CloudRestImpl cloudRestImpl; @POST - @Path("{cloud-region-id}/{cloud-owner}") @Consumes({MediaType.APPLICATION_JSON}) @Produces({MediaType.APPLICATION_JSON}) @ApiOperation(value = "CreateCloudRegion", response = Response.class, @@ -65,9 +64,8 @@ public class CloudRegionRestV1 { @ApiResponse(code = 500, message = "Create Cloud Region has failed")}) public Response createCloudRegion( @ApiParam(value = "cloud-region-id", required = true) @PathParam("cloud-region-id") String cloudRegionId, - @ApiParam(value = "cloud-owner", required = true) @PathParam("cloud-owner") String cloudOwner, @ApiParam(value = "CloudSite", required = true) final CloudSite cloudSite) { - cloudRestImpl.createCloudRegion(cloudSite, cloudOwner); + cloudRestImpl.createCloudRegion(cloudSite); return Response.status(HttpStatus.SC_CREATED).build(); } @@ -96,7 +94,7 @@ public class CloudRegionRestV1 { @ApiParam(value = "cloud-region-id", required = true) @PathParam("cloud-region-id") String cloudRegionId, @ApiParam(value = "cloud-owner", required = true) @PathParam("cloud-owner") String cloudOwner, @ApiParam(value = "CloudSite", required = true) final CloudSite cloudSite) { - cloudRestImpl.updateCloudRegion(cloudSite, cloudOwner); + cloudRestImpl.updateCloudRegion(cloudSite); return Response.status(HttpStatus.SC_OK).build(); } } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/cloudregion/CloudRestImpl.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/cloudregion/CloudRestImpl.java index 4cde8655ae..380f42fa69 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/cloudregion/CloudRestImpl.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/cloudregion/CloudRestImpl.java @@ -1,13 +1,21 @@ package org.onap.so.adapters.cloudregion; +import java.util.List; import java.util.Optional; import org.onap.aai.domain.yang.CloudRegion; +import org.onap.aai.domain.yang.Complex; +import org.onap.aai.domain.yang.NetworkTechnologies; +import org.onap.so.client.aai.AAIObjectPlurals; import org.onap.so.client.aai.AAIObjectType; import org.onap.so.client.aai.AAIResourcesClient; +import org.onap.so.client.aai.entities.uri.AAIPluralResourceUri; import org.onap.so.client.aai.entities.uri.AAIResourceUri; import org.onap.so.client.aai.entities.uri.AAIUriFactory; import org.onap.so.db.catalog.beans.CloudSite; +import org.onap.so.db.catalog.beans.NetworkTechnologyReference; import org.onap.so.db.catalog.client.CatalogDbClient; +import org.onap.so.db.catalog.data.repository.NetworkTechnologyReferenceRepository; +import org.onap.so.db.catalog.utils.MavenLikeVersioning; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -21,14 +29,17 @@ public class CloudRestImpl { private AAIResourcesClient aaiClient; @Autowired + private NetworkTechnologyReferenceRepository ctrRepo; + + @Autowired private CatalogDbClient catalogDBClient; - public void createCloudRegion(CloudSite cloudSite, String cloudOwner) throws CloudException { + public void createCloudRegion(CloudSite cloudSite) throws CloudException { createRegionInCatalogDb(cloudSite); - createCloudRegionInAAI(cloudSite, cloudOwner); + createCloudRegionInAAI(cloudSite); } - public void updateCloudRegion(CloudSite cloudSite, String cloudOwner) throws CloudException { + public void updateCloudRegion(CloudSite cloudSite) throws CloudException { updateRegionInCatalogDb(cloudSite); } @@ -50,18 +61,49 @@ public class CloudRestImpl { } } - protected void createCloudRegionInAAI(CloudSite cloudSite, String cloudOwner) { + protected void createCloudRegionInAAI(CloudSite cloudSite) { try { - CloudRegion cloudRegion = mapCloudRegion(cloudSite, cloudOwner); - AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.CLOUD_REGION, + CloudRegion cloudRegion = mapCloudRegion(cloudSite); + Optional<Complex> complex = retrieveComplex(cloudSite); + if (complex.isPresent()) { + cloudRegion.setComplexName(complex.get().getComplexName()); + } + AAIResourceUri cloudRegionURI = AAIUriFactory.createResourceUri(AAIObjectType.CLOUD_REGION, cloudRegion.getCloudOwner(), cloudRegion.getCloudRegionId()); - getAaiClient().createIfNotExists(uri, Optional.of(cloudRegion)); + getAaiClient().createIfNotExists(cloudRegionURI, Optional.of(cloudRegion)); + if (complex.isPresent()) { + AAIResourceUri complexURI = AAIUriFactory.createResourceUri(AAIObjectType.COMPLEX, cloudSite.getClli()); + getAaiClient().connect(cloudRegionURI, complexURI); + } + createCloudRegionNetworkTechnologyRelationship(cloudSite, cloudRegionURI); } catch (Exception e) { logger.error("Error creating cloud region in AAI", e); throw new CloudException("Error creating cloud region in AAI: " + e.getMessage(), e); } } + protected void createCloudRegionNetworkTechnologyRelationship(CloudSite cloudSite, AAIResourceUri cloudRegionURI) { + List<NetworkTechnologyReference> listOfNetworkTech = ctrRepo.findAllByCloudOwner(cloudSite.getCloudOwner()); + listOfNetworkTech.stream().forEach(tech -> linkCloudAndTechnology(tech.getNetworkTechnology(), cloudRegionURI)); + } + + protected Optional<Complex> retrieveComplex(CloudSite cloudSite) { + AAIResourceUri complexURI = AAIUriFactory.createResourceUri(AAIObjectType.COMPLEX, cloudSite.getClli()); + return getAaiClient().get(Complex.class, complexURI); + } + + protected void linkCloudAndTechnology(String networkTechnologyName, AAIResourceUri cloudRegionURI) { + AAIPluralResourceUri technologyPluralUri = AAIUriFactory.createResourceUri(AAIObjectPlurals.NETWORK_TECHNOLOGY) + .queryParam("network-technology-name", networkTechnologyName); + Optional<NetworkTechnologies> networkTechnology = + getAaiClient().get(NetworkTechnologies.class, technologyPluralUri); + if (networkTechnology.isPresent()) { + AAIResourceUri networkTechnologyURI = AAIUriFactory.createResourceUri(AAIObjectType.NETWORK_TECHNOLOGY, + networkTechnology.get().getNetworkTechnology().get(0).getNetworkTechnologyId()); + getAaiClient().connect(cloudRegionURI, networkTechnologyURI); + } + } + protected void createRegionInCatalogDb(CloudSite cloudSite) throws CloudException { try { CloudSite existingCloudSite = catalogDBClient.getCloudSite(cloudSite.getRegionId()); @@ -74,16 +116,22 @@ public class CloudRestImpl { } } - protected CloudRegion mapCloudRegion(CloudSite cloudSite, String cloudOwner) { + protected CloudRegion mapCloudRegion(CloudSite cloudSite) { CloudRegion region = new CloudRegion(); - region.setCloudOwner(cloudOwner); + region.setCloudOwner(cloudSite.getCloudOwner()); region.setCloudRegionId(cloudSite.getRegionId()); region.setCloudRegionVersion(cloudSite.getCloudVersion()); region.setOwnerDefinedType("cLCP"); + region.setCloudType("openstack"); + MavenLikeVersioning cloudVersion = new MavenLikeVersioning(); + cloudVersion.setVersion(cloudSite.getCloudVersion()); + if (cloudVersion.isMoreRecentThan("3.0")) { + region.setCloudZone(cloudSite.getRegionId().substring(0, cloudSite.getRegionId().length() - 1)); + } else { + region.setCloudZone(cloudSite.getRegionId()); + } region.setOrchestrationDisabled(false); - region.setComplexName("NA"); region.setInMaint(false); - region.setCloudType("openstack"); return region; } diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/CreateInventoryService.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/CreateInventoryService.java deleted file mode 100644 index 4ab4d14dac..0000000000 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/CreateInventoryService.java +++ /dev/null @@ -1,52 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * ONAP - SO - * ================================================================================ - * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.onap.so.adapters.inventory.create; - -import javax.annotation.PostConstruct; -import org.camunda.bpm.client.ExternalTaskClient; -import org.onap.so.utils.ExternalTaskServiceUtils; -import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.context.annotation.Profile; -import org.springframework.core.env.Environment; -import org.springframework.stereotype.Component; - -@Component -@Profile("!test") -public class CreateInventoryService { - - @Autowired - public Environment env; - - @Autowired - private CreateInventoryTask createInventory; - - @Autowired - private ExternalTaskServiceUtils externalTaskServiceUtils; - - @PostConstruct - public void auditAAIInventory() throws Exception { - ExternalTaskClient client = externalTaskServiceUtils.createExternalTaskClient(); - client.subscribe("InventoryCreate") - .lockDuration(Long.parseLong(env.getProperty("mso.audit.lock-time", "60000"))) - .handler(createInventory::executeExternalTask).open(); - } - -} diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/MsoNetworkAdapterImpl.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/network/MsoNetworkAdapterImpl.java index 257374fdb2..4728effdca 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 @@ -97,7 +97,7 @@ public class MsoNetworkAdapterImpl implements MsoNetworkAdapter { private static final String NETWORK_CREATED_STATUS_MESSAGE = "The new network was successfully created in the cloud"; private static final String NETWORK_NOT_EXIST_STATUS_MESSAGE = - "The network as not found, thus no network was deleted in the cloud via this request"; + "The network was not found, thus no network was deleted in the cloud via this request"; private static final String NETWORK_DELETED_STATUS_MESSAGE = "The network was successfully deleted in the cloud"; private static final Logger logger = LoggerFactory.getLogger(MsoNetworkAdapterImpl.class); diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/TaskServices.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/TaskServices.java new file mode 100644 index 0000000000..d282046b3f --- /dev/null +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/TaskServices.java @@ -0,0 +1,132 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.tasks; + +import javax.annotation.PostConstruct; +import org.camunda.bpm.client.ExternalTaskClient; +import org.onap.so.utils.ExternalTaskServiceUtils; +import org.onap.so.adapters.tasks.audit.AuditCreateStackService; +import org.onap.so.adapters.tasks.audit.AuditDeleteStackService; +import org.onap.so.adapters.tasks.audit.AuditQueryStackService; +import org.onap.so.adapters.tasks.inventory.CreateInventoryTask; +import org.onap.so.adapters.tasks.orchestration.PollService; +import org.onap.so.adapters.tasks.orchestration.RollbackService; +import org.onap.so.adapters.tasks.orchestration.StackService; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.context.annotation.Profile; +import org.springframework.stereotype.Component; + +@Component +@Profile("!test") +public class TaskServices { + + private static final Logger logger = LoggerFactory.getLogger(TaskServices.class); + + @Autowired + private ExternalTaskServiceUtils externalTaskServiceUtils; + + @Autowired + private AuditCreateStackService auditCreateStack; + + @Autowired + private AuditDeleteStackService auditDeleteStack; + + @Autowired + private AuditQueryStackService auditQueryStack; + + @Autowired + private CreateInventoryTask createInventory; + + @Autowired + private StackService stackService; + + @Autowired + private PollService pollService; + + @Autowired + private RollbackService rollbackService; + + @PostConstruct + public void auditAddAAIInventory() throws Exception { + for (int i = 0; i < externalTaskServiceUtils.getMaxClients(); i++) { + ExternalTaskClient client = externalTaskServiceUtils.createExternalTaskClient(); + client.subscribe("InventoryAddAudit").lockDuration(externalTaskServiceUtils.getLockDuration()) + .handler(auditCreateStack::executeExternalTask).open(); + } + } + + @PostConstruct + public void auditDeleteAAIInventory() throws Exception { + for (int i = 0; i < externalTaskServiceUtils.getMaxClients(); i++) { + ExternalTaskClient client = externalTaskServiceUtils.createExternalTaskClient(); + client.subscribe("InventoryDeleteAudit").lockDuration(externalTaskServiceUtils.getLockDuration()) + .handler(auditDeleteStack::executeExternalTask).open(); + } + } + + @PostConstruct + public void auditQueryInventory() throws Exception { + for (int i = 0; i < externalTaskServiceUtils.getMaxClients(); i++) { + ExternalTaskClient client = externalTaskServiceUtils.createExternalTaskClient(); + client.subscribe("InventoryQueryAudit").lockDuration(externalTaskServiceUtils.getLockDuration()) + .handler(auditQueryStack::executeExternalTask).open(); + } + } + + @PostConstruct + public void auditAAIInventory() throws Exception { + for (int i = 0; i < externalTaskServiceUtils.getMaxClients(); i++) { + ExternalTaskClient client = externalTaskServiceUtils.createExternalTaskClient(); + client.subscribe("InventoryCreate").lockDuration(externalTaskServiceUtils.getLockDuration()) + .handler(createInventory::executeExternalTask).open(); + } + } + + @PostConstruct + public void openstackInvoker() throws Exception { + for (int i = 0; i < externalTaskServiceUtils.getMaxClients(); i++) { + ExternalTaskClient client = externalTaskServiceUtils.createExternalTaskClient(); + client.subscribe("OpenstackAdapterInvoke").lockDuration(externalTaskServiceUtils.getLockDuration()) + .handler(stackService::executeExternalTask).open(); + } + } + + @PostConstruct + public void openstackPoller() throws Exception { + for (int i = 0; i < externalTaskServiceUtils.getMaxClients(); i++) { + ExternalTaskClient client = externalTaskServiceUtils.createExternalTaskClient(); + client.subscribe("OpenstackAdapterPolling").lockDuration(externalTaskServiceUtils.getLockDuration()) + .handler(pollService::executeExternalTask).open(); + } + } + + @PostConstruct + public void openstackRollback() throws Exception { + for (int i = 0; i < externalTaskServiceUtils.getMaxClients(); i++) { + ExternalTaskClient client = externalTaskServiceUtils.createExternalTaskClient(); + client.subscribe("OpenstackAdapterRollback").lockDuration(externalTaskServiceUtils.getLockDuration()) + .handler(rollbackService::executeExternalTask).open(); + } + } + +} diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AbstractAudit.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/audit/AbstractAudit.java index ad28f0daeb..7622c1ba28 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AbstractAudit.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/audit/AbstractAudit.java @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.adapters.audit; +package org.onap.so.adapters.tasks.audit; import org.onap.so.client.aai.AAIResourcesClient; 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/tasks/audit/AbstractAuditService.java index ddd9fb1b5e..2f7155bffc 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/tasks/audit/AbstractAuditService.java @@ -19,14 +19,13 @@ */ -package org.onap.so.adapters.audit; +package org.onap.so.adapters.tasks.audit; import java.util.Optional; import org.onap.so.objects.audit.AAIObjectAudit; import org.onap.so.objects.audit.AAIObjectAuditList; import org.onap.so.utils.ExternalTaskUtils; import org.onap.so.utils.RetrySequenceLevel; -import org.onap.logging.filter.base.ONAPComponents; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; 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/tasks/audit/AuditCreateStackService.java index 8291fa9882..874823a7cd 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/tasks/audit/AuditCreateStackService.java @@ -20,7 +20,7 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.adapters.audit; +package org.onap.so.adapters.tasks.audit; import java.util.HashMap; import java.util.Map; @@ -30,7 +30,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.logging.tasks.AuditMDCSetup; import org.onap.so.objects.audit.AAIObjectAuditList; import org.onap.so.utils.RetrySequenceLevel; import org.slf4j.Logger; @@ -47,13 +47,13 @@ public class AuditCreateStackService extends AbstractAuditService { public HeatStackAudit heatStackAudit; @Autowired - private AuditMDCSetup mdcSetup; + public AuditMDCSetup mdcSetup; public AuditCreateStackService() { super(); } - protected void executeExternalTask(ExternalTask externalTask, ExternalTaskService externalTaskService) { + public void executeExternalTask(ExternalTask externalTask, ExternalTaskService externalTaskService) { mdcSetup.setupMDC(externalTask); AuditInventory auditInventory = externalTask.getVariable("auditInventory"); Map<String, Object> variables = new HashMap<>(); diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditDataService.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/audit/AuditDataService.java index 1c707fe795..2c76acdb1b 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditDataService.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/audit/AuditDataService.java @@ -1,4 +1,4 @@ -package org.onap.so.adapters.audit; +package org.onap.so.adapters.tasks.audit; import java.io.IOException; import java.util.List; 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/tasks/audit/AuditDeleteStackService.java index cf077915c9..55cde4d174 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/tasks/audit/AuditDeleteStackService.java @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.adapters.audit; +package org.onap.so.adapters.tasks.audit; import java.util.HashMap; import java.util.Map; @@ -28,7 +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.logging.tasks.AuditMDCSetup; import org.onap.so.objects.audit.AAIObjectAuditList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -45,9 +45,6 @@ public class AuditDeleteStackService extends AbstractAuditService { protected HeatStackAudit heatStackAudit; @Autowired - private AuditMDCSetup mdcSetup; - - @Autowired protected AuditVServer auditVservers; @Autowired @@ -56,11 +53,15 @@ public class AuditDeleteStackService extends AbstractAuditService { @Autowired protected Environment env; + @Autowired + public AuditMDCSetup mdcSetup; + public AuditDeleteStackService() { super(); } - protected void executeExternalTask(ExternalTask externalTask, ExternalTaskService externalTaskService) { + public void executeExternalTask(ExternalTask externalTask, ExternalTaskService externalTaskService) { + mdcSetup.setupMDC(externalTask); AuditInventory auditInventory = externalTask.getVariable("auditInventory"); Map<String, Object> variables = new HashMap<>(); 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/tasks/audit/AuditQueryStackService.java index 1c69a3e5e7..ebef4425eb 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/tasks/audit/AuditQueryStackService.java @@ -1,4 +1,4 @@ -package org.onap.so.adapters.audit; +package org.onap.so.adapters.tasks.audit; import java.util.HashMap; import java.util.Map; @@ -7,7 +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.logging.tasks.AuditMDCSetup; import org.onap.so.objects.audit.AAIObjectAuditList; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -23,16 +23,16 @@ public class AuditQueryStackService extends AbstractAuditService { protected HeatStackAudit heatStackAudit; @Autowired - private AuditMDCSetup mdcSetup; + protected AuditDataService auditDataService; @Autowired - protected AuditDataService auditDataService; + public AuditMDCSetup mdcSetup; public AuditQueryStackService() { super(); } - protected void executeExternalTask(ExternalTask externalTask, ExternalTaskService externalTaskService) { + public void executeExternalTask(ExternalTask externalTask, ExternalTaskService externalTaskService) { mdcSetup.setupMDC(externalTask); AuditInventory auditInventory = externalTask.getVariable("auditInventory"); boolean success = false; diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditVServer.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/audit/AuditVServer.java index 585e001f1a..63853c34fa 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/AuditVServer.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/audit/AuditVServer.java @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.adapters.audit; +package org.onap.so.adapters.tasks.audit; import java.util.List; import java.util.Optional; diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/HeatStackAudit.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/audit/HeatStackAudit.java index ffa76cf8ee..1554881193 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/audit/HeatStackAudit.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/audit/HeatStackAudit.java @@ -20,7 +20,7 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.adapters.audit; +package org.onap.so.adapters.tasks.audit; import java.net.URI; import java.util.Arrays; diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/CreateAAIInventory.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/inventory/CreateAAIInventory.java index 69e16986da..a3cb99e3af 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/CreateAAIInventory.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/inventory/CreateAAIInventory.java @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.adapters.inventory.create; +package org.onap.so.adapters.tasks.inventory; import java.util.Optional; import java.util.stream.Stream; 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/tasks/inventory/CreateInventoryTask.java index e02258c619..04dcd9ff61 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/tasks/inventory/CreateInventoryTask.java @@ -20,13 +20,13 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.adapters.inventory.create; +package org.onap.so.adapters.tasks.inventory; import org.camunda.bpm.client.task.ExternalTask; import org.camunda.bpm.client.task.ExternalTaskService; import org.onap.logging.ref.slf4j.ONAPLogConstants; import org.onap.so.client.graphinventory.GraphInventoryCommonObjectMapperProvider; -import org.onap.so.externaltasks.logging.AuditMDCSetup; +import org.onap.so.logging.tasks.AuditMDCSetup; import org.onap.so.objects.audit.AAIObjectAuditList; import org.onap.so.utils.ExternalTaskUtils; import org.onap.so.utils.RetrySequenceLevel; @@ -48,13 +48,14 @@ public class CreateInventoryTask extends ExternalTaskUtils { CreateAAIInventory createInventory; @Autowired - private AuditMDCSetup mdcSetup; + public AuditMDCSetup mdcSetup; public CreateInventoryTask() { super(RetrySequenceLevel.SHORT); } - protected void executeExternalTask(ExternalTask externalTask, ExternalTaskService externalTaskService) { + + public void executeExternalTask(ExternalTask externalTask, ExternalTaskService externalTaskService) { mdcSetup.setupMDC(externalTask); boolean success = true; boolean inventoryException = false; diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/InventoryException.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/inventory/InventoryException.java index ed31c1c67e..7df3822961 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/inventory/create/InventoryException.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/inventory/InventoryException.java @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.adapters.inventory.create; +package org.onap.so.adapters.tasks.inventory; public class InventoryException extends Exception { diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/orchestration/PollService.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/orchestration/PollService.java new file mode 100644 index 0000000000..6e181c4696 --- /dev/null +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/orchestration/PollService.java @@ -0,0 +1,191 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Modifications Copyright (c) 2019 Samsung + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.tasks.orchestration; + +import java.io.ByteArrayInputStream; +import java.io.StringReader; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import javax.xml.bind.JAXB; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import org.apache.commons.lang3.mutable.MutableBoolean; +import org.camunda.bpm.client.task.ExternalTask; +import org.camunda.bpm.client.task.ExternalTaskService; +import org.onap.so.adapters.vnfrest.CreateVfModuleRequest; +import org.onap.so.adapters.vnfrest.CreateVolumeGroupRequest; +import org.onap.so.adapters.vnfrest.DeleteVfModuleRequest; +import org.onap.so.adapters.vnfrest.DeleteVolumeGroupRequest; +import org.onap.so.logging.tasks.AuditMDCSetup; +import org.onap.so.openstack.exceptions.MsoException; +import org.onap.so.openstack.utils.MsoHeatUtils; +import org.onap.so.utils.ExternalTaskUtils; +import org.onap.so.utils.RetrySequenceLevel; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; +import com.woorea.openstack.heat.model.Stack; + +@Component +public class PollService extends ExternalTaskUtils { + + private static final Logger logger = LoggerFactory.getLogger(PollService.class); + + @Autowired + private MsoHeatUtils msoHeatUtils; + + @Autowired + private AuditMDCSetup mdcSetup; + + public PollService() { + super(RetrySequenceLevel.SHORT); + } + + public void executeExternalTask(ExternalTask externalTask, ExternalTaskService externalTaskService) { + mdcSetup.setupMDC(externalTask); + logger.trace("Executing External Task Poll Service"); + Map<String, Object> variables = new HashMap<>(); + MutableBoolean success = new MutableBoolean(); + String errorMessage = null; + try { + String xmlRequest = externalTask.getVariable("vnfAdapterTaskRequest"); + if (xmlRequest != null) { + Optional<String> requestType = findRequestType(xmlRequest); + if ("createVolumeGroupRequest".equals(requestType.get())) { + determineCreateVolumeGroupStatus(xmlRequest, externalTask, success); + } else if ("createVfModuleRequest".equals(requestType.get())) { + determineCreateVfModuleStatus(xmlRequest, externalTask, success); + } else if ("deleteVfModuleRequest".equals(requestType.get())) { + logger.debug("Executing External Task Poll Service for Delete Vf Module"); + DeleteVfModuleRequest req = + JAXB.unmarshal(new StringReader(xmlRequest), DeleteVfModuleRequest.class); + pollDeleteResource(req.getCloudSiteId(), req.getTenantId(), externalTask, success); + } else if ("deleteVolumeGroupRequest".equals(requestType.get())) { + logger.debug("Executing External Task Poll Service for Delete Volume Group"); + DeleteVolumeGroupRequest req = + JAXB.unmarshal(new StringReader(xmlRequest), DeleteVolumeGroupRequest.class); + pollDeleteResource(req.getCloudSiteId(), req.getTenantId(), externalTask, success); + } + } + } catch (Exception e) { + logger.error("Error during External Task Poll Service", e); + errorMessage = e.getMessage(); + } + + variables.put("OpenstackPollSuccess", success.booleanValue()); + variables.put("openstackAdapterErrorMessage", errorMessage); + if (success.isTrue()) { + externalTaskService.complete(externalTask, variables); + logger.debug("The External Task Id: {} Successful", externalTask.getId()); + } else { + if (externalTask.getRetries() == null) { + logger.debug("The External Task Id: {} Failed, Setting Retries to Default Start Value: {}", + externalTask.getId(), getRetrySequence().length); + externalTaskService.handleFailure(externalTask, "errorMessage", "errorDetails", + getRetrySequence().length, 10000); + } else if (externalTask.getRetries() != null && externalTask.getRetries() - 1 == 0) { + logger.debug("The External Task Id: {} Failed, All Retries Exhausted", externalTask.getId()); + externalTaskService.complete(externalTask, variables); + } else { + logger.debug("The External Task Id: {} Failed, Decrementing Retries: {} , Retry Delay: {}", + externalTask.getId(), externalTask.getRetries() - 1, + calculateRetryDelay(externalTask.getRetries())); + externalTaskService.handleFailure(externalTask, "errorMessage", "errorDetails", + externalTask.getRetries() - 1, calculateRetryDelay(externalTask.getRetries())); + } + } + } + + private void determineCreateVolumeGroupStatus(String xmlRequest, ExternalTask externalTask, MutableBoolean success) + throws MsoException { + CreateVolumeGroupRequest req = JAXB.unmarshal(new StringReader(xmlRequest), CreateVolumeGroupRequest.class); + boolean pollRollbackStatus = externalTask.getVariable("PollRollbackStatus"); + if (pollRollbackStatus) { + logger.debug("Executing External Task Poll Service for Rollback Create Volume Group"); + pollDeleteResource(req.getCloudSiteId(), req.getTenantId(), externalTask, success); + } else { + pollCreateResource(req.getCloudSiteId(), req.getTenantId(), externalTask, success); + } + } + + private void determineCreateVfModuleStatus(String xmlRequest, ExternalTask externalTask, MutableBoolean success) + throws MsoException { + CreateVfModuleRequest req = JAXB.unmarshal(new StringReader(xmlRequest), CreateVfModuleRequest.class); + boolean pollRollbackStatus = externalTask.getVariable("PollRollbackStatus"); + if (pollRollbackStatus) { + logger.debug("Executing External Task Poll Service for Rollback Create Vf Module"); + pollDeleteResource(req.getCloudSiteId(), req.getTenantId(), externalTask, success); + } else { + logger.debug("Executing External Task Poll Service for Create Vf Module"); + pollCreateResource(req.getCloudSiteId(), req.getTenantId(), externalTask, success); + } + } + + private void pollCreateResource(String cloudSiteId, String tenantId, ExternalTask externalTask, + MutableBoolean success) throws MsoException { + Stack currentStack = createCurrentStack(externalTask.getVariable("stackId")); + Stack stack = + msoHeatUtils.pollStackForStatus(1, currentStack, "CREATE_IN_PROGRESS", cloudSiteId, tenantId, false); + msoHeatUtils.postProcessStackCreate(stack, false, 0, false, cloudSiteId, tenantId, null); + success.setTrue(); + } + + private void pollDeleteResource(String cloudSiteId, String tenantId, ExternalTask externalTask, + MutableBoolean success) throws MsoException { + Stack currentStack = createCurrentStack(externalTask.getVariable("stackId")); + Stack stack = + msoHeatUtils.pollStackForStatus(1, currentStack, "DELETE_IN_PROGRESS", cloudSiteId, tenantId, true); + if (stack != null) { // if stack is null it was not found and no need to do post process + msoHeatUtils.postProcessStackDelete(stack); + } + success.setTrue(); + } + + protected Optional<String> findRequestType(String xmlString) { + try { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + org.w3c.dom.Document doc; + doc = builder.parse(new ByteArrayInputStream(xmlString.getBytes("UTF-8"))); + return Optional.of(doc.getDocumentElement().getNodeName()); + } catch (Exception e) { + logger.error("Error Finding Request Type", e); + return Optional.empty(); + } + } + + private Stack createCurrentStack(String canonicalStackId) { + Stack currentStack = new Stack(); + String stackName = canonicalStackId; + if (canonicalStackId.contains("/")) { + String[] stacks = canonicalStackId.split("/"); + stackName = stacks[0]; + currentStack.setId(stacks[1]); + } + currentStack.setStackName(stackName); + return currentStack; + } + +} diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/orchestration/RollbackService.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/orchestration/RollbackService.java new file mode 100644 index 0000000000..c302293169 --- /dev/null +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/orchestration/RollbackService.java @@ -0,0 +1,92 @@ +package org.onap.so.adapters.tasks.orchestration; + +import java.io.ByteArrayInputStream; +import java.io.StringReader; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import javax.xml.bind.JAXB; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.ws.Holder; +import org.camunda.bpm.client.task.ExternalTask; +import org.camunda.bpm.client.task.ExternalTaskService; +import org.onap.so.adapters.vnf.MsoVnfAdapterImpl; +import org.onap.so.adapters.vnfrest.CreateVfModuleRequest; +import org.onap.so.adapters.vnfrest.CreateVolumeGroupRequest; +import org.onap.so.logging.tasks.AuditMDCSetup; +import org.onap.so.utils.ExternalTaskUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class RollbackService extends ExternalTaskUtils { + + private static final Logger logger = LoggerFactory.getLogger(RollbackService.class); + + @Autowired + private MsoVnfAdapterImpl vnfAdapterImpl; + + @Autowired + private AuditMDCSetup mdcSetup; + + public void executeExternalTask(ExternalTask externalTask, ExternalTaskService externalTaskService) { + mdcSetup.setupMDC(externalTask); + logger.trace("Executing External Task Rollback Service"); + Map<String, Object> variables = new HashMap<>(); + boolean success = false; + boolean pollRollbackStatus = false; + try { + String xmlRequest = externalTask.getVariable("vnfAdapterTaskRequest"); + if (xmlRequest != null) { + Optional<String> requestType = findRequestType(xmlRequest); + if ("createVolumeGroupRequest".equals(requestType.get())) { + logger.debug("Executing External Task Rollback Service for Create Volume Group"); + CreateVolumeGroupRequest req = + JAXB.unmarshal(new StringReader(xmlRequest), CreateVolumeGroupRequest.class); + vnfAdapterImpl.deleteVnf(req.getCloudSiteId(), req.getCloudOwner(), req.getTenantId(), + req.getVolumeGroupName(), req.getMsoRequest(), false); + pollRollbackStatus = true; + success = true; + } else if ("createVfModuleRequest".equals(requestType.get())) { + logger.debug("Executing External Task Rollback Service for Create Vf Module"); + CreateVfModuleRequest req = + JAXB.unmarshal(new StringReader(xmlRequest), CreateVfModuleRequest.class); + vnfAdapterImpl.deleteVfModule(req.getCloudSiteId(), req.getCloudOwner(), req.getTenantId(), + req.getVfModuleName(), req.getVnfId(), req.getVfModuleId(), req.getModelCustomizationUuid(), + req.getMsoRequest(), new Holder<>()); + pollRollbackStatus = true; + success = true; + } + } + } catch (Exception e) { + logger.error("Error during External Task Rollback Service", e); + } + variables.put("OpenstackRollbackSuccess", success); + variables.put("rollbackPerformed", true); + variables.put("PollRollbackStatus", pollRollbackStatus); + if (success) { + externalTaskService.complete(externalTask, variables); + logger.debug("The External Task Id: {} Successful", externalTask.getId()); + } else { + logger.debug("The External Task Id: {} Failed. Not Retrying", externalTask.getId()); + externalTaskService.complete(externalTask, variables); + } + } + + protected Optional<String> findRequestType(String xmlString) { + try { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + org.w3c.dom.Document doc; + doc = builder.parse(new ByteArrayInputStream(xmlString.getBytes("UTF-8"))); + return Optional.of(doc.getDocumentElement().getNodeName()); + } catch (Exception e) { + logger.error("Error Finding Request Type", e); + return Optional.empty(); + } + } + +} diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/orchestration/StackService.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/orchestration/StackService.java new file mode 100644 index 0000000000..34952a056b --- /dev/null +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/tasks/orchestration/StackService.java @@ -0,0 +1,207 @@ +/*- + * ============LICENSE_START======================================================= + * ONAP - SO + * ================================================================================ + * Copyright (C) 2017-2019 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Modifications Copyright (c) 2019 Samsung + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.onap.so.adapters.tasks.orchestration; + +import java.io.ByteArrayInputStream; +import java.io.StringReader; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import javax.xml.bind.JAXB; +import javax.xml.parsers.DocumentBuilder; +import javax.xml.parsers.DocumentBuilderFactory; +import javax.xml.ws.Holder; +import org.apache.commons.lang3.mutable.MutableBoolean; +import org.camunda.bpm.client.task.ExternalTask; +import org.camunda.bpm.client.task.ExternalTaskService; +import org.onap.so.adapters.vnf.MsoVnfAdapterImpl; +import org.onap.so.adapters.vnf.exceptions.VnfException; +import org.onap.so.adapters.vnfrest.CreateVfModuleRequest; +import org.onap.so.adapters.vnfrest.CreateVfModuleResponse; +import org.onap.so.adapters.vnfrest.CreateVolumeGroupRequest; +import org.onap.so.adapters.vnfrest.CreateVolumeGroupResponse; +import org.onap.so.adapters.vnfrest.DeleteVfModuleRequest; +import org.onap.so.adapters.vnfrest.DeleteVfModuleResponse; +import org.onap.so.adapters.vnfrest.DeleteVolumeGroupRequest; +import org.onap.so.adapters.vnfrest.DeleteVolumeGroupResponse; +import org.onap.so.adapters.vnfrest.VfModuleRollback; +import org.onap.so.adapters.vnfrest.VolumeGroupRollback; +import org.onap.so.logging.tasks.AuditMDCSetup; +import org.onap.so.openstack.beans.VnfRollback; +import org.onap.so.utils.ExternalTaskUtils; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.stereotype.Component; + +@Component +public class StackService extends ExternalTaskUtils { + + private static final Logger logger = LoggerFactory.getLogger(StackService.class); + + @Autowired + private MsoVnfAdapterImpl vnfAdapterImpl; + + @Autowired + private AuditMDCSetup mdcSetup; + + public void executeExternalTask(ExternalTask externalTask, ExternalTaskService externalTaskService) { + Map<String, Object> variables = new HashMap<>(); + mdcSetup.setupMDC(externalTask); + String xmlRequest = externalTask.getVariable("vnfAdapterTaskRequest"); + logger.debug("Executing External Task Stack Service. {}", xmlRequest); + MutableBoolean success = new MutableBoolean(); + MutableBoolean backout = new MutableBoolean(); + String response = ""; + Holder<String> canonicalStackId = new Holder<>(); + String errorMessage = ""; + try { + if (xmlRequest != null) { + Holder<Map<String, String>> outputs = new Holder<>(); + Holder<VnfRollback> vnfRollback = new Holder<>(); + Optional<String> requestType = findRequestType(xmlRequest); + if ("createVolumeGroupRequest".equals(requestType.get())) { + logger.debug("Executing External Task Stack Service For Create Volume Group"); + response = createVolumeGroup(xmlRequest, outputs, vnfRollback, canonicalStackId, backout, success); + } else if ("createVfModuleRequest".equals(requestType.get())) { + logger.debug("Executing External Task Stack Service For Create Vf Module"); + response = createVfModule(xmlRequest, outputs, vnfRollback, canonicalStackId, backout, success); + } else if ("deleteVfModuleRequest".equals(requestType.get())) { + logger.debug("Executing External Task Stack Service For Delete Vf Module"); + response = deleteVfModule(xmlRequest, outputs, vnfRollback, canonicalStackId, backout, success); + } else if ("deleteVolumeGroupRequest".equals(requestType.get())) { + logger.debug("Executing External Task Stack Service For Delete Volume Group"); + response = deleteVolumeGroup(xmlRequest, outputs, vnfRollback, canonicalStackId, backout, success); + } + } + } catch (Exception e) { + logger.error("Error during External Task Stack Service", e); + errorMessage = e.getMessage(); + } + variables.put("backout", backout.booleanValue()); + variables.put("WorkflowResponse", response); + variables.put("OpenstackInvokeSuccess", success.booleanValue()); + variables.put("stackId", canonicalStackId.value); + variables.put("openstackAdapterErrorMessage", errorMessage); + variables.put("PollRollbackStatus", false); + variables.put("rollbackPerformed", false); + variables.put("OpenstackRollbackSuccess", false); + variables.put("OpenstackPollSuccess", false); + + if (success.isTrue()) { + externalTaskService.complete(externalTask, variables); + logger.debug("The External Task Id: {} Successful", externalTask.getId()); + } else { + logger.debug("The External Task Id: {} Failed. Not Retrying", externalTask.getId()); + externalTaskService.complete(externalTask, variables); + } + } + + private String createVolumeGroup(String xmlRequest, Holder<Map<String, String>> outputs, + Holder<VnfRollback> vnfRollback, Holder<String> canonicalStackId, MutableBoolean backout, + MutableBoolean success) throws VnfException { + Holder<String> stackId = new Holder<>(); + CreateVolumeGroupRequest req = JAXB.unmarshal(new StringReader(xmlRequest), CreateVolumeGroupRequest.class); + String completeVnfVfModuleType = req.getVnfType() + "::" + req.getVfModuleType(); + vnfAdapterImpl.createVfModule(req.getCloudSiteId(), req.getCloudOwner(), req.getTenantId(), + completeVnfVfModuleType, req.getVnfVersion(), "", req.getVolumeGroupName(), "", "VOLUME", null, null, + req.getModelCustomizationUuid(), req.getVolumeGroupParams(), false, true, req.getEnableBridge(), + req.getMsoRequest(), stackId, outputs, vnfRollback); + success.setTrue(); + backout.setValue(!req.getSuppressBackout()); + VolumeGroupRollback rb = new VolumeGroupRollback(req.getVolumeGroupId(), stackId.value, + vnfRollback.value.getVnfCreated(), req.getTenantId(), req.getCloudOwner(), req.getCloudSiteId(), + req.getMsoRequest(), req.getMessageId()); + canonicalStackId.value = stackId.value; + CreateVolumeGroupResponse createResponse = new CreateVolumeGroupResponse(req.getVolumeGroupId(), stackId.value, + vnfRollback.value.getVnfCreated(), outputs.value, rb, req.getMessageId()); + return createResponse.toXmlString(); + } + + private String createVfModule(String xmlRequest, Holder<Map<String, String>> outputs, + Holder<VnfRollback> vnfRollback, Holder<String> canonicalStackId, MutableBoolean backout, + MutableBoolean success) throws VnfException { + Holder<String> stackId = new Holder<>(); + CreateVfModuleRequest req = JAXB.unmarshal(new StringReader(xmlRequest), CreateVfModuleRequest.class); + String completeVnfVfModuleType = req.getVnfType() + "::" + req.getVfModuleType(); + vnfAdapterImpl.createVfModule(req.getCloudSiteId(), req.getCloudOwner(), req.getTenantId(), + completeVnfVfModuleType, req.getVnfVersion(), req.getVnfId(), req.getVfModuleName(), + req.getVfModuleId(), req.getRequestType(), req.getVolumeGroupStackId(), req.getBaseVfModuleStackId(), + req.getModelCustomizationUuid(), req.getVfModuleParams(), false, false, req.getEnableBridge(), + req.getMsoRequest(), stackId, outputs, vnfRollback); + success.setTrue(); + backout.setValue(req.getBackout()); + canonicalStackId.value = stackId.value; + VfModuleRollback modRollback = + new VfModuleRollback(vnfRollback.value, req.getVfModuleId(), stackId.value, req.getMessageId()); + CreateVfModuleResponse createResponse = new CreateVfModuleResponse(req.getVnfId(), req.getVfModuleId(), + stackId.value, Boolean.TRUE, outputs.value, modRollback, req.getMessageId()); + return createResponse.toXmlString(); + } + + private String deleteVfModule(String xmlRequest, Holder<Map<String, String>> outputs, + Holder<VnfRollback> vnfRollback, Holder<String> canonicalStackId, MutableBoolean backout, + MutableBoolean success) throws VnfException { + backout.setFalse(); + DeleteVfModuleRequest req = JAXB.unmarshal(new StringReader(xmlRequest), DeleteVfModuleRequest.class); + vnfAdapterImpl.deleteVfModule(req.getCloudSiteId(), req.getCloudOwner(), req.getTenantId(), + req.getVfModuleStackId(), req.getVnfId(), req.getVfModuleId(), req.getModelCustomizationUuid(), + req.getMsoRequest(), outputs); + success.setTrue(); + if (outputs != null && outputs.value != null) { + canonicalStackId.value = outputs.value.get("canonicalStackId"); + } else { + canonicalStackId.value = req.getVfModuleStackId(); + } + DeleteVfModuleResponse deleteResponse = new DeleteVfModuleResponse(req.getVnfId(), req.getVfModuleId(), + Boolean.TRUE, req.getMessageId(), outputs.value); + return deleteResponse.toXmlString(); + } + + private String deleteVolumeGroup(String xmlRequest, Holder<Map<String, String>> outputs, + Holder<VnfRollback> vnfRollback, Holder<String> canonicalStackId, MutableBoolean backout, + MutableBoolean success) throws VnfException { + backout.setFalse(); + DeleteVolumeGroupRequest req = JAXB.unmarshal(new StringReader(xmlRequest), DeleteVolumeGroupRequest.class); + + vnfAdapterImpl.deleteVnf(req.getCloudSiteId(), req.getCloudOwner(), req.getTenantId(), + req.getVolumeGroupStackId(), req.getMsoRequest(), false); + success.setTrue(); + canonicalStackId.value = req.getVolumeGroupStackId(); + DeleteVolumeGroupResponse deleteResponse = new DeleteVolumeGroupResponse(true, req.getMessageId()); + return deleteResponse.toXmlString(); + } + + protected Optional<String> findRequestType(String xmlString) { + try { + DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance(); + DocumentBuilder builder = factory.newDocumentBuilder(); + org.w3c.dom.Document doc; + doc = builder.parse(new ByteArrayInputStream(xmlString.getBytes("UTF-8"))); + return Optional.of(doc.getDocumentElement().getNodeName()); + } catch (Exception e) { + logger.error("Error Finding Request Type", e); + return Optional.empty(); + } + } +} diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfAdapterImpl.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/MsoVnfAdapterImpl.java index 32e88d8cad..5951fda16e 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 @@ -33,6 +33,7 @@ import java.util.Optional; import javax.jws.WebService; import javax.xml.ws.Holder; import org.apache.commons.collections.CollectionUtils; +import org.onap.logging.filter.base.ErrorCode; import org.onap.so.adapters.vnf.exceptions.VnfException; import org.onap.so.adapters.vnf.exceptions.VnfNotFound; import org.onap.so.client.aai.AAIResourcesClient; @@ -53,7 +54,6 @@ import org.onap.so.entity.MsoRequest; import org.onap.so.heatbridge.HeatBridgeApi; import org.onap.so.heatbridge.HeatBridgeException; import org.onap.so.heatbridge.HeatBridgeImpl; -import org.onap.logging.filter.base.ErrorCode; import org.onap.so.logger.LoggingAnchor; import org.onap.so.logger.MessageEnum; import org.onap.so.openstack.beans.HeatStatus; @@ -104,8 +104,6 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { private static final String DELETE_VNF = "DeleteVNF"; private static final String QUERY_STACK = "QueryStack"; private static final String CREATE_VFM_MODULE = "CreateVFModule"; - private static final String CREATE_VF_STACK = "Create VF: Stack"; - private static final String STACK = "Stack"; private static final String USER_ERROR = "USER ERROR"; private static final String VERSION_MIN = "VersionMin"; private static final String VERSION_MAX = "VersionMax"; @@ -113,7 +111,7 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { "The vf module was found to already exist, thus no new vf module was created in the cloud via this request"; private static final String VF_CREATED_STATUS_MESSAGE = "The new vf module was successfully created in the cloud"; private static final String VF_NOT_EXIST_STATUS_MESSAGE = - "The vf module was not, thus no vf module was deleted in the cloud via this request"; + "The vf module was not found, thus no vf module was deleted in the cloud via this request"; private static final String VF_DELETED_STATUS_MESSAGE = "The vf module was successfully deleted in the cloud"; @Autowired @@ -323,6 +321,42 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { } /** + * This is the "Delete VNF" web service implementation. It will delete a VNF by name or ID in the specified cloud + * and tenant. + * + * The method has no outputs. + * + * @param cloudSiteId CLLI code of the cloud site in which to delete + * @param cloudOwner cloud owner of the cloud region in which to delete + * @param tenantId Openstack tenant identifier + * @param vnfName VNF Name or Openstack ID + * @param msoRequest Request tracking information for logs + */ + public void deleteVnf(String cloudSiteId, String cloudOwner, String tenantId, String vnfName, MsoRequest msoRequest, + boolean pollStackStatus) throws VnfException { + + logger.debug("Deleting VNF {} in {}", vnfName, cloudSiteId + "/" + tenantId); + + try { + msoHeatUtils.deleteStack(tenantId, cloudOwner, cloudSiteId, vnfName, pollStackStatus, 118); + } catch (MsoException me) { + me.addContext(DELETE_VNF); + // Failed to query the Stack due to an openstack exception. + // Convert to a generic VnfException + String error = + "Delete VNF: " + vnfName + " in " + cloudOwner + "/" + cloudSiteId + "/" + tenantId + ": " + me; + logger.error(LoggingAnchor.NINE, MessageEnum.RA_DELETE_VNF_ERR.toString(), vnfName, cloudOwner, cloudSiteId, + tenantId, OPENSTACK, DELETE_VNF, ErrorCode.DataError.getValue(), "Exception - " + DELETE_VNF, me); + logger.debug(error); + throw new VnfException(me); + } + + // On success, nothing is returned. + return; + } + + + /** * This web service endpoint will rollback a previous Create VNF operation. A rollback object is returned to the * client in a successful creation response. The client can pass that object as-is back to the rollbackVnf operation * to undo the creation. @@ -536,6 +570,7 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { Map<String, Object> inputs, Boolean failIfExists, Boolean backout, Boolean enableBridge, MsoRequest msoRequest, Holder<String> vnfId, Holder<Map<String, String>> outputs, Holder<VnfRollback> rollback) throws VnfException { + boolean pollForCompletion = false; String vfModuleName = vnfName; String vfModuleType = vnfType; String vfVersion = vnfVersion; @@ -1050,11 +1085,13 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { } if (msoHeatUtils != null) { heatStack = msoHeatUtils.createStack(cloudSiteId, cloudOwner, tenantId, vfModuleName, null, - template, goldenInputs, true, heatTemplate.getTimeoutMinutes(), newEnvironmentString, - nestedTemplatesChecked, heatFilesObjects, backout.booleanValue(), failIfExists); - - msoHeatUtils.updateResourceStatus(msoRequest.getRequestId(), - heatStack.isOperationPerformed() ? VF_EXIST_STATUS_MESSAGE : VF_CREATED_STATUS_MESSAGE); + template, goldenInputs, pollForCompletion, heatTemplate.getTimeoutMinutes(), + newEnvironmentString, nestedTemplatesChecked, heatFilesObjects, backout.booleanValue(), + failIfExists); + if (msoRequest.getRequestId() != null) { + msoHeatUtils.updateResourceStatus(msoRequest.getRequestId(), + heatStack.isOperationPerformed() ? VF_CREATED_STATUS_MESSAGE : VF_EXIST_STATUS_MESSAGE); + } } else { throw new MsoHeatNotFoundException(); } @@ -1134,10 +1171,15 @@ public class MsoVnfAdapterImpl implements MsoVnfAdapter { } try { - StackInfo stackInfo = - msoHeatUtils.deleteStack(tenantId, cloudOwner, cloudSiteId, vnfName, true, timeoutMinutes); + StackInfo currentStack = + msoHeatUtils.deleteStack(tenantId, cloudOwner, cloudSiteId, vnfName, false, timeoutMinutes); + if (currentStack != null && outputs != null && outputs.value != null) { + logger.debug("Adding canonical stack id to outputs " + currentStack.getCanonicalName()); + outputs.value.put("canonicalStackId", currentStack.getCanonicalName()); + } msoHeatUtils.updateResourceStatus(msoRequest.getRequestId(), - stackInfo.isOperationPerformed() ? VF_DELETED_STATUS_MESSAGE : VF_NOT_EXIST_STATUS_MESSAGE); + currentStack.isOperationPerformed() ? VF_DELETED_STATUS_MESSAGE : VF_NOT_EXIST_STATUS_MESSAGE); + } catch (MsoException me) { me.addContext(DELETE_VNF); // Failed to query the Stack due to an openstack exception. diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VnfAdapterRest.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VnfAdapterRest.java index 0836f69ba7..5b78d2f066 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VnfAdapterRest.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VnfAdapterRest.java @@ -78,6 +78,7 @@ import io.swagger.annotations.ApiResponses; * can be produced/consumed. Set Accept: and Content-Type: headers appropriately. XML is the default. For testing, call * with cloudSiteId = ___TESTING___ To test exceptions, also set tenantId = ___TESTING___ */ +@Deprecated @Path("/v1/vnfs") @Api(value = "/v1/vnfs", description = "root of vnf adapters restful web service") @Transactional diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VnfAdapterRestV2.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VnfAdapterRestV2.java index 18ed9872a0..63b4c5d0f3 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VnfAdapterRestV2.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VnfAdapterRestV2.java @@ -39,7 +39,6 @@ import javax.ws.rs.core.GenericEntity; import javax.ws.rs.core.MediaType; import javax.ws.rs.core.Response; import javax.xml.ws.Holder; -import org.onap.so.logger.LoggingAnchor; import org.apache.http.HttpStatus; import org.onap.logging.ref.slf4j.ONAPLogConstants; import org.onap.so.adapters.vnf.exceptions.VnfException; @@ -56,6 +55,7 @@ import org.onap.so.adapters.vnfrest.VfModuleExceptionResponse; import org.onap.so.adapters.vnfrest.VfModuleRollback; import org.onap.so.entity.MsoRequest; import org.onap.logging.filter.base.ErrorCode; +import org.onap.so.logger.LoggingAnchor; import org.onap.so.logger.MessageEnum; import org.onap.so.openstack.beans.VnfRollback; import org.onap.so.openstack.beans.VnfStatus; @@ -78,6 +78,7 @@ import io.swagger.annotations.ApiResponses; * * V2 incorporates run-time selection of sub-orchestrator implementation (Heat or Cloudify) based on the target cloud. */ +@Deprecated @Path("/v2/vnfs") @Api(value = "/v2/vnfs", description = "root of vnf adapters restful web service v2") @Component @@ -189,10 +190,7 @@ public class VnfAdapterRestV2 { } String cloudsite = req.getCloudSiteId(); Holder<Map<String, String>> outputs = new Holder<>(); - if (cloudsite != null && !cloudsite.equals(TESTING_KEYWORD)) { - // vnfAdapter.deleteVnf (req.getCloudSiteId(), req.getTenantId(), req.getVfModuleStackId(), - // req.getMsoRequest()); - // Support different Adapter Implementations + if (cloudsite != null) { MsoVnfAdapter adapter = vnfAdapterRestUtils.getVnfAdapterImpl(mode, cloudsite); adapter.deleteVfModule(req.getCloudSiteId(), req.getCloudOwner(), req.getTenantId(), req.getVfModuleStackId(), req.getVnfId(), req.getVfModuleId(), diff --git a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VolumeAdapterRestV2.java b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VolumeAdapterRestV2.java index cfddbba34e..a424fa92fd 100644 --- a/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VolumeAdapterRestV2.java +++ b/adapters/mso-openstack-adapters/src/main/java/org/onap/so/adapters/vnf/VolumeAdapterRestV2.java @@ -174,33 +174,26 @@ public class VolumeAdapterRestV2 { logger.debug("in createVfModuleVolumes - completeVnfVfModuleType={}", completeVnfVfModuleType); String cloudsiteId = req.getCloudSiteId(); - if (cloudsiteId != null && cloudsiteId.equals(TESTING_KEYWORD)) { - String tenant = req.getTenantId(); - if (tenant != null && tenant.equals(TESTING_KEYWORD)) { - throw new VnfException("testing."); - } - stackId.value = "479D3D8B-6360-47BC-AB75-21CC91981484"; - outputs.value = testMap(); - } else { - // Support different Adapter Implementations - MsoVnfAdapter vnfAdapter = vnfAdapterRestUtils.getVnfAdapterImpl(mode, cloudsiteId); - vnfAdapter.createVfModule(req.getCloudSiteId(), // cloudSiteId, - req.getCloudOwner(), // cloudOwner, - req.getTenantId(), // tenantId, - completeVnfVfModuleType, // vnfType, - req.getVnfVersion(), // vnfVersion, - "", // genericVnfId - req.getVolumeGroupName(), // vnfName, - "", // vfModuleId - "VOLUME", // requestType, - null, // volumeGroupHeatStackId, - null, // baseVfHeatStackId, - req.getModelCustomizationUuid(), req.getVolumeGroupParams(), // inputs, - req.getFailIfExists(), // failIfExists, - req.getSuppressBackout(), // backout, - req.getEnableBridge(), req.getMsoRequest(), // msoRequest, - stackId, outputs, vnfRollback); - } + + // Support different Adapter Implementations + MsoVnfAdapter vnfAdapter = vnfAdapterRestUtils.getVnfAdapterImpl(mode, cloudsiteId); + vnfAdapter.createVfModule(req.getCloudSiteId(), // cloudSiteId, + req.getCloudOwner(), // cloudOwner, + req.getTenantId(), // tenantId, + completeVnfVfModuleType, // vnfType, + req.getVnfVersion(), // vnfVersion, + "", // genericVnfId + req.getVolumeGroupName(), // vnfName, + "", // vfModuleId + "VOLUME", // requestType, + null, // volumeGroupHeatStackId, + null, // baseVfHeatStackId, + req.getModelCustomizationUuid(), req.getVolumeGroupParams(), // inputs, + req.getFailIfExists(), // failIfExists, + req.getSuppressBackout(), // backout, + req.getEnableBridge(), req.getMsoRequest(), // msoRequest, + stackId, outputs, vnfRollback); + VolumeGroupRollback rb = new VolumeGroupRollback(req.getVolumeGroupId(), stackId.value, vnfRollback.value.getVnfCreated(), req.getTenantId(), req.getCloudOwner(), req.getCloudSiteId(), diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/cloudregion/CloudRegionRestImplTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/cloudregion/CloudRegionRestImplTest.java index 9c62c286ac..2df56ede10 100644 --- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/cloudregion/CloudRegionRestImplTest.java +++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/cloudregion/CloudRegionRestImplTest.java @@ -23,6 +23,7 @@ import org.onap.so.client.aai.entities.uri.AAIResourceUri; import org.onap.so.client.aai.entities.uri.AAIUriFactory; import org.onap.so.db.catalog.beans.CloudSite; import org.onap.so.db.catalog.client.CatalogDbClient; +import org.onap.so.db.catalog.data.repository.NetworkTechnologyReferenceRepository; @RunWith(MockitoJUnitRunner.class) @@ -38,6 +39,9 @@ public class CloudRegionRestImplTest { @Mock private AAIResourcesClient aaiResClientMock; + @Mock + private NetworkTechnologyReferenceRepository ntRepoMock; + private CloudSite cloudSite = new CloudSite(); private CloudRegion testCloudRegion = new CloudRegion(); @@ -46,30 +50,52 @@ public class CloudRegionRestImplTest { public void setup() { cloudSite.setCloudVersion("1.0"); cloudSite.setRegionId("region1"); + cloudSite.setCloudOwner("bob"); Mockito.doReturn(aaiResClientMock).when(cloudRestImpl).getAaiClient(); testCloudRegion.setCloudOwner("bob"); testCloudRegion.setCloudRegionId("region1"); testCloudRegion.setCloudRegionVersion("1.0"); testCloudRegion.setInMaint(false); testCloudRegion.setOrchestrationDisabled(false); - testCloudRegion.setComplexName("NA"); testCloudRegion.setCloudRegionVersion("1.0"); testCloudRegion.setOwnerDefinedType("cLCP"); testCloudRegion.setCloudType("openstack"); + testCloudRegion.setCloudZone("region1"); } @Test public void mapCloudRegionTest() { - CloudRegion mappedRegion = cloudRestImpl.mapCloudRegion(cloudSite, "bob"); + CloudRegion mappedRegion = cloudRestImpl.mapCloudRegion(cloudSite); assertThat(mappedRegion, sameBeanAs(testCloudRegion)); } + + @Test + public void mapCloudRegionVersionGreaterThan3Test() { + CloudSite cloudSite2 = new CloudSite(); + cloudSite2.setCloudVersion("3.0.1"); + cloudSite2.setRegionId("region1"); + cloudSite2.setCloudOwner("bob"); + + CloudRegion mappedRegion = cloudRestImpl.mapCloudRegion(cloudSite2); + CloudRegion testRegion2 = new CloudRegion(); + testRegion2.setCloudOwner("bob"); + testRegion2.setCloudRegionId("region1"); + testRegion2.setCloudRegionVersion("3.0.1"); + testRegion2.setInMaint(false); + testRegion2.setOrchestrationDisabled(false); + testRegion2.setOwnerDefinedType("cLCP"); + testRegion2.setCloudType("openstack"); + testRegion2.setCloudZone("region"); + assertThat(mappedRegion, sameBeanAs(testRegion2)); + } + @Test public void createCloudRegionTest() { when(catalogDbClientMock.getCloudSite("region1")).thenReturn(null); when(catalogDbClientMock.postCloudSite(cloudSite)).thenReturn(cloudSite); AAIResourceUri uri = AAIUriFactory.createResourceUri(AAIObjectType.CLOUD_REGION, "bob", "region1"); - cloudRestImpl.createCloudRegion(cloudSite, "bob"); + cloudRestImpl.createCloudRegion(cloudSite); ArgumentCaptor<AAIResourceUri> actualURI = ArgumentCaptor.forClass(AAIResourceUri.class); ArgumentCaptor<Optional<Object>> actualCloudRegion = ArgumentCaptor.forClass(Optional.class); verify(catalogDbClientMock, times(1)).getCloudSite("region1"); @@ -82,7 +108,7 @@ public class CloudRegionRestImplTest { @Test public void updateCloudRegionTest() { when(catalogDbClientMock.updateCloudSite(cloudSite)).thenReturn(cloudSite); - cloudRestImpl.updateCloudRegion(cloudSite, "bob"); + cloudRestImpl.updateCloudRegion(cloudSite); verify(catalogDbClientMock, times(1)).updateCloudSite(cloudSite); } diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/audit/AuditDataServiceTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tasks/audit/AuditDataServiceTest.java index d3380a6a33..d5f8f865a8 100644 --- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/audit/AuditDataServiceTest.java +++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tasks/audit/AuditDataServiceTest.java @@ -1,4 +1,4 @@ -package org.onap.so.adapters.audit; +package org.onap.so.adapters.tasks.audit; import static org.junit.Assert.assertEquals; import static org.mockito.ArgumentMatchers.any; @@ -13,6 +13,7 @@ import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.junit.MockitoJUnitRunner; import org.onap.aai.domain.yang.Vserver; +import org.onap.so.adapters.tasks.audit.AuditDataService; import org.onap.so.audit.beans.AuditInventory; import org.onap.so.client.graphinventory.GraphInventoryCommonObjectMapperProvider; import org.onap.so.db.request.beans.RequestProcessingData; 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/tasks/audit/AuditStackServiceDataTest.java index cff4d5f994..a10ab4b7df 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/tasks/audit/AuditStackServiceDataTest.java @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.adapters.audit; +package org.onap.so.adapters.tasks.audit; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; @@ -36,8 +36,12 @@ import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; +import org.onap.so.adapters.tasks.audit.AuditCreateStackService; +import org.onap.so.adapters.tasks.audit.AuditDataService; +import org.onap.so.adapters.tasks.audit.AuditQueryStackService; +import org.onap.so.adapters.tasks.audit.HeatStackAudit; import org.onap.so.audit.beans.AuditInventory; -import org.onap.so.externaltasks.logging.AuditMDCSetup; +import org.onap.so.logging.tasks.AuditMDCSetup; import org.onap.so.objects.audit.AAIObjectAuditList; import org.springframework.core.env.Environment; import com.fasterxml.jackson.core.JsonParseException; diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/audit/AuditVServerTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tasks/audit/AuditVServerTest.java index 8e71ec46b0..af4afd41a1 100644 --- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/audit/AuditVServerTest.java +++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tasks/audit/AuditVServerTest.java @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.adapters.audit; +package org.onap.so.adapters.tasks.audit; import static org.junit.Assert.assertEquals; import static org.mockito.Mockito.doReturn; @@ -41,6 +41,7 @@ import org.onap.aai.domain.yang.LInterfaces; import org.onap.aai.domain.yang.VfModule; import org.onap.aai.domain.yang.VfModules; import org.onap.aai.domain.yang.Vserver; +import org.onap.so.adapters.tasks.audit.AuditVServer; import org.onap.so.client.aai.AAIObjectPlurals; import org.onap.so.client.aai.AAIObjectType; import org.onap.so.client.aai.AAIResourcesClient; diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/audit/HeatStackAuditTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tasks/audit/HeatStackAuditTest.java index c995064ab2..d1d0d96042 100644 --- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/audit/HeatStackAuditTest.java +++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tasks/audit/HeatStackAuditTest.java @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.adapters.audit; +package org.onap.so.adapters.tasks.audit; import static com.shazam.shazamcrest.MatcherAssert.assertThat; import static com.shazam.shazamcrest.matcher.Matchers.sameBeanAs; @@ -43,6 +43,8 @@ import org.mockito.junit.MockitoJUnitRunner; import org.onap.aai.domain.yang.LInterface; import org.onap.aai.domain.yang.LInterfaces; import org.onap.aai.domain.yang.Vserver; +import org.onap.so.adapters.tasks.audit.AuditVServer; +import org.onap.so.adapters.tasks.audit.HeatStackAudit; import org.onap.so.objects.audit.AAIObjectAuditList; import org.onap.so.openstack.utils.MsoHeatUtils; import org.onap.so.openstack.utils.MsoNeutronUtils; diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/inventory/create/CreateAAIInventoryTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tasks/inventory/CreateAAIInventoryTest.java index 8226f4fed8..e822f65072 100644 --- a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/inventory/create/CreateAAIInventoryTest.java +++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tasks/inventory/CreateAAIInventoryTest.java @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.adapters.inventory.create; +package org.onap.so.adapters.tasks.inventory; import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertTrue; @@ -38,6 +38,7 @@ import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; +import org.onap.so.adapters.tasks.inventory.CreateAAIInventory; import org.onap.so.audit.beans.AuditInventory; import org.onap.so.client.aai.AAIObjectType; import org.onap.so.client.aai.AAIResourcesClient; 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/tasks/inventory/CreateInventoryTaskTest.java index c4fa9ee2c5..fc2baefcd5 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/tasks/inventory/CreateInventoryTaskTest.java @@ -7,9 +7,9 @@ * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at - * + * * http://www.apache.org/licenses/LICENSE-2.0 - * + * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. @@ -18,7 +18,7 @@ * ============LICENSE_END========================================================= */ -package org.onap.so.adapters.inventory.create; +package org.onap.so.adapters.tasks.inventory; import static org.mockito.Mockito.doReturn; import static org.mockito.Mockito.times; @@ -30,8 +30,11 @@ import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; +import org.onap.so.adapters.tasks.inventory.CreateAAIInventory; +import org.onap.so.adapters.tasks.inventory.CreateInventoryTask; +import org.onap.so.adapters.tasks.inventory.InventoryException; import org.onap.so.client.graphinventory.GraphInventoryCommonObjectMapperProvider; -import org.onap.so.externaltasks.logging.AuditMDCSetup; +import org.onap.so.logging.tasks.AuditMDCSetup; import org.onap.so.objects.audit.AAIObjectAudit; import org.onap.so.objects.audit.AAIObjectAuditList; import com.fasterxml.jackson.core.JsonProcessingException; @@ -47,12 +50,12 @@ public class CreateInventoryTaskTest { @Mock ExternalTaskService externalTaskService; - @Mock - private AuditMDCSetup mdcSetup; - @InjectMocks CreateInventoryTask inventoryTask; + @Mock + private AuditMDCSetup mdcSetup; + @Before public void setup() { MockitoAnnotations.initMocks(this); diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tasks/orchestration/PollServiceTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tasks/orchestration/PollServiceTest.java new file mode 100644 index 0000000000..b5b0f5a8ef --- /dev/null +++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tasks/orchestration/PollServiceTest.java @@ -0,0 +1,82 @@ +package org.onap.so.adapters.tasks.orchestration; + +import org.camunda.bpm.client.task.ExternalTask; +import org.camunda.bpm.client.task.ExternalTaskService; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import static org.mockito.Mockito.any; +import static org.mockito.Mockito.eq; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.so.adapters.tasks.orchestration.PollService; +import org.onap.so.logging.tasks.AuditMDCSetup; +import org.onap.so.openstack.exceptions.MsoException; +import org.onap.so.openstack.utils.MsoHeatUtils; +import com.woorea.openstack.heat.model.Stack; + +@RunWith(MockitoJUnitRunner.class) +public class PollServiceTest { + + private String RESOURCE_PATH = "src/test/resources/__files/"; + + @Mock + private ExternalTask mockExternalTask; + + @Mock + private ExternalTaskService mockExternalTaskService; + + @Mock + private MsoHeatUtils msoHeatUtils; + + @Mock + private AuditMDCSetup mdcSetup; + + @InjectMocks + private PollService pollService; + + @Test + public void testExecuteExternalTask() throws MsoException, IOException { + String xmlString = + new String(Files.readAllBytes(Paths.get(RESOURCE_PATH + "/vnfAdapterTaskRequestCreate.xml"))); + + Mockito.when(mockExternalTask.getVariable("vnfAdapterTaskRequest")).thenReturn(xmlString); + Mockito.when(mockExternalTask.getVariable("PollRollbackStatus")).thenReturn(false); + Mockito.when(mockExternalTask.getVariable("stackId")).thenReturn("stackId/stack123"); + Mockito.when(msoHeatUtils.pollStackForStatus(eq(1), any(Stack.class), eq("CREATE_IN_PROGRESS"), eq("regionOne"), + eq("0422ffb57ba042c0800a29dc85ca70f8"), eq(false))).thenReturn(new Stack()); + // Mockito.doNothing().when(msoHeatUtils).postProcessStackCreate(Mockito.any(), Mockito.any(), Mockito.any(), + // Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any()); + + pollService.executeExternalTask(mockExternalTask, mockExternalTaskService); + + Mockito.verify(msoHeatUtils).pollStackForStatus(eq(1), any(Stack.class), eq("CREATE_IN_PROGRESS"), + eq("regionOne"), eq("0422ffb57ba042c0800a29dc85ca70f8"), eq(false)); + + } + + @Test + public void testExecuteExternalTask_rollback() throws MsoException, IOException { + String xmlString = + new String(Files.readAllBytes(Paths.get(RESOURCE_PATH + "/vnfAdapterTaskRequestCreate.xml"))); + + Mockito.when(mockExternalTask.getVariable("vnfAdapterTaskRequest")).thenReturn(xmlString); + Mockito.when(mockExternalTask.getVariable("PollRollbackStatus")).thenReturn(true); + Mockito.when(mockExternalTask.getVariable("stackId")).thenReturn("stackId/stack123"); + Mockito.when(msoHeatUtils.pollStackForStatus(eq(1), any(), eq("DELETE_IN_PROGRESS"), eq("regionOne"), + eq("0422ffb57ba042c0800a29dc85ca70f8"), eq(true))).thenReturn(new Stack()); + Mockito.doNothing().when(msoHeatUtils).postProcessStackDelete(Mockito.any()); + + + pollService.executeExternalTask(mockExternalTask, mockExternalTaskService); + + Mockito.verify(msoHeatUtils).pollStackForStatus(eq(1), any(), eq("DELETE_IN_PROGRESS"), eq("regionOne"), + eq("0422ffb57ba042c0800a29dc85ca70f8"), eq(true)); + + } + +} diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tasks/orchestration/RollbackServiceTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tasks/orchestration/RollbackServiceTest.java new file mode 100644 index 0000000000..f7613909ec --- /dev/null +++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tasks/orchestration/RollbackServiceTest.java @@ -0,0 +1,82 @@ +package org.onap.so.adapters.tasks.orchestration; + +import static org.junit.Assert.assertEquals; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import javax.xml.ws.Holder; +import org.camunda.bpm.client.task.ExternalTask; +import org.camunda.bpm.client.task.ExternalTaskService; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.so.adapters.tasks.orchestration.RollbackService; +import org.onap.so.adapters.vnf.MsoVnfAdapterImpl; +import org.onap.so.adapters.vnf.exceptions.VnfException; +import org.onap.so.entity.MsoRequest; +import org.onap.so.logging.tasks.AuditMDCSetup; +import org.onap.so.openstack.beans.VnfRollback; +import org.onap.so.openstack.exceptions.MsoException; +import org.onap.so.openstack.utils.MsoHeatUtils; +import com.woorea.openstack.heat.model.Stack; + +@RunWith(MockitoJUnitRunner.class) +public class RollbackServiceTest { + + private String RESOURCE_PATH = "src/test/resources/__files/"; + + @Mock + private ExternalTask mockExternalTask; + + @Mock + private ExternalTaskService mockExternalTaskService; + + @Mock + private MsoVnfAdapterImpl vnfAdapterImpl; + + @Mock + private MsoHeatUtils msoHeatUtils; + + @Mock + private AuditMDCSetup mdcSetup; + + @InjectMocks + private RollbackService rollbackService; + + + @Test + public void findRequestTypeTest() throws IOException { + String payload = new String(Files.readAllBytes(Paths.get(RESOURCE_PATH + "/vnfAdapterTaskRequestCreate.xml"))); + + Optional<String> actual = rollbackService.findRequestType(payload); + + assertEquals("createVfModuleRequest", actual.get()); + } + + @Test + public void testExecuteExternalTask() throws VnfException, MsoException, IOException { + String payload = new String(Files.readAllBytes(Paths.get(RESOURCE_PATH + "/vnfAdapterTaskRequestCreate.xml"))); + + Stack stack = new Stack(); + stack.setId("heatId"); + Mockito.when(mockExternalTask.getVariable("vnfAdapterTaskRequest")).thenReturn(payload); + Mockito.doNothing().when(vnfAdapterImpl).deleteVfModule(Mockito.any(), Mockito.any(), Mockito.any(), + Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any()); + Mockito.doNothing().when(mockExternalTaskService).complete(Mockito.any(), Mockito.any()); + + rollbackService.executeExternalTask(mockExternalTask, mockExternalTaskService); + + Mockito.verify(vnfAdapterImpl, Mockito.times(1)).deleteVfModule(Mockito.eq("regionOne"), + Mockito.eq("CloudOwner"), Mockito.eq("0422ffb57ba042c0800a29dc85ca70f8"), Mockito.eq("dummy_id"), + Mockito.any(String.class), Mockito.any(String.class), Mockito.any(), Mockito.any(), Mockito.any()); + Mockito.verify(mockExternalTaskService).complete(Mockito.eq(mockExternalTask), Mockito.any()); + + } + +} diff --git a/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tasks/orchestration/StackServiceTest.java b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tasks/orchestration/StackServiceTest.java new file mode 100644 index 0000000000..2f583b30a2 --- /dev/null +++ b/adapters/mso-openstack-adapters/src/test/java/org/onap/so/adapters/tasks/orchestration/StackServiceTest.java @@ -0,0 +1,113 @@ +package org.onap.so.adapters.tasks.orchestration; + +import static org.junit.Assert.assertEquals; +import java.io.IOException; +import java.nio.file.Files; +import java.nio.file.Paths; +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; +import javax.xml.ws.Holder; +import org.camunda.bpm.client.task.ExternalTask; +import org.camunda.bpm.client.task.ExternalTaskService; +import org.junit.Test; +import org.junit.runner.RunWith; +import org.mockito.InjectMocks; +import org.mockito.Mock; +import org.mockito.Mockito; +import org.mockito.junit.MockitoJUnitRunner; +import org.onap.so.adapters.tasks.orchestration.StackService; +import org.onap.so.adapters.vnf.MsoVnfAdapterImpl; +import org.onap.so.entity.MsoRequest; +import org.onap.so.logging.tasks.AuditMDCSetup; +import org.onap.so.openstack.beans.VnfRollback; +import org.onap.so.openstack.exceptions.MsoException; +import org.onap.so.openstack.utils.MsoHeatUtils; +import com.woorea.openstack.heat.model.Stack; +import org.onap.so.adapters.vnf.exceptions.VnfException; + +@RunWith(MockitoJUnitRunner.class) +public class StackServiceTest { + + private String RESOURCE_PATH = "src/test/resources/__files/"; + + @Mock + private ExternalTask mockExternalTask; + + @Mock + private ExternalTaskService mockExternalTaskService; + + @Mock + private MsoVnfAdapterImpl vnfAdapterImpl; + + @Mock + private MsoHeatUtils msoHeatUtils; + + @Mock + private AuditMDCSetup mdcSetup; + + @InjectMocks + private StackService stackService; + + @Test + public void findRequestTypeTest() throws IOException { + String payload = new String(Files.readAllBytes(Paths.get(RESOURCE_PATH + "/vnfAdapterTaskRequestCreate.xml"))); + + Optional<String> actual = stackService.findRequestType(payload); + + assertEquals("createVfModuleRequest", actual.get()); + } + + @Test + public void testExecuteExternalTask() throws VnfException, MsoException, IOException { + String payload = new String(Files.readAllBytes(Paths.get(RESOURCE_PATH + "/vnfAdapterTaskRequestCreate.xml"))); + + Stack stack = new Stack(); + stack.setId("heatId"); + Mockito.when(mockExternalTask.getVariable("vnfAdapterTaskRequest")).thenReturn(payload); + Mockito.doNothing().when(vnfAdapterImpl).createVfModule(Mockito.any(), Mockito.any(), Mockito.any(), + Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), + Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), Mockito.any(), + Mockito.any(), Mockito.any(), Mockito.any()); + Mockito.doNothing().when(mockExternalTaskService).complete(Mockito.any(), Mockito.any()); + + stackService.executeExternalTask(mockExternalTask, mockExternalTaskService); + + Map<String, Object> paramsMap = new HashMap<String, Object>(); + paramsMap.put("vf_module_id", "985a468b-328b-4c2b-ad0e-b8f1e19501c4"); + paramsMap.put("vnf_id", "6640feba-55f6-4946-9694-4d9558c8870a"); + paramsMap.put("vnf_name", "Robot_VNF_For_Volume_Group"); + paramsMap.put("availability_zone_0", "AZ-MN02"); + paramsMap.put("environment_context", "General_Revenue-Bearing"); + paramsMap.put("user_directives", "{}"); + paramsMap.put("workload_context", ""); + paramsMap.put("vf_module_name", "dummy_id"); + paramsMap.put("vf_module_index", "0"); + paramsMap.put("sdnc_directives", + "{ \"attributes\": [ {\"attribute_name\": \"availability_zone_0\", \"attribute_value\": \"AZ-MN02\"}] }"); + + Map<String, Object> variables = new HashMap<>(); + variables.put("backout", true); + variables.put("WorkflowResponse", ""); + variables.put("OpenstackInvokeSuccess", true); + variables.put("stackId", null); + variables.put("openstackAdapterErrorMessage", null); + variables.put("PollRollbackStatus", false); + variables.put("rollbackPerformed", false); + variables.put("OpenstackRollbackSuccess", false); + variables.put("OpenstackPollSuccess", false); + + Mockito.verify(vnfAdapterImpl, Mockito.times(1)).createVfModule(Mockito.eq("regionOne"), + Mockito.eq("CloudOwner"), Mockito.eq("0422ffb57ba042c0800a29dc85ca70f8"), + Mockito.eq( + "Vf zrdm5bpxmc02092017-Service/Vf zrdm5bpxmc02092017-VF 0::VfZrdm5bpxmc02092017Vf..pxmc_base..module-0"), + Mockito.eq("1.0"), Mockito.eq("6640feba-55f6-4946-9694-4d9558c8870a"), Mockito.eq("dummy_id"), + Mockito.eq("985a468b-328b-4c2b-ad0e-b8f1e19501c4"), Mockito.eq(null), Mockito.eq(null), + Mockito.eq(null), Mockito.eq("074c64d0-7e13-4bcc-8bdb-ea922331102d"), Mockito.eq(paramsMap), + Mockito.eq(false), Mockito.eq(false), Mockito.eq(null), Mockito.any(), Mockito.any(), Mockito.any(), + Mockito.any()); + Mockito.verify(mockExternalTaskService).complete(Mockito.eq(mockExternalTask), Mockito.eq(variables)); + + } + +} diff --git a/adapters/mso-openstack-adapters/src/test/resources/__files/vnfAdapterTaskRequestCreate.xml b/adapters/mso-openstack-adapters/src/test/resources/__files/vnfAdapterTaskRequestCreate.xml new file mode 100644 index 0000000000..c7c880ed92 --- /dev/null +++ b/adapters/mso-openstack-adapters/src/test/resources/__files/vnfAdapterTaskRequestCreate.xml @@ -0,0 +1,66 @@ +<?xml version="1.0" encoding="UTF-8" standalone="yes"?> +<createVfModuleRequest> + <messageId>7f4557c8-c3b9-4743-8b88-9539f9ed7bea</messageId> + <notificationUrl>http://mso-bpmn-infra-svc:9200/mso/WorkflowMessage/VNFAResponse/7f4557c8-c3b9-4743-8b88-9539f9ed7bea + </notificationUrl> + <skipAAI>true</skipAAI> + <cloudSiteId>regionOne</cloudSiteId> + <cloudOwner>CloudOwner</cloudOwner> + <tenantId>0422ffb57ba042c0800a29dc85ca70f8</tenantId> + <vnfId>6640feba-55f6-4946-9694-4d9558c8870a</vnfId> + <vnfType>Vf zrdm5bpxmc02092017-Service/Vf zrdm5bpxmc02092017-VF 0</vnfType> + <vnfVersion>1.0</vnfVersion> + <vfModuleId>985a468b-328b-4c2b-ad0e-b8f1e19501c4</vfModuleId> + <vfModuleName>dummy_id</vfModuleName> + <vfModuleType>VfZrdm5bpxmc02092017Vf..pxmc_base..module-0</vfModuleType> + <baseVfModuleId>985a468b-328b-4c2b-ad0e-b8f1e19501c4</baseVfModuleId> + <modelCustomizationUuid>074c64d0-7e13-4bcc-8bdb-ea922331102d</modelCustomizationUuid> + <failIfExists>false</failIfExists> + <backout>true</backout> + <vfModuleParams> + <entry> + <key>vf_module_id</key> + <value xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xs="http://www.w3.org/2001/XMLSchema" xsi:type="xs:string">985a468b-328b-4c2b-ad0e-b8f1e19501c4</value> + </entry> + <entry> + <key>vnf_id</key> + <value xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xs="http://www.w3.org/2001/XMLSchema" xsi:type="xs:string">6640feba-55f6-4946-9694-4d9558c8870a</value> + </entry> + <entry> + <key>vnf_name</key> + <value xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xs="http://www.w3.org/2001/XMLSchema" xsi:type="xs:string">Robot_VNF_For_Volume_Group</value> + </entry> + <entry> + <key>availability_zone_0</key> + <value xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xs="http://www.w3.org/2001/XMLSchema" xsi:type="xs:string">AZ-MN02</value> + </entry> + <entry> + <key>environment_context</key> + <value xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xs="http://www.w3.org/2001/XMLSchema" xsi:type="xs:string">General_Revenue-Bearing</value> + </entry> + <entry> + <key>user_directives</key> + <value xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xs="http://www.w3.org/2001/XMLSchema" xsi:type="xs:string">{}</value> + </entry> + <entry> + <key>workload_context</key> + <value xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xs="http://www.w3.org/2001/XMLSchema" xsi:type="xs:string"/> + </entry> + <entry> + <key>vf_module_name</key> + <value xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xs="http://www.w3.org/2001/XMLSchema" xsi:type="xs:string">dummy_id</value> + </entry> + <entry> + <key>vf_module_index</key> + <value xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xs="http://www.w3.org/2001/XMLSchema" xsi:type="xs:string">0</value> + </entry> + <entry> + <key>sdnc_directives</key> + <value xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:xs="http://www.w3.org/2001/XMLSchema" xsi:type="xs:string">{ "attributes": [ {"attribute_name": "availability_zone_0", "attribute_value": "AZ-MN02"}] }</value> + </entry> + </vfModuleParams> + <msoRequest> + <requestId>049abdd8-0e19-48b8-bd87-b18f8d49048c</requestId> + <serviceInstanceId>7dc4c4eb-b1d7-4aef-94d1-24e925d1210c</serviceInstanceId> + </msoRequest> +</createVfModuleRequest> diff --git a/adapters/mso-openstack-adapters/src/test/resources/schema.sql b/adapters/mso-openstack-adapters/src/test/resources/schema.sql index 6b791e789c..3357fec109 100644 --- a/adapters/mso-openstack-adapters/src/test/resources/schema.sql +++ b/adapters/mso-openstack-adapters/src/test/resources/schema.sql @@ -801,6 +801,7 @@ CREATE TABLE `service` ( `TOSCA_CSAR_ARTIFACT_UUID` varchar(200) DEFAULT NULL, `SERVICE_TYPE` varchar(200) DEFAULT NULL, `SERVICE_ROLE` varchar(200) DEFAULT NULL, + `SERVICE_FUNCTION` varchar(200) DEFAULT NULL, `ENVIRONMENT_CONTEXT` varchar(200) DEFAULT NULL, `WORKLOAD_CONTEXT` varchar(200) DEFAULT NULL, `SERVICE_CATEGORY` varchar(200) DEFAULT NULL, diff --git a/adapters/mso-requests-db-adapter/src/main/resources/db/migration/V8.2__Fix_Invalid_Request_Status.sql b/adapters/mso-requests-db-adapter/src/main/resources/db/migration/V8.2__Fix_Invalid_Request_Status.sql new file mode 100644 index 0000000000..9fee716326 --- /dev/null +++ b/adapters/mso-requests-db-adapter/src/main/resources/db/migration/V8.2__Fix_Invalid_Request_Status.sql @@ -0,0 +1,4 @@ +USE `requestdb`; + +UPDATE infra_active_requests SET request_status='COMPLETE' where request_status = 'COMPLETED'; +UPDATE archived_infra_requests SET request_status='COMPLETE' where request_status = 'COMPLETED';
\ No newline at end of file diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/MessageConverterConfiguration.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/MessageConverterConfiguration.java index 87e8bb4d57..bb2730bd2b 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/MessageConverterConfiguration.java +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/MessageConverterConfiguration.java @@ -28,6 +28,7 @@ import org.onap.so.adapters.vnfmadapter.converters.etsicatalog.sol003.PkgOnboard import org.onap.so.adapters.vnfmadapter.converters.etsicatalog.sol003.VnfPkgInfoConverter; import org.onap.so.adapters.vnfmadapter.converters.sol003.etsicatalog.PkgmSubscriptionRequestConverter; import org.onap.so.adapters.vnfmadapter.oauth.OAuth2AccessTokenAdapter; +import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.autoconfigure.http.HttpMessageConverters; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; @@ -43,10 +44,17 @@ import org.springframework.security.oauth2.common.OAuth2AccessToken; @Configuration public class MessageConverterConfiguration { + private final VnfmAdapterUrlProvider vnfmAdapterUrlProvider; + + @Autowired + public MessageConverterConfiguration(final VnfmAdapterUrlProvider vnfmAdapterUrlProvider) { + this.vnfmAdapterUrlProvider = vnfmAdapterUrlProvider; + } + @Bean public ConversionService conversionService() { final DefaultConversionService service = new DefaultConversionService(); - service.addConverter(new VnfPkgInfoConverter()); + service.addConverter(new VnfPkgInfoConverter(vnfmAdapterUrlProvider)); service.addConverter(new PkgmSubscriptionRequestConverter()); service.addConverter(new PkgChangeNotificationConverter()); service.addConverter(new PkgOnboardingNotificationConverter()); diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/VnfmAdapterUrlProvider.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/VnfmAdapterUrlProvider.java new file mode 100644 index 0000000000..411a57069f --- /dev/null +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/VnfmAdapterUrlProvider.java @@ -0,0 +1,105 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2020 Ericsson. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.so.adapters.vnfmadapter; + +import static org.onap.so.adapters.vnfmadapter.Constants.BASE_URL; +import static org.onap.so.adapters.vnfmadapter.Constants.ETSI_SUBSCRIPTION_NOTIFICATION_BASE_URL; +import static org.onap.so.adapters.vnfmadapter.Constants.OPERATION_NOTIFICATION_ENDPOINT; +import static org.onap.so.adapters.vnfmadapter.Constants.PACKAGE_MANAGEMENT_BASE_URL; +import static org.slf4j.LoggerFactory.getLogger; +import java.net.URI; +import java.security.GeneralSecurityException; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.onap.so.utils.CryptoUtils; +import org.slf4j.Logger; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Value; +import org.springframework.context.annotation.Configuration; + + +/** + * Provides VNFM Adapter endpoint URLs + * + * @author Waqas Ikram (waqas.ikram@est.tech) + * + */ +@Configuration +public class VnfmAdapterUrlProvider { + + private static final Logger logger = getLogger(VnfmAdapterUrlProvider.class); + private static final String COLON = ":"; + private static final int LIMIT = 2; + + private final String vnfmAdapterEndpoint; + private final String msoKeyString; + private final String vnfmAdapterAuth; + + @Autowired + public VnfmAdapterUrlProvider(@Value("${vnfmadapter.endpoint}") final String vnfmAdapterEndpoint, + @Value("${mso.key}") final String msoKeyString, + @Value("${vnfmadapter.auth:BF29BA36F0CFE1C05507781F6B97EFBCA7EFAC9F595954D465FC43F646883EF585C20A58CBB02528A6FAAC}") final String vnfmAdapterAuth) { + this.vnfmAdapterEndpoint = vnfmAdapterEndpoint; + this.msoKeyString = msoKeyString; + this.vnfmAdapterAuth = vnfmAdapterAuth; + } + + public String getEtsiSubscriptionNotificationBaseUrl() { + return vnfmAdapterEndpoint + ETSI_SUBSCRIPTION_NOTIFICATION_BASE_URL; + } + + public URI getSubscriptionUri(final String subscriptionId) { + return URI.create(getSubscriptionUriString(subscriptionId)); + } + + public ImmutablePair<String, String> getDecryptAuth() throws GeneralSecurityException { + final String decryptedAuth = CryptoUtils.decrypt(vnfmAdapterAuth, msoKeyString); + final String[] auth = decryptedAuth.split(COLON, LIMIT); + if (auth.length > 1) { + return ImmutablePair.of(auth[0], auth[1]); + } + logger.error("Unexpected auth value: {}", vnfmAdapterAuth); + return ImmutablePair.nullPair(); + } + + public String getSubscriptionUriString(final String subscriptionId) { + return vnfmAdapterEndpoint + PACKAGE_MANAGEMENT_BASE_URL + "/subscriptions/" + subscriptionId; + } + + public String getVnfLcmOperationOccurrenceNotificationUrl() { + return vnfmAdapterEndpoint + BASE_URL + OPERATION_NOTIFICATION_ENDPOINT; + } + + public String getVnfPackageUrl(final String vnfPkgId) { + return vnfmAdapterEndpoint + PACKAGE_MANAGEMENT_BASE_URL + "/vnf_packages/" + vnfPkgId; + } + + public String getVnfPackageVnfdUrl(final String vnfPkgId) { + return getVnfPackageUrl(vnfPkgId) + "/vnfd"; + } + + public String getVnfPackageContentUrl(final String vnfPkgId) { + return getVnfPackageUrl(vnfPkgId) + "/package_content"; + } + + public String getOauthTokenUrl() { + return vnfmAdapterEndpoint + "/oauth/token"; + } + +} diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/converters/etsicatalog/sol003/VnfPkgInfoConverter.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/converters/etsicatalog/sol003/VnfPkgInfoConverter.java index 160b875374..ee941f6951 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/converters/etsicatalog/sol003/VnfPkgInfoConverter.java +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/converters/etsicatalog/sol003/VnfPkgInfoConverter.java @@ -22,22 +22,22 @@ package org.onap.so.adapters.vnfmadapter.converters.etsicatalog.sol003; import java.util.ArrayList; import java.util.List; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.springframework.core.convert.converter.Converter; -import org.springframework.stereotype.Service; +import org.onap.so.adapters.vnfmadapter.VnfmAdapterUrlProvider; +import org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.Checksum; +import org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.VNFPKGMLinkSerializer; +import org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.VnfPackageArtifactInfo; +import org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.VnfPackageSoftwareImageInfo; import org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.VnfPkgInfo; import org.onap.so.adapters.vnfmadapter.extclients.vnfm.packagemanagement.model.InlineResponse2001; -import org.onap.so.adapters.vnfmadapter.extclients.vnfm.packagemanagement.model.VnfPackagesChecksum; -import org.onap.so.adapters.vnfmadapter.extclients.vnfm.packagemanagement.model.VnfPackagesSoftwareImages; -import org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.VnfPackageSoftwareImageInfo; import org.onap.so.adapters.vnfmadapter.extclients.vnfm.packagemanagement.model.VnfPackagesAdditionalArtifacts; -import org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.VnfPackageArtifactInfo; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.packagemanagement.model.VnfPackagesChecksum; import org.onap.so.adapters.vnfmadapter.extclients.vnfm.packagemanagement.model.VnfPackagesLinks; import org.onap.so.adapters.vnfmadapter.extclients.vnfm.packagemanagement.model.VnfPackagesLinksSelf; -import org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.VNFPKGMLinkSerializer; -import org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.Checksum; -import org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.UriLink; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.packagemanagement.model.VnfPackagesSoftwareImages; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; +import org.springframework.core.convert.converter.Converter; +import org.springframework.stereotype.Service; /** * Converter to convert from an Etsi Catalog Manager {@link VnfPkgInfo} Object to its equivalent SOL003 Object @@ -48,6 +48,11 @@ import org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.UriLink; @Service public class VnfPkgInfoConverter implements Converter<VnfPkgInfo, InlineResponse2001> { private static final Logger logger = LoggerFactory.getLogger(VnfPkgInfoConverter.class); + private final VnfmAdapterUrlProvider vnfmAdapterUrlProvider; + + public VnfPkgInfoConverter(final VnfmAdapterUrlProvider vnfmAdapterUrlProvider) { + this.vnfmAdapterUrlProvider = vnfmAdapterUrlProvider; + } /** * Convert a {@link VnfPkgInfo} Object to an {@link InlineResponse2001} Object @@ -58,7 +63,7 @@ public class VnfPkgInfoConverter implements Converter<VnfPkgInfo, InlineResponse @Override public InlineResponse2001 convert(final VnfPkgInfo vnfPkgInfo) { if (vnfPkgInfo == null) { - logger.info("No VnfPkgInfo Object Provided for Conversion. (Null object received, returning Null)"); + logger.error("No VnfPkgInfo Object Provided for Conversion. (Null object received, returning Null)"); return null; } final InlineResponse2001 response = new InlineResponse2001(); @@ -87,7 +92,7 @@ public class VnfPkgInfoConverter implements Converter<VnfPkgInfo, InlineResponse response.setUserDefinedData((vnfPkgInfo.getUserDefinedData())); if (vnfPkgInfo.getLinks() != null) { - response.setLinks(convertVNFPKGMLinkSerializerToVnfPackagesLinks(vnfPkgInfo.getLinks())); + response.setLinks(getVnfPackagesLinks(vnfPkgInfo.getLinks(), vnfPkgInfo.getId())); } return response; @@ -167,22 +172,27 @@ public class VnfPkgInfoConverter implements Converter<VnfPkgInfo, InlineResponse return vnfPackagesAdditionalArtifacts; } - private VnfPackagesLinks convertVNFPKGMLinkSerializerToVnfPackagesLinks( - final VNFPKGMLinkSerializer vnfpkgmLinkSerializer) { + private VnfPackagesLinks getVnfPackagesLinks(final VNFPKGMLinkSerializer links, final String vnfPkgId) { final VnfPackagesLinks vnfPackagesLinks = new VnfPackagesLinks(); - vnfPackagesLinks.setSelf(convertUriLinkToVnfPackagesLinksSelf(vnfpkgmLinkSerializer.getSelf())); - vnfPackagesLinks.setVnfd(convertUriLinkToVnfPackagesLinksSelf(vnfpkgmLinkSerializer.getVnfd())); - vnfPackagesLinks - .setPackageContent(convertUriLinkToVnfPackagesLinksSelf(vnfpkgmLinkSerializer.getPackageContent())); + + if (links.getSelf() != null) { + vnfPackagesLinks.setSelf(getVnfPackagesLinksSelf(vnfmAdapterUrlProvider.getVnfPackageUrl(vnfPkgId))); + } + + if (links.getVnfd() != null) { + vnfPackagesLinks.setVnfd(getVnfPackagesLinksSelf(vnfmAdapterUrlProvider.getVnfPackageVnfdUrl(vnfPkgId))); + } + + if (links.getPackageContent() != null) { + vnfPackagesLinks.setPackageContent( + getVnfPackagesLinksSelf(vnfmAdapterUrlProvider.getVnfPackageContentUrl(vnfPkgId))); + } + return vnfPackagesLinks; } - private VnfPackagesLinksSelf convertUriLinkToVnfPackagesLinksSelf(final UriLink uriLink) { - final VnfPackagesLinksSelf vnfPackagesLinksSelf = new VnfPackagesLinksSelf(); - if (uriLink != null) { - vnfPackagesLinksSelf.setHref(uriLink.getHref()); - } - return vnfPackagesLinksSelf; + private VnfPackagesLinksSelf getVnfPackagesLinksSelf(final String href) { + return new VnfPackagesLinksSelf().href(href); } } diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/etsicatalog/EtsiCatalogPackageManagementServiceProvider.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/etsicatalog/EtsiCatalogPackageManagementServiceProvider.java new file mode 100644 index 0000000000..95252218c8 --- /dev/null +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/etsicatalog/EtsiCatalogPackageManagementServiceProvider.java @@ -0,0 +1,72 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2020 Ericsson. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.so.adapters.vnfmadapter.extclients.etsicatalog; + +import java.util.Optional; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.packagemanagement.model.InlineResponse2001; + +/** + * @author Waqas Ikram (waqas.ikram@est.tech) + * + */ +public interface EtsiCatalogPackageManagementServiceProvider { + + /** + * GET Package Content, from VNF Package. + * + * @param vnfPkgId The ID of the VNF Package from which the "package_content" will be retrieved. + * @return The Package Content of a VNF Package ("vnfPkgId"). + */ + Optional<byte[]> getVnfPackageContent(final String vnfPkgId); + + /** + * GET VNF packages information from ETSI Catalog. Will return zero or more VNF package representations. + * + * @return An Array of all VNF packages retrieved from the ETSI Catalog. + */ + Optional<InlineResponse2001[]> getVnfPackages(); + + /** + * GET specific VNF package information from ETSI Catalog. + * + * @param vnfPkgId The ID of the VNF Package that you want to query. + * @return The VNF package retrieved from the ETSI Catalog + */ + Optional<InlineResponse2001> getVnfPackage(final String vnfPkgId); + + /** + * GET specific VNF package VNFD from ETSI Catalog. + * + * @param vnfPkgId The ID of the VNF Package that you want to query. + * @return The VNF package retrieved from the ETSI Catalog + */ + Optional<byte[]> getVnfPackageVnfd(final String vnfPkgId); + + /** + * GET Package Artifact, from VNF Package. + * + * @param vnfPkgId The ID of the VNF Package from which the artifact will be retrieved. + * @param artifactPath Sequence of one or more path segments representing the path of the artifact within the VNF + * Package, e.g., foo/bar/run.sh + * @return The Package Artifact of a VNF Package ("vnfPkgId", "artifactPath"). + */ + Optional<byte[]> getVnfPackageArtifact(final String vnfPkgId, final String artifactPath); + +} diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/etsicatalog/EtsiCatalogServiceProvider.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/etsicatalog/EtsiCatalogServiceProvider.java index 0dcc49eeac..61db82f38c 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/etsicatalog/EtsiCatalogServiceProvider.java +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/etsicatalog/EtsiCatalogServiceProvider.java @@ -20,80 +20,13 @@ package org.onap.so.adapters.vnfmadapter.extclients.etsicatalog; -import java.util.Optional; -import org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.NsdmSubscription; -import org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.PkgmSubscription; -import org.onap.so.adapters.vnfmadapter.extclients.vnfm.packagemanagement.model.InlineResponse2001; - /** * Provides methods for invoking REST calls to the ETSI Catalog Manager. * * @author gareth.roper@est.tech */ -public interface EtsiCatalogServiceProvider { - - /** - * GET Package Content, from VNF Package. - * - * @param vnfPkgId The ID of the VNF Package from which the "package_content" will be retrieved. - * @return The Package Content of a VNF Package ("vnfPkgId"). - */ - Optional<byte[]> getVnfPackageContent(final String vnfPkgId); - - /** - * GET VNF packages information from ETSI Catalog. Will return zero or more VNF package representations. - * - * @return An Array of all VNF packages retrieved from the ETSI Catalog. - */ - Optional<InlineResponse2001[]> getVnfPackages(); - - /** - * GET specific VNF package information from ETSI Catalog. - * - * @param vnfPkgId The ID of the VNF Package that you want to query. - * @return The VNF package retrieved from the ETSI Catalog - */ - Optional<InlineResponse2001> getVnfPackage(final String vnfPkgId); - - /** - * GET specific VNF package VNFD from ETSI Catalog. - * - * @param vnfPkgId The ID of the VNF Package that you want to query. - * @return The VNF package retrieved from the ETSI Catalog - */ - Optional<byte[]> getVnfPackageVnfd(final String vnfPkgId); - - /** - * GET Package Artifact, from VNF Package. - * - * @param vnfPkgId The ID of the VNF Package from which the artifact will be retrieved. - * @param artifactPath Sequence of one or more path segments representing the path of the artifact within the VNF - * Package, e.g., foo/bar/run.sh - * @return The Package Artifact of a VNF Package ("vnfPkgId", "artifactPath"). - */ - Optional<byte[]> getVnfPackageArtifact(final String vnfPkgId, final String artifactPath); - - /** - * POST the SubscriptionRequest Object. - * - * @return The ETSI Catalog Manager's PkgmSubscription object. - */ - Optional<PkgmSubscription> postSubscription( - final org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.PkgmSubscriptionRequest etsiCatalogManagerSubscriptionRequest); - - /** - * Get the Subscription from ETSI Catalog. - * - * @param subscriptionId Subscription ID - * @return The Subscription {@link NsdmSubscription} from ETSI Catalog - */ - Optional<NsdmSubscription> getSubscription(final String subscriptionId); +public interface EtsiCatalogServiceProvider + extends EtsiCatalogSubscriptionServiceProvider, EtsiCatalogPackageManagementServiceProvider { - /** - * DELETE the SubscriptionRequest Object. - * - * @return A Boolean representing if the delete was successful or not. - */ - boolean deleteSubscription(final String subscriptionId); } diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/etsicatalog/EtsiCatalogServiceProviderConfiguration.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/etsicatalog/EtsiCatalogServiceProviderConfiguration.java index 6840dd388b..860dfbbe9c 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/etsicatalog/EtsiCatalogServiceProviderConfiguration.java +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/etsicatalog/EtsiCatalogServiceProviderConfiguration.java @@ -20,16 +20,41 @@ package org.onap.so.adapters.vnfmadapter.extclients.etsicatalog; -import static org.onap.so.client.RestTemplateConfig.CONFIGURABLE_REST_TEMPLATE; +import java.io.IOException; +import java.security.KeyManagementException; +import java.security.KeyStoreException; +import java.security.NoSuchAlgorithmException; +import java.security.cert.CertificateException; +import java.util.concurrent.TimeUnit; +import javax.net.ssl.HostnameVerifier; +import javax.net.ssl.SSLContext; +import javax.net.ssl.SSLSession; +import org.apache.http.client.config.RequestConfig; +import org.apache.http.config.Registry; +import org.apache.http.config.RegistryBuilder; +import org.apache.http.conn.socket.ConnectionSocketFactory; +import org.apache.http.conn.socket.PlainConnectionSocketFactory; +import org.apache.http.conn.ssl.SSLConnectionSocketFactory; +import org.apache.http.impl.client.HttpClientBuilder; +import org.apache.http.impl.conn.PoolingHttpClientConnectionManager; +import org.apache.http.ssl.SSLContextBuilder; +import org.onap.logging.filter.spring.SpringClientPayloadFilter; import org.onap.so.adapters.vnfmadapter.extclients.AbstractServiceProviderConfiguration; import org.onap.so.configuration.rest.BasicHttpHeadersProvider; -import org.onap.so.configuration.rest.HttpHeadersProvider; +import org.onap.so.configuration.rest.HttpClientConnectionConfiguration; +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; +import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.beans.factory.annotation.Value; import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; +import org.springframework.core.io.Resource; +import org.springframework.http.client.BufferingClientHttpRequestFactory; +import org.springframework.http.client.HttpComponentsClientHttpRequestFactory; import org.springframework.web.client.RestTemplate; /** @@ -41,16 +66,105 @@ import org.springframework.web.client.RestTemplate; @Configuration public class EtsiCatalogServiceProviderConfiguration extends AbstractServiceProviderConfiguration { - @Bean(name = "etsiCatalogServiceProvider") - public HttpRestServiceProvider httpRestServiceProvider( - @Qualifier(CONFIGURABLE_REST_TEMPLATE) @Autowired final RestTemplate restTemplate) { - return getHttpRestServiceProvider(restTemplate, new BasicHttpHeadersProvider()); + public static final String ETSI_CATALOG_REST_TEMPLATE_BEAN = "etsiCatalogRestTemplate"; + + public static final String ETSI_CATALOG_SERVICE_PROVIDER_BEAN = "etsiCatalogServiceProvider"; + + private final static Logger LOGGER = LoggerFactory.getLogger(EtsiCatalogServiceProviderConfiguration.class); + + private final HttpClientConnectionConfiguration clientConnectionConfiguration; + + @Value("${etsi-catalog-manager.http.client.ssl.trust-store:#{null}}") + private Resource trustStore; + @Value("${etsi-catalog-manager.http.client.ssl.trust-store-password:#{null}}") + private String trustStorePassword; + + @Autowired + public EtsiCatalogServiceProviderConfiguration( + final HttpClientConnectionConfiguration clientConnectionConfiguration) { + this.clientConnectionConfiguration = clientConnectionConfiguration; + } + + @Bean + @Qualifier(ETSI_CATALOG_REST_TEMPLATE_BEAN) + public RestTemplate etsiCatalogRestTemplate() { + final RestTemplate restTemplate = new RestTemplate(); + restTemplate.getInterceptors().add(new SOSpringClientFilter()); + restTemplate.getInterceptors().add((new SpringClientPayloadFilter())); + return restTemplate; } - private HttpRestServiceProvider getHttpRestServiceProvider(final RestTemplate restTemplate, - final HttpHeadersProvider httpHeadersProvider) { + @Bean + @Qualifier(ETSI_CATALOG_SERVICE_PROVIDER_BEAN) + public HttpRestServiceProvider etsiCatalogHttpRestServiceProvider( + @Qualifier(ETSI_CATALOG_REST_TEMPLATE_BEAN) final RestTemplate restTemplate) { setGsonMessageConverter(restTemplate); - return new HttpRestServiceProviderImpl(restTemplate, httpHeadersProvider); + + final HttpClientBuilder httpClientBuilder = getHttpClientBuilder(); + if (trustStore != null) { + try { + LOGGER.debug("Setting up HttpComponentsClientHttpRequestFactory with SSL Context"); + LOGGER.debug("Setting client trust-store: {}", trustStore.getURL()); + LOGGER.debug("Creating SSLConnectionSocketFactory with AllowAllHostsVerifier ... "); + final SSLContext sslContext = new SSLContextBuilder() + .loadTrustMaterial(trustStore.getURL(), trustStorePassword.toCharArray()).build(); + final SSLConnectionSocketFactory sslConnectionSocketFactory = + new SSLConnectionSocketFactory(sslContext, AllowAllHostsVerifier.INSTANCE); + httpClientBuilder.setSSLSocketFactory(sslConnectionSocketFactory); + final Registry<ConnectionSocketFactory> socketFactoryRegistry = RegistryBuilder + .<ConnectionSocketFactory>create().register("http", PlainConnectionSocketFactory.INSTANCE) + .register("https", sslConnectionSocketFactory).build(); + + httpClientBuilder.setConnectionManager(getConnectionManager(socketFactoryRegistry)); + } catch (final KeyManagementException | NoSuchAlgorithmException | KeyStoreException | CertificateException + | IOException exception) { + LOGGER.error("Error reading truststore, TLS connection will fail.", exception); + } + + } else { + LOGGER.debug("Setting connection manager without SSL ConnectionSocketFactory ..."); + httpClientBuilder.setConnectionManager(getConnectionManager()); + } + + final HttpComponentsClientHttpRequestFactory factory = + new HttpComponentsClientHttpRequestFactory(httpClientBuilder.build()); + restTemplate.setRequestFactory(new BufferingClientHttpRequestFactory(factory)); + + return new HttpRestServiceProviderImpl(restTemplate, new BasicHttpHeadersProvider().getHttpHeaders()); + } + + private PoolingHttpClientConnectionManager getConnectionManager( + final Registry<ConnectionSocketFactory> socketFactoryRegistry) { + return new PoolingHttpClientConnectionManager(socketFactoryRegistry, null, null, null, + clientConnectionConfiguration.getTimeToLiveInMins(), TimeUnit.MINUTES); + } + + private PoolingHttpClientConnectionManager getConnectionManager() { + return new PoolingHttpClientConnectionManager(clientConnectionConfiguration.getTimeToLiveInMins(), + TimeUnit.MINUTES); + } + + private HttpClientBuilder getHttpClientBuilder() { + return HttpClientBuilder.create().setMaxConnPerRoute(clientConnectionConfiguration.getMaxConnectionsPerRoute()) + .setMaxConnTotal(clientConnectionConfiguration.getMaxConnections()) + .setDefaultRequestConfig(getRequestConfig()); + } + + private RequestConfig getRequestConfig() { + return RequestConfig.custom().setSocketTimeout(clientConnectionConfiguration.getSocketTimeOutInMiliSeconds()) + .setConnectTimeout(clientConnectionConfiguration.getConnectionTimeOutInMilliSeconds()).build(); + } + + private static final class AllowAllHostsVerifier implements HostnameVerifier { + + private static final AllowAllHostsVerifier INSTANCE = new AllowAllHostsVerifier(); + + @Override + public boolean verify(final String hostname, final SSLSession session) { + LOGGER.debug("Skipping hostname verification ..."); + return true; + } + } } diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/etsicatalog/EtsiCatalogServiceProviderImpl.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/etsicatalog/EtsiCatalogServiceProviderImpl.java index 30d084629c..cae413ce10 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/etsicatalog/EtsiCatalogServiceProviderImpl.java +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/etsicatalog/EtsiCatalogServiceProviderImpl.java @@ -20,6 +20,7 @@ package org.onap.so.adapters.vnfmadapter.extclients.etsicatalog; +import static org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.EtsiCatalogServiceProviderConfiguration.ETSI_CATALOG_SERVICE_PROVIDER_BEAN; import java.util.Optional; import org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.NsdmSubscription; import org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.PkgmSubscription; @@ -53,14 +54,14 @@ import org.springframework.stereotype.Service; public class EtsiCatalogServiceProviderImpl implements EtsiCatalogServiceProvider { private static final Logger logger = LoggerFactory.getLogger(EtsiCatalogServiceProviderImpl.class); - @Qualifier("etsiCatalogServiceProvider") private final HttpRestServiceProvider httpServiceProvider; private final EtsiCatalogUrlProvider etsiCatalogUrlProvider; private final ConversionService conversionService; @Autowired public EtsiCatalogServiceProviderImpl(final EtsiCatalogUrlProvider etsiCatalogUrlProvider, - final HttpRestServiceProvider httpServiceProvider, final ConversionService conversionService) { + @Qualifier(ETSI_CATALOG_SERVICE_PROVIDER_BEAN) final HttpRestServiceProvider httpServiceProvider, + final ConversionService conversionService) { this.etsiCatalogUrlProvider = etsiCatalogUrlProvider; this.httpServiceProvider = httpServiceProvider; this.conversionService = conversionService; @@ -118,8 +119,10 @@ public class EtsiCatalogServiceProviderImpl implements EtsiCatalogServiceProvide if (inlineResponse2001 != null) { responses[index] = inlineResponse2001; } + } else { + logger.error("Unable to find Converter for response class: {}", + vnfPackages[index].getClass()); } - logger.error("Unable to find Converter for response class: {}", vnfPackages[index].getClass()); } return Optional.of(responses); } diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/etsicatalog/EtsiCatalogSubscriptionServiceProvider.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/etsicatalog/EtsiCatalogSubscriptionServiceProvider.java new file mode 100644 index 0000000000..ed04ad7746 --- /dev/null +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/etsicatalog/EtsiCatalogSubscriptionServiceProvider.java @@ -0,0 +1,55 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2020 Ericsson. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.so.adapters.vnfmadapter.extclients.etsicatalog; + +import java.util.Optional; +import org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.NsdmSubscription; +import org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.PkgmSubscription; + +/** + * @author Waqas Ikram (waqas.ikram@est.tech) + * + */ +public interface EtsiCatalogSubscriptionServiceProvider { + + /** + * POST the SubscriptionRequest Object. + * + * @return The ETSI Catalog Manager's PkgmSubscription object. + */ + Optional<PkgmSubscription> postSubscription( + final org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.PkgmSubscriptionRequest etsiCatalogManagerSubscriptionRequest); + + /** + * Get the Subscription from ETSI Catalog. + * + * @param subscriptionId Subscription ID + * @return The Subscription {@link NsdmSubscription} from ETSI Catalog + */ + Optional<NsdmSubscription> getSubscription(final String subscriptionId); + + /** + * DELETE the SubscriptionRequest Object. + * + * @return A Boolean representing if the delete was successful or not. + */ + boolean deleteSubscription(final String subscriptionId); + +} diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/vnfm/VnfmHelper.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/vnfm/VnfmHelper.java index 7c22020287..fabf8839a6 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/vnfm/VnfmHelper.java +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/vnfm/VnfmHelper.java @@ -20,17 +20,13 @@ package org.onap.so.adapters.vnfmadapter.extclients.vnfm; -import static org.onap.so.adapters.vnfmadapter.Constants.BASE_URL; -import static org.onap.so.adapters.vnfmadapter.Constants.OPERATION_NOTIFICATION_ENDPOINT; -import com.google.common.reflect.TypeToken; -import com.google.gson.Gson; -import com.google.gson.JsonElement; -import com.google.gson.JsonObject; import java.security.GeneralSecurityException; import java.util.ArrayList; import java.util.List; import java.util.Map; +import org.apache.commons.lang3.tuple.ImmutablePair; import org.onap.aai.domain.yang.EsrSystemInfo; +import org.onap.so.adapters.vnfmadapter.VnfmAdapterUrlProvider; import org.onap.so.adapters.vnfmadapter.extclients.aai.AaiServiceProvider; import org.onap.so.adapters.vnfmadapter.extclients.vim.model.AccessInfo; import org.onap.so.adapters.vnfmadapter.extclients.vim.model.InterfaceInfo; @@ -47,15 +43,17 @@ import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.SubscriptionsFilte import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.SubscriptionsFilterVnfInstanceSubscriptionFilter; import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.VnfInstancesvnfInstanceIdinstantiateExtVirtualLinks; import org.onap.so.adapters.vnfmadapter.extclients.vnfm.model.VnfInstancesvnfInstanceIdinstantiateVimConnectionInfo; -import org.onap.so.utils.CryptoUtils; import org.onap.vnfmadapter.v1.model.CreateVnfRequest; import org.onap.vnfmadapter.v1.model.ExternalVirtualLink; import org.onap.vnfmadapter.v1.model.Tenant; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; import org.springframework.stereotype.Service; +import com.google.common.reflect.TypeToken; +import com.google.gson.Gson; +import com.google.gson.JsonElement; +import com.google.gson.JsonObject; /** * Provides helper methods for interactions with VNFM. @@ -66,19 +64,13 @@ public class VnfmHelper { private static final Logger logger = LoggerFactory.getLogger(VnfmHelper.class); private static final String SEPARATOR = "_"; private final AaiServiceProvider aaiServiceProvider; - - @Value("${vnfmadapter.endpoint}") - private String vnfmAdapterEndoint; - - @Value("${vnfmadapter.auth:E39823AAB2739CC654C4E92B52C05BC34149342D0A46451B00CA508C8EDC62242CE4E9DA9445D3C01A3F13}") - private String vnfmAdapterAuth; - - @Value("${mso.key}") - private String msoEncryptionKey; + private final VnfmAdapterUrlProvider vnfmAdapterUrlProvider; @Autowired - public VnfmHelper(final AaiServiceProvider aaiServiceProvider) { + public VnfmHelper(final AaiServiceProvider aaiServiceProvider, + final VnfmAdapterUrlProvider vnfmAdapterUrlProvider) { this.aaiServiceProvider = aaiServiceProvider; + this.vnfmAdapterUrlProvider = vnfmAdapterUrlProvider; } /** @@ -99,11 +91,6 @@ public class VnfmHelper { return instantiateVnfRequest; } - private String getFlavourId() { - // TODO read from csar - return "default"; - } - private List<VnfInstancesvnfInstanceIdinstantiateVimConnectionInfo> getVimConnectionInfos(final Tenant tenant) { final List<VnfInstancesvnfInstanceIdinstantiateVimConnectionInfo> connectionInfos = new ArrayList<>(); connectionInfos.add(getVimConnectionInfo(tenant)); @@ -183,7 +170,7 @@ public class VnfmHelper { throws GeneralSecurityException { final LccnSubscriptionRequest lccnSubscriptionRequest = new LccnSubscriptionRequest(); lccnSubscriptionRequest.setAuthentication(getSubscriptionsAuthentication()); - lccnSubscriptionRequest.setCallbackUri(vnfmAdapterEndoint + BASE_URL + OPERATION_NOTIFICATION_ENDPOINT); + lccnSubscriptionRequest.setCallbackUri(vnfmAdapterUrlProvider.getVnfLcmOperationOccurrenceNotificationUrl()); final SubscriptionsFilter filter = new SubscriptionsFilter(); filter.addNotificationTypesItem(NotificationTypesEnum.VNFLCMOPERATIONOCCURRENCENOTIFICATION); final SubscriptionsFilterVnfInstanceSubscriptionFilter vnfInstanceSubscriptionFilter = @@ -197,19 +184,19 @@ public class VnfmHelper { private SubscriptionsAuthentication getSubscriptionsAuthentication() throws GeneralSecurityException { final SubscriptionsAuthentication authentication = new SubscriptionsAuthentication(); - final String[] decrypedAuth = CryptoUtils.decrypt(vnfmAdapterAuth, msoEncryptionKey).split(":"); + final ImmutablePair<String, String> decrypedAuth = vnfmAdapterUrlProvider.getDecryptAuth(); - SubscriptionsAuthenticationParamsOauth2ClientCredentials oauthParams = + final SubscriptionsAuthenticationParamsOauth2ClientCredentials oauthParams = new SubscriptionsAuthenticationParamsOauth2ClientCredentials(); - oauthParams.setTokenEndpoint(vnfmAdapterEndoint + "/oauth/token"); - oauthParams.clientId(decrypedAuth[0]); - oauthParams.setClientPassword(decrypedAuth[1]); + oauthParams.setTokenEndpoint(vnfmAdapterUrlProvider.getOauthTokenUrl()); + oauthParams.clientId(decrypedAuth.getLeft()); + oauthParams.setClientPassword(decrypedAuth.getRight()); authentication.addAuthTypeItem(AuthTypeEnum.OAUTH2_CLIENT_CREDENTIALS); authentication.paramsOauth2ClientCredentials(oauthParams); final SubscriptionsAuthenticationParamsBasic basicAuthParams = new SubscriptionsAuthenticationParamsBasic(); - basicAuthParams.setUserName(decrypedAuth[0]); - basicAuthParams.setPassword(decrypedAuth[1]); + basicAuthParams.setUserName(decrypedAuth.getLeft()); + basicAuthParams.setPassword(decrypedAuth.getRight()); authentication.addAuthTypeItem(AuthTypeEnum.BASIC); authentication.paramsBasic(basicAuthParams); diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/vnfm/VnfmHttpServiceProviderConfiguration.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/vnfm/VnfmHttpServiceProviderConfiguration.java new file mode 100644 index 0000000000..9ed17e4379 --- /dev/null +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/extclients/vnfm/VnfmHttpServiceProviderConfiguration.java @@ -0,0 +1,49 @@ +/*- + * ============LICENSE_START======================================================= + * Copyright (C) 2020 Ericsson. 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. + * + * SPDX-License-Identifier: Apache-2.0 + * ============LICENSE_END========================================================= + */ +package org.onap.so.adapters.vnfmadapter.extclients.vnfm; + +import static org.onap.so.client.RestTemplateConfig.CONFIGURABLE_REST_TEMPLATE; +import org.onap.so.adapters.vnfmadapter.extclients.AbstractServiceProviderConfiguration; +import org.onap.so.configuration.rest.BasicHttpHeadersProvider; +import org.onap.so.rest.service.HttpRestServiceProvider; +import org.onap.so.rest.service.HttpRestServiceProviderImpl; +import org.springframework.beans.factory.annotation.Autowired; +import org.springframework.beans.factory.annotation.Qualifier; +import org.springframework.context.annotation.Bean; +import org.springframework.context.annotation.Configuration; +import org.springframework.web.client.RestTemplate; + +/** + * @author Waqas Ikram (waqas.ikram@est.tech) + * + */ +@Configuration +public class VnfmHttpServiceProviderConfiguration extends AbstractServiceProviderConfiguration { + public static final String VNFM_ADAPTER_HTTP_SERVICE_PROVIDER_BEAN = "vnfmAdapterHttpServiceProvider"; + + @Bean + @Qualifier(VNFM_ADAPTER_HTTP_SERVICE_PROVIDER_BEAN) + public HttpRestServiceProvider vnfmAdapterHttpRestServiceProvider( + @Autowired @Qualifier(CONFIGURABLE_REST_TEMPLATE) RestTemplate restTemplate) { + setGsonMessageConverter(restTemplate); + return new HttpRestServiceProviderImpl(restTemplate, new BasicHttpHeadersProvider().getHttpHeaders()); + } + +} 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 073fc93107..eaaa8d8544 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 @@ -28,7 +28,6 @@ import java.security.KeyStoreException; import java.security.NoSuchAlgorithmException; import java.security.UnrecoverableKeyException; import java.security.cert.CertificateException; -import java.util.ListIterator; import java.util.Map; import java.util.UUID; import java.util.concurrent.ConcurrentHashMap; @@ -40,10 +39,8 @@ 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.AbstractServiceProviderConfiguration; 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; @@ -54,7 +51,6 @@ 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.security.oauth2.client.OAuth2RestTemplate; import org.springframework.security.oauth2.client.token.grant.client.ClientCredentialsResourceDetails; @@ -102,7 +98,7 @@ public class VnfmServiceProviderConfiguration extends AbstractServiceProviderCon if (trustStore != null) { setTrustStore(restTemplate); } - return new HttpRestServiceProviderImpl(restTemplate, new BasicHttpHeadersProvider()); + return new HttpRestServiceProviderImpl(restTemplate, new BasicHttpHeadersProvider().getHttpHeaders()); } private RestTemplate createRestTemplate(final EsrVnfm vnfm) { @@ -155,14 +151,4 @@ public class VnfmServiceProviderConfiguration extends AbstractServiceProviderCon } } - 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/packagemanagement/subscriptionmanagement/AbstractNotificationServiceProvider.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/packagemanagement/subscriptionmanagement/AbstractNotificationServiceProvider.java index 86ca59cffe..d6b7ae7201 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/packagemanagement/subscriptionmanagement/AbstractNotificationServiceProvider.java +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/packagemanagement/subscriptionmanagement/AbstractNotificationServiceProvider.java @@ -19,16 +19,13 @@ */ package org.onap.so.adapters.vnfmadapter.packagemanagement.subscriptionmanagement; -import static org.onap.so.client.RestTemplateConfig.CONFIGURABLE_REST_TEMPLATE; +import static org.onap.so.adapters.vnfmadapter.extclients.vnfm.VnfmHttpServiceProviderConfiguration.VNFM_ADAPTER_HTTP_SERVICE_PROVIDER_BEAN; import java.nio.charset.StandardCharsets; import org.apache.commons.codec.binary.Base64; import org.onap.so.configuration.rest.BasicHttpHeadersProvider; -import org.onap.so.configuration.rest.HttpHeadersProvider; import org.onap.so.rest.service.HttpRestServiceProvider; -import org.onap.so.rest.service.HttpRestServiceProviderImpl; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; -import org.springframework.web.client.RestTemplate; /** * A base class that can be extended by classes for providing notification services. Provides common methods that will @@ -40,12 +37,10 @@ import org.springframework.web.client.RestTemplate; public abstract class AbstractNotificationServiceProvider { @Autowired - @Qualifier(CONFIGURABLE_REST_TEMPLATE) - private RestTemplate restTemplate; + @Qualifier(VNFM_ADAPTER_HTTP_SERVICE_PROVIDER_BEAN) + private HttpRestServiceProvider httpRestServiceProvider; - protected HttpRestServiceProvider getHttpRestServiceProvider(final HttpHeadersProvider httpHeadersProvider) { - final HttpRestServiceProvider httpRestServiceProvider = - new HttpRestServiceProviderImpl(restTemplate, httpHeadersProvider); + protected HttpRestServiceProvider getHttpRestServiceProvider() { return httpRestServiceProvider; } diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/packagemanagement/subscriptionmanagement/BasicAuthNotificationServiceProvider.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/packagemanagement/subscriptionmanagement/BasicAuthNotificationServiceProvider.java index 6f9d94e9de..cf0cdb085a 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/packagemanagement/subscriptionmanagement/BasicAuthNotificationServiceProvider.java +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/packagemanagement/subscriptionmanagement/BasicAuthNotificationServiceProvider.java @@ -47,10 +47,10 @@ public class BasicAuthNotificationServiceProvider extends AbstractNotificationSe final HttpHeadersProvider httpHeadersProvider = getBasicHttpHeadersProviderWithBasicAuth(subscriptionsAuthentication.getParamsBasic().getUserName(), subscriptionsAuthentication.getParamsBasic().getPassword()); - final HttpRestServiceProvider httpRestServiceProvider = getHttpRestServiceProvider(httpHeadersProvider); + final HttpRestServiceProvider httpRestServiceProvider = getHttpRestServiceProvider(); - final ResponseEntity<Void> responseEntity = - httpRestServiceProvider.postHttpRequest(notification, callbackUri, Void.class); + final ResponseEntity<Void> responseEntity = httpRestServiceProvider.postHttpRequest(notification, callbackUri, + httpHeadersProvider.getHttpHeaders(), Void.class); if (responseEntity.getStatusCode().is2xxSuccessful()) { logger.info("Notification sent successfully."); return true; diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/packagemanagement/subscriptionmanagement/OAuthNotificationServiceProvider.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/packagemanagement/subscriptionmanagement/OAuthNotificationServiceProvider.java index 496fb083cf..c065203cd8 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/packagemanagement/subscriptionmanagement/OAuthNotificationServiceProvider.java +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/packagemanagement/subscriptionmanagement/OAuthNotificationServiceProvider.java @@ -48,13 +48,14 @@ public class OAuthNotificationServiceProvider extends AbstractNotificationServic final String token = getAccessToken(subscriptionsAuthentication); if (token == null) { + logger.error("Failed to get access token"); return false; } final HttpHeadersProvider httpHeadersProvider = getHttpHeadersProvider(token); - final HttpRestServiceProvider httpRestServiceProvider = getHttpRestServiceProvider(httpHeadersProvider); - final ResponseEntity<Void> responseEntity = - httpRestServiceProvider.postHttpRequest(notification, callbackUri, Void.class); + final HttpRestServiceProvider httpRestServiceProvider = getHttpRestServiceProvider(); + final ResponseEntity<Void> responseEntity = httpRestServiceProvider.postHttpRequest(notification, callbackUri, + httpHeadersProvider.getHttpHeaders(), Void.class); if (responseEntity.getStatusCode().is2xxSuccessful()) { logger.info("Notification sent successfully."); return true; @@ -83,9 +84,9 @@ public class OAuthNotificationServiceProvider extends AbstractNotificationServic subscriptionsAuthentication.getParamsOauth2ClientCredentials().getClientId(), subscriptionsAuthentication.getParamsOauth2ClientCredentials().getClientPassword()); - final HttpRestServiceProvider httpRestServiceProvider = getHttpRestServiceProvider(httpHeadersProvider); - final ResponseEntity<OAuthTokenResponse> responseEntity = - httpRestServiceProvider.postHttpRequest(null, tokenEndpoint, OAuthTokenResponse.class); + final HttpRestServiceProvider httpRestServiceProvider = getHttpRestServiceProvider(); + final ResponseEntity<OAuthTokenResponse> responseEntity = httpRestServiceProvider.postHttpRequest(null, + tokenEndpoint, httpHeadersProvider.getHttpHeaders(), OAuthTokenResponse.class); if (responseEntity.getStatusCode().is2xxSuccessful()) { if (responseEntity.getBody() != null) { logger.info("Returning Access Token."); diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/packagemanagement/subscriptionmanagement/SubscriptionManager.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/packagemanagement/subscriptionmanagement/SubscriptionManager.java index a23eb6c3e3..a63e14c899 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/packagemanagement/subscriptionmanagement/SubscriptionManager.java +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/packagemanagement/subscriptionmanagement/SubscriptionManager.java @@ -29,7 +29,8 @@ import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; -import org.onap.so.adapters.vnfmadapter.Constants; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.onap.so.adapters.vnfmadapter.VnfmAdapterUrlProvider; import org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.EtsiCatalogServiceProvider; import org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.BasicAuth; import org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.NsdmSubscription; @@ -42,10 +43,8 @@ import org.onap.so.adapters.vnfmadapter.packagemanagement.subscriptionmanagement import org.onap.so.adapters.vnfmadapter.rest.exceptions.ConversionFailedException; import org.onap.so.adapters.vnfmadapter.rest.exceptions.InternalServerErrorException; import org.onap.so.adapters.vnfmadapter.rest.exceptions.SubscriptionNotFoundException; -import org.onap.so.utils.CryptoUtils; import org.slf4j.Logger; import org.springframework.beans.factory.annotation.Autowired; -import org.springframework.beans.factory.annotation.Value; import org.springframework.core.convert.ConversionService; import org.springframework.stereotype.Service; @@ -62,22 +61,16 @@ public class SubscriptionManager { private final PackageManagementCacheServiceProvider packageManagementCacheServiceProvider; private final ConversionService conversionService; private final EtsiCatalogServiceProvider etsiCatalogServiceProvider; - private final String vnfmAdapterEndpoint; - private final String msoKeyString; - private final String vnfmAdapterAuth; + private final VnfmAdapterUrlProvider vnfmAdapterUrlProvider; @Autowired public SubscriptionManager(final PackageManagementCacheServiceProvider packageManagementCacheServiceProvider, final ConversionService conversionService, final EtsiCatalogServiceProvider etsiCatalogServiceProvider, - @Value("${vnfmadapter.endpoint}") final String vnfmAdapterEndpoint, - @Value("${mso.key}") final String msoKeyString, - @Value("${vnfmadapter.auth:BF29BA36F0CFE1C05507781F6B97EFBCA7EFAC9F595954D465FC43F646883EF585C20A58CBB02528A6FAAC}") final String vnfmAdapterAuth) { + final VnfmAdapterUrlProvider vnfmAdapterUrlProvider) { this.packageManagementCacheServiceProvider = packageManagementCacheServiceProvider; this.conversionService = conversionService; this.etsiCatalogServiceProvider = etsiCatalogServiceProvider; - this.vnfmAdapterEndpoint = vnfmAdapterEndpoint; - this.vnfmAdapterAuth = vnfmAdapterAuth; - this.msoKeyString = msoKeyString; + this.vnfmAdapterUrlProvider = vnfmAdapterUrlProvider; } public Optional<InlineResponse201> createSubscription(final PkgmSubscriptionRequest pkgmSubscriptionRequest) @@ -100,7 +93,7 @@ public class SubscriptionManager { final InlineResponse201 response = new InlineResponse201(); response.setId(subscriptionId); response.setFilter(pkgmSubscriptionRequest.getFilter()); - response.setCallbackUri(getSubscriptionUri(subscriptionId).toString()); + response.setCallbackUri(vnfmAdapterUrlProvider.getSubscriptionUriString(subscriptionId)); response.setLinks(new SubscriptionsLinks() .self(new VnfPackagesLinksSelf().href(getSubscriptionUri(subscriptionId).toString()))); @@ -167,8 +160,7 @@ public class SubscriptionManager { } public URI getSubscriptionUri(final String subscriptionId) { - return URI.create( - vnfmAdapterEndpoint + Constants.PACKAGE_MANAGEMENT_BASE_URL + "/subscriptions/" + subscriptionId); + return vnfmAdapterUrlProvider.getSubscriptionUri(subscriptionId); } public Optional<PkgmSubscriptionRequest> getSubscriptionRequest(final String subscriptionId) { @@ -199,25 +191,19 @@ public class SubscriptionManager { if (etsiCatalogManagerSubscriptionRequest != null) { etsiCatalogManagerSubscriptionRequest - .setCallbackUri(vnfmAdapterEndpoint + Constants.ETSI_SUBSCRIPTION_NOTIFICATION_BASE_URL); - - final String[] auth = decryptAuth(); - final String username = auth[0]; - final String password = auth[1]; - - etsiCatalogManagerSubscriptionRequest.setAuthentication( - new org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.SubscriptionAuthentication() - .addAuthTypeItem(BASIC).paramsBasic(new BasicAuth().userName(username).password(password))); + .setCallbackUri(vnfmAdapterUrlProvider.getEtsiSubscriptionNotificationBaseUrl()); + + final ImmutablePair<String, String> immutablePair = vnfmAdapterUrlProvider.getDecryptAuth(); + if (!immutablePair.equals(ImmutablePair.nullPair())) { + etsiCatalogManagerSubscriptionRequest.setAuthentication( + new org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.SubscriptionAuthentication() + .addAuthTypeItem(BASIC).paramsBasic(new BasicAuth().userName(immutablePair.getLeft()) + .password(immutablePair.getRight()))); + } return etsiCatalogManagerSubscriptionRequest; } throw new ConversionFailedException( "Failed to convert Sol003 PkgmSubscriptionRequest to ETSI-Catalog Manager PkgmSubscriptionRequest"); } - private String[] decryptAuth() throws GeneralSecurityException { - final String decryptedAuth = CryptoUtils.decrypt(vnfmAdapterAuth, msoKeyString); - final String[] auth = decryptedAuth.split(":"); - return auth; - } - } diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/Sol003PackageManagementController.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/Sol003PackageManagementController.java index f1d20c65ef..6d067902c5 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/Sol003PackageManagementController.java +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/main/java/org/onap/so/adapters/vnfmadapter/rest/Sol003PackageManagementController.java @@ -170,8 +170,6 @@ public class Sol003PackageManagementController { + " Sol003PackageManagementController from the EtsiCatalogManager using the\n GET \"vnf_packages\" by vnfPkgId: \"" + vnfPkgId + "\" for artifactPath: \"" + artifactPath + "\"\n" + "endpoint."; logger.error(errorMessage); - // return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new - // ProblemDetails().detail(errorMessage)); return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new ProblemDetails().detail(errorMessage)); } diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/test/java/org/onap/so/adapters/vnfmadapter/rest/EtsiSubscriptionNotificationControllerTest.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/test/java/org/onap/so/adapters/vnfmadapter/rest/EtsiSubscriptionNotificationControllerTest.java index 322251e753..29afa8c549 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/test/java/org/onap/so/adapters/vnfmadapter/rest/EtsiSubscriptionNotificationControllerTest.java +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/test/java/org/onap/so/adapters/vnfmadapter/rest/EtsiSubscriptionNotificationControllerTest.java @@ -278,7 +278,7 @@ public class EtsiSubscriptionNotificationControllerTest { mockRestServer.expect(requestTo(CALLBACK_URI)).andExpect(method(HttpMethod.POST)) .andExpect(jsonPath("$.id").value(NOTIFICATION_ID)) .andExpect(jsonPath("$.notificationType").value( - VnfPackageChangeNotification.NotificationTypeEnum.VNFPACKAGECHANGENOTIFICATION.toString())) + VnfPackageChangeNotification.NotificationTypeEnum.VNFPACKAGECHANGENOTIFICATION.getValue())) .andExpect(jsonPath("$.subscriptionId").value(SUBSCRIPTION_ID)) .andExpect(jsonPath("$.timeStamp").value(TIMESTAMP.toString())) .andExpect(jsonPath("$.vnfPkgId").value(VNFPKG_ID.toString())) diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/test/java/org/onap/so/adapters/vnfmadapter/rest/Sol003PackageManagementControllerTest.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/test/java/org/onap/so/adapters/vnfmadapter/rest/Sol003PackageManagementControllerTest.java index c5194cf27e..be8b0c2e0b 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/test/java/org/onap/so/adapters/vnfmadapter/rest/Sol003PackageManagementControllerTest.java +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/test/java/org/onap/so/adapters/vnfmadapter/rest/Sol003PackageManagementControllerTest.java @@ -25,7 +25,7 @@ import static org.junit.Assert.assertEquals; import static org.junit.Assert.assertNotNull; import static org.junit.Assert.assertTrue; import static org.onap.so.adapters.vnfmadapter.Constants.PACKAGE_MANAGEMENT_BASE_URL; -import static org.onap.so.client.RestTemplateConfig.CONFIGURABLE_REST_TEMPLATE; +import static org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.EtsiCatalogServiceProviderConfiguration.ETSI_CATALOG_REST_TEMPLATE_BEAN; import static org.springframework.test.web.client.match.MockRestRequestMatchers.method; import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; import static org.springframework.test.web.client.response.MockRestResponseCreators.withStatus; @@ -45,6 +45,7 @@ import org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.VnfPackageA import org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.VnfPackageSoftwareImageInfo; import org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.model.VnfPkgInfo; import org.onap.so.adapters.vnfmadapter.extclients.vnfm.packagemanagement.model.InlineResponse2001; +import org.onap.so.adapters.vnfmadapter.extclients.vnfm.packagemanagement.model.VnfPackagesLinks; import org.onap.so.configuration.rest.BasicHttpHeadersProvider; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.beans.factory.annotation.Qualifier; @@ -74,11 +75,11 @@ public class Sol003PackageManagementControllerTest { private int port; @Autowired - @Qualifier(CONFIGURABLE_REST_TEMPLATE) - private RestTemplate testRestTemplate; + @Qualifier(ETSI_CATALOG_REST_TEMPLATE_BEAN) + private RestTemplate restTemplate; @Autowired - private TestRestTemplate restTemplate; + private TestRestTemplate testRestTemplate; private static final String VNF_PACKAGE_ID = "myVnfPackageId"; private static final String ARTIFACT_PATH = "myArtifactPath"; @@ -94,7 +95,11 @@ public class Sol003PackageManagementControllerTest { private static final String VNFD_VERSION = "vnfdVersion"; private static final String ALGORITHM = "algorithm"; private static final String HASH = "hash"; - private static final String URI_HREF = "uriHref"; + private static final String EXPECTED_BASE_URL = + "https://so-vnfm-adapter.onap:30406/so/vnfm-adapter/v1/vnfpkgm/v1/vnf_packages/"; + private static final String EXPECTED_SELF_HREF = EXPECTED_BASE_URL + VNF_PACKAGE_ID; + private static final String EXPECTED_VNFD_HREF = EXPECTED_BASE_URL + VNF_PACKAGE_ID + "/vnfd"; + private static final String EXPECTED_PACKAGE_CONTENT_HREF = EXPECTED_BASE_URL + VNF_PACKAGE_ID + "/package_content"; private MockRestServiceServer mockRestServer; private BasicHttpHeadersProvider basicHttpHeadersProvider; @@ -104,8 +109,7 @@ public class Sol003PackageManagementControllerTest { @Before public void setUp() { - final MockRestServiceServer.MockRestServiceServerBuilder builder = - MockRestServiceServer.bindTo(testRestTemplate); + final MockRestServiceServer.MockRestServiceServerBuilder builder = MockRestServiceServer.bindTo(restTemplate); builder.ignoreExpectOrder(true); mockRestServer = builder.build(); basicHttpHeadersProvider = new BasicHttpHeadersProvider(); @@ -123,7 +127,7 @@ public class Sol003PackageManagementControllerTest { + VNF_PACKAGE_ID + "/package_content"; final HttpEntity<?> request = new HttpEntity<>(basicHttpHeadersProvider.getHttpHeaders()); final ResponseEntity<byte[]> responseEntity = - restTemplate.withBasicAuth("test", "test").exchange(testURL, HttpMethod.GET, request, byte[].class); + testRestTemplate.withBasicAuth("test", "test").exchange(testURL, HttpMethod.GET, request, byte[].class); assertEquals(byte[].class, responseEntity.getBody().getClass()); assertArrayEquals(responseEntity.getBody(), responseArray); @@ -164,7 +168,7 @@ public class Sol003PackageManagementControllerTest { final ResponseEntity<ProblemDetails> responseEntity = - restTemplate.exchange(testURL, HttpMethod.GET, request, ProblemDetails.class); + testRestTemplate.exchange(testURL, HttpMethod.GET, request, ProblemDetails.class); assertTrue(responseEntity.getBody() instanceof ProblemDetails); assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, responseEntity.getStatusCode()); @@ -226,7 +230,7 @@ public class Sol003PackageManagementControllerTest { + VNF_PACKAGE_ID + "/artifacts/" + ARTIFACT_PATH; final HttpEntity<?> request = new HttpEntity<>(basicHttpHeadersProvider.getHttpHeaders()); final ResponseEntity<byte[]> responseEntity = - restTemplate.withBasicAuth("test", "test").exchange(testURL, HttpMethod.GET, request, byte[].class); + testRestTemplate.withBasicAuth("test", "test").exchange(testURL, HttpMethod.GET, request, byte[].class); assertEquals(byte[].class, responseEntity.getBody().getClass()); assertArrayEquals(responseEntity.getBody(), responseArray); @@ -267,7 +271,7 @@ public class Sol003PackageManagementControllerTest { final HttpEntity<?> request = new HttpEntity<>(basicHttpHeadersProvider.getHttpHeaders()); final ResponseEntity<ProblemDetails> responseEntity = - restTemplate.exchange(testURL, HttpMethod.GET, request, ProblemDetails.class); + testRestTemplate.exchange(testURL, HttpMethod.GET, request, ProblemDetails.class); assertNotNull(responseEntity.getBody()); assertEquals(HttpStatus.INTERNAL_SERVER_ERROR, responseEntity.getStatusCode()); @@ -331,7 +335,7 @@ public class Sol003PackageManagementControllerTest { final String testURL = localhostUrl + port + VNFPKGM_BASE_URL; final HttpEntity<?> request = new HttpEntity<>(basicHttpHeadersProvider.getHttpHeaders()); - final ResponseEntity<InlineResponse2001[]> responseEntity = restTemplate.withBasicAuth("test", "test") + final ResponseEntity<InlineResponse2001[]> responseEntity = testRestTemplate.withBasicAuth("test", "test") .exchange(testURL, HttpMethod.GET, request, InlineResponse2001[].class); assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); @@ -347,7 +351,11 @@ public class Sol003PackageManagementControllerTest { assertEquals(ARTIFACT_PATH, inlineResponse2001.getAdditionalArtifacts().get(0).getArtifactPath()); assertEquals(ALGORITHM, inlineResponse2001.getAdditionalArtifacts().get(0).getChecksum().getAlgorithm()); assertEquals(HASH, inlineResponse2001.getAdditionalArtifacts().get(0).getChecksum().getHash()); - assertEquals(URI_HREF, inlineResponse2001.getLinks().getSelf().getHref()); + final VnfPackagesLinks links = inlineResponse2001.getLinks(); + assertNotNull(links); + assertEquals(EXPECTED_SELF_HREF, links.getSelf().getHref()); + assertEquals(EXPECTED_VNFD_HREF, links.getVnfd().getHref()); + assertEquals(EXPECTED_PACKAGE_CONTENT_HREF, links.getPackageContent().getHref()); } @Test @@ -412,7 +420,7 @@ public class Sol003PackageManagementControllerTest { final String testURL = localhostUrl + port + VNFPKGM_BASE_URL + "/" + VNF_PACKAGE_ID; final HttpEntity<?> request = new HttpEntity<>(basicHttpHeadersProvider.getHttpHeaders()); - final ResponseEntity<InlineResponse2001> responseEntity = restTemplate.withBasicAuth("test", "test") + final ResponseEntity<InlineResponse2001> responseEntity = testRestTemplate.withBasicAuth("test", "test") .exchange(testURL, HttpMethod.GET, request, InlineResponse2001.class); assertEquals(HttpStatus.OK, responseEntity.getStatusCode()); @@ -427,7 +435,12 @@ public class Sol003PackageManagementControllerTest { assertEquals(ARTIFACT_PATH, inlineResponse2001.getAdditionalArtifacts().get(0).getArtifactPath()); assertEquals(ALGORITHM, inlineResponse2001.getAdditionalArtifacts().get(0).getChecksum().getAlgorithm()); assertEquals(HASH, inlineResponse2001.getAdditionalArtifacts().get(0).getChecksum().getHash()); - assertEquals(URI_HREF, inlineResponse2001.getLinks().getSelf().getHref()); + final VnfPackagesLinks links = inlineResponse2001.getLinks(); + assertNotNull(links); + assertEquals(EXPECTED_SELF_HREF, links.getSelf().getHref()); + assertEquals(EXPECTED_VNFD_HREF, links.getVnfd().getHref()); + assertEquals(EXPECTED_PACKAGE_CONTENT_HREF, links.getPackageContent().getHref()); + } @Test @@ -484,7 +497,8 @@ public class Sol003PackageManagementControllerTest { + VNF_PACKAGE_ID + "\" \n" + "endpoint.", problemDetails.getDetail()); } - // The below test method is here to improve code coverage and provide a foundation for writing future tests + // The below test method is here to improve code coverage and provide a foundation for writing + // future tests @Test public void testGetPackageVnfd_ValidArray_Success() { final byte[] responseArray = buildByteArrayWithRandomData(10); @@ -497,7 +511,7 @@ public class Sol003PackageManagementControllerTest { "http://localhost:" + port + PACKAGE_MANAGEMENT_BASE_URL + "/vnf_packages/" + VNF_PACKAGE_ID + "/vnfd"; final HttpEntity<?> request = new HttpEntity<>(basicHttpHeadersProvider.getHttpHeaders()); final ResponseEntity<byte[]> responseEntity = - restTemplate.withBasicAuth("test", "test").exchange(testURL, HttpMethod.GET, request, byte[].class); + testRestTemplate.withBasicAuth("test", "test").exchange(testURL, HttpMethod.GET, request, byte[].class); assertEquals(byte[].class, responseEntity.getBody().getClass()); assertArrayEquals(responseEntity.getBody(), responseArray); @@ -592,7 +606,7 @@ public class Sol003PackageManagementControllerTest { private ResponseEntity<ProblemDetails> sendHttpRequest(final String url) { final String testURL = localhostUrl + port + VNFPKGM_BASE_URL + "/" + url; final HttpEntity<?> request = new HttpEntity<>(basicHttpHeadersProvider.getHttpHeaders()); - return restTemplate.withBasicAuth("test", "test").exchange(testURL, HttpMethod.GET, request, + return testRestTemplate.withBasicAuth("test", "test").exchange(testURL, HttpMethod.GET, request, ProblemDetails.class); } @@ -648,8 +662,10 @@ public class Sol003PackageManagementControllerTest { } private VNFPKGMLinkSerializer createVNFPKGMLinkSerializerLinks() { - final UriLink uriLink = new UriLink().href(URI_HREF); - final VNFPKGMLinkSerializer vnfpkgmLinkSerializer = new VNFPKGMLinkSerializer().self(uriLink); - return vnfpkgmLinkSerializer; + final String baseUrl = "http://msb-iag:443/api/vnfpkgm/v1/vnf_packages"; + return new VNFPKGMLinkSerializer().self(new UriLink().href(baseUrl + "/myVnfPackageId")) + .vnfd(new UriLink().href(baseUrl + "/myVnfPackageId/vnfd")) + .packageContent(new UriLink().href(baseUrl + "/myVnfPackageId/package_content")); } + } diff --git a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/test/java/org/onap/so/adapters/vnfmadapter/rest/Sol003PackageManagementSubscriptionControllerTest.java b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/test/java/org/onap/so/adapters/vnfmadapter/rest/Sol003PackageManagementSubscriptionControllerTest.java index a2828b1f9f..c269af8e68 100644 --- a/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/test/java/org/onap/so/adapters/vnfmadapter/rest/Sol003PackageManagementSubscriptionControllerTest.java +++ b/adapters/mso-vnfm-adapter/mso-vnfm-etsi-adapter/src/test/java/org/onap/so/adapters/vnfmadapter/rest/Sol003PackageManagementSubscriptionControllerTest.java @@ -28,7 +28,7 @@ import static org.junit.Assert.assertNull; import static org.junit.Assert.assertThat; import static org.junit.Assert.assertTrue; import static org.onap.so.adapters.vnfmadapter.Constants.PACKAGE_MANAGEMENT_BASE_URL; -import static org.onap.so.client.RestTemplateConfig.CONFIGURABLE_REST_TEMPLATE; +import static org.onap.so.adapters.vnfmadapter.extclients.etsicatalog.EtsiCatalogServiceProviderConfiguration.ETSI_CATALOG_REST_TEMPLATE_BEAN; import static org.springframework.test.web.client.match.MockRestRequestMatchers.method; import static org.springframework.test.web.client.match.MockRestRequestMatchers.requestTo; import static org.springframework.test.web.client.response.MockRestResponseCreators.withStatus; @@ -102,7 +102,7 @@ public class Sol003PackageManagementSubscriptionControllerTest { private static final String LOCALHOST_URL = "http://localhost:"; @Autowired - @Qualifier(CONFIGURABLE_REST_TEMPLATE) + @Qualifier(ETSI_CATALOG_REST_TEMPLATE_BEAN) private RestTemplate restTemplate; private MockRestServiceServer mockRestServiceServer; @Autowired diff --git a/adapters/so-appc-orchestrator/src/main/java/org/onap/so/adapters/appc/orchestrator/client/beans/ConfigurationParameters.java b/adapters/so-appc-orchestrator/src/main/java/org/onap/so/adapters/appc/orchestrator/client/beans/ConfigurationParameters.java index b065e9a0c3..e5321067ac 100644 --- a/adapters/so-appc-orchestrator/src/main/java/org/onap/so/adapters/appc/orchestrator/client/beans/ConfigurationParameters.java +++ b/adapters/so-appc-orchestrator/src/main/java/org/onap/so/adapters/appc/orchestrator/client/beans/ConfigurationParameters.java @@ -1,5 +1,10 @@ package org.onap.so.adapters.appc.orchestrator.client.beans; +import java.util.HashMap; +import java.util.Map; +import com.fasterxml.jackson.annotation.JsonAnyGetter; +import com.fasterxml.jackson.annotation.JsonAnySetter; +import com.fasterxml.jackson.annotation.JsonIgnore; import com.fasterxml.jackson.annotation.JsonInclude; import com.fasterxml.jackson.annotation.JsonProperty; @@ -14,6 +19,8 @@ public class ConfigurationParameters { private String nodeList; @JsonProperty("file_parameter_content") private String fileParameterContent; + @JsonIgnore + private Map<String, String> additionalProperties = new HashMap<>(); @JsonProperty("vnf_name") @@ -50,4 +57,18 @@ public class ConfigurationParameters { this.fileParameterContent = fileParameterContent; } + @JsonAnyGetter + public Map<String, String> getAdditionalProperties() { + return this.additionalProperties; + } + + @JsonAnySetter + public void setAdditionalProperty(String name, String value) { + this.additionalProperties.put(name, value); + } + + public void setAdditionalProperties(Map<String, String> map) { + this.additionalProperties = map; + } + } diff --git a/adapters/so-appc-orchestrator/src/main/java/org/onap/so/adapters/appc/orchestrator/service/ApplicationControllerTask.java b/adapters/so-appc-orchestrator/src/main/java/org/onap/so/adapters/appc/orchestrator/service/ApplicationControllerTask.java index db70a6b5cb..2b5e4b2553 100644 --- a/adapters/so-appc-orchestrator/src/main/java/org/onap/so/adapters/appc/orchestrator/service/ApplicationControllerTask.java +++ b/adapters/so-appc-orchestrator/src/main/java/org/onap/so/adapters/appc/orchestrator/service/ApplicationControllerTask.java @@ -6,7 +6,7 @@ import org.onap.so.adapters.appc.orchestrator.client.ApplicationControllerCallba import org.onap.so.adapters.appc.orchestrator.client.ApplicationControllerSupport; import org.onap.so.adapters.appc.orchestrator.client.StatusCategory; import org.onap.so.appc.orchestrator.service.beans.ApplicationControllerTaskRequest; -import org.onap.so.externaltasks.logging.AuditMDCSetup; +import org.onap.so.logging.tasks.AuditMDCSetup; import org.onap.so.utils.ExternalTaskUtils; import org.slf4j.Logger; import org.slf4j.LoggerFactory; diff --git a/adapters/so-appc-orchestrator/src/main/java/org/onap/so/adapters/appc/orchestrator/service/ApplicationControllerTaskImpl.java b/adapters/so-appc-orchestrator/src/main/java/org/onap/so/adapters/appc/orchestrator/service/ApplicationControllerTaskImpl.java index a174ccb05a..99d6b4dc12 100644 --- a/adapters/so-appc-orchestrator/src/main/java/org/onap/so/adapters/appc/orchestrator/service/ApplicationControllerTaskImpl.java +++ b/adapters/so-appc-orchestrator/src/main/java/org/onap/so/adapters/appc/orchestrator/service/ApplicationControllerTaskImpl.java @@ -32,10 +32,10 @@ public class ApplicationControllerTaskImpl { Optional<String> vserverId = Optional.empty(); Parameters parameters = new Parameters(); ConfigurationParameters configParams = new ConfigurationParameters(); + RequestParameters requestParams = new RequestParameters(); switch (request.getAction()) { case HealthCheck: - RequestParameters requestParams = new RequestParameters(); requestParams.setHostIpAddress(request.getApplicationControllerVnf().getVnfHostIpAddress()); parameters.setRequestParameters(requestParams); payload = Optional.of((mapper.getMapper().writeValueAsString(parameters))); @@ -75,6 +75,12 @@ public class ApplicationControllerTaskImpl { payload = Optional.of((mapper.getMapper().writeValueAsString(parameters))); break; case ConfigModify: + requestParams.setHostIpAddress(request.getApplicationControllerVnf().getVnfHostIpAddress()); + configParams.setAdditionalProperties(request.getConfigParams()); + parameters.setRequestParameters(requestParams); + parameters.setConfigurationParameters(configParams); + payload = Optional.of((mapper.getMapper().writeValueAsString(parameters))); + break; case ConfigScaleOut: break; case UpgradePreCheck: @@ -97,6 +103,7 @@ public class ApplicationControllerTaskImpl { vserverId = Optional .of(request.getApplicationControllerVnf().getApplicationControllerVm().getVserverId()); } + break; default: // errorMessage = "Unable to idenify Action request for AppCClient"; break; diff --git a/adapters/so-appc-orchestrator/src/test/java/org/onap/so/adapters/appc/orchestrator/service/ApplicationControllerTaskImplTest.java b/adapters/so-appc-orchestrator/src/test/java/org/onap/so/adapters/appc/orchestrator/service/ApplicationControllerTaskImplTest.java index 640e2dbd6e..973430c37e 100644 --- a/adapters/so-appc-orchestrator/src/test/java/org/onap/so/adapters/appc/orchestrator/service/ApplicationControllerTaskImplTest.java +++ b/adapters/so-appc-orchestrator/src/test/java/org/onap/so/adapters/appc/orchestrator/service/ApplicationControllerTaskImplTest.java @@ -1,5 +1,7 @@ package org.onap.so.adapters.appc.orchestrator.service; +import java.util.HashMap; +import java.util.Map; import java.util.Optional; import org.junit.Before; import org.junit.Test; @@ -50,6 +52,10 @@ public class ApplicationControllerTaskImplTest { request.setNewSoftwareVersion("2.0"); request.setExistingSoftwareVersion("1.0"); request.setOperationsTimeout("30"); + Map<String, String> reqConfigParams = new HashMap<>(); + reqConfigParams.put("name1", "value1"); + reqConfigParams.put("name2", "value2"); + request.setConfigParams(reqConfigParams); ApplicationControllerVnf applicationControllerVnf = new ApplicationControllerVnf(); applicationControllerVnf.setVnfHostIpAddress("100.100"); applicationControllerVnf.setVnfId("testVnfId"); @@ -228,6 +234,33 @@ public class ApplicationControllerTaskImplTest { } @Test + public void testExcute_configModify() throws JsonProcessingException, ApplicationControllerOrchestratorException { + request.setAction(Action.ConfigModify); + + Parameters parameters = new Parameters(); + RequestParameters requestParams = new RequestParameters(); + requestParams.setHostIpAddress(request.getApplicationControllerVnf().getVnfHostIpAddress()); + parameters.setRequestParameters(requestParams); + ConfigurationParameters configParams = new ConfigurationParameters(); + Map<String, String> configParamMap = new HashMap<>(); + configParamMap.put("name1", "value1"); + configParamMap.put("name2", "value2"); + configParams.setAdditionalProperties(configParamMap); + parameters.setConfigurationParameters(configParams); + Optional<String> payload = Optional.of((mapper.getMapper().writeValueAsString(parameters))); + + Mockito.when(applicationControllerClient.vnfCommand(request.getAction(), "testRequestId", + request.getApplicationControllerVnf().getVnfId(), Optional.empty(), payload, "testControllerType", + listener)).thenReturn(new Status()); + + Status status = applicationControllerTaskImpl.execute("testRequestId", request, listener); + + Mockito.verify(applicationControllerClient).vnfCommand(request.getAction(), "testRequestId", + request.getApplicationControllerVnf().getVnfId(), Optional.empty(), payload, "testControllerType", + listener); + } + + @Test public void testListener() throws Exception { request.setAction(Action.QuiesceTraffic); Status status = applicationControllerTaskImpl.execute("testRequestId", request, listener); diff --git a/adapters/so-appc-orchestrator/src/test/java/org/onap/so/adapters/appc/orchestrator/service/ApplicationControllerTaskTest.java b/adapters/so-appc-orchestrator/src/test/java/org/onap/so/adapters/appc/orchestrator/service/ApplicationControllerTaskTest.java index 228ee90107..179bdabc6b 100644 --- a/adapters/so-appc-orchestrator/src/test/java/org/onap/so/adapters/appc/orchestrator/service/ApplicationControllerTaskTest.java +++ b/adapters/so-appc-orchestrator/src/test/java/org/onap/so/adapters/appc/orchestrator/service/ApplicationControllerTaskTest.java @@ -31,9 +31,9 @@ import org.mockito.InjectMocks; import org.mockito.Mock; import org.mockito.Mockito; import org.mockito.MockitoAnnotations; -import org.onap.so.externaltasks.logging.AuditMDCSetup; import org.onap.so.adapters.appc.orchestrator.client.ApplicationControllerCallback; import org.onap.so.appc.orchestrator.service.beans.ApplicationControllerTaskRequest; +import org.onap.so.logging.tasks.AuditMDCSetup; import org.onap.appc.client.lcm.model.Status; public class ApplicationControllerTaskTest extends ApplicationControllerTask { |