From 280f8015d06af1f41a3ef12e8300801c7a5e0d54 Mon Sep 17 00:00:00 2001 From: AviZi Date: Fri, 9 Jun 2017 02:39:56 +0300 Subject: [SDC-29] Amdocs OnBoard 1707 initial commit. Change-Id: Ie4d12a3f574008b792899b368a0902a8b46b5370 Signed-off-by: AviZi --- .../datatypes/heattotosca/AttachedPropertyVal.java | 57 + .../datatypes/heattotosca/AttachedResourceId.java | 12 +- .../heattotosca/PropertyRegexMatcher.java | 83 + .../datatypes/heattotosca/ReferenceType.java | 25 + .../heattotosca/ResourceReferenceType.java | 25 - .../datatypes/heattotosca/TranslationContext.java | 452 ++++ .../heattotosca/to/ResourceFileDataAndIDs.java | 1 + .../datatypes/heattotosca/to/TranslateTo.java | 2 +- .../composition/NodeTemplateInformation.java | 38 + .../composition/UnifiedCompositionData.java | 95 + .../composition/UnifiedCompositionEntity.java | 8 + .../composition/UnifiedCompositionMode.java | 13 + .../composition/UnifiedSubstitutionData.java | 145 ++ .../consolidation/ComputeConsolidationData.java | 52 + .../ComputeTemplateConsolidationData.java | 88 + .../consolidation/ConsolidationData.java | 109 + .../consolidation/EntityConsolidationData.java | 245 ++ .../FileComputeConsolidationData.java | 56 + .../consolidation/FileNestedConsolidationData.java | 55 + .../consolidation/FilePortConsolidationData.java | 54 + .../consolidation/GetAttrFuncData.java | 62 + .../consolidation/NestedConsolidationData.java | 50 + .../NestedTemplateConsolidationData.java | 11 + .../consolidation/PortConsolidationData.java | 48 + .../PortTemplateConsolidationData.java | 30 + .../consolidation/RequirementAssignmentData.java | 60 + .../TypeComputeConsolidationData.java | 59 + .../HeatToToscaTranslatorFactoryImpl.java | 1 + .../heattotosca/HeatToToscaTranslatorImpl.java | 27 +- .../services/heattotosca/ConfigConstants.java | 49 + .../heattotosca/ConsolidationDataUtil.java | 621 +++++ .../heattotosca/ConsolidationEntityType.java | 86 + .../services/heattotosca/ConsolidationService.java | 937 +++++++ .../translator/services/heattotosca/Constants.java | 13 + .../services/heattotosca/FunctionTranslation.java | 38 + .../heattotosca/FunctionTranslationFactory.java | 70 + .../services/heattotosca/HeatToToscaUtil.java | 1297 +++++++++- .../services/heattotosca/NameExtractor.java | 34 + .../services/heattotosca/NameExtractorUtil.java | 77 + .../services/heattotosca/ResourceTranslation.java | 2 + .../heattotosca/ResourceTranslationFactory.java | 103 +- .../services/heattotosca/TranslationContext.java | 172 -- .../services/heattotosca/TranslationService.java | 185 +- .../services/heattotosca/UnifiedComposition.java | 37 + .../heattotosca/UnifiedCompositionManager.java | 80 + .../heattotosca/UnifiedCompositionService.java | 2575 ++++++++++++++++++++ .../heattotosca/UnifiedCompositionUtil.java | 55 + .../IncorrectResourceReferenceErrorBuilder.java | 3 +- .../NotInSyncNumberOfInterfacesErrorBuilder.java | 2 +- ...ReferenceToUnsupportedResourceErrorBuilder.java | 4 +- .../heattotosca/errors/TranslatorErrorCodes.java | 1 + .../globaltypes/AbstractSubstituteGlobalType.java | 167 -- .../globaltypes/CinderVolumeGlobalType.java | 242 -- .../heattotosca/globaltypes/CommonGlobalTypes.java | 500 ---- .../ContrailAbstractSubstituteGlobalType.java | 196 -- .../globaltypes/ContrailComputeGlobalType.java | 128 - .../globaltypes/ContrailNetworkRuleGlobalType.java | 227 -- .../globaltypes/ContrailPortGlobalType.java | 107 - .../ContrailV2NetworkRuleGlobalType.java | 274 --- ...ontrailV2VirtualMachineInterfaceGlobalType.java | 136 -- .../ContrailV2VirtualNetworkGlobalType.java | 239 -- .../ContrailVirtualNetworkGlobalType.java | 134 - .../globaltypes/GlobalTypesGenerator.java | 93 +- .../globaltypes/GlobalTypesServiceTemplates.java | 61 + .../heattotosca/globaltypes/GlobalTypesUtil.java | 69 - .../globaltypes/NeutronNetGlobalType.java | 143 -- .../globaltypes/NeutronPortGlobalType.java | 203 -- .../NeutronSecurityRulesGlobalType.java | 175 -- .../globaltypes/NovaServerGlobalType.java | 307 --- .../helper/ContrailTranslationHelper.java | 134 +- .../ContrailV2VirtualMachineInterfaceHelper.java | 184 ++ .../helper/FunctionTranslationHelper.java | 47 + .../heattotosca/helper/NameExtractorService.java | 33 - .../heattotosca/helper/PropertyRegexMatcher.java | 69 - .../ResourceTranslationNeutronPortHelper.java | 202 ++ .../helper/VolumeTranslationHelper.java | 44 +- .../helper/impl/NameExtractorServiceImpl.java | 76 - .../heattotosca/impl/BaseResourceConnection.java | 174 -- ...ntrailV2VmInterfaceToNetResourceConnection.java | 139 -- .../impl/NovaAndPortResourceConnectionHelper.java | 106 - .../impl/NovaToVolResourceConnection.java | 228 -- .../impl/PortToNetResourceConnection.java | 200 -- .../heattotosca/impl/ResourceTranslationBase.java | 456 ---- ...ourceTranslationCinderVolumeAttachmentImpl.java | 202 -- .../impl/ResourceTranslationCinderVolumeImpl.java | 77 - ...esourceTranslationContrailAttachPolicyImpl.java | 141 -- ...sourceTranslationContrailNetworkPolicyImpl.java | 53 - ...urceTranslationContrailServiceInstanceImpl.java | 663 ----- ...urceTranslationContrailServiceTemplateImpl.java | 100 - ...urceTranslationContrailV2NetworkPolicyImpl.java | 49 - ...rceTranslationContrailV2VirtualNetworkImpl.java | 209 -- ...sourceTranslationContrailV2VmInterfaceImpl.java | 126 - ...ourceTranslationContrailVirtualNetworkImpl.java | 51 - .../impl/ResourceTranslationDefaultImpl.java | 41 - .../impl/ResourceTranslationNestedImpl.java | 781 ------ .../impl/ResourceTranslationNeutronNetImpl.java | 52 - .../impl/ResourceTranslationNeutronPortImpl.java | 233 -- ...esourceTranslationNeutronSecurityGroupImpl.java | 47 - .../impl/ResourceTranslationNeutronSubnetImpl.java | 170 -- .../ResourceTranslationNovaServerGroupsImpl.java | 119 - .../impl/ResourceTranslationNovaServerImpl.java | 419 ---- .../impl/ResourceTranslationResourceGroupImpl.java | 202 -- .../SecurityRulesToPortResourceConnection.java | 203 -- .../FunctionTranslationGetAttrImpl.java | 491 ++++ .../FunctionTranslationGetFileImpl.java | 87 + .../FunctionTranslationGetParamImpl.java | 128 + .../FunctionTranslationGetResourceImpl.java | 52 + .../NameExtractorContrailComputeImpl.java | 49 + .../nameextractor/NameExtractorNovaServerImpl.java | 50 + .../BaseResourceConnection.java | 338 +++ .../ContrailPortToNetResourceConnection.java | 191 ++ ...ontrailV2VlanToInterfaceResourceConnection.java | 172 ++ ...ntrailV2VmInterfaceToNetResourceConnection.java | 166 ++ .../NovaToVolResourceConnection.java | 269 ++ .../PortToNetResourceConnection.java | 159 ++ .../ResourceConnectionUsingCapabilityHelper.java | 210 ++ .../ResourceConnectionUsingRequirementHelper.java | 163 ++ .../ResourceTranslationBase.java | 354 +++ ...ourceTranslationCinderVolumeAttachmentImpl.java | 268 ++ .../ResourceTranslationCinderVolumeImpl.java | 92 + ...esourceTranslationContrailAttachPolicyImpl.java | 194 ++ ...sourceTranslationContrailNetworkPolicyImpl.java | 58 + ...urceTranslationContrailServiceInstanceImpl.java | 863 +++++++ ...urceTranslationContrailServiceTemplateImpl.java | 141 ++ ...urceTranslationContrailV2NetworkPolicyImpl.java | 56 + ...rceTranslationContrailV2VirtualNetworkImpl.java | 240 ++ ...eTranslationContrailV2VlanSubInterfaceImpl.java | 132 + ...sourceTranslationContrailV2VmInterfaceImpl.java | 138 ++ ...ourceTranslationContrailVirtualNetworkImpl.java | 51 + .../ResourceTranslationDefaultImpl.java | 55 + .../ResourceTranslationNestedImpl.java | 236 ++ .../ResourceTranslationNeutronNetImpl.java | 63 + .../ResourceTranslationNeutronPortImpl.java | 296 +++ ...esourceTranslationNeutronSecurityGroupImpl.java | 55 + .../ResourceTranslationNeutronSubnetImpl.java | 203 ++ .../ResourceTranslationNovaServerGroupsImpl.java | 208 ++ .../ResourceTranslationNovaServerImpl.java | 546 +++++ .../ResourceTranslationResourceGroupImpl.java | 253 ++ .../SecurityRulesToPortResourceConnection.java | 182 ++ .../UnifiedCompositionCatalogInstance.java | 28 + .../UnifiedCompositionNestedSingleCompute.java | 38 + .../UnifiedCompositionScalingInstances.java | 48 + .../UnifiedCompositionSingleSubstitution.java | 65 + .../TranslatorHeatToToscaFunctionConverter.java | 410 ---- .../TranslatorHeatToToscaParameterConverter.java | 86 +- .../TranslatorHeatToToscaPropertyConverter.java | 56 +- .../sdc/translator/utils/ResourceWalker.java | 144 ++ 147 files changed, 16277 insertions(+), 9642 deletions(-) create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/AttachedPropertyVal.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/PropertyRegexMatcher.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/ReferenceType.java delete mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/ResourceReferenceType.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/TranslationContext.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/NodeTemplateInformation.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/UnifiedCompositionData.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/UnifiedCompositionEntity.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/UnifiedCompositionMode.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/UnifiedSubstitutionData.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/ComputeConsolidationData.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/ComputeTemplateConsolidationData.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/ConsolidationData.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/EntityConsolidationData.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/FileComputeConsolidationData.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/FileNestedConsolidationData.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/FilePortConsolidationData.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/GetAttrFuncData.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/NestedConsolidationData.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/NestedTemplateConsolidationData.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/PortConsolidationData.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/PortTemplateConsolidationData.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/RequirementAssignmentData.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/TypeComputeConsolidationData.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ConfigConstants.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ConsolidationDataUtil.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ConsolidationEntityType.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ConsolidationService.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/FunctionTranslation.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/FunctionTranslationFactory.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/NameExtractor.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/NameExtractorUtil.java delete mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/TranslationContext.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/UnifiedComposition.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/UnifiedCompositionManager.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/UnifiedCompositionService.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/UnifiedCompositionUtil.java delete mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/AbstractSubstituteGlobalType.java delete mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/CinderVolumeGlobalType.java delete mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/CommonGlobalTypes.java delete mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/ContrailAbstractSubstituteGlobalType.java delete mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/ContrailComputeGlobalType.java delete mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/ContrailNetworkRuleGlobalType.java delete mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/ContrailPortGlobalType.java delete mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/ContrailV2NetworkRuleGlobalType.java delete mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/ContrailV2VirtualMachineInterfaceGlobalType.java delete mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/ContrailV2VirtualNetworkGlobalType.java delete mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/ContrailVirtualNetworkGlobalType.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/GlobalTypesServiceTemplates.java delete mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/GlobalTypesUtil.java delete mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/NeutronNetGlobalType.java delete mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/NeutronPortGlobalType.java delete mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/NeutronSecurityRulesGlobalType.java delete mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/NovaServerGlobalType.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/helper/ContrailV2VirtualMachineInterfaceHelper.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/helper/FunctionTranslationHelper.java delete mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/helper/NameExtractorService.java delete mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/helper/PropertyRegexMatcher.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/helper/ResourceTranslationNeutronPortHelper.java delete mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/BaseResourceConnection.java delete mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ContrailV2VmInterfaceToNetResourceConnection.java delete mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/NovaAndPortResourceConnectionHelper.java delete mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/NovaToVolResourceConnection.java delete mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/PortToNetResourceConnection.java delete mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationBase.java delete mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationCinderVolumeAttachmentImpl.java delete mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationCinderVolumeImpl.java delete mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationContrailAttachPolicyImpl.java delete mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationContrailNetworkPolicyImpl.java delete mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationContrailServiceInstanceImpl.java delete mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationContrailServiceTemplateImpl.java delete mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationContrailV2NetworkPolicyImpl.java delete mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationContrailV2VirtualNetworkImpl.java delete mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationContrailV2VmInterfaceImpl.java delete mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationContrailVirtualNetworkImpl.java delete mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationDefaultImpl.java delete mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationNestedImpl.java delete mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationNeutronNetImpl.java delete mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationNeutronPortImpl.java delete mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationNeutronSecurityGroupImpl.java delete mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationNeutronSubnetImpl.java delete mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationNovaServerGroupsImpl.java delete mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationNovaServerImpl.java delete mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationResourceGroupImpl.java delete mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/SecurityRulesToPortResourceConnection.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetAttrImpl.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetFileImpl.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetParamImpl.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetResourceImpl.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/nameextractor/NameExtractorContrailComputeImpl.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/nameextractor/NameExtractorNovaServerImpl.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/BaseResourceConnection.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ContrailPortToNetResourceConnection.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ContrailV2VlanToInterfaceResourceConnection.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ContrailV2VmInterfaceToNetResourceConnection.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/NovaToVolResourceConnection.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/PortToNetResourceConnection.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceConnectionUsingCapabilityHelper.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceConnectionUsingRequirementHelper.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationBase.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationCinderVolumeAttachmentImpl.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationCinderVolumeImpl.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailAttachPolicyImpl.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailNetworkPolicyImpl.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailServiceInstanceImpl.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailServiceTemplateImpl.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailV2NetworkPolicyImpl.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailV2VirtualNetworkImpl.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailV2VlanSubInterfaceImpl.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailV2VmInterfaceImpl.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailVirtualNetworkImpl.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationDefaultImpl.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNestedImpl.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNeutronNetImpl.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNeutronPortImpl.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNeutronSecurityGroupImpl.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNeutronSubnetImpl.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNovaServerGroupsImpl.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNovaServerImpl.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationResourceGroupImpl.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/SecurityRulesToPortResourceConnection.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/unifiedcomposition/UnifiedCompositionCatalogInstance.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/unifiedcomposition/UnifiedCompositionNestedSingleCompute.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/unifiedcomposition/UnifiedCompositionScalingInstances.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/unifiedcomposition/UnifiedCompositionSingleSubstitution.java delete mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/mapping/TranslatorHeatToToscaFunctionConverter.java create mode 100644 openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/utils/ResourceWalker.java (limited to 'openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org') diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/AttachedPropertyVal.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/AttachedPropertyVal.java new file mode 100644 index 0000000000..38bfc99c54 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/AttachedPropertyVal.java @@ -0,0 +1,57 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.translator.datatypes.heattotosca; + +public class AttachedPropertyVal { + private Object propertyValue; + private ReferenceType referenceType; + + /** + * Instantiates a new Attached resource id. + * + * @param propertyValue the property value + * @param referenceType the reference type + */ + public AttachedPropertyVal(Object propertyValue, ReferenceType referenceType) { + this.referenceType = referenceType; + this.propertyValue = propertyValue; + } + + public Object getPropertyValue() { + return propertyValue; + } + + public ReferenceType getReferenceType() { + return referenceType; + } + + public boolean isGetResource() { + return referenceType == ReferenceType.GET_RESOURCE; + } + + public boolean isGetParam() { + return referenceType == ReferenceType.GET_PARAM; + } + + public boolean isGetAttr() { + return referenceType == ReferenceType.GET_ATTR; + } +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/AttachedResourceId.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/AttachedResourceId.java index 4286666392..16baf4e84b 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/AttachedResourceId.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/AttachedResourceId.java @@ -23,7 +23,7 @@ package org.openecomp.sdc.translator.datatypes.heattotosca; public class AttachedResourceId { private Object translatedId; private Object entityId; - private ResourceReferenceType resourceReferenceType; + private ReferenceType resourceReferenceType; /** * Instantiates a new Attached resource id. @@ -33,7 +33,7 @@ public class AttachedResourceId { * @param resourceReferenceType the resource reference type */ public AttachedResourceId(Object translatedId, Object entityId, - ResourceReferenceType resourceReferenceType) { + ReferenceType resourceReferenceType) { this.translatedId = translatedId; this.resourceReferenceType = resourceReferenceType; this.entityId = entityId; @@ -47,19 +47,19 @@ public class AttachedResourceId { return translatedId; } - public ResourceReferenceType getResourceReferenceType() { + public ReferenceType getResourceReferenceType() { return resourceReferenceType; } public boolean isGetResource() { - return resourceReferenceType == ResourceReferenceType.GET_RESOURCE; + return resourceReferenceType == ReferenceType.GET_RESOURCE; } public boolean isGetParam() { - return resourceReferenceType == ResourceReferenceType.GET_PARAM; + return resourceReferenceType == ReferenceType.GET_PARAM; } public boolean isGetAttr() { - return resourceReferenceType == ResourceReferenceType.GET_ATTR; + return resourceReferenceType == ReferenceType.GET_ATTR; } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/PropertyRegexMatcher.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/PropertyRegexMatcher.java new file mode 100644 index 0000000000..06d96bc3c1 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/PropertyRegexMatcher.java @@ -0,0 +1,83 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.translator.datatypes.heattotosca; + +import org.apache.commons.collections.CollectionUtils; + +import java.util.ArrayList; +import java.util.List; +import java.util.regex.Pattern; + +public class PropertyRegexMatcher { + private String propertyName; + private List regexPatterns; + private String stringToSearchForPropertyValue; + + /** + * Constractor for creating PropertyRegexMatcher. + * @param propertyName property name + * @param regexPatterns regex pattern + * @param stringToSearchForPropertyValue string for search in the property value manipulation + */ + public PropertyRegexMatcher(String propertyName, + List regexPatterns, + String stringToSearchForPropertyValue) { + this.propertyName = propertyName; + setRegex(regexPatterns); + this.stringToSearchForPropertyValue = stringToSearchForPropertyValue; + } + + public String getPropertyName() { + return propertyName; + } + + public void setPropertyName(String propertyName) { + this.propertyName = propertyName; + } + + /** + * Sets regex. + * + * @param regexPatterns the regex patterns + */ + public void setRegex(List regexPatterns) { + if (CollectionUtils.isEmpty(this.regexPatterns)) { + this.regexPatterns = new ArrayList<>(); + } + + for (String regexPattern : regexPatterns) { + this.regexPatterns.add(Pattern.compile(regexPattern)); + } + } + + public List getRegexPatterns() { + return regexPatterns; + } + + public String getStringToSearchForPropertyValue() { + return stringToSearchForPropertyValue; + } + + public void setStringToSearchForPropertyValue(String stringToSearchForPropertyValue) { + this.stringToSearchForPropertyValue = stringToSearchForPropertyValue; + } + +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/ReferenceType.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/ReferenceType.java new file mode 100644 index 0000000000..1f90db9cb3 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/ReferenceType.java @@ -0,0 +1,25 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.translator.datatypes.heattotosca; + +public enum ReferenceType { + GET_RESOURCE, GET_PARAM, GET_ATTR, OTHER +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/ResourceReferenceType.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/ResourceReferenceType.java deleted file mode 100644 index 81ccd69a66..0000000000 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/ResourceReferenceType.java +++ /dev/null @@ -1,25 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.translator.datatypes.heattotosca; - -public enum ResourceReferenceType { - GET_RESOURCE, GET_PARAM, GET_ATTR, OTHER -} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/TranslationContext.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/TranslationContext.java new file mode 100644 index 0000000000..736318bcab --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/TranslationContext.java @@ -0,0 +1,452 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.translator.datatypes.heattotosca; + +import org.openecomp.config.api.Configuration; +import org.openecomp.config.api.ConfigurationManager; +import org.openecomp.core.utilities.CommonMethods; +import org.openecomp.core.utilities.file.FileContentHandler; +import org.openecomp.sdc.common.utils.SdcCommon; +import org.openecomp.sdc.datatypes.configuration.ImplementationConfiguration; +import org.openecomp.sdc.heat.datatypes.manifest.FileData; +import org.openecomp.sdc.heat.datatypes.manifest.ManifestFile; +import org.openecomp.sdc.heat.datatypes.model.Resource; +import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; +import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; +import org.openecomp.sdc.tosca.services.ToscaUtil; +import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslatedHeatResource; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.composition.UnifiedCompositionEntity; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.composition.UnifiedSubstitutionData; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.ConsolidationData; +import org.openecomp.sdc.translator.services.heattotosca.ConfigConstants; +import org.openecomp.sdc.translator.services.heattotosca.Constants; +import org.openecomp.sdc.translator.services.heattotosca.NameExtractor; +import org.openecomp.sdc.translator.services.heattotosca.globaltypes.GlobalTypesGenerator; + +import java.io.InputStream; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; + + +public class TranslationContext { + + + private static Map>> translationMapping; + private static Map globalServiceTemplates; + private static Map nameExtractorImplMap; + private static Map supportedConsolidationComputeResources; + private static Map supportedConsolidationPortResources; + + static { + Configuration config = ConfigurationManager.lookup(); + String propertyFileName = SdcCommon.HEAT_TO_TOSCA_MAPPING_CONF; + translationMapping = + config.generateMap(ConfigConstants.MAPPING_NAMESPACE, ConfigConstants.RESOURCE_MAPPING_KEY); + try { + globalServiceTemplates = GlobalTypesGenerator.getGlobalTypesServiceTemplate(); + } catch (Exception e) { + throw new RuntimeException("Failed to load GlobalTypes", e); + } + nameExtractorImplMap = config.populateMap(ConfigConstants.TRANSLATOR_NAMESPACE, + ConfigConstants.NAMING_CONVENTION_EXTRACTOR_IMPL_KEY, ImplementationConfiguration.class); + supportedConsolidationComputeResources = config.populateMap(ConfigConstants + .MANDATORY_UNIFIED_MODEL_NAMESPACE, ConfigConstants + .SUPPORTED_CONSOLIDATION_COMPUTE_RESOURCES_KEY, ImplementationConfiguration.class); + supportedConsolidationPortResources = config.populateMap(ConfigConstants + .MANDATORY_UNIFIED_MODEL_NAMESPACE, ConfigConstants + .SUPPORTED_CONSOLIDATION_PORT_RESOURCES_KEY, ImplementationConfiguration.class); + + } + + private Map unifiedSubstitutionData = new HashMap<>(); + private ManifestFile manifest; + private FileContentHandler files = new FileContentHandler(); + private Map manifestFiles = new HashMap<>(); + //Key - file name, value - file type + private Set nestedHeatsFiles = new HashSet<>(); + private FileContentHandler externalArtifacts = new FileContentHandler(); + // Key - heat file name,value - set of heat resource ids which were translated + private Map> translatedResources = new HashMap<>(); + // Key - heat file name, value - translated Node template id + private Map> heatStackGroupMembers = new HashMap<>(); + // Key - heat file name, value - Map with Key - heat resource Id, Value - tosca entity template id + private Map> translatedIds = new HashMap<>(); + // key - service template type, value - translated service templates + private Map translatedServiceTemplates = new HashMap<>(); + //key - heat param name, value - shared resource data + private Map heatSharedResourcesByParam = new HashMap<>(); + //key - translated substitute service template file name, value - source nested heat file name + private Map nestedHeatFileName = new HashMap<>(); + //Key - heat file name,value - Map eith key - heat pseudo param name, + // value - translated tosca parameter name + private Map> usedHeatPseudoParams = new HashMap<>(); + //Consolidation data gathered for Unified TOSCA model + private ConsolidationData consolidationData = new ConsolidationData(); + + public static Map + getSupportedConsolidationComputeResources() { + return supportedConsolidationComputeResources; + } + + public static void setSupportedConsolidationComputeResources( + Map supportedConsolidationComputeResources) { + TranslationContext.supportedConsolidationComputeResources = + supportedConsolidationComputeResources; + } + + public static Map getSupportedConsolidationPortResources() { + return supportedConsolidationPortResources; + } + + public static void setSupportedConsolidationPortResources( + Map supportedConsolidationPortResources) { + TranslationContext.supportedConsolidationPortResources = supportedConsolidationPortResources; + } + + /** + * Get nameExtractor implemetation class instance. + * + * @param extractorImplKey configuration key for the implementation class + * @return implemetation class instance + */ + public static NameExtractor getNameExtractorImpl(String extractorImplKey) { + String nameExtractorImplClassName = + nameExtractorImplMap.get(extractorImplKey).getImplementationClass(); + + return CommonMethods.newInstance(nameExtractorImplClassName, NameExtractor.class); + } + + public Map getUnifiedSubstitutionData() { + return unifiedSubstitutionData; + } + + public void setUnifiedSubstitutionData( + Map unifiedSubstitutionData) { + this.unifiedSubstitutionData = unifiedSubstitutionData; + } + + public void addCleanedNodeTemplate(String serviceTemplateName, + String nodeTemplateId, + UnifiedCompositionEntity unifiedCompositionEntity, + NodeTemplate nodeTemplate) { + this.unifiedSubstitutionData.putIfAbsent(serviceTemplateName, new UnifiedSubstitutionData()); + this.unifiedSubstitutionData + .get(serviceTemplateName) + .addCleanedNodeTemplate(nodeTemplateId, unifiedCompositionEntity, nodeTemplate); + } + + public NodeTemplate getCleanedNodeTemplate(String serviceTemplateName, + String nodeTemplateId) { + return this.unifiedSubstitutionData.get(serviceTemplateName) + .getCleanedNodeTemplate(nodeTemplateId); + } + + public void addUnifiedNestedNodeTemplateId(String serviceTemplateName, + String nestedNodeTemplateId, + String unifiedNestedNodeTemplateId) { + this.unifiedSubstitutionData.putIfAbsent(serviceTemplateName, new UnifiedSubstitutionData()); + this.unifiedSubstitutionData.get(serviceTemplateName) + .addUnifiedNestedNodeTemplateId(nestedNodeTemplateId, unifiedNestedNodeTemplateId); + } + + public Optional getUnifiedNestedNodeTemplateId(String serviceTemplateName, + String nestedNodeTemplateId) { + return this.unifiedSubstitutionData.get(serviceTemplateName) == null ? Optional.empty() + :this.unifiedSubstitutionData.get(serviceTemplateName).getUnifiedNestedNodeTemplateId(nestedNodeTemplateId); + } + + public void addUnifiedNestedNodeTypeId(String serviceTemplateName, + String nestedNodeTypeId, + String unifiedNestedNodeTypeId){ + this.unifiedSubstitutionData.putIfAbsent(serviceTemplateName, new UnifiedSubstitutionData()); + this.unifiedSubstitutionData.get(serviceTemplateName).addUnifiedNestedNodeTypeId(nestedNodeTypeId, unifiedNestedNodeTypeId); + } + + public Optional getUnifiedNestedNodeTypeId(String serviceTemplateName, + String nestedNodeTemplateId) { + return this.unifiedSubstitutionData.get(serviceTemplateName) == null ? Optional.empty() + : this.unifiedSubstitutionData.get(serviceTemplateName).getUnifiedNestedNodeTypeId(nestedNodeTemplateId); + } + + public ConsolidationData getConsolidationData() { + return consolidationData; + } + + public void setConsolidationData(ConsolidationData consolidationData) { + this.consolidationData = consolidationData; + } + + public void addManifestFile(String fileName, FileData.Type fileType) { + this.manifestFiles.put(fileName, fileType); + } + + public Set getNestedHeatsFiles() { + return nestedHeatsFiles; + } + + public Map> getHeatStackGroupMembers() { + return heatStackGroupMembers; + } + + public FileContentHandler getFiles() { + return files; + } + + public void setFiles(Map files) { + this.files.putAll(files); + } + + public InputStream getFileContent(String fileName) { + return files.getFileContent(fileName); + } + + public void addFile(String name, byte[] content) { + files.addFile(name, content); + } + + public ManifestFile getManifest() { + return manifest; + } + + public void setManifest(ManifestFile manifest) { + this.manifest = manifest; + } + + public Map> getTranslatedResources() { + return translatedResources; + } + + public Map> getTranslatedIds() { + return translatedIds; + } + + // get tosca name from mapping configuration file + //element type - parameter/attribute + // element name - heat parameter/attribute name + //return value - tosca parameter/attribute name + public String getElementMapping(String resourceType, String elementType, String elementName) { + if (Objects.isNull(translationMapping.get(resourceType))) { + return null; + } + if (Objects.isNull(translationMapping.get(resourceType).get(elementType))) { + return null; + } + return translationMapping.get(resourceType).get(elementType).get(elementName); + } + + public Map getElementMapping(String resourceType, String elementType) { + if (Objects.isNull(translationMapping.get(resourceType))) { + return null; + } + return translationMapping.get(resourceType).get(elementType); + } + + public Set getElementSet(String resourceType, String elementType) { + if (Objects.isNull(translationMapping.get(resourceType))) { + return new HashSet<>(); + } + if (Objects.isNull(translationMapping.get(resourceType).get(elementType))) { + return new HashSet<>(); + } + return translationMapping.get(resourceType).get(elementType).keySet(); + } + + public Map getTranslatedServiceTemplates() { + return translatedServiceTemplates; + } + + public ServiceTemplate getGlobalSubstitutionServiceTemplate() { + return getTranslatedServiceTemplates().get(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME); + } + + public FileContentHandler getExternalArtifacts() { + return externalArtifacts; + } + + public void addExternalArtifacts(String name, byte[] content) { + this.externalArtifacts.addFile(name, content); + } + + public Map getHeatSharedResourcesByParam() { + return heatSharedResourcesByParam; + } + + public void addHeatSharedResourcesByParam(String parameterName, String resourceId, + Resource resource) { + this.addHeatSharedResourcesByParam(parameterName, + new TranslatedHeatResource(resourceId, resource)); + } + + private void addHeatSharedResourcesByParam(String parameterName, + TranslatedHeatResource translatedHeatResource) { + this.heatSharedResourcesByParam.put(parameterName, translatedHeatResource); + } + + public Map getGlobalServiceTemplates() { + return globalServiceTemplates; + } + + public Map getNestedHeatFileName() { + return nestedHeatFileName; + } + + public void addNestedHeatFileName(String substituteServiceTempalteName, + String nestedHeatFileName) { + this.nestedHeatFileName.put(substituteServiceTempalteName, nestedHeatFileName); + } + + public Map> getUsedHeatPseudoParams() { + return usedHeatPseudoParams; + } + + public void addUsedHeatPseudoParams(String heatFileName, String heatPseudoParam, String + translatedToscaParam) { + if (Objects.isNull(this.usedHeatPseudoParams.get(heatFileName))) { + this.usedHeatPseudoParams.put(heatFileName, new HashMap<>()); + } + this.usedHeatPseudoParams.get(heatFileName).put(heatPseudoParam, translatedToscaParam); + } + + /** + * Add the unified substitution data info in context. Contains a mapping of original node + * template id and the new node template id in the abstract substitute + * + * @param serviceTemplateFileName the service template file name + * @param originalNodeTemplateId the original node template id + * @param abstractNodeTemplateId the node template id in the abstract substitute + */ + public void addUnifiedSubstitutionData(String serviceTemplateFileName, + String originalNodeTemplateId, + String abstractNodeTemplateId) { + + Map nodeAbstractNodeTemplateIdMap = this.getUnifiedSubstitutionData() + .computeIfAbsent(serviceTemplateFileName, k -> new UnifiedSubstitutionData()) + .getNodesRelatedAbstractNode(); + + if (nodeAbstractNodeTemplateIdMap == null) { + nodeAbstractNodeTemplateIdMap = new HashMap<>(); + } + nodeAbstractNodeTemplateIdMap.put(originalNodeTemplateId, abstractNodeTemplateId); + this.getUnifiedSubstitutionData().get(serviceTemplateFileName).setNodesRelatedAbstractNode( + nodeAbstractNodeTemplateIdMap); + } + + /** + * Add the unified substitution data info in context. Contains a mapping of original node + * template id and the new node template id in the abstract substitute + * + * @param serviceTemplateFileName the service template file name + * @param originalNodeTemplateId the original node template id + * @param substitutionServiceTemplateNodeTemplateId the node template id in the substitution + * service template + */ + public void addSubstitutionServiceTemplateUnifiedSubstitutionData(String serviceTemplateFileName, + String originalNodeTemplateId, + String substitutionServiceTemplateNodeTemplateId) { + + Map nodesRelatedSubstitutionServiceTemplateNodeTemplateIdMap = this + .getUnifiedSubstitutionData() + .computeIfAbsent(serviceTemplateFileName, k -> new UnifiedSubstitutionData()) + .getNodesRelatedSubstitutionServiceTemplateNode(); + + if (nodesRelatedSubstitutionServiceTemplateNodeTemplateIdMap == null) { + nodesRelatedSubstitutionServiceTemplateNodeTemplateIdMap = new HashMap<>(); + } + nodesRelatedSubstitutionServiceTemplateNodeTemplateIdMap.put(originalNodeTemplateId, + substitutionServiceTemplateNodeTemplateId); + this.getUnifiedSubstitutionData().get(serviceTemplateFileName) + .setNodesRelatedSubstitutionServiceTemplateNode( + nodesRelatedSubstitutionServiceTemplateNodeTemplateIdMap); + } + + /** + * Get unified abstract node template which is mapped to the input node template id. + * + * @param serviceTemplate the service template + * @param nodeTemplateId the node template id + */ + public String getUnifiedAbstractNodeTemplateId(ServiceTemplate serviceTemplate, + String nodeTemplateId) { + UnifiedSubstitutionData unifiedSubstitutionData = + this.unifiedSubstitutionData.get(ToscaUtil.getServiceTemplateFileName(serviceTemplate)); + return unifiedSubstitutionData.getNodesRelatedAbstractNode().get(nodeTemplateId); + } + + /** + * Get unified node template in the substitution service template which is mapped to the + * original input node template id. + * + * @param serviceTemplate the service template + * @param nodeTemplateId the node template id + */ + public String getUnifiedSubstitutionNodeTemplateId(ServiceTemplate serviceTemplate, + String nodeTemplateId) { + UnifiedSubstitutionData unifiedSubstitutionData = + this.unifiedSubstitutionData.get(ToscaUtil.getServiceTemplateFileName(serviceTemplate)); + return unifiedSubstitutionData.getNodesRelatedSubstitutionServiceTemplateNode() + .get(nodeTemplateId); + } + + public int getHandledNestedComputeNodeTemplateIndex(String serviceTemplateName, + String computeType){ + return this.unifiedSubstitutionData.get(serviceTemplateName) + .getHandledNestedComputeNodeTemplateIndex(computeType); + } + + public void updateHandledComputeType(String serviceTemplateName, + String nestedServiceTemplateFileName, + String handledComputeType){ + this.unifiedSubstitutionData.putIfAbsent(serviceTemplateName, new UnifiedSubstitutionData()); + this.unifiedSubstitutionData.get(serviceTemplateName) + .addHandledComputeType(nestedServiceTemplateFileName, handledComputeType); + } + + public boolean isNestedServiceTemplateWasHandled(String serviceTemplateName, + String nestedServiceTemplateFileName){ + if(Objects.isNull(this.unifiedSubstitutionData.get(serviceTemplateName))){ + return false; + } + return this.unifiedSubstitutionData.get(serviceTemplateName) + .isNestedServiceTemplateWasHandled(nestedServiceTemplateFileName); + } + + public void addNestedFileToUsedNestedComputeType(String serviceTemplateName, + String nestedServiceTemplateFileName, + String computeType){ + this.unifiedSubstitutionData.putIfAbsent(serviceTemplateName, new UnifiedSubstitutionData()); + + this.unifiedSubstitutionData.get(serviceTemplateName).addNestedFileToUsedNestedComputeType + (computeType, nestedServiceTemplateFileName); + } + + public int getGlobalNodeTypeIndex(String serviceTemplateName, + String computeType){ + if(Objects.isNull(this.unifiedSubstitutionData.get(serviceTemplateName))){ + return 0; + } + return this.unifiedSubstitutionData.get(serviceTemplateName).getGlobalNodeTypeIndex + (computeType); + } +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/to/ResourceFileDataAndIDs.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/to/ResourceFileDataAndIDs.java index b8349444d7..24eef115e2 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/to/ResourceFileDataAndIDs.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/to/ResourceFileDataAndIDs.java @@ -23,6 +23,7 @@ package org.openecomp.sdc.translator.datatypes.heattotosca.to; import org.openecomp.sdc.heat.datatypes.manifest.FileData; + public class ResourceFileDataAndIDs { private String resourceId; private String translatedResourceId; diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/to/TranslateTo.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/to/TranslateTo.java index 6c56715f79..56ba9d120d 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/to/TranslateTo.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/to/TranslateTo.java @@ -24,7 +24,7 @@ package org.openecomp.sdc.translator.datatypes.heattotosca.to; import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate; import org.openecomp.sdc.heat.datatypes.model.Resource; import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; -import org.openecomp.sdc.translator.services.heattotosca.TranslationContext; +import org.openecomp.sdc.translator.datatypes.heattotosca.TranslationContext; public class TranslateTo { private String heatFileName; diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/NodeTemplateInformation.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/NodeTemplateInformation.java new file mode 100644 index 0000000000..bd1263da5f --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/NodeTemplateInformation.java @@ -0,0 +1,38 @@ +package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.composition; + +import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; +import org.openecomp.sdc.translator.services.heattotosca.UnifiedCompositionService; + +/** + * Created by Talio on 4/4/2017. + */ +public class NodeTemplateInformation { + UnifiedCompositionEntity unifiedCompositionEntity; + private NodeTemplate nodeTemplate; + + public NodeTemplateInformation(){} + + public NodeTemplateInformation( + UnifiedCompositionEntity unifiedCompositionEntity, + NodeTemplate nodeTemplate) { + this.unifiedCompositionEntity = unifiedCompositionEntity; + this.nodeTemplate = nodeTemplate; + } + + public UnifiedCompositionEntity getUnifiedCompositionEntity() { + return unifiedCompositionEntity; + } + + public void setUnifiedCompositionEntity( + UnifiedCompositionEntity unifiedCompositionEntity) { + this.unifiedCompositionEntity = unifiedCompositionEntity; + } + + public NodeTemplate getNodeTemplate() { + return nodeTemplate; + } + + public void setNodeTemplate(NodeTemplate nodeTemplate) { + this.nodeTemplate = nodeTemplate; + } +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/UnifiedCompositionData.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/UnifiedCompositionData.java new file mode 100644 index 0000000000..a3635391ba --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/UnifiedCompositionData.java @@ -0,0 +1,95 @@ +package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.composition; + +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.ComputeTemplateConsolidationData; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.NestedTemplateConsolidationData; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.PortTemplateConsolidationData; + +import java.util.ArrayList; +import java.util.List; + +/** + * The type Unified composition data. + */ +public class UnifiedCompositionData { + /** + * The Compute template consolidation data. + */ + private ComputeTemplateConsolidationData computeTemplateConsolidationData; + /** + * The Port template consolidation data list. + */ + private List portTemplateConsolidationDataList; + + + private NestedTemplateConsolidationData nestedTemplateConsolidationData; + + /** + * Gets compute template consolidation data. + * + * @return the compute template consolidation data + */ + public ComputeTemplateConsolidationData getComputeTemplateConsolidationData() { + return computeTemplateConsolidationData; + } + + /** + * Sets compute template consolidation data. + * + * @param computeTemplateConsolidationData the compute template consolidation data + */ + public void setComputeTemplateConsolidationData( + ComputeTemplateConsolidationData computeTemplateConsolidationData) { + this.computeTemplateConsolidationData = computeTemplateConsolidationData; + } + + /** + * Gets port template consolidation data list. + * + * @return the port template consolidation data list + */ + public List getPortTemplateConsolidationDataList() { + return portTemplateConsolidationDataList; + } + + /** + * Sets port template consolidation data list. + * + * @param portTemplateConsolidationDataList the port template consolidation data list + */ + public void setPortTemplateConsolidationDataList( + List portTemplateConsolidationDataList) { + this.portTemplateConsolidationDataList = portTemplateConsolidationDataList; + } + + /** + * Add port consolidation data. + * + * @param portTemplateConsolidationData the port consolidation data + */ + public void addPortTemplateConsolidationData( + PortTemplateConsolidationData portTemplateConsolidationData) { + if (this.portTemplateConsolidationDataList == null) { + this.portTemplateConsolidationDataList = new ArrayList<>(); + } + this.portTemplateConsolidationDataList.add(portTemplateConsolidationData); + } + + /** + * Gets nested template consolidation data. + * + * @return the nested template consolidation data + */ + public NestedTemplateConsolidationData getNestedTemplateConsolidationData() { + return nestedTemplateConsolidationData; + } + + /** + * Sets nested template consolidation data. + * + * @param nestedTemplateConsolidationData the nested template consolidation data + */ + public void setNestedTemplateConsolidationData( + NestedTemplateConsolidationData nestedTemplateConsolidationData) { + this.nestedTemplateConsolidationData = nestedTemplateConsolidationData; + } +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/UnifiedCompositionEntity.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/UnifiedCompositionEntity.java new file mode 100644 index 0000000000..d0bb826904 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/UnifiedCompositionEntity.java @@ -0,0 +1,8 @@ +package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.composition; + +public enum UnifiedCompositionEntity { + Compute, + Port, + Nested, + Other; +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/UnifiedCompositionMode.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/UnifiedCompositionMode.java new file mode 100644 index 0000000000..c4e6f1ce4a --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/UnifiedCompositionMode.java @@ -0,0 +1,13 @@ +package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.composition; + +/** + * @author SHIRIA + * @since March 02, 2017. + */ +public enum UnifiedCompositionMode { + SingleSubstitution, + ScalingInstances, + // todo - support B1 SingleSubstitution, but create diff types/services vm_type+ + CatalogInstance, + NestedSingleCompute; +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/UnifiedSubstitutionData.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/UnifiedSubstitutionData.java new file mode 100644 index 0000000000..57f77a51e5 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/composition/UnifiedSubstitutionData.java @@ -0,0 +1,145 @@ +package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.composition; + +import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; + +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Optional; +import java.util.Set; + +public class UnifiedSubstitutionData { + + //Key - node template id, Value - related abstract node template id + private Map nodesRelatedAbstractNode = new HashMap<>(); + //Key - node template id, Value - related node template id in the substitution service template + private Map nodesRelatedSubstitutionServiceTemplateNode = new HashMap<>(); + private Map cleanedNodeTemplates = new HashMap<>(); + //Key - nested node template id, Value - related unified nested node template id + private Map nestedNodeTemplateRelatedUnifiedTranslatedId = new HashMap<>(); + //Key - nested node type id, Value - related unified nested node template id + private Map nestedNodeTypeRelatedUnifiedTranslatedId = new HashMap<>(); + //Key - handled compute type, Value - number of times it was handled + private Map handledComputeTypesInNestedSubstitutionTemplate = + new HashMap<>(); + //Key - nested compute type, Value - list of nested files that the compute type is present + private Map> handledNestedComputeTypesNestedFiles = new HashMap<>(); + //handled nested files + private Set handledNestedFiles = new HashSet<>(); + + public Map getNodesRelatedAbstractNode() { + return nodesRelatedAbstractNode; + } + + public void setNodesRelatedAbstractNode( + Map nodesRelatedAbstractNode) { + this.nodesRelatedAbstractNode = nodesRelatedAbstractNode; + } + + public Map getNodesRelatedSubstitutionServiceTemplateNode() { + return nodesRelatedSubstitutionServiceTemplateNode; + } + + public void setNodesRelatedSubstitutionServiceTemplateNode( + Map nodesRelatedSubstitutionServiceTemplateNode) { + this.nodesRelatedSubstitutionServiceTemplateNode = nodesRelatedSubstitutionServiceTemplateNode; + } + + public String getNodeRelatedAbstractNode(String origNodeId) { + return this.nodesRelatedAbstractNode.get(origNodeId); + } + + public Collection getAllRelatedAbstractNodeIds() { + return this.nodesRelatedAbstractNode.values(); + } + + public Collection getAllUnifiedNestedNodeTemplateIds() { + return this.nestedNodeTemplateRelatedUnifiedTranslatedId.values(); + } + + /** + * Add cleaned node template. + * + * @param nodeTemplateId the node template id + * @param unifiedCompositionEntity the unified composition entity + * @param nodeTemplate the node template + */ + public void addCleanedNodeTemplate(String nodeTemplateId, + UnifiedCompositionEntity unifiedCompositionEntity, + NodeTemplate nodeTemplate) { + NodeTemplateInformation nodeTemplateInformation = new NodeTemplateInformation( + unifiedCompositionEntity, nodeTemplate); + this.cleanedNodeTemplates.putIfAbsent(nodeTemplateId, nodeTemplateInformation); + } + + public NodeTemplate getCleanedNodeTemplate(String nodeTemplateId) { + return this.cleanedNodeTemplates.get(nodeTemplateId).getNodeTemplate().clone(); + } + + public UnifiedCompositionEntity getCleanedNodeTemplateCompositionEntity(String nodeTemplateId) { + return this.cleanedNodeTemplates.get(nodeTemplateId).getUnifiedCompositionEntity(); + } + + public void addUnifiedNestedNodeTemplateId(String nestedNodeTemplateId, + String unifiedNestedNodeRelatedId) { + this.nestedNodeTemplateRelatedUnifiedTranslatedId + .put(nestedNodeTemplateId, unifiedNestedNodeRelatedId); + } + + public Optional getUnifiedNestedNodeTemplateId(String nestedNodeTemplateId) { + return this.nestedNodeTemplateRelatedUnifiedTranslatedId.get(nestedNodeTemplateId) == null + ? Optional.empty() + : Optional.of(this.nestedNodeTemplateRelatedUnifiedTranslatedId.get(nestedNodeTemplateId)); + } + + public void addUnifiedNestedNodeTypeId(String nestedNodeTypeId, + String unifiedNestedNodeRelatedId) { + this.nestedNodeTypeRelatedUnifiedTranslatedId.put(nestedNodeTypeId, unifiedNestedNodeRelatedId); + } + + public Optional getUnifiedNestedNodeTypeId(String nestedNodeTypeId) { + return this.nestedNodeTypeRelatedUnifiedTranslatedId.get(nestedNodeTypeId) == null ? Optional + .empty() + : Optional.of(this.nestedNodeTypeRelatedUnifiedTranslatedId.get(nestedNodeTypeId)); + } + + public void addHandledComputeType(String nestedServiceTemplateFileName, + String handledComputeType) { + + if (this.handledComputeTypesInNestedSubstitutionTemplate.containsKey(handledComputeType)) { + Integer timesHandled = + this.handledComputeTypesInNestedSubstitutionTemplate.get(handledComputeType); + this.handledComputeTypesInNestedSubstitutionTemplate + .put(handledComputeType, timesHandled + 1); + } else { + this.handledNestedFiles.add(nestedServiceTemplateFileName); + handledComputeTypesInNestedSubstitutionTemplate.put(handledComputeType, 0); + } + } + + public boolean isComputeTypeHandledInServiceTemplate(String computeType) { + return this.handledComputeTypesInNestedSubstitutionTemplate.containsKey(computeType); + } + + public int getHandledNestedComputeNodeTemplateIndex(String computeType) { + return this.handledComputeTypesInNestedSubstitutionTemplate.containsKey(computeType) ? + this.handledComputeTypesInNestedSubstitutionTemplate.get(computeType): + 0; + } + + public boolean isNestedServiceTemplateWasHandled(String nestedServiceTemplateFileName) { + return this.handledNestedFiles.contains(nestedServiceTemplateFileName); + } + + public void addNestedFileToUsedNestedComputeType(String computeType, + String nestedServiceTemplateFileName){ + this.handledNestedComputeTypesNestedFiles.putIfAbsent(computeType, new HashSet<>()); + this.handledNestedComputeTypesNestedFiles.get(computeType).add(nestedServiceTemplateFileName); + } + + public int getGlobalNodeTypeIndex(String computeType){ + return this.handledNestedComputeTypesNestedFiles.get(computeType).size() == 1 ? 0: + this.handledNestedComputeTypesNestedFiles.get(computeType).size() - 1; + } +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/ComputeConsolidationData.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/ComputeConsolidationData.java new file mode 100644 index 0000000000..d2f6083d23 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/ComputeConsolidationData.java @@ -0,0 +1,52 @@ +package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation; + +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +/** + * The type Compute consolidation data. + */ +public class ComputeConsolidationData { + + //Key - Service template file name + private Map fileComputeConsolidationData; + + /** + * Instantiates a new Compute consolidation data. + */ + public ComputeConsolidationData() { + fileComputeConsolidationData = new HashMap<>(); + } + + /** + * Gets all files. + * + * @return the all files + */ + public Set getAllServiceTemplateFileNames() { + return fileComputeConsolidationData.keySet(); + } + + /** + * Gets file compute consolidation data. + * + * @param serviceTemplateFileName the file name + * @return the file compute consolidation data + */ + public FileComputeConsolidationData getFileComputeConsolidationData(String + serviceTemplateFileName) { + return fileComputeConsolidationData.get(serviceTemplateFileName); + } + + /** + * Sets file compute consolidation data. + * + * @param serviceTemplateFileName the file name + * @param fileComputeConsolidationData the file compute consolidation data + */ + public void setFileComputeConsolidationData(String serviceTemplateFileName, + FileComputeConsolidationData fileComputeConsolidationData) { + this.fileComputeConsolidationData.put(serviceTemplateFileName, fileComputeConsolidationData); + } +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/ComputeTemplateConsolidationData.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/ComputeTemplateConsolidationData.java new file mode 100644 index 0000000000..c6721ce18f --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/ComputeTemplateConsolidationData.java @@ -0,0 +1,88 @@ +package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation; + +import org.openecomp.sdc.tosca.datatypes.model.RequirementAssignment; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * The type Compute template consolidation data. + */ +public class ComputeTemplateConsolidationData extends EntityConsolidationData { + // key - volume node template id + // List of requirement id and the requirement assignment on the + // compute node which connect to this volume + private Map> volumes; + + // key - port type (port id excluding index), + // value - List of connected port node template ids, with this port type + private Map> ports; + + /** + * Gets volumes. + * + * @return the volumes + */ + public Map> getVolumes() { + return volumes; + } + + /** + * Sets volumes. + * + * @param volumes the volumes + */ + public void setVolumes(Map> volumes) { + this.volumes = volumes; + } + + /** + * Gets ports. + * + * @return the ports + */ + public Map> getPorts() { + return ports; + } + + /** + * Sets ports. + * + * @param ports the ports + */ + public void setPorts(Map> ports) { + this.ports = ports; + } + + /** + * Add port. + * + * @param portType the port type + * @param portNodeTemplateId the port node template id + */ + public void addPort(String portType, String portNodeTemplateId) { + if (this.ports == null) { + this.ports = new HashMap<>(); + } + this.ports.putIfAbsent(portType, new ArrayList<>()); + this.ports.get(portType).add(portNodeTemplateId); + } + + + /** + * Add volume. + * + * @param requirementId the requirement id + * @param requirementAssignment the requirement assignment + */ + public void addVolume(String requirementId, RequirementAssignment requirementAssignment) { + if (this.volumes == null) { + this.volumes = new HashMap<>(); + } + this.volumes.computeIfAbsent(requirementAssignment.getNode(), k -> new ArrayList<>()) + .add(new RequirementAssignmentData(requirementId, + requirementAssignment)); + } +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/ConsolidationData.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/ConsolidationData.java new file mode 100644 index 0000000000..496da78f76 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/ConsolidationData.java @@ -0,0 +1,109 @@ +package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation; + +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * The type Consolidation data. + */ +public class ConsolidationData { + + //Compute consolidation data + private ComputeConsolidationData computeConsolidationData; + + //Port Consolidation data + private PortConsolidationData portConsolidationData; + + //Key - Service Template file name + //value - List of the abstract/substitute node template id + private Map> substituteNodeTemplates; // todo - remove this one and use + // nestedConsolidationData instead + + //Nested Consolidation data + private NestedConsolidationData nestedConsolidationData; + + + /** + * Instantiates a new Consolidation data. + */ + public ConsolidationData() { + computeConsolidationData = new ComputeConsolidationData(); + portConsolidationData = new PortConsolidationData(); + nestedConsolidationData = new NestedConsolidationData(); + substituteNodeTemplates = new HashMap<>(); + } + + /** + * Gets compute consolidation data. + * + * @return the compute consolidation data + */ + public ComputeConsolidationData getComputeConsolidationData() { + return computeConsolidationData; + } + + /** + * Sets compute consolidation data. + * + * @param computeConsolidationData the compute consolidation data + */ + public void setComputeConsolidationData(ComputeConsolidationData computeConsolidationData) { + this.computeConsolidationData = computeConsolidationData; + } + + /** + * Gets port consolidation data. + * + * @return the port consolidation data + */ + public PortConsolidationData getPortConsolidationData() { + return portConsolidationData; + } + + /** + * Sets port consolidation data. + * + * @param portConsolidationData the port consolidation data + */ + public void setPortConsolidationData( + PortConsolidationData portConsolidationData) { + this.portConsolidationData = portConsolidationData; + } + + /** + * Gets substitute node templates. + * + * @return the substitute node templates + */ + public Map> getSubstituteNodeTemplates() { + return substituteNodeTemplates; + } + + /** + * Sets substitute node templates. + * + * @param substituteNodeTemplates the substitute node templates + */ + public void setSubstituteNodeTemplates(Map> substituteNodeTemplates) { + this.substituteNodeTemplates = substituteNodeTemplates; + } + + /** + * Gets nested consolidation data. + * + * @return the nested consolidation data + */ + public NestedConsolidationData getNestedConsolidationData() { + return nestedConsolidationData; + } + + /** + * Sets nested consolidation data. + * + * @param nestedConsolidationData the nested consolidation data + */ + public void setNestedConsolidationData(NestedConsolidationData nestedConsolidationData) { + this.nestedConsolidationData = nestedConsolidationData; + } +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/EntityConsolidationData.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/EntityConsolidationData.java new file mode 100644 index 0000000000..4545d5cdbd --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/EntityConsolidationData.java @@ -0,0 +1,245 @@ +package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation; + +import org.openecomp.sdc.tosca.datatypes.model.RequirementAssignment; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * The type Entity consolidation data. + */ +public class EntityConsolidationData { + + private String nodeTemplateId; + + //groups that point to this entity node template + private List groupIds; + + // key - node template id which has connection to this entity + // value - List of Requirement assignment data which connect to this entity + private Map> nodesConnectedIn; + + // key - node template id which connected from this entity + // List of Requirement assignment data which connect to the key node template id + private Map> nodesConnectedOut; + + //key - node template id which include get attribute function from this entity + //key - node template id which include get attribute function from this entity + //value - List of getAttr data + private Map> nodesGetAttrIn; + + //key - node template id which is pointed by this entity using get attribute function + //value - List of getAttr data + private Map> nodesGetAttrOut; + + //List of getAttr data + private List outputParametersGetAttrIn; + + /** + * Gets node template id. + * + * @return the node template id + */ + public String getNodeTemplateId() { + return nodeTemplateId; + } + + /** + * Sets node template id. + * + * @param nodeTemplateId the node template id + */ + public void setNodeTemplateId(String nodeTemplateId) { + this.nodeTemplateId = nodeTemplateId; + } + + /** + * Gets group ids point to me. + * + * @return the group ids point to me + */ + public List getGroupIds() { + return groupIds; + } + + /** + * Sets group ids point to me. + * + * @param groupIds the group ids point to me + */ + public void setGroupIds(List groupIds) { + this.groupIds = groupIds; + } + + + /** + * Sets node connected to me. + * + * @param nodesConnectedIn the node connected to me + */ + public void setNodesConnectedIn(Map> nodesConnectedIn) { + this.nodesConnectedIn = nodesConnectedIn; + } + + /** + * Add nodeConnectedIn. + * + * @param nodeTemplateId the node template id which has connection to me + * @param requirementId the requirement id + * @param requirementAssignment the requirement assignment + */ + public void addNodesConnectedIn(String nodeTemplateId, String requirementId, + RequirementAssignment requirementAssignment) { + if (this.nodesConnectedIn == null) { + this.nodesConnectedIn = new HashMap<>(); + } + this.nodesConnectedIn.computeIfAbsent(nodeTemplateId, k -> new ArrayList<>()); + this.nodesConnectedIn.get(nodeTemplateId).add(new RequirementAssignmentData(requirementId, + requirementAssignment)); + } + + /** + * Gets node connected to me. + * + * @return the node connected to me + */ + public Map> getNodesConnectedIn() { + return nodesConnectedIn; + } + + + /** + * Gets node connected from me. + * + * @return the node connected from me + */ + public Map> getNodesConnectedOut() { + return nodesConnectedOut; + } + + /** + * Sets node connected from me. + * + * @param nodesConnectedOut the node connected from me + */ + public void setNodesConnectedOut( + Map> nodesConnectedOut) { + this.nodesConnectedOut = nodesConnectedOut; + } + + /** + * Add nodeConnectedOut. + * + * @param nodeTemplateId the node template id which is connected from me + * @param requirementId the requirement id + * @param requirementAssignment the requirement assignment + */ + public void addNodesConnectedOut(String nodeTemplateId, String requirementId, + RequirementAssignment + requirementAssignment) { + if (this.nodesConnectedOut == null) { + this.nodesConnectedOut = new HashMap<>(); + } + this.nodesConnectedOut.computeIfAbsent(nodeTemplateId, k -> new ArrayList<>()); + this.nodesConnectedOut.get(nodeTemplateId).add(new RequirementAssignmentData(requirementId, + requirementAssignment)); + } + + /** + * Gets nodes get attr in. + * + * @return the get attr in + */ + public Map> getNodesGetAttrIn() { + return nodesGetAttrIn; + } + + /** + * Sets nodes get attr in. + * + * @param nodesGetAttrIn the get attr in + */ + public void setNodesGetAttrIn( + Map> nodesGetAttrIn) { + this.nodesGetAttrIn = nodesGetAttrIn; + } + + /** + * Add nodes get attr in data. + * + * @param nodeTemplateId the node template id + * @param getAttrFuncData get attr data + */ + public void addNodesGetAttrIn(String nodeTemplateId, GetAttrFuncData getAttrFuncData) { + if (nodesGetAttrIn == null) { + nodesGetAttrIn = new HashMap<>(); + } + this.nodesGetAttrIn.putIfAbsent(nodeTemplateId, new ArrayList<>()); + this.nodesGetAttrIn.get(nodeTemplateId).add(getAttrFuncData); + } + + /** + * Gets output parameters get attr from me. + * + * @return the get attr from me + */ + public List getOutputParametersGetAttrIn() { + return outputParametersGetAttrIn; + } + + /** + * Sets output parameters get attr from me. + * + * @param outputParametersGetAttrIn the output parameters get attr from me + */ + public void setOutputParametersGetAttrIn(List outputParametersGetAttrIn) { + this.outputParametersGetAttrIn = outputParametersGetAttrIn; + } + + /** + * Add output parameters get attr data. + * + * @param getAttrFuncData get attr data + */ + public void addOutputParamGetAttrIn(GetAttrFuncData getAttrFuncData) { + if (outputParametersGetAttrIn == null) { + outputParametersGetAttrIn = new ArrayList<>(); + } + this.outputParametersGetAttrIn.add(getAttrFuncData); + } + + /** + * Gets nodes get attr out. + * + * @return the get attr out + */ + public Map> getNodesGetAttrOut() { + return nodesGetAttrOut; + } + + /** + * Sets nodes get attr out. + * + * @param nodesGetAttrOut the get attr out + */ + public void setNodesGetAttrOut( + Map> nodesGetAttrOut) { + this.nodesGetAttrOut = nodesGetAttrOut; + } + + /** + * Add nodes get attr out data. + * + * @param nodeTemplateId the node template id + * @param getAttrFuncData get attr data + */ + public void addNodesGetAttrOut(String nodeTemplateId, GetAttrFuncData getAttrFuncData) { + if (nodesGetAttrOut == null) { + nodesGetAttrOut = new HashMap<>(); + } + this.nodesGetAttrOut.putIfAbsent(nodeTemplateId, new ArrayList<>()); + this.nodesGetAttrOut.get(nodeTemplateId).add(getAttrFuncData); + } +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/FileComputeConsolidationData.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/FileComputeConsolidationData.java new file mode 100644 index 0000000000..04a75d37b2 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/FileComputeConsolidationData.java @@ -0,0 +1,56 @@ +package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation; + +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +/** + * The type File compute consolidation data. + */ +public class FileComputeConsolidationData { + + //key - compute node type name (vm_type) + private Map typeComputeConsolidationData; + + /** + * Instantiates a new File compute consolidation data. + */ + public FileComputeConsolidationData() { + typeComputeConsolidationData = new HashMap<>(); + } + + /** + * Gets all compute types. + * + * @return the all compute types + */ + public Set getAllComputeTypes() { + return typeComputeConsolidationData.keySet(); + } + + public Collection getAllTypeComputeConsolidationData(){ + return typeComputeConsolidationData.values(); + } + + /** + * Gets type compute consolidation data. + * + * @param computeType the compute type + * @return the type compute consolidation data + */ + public TypeComputeConsolidationData getTypeComputeConsolidationData(String computeType) { + return typeComputeConsolidationData.get(computeType); + } + + /** + * Sets type compute consolidation data. + * + * @param computeType the compute type + * @param typeComputeConsolidationData the type compute consolidation data + */ + public void setTypeComputeConsolidationData(String computeType, TypeComputeConsolidationData + typeComputeConsolidationData) { + this.typeComputeConsolidationData.put(computeType, typeComputeConsolidationData); + } +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/FileNestedConsolidationData.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/FileNestedConsolidationData.java new file mode 100644 index 0000000000..1a3948a3a8 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/FileNestedConsolidationData.java @@ -0,0 +1,55 @@ +package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation; + +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +/** + * The type File nested node consolidation data. + */ +public class FileNestedConsolidationData { + + //key - nested node template id + private Map nestedTemplateConsolidationData; + + public FileNestedConsolidationData() { + this.nestedTemplateConsolidationData = new HashMap<>(); + } + + /** + * Gets all nested node template ids. + * + * @return the all nested node template ids + */ + public Set getAllNestedNodeTemplateIds() { + return nestedTemplateConsolidationData.keySet(); + } + + public Collection getAllNestedConsolidationData() { + return nestedTemplateConsolidationData.values(); + } + + /** + * Gets nested template consolidation data. + * + * @param nestedNodeTemplateId the nested node template id + * @return the nested template consolidation data + */ + public NestedTemplateConsolidationData getNestedTemplateConsolidationData( + String nestedNodeTemplateId) { + return nestedTemplateConsolidationData.get(nestedNodeTemplateId); + } + + /** + * Sets nested template consolidation data. + * + * @param nestedNodeTemplateId the nested node template id + * @param nestedTemplateConsolidationData the nested template consolidation data + */ + public void setNestedTemplateConsolidationData( + String nestedNodeTemplateId, + NestedTemplateConsolidationData nestedTemplateConsolidationData) { + this.nestedTemplateConsolidationData.put(nestedNodeTemplateId, nestedTemplateConsolidationData); + } +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/FilePortConsolidationData.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/FilePortConsolidationData.java new file mode 100644 index 0000000000..fd02edb818 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/FilePortConsolidationData.java @@ -0,0 +1,54 @@ +package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation; + +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +/** + * The type File port consolidation data. + */ +public class FilePortConsolidationData { + + //key - port node template id + private Map portTemplateConsolidationData; + + public FilePortConsolidationData() { + this.portTemplateConsolidationData = new HashMap<>(); + } + + /** + * Gets all port node template ids. + * + * @return the all port node template ids + */ + public Set getAllPortNodeTemplateIds() { + return portTemplateConsolidationData.keySet(); + } + + public Collection getAllPortConsolidationData() { + return portTemplateConsolidationData.values(); + } + + /** + * Gets port template consolidation data. + * + * @param portNodeTemplateId the port node template id + * @return the port template consolidation data + */ + public PortTemplateConsolidationData getPortTemplateConsolidationData(String portNodeTemplateId) { + return portTemplateConsolidationData.get(portNodeTemplateId); + } + + /** + * Sets port template consolidation data. + * + * @param portNodeTemplateId the port node template id + * @param portTemplateConsolidationData the port template consolidation data + */ + public void setPortTemplateConsolidationData(String portNodeTemplateId, + PortTemplateConsolidationData + portTemplateConsolidationData) { + this.portTemplateConsolidationData.put(portNodeTemplateId, portTemplateConsolidationData); + } +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/GetAttrFuncData.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/GetAttrFuncData.java new file mode 100644 index 0000000000..8c88232e57 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/GetAttrFuncData.java @@ -0,0 +1,62 @@ +package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation; + +/** + * The type get attribute data. + */ +public class GetAttrFuncData { + + private String fieldName; + private String attributeName; + + public GetAttrFuncData(){} + + public GetAttrFuncData(String fieldName, String attributeName) { + this.fieldName = fieldName; + this.attributeName = attributeName; + } + + public String getFieldName() { + return fieldName; + } + + public void setFieldName(String fieldName) { + this.fieldName = fieldName; + } + + public String getAttributeName() { + return attributeName; + } + + public void setAttributeName(String attributeName) { + this.attributeName = attributeName; + } + + @Override + public boolean equals(Object o) { + if (this == o) { + return true; + } + if (o == null || getClass() != o.getClass()) { + return false; + } + + GetAttrFuncData that = (GetAttrFuncData) o; + + if (fieldName != null ? !fieldName.equals(that.fieldName) : that.fieldName != null) { + return false; + } + if (attributeName != null ? !attributeName.equals(that.attributeName) + : that.attributeName != null) { + return false; + } + + return true; + } + + @Override + public int hashCode() { + int result = fieldName != null ? fieldName.hashCode() : 0; + result = 31 * result + (attributeName != null ? attributeName.hashCode() : 0); + return result; + } +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/NestedConsolidationData.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/NestedConsolidationData.java new file mode 100644 index 0000000000..8dde9510e2 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/NestedConsolidationData.java @@ -0,0 +1,50 @@ +package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation; + +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +/** + * The type Nested Node consolidation data. + */ +public class NestedConsolidationData { + + //Key - Service template file name + private Map fileNestedConsolidationData; + + public NestedConsolidationData() { + this.fileNestedConsolidationData = new HashMap<>(); + } + + /** + * Gets all files. + * + * @return the all files + */ + public Set getAllServiceTemplateFileNames() { + return fileNestedConsolidationData.keySet(); + } + + /** + * Gets file nested consolidation data. + * + * @param serviceTemplateFileName the service template file name + * @return the file nested consolidation data + */ + public FileNestedConsolidationData getFileNestedConsolidationData(String + serviceTemplateFileName) { + return fileNestedConsolidationData.get(serviceTemplateFileName); + } + + /** + * Sets file nested consolidation data. + * + * @param serviceTemplateFileName the service template file name + * @param fileNestedConsolidationData the file nested consolidation data + */ + public void setFileNestedConsolidationData(String serviceTemplateFileName, + FileNestedConsolidationData + fileNestedConsolidationData) { + this.fileNestedConsolidationData.put(serviceTemplateFileName, fileNestedConsolidationData); + } +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/NestedTemplateConsolidationData.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/NestedTemplateConsolidationData.java new file mode 100644 index 0000000000..b07c2039b8 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/NestedTemplateConsolidationData.java @@ -0,0 +1,11 @@ +package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation; + +import java.util.List; + + +/** + * The type nested template consolidation data. + */ +public class NestedTemplateConsolidationData extends EntityConsolidationData { + +} \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/PortConsolidationData.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/PortConsolidationData.java new file mode 100644 index 0000000000..5c1d38b6e4 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/PortConsolidationData.java @@ -0,0 +1,48 @@ +package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation; + +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +/** + * The type Port consolidation data. + */ +public class PortConsolidationData { + + //Key - Service template file name + private Map filePortConsolidationData; + + public PortConsolidationData() { + this.filePortConsolidationData = new HashMap<>(); + } + + /** + * Gets all files. + * + * @return the all files + */ + public Set getAllServiceTemplateFileNames() { + return filePortConsolidationData.keySet(); + } + + /** + * Gets file port consolidation data. + * + * @param serviceTemplateFileName the service template file name + * @return the file port consolidation data + */ + public FilePortConsolidationData getFilePortConsolidationData(String serviceTemplateFileName) { + return filePortConsolidationData.get(serviceTemplateFileName); + } + + /** + * Sets file port consolidation data. + * + * @param serviceTemplateFileName the service template file name + * @param filePortConsolidationData the file port consolidation data + */ + public void setFilePortConsolidationData(String serviceTemplateFileName, FilePortConsolidationData + filePortConsolidationData) { + this.filePortConsolidationData.put(serviceTemplateFileName, filePortConsolidationData); + } +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/PortTemplateConsolidationData.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/PortTemplateConsolidationData.java new file mode 100644 index 0000000000..c9b59f99db --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/PortTemplateConsolidationData.java @@ -0,0 +1,30 @@ +package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation; + +import java.util.List; + + +/** + * The type Port template consolidation data. + */ +public class PortTemplateConsolidationData extends EntityConsolidationData { + + private List subPortIds; //sub ports which point to this port + + /** + * Gets sub port ids. + * + * @return the sub port ids + */ + public List getSubPortIds() { + return subPortIds; + } + + /** + * Sets sub port ids. + * + * @param subPortIds the sub port ids + */ + public void setSubPortIds(List subPortIds) { + this.subPortIds = subPortIds; + } +} \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/RequirementAssignmentData.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/RequirementAssignmentData.java new file mode 100644 index 0000000000..a2fffd5a3b --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/RequirementAssignmentData.java @@ -0,0 +1,60 @@ +package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation; + +import org.openecomp.sdc.tosca.datatypes.model.RequirementAssignment; + +/** + * The type Requirement assignment data. + */ +public class RequirementAssignmentData { + + private String requirementId; + private RequirementAssignment requirementAssignment; + + /** + * Instantiates a new Requirement assignment data. + * + * @param requirementId the requirement id + * @param requirementAssignment the requirement assignment + */ + public RequirementAssignmentData(String requirementId, RequirementAssignment + requirementAssignment) { + this.requirementId = requirementId; + this.requirementAssignment = requirementAssignment; + } + + /** + * Gets requirement id. + * + * @return the requirement id + */ + public String getRequirementId() { + return requirementId; + } + + /** + * Sets requirement id. + * + * @param requirementId the requirement id + */ + public void setRequirementId(String requirementId) { + this.requirementId = requirementId; + } + + /** + * Gets requirement assignment. + * + * @return the requirement assignment + */ + public RequirementAssignment getRequirementAssignment() { + return requirementAssignment; + } + + /** + * Sets requirement assignment. + * + * @param requirementAssignment the requirement assignment + */ + public void setRequirementAssignment(RequirementAssignment requirementAssignment) { + this.requirementAssignment = requirementAssignment; + } +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/TypeComputeConsolidationData.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/TypeComputeConsolidationData.java new file mode 100644 index 0000000000..c95db52b95 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/datatypes/heattotosca/unifiedmodel/consolidation/TypeComputeConsolidationData.java @@ -0,0 +1,59 @@ +package org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation; + +import java.util.Collection; +import java.util.HashMap; +import java.util.Map; +import java.util.Set; + +/** + * The type Type compute consolidation data. + */ +public class TypeComputeConsolidationData { + + //key - compute node template id + private Map computeTemplateConsolidationData; + + /** + * Instantiates a new Type compute consolidation data. + */ + public TypeComputeConsolidationData() { + computeTemplateConsolidationData = new HashMap<>(); + } + + /** + * Gets all compute node template ids. + * + * @return the all compute node template ids + */ + public Set getAllComputeNodeTemplateIds() { + return computeTemplateConsolidationData.keySet(); + } + + public Collection getAllComputeTemplateConsolidationData(){ + return computeTemplateConsolidationData.values(); + } + + /** + * Gets compute template consolidation data. + * + * @param computeNodeTemplateId the compute node template id + * @return the compute template consolidation data + */ + public ComputeTemplateConsolidationData getComputeTemplateConsolidationData( + String computeNodeTemplateId) { + return computeTemplateConsolidationData.get(computeNodeTemplateId); + } + + /** + * Sets compute template consolidation data. + * + * @param computeNodeTemplateId the compute node template id + * @param computeTemplateConsolidationData the compute template consolidation data + */ + public void setComputeTemplateConsolidationData(String computeNodeTemplateId, + ComputeTemplateConsolidationData + computeTemplateConsolidationData) { + this.computeTemplateConsolidationData.put(computeNodeTemplateId, + computeTemplateConsolidationData); + } +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/impl/heattotosca/HeatToToscaTranslatorFactoryImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/impl/heattotosca/HeatToToscaTranslatorFactoryImpl.java index 57f753f103..fe2286c912 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/impl/heattotosca/HeatToToscaTranslatorFactoryImpl.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/impl/heattotosca/HeatToToscaTranslatorFactoryImpl.java @@ -23,6 +23,7 @@ package org.openecomp.sdc.translator.impl.heattotosca; import org.openecomp.core.translator.api.HeatToToscaTranslator; import org.openecomp.core.translator.factory.HeatToToscaTranslatorFactory; + public class HeatToToscaTranslatorFactoryImpl extends HeatToToscaTranslatorFactory { private static HeatToToscaTranslator INSTANCE = new HeatToToscaTranslatorImpl(); diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/impl/heattotosca/HeatToToscaTranslatorImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/impl/heattotosca/HeatToToscaTranslatorImpl.java index 0a6986816c..e09be6cdd9 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/impl/heattotosca/HeatToToscaTranslatorImpl.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/impl/heattotosca/HeatToToscaTranslatorImpl.java @@ -21,22 +21,30 @@ package org.openecomp.sdc.translator.impl.heattotosca; import org.apache.commons.collections4.MapUtils; +import org.openecomp.config.api.Configuration; +import org.openecomp.config.api.ConfigurationManager; import org.openecomp.core.translator.api.HeatToToscaTranslator; import org.openecomp.core.translator.datatypes.TranslatorOutput; import org.openecomp.core.utilities.file.FileUtils; import org.openecomp.core.utilities.json.JsonUtil; import org.openecomp.core.validation.api.ValidationManager; -import org.openecomp.core.validation.errors.Messages; import org.openecomp.core.validation.factory.ValidationManagerFactory; -import org.openecomp.core.validation.types.MessageContainerUtil; -import org.openecomp.sdc.common.utils.AsdcCommon; +import org.openecomp.core.validation.util.MessageContainerUtil; +import org.openecomp.sdc.common.errors.Messages; +import org.openecomp.sdc.common.utils.SdcCommon; +import org.openecomp.sdc.datatypes.configuration.ImplementationConfiguration; import org.openecomp.sdc.datatypes.error.ErrorLevel; import org.openecomp.sdc.datatypes.error.ErrorMessage; import org.openecomp.sdc.heat.datatypes.manifest.FileData; import org.openecomp.sdc.heat.datatypes.manifest.ManifestContent; import org.openecomp.sdc.heat.datatypes.manifest.ManifestFile; -import org.openecomp.sdc.translator.services.heattotosca.TranslationContext; +import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel; +import org.openecomp.sdc.translator.datatypes.heattotosca.TranslationContext; +import org.openecomp.sdc.translator.services.heattotosca.ConfigConstants; +import org.openecomp.sdc.translator.services.heattotosca.ConsolidationService; import org.openecomp.sdc.translator.services.heattotosca.TranslationService; +import org.openecomp.sdc.translator.services.heattotosca.UnifiedCompositionManager; +import org.openecomp.sdc.translator.services.heattotosca.UnifiedCompositionService; import java.io.InputStream; import java.util.HashMap; @@ -59,7 +67,7 @@ public class HeatToToscaTranslatorImpl implements HeatToToscaTranslator { manifest.setContent(manifestData); translationContext.setManifest(manifest); translationContext.addFile(name, content); - validationManager.addFile(AsdcCommon.MANIFEST_NAME, content); + validationManager.addFile(SdcCommon.MANIFEST_NAME, content); addFilesFromManifestToTranslationContextManifestFilesMap(manifestData.getData()); isValid = false; } @@ -82,7 +90,7 @@ public class HeatToToscaTranslatorImpl implements HeatToToscaTranslator { Map> errors = new HashMap<>(); if (translationContext.getManifest() == null) { - ErrorMessage.ErrorMessageUtil.addMessage(AsdcCommon.MANIFEST_NAME, errors) + ErrorMessage.ErrorMessageUtil.addMessage(SdcCommon.MANIFEST_NAME, errors) .add(new ErrorMessage(ErrorLevel.ERROR, Messages.MANIFEST_NOT_EXIST.getErrorMessage())); return errors; } @@ -90,7 +98,7 @@ public class HeatToToscaTranslatorImpl implements HeatToToscaTranslator { if (MapUtils.isEmpty(errors)) { errors = validationManager.validate(); } - if (MapUtils.isEmpty(errors)) { + if (MapUtils.isEmpty(MessageContainerUtil.getMessageByLevel(ErrorLevel.ERROR, errors))) { isValid = true; } return errors; @@ -100,6 +108,8 @@ public class HeatToToscaTranslatorImpl implements HeatToToscaTranslator { public TranslatorOutput translate() { TranslationService translationService = new TranslationService(); TranslatorOutput translatorOutput = new TranslatorOutput(); + UnifiedCompositionManager unifiedCompositionManager = new UnifiedCompositionManager(new + ConsolidationService(new UnifiedCompositionService())); if (!isValid) { Map> errors = validate(); @@ -110,6 +120,9 @@ public class HeatToToscaTranslatorImpl implements HeatToToscaTranslator { } translatorOutput = translationService.translateHeatFiles(translationContext); + ToscaServiceModel unifiedToscaServiceModel = unifiedCompositionManager + .createUnifiedComposition(translatorOutput.getToscaServiceModel(), translationContext); + translatorOutput.setToscaServiceModel(unifiedToscaServiceModel); return translatorOutput; } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ConfigConstants.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ConfigConstants.java new file mode 100644 index 0000000000..f6918e382b --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ConfigConstants.java @@ -0,0 +1,49 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.translator.services.heattotosca; + +public class ConfigConstants { + //namespaces + public static final String MANDATORY_TRANSLATOR_NAMESPACE = "mandatoryHeatToToscaTranslator"; + public static final String MANDATORY_UNIFIED_MODEL_NAMESPACE = "mandatoryUnifiedModel"; + public static final String TRANSLATOR_NAMESPACE = "heatToToscaTranslator"; + public static final String MAPPING_NAMESPACE = "heatToToscaMapping"; + + //keys + public static final String RESOURCE_TRANSLATION_IMPL_KEY = "resourceTranslationImpl"; + public static final String NESTED_RESOURCE_TRANSLATION_IMPL_KEY = "NestedResource"; + public static final String DEFAULT_RESOURCE_TRANSLATION_IMPL_KEY = "DefaultResource"; + public static final String FUNCTION_TRANSLATION_IMPL_KEY = "functionTranslationImpl"; + public static final String NAMING_CONVENTION_EXTRACTOR_IMPL_KEY = "namingConventionExtractImpl"; + public static final String UNIFIED_COMPOSITION_IMPL_KEY = "unifiedCompositionImpl"; + public static final String CONTRAIL_COMPUTE_NODE_TYPE_IMPL_KEY = "ContrailComputeNodeTypeName"; + public static final String RESOURCE_MAPPING_KEY = "resourceMapping"; + public static final String SUPPORTED_CONSOLIDATION_COMPUTE_RESOURCES_KEY = + "supportedConsolidationComputeResources"; + public static final String SUPPORTED_CONSOLIDATION_PORT_RESOURCES_KEY = + "supportedConsolidationPortResources"; + + //others + public static final String TRANS_MAPPING_DELIMITER_CHAR = "#"; + + private ConfigConstants() { + } +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ConsolidationDataUtil.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ConsolidationDataUtil.java new file mode 100644 index 0000000000..a89d08bcf6 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ConsolidationDataUtil.java @@ -0,0 +1,621 @@ +package org.openecomp.sdc.translator.services.heattotosca; + +import org.apache.commons.collections4.MapUtils; +import org.apache.commons.lang3.math.NumberUtils; +import org.openecomp.sdc.datatypes.configuration.ImplementationConfiguration; +import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate; +import org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes; +import org.openecomp.sdc.heat.datatypes.model.Resource; +import org.openecomp.sdc.logging.api.Logger; +import org.openecomp.sdc.logging.api.LoggerFactory; +import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; +import org.openecomp.sdc.tosca.datatypes.model.RequirementAssignment; +import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; +import org.openecomp.sdc.tosca.services.DataModelUtil; +import org.openecomp.sdc.tosca.services.ToscaUtil; +import org.openecomp.sdc.translator.datatypes.heattotosca.TranslationContext; +import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.ComputeConsolidationData; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.ComputeTemplateConsolidationData; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.ConsolidationData; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.EntityConsolidationData; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.FileComputeConsolidationData; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.FileNestedConsolidationData; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.FilePortConsolidationData; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.GetAttrFuncData; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.NestedConsolidationData; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.NestedTemplateConsolidationData; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.PortConsolidationData; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.PortTemplateConsolidationData; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.RequirementAssignmentData; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.TypeComputeConsolidationData; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.Iterator; +import java.util.List; +import java.util.Map; +import java.util.Objects; + + +/** + * Utility class for consolidation data collection helper methods. + */ +public class ConsolidationDataUtil { + + protected static Logger logger = (Logger) LoggerFactory.getLogger(ConsolidationDataUtil.class); + + /** + * Gets compute template consolidation data. + * + * @param context the translation context + * @param serviceTemplate the service template + * @param computeNodeType the compute node type + * @param computeNodeTemplateId the compute node template id + * @return the compute template consolidation data + */ + public static ComputeTemplateConsolidationData getComputeTemplateConsolidationData( + TranslationContext context, + ServiceTemplate serviceTemplate, + String computeNodeType, + String computeNodeTemplateId) { + + ConsolidationData consolidationData = context.getConsolidationData(); + String serviceTemplateFileName = ToscaUtil.getServiceTemplateFileName(serviceTemplate); + + ComputeConsolidationData computeConsolidationData = consolidationData + .getComputeConsolidationData(); + + FileComputeConsolidationData fileComputeConsolidationData = computeConsolidationData + .getFileComputeConsolidationData(serviceTemplateFileName); + + if (fileComputeConsolidationData == null) { + fileComputeConsolidationData = new FileComputeConsolidationData(); + computeConsolidationData.setFileComputeConsolidationData(serviceTemplateFileName, + fileComputeConsolidationData); + } + + TypeComputeConsolidationData typeComputeConsolidationData = fileComputeConsolidationData + .getTypeComputeConsolidationData(computeNodeType); + if (typeComputeConsolidationData == null) { + typeComputeConsolidationData = new TypeComputeConsolidationData(); + fileComputeConsolidationData.setTypeComputeConsolidationData(computeNodeType, + typeComputeConsolidationData); + } + + ComputeTemplateConsolidationData computeTemplateConsolidationData = + typeComputeConsolidationData.getComputeTemplateConsolidationData(computeNodeTemplateId); + if (computeTemplateConsolidationData == null) { + computeTemplateConsolidationData = new ComputeTemplateConsolidationData(); + computeTemplateConsolidationData.setNodeTemplateId(computeNodeTemplateId); + typeComputeConsolidationData.setComputeTemplateConsolidationData(computeNodeTemplateId, + computeTemplateConsolidationData); + } + + return computeTemplateConsolidationData; + } + + + /** + * Gets port template consolidation data. + * + * @param context the context + * @param serviceTemplate the service template + * @param portNodeTemplateId the port node template id + * @return the port template consolidation data + */ + public static PortTemplateConsolidationData getPortTemplateConsolidationData( + TranslationContext context, + ServiceTemplate serviceTemplate, + String portNodeTemplateId) { + + ConsolidationData consolidationData = context.getConsolidationData(); + String serviceTemplateFileName = ToscaUtil.getServiceTemplateFileName(serviceTemplate); + + PortConsolidationData portConsolidationData = consolidationData.getPortConsolidationData(); + + FilePortConsolidationData filePortConsolidationData = portConsolidationData + .getFilePortConsolidationData(serviceTemplateFileName); + + if (filePortConsolidationData == null) { + filePortConsolidationData = new FilePortConsolidationData(); + portConsolidationData.setFilePortConsolidationData(serviceTemplateFileName, + filePortConsolidationData); + } + + PortTemplateConsolidationData portTemplateConsolidationData = + filePortConsolidationData.getPortTemplateConsolidationData(portNodeTemplateId); + if (portTemplateConsolidationData == null) { + portTemplateConsolidationData = new PortTemplateConsolidationData(); + portTemplateConsolidationData.setNodeTemplateId(portNodeTemplateId); + filePortConsolidationData.setPortTemplateConsolidationData(portNodeTemplateId, + portTemplateConsolidationData); + } + + return portTemplateConsolidationData; + } + + + /** + * Gets nested template consolidation data. + * + * @param context the context + * @param serviceTemplate the service template + * @param nestedNodeTemplateId the nested node template id + * @return the nested template consolidation data + */ + public static NestedTemplateConsolidationData getNestedTemplateConsolidationData( + TranslationContext context, + ServiceTemplate serviceTemplate, + String nestedNodeTemplateId) { + + ConsolidationData consolidationData = context.getConsolidationData(); + String serviceTemplateFileName = ToscaUtil.getServiceTemplateFileName(serviceTemplate); + + NestedConsolidationData nestedConsolidationData = consolidationData + .getNestedConsolidationData(); + + FileNestedConsolidationData fileNestedConsolidationData = nestedConsolidationData + .getFileNestedConsolidationData(serviceTemplateFileName); + + if (fileNestedConsolidationData == null) { + fileNestedConsolidationData = new FileNestedConsolidationData(); + nestedConsolidationData.setFileNestedConsolidationData(serviceTemplateFileName, + fileNestedConsolidationData); + } + + NestedTemplateConsolidationData nestedTemplateConsolidationData = + fileNestedConsolidationData.getNestedTemplateConsolidationData(nestedNodeTemplateId); + if (nestedTemplateConsolidationData == null) { + nestedTemplateConsolidationData = new NestedTemplateConsolidationData(); + nestedTemplateConsolidationData.setNodeTemplateId(nestedNodeTemplateId); + fileNestedConsolidationData.setNestedTemplateConsolidationData(nestedNodeTemplateId, + nestedTemplateConsolidationData); + } + + return nestedTemplateConsolidationData; + } + + /** + * Update group id information in consolidation data. + * + * @param entityConsolidationData Entity consolidation data (Port/Compute) + * @param translatedGroupId Group id of which compute node is a part + */ + public static void updateGroupIdInConsolidationData(EntityConsolidationData + entityConsolidationData, + String translatedGroupId) { + if (entityConsolidationData.getGroupIds() == null) { + entityConsolidationData.setGroupIds(new ArrayList<>()); + } + entityConsolidationData.getGroupIds().add(translatedGroupId); + } + + /** + * Update volume information in consolidation data. + * + * @param translateTo {@link TranslateTo} object + * @param computeType Local type of the compute node + * @param computeNodeTemplateId Node template id of the compute node + * @param requirementAssignment RequirementAssignment object + */ + public static void updateComputeConsolidationDataVolumes(TranslateTo translateTo, + String computeType, + String computeNodeTemplateId, + String requirementId, + RequirementAssignment + requirementAssignment) { + TranslationContext translationContext = translateTo.getContext(); + ServiceTemplate serviceTemplate = translateTo.getServiceTemplate(); + ComputeTemplateConsolidationData computeTemplateConsolidationData = + getComputeTemplateConsolidationData(translationContext, serviceTemplate, computeType, + computeNodeTemplateId); + computeTemplateConsolidationData.addVolume(requirementId, requirementAssignment); + } + + + /** + * Update port in consolidation data. + * + * @param translateTo the translate to + * @param computeNodeType the compute node type + * @param portNodeTemplateId the port node template id + */ + public static void updatePortInConsolidationData(TranslateTo translateTo, + String computeNodeType, + String portNodeTemplateId) { + TranslationContext translationContext = translateTo.getContext(); + ServiceTemplate serviceTemplate = translateTo.getServiceTemplate(); + ComputeTemplateConsolidationData computeTemplateConsolidationData = + getComputeTemplateConsolidationData(translationContext, serviceTemplate, computeNodeType, + translateTo.getTranslatedId()); + computeTemplateConsolidationData.addPort(getPortType(portNodeTemplateId), portNodeTemplateId); + // create port in consolidation data + getPortTemplateConsolidationData(translationContext, serviceTemplate, portNodeTemplateId); + } + + /** + * Update nodes connected in and out for Depends on and connectivity in consolidation data. + * + * @param translateTo the translate to + * @param targetResourceId the target resource id + * @param nodeTemplateId the source node template id + * @param requirementAssignment the requirement assignment + */ + public static void updateNodesConnectedData(TranslateTo translateTo, String targetResourceId, + Resource targetResource, Resource sourceResource, + String nodeTemplateId, String requirementId, + RequirementAssignment requirementAssignment) { + ConsolidationEntityType consolidationEntityType = ConsolidationEntityType.OTHER; + HeatOrchestrationTemplate heatOrchestrationTemplate = translateTo + .getHeatOrchestrationTemplate(); + TranslationContext translationContext = translateTo.getContext(); + + consolidationEntityType.setEntityType(heatOrchestrationTemplate, sourceResource, + targetResource, translateTo.getContext()); + // Add resource dependency information in nodesConnectedIn if the target node + // is a consolidation entity + if (isConsolidationEntity(consolidationEntityType.getTargetEntityType()) + && HeatToToscaUtil + .isValidDependsOnCandidate(heatOrchestrationTemplate, sourceResource, + targetResource, consolidationEntityType, translationContext)) { + ConsolidationDataUtil.updateNodesConnectedIn(translateTo, + nodeTemplateId, consolidationEntityType.getTargetEntityType(), targetResourceId, + requirementId, requirementAssignment); + } + + //Add resource dependency information in nodesConnectedOut if the source node + //is a consolidation entity + if (isConsolidationEntity(consolidationEntityType.getSourceEntityType()) + && HeatToToscaUtil + .isValidDependsOnCandidate(heatOrchestrationTemplate, sourceResource, + targetResource, consolidationEntityType, translationContext)) { + ConsolidationDataUtil.updateNodesConnectedOut(translateTo, + requirementAssignment.getNode(), consolidationEntityType.getSourceEntityType(), + requirementId, requirementAssignment); + } + } + + + private static boolean isConsolidationEntity(ConsolidationEntityType consolidationEntityType) { + return (consolidationEntityType == ConsolidationEntityType.COMPUTE + || consolidationEntityType == ConsolidationEntityType.PORT + || consolidationEntityType == ConsolidationEntityType.NESTED + || consolidationEntityType == ConsolidationEntityType.VFC_NESTED); + } + + /** + * Update nodes connected from this node in consolidation data. + * + * @param translateTo the translate to + * @param nodeTemplateId the node template id of the target node + * @param consolidationEntityType the entity type (compute or port) + * @param requirementId the requirement id + * @param requirementAssignment the requirement assignment + */ + public static void updateNodesConnectedOut(TranslateTo translateTo, + String nodeTemplateId, + ConsolidationEntityType consolidationEntityType, + String requirementId, + RequirementAssignment requirementAssignment) { + EntityConsolidationData entityConsolidationData = null; + TranslationContext translationContext = translateTo.getContext(); + ServiceTemplate serviceTemplate = translateTo.getServiceTemplate(); + RequirementAssignmentData requirementAssignmentData = new RequirementAssignmentData( + requirementId, requirementAssignment); + + if (consolidationEntityType == ConsolidationEntityType.COMPUTE) { + String nodeType = DataModelUtil.getNodeTemplate(serviceTemplate, translateTo + .getTranslatedId()).getType(); + entityConsolidationData = getComputeTemplateConsolidationData(translationContext, + serviceTemplate, nodeType, translateTo.getTranslatedId()); + } else if (consolidationEntityType == ConsolidationEntityType.PORT) { + entityConsolidationData = getPortTemplateConsolidationData(translationContext, + serviceTemplate, translateTo.getTranslatedId()); + } else if (consolidationEntityType == ConsolidationEntityType.VFC_NESTED + || consolidationEntityType == ConsolidationEntityType.NESTED) { + //ConnectedOut data for nested is not updated + return; + } + + if (entityConsolidationData.getNodesConnectedOut() == null) { + entityConsolidationData.setNodesConnectedOut(new HashMap<>()); + } + + entityConsolidationData.getNodesConnectedOut() + .computeIfAbsent(nodeTemplateId, k -> new ArrayList<>()) + .add(requirementAssignmentData); + } + + /** + * Update nodes connected from this node in consolidation data. + * + * @param translateTo the translate to + * @param sourceNodeTemplateId the node template id of the source node + * @param consolidationEntityType Entity type (compute or port) + * @param requirementId Requirement Id + * @param requirementAssignment the requirement assignment + */ + public static void updateNodesConnectedIn(TranslateTo translateTo, String sourceNodeTemplateId, + ConsolidationEntityType consolidationEntityType, + String targetResourceId, + String requirementId, + RequirementAssignment requirementAssignment) { + EntityConsolidationData entityConsolidationData = null; + TranslationContext translationContext = translateTo.getContext(); + ServiceTemplate serviceTemplate = translateTo.getServiceTemplate(); + RequirementAssignmentData requirementAssignmentData = new RequirementAssignmentData( + requirementId, requirementAssignment); + String dependentNodeTemplateId = requirementAssignment.getNode(); + if (consolidationEntityType == ConsolidationEntityType.COMPUTE) { + NodeTemplate computeNodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, + dependentNodeTemplateId); + String nodeType = null; + if (Objects.isNull(computeNodeTemplate)) { + Resource targetResource = + translateTo.getHeatOrchestrationTemplate().getResources().get(targetResourceId); + NameExtractor nodeTypeNameExtractor = + translateTo.getContext().getNameExtractorImpl(targetResource.getType()); + nodeType = + nodeTypeNameExtractor.extractNodeTypeName(translateTo.getHeatOrchestrationTemplate() + .getResources().get(dependentNodeTemplateId), + dependentNodeTemplateId, dependentNodeTemplateId); + } else { + nodeType = computeNodeTemplate.getType(); + } + + entityConsolidationData = getComputeTemplateConsolidationData(translationContext, + serviceTemplate, nodeType, dependentNodeTemplateId); + } else if (consolidationEntityType == ConsolidationEntityType.PORT) { + entityConsolidationData = getPortTemplateConsolidationData(translationContext, + serviceTemplate, dependentNodeTemplateId); + } else if (consolidationEntityType == ConsolidationEntityType.NESTED + || consolidationEntityType == ConsolidationEntityType.VFC_NESTED) { + entityConsolidationData = getNestedTemplateConsolidationData(translationContext, + serviceTemplate, dependentNodeTemplateId); + } + + if (entityConsolidationData.getNodesConnectedIn() == null) { + entityConsolidationData.setNodesConnectedIn(new HashMap<>()); + } + + entityConsolidationData.getNodesConnectedIn() + .computeIfAbsent(sourceNodeTemplateId, k -> new ArrayList<>()) + .add(requirementAssignmentData); + + } + + /** + * Checks if the current HEAT resource if of type compute. + * + * @param heatOrchestrationTemplate the heat orchestration template + * @param resourceId the resource id + * @return true if the resource is of compute type and false otherwise + */ + public static boolean isComputeResource(HeatOrchestrationTemplate heatOrchestrationTemplate, + String resourceId) { + String resourceType = heatOrchestrationTemplate.getResources().get(resourceId).getType(); + Map supportedComputeResources = TranslationContext + .getSupportedConsolidationComputeResources(); + if (supportedComputeResources.containsKey(resourceType)) { + if (supportedComputeResources.get(resourceType).isEnable()) { + return true; + } + return false; + } + return false; + } + + /** + * Checks if the current HEAT resource if of type compute. + * + * @param resource the resource + * @return true if the resource is of compute type and false otherwise + */ + public static boolean isComputeResource(Resource resource) { + String resourceType = resource.getType(); + Map supportedComputeResources = TranslationContext + .getSupportedConsolidationComputeResources(); + if (supportedComputeResources.containsKey(resourceType)) { + if (supportedComputeResources.get(resourceType).isEnable()) { + return true; + } + return false; + } + return false; + } + + /** + * Checks if the current HEAT resource if of type port. + * + * @param heatOrchestrationTemplate the heat orchestration template + * @param resourceId the resource id + * @return true if the resource is of port type and false otherwise + */ + public static boolean isPortResource(HeatOrchestrationTemplate heatOrchestrationTemplate, + String resourceId) { + String resourceType = heatOrchestrationTemplate.getResources().get(resourceId).getType(); + Map supportedPortResources = TranslationContext + .getSupportedConsolidationPortResources(); + if (supportedPortResources.containsKey(resourceType)) { + if (supportedPortResources.get(resourceType).isEnable()) { + return true; + } + return false; + } + return false; + } + + /** + * Checks if the current HEAT resource if of type port. + * + * @param resource the resource + * @return true if the resource is of port type and false otherwise + */ + public static boolean isPortResource(Resource resource) { + String resourceType = resource.getType(); + Map supportedPortResources = TranslationContext + .getSupportedConsolidationPortResources(); + if (supportedPortResources.containsKey(resourceType)) { + if (supportedPortResources.get(resourceType).isEnable()) { + return true; + } + return false; + } + return false; + } + + /** + * Checks if the current HEAT resource if of type volume. + * + * @param heatOrchestrationTemplate the heat orchestration template + * @param resourceId the resource id + * @return true if the resource is of volume type and false otherwise + */ + public static boolean isVolumeResource(HeatOrchestrationTemplate heatOrchestrationTemplate, + String resourceId) { + String resourceType = heatOrchestrationTemplate.getResources().get(resourceId).getType(); + return (resourceType.equals(HeatResourcesTypes.CINDER_VOLUME_RESOURCE_TYPE.getHeatResource()) + || resourceType.equals(HeatResourcesTypes.CINDER_VOLUME_ATTACHMENT_RESOURCE_TYPE + .getHeatResource())); + } + + /** + * Checks if the current HEAT resource if of type volume. + * + * @param resource the resource + * @return true if the resource is of volume type and false otherwise + */ + public static boolean isVolumeResource(Resource resource) { + String resourceType = resource.getType(); + return (resourceType.equals(HeatResourcesTypes.CINDER_VOLUME_RESOURCE_TYPE.getHeatResource()) + || resourceType.equals(HeatResourcesTypes.CINDER_VOLUME_ATTACHMENT_RESOURCE_TYPE + .getHeatResource())); + } + + /** + * Gets port type. + * + * @param portNodeTemplateId the port node template id + * @return the port type + */ + public static String getPortType(String portNodeTemplateId) { + String[] portSplitArr = portNodeTemplateId.split("(?<=\\D)(?=\\d)|(?<=\\d)(?=\\D)"); + String finalValue = ""; + if (NumberUtils.isNumber(portSplitArr[portSplitArr.length - 1])) { + for (String id : portSplitArr) { + finalValue = finalValue + id; + } + while (finalValue.length() > 0) { + if (Character.isLetter(finalValue.charAt(finalValue.length() - 1))) { + break; + } + finalValue = finalValue.substring(0, finalValue.length() - 1); + } + } else { + for (String id : portSplitArr) { + if (!NumberUtils.isNumber(id)) { + finalValue = finalValue + id; + } + } + } + return finalValue; + } + + /** + * Update node template id for the nested node templates in the consolidation data. + * + * @param translateTo the translate to + */ + public static void updateNestedNodeTemplateId(TranslateTo translateTo) { + TranslationContext context = translateTo.getContext(); + ServiceTemplate serviceTemplate = translateTo.getServiceTemplate(); + getNestedTemplateConsolidationData(context, serviceTemplate, translateTo.getTranslatedId()); + } + + public static void removeSharedResource(ServiceTemplate serviceTemplate, + HeatOrchestrationTemplate heatOrchestrationTemplate, + TranslationContext context, + String paramName, + String contrailSharedResourceId, + String sharedTranslatedResourceId) { + if (ConsolidationDataUtil.isComputeResource(heatOrchestrationTemplate, + contrailSharedResourceId)) { + NodeTemplate nodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, + sharedTranslatedResourceId); + EntityConsolidationData entityConsolidationData = getComputeTemplateConsolidationData( + context, serviceTemplate, nodeTemplate.getType(), sharedTranslatedResourceId); + List getAttrFuncDataList = entityConsolidationData + .getOutputParametersGetAttrIn(); + removeParamNameFromAttrFuncList(paramName, getAttrFuncDataList); + } + if (ConsolidationDataUtil.isPortResource(heatOrchestrationTemplate, + contrailSharedResourceId)) { + NodeTemplate nodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, + sharedTranslatedResourceId); + EntityConsolidationData entityConsolidationData = getPortTemplateConsolidationData(context, + serviceTemplate, sharedTranslatedResourceId); + List getAttrFuncDataList = entityConsolidationData + .getOutputParametersGetAttrIn(); + removeParamNameFromAttrFuncList(paramName, getAttrFuncDataList); + } + } + + private static void removeParamNameFromAttrFuncList(String paramName, + List getAttrFuncDataList) { + Iterator itr = getAttrFuncDataList.iterator(); + while (itr.hasNext()) { + GetAttrFuncData getAttrFuncData = itr.next(); + if (paramName.equals(getAttrFuncData.getFieldName())) { + itr.remove(); + } + } + } + + public static void updateNodeGetAttributeIn(EntityConsolidationData entityConsolidationData, + String nodeTemplateId, String propertyName, + String attributeName) { + GetAttrFuncData getAttrFuncData = new GetAttrFuncData(); + getAttrFuncData.setFieldName(propertyName); + getAttrFuncData.setAttributeName(attributeName); + entityConsolidationData.addNodesGetAttrIn(nodeTemplateId, getAttrFuncData); + + } + + public static void updateNodeGetAttributeOut(EntityConsolidationData entityConsolidationData, + String nodeTemplateId, String propertyName, + String attributeName) { + GetAttrFuncData getAttrFuncData = new GetAttrFuncData(); + getAttrFuncData.setFieldName(propertyName); + getAttrFuncData.setAttributeName(attributeName); + entityConsolidationData.addNodesGetAttrOut(nodeTemplateId, getAttrFuncData); + + } + + public static void updateOutputGetAttributeInConsolidationData(EntityConsolidationData + entityConsolidationData, + String outputParameterName, + String attributeName) { + + + GetAttrFuncData getAttrFuncData = new GetAttrFuncData(); + getAttrFuncData.setFieldName(outputParameterName); + getAttrFuncData.setAttributeName(attributeName); + entityConsolidationData.addOutputParamGetAttrIn(getAttrFuncData); + + } + + public static boolean isComputeReferenceToPortId(ComputeTemplateConsolidationData compute, + String portId) { + if (MapUtils.isEmpty(compute.getPorts())) { + return false; + } + for (List portIdsPerType : compute.getPorts().values()) { + if (portIdsPerType.contains(portId)) { + return true; + } + } + return false; + } + +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ConsolidationEntityType.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ConsolidationEntityType.java new file mode 100644 index 0000000000..c2de58fd5a --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ConsolidationEntityType.java @@ -0,0 +1,86 @@ +package org.openecomp.sdc.translator.services.heattotosca; + +import static org.openecomp.sdc.translator.services.heattotosca.ConsolidationDataUtil.isComputeResource; +import static org.openecomp.sdc.translator.services.heattotosca.ConsolidationDataUtil.isPortResource; +import static org.openecomp.sdc.translator.services.heattotosca.ConsolidationDataUtil.isVolumeResource; + +import org.apache.commons.lang3.ObjectUtils; +import org.openecomp.core.utilities.yaml.YamlUtil; +import org.openecomp.sdc.heat.datatypes.manifest.FileData; +import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate; +import org.openecomp.sdc.heat.datatypes.model.Resource; +import org.openecomp.sdc.translator.datatypes.heattotosca.TranslationContext; + +import java.util.Collection; +import java.util.Objects; +import java.util.Optional; + +/** + * The enum Entity type. + */ +public enum ConsolidationEntityType { + COMPUTE, + PORT, + VOLUME, + NESTED, + VFC_NESTED, + SUB_PORT, + OTHER; + + private ConsolidationEntityType sourceEntityType; + private ConsolidationEntityType targetEntityType; + + public ConsolidationEntityType getSourceEntityType() { + return sourceEntityType; + } + + public ConsolidationEntityType getTargetEntityType() { + return targetEntityType; + } + + /** + * Sets entity type. + * + * @param heatOrchestrationTemplate the heat orchestration template + * @param sourceResource the source resource + * @param targetResource the target resource + */ + public void setEntityType(HeatOrchestrationTemplate heatOrchestrationTemplate, + Resource sourceResource, + Resource targetResource, + TranslationContext context) { + targetEntityType = + getEntityType(heatOrchestrationTemplate, targetResource, context); + sourceEntityType = + getEntityType(heatOrchestrationTemplate, sourceResource, context); + } + + private ConsolidationEntityType getEntityType(HeatOrchestrationTemplate heatOrchestrationTemplate, + Resource resource, TranslationContext context) { + if (isComputeResource(resource)) { + return ConsolidationEntityType.COMPUTE; + } else if (isPortResource(resource)) { + return ConsolidationEntityType.PORT; + } else if (isVolumeResource(resource)) { + return ConsolidationEntityType.VOLUME; + } else if (HeatToToscaUtil.isNestedResource(resource)) { + Optional nestedHeatFileName = HeatToToscaUtil.getNestedHeatFileName(resource); + if (nestedHeatFileName.isPresent()) { + HeatOrchestrationTemplate nestedHeatOrchestrationTemplate = new YamlUtil() + .yamlToObject(context.getFileContent(nestedHeatFileName.get()), + HeatOrchestrationTemplate.class); + if (Objects.nonNull(nestedHeatOrchestrationTemplate.getResources())) { + for (String innerResourceId : nestedHeatOrchestrationTemplate.getResources().keySet()) { + if (ConsolidationDataUtil + .isComputeResource(nestedHeatOrchestrationTemplate, innerResourceId)) { + return ConsolidationEntityType.VFC_NESTED; + } + } + } + } + return ConsolidationEntityType.NESTED; + } else { + return ConsolidationEntityType.OTHER; + } + } +} \ No newline at end of file diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ConsolidationService.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ConsolidationService.java new file mode 100644 index 0000000000..607dc36c4b --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ConsolidationService.java @@ -0,0 +1,937 @@ +package org.openecomp.sdc.translator.services.heattotosca; + +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.collections4.MapUtils; +import org.openecomp.sdc.common.errors.CoreException; +import org.openecomp.sdc.common.errors.ErrorCode; +import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; +import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; +import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; +import org.openecomp.sdc.tosca.services.ToscaConstants; +import org.openecomp.sdc.tosca.services.ToscaUtil; +import org.openecomp.sdc.translator.datatypes.heattotosca.TranslationContext; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.composition.UnifiedCompositionData; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.composition.UnifiedCompositionMode; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.ComputeTemplateConsolidationData; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.ConsolidationData; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.EntityConsolidationData; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.FileComputeConsolidationData; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.FileNestedConsolidationData; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.FilePortConsolidationData; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.GetAttrFuncData; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.NestedTemplateConsolidationData; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.PortTemplateConsolidationData; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.RequirementAssignmentData; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.TypeComputeConsolidationData; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.Collections; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; + +public class ConsolidationService { + + private MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); + private UnifiedCompositionService unifiedCompositionService; + + public ConsolidationService(UnifiedCompositionService unifiedCompositionService) { + this.unifiedCompositionService = unifiedCompositionService; + } + + ConsolidationService() { + + } + + void mainServiceTemplateConsolidation(ServiceTemplate serviceTemplate, + TranslationContext translationContext) { + + ConsolidationData consolidationData = translationContext.getConsolidationData(); + + FileComputeConsolidationData fileComputeConsolidationData = + consolidationData.getComputeConsolidationData() + .getFileComputeConsolidationData(ToscaUtil.getServiceTemplateFileName(serviceTemplate)); + + if (Objects.isNull(fileComputeConsolidationData)) { + return; + } + for (TypeComputeConsolidationData typeComputeConsolidationData : + fileComputeConsolidationData.getAllTypeComputeConsolidationData()) { + boolean preConditionResult = + consolidationPreCondition( + serviceTemplate, consolidationData, typeComputeConsolidationData); + + List unifiedCompositionDataList = + createUnifiedCompositionDataList( + serviceTemplate, consolidationData, typeComputeConsolidationData); + + if (preConditionResult) { + boolean consolidationRuleCheckResult = + checkConsolidationRules(serviceTemplate, typeComputeConsolidationData, + consolidationData); + + unifiedCompositionService.createUnifiedComposition( + serviceTemplate, null, unifiedCompositionDataList, + consolidationRuleCheckResult ? UnifiedCompositionMode.ScalingInstances + : UnifiedCompositionMode.CatalogInstance, + translationContext); + } else { + unifiedCompositionService.createUnifiedComposition( + serviceTemplate, null, unifiedCompositionDataList, UnifiedCompositionMode + .SingleSubstitution, + translationContext); + } + } + + } + + private Map getConsolidationEntityIdToType(ServiceTemplate serviceTemplate, + ConsolidationData consolidationData) { + Map consolidationEntityIdToType = new HashMap<>(); + + String serviceTemplateFileName = ToscaUtil.getServiceTemplateFileName(serviceTemplate); + FileComputeConsolidationData fileComputeConsolidationData = + consolidationData.getComputeConsolidationData() + .getFileComputeConsolidationData(serviceTemplateFileName); + FilePortConsolidationData filePortConsolidationData = + consolidationData.getPortConsolidationData() + .getFilePortConsolidationData(serviceTemplateFileName); + + for (String computeType : fileComputeConsolidationData.getAllComputeTypes()) { + TypeComputeConsolidationData typeComputeConsolidationData = + fileComputeConsolidationData.getTypeComputeConsolidationData(computeType); + Set computeNodeTemplateIds = + typeComputeConsolidationData.getAllComputeNodeTemplateIds(); + for (String computeNodeTemplateId : computeNodeTemplateIds) { + consolidationEntityIdToType.put(computeNodeTemplateId, computeType); + } + } + + Set portNodeTemplateIds = filePortConsolidationData.getAllPortNodeTemplateIds(); + for (String portNodeTemplateId : portNodeTemplateIds) { + consolidationEntityIdToType + .put(portNodeTemplateId, ConsolidationDataUtil.getPortType(portNodeTemplateId)); + } + + return consolidationEntityIdToType; + } + + + private boolean checkConsolidationRules(ServiceTemplate serviceTemplate, + TypeComputeConsolidationData typeComputeConsolidationData, + ConsolidationData consolidationData) { + return checkComputeConsolidation(serviceTemplate, typeComputeConsolidationData) + && checkPortConsolidation(serviceTemplate, typeComputeConsolidationData, consolidationData) + && !checkGetAttrBetweenEntityConsolidationOfTheSameType(serviceTemplate, + typeComputeConsolidationData, consolidationData); + } + + private boolean checkGetAttrBetweenConsolidationDataEntitiesNotFromSameType( + ServiceTemplate serviceTemplate, + TypeComputeConsolidationData typeComputeConsolidationData, + ConsolidationData consolidationData) { + List computeTemplateConsolidationDataList = + new ArrayList(typeComputeConsolidationData.getAllComputeTemplateConsolidationData()); + + Set computeNodeTemplateIds = + typeComputeConsolidationData.getAllComputeNodeTemplateIds(); + + Map> portTypeToIds = UnifiedCompositionUtil + .collectAllPortsFromEachTypesFromComputes(computeTemplateConsolidationDataList); + + return + checkGetAttrOutFromEntityToPortIsLegal(computeTemplateConsolidationDataList, portTypeToIds) + && checkGetAttrOutFromPortLegal(ToscaUtil.getServiceTemplateFileName(serviceTemplate), + computeNodeTemplateIds, portTypeToIds, consolidationData); + + } + + private boolean checkGetAttrInEntityConsolidationWithPortIsLegal( + List entityConsolidationDatas, + TypeComputeConsolidationData typeComputeConsolidationData) { + Map> portTypeToIds = + UnifiedCompositionUtil.collectAllPortsFromEachTypesFromComputes( + typeComputeConsolidationData.getAllComputeTemplateConsolidationData()); + + Set startingPortTypesPointByGetAttr = + getPortTypesPointedByGetAttrFromEntity( + (EntityConsolidationData) entityConsolidationDatas.get(0), portTypeToIds); + + for (int i = 1; i < entityConsolidationDatas.size(); i++) { + Set currentPortTypesPointByGetAttr = + getPortTypesPointedByGetAttrFromEntity( + (EntityConsolidationData) entityConsolidationDatas.get(i), portTypeToIds); + if (!startingPortTypesPointByGetAttr.equals(currentPortTypesPointByGetAttr)) { + return false; + } + } + + return true; + } + + private Set getPortTypesPointedByGetAttrFromEntity( + EntityConsolidationData entity, + Map> portTypeToIds) { + return getPortTypeToIdPointByGetAttrInOrOut( + entity.getNodesGetAttrIn(), portTypeToIds, entity).keySet(); + } + + private boolean checkGetAttrInToPortIsLegal( + ServiceTemplate serviceTemplate, + TypeComputeConsolidationData typeComputeConsolidationData, + ConsolidationData consolidationData) { + + Map> portTypeToIds = UnifiedCompositionUtil + .collectAllPortsFromEachTypesFromComputes( + typeComputeConsolidationData.getAllComputeTemplateConsolidationData()); + + for (Set portIdsFromSameType : portTypeToIds.values()) { + List portTemplateConsolidationDataList = + collectAllPortsTemplateConsolidationData( + portIdsFromSameType, ToscaUtil.getServiceTemplateFileName(serviceTemplate), + consolidationData); + + if (!checkGetAttrInEntityConsolidationWithPortIsLegal( + portTemplateConsolidationDataList, typeComputeConsolidationData)) { + return false; + } + } + + return true; + } + + + private boolean checkGetAttrOutFromPortLegal(String serviceTemplateName, + Set computeNodeTemplateIds, + Map> portTypeToIds, + ConsolidationData consolidationData) { + for (Set portIdsFromSameType : portTypeToIds.values()) { + List portTemplateConsolidationDataList = + collectAllPortsTemplateConsolidationData(portIdsFromSameType, serviceTemplateName, + consolidationData); + + if (!(checkGetAttrOutFromEntityToPortIsLegal(portTemplateConsolidationDataList, portTypeToIds) + && checkGetAttrOutFromPortToComputeIsLegal(portTemplateConsolidationDataList, + computeNodeTemplateIds))) { + return false; + } + } + + return true; + } + + private boolean checkGetAttrOutFromEntityToPortIsLegal(List entityConsolidationDataList, + Map> portTypeToIds) { + + for (String portType : portTypeToIds.keySet()) { + Set startingGetAttrFunc = + getEntityGetAttrFuncAsSet(portType, + (EntityConsolidationData) entityConsolidationDataList.get(0)); + for (int i = 1; i < entityConsolidationDataList.size(); i++) { + Object entity = entityConsolidationDataList.get(i); + Set currentGetAttrFuncData = + getEntityGetAttrFuncAsSet(portType, + (EntityConsolidationData) entity); + if (!(startingGetAttrFunc.equals(currentGetAttrFuncData))) { + return false; + } + } + } + + return true; + } + + private boolean checkGetAttrOutFromPortToComputeIsLegal( + List portTemplateConsolidationDataList, + Set computeNodeTemplateIds) { + PortTemplateConsolidationData startingPortTemplate = + portTemplateConsolidationDataList.get(0); + Map> startingComputeGetAttrOutFuncData = + getComputeGetAttrOutFuncData(startingPortTemplate.getNodesGetAttrOut(), + computeNodeTemplateIds); + + for (int i = 1; i < portTemplateConsolidationDataList.size(); i++) { + PortTemplateConsolidationData currentPortTemplate = + portTemplateConsolidationDataList.get(i); + Map> currentComputeGetAttrOutFuncData = + getComputeGetAttrOutFuncData(currentPortTemplate.getNodesGetAttrOut(), + computeNodeTemplateIds); + + if (!isGetAttrRelationToComputeSimilarBetweenEntities(startingComputeGetAttrOutFuncData, + currentComputeGetAttrOutFuncData)) { + return false; + } + } + + return true; + } + + private boolean isGetAttrRelationToComputeSimilarBetweenEntities( + Map> firstMap, + Map> secondMap) { + if (MapUtils.isEmpty(firstMap) != MapUtils.isEmpty(secondMap)) { + return false; + } + + if (MapUtils.isEmpty(firstMap) && MapUtils.isEmpty(secondMap)) { + return true; + } + + return new ArrayList<>(firstMap.values()).equals(new ArrayList<>(secondMap.values())); + } + + private Set getEntityGetAttrFuncAsSet(String portType, + EntityConsolidationData entityConsolidationData) { + + Set getAttrFuncDataFromPortsWithSameType = new HashSet<>(); + Map> nodesGetAttrOut = + entityConsolidationData.getNodesGetAttrOut(); + + if (MapUtils.isEmpty(nodesGetAttrOut)) { + return getAttrFuncDataFromPortsWithSameType; + } + + for (Map.Entry> entry : nodesGetAttrOut.entrySet()) { + if (portType.equals(ConsolidationDataUtil.getPortType(entry.getKey()))) { + getAttrFuncDataFromPortsWithSameType.addAll(entry.getValue()); + } + } + + return getAttrFuncDataFromPortsWithSameType; + } + + private Map> getComputeGetAttrOutFuncData( + Map> nodesGetAttrOut, + Set computeNodeTemplateIds) { + Map> computeGetAttrFuncData = new HashMap<>(); + + if (MapUtils.isEmpty(nodesGetAttrOut)) { + return computeGetAttrFuncData; + } + + for (Map.Entry> getAttrFuncEntry : nodesGetAttrOut.entrySet()) { + if (computeNodeTemplateIds.contains(getAttrFuncEntry.getKey())) { + computeGetAttrFuncData.put(getAttrFuncEntry.getKey(), new HashSet<>(getAttrFuncEntry + .getValue())); + } + } + + return computeGetAttrFuncData; + } + + private Map> getPortTypeToIdPointByGetAttrInOrOut( + Map> getAttr, + Map> portTypeToIds, + EntityConsolidationData entityConsolidationData) { + Map> portIdToType = new HashMap<>(); + + if (MapUtils.isEmpty(getAttr)) { + return portIdToType; + } + + for (String getAttrId : getAttr.keySet()) { + if (isNodeTemplateIdIsInComputeConsolidationData(getAttrId, portTypeToIds)) { + String portType = ConsolidationDataUtil.getPortType(getAttrId); + portIdToType.putIfAbsent(portType, new ArrayList<>()); + portIdToType.get(portType).add(getAttrId); + } + } + + return portIdToType; + + } + + + private boolean isNodeTemplateIdIsInComputeConsolidationData( + String getAttrInId, + Map> portTypeToIds) { + return portTypeToIds.keySet().contains(ConsolidationDataUtil.getPortType(getAttrInId)); + } + + private boolean checkGetAttrBetweenEntityConsolidationOfTheSameType( + ServiceTemplate serviceTemplate, + TypeComputeConsolidationData typeComputeConsolidationData, + ConsolidationData consolidationData) { + return checkGetAttrRelationsBetweenComputesOfSameType(typeComputeConsolidationData) + || checkGetAttrRelationsBetweenPortsOfTheSameType(serviceTemplate, + typeComputeConsolidationData, consolidationData); + + } + + private boolean checkGetAttrRelationsBetweenComputesOfSameType( + TypeComputeConsolidationData typeComputeConsolidationData) { + + Collection computeTemplateConsolidationDatas = + typeComputeConsolidationData.getAllComputeTemplateConsolidationData(); + Set computeNodeTemplateIds = + typeComputeConsolidationData.getAllComputeNodeTemplateIds(); + + return checkGetAttrRelationsForEntityConsolidationData( + computeTemplateConsolidationDatas, computeNodeTemplateIds); + } + + private boolean checkGetAttrRelationsBetweenPortsOfTheSameType( + ServiceTemplate serviceTemplate, + TypeComputeConsolidationData typeComputeConsolidationData, + ConsolidationData consolidationData) { + + Collection computeTemplateConsolidationDatas = + typeComputeConsolidationData.getAllComputeTemplateConsolidationData(); + Map> portTypeToPortIds = UnifiedCompositionUtil + .collectAllPortsFromEachTypesFromComputes(computeTemplateConsolidationDatas); + + FilePortConsolidationData filePortConsolidationData = + consolidationData.getPortConsolidationData().getFilePortConsolidationData(ToscaUtil + .getServiceTemplateFileName(serviceTemplate)); + + for (Set portsOfTheSameTypeIds : portTypeToPortIds.values()) { + List portTemplateConsolidationDataOfSameType = + getAllPortTemplateConsolidationData(portsOfTheSameTypeIds, filePortConsolidationData); + if (!checkGetAttrRelationsForEntityConsolidationData(portTemplateConsolidationDataOfSameType, + portsOfTheSameTypeIds)) { + return false; + } + } + + return true; + } + + private List getAllPortTemplateConsolidationData( + Set portsIds, + FilePortConsolidationData filePortConsolidationData) { + List portTemplateConsolidationDataOfSameType = new ArrayList<>(); + + for (String portId : portsIds) { + PortTemplateConsolidationData portTemplateConsolidationData = + filePortConsolidationData.getPortTemplateConsolidationData(portId); + if (Objects.nonNull(portTemplateConsolidationData)) { + portTemplateConsolidationDataOfSameType.add(portTemplateConsolidationData); + } + } + + return portTemplateConsolidationDataOfSameType; + } + + private boolean checkGetAttrRelationsForEntityConsolidationData( + Collection entities, + Set nodeTemplateIdsOfTheSameType) { + + List entityConsolidationDataList = + new ArrayList(entities); + + for (EntityConsolidationData entityConsolidationData : entityConsolidationDataList) { + Set getAttrInNodeIds = + entityConsolidationData.getNodesGetAttrIn() == null ? new HashSet<>() + : entityConsolidationData.getNodesGetAttrIn().keySet(); + for (String nodeId : getAttrInNodeIds) { + if (nodeTemplateIdsOfTheSameType.contains(nodeId)) { + return true; + } + } + } + + return false; + } + + + private boolean checkComputeConsolidation( + ServiceTemplate serviceTemplate, + TypeComputeConsolidationData typeComputeConsolidationData) { + List computeNodeTemplateIds = + new ArrayList(typeComputeConsolidationData.getAllComputeNodeTemplateIds()); + List propertiesWithIdenticalVal = getPropertiesWithIdenticalVal(); + + return arePropertiesSimilarBetweenComputeNodeTemplates( + serviceTemplate, computeNodeTemplateIds, propertiesWithIdenticalVal) + && checkComputeRelations( + typeComputeConsolidationData.getAllComputeTemplateConsolidationData()); + } + + + private boolean checkComputeRelations( + Collection computeTemplateConsolidationDatas) { + + return checkEntityConsolidationDataRelations(computeTemplateConsolidationDatas) + && checkComputesRelationsToVolume(computeTemplateConsolidationDatas); + } + + private boolean checkEntityConsolidationDataRelations(Collection entities) { + List entityConsolidationDataList = + new ArrayList(entities); + EntityConsolidationData startingEntity = entityConsolidationDataList.get(0); + + for (int i = 1; i < entityConsolidationDataList.size(); i++) { + EntityConsolidationData currentEntity = entityConsolidationDataList.get(i); + if (!(checkNodesConnectedInRelations(startingEntity, currentEntity) + && (checkNodesConnectedOutRelations(startingEntity, currentEntity)) + && (checkGroupIdsRelations(startingEntity, currentEntity)))) { + return false; + } + } + return true; + } + + private boolean checkNodesConnectedInRelations(EntityConsolidationData firstEntity, + EntityConsolidationData secondEntity) { + return compareNodeConnectivity(firstEntity.getNodesConnectedIn(), + secondEntity.getNodesConnectedIn()); + } + + private boolean checkNodesConnectedOutRelations(EntityConsolidationData firstEntity, + EntityConsolidationData secondEntity) { + return compareNodeConnectivity(firstEntity.getNodesConnectedOut(), + secondEntity.getNodesConnectedOut()); + } + + private boolean compareNodeConnectivity( + Map> firstEntityMap, + Map> secondEntityMap) { + if (MapUtils.isEmpty(firstEntityMap) + && MapUtils.isEmpty(secondEntityMap)) { + return true; + } + if (!MapUtils.isEmpty(firstEntityMap) + && !MapUtils.isEmpty(secondEntityMap)) { + return firstEntityMap.keySet().equals(secondEntityMap.keySet()); + } + return false; + } + + private boolean checkGroupIdsRelations(EntityConsolidationData startingEntity, + EntityConsolidationData currentEntity) { + if (CollectionUtils.isEmpty(startingEntity.getGroupIds()) && + CollectionUtils.isEmpty(currentEntity.getGroupIds())) { + return true; + } + + return startingEntity.getGroupIds().equals(currentEntity.getGroupIds()); + } + + private boolean checkComputesRelationsToVolume( + Collection computeTemplateConsolidationDatas) { + + Set volumeRelationsFromComputes = new HashSet<>(); + List computeTemplateConsolidationDataList = + new ArrayList(computeTemplateConsolidationDatas); + + Map> startingVolumes = + computeTemplateConsolidationDataList.get(0).getVolumes(); + + for (int i = 1; i < computeTemplateConsolidationDataList.size(); i++) { + Map> currentVolumes = + computeTemplateConsolidationDataList.get(i).getVolumes(); + if (!compareNodeConnectivity(startingVolumes, currentVolumes)) { + return false; + } + } + return true; + } + + + private boolean checkPortConsolidation(ServiceTemplate serviceTemplate, + TypeComputeConsolidationData typeComputeConsolidationData, + ConsolidationData consolidationData) { + return isWantedPortPropertiesUsageIsSimilarInAllPorts(serviceTemplate, + typeComputeConsolidationData) + && checkPortRelations(ToscaUtil.getServiceTemplateFileName(serviceTemplate), + typeComputeConsolidationData, consolidationData); + } + + + private boolean isWantedPortPropertiesUsageIsSimilarInAllPorts(ServiceTemplate serviceTemplate, + TypeComputeConsolidationData typeComputeConsolidationData) { + + Collection computeTemplateConsolidationDataCollection = + typeComputeConsolidationData.getAllComputeTemplateConsolidationData(); + List propertiesThatNeedHaveUsage = getPropertiesThatNeedHaveUsage(); + Map> portTypeToIds = UnifiedCompositionUtil + .collectAllPortsFromEachTypesFromComputes(computeTemplateConsolidationDataCollection); + + for (Set portsIds : portTypeToIds.values()) { + if (!areAllPortsFromSameTypeHaveTheSameUsageForProperties( + serviceTemplate, portsIds, propertiesThatNeedHaveUsage)) { + return false; + } + } + + return true; + } + + private boolean checkPortRelations(String serviceTemplateName, + TypeComputeConsolidationData typeComputeConsolidationData, + ConsolidationData consolidationData) { + Collection computeTemplateConsolidationDataCollection = + typeComputeConsolidationData.getAllComputeTemplateConsolidationData(); + Map> portTypeToIds = UnifiedCompositionUtil + .collectAllPortsFromEachTypesFromComputes(computeTemplateConsolidationDataCollection); + + for (Set portIds : portTypeToIds.values()) { + List portTemplateConsolidationDataList = + collectAllPortsTemplateConsolidationData( + portIds, serviceTemplateName, consolidationData); + + if (!checkEntityConsolidationDataRelations(portTemplateConsolidationDataList)) { + return false; + } + } + + return true; + } + + private List + collectAllPortsTemplateConsolidationData(Set portIds, + String serviceTemplateName, + ConsolidationData consolidationData) { + + FilePortConsolidationData filePortConsolidationData = + consolidationData.getPortConsolidationData() + .getFilePortConsolidationData(serviceTemplateName); + List portTemplateConsolidationDataList = new ArrayList<>(); + + for (String portId : portIds) { + PortTemplateConsolidationData portTemplateConsolidationData = filePortConsolidationData + .getPortTemplateConsolidationData(portId); + if (Objects.nonNull(portTemplateConsolidationData)) { + portTemplateConsolidationDataList.add(portTemplateConsolidationData); + } + } + + return portTemplateConsolidationDataList; + } + + private boolean areAllPortsFromSameTypeHaveTheSameUsageForProperties( + ServiceTemplate serviceTemplate, + Set portNodeTemplateIds, + List propertiesThatNeedToHaveUsage) { + Map nodeTemplates = + serviceTemplate.getTopology_template().getNode_templates(); + + for (String property : propertiesThatNeedToHaveUsage) { + if (!areAllPortsContainWantedProperty(property, portNodeTemplateIds, nodeTemplates)) { + return false; + } + } + + return true; + } + + private boolean areAllPortsContainWantedProperty( + String propertyToCheck, + Set portNodeTemplateIds, + Map nodeTemplates) { + + List portNodeTemplateIdList = new ArrayList(portNodeTemplateIds); + NodeTemplate startingPortNodeTemplate = nodeTemplates.get(portNodeTemplateIdList.get(0)); + + if (Objects.isNull(startingPortNodeTemplate)) { + throw new CoreException((new ErrorCode.ErrorCodeBuilder()) + .withMessage("Resource with id " + + portNodeTemplateIdList.get(0) + " occures more than once in different addOn files") + .build()); + } + + boolean startingUsageCondition = + startingPortNodeTemplate.getProperties().containsKey(propertyToCheck); + + for (int i = 1; i < portNodeTemplateIdList.size(); i++) { + NodeTemplate portNodeTemplate = nodeTemplates.get(portNodeTemplateIdList.get(i)); + + if (Objects.isNull(portNodeTemplate)) { + throw new CoreException((new ErrorCode.ErrorCodeBuilder()) + .withMessage("Resource with id " + + portNodeTemplateIdList.get(i) + " occures more than once in different addOn " + + "files").build()); + } + + Map properties = portNodeTemplate.getProperties(); + if (!(properties.containsKey(propertyToCheck) == startingUsageCondition)) { + return false; + } + } + + return true; + } + + + private boolean arePropertiesSimilarBetweenComputeNodeTemplates( + ServiceTemplate serviceTemplate, + List computeNodeTemplateIds, + List propertiesThatNeedToBeSimilar) { + + Map idToNodeTemplate = + serviceTemplate.getTopology_template().getNode_templates(); + + for (String property : propertiesThatNeedToBeSimilar) { + if (!isPropertySimilarBetweenComputeNodeTemplates(property, computeNodeTemplateIds, + idToNodeTemplate)) { + return false; + } + } + return true; + } + + private boolean isPropertySimilarBetweenComputeNodeTemplates( + String propertyToCheck, + List computeNodeTemplateIds, + Map idToNodeTemplate) { + Set propertiesValues = new HashSet<>(); + for (String computeNodeId : computeNodeTemplateIds) { + NodeTemplate currentNodeTemplate = idToNodeTemplate.get(computeNodeId); + if (Objects.isNull(currentNodeTemplate)) { + throw new CoreException((new ErrorCode.ErrorCodeBuilder()) + .withMessage("Resource with id " + + computeNodeId + " occures more than once in different addOn files").build()); + } + propertiesValues + .add(currentNodeTemplate.getProperties().get(propertyToCheck)); + } + + return propertiesValues.size() == 1; + } + + public void substitutionServiceTemplateConsolidation(String substituteNodeTemplateId, + ServiceTemplate mainServiceTemplate, + ServiceTemplate substitutionServiceTemplate, + TranslationContext translationContext) { + + ConsolidationData consolidationData = translationContext.getConsolidationData(); + + FileComputeConsolidationData fileComputeConsolidationData = + translationContext.getConsolidationData().getComputeConsolidationData() + .getFileComputeConsolidationData( + ToscaUtil.getServiceTemplateFileName(substitutionServiceTemplate)); + boolean consolidationRuleResult = + substitutionServiceTemplateConsolidationRule(substitutionServiceTemplate, + fileComputeConsolidationData, translationContext); + + if (consolidationRuleResult) { + List unifiedCompositionDataList = + createSubstitutionUnifiedCompositionDataList(substituteNodeTemplateId, + mainServiceTemplate, consolidationData); + unifiedCompositionService + .createUnifiedComposition(mainServiceTemplate, substitutionServiceTemplate, + unifiedCompositionDataList, UnifiedCompositionMode.NestedSingleCompute, + translationContext); + } else { + //The node template does not qualify for unified composition + //Adding the id in the context for fixing connectivity from/to nested non-unified nodes + translationContext.addUnifiedNestedNodeTemplateId(ToscaUtil + .getServiceTemplateFileName(mainServiceTemplate), + substituteNodeTemplateId, substituteNodeTemplateId); + } + } + + private boolean substitutionServiceTemplateConsolidationRule( + ServiceTemplate nestedServiceTemplate, + FileComputeConsolidationData fileComputeConsolidationData, + TranslationContext context) { + if (Objects.isNull(fileComputeConsolidationData)) { + return false; + } + return isNumberOfComputeTypesLegal(fileComputeConsolidationData) + && isNumberOfComputeConsolidationDataPerTypeLegal( + fileComputeConsolidationData.getAllTypeComputeConsolidationData().iterator().next()) + && !isThereMoreThanOneNestedLevel(nestedServiceTemplate, context.getConsolidationData()); + } + + private boolean isNumberOfComputeTypesLegal( + FileComputeConsolidationData fileComputeConsolidationData) { + return fileComputeConsolidationData.getAllTypeComputeConsolidationData().size() == 1; + } + + private boolean isNumberOfComputeConsolidationDataPerTypeLegal( + TypeComputeConsolidationData typeComputeConsolidationData) { + return typeComputeConsolidationData.getAllComputeTemplateConsolidationData().size() == 1; + } + + private boolean isThereMoreThanOneNestedLevel(ServiceTemplate nestedServiceTemplate, + ConsolidationData consolidationData) { + String nestedServiceTemplateName = ToscaUtil.getServiceTemplateFileName(nestedServiceTemplate); + if (Objects.isNull(nestedServiceTemplateName)) { + return false; + } + + FileNestedConsolidationData fileNestedConsolidationData = + consolidationData.getNestedConsolidationData() == null ? new FileNestedConsolidationData() + : consolidationData.getNestedConsolidationData() + .getFileNestedConsolidationData(nestedServiceTemplateName); + + if (Objects.isNull(fileNestedConsolidationData)) { + return false; + } + + return !CollectionUtils.isEmpty(fileNestedConsolidationData.getAllNestedNodeTemplateIds()); + } + + + private List createUnifiedCompositionDataList( + ServiceTemplate serviceTemplate, + ConsolidationData consolidationData, + TypeComputeConsolidationData typeComputeConsolidationData) { + + List unifiedCompositionDataList = new ArrayList<>(); + + for (ComputeTemplateConsolidationData computeTemplateConsolidationData : typeComputeConsolidationData + .getAllComputeTemplateConsolidationData()) { + + UnifiedCompositionData unifiedCompositionData = new UnifiedCompositionData(); + unifiedCompositionData.setComputeTemplateConsolidationData(computeTemplateConsolidationData); + + Collection> portCollection = + computeTemplateConsolidationData.getPorts() == null ? Collections.emptyList() + : computeTemplateConsolidationData.getPorts().values(); + + FilePortConsolidationData filePortConsolidationData = + consolidationData.getPortConsolidationData().getFilePortConsolidationData(ToscaUtil + .getServiceTemplateFileName(serviceTemplate)); + + for (List portList : portCollection) { + for (String portId : portList) { + if (!Objects.isNull(filePortConsolidationData)) { + unifiedCompositionData.addPortTemplateConsolidationData( + (filePortConsolidationData.getPortTemplateConsolidationData(portId))); + } + } + } + unifiedCompositionDataList.add(unifiedCompositionData); + } + + return unifiedCompositionDataList; + } + + private List createSubstitutionUnifiedCompositionDataList( + String substituteNodeTemplateId, + ServiceTemplate serviceTemplate, + ConsolidationData consolidationData) { + List unifiedCompositionDataList = new ArrayList<>(); + FileNestedConsolidationData fileNestedConsolidationData = + consolidationData.getNestedConsolidationData() + .getFileNestedConsolidationData(ToscaUtil.getServiceTemplateFileName(serviceTemplate)); + + if (Objects.nonNull(fileNestedConsolidationData)) { + Collection nestedConsolidationDatas = + fileNestedConsolidationData.getAllNestedConsolidationData(); + + for (NestedTemplateConsolidationData nested : nestedConsolidationDatas) { + if (nested.getNodeTemplateId().equals(substituteNodeTemplateId)) { + UnifiedCompositionData unifiedCompositionData = new UnifiedCompositionData(); + unifiedCompositionData.setNestedTemplateConsolidationData(nested); + unifiedCompositionDataList.add(unifiedCompositionData); + } + } + } + + return unifiedCompositionDataList; + } + + private boolean consolidationPreCondition(ServiceTemplate serviceTemplate, + ConsolidationData consolidationData, + TypeComputeConsolidationData typeComputeConsolidationData) { + + return (isThereMoreThanOneComputeTypeInstance(typeComputeConsolidationData) + && isNumberOfPortsEqualsBetweenComputeNodes(typeComputeConsolidationData) + && isNumberOfPortFromEachTypeLegal(typeComputeConsolidationData) + && isPortTypesEqualsBetweenComputeNodes(typeComputeConsolidationData) + && checkGetAttrBetweenConsolidationDataEntitiesNotFromSameType(serviceTemplate, + typeComputeConsolidationData, consolidationData)); + + } + + private boolean isThereMoreThanOneComputeTypeInstance( + TypeComputeConsolidationData typeComputeConsolidationData) { + return typeComputeConsolidationData.getAllComputeNodeTemplateIds().size() > 1; + } + + private boolean isNumberOfPortsEqualsBetweenComputeNodes( + TypeComputeConsolidationData typeComputeConsolidationData) { + + ArrayList computeTemplateConsolidationDataList = + new ArrayList(typeComputeConsolidationData.getAllComputeTemplateConsolidationData()); + int startingNumberOfPorts = + getNumberOfPortsPerCompute(computeTemplateConsolidationDataList.get(0)); + + + for (int i = 1; i < computeTemplateConsolidationDataList.size(); i++) { + int currNumberOfPorts = + getNumberOfPortsPerCompute(computeTemplateConsolidationDataList.get(i)); + if (currNumberOfPorts != startingNumberOfPorts) { + return false; + } + } + + return true; + } + + + private boolean isNumberOfPortFromEachTypeLegal( + TypeComputeConsolidationData typeComputeConsolidationData) { + + ArrayList computeTemplateConsolidationDataList = + new ArrayList(typeComputeConsolidationData.getAllComputeTemplateConsolidationData()); + + for (ComputeTemplateConsolidationData computeTemplate : computeTemplateConsolidationDataList) { + Map> currPortsMap = computeTemplate.getPorts(); + if (MapUtils.isEmpty(currPortsMap)) { + return true; + } + for (List portList : currPortsMap.values()) { + if (portList.size() > 1) { + return false; + } + } + } + + return true; + } + + private boolean isPortTypesEqualsBetweenComputeNodes( + TypeComputeConsolidationData typeComputeConsolidationData) { + + ArrayList computeTemplateConsolidationDataList = + new ArrayList(typeComputeConsolidationData.getAllComputeTemplateConsolidationData()); + Set staringPortIds = getPortsIds(computeTemplateConsolidationDataList.get(0)); + + for (int i = 1; i < computeTemplateConsolidationDataList.size(); i++) { + Set currentPortIds = getPortsIds(computeTemplateConsolidationDataList.get(i)); + if (!currentPortIds.equals(staringPortIds)) { + return false; + } + } + + return true; + } + + private int getNumberOfPortsPerCompute( + ComputeTemplateConsolidationData computeTemplateConsolidationData) { + return getPortsIds(computeTemplateConsolidationData) == null ? 0 : + getPortsIds(computeTemplateConsolidationData).size(); + } + + private Set getPortsIds( + ComputeTemplateConsolidationData computeTemplateConsolidationData) { + return computeTemplateConsolidationData.getPorts() == null ? new HashSet<>() + : computeTemplateConsolidationData + .getPorts().keySet(); + } + + List getPropertiesWithIdenticalVal() { + List propertyWithIdenticalValue = new ArrayList<>(); + propertyWithIdenticalValue.add(ToscaConstants.COMPUTE_IMAGE); + propertyWithIdenticalValue.add(ToscaConstants.COMPUTE_FLAVOR); + return propertyWithIdenticalValue; + } + + private List getPropertiesThatNeedHaveUsage() { + List propertiesThatNeedToHaveUsage = new ArrayList<>(); + propertiesThatNeedToHaveUsage.add(ToscaConstants.PORT_FIXED_IPS); + propertiesThatNeedToHaveUsage.add(ToscaConstants.PORT_ALLOWED_ADDRESS_PAIRS); + propertiesThatNeedToHaveUsage.add(ToscaConstants.MAC_ADDRESS); + + return propertiesThatNeedToHaveUsage; + } +} + diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/Constants.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/Constants.java index abd6c27a21..e5d752798b 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/Constants.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/Constants.java @@ -44,6 +44,13 @@ public class Constants { public static final String CONTRAIL_PORT_TEMPLATE_NAME = "ContrailPortGlobalTypes"; public static final String CONTRAIL_ABSTRACT_SUBSTITUTE_TEMPLATE_NAME = "ContrailAbstractSubstituteGlobalTypes"; + public static final String MAIN_TEMPLATE_NAME = "Main"; + public static final String PORT_TEMPLATE_NAME = "PortGlobalTypes"; + public static final String COMPUTE_TEMPLATE_NAME = "ComputeGlobalTypes"; + public static final String NETWORK_TEMPLATE_NAME = "NetworkGlobalTypes"; + public static final String SUB_INTERFACE_TEMPLATE_NAME = "SubInterfaceGlobalTypes"; + public static final String CONTRAILV2_VLAN_SUB_INTERFACE_TEMPLATE_NAME = + "ContrailV2VLANSubInterfaceGlobalType"; //properties public static final String MAX_INSTANCES_PROPERTY_NAME = "max_instances"; public static final String DESCRIPTION_PROPERTY_NAME = "description"; @@ -54,6 +61,12 @@ public class Constants { //General public static final String PROP = "properties"; public static final String ATTR = "attributes"; + public static final String SERVICE_INSTANCE_PORT_PREFIX = "port_"; + public static final String SERVICE_INSTANCE_LINK_PREFIX = "link_"; + //Unified model + public static final String IDENTICAL_VALUE_PROPERTY_PREFIX = "vm_"; + public static final String IDENTICAL_VALUE_PROPERTY_SUFFIX = "_name"; + public static final String ABSTRACT_NODE_TEMPLATE_ID_PREFIX = "abstract_"; private Constants() { } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/FunctionTranslation.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/FunctionTranslation.java new file mode 100644 index 0000000000..dbbc63ece1 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/FunctionTranslation.java @@ -0,0 +1,38 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.translator.services.heattotosca; + + +import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate; +import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; +import org.openecomp.sdc.tosca.datatypes.model.Template; +import org.openecomp.sdc.translator.datatypes.heattotosca.TranslationContext; + + +public interface FunctionTranslation { + + //return the value of the translated function ("get_param", "get_attr" and etc) + Object translateFunction(ServiceTemplate serviceTemplate, + String resourceId, String propertyName, String functionKey, + Object functionValue, String heatFileName, + HeatOrchestrationTemplate heatOrchestrationTemplate, + Template toscaTemplate, TranslationContext context); +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/FunctionTranslationFactory.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/FunctionTranslationFactory.java new file mode 100644 index 0000000000..07e8fcdad6 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/FunctionTranslationFactory.java @@ -0,0 +1,70 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.translator.services.heattotosca; + + +import org.openecomp.config.api.Configuration; +import org.openecomp.config.api.ConfigurationManager; +import org.openecomp.core.utilities.CommonMethods; +import org.openecomp.sdc.datatypes.configuration.ImplementationConfiguration; + +import java.util.Map; +import java.util.Optional; + + +public class FunctionTranslationFactory { + private static Map functionTranslationImplMap; + + static { + Configuration config = ConfigurationManager.lookup(); + functionTranslationImplMap = config.populateMap(ConfigConstants.TRANSLATOR_NAMESPACE, + ConfigConstants.FUNCTION_TRANSLATION_IMPL_KEY, ImplementationConfiguration.class); + functionTranslationImplMap.putAll(config.populateMap(ConfigConstants.MANDATORY_TRANSLATOR_NAMESPACE, + ConfigConstants.FUNCTION_TRANSLATION_IMPL_KEY, ImplementationConfiguration.class)); + + } + + /** + * Gets function translation instance. + * + * @param heatFunctionKey heat function key + * @return the instance + */ + public static Optional getInstance(String heatFunctionKey) { + if (isSupportedFunction(heatFunctionKey)) { + String functionTranslationImplClassName = + functionTranslationImplMap.get(heatFunctionKey).getImplementationClass(); + return Optional.of(CommonMethods + .newInstance(functionTranslationImplClassName, FunctionTranslation.class)); + } + + return Optional.empty(); + } + + private static boolean isSupportedFunction(String heatFunctionKey) { + if (functionTranslationImplMap.containsKey(heatFunctionKey)) { + return true; + } + return false; + } + +} + diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/HeatToToscaUtil.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/HeatToToscaUtil.java index f245a6dee6..7c67a5af2c 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/HeatToToscaUtil.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/HeatToToscaUtil.java @@ -21,27 +21,74 @@ package org.openecomp.sdc.translator.services.heattotosca; import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.collections4.MapUtils; +import org.openecomp.core.translator.api.HeatToToscaTranslator; +import org.openecomp.core.translator.datatypes.TranslatorOutput; +import org.openecomp.core.translator.factory.HeatToToscaTranslatorFactory; +import org.openecomp.core.utilities.CommonMethods; +import org.openecomp.core.utilities.file.FileContentHandler; +import org.openecomp.core.utilities.file.FileUtils; import org.openecomp.core.utilities.yaml.YamlUtil; +import org.openecomp.core.validation.util.MessageContainerUtil; import org.openecomp.sdc.common.errors.CoreException; +import org.openecomp.sdc.common.utils.SdcCommon; +import org.openecomp.sdc.datatypes.error.ErrorLevel; +import org.openecomp.sdc.datatypes.error.ErrorMessage; import org.openecomp.sdc.heat.datatypes.HeatBoolean; import org.openecomp.sdc.heat.datatypes.manifest.FileData; import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate; import org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes; import org.openecomp.sdc.heat.datatypes.model.Resource; +import org.openecomp.sdc.heat.datatypes.structure.HeatStructureTree; +import org.openecomp.sdc.heat.datatypes.structure.ValidationStructureList; import org.openecomp.sdc.heat.services.HeatConstants; +import org.openecomp.sdc.heat.services.tree.HeatTreeManager; +import org.openecomp.sdc.heat.services.tree.HeatTreeManagerUtil; +import org.openecomp.sdc.logging.api.Logger; +import org.openecomp.sdc.logging.api.LoggerFactory; +import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; +import org.openecomp.sdc.logging.context.impl.MdcDataErrorMessage; +import org.openecomp.sdc.logging.types.LoggerConstants; +import org.openecomp.sdc.logging.types.LoggerErrorCode; +import org.openecomp.sdc.logging.types.LoggerErrorDescription; +import org.openecomp.sdc.logging.types.LoggerTragetServiceName; +import org.openecomp.sdc.tosca.datatypes.ToscaCapabilityType; +import org.openecomp.sdc.tosca.datatypes.ToscaElementTypes; +import org.openecomp.sdc.tosca.datatypes.ToscaNodeType; +import org.openecomp.sdc.tosca.datatypes.ToscaRelationshipType; import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel; +import org.openecomp.sdc.tosca.datatypes.model.AttributeDefinition; +import org.openecomp.sdc.tosca.datatypes.model.CapabilityDefinition; +import org.openecomp.sdc.tosca.datatypes.model.Import; import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; +import org.openecomp.sdc.tosca.datatypes.model.NodeType; +import org.openecomp.sdc.tosca.datatypes.model.ParameterDefinition; +import org.openecomp.sdc.tosca.datatypes.model.PropertyDefinition; +import org.openecomp.sdc.tosca.datatypes.model.PropertyType; +import org.openecomp.sdc.tosca.datatypes.model.RequirementAssignment; +import org.openecomp.sdc.tosca.datatypes.model.RequirementDefinition; import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; +import org.openecomp.sdc.tosca.datatypes.model.SubstitutionMapping; +import org.openecomp.sdc.tosca.datatypes.model.Template; +import org.openecomp.sdc.tosca.datatypes.model.TopologyTemplate; +import org.openecomp.sdc.tosca.services.DataModelUtil; +import org.openecomp.sdc.tosca.services.ToscaAnalyzerService; +import org.openecomp.sdc.tosca.services.ToscaConstants; import org.openecomp.sdc.tosca.services.ToscaUtil; +import org.openecomp.sdc.tosca.services.impl.ToscaAnalyzerServiceImpl; +import org.openecomp.sdc.tosca.services.yamlutil.ToscaExtensionYamlUtil; +import org.openecomp.sdc.translator.datatypes.heattotosca.AttachedPropertyVal; import org.openecomp.sdc.translator.datatypes.heattotosca.AttachedResourceId; -import org.openecomp.sdc.translator.datatypes.heattotosca.ResourceReferenceType; +import org.openecomp.sdc.translator.datatypes.heattotosca.ReferenceType; +import org.openecomp.sdc.translator.datatypes.heattotosca.TranslationContext; import org.openecomp.sdc.translator.datatypes.heattotosca.to.FileDataCollection; import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; import org.openecomp.sdc.translator.services.heattotosca.errors.ResourceNotFoundInHeatFileErrorBuilder; -import org.openecomp.sdc.translator.services.heattotosca.mapping.TranslatorHeatToToscaFunctionConverter; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.openecomp.sdc.translator.services.heattotosca.globaltypes.GlobalTypesGenerator; +import org.openecomp.sdc.translator.services.heattotosca.helper.FunctionTranslationHelper; +import org.openecomp.sdc.translator.services.heattotosca.mapping.TranslatorHeatToToscaPropertyConverter; +import java.io.InputStream; import java.util.ArrayList; import java.util.Collection; import java.util.HashMap; @@ -53,10 +100,58 @@ import java.util.Optional; import java.util.Set; import java.util.stream.Collectors; +/** + * The type Heat to tosca util. + */ public class HeatToToscaUtil { - protected static Logger logger = LoggerFactory.getLogger(HeatToToscaUtil.class); + protected static Logger logger = (Logger) LoggerFactory.getLogger(HeatToToscaUtil.class); + protected static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); + + + /** + * Load and translate template data translator output. + * + * @param fileNameContentMap the file name content map + * @return the translator output + */ + public static TranslatorOutput loadAndTranslateTemplateData( + FileContentHandler fileNameContentMap) { + mdcDataDebugMessage.debugEntryMessage(null, null); + HeatToToscaTranslator heatToToscaTranslator = + HeatToToscaTranslatorFactory.getInstance().createInterface(); + InputStream fileContent = fileNameContentMap.getFileContent(SdcCommon.MANIFEST_NAME); + + heatToToscaTranslator.addManifest(SdcCommon.MANIFEST_NAME, FileUtils.toByteArray(fileContent)); + + fileNameContentMap.getFileList().stream() + .filter(fileName -> !(fileName.equals(SdcCommon.MANIFEST_NAME))).forEach( + fileName -> heatToToscaTranslator + .addFile(fileName, FileUtils.toByteArray + (fileNameContentMap.getFileContent(fileName)))); + + Map> errors = heatToToscaTranslator.validate(); + if (MapUtils.isNotEmpty(MessageContainerUtil.getMessageByLevel(ErrorLevel.ERROR, errors))) { + TranslatorOutput translatorOutput = new TranslatorOutput(); + translatorOutput.setErrorMessages(errors); + return translatorOutput; + } + + InputStream structureFile = getHeatStructureTreeFile(fileNameContentMap); + heatToToscaTranslator.addExternalArtifacts(SdcCommon.HEAT_META, structureFile); + + mdcDataDebugMessage.debugExitMessage(null, null); + return heatToToscaTranslator.translate(); + } + + private static InputStream getHeatStructureTreeFile(FileContentHandler fileNameContentMap) { + HeatTreeManager heatTreeManager = HeatTreeManagerUtil.initHeatTreeManager(fileNameContentMap); + heatTreeManager.createTree(); + HeatStructureTree tree = heatTreeManager.getTree(); + ValidationStructureList validationStructureList = new ValidationStructureList(tree); + return FileUtils.convertToInputStream(validationStructureList, FileUtils.FileExtension.JSON); + } /** * Build list of files to search optional. @@ -77,6 +172,13 @@ public class HeatToToscaUtil { return Optional.ofNullable(HeatToToscaUtil.getFilteredListOfFileDataByTypes(list, types)); } + /** + * Gets filtered list of file data by types. + * + * @param filesToSearch the files to search + * @param types the types + * @return the filtered list of file data by types + */ public static List getFilteredListOfFileDataByTypes(List filesToSearch, FileData.Type... types) { return filesToSearch.stream().filter(FileData.buildFileDataPredicateByType(types)) @@ -84,7 +186,7 @@ public class HeatToToscaUtil { } /** - * Gets file data. + * Gets file data from the list according to the input heat file name. * * @param heatFileName the heat file name * @param fileDataList the file data list @@ -100,6 +202,26 @@ public class HeatToToscaUtil { return Optional.empty(); } + /** + * Gets file data which is supported by the translator, from the context according the input heat + * file name. + * + * @param heatFileName the heat file name + * @param context the translation context + * @return the file data + */ + public static FileData getFileData(String heatFileName, TranslationContext context) { + + List fileDataList = context.getManifest().getContent().getData(); + for (FileData fileData : fileDataList) { + if (TranslationService.getTypesToProcessByTranslator().contains(fileData.getType()) + && fileData.getFile().equals(heatFileName)) { + return fileData; + } + } + return null; + } + static FileDataCollection getFileCollectionsByFilter(List fileDataList, Set typeFilter, TranslationContext translationContext) { @@ -118,20 +240,23 @@ public class HeatToToscaUtil { HeatOrchestrationTemplate heatOrchestrationTemplate = new YamlUtil() .yamlToObject(translationContext.getFileContent(fileName), HeatOrchestrationTemplate.class); - for (Resource resource : heatOrchestrationTemplate.getResources().values()) { - if (filenames.contains(resource.getType())) { - handleNestedFile(translationContext, fileDataCollection, filteredFiles, referenced, - resource.getType()); - } else if (resource.getType() - .equals(HeatResourcesTypes.RESOURCE_GROUP_RESOURCE_TYPE.getHeatResource())) { - Object resourceDef = - resource.getProperties().get(HeatConstants.RESOURCE_DEF_PROPERTY_NAME); - Object innerTypeDef = ((Map) resourceDef).get("type"); - if (innerTypeDef instanceof String) { - String internalResourceType = (String) innerTypeDef; - if (filenames.contains(internalResourceType)) { - handleNestedFile(translationContext, fileDataCollection, filteredFiles, referenced, - internalResourceType); + if (!MapUtils.isEmpty(heatOrchestrationTemplate.getResources())) { + for (Resource resource : heatOrchestrationTemplate.getResources().values()) { + if (filenames.contains(resource.getType())) { + handleNestedFile(translationContext, fileDataCollection, filteredFiles, referenced, + resource.getType()); + } else if (resource.getType() + .equals(HeatResourcesTypes.RESOURCE_GROUP_RESOURCE_TYPE.getHeatResource())) { + Object resourceDef = + resource.getProperties().get(HeatConstants.RESOURCE_DEF_PROPERTY_NAME); + Object innerTypeDef = ((Map) resourceDef).get("type"); + if (innerTypeDef instanceof String) { + String internalResourceType = (String) innerTypeDef; + if (filenames.contains(internalResourceType)) { + handleNestedFile(translationContext, fileDataCollection, filteredFiles, + referenced, + internalResourceType); + } } } } @@ -157,9 +282,15 @@ public class HeatToToscaUtil { FileDataCollection fileDataCollection, Map filteredFiles, Set referenced, String nestedFileName) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + referenced.add(nestedFileName); fileDataCollection.addNestedFiles(filteredFiles.get(nestedFileName)); translationContext.getNestedHeatsFiles().add(nestedFileName); + + mdcDataDebugMessage.debugExitMessage(null, null); } private static Map filterFileDataListByType(List fileDataList, @@ -183,10 +314,16 @@ public class HeatToToscaUtil { */ public static Optional extractAttachedResourceId(TranslateTo translateTo, String propertyName) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + Object propertyValue = translateTo.getResource().getProperties().get(propertyName); if (propertyValue == null) { return Optional.empty(); } + + mdcDataDebugMessage.debugExitMessage(null, null); return extractAttachedResourceId(translateTo.getHeatFileName(), translateTo.getHeatOrchestrationTemplate(), translateTo.getContext(), propertyValue); } @@ -201,9 +338,9 @@ public class HeatToToscaUtil { * @return the optional */ public static Optional extractAttachedResourceId(String heatFileName, - HeatOrchestrationTemplate heatOrchestrationTemplate, - TranslationContext context, - Object propertyValue) { + HeatOrchestrationTemplate heatOrchestrationTemplate, + TranslationContext context, + Object propertyValue) { Object entity; Object translatedId; @@ -212,7 +349,7 @@ public class HeatToToscaUtil { return Optional.empty(); } - ResourceReferenceType referenceType = ResourceReferenceType.OTHER; + ReferenceType referenceType = ReferenceType.OTHER; if (propertyValue instanceof Map && !((Map) propertyValue).isEmpty()) { Map propMap = (Map) propertyValue; Map.Entry entry = propMap.entrySet().iterator().next(); @@ -220,21 +357,28 @@ public class HeatToToscaUtil { String key = entry.getKey(); switch (key) { case "get_resource": - referenceType = ResourceReferenceType.GET_RESOURCE; + referenceType = ReferenceType.GET_RESOURCE; break; case "get_param": - referenceType = ResourceReferenceType.GET_PARAM; + referenceType = ReferenceType.GET_PARAM; break; case "get_attr": - referenceType = ResourceReferenceType.GET_ATTR; + referenceType = ReferenceType.GET_ATTR; break; default: + referenceType = ReferenceType.OTHER; + break; + } + + if (!FunctionTranslationFactory.getInstance(entry.getKey()).isPresent()) { + translatedId = null; + } else { + translatedId = FunctionTranslationFactory.getInstance(entry.getKey()).get() + .translateFunction(null, null, null, entry.getKey(), entry.getValue(), heatFileName, + heatOrchestrationTemplate, null, context); } - translatedId = TranslatorHeatToToscaFunctionConverter - .getToscaFunction(entry.getKey(), entry.getValue(), heatFileName, - heatOrchestrationTemplate, null, context); if (translatedId instanceof String - && !TranslatorHeatToToscaFunctionConverter.isResourceSupported((String) translatedId)) { + && !FunctionTranslationHelper.isResourceSupported((String) translatedId)) { translatedId = null; } @@ -254,6 +398,10 @@ public class HeatToToscaUtil { */ public static Optional getContrailAttachedHeatResourceId( AttachedResourceId attachedResource) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + if (attachedResource == null) { return Optional.empty(); } @@ -267,6 +415,7 @@ public class HeatToToscaUtil { return Optional.of((String) ((List) attachedResource.getEntityId()).get(0)); } + mdcDataDebugMessage.debugExitMessage(null, null); return Optional.empty(); } @@ -276,37 +425,40 @@ public class HeatToToscaUtil { * @param propertyValue the property value * @return the optional */ - public static Optional extractProperty(Object propertyValue) { + public static Optional extractProperty(Object propertyValue) { - Object entity; + mdcDataDebugMessage.debugEntryMessage(null, null); + Object attachedPropertyVal; if (Objects.isNull(propertyValue)) { return Optional.empty(); } - ResourceReferenceType referenceType = ResourceReferenceType.OTHER; + ReferenceType referenceType = ReferenceType.OTHER; if (propertyValue instanceof Map && !((Map) propertyValue).isEmpty()) { Map propMap = (Map) propertyValue; Map.Entry entry = propMap.entrySet().iterator().next(); - entity = entry.getValue(); + attachedPropertyVal = entry.getValue(); String key = entry.getKey(); switch (key) { case "get_resource": - referenceType = ResourceReferenceType.GET_RESOURCE; + referenceType = ReferenceType.GET_RESOURCE; break; case "get_param": - referenceType = ResourceReferenceType.GET_PARAM; + referenceType = ReferenceType.GET_PARAM; break; case "get_attr": - referenceType = ResourceReferenceType.GET_ATTR; + referenceType = ReferenceType.GET_ATTR; break; default: + break; } } else { - entity = propertyValue; + attachedPropertyVal = propertyValue; } - return Optional.of(new AttachedResourceId(null, entity, referenceType)); + mdcDataDebugMessage.debugExitMessage(null, null); + return Optional.of(new AttachedPropertyVal(attachedPropertyVal, referenceType)); } /** @@ -316,10 +468,14 @@ public class HeatToToscaUtil { * @param propertyKey the property key */ public static void mapBoolean(NodeTemplate nodeTemplate, String propertyKey) { + mdcDataDebugMessage.debugEntryMessage(null, null); + Object value = nodeTemplate.getProperties().get(propertyKey); if (value != null && !(value instanceof Map)) { nodeTemplate.getProperties().put(propertyKey, HeatBoolean.eval(value)); } + + mdcDataDebugMessage.debugExitMessage(null, null); } /** @@ -342,6 +498,12 @@ public class HeatToToscaUtil { } + /** + * Is yml file type boolean. + * + * @param filename the filename + * @return the boolean + */ public static boolean isYmlFileType(String filename) { return (filename.indexOf("yaml") > 0 || filename.indexOf("yml") > 0); } @@ -353,10 +515,17 @@ public class HeatToToscaUtil { * @return the boolean */ public static boolean isNestedResource(Resource resource) { + mdcDataDebugMessage.debugEntryMessage(null, null); + String resourceType = resource.getType(); if (resourceType.equals(HeatResourcesTypes.RESOURCE_GROUP_RESOURCE_TYPE.getHeatResource())) { Object resourceDef = resource.getProperties().get(HeatConstants.RESOURCE_DEF_PROPERTY_NAME); + if (!(((Map) resourceDef).get("type") instanceof String)) { + //currently only resource group which is poinitng to nested heat file is supported + //dynamic type is currently not supported + return false; + } String internalResourceType = (String) ((Map) resourceDef).get("type"); if (isYamlFile(internalResourceType)) { return true; @@ -364,9 +533,36 @@ public class HeatToToscaUtil { } else if (isYamlFile(resourceType)) { return true; } + + mdcDataDebugMessage.debugExitMessage(null, null); return false; } + /** + * Get nested heat file name in case of nested resource. + * + * @param resource the resource + * @return the nested heat file name + */ + public static Optional getNestedHeatFileName(Resource resource) { + mdcDataDebugMessage.debugEntryMessage(null, null); + + if (!isNestedResource(resource)) { + return Optional.empty(); + } + + String resourceType = resource.getType(); + + if (resourceType.equals(HeatResourcesTypes.RESOURCE_GROUP_RESOURCE_TYPE.getHeatResource())) { + Object resourceDef = resource.getProperties().get(HeatConstants.RESOURCE_DEF_PROPERTY_NAME); + String internalResourceType = (String) ((Map) resourceDef).get("type"); + return Optional.of(internalResourceType); + } + + mdcDataDebugMessage.debugExitMessage(null, null); + return Optional.of(resourceType); + } + /** * Gets nested file. * @@ -374,6 +570,10 @@ public class HeatToToscaUtil { * @return the nested file */ public static Optional getNestedFile(Resource resource) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + if (!isNestedResource(resource)) { return Optional.empty(); } @@ -381,8 +581,11 @@ public class HeatToToscaUtil { if (resourceType.equals(HeatResourcesTypes.RESOURCE_GROUP_RESOURCE_TYPE.getHeatResource())) { Object resourceDef = resource.getProperties().get(HeatConstants.RESOURCE_DEF_PROPERTY_NAME); String internalResourceType = (String) ((Map) resourceDef).get("type"); + + mdcDataDebugMessage.debugExitMessage(null, null); return Optional.of(internalResourceType); } else { + mdcDataDebugMessage.debugExitMessage(null, null); return Optional.of(resourceType); } } @@ -401,27 +604,69 @@ public class HeatToToscaUtil { */ public static Resource getResource(HeatOrchestrationTemplate heatOrchestrationTemplate, String resourceId, String heatFileName) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + Resource resource = heatOrchestrationTemplate.getResources().get(resourceId); if (resource == null) { + MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, + LoggerTragetServiceName.GET_RESOURCE, ErrorLevel.ERROR.name(), + LoggerErrorCode.DATA_ERROR.getErrorCode(), LoggerErrorDescription.TRANSLATE_HEAT); throw new CoreException( new ResourceNotFoundInHeatFileErrorBuilder(resourceId, heatFileName).build()); } + + mdcDataDebugMessage.debugExitMessage(null, null); return resource; } + + /** + * Get resource type. + * + * @param resourceId the resource id + * @param heatOrchestrationTemplate heat orchestration template + * @param heatFileName heat file name + * @return resource type + */ + public static String getResourceType(String resourceId, + HeatOrchestrationTemplate heatOrchestrationTemplate, + String heatFileName) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + mdcDataDebugMessage.debugExitMessage(null, null); + return HeatToToscaUtil.getResource(heatOrchestrationTemplate, resourceId, heatFileName) + .getType(); + } + + /** + * Is heat file nested boolean. + * + * @param translateTo the translate to + * @param heatFileName the heat file name + * @return the boolean + */ public static boolean isHeatFileNested(TranslateTo translateTo, String heatFileName) { return translateTo.getContext().getNestedHeatsFiles().contains(heatFileName); } /** - * Extract contrail get resource attached heat resource id string. + * Extract contrail get resource attached heat resource id optional. * * @param propertyValue the property value - * @return the string + * @return the optional */ - public static String extractContrailGetResourceAttachedHeatResourceId(Object propertyValue) { + public static Optional extractContrailGetResourceAttachedHeatResourceId( + Object propertyValue) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + if (propertyValue == null) { - return null; + return Optional.empty(); } Object value; @@ -431,7 +676,7 @@ public class HeatToToscaUtil { if (value instanceof List) { if (((List) value).size() == 2 && ((List) value).get(1).equals("fq_name")) { if (((List) value).get(0) instanceof String) { - return (String) ((List) value).get(0); + return Optional.of((String) ((List) value).get(0)); } else { logger.warn("invalid format of 'get_attr' function - " + propertyValue.toString()); } @@ -440,15 +685,15 @@ public class HeatToToscaUtil { } else if (((Map) propertyValue).containsKey("get_resource")) { value = ((Map) propertyValue).get("get_resource"); if (value instanceof String) { - return (String) value; + return Optional.of((String) value); } else { logger.warn("invalid format of 'get_resource' function - " + propertyValue.toString()); } } else { Collection valCollection = ((Map) propertyValue).values(); for (Object entryValue : valCollection) { - String ret = extractContrailGetResourceAttachedHeatResourceId(entryValue); - if (ret != null) { + Optional ret = extractContrailGetResourceAttachedHeatResourceId(entryValue); + if (ret.isPresent()) { return ret; } @@ -456,31 +701,54 @@ public class HeatToToscaUtil { } } else if (propertyValue instanceof List) { for (Object prop : (List) propertyValue) { - String ret = extractContrailGetResourceAttachedHeatResourceId(prop); - if (ret != null) { + Optional ret = extractContrailGetResourceAttachedHeatResourceId(prop); + if (ret.isPresent()) { return ret; } } } - return null; + + mdcDataDebugMessage.debugExitMessage(null, null); + return Optional.empty(); + } + + /** + * Gets tosca service model. + * + * @param context translation context + * @return the tosca service model + */ + public static ToscaServiceModel getToscaServiceModel(TranslationContext context) { + mdcDataDebugMessage.debugEntryMessage(null, null); + mdcDataDebugMessage.debugExitMessage(null, null); + + Map metadata = new HashMap<>(); + metadata.put(ToscaConstants.ST_METADATA_TEMPLATE_NAME, Constants.MAIN_TEMPLATE_NAME); + return getToscaServiceModel(context, metadata); } /** * Gets tosca service model. * - * @param translateTo the translate to + * @param context translation context + * @param entryDefinitionMetadata template name of the entry definition servie template * @return the tosca service model */ - public static ToscaServiceModel getToscaServiceModel(TranslateTo translateTo) { + public static ToscaServiceModel getToscaServiceModel(TranslationContext context, + Map entryDefinitionMetadata) { + mdcDataDebugMessage.debugEntryMessage(null, null); + Map serviceTemplates = - new HashMap<>(translateTo.getContext().getGlobalServiceTemplates()); + new HashMap<>(context.getGlobalServiceTemplates()); Collection tmpServiceTemplates = - translateTo.getContext().getTranslatedServiceTemplates().values(); + context.getTranslatedServiceTemplates().values(); for (ServiceTemplate serviceTemplate : tmpServiceTemplates) { ToscaUtil.addServiceTemplateToMapWithKeyFileName(serviceTemplates, serviceTemplate); } + + mdcDataDebugMessage.debugExitMessage(null, null); return new ToscaServiceModel(null, serviceTemplates, - ToscaUtil.getServiceTemplateFileName(translateTo.getResource().getType())); + ToscaUtil.getServiceTemplateFileName(entryDefinitionMetadata)); } /** @@ -492,12 +760,929 @@ public class HeatToToscaUtil { */ public static Optional getServiceTemplateFromContext( String serviceTemplateFileName, TranslationContext context) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + for (ServiceTemplate serviceTemplate : context.getTranslatedServiceTemplates().values()) { if (ToscaUtil.getServiceTemplateFileName(serviceTemplate).equals(serviceTemplateFileName)) { + mdcDataDebugMessage.debugExitMessage(null, null); return Optional.of(serviceTemplate); } } + mdcDataDebugMessage.debugExitMessage(null, null); return Optional.empty(); } + + /** + * Adding binding requerment from port node template to compute node template. + * + * @param computeNodeTemplateId compute node template id + * @param portNodeTemplate port node template + */ + public static void addBindingReqFromPortToCompute(String computeNodeTemplateId, + NodeTemplate portNodeTemplate) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + RequirementAssignment requirementAssignment = new RequirementAssignment(); + requirementAssignment.setCapability(ToscaCapabilityType.NATIVE_NETWORK_BINDABLE); + requirementAssignment.setRelationship(ToscaRelationshipType.NATIVE_NETWORK_BINDS_TO); + requirementAssignment.setNode(computeNodeTemplateId); + DataModelUtil.addRequirementAssignment(portNodeTemplate, ToscaConstants.BINDING_REQUIREMENT_ID, + requirementAssignment); + + mdcDataDebugMessage.debugExitMessage(null, null); + } + + /** + * Adding link requerment from port node template to network node template. + * + * @param portNodeTemplate port node template + * @param networkTranslatedId network node template id + */ + public static RequirementAssignment addLinkReqFromPortToNetwork(NodeTemplate portNodeTemplate, + String networkTranslatedId) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + RequirementAssignment requirement = new RequirementAssignment(); + requirement.setCapability(ToscaCapabilityType.NATIVE_NETWORK_LINKABLE); + requirement.setRelationship(ToscaRelationshipType.NATIVE_NETWORK_LINK_TO); + requirement.setNode(networkTranslatedId); + DataModelUtil.addRequirementAssignment(portNodeTemplate, + ToscaConstants.LINK_REQUIREMENT_ID, requirement); + + mdcDataDebugMessage.debugExitMessage(null, null); + + return requirement; + } + + /** + * Adding binding requerment from sub interface node template to interface (port) node template. + * + * @param subInterfaceNodeTemplate sub interface template + * @param interfaceTranslatedId interface node template id + */ + public static void addBindingReqFromSubInterfaceToInterface( + NodeTemplate subInterfaceNodeTemplate, String interfaceTranslatedId) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + RequirementAssignment requirement = new RequirementAssignment(); + requirement.setCapability(ToscaCapabilityType.NATIVE_NETWORK_BINDABLE); + requirement.setRelationship(ToscaRelationshipType.NATIVE_NETWORK_BINDS_TO); + requirement.setNode(interfaceTranslatedId); + DataModelUtil + .addRequirementAssignment(subInterfaceNodeTemplate, + ToscaConstants.BINDING_REQUIREMENT_ID, requirement); + + mdcDataDebugMessage.debugExitMessage(null, null); + } + + /** + * Get property Parameter Name Value. + * + * @param property property + * @return Parameter name in case the property include "get_param" function + */ + public static Optional getPropertyParameterNameValue(Object property) { + if (Objects.isNull(property)) { + return Optional.empty(); + } + Optional extractedProperty = extractProperty(property); + if (extractedProperty.isPresent()) { + return getParameterName(extractedProperty.get()); + } + return Optional.empty(); + } + + private static Optional getParameterName(AttachedPropertyVal extractedProperty) { + if (!extractedProperty.isGetParam()) { + return Optional.empty(); + } + Object getParamFuncValue = extractedProperty.getPropertyValue(); + if (getParamFuncValue instanceof String) { + return Optional.of((String) getParamFuncValue); + } else { + return Optional.of((String) ((List) getParamFuncValue).get(0)); + } + } + + public static String getToscaPropertyName(TranslationContext context, String heatResourceType, + String heatPropertyName) { + return context.getElementMapping(heatResourceType, Constants.PROP, heatPropertyName); + } + + /** + * Gets tosca property name. + * + * @param translateTo the translate to + * @param heatPropertyName the heat property name + * @return the tosca property name + */ + public static String getToscaPropertyName(TranslateTo translateTo, String heatPropertyName) { + return translateTo.getContext() + .getElementMapping(translateTo.getResource().getType(), Constants.PROP, heatPropertyName); + } + + /** + * Gets tosca attribute name. + * + * @param context the context + * @param heatResourceType the heat resource type + * @param heatAttrName the heat attr name + * @return the tosca attribute name + */ + public static String getToscaAttributeName(TranslationContext context, String heatResourceType, + String heatAttrName) { + return context.getElementMapping(heatResourceType, Constants.ATTR, heatAttrName); + } + + /** + * Gets tosca attribute name. + * + * @param translateTo the translate to + * @param heatAttrName the heat attr name + * @return the tosca attribute name + */ + public static String getToscaAttributeName(TranslateTo translateTo, String heatAttrName) { + return translateTo.getContext() + .getElementMapping(translateTo.getResource().getType(), Constants.ATTR, heatAttrName); + } + + /** + * Create init substitution service template service template. + * + * @param templateName the template name + * @return the service template + */ + public static ServiceTemplate createInitSubstitutionServiceTemplate(String templateName) { + ServiceTemplate nestedSubstitutionServiceTemplate = new ServiceTemplate(); + Map templateMetadata = new HashMap<>(); + templateMetadata.put(ToscaConstants.ST_METADATA_TEMPLATE_NAME, templateName); + nestedSubstitutionServiceTemplate.setMetadata(templateMetadata); + nestedSubstitutionServiceTemplate + .setTosca_definitions_version(ToscaConstants.TOSCA_DEFINITIONS_VERSION); + nestedSubstitutionServiceTemplate.setTopology_template(new TopologyTemplate()); + List> globalTypesImportList = + GlobalTypesGenerator.getGlobalTypesImportList(); + globalTypesImportList.addAll( + HeatToToscaUtil.createImportList(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME)); + nestedSubstitutionServiceTemplate.setImports(globalTypesImportList); + return nestedSubstitutionServiceTemplate; + } + + /** + * Create init global substitution service template service template. + * + * @return the service template + */ + public static ServiceTemplate createInitGlobalSubstitutionServiceTemplate() { + ServiceTemplate globalSubstitutionServiceTemplate = new ServiceTemplate(); + Map templateMetadata = new HashMap<>(); + templateMetadata.put(ToscaConstants.ST_METADATA_TEMPLATE_NAME, + Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME); + globalSubstitutionServiceTemplate.setMetadata(templateMetadata); + globalSubstitutionServiceTemplate + .setImports(GlobalTypesGenerator.getGlobalTypesImportList()); + globalSubstitutionServiceTemplate + .setTosca_definitions_version(ToscaConstants.TOSCA_DEFINITIONS_VERSION); + return globalSubstitutionServiceTemplate; + } + + /** + * Create substitution node type node type. + * + * @param substitutionServiceTemplate the substitution service template + * @return the node type + */ + public NodeType createSubstitutionNodeType(ServiceTemplate substitutionServiceTemplate) { + NodeType substitutionNodeType = new NodeType(); + substitutionNodeType.setDerived_from(ToscaNodeType.ABSTRACT_SUBSTITUTE); + substitutionNodeType.setDescription(substitutionServiceTemplate.getDescription()); + substitutionNodeType + .setProperties(manageSubstitutionNodeTypeProperties(substitutionServiceTemplate)); + substitutionNodeType + .setAttributes(manageSubstitutionNodeTypeAttributes(substitutionServiceTemplate)); + return substitutionNodeType; + } + + private Map manageSubstitutionNodeTypeProperties( + ServiceTemplate substitutionServiceTemplate) { + mdcDataDebugMessage.debugEntryMessage(null, null); + + Map substitutionNodeTypeProperties = new HashMap<>(); + Map properties = + substitutionServiceTemplate.getTopology_template().getInputs(); + if (properties == null) { + mdcDataDebugMessage.debugExitMessage(null, null); + return null; + } + + PropertyDefinition propertyDefinition; + String toscaPropertyName; + for (Map.Entry entry : properties.entrySet()) { + toscaPropertyName = entry.getKey(); + propertyDefinition = new PropertyDefinition(); + ParameterDefinition parameterDefinition = + substitutionServiceTemplate.getTopology_template().getInputs().get(toscaPropertyName); + propertyDefinition.setType(parameterDefinition.getType()); + propertyDefinition.setDescription(parameterDefinition.getDescription()); + propertyDefinition.setRequired(parameterDefinition.getRequired()); + propertyDefinition.set_default(parameterDefinition.get_default()); + propertyDefinition.setConstraints(parameterDefinition.getConstraints()); + propertyDefinition.setEntry_schema(parameterDefinition.getEntry_schema()); + propertyDefinition.setStatus(parameterDefinition.getStatus()); + substitutionNodeTypeProperties.put(toscaPropertyName, propertyDefinition); + } + + mdcDataDebugMessage.debugExitMessage(null, null); + return substitutionNodeTypeProperties; + } + + private Map manageSubstitutionNodeTypeAttributes( + ServiceTemplate substitutionServiceTemplate) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + Map substitutionNodeTypeAttributes = new HashMap<>(); + Map attributes = + substitutionServiceTemplate.getTopology_template().getOutputs(); + if (attributes == null) { + mdcDataDebugMessage.debugExitMessage(null, null); + return null; + } + AttributeDefinition attributeDefinition; + String toscaAttributeName; + + for (Map.Entry entry : attributes.entrySet()) { + attributeDefinition = new AttributeDefinition(); + toscaAttributeName = entry.getKey(); + ParameterDefinition parameterDefinition = + substitutionServiceTemplate.getTopology_template().getOutputs().get(toscaAttributeName); + if (parameterDefinition.getType() != null && !parameterDefinition.getType().isEmpty()) { + attributeDefinition.setType(parameterDefinition.getType()); + } else { + attributeDefinition.setType(PropertyType.STRING.getDisplayName()); + } + attributeDefinition.setDescription(parameterDefinition.getDescription()); + attributeDefinition.set_default(parameterDefinition.get_default()); + attributeDefinition.setEntry_schema(parameterDefinition.getEntry_schema()); + attributeDefinition.setStatus(parameterDefinition.getStatus()); + substitutionNodeTypeAttributes.put(toscaAttributeName, attributeDefinition); + } + + mdcDataDebugMessage.debugExitMessage(null, null); + return substitutionNodeTypeAttributes; + } + + /** + * . + * Create and add substitution mapping to the nested substitution service template, and update + * the subtitution node type accordingly with the exposed requerments and capabilities + * + * @param context the translation context + * @param substitutionNodeTypeKey the substitution node type key + * @param nestedSubstitutionServiceTemplate the nested substitution service template + * @param substitutionNodeType the substitution node type + */ + public static void handleSubstitutionMapping( + TranslationContext context, + String substitutionNodeTypeKey, + ServiceTemplate nestedSubstitutionServiceTemplate, + NodeType substitutionNodeType) { + Map>> substitutionMapping = + getSubstitutionNodeTypeExposedConnectionPoints(substitutionNodeType, + nestedSubstitutionServiceTemplate, context); + //add substitution mapping after capability and requirement expose calculation + nestedSubstitutionServiceTemplate.getTopology_template().setSubstitution_mappings( + createSubstitutionTemplateSubMapping(substitutionNodeTypeKey, + substitutionNodeType, substitutionMapping)); + } + + /** + * Gets node type with flat hierarchy. + * + * @param nodeTypeId the node type id + * @param serviceTemplate the service template + * @param context the context + * @return the node type with flat hierarchy + */ + public static NodeType getNodeTypeWithFlatHierarchy(String nodeTypeId, + ServiceTemplate serviceTemplate, + TranslationContext context) { + ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl(); + ToscaServiceModel toscaServiceModel = HeatToToscaUtil + .getToscaServiceModel(context, serviceTemplate.getMetadata()); + NodeType flatNodeType = (NodeType) toscaAnalyzerService + .getFlatEntity(ToscaElementTypes.NODE_TYPE, nodeTypeId, serviceTemplate, toscaServiceModel); + return flatNodeType; + } + + /** + * Create substitution node template node template. + * + * @param translateTo the translate to + * @param templateName the template name + * @param substitutionNodeTypeKey the substitution node type key + * @return the node template + */ + public NodeTemplate createSubstitutionNodeTemplate(TranslateTo translateTo, String templateName, + String substitutionNodeTypeKey) { + NodeTemplate substitutionNodeTemplate = new NodeTemplate(); + List directiveList = new ArrayList<>(); + directiveList.add(ToscaConstants.NODE_TEMPLATE_DIRECTIVE_SUBSTITUTABLE); + substitutionNodeTemplate.setDirectives(directiveList); + substitutionNodeTemplate.setType(substitutionNodeTypeKey); + substitutionNodeTemplate.setProperties( + managerSubstitutionNodeTemplateProperties(translateTo, substitutionNodeTemplate, + templateName)); + return substitutionNodeTemplate; + } + + /** + * Create abstract substitution node template. + * + * @param translateTo the translate to + * @param templateName the template name + * @param substitutionNodeTypeKey the substitution node type key + * @return the abstract substitute node template + */ + public static NodeTemplate createAbstractSubstitutionNodeTemplate( + TranslateTo translateTo, + String templateName, + String substitutionNodeTypeKey) { + NodeTemplate substitutionNodeTemplate = new NodeTemplate(); + List directiveList = new ArrayList<>(); + directiveList.add(ToscaConstants.NODE_TEMPLATE_DIRECTIVE_SUBSTITUTABLE); + substitutionNodeTemplate.setDirectives(directiveList); + substitutionNodeTemplate.setType(substitutionNodeTypeKey); + substitutionNodeTemplate.setProperties( + managerSubstitutionNodeTemplateProperties(translateTo, substitutionNodeTemplate, + templateName)); + return substitutionNodeTemplate; + } + + + /** + * Checks if the source and target resource is a valid candidate for adding tosca dependency + * relationship. + * + * @param heatOrchestrationTemplate the heat orchestration template + * @param sourceResource the source resource + * @param targetResource the target resource + * @param dependencyEntity the dependency entity + * @return true if the candidate resources are a valid combination for the dependency relationship + * and false otherwise + */ + public static boolean isValidDependsOnCandidate(HeatOrchestrationTemplate + heatOrchestrationTemplate, + Resource sourceResource, + Resource targetResource, + ConsolidationEntityType dependencyEntity, + TranslationContext context) { + dependencyEntity + .setEntityType(heatOrchestrationTemplate, sourceResource, targetResource, context); + ConsolidationEntityType sourceEntityType = dependencyEntity.getSourceEntityType(); + ConsolidationEntityType targetEntityType = dependencyEntity.getTargetEntityType(); + + //Ignore Compute->Port, Compute->volume, Compute->Compute and Compute->VFC Nested relationships + if (sourceEntityType == ConsolidationEntityType.COMPUTE) { + if (targetEntityType == ConsolidationEntityType.COMPUTE + || targetEntityType == ConsolidationEntityType.VOLUME + || targetEntityType == ConsolidationEntityType.PORT + || targetEntityType == ConsolidationEntityType.VFC_NESTED) { + return false; + } + } + //Ignore Port->Compute, Port->volume, Port->Port and Port->VFC Nested relationships + if (sourceEntityType == ConsolidationEntityType.PORT) { + if (targetEntityType == ConsolidationEntityType.COMPUTE + || targetEntityType == ConsolidationEntityType.VOLUME + || targetEntityType == ConsolidationEntityType.PORT + || targetEntityType == ConsolidationEntityType.VFC_NESTED) { + return false; + } + } + + //Ignore Volume->Compute, Volume->Volume, Volume->Port and Volume->VFC Nested relationships + if (sourceEntityType == ConsolidationEntityType.VOLUME) { + if (targetEntityType == ConsolidationEntityType.COMPUTE + || targetEntityType == ConsolidationEntityType.VOLUME + || targetEntityType == ConsolidationEntityType.PORT + || targetEntityType == ConsolidationEntityType.VFC_NESTED) { + return false; + } + } + + //Ignore VFC Nested->Compute, VFC Nested->Volume, VFC Nested->Port and + // VFC Nested->VFC Nested relationships + if (sourceEntityType == ConsolidationEntityType.VFC_NESTED) { + if (targetEntityType == ConsolidationEntityType.COMPUTE + || targetEntityType == ConsolidationEntityType.VOLUME + || targetEntityType == ConsolidationEntityType.PORT + || targetEntityType == ConsolidationEntityType.VFC_NESTED) { + return false; + } + } + return true; + } + + private static Map managerSubstitutionNodeTemplateProperties( + TranslateTo translateTo, + Template template, + String templateName) { + mdcDataDebugMessage.debugEntryMessage(null, null); + + Map substitutionProperties = new HashMap<>(); + Map heatProperties = translateTo.getResource().getProperties(); + if (Objects.nonNull(heatProperties)) { + for (Map.Entry entry : heatProperties.entrySet()) { + Object property = TranslatorHeatToToscaPropertyConverter + .getToscaPropertyValue(translateTo.getServiceTemplate(), + translateTo.getTranslatedId(), entry.getKey(), + entry.getValue(), null, translateTo.getHeatFileName(), + translateTo.getHeatOrchestrationTemplate(), template, translateTo.getContext()); + substitutionProperties.put(entry.getKey(), property); + } + } + + mdcDataDebugMessage.debugExitMessage(null, null); + return addAbstractSubstitutionProperty(templateName, substitutionProperties); + } + + private static Map addAbstractSubstitutionProperty(String templateName, + Map + substitutionProperties) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + Map innerProps = new HashMap<>(); + innerProps.put(ToscaConstants.SUBSTITUTE_SERVICE_TEMPLATE_PROPERTY_NAME, + ToscaUtil.getServiceTemplateFileName(templateName)); + substitutionProperties.put(ToscaConstants.SERVICE_TEMPLATE_FILTER_PROPERTY_NAME, innerProps); + + mdcDataDebugMessage.debugExitMessage(null, null); + return substitutionProperties; + } + + private static SubstitutionMapping createSubstitutionTemplateSubMapping( + String nodeTypeKey, + NodeType substitutionNodeType, + Map>> mapping) { + mdcDataDebugMessage.debugEntryMessage(null, null); + SubstitutionMapping substitutionMapping = new SubstitutionMapping(); + substitutionMapping.setNode_type(nodeTypeKey); + substitutionMapping.setCapabilities( + manageCapabilityMapping(substitutionNodeType.getCapabilities(), mapping.get("capability"))); + substitutionMapping.setRequirements( + manageRequirementMapping(substitutionNodeType.getRequirements(), + mapping.get("requirement"))); + + mdcDataDebugMessage.debugExitMessage(null, null); + return substitutionMapping; + } + + private static Map> manageRequirementMapping( + List> requirementList, + Map> requirementSubstitutionMapping) { + mdcDataDebugMessage.debugEntryMessage(null, null); + + if (requirementList == null) { + return null; + } + Map> requirementMapping = new HashMap<>(); + String requirementKey; + List requirementMap; + for (Map requirementDefMap : requirementList) { + for (Map.Entry entry : requirementDefMap.entrySet()) { + requirementKey = entry.getKey(); + requirementMap = requirementSubstitutionMapping.get(requirementKey); + requirementMapping.put(requirementKey, requirementMap); + } + } + + mdcDataDebugMessage.debugExitMessage(null, null); + return requirementMapping; + } + + private static Map> manageCapabilityMapping( + Map capabilities, + Map> capabilitySubstitutionMapping) { + mdcDataDebugMessage.debugEntryMessage(null, null); + + if (capabilities == null) { + mdcDataDebugMessage.debugExitMessage(null, null); + return null; + } + + Map> capabilityMapping = new HashMap<>(); + String capabilityKey; + List capabilityMap; + for (Map.Entry entry : capabilities.entrySet()) { + capabilityKey = entry.getKey(); + capabilityMap = capabilitySubstitutionMapping.get(capabilityKey); + capabilityMapping.put(capabilityKey, capabilityMap); + } + + mdcDataDebugMessage.debugExitMessage(null, null); + return capabilityMapping; + } + + private static Map>> + getSubstitutionNodeTypeExposedConnectionPoints(NodeType substitutionNodeType, + ServiceTemplate substitutionServiceTemplate, + TranslationContext context) { + mdcDataDebugMessage.debugEntryMessage(null, null); + + Map nodeTemplates = + substitutionServiceTemplate.getTopology_template().getNode_templates(); + String nodeTemplateId; + NodeTemplate nodeTemplate; + String nodeType; + Map>> substitutionMapping = new HashMap<>(); + if (nodeTemplates == null) { + return substitutionMapping; + } + + Map> capabilitySubstitutionMapping = new HashMap<>(); + Map> requirementSubstitutionMapping = new HashMap<>(); + substitutionMapping.put("capability", capabilitySubstitutionMapping); + substitutionMapping.put("requirement", requirementSubstitutionMapping); + List> nodeTypeRequirementsDefinition; + Map nodeTemplateRequirementsAssignment; + List> exposedRequirementsDefinition; + Map> fullFilledRequirementsDefinition = + new HashMap<>(); + Map nodeTypeCapabilitiesDefinition = new HashMap<>(); + Map exposedCapabilitiesDefinition; + + for (Map.Entry entry : nodeTemplates.entrySet()) { + nodeTemplateId = entry.getKey(); + nodeTemplate = entry.getValue(); + nodeType = nodeTemplate.getType(); + + // get requirements + nodeTypeRequirementsDefinition = + getNodeTypeReqs(nodeType, nodeTemplateId, substitutionServiceTemplate, + requirementSubstitutionMapping, context); + nodeTemplateRequirementsAssignment = DataModelUtil.getNodeTemplateRequirements(nodeTemplate); + fullFilledRequirementsDefinition.put(nodeTemplateId, nodeTemplateRequirementsAssignment); + //set substitution node type requirements + exposedRequirementsDefinition = calculateExposedRequirements(nodeTypeRequirementsDefinition, + nodeTemplateRequirementsAssignment); + addSubstitutionNodeTypeRequirements(substitutionNodeType, exposedRequirementsDefinition, + nodeTemplateId); + + //get capabilities + addNodeTypeCapabilitiesToSubMapping(nodeTypeCapabilitiesDefinition, + capabilitySubstitutionMapping, nodeType, + nodeTemplateId, substitutionServiceTemplate, context); + } + + exposedCapabilitiesDefinition = calculateExposedCapabilities(nodeTypeCapabilitiesDefinition, + fullFilledRequirementsDefinition); + DataModelUtil.addNodeTypeCapabilitiesDef(substitutionNodeType, exposedCapabilitiesDefinition); + + mdcDataDebugMessage.debugExitMessage(null, null); + return substitutionMapping; + } + + private static Map calculateExposedCapabilities( + Map nodeTypeCapabilitiesDefinition, + Map> fullFilledRequirementsDefinitionMap) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + String capabilityKey; + String capability; + String node; + for (Map.Entry> entry : + fullFilledRequirementsDefinitionMap.entrySet()) { + for (Map.Entry fullFilledEntry : entry.getValue().entrySet()) { + + capability = fullFilledEntry.getValue().getCapability(); + fullFilledEntry.getValue().getOccurrences(); + node = fullFilledEntry.getValue().getNode(); + capabilityKey = capability + "_" + node; + CapabilityDefinition capabilityDefinition = nodeTypeCapabilitiesDefinition.get( + capabilityKey); + if (capabilityDefinition != null) { + CapabilityDefinition clonedCapabilityDefinition = capabilityDefinition.clone(); + nodeTypeCapabilitiesDefinition.put(capabilityKey, capabilityDefinition.clone()); + if (evaluateCapabilityFulfillment(clonedCapabilityDefinition)) { + nodeTypeCapabilitiesDefinition.remove(capabilityKey); + } else { + nodeTypeCapabilitiesDefinition.put(capabilityKey, clonedCapabilityDefinition); + } + } + } + } + + Map exposedCapabilitiesDefinition = new HashMap<>(); + for (Map.Entry entry : nodeTypeCapabilitiesDefinition + .entrySet()) { + exposedCapabilitiesDefinition.put(entry.getKey(), entry.getValue()); + } + + mdcDataDebugMessage.debugExitMessage(null, null); + return exposedCapabilitiesDefinition; + } + + private static void addNodeTypeCapabilitiesToSubMapping( + Map nodeTypeCapabilitiesDefinition, + Map> capabilitySubstitutionMapping, String type, String templateName, + ServiceTemplate serviceTemplate, TranslationContext context) { + mdcDataDebugMessage.debugEntryMessage(null, null); + + NodeType flatNodeType = + getNodeTypeWithFlatHierarchy(type, serviceTemplate, context); + String capabilityKey; + List capabilityMapping; + if (flatNodeType.getCapabilities() != null) { + for (Map.Entry capabilityNodeEntry : flatNodeType + .getCapabilities() + .entrySet()) { + capabilityKey = capabilityNodeEntry.getKey() + "_" + templateName; + nodeTypeCapabilitiesDefinition.put(capabilityKey, capabilityNodeEntry.getValue().clone()); + capabilityMapping = new ArrayList<>(); + capabilityMapping.add(templateName); + capabilityMapping.add(capabilityNodeEntry.getKey()); + capabilitySubstitutionMapping.put(capabilityKey, capabilityMapping); + } + } + mdcDataDebugMessage.debugExitMessage(null, null); + } + + private static void addSubstitutionNodeTypeRequirements(NodeType substitutionNodeType, + List> + requirementsList, + String templateName) { + mdcDataDebugMessage.debugEntryMessage(null, null); + + if (requirementsList == null || requirementsList.size() == 0) { + return; + } + + if (substitutionNodeType.getRequirements() == null) { + substitutionNodeType.setRequirements(new ArrayList<>()); + } + + for (Map requirementDef : requirementsList) { + for (Map.Entry entry : requirementDef.entrySet()) { + Map requirementMap = new HashMap<>(); + requirementMap.put(entry.getKey() + "_" + templateName, entry.getValue().clone()); + substitutionNodeType.getRequirements().add(requirementMap); + } + } + + mdcDataDebugMessage.debugExitMessage(null, null); + } + + private static List> getNodeTypeReqs( + String type, + String templateName, + ServiceTemplate serviceTemplate, + Map> requirementSubstitutionMapping, + TranslationContext context) { + mdcDataDebugMessage.debugEntryMessage(null, null); + List> requirementList = new ArrayList<>(); + NodeType flatNodeType = + getNodeTypeWithFlatHierarchy(type, serviceTemplate, context); + List requirementMapping; + + if (flatNodeType.getRequirements() != null) { + for (Map requirementMap : flatNodeType.getRequirements()) { + for (Map.Entry requirementNodeEntry : requirementMap + .entrySet()) { + ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil(); + RequirementDefinition requirementNodeEntryValue = toscaExtensionYamlUtil + .yamlToObject(toscaExtensionYamlUtil.objectToYaml(requirementNodeEntry.getValue()), + RequirementDefinition.class); + if (requirementNodeEntryValue.getOccurrences() == null) { + requirementNodeEntryValue.setOccurrences(new Object[]{1, 1}); + } + Map requirementDef = new HashMap<>(); + requirementDef.put(requirementNodeEntry.getKey(), requirementNodeEntryValue); + DataModelUtil.addRequirementToList(requirementList, requirementDef); + requirementMapping = new ArrayList<>(); + requirementMapping.add(templateName); + requirementMapping.add(requirementNodeEntry.getKey()); + requirementSubstitutionMapping + .put(requirementNodeEntry.getKey() + "_" + templateName, requirementMapping); + if (requirementNodeEntryValue.getNode() == null) { + requirementNodeEntryValue.setOccurrences(new Object[]{1, 1}); + } + } + } + } + + mdcDataDebugMessage.debugExitMessage(null, null); + return requirementList; + } + + private static List> calculateExposedRequirements( + List> nodeTypeRequirementsDefinitionList, + Map nodeTemplateRequirementsAssignment) { + mdcDataDebugMessage.debugEntryMessage(null, null); + + if (nodeTypeRequirementsDefinitionList == null) { + return null; + } + for (Map.Entry entry : nodeTemplateRequirementsAssignment + .entrySet()) { + if (entry.getValue().getNode() != null) { + Optional requirementDefinition = + DataModelUtil.getRequirementDefinition(nodeTypeRequirementsDefinitionList, entry + .getKey()); + RequirementDefinition cloneRequirementDefinition; + if (requirementDefinition.isPresent()) { + cloneRequirementDefinition = requirementDefinition.get().clone(); + if (!evaluateRequirementFulfillment(cloneRequirementDefinition)) { + CommonMethods.mergeEntryInList(entry.getKey(), cloneRequirementDefinition, + nodeTypeRequirementsDefinitionList); + } else { + DataModelUtil.removeRequirementsDefinition(nodeTypeRequirementsDefinitionList, entry + .getKey()); + } + } + } else { + for (Map nodeTypeRequirementsMap : + nodeTypeRequirementsDefinitionList) { + Object max = nodeTypeRequirementsMap.get(entry.getKey()).getOccurrences() != null + && nodeTypeRequirementsMap.get(entry.getKey()).getOccurrences().length > 0 + ? nodeTypeRequirementsMap.get(entry.getKey()).getOccurrences()[1] : 1; + Object min = nodeTypeRequirementsMap.get(entry.getKey()).getOccurrences() != null + && nodeTypeRequirementsMap.get(entry.getKey()).getOccurrences().length > 0 + ? nodeTypeRequirementsMap.get(entry.getKey()).getOccurrences()[0] : 1; + nodeTypeRequirementsMap.get(entry.getKey()).setOccurrences(new Object[]{min, max}); + } + } + } + + mdcDataDebugMessage.debugExitMessage(null, null); + return nodeTypeRequirementsDefinitionList; + } + + private static boolean evaluateRequirementFulfillment(RequirementDefinition + requirementDefinition) { + Object[] occurrences = requirementDefinition.getOccurrences(); + if (occurrences == null) { + requirementDefinition.setOccurrences(new Object[]{1, 1}); + return false; + } + if (occurrences[1].equals(ToscaConstants.UNBOUNDED)) { + return false; + } + + if (occurrences[1].equals(1)) { + return true; + } + occurrences[1] = (Integer) occurrences[1] - 1; + return false; + } + + private static boolean evaluateCapabilityFulfillment(CapabilityDefinition capabilityDefinition) { + + Object[] occurrences = capabilityDefinition.getOccurrences(); + if (occurrences == null) { + capabilityDefinition.setOccurrences(new Object[]{1, ToscaConstants.UNBOUNDED}); + return false; + } + if (occurrences[1].equals(ToscaConstants.UNBOUNDED)) { + return false; + } + + if (occurrences[1].equals(1)) { + return true; + } + occurrences[1] = (Integer) occurrences[1] - 1; + return false; + } + + /** + * Fetch global substitution service template service template. + * + * @param serviceTemplate the service template + * @param context the context + * @return the service template + */ + public static ServiceTemplate fetchGlobalSubstitutionServiceTemplate( + ServiceTemplate serviceTemplate, + TranslationContext context) { + ServiceTemplate globalSubstitutionServiceTemplate = + context.getTranslatedServiceTemplates() + .get(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME); + if (globalSubstitutionServiceTemplate == null) { + globalSubstitutionServiceTemplate = + HeatToToscaUtil.createInitGlobalSubstitutionServiceTemplate(); + context.getTranslatedServiceTemplates() + .put(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME, + globalSubstitutionServiceTemplate); + } + boolean isImportAddedToServiceTemplate = + DataModelUtil.isImportAddedToServiceTemplate(serviceTemplate.getImports(), Constants + .GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME); + if (!isImportAddedToServiceTemplate) { + serviceTemplate.getImports() + .addAll( + HeatToToscaUtil.createImportList(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME)); + } + return globalSubstitutionServiceTemplate; + } + + public static List> createImportList(String templateName) { + List> imports = new ArrayList<>(); + Map importsMap = new HashMap<>(); + importsMap.put(templateName, HeatToToscaUtil.createServiceTemplateImport(templateName)); + imports.add(importsMap); + return imports; + } + + /** + * Create service template import import. + * + * @param serviceTemplate the service template + * @return the import + */ + public static Import createServiceTemplateImport(ServiceTemplate serviceTemplate) { + Import serviceTemplateImport = new Import(); + serviceTemplateImport.setFile(ToscaUtil.getServiceTemplateFileName(serviceTemplate)); + return serviceTemplateImport; + } + + /** + * Create service template import import. + * + * @param metadataTemplateName the service template name + * @return the import + */ + public static Import createServiceTemplateImport(String metadataTemplateName) { + Import serviceTemplateImport = new Import(); + serviceTemplateImport.setFile(ToscaUtil.getServiceTemplateFileName(metadataTemplateName)); + return serviceTemplateImport; + } + + public static ToscaServiceModel createToscaServiceModel(ServiceTemplate + entryDefinitionServiceTemplate, + TranslationContext translationContext) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + mdcDataDebugMessage.debugExitMessage(null, null); + return new ToscaServiceModel(getCsarArtifactFiles(translationContext), + getServiceTemplates(translationContext), + ToscaUtil.getServiceTemplateFileName(entryDefinitionServiceTemplate)); + } + + private static FileContentHandler getCsarArtifactFiles(TranslationContext translationContext) { + + mdcDataDebugMessage.debugEntryMessage(null, null); + + FileContentHandler artifactFiles = new FileContentHandler(); + artifactFiles.setFiles(translationContext.getFiles()); + artifactFiles.setFiles(translationContext.getExternalArtifacts()); + + HeatTreeManager heatTreeManager = + HeatTreeManagerUtil.initHeatTreeManager(translationContext.getFiles()); + heatTreeManager.createTree(); + ValidationStructureList validationStructureList = + new ValidationStructureList(heatTreeManager.getTree()); + byte[] validationStructureFile = + FileUtils.convertToBytes(validationStructureList, FileUtils.FileExtension.JSON); + artifactFiles.addFile("HEAT.meta", validationStructureFile); + + mdcDataDebugMessage.debugExitMessage(null, null); + return artifactFiles; + } + + + private static Map getServiceTemplates(TranslationContext + translationContext) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + List serviceTemplates = new ArrayList<>(); + serviceTemplates.addAll(GlobalTypesGenerator.getGlobalTypesServiceTemplate().values()); + serviceTemplates.addAll(translationContext.getTranslatedServiceTemplates().values()); + Map serviceTemplatesMap = new HashMap<>(); + + for (ServiceTemplate template : serviceTemplates) { + serviceTemplatesMap.put(ToscaUtil.getServiceTemplateFileName(template), template); + } + + mdcDataDebugMessage.debugExitMessage(null, null); + return serviceTemplatesMap; + } + } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/NameExtractor.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/NameExtractor.java new file mode 100644 index 0000000000..fc4c3f8841 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/NameExtractor.java @@ -0,0 +1,34 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.translator.services.heattotosca; + +import org.openecomp.sdc.heat.datatypes.model.Resource; +import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; + +import java.util.List; +import java.util.Map; +import java.util.Optional; + +public interface NameExtractor { + + String extractNodeTypeName(Resource resource, String resourceId, String translatedId); + +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/NameExtractorUtil.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/NameExtractorUtil.java new file mode 100644 index 0000000000..8241603fed --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/NameExtractorUtil.java @@ -0,0 +1,77 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.translator.services.heattotosca; + +import org.openecomp.sdc.translator.datatypes.heattotosca.AttachedPropertyVal; +import org.openecomp.sdc.translator.datatypes.heattotosca.AttachedResourceId; +import org.openecomp.sdc.translator.datatypes.heattotosca.PropertyRegexMatcher; + +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.regex.Pattern; + +public class NameExtractorUtil { + + /** + * Extract Node Type Name By Properties Priority. + * @param properties properties list + * @param propertiesRegexMatchers Regex expression list + * @return node type name + */ + public static Optional extractNodeTypeNameByPropertiesPriority( + Map properties, + List propertiesRegexMatchers) { + + for (PropertyRegexMatcher propertyRegexMatcher : propertiesRegexMatchers) { + Optional parameterNameValue = + HeatToToscaUtil.getPropertyParameterNameValue( + properties.get(propertyRegexMatcher.getPropertyName())); + if (parameterNameValue.isPresent()) { + if (isPropertyValueMatchNamingConvention(propertyRegexMatcher, parameterNameValue.get())) { + return Optional.of(parameterNameValue.get().substring(0, parameterNameValue.get() + .lastIndexOf(propertyRegexMatcher.getStringToSearchForPropertyValue()))); + } + } + } + return Optional.empty(); + } + + /** + * Check if property value match the naming convention using Regex expression. + * @param propertyRegexMatcher naming convention using Regex expression + * @param propertyValue property value + * @return true is there is a match, false otherwise + */ + public static boolean isPropertyValueMatchNamingConvention(PropertyRegexMatcher + propertyRegexMatcher, + String propertyValue) { + for (Pattern pattern : propertyRegexMatcher.getRegexPatterns()) { + if (pattern.matcher(propertyValue).matches()) { + return true; + } + } + return false; + } + + +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ResourceTranslation.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ResourceTranslation.java index 231eb42c03..634e703f5e 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ResourceTranslation.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ResourceTranslation.java @@ -24,9 +24,11 @@ package org.openecomp.sdc.translator.services.heattotosca; import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate; import org.openecomp.sdc.heat.datatypes.model.Resource; import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; +import org.openecomp.sdc.translator.datatypes.heattotosca.TranslationContext; import java.util.Optional; + public interface ResourceTranslation { //return the Id of translated object (NodeTemplate, RelationshipTemplate and etc) diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ResourceTranslationFactory.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ResourceTranslationFactory.java index 730c2ddd7a..ab8230d946 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ResourceTranslationFactory.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/ResourceTranslationFactory.java @@ -21,87 +21,56 @@ package org.openecomp.sdc.translator.services.heattotosca; -import org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes; +import org.openecomp.config.api.Configuration; +import org.openecomp.config.api.ConfigurationManager; +import org.openecomp.core.utilities.CommonMethods; +import org.openecomp.sdc.datatypes.configuration.ImplementationConfiguration; import org.openecomp.sdc.heat.datatypes.model.Resource; +import org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation.ResourceTranslationBase; -import org.openecomp.sdc.translator.services.heattotosca.impl.ResourceTranslationBase; -import org.openecomp.sdc.translator.services.heattotosca.impl.ResourceTranslationCinderVolumeAttachmentImpl; -import org.openecomp.sdc.translator.services.heattotosca.impl.ResourceTranslationCinderVolumeImpl; -import org.openecomp.sdc.translator.services.heattotosca.impl.ResourceTranslationContrailAttachPolicyImpl; -import org.openecomp.sdc.translator.services.heattotosca.impl.ResourceTranslationContrailNetworkPolicyImpl; -import org.openecomp.sdc.translator.services.heattotosca.impl.ResourceTranslationContrailServiceInstanceImpl; -import org.openecomp.sdc.translator.services.heattotosca.impl.ResourceTranslationContrailServiceTemplateImpl; -import org.openecomp.sdc.translator.services.heattotosca.impl.ResourceTranslationContrailV2NetworkPolicyImpl; -import org.openecomp.sdc.translator.services.heattotosca.impl.ResourceTranslationContrailV2VirtualNetworkImpl; -import org.openecomp.sdc.translator.services.heattotosca.impl.ResourceTranslationContrailV2VmInterfaceImpl; -import org.openecomp.sdc.translator.services.heattotosca.impl.ResourceTranslationContrailVirtualNetworkImpl; -import org.openecomp.sdc.translator.services.heattotosca.impl.ResourceTranslationDefaultImpl; -import org.openecomp.sdc.translator.services.heattotosca.impl.ResourceTranslationNestedImpl; -import org.openecomp.sdc.translator.services.heattotosca.impl.ResourceTranslationNeutronNetImpl; -import org.openecomp.sdc.translator.services.heattotosca.impl.ResourceTranslationNeutronPortImpl; -import org.openecomp.sdc.translator.services.heattotosca.impl.ResourceTranslationNeutronSecurityGroupImpl; -import org.openecomp.sdc.translator.services.heattotosca.impl.ResourceTranslationNeutronSubnetImpl; -import org.openecomp.sdc.translator.services.heattotosca.impl.ResourceTranslationNovaServerGroupsImpl; -import org.openecomp.sdc.translator.services.heattotosca.impl.ResourceTranslationNovaServerImpl; -import org.openecomp.sdc.translator.services.heattotosca.impl.ResourceTranslationResourceGroupImpl; +import java.util.Map; -import java.util.Objects; public class ResourceTranslationFactory { + private static Map resourceTranslationImplMap; + + static { + Configuration config = ConfigurationManager.lookup(); + resourceTranslationImplMap = config.populateMap(ConfigConstants.TRANSLATOR_NAMESPACE, + ConfigConstants.RESOURCE_TRANSLATION_IMPL_KEY, ImplementationConfiguration.class); + resourceTranslationImplMap.putAll(config.populateMap(ConfigConstants.MANDATORY_TRANSLATOR_NAMESPACE, + ConfigConstants.RESOURCE_TRANSLATION_IMPL_KEY, ImplementationConfiguration.class)); + } /** - * Gets instance. + * Gets resource translation instance. * * @param resource the resource * @return the instance */ public static ResourceTranslationBase getInstance(Resource resource) { - HeatResourcesTypes heatResource = HeatResourcesTypes.findByHeatResource(resource.getType()); - if (Objects.isNull(heatResource)) { - if (HeatToToscaUtil.isYmlFileType(resource.getType())) { - return new ResourceTranslationNestedImpl(); - } - return new ResourceTranslationDefaultImpl(); - } - switch (heatResource) { - case NOVA_SERVER_RESOURCE_TYPE: - return new ResourceTranslationNovaServerImpl(); - case NOVA_SERVER_GROUP_RESOURCE_TYPE: - return new ResourceTranslationNovaServerGroupsImpl(); - case NEUTRON_SECURITY_GROUP_RESOURCE_TYPE: - return new ResourceTranslationNeutronSecurityGroupImpl(); - case NEUTRON_PORT_RESOURCE_TYPE: - return new ResourceTranslationNeutronPortImpl(); - case CONTRAIL_VIRTUAL_NETWORK_RESOURCE_TYPE: - return new ResourceTranslationContrailVirtualNetworkImpl(); - case CONTRAIL_V2_VIRTUAL_NETWORK_RESOURCE_TYPE: - return new ResourceTranslationContrailV2VirtualNetworkImpl(); - case CONTRAIL_V2_VIRTUAL_MACHINE_INTERFACE_RESOURCE_TYPE: - return new ResourceTranslationContrailV2VmInterfaceImpl(); - case CINDER_VOLUME_RESOURCE_TYPE: - return new ResourceTranslationCinderVolumeImpl(); - case CINDER_VOLUME_ATTACHMENT_RESOURCE_TYPE: - return new ResourceTranslationCinderVolumeAttachmentImpl(); - case NEUTRON_NET_RESOURCE_TYPE: - return new ResourceTranslationNeutronNetImpl(); - case NEUTRON_SUBNET_RESOURCE_TYPE: - return new ResourceTranslationNeutronSubnetImpl(); - case CONTRAIL_NETWORK_RULE_RESOURCE_TYPE: - return new ResourceTranslationContrailNetworkPolicyImpl(); - case CONTRAIL_V2_NETWORK_RULE_RESOURCE_TYPE: - return new ResourceTranslationContrailV2NetworkPolicyImpl(); - case CONTRAIL_NETWORK_ATTACH_RULE_RESOURCE_TYPE: - return new ResourceTranslationContrailAttachPolicyImpl(); - case RESOURCE_GROUP_RESOURCE_TYPE: - return new ResourceTranslationResourceGroupImpl(); - case CONTRAIL_SERVICE_TEMPLATE: - return new ResourceTranslationContrailServiceTemplateImpl(); - case CONTRAIL_SERVICE_INSTANCE: - return new ResourceTranslationContrailServiceInstanceImpl(); - default: - return new ResourceTranslationDefaultImpl(); + if (isSupportedResource(resource.getType())) { + return getResourceTranslationImpl(resource.getType()); + } else if (HeatToToscaUtil.isYmlFileType(resource.getType())) { + return getResourceTranslationImpl(ConfigConstants.NESTED_RESOURCE_TRANSLATION_IMPL_KEY); } + return getResourceTranslationImpl(ConfigConstants.DEFAULT_RESOURCE_TRANSLATION_IMPL_KEY); + } + + private static ResourceTranslationBase getResourceTranslationImpl(String resourceImplKey) { + String resourceTranslationImplClassName = resourceTranslationImplMap + .get(resourceImplKey).getImplementationClass(); + return CommonMethods + .newInstance(resourceTranslationImplClassName, ResourceTranslationBase.class); } + private static boolean isSupportedResource(String resourceType) { + if (resourceTranslationImplMap.containsKey(resourceType) + && resourceTranslationImplMap.get(resourceType).isEnable()) { + return true; + } + return false; + } } + diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/TranslationContext.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/TranslationContext.java deleted file mode 100644 index a242eda3f0..0000000000 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/TranslationContext.java +++ /dev/null @@ -1,172 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.translator.services.heattotosca; - -import org.openecomp.core.utilities.file.FileContentHandler; -import org.openecomp.core.utilities.file.FileUtils; -import org.openecomp.core.utilities.json.JsonUtil; -import org.openecomp.sdc.common.utils.AsdcCommon; -import org.openecomp.sdc.heat.datatypes.manifest.FileData; -import org.openecomp.sdc.heat.datatypes.manifest.ManifestFile; -import org.openecomp.sdc.heat.datatypes.model.Resource; -import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; -import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslatedHeatResource; -import org.openecomp.sdc.translator.services.heattotosca.globaltypes.GlobalTypesGenerator; - -import java.io.InputStream; -import java.util.HashMap; -import java.util.HashSet; -import java.util.Map; -import java.util.Set; - - -public class TranslationContext { - - - private static Map>> translationMapping; - private static Map globalServiceTemplates; - - static { - - String propertyFileName = AsdcCommon.HEAT_TO_TOSCA_MAPPING_CONF; - InputStream is = FileUtils.getFileInputStream(propertyFileName); - translationMapping = JsonUtil.json2Object(is, Map.class); - globalServiceTemplates = GlobalTypesGenerator.getGlobalTypesServiceTemplate(); - } - - private ManifestFile manifest; - - private FileContentHandler files = new FileContentHandler(); - - private Map manifestFiles = new HashMap<>(); - //Key - file name, value - file type - private Set nestedHeatsFiles = new HashSet<>(); - private FileContentHandler externalArtifacts = new FileContentHandler(); - - private Map> translatedResources = new HashMap<>(); - // Key - heat file name,value - set of heat resource ids which were translated - private Map> heatStackGroupMembers = new HashMap<>(); - // Key - heat file name, value - translated Node template id - private Map> translatedIds = new HashMap<>(); - // Key - heat file name, value - Map with Key - heat resource Id, Value - tosca entity template id - private Map translatedServiceTemplates = new HashMap<>(); - // key - service template type, value - translated service templates - private Map heatSharedResourcesByParam = new HashMap<>(); - //key - heat param name, value - shared resource data - - public void addManifestFile(String fileName, FileData.Type fileType) { - this.manifestFiles.put(fileName, fileType); - } - - public Set getNestedHeatsFiles() { - return nestedHeatsFiles; - } - - public Map> getHeatStackGroupMembers() { - return heatStackGroupMembers; - } - - public FileContentHandler getFiles() { - return files; - } - - public void setFiles(Map files) { - this.files.putAll(files); - } - - public InputStream getFileContent(String fileName) { - return files.getFileContent(fileName); - } - - public void addFile(String name, byte[] content) { - files.addFile(name, content); - } - - public ManifestFile getManifest() { - return manifest; - } - - public void setManifest(ManifestFile manifest) { - this.manifest = manifest; - } - - public Map> getTranslatedResources() { - return translatedResources; - } - - public Map> getTranslatedIds() { - return translatedIds; - } - - // get tosca name from mapping configuration file - //element type - parameter/attribute - // element name - heat parameter/attribute name - //return value - tosca parameter/attribute name - public String getElementMapping(String resourceType, String elementType, String elementName) { - return translationMapping.get(resourceType).get(elementType).get(elementName); - } - - public Map getElementMapping(String resourceType, String elementType) { - return translationMapping.get(resourceType).get(elementType); - } - - public Set getElementSet(String resourceType, String elementType) { - return translationMapping.get(resourceType).get(elementType).keySet(); - } - - public Map getTranslatedServiceTemplates() { - return translatedServiceTemplates; - } - - public ServiceTemplate getGlobalSubstitutionServiceTemplate() { - return getTranslatedServiceTemplates().get(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME); - } - - public FileContentHandler getExternalArtifacts() { - return externalArtifacts; - } - - public void addExternalArtifacts(String name, byte[] content) { - this.externalArtifacts.addFile(name, content); - } - - - public Map getHeatSharedResourcesByParam() { - return heatSharedResourcesByParam; - } - - public void addHeatSharedResourcesByParam(String parameterName, String resourceId, - Resource resource) { - this.addHeatSharedResourcesByParam(parameterName, - new TranslatedHeatResource(resourceId, resource)); - } - - public void addHeatSharedResourcesByParam(String parameterName, - TranslatedHeatResource translatedHeatResource) { - this.heatSharedResourcesByParam.put(parameterName, translatedHeatResource); - } - - public Map getGlobalServiceTemplates() { - return globalServiceTemplates; - } - - -} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/TranslationService.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/TranslationService.java index 1d90d8b2af..ab41d43cc9 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/TranslationService.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/TranslationService.java @@ -20,11 +20,13 @@ package org.openecomp.sdc.translator.services.heattotosca; +import org.apache.commons.collections4.MapUtils; import org.openecomp.core.translator.datatypes.TranslatorOutput; import org.openecomp.core.utilities.file.FileContentHandler; import org.openecomp.core.utilities.file.FileUtils; import org.openecomp.core.utilities.yaml.YamlUtil; import org.openecomp.sdc.common.errors.CoreException; +import org.openecomp.sdc.datatypes.error.ErrorLevel; import org.openecomp.sdc.heat.datatypes.manifest.FileData; import org.openecomp.sdc.heat.datatypes.model.Environment; import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate; @@ -33,38 +35,50 @@ import org.openecomp.sdc.heat.datatypes.model.Resource; import org.openecomp.sdc.heat.datatypes.structure.ValidationStructureList; import org.openecomp.sdc.heat.services.tree.HeatTreeManager; import org.openecomp.sdc.heat.services.tree.HeatTreeManagerUtil; +import org.openecomp.sdc.logging.api.Logger; +import org.openecomp.sdc.logging.api.LoggerFactory; +import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; +import org.openecomp.sdc.logging.context.impl.MdcDataErrorMessage; +import org.openecomp.sdc.logging.types.LoggerConstants; +import org.openecomp.sdc.logging.types.LoggerErrorCode; +import org.openecomp.sdc.logging.types.LoggerErrorDescription; +import org.openecomp.sdc.logging.types.LoggerTragetServiceName; import org.openecomp.sdc.tosca.datatypes.ToscaGroupType; import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel; import org.openecomp.sdc.tosca.datatypes.model.GroupDefinition; -import org.openecomp.sdc.tosca.datatypes.model.Metadata; +import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; import org.openecomp.sdc.tosca.datatypes.model.ParameterDefinition; +import org.openecomp.sdc.tosca.datatypes.model.PropertyType; import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; import org.openecomp.sdc.tosca.datatypes.model.TopologyTemplate; +import org.openecomp.sdc.tosca.services.DataModelUtil; import org.openecomp.sdc.tosca.services.ToscaConstants; import org.openecomp.sdc.tosca.services.ToscaFileOutputService; import org.openecomp.sdc.tosca.services.ToscaUtil; import org.openecomp.sdc.tosca.services.impl.ToscaFileOutputServiceCsarImpl; import org.openecomp.sdc.translator.datatypes.heattotosca.AttachedResourceId; +import org.openecomp.sdc.translator.datatypes.heattotosca.TranslationContext; import org.openecomp.sdc.translator.datatypes.heattotosca.to.FileDataCollection; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.EntityConsolidationData; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.GetAttrFuncData; import org.openecomp.sdc.translator.services.heattotosca.errors.ResourceNotFoundInHeatFileErrorBuilder; import org.openecomp.sdc.translator.services.heattotosca.globaltypes.GlobalTypesGenerator; import org.openecomp.sdc.translator.services.heattotosca.mapping.TranslatorHeatToToscaParameterConverter; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; import java.util.ArrayList; import java.util.HashMap; import java.util.HashSet; +import java.util.Iterator; import java.util.List; import java.util.Map; import java.util.Objects; import java.util.Optional; import java.util.Set; - public class TranslationService { - protected static Logger logger = LoggerFactory.getLogger(TranslationService.class); + protected static Logger logger = (Logger) LoggerFactory.getLogger(TranslationService.class); + protected static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); /** * Gets types to process by translator. @@ -85,6 +99,8 @@ public class TranslationService { * @return the translator output */ public TranslatorOutput translateHeatFiles(TranslationContext translationContext) { + mdcDataDebugMessage.debugEntryMessage(null, null); + ServiceTemplate mainServiceTemplate = createMainServiceTemplate(translationContext); List fileDataList = translationContext.getManifest().getContent().getData(); FileDataCollection fileDataCollection = HeatToToscaUtil.getFileCollectionsByFilter(fileDataList, @@ -102,59 +118,31 @@ public class TranslationService { } ToscaServiceModel toscaServiceModel = - createToscaServiceModel(mainServiceTemplate, translationContext); + HeatToToscaUtil.createToscaServiceModel(mainServiceTemplate, translationContext); TranslatorOutput translatorOutput = new TranslatorOutput(); translatorOutput.setToscaServiceModel(toscaServiceModel); - return translatorOutput; - } - private ToscaServiceModel createToscaServiceModel(ServiceTemplate entryDefinitionServiceTemplate, - TranslationContext translationContext) { - return new ToscaServiceModel(getCsarArtifactFiles(translationContext), - getServiceTemplates(translationContext), - ToscaUtil.getServiceTemplateFileName(entryDefinitionServiceTemplate)); + mdcDataDebugMessage.debugExitMessage(null, null); + return translatorOutput; } - private Map getServiceTemplates(TranslationContext translationContext) { - List serviceTemplates = new ArrayList<>(); - serviceTemplates.addAll(GlobalTypesGenerator.getGlobalTypesServiceTemplate().values()); - serviceTemplates.addAll(translationContext.getTranslatedServiceTemplates().values()); - Map serviceTemplatesMap = new HashMap<>(); + private ServiceTemplate createMainServiceTemplate(TranslationContext translationContext) { - for (ServiceTemplate template : serviceTemplates) { - serviceTemplatesMap.put(ToscaUtil.getServiceTemplateFileName(template), template); - } - return serviceTemplatesMap; - } - private FileContentHandler getCsarArtifactFiles(TranslationContext translationContext) { - FileContentHandler artifactFiles = new FileContentHandler(); - artifactFiles.setFiles(translationContext.getFiles()); - artifactFiles.setFiles(translationContext.getExternalArtifacts()); - - HeatTreeManager heatTreeManager = - HeatTreeManagerUtil.initHeatTreeManager(translationContext.getFiles()); - heatTreeManager.createTree(); - ValidationStructureList validationStructureList = - new ValidationStructureList(heatTreeManager.getTree()); - byte[] validationStructureFile = - FileUtils.convertToBytes(validationStructureList, FileUtils.FileExtension.JSON); - artifactFiles.addFile("HEAT.meta", validationStructureFile); - - return artifactFiles; - } + mdcDataDebugMessage.debugEntryMessage(null, null); - private ServiceTemplate createMainServiceTemplate(TranslationContext translationContext) { ServiceTemplate mainServiceTemplate = new ServiceTemplate(); - translationContext.getTranslatedServiceTemplates().put("Main", mainServiceTemplate); - Metadata templateMetadata = new Metadata(); - templateMetadata.setTemplate_name("Main"); + translationContext.getTranslatedServiceTemplates() + .put(Constants.MAIN_TEMPLATE_NAME, mainServiceTemplate); + Map templateMetadata = new HashMap<>(); + templateMetadata.put(ToscaConstants.ST_METADATA_TEMPLATE_NAME, Constants.MAIN_TEMPLATE_NAME); mainServiceTemplate.setTosca_definitions_version(ToscaConstants.TOSCA_DEFINITIONS_VERSION); mainServiceTemplate.setMetadata(templateMetadata); mainServiceTemplate.setTopology_template(new TopologyTemplate()); mainServiceTemplate.setImports(GlobalTypesGenerator.getGlobalTypesImportList()); + mdcDataDebugMessage.debugExitMessage(null, null); return mainServiceTemplate; } @@ -167,6 +155,10 @@ public class TranslationService { */ public void translateHeatFile(ServiceTemplate serviceTemplate, FileData heatFileData, TranslationContext context) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + String heatFileName = heatFileData.getFile(); HeatOrchestrationTemplate heatOrchestrationTemplate = new YamlUtil() .yamlToObject(context.getFileContent(heatFileName), HeatOrchestrationTemplate.class); @@ -177,23 +169,47 @@ public class TranslationService { translateOutputParameters(serviceTemplate, heatOrchestrationTemplate, heatFileData, heatFileName, context); createHeatStackGroup(serviceTemplate, heatFileData, heatOrchestrationTemplate, context); + handleHeatPseudoParam(heatFileName, serviceTemplate, context); if (Objects.nonNull(heatFileData.getData())) { heatFileData.getData().stream().filter(data -> data.getType() == FileData.Type.HEAT_VOL) .forEach(data -> translateHeatFile(serviceTemplate, data, context)); } + + mdcDataDebugMessage.debugExitMessage(null, null); + } + + private void handleHeatPseudoParam(String heatFileName, ServiceTemplate serviceTemplate, + TranslationContext context) { + Map translatedHeatPseudoParam = + context.getUsedHeatPseudoParams().get(heatFileName); + if (Objects.nonNull(translatedHeatPseudoParam)) { + for (String heatPseudoParam : translatedHeatPseudoParam.keySet()) { + if (!serviceTemplate.getTopology_template().getInputs().containsKey(heatPseudoParam)) { + ParameterDefinition parameterDefinition = new ParameterDefinition(); + parameterDefinition.setType(PropertyType.STRING.getDisplayName()); + parameterDefinition.setRequired(false); + String parameterDefinitionId = translatedHeatPseudoParam.get(heatPseudoParam); + DataModelUtil.addInputParameterToTopologyTemplate(serviceTemplate, parameterDefinitionId, + parameterDefinition); + } + } + } } private void createHeatStackGroup(ServiceTemplate serviceTemplate, FileData heatFileData, HeatOrchestrationTemplate heatOrchestrationTemplate, TranslationContext context) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + ToscaFileOutputService toscaFileOutputService = new ToscaFileOutputServiceCsarImpl(); - String fileName = heatFileData.getFile(); - final String fileNameWoExtension = - FileUtils.getFileWithoutExtention(fileName);//.heatFileData.getFile().split("\\.")[0]; + final String fileName = heatFileData.getFile(); + final String heatStackGroupId = FileUtils.getFileWithoutExtention(fileName) + "_group"; GroupDefinition groupDefinition = new GroupDefinition(); - groupDefinition.setType(ToscaGroupType.HEAT_STACK.getDisplayName()); + groupDefinition.setType(ToscaGroupType.HEAT_STACK); groupDefinition.setProperties(new HashMap<>()); groupDefinition.getProperties() .put("heat_file", "../" + toscaFileOutputService.getArtifactsFolderName() + "/" + fileName); @@ -207,11 +223,10 @@ public class TranslationService { return; //not creating a group when no resources are present in the heat input } groupDefinition.getMembers().addAll(heatStackGroupMembers.get(fileName)); - if (serviceTemplate.getTopology_template().getGroups() == null) { - Map groups = new HashMap<>(); - serviceTemplate.getTopology_template().setGroups(groups); - } - serviceTemplate.getTopology_template().getGroups().put(fileNameWoExtension, groupDefinition); + DataModelUtil + .addGroupDefinitionToTopologyTemplate(serviceTemplate, heatStackGroupId, groupDefinition); + + mdcDataDebugMessage.debugExitMessage(null, null); } private void translateInputParameters(ServiceTemplate serviceTemplate, @@ -219,13 +234,16 @@ public class TranslationService { FileData heatFileData, TranslationContext context, String heatFileName) { + + mdcDataDebugMessage.debugEntryMessage(null, null); + if (heatOrchestrationTemplate.getParameters() == null) { return; } Map parameterDefinitionMap = TranslatorHeatToToscaParameterConverter - .parameterConverter(heatOrchestrationTemplate.getParameters(), + .parameterConverter(serviceTemplate,heatOrchestrationTemplate.getParameters(), heatOrchestrationTemplate, heatFileName, context); Environment heatEnvFile = getHeatEnvFile(heatFileData, context); Map parameters = heatEnvFile.getParameters(); @@ -236,7 +254,7 @@ public class TranslationService { parameterValue = parameters.get(paramName); if (parameterValue != null) { entry.getValue().set_default(TranslatorHeatToToscaParameterConverter - .getToscaParameterDefaultValue(parameterValue, entry.getValue().getType(), + .getToscaParameterDefaultValue(null, null, parameterValue, entry.getValue().getType(), heatFileName, heatOrchestrationTemplate, context)); } } @@ -248,18 +266,24 @@ public class TranslationService { } else { inputs.putAll(parameterDefinitionMap); } + + mdcDataDebugMessage.debugExitMessage(null, null); } private void translateOutputParameters(ServiceTemplate serviceTemplate, HeatOrchestrationTemplate heatOrchestrationTemplate, FileData heatFileData, String heatFileName, TranslationContext context) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + if (heatOrchestrationTemplate.getOutputs() == null) { return; } Map parameterDefinitionMap = TranslatorHeatToToscaParameterConverter - .parameterOutputConverter(heatOrchestrationTemplate.getOutputs(), + .parameterOutputConverter(serviceTemplate,heatOrchestrationTemplate.getOutputs(), heatOrchestrationTemplate, heatFileName, context); if (serviceTemplate.getTopology_template().getOutputs() != null) { serviceTemplate.getTopology_template().getOutputs().putAll(parameterDefinitionMap); @@ -271,30 +295,40 @@ public class TranslationService { updateSharedResources(serviceTemplate, heatFileName, heatOrchestrationTemplate, heatOrchestrationTemplate.getOutputs(), context); } + + mdcDataDebugMessage.debugExitMessage(null, null); } private void updateSharedResources(ServiceTemplate serviceTemplate, String heatFileName, HeatOrchestrationTemplate heatOrchestrationTemplate, Map outputs, TranslationContext context) { - for (Map.Entry paramName : outputs.entrySet()) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + for (Map.Entry parameter : outputs.entrySet()) { Optional attachedSharedResourceId = HeatToToscaUtil .extractAttachedResourceId(heatFileName, heatOrchestrationTemplate, context, - paramName.getValue().getValue()); + parameter.getValue().getValue()); if (attachedSharedResourceId.isPresent() && attachedSharedResourceId.get().isGetResource() && attachedSharedResourceId.get().getTranslatedId() != null) { String sharedTranslatedResourceId = attachedSharedResourceId.get().getTranslatedId().toString(); - updateSharedResource(serviceTemplate, context, paramName, sharedTranslatedResourceId, + updateSharedResource(serviceTemplate, context, parameter, sharedTranslatedResourceId, heatOrchestrationTemplate.getResources() .get(attachedSharedResourceId.get().getEntityId())); } else { - String contrailSharedResourceId = HeatToToscaUtil - .extractContrailGetResourceAttachedHeatResourceId(paramName.getValue().getValue()); - if (contrailSharedResourceId != null - && context.getTranslatedIds().get(heatFileName).get(contrailSharedResourceId) != null) { - updateSharedResource(serviceTemplate, context, paramName, - context.getTranslatedIds().get(heatFileName).get(contrailSharedResourceId), - heatOrchestrationTemplate.getResources().get(contrailSharedResourceId)); + Optional contrailSharedResourceId = HeatToToscaUtil + .extractContrailGetResourceAttachedHeatResourceId(parameter.getValue().getValue()); + if (contrailSharedResourceId.isPresent() + && context.getTranslatedIds().get(heatFileName).get(contrailSharedResourceId.get()) + != null) { + String sharedTranslatedResourceId = context.getTranslatedIds().get(heatFileName).get + (contrailSharedResourceId.get()); + ConsolidationDataUtil.removeSharedResource(serviceTemplate, heatOrchestrationTemplate, + context, parameter.getKey(),contrailSharedResourceId.get(), sharedTranslatedResourceId); + updateSharedResource(serviceTemplate, context, parameter,sharedTranslatedResourceId, + heatOrchestrationTemplate.getResources().get(contrailSharedResourceId.get())); } } } @@ -302,21 +336,40 @@ public class TranslationService { && serviceTemplate.getTopology_template().getOutputs().size() == 0) { serviceTemplate.getTopology_template().setOutputs(null); } + + mdcDataDebugMessage.debugExitMessage(null, null); } private void updateSharedResource(ServiceTemplate serviceTemplate, TranslationContext context, Map.Entry paramName, String sharedTranslatedResourceId, Resource resource) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + context.addHeatSharedResourcesByParam(paramName.getKey(), sharedTranslatedResourceId, resource); serviceTemplate.getTopology_template().getOutputs().remove(paramName.getKey()); + + mdcDataDebugMessage.debugExitMessage(null, null); } private void translateResources(String heatFileName, ServiceTemplate serviceTemplate, HeatOrchestrationTemplate heatOrchestrationTemplate, TranslationContext context) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + if(MapUtils.isEmpty(heatOrchestrationTemplate.getResources())){ + return; + } + for (String resourceId : heatOrchestrationTemplate.getResources().keySet()) { Resource resource = heatOrchestrationTemplate.getResources().get(resourceId); if (resource == null) { + MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, + LoggerTragetServiceName.TRANSLATE_RESOURCE, ErrorLevel.ERROR.name(), + LoggerErrorCode.DATA_ERROR.getErrorCode(), LoggerErrorDescription.TRANSLATE_HEAT); throw new CoreException( new ResourceNotFoundInHeatFileErrorBuilder(resourceId, heatFileName).build()); } @@ -324,6 +377,8 @@ public class TranslationService { .translateResource(heatFileName, serviceTemplate, heatOrchestrationTemplate, resource, resourceId, context); } + + mdcDataDebugMessage.debugExitMessage(null, null); } private Environment getHeatEnvFile(FileData heatFileData, TranslationContext context) { diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/UnifiedComposition.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/UnifiedComposition.java new file mode 100644 index 0000000000..d72915c843 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/UnifiedComposition.java @@ -0,0 +1,37 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.translator.services.heattotosca; + +import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; +import org.openecomp.sdc.translator.datatypes.heattotosca.TranslationContext; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.composition.UnifiedCompositionData; + +import java.util.List; + +public interface UnifiedComposition { + + void createUnifiedComposition(ServiceTemplate serviceTemplate, + ServiceTemplate nestedServiceTemplate, + List unifiedComposotionDataList, + TranslationContext context); + + +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/UnifiedCompositionManager.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/UnifiedCompositionManager.java new file mode 100644 index 0000000000..2e67983194 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/UnifiedCompositionManager.java @@ -0,0 +1,80 @@ +package org.openecomp.sdc.translator.services.heattotosca; + +import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; +import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel; +import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; +import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; +import org.openecomp.sdc.tosca.services.ToscaAnalyzerService; +import org.openecomp.sdc.tosca.services.impl.ToscaAnalyzerServiceImpl; +import org.openecomp.sdc.translator.datatypes.heattotosca.TranslationContext; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.FileNestedConsolidationData; + +import java.util.HashSet; +import java.util.Map; +import java.util.Optional; +import java.util.Set; + +public class UnifiedCompositionManager { + + private MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); + private ConsolidationService consolidationService; + private TranslationService translationService = new TranslationService(); + private UnifiedCompositionService unifiedCompositionService = new UnifiedCompositionService(); + + public UnifiedCompositionManager(ConsolidationService consolidationService) { + this.consolidationService = consolidationService; + } + + public UnifiedCompositionManager() { + + } + + /** + * Create unified composition. + * + * @param toscaServiceModel the tosca service model + * @param translationContext the translation context + * @return the tosca service model + */ + public ToscaServiceModel createUnifiedComposition(ToscaServiceModel toscaServiceModel, + TranslationContext translationContext) { + + mdcDataDebugMessage.debugEntryMessage(null, null); + Map serviceTemplates = toscaServiceModel.getServiceTemplates(); + ServiceTemplate mainServiceTemplate = + serviceTemplates.get(toscaServiceModel.getEntryDefinitionServiceTemplate()); + consolidationService.mainServiceTemplateConsolidation(mainServiceTemplate, translationContext); + ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl(); + + + FileNestedConsolidationData mainFileNestedConsolidationData = + translationContext.getConsolidationData().getNestedConsolidationData() + .getFileNestedConsolidationData(toscaServiceModel.getEntryDefinitionServiceTemplate()); + Set substituteNodeTemplatesId = + mainFileNestedConsolidationData == null + || mainFileNestedConsolidationData.getAllNestedNodeTemplateIds() == null + ? new HashSet<>() : mainFileNestedConsolidationData.getAllNestedNodeTemplateIds(); + + for (String substituteNodeTemplateId : substituteNodeTemplatesId) { + NodeTemplate subNodeTemplate = mainServiceTemplate.getTopology_template().getNode_templates() + .get(substituteNodeTemplateId); + Optional substituteServiceTemplateName = toscaAnalyzerService + .getSubstituteServiceTemplateName(substituteNodeTemplateId, subNodeTemplate); + if (substituteServiceTemplateName.isPresent()) { + ServiceTemplate substituteServiceTemplate = + serviceTemplates.get(substituteServiceTemplateName.get()); + + consolidationService.substitutionServiceTemplateConsolidation(substituteNodeTemplateId, + mainServiceTemplate, substituteServiceTemplate, translationContext); + } + } + unifiedCompositionService + .updateUnifiedAbstractNodesConnectivity(mainServiceTemplate, translationContext); + ToscaServiceModel unifiedToscaServiceModel = + HeatToToscaUtil.createToscaServiceModel(mainServiceTemplate, translationContext); + + mdcDataDebugMessage.debugExitMessage(null, null); + return unifiedToscaServiceModel; + } +} + diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/UnifiedCompositionService.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/UnifiedCompositionService.java new file mode 100644 index 0000000000..471b1475d6 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/UnifiedCompositionService.java @@ -0,0 +1,2575 @@ +/* + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.translator.services.heattotosca; + +import org.apache.commons.collections.map.HashedMap; +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.collections4.MapUtils; +import org.apache.commons.lang3.StringUtils; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.apache.commons.lang3.tuple.Pair; +import org.openecomp.config.api.Configuration; +import org.openecomp.config.api.ConfigurationManager; +import org.openecomp.core.utilities.CommonMethods; +import org.openecomp.core.utilities.yaml.YamlUtil; +import org.openecomp.sdc.datatypes.configuration.ImplementationConfiguration; +import org.openecomp.sdc.heat.services.HeatConstants; +import org.openecomp.sdc.logging.api.Logger; +import org.openecomp.sdc.logging.api.LoggerFactory; +import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; +import org.openecomp.sdc.tosca.datatypes.ToscaFunctions; +import org.openecomp.sdc.tosca.datatypes.ToscaGroupType; +import org.openecomp.sdc.tosca.datatypes.ToscaNodeType; +import org.openecomp.sdc.tosca.datatypes.ToscaRelationshipType; +import org.openecomp.sdc.tosca.datatypes.model.CapabilityDefinition; +import org.openecomp.sdc.tosca.datatypes.model.Constraint; +import org.openecomp.sdc.tosca.datatypes.model.EntrySchema; +import org.openecomp.sdc.tosca.datatypes.model.GroupDefinition; +import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; +import org.openecomp.sdc.tosca.datatypes.model.NodeType; +import org.openecomp.sdc.tosca.datatypes.model.ParameterDefinition; +import org.openecomp.sdc.tosca.datatypes.model.PropertyType; +import org.openecomp.sdc.tosca.datatypes.model.RelationshipTemplate; +import org.openecomp.sdc.tosca.datatypes.model.RequirementAssignment; +import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; +import org.openecomp.sdc.tosca.datatypes.model.SubstitutionMapping; +import org.openecomp.sdc.tosca.datatypes.model.heatextend.PropertyTypeExt; +import org.openecomp.sdc.tosca.services.DataModelUtil; +import org.openecomp.sdc.tosca.services.ToscaAnalyzerService; +import org.openecomp.sdc.tosca.services.ToscaConstants; +import org.openecomp.sdc.tosca.services.ToscaUtil; +import org.openecomp.sdc.tosca.services.impl.ToscaAnalyzerServiceImpl; +import org.openecomp.sdc.translator.datatypes.heattotosca.TranslationContext; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.composition.UnifiedCompositionData; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.composition.UnifiedCompositionEntity; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.composition.UnifiedCompositionMode; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.composition.UnifiedSubstitutionData; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.ComputeTemplateConsolidationData; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.ConsolidationData; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.EntityConsolidationData; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.FileComputeConsolidationData; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.GetAttrFuncData; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.NestedTemplateConsolidationData; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.PortTemplateConsolidationData; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.RequirementAssignmentData; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.TypeComputeConsolidationData; + +import java.io.ByteArrayInputStream; +import java.io.ByteArrayOutputStream; +import java.io.IOException; +import java.io.NotSerializableException; +import java.io.ObjectInputStream; +import java.io.ObjectOutputStream; +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.LinkedHashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; +import java.util.regex.Pattern; + +import static org.openecomp.sdc.translator.services.heattotosca.Constants.ABSTRACT_NODE_TEMPLATE_ID_PREFIX; +import static org.openecomp.sdc.translator.services.heattotosca.Constants.IDENTICAL_VALUE_PROPERTY_PREFIX; +import static org.openecomp.sdc.translator.services.heattotosca.Constants.IDENTICAL_VALUE_PROPERTY_SUFFIX; + +public class UnifiedCompositionService { + + protected static Logger logger = + (Logger) LoggerFactory.getLogger(UnifiedCompositionService.class); + protected static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); + private static Map unifiedCompositionImplMap; + + static { + Configuration config = ConfigurationManager.lookup(); + unifiedCompositionImplMap = + config.populateMap(ConfigConstants.MANDATORY_UNIFIED_MODEL_NAMESPACE, + ConfigConstants.UNIFIED_COMPOSITION_IMPL_KEY, ImplementationConfiguration.class); + + } + + private ConsolidationService consolidationService = new ConsolidationService(); + + private static List getPortConsolidationDataList( + Set portIds, + List unifiedCompositionDataList) { + List portConsolidationDataList = new ArrayList<>(); + for (UnifiedCompositionData unifiedCompositionData : unifiedCompositionDataList) { + for (PortTemplateConsolidationData portTemplateConsolidationData : unifiedCompositionData + .getPortTemplateConsolidationDataList()) { + if (portIds.contains(portTemplateConsolidationData.getNodeTemplateId())) { + portConsolidationDataList.add(portTemplateConsolidationData); + } + } + } + return portConsolidationDataList; + } + + /** + * Create unified composition. + * + * @param serviceTemplate the service template + * @param nestedServiceTemplate the nested service template + * @param unifiedCompositionDataList the unified composition data list. In case no consolidation, + * one entry will be in this list, in case of having + * consolidation, all entries in the list are the once which + * need to be consolidated. + * @param mode the mode + * @param context the context + */ + public void createUnifiedComposition(ServiceTemplate serviceTemplate, + ServiceTemplate nestedServiceTemplate, + List unifiedCompositionDataList, + UnifiedCompositionMode mode, TranslationContext context) { + mdcDataDebugMessage.debugEntryMessage(null, null); + Optional unifiedCompositionInstance = getUnifiedCompositionInstance(mode); + if (!unifiedCompositionInstance.isPresent()) { + return; + } + unifiedCompositionInstance.get() + .createUnifiedComposition(serviceTemplate, nestedServiceTemplate, + unifiedCompositionDataList, context); + mdcDataDebugMessage.debugExitMessage(null, null); + } + + /** + * Create unified substitution service template according to the input service template, based on + * the unified composition data. + * + * @param serviceTemplate the service template + * @param unifiedCompositionDataList the unified composition data list. In case no consolidation, + * one entry will be in this list, in case of having + * consolidation, all entries in the list are the once which + * need to be consolidated. + * @param context the translation context + * @return the substitution service template + */ + public Optional createUnifiedSubstitutionServiceTemplate( + ServiceTemplate serviceTemplate, List unifiedCompositionDataList, + TranslationContext context, Integer index) { + if (CollectionUtils.isEmpty(unifiedCompositionDataList)) { + return Optional.empty(); + } + UnifiedCompositionData unifiedCompositionData = unifiedCompositionDataList.get(0); + String templateName = + getTemplateName(serviceTemplate, unifiedCompositionData, index); + ServiceTemplate substitutionServiceTemplate = + HeatToToscaUtil.createInitSubstitutionServiceTemplate(templateName); + + createIndexInputParameter(substitutionServiceTemplate); + + String computeNodeType = + handleCompute(serviceTemplate, substitutionServiceTemplate, unifiedCompositionDataList, + context); + handlePorts(serviceTemplate, substitutionServiceTemplate, unifiedCompositionDataList, + computeNodeType, context); + createOutputParameters(serviceTemplate, substitutionServiceTemplate, unifiedCompositionDataList, + computeNodeType); + NodeType substitutionGlobalNodeType = + handleSubstitutionGlobalNodeType(serviceTemplate, substitutionServiceTemplate, + context, unifiedCompositionData, index); + + HeatToToscaUtil.handleSubstitutionMapping(context, + getSubstitutionNodeTypeId(serviceTemplate, unifiedCompositionData, index), + substitutionServiceTemplate, substitutionGlobalNodeType); + + context.getTranslatedServiceTemplates().put(templateName, substitutionServiceTemplate); + return Optional.of(substitutionServiceTemplate); + } + + /** + * Create abstract substitute node template that can be substituted by the input + * substitutionServiceTemplate. + * + * @param serviceTemplate the service template + * @param substitutionServiceTemplate the subtitution service template + * @param unifiedCompositionDataList the unified composition data list. In case no consolidation, + * one entry will be in this list, in case of having + * consolidation, all entries in the list are the once which + * need to be consolidated. + * @param context the translation context + * @return the abstract substitute node template id + */ + public String createAbstractSubstituteNodeTemplate( + ServiceTemplate serviceTemplate, + ServiceTemplate substitutionServiceTemplate, + List unifiedCompositionDataList, + TranslationContext context, + Integer index) { + + NodeTemplate substitutionNodeTemplate = new NodeTemplate(); + List directiveList = new ArrayList<>(); + directiveList.add(ToscaConstants.NODE_TEMPLATE_DIRECTIVE_SUBSTITUTABLE); + substitutionNodeTemplate.setDirectives(directiveList); + String substituteNodeTemplateType = + getSubstitutionNodeTypeId(serviceTemplate, unifiedCompositionDataList.get(0), index); + substitutionNodeTemplate.setType(substituteNodeTemplateType); + Optional> abstractSubstitutionProperties = + createAbstractSubstitutionProperties(serviceTemplate, + substitutionServiceTemplate, unifiedCompositionDataList); + abstractSubstitutionProperties.ifPresent(substitutionNodeTemplate::setProperties); + + //Add substitution filtering property + String substitutionServiceTemplateName = ToscaUtil.getServiceTemplateFileName( + substitutionServiceTemplate); + int count = unifiedCompositionDataList.size(); + addSubstitutionFilteringProperty(substitutionServiceTemplateName, substitutionNodeTemplate, + count); + //Add index_value property + addIndexValueProperty(substitutionNodeTemplate); + String substituteNodeTemplateId = + getSubstituteNodeTemplateId(serviceTemplate, unifiedCompositionDataList.get(0), index); + //Add node template id and related abstract node template id in context + addUnifiedSubstitionData(context, serviceTemplate, unifiedCompositionDataList, + substituteNodeTemplateId); + DataModelUtil + .addNodeTemplate(serviceTemplate, substituteNodeTemplateId, substitutionNodeTemplate); + return substituteNodeTemplateId; + + } + + /** + * Update the connectivity from/to the "moved" nodes from the original service template to the new + * substitution service template. + * + * @param serviceTemplate the service template + * @param unifiedCompositionDataList the unified composition data list. In case no consolidation, + * one entry will be in this list, in case of having + * consolidation, all entries in the list are the once which + * need to be consolidated. + * @param context the translation context + */ + public void updateCompositionConnectivity(ServiceTemplate serviceTemplate, + List unifiedCompositionDataList, + TranslationContext context) { + updOutputParamGetAttrInConnectivity(serviceTemplate, unifiedCompositionDataList, context); + updNodesGetAttrInConnectivity(serviceTemplate, unifiedCompositionDataList, context); + updNodesConnectedOutConnectivity(serviceTemplate, unifiedCompositionDataList, context); + updNodesConnectedInConnectivity(serviceTemplate, unifiedCompositionDataList, context); + updVolumeConnectivity(serviceTemplate, unifiedCompositionDataList, context); + updGroupsConnectivity(serviceTemplate, unifiedCompositionDataList, context); + } + + /** + * Delete the "moved" nodes from the original service template to the new substitution service + * template. + * + * @param serviceTemplate the service template + * @param unifiedCompositionDataList the unified composition data list. In case no consolidation, + * one entry will be in this list, in case of having + * consolidation, all entries in the list are the once which + * need to be consolidated. + * @param context the translation context + */ + public void cleanUnifiedCompositionEntities( + ServiceTemplate serviceTemplate, + List unifiedCompositionDataList, + TranslationContext context) { + for (UnifiedCompositionData unifiedCompositionData : unifiedCompositionDataList) { + ComputeTemplateConsolidationData computeTemplateConsolidationData = + unifiedCompositionData.getComputeTemplateConsolidationData(); + cleanServiceTemplate(serviceTemplate, computeTemplateConsolidationData, context); + + List portTemplateConsolidationDataList = + getPortTemplateConsolidationDataList(unifiedCompositionData); + for (PortTemplateConsolidationData portTemplateConsolidationData : + portTemplateConsolidationDataList) { + cleanServiceTemplate(serviceTemplate, portTemplateConsolidationData, context); + } + } + + } + + public void cleanNodeTypes(ServiceTemplate serviceTemplate, + List unifiedCompositionDataList, + TranslationContext context) { + for (UnifiedCompositionData unifiedData : unifiedCompositionDataList) { + removeCleanedNodeType( + unifiedData.getComputeTemplateConsolidationData().getNodeTemplateId(), serviceTemplate, + context); + } + + if (MapUtils.isEmpty(serviceTemplate.getNode_types())) { + serviceTemplate.setNode_types(null); + } + } + + /** + * Update unified abstract nodes connectivity. + * + * @param serviceTemplate the service template + * @param context the context + */ + public void updateUnifiedAbstractNodesConnectivity(ServiceTemplate serviceTemplate, + TranslationContext context) { + + + String serviceTemplateFileName = ToscaUtil.getServiceTemplateFileName(serviceTemplate); + UnifiedSubstitutionData unifiedSubstitutionData = context.getUnifiedSubstitutionData() + .get(serviceTemplateFileName); + + if (Objects.nonNull(unifiedSubstitutionData)) { + //Handle get attribute in connectivity for abstarct node to abstract node templates + Set abstractNodeIds = + new HashSet<>(unifiedSubstitutionData.getAllRelatedAbstractNodeIds()); + handleGetAttrInConnectivity(serviceTemplate, abstractNodeIds, context); + //Handle get attribute in connectivity for abstract node templates to nested node template + Set nestedNodeIds = + new HashSet<>(unifiedSubstitutionData.getAllUnifiedNestedNodeTemplateIds()); + handleGetAttrInConnectivity(serviceTemplate, nestedNodeIds, context); + } + } + + public void handleUnifiedNestedDefinition(ServiceTemplate mainServiceTemplate, + ServiceTemplate nestedServiceTemplate, + List unifiedCompositionDataList, + TranslationContext context) { + handleUnifiedNestedNodeType(mainServiceTemplate, nestedServiceTemplate, context); + updateUnifiedNestedTemplates(mainServiceTemplate, nestedServiceTemplate, unifiedCompositionDataList, context); + } + + private void handleGetAttrInConnectivity(ServiceTemplate serviceTemplate, + Set unifiedNodeIds, + TranslationContext context) { + Map nodeTemplates = + serviceTemplate.getTopology_template().getNode_templates(); + String serviceTemplateFileName = ToscaUtil.getServiceTemplateFileName(serviceTemplate); + for (String unifiedNodeId : unifiedNodeIds) { + NodeTemplate nodeTemplate = nodeTemplates.get(unifiedNodeId); + handleGetAttrInAbstractNodeTemplate(serviceTemplate, context, serviceTemplateFileName, + nodeTemplate); + } + } + + private void handleUnifiedNestedNodeType(ServiceTemplate mainServiceTemplate, + ServiceTemplate nestedServiceTemplate, + TranslationContext context) { + + + SubstitutionMapping substitutionMappings = + nestedServiceTemplate.getTopology_template().getSubstitution_mappings(); + String nodeTypeId = substitutionMappings.getNode_type(); + + Optional newNestedNodeTypeId = + getNewNestedNodeTypeId(mainServiceTemplate, nestedServiceTemplate, context); + + if (isNestedServiceTemplateWasHandled(mainServiceTemplate, nestedServiceTemplate, context, + newNestedNodeTypeId)) { + context.updateHandledComputeType( + ToscaUtil.getServiceTemplateFileName(mainServiceTemplate), + ToscaUtil.getServiceTemplateFileName(nestedServiceTemplate), + newNestedNodeTypeId.get()); + return; + } + + ServiceTemplate globalSubstitutionServiceTemplate = + context.getGlobalSubstitutionServiceTemplate(); + + newNestedNodeTypeId.ifPresent( + newNestedNodeTypeIdVal -> updateNestedNodeType(nodeTypeId, newNestedNodeTypeIdVal, + nestedServiceTemplate, mainServiceTemplate, globalSubstitutionServiceTemplate, + context)); + + } + + private boolean isNestedServiceTemplateWasHandled(ServiceTemplate mainServiceTemplate, + ServiceTemplate nestedServiceTemplate, + TranslationContext context, + Optional newNestedNodeTypeId) { + return newNestedNodeTypeId.isPresent() + && context.isNestedServiceTemplateWasHandled( + ToscaUtil.getServiceTemplateFileName(mainServiceTemplate), + ToscaUtil.getServiceTemplateFileName(nestedServiceTemplate)); + } + + private void updateNestedNodeType(String nodeTypeId, String newNestedNodeTypeId, + ServiceTemplate nestedServiceTemplate, + ServiceTemplate mainServiceTemplate, + ServiceTemplate globalSubstitutionServiceTemplate, + TranslationContext context) { + context.addNestedFileToUsedNestedComputeType( + ToscaUtil.getServiceTemplateFileName(mainServiceTemplate), + ToscaUtil.getServiceTemplateFileName(nestedServiceTemplate), + newNestedNodeTypeId); + String indexedNodeType = + handleNestedNodeTypeInGlobalSubstitutionTemplate(nodeTypeId, newNestedNodeTypeId, + mainServiceTemplate, globalSubstitutionServiceTemplate, context); + + handleSubstitutionMappingInNestedServiceTemplate(indexedNodeType, nestedServiceTemplate); + + context + .updateHandledComputeType( + ToscaUtil.getServiceTemplateFileName(mainServiceTemplate), + ToscaUtil.getServiceTemplateFileName(nestedServiceTemplate), + newNestedNodeTypeId); + } + + private String handleNestedNodeTypeInGlobalSubstitutionTemplate(String nodeTypeId, + String newNestedNodeTypeId, + ServiceTemplate mainServiceTemplate, + ServiceTemplate globalSubstitutionServiceTemplate, + TranslationContext context) { + String indexedNodeType = + getIndexedGlobalNodeTypeId(newNestedNodeTypeId, mainServiceTemplate, context); + handleNestedNodeTypesInGlobalSubstituteServiceTemplate(nodeTypeId, indexedNodeType, + globalSubstitutionServiceTemplate, context); + return indexedNodeType; + } + + private String getIndexedGlobalNodeTypeId(String newNestedNodeTypeId, + ServiceTemplate mainServiceTemplate, + TranslationContext context) { + int globalNodeTypeIndex = + context.getGlobalNodeTypeIndex(ToscaUtil.getServiceTemplateFileName(mainServiceTemplate), + newNestedNodeTypeId); + return globalNodeTypeIndex > 0 ? + newNestedNodeTypeId + "_" + String.valueOf(globalNodeTypeIndex) : newNestedNodeTypeId; + } + + private void updateUnifiedNestedTemplates(ServiceTemplate mainServiceTemplate, + ServiceTemplate nestedServiceTemplate, + List unifiedCompositionDataList, + TranslationContext context) { + + for (UnifiedCompositionData unifiedCompositionData : unifiedCompositionDataList) { + NestedTemplateConsolidationData nestedTemplateConsolidationData = + unifiedCompositionData.getNestedTemplateConsolidationData(); + if (Objects.isNull(nestedTemplateConsolidationData)) { + continue; + } + handleNestedNodeTemplateInMainServiceTemplate(nestedTemplateConsolidationData.getNodeTemplateId(), mainServiceTemplate, nestedServiceTemplate, context); + } + } + + /** + * Update connectivity for unified nested patterns. + * + * @param serviceTemplate the service template + * @param nestedServiceTemplate the nested service template + * @param unifiedCompositionDataList the unified composition data list + * @param context the context + */ + public void updateUnifiedNestedConnectivity(ServiceTemplate serviceTemplate, + ServiceTemplate nestedServiceTemplate, + List + unifiedCompositionDataList, + TranslationContext context) { + + updNestedCompositionNodesConnectedInConnectivity(serviceTemplate, unifiedCompositionDataList, + context); + updNestedCompositionNodesGetAttrInConnectivity(serviceTemplate, unifiedCompositionDataList, + context); + updNestedCompositionOutputParamGetAttrInConnectivity(serviceTemplate, + unifiedCompositionDataList, context); + } + + + /** + * Clean unified nested entities. Update the heat stack group with the new node template ids. + * + * @param serviceTemplate the service template + * @param unifiedCompositionDataList the unified composition data list + * @param context the context + */ + public void cleanUnifiedNestedEntities(ServiceTemplate serviceTemplate, + List unifiedCompositionDataList, + TranslationContext context) { + EntityConsolidationData entityConsolidationData = unifiedCompositionDataList.get(0) + .getNestedTemplateConsolidationData(); + updateHeatStackGroupNestedComposition(serviceTemplate, entityConsolidationData, context); + + } + + protected void updNodesConnectedOutConnectivity(ServiceTemplate serviceTemplate, + List + unifiedCompositionDataList, + TranslationContext context) { + for (UnifiedCompositionData unifiedCompositionData : unifiedCompositionDataList) { + ComputeTemplateConsolidationData computeTemplateConsolidationData = unifiedCompositionData + .getComputeTemplateConsolidationData(); + //Add requirements in the abstract node template for nodes connected out for computes + String newComputeNodeTemplateId = getNewComputeNodeTemplateId(serviceTemplate, + computeTemplateConsolidationData.getNodeTemplateId()); + Map> computeNodesConnectedOut = + computeTemplateConsolidationData.getNodesConnectedOut(); + if (computeNodesConnectedOut != null) { + updateRequirementInAbstractNodeTemplate(serviceTemplate, computeTemplateConsolidationData, + newComputeNodeTemplateId, computeNodesConnectedOut, context); + } + String computeType = getComputeTypeSuffix(serviceTemplate, computeTemplateConsolidationData + .getNodeTemplateId()); + //Add requirements in the abstract node template for nodes connected out for ports + List portTemplateConsolidationDataList = + getPortTemplateConsolidationDataList(unifiedCompositionData); + for (PortTemplateConsolidationData portTemplateConsolidationData : + portTemplateConsolidationDataList) { + String newPortNodeTemplateId = getNewPortNodeTemplateId(portTemplateConsolidationData + .getNodeTemplateId(), computeType, computeTemplateConsolidationData); + Map> portNodesConnectedOut = + portTemplateConsolidationData.getNodesConnectedOut(); + if (portNodesConnectedOut != null) { + updateRequirementInAbstractNodeTemplate(serviceTemplate, portTemplateConsolidationData, + newPortNodeTemplateId, portNodesConnectedOut, context); + } + } + } + } + + protected void updNodesConnectedInConnectivity(ServiceTemplate serviceTemplate, + List + unifiedCompositionDataList, + TranslationContext context) { + for (UnifiedCompositionData unifiedCompositionData : unifiedCompositionDataList) { + ComputeTemplateConsolidationData computeTemplateConsolidationData = unifiedCompositionData + .getComputeTemplateConsolidationData(); + //Update requirements in the node template which pointing to the computes + String newComputeNodeTemplateId = getNewComputeNodeTemplateId(serviceTemplate, + computeTemplateConsolidationData.getNodeTemplateId()); + updNodesConnectedInConnectivity(serviceTemplate, computeTemplateConsolidationData, + newComputeNodeTemplateId, context, false); + + String computeType = getComputeTypeSuffix(serviceTemplate, computeTemplateConsolidationData + .getNodeTemplateId()); + //Update requirements in the node template which pointing to the ports + List portTemplateConsolidationDataList = + getPortTemplateConsolidationDataList(unifiedCompositionData); + for (PortTemplateConsolidationData portTemplateConsolidationData : + portTemplateConsolidationDataList) { + String newPortNodeTemplateId = getNewPortNodeTemplateId(portTemplateConsolidationData + .getNodeTemplateId(), computeType, computeTemplateConsolidationData); + updNodesConnectedInConnectivity(serviceTemplate, portTemplateConsolidationData, + newPortNodeTemplateId, context, false); + } + } + } + + private void updNodesConnectedInConnectivity(ServiceTemplate serviceTemplate, + EntityConsolidationData entityConsolidationData, + String newNodeTemplateId, + TranslationContext context, + boolean isNested) { + Map> nodesConnectedIn = + entityConsolidationData.getNodesConnectedIn(); + if (nodesConnectedIn == null) { + //No nodes connected in info + return; + } + for (Map.Entry> entry : nodesConnectedIn + .entrySet()) { + List requirementAssignmentDataList = entry.getValue(); + for (RequirementAssignmentData requirementAssignmentData : requirementAssignmentDataList) { + RequirementAssignment requirementAssignment = requirementAssignmentData + .getRequirementAssignment(); + if (!requirementAssignment.getNode().equals(entityConsolidationData + .getNodeTemplateId())) { + //The requirement assignment target node should be the one which we are handling in the + //consolidation object + continue; + } + //Update the requirement assignment object in the original node template + if (isNested) { + updateRequirementForNestedCompositionNodesConnectedIn(serviceTemplate, + requirementAssignmentData, entityConsolidationData, newNodeTemplateId, context); + } else { + updateRequirementForNodesConnectedIn(serviceTemplate, requirementAssignmentData, + entityConsolidationData, entry.getKey(), newNodeTemplateId, context); + } + + } + } + } + + protected void updNestedCompositionNodesConnectedInConnectivity(ServiceTemplate serviceTemplate, + List + unifiedCompositionDataList, + TranslationContext context) { + for (UnifiedCompositionData unifiedCompositionData : unifiedCompositionDataList) { + NestedTemplateConsolidationData nestedTemplateConsolidationData = unifiedCompositionData + .getNestedTemplateConsolidationData(); + //Update requirements in the node template which pointing to the nested nodes + String serviceTemplateFileName = ToscaUtil.getServiceTemplateFileName(serviceTemplate); + Optional newNestedNodeTemplateId = context.getUnifiedNestedNodeTemplateId( + serviceTemplateFileName, nestedTemplateConsolidationData.getNodeTemplateId()); + newNestedNodeTemplateId.ifPresent( + newNestedNodeTemplateIdVal -> updNodesConnectedInConnectivity(serviceTemplate, + nestedTemplateConsolidationData, + newNestedNodeTemplateIdVal, context, true)); + } + } + + protected void updVolumeConnectivity(ServiceTemplate serviceTemplate, + List + unifiedCompositionDataList, + TranslationContext context) { + for (UnifiedCompositionData unifiedCompositionData : unifiedCompositionDataList) { + ComputeTemplateConsolidationData computeTemplateConsolidationData = unifiedCompositionData + .getComputeTemplateConsolidationData(); + //Add requirements in the abstract node template for compute volumes + String newComputeNodeTemplateId = getNewComputeNodeTemplateId(serviceTemplate, + computeTemplateConsolidationData.getNodeTemplateId()); + Map> computeVolumes = + computeTemplateConsolidationData.getVolumes(); + if (computeVolumes != null) { + updateRequirementInAbstractNodeTemplate(serviceTemplate, computeTemplateConsolidationData, + newComputeNodeTemplateId, computeVolumes, context); + } + } + } + + protected void updGroupsConnectivity(ServiceTemplate serviceTemplate, + List + unifiedCompositionDataList, + TranslationContext context) { + for (UnifiedCompositionData unifiedCompositionData : unifiedCompositionDataList) { + ComputeTemplateConsolidationData computeTemplateConsolidationData = unifiedCompositionData + .getComputeTemplateConsolidationData(); + //Add requirements in the abstract node template for nodes connected in for computes + String newComputeNodeTemplateId = getNewComputeNodeTemplateId(serviceTemplate, + computeTemplateConsolidationData.getNodeTemplateId()); + updGroupsConnectivity(serviceTemplate, computeTemplateConsolidationData, context); + + String computeType = getComputeTypeSuffix(serviceTemplate, computeTemplateConsolidationData + .getNodeTemplateId()); + //Add requirements in the abstract node template for nodes connected in for ports + List portTemplateConsolidationDataList = + getPortTemplateConsolidationDataList(unifiedCompositionData); + for (PortTemplateConsolidationData portTemplateConsolidationData : + portTemplateConsolidationDataList) { + String newPortNodeTemplateId = getNewPortNodeTemplateId(portTemplateConsolidationData + .getNodeTemplateId(), computeType, computeTemplateConsolidationData); + updGroupsConnectivity(serviceTemplate, portTemplateConsolidationData, context); + } + } + } + + private void updGroupsConnectivity(ServiceTemplate serviceTemplate, EntityConsolidationData + entityConsolidationData, TranslationContext context) { + List groupIds = entityConsolidationData.getGroupIds(); + if (groupIds == null) { + return; + } + String oldNodeTemplateId = entityConsolidationData.getNodeTemplateId(); + String abstractNodeTemplateId = context.getUnifiedAbstractNodeTemplateId( + serviceTemplate, entityConsolidationData.getNodeTemplateId()); + Map groups = serviceTemplate.getTopology_template().getGroups(); + if (groups != null) { + for (String groupId : groupIds) { + GroupDefinition groupDefinition = groups.get(groupId); + if (groupDefinition != null) { + List groupMembers = groupDefinition.getMembers(); + if (groupMembers.contains(oldNodeTemplateId)) { + //Replace the old node template id + groupMembers.remove(oldNodeTemplateId); + if (!groupMembers.contains(abstractNodeTemplateId)) { + //Add the abstract node template id if not already present + groupMembers.add(abstractNodeTemplateId); + } + } + } + } + } + } + + protected void updOutputParamGetAttrInConnectivity( + ServiceTemplate serviceTemplate, List unifiedComposotionDataList, + TranslationContext context) { + for (UnifiedCompositionData unifiedCompositionData : unifiedComposotionDataList) { + ComputeTemplateConsolidationData computeTemplateConsolidationData = + unifiedCompositionData.getComputeTemplateConsolidationData(); + String newComputeNodeTemplateId = getNewComputeNodeTemplateId(serviceTemplate, + computeTemplateConsolidationData.getNodeTemplateId()); + + updOutputParamGetAttrInConnectivity(serviceTemplate, computeTemplateConsolidationData, + computeTemplateConsolidationData.getNodeTemplateId(), newComputeNodeTemplateId, + context, false); + + String computeType = + getComputeTypeSuffix(serviceTemplate, + computeTemplateConsolidationData.getNodeTemplateId()); + List portTemplateConsolidationDataList = + getPortTemplateConsolidationDataList(unifiedCompositionData); + for (PortTemplateConsolidationData portTemplateConsolidationData : + portTemplateConsolidationDataList) { + String newPortNodeTemplateId = + getNewPortNodeTemplateId(portTemplateConsolidationData.getNodeTemplateId(), computeType, + computeTemplateConsolidationData); + + updOutputParamGetAttrInConnectivity(serviceTemplate, portTemplateConsolidationData, + portTemplateConsolidationData.getNodeTemplateId(), newPortNodeTemplateId, context, + false); + } + } + } + + protected void updNodesGetAttrInConnectivity( + ServiceTemplate serviceTemplate, + List unifiedComposotionDataList, + TranslationContext context) { + Map consolidationNodeTemplateIdAndType = + getAllConsolidationNodeTemplateIdAndType(unifiedComposotionDataList); + for (UnifiedCompositionData unifiedCompositionData : unifiedComposotionDataList) { + ComputeTemplateConsolidationData computeTemplateConsolidationData = + unifiedCompositionData.getComputeTemplateConsolidationData(); + String newComputeNodeTemplateId = getNewComputeNodeTemplateId(serviceTemplate, + computeTemplateConsolidationData.getNodeTemplateId()); + + updNodeGetAttrInConnectivity(serviceTemplate, computeTemplateConsolidationData, + computeTemplateConsolidationData.getNodeTemplateId(), + newComputeNodeTemplateId, context, consolidationNodeTemplateIdAndType, false); + + String computeType = + getComputeTypeSuffix(serviceTemplate, + computeTemplateConsolidationData.getNodeTemplateId()); + + List portTemplateConsolidationDataList = + getPortTemplateConsolidationDataList(unifiedCompositionData); + for (PortTemplateConsolidationData portTemplateConsolidationData : + portTemplateConsolidationDataList) { + String newPotNodeTemplateId = + getNewPortNodeTemplateId(portTemplateConsolidationData.getNodeTemplateId(), computeType, + computeTemplateConsolidationData); + + updNodeGetAttrInConnectivity(serviceTemplate, portTemplateConsolidationData, + portTemplateConsolidationData.getNodeTemplateId(), + newPotNodeTemplateId, context, consolidationNodeTemplateIdAndType, false); + } + } + } + + protected void updNestedCompositionOutputParamGetAttrInConnectivity( + ServiceTemplate serviceTemplate, List unifiedComposotionDataList, + TranslationContext context) { + for (UnifiedCompositionData unifiedCompositionData : unifiedComposotionDataList) { + NestedTemplateConsolidationData nestedTemplateConsolidationData = + unifiedCompositionData.getNestedTemplateConsolidationData(); + if (Objects.isNull(nestedTemplateConsolidationData)) { + continue; + } + String serviceTemplateFileName = ToscaUtil.getServiceTemplateFileName(serviceTemplate); + Optional newNestedNodeTemplateId = context.getUnifiedNestedNodeTemplateId( + serviceTemplateFileName, nestedTemplateConsolidationData.getNodeTemplateId()); + + newNestedNodeTemplateId.ifPresent( + newNestedNodeTemplateIdVal -> updOutputParamGetAttrInConnectivity(serviceTemplate, + nestedTemplateConsolidationData, nestedTemplateConsolidationData.getNodeTemplateId(), + newNestedNodeTemplateIdVal, context, true)); + } + } + + protected void updNestedCompositionNodesGetAttrInConnectivity( + ServiceTemplate serviceTemplate, + List unifiedCompositionDataList, + TranslationContext context) { + for (UnifiedCompositionData unifiedCompositionData : unifiedCompositionDataList) { + NestedTemplateConsolidationData nestedTemplateConsolidationData = + unifiedCompositionData.getNestedTemplateConsolidationData(); + if (Objects.isNull(nestedTemplateConsolidationData)) { + continue; + } + String serviceTemplateFileName = ToscaUtil.getServiceTemplateFileName(serviceTemplate); + Optional newNestedNodeTemplateId = context.getUnifiedNestedNodeTemplateId( + serviceTemplateFileName, nestedTemplateConsolidationData.getNodeTemplateId()); + + newNestedNodeTemplateId.ifPresent( + newNestedNodeTemplateIdVal -> updNodeGetAttrInConnectivity(serviceTemplate, + nestedTemplateConsolidationData, nestedTemplateConsolidationData.getNodeTemplateId(), + newNestedNodeTemplateIdVal, context, null, true)); + } + } + + private void updateRequirementForNodesConnectedIn( + ServiceTemplate serviceTemplate, + RequirementAssignmentData requirementAssignmentData, + EntityConsolidationData entityConsolidationData, + String originalNodeTemplateId, + String newNodeTemplateId, + TranslationContext context) { + ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl(); + RequirementAssignment requirementAssignment = requirementAssignmentData + .getRequirementAssignment(); + String newAbstractUnifiedNodeTemplateId = context.getUnifiedAbstractNodeTemplateId( + serviceTemplate, entityConsolidationData.getNodeTemplateId()); + NodeTemplate abstractUnifiedNodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, + newAbstractUnifiedNodeTemplateId); + Optional newCapabilityId = getNewCapabilityForNodesConnectedIn(serviceTemplate, + abstractUnifiedNodeTemplate, requirementAssignment, newNodeTemplateId, context); + if (newCapabilityId.isPresent()) { + //Creating a copy of the requirement object and checking if it already exists in the + // original node template + RequirementAssignment requirementAssignmentCopy = (RequirementAssignment) getClonedObject( + requirementAssignmentData.getRequirementAssignment(), RequirementAssignment.class); + NodeTemplate originalNodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, + originalNodeTemplateId); + requirementAssignmentCopy.setCapability(newCapabilityId.get()); + requirementAssignmentCopy.setNode(newAbstractUnifiedNodeTemplateId); + if (!toscaAnalyzerService.isRequirementExistInNodeTemplate(originalNodeTemplate, + requirementAssignmentData.getRequirementId(), requirementAssignmentCopy)) { + //Update the existing requirement + requirementAssignmentData.getRequirementAssignment().setCapability(newCapabilityId + .get()); + requirementAssignmentData.getRequirementAssignment() + .setNode(newAbstractUnifiedNodeTemplateId); + } else { + //The updated requirement already exists in the node template so simply remove the + // current one + DataModelUtil.removeRequirementAssignment(originalNodeTemplate, requirementAssignmentData + .getRequirementId(), requirementAssignmentData.getRequirementAssignment()); + } + } + } + + private void updateRequirementForNestedCompositionNodesConnectedIn( + ServiceTemplate serviceTemplate, + RequirementAssignmentData requirementAssignmentData, + EntityConsolidationData entityConsolidationData, + String newNodeTemplateId, + TranslationContext context) { + ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl(); + String newAbstractUnifiedNodeTemplateId = newNodeTemplateId; + RequirementAssignment requirementAssignment = requirementAssignmentData + .getRequirementAssignment(); + //Creating a copy of the requirement object and checking if it already exists in the + // original node template + RequirementAssignment requirementAssignmentCopy = (RequirementAssignment) getClonedObject( + requirementAssignmentData.getRequirementAssignment(), RequirementAssignment.class); + NodeTemplate unifiedAbstractNestedNodeTemplate = DataModelUtil + .getNodeTemplate(serviceTemplate, newAbstractUnifiedNodeTemplateId); + requirementAssignmentCopy.setCapability(requirementAssignment.getCapability()); + requirementAssignmentCopy.setNode(newAbstractUnifiedNodeTemplateId); + if (!toscaAnalyzerService.isRequirementExistInNodeTemplate(unifiedAbstractNestedNodeTemplate, + requirementAssignmentData.getRequirementId(), requirementAssignmentCopy)) { + //Update the existing requirement + requirementAssignmentData.getRequirementAssignment() + .setNode(newAbstractUnifiedNodeTemplateId); + } else { + //The updated requirement already exists in the node template so simply remove the + // current one + DataModelUtil.removeRequirementAssignment(unifiedAbstractNestedNodeTemplate, + requirementAssignmentData.getRequirementId(), requirementAssignmentData + .getRequirementAssignment()); + } + } + + private Optional getNewCapabilityForNodesConnectedIn(ServiceTemplate serviceTemplate, + NodeTemplate unifiedNodeTemplate, + RequirementAssignment + requirementAssignment, + String newNodeTemplateId, + TranslationContext context) { + ServiceTemplate globalSubstitutionServiceTemplate = + HeatToToscaUtil.fetchGlobalSubstitutionServiceTemplate(serviceTemplate, context); + Map nodeTypes = globalSubstitutionServiceTemplate.getNode_types(); + String unifiedNodeTemplateType = unifiedNodeTemplate.getType(); + NodeType unifiedNodeType = nodeTypes.get(unifiedNodeTemplateType); + Map abstractNodeTypeCapabilities = unifiedNodeType + .getCapabilities(); + for (Map.Entry entry : abstractNodeTypeCapabilities.entrySet()) { + String capabilityId = entry.getKey(); + CapabilityDefinition capabilityDefinition = entry.getValue(); + String capabilityType = capabilityDefinition.getType(); + if (capabilityType.equals(requirementAssignment.getCapability())) { + //Matching capability type found..Check if the id ends with new node template id + if (capabilityId.endsWith(newNodeTemplateId)) { + return Optional.ofNullable(capabilityId); + } + } + } + return Optional.empty(); + } + + + private void updateRequirementInAbstractNodeTemplate(ServiceTemplate serviceTemplate, + EntityConsolidationData + entityConsolidationData, + String newNodeTemplateId, + Map> + requirementAssignmentDataMap, + TranslationContext context) { + ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl(); + for (Map.Entry> entry : requirementAssignmentDataMap + .entrySet()) { + String abstractNodeTemplateId = context.getUnifiedAbstractNodeTemplateId( + serviceTemplate, entityConsolidationData.getNodeTemplateId()); + NodeTemplate abstractNodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, + abstractNodeTemplateId); + if (abstractNodeTemplate == null) { + //The abstract node template is not found from id in the context + return; + } + List requirementAssignmentDataList = entry.getValue(); + for (RequirementAssignmentData requirementAssignmentData : requirementAssignmentDataList) { + String oldRequirementId = requirementAssignmentData.getRequirementId(); + RequirementAssignment abstractRequirementAssignment = (RequirementAssignment) + getClonedObject(requirementAssignmentData.getRequirementAssignment(), + RequirementAssignment.class); + String newRequirementId = oldRequirementId + "_" + newNodeTemplateId; + //Check if the requirement is not already present in the list of requirements of the + // abstract node template + if (!toscaAnalyzerService.isRequirementExistInNodeTemplate(abstractNodeTemplate, + newRequirementId, abstractRequirementAssignment)) { + DataModelUtil.addRequirementAssignment(abstractNodeTemplate, newRequirementId, + abstractRequirementAssignment); + //Update the volume relationship template if required + updateVolumeRelationshipTemplate(serviceTemplate, abstractRequirementAssignment + .getRelationship(), context); + } + } + } + } + + private NodeTemplate getAbstractNodeTemplate( + ServiceTemplate serviceTemplate, + UnifiedCompositionEntity unifiedCompositionEntity, + ComputeTemplateConsolidationData computeTemplateConsolidationData, + PortTemplateConsolidationData portTemplateConsolidationData, + TranslationContext context) { + String abstractNodeTemplateId = + getAbstractNodeTemplateId(serviceTemplate, unifiedCompositionEntity, + computeTemplateConsolidationData, portTemplateConsolidationData, context); + + return DataModelUtil.getNodeTemplate(serviceTemplate, + abstractNodeTemplateId); + } + + private String getAbstractNodeTemplateId( + ServiceTemplate serviceTemplate, + UnifiedCompositionEntity unifiedCompositionEntity, + ComputeTemplateConsolidationData computeTemplateConsolidationData, + PortTemplateConsolidationData portTemplateConsolidationData, + TranslationContext context) { + switch (unifiedCompositionEntity) { + case Compute: + return context.getUnifiedAbstractNodeTemplateId(serviceTemplate, + computeTemplateConsolidationData.getNodeTemplateId()); + case Port: + return context.getUnifiedAbstractNodeTemplateId(serviceTemplate, + portTemplateConsolidationData.getNodeTemplateId()); + default: + return null; + } + } + + private void updNodeGetAttrInConnectivity( + ServiceTemplate serviceTemplate, + EntityConsolidationData entityConsolidationData, + String oldNodeTemplateId, String newNodeTemplateId, + TranslationContext context, + Map consolidationNodeTemplateIdAndType, + boolean isNested) { + Map> nodesGetAttrIn = entityConsolidationData.getNodesGetAttrIn(); + if (MapUtils.isEmpty(nodesGetAttrIn)) { + return; + } + + for (String sourceNodeTemplateId : nodesGetAttrIn.keySet()) { + NodeTemplate sourceNodeTemplate = + DataModelUtil.getNodeTemplate(serviceTemplate, sourceNodeTemplateId); + if (!isNested && consolidationNodeTemplateIdAndType.keySet().contains(sourceNodeTemplateId)) { + continue; + } + List getAttrFuncDataList = nodesGetAttrIn.get(sourceNodeTemplateId); + for (GetAttrFuncData getAttrFuncData : getAttrFuncDataList) { + Object propertyValue = + DataModelUtil.getPropertyValue(sourceNodeTemplate, getAttrFuncData.getFieldName()); + String newAttrName = null; + String newGetAttrAbstractNodeTemplateId = newNodeTemplateId; + if (!isNested) { + newGetAttrAbstractNodeTemplateId = + context.getUnifiedAbstractNodeTemplateId(serviceTemplate, oldNodeTemplateId); + newAttrName = getNewSubstitutionOutputParameterId(newNodeTemplateId, getAttrFuncData + .getAttributeName()); + } + List> getAttrFuncValueList = extractGetAttrFunction(propertyValue); + updateGetAttrValue(oldNodeTemplateId, getAttrFuncData, newGetAttrAbstractNodeTemplateId, + newAttrName, getAttrFuncValueList, isNested); + } + } + } + + private void updateGetAttrValue(String oldNodeTemplateId, GetAttrFuncData getAttrFuncData, + String newNodeTemplateId, String newAttrName, + List> getAttrFuncValueList, boolean isNested) { + for (List getAttrFuncValue : getAttrFuncValueList) { + if (oldNodeTemplateId.equals(getAttrFuncValue.get(0)) + && getAttrFuncData.getAttributeName().equals(getAttrFuncValue.get(1))) { + getAttrFuncValue.set(0, newNodeTemplateId); + if (!isNested) { + getAttrFuncValue.set(1, newAttrName); + } + } + } + } + + private String getTemplateName(ServiceTemplate serviceTemplate, + UnifiedCompositionData unifiedCompositionData, + Integer index) { + ComputeTemplateConsolidationData computeTemplateConsolidationData = + unifiedCompositionData.getComputeTemplateConsolidationData(); + String computeType = + getComputeTypeSuffix(serviceTemplate, computeTemplateConsolidationData.getNodeTemplateId()); + String templateName = "Nested_" + computeType; + if (Objects.nonNull(index)) { + templateName = templateName + "_" + index.toString(); + } + return templateName; + } + + private String getComputeTypeSuffix(ServiceTemplate serviceTemplate, + String computeNodeTemplateId) { + NodeTemplate computeNodeTemplate = + DataModelUtil.getNodeTemplate(serviceTemplate, computeNodeTemplateId); + return getComputeTypeSuffix(computeNodeTemplate.getType()); + } + + /** + * Gets compute type. + * + * @param computeType the compute node type abc.def.vFSB + * @return the compute type e.g.:vFSB + */ + private String getComputeTypeSuffix(String computeType) { + return DataModelUtil.getNamespaceSuffix(computeType); + } + + private void updOutputParamGetAttrInConnectivity(ServiceTemplate serviceTemplate, + EntityConsolidationData entityConsolidationData, + String oldNodeTemplateId, + String newNodeTemplateId, + TranslationContext context, + boolean isNested) { + List outputParametersGetAttrIn = + entityConsolidationData.getOutputParametersGetAttrIn(); + if (CollectionUtils.isEmpty(outputParametersGetAttrIn)) { + return; + } + for (GetAttrFuncData getAttrFuncData : outputParametersGetAttrIn) { + Object outputParamValue = + DataModelUtil.getOuputParameter(serviceTemplate, getAttrFuncData.getFieldName()) + .getValue(); + String newAttrName = null; + String newGetAttrAbstractNodeTemplateId = newNodeTemplateId; + if (!isNested) { + newGetAttrAbstractNodeTemplateId = + context.getUnifiedAbstractNodeTemplateId(serviceTemplate, oldNodeTemplateId); + newAttrName = getNewSubstitutionOutputParameterId(newNodeTemplateId, getAttrFuncData + .getAttributeName()); + } + List> getAttrFuncValueList = extractGetAttrFunction(outputParamValue); + updateGetAttrValue(oldNodeTemplateId, getAttrFuncData, newGetAttrAbstractNodeTemplateId, + newAttrName, + getAttrFuncValueList, isNested); + } + + } + + private List> extractGetAttrFunction(Object valueObject) { + + List> getAttrValueList = new ArrayList<>(); + + if (valueObject instanceof Map) { + if (((Map) valueObject).containsKey(ToscaFunctions.GET_ATTRIBUTE.getDisplayName())) { + getAttrValueList.add( + (List) ((Map) valueObject).get(ToscaFunctions.GET_ATTRIBUTE.getDisplayName())); + } + + for (Object key : ((Map) valueObject).keySet()) { + getAttrValueList.addAll(extractGetAttrFunction(((Map) valueObject).get(key))); + } + + + } else if (valueObject instanceof List) { + for (Object valueEntity : (List) valueObject) { + getAttrValueList.addAll(extractGetAttrFunction(valueEntity)); + } + } + return getAttrValueList; + } + + private boolean isIncludeGetInputFunc(Object valueObject) { + if (valueObject instanceof Map) { + if (((Map) valueObject).containsKey(ToscaFunctions.GET_INPUT.getDisplayName())) { + return true; + } + Map.Entry functionMapEntry = + (Map.Entry) ((Map) valueObject).entrySet().iterator().next(); + return isIncludeGetInputFunc(functionMapEntry.getValue()); + + } else if (valueObject instanceof List) { + for (Object valueEntity : (List) valueObject) { + if (isIncludeGetInputFunc(valueEntity) == true) { + return true; + } + } + } + return false; + } + + private void createOutputParameters(ServiceTemplate serviceTemplate, + ServiceTemplate substitutionServiceTemplate, + List unifiedCompositionDataList, + String computeNodeType) { + + createOutputParametersForCompute(serviceTemplate, substitutionServiceTemplate, + unifiedCompositionDataList); + createOutputParameterForPorts(serviceTemplate, substitutionServiceTemplate, + unifiedCompositionDataList, computeNodeType); + } + + private void createOutputParameterForPorts( + ServiceTemplate serviceTemplate, + ServiceTemplate substitutionServiceTemplate, + List unifiedCompositionDataList, + String connectedComputeNodeType) { + for (UnifiedCompositionData unifiedCompositionData : unifiedCompositionDataList) { + List portTemplateConsolidationDataList = + getPortTemplateConsolidationDataList(unifiedCompositionData); + if (CollectionUtils.isEmpty(portTemplateConsolidationDataList)) { + return; + } + + for (PortTemplateConsolidationData portTemplateConsolidationData : + portTemplateConsolidationDataList) { + String newPortNodeTemplateId = + getNewPortNodeTemplateId(portTemplateConsolidationData.getNodeTemplateId(), + connectedComputeNodeType, + unifiedCompositionData.getComputeTemplateConsolidationData()); + addOutputParameters(portTemplateConsolidationData, newPortNodeTemplateId, + substitutionServiceTemplate, unifiedCompositionDataList); + } + } + } + + //The ID should be _ or _ + private String getNewPortNodeTemplateId( + String portNodeTemplateId, + String connectedComputeNodeType, + ComputeTemplateConsolidationData computeTemplateConsolidationData) { + + StringBuilder newPortNodeTemplateId = new StringBuilder(); + String portType = ConsolidationDataUtil.getPortType(portNodeTemplateId); + newPortNodeTemplateId.append(DataModelUtil.getNamespaceSuffix(connectedComputeNodeType)); + if (computeTemplateConsolidationData.getPorts().get(portType).size() > 1) { + //single port + newPortNodeTemplateId.append("_").append(portNodeTemplateId); + } else { + //consolidation port + newPortNodeTemplateId.append("_").append(portType); + } + return newPortNodeTemplateId.toString(); + } + + private void createOutputParametersForCompute( + ServiceTemplate serviceTemplate, + ServiceTemplate substitutionServiceTemplate, + List + unifiedCompositionDataList) { + List computeConsolidationDataList = + getComputeConsolidationDataList(unifiedCompositionDataList); + + for (EntityConsolidationData computeTemplateConsolidationData : computeConsolidationDataList) { + String newComputeNodeTemplateId = + getNewComputeNodeTemplateId(serviceTemplate, + computeTemplateConsolidationData.getNodeTemplateId()); + addOutputParameters(computeTemplateConsolidationData, newComputeNodeTemplateId, + substitutionServiceTemplate, unifiedCompositionDataList); + } + } + + private void addOutputParameters(EntityConsolidationData entityConsolidationData, + String newNodeTemplateId, + ServiceTemplate substitutionServiceTemplate, + List unifiedCompositionDataList) { + handleNodesGetAttrIn(entityConsolidationData, newNodeTemplateId, substitutionServiceTemplate, + unifiedCompositionDataList); + + handleOutputParamGetAttrIn(entityConsolidationData, newNodeTemplateId, + substitutionServiceTemplate); + } + + private void handleOutputParamGetAttrIn(EntityConsolidationData entityConsolidationData, + String newNodeTemplateId, + ServiceTemplate substitutionServiceTemplate) { + List outputParametersGetAttrIn = + entityConsolidationData.getOutputParametersGetAttrIn(); + if (!CollectionUtils.isEmpty(outputParametersGetAttrIn)) { + for (GetAttrFuncData getAttrFuncData : outputParametersGetAttrIn) { + createAndAddOutputParameter(entityConsolidationData, newNodeTemplateId, + substitutionServiceTemplate, getAttrFuncData); + } + } + } + + private void handleNodesGetAttrIn(EntityConsolidationData entityConsolidationData, + String newNodeTemplateId, + ServiceTemplate substitutionServiceTemplate, + List unifiedCompositionDataList) { + Map> getAttrIn = entityConsolidationData.getNodesGetAttrIn(); + + if (!MapUtils.isEmpty(getAttrIn)) { + Map consolidationNodeTemplateIdAndType = + getAllConsolidationNodeTemplateIdAndType(unifiedCompositionDataList); + for (String sourceNodeTemplateId : getAttrIn.keySet()) { + if (!consolidationNodeTemplateIdAndType.keySet().contains(sourceNodeTemplateId)) { + List getAttrFuncDataList = getAttrIn.get(sourceNodeTemplateId); + for (GetAttrFuncData getAttrFuncData : getAttrFuncDataList) { + createAndAddOutputParameter(entityConsolidationData, newNodeTemplateId, + substitutionServiceTemplate, getAttrFuncData); + } + } + } + } + } + + private void createAndAddOutputParameter(EntityConsolidationData entityConsolidationData, + String newNodeTemplateId, + ServiceTemplate substitutionServiceTemplate, + GetAttrFuncData getAttrFuncData) { + Map> parameterValue = new HashMap<>(); + List valueList = new ArrayList<>(); + valueList.add(newNodeTemplateId); + valueList.add(getAttrFuncData.getAttributeName()); + parameterValue.put(ToscaFunctions.GET_ATTRIBUTE.getDisplayName(), valueList); + ParameterDefinition outputParameter = new ParameterDefinition(); + outputParameter.setValue(parameterValue); + //todo - the type need to be change based on the attribute type in the accordingly node type + // of this node template - XXX, instead of list of string, list of XXXX, + outputParameter.setType(PropertyType.LIST.getDisplayName()); + outputParameter.setEntry_schema( + DataModelUtil.createEntrySchema(PropertyType.STRING.getDisplayName(), null, null)); + DataModelUtil.addOutputParameterToTopologyTemplate(substitutionServiceTemplate, + getNewSubstitutionOutputParameterId(newNodeTemplateId, getAttrFuncData.getAttributeName()), + outputParameter); + } + + private String getNewSubstitutionOutputParameterId(String newNodeTemplateId, + String attributeName) { + return newNodeTemplateId + "_" + attributeName; + } + + private void addUnifiedSubstitionData(TranslationContext context, ServiceTemplate + serviceTemplate, List unifiedCompositionDataList, String + substituteNodeTemplateId) { + String serviceTemplateFileName = ToscaUtil.getServiceTemplateFileName(serviceTemplate); + for (UnifiedCompositionData unifiedCompositionData : unifiedCompositionDataList) { + //Add compute node template mapping information + ComputeTemplateConsolidationData computeTemplateConsolidationData = + unifiedCompositionData.getComputeTemplateConsolidationData(); + String computeNodeTemplateId = computeTemplateConsolidationData.getNodeTemplateId(); + context.addUnifiedSubstitutionData(serviceTemplateFileName, computeNodeTemplateId, + substituteNodeTemplateId); + //Add Port template mapping information + List portTemplateConsolidationDataList = + getPortTemplateConsolidationDataList(unifiedCompositionData); + + if (CollectionUtils.isNotEmpty(portTemplateConsolidationDataList)) { + for (PortTemplateConsolidationData portTemplateConsolidationData : + portTemplateConsolidationDataList) { + String oldPortNodeTemplateId = portTemplateConsolidationData.getNodeTemplateId(); + context.addUnifiedSubstitutionData(serviceTemplateFileName, oldPortNodeTemplateId, + substituteNodeTemplateId); + } + } + } + } + + private void addSubstitutionFilteringProperty(String templateName, NodeTemplate nodeTemplate, + int count) { + Map serviceTemplateFilterPropertyValue = new HashMap<>(); + Map properties = nodeTemplate.getProperties(); + serviceTemplateFilterPropertyValue.put(ToscaConstants + .SUBSTITUTE_SERVICE_TEMPLATE_PROPERTY_NAME, templateName); + serviceTemplateFilterPropertyValue.put(ToscaConstants.COUNT_PROPERTY_NAME, count); + properties.put(ToscaConstants.SERVICE_TEMPLATE_FILTER_PROPERTY_NAME, + serviceTemplateFilterPropertyValue); + nodeTemplate.setProperties(properties); + } + + private void addIndexValueProperty(NodeTemplate nodeTemplate) { + List indexValueGetPropertyValue = new ArrayList<>(); + indexValueGetPropertyValue.add(ToscaConstants.MODELABLE_ENTITY_NAME_SELF); + indexValueGetPropertyValue.add(ToscaConstants.SERVICE_TEMPLATE_FILTER_PROPERTY_NAME); + indexValueGetPropertyValue.add(ToscaConstants.INDEX_VALUE_PROPERTY_NAME); + + Map indexPropertyValue = new HashMap<>(); + Map properties = nodeTemplate.getProperties(); + indexPropertyValue.put(ToscaFunctions.GET_PROPERTY.getDisplayName(), + indexValueGetPropertyValue); + properties.put(ToscaConstants.INDEX_VALUE_PROPERTY_NAME, + indexPropertyValue); + nodeTemplate.setProperties(properties); + } + + private String getSubstituteNodeTemplateId(ServiceTemplate serviceTemplate, + UnifiedCompositionData unifiedCompositionData, + Integer index) { + String computeNodeTemplateId = + unifiedCompositionData.getComputeTemplateConsolidationData().getNodeTemplateId(); + NodeTemplate computeNodeTemplate = + DataModelUtil.getNodeTemplate(serviceTemplate, computeNodeTemplateId); + String nodeTemplateId = ABSTRACT_NODE_TEMPLATE_ID_PREFIX + DataModelUtil + .getNamespaceSuffix(computeNodeTemplate.getType()); + if (Objects.nonNull(index)) { + nodeTemplateId = nodeTemplateId + "_" + index.toString(); + } + return nodeTemplateId; + } + + private String getSubstitutionNodeTypeId(ServiceTemplate serviceTemplate, + UnifiedCompositionData unifiedCompositionData, + Integer index) { + String computeNodeTemplateId = + unifiedCompositionData.getComputeTemplateConsolidationData().getNodeTemplateId(); + NodeTemplate computeNodeTemplate = + DataModelUtil.getNodeTemplate(serviceTemplate, computeNodeTemplateId); + String nodeTypeId = ToscaNodeType.ABSTRACT_NODE_TYPE_PREFIX + + DataModelUtil.getNamespaceSuffix(computeNodeTemplate.getType()); + if (Objects.nonNull(index)) { + nodeTypeId = nodeTypeId + "_" + index.toString(); + } + return nodeTypeId; + } + + private String getNewComputeNodeTemplateId( + ServiceTemplate serviceTemplate, + String computeNodeTemplateId) { + return getComputeTypeSuffix(serviceTemplate, computeNodeTemplateId); + } + + private NodeType handleSubstitutionGlobalNodeType(ServiceTemplate serviceTemplate, + ServiceTemplate substitutionServiceTemplate, + TranslationContext context, + UnifiedCompositionData unifiedCompositionData, + Integer index) { + String substitutionNodeTypeId = + getSubstitutionNodeTypeId(serviceTemplate, unifiedCompositionData, index); + NodeType substitutionNodeType = new ToscaAnalyzerServiceImpl() + .createInitSubstitutionNodeType(substitutionServiceTemplate, + ToscaNodeType.VFC_ABSTRACT_SUBSTITUTE); + ServiceTemplate globalSubstitutionServiceTemplate = + HeatToToscaUtil.fetchGlobalSubstitutionServiceTemplate(serviceTemplate, context); + DataModelUtil.addNodeType(globalSubstitutionServiceTemplate, substitutionNodeTypeId, + substitutionNodeType); + + return substitutionNodeType; + } + + private void handlePorts(ServiceTemplate serviceTemplate, + ServiceTemplate substitutionServiceTemplate, + List unifiedCompositionDataList, + String connectedComputeNodeType, + TranslationContext context) { + + if (unifiedCompositionDataList.size() > 1) { + handleConsolidationPorts(serviceTemplate, substitutionServiceTemplate, + unifiedCompositionDataList, connectedComputeNodeType, context); + } else { + handleSinglePorts(serviceTemplate, substitutionServiceTemplate, connectedComputeNodeType, + unifiedCompositionDataList, context); + } + } + + private void handleSinglePorts(ServiceTemplate serviceTemplate, + ServiceTemplate substitutionServiceTemplate, + String connectedComputeNodeType, + List unifiedCompositionDataList, + TranslationContext context) { + UnifiedCompositionData unifiedCompositionData = unifiedCompositionDataList.get(0); + List portTemplateConsolidationDataList = + getPortTemplateConsolidationDataList(unifiedCompositionData); + if (CollectionUtils.isEmpty(portTemplateConsolidationDataList)) { + return; + } + for (PortTemplateConsolidationData portTemplateConsolidationData : + portTemplateConsolidationDataList) { + List portConsolidationDataList = new ArrayList<>(); + portConsolidationDataList.add(portTemplateConsolidationData); + handlePortNodeTemplate(serviceTemplate, substitutionServiceTemplate, + portConsolidationDataList, connectedComputeNodeType, + unifiedCompositionData.getComputeTemplateConsolidationData(), + unifiedCompositionDataList, context); + } + } + + private void handleConsolidationPorts(ServiceTemplate serviceTemplate, + ServiceTemplate substitutionServiceTemplate, + List unifiedCompositionDataList, + String connectedComputeNodeType, + TranslationContext context) { + Collection computeConsolidationDataList = + (Collection) getComputeConsolidationDataList(unifiedCompositionDataList); + + Map> portIdsPerPortType = UnifiedCompositionUtil + .collectAllPortsFromEachTypesFromComputes(computeConsolidationDataList); + + for (String portType : portIdsPerPortType.keySet()) { + List portTemplateConsolidationDataList = + getPortConsolidationDataList(portIdsPerPortType.get(portType), + unifiedCompositionDataList); + if (CollectionUtils.isEmpty(portTemplateConsolidationDataList)) { + continue; + } + + handlePortNodeTemplate(serviceTemplate, substitutionServiceTemplate, + portTemplateConsolidationDataList, connectedComputeNodeType, + unifiedCompositionDataList.get(0).getComputeTemplateConsolidationData(), + unifiedCompositionDataList, context); + } + } + + private void handlePortNodeTemplate( + ServiceTemplate serviceTemplate, + ServiceTemplate substitutionServiceTemplate, + List portTemplateConsolidationDataList, + String connectedComputeNodeType, + ComputeTemplateConsolidationData computeTemplateConsolidationData, + List unifiedCompositionDataList, + TranslationContext context) { + EntityConsolidationData portTemplateConsolidationData = + portTemplateConsolidationDataList.get(0); + NodeTemplate newPortNodeTemplate = getNodeTemplate( + portTemplateConsolidationData.getNodeTemplateId(), serviceTemplate, context).clone(); + + removeConnectivityOut(portTemplateConsolidationData, newPortNodeTemplate); + handleProperties(serviceTemplate, newPortNodeTemplate, substitutionServiceTemplate, + UnifiedCompositionEntity.Port, portTemplateConsolidationDataList, + computeTemplateConsolidationData, unifiedCompositionDataList, context); + + String newPortNodeTemplateId = + getNewPortNodeTemplateId(portTemplateConsolidationData + .getNodeTemplateId(), connectedComputeNodeType, + computeTemplateConsolidationData); + //Update requirements for relationships between the consolidation entities + handleConsolidationEntitiesRequirementConnectivity(newPortNodeTemplateId, newPortNodeTemplate, + substitutionServiceTemplate, context); + DataModelUtil.addNodeTemplate(substitutionServiceTemplate, newPortNodeTemplateId, + newPortNodeTemplate); + + //Add the node template mapping in the context for handling requirement updation + context.addSubstitutionServiceTemplateUnifiedSubstitutionData(ToscaUtil + .getServiceTemplateFileName(substitutionServiceTemplate), + portTemplateConsolidationData.getNodeTemplateId(), newPortNodeTemplateId); + } + + + private NodeTemplate getNodeTemplate(String nodeTemplateId, ServiceTemplate serviceTemplate, + TranslationContext context) { + + NodeTemplate nodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, nodeTemplateId); + + if (Objects.isNull(nodeTemplate)) { + nodeTemplate = context + .getCleanedNodeTemplate(ToscaUtil.getServiceTemplateFileName(serviceTemplate), + nodeTemplateId); + + } + return nodeTemplate; + } + + + private String handleCompute(ServiceTemplate serviceTemplate, + ServiceTemplate substitutionServiceTemplate, + List unifiedCompositionDataList, + TranslationContext context) { + ComputeTemplateConsolidationData computeTemplateConsolidationData = + unifiedCompositionDataList.get(0).getComputeTemplateConsolidationData(); + handleComputeNodeTemplate(serviceTemplate, substitutionServiceTemplate, + unifiedCompositionDataList, context); + return handleComputeNodeType(serviceTemplate, substitutionServiceTemplate, + computeTemplateConsolidationData); + } + + private String handleComputeNodeType( + ServiceTemplate serviceTemplate, + ServiceTemplate substitutionServiceTemplate, + ComputeTemplateConsolidationData computeTemplateConsolidationData) { + NodeTemplate computeNodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, + computeTemplateConsolidationData.getNodeTemplateId()); + NodeType computeNodeType = + DataModelUtil.getNodeType(serviceTemplate, computeNodeTemplate.getType()); + DataModelUtil + .addNodeType(substitutionServiceTemplate, computeNodeTemplate.getType(), computeNodeType); + + return computeNodeTemplate.getType(); + } + + private void handleComputeNodeTemplate(ServiceTemplate serviceTemplate, + ServiceTemplate substitutionServiceTemplate, + List unifiedCompositionDataList, + TranslationContext context) { + ComputeTemplateConsolidationData computeTemplateConsolidationData = + unifiedCompositionDataList.get(0).getComputeTemplateConsolidationData(); + NodeTemplate newComputeNodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, + computeTemplateConsolidationData.getNodeTemplateId()).clone(); + + removeConnectivityOut(computeTemplateConsolidationData, newComputeNodeTemplate); + removeVolumeConnectivity(computeTemplateConsolidationData, newComputeNodeTemplate); + + List computeConsoliadtionDataList = + getComputeConsolidationDataList(unifiedCompositionDataList); + + handleProperties(serviceTemplate, newComputeNodeTemplate, substitutionServiceTemplate, + UnifiedCompositionEntity.Compute, computeConsoliadtionDataList, + computeTemplateConsolidationData, unifiedCompositionDataList, context); + + String newComputeNodeTemplateId = getNewComputeNodeTemplateId(serviceTemplate, + computeTemplateConsolidationData.getNodeTemplateId()); + //Update requirements for relationships between the consolidation entities + handleConsolidationEntitiesRequirementConnectivity(newComputeNodeTemplateId, + newComputeNodeTemplate, + substitutionServiceTemplate, context); + DataModelUtil + .addNodeTemplate(substitutionServiceTemplate, + newComputeNodeTemplateId, newComputeNodeTemplate); + //Add the node template mapping in the context for handling requirement updation + context.addSubstitutionServiceTemplateUnifiedSubstitutionData(ToscaUtil + .getServiceTemplateFileName(substitutionServiceTemplate), + computeTemplateConsolidationData.getNodeTemplateId(), newComputeNodeTemplateId); + + } + + private List getComputeConsolidationDataList( + List unifiedCompositionDataList) { + List computeConsolidationDataList = new ArrayList<>(); + for (UnifiedCompositionData unifiedCompositionData : unifiedCompositionDataList) { + computeConsolidationDataList + .add(unifiedCompositionData.getComputeTemplateConsolidationData()); + } + return computeConsolidationDataList; + } + + + private void handleProperties(ServiceTemplate serviceTemplate, NodeTemplate nodeTemplate, + ServiceTemplate substitutionServiceTemplate, + UnifiedCompositionEntity unifiedCompositionEntity, + List entityConsolidationDataList, + ComputeTemplateConsolidationData computeTemplateConsolidationData, + List unifiedCompositionDataList, + TranslationContext context) { + List propertiesWithIdenticalVal = consolidationService.getPropertiesWithIdenticalVal(); + nodeTemplate.setProperties(new HashedMap()); + + for (EntityConsolidationData entityConsolidationData : entityConsolidationDataList) { + String nodeTemplateId = entityConsolidationData.getNodeTemplateId(); + Map properties = + DataModelUtil.getNodeTemplateProperties(serviceTemplate, nodeTemplateId); + if (MapUtils.isEmpty(properties)) { + continue; + } + + for (Map.Entry propertyEntry : properties.entrySet()) { + if (propertiesWithIdenticalVal.contains(propertyEntry.getKey())) { + String parameterId = updateIdenticalProperty(nodeTemplate, propertyEntry.getKey()); + addInputParameter(parameterId, PropertyType.STRING.getDisplayName(), null, + substitutionServiceTemplate); + } else { + Optional parameterId = + updateProperty(serviceTemplate, nodeTemplateId, nodeTemplate, propertyEntry, + unifiedCompositionEntity, computeTemplateConsolidationData, + unifiedCompositionDataList, + context); + + //todo - define list of type which will match the node property type (instead of string) + NodeType nodeTypeWithFlatHierarchy = + HeatToToscaUtil.getNodeTypeWithFlatHierarchy(nodeTemplate.getType(), serviceTemplate, + context); + String propertyType = + nodeTypeWithFlatHierarchy.getProperties().get(propertyEntry.getKey()) + .getType(); + + if (propertyType.equalsIgnoreCase(PropertyType.STRING.getDisplayName()) + || propertyType.equalsIgnoreCase(PropertyType.INTEGER.getDisplayName()) + || propertyType.equalsIgnoreCase(PropertyType.FLOAT.getDisplayName()) + || propertyType.equalsIgnoreCase(PropertyType.BOOLEAN.getDisplayName())) { + parameterId + .ifPresent(parameterIdValue -> addInputParameter(parameterIdValue, + PropertyType.LIST.getDisplayName(), + DataModelUtil + .createEntrySchema(propertyType.toLowerCase(), null, null), + substitutionServiceTemplate)); + } else { + parameterId + .ifPresent(parameterIdValue -> addInputParameter(parameterIdValue, + PropertyType.LIST.getDisplayName(), + DataModelUtil + .createEntrySchema(PropertyTypeExt.JSON.getDisplayName(), null, null), + substitutionServiceTemplate)); + } + } + } + } + } + + private void handleConsolidationEntitiesRequirementConnectivity(String nodeTemplateId, + NodeTemplate nodeTemplate, + ServiceTemplate + substitutionServiceTemplate, + TranslationContext context) { + Map updatedNodeTemplateRequirements = new HashMap<>(); + List> nodeTemplateRequirements = DataModelUtil + .getNodeTemplateRequirementList(nodeTemplate); + if (CollectionUtils.isEmpty(nodeTemplateRequirements)) { + return; + } + + for (Map requirement : nodeTemplateRequirements) { + for (Map.Entry entry : requirement.entrySet()) { + RequirementAssignment requirementAssignment = entry.getValue(); + String requirementNode = requirementAssignment.getNode(); + String unifiedNodeTemplateId = + context.getUnifiedSubstitutionNodeTemplateId(substitutionServiceTemplate, + requirementNode); + if (unifiedNodeTemplateId != null) { + //Update the node id in the requirement + requirementAssignment.setNode(unifiedNodeTemplateId); + } + } + } + nodeTemplate.setRequirements(nodeTemplateRequirements); + } + + /** + * Update the node references in the volume relationship templates. + * + * @param serviceTemplate the service template + * @param context the context + */ + private void updateVolumeRelationshipTemplate(ServiceTemplate serviceTemplate, + String relationshipId, + TranslationContext context) { + Map relationshipTemplates = DataModelUtil + .getRelationshipTemplates(serviceTemplate); + if (relationshipTemplates != null) { + RelationshipTemplate relationshipTemplate = relationshipTemplates.get(relationshipId); + if (relationshipTemplate != null) { + String relationshipTemplateType = relationshipTemplate.getType(); + if (relationshipTemplateType.equals(ToscaRelationshipType.CINDER_VOLUME_ATTACHES_TO)) { + handleCinderVolumeAttachmentRelationshipTemplate(serviceTemplate, + relationshipTemplate, context); + } + } + } + } + + + private void handleCinderVolumeAttachmentRelationshipTemplate(ServiceTemplate + substitutionServiceTemplate, + RelationshipTemplate + relationshipTemplate, + TranslationContext context) { + Map properties = relationshipTemplate.getProperties(); + properties.computeIfPresent(HeatConstants.INSTANCE_UUID_PROPERTY_NAME, (key, value) -> + context.getUnifiedAbstractNodeTemplateId(substitutionServiceTemplate, + (String) value)); + } + + private String updateIdenticalProperty(NodeTemplate nodeTemplate, String propertyId) { + Map propertyVal = new HashMap<>(); + String inputParamId = IDENTICAL_VALUE_PROPERTY_PREFIX + propertyId + + IDENTICAL_VALUE_PROPERTY_SUFFIX; + propertyVal.put(ToscaFunctions.GET_INPUT.getDisplayName(), inputParamId); + nodeTemplate.getProperties().put(propertyId, propertyVal); + return inputParamId; + } + + private void addInputParameter(String parameterId, String parameterType, EntrySchema entrySchema, + ServiceTemplate serviceTemplate) { + + ParameterDefinition parameterDefinition = + DataModelUtil.createParameterDefinition(parameterType, null, null, + true, null, null, entrySchema, null); + DataModelUtil + .addInputParameterToTopologyTemplate(serviceTemplate, parameterId, parameterDefinition); + } + + // Return the input parameter Id which is used in the new property value if there is one + private Optional updateProperty( + ServiceTemplate serviceTemplate, + String nodeTemplateId, NodeTemplate nodeTemplate, + Map.Entry propertyEntry, + UnifiedCompositionEntity compositionEntity, + ComputeTemplateConsolidationData computeTemplateConsolidationData, + List unifiedCompositionDataList, + TranslationContext context) { + + if (handleGetAttrFromConsolidationNodes(serviceTemplate, nodeTemplate, propertyEntry, + unifiedCompositionDataList, context)) { + return Optional.empty(); + } + + Map> propertyVal = new HashMap<>(); + List getInputFuncParams = new ArrayList<>(); + String inputParamId = + getParameterId(nodeTemplateId, nodeTemplate, propertyEntry.getKey(), compositionEntity, + computeTemplateConsolidationData); + getInputFuncParams.add(inputParamId); + getInputFuncParams.add(ToscaConstants.INDEX_VALUE_PROPERTY_NAME); + propertyVal.put(ToscaFunctions.GET_INPUT.getDisplayName(), getInputFuncParams); + nodeTemplate.getProperties().put(propertyEntry.getKey(), propertyVal); + return Optional.of(inputParamId); + } + + private boolean handleGetAttrFromConsolidationNodes( + ServiceTemplate serviceTemplate, + NodeTemplate nodeTemplate, + Map.Entry propertyEntry, + List unifiedCompositionDataList, + TranslationContext context) { + Map consolidationNodeTemplateIdAndType = + getAllConsolidationNodeTemplateIdAndType(unifiedCompositionDataList); + + Set consolidationNodeTemplateIds = consolidationNodeTemplateIdAndType.keySet(); + boolean includeGetAttrFromConsolidationNodes = false; + boolean includeGetAttrFromOutsideNodes = false; + List> getAttrFunctionList = extractGetAttrFunction(propertyEntry.getValue()); + for (List getAttrFunc : getAttrFunctionList) { + if (consolidationNodeTemplateIds.contains(getAttrFunc.get(0))) { + includeGetAttrFromConsolidationNodes = true; + } else { + includeGetAttrFromOutsideNodes = true; + } + } + if ((includeGetAttrFromConsolidationNodes && includeGetAttrFromOutsideNodes) + || + (includeGetAttrFromConsolidationNodes && isIncludeGetInputFunc(propertyEntry.getValue()))) { + //This case is currently not supported - this property will be ignored + return true; + } else if (includeGetAttrFromConsolidationNodes) { + Object clonedPropertyValue = getClonedPropertyValue(propertyEntry); + List> clonedGetAttrFuncList = extractGetAttrFunction(clonedPropertyValue); + for (List getAttrFunc : clonedGetAttrFuncList) { + String targetNodeTemplateId = (String) getAttrFunc.get(0); + if (consolidationNodeTemplateIds.contains(targetNodeTemplateId)) { + updatePropertyGetAttrFunc(serviceTemplate, unifiedCompositionDataList, context, + consolidationNodeTemplateIdAndType, targetNodeTemplateId, getAttrFunc); + } + } + nodeTemplate.getProperties().put(propertyEntry.getKey(), clonedPropertyValue); + return true; + } + return false; + } + + private void updatePropertyGetAttrFunc( + ServiceTemplate serviceTemplate, + List unifiedCompositionDataList, + TranslationContext context, + Map consolidationNodeTemplateIdAndType, + String targetNodeTemplateId, + List getAttrFunc) { + UnifiedCompositionEntity targetCompositionEntity = + consolidationNodeTemplateIdAndType.get(targetNodeTemplateId); + String targetNewNodeTemplateId = + getNewNodeTemplateId(serviceTemplate, unifiedCompositionDataList, targetNodeTemplateId, + targetCompositionEntity); + getAttrFunc.set(0, targetNewNodeTemplateId); + } + + private String getNewNodeTemplateId(ServiceTemplate serviceTemplate, + List unifiedCompositionDataList, + String nodeTemplateId, + UnifiedCompositionEntity compositionEntity) { + switch (compositionEntity) { + case Compute: + return getNewComputeNodeTemplateId(serviceTemplate, nodeTemplateId); + case Port: + ComputeTemplateConsolidationData connectedComputeConsolidationData = + getConnectedComputeConsolidationData(serviceTemplate, + unifiedCompositionDataList, nodeTemplateId); + NodeTemplate connectedComputeNodeTemplate = + DataModelUtil.getNodeTemplate(serviceTemplate, + connectedComputeConsolidationData.getNodeTemplateId()); + return getNewPortNodeTemplateId(nodeTemplateId, connectedComputeNodeTemplate.getType(), + connectedComputeConsolidationData); + default: + return null; + } + } + + private String getNewNodeTemplateId(String origNodeTemplateId, + String serviceTemplateFileName, + ServiceTemplate serviceTemplate, + TranslationContext context) { + ConsolidationData consolidationData = context.getConsolidationData(); + + if (isIdIsOfExpectedType(origNodeTemplateId, UnifiedCompositionEntity.Port, + serviceTemplateFileName, + consolidationData, context)) { + return handleIdOfPort(origNodeTemplateId, serviceTemplateFileName, consolidationData); + } else if (isIdIsOfExpectedType(origNodeTemplateId, UnifiedCompositionEntity.Compute, + serviceTemplateFileName, consolidationData, context)) { + NodeTemplate nodeTemplate = + getComputeNodeTemplate(origNodeTemplateId, serviceTemplate, context); + return getComputeTypeSuffix(nodeTemplate.getType()); + } + + return null; + } + + private ComputeTemplateConsolidationData getConnectedComputeConsolidationData( + ServiceTemplate serviceTemplate, + List unifiedCompositionDataList, + String portNodeTemplateId) { + for (UnifiedCompositionData unifiedCompositionData : unifiedCompositionDataList) { + Collection> portsCollection = + unifiedCompositionData.getComputeTemplateConsolidationData().getPorts().values(); + for (List portIdList : portsCollection) { + for (String portId : portIdList) { + if (portId.equals(portNodeTemplateId)) { + return unifiedCompositionData.getComputeTemplateConsolidationData(); + } + } + } + } + return null; + } + + private Object getClonedPropertyValue(Map.Entry propertyEntry) { + if (propertyEntry.getValue() instanceof Map) { + return getClonedObject(propertyEntry.getValue(), Map.class); + } else if (propertyEntry.getValue() instanceof List) { + return getClonedObject(propertyEntry.getValue(), List.class); + } + return propertyEntry.getValue(); + } + + + private String getParameterId(String nodeTemplateId, NodeTemplate nodeTemplate, String propertyId, + UnifiedCompositionEntity unifiedCompositionEntity, + ComputeTemplateConsolidationData computeTemplateConsolidationData) { + switch (unifiedCompositionEntity) { + case Compute: + return UnifiedCompositionEntity.Compute.name().toLowerCase() + "_" + + getComputeTypeSuffix(nodeTemplate.getType()) + "_" + propertyId; + case Port: + String portType = ConsolidationDataUtil.getPortType(nodeTemplateId); + if (computeTemplateConsolidationData.getPorts().get(portType).size() > 1) { + return UnifiedCompositionEntity.Port.name().toLowerCase() + "_" + nodeTemplateId + "_" + + propertyId; + } + return UnifiedCompositionEntity.Port.name().toLowerCase() + "_" + portType + "_" + + propertyId; + default: + return propertyId; + } + } + + private void removeConnectivityOut(EntityConsolidationData entityConsolidationData, + NodeTemplate nodeTemplate) { + if (MapUtils.isEmpty(entityConsolidationData.getNodesConnectedOut())) { + return; + } + + for (List requirementAssignmentDataList : entityConsolidationData + .getNodesConnectedOut().values()) { + for (RequirementAssignmentData requirementAssignmentData : requirementAssignmentDataList) { + DataModelUtil.removeRequirementsAssignment(nodeTemplate.getRequirements(), + requirementAssignmentData.getRequirementId()); + } + if (nodeTemplate.getRequirements().isEmpty()) { + nodeTemplate.setRequirements(null); + } + } + } + + private void removeVolumeConnectivity( + ComputeTemplateConsolidationData computeTemplateConsolidationData, + NodeTemplate computeNodeTemplate) { + if (MapUtils.isEmpty(computeTemplateConsolidationData.getVolumes())) { + return; + } + Collection> volumeCollection = + computeTemplateConsolidationData.getVolumes().values(); + for (List requirementAssignmentDataList : volumeCollection) { + for (RequirementAssignmentData requirementAssignmentData : requirementAssignmentDataList) { + DataModelUtil.removeRequirementsAssignment(computeNodeTemplate.getRequirements(), + requirementAssignmentData.getRequirementId()); + } + } + if (computeNodeTemplate.getRequirements().isEmpty()) { + computeNodeTemplate.setRequirements(null); + } + } + + private void createIndexInputParameter(ServiceTemplate substitutionServiceTemplate) { + ParameterDefinition indexParameterDefinition = + DataModelUtil.createParameterDefinition(PropertyType.INTEGER.getDisplayName(), + "Index value of this substitution service template runtime instance", null, + false, createIndexValueConstraint(), null, null, 0); + DataModelUtil.addInputParameterToTopologyTemplate(substitutionServiceTemplate, + ToscaConstants.INDEX_VALUE_PROPERTY_NAME, indexParameterDefinition); + } + + + private List createIndexValueConstraint() { + List constraints; + constraints = new ArrayList<>(); + Constraint constraint = new Constraint(); + constraint.setGreater_or_equal(0); + constraints.add(constraint); + return constraints; + } + + private Optional getUnifiedCompositionInstance(UnifiedCompositionMode mode) { + String unifiedCompositionImplClassName = + unifiedCompositionImplMap.get(mode.name()).getImplementationClass(); + if (StringUtils.isEmpty(unifiedCompositionImplClassName)) { + return Optional.empty(); + } + return Optional + .of(CommonMethods.newInstance(unifiedCompositionImplClassName, UnifiedComposition.class)); + } + + private Optional> createAbstractSubstitutionProperties( + ServiceTemplate serviceTemplate, + ServiceTemplate substitutionServiceTemplate, + List unifiedCompositionDataList) { + Map abstractSubstituteProperties = new LinkedHashMap<>(); + Map substitutionTemplateInputs = DataModelUtil + .getInputParameters(substitutionServiceTemplate); + if (substitutionTemplateInputs == null) { + return Optional.empty(); + } + //Since all the computes have the same type fetching the type from the first entry + NodeTemplate firstComputeNodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, + unifiedCompositionDataList.get(0) + .getComputeTemplateConsolidationData().getNodeTemplateId()); + String computeType = getComputeTypeSuffix(firstComputeNodeTemplate.getType()); + for (Map.Entry input : substitutionTemplateInputs.entrySet()) { + String substitutionTemplateInputName = input.getKey(); + ParameterDefinition inputParameterDefinition = input.getValue(); + String inputType = inputParameterDefinition.getType(); + if (!inputType.equalsIgnoreCase(PropertyType.LIST.getDisplayName())) { + if (isIdenticalValueProperty(substitutionTemplateInputName)) { + //Handle identical value properties + Object abstractPropertyValue = getPropertyValueFromNodeTemplate( + getIdenticalValuePropertyName(substitutionTemplateInputName), + firstComputeNodeTemplate); + abstractSubstituteProperties.put(substitutionTemplateInputName, abstractPropertyValue); + } + continue; + } + + //Check if the input is of type compute or port + UnifiedCompositionEntity inputUnifiedCompositionEntity = getInputCompositionEntity( + substitutionTemplateInputName); + List abstractPropertyValue = new ArrayList<>(); + Object propertyValue = null; + switch (inputUnifiedCompositionEntity) { + case Compute: + for (UnifiedCompositionData compositionData : unifiedCompositionDataList) { + ComputeTemplateConsolidationData computeTemplateConsolidationData = + compositionData.getComputeTemplateConsolidationData(); + propertyValue = getComputePropertyValue(substitutionTemplateInputName, + serviceTemplate, computeTemplateConsolidationData); + if (!(propertyValue instanceof Optional)) { + abstractPropertyValue.add(propertyValue); + } + } + break; + case Port: + for (UnifiedCompositionData compositionData : unifiedCompositionDataList) { + ComputeTemplateConsolidationData computeTemplateConsolidationData = compositionData + .getComputeTemplateConsolidationData(); + List portTemplateConsolidationDataList = + getPortTemplateConsolidationDataList(compositionData); + //Get the input type for this input whether it is of type + // port__ or port__ + PortInputType portInputType = getPortInputType(substitutionTemplateInputName, + compositionData); + for (PortTemplateConsolidationData portTemplateConsolidationData : + portTemplateConsolidationDataList) { + //Get the port property value + String portNodeTemplateId = portTemplateConsolidationData.getNodeTemplateId(); + propertyValue = getPortPropertyValue(substitutionTemplateInputName, + computeType, portInputType, serviceTemplate, computeTemplateConsolidationData, + portNodeTemplateId); + //If the value object is Optional.empty it implies that the property name was not + // found in the input name + if (!(propertyValue instanceof Optional)) { + abstractPropertyValue.add(propertyValue); + } + } + } + break; + default: + break; + } + abstractSubstituteProperties.put(substitutionTemplateInputName, abstractPropertyValue); + } + return Optional.ofNullable(abstractSubstituteProperties); + } + + private PortInputType getPortInputType(String inputName, + UnifiedCompositionData unifiedCompositionData) { + String portInputPrefix = UnifiedCompositionEntity.Port.name().toLowerCase() + "_"; + ComputeTemplateConsolidationData computeTemplateConsolidationData = unifiedCompositionData + .getComputeTemplateConsolidationData(); + List portTemplateConsolidationDataList = + getPortTemplateConsolidationDataList(unifiedCompositionData); + //Scan the available port node template ids to check if the input is of the form + // "port__" + for (PortTemplateConsolidationData portTemplateConsolidationData : + portTemplateConsolidationDataList) { + String portNodeTemplateId = portTemplateConsolidationData.getNodeTemplateId(); + String portNodeTemplateIdPrefix = portInputPrefix + portNodeTemplateId; + if (inputName.startsWith(portNodeTemplateIdPrefix)) { + return PortInputType.NodeTemplateId; + } + } + //Check whether the input is of the form "port__" + Set portTypes = computeTemplateConsolidationData.getPorts().keySet(); + for (String portType : portTypes) { + String expectedPortTypeSusbtring = portInputPrefix + portType + "_"; + if (inputName.startsWith(expectedPortTypeSusbtring)) { + return PortInputType.PortType; + } + } + return PortInputType.Other; + } + + private void cleanServiceTemplate(ServiceTemplate serviceTemplate, + EntityConsolidationData entity, + TranslationContext context) { + removeNodeTemplateFromServiceTemplate(serviceTemplate, entity, context); + updateHeatStackGroup(serviceTemplate, entity, context); + } + + private void removeNodeTemplateFromServiceTemplate(ServiceTemplate serviceTemplate, + EntityConsolidationData entity, + TranslationContext context) { + String nodeTemplateIdToRemove = entity.getNodeTemplateId(); + Map nodeTemplates = + serviceTemplate.getTopology_template().getNode_templates(); + NodeTemplate nodeTemplateToRemove = + nodeTemplates.get(nodeTemplateIdToRemove); + nodeTemplates.remove(nodeTemplateIdToRemove); + + context.addCleanedNodeTemplate(ToscaUtil.getServiceTemplateFileName(serviceTemplate), + nodeTemplateIdToRemove, + entity.getClass() == ComputeTemplateConsolidationData.class + ? UnifiedCompositionEntity.Compute + : UnifiedCompositionEntity.Port, + nodeTemplateToRemove); + + } + + private void removeCleanedNodeType(String cleanedNodeTemplateId, + ServiceTemplate serviceTemplate, + TranslationContext context) { + NodeTemplate cleanedNodeTemplate = + context + .getCleanedNodeTemplate(ToscaUtil.getServiceTemplateFileName(serviceTemplate), + cleanedNodeTemplateId); + String typeToRemove = cleanedNodeTemplate.getType(); + + if (Objects.nonNull(typeToRemove) + && serviceTemplate.getNode_types().containsKey(typeToRemove)) { + serviceTemplate.getNode_types().remove(typeToRemove); + } + } + + private void updateHeatStackGroup(ServiceTemplate serviceTemplate, + EntityConsolidationData entity, + TranslationContext context) { + Map groups = serviceTemplate.getTopology_template() + .getGroups() == null ? new HashMap<>() + : serviceTemplate.getTopology_template().getGroups(); + String serviceTemplateFileName = ToscaUtil.getServiceTemplateFileName(serviceTemplate); + String nodeRelatedAbstractNodeId = + context.getUnifiedAbstractNodeTemplateId(serviceTemplate, entity.getNodeTemplateId()); + + for (Map.Entry groupEntry : groups.entrySet()) { + GroupDefinition groupDefinition = groupEntry.getValue(); + if (isHeatStackGroup(groupDefinition.getType())) { + updateGroupMembersWithNewUnifiedNodeTemplateId(entity, nodeRelatedAbstractNodeId, + groupEntry); + } + } + } + + private void updateGroupMembersWithNewUnifiedNodeTemplateId( + EntityConsolidationData entity, + String newNodetemplateId, + Map.Entry groupEntry) { + List members = groupEntry.getValue().getMembers(); + if (members.contains(entity.getNodeTemplateId())) { + members.remove(entity.getNodeTemplateId()); + if (!members.contains(newNodetemplateId)) { + members.add(newNodetemplateId); + } + } + groupEntry.getValue().setMembers(members); + } + + private void updateHeatStackGroupNestedComposition(ServiceTemplate serviceTemplate, + EntityConsolidationData entity, + TranslationContext context) { + Map groups = serviceTemplate.getTopology_template() + .getGroups() == null ? new HashMap<>() : serviceTemplate.getTopology_template().getGroups(); + String serviceTemplateFileName = ToscaUtil.getServiceTemplateFileName(serviceTemplate); + Optional nestedNodeTemplateId = + context.getUnifiedNestedNodeTemplateId(serviceTemplateFileName, entity.getNodeTemplateId()); + + if (nestedNodeTemplateId.isPresent()) { + for (Map.Entry groupEntry : groups.entrySet()) { + GroupDefinition groupDefinition = groupEntry.getValue(); + if (isHeatStackGroup(groupDefinition.getType())) { + updateGroupMembersWithNewUnifiedNodeTemplateId(entity, nestedNodeTemplateId.get(), + groupEntry); + } + } + } + } + + private void handleNestedNodeTemplateInMainServiceTemplate(String nestedNodeTemplateId, + ServiceTemplate mainServiceTemplate, + ServiceTemplate nestedServiceTemplate, + TranslationContext context) { + NodeTemplate nestedNodeTemplate = DataModelUtil.getNodeTemplate(mainServiceTemplate, + nestedNodeTemplateId); + if (Objects.isNull(nestedNodeTemplate)) { + return; + } + + Optional unifiedNestedNodeTypeId = context + .getUnifiedNestedNodeTypeId(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME, + nestedNodeTemplate.getType()); + unifiedNestedNodeTypeId + .ifPresent(unifiedNestedNodeTypeIdVal -> updateNestedNodeTemplate( + unifiedNestedNodeTypeIdVal, nestedNodeTemplateId, nestedNodeTemplate, + mainServiceTemplate, nestedServiceTemplate, context)); + } + + private void handleSubstitutionMappingInNestedServiceTemplate( + String newNestedNodeType, + ServiceTemplate nestedServiceTemplate) { + if (Objects.isNull(newNestedNodeType)) { + return; + } + + SubstitutionMapping substitutionMappings = + nestedServiceTemplate.getTopology_template().getSubstitution_mappings(); + substitutionMappings.setNode_type(newNestedNodeType); + } + + private void updateNestedNodeTemplate(String newNestedNodeTypeId, + String nestedNodeTemplateId, + NodeTemplate nestedNodeTemplate, + ServiceTemplate mainServiceTemplate, + ServiceTemplate nestedServiceTemplate, + TranslationContext context) { + String mainServiceTemplateName = ToscaUtil.getServiceTemplateFileName(mainServiceTemplate); + int index = + context.getHandledNestedComputeNodeTemplateIndex(mainServiceTemplateName, + newNestedNodeTypeId); + String newNodeTemplateId = + Constants.ABSTRACT_NODE_TEMPLATE_ID_PREFIX + getComputeTypeSuffix(newNestedNodeTypeId) + "_" + index; + + nestedNodeTemplate.setType(newNestedNodeTypeId); + mainServiceTemplate.getTopology_template().getNode_templates().remove(nestedNodeTemplateId); + mainServiceTemplate.getTopology_template().getNode_templates() + .put(newNodeTemplateId, nestedNodeTemplate); + + context + .addUnifiedNestedNodeTemplateId(mainServiceTemplateName, + nestedNodeTemplateId, newNodeTemplateId); + } + + private void handleNestedNodeTypesInGlobalSubstituteServiceTemplate( + String origNestedNodeTypeId, + String newNestedNodeTypeId, + ServiceTemplate globalSubstitutionServiceTemplate, + TranslationContext context) { + Map nodeTypes = globalSubstitutionServiceTemplate.getNode_types(); + NodeType nested = DataModelUtil.getNodeType(globalSubstitutionServiceTemplate, + origNestedNodeTypeId); + setNewValuesForNestedNodeType(origNestedNodeTypeId, newNestedNodeTypeId, nested, nodeTypes); + context.addUnifiedNestedNodeTypeId(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME, + origNestedNodeTypeId, newNestedNodeTypeId); + } + + private void setNewValuesForNestedNodeType(String origNestedNodeType, + String newNestedNodeTypeId, + NodeType nested, + Map nodeTypes) { + if (Objects.nonNull(nested)) { + nested.setDerived_from(ToscaNodeType.VFC_ABSTRACT_SUBSTITUTE); + nodeTypes.remove(origNestedNodeType); + nodeTypes.put(newNestedNodeTypeId, nested); + } + } + + private Optional getNewNestedNodeTypeId(ServiceTemplate mainServiceTemplate, + ServiceTemplate nestedServiceTemplate, + TranslationContext context) { + FileComputeConsolidationData fileComputeConsolidationData = + context.getConsolidationData().getComputeConsolidationData() + .getFileComputeConsolidationData( + ToscaUtil.getServiceTemplateFileName(nestedServiceTemplate)); + + if (Objects.nonNull(fileComputeConsolidationData)) { + String nestedNodeTypePrefix = ToscaNodeType.ABSTRACT_NODE_TYPE_PREFIX + "heat."; + return Optional + .of(nestedNodeTypePrefix + getComputeTypeInNestedFile(fileComputeConsolidationData)); + } + return Optional.empty(); + } + + private String getComputeTypeInNestedFile( + FileComputeConsolidationData fileComputeConsolidationData) { + List typeComputeConsolidationDatas = + new ArrayList<>(fileComputeConsolidationData.getAllTypeComputeConsolidationData()); + if (typeComputeConsolidationDatas.size() == 0) { + return null; + } else { + String computeNodeType = fileComputeConsolidationData.getAllComputeTypes().iterator().next(); + return getComputeTypeSuffix(computeNodeType); + } + } + + private void handleGetAttrInAbstractNodeTemplate(ServiceTemplate serviceTemplate, + TranslationContext context, + String serviceTemplateFileName, + NodeTemplate abstractNodeTemplate) { + Map properties = + abstractNodeTemplate == null || abstractNodeTemplate.getProperties() == null + ? new HashMap<>() + : abstractNodeTemplate.getProperties(); + for (Object propertyValue : properties.values()) { + List> getAttrList = extractGetAttrFunction(propertyValue); + for (List getAttrFuncValue : getAttrList) { + String origNodeTemplateId = (String) getAttrFuncValue.get(0); + Optional nestedNodeTemplateId = context.getUnifiedNestedNodeTemplateId(ToscaUtil + .getServiceTemplateFileName(serviceTemplate), origNodeTemplateId); + if (nestedNodeTemplateId.isPresent()) { + getAttrFuncValue.set(0, nestedNodeTemplateId.get()); + } else { + replaceGetAttrNodeIdAndAttrName(serviceTemplate, context, serviceTemplateFileName, + getAttrFuncValue); + } + } + } + } + + private void replaceGetAttrNodeIdAndAttrName(ServiceTemplate serviceTemplate, + TranslationContext context, + String serviceTemplateFileName, + List getAttrFuncValue) { + String origNodeTemplateId = (String) getAttrFuncValue.get(0); + String attributeName = (String) getAttrFuncValue.get(1); + + String unifiedAbstractNodeTemplateId = + context.getUnifiedAbstractNodeTemplateId(serviceTemplate, origNodeTemplateId); + + if (Objects.isNull(unifiedAbstractNodeTemplateId)) { + return; + } + + String newNodeTemplateId = + getNewNodeTemplateId(origNodeTemplateId, serviceTemplateFileName, serviceTemplate, context); + + String newSubstitutionOutputParameterId = + getNewSubstitutionOutputParameterId(newNodeTemplateId, attributeName); + + getAttrFuncValue.set(0, unifiedAbstractNodeTemplateId); + getAttrFuncValue.set(1, newSubstitutionOutputParameterId); + } + + private NodeTemplate getComputeNodeTemplate(String origNodeTemplateId, + ServiceTemplate serviceTemplate, + TranslationContext context) { + NodeTemplate computeNodeTemplate = + DataModelUtil.getNodeTemplate(serviceTemplate, origNodeTemplateId); + if (computeNodeTemplate == null) { + computeNodeTemplate = + context.getCleanedNodeTemplate(ToscaUtil.getServiceTemplateFileName(serviceTemplate), + origNodeTemplateId); + } + return computeNodeTemplate; + } + + private String handleIdOfPort(String origNodeTemplateId, String serviceTemplateFileName, + ConsolidationData consolidationData) { + Optional> + computeTypeAndComputeTemplateByPortId = + getComputeTypeAndComputeTemplateByPortId(origNodeTemplateId, serviceTemplateFileName, + consolidationData); + if (computeTypeAndComputeTemplateByPortId.isPresent()) { + Pair computeIdToComputeData = + computeTypeAndComputeTemplateByPortId.get(); + return getNewPortNodeTemplateId(origNodeTemplateId, computeIdToComputeData.getKey(), + computeIdToComputeData.getValue()); + } + + return null; + } + + private Optional> + getComputeTypeAndComputeTemplateByPortId(String portId, String serviceTemplateFileName, + ConsolidationData consolidationData) { + FileComputeConsolidationData fileComputeConsolidationData = + consolidationData.getComputeConsolidationData() + .getFileComputeConsolidationData(serviceTemplateFileName); + Set computeTypes = + fileComputeConsolidationData.getAllComputeTypes(); + + for (String computeType : computeTypes) { + Collection computeTemplateConsolidationDatas = + fileComputeConsolidationData.getTypeComputeConsolidationData(computeType) + .getAllComputeTemplateConsolidationData(); + + for (ComputeTemplateConsolidationData compute : computeTemplateConsolidationDatas) { + if (ConsolidationDataUtil.isComputeReferenceToPortId(compute, portId)) { + return Optional.of(new ImmutablePair<>(computeType, compute)); + } + } + } + + return Optional.empty(); + } + + private boolean isIdIsOfExpectedType(String id, + UnifiedCompositionEntity expectedUnifiedCompositionEntity, + String serviceTemplateFileName, + ConsolidationData consolidationData, + TranslationContext context) { + UnifiedSubstitutionData unifiedSubstitutionData = + context.getUnifiedSubstitutionData().get(serviceTemplateFileName); + if (Objects.isNull(unifiedSubstitutionData)) { + return false; + } + + UnifiedCompositionEntity actualUnifiedCompositionEntity = + unifiedSubstitutionData.getCleanedNodeTemplateCompositionEntity(id); + + return actualUnifiedCompositionEntity == null ? false + : actualUnifiedCompositionEntity.equals(expectedUnifiedCompositionEntity); + } + + private boolean isHeatStackGroup(String groupType) { + return groupType.equals(ToscaGroupType.HEAT_STACK); + } + + private Object getPortPropertyValue(String inputName, + String computeType, + PortInputType portInputType, + ServiceTemplate serviceTemplate, + ComputeTemplateConsolidationData + computeTemplateConsolidationData, + String portNodeTemplateId) { + //Get the input prefix to extract the property name from the input name + String portInputPrefix = getPortInputPrefix(computeTemplateConsolidationData, + portNodeTemplateId, portInputType); + //Get the property name from the input + Optional propertyName = getPropertyNameFromInput(inputName, + UnifiedCompositionEntity.Port, computeType, portInputPrefix); + //Get the property value from the node template + if (propertyName.isPresent()) { + NodeTemplate portNodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, + portNodeTemplateId); + return getPropertyValueFromNodeTemplate(propertyName.get(), portNodeTemplate); + } + return Optional.empty(); + } + + private Optional getPortTypeFromInput( + String inputName, + String portNodeTemplateId, + ComputeTemplateConsolidationData computeTemplateConsolidationData) { + String portTypeFromInput = null; + String portInputPrefix = UnifiedCompositionEntity.Port.name().toLowerCase() + "_"; + String portNodeTemplateIdPrefix = portInputPrefix + portNodeTemplateId; + if (inputName.startsWith(portNodeTemplateIdPrefix)) { + return Optional.empty(); + } + Set portTypes = computeTemplateConsolidationData.getPorts().keySet(); + for (String portType : portTypes) { + String expectedPortTypeSusbtring = "_" + portType + "_"; + if (inputName.contains(expectedPortTypeSusbtring)) { + portTypeFromInput = portType; + break; + } + } + return Optional.ofNullable(portTypeFromInput); + } + + private Object getComputePropertyValue( + String inputName, + ServiceTemplate serviceTemplate, + ComputeTemplateConsolidationData computeTemplateConsolidationData) { + NodeTemplate nodeTemplate = DataModelUtil.getNodeTemplate(serviceTemplate, + computeTemplateConsolidationData.getNodeTemplateId()); + String nodeType = getComputeTypeSuffix(nodeTemplate.getType()); + Optional propertyName = + getPropertyNameFromInput(inputName, UnifiedCompositionEntity.Compute, nodeType, null); + if (propertyName.isPresent()) { + return getPropertyValueFromNodeTemplate(propertyName.get(), nodeTemplate); + } + return Optional.empty(); + } + + private UnifiedCompositionEntity getInputCompositionEntity(String inputName) { + UnifiedCompositionEntity inputCompositionEntity = UnifiedCompositionEntity.Other; + String inputType = inputName.substring(0, inputName.indexOf('_')); + if (inputType.equals(UnifiedCompositionEntity.Compute.name().toLowerCase())) { + inputCompositionEntity = UnifiedCompositionEntity.Compute; + } else if (inputType.equals(UnifiedCompositionEntity.Port.name().toLowerCase())) { + inputCompositionEntity = UnifiedCompositionEntity.Port; + } + return inputCompositionEntity; + } + + private Optional getPropertyNameFromInput( + String inputName, + UnifiedCompositionEntity compositionEntity, + String computeType, String portInputPrefix) { + String propertyName = null; + switch (compositionEntity) { + case Compute: + propertyName = inputName.substring(inputName.lastIndexOf(computeType) + + computeType.length() + 1); + break; + case Port: + if (inputName.startsWith(portInputPrefix)) { + propertyName = inputName.split(portInputPrefix)[1]; + } + break; + default: + break; + } + return Optional.ofNullable(propertyName); + } + + private String getPortInputPrefix( + ComputeTemplateConsolidationData computeTemplateConsolidationData, + String portNodeTemplateId, + PortInputType portInputType) { + String portInputPrefix = UnifiedCompositionEntity.Port.name().toLowerCase() + "_"; + String portType = ConsolidationDataUtil.getPortType(portNodeTemplateId); + if (portInputType == PortInputType.NodeTemplateId) { + portInputPrefix += portNodeTemplateId + "_"; + } else if (portInputType == PortInputType.PortType) { + portInputPrefix += portType + "_"; + } + return portInputPrefix; + } + + private boolean isIdenticalValueProperty(String inputName) { + StringBuilder builder = new StringBuilder(IDENTICAL_VALUE_PROPERTY_PREFIX); + builder.append("[a-z]+"); + builder.append(IDENTICAL_VALUE_PROPERTY_SUFFIX); + boolean isMatchingProperty = Pattern.matches(builder.toString(), inputName); + List identicalValuePropertyList = consolidationService.getPropertiesWithIdenticalVal(); + if (isMatchingProperty + && identicalValuePropertyList.contains(getIdenticalValuePropertyName(inputName))) { + return true; + } + return false; + } + + private String getIdenticalValuePropertyName(String input) { + return input.split("_")[1]; + } + + private Object getPropertyValueFromNodeTemplate(String propertyName, NodeTemplate nodeTemplate) { + Map nodeTemplateProperties = nodeTemplate.getProperties(); + if (nodeTemplateProperties != null) { + Object propertyValue = nodeTemplateProperties.get(propertyName); + propertyValue = getClonedObject(propertyValue); + return propertyValue; + } + return null; + } + + private Object getClonedObject(Object objectValue, Class clazz) { + YamlUtil yamlUtil = new YamlUtil(); + Object clonedObjectValue; + String objectToYaml = yamlUtil.objectToYaml(objectValue); + clonedObjectValue = yamlUtil.yamlToObject(objectToYaml, clazz); + return clonedObjectValue; + } + + private Object getClonedObject(Object objectValue) { + Object clonedObjectValue; + try { + ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(); + ObjectOutputStream objectOutputStream = new ObjectOutputStream(byteArrayOutputStream); + objectOutputStream.writeObject(objectValue); + + ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(byteArrayOutputStream + .toByteArray()); + ObjectInputStream objectInputStream = new ObjectInputStream(byteArrayInputStream); + clonedObjectValue = objectInputStream.readObject(); + } catch (NotSerializableException ex) { + return getClonedObject(objectValue, objectValue.getClass()); + } catch (IOException ioe) { + return null; + } catch (ClassNotFoundException cnfe) { + return null; + } + return clonedObjectValue; + } + + private Map getAllConsolidationNodeTemplateIdAndType( + List unifiedCompositionDataList) { + + Map consolidationNodeTemplateIdAndType = new HashMap<>(); + for (UnifiedCompositionData unifiedCompositionData : unifiedCompositionDataList) { + ComputeTemplateConsolidationData computeTemplateConsolidationData = + unifiedCompositionData.getComputeTemplateConsolidationData(); + if (Objects.nonNull(computeTemplateConsolidationData)) { + consolidationNodeTemplateIdAndType + .put(computeTemplateConsolidationData.getNodeTemplateId(), + UnifiedCompositionEntity.Compute); + } + List portTemplateConsolidationDataList = + getPortTemplateConsolidationDataList(unifiedCompositionData); + for (PortTemplateConsolidationData portTemplateConsolidationData : + portTemplateConsolidationDataList) { + consolidationNodeTemplateIdAndType.put(portTemplateConsolidationData.getNodeTemplateId(), + UnifiedCompositionEntity.Port); + } + NestedTemplateConsolidationData nestedTemplateConsolidationData = + unifiedCompositionData.getNestedTemplateConsolidationData(); + if (Objects.nonNull(nestedTemplateConsolidationData)) { + consolidationNodeTemplateIdAndType + .put(nestedTemplateConsolidationData.getNodeTemplateId(), + UnifiedCompositionEntity.Nested); + } + } + return consolidationNodeTemplateIdAndType; + } + + private enum PortInputType { + NodeTemplateId, + PortType, + Other; + } + + private List getPortTemplateConsolidationDataList( + UnifiedCompositionData unifiedCompositionData) { + return unifiedCompositionData.getPortTemplateConsolidationDataList() == null ? new + ArrayList<>() : unifiedCompositionData.getPortTemplateConsolidationDataList(); + } +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/UnifiedCompositionUtil.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/UnifiedCompositionUtil.java new file mode 100644 index 0000000000..4d08176943 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/UnifiedCompositionUtil.java @@ -0,0 +1,55 @@ +package org.openecomp.sdc.translator.services.heattotosca; + +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.collections4.MapUtils; +import org.openecomp.sdc.logging.api.Logger; +import org.openecomp.sdc.logging.api.LoggerFactory; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.composition.UnifiedCompositionData; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.ComputeTemplateConsolidationData; + +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Set; + +/** + * Utility class for consolidation data collection helper methods. + */ +public class UnifiedCompositionUtil { + + protected static Logger logger = (Logger) LoggerFactory.getLogger(UnifiedCompositionUtil.class); + + /** + * Gets all ports per port type, which are connected to the computes from the input + * computeTemplateConsolidationDataCollection. + * + * @param computeTemplateConsolidationDataCollection collection of compute template + * consolidation data + * @return set of port ids, per port type + */ + public static Map> collectAllPortsFromEachTypesFromComputes( + Collection computeTemplateConsolidationDataCollection) { + Map> portTypeToIds = new HashMap<>(); + + for (ComputeTemplateConsolidationData compute : computeTemplateConsolidationDataCollection) { + Map> ports = compute.getPorts(); + if (!MapUtils.isEmpty(ports)) { + addPortsToMap(portTypeToIds, ports); + } + } + + return portTypeToIds; + } + + private static void addPortsToMap(Map> portTypeToIds, + Map> ports) { + for (Map.Entry> portTypeToIdEntry : ports.entrySet()) { + portTypeToIds.putIfAbsent(portTypeToIdEntry.getKey(), new HashSet<>()); + portTypeToIds.get(portTypeToIdEntry.getKey()).addAll(portTypeToIdEntry.getValue()); + } + } + + +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/IncorrectResourceReferenceErrorBuilder.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/IncorrectResourceReferenceErrorBuilder.java index c713855f60..fddf2a82d8 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/IncorrectResourceReferenceErrorBuilder.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/IncorrectResourceReferenceErrorBuilder.java @@ -23,11 +23,12 @@ package org.openecomp.sdc.translator.services.heattotosca.errors; import org.openecomp.sdc.common.errors.BaseErrorBuilder; import org.openecomp.sdc.common.errors.ErrorCategory; + public class IncorrectResourceReferenceErrorBuilder extends BaseErrorBuilder { private static final String INCORRECT_RESOURCE_REFERENCE_MSG = "resource id '%s' with type '%s' has reference to resource '%s' with" - + " type '%s' in property '%s'. Invalid type, resource type should be type of '%s'."; + + " type '%s' in property '%s'. Invalid type, resource type should be type of '%s'."; /** * Instantiates a new Incorrect resource reference error builder. diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/NotInSyncNumberOfInterfacesErrorBuilder.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/NotInSyncNumberOfInterfacesErrorBuilder.java index 810c09880e..ae903946e4 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/NotInSyncNumberOfInterfacesErrorBuilder.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/NotInSyncNumberOfInterfacesErrorBuilder.java @@ -28,7 +28,7 @@ public class NotInSyncNumberOfInterfacesErrorBuilder extends BaseErrorBuilder { private static final String NOT_IN_SYNC_NUMBER_OF_INTERFACES_MSG = "More than one ServiceInstance pointing to the same " - + "ServiceTemplate '%s', with different number of interfaces."; + + "ServiceTemplate '%s', with different number of interfaces."; /** * Instantiates a new Not in sync number of interfaces error builder. diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/ReferenceToUnsupportedResourceErrorBuilder.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/ReferenceToUnsupportedResourceErrorBuilder.java index 5b48cb2c59..dc41e5d207 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/ReferenceToUnsupportedResourceErrorBuilder.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/ReferenceToUnsupportedResourceErrorBuilder.java @@ -27,8 +27,8 @@ import org.openecomp.sdc.common.errors.ErrorCategory; public class ReferenceToUnsupportedResourceErrorBuilder extends BaseErrorBuilder { private static final String REFERENCE_TO_UNSUPPORTED_RESOURCE_MSG = - "Resource id '%s' with type '%s' has reference to" - + " unsupported resource '%s' with type '%s' in property '%s'"; + "Resource id '%s' with type '%s' has reference " + + "to unsupported resource '%s' with type '%s' in property '%s'"; /** * Instantiates a new Reference to unsupported resource error builder. diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/TranslatorErrorCodes.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/TranslatorErrorCodes.java index f9b873adca..bfcf834ae1 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/TranslatorErrorCodes.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/errors/TranslatorErrorCodes.java @@ -20,6 +20,7 @@ package org.openecomp.sdc.translator.services.heattotosca.errors; + public class TranslatorErrorCodes { public static final String MISSING_MANDATORY_PROPERTY = "MISSING_MANDATORY_PROPERTY"; public static final String HEAT_TO_TOSCA_MAPPING_COLLISION = "HEAT_TO_TOSCA_MAPPING_COLLISION"; diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/AbstractSubstituteGlobalType.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/AbstractSubstituteGlobalType.java deleted file mode 100644 index 221a9e522b..0000000000 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/AbstractSubstituteGlobalType.java +++ /dev/null @@ -1,167 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.translator.services.heattotosca.globaltypes; - -import org.openecomp.sdc.tosca.datatypes.ToscaDataType; -import org.openecomp.sdc.tosca.datatypes.ToscaNodeType; -import org.openecomp.sdc.tosca.datatypes.model.Constraint; -import org.openecomp.sdc.tosca.datatypes.model.DataType; -import org.openecomp.sdc.tosca.datatypes.model.NodeType; -import org.openecomp.sdc.tosca.datatypes.model.PropertyDefinition; -import org.openecomp.sdc.tosca.datatypes.model.PropertyType; -import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; -import org.openecomp.sdc.tosca.services.DataModelUtil; -import org.openecomp.sdc.tosca.services.ToscaConstants; -import org.openecomp.sdc.translator.services.heattotosca.Constants; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - - -public class AbstractSubstituteGlobalType { - - private AbstractSubstituteGlobalType() { - } - - /** - * Create service template service template. - * - * @return the service template - */ - public static ServiceTemplate createServiceTemplate() { - ServiceTemplate serviceTemplate = new ServiceTemplate(); - serviceTemplate.setTosca_definitions_version(ToscaConstants.TOSCA_DEFINITIONS_VERSION); - serviceTemplate.setMetadata( - DataModelUtil.createMetadata(Constants.ABSTRACT_SUBSTITUTE_TEMPLATE_NAME, "1.0.0", null)); - serviceTemplate.setImports(GlobalTypesUtil.createCommonImportList()); - serviceTemplate.setDescription("Abstract Substitute Global Types"); - serviceTemplate.setData_types(createGlobalDataTypes()); - serviceTemplate.setNode_types(createGlobalNodeTypes()); - return serviceTemplate; - } - - private static Map createGlobalNodeTypes() { - Map globalNodeTypes = new HashMap<>(); - globalNodeTypes.put(ToscaNodeType.ABSTRACT_SUBSTITUTE.getDisplayName(), - createAbstractSubstituteNodeType()); - return globalNodeTypes; - } - - private static NodeType createAbstractSubstituteNodeType() { - NodeType nodeType = new NodeType(); - nodeType.setDerived_from(ToscaNodeType.ROOT.getDisplayName()); - nodeType.setProperties(createAbstractSubstituteProperties()); - return nodeType; - } - - private static Map createAbstractSubstituteProperties() { - Map props = new HashMap<>(); - props.put(ToscaConstants.SERVICE_TEMPLATE_FILTER_PROPERTY_NAME, DataModelUtil - .createPropertyDefinition(ToscaDataType.SUBSTITUTION_FILTERING.getDisplayName(), - "Substitution Filter", true, null, null, null, null)); - - return props; - } - - - private static Map createGlobalDataTypes() { - Map globalDataTypes = new HashMap<>(); - globalDataTypes.put(ToscaDataType.SUBSTITUTION_FILTER.getDisplayName(), - createSubstitutionFilterDataType()); - globalDataTypes.put(ToscaDataType.SUBSTITUTION_FILTERING.getDisplayName(), - createSubstitutionFilteringDataType()); - return globalDataTypes; - } - - private static DataType createSubstitutionFilterDataType() { - DataType dataType = new DataType(); - dataType.setDerived_from(ToscaDataType.ROOT.getDisplayName()); - dataType.setDescription("Substitution Filter"); - Map properties = new HashMap<>(); - properties.put(ToscaConstants.COUNT_PROPERTY_NAME, DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), "Count", false, null, null, - null, 1)); - properties.put(ToscaConstants.SCALING_ENABLED_PROPERTY_NAME, DataModelUtil - .createPropertyDefinition(PropertyType.BOOLEAN.getDisplayName(), - "Indicates whether service scaling is enabled", false, null, null, null, true)); - properties.put(ToscaConstants.SUBSTITUTE_SERVICE_TEMPLATE_PROPERTY_NAME, DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), - "Substitute Service Template", true, null, null, null, null)); - properties.put("mandatory", DataModelUtil - .createPropertyDefinition(PropertyType.BOOLEAN.getDisplayName(), "Mandatory", false, null, - null, null, true)); - properties.put("index_variable", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), "Index variable", false, - createMinLengthConstraint(), null, null, "%index%")); - - dataType.setProperties(properties); - return dataType; - } - - private static List createMinLengthConstraint() { - List constraints; - constraints = new ArrayList<>(); - Constraint constraint = new Constraint(); - constraint.setMin_length(3); - constraints.add(constraint); - return constraints; - } - - private static DataType createSubstitutionFilteringDataType() { - DataType dataType = new DataType(); - dataType.setDerived_from(ToscaDataType.ROOT.getDisplayName()); - dataType.setDescription("Substitution Filter"); - Map properties = new HashMap<>(); - properties.put(ToscaConstants.COUNT_PROPERTY_NAME, DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), "Count", false, null, null, - null, 1)); - properties.put(ToscaConstants.INDEX_VALUE_PROPERTY_NAME, DataModelUtil - .createPropertyDefinition(PropertyType.INTEGER.getDisplayName(), - "Index value of the substitution service template runtime instance", false, - createIndexValueConstraint(), null, null, 0)); - properties.put(ToscaConstants.SCALING_ENABLED_PROPERTY_NAME, DataModelUtil - .createPropertyDefinition(PropertyType.BOOLEAN.getDisplayName(), - "Indicates whether service scaling is enabled", false, null, null, null, true)); - properties.put(ToscaConstants.SUBSTITUTE_SERVICE_TEMPLATE_PROPERTY_NAME, DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), - "Substitute Service Template", true, null, null, null, null)); - properties.put("mandatory", DataModelUtil - .createPropertyDefinition(PropertyType.BOOLEAN.getDisplayName(), "Mandatory", false, null, - null, null, true)); - - - dataType.setProperties(properties); - return dataType; - } - - private static List createIndexValueConstraint() { - List constraints; - constraints = new ArrayList<>(); - Constraint constraint = new Constraint(); - constraint.setGreater_or_equal(0); - constraints.add(constraint); - return constraints; - } - - -} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/CinderVolumeGlobalType.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/CinderVolumeGlobalType.java deleted file mode 100644 index 72f3043225..0000000000 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/CinderVolumeGlobalType.java +++ /dev/null @@ -1,242 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.translator.services.heattotosca.globaltypes; - -import org.openecomp.sdc.tosca.datatypes.ToscaNodeType; -import org.openecomp.sdc.tosca.datatypes.ToscaRelationshipType; -import org.openecomp.sdc.tosca.datatypes.model.AttributeDefinition; -import org.openecomp.sdc.tosca.datatypes.model.Constraint; -import org.openecomp.sdc.tosca.datatypes.model.NodeType; -import org.openecomp.sdc.tosca.datatypes.model.PropertyDefinition; -import org.openecomp.sdc.tosca.datatypes.model.PropertyType; -import org.openecomp.sdc.tosca.datatypes.model.RelationshipType; -import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; -import org.openecomp.sdc.tosca.services.DataModelUtil; -import org.openecomp.sdc.tosca.services.ToscaConstants; -import org.openecomp.sdc.translator.services.heattotosca.Constants; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class CinderVolumeGlobalType { - - /** - * Create service template service template. - * - * @return the service template - */ - public static ServiceTemplate createServiceTemplate() { - ServiceTemplate cinderVolumeServiceTemplate = new ServiceTemplate(); - cinderVolumeServiceTemplate - .setTosca_definitions_version(ToscaConstants.TOSCA_DEFINITIONS_VERSION); - cinderVolumeServiceTemplate.setMetadata( - DataModelUtil.createMetadata(Constants.CINDER_VOLUME_TEMPLATE_NAME, "1.0.0", null)); - cinderVolumeServiceTemplate.setDescription("Cinder Volume TOSCA Global Types"); - cinderVolumeServiceTemplate.setRelationship_types(createGlobalRelationshipTypes()); - cinderVolumeServiceTemplate.setNode_types(createGlobalNodeTypes()); - return cinderVolumeServiceTemplate; - } - - private static Map createGlobalNodeTypes() { - Map globalNodeTypes = new HashMap<>(); - globalNodeTypes.put(ToscaNodeType.CINDER_VOLUME.getDisplayName(), createCinderVolumeNodeType()); - return globalNodeTypes; - } - - private static NodeType createCinderVolumeNodeType() { - NodeType cinderVolumeNodeType = new NodeType(); - cinderVolumeNodeType.setDerived_from(ToscaNodeType.BLOCK_STORAGE.getDisplayName()); - cinderVolumeNodeType.setProperties(createCinderVolumeProperties()); - cinderVolumeNodeType.setAttributes(createCinderVolumeAttributes()); - return cinderVolumeNodeType; - } - - private static Map createGlobalRelationshipTypes() { - Map globalRelationshipTypes = new HashMap<>(); - globalRelationshipTypes.put(ToscaRelationshipType.CINDER_VOLUME_ATTACHES_TO.getDisplayName(), - createCinderVolumeAttachesToRelationshipType()); - return globalRelationshipTypes; - } - - private static RelationshipType createCinderVolumeAttachesToRelationshipType() { - RelationshipType cinderVolumeAttachesToRelationType = new RelationshipType(); - cinderVolumeAttachesToRelationType - .setDerived_from(ToscaRelationshipType.NATIVE_ATTACHES_TO.getDisplayName()); - cinderVolumeAttachesToRelationType - .setDescription("This type represents an attachment relationship for associating volume"); - - Map cinderVolumeAttachesToProps = new HashMap<>(); - cinderVolumeAttachesToProps.put("location", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), - "The location where the volume is exposed on the instance, mountpoint", false, null, - null, null, null)); //overridden location prop from attachesTo - cinderVolumeAttachesToProps.put("instance_uuid", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), - "The ID of the server to which the volume attaches", true, null, null, null, null)); - cinderVolumeAttachesToProps.put("volume_id", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), - "The ID of the volume to be attached", true, null, null, null, null)); - cinderVolumeAttachesToRelationType.setProperties(cinderVolumeAttachesToProps); - - Map cinderVolumeAttachesToAttributes = new HashMap<>(); - cinderVolumeAttachesToAttributes.put("show", DataModelUtil - .createAttributeDefinition(PropertyType.STRING.getDisplayName(), - "Detailed information about resource", null, null, null)); - cinderVolumeAttachesToRelationType.setAttributes(cinderVolumeAttachesToAttributes); - - return cinderVolumeAttachesToRelationType; - } - - private static Map createCinderVolumeProperties() { - Map cinderVolumePropertyDefMap = new HashMap<>(); - cinderVolumePropertyDefMap.put("availability_zone", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), - "The availability zone in which the volume will be created", false, null, null, null, - null)); - cinderVolumePropertyDefMap.put("backup_id", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), - "If specified, the backup to create the volume from", false, null, null, null, null)); - cinderVolumePropertyDefMap.put(Constants.DESCRIPTION_PROPERTY_NAME, DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), - "A description of the volume", false, null, null, null, null)); - cinderVolumePropertyDefMap.put("image", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), - "If specified, the name or ID of the image to create the volume from", false, null, - null, null, null)); - cinderVolumePropertyDefMap.put("metadata", DataModelUtil - .createPropertyDefinition(PropertyType.MAP.getDisplayName(), - "Key/value pairs to associate with the volume", false, null, null, - DataModelUtil.createEntrySchema(PropertyType.STRING.getDisplayName(), null, null), - null)); - cinderVolumePropertyDefMap.put("multiattach", DataModelUtil - .createPropertyDefinition(PropertyType.BOOLEAN.getDisplayName(), - "Whether allow the volume to be attached more than once", false, null, null, null, - null)); - cinderVolumePropertyDefMap.put(Constants.NAME_PROPERTY_NAME, DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), - "A name used to distinguish the volume", false, null, null, null, null)); - cinderVolumePropertyDefMap.put("read_only", DataModelUtil - .createPropertyDefinition(PropertyType.BOOLEAN.getDisplayName(), - "Enables or disables read-only access mode of volume", false, null, null, null, null)); - cinderVolumePropertyDefMap.put("scheduler_hints", DataModelUtil - .createPropertyDefinition(PropertyType.MAP.getDisplayName(), - "Arbitrary key-value pairs specified by the client " - + "to help the Cinder scheduler creating a volume", - false, null, null, - DataModelUtil.createEntrySchema(PropertyType.STRING.getDisplayName(), null, null), - null)); - cinderVolumePropertyDefMap.put("size", DataModelUtil - .createPropertyDefinition(PropertyType.SCALAR_UNIT_SIZE.getDisplayName(), - "The requested storage size (default unit is MB)", false, getSizeConstraints(), null, - null, null)); - cinderVolumePropertyDefMap.put("source_volid", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), - "If specified, the volume to use as source", false, null, null, null, null)); - cinderVolumePropertyDefMap.put("volume_type", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), - "If specified, the type of volume to use, mapping to a specific backend", false, null, - null, null, null)); - cinderVolumePropertyDefMap.put("delete_on_termination", DataModelUtil - .createPropertyDefinition(PropertyType.BOOLEAN.getDisplayName(), - "Indicate whether the volume should be deleted when the server is terminated", false, - null, null, null, null)); - cinderVolumePropertyDefMap.put("boot_index", DataModelUtil - .createPropertyDefinition(PropertyType.INTEGER.getDisplayName(), - "Integer used for ordering the boot disks", false, null, null, null, null)); - cinderVolumePropertyDefMap.put("device_type", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), "Device type", false, - getDeviceTypeConstraints(), null, null, null)); - cinderVolumePropertyDefMap.put("disk_bus", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), - "Bus of the device: hypervisor driver chooses a suitable default if omitted", false, - getDiskBusConstraints(), null, null, null)); - cinderVolumePropertyDefMap.put("swap_size", DataModelUtil - .createPropertyDefinition(PropertyType.SCALAR_UNIT_SIZE.getDisplayName(), - "The size of the swap, in MB", false, null, null, null, null)); - - return cinderVolumePropertyDefMap; - } - - private static Map createCinderVolumeAttributes() { - Map cinderVolumeAttributesDefMap = new HashMap<>(); - cinderVolumeAttributesDefMap.put("attachments", DataModelUtil - .createAttributeDefinition(PropertyType.STRING.getDisplayName(), - "The list of attachments of the volume", null, - DataModelUtil.createEntrySchema(PropertyType.STRING.getDisplayName(), null, null), - null)); - cinderVolumeAttributesDefMap.put("bootable", DataModelUtil - .createAttributeDefinition(PropertyType.BOOLEAN.getDisplayName(), - "Boolean indicating if the volume can be booted or not", null, null, null)); - cinderVolumeAttributesDefMap.put("created_at", DataModelUtil - .createAttributeDefinition(PropertyType.TIMESTAMP.getDisplayName(), - "The timestamp indicating volume creation", null, null, null)); - cinderVolumeAttributesDefMap.put("display_description", DataModelUtil - .createAttributeDefinition(PropertyType.STRING.getDisplayName(), - "Description of the volume", null, null, null)); - cinderVolumeAttributesDefMap.put("display_name", DataModelUtil - .createAttributeDefinition(PropertyType.STRING.getDisplayName(), "Name of the volume", null, - null, null)); - cinderVolumeAttributesDefMap.put("encrypted", DataModelUtil - .createAttributeDefinition(PropertyType.BOOLEAN.getDisplayName(), - "Boolean indicating if the volume is encrypted or not", null, null, null)); - cinderVolumeAttributesDefMap.put("metadata_values", DataModelUtil - .createAttributeDefinition(PropertyType.MAP.getDisplayName(), - "Key/value pairs associated with the volume in raw dict form", null, - DataModelUtil.createEntrySchema(PropertyType.STRING.getDisplayName(), null, null), - null)); - cinderVolumeAttributesDefMap.put("show", DataModelUtil - .createAttributeDefinition(PropertyType.STRING.getDisplayName(), - "Detailed information about resource", null, null, null)); - cinderVolumeAttributesDefMap.put("status", DataModelUtil - .createAttributeDefinition(PropertyType.STRING.getDisplayName(), - "The current status of the volume", null, null, null)); - return cinderVolumeAttributesDefMap; - } - - private static List getDeviceTypeConstraints() { - Constraint validValues; - List constraints = new ArrayList<>(); - validValues = DataModelUtil.createValidValuesConstraint("cdrom", "disk"); - constraints.add(validValues); - return constraints; - } - - private static List getDiskBusConstraints() { - Constraint validValues; - List constraints = new ArrayList<>(); - validValues = - DataModelUtil.createValidValuesConstraint("ide", "lame_bus", "scsi", "usb", "virtio"); - constraints.add(validValues); - return constraints; - } - - - private static List getSizeConstraints() { - List constraints; - constraints = new ArrayList<>(); - Constraint constraint = new Constraint(); - constraint.setGreater_or_equal("1 GB"); - constraints.add(constraint); - return constraints; - } -} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/CommonGlobalTypes.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/CommonGlobalTypes.java deleted file mode 100644 index 43a4782149..0000000000 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/CommonGlobalTypes.java +++ /dev/null @@ -1,500 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.translator.services.heattotosca.globaltypes; - - -import org.openecomp.sdc.tosca.datatypes.ToscaCapabilityType; -import org.openecomp.sdc.tosca.datatypes.ToscaDataType; -import org.openecomp.sdc.tosca.datatypes.ToscaGroupType; -import org.openecomp.sdc.tosca.datatypes.ToscaPolicyType; -import org.openecomp.sdc.tosca.datatypes.ToscaRelationshipType; -import org.openecomp.sdc.tosca.datatypes.model.AttributeDefinition; -import org.openecomp.sdc.tosca.datatypes.model.CapabilityType; -import org.openecomp.sdc.tosca.datatypes.model.Constraint; -import org.openecomp.sdc.tosca.datatypes.model.DataType; -import org.openecomp.sdc.tosca.datatypes.model.GroupType; -import org.openecomp.sdc.tosca.datatypes.model.Import; -import org.openecomp.sdc.tosca.datatypes.model.PolicyType; -import org.openecomp.sdc.tosca.datatypes.model.PropertyDefinition; -import org.openecomp.sdc.tosca.datatypes.model.PropertyType; -import org.openecomp.sdc.tosca.datatypes.model.RelationshipType; -import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; -import org.openecomp.sdc.tosca.services.DataModelUtil; -import org.openecomp.sdc.tosca.services.ToscaConstants; -import org.openecomp.sdc.tosca.services.ToscaUtil; -import org.openecomp.sdc.translator.services.heattotosca.Constants; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class CommonGlobalTypes { - - /** - * Create service template service template. - * - * @return the service template - */ - public static ServiceTemplate createServiceTemplate() { - ServiceTemplate serviceTemplate = new ServiceTemplate(); - serviceTemplate.setTosca_definitions_version(ToscaConstants.TOSCA_DEFINITIONS_VERSION); - serviceTemplate.setMetadata( - DataModelUtil.createMetadata(Constants.COMMON_GLOBAL_TEMPLATE_NAME, "1.0.0", null)); - serviceTemplate.setDescription("TOSCA Global Types"); - serviceTemplate.setData_types(createGlobalDataTypes()); - serviceTemplate.setGroup_types(createGroupTypes()); - serviceTemplate.setPolicy_types(createPolicyTypes()); - serviceTemplate.setRelationship_types(createRelationTypes()); - serviceTemplate.setCapability_types(createCapabilityTypes()); - serviceTemplate.setImports(createImportList()); - return serviceTemplate; - } - - private static Map createCapabilityTypes() { - Map capabilityMap = new HashMap<>(); - capabilityMap.put(ToscaCapabilityType.METRIC.getDisplayName(), createMetricCapabilityType()); - capabilityMap - .put(ToscaCapabilityType.METRIC_CEILOMETER.getDisplayName(), createMetricCeilometerType()); - capabilityMap.put(ToscaCapabilityType.METRIC_SNMP_TRAP.getDisplayName(), createMetricSnmpType( - "A node type that includes the Metric capability" - + " indicates that it can be monitored using snmp trap.")); - capabilityMap.put(ToscaCapabilityType.METRIC_SNMP_POLLING.getDisplayName(), - createMetricSnmpType( - "A node type that includes the Metric capability indicates" - + " that it can be monitored using snmp polling.")); - return capabilityMap; - } - - - private static CapabilityType createMetricSnmpType(String description) { - CapabilityType capabilityType = new CapabilityType(); - capabilityType.setDerived_from(ToscaCapabilityType.METRIC.getDisplayName()); - capabilityType.setDescription(description); - capabilityType.setProperties(createCapabilityMetricSnmpProperties()); - - return capabilityType; - } - - - private static Map createCapabilityMetricSnmpProperties() { - Map propertyDefinitionMap = new HashMap<>(); - propertyDefinitionMap.put("oid", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), "Object Id of the metric", - true, null, null, null, null)); - return propertyDefinitionMap; - } - - private static CapabilityType createMetricCeilometerType() { - CapabilityType capabilityType = new CapabilityType(); - capabilityType.setDerived_from(ToscaCapabilityType.METRIC.getDisplayName()); - capabilityType.setDescription( - "A node type that includes the Metric capability" - + " indicates that it can be monitored using ceilometer."); - capabilityType.setProperties(createCapabilityMetricCeilometerProperties()); - return capabilityType; - } - - - private static Map createCapabilityMetricCeilometerProperties() { - Map propertyDefinitionMap = new HashMap<>(); - propertyDefinitionMap.put(Constants.NAME_PROPERTY_NAME, DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), - "Ceilometer metric type name to monitor. (The name ceilometer is using)", true, null, - null, null, null)); - return propertyDefinitionMap; - } - - private static Map createImportList() { - Map importsMap = new HashMap<>(); - importsMap.put(ToscaConstants.NATIVE_TYPES_SERVICE_TEMPLATE_NAME, GlobalTypesUtil - .createServiceTemplateImport(ToscaConstants.NATIVE_TYPES_SERVICE_TEMPLATE_NAME)); - return importsMap; - } - - /** - * Create metric capability type capability type. - * - * @return the capability type - */ - public static CapabilityType createMetricCapabilityType() { - CapabilityType capabilityType = new CapabilityType(); - capabilityType.setDerived_from(ToscaCapabilityType.NFV_METRIC.getDisplayName()); - capabilityType.setDescription( - "A node type that includes the Metric capability indicates that it can be monitored."); - capabilityType.setProperties(createCapabilityMetricProperties()); - capabilityType.setAttributes(createCapabilityMetricAttributes()); - return capabilityType; - } - - private static Map createCapabilityMetricAttributes() { - Map attributeDefinitionMap = new HashMap<>(); - - attributeDefinitionMap.put("value", DataModelUtil - .createAttributeDefinition(PropertyType.STRING.getDisplayName(), "Runtime monitored value", - null, null, null)); - return attributeDefinitionMap; - } - - private static Map createCapabilityMetricProperties() { - Map propertyDefinitionMap = new HashMap<>(); - propertyDefinitionMap.put("type", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), - "Type of the metric value, for an example, Cumulative, Delta, Gauge and etc.", true, - null, null, null, null)); - propertyDefinitionMap.put("unit", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), "Unit of the metric value", - true, null, null, null, null)); - propertyDefinitionMap.put("category", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), - "Category of the metric, for an example, compute, disk, network, storage and etc.", - false, null, null, null, null)); - propertyDefinitionMap.put(Constants.DESCRIPTION_PROPERTY_NAME, DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), "Description of the metric", - false, null, null, null, null)); - return propertyDefinitionMap; - } - - private static Map createRelationTypes() { - Map globalRelationshipTypes = new HashMap<>(); - globalRelationshipTypes.put(ToscaRelationshipType.ATTACHES_TO.getDisplayName(), - createAttachesToRelationshipType()); - return globalRelationshipTypes; - } - - private static RelationshipType createAttachesToRelationshipType() { - RelationshipType attachesToRelationType = new RelationshipType(); - attachesToRelationType.setDerived_from(ToscaRelationshipType.ROOT.getDisplayName()); - attachesToRelationType.setDescription("This type represents an attachment relationship"); - return attachesToRelationType; - } - - private static Map createPolicyTypes() { - Map globalPolicyTypes = new HashMap<>(); - globalPolicyTypes - .put(ToscaPolicyType.PLACEMENT_ANTILOCATE.getDisplayName(), createAntilocatePolicyType()); - globalPolicyTypes - .put(ToscaPolicyType.PLACEMENT_COLOCATE.getDisplayName(), createColocatePolicyType()); - globalPolicyTypes.put(ToscaPolicyType.PLACEMENT_VALET_AFFINITY.getDisplayName(), - createValetAffinityPolicyType()); - globalPolicyTypes.put(ToscaPolicyType.PLACEMENT_VALET_DIVERSITY.getDisplayName(), - createValetDiversityPolicyType()); - globalPolicyTypes.put(ToscaPolicyType.PLACEMENT_VALET_EXCLUSIVITY.getDisplayName(), - createValetExclusivityPolicyType()); - return globalPolicyTypes; - } - - private static PolicyType createValetDiversityPolicyType() { - PolicyType policyType = new PolicyType(); - policyType.setDerived_from(ToscaPolicyType.PLACEMENT.getDisplayName()); - policyType.setDescription("Valet Diversity"); - policyType.setProperties(new HashMap<>()); - policyType.getProperties().put("level", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), "diversity", false, - DataModelUtil.createValidValuesConstraintsList("host", "rack"), null, null, "host")); - - return policyType; - } - - private static PolicyType createValetExclusivityPolicyType() { - PolicyType policyType = new PolicyType(); - policyType.setDerived_from(ToscaPolicyType.PLACEMENT.getDisplayName()); - policyType.setDescription("Valet Exclusivity"); - policyType.setProperties(addNamePropertyToPolicyType()); - policyType.setProperties(new HashMap<>()); - policyType.getProperties().put("level", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), "exclusivity", false, - DataModelUtil.createValidValuesConstraintsList("host", "rack"), null, null, "host")); - return policyType; - } - - private static PolicyType createValetAffinityPolicyType() { - PolicyType policyType = new PolicyType(); - policyType.setDerived_from(ToscaPolicyType.PLACEMENT.getDisplayName()); - policyType.setDescription("Valet Affinity"); - policyType.setProperties(new HashMap<>()); - policyType.getProperties().put("level", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), "affinity", false, - DataModelUtil.createValidValuesConstraintsList("host", "rack"), null, null, "host")); - - return policyType; - } - - - private static PolicyType createColocatePolicyType() { - PolicyType policyType = new PolicyType(); - policyType.setDerived_from(ToscaPolicyType.PLACEMENT.getDisplayName()); - policyType.setDescription("Keep associated nodes (groups of nodes) based upon affinity value"); - policyType.setProperties(addNamePropertyToPolicyType()); - policyType.getProperties().put("affinity", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), "affinity", true, - DataModelUtil.createValidValuesConstraintsList("host", "region", "compute"), null, null, - null)); - - return policyType; - } - - private static PolicyType createAntilocatePolicyType() { - PolicyType policyType = new PolicyType(); - policyType.setDerived_from(ToscaPolicyType.PLACEMENT.getDisplayName()); - policyType.setDescription("My placement policy for separation based upon container type value"); - policyType.setProperties(addNamePropertyToPolicyType()); - policyType.getProperties().put("container_type", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), "container type", false, - DataModelUtil.createValidValuesConstraintsList("host", "region", "compute"), null, null, - null)); - return policyType; - } - - private static Map addNamePropertyToPolicyType() { - Map policyTypeProperties = new HashMap<>(); - policyTypeProperties.put(Constants.NAME_PROPERTY_NAME, DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), "The name of the policy", - false, null, null, null, null)); - return policyTypeProperties; - } - - private static Map createGroupTypes() { - Map globalGroupTypes = new HashMap<>(); - globalGroupTypes.put(ToscaGroupType.HEAT_STACK.getDisplayName(), createHeatStackGroupType()); - return globalGroupTypes; - } - - private static GroupType createHeatStackGroupType() { - GroupType heatStackGroupType = new GroupType(); - heatStackGroupType.setDerived_from(ToscaGroupType.ROOT.getDisplayName()); - heatStackGroupType - .setDescription("Grouped all heat resources which are in the same heat stack"); - heatStackGroupType.setProperties(createHeatStackGroupProperties()); - - return heatStackGroupType; - } - - private static Map createHeatStackGroupProperties() { - Map propertiesDef = new HashMap<>(); - propertiesDef.put("heat_file", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), - "Heat file which associate to this group/heat stack", true, null, null, null, null)); - propertiesDef.put(Constants.DESCRIPTION_PROPERTY_NAME, DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), "Heat file description", - false, null, null, null, null)); - return propertiesDef; - } - - - /** - * Create common service template import import. - * - * @return the import - */ - public static Import createCommonServiceTemplateImport() { - Import commonServiceTemplateImport = new Import(); - commonServiceTemplateImport - .setFile(ToscaUtil.getServiceTemplateFileName(Constants.COMMON_GLOBAL_TEMPLATE_NAME)); - return commonServiceTemplateImport; - } - - private static Map createGlobalDataTypes() { - Map globalDataTypes = new HashMap<>(); - globalDataTypes.put(ToscaDataType.NETWORK_ALLOCATION_POOL.getDisplayName(), - createAllocationPoolDataType()); - globalDataTypes - .put(ToscaDataType.NETWORK_HOST_ROUTE.getDisplayName(), createHostRouteDataType()); - globalDataTypes.put(ToscaDataType.NEUTRON_SUBNET.getDisplayName(), createSubnetDataType()); - globalDataTypes - .put(ToscaDataType.NETWORK_ADDRESS_PAIR.getDisplayName(), createAddressPairDataType()); - globalDataTypes.put(ToscaDataType.CONTRAIL_STATIC_ROUTE.getDisplayName(), - createContrailStaticRouteDataType()); - globalDataTypes.put(ToscaDataType.CONTRAIL_ADDRESS_PAIR.getDisplayName(), - createContrailAddressPairDataType()); - return globalDataTypes; - } - - private static DataType createContrailStaticRouteDataType() { - DataType dataType = new DataType(); - dataType.setDerived_from(ToscaDataType.ROOT.getDisplayName()); - dataType.setDescription("static route"); - Map prop = new HashMap<>(); - - prop.put("prefix", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), "Route prefix", false, null, - null, null, null)); - prop.put("next_hop", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), "Next hop", false, null, - null, null, null)); - prop.put("next_hop_type", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), "Next hop type", false, - null, null, null, null)); - - dataType.setProperties(prop); - return dataType; - } - - private static DataType createContrailAddressPairDataType() { - DataType dataType = new DataType(); - dataType.setDerived_from(ToscaDataType.ROOT.getDisplayName()); - dataType.setDescription("Address Pair"); - Map prop = new HashMap<>(); - - prop.put("prefix", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), "IP address prefix", false, - null, null, null, null)); - prop.put("mac_address", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), "Mac address", false, null, - null, null, null)); - prop.put("address_mode", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), - "Address mode active-active or active-standy", false, - DataModelUtil.createValidValuesConstraintsList("active-active", "active-standby"), null, - null, null)); - - dataType.setProperties(prop); - return dataType; - } - - private static DataType createAddressPairDataType() { - DataType addressPairDataType = new DataType(); - addressPairDataType.setDerived_from(ToscaDataType.ROOT.getDisplayName()); - addressPairDataType.setDescription("MAC/IP address pairs"); - Map addressPairProp = new HashMap<>(); - - addressPairProp.put("ip_address", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), "IP address", false, null, - null, null, null)); - addressPairProp.put("mac_address", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), "MAC address", false, null, - null, null, null)); - addressPairDataType.setProperties(addressPairProp); - - return addressPairDataType; - } - - private static DataType createHostRouteDataType() { - DataType hostRouteDataType = new DataType(); - hostRouteDataType.setDerived_from(ToscaDataType.ROOT.getDisplayName()); - hostRouteDataType.setDescription("Host route info for the subnet"); - - Map hostRoutePoolProp = new HashMap<>(); - hostRoutePoolProp.put("destination", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), - "The destination for static route", false, null, null, null, null)); - hostRoutePoolProp.put("nexthop", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), - "The next hop for the destination", false, null, null, null, null)); - hostRouteDataType.setProperties(hostRoutePoolProp); - - return hostRouteDataType; - } - - private static DataType createAllocationPoolDataType() { - DataType allocationPoolDataType = new DataType(); - allocationPoolDataType.setDerived_from(ToscaDataType.ROOT.getDisplayName()); - allocationPoolDataType.setDescription("The start and end addresses for the allocation pool"); - - Map allocationPoolProp = new HashMap<>(); - allocationPoolProp.put("start", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), - "Start address for the allocation pool", false, null, null, null, null)); - allocationPoolProp.put("end", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), - "End address for the allocation pool", false, null, null, null, null)); - allocationPoolDataType.setProperties(allocationPoolProp); - - return allocationPoolDataType; - } - - private static DataType createSubnetDataType() { - DataType subnetDataType = new DataType(); - subnetDataType.setDerived_from(ToscaDataType.ROOT.getDisplayName()); - subnetDataType.setDescription( - "A subnet represents an IP address block that can " - + "be used for assigning IP addresses to virtual instances"); - - Map subnetProp = new HashMap<>(); - subnetProp.put("allocation_pools", DataModelUtil - .createPropertyDefinition(PropertyType.LIST.getDisplayName(), - "The start and end addresses for the allocation pools", false, null, null, DataModelUtil - .createEntrySchema(ToscaDataType.NETWORK_ALLOCATION_POOL.getDisplayName(), null, - null), null)); - subnetProp.put("cidr", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), "The CIDR", false, null, - null, null, null)); - subnetProp.put("dns_nameservers", DataModelUtil - .createPropertyDefinition(PropertyType.LIST.getDisplayName(), - "A specified set of DNS name servers to be used", false, null, null, - DataModelUtil.createEntrySchema(PropertyType.STRING.getDisplayName(), null, null), - new ArrayList())); - subnetProp.put("enable_dhcp", DataModelUtil - .createPropertyDefinition(PropertyType.BOOLEAN.getDisplayName(), - "Set to true if DHCP is enabled and false if DHCP is disabled", false, null, null, null, - true)); - subnetProp.put("gateway_ip", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), "The gateway IP address", - false, null, null, null, null)); - subnetProp.put("host_routes", DataModelUtil - .createPropertyDefinition(PropertyType.LIST.getDisplayName(), "The gateway IP address", - false, null, null, DataModelUtil - .createEntrySchema(ToscaDataType.NETWORK_HOST_ROUTE.getDisplayName(), null, null), - null)); - subnetProp.put("ip_version", DataModelUtil - .createPropertyDefinition(PropertyType.INTEGER.getDisplayName(), "The gateway IP address", - false, DataModelUtil.createValidValuesConstraintsList("4", "6"), null, null, 4)); - subnetProp.put("ipv6_address_mode", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), "IPv6 address mode", false, - DataModelUtil - .createValidValuesConstraintsList("dhcpv6-stateful", "dhcpv6-stateless", "slaac"), - null, null, null)); - subnetProp.put("ipv6_ra_mode", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), - "IPv6 RA (Router Advertisement) mode", false, DataModelUtil - .createValidValuesConstraintsList("dhcpv6-stateful", "dhcpv6-stateless", "slaac"), - null, null, null)); - subnetProp.put(Constants.NAME_PROPERTY_NAME, DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), "The name of the subnet", - false, null, null, null, null)); - subnetProp.put("prefixlen", DataModelUtil - .createPropertyDefinition(PropertyType.INTEGER.getDisplayName(), - "Prefix length for subnet allocation from subnet pool", false, - createPrefixlenConstraint(), null, null, null)); - subnetProp.put("subnetpool", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), - "The name or ID of the subnet pool", false, null, null, null, null)); - subnetProp.put("tenant_id", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), - "The ID of the tenant who owns the network", false, null, null, null, null)); - subnetProp.put("value_specs", DataModelUtil - .createPropertyDefinition(PropertyType.MAP.getDisplayName(), - "Extra parameters to include in the request", false, null, null, - DataModelUtil.createEntrySchema(PropertyType.STRING.getDisplayName(), null, null), - new HashMap<>())); - subnetDataType.setProperties(subnetProp); - - return subnetDataType; - } - - private static List createPrefixlenConstraint() { - List constraints = new ArrayList<>(); - Constraint constraint = new Constraint(); - constraint.setGreater_or_equal(0); - constraints.add(constraint); - return constraints; - } -} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/ContrailAbstractSubstituteGlobalType.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/ContrailAbstractSubstituteGlobalType.java deleted file mode 100644 index 7b0b810b61..0000000000 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/ContrailAbstractSubstituteGlobalType.java +++ /dev/null @@ -1,196 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.translator.services.heattotosca.globaltypes; - -import org.openecomp.sdc.tosca.datatypes.ToscaDataType; -import org.openecomp.sdc.tosca.datatypes.ToscaNodeType; -import org.openecomp.sdc.tosca.datatypes.model.AttributeDefinition; -import org.openecomp.sdc.tosca.datatypes.model.DataType; -import org.openecomp.sdc.tosca.datatypes.model.NodeType; -import org.openecomp.sdc.tosca.datatypes.model.PropertyDefinition; -import org.openecomp.sdc.tosca.datatypes.model.PropertyType; -import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; -import org.openecomp.sdc.tosca.services.DataModelUtil; -import org.openecomp.sdc.tosca.services.ToscaConstants; -import org.openecomp.sdc.translator.services.heattotosca.Constants; - -import java.util.HashMap; -import java.util.Map; - - -public class ContrailAbstractSubstituteGlobalType { - - /** - * Create service template service template. - * - * @return the service template - */ - public static ServiceTemplate createServiceTemplate() { - ServiceTemplate serviceTemplate = new ServiceTemplate(); - serviceTemplate.setTosca_definitions_version(ToscaConstants.TOSCA_DEFINITIONS_VERSION); - serviceTemplate.setMetadata( - DataModelUtil.createMetadata(Constants - .CONTRAIL_ABSTRACT_SUBSTITUTE_TEMPLATE_NAME, "1.0.0", null)); - serviceTemplate.setImports(GlobalTypesUtil.createCommonImportList()); - serviceTemplate.setDescription("Contrail Abstract Substitute Global Types"); - serviceTemplate.setData_types(createGlobalDataTypes()); - serviceTemplate.setNode_types(createGlobalNodeTypes()); - return serviceTemplate; - } - - private static Map createGlobalNodeTypes() { - Map globalNodeTypes = new HashMap<>(); - globalNodeTypes.put(ToscaNodeType.CONTRAIL_ABSTRACT_SUBSTITUTE.getDisplayName(), - createContrailAbstractSubstituteNodeType()); - return globalNodeTypes; - } - - private static NodeType createContrailAbstractSubstituteNodeType() { - NodeType nodeType = new NodeType(); - nodeType.setDerived_from(ToscaNodeType.ABSTRACT_SUBSTITUTE.getDisplayName()); - nodeType.setProperties(createContrailAbstractSubstituteProperties()); - nodeType.setAttributes(createContrailAbstractSubstituteAttributes()); - - return nodeType; - } - - private static Map createContrailAbstractSubstituteAttributes() { - Map attributesDefMap = new HashMap<>(); - attributesDefMap.put("service_instance_name", DataModelUtil - .createAttributeDefinition(PropertyType.STRING.getDisplayName(), - "The name of the service instance", null, null, null)); - attributesDefMap.put("fq_name", DataModelUtil - .createAttributeDefinition(PropertyType.STRING.getDisplayName(), - "The FQ name of the service instance", null, null, null)); - attributesDefMap.put("status", DataModelUtil - .createAttributeDefinition(PropertyType.STRING.getDisplayName(), - "Status of the service instance", null, null, null)); - attributesDefMap.put("service_template_name", DataModelUtil - .createAttributeDefinition(PropertyType.STRING.getDisplayName(), - "Service Template of the Service Instance", null, null, null)); - attributesDefMap.put("virtual_machines", DataModelUtil - .createAttributeDefinition(PropertyType.STRING.getDisplayName(), - "Service VMs for the Service Instance", null, null, null)); - attributesDefMap.put("active_vms", DataModelUtil - .createAttributeDefinition(PropertyType.STRING.getDisplayName(), - "Number of service VMs active for this Service Instance", null, null, null)); - attributesDefMap.put("tenant_id", DataModelUtil - .createAttributeDefinition(PropertyType.STRING.getDisplayName(), - "Tenant id of the Service Instance", null, null, null)); - attributesDefMap.put("show", DataModelUtil - .createAttributeDefinition(PropertyType.STRING.getDisplayName(), "All attributes", null, - null, null)); - - return attributesDefMap; - } - - private static Map createContrailAbstractSubstituteProperties() { - Map props = new HashMap<>(); - props.put("service_template_name", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), "Service template name", - false, null, null, null, null)); - props.put("service_mode", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), "Service mode", true, - DataModelUtil - .createValidValuesConstraintsList("transparent", "in-network", "in-network-nat"), - null, null, null)); - props.put("service_type", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), "Service type", true, - DataModelUtil.createValidValuesConstraintsList("firewall", "analyzer", "source-nat", - "loadbalancer"), null, null, null)); - props.put("image_name", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), "Image name", true, null, - null, null, null)); - props.put("flavor", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), "flavor", false, null, null, - null, null)); - props.put("service_interface_type_list", DataModelUtil - .createPropertyDefinition(PropertyType.LIST.getDisplayName(), "List of interface types", - true, null, null, DataModelUtil - .createEntrySchema(PropertyType.STRING.getDisplayName(), null, DataModelUtil - .createValidValuesConstraintsList("management", "left", "right", "other")), - null)); - props.put("shared_ip_list", DataModelUtil - .createPropertyDefinition(PropertyType.LIST.getDisplayName(), "Shared ips enabled", false, - null, null, - DataModelUtil.createEntrySchema(PropertyType.BOOLEAN.getDisplayName(), null, null), - null)); - props.put("static_routes_list", DataModelUtil - .createPropertyDefinition(PropertyType.LIST.getDisplayName(), "Static routes enabled", - false, null, null, - DataModelUtil.createEntrySchema(PropertyType.BOOLEAN.getDisplayName(), null, null), - null)); - props.put("ordered_interfaces", DataModelUtil - .createPropertyDefinition(PropertyType.BOOLEAN.getDisplayName(), - "Indicates if service interface are ordered", false, null, null, null, false)); - props.put("availability_zone_enable", DataModelUtil - .createPropertyDefinition(PropertyType.BOOLEAN.getDisplayName(), - "Indicates availability zone is enabled", false, null, null, null, false)); - props.put("availability_zone", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), - "Availability zone to create servers in", false, null, null, null, null)); - props.put("service_instance_name", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), "Service instance name", - true, null, null, null, null)); - props.put("interface_list", DataModelUtil - .createPropertyDefinition(PropertyType.LIST.getDisplayName(), "List of interfaces", false, - null, null, DataModelUtil - .createEntrySchema(ToscaDataType.CONTRAIL_INTERFACE_DATA.getDisplayName(), null, - null), null)); - return props; - } - - - private static Map createGlobalDataTypes() { - Map globalDataTypes = new HashMap<>(); - globalDataTypes - .put(ToscaDataType.CONTRAIL_INTERFACE_DATA.getDisplayName(), createInterfaceDataType()); - return globalDataTypes; - } - - private static DataType createInterfaceDataType() { - DataType dataType = new DataType(); - dataType.setDerived_from(ToscaDataType.ROOT.getDisplayName()); - dataType.setDescription("Interface Data"); - Map propertyDefMap = new HashMap<>(); - propertyDefMap.put("virtual_network", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), - "Virtual Network for this interface", true, null, null, null, null)); - propertyDefMap.put("ip_address", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), "IP for this interface", - false, null, null, null, null)); - propertyDefMap.put("static_routes", DataModelUtil - .createPropertyDefinition(PropertyType.LIST.getDisplayName(), - "An ordered list of static routes to be added to this interface", false, null, null, - DataModelUtil - .createEntrySchema(ToscaDataType.CONTRAIL_STATIC_ROUTE.getDisplayName(), null, - null), null)); - propertyDefMap.put("allowed_address_pairs", DataModelUtil - .createPropertyDefinition(PropertyType.LIST.getDisplayName(), - "List of allowed address pair for this interface", false, null, null, DataModelUtil - .createEntrySchema(ToscaDataType.CONTRAIL_ADDRESS_PAIR.getDisplayName(), null, - null), null)); - dataType.setProperties(propertyDefMap); - return dataType; - } - - -} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/ContrailComputeGlobalType.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/ContrailComputeGlobalType.java deleted file mode 100644 index 50faec0c69..0000000000 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/ContrailComputeGlobalType.java +++ /dev/null @@ -1,128 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.translator.services.heattotosca.globaltypes; - -import org.openecomp.sdc.tosca.datatypes.ToscaNodeType; -import org.openecomp.sdc.tosca.datatypes.model.AttributeDefinition; -import org.openecomp.sdc.tosca.datatypes.model.NodeType; -import org.openecomp.sdc.tosca.datatypes.model.PropertyDefinition; -import org.openecomp.sdc.tosca.datatypes.model.PropertyType; -import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; -import org.openecomp.sdc.tosca.services.DataModelUtil; -import org.openecomp.sdc.tosca.services.ToscaConstants; -import org.openecomp.sdc.translator.services.heattotosca.Constants; - -import java.util.HashMap; -import java.util.Map; - -public class ContrailComputeGlobalType { - - /** - * Create service template service template. - * - * @return the service template - */ - public static ServiceTemplate createServiceTemplate() { - ServiceTemplate serviceTemplate = new ServiceTemplate(); - serviceTemplate.setTosca_definitions_version(ToscaConstants.TOSCA_DEFINITIONS_VERSION); - serviceTemplate.setMetadata( - DataModelUtil.createMetadata(Constants.CONTRAIL_COMPUTE_TEMPLATE_NAME, "1.0.0", null)); - serviceTemplate.setDescription("Contrail Compute TOSCA Global Types"); - serviceTemplate.setImports(GlobalTypesUtil.createCommonImportList()); - serviceTemplate.setNode_types(createGlobalNodeTypes()); - return serviceTemplate; - } - - - private static Map createGlobalNodeTypes() { - Map globalNodeTypes = new HashMap<>(); - globalNodeTypes - .put(ToscaNodeType.CONTRAIL_COMPUTE.getDisplayName(), createContrailComputeNodeType()); - return globalNodeTypes; - } - - private static NodeType createContrailComputeNodeType() { - NodeType nodeType = new NodeType(); - nodeType.setDerived_from(ToscaNodeType.COMPUTE.getDisplayName()); - nodeType.setProperties(createContrailComputeProperties()); - nodeType.setAttributes(createContrailComputeAttributes()); - return nodeType; - } - - - private static Map createContrailComputeProperties() { - Map propertyDefMap = new HashMap<>(); - propertyDefMap.put("service_instance_name", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), "Service instance name", - true, null, null, null, null)); - propertyDefMap.put("service_template_name", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), "Service template name", - false, null, null, null, null)); - propertyDefMap.put("image_name", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), "Image name", true, null, - null, null, null)); - propertyDefMap.put("service_mode", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), "Service mode", true, - DataModelUtil - .createValidValuesConstraintsList("transparent", "in-network", "in-network-nat"), - null, null, null)); - propertyDefMap.put("service_type", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), "Service type", true, - DataModelUtil.createValidValuesConstraintsList("firewall", "analyzer", "source-nat", - "loadbalancer"), null, null, null)); - propertyDefMap.put("image_name", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), "Image name", true, null, - null, null, null)); - propertyDefMap.put("flavor", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), "flavor", false, null, null, - null, null)); - propertyDefMap.put("availability_zone_enable", DataModelUtil - .createPropertyDefinition(PropertyType.BOOLEAN.getDisplayName(), - "Indicates availability zone is enabled", false, null, null, null, false)); - propertyDefMap.put("availability_zone", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), - "Availability zone to create servers in", false, null, null, null, null)); - return propertyDefMap; - } - - private static Map createContrailComputeAttributes() { - Map attributesDefMap = new HashMap<>(); - attributesDefMap.put("fq_name", DataModelUtil - .createAttributeDefinition(PropertyType.STRING.getDisplayName(), "fq_name", null, null, - null)); - attributesDefMap.put("status", DataModelUtil - .createAttributeDefinition(PropertyType.STRING.getDisplayName(), "status of the compute", - null, null, null)); - attributesDefMap.put("virtual_machines", DataModelUtil - .createAttributeDefinition(PropertyType.STRING.getDisplayName(), "VMs of this compute", - null, null, null)); - attributesDefMap.put("active_vms", DataModelUtil - .createAttributeDefinition(PropertyType.STRING.getDisplayName(), "Number of active VMs", - null, null, null)); - attributesDefMap.put("tenant_id", DataModelUtil - .createAttributeDefinition(PropertyType.STRING.getDisplayName(), "Tenant id of the VM", - null, null, null)); - attributesDefMap.put("show", DataModelUtil - .createAttributeDefinition(PropertyType.STRING.getDisplayName(), "All attributes", null, - null, null)); - return attributesDefMap; - } -} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/ContrailNetworkRuleGlobalType.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/ContrailNetworkRuleGlobalType.java deleted file mode 100644 index 0081ad5a78..0000000000 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/ContrailNetworkRuleGlobalType.java +++ /dev/null @@ -1,227 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.translator.services.heattotosca.globaltypes; - -import org.openecomp.sdc.tosca.datatypes.ToscaCapabilityType; -import org.openecomp.sdc.tosca.datatypes.ToscaDataType; -import org.openecomp.sdc.tosca.datatypes.ToscaNodeType; -import org.openecomp.sdc.tosca.datatypes.ToscaRelationshipType; -import org.openecomp.sdc.tosca.datatypes.model.AttributeDefinition; -import org.openecomp.sdc.tosca.datatypes.model.DataType; -import org.openecomp.sdc.tosca.datatypes.model.NodeType; -import org.openecomp.sdc.tosca.datatypes.model.PropertyDefinition; -import org.openecomp.sdc.tosca.datatypes.model.PropertyType; -import org.openecomp.sdc.tosca.datatypes.model.RequirementDefinition; -import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; -import org.openecomp.sdc.tosca.services.DataModelUtil; -import org.openecomp.sdc.tosca.services.ToscaConstants; -import org.openecomp.sdc.translator.services.heattotosca.Constants; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class ContrailNetworkRuleGlobalType { - /** - * Create service template service template. - * - * @return the service template - */ - public static ServiceTemplate createServiceTemplate() { - ServiceTemplate contrailNetworkRuleServiceTemplate = new ServiceTemplate(); - contrailNetworkRuleServiceTemplate - .setTosca_definitions_version(ToscaConstants.TOSCA_DEFINITIONS_VERSION); - contrailNetworkRuleServiceTemplate.setMetadata( - DataModelUtil.createMetadata(Constants.CONTRAIL_NETWORK_RULE_TEMPLATE_NAME, "1.0.0", null)); - contrailNetworkRuleServiceTemplate.setImports(GlobalTypesUtil.createCommonImportList()); - contrailNetworkRuleServiceTemplate.setDescription("Contrail Network Rule Global Types"); - contrailNetworkRuleServiceTemplate.setData_types(createGlobalDataTypes()); - contrailNetworkRuleServiceTemplate.setNode_types(createGlobalNodeTypes()); - return contrailNetworkRuleServiceTemplate; - } - - - private static Map createGlobalDataTypes() { - Map globalDataTypes = new HashMap<>(); - globalDataTypes.put(ToscaDataType.CONTRAIL_NETWORK_RULE_PORT_PAIRS.getDisplayName(), - createRulePortPairsDataType()); - globalDataTypes.put(ToscaDataType.CONTRAIL_NETWORK_RULE.getDisplayName(), createRuleDataType()); - globalDataTypes.put(ToscaDataType.CONTRAIL_NETWORK_RULE_VIRTUAL_NETWORK.getDisplayName(), - createRuleVirtualNetworkDataType()); - globalDataTypes.put(ToscaDataType.CONTRAIL_NETWORK_RULE_LIST.getDisplayName(), - createPolicyRulesListDataType()); - return globalDataTypes; - } - - private static DataType createRuleDataType() { - DataType dataType = new DataType(); - dataType.setDerived_from(ToscaDataType.ROOT.getDisplayName()); - dataType.setDescription("policy rule"); - Map properties = new HashMap<>(); - properties.put("direction", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), "Direction", false, null, - null, null, null)); - properties.put("protocol", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), "Protocol", false, null, - null, null, null)); - properties.put("src_ports", DataModelUtil - .createPropertyDefinition(PropertyType.LIST.getDisplayName(), "Source ports", false, null, - null, DataModelUtil - .createEntrySchema(ToscaDataType.CONTRAIL_NETWORK_RULE_PORT_PAIRS.getDisplayName(), - null, null), null)); - properties.put("dst_ports", DataModelUtil - .createPropertyDefinition(PropertyType.LIST.getDisplayName(), "Destination ports", false, - null, null, DataModelUtil - .createEntrySchema(ToscaDataType.CONTRAIL_NETWORK_RULE_PORT_PAIRS.getDisplayName(), - null, null), null)); - properties.put("dst_addresses", DataModelUtil - .createPropertyDefinition(PropertyType.LIST.getDisplayName(), "Destination addresses", - false, null, null, DataModelUtil.createEntrySchema( - ToscaDataType.CONTRAIL_NETWORK_RULE_VIRTUAL_NETWORK.getDisplayName(), null, null), - null)); - properties.put("apply_service", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), "Service to apply", false, - null, null, null, null)); - properties.put("src_addresses", DataModelUtil - .createPropertyDefinition(PropertyType.LIST.getDisplayName(), "Source addresses", false, - null, null, DataModelUtil.createEntrySchema( - ToscaDataType.CONTRAIL_NETWORK_RULE_VIRTUAL_NETWORK.getDisplayName(), null, null), - null)); - - dataType.setProperties(properties); - return dataType; - - } - - - private static DataType createRuleVirtualNetworkDataType() { - DataType dataType = new DataType(); - dataType.setDerived_from(ToscaDataType.ROOT.getDisplayName()); - dataType.setDescription("source and destination addresses"); - Map properties = new HashMap<>(); - - properties.put("virtual_network", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), "Virtual network", false, - null, null, null, null)); - - dataType.setProperties(properties); - return dataType; - } - - private static DataType createPolicyRulesListDataType() { - DataType dataType = new DataType(); - dataType.setDerived_from(ToscaDataType.ROOT.getDisplayName()); - dataType.setDescription("list of policy rules"); - Map properties = new HashMap<>(); - - properties.put("policy_rule", DataModelUtil - .createPropertyDefinition(PropertyType.LIST.getDisplayName(), "Contrail network rule", - false, null, null, DataModelUtil - .createEntrySchema(ToscaDataType.CONTRAIL_NETWORK_RULE.getDisplayName(), null, - null), null)); - - dataType.setProperties(properties); - return dataType; - } - - - private static DataType createRulePortPairsDataType() { - DataType dataType = new DataType(); - dataType.setDerived_from(ToscaDataType.ROOT.getDisplayName()); - dataType.setDescription("source and destination port pairs"); - Map properties = new HashMap<>(); - - properties.put("start_port", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), "Start port", false, null, - null, null, null)); - properties.put("end_port", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), "End port", false, null, - null, null, null)); - - dataType.setProperties(properties); - return dataType; - } - - private static Map createGlobalNodeTypes() { - Map globalNodeTypes = new HashMap<>(); - globalNodeTypes.put(ToscaNodeType.CONTRAIL_NETWORK_RULE.getDisplayName(), - createContrailNetworkRuleNodeType()); - return globalNodeTypes; - } - - private static NodeType createContrailNetworkRuleNodeType() { - NodeType contrailNetworkRuleNodeType = new NodeType(); - contrailNetworkRuleNodeType.setDerived_from(ToscaNodeType.ROOT.getDisplayName()); - contrailNetworkRuleNodeType.setProperties(createContrailNetworkRuleProperties()); - contrailNetworkRuleNodeType.setAttributes(createContrailNetworkRuleAttributes()); - contrailNetworkRuleNodeType.setRequirements(createContrailNetworkRuleRequirements()); - return contrailNetworkRuleNodeType; - } - - - private static Map createContrailNetworkRuleProperties() { - Map contrailNetworkRulePropertyDefMap = new HashMap<>(); - contrailNetworkRulePropertyDefMap.put(Constants.NAME_PROPERTY_NAME, DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), - "A symbolic name for this contrail network rule", false, null, null, null, null)); - contrailNetworkRulePropertyDefMap.put("entries", DataModelUtil - .createPropertyDefinition(ToscaDataType.CONTRAIL_NETWORK_RULE_LIST.getDisplayName(), - "A symbolic name for this contrail network rule", false, null, null, null, null)); - - return contrailNetworkRulePropertyDefMap; - } - - - private static Map createContrailNetworkRuleAttributes() { - Map contrailNetworkRuleAttributesDefMap = new HashMap<>(); - contrailNetworkRuleAttributesDefMap.put("fq_name", DataModelUtil - .createAttributeDefinition(PropertyType.STRING.getDisplayName(), "fq_name", null, null, - null)); - contrailNetworkRuleAttributesDefMap.put("tenant_id", DataModelUtil - .createAttributeDefinition(PropertyType.STRING.getDisplayName(), "tenant_id", null, null, - null)); - contrailNetworkRuleAttributesDefMap.put("rules", DataModelUtil - .createAttributeDefinition(PropertyType.LIST.getDisplayName(), "List of rules", null, - DataModelUtil.createEntrySchema(PropertyType.STRING.getDisplayName(), null, null), - null)); - contrailNetworkRuleAttributesDefMap.put("show", DataModelUtil - .createAttributeDefinition(PropertyType.STRING.getDisplayName(), "All attributes.", null, - null, null)); - - return contrailNetworkRuleAttributesDefMap; - } - - private static List> createContrailNetworkRuleRequirements() { - final List> requirements = new ArrayList<>(); - final Map - contrailNetworkRuleRequirementsDefMap = new HashMap<>(); - RequirementDefinition req = new RequirementDefinition(); - req.setCapability(ToscaCapabilityType.ATTACHMENT.getDisplayName()); - req.setOccurrences(new Object[]{0, ToscaConstants.UNBOUNDED}); - req.setNode(ToscaNodeType.NETWORK.getDisplayName()); - req.setRelationship(ToscaRelationshipType.ATTACHES_TO.getDisplayName()); - contrailNetworkRuleRequirementsDefMap.put("network", req); - requirements.add(contrailNetworkRuleRequirementsDefMap); - - return requirements; - } -} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/ContrailPortGlobalType.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/ContrailPortGlobalType.java deleted file mode 100644 index 1590372813..0000000000 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/ContrailPortGlobalType.java +++ /dev/null @@ -1,107 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.translator.services.heattotosca.globaltypes; - -import org.openecomp.sdc.tosca.datatypes.ToscaDataType; -import org.openecomp.sdc.tosca.datatypes.ToscaNodeType; -import org.openecomp.sdc.tosca.datatypes.model.AttributeDefinition; -import org.openecomp.sdc.tosca.datatypes.model.NodeType; -import org.openecomp.sdc.tosca.datatypes.model.PropertyDefinition; -import org.openecomp.sdc.tosca.datatypes.model.PropertyType; -import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; -import org.openecomp.sdc.tosca.services.DataModelUtil; -import org.openecomp.sdc.tosca.services.ToscaConstants; -import org.openecomp.sdc.translator.services.heattotosca.Constants; - -import java.util.HashMap; -import java.util.Map; - -public class ContrailPortGlobalType { - /** - * Create service template service template. - * - * @return the service template - */ - public static ServiceTemplate createServiceTemplate() { - ServiceTemplate serviceTemplate = new ServiceTemplate(); - serviceTemplate.setTosca_definitions_version(ToscaConstants.TOSCA_DEFINITIONS_VERSION); - serviceTemplate.setMetadata( - DataModelUtil.createMetadata(Constants.CONTRAIL_PORT_TEMPLATE_NAME, "1.0.0", null)); - serviceTemplate.setImports(GlobalTypesUtil.createCommonImportList()); - serviceTemplate.setDescription("Contrail Port TOSCA Global Types"); - serviceTemplate.setNode_types(createGlobalNodeTypes()); - return serviceTemplate; - } - - private static Map createGlobalNodeTypes() { - Map globalNodeTypes = new HashMap<>(); - globalNodeTypes.put(ToscaNodeType.CONTRAIL_PORT.getDisplayName(), createContrailPortNodeType()); - return globalNodeTypes; - } - - private static NodeType createContrailPortNodeType() { - NodeType nodeType = new NodeType(); - nodeType.setDerived_from(ToscaNodeType.NETWORK_PORT.getDisplayName()); - nodeType.setProperties(createContrailPortProperties()); - nodeType.setAttributes(createContrailPortAttributes()); - return nodeType; - } - - private static Map createContrailPortProperties() { - Map propertyDefMap = new HashMap<>(); - propertyDefMap.put("interface_type", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), "Interface type", true, - DataModelUtil.createValidValuesConstraintsList("management", "left", "right", "other"), - null, null, null)); - propertyDefMap.put("shared_ip", DataModelUtil - .createPropertyDefinition(PropertyType.BOOLEAN.getDisplayName(), "Shared ip enabled", false, - null, null, null, false)); - propertyDefMap.put("static_route", DataModelUtil - .createPropertyDefinition(PropertyType.BOOLEAN.getDisplayName(), "Static route enabled", - false, null, null, null, false)); - propertyDefMap.put("virtual_network", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), - "Virtual Network for this interface", true, null, null, null, null)); - propertyDefMap.put("static_routes", DataModelUtil - .createPropertyDefinition(PropertyType.LIST.getDisplayName(), - "An ordered list of static routes to be added to this interface", false, null, null, - DataModelUtil - .createEntrySchema(ToscaDataType.CONTRAIL_STATIC_ROUTE.getDisplayName(), null, - null), null)); - propertyDefMap.put("allowed_address_pairs", DataModelUtil - .createPropertyDefinition(PropertyType.LIST.getDisplayName(), - "List of allowed address pair for this interface", false, null, null, DataModelUtil - .createEntrySchema(ToscaDataType.CONTRAIL_ADDRESS_PAIR.getDisplayName(), null, - null), null)); - propertyDefMap.put("ip_address", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), "IP for this interface", - false, null, null, null, null)); - return propertyDefMap; - } - - private static Map createContrailPortAttributes() { - Map attributesDefMap = new HashMap<>(); - attributesDefMap.put("fq_name", DataModelUtil - .createAttributeDefinition(PropertyType.STRING.getDisplayName(), "fq_name", null, null, - null)); - return attributesDefMap; - } -} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/ContrailV2NetworkRuleGlobalType.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/ContrailV2NetworkRuleGlobalType.java deleted file mode 100644 index 4141aa7f0a..0000000000 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/ContrailV2NetworkRuleGlobalType.java +++ /dev/null @@ -1,274 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.translator.services.heattotosca.globaltypes; - -import org.openecomp.sdc.tosca.datatypes.ToscaCapabilityType; -import org.openecomp.sdc.tosca.datatypes.ToscaDataType; -import org.openecomp.sdc.tosca.datatypes.ToscaNodeType; -import org.openecomp.sdc.tosca.datatypes.ToscaRelationshipType; -import org.openecomp.sdc.tosca.datatypes.model.AttributeDefinition; -import org.openecomp.sdc.tosca.datatypes.model.DataType; -import org.openecomp.sdc.tosca.datatypes.model.NodeType; -import org.openecomp.sdc.tosca.datatypes.model.PropertyDefinition; -import org.openecomp.sdc.tosca.datatypes.model.PropertyType; -import org.openecomp.sdc.tosca.datatypes.model.RequirementDefinition; -import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; -import org.openecomp.sdc.tosca.services.DataModelUtil; -import org.openecomp.sdc.tosca.services.ToscaConstants; -import org.openecomp.sdc.translator.services.heattotosca.Constants; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class ContrailV2NetworkRuleGlobalType { - /** - * Create service template service template. - * - * @return the service template - */ - public static ServiceTemplate createServiceTemplate() { - ServiceTemplate contrailNetworkRuleServiceTemplate = new ServiceTemplate(); - contrailNetworkRuleServiceTemplate - .setTosca_definitions_version(ToscaConstants.TOSCA_DEFINITIONS_VERSION); - contrailNetworkRuleServiceTemplate.setMetadata( - DataModelUtil.createMetadata(Constants - .CONTRAILV2_NETWORK_RULE_TEMPLATE_NAME, "1.0.0", null)); - contrailNetworkRuleServiceTemplate.setImports(GlobalTypesUtil.createCommonImportList()); - contrailNetworkRuleServiceTemplate.setDescription("Contrail V2 Network Rule Global Types"); - contrailNetworkRuleServiceTemplate.setData_types(createGlobalDataTypes()); - contrailNetworkRuleServiceTemplate.setNode_types(createGlobalNodeTypes()); - return contrailNetworkRuleServiceTemplate; - } - - - private static Map createGlobalDataTypes() { - Map globalDataTypes = new HashMap<>(); - globalDataTypes.put(ToscaDataType.CONTRAILV2_NETWORK_RULE_SRC_PORT_PAIRS.getDisplayName(), - createRuleSrcPortPairsDataType()); - globalDataTypes.put(ToscaDataType.CONTRAILV2_NETWORK_RULE_DST_PORT_PAIRS.getDisplayName(), - createRuleDstPortPairsDataType()); - globalDataTypes - .put(ToscaDataType.CONTRAILV2_NETWORK_RULE.getDisplayName(), createRuleDataType()); - globalDataTypes.put(ToscaDataType.CONTRAILV2_NETWORK_RULE_DST_VIRTUAL_NETWORK.getDisplayName(), - createRuleDstVirtualNetworkDataType()); - globalDataTypes.put(ToscaDataType.CONTRAILV2_NETWORK_RULE_SRC_VIRTUAL_NETWORK.getDisplayName(), - createRuleSrcVirtualNetworkDataType()); - globalDataTypes.put(ToscaDataType.CONTRAILV2_NETWORK_RULE_LIST.getDisplayName(), - createPolicyRulesListDataType()); - globalDataTypes.put(ToscaDataType.CONTRAILV2_NETWORK_RULE_ACTION_LIST.getDisplayName(), - createRuleActionListDataType()); - return globalDataTypes; - } - - private static DataType createRuleDataType() { - DataType dataType = new DataType(); - dataType.setDerived_from(ToscaDataType.ROOT.getDisplayName()); - dataType.setDescription("policy rule"); - Map properties = new HashMap<>(); - properties.put("network_policy_entries_policy_rule_direction", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), "Direction", false, null, - null, null, null)); - properties.put("network_policy_entries_policy_rule_protocol", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), "Protocol", false, null, - null, null, null)); - properties.put("network_policy_entries_policy_rule_src_ports", DataModelUtil - .createPropertyDefinition(PropertyType.LIST.getDisplayName(), "Source ports", false, null, - null, DataModelUtil.createEntrySchema( - ToscaDataType.CONTRAILV2_NETWORK_RULE_SRC_PORT_PAIRS.getDisplayName(), null, null), - null)); - properties.put("network_policy_entries_policy_rule_dst_ports", DataModelUtil - .createPropertyDefinition(PropertyType.LIST.getDisplayName(), "Destination ports", false, - null, null, DataModelUtil.createEntrySchema( - ToscaDataType.CONTRAILV2_NETWORK_RULE_DST_PORT_PAIRS.getDisplayName(), null, null), - null)); - properties.put("network_policy_entries_policy_rule_dst_addresses", DataModelUtil - .createPropertyDefinition(PropertyType.LIST.getDisplayName(), "Destination addresses", - false, null, null, DataModelUtil.createEntrySchema( - ToscaDataType.CONTRAILV2_NETWORK_RULE_DST_VIRTUAL_NETWORK.getDisplayName(), null, - null), null)); - properties.put("network_policy_entries_policy_rule_src_addresses", DataModelUtil - .createPropertyDefinition(PropertyType.LIST.getDisplayName(), "Source addresses", false, - null, null, DataModelUtil.createEntrySchema( - ToscaDataType.CONTRAILV2_NETWORK_RULE_SRC_VIRTUAL_NETWORK.getDisplayName(), null, - null), null)); - properties.put("network_policy_entries_policy_rule_action_list", DataModelUtil - .createPropertyDefinition( - ToscaDataType.CONTRAILV2_NETWORK_RULE_ACTION_LIST.getDisplayName(), "Action list", - false, null, null, null, null)); - - dataType.setProperties(properties); - return dataType; - - } - - - private static DataType createRuleDstVirtualNetworkDataType() { - DataType dataType = new DataType(); - dataType.setDerived_from(ToscaDataType.ROOT.getDisplayName()); - dataType.setDescription("destination addresses"); - Map properties = new HashMap<>(); - - properties.put("network_policy_entries_policy_rule_dst_addresses_virtual_network", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), - "Destination addresses Virtual network", false, null, null, null, null)); - - dataType.setProperties(properties); - return dataType; - } - - private static DataType createRuleSrcVirtualNetworkDataType() { - DataType dataType = new DataType(); - dataType.setDerived_from(ToscaDataType.ROOT.getDisplayName()); - dataType.setDescription("source addresses"); - Map properties = new HashMap<>(); - - properties.put("network_policy_entries_policy_rule_src_addresses_virtual_network", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), - "Source addresses Virtual network", false, null, null, null, null)); - - dataType.setProperties(properties); - return dataType; - } - - private static DataType createPolicyRulesListDataType() { - DataType dataType = new DataType(); - dataType.setDerived_from(ToscaDataType.ROOT.getDisplayName()); - dataType.setDescription("list of policy rules"); - Map properties = new HashMap<>(); - - properties.put("network_policy_entries_policy_rule", DataModelUtil - .createPropertyDefinition(PropertyType.LIST.getDisplayName(), "Contrail network rule", - false, null, null, DataModelUtil - .createEntrySchema(ToscaDataType.CONTRAILV2_NETWORK_RULE.getDisplayName(), null, - null), null)); - - dataType.setProperties(properties); - return dataType; - } - - private static DataType createRuleActionListDataType() { - DataType dataType = new DataType(); - dataType.setDerived_from(ToscaDataType.ROOT.getDisplayName()); - dataType.setDescription("Action List"); - Map properties = new HashMap<>(); - - properties.put("network_policy_entries_policy_rule_action_list_simple_action", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), "Simple Action", false, - null, null, null, null)); - properties.put("network_policy_entries_policy_rule_action_list_apply_service", DataModelUtil - .createPropertyDefinition(PropertyType.LIST.getDisplayName(), "Apply Service", false, null, - null, DataModelUtil.createEntrySchema(PropertyType.STRING.getDisplayName(), null, null), - null)); - - dataType.setProperties(properties); - return dataType; - } - - private static DataType createRuleDstPortPairsDataType() { - DataType dataType = new DataType(); - dataType.setDerived_from(ToscaDataType.ROOT.getDisplayName()); - dataType.setDescription("destination port pairs"); - Map properties = new HashMap<>(); - - properties.put("network_policy_entries_policy_rule_dst_ports_start_port", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), "Start port", false, null, - null, null, null)); - properties.put("network_policy_entries_policy_rule_dst_ports_end_port", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), "End port", false, null, - null, null, null)); - - dataType.setProperties(properties); - return dataType; - } - - private static DataType createRuleSrcPortPairsDataType() { - DataType dataType = new DataType(); - dataType.setDerived_from(ToscaDataType.ROOT.getDisplayName()); - dataType.setDescription("source port pairs"); - Map properties = new HashMap<>(); - - properties.put("network_policy_entries_policy_rule_src_ports_start_port", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), "Start port", false, null, - null, null, null)); - properties.put("network_policy_entries_policy_rule_src_ports_end_port", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), "End port", false, null, - null, null, null)); - - dataType.setProperties(properties); - return dataType; - } - - private static Map createGlobalNodeTypes() { - Map globalNodeTypes = new HashMap<>(); - globalNodeTypes.put(ToscaNodeType.CONTRAILV2_NETWORK_RULE.getDisplayName(), - createContrailV2NetworkRuleNodeType()); - return globalNodeTypes; - } - - private static NodeType createContrailV2NetworkRuleNodeType() { - NodeType contrailNetworkRuleNodeType = new NodeType(); - contrailNetworkRuleNodeType.setDerived_from(ToscaNodeType.ROOT.getDisplayName()); - contrailNetworkRuleNodeType.setProperties(createContrailNetworkRuleProperties()); - contrailNetworkRuleNodeType.setAttributes(createContrailNetworkRuleAttributes()); - contrailNetworkRuleNodeType.setRequirements(createContrailNetworkRuleRequirements()); - return contrailNetworkRuleNodeType; - } - - - private static Map createContrailNetworkRuleProperties() { - Map contrailNetworkRulePropertyDefMap = new HashMap<>(); - contrailNetworkRulePropertyDefMap.put(Constants.NAME_PROPERTY_NAME, DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), - "A symbolic name for this contrail v2 network rule", false, null, null, null, null)); - contrailNetworkRulePropertyDefMap.put("network_policy_entries", DataModelUtil - .createPropertyDefinition(ToscaDataType.CONTRAILV2_NETWORK_RULE_LIST.getDisplayName(), - "A symbolic name for this contrail v2 network rule", false, null, null, null, null)); - - return contrailNetworkRulePropertyDefMap; - } - - - private static Map createContrailNetworkRuleAttributes() { - Map contrailNetworkRuleAttributesDefMap = new HashMap<>(); - contrailNetworkRuleAttributesDefMap.put("fq_name", DataModelUtil - .createAttributeDefinition(PropertyType.STRING.getDisplayName(), "fq_name", null, null, - null)); - - return contrailNetworkRuleAttributesDefMap; - } - - private static List> createContrailNetworkRuleRequirements() { - final List> requirements = new ArrayList<>(); - final Map - contrailNetworkRuleRequirementsDefMap = new HashMap<>(); - RequirementDefinition req = new RequirementDefinition(); - req.setCapability(ToscaCapabilityType.ATTACHMENT.getDisplayName()); - req.setOccurrences(new Object[]{0, ToscaConstants.UNBOUNDED}); - req.setNode(ToscaNodeType.NETWORK.getDisplayName()); - req.setRelationship(ToscaRelationshipType.ATTACHES_TO.getDisplayName()); - contrailNetworkRuleRequirementsDefMap.put("network", req); - requirements.add(contrailNetworkRuleRequirementsDefMap); - - return requirements; - } -} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/ContrailV2VirtualMachineInterfaceGlobalType.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/ContrailV2VirtualMachineInterfaceGlobalType.java deleted file mode 100644 index 75501cb8d4..0000000000 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/ContrailV2VirtualMachineInterfaceGlobalType.java +++ /dev/null @@ -1,136 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.translator.services.heattotosca.globaltypes; - -import org.openecomp.sdc.tosca.datatypes.ToscaDataType; -import org.openecomp.sdc.tosca.datatypes.ToscaNodeType; -import org.openecomp.sdc.tosca.datatypes.model.AttributeDefinition; -import org.openecomp.sdc.tosca.datatypes.model.DataType; -import org.openecomp.sdc.tosca.datatypes.model.NodeType; -import org.openecomp.sdc.tosca.datatypes.model.PropertyDefinition; -import org.openecomp.sdc.tosca.datatypes.model.PropertyType; -import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; -import org.openecomp.sdc.tosca.services.DataModelUtil; -import org.openecomp.sdc.tosca.services.ToscaConstants; -import org.openecomp.sdc.translator.services.heattotosca.Constants; - -import java.util.HashMap; -import java.util.Map; - -class ContrailV2VirtualMachineInterfaceGlobalType { - private ContrailV2VirtualMachineInterfaceGlobalType() { - } - - public static ServiceTemplate createServiceTemplate() { - ServiceTemplate contrailVirtualMachineInterface = new ServiceTemplate(); - contrailVirtualMachineInterface - .setTosca_definitions_version(ToscaConstants.TOSCA_DEFINITIONS_VERSION); - contrailVirtualMachineInterface.setMetadata(DataModelUtil - .createMetadata(Constants.CONTRAILV2_VIRTUAL_MACHINE_INTERFACE_TEMPLATE_NAME, "1.0.0", - null)); - contrailVirtualMachineInterface.setImports(GlobalTypesUtil.createCommonImportList()); - contrailVirtualMachineInterface - .setDescription("Contrail Virtual Machine Interface TOSCA Global Types"); - contrailVirtualMachineInterface.setNode_types(createGlobalNodeTypes()); - contrailVirtualMachineInterface.setData_types(createGlobalDataTypes()); - return contrailVirtualMachineInterface; - } - - private static Map createGlobalDataTypes() { - Map globalDataTypes = new HashMap<>(); - globalDataTypes - .put(ToscaDataType.CONTRAILV2_VIRTUAL_MACHINE_INTERFACE_PROPERTIES.getDisplayName(), - createVmiPropertiesDataType()); - return globalDataTypes; - } - - private static DataType createVmiPropertiesDataType() { - DataType dataType = new DataType(); - dataType.setDerived_from(ToscaDataType.ROOT.getDisplayName()); - dataType.setDescription("Virtual Machine Interface Properties."); - Map properties = new HashMap<>(); - - properties.put("virtual_machine_interface_properties_service_interface_type", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), "Service Interface Type.", - false, null, null, null, null)); - dataType.setProperties(properties); - return dataType; - } - - private static Map createGlobalNodeTypes() { - Map globalNodeTypes = new HashMap<>(); - globalNodeTypes.put(ToscaNodeType.CONTRAILV2_VIRTUAL_MACHINE_INTERFACE.getDisplayName(), - createVmiNodeType()); - return globalNodeTypes; - } - - private static NodeType createVmiNodeType() { - NodeType nodeType = new NodeType(); - nodeType.setDerived_from(ToscaNodeType.NETWORK_PORT.getDisplayName()); - nodeType.setProperties(createVmiProperties()); - nodeType.setAttributes(createVmiAttributes()); - return nodeType; - } - - private static Map createVmiAttributes() { - Map vmiAttributesDefMap = new HashMap<>(); - vmiAttributesDefMap.put("fq_name", DataModelUtil - .createAttributeDefinition(PropertyType.STRING.getDisplayName(), - "The FQ name of the Virtual Network.", null, null, null)); - vmiAttributesDefMap.put("show", DataModelUtil - .createAttributeDefinition(PropertyType.STRING.getDisplayName(), "All attributes.", null, - null, null)); - return vmiAttributesDefMap; - } - - private static Map createVmiProperties() { - Map virtualMachineInterfacePropertyDefMap = new HashMap<>(); - virtualMachineInterfacePropertyDefMap.put(Constants.NAME_PROPERTY_NAME, DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), - "Virtual Machine Interface name", false, null, null, null, null)); - virtualMachineInterfacePropertyDefMap.put("virtual_machine_intefrace_mac_addresses", - DataModelUtil - .createPropertyDefinition(PropertyType.LIST.getDisplayName(), "List of mac addresses.", - false, null, null, - DataModelUtil.createEntrySchema(PropertyType.STRING.getDisplayName(), null, null), - null)); - virtualMachineInterfacePropertyDefMap.put("virtual_network_refs", DataModelUtil - .createPropertyDefinition(PropertyType.LIST.getDisplayName(), "List of virtual networks.", - false, null, null, - DataModelUtil.createEntrySchema(PropertyType.STRING.getDisplayName(), null, null), - null)); - virtualMachineInterfacePropertyDefMap.put("port_tuple_refs", DataModelUtil - .createPropertyDefinition(PropertyType.LIST.getDisplayName(), "List of port tuples.", false, - null, null, - DataModelUtil.createEntrySchema(PropertyType.STRING.getDisplayName(), null, null), - null)); - virtualMachineInterfacePropertyDefMap.put("security_group_refs", DataModelUtil - .createPropertyDefinition(PropertyType.LIST.getDisplayName(), "List of security groups.", - false, null, null, - DataModelUtil.createEntrySchema(PropertyType.STRING.getDisplayName(), null, null), - null)); - virtualMachineInterfacePropertyDefMap.put("virtual_machine_interface_properties", DataModelUtil - .createPropertyDefinition( - ToscaDataType.CONTRAILV2_VIRTUAL_MACHINE_INTERFACE_PROPERTIES.getDisplayName(), - "virtual machine interface properties.", false, null, null, null, null)); - return virtualMachineInterfacePropertyDefMap; - } -} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/ContrailV2VirtualNetworkGlobalType.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/ContrailV2VirtualNetworkGlobalType.java deleted file mode 100644 index 728b9f6149..0000000000 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/ContrailV2VirtualNetworkGlobalType.java +++ /dev/null @@ -1,239 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.translator.services.heattotosca.globaltypes; - -import org.openecomp.sdc.tosca.datatypes.ToscaDataType; -import org.openecomp.sdc.tosca.datatypes.ToscaNodeType; -import org.openecomp.sdc.tosca.datatypes.model.AttributeDefinition; -import org.openecomp.sdc.tosca.datatypes.model.CapabilityDefinition; -import org.openecomp.sdc.tosca.datatypes.model.DataType; -import org.openecomp.sdc.tosca.datatypes.model.NodeType; -import org.openecomp.sdc.tosca.datatypes.model.PropertyDefinition; -import org.openecomp.sdc.tosca.datatypes.model.PropertyType; -import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; -import org.openecomp.sdc.tosca.services.DataModelUtil; -import org.openecomp.sdc.tosca.services.ToscaConstants; -import org.openecomp.sdc.translator.services.heattotosca.Constants; - -import java.util.HashMap; -import java.util.Map; - -public class ContrailV2VirtualNetworkGlobalType { - - /** - * Create service template service template. - * - * @return the service template - */ - public static ServiceTemplate createServiceTemplate() { - ServiceTemplate contrailVirtualNetworkServiceTemplate = new ServiceTemplate(); - contrailVirtualNetworkServiceTemplate - .setTosca_definitions_version(ToscaConstants.TOSCA_DEFINITIONS_VERSION); - contrailVirtualNetworkServiceTemplate.setMetadata(DataModelUtil - .createMetadata(Constants.CONTRAILV2_VIRTUAL_NETWORK_TEMPLATE_NAME, "1.0.0", null)); - contrailVirtualNetworkServiceTemplate - .setDescription("Contrail V2 Virtual Network Global Types"); - contrailVirtualNetworkServiceTemplate.setImports(GlobalTypesUtil.createCommonImportList()); - contrailVirtualNetworkServiceTemplate.setNode_types(createGlobalNodeTypes()); - contrailVirtualNetworkServiceTemplate.setData_types(createGlobalDataTypes()); - return contrailVirtualNetworkServiceTemplate; - } - - private static Map createGlobalNodeTypes() { - Map globalNodeTypes = new HashMap<>(); - globalNodeTypes.put(ToscaNodeType.CONTRAILV2_VIRTUAL_NETWORK.getDisplayName(), - createContrailVirtualNetworkNodeType()); - return globalNodeTypes; - } - - private static NodeType createContrailVirtualNetworkNodeType() { - NodeType contrailV2VirtualNetworkNodeType = new NodeType(); - contrailV2VirtualNetworkNodeType.setDerived_from(ToscaNodeType.NETWORK.getDisplayName()); - contrailV2VirtualNetworkNodeType.setProperties(createContrailVirtualNetworkProperties()); - contrailV2VirtualNetworkNodeType.setAttributes(createContrailVirtualNetworkAttributes()); - contrailV2VirtualNetworkNodeType.setCapabilities(createContrailVirtualNetworkCapabilities()); - return contrailV2VirtualNetworkNodeType; - } - - private static Map createContrailVirtualNetworkCapabilities() { - Map capabilities = new HashMap<>(); - capabilities.put("attachment", GlobalTypesUtil.createAttachmentCapability()); - return capabilities; - } - - private static Map createContrailVirtualNetworkProperties() { - Map contrailVirtualNetworkPropertyDefMap = new HashMap<>(); - //contrailVirtualNetworkPropertyDefMap.put("name", DataModelUtil. - // createPropertyDefinition(PropertyType.STRING.getDisplayName() - // , "Name", false, null, null, null, null)); - contrailVirtualNetworkPropertyDefMap.put("network_ipam_refs", DataModelUtil - .createPropertyDefinition(PropertyType.LIST.getDisplayName(), "IPAM references", false, - null, null, - DataModelUtil.createEntrySchema(PropertyType.STRING.getDisplayName(), null, null), - null)); - contrailVirtualNetworkPropertyDefMap.put("network_ipam_refs_data", DataModelUtil - .createPropertyDefinition(PropertyType.LIST.getDisplayName(), "IPAM references Data", false, - null, null, DataModelUtil.createEntrySchema( - ToscaDataType.CONTRAILV2_VIRTUAL_NETWORK_IPAM_REF_DATA.getDisplayName(), null, - null), null)); - contrailVirtualNetworkPropertyDefMap.put("network_policy_refs", DataModelUtil - .createPropertyDefinition(PropertyType.LIST.getDisplayName(), "Policy references", false, - null, null, - DataModelUtil.createEntrySchema(PropertyType.STRING.getDisplayName(), null, null), - null)); - contrailVirtualNetworkPropertyDefMap.put("network_policy_refs_data", DataModelUtil - .createPropertyDefinition(PropertyType.LIST.getDisplayName(), "Policy references data", - false, null, null, DataModelUtil.createEntrySchema( - ToscaDataType.CONTRAILV2_VIRTUAL_NETWORK_POLICY_REF_DATA.getDisplayName(), null, - null), null)); - contrailVirtualNetworkPropertyDefMap.put("subnets", DataModelUtil - .createPropertyDefinition(PropertyType.MAP.getDisplayName(), "Network related subnets", - false, null, null, DataModelUtil - .createEntrySchema(ToscaDataType.NEUTRON_SUBNET.getDisplayName(), null, null), - null)); - return contrailVirtualNetworkPropertyDefMap; - } - - private static Map createGlobalDataTypes() { - Map globalDataTypes = new HashMap<>(); - globalDataTypes.put(ToscaDataType.CONTRAILV2_VIRTUAL_NETWORK_IPAM_REF_DATA.getDisplayName(), - createVirtualNetworkIpamRefDataDataType()); - globalDataTypes.put( - ToscaDataType.CONTRAILV2_VIRTUAL_NETWORK_IPAM_REF_DATA_IPAM_SUBNET_LIST.getDisplayName(), - createVirtualNetworkIpamRefDataIpanSubnetListDataType()); - globalDataTypes - .put(ToscaDataType.CONTRAILV2_VIRTUAL_NETWORK_IPAM_REF_DATA_IPAM_SUBNET.getDisplayName(), - createVirtualNetworkIpamRefDataIpanSubnetDataType()); - globalDataTypes.put(ToscaDataType.CONTRAILV2_VIRTUAL_NETWORK_POLICY_REF_DATA.getDisplayName(), - createVirtualNetworkPolicyRefDataDataType()); - globalDataTypes - .put(ToscaDataType.CONTRAILV2_VIRTUAL_NETWORK_POLICY_REF_DATA_SEQUENCE.getDisplayName(), - createVirtualNetworkPolicyRefSequenceDataDataType()); - return globalDataTypes; - } - - private static DataType createVirtualNetworkIpamRefDataDataType() { - DataType dataType = new DataType(); - dataType.setDerived_from(ToscaDataType.ROOT.getDisplayName()); - dataType.setDescription("Network Ipam Ref Data"); - Map properties = new HashMap<>(); - - properties.put("network_ipam_refs_data_ipam_subnets", DataModelUtil - .createPropertyDefinition(PropertyType.LIST.getDisplayName(), - "Network ipam refs data ipam subnets", false, null, null, DataModelUtil - .createEntrySchema( - ToscaDataType.CONTRAILV2_VIRTUAL_NETWORK_IPAM_REF_DATA_IPAM_SUBNET_LIST - .getDisplayName(), null, null), null)); - dataType.setProperties(properties); - return dataType; - } - - private static DataType createVirtualNetworkIpamRefDataIpanSubnetListDataType() { - DataType dataType = new DataType(); - dataType.setDerived_from(ToscaDataType.ROOT.getDisplayName()); - dataType.setDescription("Network Ipam Ref Data Subnet List"); - Map properties = new HashMap<>(); - - properties.put("network_ipam_refs_data_ipam_subnets_subnet", DataModelUtil - .createPropertyDefinition( - ToscaDataType.CONTRAILV2_VIRTUAL_NETWORK_IPAM_REF_DATA_IPAM_SUBNET.getDisplayName(), - "Network ipam refs data ipam subnets", false, null, null, null, null)); - properties.put("network_ipam_refs_data_ipam_subnets_addr_from_start", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), - "Network ipam refs data ipam subnets addr from start", false, null, null, null, null)); - - dataType.setProperties(properties); - return dataType; - } - - private static DataType createVirtualNetworkIpamRefDataIpanSubnetDataType() { - DataType dataType = new DataType(); - dataType.setDerived_from(ToscaDataType.ROOT.getDisplayName()); - dataType.setDescription("Network Ipam Ref Data Subnet"); - Map properties = new HashMap<>(); - - properties.put("network_ipam_refs_data_ipam_subnets_subnet_ip_prefix", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), - "Network ipam refs data ipam subnets ip prefix", false, null, null, null, null)); - properties.put("network_ipam_refs_data_ipam_subnets_subnet_ip_prefix_len", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), - "Network ipam refs data ipam subnets ip prefix len", false, null, null, null, null)); - dataType.setProperties(properties); - return dataType; - } - - - private static DataType createVirtualNetworkPolicyRefDataDataType() { - DataType dataType = new DataType(); - dataType.setDerived_from(ToscaDataType.ROOT.getDisplayName()); - dataType.setDescription("network policy refs data"); - Map properties = new HashMap<>(); - - properties.put("network_policy_refs_data_sequence", DataModelUtil.createPropertyDefinition( - ToscaDataType.CONTRAILV2_VIRTUAL_NETWORK_POLICY_REF_DATA_SEQUENCE.getDisplayName(), - "Network Policy ref data sequence", false, null, null, null, null)); - - - dataType.setProperties(properties); - return dataType; - } - - - private static DataType createVirtualNetworkPolicyRefSequenceDataDataType() { - DataType dataType = new DataType(); - dataType.setDerived_from(ToscaDataType.ROOT.getDisplayName()); - dataType.setDescription("network policy refs data sequence"); - Map properties = new HashMap<>(); - - properties.put("network_policy_refs_data_sequence_major", DataModelUtil - .createPropertyDefinition(PropertyType.INTEGER.getDisplayName(), - "Network Policy ref data sequence Major", false, null, null, null, null)); - properties.put("network_policy_refs_data_sequence_minor", DataModelUtil - .createPropertyDefinition(PropertyType.INTEGER.getDisplayName(), - "Network Policy ref data sequence Minor", false, null, null, null, null)); - - dataType.setProperties(properties); - return dataType; - } - - private static Map createContrailVirtualNetworkAttributes() { - Map contrailVirtualNetworkAttributesDefMap = new HashMap<>(); - contrailVirtualNetworkAttributesDefMap.put("subnets_name", DataModelUtil - .createAttributeDefinition(PropertyType.LIST.getDisplayName(), - "Subnets name of this network", null, - DataModelUtil.createEntrySchema(PropertyType.STRING.getDisplayName(), null, null), - null)); - contrailVirtualNetworkAttributesDefMap.put("subnets", DataModelUtil - .createAttributeDefinition(PropertyType.MAP.getDisplayName(), "Network related subnets", - null, DataModelUtil - .createEntrySchema(ToscaDataType.NEUTRON_SUBNET.getDisplayName(), null, null), - null)); - contrailVirtualNetworkAttributesDefMap.put("subnets_show", DataModelUtil - .createAttributeDefinition(PropertyType.MAP.getDisplayName(), - "Detailed information about each subnet", null, - DataModelUtil.createEntrySchema(PropertyType.STRING.getDisplayName(), null, null), - null)); - contrailVirtualNetworkAttributesDefMap.put("fq_name", DataModelUtil - .createAttributeDefinition(PropertyType.STRING.getDisplayName(), "fq_name", null, null, - null)); - return contrailVirtualNetworkAttributesDefMap; - } -} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/ContrailVirtualNetworkGlobalType.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/ContrailVirtualNetworkGlobalType.java deleted file mode 100644 index 1014757a2c..0000000000 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/ContrailVirtualNetworkGlobalType.java +++ /dev/null @@ -1,134 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.translator.services.heattotosca.globaltypes; - -import org.openecomp.sdc.tosca.datatypes.ToscaDataType; -import org.openecomp.sdc.tosca.datatypes.ToscaNodeType; -import org.openecomp.sdc.tosca.datatypes.model.AttributeDefinition; -import org.openecomp.sdc.tosca.datatypes.model.CapabilityDefinition; -import org.openecomp.sdc.tosca.datatypes.model.NodeType; -import org.openecomp.sdc.tosca.datatypes.model.PropertyDefinition; -import org.openecomp.sdc.tosca.datatypes.model.PropertyType; -import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; -import org.openecomp.sdc.tosca.services.DataModelUtil; -import org.openecomp.sdc.tosca.services.ToscaConstants; -import org.openecomp.sdc.translator.services.heattotosca.Constants; - -import java.util.HashMap; -import java.util.Map; - -public class ContrailVirtualNetworkGlobalType { - - /** - * Create service template service template. - * - * @return the service template - */ - public static ServiceTemplate createServiceTemplate() { - ServiceTemplate contrailVirtualNetworkServiceTemplate = new ServiceTemplate(); - contrailVirtualNetworkServiceTemplate - .setTosca_definitions_version(ToscaConstants.TOSCA_DEFINITIONS_VERSION); - contrailVirtualNetworkServiceTemplate.setMetadata(DataModelUtil - .createMetadata(Constants.CONTRAIL_VIRTUAL_NETWORK_TEMPLATE_NAME, "1.0.0", null)); - contrailVirtualNetworkServiceTemplate.setDescription("Contrail Virtual Network Global Types"); - contrailVirtualNetworkServiceTemplate.setImports(GlobalTypesUtil.createCommonImportList()); - contrailVirtualNetworkServiceTemplate.setNode_types(createGlobalNodeTypes()); - return contrailVirtualNetworkServiceTemplate; - } - - private static Map createGlobalNodeTypes() { - Map globalNodeTypes = new HashMap<>(); - globalNodeTypes.put(ToscaNodeType.CONTRAIL_VIRTUAL_NETWORK.getDisplayName(), - createContrailVirtualNetworkNodeType()); - return globalNodeTypes; - } - - private static NodeType createContrailVirtualNetworkNodeType() { - NodeType contrailVirtualNetworkNodeType = new NodeType(); - contrailVirtualNetworkNodeType.setDerived_from(ToscaNodeType.NETWORK.getDisplayName()); - contrailVirtualNetworkNodeType.setProperties(createContrailVirtualNetworkProperties()); - contrailVirtualNetworkNodeType.setAttributes(createContrailVirtualNetworkAttributes()); - contrailVirtualNetworkNodeType.setCapabilities(createContrailVirtualNetworkCapabilities()); - return contrailVirtualNetworkNodeType; - } - - private static Map createContrailVirtualNetworkCapabilities() { - Map capabilities = new HashMap<>(); - capabilities.put("attachment", GlobalTypesUtil.createAttachmentCapability()); - return capabilities; - } - - private static Map createContrailVirtualNetworkProperties() { - Map contrailVirtualNetworkPropertyDefMap = new HashMap<>(); - contrailVirtualNetworkPropertyDefMap.put("shared", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), "Is virtual network shared", - false, null, null, null, null)); - contrailVirtualNetworkPropertyDefMap.put("external", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), - "Is virtual network external", false, null, null, null, null)); - contrailVirtualNetworkPropertyDefMap.put("allow_transit", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), - "Whether this network should be transitive.", false, null, null, null, null)); - contrailVirtualNetworkPropertyDefMap.put("route_targets", DataModelUtil - .createPropertyDefinition(PropertyType.LIST.getDisplayName(), - "route targets associated with the virtual network", false, null, null, - DataModelUtil.createEntrySchema(PropertyType.STRING.getDisplayName(), null, null), - null)); - contrailVirtualNetworkPropertyDefMap.put("forwarding_mode", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), - "forwarding mode of the virtual network", false, null, null, null, null)); - contrailVirtualNetworkPropertyDefMap.put("flood_unknown_unicast", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), - "flood L2 packets on network", false, null, null, null, null)); - contrailVirtualNetworkPropertyDefMap.put("subnets", DataModelUtil - .createPropertyDefinition(PropertyType.MAP.getDisplayName(), "Network related subnets", - false, null, null, DataModelUtil - .createEntrySchema(ToscaDataType.NEUTRON_SUBNET.getDisplayName(), null, null), - null)); - return contrailVirtualNetworkPropertyDefMap; - } - - private static Map createContrailVirtualNetworkAttributes() { - Map contrailVirtualNetworkAttributesDefMap = new HashMap<>(); - contrailVirtualNetworkAttributesDefMap.put("subnets_name", DataModelUtil - .createAttributeDefinition(PropertyType.LIST.getDisplayName(), - "Subnets name of this network", null, - DataModelUtil.createEntrySchema(PropertyType.STRING.getDisplayName(), null, null), - null)); - contrailVirtualNetworkAttributesDefMap.put("subnets", DataModelUtil - .createAttributeDefinition(PropertyType.MAP.getDisplayName(), "Network related subnets", - null, DataModelUtil - .createEntrySchema(ToscaDataType.NEUTRON_SUBNET.getDisplayName(), null, null), - null)); - contrailVirtualNetworkAttributesDefMap.put("subnets_show", DataModelUtil - .createAttributeDefinition(PropertyType.MAP.getDisplayName(), - "Detailed information about each subnet", null, - DataModelUtil.createEntrySchema(PropertyType.STRING.getDisplayName(), null, null), - null)); - contrailVirtualNetworkAttributesDefMap.put("fq_name", DataModelUtil - .createAttributeDefinition(PropertyType.STRING.getDisplayName(), "fq_name", null, null, - null)); - contrailVirtualNetworkAttributesDefMap.put("show", DataModelUtil - .createAttributeDefinition(PropertyType.STRING.getDisplayName(), "All attributes.", null, - null, null)); - return contrailVirtualNetworkAttributesDefMap; - } -} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/GlobalTypesGenerator.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/GlobalTypesGenerator.java index a4ec764e14..6dada6ab84 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/GlobalTypesGenerator.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/GlobalTypesGenerator.java @@ -22,13 +22,14 @@ package org.openecomp.sdc.translator.services.heattotosca.globaltypes; import org.openecomp.sdc.tosca.datatypes.model.Import; import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; -import org.openecomp.sdc.tosca.services.ToscaNativeTypesServiceTemplate; -import org.openecomp.sdc.tosca.services.ToscaUtil; -import org.openecomp.sdc.translator.services.heattotosca.Constants; +import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; +import java.util.ArrayList; import java.util.HashMap; +import java.util.List; import java.util.Map; + public class GlobalTypesGenerator { private GlobalTypesGenerator() { @@ -40,51 +41,7 @@ public class GlobalTypesGenerator { * @return the global types service template */ public static Map getGlobalTypesServiceTemplate() { - Map serviceTemplates = new HashMap<>(); - - ToscaUtil.addServiceTemplateToMapWithKeyFileName(serviceTemplates, - CommonGlobalTypes.createServiceTemplate()); - ToscaUtil.addServiceTemplateToMapWithKeyFileName(serviceTemplates, - NovaServerGlobalType.createServiceTemplate()); - ToscaUtil.addServiceTemplateToMapWithKeyFileName(serviceTemplates, - CinderVolumeGlobalType.createServiceTemplate()); - ToscaUtil.addServiceTemplateToMapWithKeyFileName(serviceTemplates, - ContrailVirtualNetworkGlobalType.createServiceTemplate()); - ToscaUtil.addServiceTemplateToMapWithKeyFileName(serviceTemplates, - ContrailV2VirtualNetworkGlobalType.createServiceTemplate()); - ToscaUtil.addServiceTemplateToMapWithKeyFileName(serviceTemplates, - ContrailV2VirtualMachineInterfaceGlobalType.createServiceTemplate()); - ToscaUtil.addServiceTemplateToMapWithKeyFileName(serviceTemplates, - NeutronNetGlobalType.createServiceTemplate()); - ToscaUtil.addServiceTemplateToMapWithKeyFileName(serviceTemplates, - NeutronPortGlobalType.createServiceTemplate()); - ToscaUtil.addServiceTemplateToMapWithKeyFileName(serviceTemplates, - ContrailNetworkRuleGlobalType.createServiceTemplate()); - ToscaUtil.addServiceTemplateToMapWithKeyFileName(serviceTemplates, - ContrailV2NetworkRuleGlobalType.createServiceTemplate()); - ToscaUtil.addServiceTemplateToMapWithKeyFileName(serviceTemplates, - NeutronSecurityRulesGlobalType.createServiceTemplate()); - ToscaUtil.addServiceTemplateToMapWithKeyFileName(serviceTemplates, - AbstractSubstituteGlobalType.createServiceTemplate()); - ToscaUtil.addServiceTemplateToMapWithKeyFileName(serviceTemplates, - ToscaNativeTypesServiceTemplate.createServiceTemplate()); - ToscaUtil.addServiceTemplateToMapWithKeyFileName(serviceTemplates, - ContrailComputeGlobalType.createServiceTemplate()); - ToscaUtil.addServiceTemplateToMapWithKeyFileName(serviceTemplates, - ContrailPortGlobalType.createServiceTemplate()); - ToscaUtil.addServiceTemplateToMapWithKeyFileName(serviceTemplates, - ContrailV2NetworkRuleGlobalType.createServiceTemplate()); - ToscaUtil.addServiceTemplateToMapWithKeyFileName(serviceTemplates, - ContrailV2VirtualNetworkGlobalType.createServiceTemplate()); - ToscaUtil.addServiceTemplateToMapWithKeyFileName(serviceTemplates, - ContrailAbstractSubstituteGlobalType.createServiceTemplate()); - return serviceTemplates; - } - - private static void addGlobalServiceTemplate(Map serviceTemplates, - ServiceTemplate commonServiceTemplate) { - serviceTemplates - .put(ToscaUtil.getServiceTemplateFileName(commonServiceTemplate), commonServiceTemplate); + return GlobalTypesServiceTemplates.getGlobalTypesServiceTemplates(); } /** @@ -92,37 +49,15 @@ public class GlobalTypesGenerator { * * @return the global types import list */ - public static Map getGlobalTypesImportList() { + public static List> getGlobalTypesImportList() { + List> globalImports = new ArrayList<>(); Map globalImportMap = new HashMap<>(); - globalImportMap.put(Constants.COMMON_GLOBAL_TEMPLATE_NAME, - GlobalTypesUtil.createServiceTemplateImport(Constants.COMMON_GLOBAL_TEMPLATE_NAME)); - globalImportMap.put(Constants.NOVA_SERVER_TEMPLATE_NAME, - GlobalTypesUtil.createServiceTemplateImport(Constants.NOVA_SERVER_TEMPLATE_NAME)); - globalImportMap.put(Constants.NEUTRON_PORT_TEMPLATE_NAME, - GlobalTypesUtil.createServiceTemplateImport(Constants.NEUTRON_PORT_TEMPLATE_NAME)); - globalImportMap.put(Constants.NEUTRON_SECURITY_RULES_TEMPLATE_NAME, GlobalTypesUtil - .createServiceTemplateImport(Constants.NEUTRON_SECURITY_RULES_TEMPLATE_NAME)); - globalImportMap.put(Constants.NEUTRON_NET_TEMPLATE_NAME, - GlobalTypesUtil.createServiceTemplateImport(Constants.NEUTRON_NET_TEMPLATE_NAME)); - globalImportMap.put(Constants.CINDER_VOLUME_TEMPLATE_NAME, - GlobalTypesUtil.createServiceTemplateImport(Constants.CINDER_VOLUME_TEMPLATE_NAME)); - globalImportMap.put(Constants.CONTRAIL_VIRTUAL_NETWORK_TEMPLATE_NAME, GlobalTypesUtil - .createServiceTemplateImport(Constants.CONTRAIL_VIRTUAL_NETWORK_TEMPLATE_NAME)); - globalImportMap.put(Constants.CONTRAIL_NETWORK_RULE_TEMPLATE_NAME, - GlobalTypesUtil.createServiceTemplateImport(Constants.CONTRAIL_NETWORK_RULE_TEMPLATE_NAME)); - globalImportMap.put(Constants.ABSTRACT_SUBSTITUTE_TEMPLATE_NAME, - GlobalTypesUtil.createServiceTemplateImport(Constants.ABSTRACT_SUBSTITUTE_TEMPLATE_NAME)); - globalImportMap.put(Constants.CONTRAILV2_VIRTUAL_MACHINE_INTERFACE_TEMPLATE_NAME, - GlobalTypesUtil.createServiceTemplateImport( - Constants.CONTRAILV2_VIRTUAL_MACHINE_INTERFACE_TEMPLATE_NAME)); - globalImportMap.put(Constants.CONTRAIL_COMPUTE_TEMPLATE_NAME, - GlobalTypesUtil.createServiceTemplateImport(Constants.CONTRAIL_COMPUTE_TEMPLATE_NAME)); - globalImportMap.put(Constants.CONTRAIL_PORT_TEMPLATE_NAME, - GlobalTypesUtil.createServiceTemplateImport(Constants.CONTRAIL_PORT_TEMPLATE_NAME)); - globalImportMap.put(Constants.CONTRAIL_ABSTRACT_SUBSTITUTE_TEMPLATE_NAME, GlobalTypesUtil - .createServiceTemplateImport(Constants.CONTRAIL_ABSTRACT_SUBSTITUTE_TEMPLATE_NAME)); - return globalImportMap; + Map globalTypesServiceTemplate = + GlobalTypesGenerator.getGlobalTypesServiceTemplate(); + globalImportMap.put("openecomp_heat_index", + HeatToToscaUtil.createServiceTemplateImport(globalTypesServiceTemplate.get + ("openecomp-heat/_index.yml"))); + globalImports.add(globalImportMap); + return globalImports; } - - } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/GlobalTypesServiceTemplates.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/GlobalTypesServiceTemplates.java new file mode 100644 index 0000000000..cbc56d7773 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/GlobalTypesServiceTemplates.java @@ -0,0 +1,61 @@ +package org.openecomp.sdc.translator.services.heattotosca.globaltypes; + +import org.openecomp.sdc.common.errors.CoreException; +import org.openecomp.sdc.common.errors.ErrorCategory; +import org.openecomp.sdc.common.errors.ErrorCode; +import org.openecomp.sdc.logging.types.LoggerErrorDescription; +import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; +import org.openecomp.sdc.tosca.services.ToscaUtil; +import org.openecomp.sdc.tosca.services.yamlutil.ToscaExtensionYamlUtil; +import org.openecomp.sdc.translator.utils.ResourceWalker; + +import java.util.HashMap; +import java.util.Map; + +/** + * @author Avrahamg + * @since April 03, 2017 + */ +public class GlobalTypesServiceTemplates { + private static Map globalTypesServiceTemplates; + + + public static Map getGlobalTypesServiceTemplates() { + if (globalTypesServiceTemplates == null) { + synchronized (GlobalTypesServiceTemplates.class) { + if (globalTypesServiceTemplates == null) { + init(); + } + } + } + return globalTypesServiceTemplates; + } + + private static void init() { + globalTypesServiceTemplates = new HashMap<>(); + Map globalTypes = null; + try { + globalTypes = ResourceWalker.readResourcesFromDirectory("globalTypes"); + } catch (CoreException coreException) { + throw coreException; + } catch (Exception exception) { + throw new CoreException((new ErrorCode.ErrorCodeBuilder()) + .withMessage(LoggerErrorDescription.FAILED_TO_GENERATE_GLOBAL_TYPES) + .withId("GlobalTypes Read Error").withCategory(ErrorCategory.APPLICATION).build(), + exception); + } + ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil(); + for (Map.Entry globalTypeContent : globalTypes.entrySet()) { + if (globalTypeContent.getKey().contains("openecomp-inventory")) { // this global types folder + // should not be + // processed to the CSAR + continue; + } + ToscaUtil.addServiceTemplateToMapWithKeyFileName(globalTypesServiceTemplates, + toscaExtensionYamlUtil.yamlToObject(globalTypeContent.getValue(), ServiceTemplate.class)); + } + } + + private GlobalTypesServiceTemplates() { + } +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/GlobalTypesUtil.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/GlobalTypesUtil.java deleted file mode 100644 index 9566dec581..0000000000 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/GlobalTypesUtil.java +++ /dev/null @@ -1,69 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.translator.services.heattotosca.globaltypes; - - -import org.openecomp.sdc.tosca.datatypes.ToscaCapabilityType; -import org.openecomp.sdc.tosca.datatypes.model.CapabilityDefinition; -import org.openecomp.sdc.tosca.datatypes.model.Import; -import org.openecomp.sdc.tosca.services.ToscaUtil; - -import java.util.HashMap; -import java.util.Map; - -public class GlobalTypesUtil { - - - /** - * Create common import list map. - * - * @return the map - */ - public static Map createCommonImportList() { - Map importsMap = new HashMap<>(); - importsMap.put("common_definitions", CommonGlobalTypes.createCommonServiceTemplateImport()); - return importsMap; - } - - /** - * Create attachment capability capability definition. - * - * @return the capability definition - */ - public static CapabilityDefinition createAttachmentCapability() { - CapabilityDefinition capability = new CapabilityDefinition(); - capability.setType(ToscaCapabilityType.ATTACHMENT.getDisplayName()); - - return capability; - } - - /** - * Create service template import import. - * - * @param serviceTemplateName the service template name - * @return the import - */ - public static Import createServiceTemplateImport(String serviceTemplateName) { - Import serviceTemplateImport = new Import(); - serviceTemplateImport.setFile(ToscaUtil.getServiceTemplateFileName(serviceTemplateName)); - return serviceTemplateImport; - } -} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/NeutronNetGlobalType.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/NeutronNetGlobalType.java deleted file mode 100644 index 2532f87cf5..0000000000 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/NeutronNetGlobalType.java +++ /dev/null @@ -1,143 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.translator.services.heattotosca.globaltypes; - -import org.openecomp.sdc.tosca.datatypes.ToscaDataType; -import org.openecomp.sdc.tosca.datatypes.ToscaNodeType; -import org.openecomp.sdc.tosca.datatypes.model.AttributeDefinition; -import org.openecomp.sdc.tosca.datatypes.model.CapabilityDefinition; -import org.openecomp.sdc.tosca.datatypes.model.NodeType; -import org.openecomp.sdc.tosca.datatypes.model.PropertyDefinition; -import org.openecomp.sdc.tosca.datatypes.model.PropertyType; -import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; -import org.openecomp.sdc.tosca.services.DataModelUtil; -import org.openecomp.sdc.tosca.services.ToscaConstants; -import org.openecomp.sdc.translator.services.heattotosca.Constants; - -import java.util.HashMap; -import java.util.Map; - -public class NeutronNetGlobalType { - /** - * Create service template service template. - * - * @return the service template - */ - public static ServiceTemplate createServiceTemplate() { - ServiceTemplate neutronNetServiceTemplate = new ServiceTemplate(); - neutronNetServiceTemplate - .setTosca_definitions_version(ToscaConstants.TOSCA_DEFINITIONS_VERSION); - neutronNetServiceTemplate.setMetadata( - DataModelUtil.createMetadata(Constants.NEUTRON_NET_TEMPLATE_NAME, "1.0.0", null)); - neutronNetServiceTemplate.setDescription("Neutron Network TOSCA Global Types"); - neutronNetServiceTemplate.setImports(GlobalTypesUtil.createCommonImportList()); - neutronNetServiceTemplate.setNode_types(createGlobalNodeTypes()); - return neutronNetServiceTemplate; - } - - - private static Map createGlobalNodeTypes() { - Map globalNodeTypes = new HashMap<>(); - globalNodeTypes.put(ToscaNodeType.NEUTRON_NET.getDisplayName(), createNeutronNetworkNodeType()); - return globalNodeTypes; - } - - private static NodeType createNeutronNetworkNodeType() { - NodeType neutronNetworkNode = new NodeType(); - neutronNetworkNode.setDerived_from(ToscaNodeType.NETWORK.getDisplayName()); - neutronNetworkNode.setProperties(createNeutronNetworkProperties()); - neutronNetworkNode.setAttributes(createNeutronNetworkAttributes()); - neutronNetworkNode.setCapabilities(createNeutronNetworkCapabilities()); - - return neutronNetworkNode; - } - - private static Map createNeutronNetworkCapabilities() { - Map capabilities = new HashMap<>(); - capabilities.put("attachment", GlobalTypesUtil.createAttachmentCapability()); - return capabilities; - } - - private static Map createNeutronNetworkProperties() { - Map neutronNetworkPropertyDefMap = new HashMap<>(); - neutronNetworkPropertyDefMap.put("admin_state_up", DataModelUtil - .createPropertyDefinition(PropertyType.BOOLEAN.getDisplayName(), - "A boolean value specifying the administrative status of the network", false, null, - null, null, true)); - neutronNetworkPropertyDefMap.put("dhcp_agent_ids", DataModelUtil - .createPropertyDefinition(PropertyType.LIST.getDisplayName(), - "The IDs of the DHCP agent to schedule the network", false, null, null, - DataModelUtil.createEntrySchema(PropertyType.STRING.getDisplayName(), null, null), - null)); - neutronNetworkPropertyDefMap.put("port_security_enabled", DataModelUtil - .createPropertyDefinition(PropertyType.BOOLEAN.getDisplayName(), - "Flag to enable/disable port security on the network", false, null, null, null, null)); - neutronNetworkPropertyDefMap.put("qos_policy", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), - "The name or ID of QoS policy to attach to this network", false, null, null, null, - null)); - neutronNetworkPropertyDefMap.put("shared", DataModelUtil - .createPropertyDefinition(PropertyType.BOOLEAN.getDisplayName(), - "Whether this network should be shared across all tenants", false, null, null, null, - false)); - neutronNetworkPropertyDefMap.put("tenant_id", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), - "The ID of the tenant which will own the network", false, null, null, null, null)); - neutronNetworkPropertyDefMap.put("value_specs", DataModelUtil - .createPropertyDefinition(PropertyType.MAP.getDisplayName(), - "Extra parameters to include in the request", false, null, null, - DataModelUtil.createEntrySchema(PropertyType.STRING.getDisplayName(), null, null), - new HashMap())); - neutronNetworkPropertyDefMap.put("subnets", DataModelUtil - .createPropertyDefinition(PropertyType.MAP.getDisplayName(), "Network related subnets", - false, null, null, DataModelUtil - .createEntrySchema(ToscaDataType.NEUTRON_SUBNET.getDisplayName(), null, null), - null)); - return neutronNetworkPropertyDefMap; - } - - private static Map createNeutronNetworkAttributes() { - Map neutronNetworkAttributesDefMap = new HashMap<>(); - neutronNetworkAttributesDefMap.put("mtu", DataModelUtil - .createAttributeDefinition(PropertyType.SCALAR_UNIT_SIZE.getDisplayName(), - "The maximum transmission unit size(in bytes) for the network", null, null, null)); - neutronNetworkAttributesDefMap.put("qos_policy_id", DataModelUtil - .createAttributeDefinition(PropertyType.STRING.getDisplayName(), - "The QoS policy ID attached to this network", null, null, null)); - neutronNetworkAttributesDefMap.put("show", DataModelUtil - .createAttributeDefinition(PropertyType.STRING.getDisplayName(), - "Detailed information about resource", null, null, null)); - neutronNetworkAttributesDefMap.put("status", DataModelUtil - .createAttributeDefinition(PropertyType.STRING.getDisplayName(), - "The status of the network", null, null, null)); - neutronNetworkAttributesDefMap.put("subnets_name", DataModelUtil - .createAttributeDefinition(PropertyType.LIST.getDisplayName(), - "Subnets name of this network", null, - DataModelUtil.createEntrySchema(PropertyType.STRING.getDisplayName(), null, null), - null)); - neutronNetworkAttributesDefMap.put("subnets", DataModelUtil - .createAttributeDefinition(PropertyType.MAP.getDisplayName(), "Network related subnets", - null, DataModelUtil - .createEntrySchema(ToscaDataType.NEUTRON_SUBNET.getDisplayName(), null, null), - null)); - return neutronNetworkAttributesDefMap; - } -} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/NeutronPortGlobalType.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/NeutronPortGlobalType.java deleted file mode 100644 index 2106b9b3bc..0000000000 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/NeutronPortGlobalType.java +++ /dev/null @@ -1,203 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.translator.services.heattotosca.globaltypes; - -import org.openecomp.sdc.tosca.datatypes.ToscaDataType; -import org.openecomp.sdc.tosca.datatypes.ToscaNodeType; -import org.openecomp.sdc.tosca.datatypes.model.AttributeDefinition; -import org.openecomp.sdc.tosca.datatypes.model.CapabilityDefinition; -import org.openecomp.sdc.tosca.datatypes.model.Constraint; -import org.openecomp.sdc.tosca.datatypes.model.DataType; -import org.openecomp.sdc.tosca.datatypes.model.NodeType; -import org.openecomp.sdc.tosca.datatypes.model.PropertyDefinition; -import org.openecomp.sdc.tosca.datatypes.model.PropertyType; -import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; -import org.openecomp.sdc.tosca.services.DataModelUtil; -import org.openecomp.sdc.tosca.services.ToscaConstants; -import org.openecomp.sdc.translator.services.heattotosca.Constants; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class NeutronPortGlobalType { - /** - * Create service template service template. - * - * @return the service template - */ - public static ServiceTemplate createServiceTemplate() { - ServiceTemplate neutronPortServiceTemplate = new ServiceTemplate(); - neutronPortServiceTemplate - .setTosca_definitions_version(ToscaConstants.TOSCA_DEFINITIONS_VERSION); - neutronPortServiceTemplate.setMetadata( - DataModelUtil.createMetadata(Constants.NEUTRON_PORT_TEMPLATE_NAME, "1.0.0", null)); - neutronPortServiceTemplate.setImports(GlobalTypesUtil.createCommonImportList()); - neutronPortServiceTemplate.setDescription("Neutron Port TOSCA Global Types"); - neutronPortServiceTemplate.setData_types(createGlobalDataTypes()); - neutronPortServiceTemplate.setNode_types(createGlobalNodeTypes()); - return neutronPortServiceTemplate; - } - - private static Map createGlobalDataTypes() { - Map globalDataTypes = new HashMap<>(); - globalDataTypes - .put(ToscaDataType.NEUTRON_PORT_FIXED_IPS.getDisplayName(), createFixedIpsDataType()); - return globalDataTypes; - } - - private static DataType createFixedIpsDataType() { - DataType dataType = new DataType(); - dataType.setDerived_from(ToscaDataType.ROOT.getDisplayName()); - dataType.setDescription("subnet/ip_address"); - Map prop = new HashMap<>(); - - prop.put("subnet", DataModelUtil.createPropertyDefinition(PropertyType.STRING.getDisplayName(), - "Subnet in which to allocate the IP address for this port", false, null, null, null, null)); - prop.put("ip_address", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), - "IP address desired in the subnet for this port", false, null, null, null, null)); - - dataType.setProperties(prop); - return dataType; - } - - private static Map createGlobalNodeTypes() { - Map globalNodeTypes = new HashMap<>(); - globalNodeTypes.put(ToscaNodeType.NEUTRON_PORT.getDisplayName(), createNeutronPortNodeType()); - return globalNodeTypes; - } - - private static NodeType createNeutronPortNodeType() { - NodeType nodeType = new NodeType(); - nodeType.setDerived_from(ToscaNodeType.NETWORK_PORT.getDisplayName()); - nodeType.setProperties(createNeutronPortProperties()); - nodeType.setAttributes(createNeutronPortAttributes()); - nodeType.setCapabilities(createNeutronPortCapabilities()); - return nodeType; - } - - private static Map createNeutronPortCapabilities() { - Map capabilities = new HashMap<>(); - capabilities.put("attachment", GlobalTypesUtil.createAttachmentCapability()); - return capabilities; - } - - private static Map createNeutronPortProperties() { - Map neutronPortPropertyDefMap = new HashMap<>(); - neutronPortPropertyDefMap.put("admin_state_up", DataModelUtil - .createPropertyDefinition(PropertyType.BOOLEAN.getDisplayName(), - "A boolean value specifying the administrative status of the network", false, null, - null, null, true)); - neutronPortPropertyDefMap.put("allowed_address_pairs", DataModelUtil - .createPropertyDefinition(PropertyType.LIST.getDisplayName(), - "Additional MAC/IP address pairs allowed to pass through the port", false, null, null, - DataModelUtil - .createEntrySchema(ToscaDataType.NETWORK_ADDRESS_PAIR.getDisplayName(), null, null), - null)); - neutronPortPropertyDefMap.put("binding:vnic_type", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), - "The vnic type to be bound on the neutron port", false, createBindingConstraint(), null, - null, null)); - neutronPortPropertyDefMap.put("device_id", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), "Device ID of this port", - false, null, null, null, null)); - neutronPortPropertyDefMap.put("device_owner", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), - "Name of the network owning the port", false, null, null, null, null)); - neutronPortPropertyDefMap.put("fixed_ips", DataModelUtil - .createPropertyDefinition(PropertyType.LIST.getDisplayName(), "Desired IPs for this port", - false, null, null, DataModelUtil - .createEntrySchema(ToscaDataType.NEUTRON_PORT_FIXED_IPS.getDisplayName(), null, - null), null)); - neutronPortPropertyDefMap.put("mac_address", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), - "MAC address to give to this port", false, null, null, null, null)); - neutronPortPropertyDefMap.put(Constants.NAME_PROPERTY_NAME, DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), - "A symbolic name for this port", false, null, null, null, null)); - neutronPortPropertyDefMap.put("port_security_enabled", DataModelUtil - .createPropertyDefinition(PropertyType.BOOLEAN.getDisplayName(), - "Flag to enable/disable port security on the network", false, null, null, null, null)); - neutronPortPropertyDefMap.put("qos_policy", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), - "The name or ID of QoS policy to attach to this network", false, null, null, null, - null)); - neutronPortPropertyDefMap.put(Constants.SECURITY_GROUPS_PROPERTY_NAME, DataModelUtil - .createPropertyDefinition(PropertyType.LIST.getDisplayName(), - "List of security group names or IDs", false, null, null, - DataModelUtil.createEntrySchema(PropertyType.STRING.getDisplayName(), null, null), - null)); - neutronPortPropertyDefMap.put("value_specs", DataModelUtil - .createPropertyDefinition(PropertyType.MAP.getDisplayName(), - "Extra parameters to include in the request", false, null, null, - DataModelUtil.createEntrySchema(PropertyType.STRING.getDisplayName(), null, null), - new HashMap())); - neutronPortPropertyDefMap.put("replacement_policy", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), - "Policy on how to respond to a stack-update for this resource", false, - createReplacementPolicyConstrain(), null, null, "AUTO")); - neutronPortPropertyDefMap.put("network", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), - "Network this port belongs to", false, null, null, null, null)); - return neutronPortPropertyDefMap; - } - - private static List createBindingConstraint() { - List constraints = new ArrayList<>(); - Constraint validValues = - DataModelUtil.createValidValuesConstraint("macvtap", "direct", "normal"); - constraints.add(validValues); - return constraints; - } - - private static List createReplacementPolicyConstrain() { - List constraints = new ArrayList<>(); - Constraint validValues = DataModelUtil.createValidValuesConstraint("REPLACE_ALWAYS", "AUTO"); - constraints.add(validValues); - return constraints; - } - - private static Map createNeutronPortAttributes() { - Map neutronPortAttributesDefMap = new HashMap<>(); - neutronPortAttributesDefMap.put("network_id", DataModelUtil - .createAttributeDefinition(PropertyType.STRING.getDisplayName(), - "Unique identifier for the network owning the port", null, null, null)); - neutronPortAttributesDefMap.put("qos_policy_id", DataModelUtil - .createAttributeDefinition(PropertyType.STRING.getDisplayName(), - "The QoS policy ID attached to this network", null, null, null)); - neutronPortAttributesDefMap.put("show", DataModelUtil - .createAttributeDefinition(PropertyType.STRING.getDisplayName(), - "Detailed information about resource", null, null, null)); - neutronPortAttributesDefMap.put("status", DataModelUtil - .createAttributeDefinition(PropertyType.STRING.getDisplayName(), - "The status of the network", null, null, null)); - neutronPortAttributesDefMap.put("subnets", DataModelUtil - .createAttributeDefinition(PropertyType.LIST.getDisplayName(), "Subnets of this network", - null, DataModelUtil.createEntrySchema(PropertyType.STRING.getDisplayName(), null, null), - null)); - neutronPortAttributesDefMap.put("tenant_id", DataModelUtil - .createAttributeDefinition(PropertyType.STRING.getDisplayName(), "Tenant owning the port", - null, null, null)); - return neutronPortAttributesDefMap; - } -} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/NeutronSecurityRulesGlobalType.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/NeutronSecurityRulesGlobalType.java deleted file mode 100644 index 4c5b033e0e..0000000000 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/NeutronSecurityRulesGlobalType.java +++ /dev/null @@ -1,175 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.translator.services.heattotosca.globaltypes; - -import org.openecomp.sdc.tosca.datatypes.ToscaCapabilityType; -import org.openecomp.sdc.tosca.datatypes.ToscaDataType; -import org.openecomp.sdc.tosca.datatypes.ToscaNodeType; -import org.openecomp.sdc.tosca.datatypes.ToscaRelationshipType; -import org.openecomp.sdc.tosca.datatypes.model.AttributeDefinition; -import org.openecomp.sdc.tosca.datatypes.model.Constraint; -import org.openecomp.sdc.tosca.datatypes.model.DataType; -import org.openecomp.sdc.tosca.datatypes.model.NodeType; -import org.openecomp.sdc.tosca.datatypes.model.PropertyDefinition; -import org.openecomp.sdc.tosca.datatypes.model.PropertyType; -import org.openecomp.sdc.tosca.datatypes.model.RequirementDefinition; -import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; -import org.openecomp.sdc.tosca.services.DataModelUtil; -import org.openecomp.sdc.tosca.services.ToscaConstants; -import org.openecomp.sdc.translator.services.heattotosca.Constants; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class NeutronSecurityRulesGlobalType { - /** - * Create service template service template. - * - * @return the service template - */ - public static ServiceTemplate createServiceTemplate() { - ServiceTemplate neutronSecurityRulesServiceTemplate = new ServiceTemplate(); - neutronSecurityRulesServiceTemplate - .setTosca_definitions_version(ToscaConstants.TOSCA_DEFINITIONS_VERSION); - neutronSecurityRulesServiceTemplate.setMetadata(DataModelUtil - .createMetadata(Constants.NEUTRON_SECURITY_RULES_TEMPLATE_NAME, "1.0.0", null)); - neutronSecurityRulesServiceTemplate.setImports(GlobalTypesUtil.createCommonImportList()); - neutronSecurityRulesServiceTemplate.setDescription("Neutron Security Rules TOSCA Global Types"); - neutronSecurityRulesServiceTemplate.setData_types(createGlobalDataTypes()); - neutronSecurityRulesServiceTemplate.setNode_types(createGlobalNodeTypes()); - return neutronSecurityRulesServiceTemplate; - } - - - private static Map createGlobalDataTypes() { - Map globalDataTypes = new HashMap<>(); - globalDataTypes.put(ToscaDataType.NEUTRON_SECURITY_RULES_RULE.getDisplayName(), - createSecurityRulesDataType()); - return globalDataTypes; - } - - private static DataType createSecurityRulesDataType() { - DataType addressPairDataType = new DataType(); - addressPairDataType.setDerived_from(ToscaDataType.ROOT.getDisplayName()); - addressPairDataType.setDescription("Rules Pairs"); - Map addressPairProp = new HashMap<>(); - - addressPairProp.put("direction", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), - "The direction in which the security group rule is applied", false, - DataModelUtil.createValidValuesConstraintsList("egress", "ingress"), null, null, - "ingress")); - addressPairProp.put("ethertype", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), "Ethertype of the traffic", - false, DataModelUtil.createValidValuesConstraintsList("IPv4", "IPv6"), null, null, - "IPv4")); - Constraint portRangeMaxConstraint = new Constraint(); - portRangeMaxConstraint.setIn_range(new Integer[]{0, 65535}); - addressPairProp.put("port_range_max", DataModelUtil - .createPropertyDefinition(PropertyType.INTEGER.getDisplayName(), - "The maximum port number in the range that is matched by the security group rule. ", - false, DataModelUtil.getConstrainList(portRangeMaxConstraint), null, null, null)); - Constraint portRangeMinConstraint = new Constraint(); - portRangeMinConstraint.setIn_range(new Integer[]{0, 65535}); - addressPairProp.put("port_range_min", DataModelUtil - .createPropertyDefinition(PropertyType.INTEGER.getDisplayName(), - "The minimum port number in the range that is matched by the security group rule.", - false, DataModelUtil.getConstrainList(portRangeMinConstraint), null, null, null)); - addressPairProp.put("protocol", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), - "The protocol that is matched by the security group rule", false, - DataModelUtil.createValidValuesConstraintsList("tcp", "udp", "icmp"), null, null, - null)); - addressPairProp.put("remote_group_id", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), - "The remote group ID to be associated with this security group rule", false, null, null, - null, null)); - addressPairProp.put("remote_ip_prefix", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), - "The remote IP prefix (CIDR) to be associated with this security group rule", false, - null, null, null, null)); - addressPairProp.put("remote_mode", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), - "Whether to specify a remote group or a remote IP prefix", false, - DataModelUtil.createValidValuesConstraintsList("remote_ip_prefix", "remote_group_id"), - null, null, "remote_ip_prefix")); - addressPairDataType.setProperties(addressPairProp); - - return addressPairDataType; - } - - private static Map createGlobalNodeTypes() { - Map globalNodeTypes = new HashMap<>(); - globalNodeTypes.put(ToscaNodeType.NEUTRON_SECURITY_RULES.getDisplayName(), - createNeutronSecurityRulesNodeType()); - return globalNodeTypes; - } - - private static NodeType createNeutronSecurityRulesNodeType() { - NodeType novaServerNodeType = new NodeType(); - novaServerNodeType.setDerived_from(ToscaNodeType.ROOT.getDisplayName()); - novaServerNodeType.setProperties(createNeutronSecurityRulesProperties()); - novaServerNodeType.setAttributes(createNeutronSecurityRulesAttributes()); - novaServerNodeType.setRequirements(createNeutronSecurityRequirements()); - return novaServerNodeType; - } - - private static List> createNeutronSecurityRequirements() { - final List> requirements = new ArrayList<>(); - final Map portRequirement = new HashMap<>(); - RequirementDefinition requirementDefinition = new RequirementDefinition(); - requirementDefinition.setCapability(ToscaCapabilityType.ATTACHMENT.getDisplayName()); - requirementDefinition.setNode(ToscaNodeType.NEUTRON_PORT.getDisplayName()); - requirementDefinition.setRelationship(ToscaRelationshipType.ATTACHES_TO.getDisplayName()); - requirementDefinition.setOccurrences(new Object[]{0, ToscaConstants.UNBOUNDED}); - portRequirement.put(ToscaConstants.PORT_REQUIREMENT_ID, requirementDefinition); - requirements.add(portRequirement); - - return requirements; - } - - private static Map createNeutronSecurityRulesProperties() { - Map neutronSecurityRulesPropertyDefMap = new HashMap<>(); - neutronSecurityRulesPropertyDefMap.put(Constants.NAME_PROPERTY_NAME, DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), - "A symbolic name for this security group, which is not required to be unique.", false, - null, null, null, null)); - neutronSecurityRulesPropertyDefMap.put(Constants.DESCRIPTION_PROPERTY_NAME, DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), - "Description of the security group", false, null, null, null, null)); - neutronSecurityRulesPropertyDefMap.put(Constants.RULES_PROPERTY_NAME, DataModelUtil - .createPropertyDefinition(PropertyType.LIST.getDisplayName(), - "List of security group rules", false, null, null, DataModelUtil - .createEntrySchema(ToscaDataType.NEUTRON_SECURITY_RULES_RULE.getDisplayName(), null, - null), null)); - return neutronSecurityRulesPropertyDefMap; - } - - private static Map createNeutronSecurityRulesAttributes() { - Map neutronSecurityRulesAttributesDefMap = new HashMap<>(); - neutronSecurityRulesAttributesDefMap.put("show", DataModelUtil - .createAttributeDefinition(PropertyType.STRING.getDisplayName(), - "Detailed information about resource", null, null, null)); - return neutronSecurityRulesAttributesDefMap; - } -} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/NovaServerGlobalType.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/NovaServerGlobalType.java deleted file mode 100644 index d38d70a4f7..0000000000 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/globaltypes/NovaServerGlobalType.java +++ /dev/null @@ -1,307 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.translator.services.heattotosca.globaltypes; - -import org.openecomp.sdc.tosca.datatypes.ToscaDataType; -import org.openecomp.sdc.tosca.datatypes.ToscaNodeType; -import org.openecomp.sdc.tosca.datatypes.model.AttributeDefinition; -import org.openecomp.sdc.tosca.datatypes.model.Constraint; -import org.openecomp.sdc.tosca.datatypes.model.DataType; -import org.openecomp.sdc.tosca.datatypes.model.NodeType; -import org.openecomp.sdc.tosca.datatypes.model.PropertyDefinition; -import org.openecomp.sdc.tosca.datatypes.model.PropertyType; -import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; -import org.openecomp.sdc.tosca.datatypes.model.heatextend.PropertyTypeExt; -import org.openecomp.sdc.tosca.services.DataModelUtil; -import org.openecomp.sdc.tosca.services.ToscaConstants; -import org.openecomp.sdc.translator.services.heattotosca.Constants; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; - -public class NovaServerGlobalType { - - /** - * Create service template service template. - * - * @return the service template - */ - public static ServiceTemplate createServiceTemplate() { - ServiceTemplate novaeServerServiceTemplate = new ServiceTemplate(); - novaeServerServiceTemplate - .setTosca_definitions_version(ToscaConstants.TOSCA_DEFINITIONS_VERSION); - novaeServerServiceTemplate.setMetadata( - DataModelUtil.createMetadata(Constants.NOVA_SERVER_TEMPLATE_NAME, "1.0.0", null)); - novaeServerServiceTemplate.setDescription("Nova Server TOSCA Global Types"); - novaeServerServiceTemplate.setImports(GlobalTypesUtil.createCommonImportList()); - novaeServerServiceTemplate.setData_types(createGlobalDataTypes()); - novaeServerServiceTemplate.setNode_types(createGlobalNodeTypes()); - return novaeServerServiceTemplate; - } - - - private static Map createGlobalNodeTypes() { - Map globalNodeTypes = new HashMap<>(); - globalNodeTypes.put(ToscaNodeType.NOVA_SERVER.getDisplayName(), createNovaServerNodeType()); - return globalNodeTypes; - } - - private static NodeType createNovaServerNodeType() { - NodeType novaServerNodeType = new NodeType(); - novaServerNodeType.setDerived_from(ToscaNodeType.COMPUTE.getDisplayName()); - novaServerNodeType.setProperties(createNovaServerProperties()); - novaServerNodeType.setAttributes(createNovaServerAttributes()); - return novaServerNodeType; - } - - - private static Map createNovaServerProperties() { - Map novaServerPropertyDefMap = new HashMap<>(); - novaServerPropertyDefMap.put("flavor", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), - "The ID or name of the flavor to boot onto", true, null, null, null, null)); - novaServerPropertyDefMap.put("admin_pass", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), - "The administrator password for the server", false, null, null, null, null)); - novaServerPropertyDefMap.put("availability_zone", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), - "Availability zone to create servers in", false, null, null, null, null)); - novaServerPropertyDefMap.put("config_drive", DataModelUtil - .createPropertyDefinition(PropertyType.BOOLEAN.getDisplayName(), - "enable config drive on the server", false, null, null, null, null)); - novaServerPropertyDefMap.put("contrail_service_instance_ind", DataModelUtil - .createPropertyDefinition(PropertyType.BOOLEAN.getDisplayName(), - "Nova server related to service instance indicator", false, null, null, null, false)); - novaServerPropertyDefMap.put("diskConfig", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), - "Control how the disk is partitioned when the server is created", false, - getDiskConfigConstraints(), null, null, null)); - novaServerPropertyDefMap.put("flavor_update_policy", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), - "Policy on how to apply a flavor update", false, getFlavorUpdatePolicyConstraints(), - null, null, "RESIZE")); - novaServerPropertyDefMap.put("image", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), - "The ID or name of the image to boot with", false, null, null, null, null)); - novaServerPropertyDefMap.put("image_update_policy", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), - "Policy on how to apply an image-id update", false, getImageUpdatePolicyConstraints(), - null, null, "REBUILD")); - novaServerPropertyDefMap.put("key_name", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), - "Name of keypair to inject into the server", false, null, null, null, null)); - novaServerPropertyDefMap.put("metadata", DataModelUtil - .createPropertyDefinition(PropertyTypeExt.JSON.getDisplayName(), - "Arbitrary JSON metadata to store for this server", false, null, null, null, null)); - novaServerPropertyDefMap.put(Constants.NAME_PROPERTY_NAME, DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), "Server name", false, null, - null, null, null)); - novaServerPropertyDefMap.put("personality", DataModelUtil - .createPropertyDefinition(PropertyType.MAP.getDisplayName(), - "A map of files to create/overwrite on the server upon boot", false, null, null, - DataModelUtil.createEntrySchema(PropertyType.STRING.getDisplayName(), null, null), - new HashMap())); - novaServerPropertyDefMap.put("reservation_id", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), - "A UUID for the set of servers being requested", false, null, null, null, null)); - novaServerPropertyDefMap.put("scheduler_hints", DataModelUtil - .createPropertyDefinition(PropertyType.MAP.getDisplayName(), - "Arbitrary key-value pairs specified by the client to help boot a server", false, null, - null, DataModelUtil.createEntrySchema(PropertyType.STRING.getDisplayName(), null, null), - null)); - novaServerPropertyDefMap.put(Constants.SECURITY_GROUPS_PROPERTY_NAME, DataModelUtil - .createPropertyDefinition(PropertyType.LIST.getDisplayName(), - "List of security group names or IDs", false, null, null, - DataModelUtil.createEntrySchema(PropertyType.STRING.getDisplayName(), null, null), - new ArrayList<>())); - novaServerPropertyDefMap.put("software_config_transport", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), - "How the server should receive the metadata required for software configuration", false, - getSoftwareConfigTransportConstraints(), null, null, "POLL_SERVER_CFN")); - novaServerPropertyDefMap.put("user_data", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), - "User data script to be executed by cloud-init", false, null, null, null, "")); - novaServerPropertyDefMap.put("user_data_format", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), - "How the user_data should be formatted for the server", false, - getUserDataFormatConstraint(), null, null, "HEAT_CFNTOOLS")); - novaServerPropertyDefMap.put("user_data_update_policy", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), - "Policy on how to apply a user_data update", false, - getUserDataUpdatePolicyConstraints(), null, null, "REPLACE")); - return novaServerPropertyDefMap; - } - - private static Map createNovaServerAttributes() { - Map novaServerAttributesDefMap = new HashMap<>(); - novaServerAttributesDefMap.put("accessIPv4", DataModelUtil - .createAttributeDefinition(PropertyType.STRING.getDisplayName(), - "The manually assigned alternative public IPv4 address of the server", null, null, - null)); - novaServerAttributesDefMap.put("accessIPv6", DataModelUtil - .createAttributeDefinition(PropertyType.STRING.getDisplayName(), - "The manually assigned alternative public IPv6 address of the server", null, null, - null)); - novaServerAttributesDefMap.put("addresses", DataModelUtil - .createAttributeDefinition(PropertyType.MAP.getDisplayName(), - "A dict of all network addresses with corresponding port_id", null, DataModelUtil - .createEntrySchema(ToscaDataType.NOVA_SERVER_NETWORK_ADDRESS_INFO.getDisplayName(), - null, null), null)); - novaServerAttributesDefMap.put("console_urls", DataModelUtil - .createAttributeDefinition(PropertyType.STRING.getDisplayName(), "URLs of servers consoles", - null, null, null)); - novaServerAttributesDefMap.put("instance_name", DataModelUtil - .createAttributeDefinition(PropertyType.STRING.getDisplayName(), - "AWS compatible instance name", null, null, null)); - novaServerAttributesDefMap.put(Constants.NAME_PROPERTY_NAME, DataModelUtil - .createAttributeDefinition(PropertyType.STRING.getDisplayName(), "Name of the server", null, - null, null)); - novaServerAttributesDefMap.put("show", DataModelUtil - .createAttributeDefinition(PropertyType.STRING.getDisplayName(), - "Detailed information about resource", null, null, null)); - return novaServerAttributesDefMap; - } - - private static List getUserDataFormatConstraint() { - List constraints; - Constraint validValues; - constraints = new ArrayList<>(); - validValues = - DataModelUtil.createValidValuesConstraint("SOFTWARE_CONFIG", "RAW", "HEAT_CFNTOOLS"); - constraints.add(validValues); - return constraints; - } - - private static List getUserDataUpdatePolicyConstraints() { - List constraints; - Constraint validValues; - constraints = new ArrayList<>(); - validValues = DataModelUtil.createValidValuesConstraint("REPLACE", "IGNORE"); - constraints.add(validValues); - return constraints; - } - - private static List getSoftwareConfigTransportConstraints() { - List constraints; - Constraint validValues; - constraints = new ArrayList<>(); - validValues = DataModelUtil - .createValidValuesConstraint("POLL_SERVER_CFN", "POLL_SERVER_HEAT", "POLL_TEMP_URL", - "ZAQAR_MESSAGE"); - constraints.add(validValues); - return constraints; - } - - private static List getImageUpdatePolicyConstraints() { - List constraints; - Constraint validValues; - constraints = new ArrayList<>(); - validValues = DataModelUtil - .createValidValuesConstraint("REBUILD_PRESERVE_EPHEMERAL", "REPLACE", "REBUILD"); - constraints.add(validValues); - return constraints; - } - - private static List getFlavorUpdatePolicyConstraints() { - Constraint validValues; - List constraints = new ArrayList<>(); - validValues = DataModelUtil.createValidValuesConstraint("RESIZE", "REPLACE"); - constraints.add(validValues); - return constraints; - } - - private static List getDiskConfigConstraints() { - List constraints = new ArrayList<>(); - Constraint validValues = DataModelUtil.createValidValuesConstraint("AUTO", "MANUAL"); - constraints.add(validValues); - return constraints; - } - - private static Map createGlobalDataTypes() { - Map globalDataTypes = new HashMap<>(); - globalDataTypes.put(ToscaDataType.NOVA_SERVER_PORT_EXTRA_PROPERTIES.getDisplayName(), - createPortExtraDataDataType()); - globalDataTypes.put(ToscaDataType.NOVA_SERVER_NETWORK_ADDRESS_INFO.getDisplayName(), - createAddressInfoDataType()); - return globalDataTypes; - } - - private static DataType createAddressInfoDataType() { - DataType addressInfoDataType = new DataType(); - addressInfoDataType.setDerived_from(ToscaDataType.NETWORK_NETWORK_INFO.getDisplayName()); - addressInfoDataType.setDescription("Network addresses with corresponding port id"); - - Map addressInfoProp = new HashMap<>(); - addressInfoProp.put("port_id", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), "Port id", false, null, - null, null, null)); - addressInfoDataType.setProperties(addressInfoProp); - - return addressInfoDataType; - } - - - private static DataType createPortExtraDataDataType() { - DataType portExtraDataType = new DataType(); - portExtraDataType.setDerived_from(ToscaDataType.ROOT.getDisplayName()); - portExtraDataType.setDescription("Nova server network expand properties for port"); - Map portExtraPropMap = new HashMap<>(); - - portExtraPropMap.put("admin_state_up", DataModelUtil - .createPropertyDefinition(PropertyType.BOOLEAN.getDisplayName(), - "The administrative state of this port", false, null, null, null, true)); - portExtraPropMap.put("allowed_address_pairs", DataModelUtil - .createPropertyDefinition(PropertyType.LIST.getDisplayName(), - "Additional MAC/IP address pairs allowed to pass through the port", false, null, null, - DataModelUtil - .createEntrySchema(ToscaDataType.NETWORK_ADDRESS_PAIR.getDisplayName(), null, null), - null)); - - List bindingVnicConstraints = new ArrayList<>(); - Constraint validValues = - DataModelUtil.createValidValuesConstraint("macvtap", "direct", "normal"); - bindingVnicConstraints.add(validValues); - portExtraPropMap.put("binding:vnic_type", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), - "The vnic type to be bound on the neutron port", false, bindingVnicConstraints, null, - null, null)); - - portExtraPropMap.put("mac_address", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), - "MAC address to give to this port", false, null, null, null, null)); - portExtraPropMap.put("port_security_enabled", DataModelUtil - .createPropertyDefinition(PropertyType.BOOLEAN.getDisplayName(), - "Flag to enable/disable port security on the port", false, null, null, null, null)); - portExtraPropMap.put("qos_policy", DataModelUtil - .createPropertyDefinition(PropertyType.STRING.getDisplayName(), - "The name or ID of QoS policy to attach to this port", false, null, null, null, null)); - portExtraPropMap.put("value_specs", DataModelUtil - .createPropertyDefinition(PropertyType.MAP.getDisplayName(), - "Extra parameters to include in the request", false, null, null, - DataModelUtil.createEntrySchema(PropertyType.STRING.getDisplayName(), null, null), - new HashMap())); - portExtraDataType.setProperties(portExtraPropMap); - return portExtraDataType; - } - -} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/helper/ContrailTranslationHelper.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/helper/ContrailTranslationHelper.java index 2e1aa9e372..a86f584bf0 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/helper/ContrailTranslationHelper.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/helper/ContrailTranslationHelper.java @@ -20,46 +20,138 @@ package org.openecomp.sdc.translator.services.heattotosca.helper; +import org.openecomp.core.utilities.file.FileUtils; +import org.openecomp.sdc.common.utils.CommonUtil; +import org.openecomp.sdc.heat.datatypes.HeatBoolean; import org.openecomp.sdc.heat.datatypes.model.Resource; +import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; import org.openecomp.sdc.tosca.services.ToscaConstants; -import org.openecomp.sdc.translator.services.heattotosca.helper.impl.NameExtractorServiceImpl; +import org.openecomp.sdc.tosca.datatypes.ToscaFunctions; +import org.openecomp.sdc.translator.datatypes.heattotosca.PropertyRegexMatcher; +import org.openecomp.sdc.translator.services.heattotosca.ConfigConstants; +import org.openecomp.sdc.translator.services.heattotosca.NameExtractor; +import org.openecomp.sdc.translator.datatypes.heattotosca.TranslationContext; import java.util.ArrayList; import java.util.Collections; +import java.util.HashMap; import java.util.List; +import java.util.Map; import java.util.Optional; public class ContrailTranslationHelper { + + private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); /** * Gets compute node type id. * - * @param serviceTemplateTranslatedId the service template translated id - * @param serviceTemplateResource the service template resource + * @param contrailServiceTemplateResource contrail service teamplte resource + * @param contrailServiceTemplateResourceId contrailservice template resource id + * @param contrailServiceTemplateTranslatedId contrail service tempalte resource translated id * @return the compute node type id */ - public String getComputeNodeTypeId(String serviceTemplateTranslatedId, - Resource serviceTemplateResource) { - NameExtractorService nodeTypeNameExtractor = new NameExtractorServiceImpl(); - List propertyRegexMatchers = - getPropertiesAndRegexMatchers(nodeTypeNameExtractor); - Optional extractedNodeTypeName = nodeTypeNameExtractor - .extractNodeTypeNameByPropertiesPriority(serviceTemplateResource.getProperties(), - propertyRegexMatchers); - - return ToscaConstants.NODES_PREFIX - + (extractedNodeTypeName.isPresent() ? extractedNodeTypeName.get() - : "compute_" + serviceTemplateTranslatedId); + public String getComputeNodeTypeId(Resource contrailServiceTemplateResource, + String contrailServiceTemplateResourceId, + String contrailServiceTemplateTranslatedId, + TranslationContext context) { + mdcDataDebugMessage.debugEntryMessage(null, null); + NameExtractor nodeTypeNameExtractor = + context.getNameExtractorImpl(ConfigConstants.CONTRAIL_COMPUTE_NODE_TYPE_IMPL_KEY); + + mdcDataDebugMessage.debugExitMessage(null, null); + return nodeTypeNameExtractor + .extractNodeTypeName(contrailServiceTemplateResource, contrailServiceTemplateResourceId, + contrailServiceTemplateTranslatedId); } - private List getPropertiesAndRegexMatchers( - NameExtractorService nodeTypeNameExtractor) { + /** + * Get property Regx matcher list. + * + * @return Regex exprission per contrail service template resource property, while contail compute + * type name is consider when setting the name value + */ + public List getPropertyRegexMatchersForComputeNodeType() { List propertyRegexMatchers = new ArrayList<>(); - propertyRegexMatchers.add(nodeTypeNameExtractor - .getPropertyRegexMatcher("image_name", Collections.singletonList(".+_image_name$"), + propertyRegexMatchers + .add(new PropertyRegexMatcher("image_name", Collections.singletonList(".+_image_name$"), "_image_name")); - propertyRegexMatchers.add(nodeTypeNameExtractor - .getPropertyRegexMatcher("flavor", Collections.singletonList(".+_flavor_name$"), + propertyRegexMatchers + .add(new PropertyRegexMatcher("flavor", Collections.singletonList(".+_flavor_name$"), "_flavor_name")); return propertyRegexMatchers; } + + public String getSubstitutionContrailServiceTemplateMetadata(String heatFileName, + String serviceInstanceTranslatedId) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + mdcDataDebugMessage.debugExitMessage(null, null); + return FileUtils.getFileWithoutExtention(heatFileName) + "_" + serviceInstanceTranslatedId; + } + + /** + * Translate fn split function optional. + * + * @param propertyValue the property value + * @param listSize the list size + * @param includeBooleanValue the include boolean value + * @return the optional + */ + public Optional>> translateFnSplitFunction(Object propertyValue, + int listSize, + boolean + includeBooleanValue) { + List> tokenPropertyValueList = new ArrayList<>(); + + if (propertyValue instanceof Map && !((Map) propertyValue).isEmpty()) { + Map propMap = (Map) propertyValue; + Map.Entry entry = propMap.entrySet().iterator().next(); + Object entity = entry.getValue(); + String key = entry.getKey(); + String tokenChar; + + if (key.equals("Fn::Split") && entity instanceof List) { + tokenChar = (String) ((List) entity).get(0); + Object refParameter = ((List) entity).get(1); + + for (int substringIndex = 0; substringIndex < listSize; substringIndex++) { + Map tokenPropertyValue = new HashMap<>(); + tokenPropertyValue.put("token", new ArrayList<>()); + + if (refParameter instanceof Map && ((Map) refParameter).get("Ref") != null) { + Map stringWithToken = new HashMap<>(); + ((Map) stringWithToken) + .put(ToscaFunctions.GET_INPUT.getDisplayName(), ((Map) refParameter).get("Ref")); + tokenPropertyValue.get("token").add(stringWithToken); + } else if (refParameter instanceof String) { + if (includeBooleanValue) { + StringBuffer booleanBuffer = new StringBuffer(); + String[] booleanValueList = ((String) refParameter).split(tokenChar); + for (int i = 0; i < booleanValueList.length; i++) { + if (i == 0) { + booleanBuffer.append(HeatBoolean.eval(booleanValueList[i])); + } else { + booleanBuffer.append(tokenChar); + booleanBuffer.append(HeatBoolean.eval(booleanValueList[i])); + } + } + tokenPropertyValue.get("token").add(booleanBuffer.toString()); + } else { + tokenPropertyValue.get("token").add(refParameter); + } + } + tokenPropertyValue.get("token").add(tokenChar); + tokenPropertyValue.get("token").add(substringIndex); + tokenPropertyValueList.add(tokenPropertyValue); + } + + return Optional.of(tokenPropertyValueList); + + } + } + + return Optional.empty(); + } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/helper/ContrailV2VirtualMachineInterfaceHelper.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/helper/ContrailV2VirtualMachineInterfaceHelper.java new file mode 100644 index 0000000000..402db74a9b --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/helper/ContrailV2VirtualMachineInterfaceHelper.java @@ -0,0 +1,184 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.translator.services.heattotosca.helper; + +import org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes; +import org.openecomp.sdc.heat.datatypes.model.Resource; +import org.openecomp.sdc.heat.services.HeatConstants; +import org.openecomp.sdc.logging.api.Logger; +import org.openecomp.sdc.logging.api.LoggerFactory; +import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; +import org.openecomp.sdc.tosca.datatypes.ToscaNodeType; +import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; +import org.openecomp.sdc.tosca.datatypes.model.RequirementAssignment; +import org.openecomp.sdc.tosca.services.ToscaConstants; +import org.openecomp.sdc.translator.datatypes.heattotosca.AttachedResourceId; +import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; +import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslatedHeatResource; +import org.openecomp.sdc.translator.services.heattotosca.ConsolidationDataUtil; +import org.openecomp.sdc.translator.services.heattotosca.ConsolidationEntityType; +import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; +import org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation.ResourceTranslationBase; + +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +public class ContrailV2VirtualMachineInterfaceHelper { + static Logger logger = + (Logger) LoggerFactory.getLogger(ContrailV2VirtualMachineInterfaceHelper.class); + private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); + + /** + * Connect Virtual Machine Interface node template to network node template in TOSCA. + * + * @param resourceTranslationImpl resource translation implemetation + * @param translateTo translated ro object + * @param vmiNodeTemplate Virtual Machine Interface node template + */ + public void connectVmiToNetwork(ResourceTranslationBase resourceTranslationImpl, + TranslateTo translateTo, NodeTemplate vmiNodeTemplate) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + Object virtualNetworkRefs = + translateTo.getResource().getProperties() + .get(HeatConstants.VIRTUAL_NETWORK_REFS_PROPERTY_NAME); + if (Objects.isNull(virtualNetworkRefs) || !(virtualNetworkRefs instanceof List) + || ((List) virtualNetworkRefs).size() == 0) { + return; + } + List acceptableResourceTypes = Arrays + .asList(HeatResourcesTypes.NEUTRON_NET_RESOURCE_TYPE.getHeatResource(), + HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_NETWORK_RESOURCE_TYPE.getHeatResource()); + + if (((List) virtualNetworkRefs).size() > 1) { + logger.warn("Heat resource: '" + translateTo.getResourceId() + "' with type: '" + + translateTo.getResource().getType() + + "' include '" + + HeatConstants.VIRTUAL_NETWORK_REFS_PROPERTY_NAME + + "' property with more than one network values, only " + + "the first network will be connected, " + + "all rest will be ignored in TOSCA translation."); + } + Object virtualNetworkRef = ((List) virtualNetworkRefs).get(0); + + Optional networkResourceId = + HeatToToscaUtil.extractContrailGetResourceAttachedHeatResourceId(virtualNetworkRef); + if (networkResourceId.isPresent()) { // get_resource + Resource networkResource = HeatToToscaUtil + .getResource(translateTo.getHeatOrchestrationTemplate(), networkResourceId.get(), + translateTo.getHeatFileName()); + if (acceptableResourceTypes.contains(networkResource.getType())) { + Optional resourceTranslatedId = + resourceTranslationImpl.getResourceTranslatedId(translateTo.getHeatFileName(), + translateTo.getHeatOrchestrationTemplate(), networkResourceId.get(), + translateTo.getContext()); + + if (resourceTranslatedId.isPresent()) { + RequirementAssignment requirementAssignment = HeatToToscaUtil.addLinkReqFromPortToNetwork( + vmiNodeTemplate, resourceTranslatedId.get()); + + if (ToscaNodeType.CONTRAILV2_VIRTUAL_MACHINE_INTERFACE + .equals(vmiNodeTemplate.getType())) { + ConsolidationDataUtil + .updateNodesConnectedOut(translateTo, resourceTranslatedId.get(), + ConsolidationEntityType.PORT, + ToscaConstants.LINK_REQUIREMENT_ID, requirementAssignment); + } + } + } else { + logger.warn("Heat resource: '" + translateTo.getResourceId() + "' with type: '" + + translateTo.getResource().getType() + + "' include '" + HeatConstants.VIRTUAL_NETWORK_REFS_PROPERTY_NAME + + "' property which is connect to " + + "unsupported/incorrect resource with type '" + + networkResource.getType() + + "', therefore, this connection will be ignored in TOSCA translation."); + } + } else { + Optional attachedResourceId = HeatToToscaUtil + .extractAttachedResourceId(translateTo.getHeatFileName(), + translateTo.getHeatOrchestrationTemplate(), translateTo.getContext(), + virtualNetworkRef); + if (attachedResourceId.isPresent() && attachedResourceId.get().isGetParam() + && attachedResourceId.get().getEntityId() instanceof String) { + TranslatedHeatResource translatedSharedResourceId = + translateTo.getContext().getHeatSharedResourcesByParam() + .get(attachedResourceId.get().getEntityId()); + if (Objects.nonNull(translatedSharedResourceId) + && !HeatToToscaUtil.isHeatFileNested(translateTo, translateTo.getHeatFileName())) { + RequirementAssignment requirementAssignment = HeatToToscaUtil.addLinkReqFromPortToNetwork( + vmiNodeTemplate, translatedSharedResourceId.getTranslatedId()); + + if (ToscaNodeType.CONTRAILV2_VIRTUAL_MACHINE_INTERFACE + .equals(vmiNodeTemplate.getType())) { + ConsolidationDataUtil.updateNodesConnectedOut(translateTo, translatedSharedResourceId + .getTranslatedId(), ConsolidationEntityType.PORT, + ToscaConstants.LINK_REQUIREMENT_ID, + requirementAssignment); + } + } + } + } + + mdcDataDebugMessage.debugExitMessage(null, null); + } + + /** + * Check if the input heat resource is Vlan sub interface resource + * + * @param resource heat resource to be checked + * @return true - if input resource is valn sub interface resource flase - otherwise. + */ + public boolean isVlanSubInterfaceResource(Resource resource) { + + if (resource.getType().equals(HeatResourcesTypes + .CONTRAIL_V2_VIRTUAL_MACHINE_INTERFACE_RESOURCE_TYPE.getHeatResource()) + && getVlanTagPropertyValue(resource).isPresent()) { + return true; + } + + return false; + } + + private Optional getVlanTagPropertyValue(Resource resource) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + Object vmiProperties = resource.getProperties() + .get(HeatConstants.VMI_PROPERTIES_PROPERTY_NAME); + if (vmiProperties != null && vmiProperties instanceof Map) { + mdcDataDebugMessage.debugExitMessage(null, null); + return Optional.ofNullable(((Map) vmiProperties) + .get(HeatConstants.VMI_SUB_INTERFACE_VLAN_TAG_PROPERTY_NAME)); + } + + mdcDataDebugMessage.debugExitMessage(null, null); + return Optional.empty(); + } + + +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/helper/FunctionTranslationHelper.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/helper/FunctionTranslationHelper.java new file mode 100644 index 0000000000..c06892046f --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/helper/FunctionTranslationHelper.java @@ -0,0 +1,47 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.translator.services.heattotosca.helper; + +/** + * @author SHIRIA + * @since December 15, 2016. + */ +public class FunctionTranslationHelper { + + private static final String UNSUPPORTED_RESOURCE = "UNSUPPORTED_RESOURCE_"; + private static final String UNSUPPORTED_ATTRIBUTE = "UNSUPPORTED_ATTRIBUTE_"; + + public static boolean isResourceSupported(String translatedResourceId) { + return !translatedResourceId.startsWith(UNSUPPORTED_RESOURCE); + } + + public static boolean isAttributeSupported(String translatedAttName) { + return !translatedAttName.startsWith(UNSUPPORTED_ATTRIBUTE); + } + + public static String getUnsupportedResourcePrefix() { + return UNSUPPORTED_RESOURCE; + } + + public static String getUnsupportedAttributePrefix() { + return UNSUPPORTED_ATTRIBUTE; + } +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/helper/NameExtractorService.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/helper/NameExtractorService.java deleted file mode 100644 index ed338e2bf5..0000000000 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/helper/NameExtractorService.java +++ /dev/null @@ -1,33 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.translator.services.heattotosca.helper; - -import java.util.List; -import java.util.Map; -import java.util.Optional; - -public interface NameExtractorService { - Optional extractNodeTypeNameByPropertiesPriority( - Map properties,List propertiesRegexMatchers); - - PropertyRegexMatcher getPropertyRegexMatcher(String propertyName, List regexMatchers, - String propertyValueSearchTerm); -} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/helper/PropertyRegexMatcher.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/helper/PropertyRegexMatcher.java deleted file mode 100644 index b04234b413..0000000000 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/helper/PropertyRegexMatcher.java +++ /dev/null @@ -1,69 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.translator.services.heattotosca.helper; - -import org.apache.commons.collections.CollectionUtils; - -import java.util.ArrayList; -import java.util.List; -import java.util.regex.Pattern; - -public class PropertyRegexMatcher { - private String propertyName; - private List regexPatterns; - private String stringToSearchForPropertyValue; - - public String getPropertyName() { - return propertyName; - } - - public void setPropertyName(String propertyName) { - this.propertyName = propertyName; - } - - /** - * Sets regex. - * - * @param regexPatterns the regex patterns - */ - public void setRegex(List regexPatterns) { - if (CollectionUtils.isEmpty(this.regexPatterns)) { - this.regexPatterns = new ArrayList<>(); - } - - for (String regexPattern : regexPatterns) { - this.regexPatterns.add(Pattern.compile(regexPattern)); - } - } - - public List getRegexPatterns() { - return regexPatterns; - } - - public String getStringToSearchForPropertyValue() { - return stringToSearchForPropertyValue; - } - - public void setStringToSearchForPropertyValue(String stringToSearchForPropertyValue) { - this.stringToSearchForPropertyValue = stringToSearchForPropertyValue; - } - -} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/helper/ResourceTranslationNeutronPortHelper.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/helper/ResourceTranslationNeutronPortHelper.java new file mode 100644 index 0000000000..a99c95c148 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/helper/ResourceTranslationNeutronPortHelper.java @@ -0,0 +1,202 @@ +package org.openecomp.sdc.translator.services.heattotosca.helper; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; + +public class ResourceTranslationNeutronPortHelper { + + public static final String IP_COUNT_REQUIRED = "ip_count_required"; + public static final String FLOATING_IP_COUNT_REQUIRED = "floating_ip_count_required"; + public static final String NETWORK = "network"; + public static final String NETWORK_ROLE_TAG = "network_role_tag"; + public static final String FIXED_IPS = "fixed_ips"; + public static final String IP_VERSION = "ip_version"; + public static final String IP_ADDRESS = "ip_address"; + public static final String GET_INPUT = "get_input"; + public static final String ALLOWED_ADDRESS_PAIRS = "allowed_address_pairs"; + public static final String FLOATING_IP = "_floating_ip"; + public static final String FLOATING_V6_IP = "_floating_v6_ip"; + public static final String IPS = "_ips"; + public static final String V6_IPS = "_v6_ips"; + public static final String NET_NAME = "_net_name"; + public static final String NET_ID = "_net_id"; + public static final String NET_FQDN = "_net_fqdn"; + public static final String IPV4_REGEX = "\\w*_ip_\\d+"; + public static final String IPV6_REGEX = "\\w*_v6_ip_\\d+"; + public static final String MAC_COUNT_REQUIRED = "mac_count_required"; + public static final String MAC_ADDRESS = "mac_address"; + public static final String IS_REQUIRED = "is_required"; + public static final String IP_REQUIREMENTS = "ip_requirements"; + public static final String MAC_REQUIREMENTS = "mac_requirements"; + + public void setAdditionalProperties(Map properties) { + setNetworkRoleTag(properties); + Map ipRequirements = new HashMap(); + Map macRequirements = new HashMap(); + Map isRequired = new HashMap(); + Map floatingIsRequired = new HashMap(); + Map macIsRequired = new HashMap(); + + isRequired.put(IS_REQUIRED, Boolean.FALSE); + floatingIsRequired.put(IS_REQUIRED, Boolean.FALSE); + macIsRequired.put(IS_REQUIRED, Boolean.FALSE); + + ipRequirements.put(IP_COUNT_REQUIRED, isRequired); + ipRequirements.put(FLOATING_IP_COUNT_REQUIRED, floatingIsRequired); + ipRequirements.put(IP_VERSION, 4); + macRequirements.put(MAC_COUNT_REQUIRED, macIsRequired); + + List> ipRequirementsList = new ArrayList<>(); + ipRequirementsList.add(ipRequirements); + properties.put(IP_REQUIREMENTS , ipRequirementsList); + + properties.put(MAC_REQUIREMENTS , macRequirements); + + setIpVersion(properties); + setFloatingIpVersion(properties); + + setMacCount(properties); + } + + private void setMacCount(Map properties) { + if(properties.containsKey(MAC_ADDRESS)) { + Map macRequirements = (Map) properties.get(MAC_REQUIREMENTS); + Map macIsRequired = new HashMap(); + macIsRequired.put(IS_REQUIRED, Boolean.TRUE); + macRequirements.put(MAC_COUNT_REQUIRED, macIsRequired); + properties.put(MAC_REQUIREMENTS, macRequirements); + } + } + + private void setFloatingIpVersion(Map properties) { + List> ipRequirementsList = + (List>) properties.get(IP_REQUIREMENTS); + Map ipRequirements = ipRequirementsList.get(0); + Object propertyValue; + Map isRequired = new HashMap(); + isRequired.put(IS_REQUIRED, Boolean.TRUE); + + propertyValue = properties.get(ALLOWED_ADDRESS_PAIRS); + if (propertyValue instanceof Map && !((Map) propertyValue).isEmpty()) { + Map.Entry mapEntry = + (Map.Entry) ((Map) propertyValue).entrySet().iterator().next(); + if (getFloatingIpVersion(mapEntry.getValue()) != null) { + ipRequirements.put(IP_VERSION, getFloatingIpVersion(mapEntry.getValue())); + ipRequirements.put(FLOATING_IP_COUNT_REQUIRED, isRequired); + } + } + else if (propertyValue instanceof List && !((List) propertyValue).isEmpty()) { + for (int i = 0; i < ((List) propertyValue).size(); i++) { + Object ipMap = ((List) propertyValue).get(i); + if(ipMap instanceof Map && !((Map) ipMap).isEmpty()) { + Object ipAddressMap = ((Map) ipMap).get(IP_ADDRESS); + if (ipAddressMap instanceof Map && !((Map) ipAddressMap).isEmpty()) { + Object ipList = ((Map) ipAddressMap).get(GET_INPUT); + if (ipList instanceof String && !((String) ipList).isEmpty()) { + if (getFloatingIpVersion(ipList) != null) { + ipRequirements.put(IP_VERSION, getFloatingIpVersion(ipList)); + ipRequirements.put(FLOATING_IP_COUNT_REQUIRED, isRequired); + } + } + } + } + } + } + } + + private void setIpVersion(Map properties) { + List> ipRequirementsList = + (List>) properties.get(IP_REQUIREMENTS); + Map ipRequirements = ipRequirementsList.get(0); + Object propertyValue; + Map isRequired = new HashMap(); + isRequired.put(IS_REQUIRED, Boolean.TRUE); + + propertyValue = properties.get(FIXED_IPS); + if (propertyValue instanceof Map && !((Map) propertyValue).isEmpty()) { + Map.Entry mapEntry = + (Map.Entry) ((Map) propertyValue).entrySet().iterator().next(); + if (getIpVersion(mapEntry.getValue()) != null) { + ipRequirements.put(IP_VERSION, getIpVersion(mapEntry.getValue())); + ipRequirements.put(IP_COUNT_REQUIRED, isRequired); + } + } + else if (propertyValue instanceof List && !((List) propertyValue).isEmpty()) { + for (int i = 0; i < ((List) propertyValue).size(); i++) { + Object ipMap = ((List) propertyValue).get(i); + if(ipMap instanceof Map && !((Map) ipMap).isEmpty()) { + Object ipAddressMap = ((Map) ipMap).get(IP_ADDRESS); + if (ipAddressMap instanceof Map && !((Map) ipAddressMap).isEmpty()) { + Object ipList = ((Map) ipAddressMap).get(GET_INPUT); + if (ipList instanceof List && !((List) ipList).isEmpty()) { + if (getIpVersion(((List) ipList).get(0)) != null) { + ipRequirements.put(IP_VERSION, getIpVersion(((List) ipList).get(0))); + ipRequirements.put(IP_COUNT_REQUIRED, isRequired); + } + } + else if (ipList instanceof String && !((String) ipList).isEmpty()) { + if (getIpVersion(ipList) != null) { + ipRequirements.put(IP_VERSION, getIpVersion(ipList)); + ipRequirements.put(IP_COUNT_REQUIRED, isRequired); + } + } + } + } + } + } + } + + private void setNetworkRoleTag(Map properties) { + Object propertyValue = properties.get(NETWORK); + if (propertyValue instanceof Map && !((Map) propertyValue).isEmpty()) { + Map.Entry mapEntry = + (Map.Entry) ((Map) propertyValue).entrySet().iterator().next(); + if (mapEntry.getValue() instanceof String && getNetworkRole(mapEntry.getValue())!=null) { + properties.put(NETWORK_ROLE_TAG, getNetworkRole(mapEntry.getValue())); + } + } + } + + private Object getFloatingIpVersion(Object value) { + Object ipVersion = null; + if(value instanceof String) { + if (((String) value).endsWith(FLOATING_V6_IP)) { + ipVersion = 6; + } + else { + ipVersion = 4; + } + } + return ipVersion; + } + + private Object getIpVersion(Object value) { + Object ipVersion = null; + if(value instanceof String) { + if (((String) value).endsWith(V6_IPS) || ((String) value).matches(IPV6_REGEX)) { + ipVersion = 6; + } + else { + ipVersion = 4; + } + } + return ipVersion; + } + + private Object getNetworkRole(String value) { + Object networkRole = null; + if(value.endsWith(NET_NAME)) { + networkRole = (Object) value.substring(0, value.length() - NET_NAME.length()); + } + else if(value.endsWith(NET_ID)) { + networkRole = (Object) value.substring(0, value.length() - NET_ID.length()); + } + else if(value.endsWith(NET_FQDN)) { + networkRole = (Object) value.substring(0, value.length() - NET_FQDN.length()); + } + return networkRole; + } +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/helper/VolumeTranslationHelper.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/helper/VolumeTranslationHelper.java index ebd38c89d2..5f4e40a4b2 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/helper/VolumeTranslationHelper.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/helper/VolumeTranslationHelper.java @@ -20,20 +20,23 @@ package org.openecomp.sdc.translator.services.heattotosca.helper; +import static org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes.CINDER_VOLUME_RESOURCE_TYPE; + import org.apache.commons.collections4.CollectionUtils; +import org.openecomp.sdc.common.utils.CommonUtil; +import org.openecomp.sdc.logging.api.Logger; import org.openecomp.core.utilities.yaml.YamlUtil; import org.openecomp.sdc.heat.datatypes.manifest.FileData; import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate; -import org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes; import org.openecomp.sdc.heat.datatypes.model.Output; import org.openecomp.sdc.heat.datatypes.model.Resource; +import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; import org.openecomp.sdc.translator.datatypes.heattotosca.AttachedResourceId; import org.openecomp.sdc.translator.datatypes.heattotosca.to.ResourceFileDataAndIDs; import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; -import org.openecomp.sdc.translator.services.heattotosca.TranslationContext; -import org.openecomp.sdc.translator.services.heattotosca.impl.ResourceTranslationBase; -import org.slf4j.Logger; +import org.openecomp.sdc.translator.datatypes.heattotosca.TranslationContext; +import org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation.ResourceTranslationBase; import java.util.ArrayList; import java.util.List; @@ -45,6 +48,7 @@ import java.util.stream.Collectors; public class VolumeTranslationHelper { private final Logger logger; + private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); public VolumeTranslationHelper(Logger logger) { this.logger = logger; @@ -63,22 +67,34 @@ public class VolumeTranslationHelper { String resourceId, TranslateTo translateTo, FileData.Type... types) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + if (CollectionUtils.isEmpty(filesToSearch)) { + mdcDataDebugMessage.debugExitMessage(null, null); return Optional.empty(); } - List fileDatas = Objects.isNull(types) ? filesToSearch - : HeatToToscaUtil.getFilteredListOfFileDataByTypes(filesToSearch, types); + List fileDatas = Objects.isNull(types) ? filesToSearch : HeatToToscaUtil + .getFilteredListOfFileDataByTypes(filesToSearch, types); Optional fileDataAndIDs = getResourceFileDataAndIDsForVolumeConnection(resourceId, translateTo, fileDatas); if (fileDataAndIDs.isPresent()) { + mdcDataDebugMessage.debugExitMessage(null, null); return fileDataAndIDs; } + + mdcDataDebugMessage.debugExitMessage(null, null); return Optional.empty(); } private Optional getResourceFileDataAndIDsForVolumeConnection( String resourceId, TranslateTo translateTo, List fileDatas) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + for (FileData data : fileDatas) { HeatOrchestrationTemplate heatOrchestrationTemplate = new YamlUtil() .yamlToObject(translateTo.getContext().getFiles().getFileContent(data.getFile()), @@ -108,13 +124,15 @@ public class VolumeTranslationHelper { } else { logger.warn( "output: '" + resourceId + "' in file '" + data.getFile() + "' is not of type '" - + HeatResourcesTypes.CINDER_VOLUME_RESOURCE_TYPE.getHeatResource() + "'"); + + CINDER_VOLUME_RESOURCE_TYPE.getHeatResource() + "'"); } } } else { logger.warn("output: '" + resourceId + "' in file '" + data.getFile() + "' is not found"); } } + + mdcDataDebugMessage.debugExitMessage(null, null); return Optional.empty(); } @@ -122,14 +140,16 @@ public class VolumeTranslationHelper { HeatOrchestrationTemplate heatOrchestrationTemplate, String translatedId) { return getResourceByTranslatedResourceId(data.getFile(), heatOrchestrationTemplate, - translatedId, translateTo, - HeatResourcesTypes.CINDER_VOLUME_RESOURCE_TYPE.getHeatResource()) - .isPresent(); + translatedId, translateTo, CINDER_VOLUME_RESOURCE_TYPE.getHeatResource()).isPresent(); } private Optional>> getResourceByTranslatedResourceId( String fileName, HeatOrchestrationTemplate heatOrchestrationTemplate, String translatedResourceId, TranslateTo translateTo, String heatResourceType) { + + + mdcDataDebugMessage.debugEntryMessage("file", fileName); + List> list = heatOrchestrationTemplate.getResources().entrySet() .stream() .filter( @@ -139,8 +159,10 @@ public class VolumeTranslationHelper { .allMatch(p -> p.test(entry))) .collect(Collectors.toList()); if (CollectionUtils.isEmpty(list)) { + mdcDataDebugMessage.debugExitMessage("file", fileName); return Optional.empty(); } else { + mdcDataDebugMessage.debugExitMessage("file", fileName); return Optional.of(list); } } @@ -165,7 +187,7 @@ public class VolumeTranslationHelper { return true; } else { logger.warn("output: '" + resourceId + "' in file '" + data.getFile() - + "' is not defined as get_resource and therefor not supported."); + + "' is not defined as get_resource and therefore not supported as shared resource."); return false; } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/helper/impl/NameExtractorServiceImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/helper/impl/NameExtractorServiceImpl.java index 9bd3494698..3867dadaeb 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/helper/impl/NameExtractorServiceImpl.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/helper/impl/NameExtractorServiceImpl.java @@ -17,79 +17,3 @@ * limitations under the License. * ============LICENSE_END========================================================= */ - -package org.openecomp.sdc.translator.services.heattotosca.helper.impl; - -import org.openecomp.sdc.translator.datatypes.heattotosca.AttachedResourceId; -import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; -import org.openecomp.sdc.translator.services.heattotosca.helper.NameExtractorService; -import org.openecomp.sdc.translator.services.heattotosca.helper.PropertyRegexMatcher; - -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.regex.Pattern; - -public class NameExtractorServiceImpl implements NameExtractorService { - - @Override - public Optional extractNodeTypeNameByPropertiesPriority( - Map properties,List propertiesRegexMatchers) { - for (PropertyRegexMatcher propertyRegexMatcher : propertiesRegexMatchers) { - Optional parameterNameValue = - getPropertyParameterNameValue(properties, propertyRegexMatcher.getPropertyName()); - if (parameterNameValue.isPresent()) { - if (isPropertyValueMatchNamingConvention(propertyRegexMatcher, parameterNameValue.get())) { - return Optional.of(parameterNameValue.get().substring(0, parameterNameValue.get() - .lastIndexOf(propertyRegexMatcher.getStringToSearchForPropertyValue()))); - } - } - } - - return Optional.empty(); - } - - private boolean isPropertyValueMatchNamingConvention(PropertyRegexMatcher propertyRegexMatcher, - String propertyValue) { - for (Pattern pattern : propertyRegexMatcher.getRegexPatterns()) { - if (pattern.matcher(propertyValue).matches()) { - return true; - } - } - return false; - } - - private Optional getPropertyParameterNameValue(Map properties, - String prop) { - Object propObj = properties.get(prop); - Optional property = HeatToToscaUtil.extractProperty(propObj); - if (property.isPresent()) { - AttachedResourceId extractedProperty = property.get(); - return getParameterName(extractedProperty); - } - return Optional.empty(); - } - - private Optional getParameterName(AttachedResourceId extractedProperty) { - if (!extractedProperty.isGetParam()) { - return Optional.empty(); - } - Object entityId = extractedProperty.getEntityId(); - if (entityId instanceof String) { - return Optional.of((String) entityId); - } else { - return Optional.of((String) ((List) entityId).get(0)); - } - } - - @Override - public PropertyRegexMatcher getPropertyRegexMatcher(String propertyName, - List regexMatchers, - String propertyValueSearchTerm) { - PropertyRegexMatcher propertyRegexMatcher = new PropertyRegexMatcher(); - propertyRegexMatcher.setPropertyName(propertyName); - propertyRegexMatcher.setRegex(regexMatchers); - propertyRegexMatcher.setStringToSearchForPropertyValue(propertyValueSearchTerm); - return propertyRegexMatcher; - } -} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/BaseResourceConnection.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/BaseResourceConnection.java deleted file mode 100644 index d901ae9c98..0000000000 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/BaseResourceConnection.java +++ /dev/null @@ -1,174 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.translator.services.heattotosca.impl; - -import org.apache.commons.collections4.MapUtils; -import org.openecomp.core.utilities.yaml.YamlUtil; -import org.openecomp.sdc.common.errors.CoreException; -import org.openecomp.sdc.common.errors.ErrorCategory; -import org.openecomp.sdc.common.errors.ErrorCode; -import org.openecomp.sdc.heat.datatypes.manifest.FileData; -import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate; -import org.openecomp.sdc.heat.datatypes.model.Resource; -import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; -import org.openecomp.sdc.tosca.datatypes.model.NodeType; -import org.openecomp.sdc.tosca.datatypes.model.RequirementAssignment; -import org.openecomp.sdc.tosca.datatypes.model.RequirementDefinition; -import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; -import org.openecomp.sdc.tosca.services.DataModelUtil; -import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; -import org.openecomp.sdc.translator.services.heattotosca.errors.TranslatorErrorCodes; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.function.Predicate; - -abstract class BaseResourceConnection { - protected static Logger logger = - LoggerFactory.getLogger(ResourceTranslationCinderVolumeAttachmentImpl.class); - protected TranslateTo translateTo; - FileData nestedFileData; - NodeTemplate substitutionNodeTemplate; - NodeType nodeType; - ResourceTranslationBase resourceTranslationBase; - - BaseResourceConnection(ResourceTranslationBase resourceTranslationBase, TranslateTo translateTo, - FileData nestedFileData, NodeTemplate substitutionNodeTemplate, - NodeType nodeType) { - this.translateTo = translateTo; - this.nestedFileData = nestedFileData; - this.substitutionNodeTemplate = substitutionNodeTemplate; - this.nodeType = nodeType; - this.resourceTranslationBase = resourceTranslationBase; - } - - abstract boolean isDesiredNodeTemplateType(NodeTemplate nodeTemplate); - - abstract List> getPredicatesListForConnectionPoints(); - - abstract Optional> getConnectorParamName(String heatResourceId, - Resource heatResource, - HeatOrchestrationTemplate - nestedHeatOrchestrationTemplate); - - abstract String getDesiredResourceType(); - - abstract String getTranslatedResourceIdFromSubstitutionMapping( - ServiceTemplate nestedServiceTemplate, Map.Entry entry); - - abstract void addRequirementToConnectResources(Map.Entry entry, - List paramNames); - - abstract List> getAllConnectionPoints(); - - void connect() { - ServiceTemplate nestedServiceTemplate = translateTo.getContext().getTranslatedServiceTemplates() - .get(translateTo.getResource().getType()); - List paramNames = null; - HeatOrchestrationTemplate nestedHeatOrchestrationTemplate = new YamlUtil() - .yamlToObject(translateTo.getContext().getFileContent(nestedFileData.getFile()), - HeatOrchestrationTemplate.class); - List> exposedConnectionPoints = getAllConnectionPoints(); - for (Map connectionPointsMap : exposedConnectionPoints) { - for (Map.Entry entry : connectionPointsMap.entrySet()) { - String translatedResourceId = - getTranslatedResourceIdFromSubstitutionMapping(nestedServiceTemplate, entry); - NodeTemplate nodeTemplate = nestedServiceTemplate.getTopology_template().getNode_templates() - .get(translatedResourceId); - if (!isDesiredNodeTemplateType(nodeTemplate)) { - continue; - } - paramNames = createResourcesConnection(translatedResourceId, paramNames, - nestedHeatOrchestrationTemplate, entry); - } - } - } - - private List createResourcesConnection(String translatedResourceId, - List paramNames, - HeatOrchestrationTemplate - nestedHeatOrchestrationTemplate, - Map.Entry entry) { - List params = paramNames; - Optional>> heatResources = - getResourceByTranslatedResourceId(translatedResourceId, nestedHeatOrchestrationTemplate); - if (heatResources.isPresent()) { - params = - addRequirementAndGetConnectorParamsFromResourceProperties(nestedHeatOrchestrationTemplate, - entry, params, heatResources.get()); - } - return params; - } - - private List addRequirementAndGetConnectorParamsFromResourceProperties( - HeatOrchestrationTemplate nestedHeatOrchestrationTemplate, Map.Entry entry, - List params, List> heatResources) { - Resource heatResource; - for (Map.Entry resourceEntry : heatResources) { - heatResource = resourceEntry.getValue(); - if (!MapUtils.isEmpty(heatResource.getProperties())) { - Optional> connectorParamName = - getConnectorParamName(resourceEntry.getKey(), heatResource, - nestedHeatOrchestrationTemplate); - if (!connectorParamName.isPresent()) { - break; - } else { - params = connectorParamName.get(); - } - } - Objects.requireNonNull(params); - addRequirementToConnectResources(entry, params); - } - return params; - } - - protected Optional>> getResourceByTranslatedResourceId( - String translatedResourceId, HeatOrchestrationTemplate nestedHeatOrchestrationTemplate) { - Optional>> resourceByTranslatedResourceId = - resourceTranslationBase.getResourceByTranslatedResourceId(nestedFileData.getFile(), - nestedHeatOrchestrationTemplate, translatedResourceId, translateTo, - getDesiredResourceType()); - if (!resourceByTranslatedResourceId.isPresent()) { - throw new CoreException((new ErrorCode.ErrorCodeBuilder()).withMessage( - "Failed to get original resource from heat for translate resource id '" - + translatedResourceId + "'") - .withId(TranslatorErrorCodes.HEAT_TO_TOSCA_MAPPING_COLLISION) - .withCategory(ErrorCategory.APPLICATION).build()); - } - return resourceByTranslatedResourceId; - } - - void createRequirementAssignment(Map.Entry entry, String node, - NodeTemplate nodeTemplate) { - if (Objects.nonNull(node)) { - RequirementAssignment requirementAssignment; - requirementAssignment = new RequirementAssignment(); - requirementAssignment.setRelationship(entry.getValue().getRelationship()); - requirementAssignment.setCapability(entry.getValue().getCapability()); - requirementAssignment.setNode(node); - DataModelUtil.addRequirementAssignment(nodeTemplate, entry.getKey(), requirementAssignment); - } - } -} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ContrailV2VmInterfaceToNetResourceConnection.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ContrailV2VmInterfaceToNetResourceConnection.java deleted file mode 100644 index 890d2a76af..0000000000 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ContrailV2VmInterfaceToNetResourceConnection.java +++ /dev/null @@ -1,139 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.translator.services.heattotosca.impl; - -import org.openecomp.sdc.heat.datatypes.manifest.FileData; -import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate; -import org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes; -import org.openecomp.sdc.heat.datatypes.model.Resource; -import org.openecomp.sdc.tosca.datatypes.ToscaCapabilityType; -import org.openecomp.sdc.tosca.datatypes.ToscaNodeType; -import org.openecomp.sdc.tosca.datatypes.ToscaRelationshipType; -import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; -import org.openecomp.sdc.tosca.datatypes.model.NodeType; -import org.openecomp.sdc.tosca.datatypes.model.RequirementDefinition; -import org.openecomp.sdc.translator.datatypes.heattotosca.AttachedResourceId; -import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; -import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslatedHeatResource; -import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; - -import java.util.ArrayList; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.function.Predicate; - -public class ContrailV2VmInterfaceToNetResourceConnection extends PortToNetResourceConnection { - - public ContrailV2VmInterfaceToNetResourceConnection( - ResourceTranslationBase resourceTranslationBase, TranslateTo translateTo, - FileData nestedFileData, NodeTemplate substitutionNodeTemplate, NodeType nodeType) { - super(resourceTranslationBase, translateTo, nestedFileData, substitutionNodeTemplate, nodeType); - } - - @Override - protected boolean isDesiredNodeTemplateType(NodeTemplate nodeTemplate) { - return nodeTemplate.getType() - .equals(ToscaNodeType.CONTRAILV2_VIRTUAL_MACHINE_INTERFACE.getDisplayName()); - } - - @Override - protected Optional> getConnectorParamName(String heatResourceId, - Resource heatResource, - HeatOrchestrationTemplate nestedHeatOrchestrationTemplate) { - List networks = new ArrayList<>(); - Object virtualNetworkRefs = heatResource.getProperties().get("virtual_network_refs"); - if (Objects.isNull(virtualNetworkRefs) || !(virtualNetworkRefs instanceof List) - || ((List) virtualNetworkRefs).size() == 0) { - return Optional.empty(); - } - if (((List) virtualNetworkRefs).size() > 1) { - logger.warn("Heat resource: '" + translateTo.getResourceId() + "' with nested heat file: '" - + translateTo.getResource().getType() - + "' has resource '" + heatResourceId + "' with type '" - + HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_MACHINE_INTERFACE_RESOURCE_TYPE.getHeatResource() - + "' which include 'virtual_network_refs' property with more than one network values, " - + "only the first network will be translated, all rest will be ignored in TOSCA " - + "translation."); - } - Object virtualNetworkRef = ((List) virtualNetworkRefs).get(0); - Optional network = HeatToToscaUtil - .extractAttachedResourceId(nestedFileData.getFile(), nestedHeatOrchestrationTemplate, - translateTo.getContext(), virtualNetworkRef); - if (network.isPresent() && network.get().isGetParam()) { - networks.add((String) network.get().getEntityId()); - } - return Optional.of(networks); - } - - @Override - protected String getDesiredResourceType() { - return HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_MACHINE_INTERFACE_RESOURCE_TYPE.getHeatResource(); - } - - @Override - protected void addRequirementToConnectResources(Map.Entry entry, - List paramNames) { - for (String paramName : paramNames) { - Object paramValue = translateTo.getResource().getProperties().get(paramName); - String contrailAttachedResourceId = - HeatToToscaUtil.extractContrailGetResourceAttachedHeatResourceId(paramValue); - Optional node; - if (contrailAttachedResourceId != null) { // contrail get resource - node = ResourceTranslationBase.getResourceTranslatedId(translateTo.getHeatFileName(), - translateTo.getHeatOrchestrationTemplate(), contrailAttachedResourceId, - translateTo.getContext()); - if (node.isPresent()) { - createRequirementAssignment(entry, node.get(), substitutionNodeTemplate); - } - } else { - Optional attachedResourceId = - HeatToToscaUtil.extractAttachedResourceId(translateTo, paramName); - if (!attachedResourceId.isPresent()) { - return; - } - AttachedResourceId resourceId = attachedResourceId.get(); - if (resourceId.isGetParam()) { - TranslatedHeatResource shareResource = - translateTo.getContext().getHeatSharedResourcesByParam() - .get(resourceId.getEntityId()); - if (Objects.nonNull(shareResource) - && !HeatToToscaUtil.isHeatFileNested(translateTo, translateTo.getHeatFileName())) { - createRequirementAssignment(entry, shareResource.getTranslatedId(), - substitutionNodeTemplate); - } - } - } - } - } - - @Override - protected List> getPredicatesListForConnectionPoints() { - ArrayList> predicates = new ArrayList<>(); - predicates.add( - req -> req.getCapability().equals(ToscaCapabilityType.NETWORK_LINKABLE.getDisplayName()) - && req.getNode().equals(ToscaNodeType.ROOT.getDisplayName()) - && req.getRelationship().equals(ToscaRelationshipType.NETWORK_LINK_TO.getDisplayName()) - ); - return predicates; - } -} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/NovaAndPortResourceConnectionHelper.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/NovaAndPortResourceConnectionHelper.java deleted file mode 100644 index bc60a24223..0000000000 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/NovaAndPortResourceConnectionHelper.java +++ /dev/null @@ -1,106 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.translator.services.heattotosca.impl; - -import org.openecomp.sdc.heat.datatypes.manifest.FileData; -import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate; -import org.openecomp.sdc.heat.datatypes.model.Resource; -import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; -import org.openecomp.sdc.tosca.datatypes.model.NodeType; -import org.openecomp.sdc.tosca.datatypes.model.RequirementDefinition; -import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; -import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.function.Predicate; - -public class NovaAndPortResourceConnectionHelper - extends BaseResourceConnection { - public NovaAndPortResourceConnectionHelper(ResourceTranslationBase resourceTranslationBase, - TranslateTo translateTo, FileData nestedFileData, - NodeTemplate substitutionNodeTemplate, - NodeType nodeType) { - super(resourceTranslationBase, translateTo, nestedFileData, substitutionNodeTemplate, nodeType); - } - - @Override - boolean isDesiredNodeTemplateType(NodeTemplate nodeTemplate) { - return false; - } - - @Override - List> getPredicatesListForConnectionPoints() { - return null; - } - - @Override - Optional> getConnectorParamName(String heatResourceId, - Resource heatResource, - HeatOrchestrationTemplate - nestedHeatOrchestrationTemplate) { - return null; - } - - @Override - String getDesiredResourceType() { - return null; - } - - @Override - String getTranslatedResourceIdFromSubstitutionMapping( - ServiceTemplate nestedServiceTemplate,Map.Entry entry) { - return null; - } - - @Override - void addRequirementToConnectResources(Map.Entry entry, - List paramNames) { - - } - - @Override - List> getAllConnectionPoints() { - List> exposedRequirementsList = new ArrayList<>(); - List> predicates = getPredicatesListForConnectionPoints(); - List> requirements = this.nodeType.getRequirements(); - if (requirements == null) { - return exposedRequirementsList; - } - requirements.stream() - .map(Map::entrySet) - .forEach(x -> x.stream() - .filter(entry -> predicates - .stream() - .anyMatch(p -> p.test(entry.getValue()))) - .forEach(entry -> { - Map exposedRequirementsMap = new HashMap<>(); - exposedRequirementsMap.put(entry.getKey(), entry.getValue()); - exposedRequirementsList.add(exposedRequirementsMap); - })); - - return exposedRequirementsList; - } -} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/NovaToVolResourceConnection.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/NovaToVolResourceConnection.java deleted file mode 100644 index 8bab0dbc50..0000000000 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/NovaToVolResourceConnection.java +++ /dev/null @@ -1,228 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.translator.services.heattotosca.impl; - -import org.apache.commons.collections4.CollectionUtils; -import org.apache.commons.lang3.StringUtils; -import org.openecomp.sdc.common.errors.CoreException; -import org.openecomp.sdc.heat.datatypes.manifest.FileData; -import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate; -import org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes; -import org.openecomp.sdc.heat.datatypes.model.Resource; -import org.openecomp.sdc.tosca.datatypes.ToscaCapabilityType; -import org.openecomp.sdc.tosca.datatypes.ToscaNodeType; -import org.openecomp.sdc.tosca.datatypes.ToscaRelationshipType; -import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel; -import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; -import org.openecomp.sdc.tosca.datatypes.model.NodeType; -import org.openecomp.sdc.tosca.datatypes.model.RequirementDefinition; -import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; -import org.openecomp.sdc.tosca.services.ToscaAnalyzerService; -import org.openecomp.sdc.tosca.services.impl.ToscaAnalyzerServiceImpl; -import org.openecomp.sdc.translator.datatypes.heattotosca.AttachedResourceId; -import org.openecomp.sdc.translator.datatypes.heattotosca.to.ResourceFileDataAndIDs; -import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; -import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslatedHeatResource; -import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; -import org.openecomp.sdc.translator.services.heattotosca.TranslationContext; -import org.openecomp.sdc.translator.services.heattotosca.errors.MissingMandatoryPropertyErrorBuilder; -import org.openecomp.sdc.translator.services.heattotosca.helper.VolumeTranslationHelper; - -import java.util.ArrayList; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.function.Predicate; -import java.util.stream.Collectors; - -class NovaToVolResourceConnection extends NovaAndPortResourceConnectionHelper { - - public NovaToVolResourceConnection(ResourceTranslationBase resourceTranslationBase, - TranslateTo translateTo, FileData nestedFileData, - NodeTemplate substitutionNodeTemplate, NodeType nodeType) { - super(resourceTranslationBase, translateTo, nestedFileData, substitutionNodeTemplate, nodeType); - } - - @Override - boolean isDesiredNodeTemplateType(NodeTemplate nodeTemplate) { - ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl(); - ToscaServiceModel toscaServiceModel = HeatToToscaUtil.getToscaServiceModel(translateTo); - return toscaAnalyzerService.isTypeOf(nodeTemplate, ToscaNodeType.NOVA_SERVER.getDisplayName(), - translateTo.getContext().getTranslatedServiceTemplates() - .get(translateTo.getResource().getType()), toscaServiceModel); - } - - @Override - List> getPredicatesListForConnectionPoints() { - ArrayList> predicates = new ArrayList<>(); - predicates - .add(req -> req.getCapability().equals(ToscaCapabilityType.ATTACHMENT.getDisplayName()) - && req.getNode().equals(ToscaNodeType.BLOCK_STORAGE.getDisplayName()) - && req.getRelationship() - .equals(ToscaRelationshipType.NATIVE_ATTACHES_TO.getDisplayName())); - return predicates; - } - - @Override - Optional> getConnectorParamName( - String heatResourceId, Resource heatResource, - HeatOrchestrationTemplate nestedHeatOrchestrationTemplate) { - Optional volumeId = HeatToToscaUtil - .extractAttachedResourceId(nestedFileData.getFile(), nestedHeatOrchestrationTemplate, - translateTo.getContext(), heatResource.getProperties().get("volume_id")); - if (volumeId.isPresent() && volumeId.get().isGetParam()) { - return Optional.of(Collections.singletonList((String) volumeId.get().getEntityId())); - } else { - return Optional.empty(); - } - } - - @Override - String getDesiredResourceType() { - return HeatResourcesTypes.CINDER_VOLUME_ATTACHMENT_RESOURCE_TYPE.getHeatResource(); - } - - @Override - protected Optional>> getResourceByTranslatedResourceId( - String translatedResourceId, HeatOrchestrationTemplate nestedHeatOrchestrationTemplate) { - - List>> predicates = - buildPredicates(nestedFileData.getFile(), nestedHeatOrchestrationTemplate, - translatedResourceId); - List> list = - nestedHeatOrchestrationTemplate.getResources().entrySet() - .stream() - .filter(entry -> predicates - .stream() - .allMatch(p -> p.test(entry))) - .collect(Collectors.toList()); - if (CollectionUtils.isEmpty(list)) { - return Optional.empty(); - } else { - return Optional.of(list); - } - } - - private List>> buildPredicates(String fileName, - HeatOrchestrationTemplate - heatOrchestrationTemplate, - String - novaTranslatedResourceId) { - List>> list = new ArrayList<>(); - list.add(entry -> entry.getValue().getType().equals(getDesiredResourceType())); - list.add(entry -> { - Object instanceUuidProp = entry.getValue().getProperties().get("instance_uuid"); - TranslationContext context = translateTo.getContext(); - Optional instanceUuid = HeatToToscaUtil - .extractAttachedResourceId(fileName, heatOrchestrationTemplate, context, - instanceUuidProp); - if (instanceUuid.isPresent()) { - Optional resourceTranslatedId = ResourceTranslationBase - .getResourceTranslatedId(fileName, heatOrchestrationTemplate, - (String) instanceUuid.get().getTranslatedId(), context); - return resourceTranslatedId.isPresent() - && resourceTranslatedId.get().equals(novaTranslatedResourceId); - - } else { - throw new CoreException(new MissingMandatoryPropertyErrorBuilder("instance_uuid").build()); - } - }); - return list; - } - - @Override - String getTranslatedResourceIdFromSubstitutionMapping(ServiceTemplate nestedServiceTemplate, - Map.Entry entry) { - List substitutionMapping = - nestedServiceTemplate.getTopology_template().getSubstitution_mappings().getRequirements() - .get(entry.getKey()); - return substitutionMapping.get(0); - } - - @Override - void addRequirementToConnectResources(Map.Entry entry, - List paramNames) { - String paramName = paramNames.get(0); - Optional attachedResourceId = - HeatToToscaUtil.extractAttachedResourceId(translateTo, paramName); - String node; - if (!attachedResourceId.isPresent()) { - return; - } - AttachedResourceId attachedResource = attachedResourceId.get(); - if (attachedResource.isGetResource()) { - String volTranslatedId = (String) attachedResource.getTranslatedId(); - Resource volServerResource = HeatToToscaUtil - .getResource(translateTo.getHeatOrchestrationTemplate(), volTranslatedId, - translateTo.getHeatFileName()); - if (!StringUtils.equals(HeatResourcesTypes.CINDER_VOLUME_RESOURCE_TYPE.getHeatResource(), - volServerResource.getType())) { - logger.warn("Volume attachment used from nested resource " + translateTo.getResourceId() - + " is pointing to incorrect resource type(" + volServerResource.getType() - + ") for relation through the parameter '" + paramName + "." - + " The connection to the volume is ignored. " - + "Supported types are: " - + HeatResourcesTypes.CINDER_VOLUME_RESOURCE_TYPE.getHeatResource()); - return; - } - node = volTranslatedId; - createRequirementAssignment(entry, node, substitutionNodeTemplate); - } else if (attachedResource.isGetParam()) { - TranslatedHeatResource shareResource = - translateTo.getContext().getHeatSharedResourcesByParam() - .get(attachedResource.getEntityId()); - if (Objects.nonNull(shareResource) - && !HeatToToscaUtil.isHeatFileNested(translateTo, translateTo.getHeatFileName())) { - if (!StringUtils.equals(HeatResourcesTypes.CINDER_VOLUME_RESOURCE_TYPE.getHeatResource(), - shareResource.getHeatResource().getType())) { - logger.warn("Volume attachment used from nested resource " + translateTo.getResourceId() - + " is pointing to incorrect resource type(" - + shareResource.getHeatResource().getType() + ") for relation through the parameter '" - + paramName + "." - + " The connection to the volume is ignored. " - + "Supported types are: " - + HeatResourcesTypes.CINDER_VOLUME_RESOURCE_TYPE.getHeatResource()); - return; - } - node = shareResource.getTranslatedId(); - createRequirementAssignment(entry, node, substitutionNodeTemplate); - } else if (Objects.isNull(shareResource)) { - List allFilesData = translateTo.getContext().getManifest().getContent().getData(); - Optional fileData = - HeatToToscaUtil.getFileData(translateTo.getHeatFileName(), allFilesData); - if (fileData.isPresent()) { - Optional fileDataContainingResource = - new VolumeTranslationHelper(logger) - .getFileDataContainingVolume(fileData.get().getData(), - (String) attachedResource.getEntityId(), translateTo, FileData.Type.HEAT_VOL); - if (fileDataContainingResource.isPresent()) { - createRequirementAssignment(entry, - fileDataContainingResource.get().getTranslatedResourceId(), - substitutionNodeTemplate); - } - } - } - } - } -} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/PortToNetResourceConnection.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/PortToNetResourceConnection.java deleted file mode 100644 index 8adfca305e..0000000000 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/PortToNetResourceConnection.java +++ /dev/null @@ -1,200 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.translator.services.heattotosca.impl; - -import org.openecomp.sdc.heat.datatypes.manifest.FileData; -import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate; -import org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes; -import org.openecomp.sdc.heat.datatypes.model.Resource; -import org.openecomp.sdc.tosca.datatypes.ToscaCapabilityType; -import org.openecomp.sdc.tosca.datatypes.ToscaNodeType; -import org.openecomp.sdc.tosca.datatypes.ToscaRelationshipType; -import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; -import org.openecomp.sdc.tosca.datatypes.model.NodeType; -import org.openecomp.sdc.tosca.datatypes.model.RequirementDefinition; -import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; -import org.openecomp.sdc.translator.datatypes.heattotosca.AttachedResourceId; -import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; -import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslatedHeatResource; -import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.function.Predicate; - -public class PortToNetResourceConnection extends NovaAndPortResourceConnectionHelper { - - public PortToNetResourceConnection(ResourceTranslationBase resourceTranslationBase, - TranslateTo translateTo, FileData nestedFileData, - NodeTemplate substitutionNodeTemplate, NodeType nodeType) { - super(resourceTranslationBase, translateTo, nestedFileData, substitutionNodeTemplate, nodeType); - } - - @Override - protected boolean isDesiredNodeTemplateType(NodeTemplate nodeTemplate) { - return nodeTemplate.getType().equals(ToscaNodeType.NEUTRON_PORT.getDisplayName()); - } - - @Override - protected List> getPredicatesListForConnectionPoints() { - ArrayList> predicates = new ArrayList<>(); - predicates.add( - req -> req.getCapability().equals(ToscaCapabilityType.NETWORK_LINKABLE.getDisplayName()) - && req.getNode().equals(ToscaNodeType.ROOT.getDisplayName()) - && req.getRelationship().equals( - ToscaRelationshipType.NETWORK_LINK_TO.getDisplayName())); - return predicates; - } - - @Override - protected Optional> getConnectorParamName(String heatResourceId, - Resource heatResource, - HeatOrchestrationTemplate - nestedHeatOrchestrationTemplate) { - Optional network = HeatToToscaUtil - .extractAttachedResourceId(nestedFileData.getFile(), nestedHeatOrchestrationTemplate, - translateTo.getContext(), heatResource.getProperties().get("network")); - if (network.isPresent() && network.get().isGetParam()) { - return Optional.of(Collections.singletonList((String) network.get().getEntityId())); - } else { - network = HeatToToscaUtil - .extractAttachedResourceId(nestedFileData.getFile(), nestedHeatOrchestrationTemplate, - translateTo.getContext(), heatResource.getProperties().get("network_id")); - if (network.isPresent() && network.get().isGetParam()) { - return Optional.of(Collections.singletonList((String) network.get().getEntityId())); - } else { - return Optional.empty(); - } - } - } - - @Override - protected String getDesiredResourceType() { - return HeatResourcesTypes.NEUTRON_PORT_RESOURCE_TYPE.getHeatResource(); - } - - @Override - protected String getTranslatedResourceIdFromSubstitutionMapping( - ServiceTemplate nestedServiceTemplate, Map.Entry entry) { - List substitutionMapping = - nestedServiceTemplate.getTopology_template().getSubstitution_mappings().getRequirements() - .get(entry.getKey()); - return substitutionMapping.get(0); - } - - @Override - protected void addRequirementToConnectResources(Map.Entry entry, - List paramNames) { - String paramName = paramNames.get( - 0); // port can connect to one network only and - // we are expecting to have only one param(unlike security rules to port) - Object paramValue = translateTo.getResource().getProperties().get(paramName); - if (paramValue == null) { - logger.warn( - "Nested resource '" + translateTo.getResourceId() + "' is not including property '" - + paramName + "' with value for the nested heat file, therefore, '" + entry.getKey() - + "' TOSCA requirement will not be connected."); - return; - } - List supportedNetworkTypes = - Arrays.asList(HeatResourcesTypes.NEUTRON_NET_RESOURCE_TYPE.getHeatResource(), - HeatResourcesTypes.CONTRAIL_VIRTUAL_NETWORK_RESOURCE_TYPE.getHeatResource(), - HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_NETWORK_RESOURCE_TYPE.getHeatResource()); - - Optional targetTranslatedNodeId = - getConnectionTargetNodeUsingGetResourceFunc(entry, paramName, paramValue, - supportedNetworkTypes); - if (targetTranslatedNodeId.isPresent()) { - createRequirementAssignment(entry, targetTranslatedNodeId.get(), substitutionNodeTemplate); - } else { - targetTranslatedNodeId = - getConnectionTargetNodeUsingGetParam(entry, paramName, supportedNetworkTypes); - if (targetTranslatedNodeId.isPresent()) { - createRequirementAssignment(entry, targetTranslatedNodeId.get(), substitutionNodeTemplate); - } - } - } - - private boolean validateResourceTypeSupportedForReqCreation(String sourceResourceId, - final String sourcePropertyName, - String sourceReqId, - Resource targetResource, - List supportedTypes) { - if (!resourceTranslationBase.isResourceTypeSupported(targetResource, supportedTypes)) { - logger.warn("Nested resource '" + sourceResourceId + "' property '" + sourcePropertyName - + "' is pointing to a resource with type '" + targetResource.getType() - + "' which is not supported for requirement '" + sourceReqId - + "' that connect port to network. \nSupported types are: '" + supportedTypes.toString() - + "', therefore, this TOSCA requirement will not be connected."); - return false; - } - return true; - } - - private Optional getConnectionTargetNodeUsingGetParam( - Map.Entry requirementDefinitionEntry, String paramName, - List supportedTargetNodeTypes) { - Optional attachedResourceId = - HeatToToscaUtil.extractAttachedResourceId(translateTo, paramName); - if (!attachedResourceId.isPresent()) { - return Optional.empty(); - } - AttachedResourceId resourceId = attachedResourceId.get(); - if (resourceId.isGetParam()) { - TranslatedHeatResource shareResource = - translateTo.getContext().getHeatSharedResourcesByParam().get(resourceId.getEntityId()); - if (Objects.nonNull(shareResource) - && !HeatToToscaUtil.isHeatFileNested(translateTo, translateTo.getHeatFileName())) { - if (validateResourceTypeSupportedForReqCreation(translateTo.getResourceId(), paramName, - requirementDefinitionEntry.getKey(), shareResource.getHeatResource(), - supportedTargetNodeTypes)) { - return Optional.of(shareResource.getTranslatedId()); - } - } - } - - return Optional.empty(); - } - - private Optional getConnectionTargetNodeUsingGetResourceFunc( - Map.Entry requirementDefinitionEntry, String paramName, - Object paramValue, List supportedTargetNodeTypes) { - String getResourceAttachedResourceId = - HeatToToscaUtil.extractContrailGetResourceAttachedHeatResourceId(paramValue); - if (getResourceAttachedResourceId != null) { // get resource - Resource resource = translateTo.getHeatOrchestrationTemplate().getResources() - .get(getResourceAttachedResourceId); - if (validateResourceTypeSupportedForReqCreation(translateTo.getResourceId(), paramName, - requirementDefinitionEntry.getKey(), resource, supportedTargetNodeTypes)) { - return ResourceTranslationBase.getResourceTranslatedId(translateTo.getHeatFileName(), - translateTo.getHeatOrchestrationTemplate(), getResourceAttachedResourceId, - translateTo.getContext()); - } - } - - return Optional.empty(); - } -} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationBase.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationBase.java deleted file mode 100644 index 45e3830f6f..0000000000 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationBase.java +++ /dev/null @@ -1,456 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.translator.services.heattotosca.impl; - -import org.apache.commons.collections4.CollectionUtils; -import org.apache.commons.collections4.MapUtils; -import org.apache.commons.lang3.StringUtils; -import org.openecomp.core.utilities.yaml.YamlUtil; -import org.openecomp.sdc.common.errors.CoreException; -import org.openecomp.sdc.heat.datatypes.manifest.FileData; -import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate; -import org.openecomp.sdc.heat.datatypes.model.Output; -import org.openecomp.sdc.heat.datatypes.model.Resource; -import org.openecomp.sdc.tosca.datatypes.ToscaCapabilityType; -import org.openecomp.sdc.tosca.datatypes.ToscaRelationshipType; -import org.openecomp.sdc.tosca.datatypes.model.ArtifactDefinition; -import org.openecomp.sdc.tosca.datatypes.model.AttributeDefinition; -import org.openecomp.sdc.tosca.datatypes.model.CapabilityDefinition; -import org.openecomp.sdc.tosca.datatypes.model.Import; -import org.openecomp.sdc.tosca.datatypes.model.InterfaceDefinition; -import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; -import org.openecomp.sdc.tosca.datatypes.model.NodeType; -import org.openecomp.sdc.tosca.datatypes.model.PropertyDefinition; -import org.openecomp.sdc.tosca.datatypes.model.RequirementAssignment; -import org.openecomp.sdc.tosca.datatypes.model.RequirementDefinition; -import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; -import org.openecomp.sdc.tosca.services.DataModelUtil; -import org.openecomp.sdc.tosca.services.ToscaConstants; -import org.openecomp.sdc.tosca.services.ToscaNativeTypesServiceTemplate; -import org.openecomp.sdc.translator.datatypes.heattotosca.AttachedResourceId; -import org.openecomp.sdc.translator.datatypes.heattotosca.to.ResourceFileDataAndIDs; -import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; -import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; -import org.openecomp.sdc.translator.services.heattotosca.ResourceTranslation; -import org.openecomp.sdc.translator.services.heattotosca.ResourceTranslationFactory; -import org.openecomp.sdc.translator.services.heattotosca.TranslationContext; -import org.openecomp.sdc.translator.services.heattotosca.TranslationService; -import org.openecomp.sdc.translator.services.heattotosca.errors.ResourceNotFoundInHeatFileErrorBuilder; -import org.openecomp.sdc.translator.services.heattotosca.globaltypes.GlobalTypesGenerator; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.function.Predicate; -import java.util.stream.Collectors; - -public abstract class ResourceTranslationBase implements ResourceTranslation { - - protected static Logger logger = LoggerFactory.getLogger(ResourceTranslationBase.class); - - static Optional getFileDataContainingResource( - List filesToSearch, String resourceId, TranslationContext context, - FileData.Type... types) { - if (CollectionUtils.isEmpty(filesToSearch)) { - return Optional.empty(); - } - - List fileDatas = Objects.isNull(types) ? filesToSearch - : HeatToToscaUtil.getFilteredListOfFileDataByTypes(filesToSearch, types); - for (FileData data : fileDatas) { - HeatOrchestrationTemplate heatOrchestrationTemplate = new YamlUtil() - .yamlToObject(context.getFiles().getFileContent(data.getFile()), - HeatOrchestrationTemplate.class); - Map outputs = heatOrchestrationTemplate.getOutputs(); - if (Objects.isNull(outputs)) { - continue; - } - Output output = outputs.get(resourceId); - if (Objects.nonNull(output)) { - Optional attachedOutputId = HeatToToscaUtil - .extractAttachedResourceId(data.getFile(), heatOrchestrationTemplate, context, - output.getValue()); - if (attachedOutputId.isPresent()) { - AttachedResourceId attachedResourceId = attachedOutputId.get(); - if (!attachedResourceId.isGetResource()) { - logger.warn("output: '" + resourceId + "' in file '" + data.getFile() - + "' is not defined as get_resource and therefor not supported."); - continue; - } - ResourceFileDataAndIDs fileDataAndIDs = - new ResourceFileDataAndIDs((String) attachedResourceId.getEntityId(), - (String) attachedResourceId.getTranslatedId(), - data); - return Optional.of(fileDataAndIDs); - } - } - } - return Optional.empty(); - } - - /** - * Gets resource translated id. - * - * @param heatFileName the heat file name - * @param heatOrchestrationTemplate the heat orchestration template - * @param resourceId the resource id - * @param context the context - * @return the resource translated id - */ - public static Optional getResourceTranslatedId(String heatFileName, - HeatOrchestrationTemplate - heatOrchestrationTemplate, - String resourceId, - TranslationContext context) { - if (!context.getTranslatedIds().containsKey(heatFileName)) { - context.getTranslatedIds().put(heatFileName, new HashMap<>()); - } - - Map translatedIdsPerFile = context.getTranslatedIds().get(heatFileName); - String translatedId = translatedIdsPerFile.get(resourceId); - if (translatedId != null) { - return Optional.of(translatedId); - } - - Resource resource = heatOrchestrationTemplate.getResources().get(resourceId); - if (resource == null) { - throw new CoreException( - new ResourceNotFoundInHeatFileErrorBuilder(resourceId, heatFileName).build()); - } - TranslateTo translateTo = - generateTranslationTo(heatFileName, null, heatOrchestrationTemplate, resource, resourceId, - null, context); - translatedId = - ResourceTranslationFactory.getInstance(resource).generateTranslatedId(translateTo); - if (translatedId != null) { - context.getTranslatedIds().get(heatFileName).put(resourceId, translatedId); - } - return Optional.ofNullable(translatedId); - } - - private static TranslateTo generateTranslationTo(String heatFileName, - ServiceTemplate serviceTemplate, - HeatOrchestrationTemplate - heatOrchestrationTemplate, - Resource resource, String resourceId, - String translatedId, - TranslationContext context) { - TranslateTo to = new TranslateTo(); - to.setHeatFileName(heatFileName); - to.setServiceTemplate(serviceTemplate); - to.setHeatOrchestrationTemplate(heatOrchestrationTemplate); - to.setResource(resource); - to.setResourceId(resourceId); - to.setTranslatedId(translatedId); - to.setContext(context); - return to; - } - - protected abstract void translate(TranslateTo translateTo); - - protected String generateTranslatedId(TranslateTo translateTo) { - isEssentialRequirementsValid(translateTo); - return translateTo.getResourceId(); - } - - protected boolean isEssentialRequirementsValid(TranslateTo translateTo) { - return true; - } - - @Override - public Optional translateResource(String heatFileName, ServiceTemplate serviceTemplate, - HeatOrchestrationTemplate heatOrchestrationTemplate, - Resource resource, String resourceId, - TranslationContext context) { - Optional translatedId = - getResourceTranslatedId(heatFileName, heatOrchestrationTemplate, resourceId, context); - context.getTranslatedResources().putIfAbsent(heatFileName, new HashSet<>()); - if (context.getTranslatedResources().get(heatFileName).contains(resourceId)) { - return translatedId; - } - if (!translatedId.isPresent()) { - return Optional.empty(); - } - logger.debug("Translate- file:" + heatFileName + " resource Id:" + resourceId - + " translated resource id:" + translatedId.get()); - translate(new TranslateTo(heatFileName, serviceTemplate, heatOrchestrationTemplate, resource, - resourceId, translatedId.get(), context)); - context.getTranslatedResources().get(heatFileName).add(resourceId); - - if (isNodeTemplate(translatedId.get(), serviceTemplate)) { - if (!context.getHeatStackGroupMembers().containsKey(heatFileName)) { - context.getHeatStackGroupMembers().put(heatFileName, new HashSet<>()); - } - context.getHeatStackGroupMembers().get(heatFileName).add(translatedId.get()); - updateResourceDependency(heatFileName, resource, heatOrchestrationTemplate, - translatedId.get(), serviceTemplate, context); - } - - return translatedId; - } - - private void updateResourceDependency(String heatFileName, Resource resource, - HeatOrchestrationTemplate heatOrchestrationTemplate, - String translatedId, ServiceTemplate serviceTemplate, - TranslationContext context) { - if (resource.getDepends_on() == null) { - return; - } - - if (resource.getDepends_on() instanceof List) { - List dependsOnList = (List) resource.getDepends_on(); - for (String dependsOnResourceId : dependsOnList) { - addDependOnRequirement(dependsOnResourceId, translatedId, serviceTemplate, heatFileName, - heatOrchestrationTemplate, context); - } - } else { - String dependsOnResourceId = (String) resource.getDepends_on(); - addDependOnRequirement(dependsOnResourceId, translatedId, serviceTemplate, heatFileName, - heatOrchestrationTemplate, context); - } - - } - - private void addDependOnRequirement(String dependsOnResourceId, String nodeTemplateId, - ServiceTemplate serviceTemplate, String heatFileName, - HeatOrchestrationTemplate heatOrchestrationTemplate, - TranslationContext context) { - RequirementAssignment requirementAssignment = new RequirementAssignment(); - Optional resourceTranslatedId = - getResourceTranslatedId(heatFileName, heatOrchestrationTemplate, dependsOnResourceId, - context); - - if (resourceTranslatedId.isPresent() - && isNodeTemplate(resourceTranslatedId.get(), serviceTemplate)) { - requirementAssignment.setNode(resourceTranslatedId.get()); - requirementAssignment.setCapability(ToscaCapabilityType.NODE.getDisplayName()); - requirementAssignment.setRelationship(ToscaRelationshipType.DEPENDS_ON.getDisplayName()); - DataModelUtil.addRequirementAssignment( - serviceTemplate.getTopology_template().getNode_templates().get(nodeTemplateId), - ToscaConstants.DEPENDS_ON_REQUIREMENT_ID, requirementAssignment); - } - } - - private boolean isNodeTemplate(String entryId, ServiceTemplate serviceTemplate) { - return serviceTemplate.getTopology_template().getNode_templates() != null - && serviceTemplate.getTopology_template().getNode_templates().get(entryId) != null; - } - - FileData getFileData(String fileName, TranslationContext context) { - - List fileDataList = context.getManifest().getContent().getData(); - for (FileData fileData : fileDataList) { - if (TranslationService.getTypesToProcessByTranslator().contains(fileData.getType()) - && fileData.getFile().equals(fileName)) { - return fileData; - } - } - return null; - } - - NodeType getNodeTypeWithFlatHierarchy(String nodeTypeId, ServiceTemplate serviceTemplate, - TranslationContext context) { - NodeType nodeType; - if (serviceTemplate != null && serviceTemplate.getNode_types() != null) { - nodeType = serviceTemplate.getNode_types().get(nodeTypeId); - - if (nodeType != null) { - return enrichNodeType(nodeType, serviceTemplate, context); - } - } - Map> globalNodeTypesMap = new HashMap<>(); - Collection globalNodeTypes = - GlobalTypesGenerator.getGlobalTypesServiceTemplate().values(); - ServiceTemplate nativeNodeTypeServiceTemplate = - ToscaNativeTypesServiceTemplate.createServiceTemplate(); - for (ServiceTemplate globalNodeType : globalNodeTypes) { - globalNodeTypesMap - .put(globalNodeType.getMetadata().getTemplate_name(), globalNodeType.getNode_types()); - } - if (Objects.nonNull(serviceTemplate) && MapUtils.isNotEmpty(serviceTemplate.getImports())) { - for (Map.Entry entry : serviceTemplate.getImports().entrySet()) { - if (globalNodeTypesMap.containsKey(entry.getKey())) { - Map nodeTypes = globalNodeTypesMap.get(entry.getKey()); - if (nodeTypes != null && nodeTypes.containsKey(nodeTypeId)) { - return enrichNodeType(nodeTypes.get(nodeTypeId), serviceTemplate, context); - } - } - if (context.getGlobalSubstitutionServiceTemplate() != null - && context.getGlobalSubstitutionServiceTemplate().getNode_types() != null - && context.getGlobalSubstitutionServiceTemplate().getNode_types() - .containsKey(nodeTypeId)) { - return enrichNodeType( - context.getGlobalSubstitutionServiceTemplate().getNode_types().get(nodeTypeId), - serviceTemplate, context); - } - if (nativeNodeTypeServiceTemplate.getNode_types().containsKey(nodeTypeId)) { - return enrichNodeType(nativeNodeTypeServiceTemplate.getNode_types().get(nodeTypeId), - serviceTemplate, context); - } - } - } - return new NodeType(); - - } - - private NodeType enrichNodeType(NodeType nodeType, ServiceTemplate serviceTemplate, - TranslationContext context) { - NodeType clonedNodeType; - - if (StringUtils.isEmpty(nodeType.getDerived_from())) { - return nodeType.clone(); - } - - clonedNodeType = enrichNodeType( - getNodeTypeWithFlatHierarchy(nodeType.getDerived_from(), serviceTemplate, context), - serviceTemplate, context); - mergeNodeTypes(clonedNodeType, nodeType); - return clonedNodeType; - - } - - private void mergeNodeTypes(NodeType target, NodeType source) { - target.setDerived_from(source.getDerived_from()); - target.setDescription(source.getDescription()); - target.setVersion(source.getVersion()); - target.setProperties( - mergeMaps(target.getProperties(), source.getProperties(), PropertyDefinition.class)); - target.setInterfaces( - mergeMaps(target.getInterfaces(), source.getInterfaces(), InterfaceDefinition.class)); - target.setArtifacts( - mergeMaps(target.getArtifacts(), source.getArtifacts(), ArtifactDefinition.class)); - target.setAttributes( - mergeMaps(target.getAttributes(), source.getAttributes(), AttributeDefinition.class)); - target.setCapabilities( - mergeMaps(target.getCapabilities(), source.getCapabilities(), CapabilityDefinition.class)); - target.setRequirements(mergeLists(target.getRequirements(), source.getRequirements(), - RequirementDefinition.class)); - } - - private List> mergeLists(List> target, List> source, - Class value) { - List> retList = new ArrayList<>(); - if (Objects.nonNull(target)) { - retList.addAll(target); - } - - if (Objects.nonNull(source)) { - for (Map sourceMap : source) { - for (Map.Entry entry : sourceMap.entrySet()) { - mergeEntryInList(entry.getKey(), entry.getValue(), retList); - } - } - } - return retList; - } - - void mergeEntryInList(T key, S value, List> target) { - boolean found = false; - for (Map map : target) { - if (map.containsKey(key)) { - map.put(key, value); - found = true; - } - } - - if (!found) { - Map newMap = new HashMap<>(); - newMap.put(key, value); - target.add(newMap); - } - } - - - private Map mergeMaps(Map target, Map source, Class value) { - Map retMap = new HashMap<>(); - if (MapUtils.isNotEmpty(target)) { - retMap.putAll(target); - } - - if (MapUtils.isNotEmpty(source)) { - retMap.putAll(source); - } - return retMap; - } - - Optional>> getResourceByTranslatedResourceId( - String fileName, - HeatOrchestrationTemplate heatOrchestrationTemplate, - String translatedResourceId,TranslateTo translateTo,String heatResourceType) { - List> list = heatOrchestrationTemplate.getResources().entrySet() - .stream() - .filter( - entry -> getPredicatesForTranslatedIdToResourceId(fileName, heatOrchestrationTemplate, - translatedResourceId, translateTo.getContext(), heatResourceType) - .stream() - .allMatch(p -> p.test(entry))) - .collect(Collectors.toList()); - if (CollectionUtils.isEmpty(list)) { - return Optional.empty(); - } else { - return Optional.of(list); - } - } - - private List>> getPredicatesForTranslatedIdToResourceId( - String fileName, HeatOrchestrationTemplate heatOrchestrationTemplate, - String translatedResourceId, TranslationContext context, String heatResourceType) { - List>> list = new ArrayList<>(); - list.add(entry -> - entry.getValue().getType().equals(heatResourceType)); - list.add(entry -> { - Optional resourceTranslatedId = - getResourceTranslatedId(fileName, heatOrchestrationTemplate, entry.getKey(), context); - return resourceTranslatedId.isPresent() - && resourceTranslatedId.get().equals(translatedResourceId); - }); - return list; - } - - void addBindingReqFromPortToCompute(String computeNodeTemplateId, NodeTemplate portNodeTemplate) { - RequirementAssignment requirementAssignment = new RequirementAssignment(); - requirementAssignment.setCapability(ToscaCapabilityType.NETWORK_BINDABLE.getDisplayName()); - requirementAssignment.setRelationship(ToscaRelationshipType.NETWORK_BINDS_TO.getDisplayName()); - requirementAssignment.setNode(computeNodeTemplateId); - DataModelUtil.addRequirementAssignment(portNodeTemplate, ToscaConstants.BINDING_REQUIREMENT_ID, - requirementAssignment); - } - - void addLinkReqFromPortToNetwork(NodeTemplate nodeTemplate, String translatedId) { - RequirementAssignment requirement = new RequirementAssignment(); - requirement.setCapability(ToscaCapabilityType.NETWORK_LINKABLE.getDisplayName()); - requirement.setRelationship(ToscaRelationshipType.NETWORK_LINK_TO.getDisplayName()); - requirement.setNode(translatedId); - DataModelUtil - .addRequirementAssignment(nodeTemplate, ToscaConstants.LINK_REQUIREMENT_ID, requirement); - } - - boolean isResourceTypeSupported(Resource resource, List supportedTypes) { - return Objects.nonNull(resource) && supportedTypes.contains(resource.getType()); - } -} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationCinderVolumeAttachmentImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationCinderVolumeAttachmentImpl.java deleted file mode 100644 index cbad52a95d..0000000000 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationCinderVolumeAttachmentImpl.java +++ /dev/null @@ -1,202 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.translator.services.heattotosca.impl; - -import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil.getResource; - -import org.apache.commons.lang3.StringUtils; -import org.openecomp.sdc.common.errors.CoreException; -import org.openecomp.sdc.heat.datatypes.manifest.FileData; -import org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes; -import org.openecomp.sdc.heat.datatypes.model.Resource; -import org.openecomp.sdc.tosca.datatypes.ToscaRelationshipType; -import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; -import org.openecomp.sdc.tosca.datatypes.model.RelationshipTemplate; -import org.openecomp.sdc.tosca.datatypes.model.RequirementAssignment; -import org.openecomp.sdc.tosca.services.DataModelUtil; -import org.openecomp.sdc.translator.datatypes.heattotosca.AttachedResourceId; -import org.openecomp.sdc.translator.datatypes.heattotosca.to.ResourceFileDataAndIDs; -import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; -import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; -import org.openecomp.sdc.translator.services.heattotosca.ResourceTranslationFactory; -import org.openecomp.sdc.translator.services.heattotosca.errors.MissingMandatoryPropertyErrorBuilder; -import org.openecomp.sdc.translator.services.heattotosca.helper.VolumeTranslationHelper; -import org.openecomp.sdc.translator.services.heattotosca.mapping.TranslatorHeatToToscaPropertyConverter; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.List; -import java.util.Optional; - -public class ResourceTranslationCinderVolumeAttachmentImpl extends ResourceTranslationBase { - protected static Logger logger = - LoggerFactory.getLogger(ResourceTranslationCinderVolumeAttachmentImpl.class); - - @Override - protected void translate(TranslateTo translateTo) { - String volumeIdPropertyName = "volume_id"; - RelationshipTemplate relationTemplate = new RelationshipTemplate(); - relationTemplate.setType(ToscaRelationshipType.CINDER_VOLUME_ATTACHES_TO.getDisplayName()); - String relationshipTemplateId = translateTo.getTranslatedId(); - String heatFileName = translateTo.getHeatFileName(); - relationTemplate.setProperties(TranslatorHeatToToscaPropertyConverter - .getToscaPropertiesSimpleConversion(translateTo.getResource().getProperties(), - relationTemplate.getProperties(), heatFileName, - translateTo.getHeatOrchestrationTemplate(), translateTo.getResource().getType(), - relationTemplate, translateTo.getContext())); - - AttachedResourceId attachedVolumeId = getAttachedResourceId(translateTo, volumeIdPropertyName); - String instanceUuid = "instance_uuid"; - AttachedResourceId attachedNovaServerId = getAttachedResourceId(translateTo, instanceUuid); - - if (attachedNovaServerId.isGetResource()) { - handleNovaGetResource(translateTo, relationTemplate, relationshipTemplateId, heatFileName, - attachedVolumeId, (String) attachedNovaServerId.getEntityId()); - } else { - logger.warn("Heat resource: '" + translateTo.getResourceId() + "' with type: '" - + translateTo.getResource().getType() - + "' include 'instance_uuid' property without 'get_resource' function, therefore this " - + "resource will be ignored in TOSCA translation."); - } - } - - private AttachedResourceId getAttachedResourceId(TranslateTo translateTo, String propertyName) { - Optional attachedResourceId = - HeatToToscaUtil.extractAttachedResourceId(translateTo, propertyName); - if (!attachedResourceId.isPresent()) { - throw new CoreException(new MissingMandatoryPropertyErrorBuilder(propertyName).build()); - } - - return attachedResourceId.get(); - } - - private void handleNovaGetResource(TranslateTo translateTo, RelationshipTemplate relationTemplate, - String relationshipTemplateId, String heatFileName, - AttachedResourceId volResourceId, String novaResourceId) { - String toscaCapabilityAttachment = "tosca.capabilities.Attachment"; - RequirementAssignment requirement = new RequirementAssignment(); - requirement.setCapability(toscaCapabilityAttachment); - if (volResourceId.isGetResource()) { - Resource volServerResource = getResource(translateTo.getHeatOrchestrationTemplate(), - (String) volResourceId.getTranslatedId(), heatFileName); - if (!StringUtils.equals(HeatResourcesTypes.CINDER_VOLUME_RESOURCE_TYPE.getHeatResource(), - volServerResource.getType())) { - logger.warn("Volume attachment with id '" + translateTo.getResourceId() - + "' is pointing to unsupported resource type(" + volServerResource.getType() - + ") through the property 'volume_id'." - + " The connection to the volume is ignored. " - + "Supported types are: " - + HeatResourcesTypes.CINDER_VOLUME_RESOURCE_TYPE.getHeatResource()); - return; - } - requirement.setNode((String) volResourceId.getTranslatedId()); - requirement.setRelationship(relationshipTemplateId); - DataModelUtil - .addRelationshipTemplate(translateTo.getServiceTemplate(), relationshipTemplateId, - relationTemplate); - } else if (volResourceId.isGetParam()) { - String volumeResourceIdParamName = (String) volResourceId.getEntityId(); - if (translateTo.getContext().getHeatSharedResourcesByParam() - .containsKey(volumeResourceIdParamName) && !isHeatFileNested(translateTo, heatFileName)) { - Resource volServerResource = - translateTo.getContext().getHeatSharedResourcesByParam().get(volumeResourceIdParamName) - .getHeatResource(); - if (!StringUtils.equals(HeatResourcesTypes.CINDER_VOLUME_RESOURCE_TYPE.getHeatResource(), - volServerResource.getType())) { - logger.warn("Volume attachment with id '" + translateTo.getResourceId() - + "' is pointing to unsupported resource type(" + volServerResource.getType() - + ") through the property 'volume_id'." - + " The connection to the volume is ignored. " - + "Supported types are: " - + HeatResourcesTypes.CINDER_VOLUME_RESOURCE_TYPE.getHeatResource()); - return; - } - requirement.setNode( - translateTo.getContext().getHeatSharedResourcesByParam().get(volumeResourceIdParamName) - .getTranslatedId()); - requirement.setRelationship(relationshipTemplateId); - DataModelUtil - .addRelationshipTemplate(translateTo.getServiceTemplate(), relationshipTemplateId, - relationTemplate); - } else { - handleUnsharedVolume(translateTo, relationTemplate, relationshipTemplateId, heatFileName, - requirement, volumeResourceIdParamName); - } - } - Resource novaServerResource = - getResource(translateTo.getHeatOrchestrationTemplate(), novaResourceId, heatFileName); - if (!StringUtils.equals(HeatResourcesTypes.NOVA_SERVER_RESOURCE_TYPE.getHeatResource(), - novaServerResource.getType())) { - logger.warn("Volume attachment with id '" + translateTo.getResourceId() - + "' is pointing to unsupported resource type(" + novaServerResource.getType() - + ") through the property 'instance_uuid'." - + " The connection to the nova server is ignored. " - + "Supported types are: " + HeatResourcesTypes.NOVA_SERVER_RESOURCE_TYPE - .getHeatResource()); - return; - } - Optional translatedNovaServerId = - ResourceTranslationFactory.getInstance(novaServerResource) - .translateResource(heatFileName, translateTo.getServiceTemplate(), - translateTo.getHeatOrchestrationTemplate(), novaServerResource, novaResourceId, - translateTo.getContext()); - - if (translatedNovaServerId.isPresent() && StringUtils.isNotEmpty(requirement.getNode())) { - NodeTemplate novaServerNodeTemplate = DataModelUtil - .getNodeTemplate(translateTo.getServiceTemplate(), translatedNovaServerId.get()); - DataModelUtil.addRequirementAssignment(novaServerNodeTemplate, "local_storage", requirement); - } - } - - private void handleUnsharedVolume(TranslateTo translateTo, RelationshipTemplate relationTemplate, - String relationshipTemplateId, String heatFileName, - RequirementAssignment requirement, String volumeResourceId) { - List allFilesData = translateTo.getContext().getManifest().getContent().getData(); - Optional fileData = HeatToToscaUtil.getFileData(heatFileName, allFilesData); - if (fileData.isPresent()) { - Optional fileDataContainingResource = - new VolumeTranslationHelper(logger) - .getFileDataContainingVolume(fileData.get().getData(), volumeResourceId, translateTo, - FileData.Type.HEAT_VOL); - if (fileDataContainingResource.isPresent()) { - addRelationshipToServiceTemplate(translateTo, relationTemplate, relationshipTemplateId, - requirement, fileDataContainingResource.get()); - } - } - } - - private boolean isHeatFileNested(TranslateTo translateTo, String heatFileName) { - return translateTo.getContext().getNestedHeatsFiles().contains(heatFileName); - } - - private void addRelationshipToServiceTemplate(TranslateTo translateTo, - RelationshipTemplate relationTemplate, - String relationshipTemplateId, - RequirementAssignment requirement, - ResourceFileDataAndIDs resourceFileDataAndIDs) { - String translatedId = resourceFileDataAndIDs.getTranslatedResourceId(); - relationTemplate.getProperties().put("volume_id", translatedId); - requirement.setNode(translatedId); - requirement.setRelationship(relationshipTemplateId); - DataModelUtil.addRelationshipTemplate(translateTo.getServiceTemplate(), relationshipTemplateId, - relationTemplate); - } -} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationCinderVolumeImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationCinderVolumeImpl.java deleted file mode 100644 index c1e5fe3900..0000000000 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationCinderVolumeImpl.java +++ /dev/null @@ -1,77 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.translator.services.heattotosca.impl; - -import org.openecomp.sdc.heat.datatypes.HeatBoolean; -import org.openecomp.sdc.tosca.datatypes.ToscaNodeType; -import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; -import org.openecomp.sdc.tosca.services.DataModelUtil; -import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; -import org.openecomp.sdc.translator.services.heattotosca.mapping.TranslatorHeatToToscaPropertyConverter; - -import java.util.Map; -import java.util.Optional; - -public class ResourceTranslationCinderVolumeImpl extends ResourceTranslationBase { - - @Override - public void translate(TranslateTo translateTo) { - NodeTemplate nodeTemplate = new NodeTemplate(); - nodeTemplate.setType(ToscaNodeType.CINDER_VOLUME.getDisplayName()); - - nodeTemplate.setProperties(TranslatorHeatToToscaPropertyConverter - .getToscaPropertiesSimpleConversion(translateTo.getResource().getProperties(), - nodeTemplate.getProperties(), translateTo.getHeatFileName(), - translateTo.getHeatOrchestrationTemplate(), translateTo.getResource().getType(), - nodeTemplate, translateTo.getContext())); - handleSizeProperty(nodeTemplate.getProperties()); - Object readOnly = nodeTemplate.getProperties().get("read_only"); - if (readOnly != null && !(readOnly instanceof Map)) { - nodeTemplate.getProperties().put("read_only", HeatBoolean.eval(readOnly)); - } - Optional resourceTranslatedId = getResourceTranslatedId(translateTo.getHeatFileName(), - translateTo.getHeatOrchestrationTemplate(), translateTo.getResourceId(), - translateTo.getContext()); - if (resourceTranslatedId.isPresent()) { - DataModelUtil.addNodeTemplate(translateTo.getServiceTemplate(), resourceTranslatedId.get(), - nodeTemplate); - } - } - - private void handleSizeProperty(Map nodeTemplateProperties) { - Object size = nodeTemplateProperties.get("size"); - if (size == null) { - return; - } - - if (size instanceof Map) { - Map propMap = (Map) size; - if (propMap.entrySet().iterator().hasNext()) { - Map.Entry entry = propMap.entrySet().iterator().next(); - String val = "(" + entry.getKey() + " : " + entry.getValue() + ") * 1024"; - nodeTemplateProperties.put("size", val); - return; - } - } else { - nodeTemplateProperties.put("size", size + "*1024"); - } - } -} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationContrailAttachPolicyImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationContrailAttachPolicyImpl.java deleted file mode 100644 index 307e407119..0000000000 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationContrailAttachPolicyImpl.java +++ /dev/null @@ -1,141 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.translator.services.heattotosca.impl; - -import org.openecomp.sdc.common.errors.CoreException; -import org.openecomp.sdc.heat.datatypes.model.Resource; -import org.openecomp.sdc.tosca.datatypes.ToscaCapabilityType; -import org.openecomp.sdc.tosca.datatypes.ToscaRelationshipType; -import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; -import org.openecomp.sdc.tosca.datatypes.model.RequirementAssignment; -import org.openecomp.sdc.tosca.services.DataModelUtil; -import org.openecomp.sdc.tosca.services.ToscaConstants; -import org.openecomp.sdc.translator.datatypes.heattotosca.AttachedResourceId; -import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; -import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; -import org.openecomp.sdc.translator.services.heattotosca.ResourceTranslationFactory; -import org.openecomp.sdc.translator.services.heattotosca.errors.MissingMandatoryPropertyErrorBuilder; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.Optional; - -public class ResourceTranslationContrailAttachPolicyImpl extends ResourceTranslationBase { - protected static Logger logger = - LoggerFactory.getLogger(ResourceTranslationContrailAttachPolicyImpl.class); - - @Override - protected void translate(TranslateTo translateTo) { - String heatFileName = translateTo.getHeatFileName(); - String translatedNetworkResourceId = getTranslatedNetworkResourceId(translateTo); - if (translatedNetworkResourceId == null) { - return; - } - - NodeTemplate policyNodeTemplate = getTranslatedPolicyNodeTemplate(translateTo, heatFileName); - if (policyNodeTemplate != null) { - DataModelUtil - .addRequirementAssignment(policyNodeTemplate, ToscaConstants.NETWORK_REQUIREMENT_ID, - createRequirementAssignment(translatedNetworkResourceId)); - } - } - - private NodeTemplate getTranslatedPolicyNodeTemplate(TranslateTo translateTo, - String heatFileName) { - Optional attachedPolicyResourceId = - extractAttachedResourceIdHandleMissing(translateTo, "policy"); - NodeTemplate policyNodeTemplate = new NodeTemplate(); - Optional policyResourceId = - HeatToToscaUtil.getContrailAttachedHeatResourceId(attachedPolicyResourceId.get()); - if (policyResourceId.isPresent()) { - policyNodeTemplate = getPolicyNodeTemplate(translateTo, heatFileName, policyResourceId.get()); - } else { - logger.warn("Heat resource: '" + translateTo.getResourceId() + "' with type: '" - + translateTo.getResource().getType() - + "' include 'policy' property without 'get_attr' of 'fq_name'/'get_resource'" - + " function, therefore this resource will be ignored in TOSCA translation."); - } - return policyNodeTemplate; - } - - private NodeTemplate getPolicyNodeTemplate(TranslateTo translateTo, String heatFileName, - String policyResourceId) { - Resource policyResource = HeatToToscaUtil - .getResource(translateTo.getHeatOrchestrationTemplate(), policyResourceId, heatFileName); - Optional translatedPolicyResourceId = - ResourceTranslationFactory.getInstance(policyResource) - .translateResource(heatFileName, translateTo.getServiceTemplate(), - translateTo.getHeatOrchestrationTemplate(), policyResource, policyResourceId, - translateTo.getContext()); - if (!translatedPolicyResourceId.isPresent()) { - logger.warn("Heat resource: '" + translateTo.getResourceId() + "' with type: '" - + translateTo.getResource().getType() - + "' include unsupported policy resource, therefore this " - + "resource will be ignored in TOSCA translation. "); - return null; - } - return DataModelUtil - .getNodeTemplate(translateTo.getServiceTemplate(), - translatedPolicyResourceId.get()); - } - - private String getTranslatedNetworkResourceId(TranslateTo translateTo) { - Optional attachedNetworkResourceId = - extractAttachedResourceIdHandleMissing(translateTo, "network"); - - String translatedNetworkResourceId = null; - if (attachedNetworkResourceId.get().isGetResource()) { - translatedNetworkResourceId = (String) attachedNetworkResourceId.get().getTranslatedId(); - } else { - logger.warn("Heat resource: '" + translateTo.getResourceId() + "' with type: '" - + translateTo.getResource().getType() - + "' include 'network' property without 'get_resource' function, " - + "therefore this resource will be ignored in TOSCA translation."); - } - return translatedNetworkResourceId; - } - - private RequirementAssignment createRequirementAssignment(String translatedNetworkResourceId) { - RequirementAssignment requirement = new RequirementAssignment(); - requirement.setCapability(ToscaCapabilityType.ATTACHMENT.getDisplayName()); - requirement.setNode(translatedNetworkResourceId); - requirement.setRelationship(ToscaRelationshipType.ATTACHES_TO.getDisplayName()); - return requirement; - } - - private Optional extractAttachedResourceIdHandleMissing( - TranslateTo translateTo, String propertyName) { - Optional attachedResourceId = - HeatToToscaUtil.extractAttachedResourceId(translateTo, propertyName); - - if (!attachedResourceId.isPresent()) { - throw new CoreException(new MissingMandatoryPropertyErrorBuilder(propertyName).build()); - } - return attachedResourceId; - } - - - @Override - protected String generateTranslatedId(TranslateTo translateTo) { - return extractAttachedResourceIdHandleMissing(translateTo, "network").get().getEntityId() - .toString(); - } -} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationContrailNetworkPolicyImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationContrailNetworkPolicyImpl.java deleted file mode 100644 index 8084433fd5..0000000000 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationContrailNetworkPolicyImpl.java +++ /dev/null @@ -1,53 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.translator.services.heattotosca.impl; - -import org.openecomp.sdc.tosca.datatypes.ToscaNodeType; -import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; -import org.openecomp.sdc.tosca.services.DataModelUtil; -import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; -import org.openecomp.sdc.translator.services.heattotosca.mapping.TranslatorHeatToToscaPropertyConverter; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class ResourceTranslationContrailNetworkPolicyImpl extends ResourceTranslationBase { - - protected static Logger logger = - LoggerFactory.getLogger(ResourceTranslationContrailNetworkPolicyImpl.class); - - @Override - protected void translate(TranslateTo translateTo) { - - NodeTemplate nodeTemplate = new NodeTemplate(); - nodeTemplate.setType(ToscaNodeType.CONTRAIL_NETWORK_RULE.getDisplayName()); - - nodeTemplate.setProperties(TranslatorHeatToToscaPropertyConverter - .getToscaPropertiesSimpleConversion(translateTo.getResource().getProperties(), - nodeTemplate.getProperties(), translateTo.getHeatFileName(), - translateTo.getHeatOrchestrationTemplate(), translateTo.getResource().getType(), - nodeTemplate, translateTo.getContext())); - - DataModelUtil.addNodeTemplate(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), - nodeTemplate); - - - } -} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationContrailServiceInstanceImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationContrailServiceInstanceImpl.java deleted file mode 100644 index b2475f28a9..0000000000 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationContrailServiceInstanceImpl.java +++ /dev/null @@ -1,663 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.translator.services.heattotosca.impl; - -import org.openecomp.sdc.common.errors.CoreException; -import org.openecomp.sdc.heat.datatypes.HeatBoolean; -import org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes; -import org.openecomp.sdc.heat.datatypes.model.Resource; -import org.openecomp.sdc.heat.services.HeatConstants; -import org.openecomp.sdc.tosca.datatypes.ToscaCapabilityType; -import org.openecomp.sdc.tosca.datatypes.ToscaFunctions; -import org.openecomp.sdc.tosca.datatypes.ToscaGroupType; -import org.openecomp.sdc.tosca.datatypes.ToscaNodeType; -import org.openecomp.sdc.tosca.datatypes.ToscaRelationshipType; -import org.openecomp.sdc.tosca.datatypes.model.AttributeDefinition; -import org.openecomp.sdc.tosca.datatypes.model.GroupDefinition; -import org.openecomp.sdc.tosca.datatypes.model.Metadata; -import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; -import org.openecomp.sdc.tosca.datatypes.model.NodeType; -import org.openecomp.sdc.tosca.datatypes.model.ParameterDefinition; -import org.openecomp.sdc.tosca.datatypes.model.PropertyDefinition; -import org.openecomp.sdc.tosca.datatypes.model.RequirementAssignment; -import org.openecomp.sdc.tosca.datatypes.model.RequirementDefinition; -import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; -import org.openecomp.sdc.tosca.datatypes.model.SubstitutionMapping; -import org.openecomp.sdc.tosca.datatypes.model.TopologyTemplate; -import org.openecomp.sdc.tosca.services.DataModelUtil; -import org.openecomp.sdc.tosca.services.ToscaConstants; -import org.openecomp.sdc.tosca.services.ToscaUtil; -import org.openecomp.sdc.tosca.services.impl.ToscaFileOutputServiceCsarImpl; -import org.openecomp.sdc.translator.datatypes.heattotosca.AttachedResourceId; -import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; -import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslatedHeatResource; -import org.openecomp.sdc.translator.services.heattotosca.Constants; -import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; -import org.openecomp.sdc.translator.services.heattotosca.ResourceTranslationFactory; -import org.openecomp.sdc.translator.services.heattotosca.errors.MissingMandatoryPropertyErrorBuilder; -import org.openecomp.sdc.translator.services.heattotosca.globaltypes.ContrailAbstractSubstituteGlobalType; -import org.openecomp.sdc.translator.services.heattotosca.globaltypes.ContrailComputeGlobalType; -import org.openecomp.sdc.translator.services.heattotosca.globaltypes.GlobalTypesGenerator; -import org.openecomp.sdc.translator.services.heattotosca.globaltypes.GlobalTypesUtil; -import org.openecomp.sdc.translator.services.heattotosca.helper.ContrailTranslationHelper; -import org.openecomp.sdc.translator.services.heattotosca.mapping.TranslatorHeatToToscaFunctionConverter; -import org.openecomp.sdc.translator.services.heattotosca.mapping.TranslatorHeatToToscaPropertyConverter; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - -public class ResourceTranslationContrailServiceInstanceImpl extends ResourceTranslationBase { - protected static Logger logger = - LoggerFactory.getLogger(ResourceTranslationContrailServiceInstanceImpl.class); - - @Override - public void translate(TranslateTo translateTo) { - Resource serviceInstanceResource = translateTo.getResource(); - AttachedResourceId contrailServiceTemplateAttached = - getServiceTemplateAttachedId(translateTo, serviceInstanceResource); - if (contrailServiceTemplateAttached.isGetResource()) { - String contrailServiceTemplateResourceId = - (String) contrailServiceTemplateAttached.getEntityId(); - Resource contrailServiceTemplateResource = HeatToToscaUtil - .getResource(translateTo.getHeatOrchestrationTemplate(), - contrailServiceTemplateResourceId, translateTo.getHeatFileName()); - if (!contrailServiceTemplateResource.getType() - .equals(HeatResourcesTypes.CONTRAIL_SERVICE_TEMPLATE.getHeatResource())) { - logger.warn("resource id '" + translateTo.getResourceId() + "' with type '" - + translateTo.getResource().getType() - + "+ has reference to resource '" + contrailServiceTemplateResourceId + "' with type " - + "'" - + contrailServiceTemplateResource.getType() - + "' in property service_template. Invalid type, resource type should be type of '" - + HeatResourcesTypes.CONTRAIL_SERVICE_TEMPLATE.getHeatResource() - + "', therefore this resource will be ignored in TOSCA translation."); - return; - } - Optional contrailServiceTemplateTranslatedId = - ResourceTranslationFactory.getInstance(contrailServiceTemplateResource) - .translateResource(translateTo.getHeatFileName(), translateTo.getServiceTemplate(), - translateTo.getHeatOrchestrationTemplate(), contrailServiceTemplateResource, - contrailServiceTemplateResourceId, translateTo.getContext()); - if (!contrailServiceTemplateTranslatedId.isPresent()) { - logger.warn("Resource id '" + translateTo.getResourceId() + "' with type '" - + translateTo.getResource().getType() - + "' has reference to unsupported resource '" + contrailServiceTemplateResourceId - + "' with type '" + contrailServiceTemplateResource.getType() - + "' in property 'service_template'" - + ", therefore this resource will be ignored in TOSCA translation."); - return; - } - - ServiceTemplate globalSubstitutionServiceTemplate = - translateTo.getContext().getTranslatedServiceTemplates() - .get(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME); - String contrailStId = ResourceTranslationContrailServiceTemplateImpl - .getContrailSubstitutedNodeTypeId(contrailServiceTemplateTranslatedId.get()); - NodeType substitutedNodeType = - DataModelUtil.getNodeType(globalSubstitutionServiceTemplate, contrailStId); - - int numberOfPorts = getServiceInstanceNumberOfPorts(serviceInstanceResource); - if (substitutedNodeType.getRequirements() != null - && substitutedNodeType.getRequirements().size() != numberOfPorts) { - logger.warn("More than one ServiceInstance pointing to the same ServiceTemplate '" - + contrailServiceTemplateResourceId + " ' with different number of interfaces." - + ", therefore this resource will be ignored in TOSCA translation."); - return; - } - - addNetworkLinkRequirements(substitutedNodeType, numberOfPorts); - NodeTemplate substitutedNodeTemplate = - createSubstitutedNodeTemplate(translateTo, contrailServiceTemplateResource, contrailStId, - numberOfPorts); - - String computeNodeTypeId = new ContrailTranslationHelper() - .getComputeNodeTypeId(contrailServiceTemplateTranslatedId.get(), - contrailServiceTemplateResource); - boolean orderedInterfaces = getOrderedInterfaces(contrailServiceTemplateResource); - ServiceTemplate nestedServiceTemplate = - createNestedServiceTemplate(translateTo, computeNodeTypeId, contrailStId, - substitutedNodeTemplate, orderedInterfaces); - addAbstractSubstitutionProperty(translateTo, substitutedNodeTemplate.getProperties(), - nestedServiceTemplate, contrailServiceTemplateResource); - translateTo.getContext().getTranslatedServiceTemplates() - .put(translateTo.getTranslatedId(), nestedServiceTemplate); - - } else { - logger.warn("Heat resource: '" + translateTo.getResourceId() + "' with type: '" - + translateTo.getResource().getType() - + "' include 'service_template' property without 'get_resource' function, currently not " - + "supported, therefore this resource will be ignored in TOSCA translation."); - } - - } - - private void addAbstractSubstitutionProperty(TranslateTo translateTo, - Map substitutionProperties, - ServiceTemplate nestedServiceTemplate, - Resource contrailServiceTemplateResource) { - Map innerProps = new HashMap<>(); - innerProps.put(ToscaConstants.SUBSTITUTE_SERVICE_TEMPLATE_PROPERTY_NAME, - ToscaUtil.getServiceTemplateFileName(nestedServiceTemplate)); - - Object countValue = handleScaleOutProperty(translateTo, innerProps); - handleServiceScalingProperty(translateTo, innerProps, contrailServiceTemplateResource); - - boolean mandatory = false; - if (countValue instanceof Integer && (Integer) countValue > 0) { - mandatory = true; - } - if (countValue == null) { - mandatory = true; - } - innerProps.put("mandatory", mandatory); - substitutionProperties.put(ToscaConstants.SERVICE_TEMPLATE_FILTER_PROPERTY_NAME, innerProps); - } - - private Object handleScaleOutProperty(TranslateTo translateTo, Map innerProps) { - Object scaleOutPropertyValue = - translateTo.getResource().getProperties().get(HeatConstants.SCALE_OUT_PROPERTY_NAME); - Object countValue = null; - if (scaleOutPropertyValue != null && scaleOutPropertyValue instanceof Map) { - countValue = TranslatorHeatToToscaPropertyConverter - .getToscaPropertyValue(Constants.MAX_INSTANCES_PROPERTY_NAME, - ((Map) scaleOutPropertyValue).get(Constants.MAX_INSTANCES_PROPERTY_NAME), null, - translateTo.getHeatFileName(), translateTo.getHeatOrchestrationTemplate(), null, - translateTo.getContext()); - if (countValue != null) { - innerProps.put(ToscaConstants.COUNT_PROPERTY_NAME, countValue); - } else { - innerProps.put(ToscaConstants.COUNT_PROPERTY_NAME, 1); - } - } else { - innerProps.put(ToscaConstants.COUNT_PROPERTY_NAME, 1); - } - return countValue; - } - - private void handleServiceScalingProperty(TranslateTo translateTo, Map innerProps, - Resource contrailServiceTemplateResource) { - Object serviceScalingPropertyValue = contrailServiceTemplateResource.getProperties() - .get(HeatConstants.SERVICE_SCALING_PROPERTY_NAME); - Object serviceScalingValue = null; - if (serviceScalingPropertyValue != null) { - serviceScalingValue = TranslatorHeatToToscaPropertyConverter - .getToscaPropertyValue(HeatConstants.SERVICE_SCALING_PROPERTY_NAME, - serviceScalingPropertyValue, null, translateTo.getHeatFileName(), - translateTo.getHeatOrchestrationTemplate(), null, translateTo.getContext()); - if (serviceScalingValue != null) { - innerProps.put(ToscaConstants.SCALING_ENABLED_PROPERTY_NAME, - (HeatBoolean.isValueBoolean(serviceScalingValue)) ? HeatBoolean - .eval(serviceScalingValue) : serviceScalingValue); - } - } - } - - private boolean getOrderedInterfaces(Resource contrailServiceTemplate) { - Object orderedInterfaces = contrailServiceTemplate.getProperties().get("ordered_interfaces"); - if (orderedInterfaces == null) { - return false; - } - if (orderedInterfaces instanceof String) { - return HeatBoolean.eval(orderedInterfaces); - } - //if get_param, set default value to true - return true; - } - - private ServiceTemplate createNestedServiceTemplate(TranslateTo translateTo, - String computeNodeTypeId, - String substitutedNodeTypeId, - NodeTemplate substitutedNodeTemplate, - boolean orderedInterfaces) { - ServiceTemplate nestedSubstitutionServiceTemplate = new ServiceTemplate(); - setNestedServiceTemplateGeneralDetails(translateTo, nestedSubstitutionServiceTemplate); - String heatStackGroupKey = addHeatStackGroup(translateTo, nestedSubstitutionServiceTemplate); - addSubstitutionMappingEntry(nestedSubstitutionServiceTemplate, substitutedNodeTypeId); - - handleInputParameters(nestedSubstitutionServiceTemplate); - String computeNodeTemplateId = - handleComputeNodeTemplate(translateTo, computeNodeTypeId, nestedSubstitutionServiceTemplate, - heatStackGroupKey); - handleOutputParameters(nestedSubstitutionServiceTemplate, computeNodeTemplateId); - handleServiceInstanceInterfaces(translateTo, nestedSubstitutionServiceTemplate, - substitutedNodeTemplate, heatStackGroupKey, orderedInterfaces, computeNodeTemplateId); - - return nestedSubstitutionServiceTemplate; - } - - private void handleOutputParameters(ServiceTemplate nestedSubstitutionServiceTemplate, - String nodeTemplateId) { - if (nodeTemplateId == null) { - return; - } - NodeType contrailAbstractNodeType = - ContrailAbstractSubstituteGlobalType.createServiceTemplate().getNode_types() - .get(ToscaNodeType.CONTRAIL_ABSTRACT_SUBSTITUTE.getDisplayName()); - Map contrailAbstractAttributes = - contrailAbstractNodeType.getAttributes(); - Map nestedSubstitutionServiceTemplateOutputs = new HashMap<>(); - - if (contrailAbstractAttributes == null) { - return; - } - - for (String attributeKey : contrailAbstractAttributes.keySet()) { - AttributeDefinition abstractAttributeDef = contrailAbstractAttributes.get(attributeKey); - if (abstractAttributeDef != null) { - Map outputValue = new HashMap<>(); - List outputGetAttributeList = new ArrayList<>(); - outputGetAttributeList.add(nodeTemplateId); - outputGetAttributeList.add(attributeKey); - outputValue.put(ToscaFunctions.GET_ATTRIBUTE.getDisplayName(), outputGetAttributeList); - nestedSubstitutionServiceTemplateOutputs.put(attributeKey, - DataModelUtil.convertAttributeDefToParameterDef(abstractAttributeDef, outputValue)); - } - } - if (!nestedSubstitutionServiceTemplateOutputs.isEmpty()) { - nestedSubstitutionServiceTemplate.getTopology_template() - .setOutputs(nestedSubstitutionServiceTemplateOutputs); - } - } - - private void handleServiceInstanceInterfaces(TranslateTo translateTo, - ServiceTemplate nestedSubstitutionServiceTemplate, - NodeTemplate substitutedNodeTemplate, - String heatStackGroupKey, boolean orderedInterfaces, - String computeNodeTemplateId) { - Resource serviceInstanceResource = translateTo.getResource(); - Object interfaceListProperty = serviceInstanceResource.getProperties().get("interface_list"); - if (interfaceListProperty == null) { - return; - } - if (interfaceListProperty instanceof List) { - for (int index = 0; index < ((List) interfaceListProperty).size(); index++) { - Object interfaceEntry = ((List) interfaceListProperty).get(index); - handleInterface(translateTo, interfaceEntry, index, nestedSubstitutionServiceTemplate, - heatStackGroupKey, substitutedNodeTemplate, orderedInterfaces, computeNodeTemplateId); - } - } else if (interfaceListProperty instanceof Map) { - handleInterface(translateTo, interfaceListProperty, null, nestedSubstitutionServiceTemplate, - heatStackGroupKey, substitutedNodeTemplate, orderedInterfaces, computeNodeTemplateId); - } - } - - private void handleInterface(TranslateTo translateTo, Object interfacePropertyValue, - Integer index, - ServiceTemplate nestedSubstitutionServiceTemplate, - String heatStackGroupKey, NodeTemplate substitutedNodeTemplate, - boolean orderedInterfaces, String computeNodeTemplateId) { - if (index == null) { - index = new Integer(0); - } - NodeTemplate portNodeTemplate = - createPortNodeTemplate(index, orderedInterfaces, computeNodeTemplateId); - String portNodeTemplateId = "port_" + index; - String portReqMappingKey = "link_" + portNodeTemplateId; - - DataModelUtil - .addNodeTemplate(nestedSubstitutionServiceTemplate, portNodeTemplateId, portNodeTemplate); - updateSubstitutionMappingRequirement(nestedSubstitutionServiceTemplate, portReqMappingKey, - portNodeTemplateId); - updateHeatStackGroup(nestedSubstitutionServiceTemplate, heatStackGroupKey, portNodeTemplateId); - connectPortToNetwork(translateTo, interfacePropertyValue, substitutedNodeTemplate, - portReqMappingKey); - } - - private void connectPortToNetwork(TranslateTo translateTo, Object interfacePropertyValue, - NodeTemplate substitutedNodeTemplate, - String portReqMappingKey) { - List validNetworksForConnections = Arrays - .asList(HeatResourcesTypes.NEUTRON_NET_RESOURCE_TYPE.getHeatResource(), - HeatResourcesTypes.CONTRAIL_VIRTUAL_NETWORK_RESOURCE_TYPE.getHeatResource()); - - if (interfacePropertyValue instanceof Map) { - Object virtualNetworkValue = ((Map) interfacePropertyValue).get("virtual_network"); - if (virtualNetworkValue != null) { - Optional networkAttachedResourceId = HeatToToscaUtil - .extractAttachedResourceId(translateTo.getHeatFileName(), - translateTo.getHeatOrchestrationTemplate(), translateTo.getContext(), - virtualNetworkValue); - if (networkAttachedResourceId.isPresent()) { - Optional networkResourceId = - HeatToToscaUtil.getContrailAttachedHeatResourceId(networkAttachedResourceId.get()); - if (networkResourceId.isPresent()) { - Resource networkResource = HeatToToscaUtil - .getResource(translateTo.getHeatOrchestrationTemplate(), networkResourceId.get(), - translateTo.getHeatFileName()); - if (validNetworksForConnections.contains(networkResource.getType())) { - Optional networkTranslatedId = - getResourceTranslatedId(translateTo.getHeatFileName(), - translateTo.getHeatOrchestrationTemplate(), networkResourceId.get(), - translateTo.getContext()); - if (networkTranslatedId.isPresent()) { - addLinkToNetworkRequirementAssignment(substitutedNodeTemplate, - networkTranslatedId.get(), portReqMappingKey); - } - } else { - logger.warn("Heat resource " + translateTo.getResourceId() + " with type " - + translateTo.getResource().getType() - + " has connection to invalid/not supported network resource, therefore, this " - + "connection will be ignored in the translation."); - } - } else if (networkAttachedResourceId.get().isGetParam()) { - TranslatedHeatResource translatedSharedResourceId = - translateTo.getContext().getHeatSharedResourcesByParam() - .get(networkAttachedResourceId.get().getEntityId()); - if (Objects.nonNull(translatedSharedResourceId) - && !HeatToToscaUtil.isHeatFileNested(translateTo, translateTo.getHeatFileName())) { - addLinkToNetworkRequirementAssignment(substitutedNodeTemplate, - translatedSharedResourceId.getTranslatedId(), portReqMappingKey); - } - } else { - logger.warn("Heat resource: '" + translateTo.getResourceId() + "' with type: '" - + translateTo.getResource().getType() - + "' include 'virtual_network' property with value '" - + virtualNetworkValue.toString() - + "', the connection to this network wasn't found/not supported therefore this " - + "connection will be ignored in TOSCA translation for this property."); - } - } - } else { - logger.warn("Heat resource: '" + translateTo.getResourceId() + "' with type: '" - + translateTo.getResource().getType() - + "' missing 'virtual_network' property in 'interface_list' entry, therefore, no " - + "network connection is define for this entry."); - } - } - } - - private NodeTemplate createPortNodeTemplate(Integer index, boolean orderedInterfaces, - String computeNodeTemplateId) { - NodeTemplate portNodeTemplate = new NodeTemplate(); - portNodeTemplate.setType(ToscaNodeType.CONTRAIL_PORT.getDisplayName()); - Map portProperties = new HashMap<>(); - portProperties.put("static_routes", DataModelUtil - .createGetInputPropertyValueFromListParameter("interface_list", index, "static_routes")); - portProperties.put("virtual_network", DataModelUtil - .createGetInputPropertyValueFromListParameter("interface_list", index, "virtual_network")); - portProperties.put("allowed_address_pairs", DataModelUtil - .createGetInputPropertyValueFromListParameter("interface_list", index, - "allowed_address_pairs")); - portProperties.put("ip_address", DataModelUtil - .createGetInputPropertyValueFromListParameter("interface_list", index, "ip_address")); - portProperties.put("static_route", - DataModelUtil.createGetInputPropertyValueFromListParameter("static_routes_list", index)); - portProperties.put("shared_ip", - DataModelUtil.createGetInputPropertyValueFromListParameter("shared_ip_list", index)); - portProperties.put("interface_type", DataModelUtil - .createGetInputPropertyValueFromListParameter("service_interface_type_list", index)); - if (orderedInterfaces) { - portProperties.put("order", index); - } - portNodeTemplate.setProperties(portProperties); - addBindingReqFromPortToCompute(computeNodeTemplateId, portNodeTemplate); - return portNodeTemplate; - } - - - private void addLinkToNetworkRequirementAssignment(NodeTemplate nodeTemplate, - String connectedNodeTranslatedId, - String requirementId) { - if (nodeTemplate == null || connectedNodeTranslatedId == null) { - return; - } - - RequirementAssignment requirement = new RequirementAssignment(); - requirement.setCapability(ToscaCapabilityType.NETWORK_LINKABLE.getDisplayName()); - requirement.setRelationship(ToscaRelationshipType.NETWORK_LINK_TO.getDisplayName()); - requirement.setNode(connectedNodeTranslatedId); - DataModelUtil.addRequirementAssignment(nodeTemplate, requirementId, requirement); - } - - private void updateHeatStackGroup(ServiceTemplate serviceTemplate, String heatStackGroupKey, - String memberId) { - serviceTemplate.getTopology_template().getGroups().get(heatStackGroupKey).getMembers() - .add(memberId); - } - - private void updateSubstitutionMappingRequirement(ServiceTemplate serviceTemplate, - String portReqMappingKey, - String portNodeTemplateId) { - List portReqMappingValue = new ArrayList<>(); - portReqMappingValue.add(portNodeTemplateId); - portReqMappingValue.add(ToscaConstants.LINK_REQUIREMENT_ID); - DataModelUtil - .addSubstitutionMappingReq(serviceTemplate, portReqMappingKey, portReqMappingValue); - } - - private void addSubstitutionMappingEntry(ServiceTemplate nestedSubstitutionServiceTemplate, - String substitutedNodeTypeId) { - SubstitutionMapping substitutionMappings = new SubstitutionMapping(); - substitutionMappings.setNode_type(substitutedNodeTypeId); - DataModelUtil.addSubstitutionMapping(nestedSubstitutionServiceTemplate, substitutionMappings); - } - - private void handleInputParameters(ServiceTemplate nestedSubstitutionServiceTemplate) { - NodeType contrailAbstractNodeType = - ContrailAbstractSubstituteGlobalType.createServiceTemplate().getNode_types() - .get(ToscaNodeType.CONTRAIL_ABSTRACT_SUBSTITUTE.getDisplayName()); - Map contrailAbstractProperties = - contrailAbstractNodeType.getProperties(); - Map nestedSubstitutionServiceTemplateInputs = new HashMap<>(); - - for (String propertyKey : contrailAbstractProperties.keySet()) { - PropertyDefinition abstractPropertyDef = contrailAbstractProperties.get(propertyKey); - if (abstractPropertyDef != null) { - nestedSubstitutionServiceTemplateInputs - .put(propertyKey, DataModelUtil.convertPropertyDefToParameterDef(abstractPropertyDef)); - - } - } - if (!nestedSubstitutionServiceTemplateInputs.isEmpty()) { - nestedSubstitutionServiceTemplate.getTopology_template() - .setInputs(nestedSubstitutionServiceTemplateInputs); - } - } - - private String handleComputeNodeTemplate(TranslateTo translateTo, String computeNodeTypeId, - ServiceTemplate nestedSubstitutionServiceTemplate, - String heatStackGroupKey) { - NodeType contrailComputeNodeType = - ContrailComputeGlobalType.createServiceTemplate().getNode_types() - .get(ToscaNodeType.CONTRAIL_COMPUTE.getDisplayName()); - Map contrailComputeProperties = - contrailComputeNodeType.getProperties(); - Map computeNodeTemplateProperties = new HashMap<>(); - - if (contrailComputeProperties != null) { - for (String computePropertyKey : contrailComputeProperties.keySet()) { - Map getInputProperty = new HashMap<>(); - getInputProperty.put(ToscaFunctions.GET_INPUT.getDisplayName(), computePropertyKey); - computeNodeTemplateProperties.put(computePropertyKey, getInputProperty); - } - } - - NodeTemplate computeNodeTemplate = new NodeTemplate(); - computeNodeTemplate.setType(computeNodeTypeId); - if (!computeNodeTemplateProperties.isEmpty()) { - computeNodeTemplate.setProperties(computeNodeTemplateProperties); - } - String computeNodeTemplateId = translateTo.getTranslatedId(); - DataModelUtil.addNodeTemplate(nestedSubstitutionServiceTemplate, computeNodeTemplateId, - computeNodeTemplate); - nestedSubstitutionServiceTemplate.getTopology_template().getGroups().get(heatStackGroupKey) - .getMembers().add(computeNodeTemplateId); - - return computeNodeTemplateId; - } - - private String addHeatStackGroup(TranslateTo translateTo, ServiceTemplate serviceTemplate) { - GroupDefinition serviceInstanceGroupDefinition = new GroupDefinition(); - serviceInstanceGroupDefinition.setType(ToscaGroupType.HEAT_STACK.getDisplayName()); - Map groupProperties = new HashMap<>(); - groupProperties.put("heat_file", - "../" + (new ToscaFileOutputServiceCsarImpl()).getArtifactsFolderName() + "/" - + translateTo.getHeatFileName()); - serviceInstanceGroupDefinition.setProperties(groupProperties); - serviceInstanceGroupDefinition.setMembers(new ArrayList<>()); - String heatStackGroupKey = translateTo.getTranslatedId(); - DataModelUtil.addGroupDefinitionToTopologyTemplate(serviceTemplate, heatStackGroupKey, - serviceInstanceGroupDefinition); - - return heatStackGroupKey; - } - - - private void setNestedServiceTemplateGeneralDetails(TranslateTo translateTo, - ServiceTemplate nestedSubstitutionServiceTemplate) { - Metadata nestedTemplateMetadata = new Metadata(); - String nestedTemplateName = translateTo.getResourceId(); - nestedTemplateMetadata.setTemplate_name(nestedTemplateName); - nestedSubstitutionServiceTemplate.setMetadata(nestedTemplateMetadata); - nestedSubstitutionServiceTemplate - .setTosca_definitions_version(ToscaConstants.TOSCA_DEFINITIONS_VERSION); - nestedSubstitutionServiceTemplate.setTopology_template(new TopologyTemplate()); - nestedSubstitutionServiceTemplate.setImports(GlobalTypesGenerator.getGlobalTypesImportList()); - nestedSubstitutionServiceTemplate.getImports() - .put(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME, GlobalTypesUtil - .createServiceTemplateImport(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME)); - } - - private NodeTemplate createSubstitutedNodeTemplate(TranslateTo translateTo, - Resource contrailServiceTemplateResource, - String contrailServiceTemplateTranslatedId, - int numberOfPorts) { - - translateTo.getServiceTemplate().getImports() - .put(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME, GlobalTypesUtil - .createServiceTemplateImport(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME)); - NodeTemplate substitutesNodeTemplate = new NodeTemplate(); - substitutesNodeTemplate.setType(contrailServiceTemplateTranslatedId); - List directiveList = new ArrayList<>(); - directiveList.add(ToscaConstants.NODE_TEMPLATE_DIRECTIVE_SUBSTITUTABLE); - substitutesNodeTemplate.setDirectives(directiveList); - substitutesNodeTemplate.setProperties(TranslatorHeatToToscaPropertyConverter - .getToscaPropertiesSimpleConversion(translateTo.getResource().getProperties(), - substitutesNodeTemplate.getProperties(), translateTo.getHeatFileName(), - translateTo.getHeatOrchestrationTemplate(), - HeatResourcesTypes.CONTRAIL_SERVICE_INSTANCE.getHeatResource(), substitutesNodeTemplate, - translateTo.getContext())); - substitutesNodeTemplate.setProperties(TranslatorHeatToToscaPropertyConverter - .getToscaPropertiesSimpleConversion(contrailServiceTemplateResource.getProperties(), - substitutesNodeTemplate.getProperties(), translateTo.getHeatFileName(), - translateTo.getHeatOrchestrationTemplate(), - HeatResourcesTypes.CONTRAIL_SERVICE_TEMPLATE.getHeatResource(), substitutesNodeTemplate, - translateTo.getContext())); - HeatToToscaUtil.mapBoolean(substitutesNodeTemplate, "availability_zone_enable"); - HeatToToscaUtil.mapBoolean(substitutesNodeTemplate, "ordered_interfaces"); - - Object sharedIpListPropertyValue = - contrailServiceTemplateResource.getProperties().get("shared_ip_list"); - Optional>> sharedIpTranslatedSplitFun = - TranslatorHeatToToscaFunctionConverter - .translateFnSplitFunction(sharedIpListPropertyValue, numberOfPorts, true); - if (sharedIpTranslatedSplitFun.isPresent()) { - substitutesNodeTemplate.getProperties() - .put("shared_ip_list", sharedIpTranslatedSplitFun.get()); - } else { - HeatToToscaUtil.mapBooleanList(substitutesNodeTemplate, "shared_ip_list"); - } - - Object staticRouteListPropertyValue = - contrailServiceTemplateResource.getProperties().get("static_routes_list"); - Optional>> staticRouteTranslatedSplitFun = - TranslatorHeatToToscaFunctionConverter - .translateFnSplitFunction(staticRouteListPropertyValue, numberOfPorts, true); - if (staticRouteTranslatedSplitFun.isPresent()) { - substitutesNodeTemplate.getProperties() - .put("static_routes_list", staticRouteTranslatedSplitFun.get()); - } else { - HeatToToscaUtil.mapBooleanList(substitutesNodeTemplate, "static_routes_list"); - } - - Object serviceInterfaceTypeListPropertyValue = - contrailServiceTemplateResource.getProperties().get("service_interface_type_list"); - Optional>> serviceInterfaceTypeTranslatedSplitFun = - TranslatorHeatToToscaFunctionConverter - .translateFnSplitFunction(serviceInterfaceTypeListPropertyValue, numberOfPorts, false); - if (serviceInterfaceTypeTranslatedSplitFun.isPresent()) { - substitutesNodeTemplate.getProperties() - .put("service_interface_type_list", serviceInterfaceTypeTranslatedSplitFun.get()); - } - - String substitutedNodeTemplateId = translateTo.getTranslatedId(); - DataModelUtil.addNodeTemplate(translateTo.getServiceTemplate(), substitutedNodeTemplateId, - substitutesNodeTemplate); - return substitutesNodeTemplate; - } - - private void addNetworkLinkRequirements(NodeType nodeType, int numberOfPorts) { - if (nodeType.getRequirements() == null) { - List> requirementList = new ArrayList<>(); - for (int i = 0; i < numberOfPorts; i++) { - Map requirementDefinitionMap = new HashMap<>(); - requirementDefinitionMap.put(ToscaConstants.LINK_REQUIREMENT_ID + "_port_" + i, - DataModelUtil.createRequirement(ToscaCapabilityType.NETWORK_LINKABLE.getDisplayName(), - ToscaNodeType.ROOT.getDisplayName(), - ToscaRelationshipType.NETWORK_LINK_TO.getDisplayName(), null)); - requirementList.add(requirementDefinitionMap); - } - if (numberOfPorts > 0) { - nodeType.setRequirements(requirementList); - } - } - } - - private int getServiceInstanceNumberOfPorts(Resource serviceInstanceResource) { - int numberOfPorts; - Object interfaceTypeProperty = serviceInstanceResource.getProperties().get("interface_list"); - if (interfaceTypeProperty == null) { - numberOfPorts = 0; - } else if (interfaceTypeProperty instanceof List) { - numberOfPorts = ((List) interfaceTypeProperty).size(); - } else if (interfaceTypeProperty instanceof Map) { - numberOfPorts = 1; - } else { - numberOfPorts = 0; - } - - return numberOfPorts; - } - - private AttachedResourceId getServiceTemplateAttachedId(TranslateTo translateTo, - Resource serviceInstanceResource) { - Object serviceTemplateProperty = - serviceInstanceResource.getProperties().get("service_template"); - Optional serviceTemplateId = HeatToToscaUtil - .extractAttachedResourceId(translateTo.getHeatFileName(), - translateTo.getHeatOrchestrationTemplate(), translateTo.getContext(), - serviceTemplateProperty); - if (serviceTemplateId.isPresent()) { - return serviceTemplateId.get(); - } else { - throw new CoreException(new MissingMandatoryPropertyErrorBuilder("service_template").build()); - } - } - - -} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationContrailServiceTemplateImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationContrailServiceTemplateImpl.java deleted file mode 100644 index e0a3ed422f..0000000000 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationContrailServiceTemplateImpl.java +++ /dev/null @@ -1,100 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.translator.services.heattotosca.impl; - -import org.openecomp.sdc.common.errors.CoreException; -import org.openecomp.sdc.tosca.datatypes.ToscaNodeType; -import org.openecomp.sdc.tosca.datatypes.model.Metadata; -import org.openecomp.sdc.tosca.datatypes.model.NodeType; -import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; -import org.openecomp.sdc.tosca.services.DataModelUtil; -import org.openecomp.sdc.tosca.services.ToscaConstants; -import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; -import org.openecomp.sdc.translator.services.heattotosca.Constants; -import org.openecomp.sdc.translator.services.heattotosca.errors.MissingMandatoryPropertyErrorBuilder; -import org.openecomp.sdc.translator.services.heattotosca.globaltypes.GlobalTypesGenerator; -import org.openecomp.sdc.translator.services.heattotosca.helper.ContrailTranslationHelper; - -import java.util.Map; -import java.util.Objects; - -public class ResourceTranslationContrailServiceTemplateImpl extends ResourceTranslationBase { - - static String getContrailSubstitutedNodeTypeId(String serviceTemplateTranslatedId) { - return ToscaConstants.NODES_SUBSTITUTION_PREFIX + serviceTemplateTranslatedId; - } - - @Override - protected boolean isEssentialRequirementsValid(TranslateTo translateTo) { - Map properties = translateTo.getResource().getProperties(); - if (Objects.isNull(properties) || Objects.isNull(properties.get("image_name"))) { - throw new CoreException(new MissingMandatoryPropertyErrorBuilder("image_name").build()); - } - return true; - } - - @Override - public void translate(TranslateTo translateTo) { - - ServiceTemplate globalSubstitutionServiceTemplate = - getGlobalSubstitutionTypesServiceTemplate(translateTo); - addSubstitutedNodeType(translateTo, globalSubstitutionServiceTemplate); - addComputeNodeType(translateTo, globalSubstitutionServiceTemplate); - } - - private void addComputeNodeType(TranslateTo translateTo, - ServiceTemplate globalSubstitutionServiceTemplate) { - NodeType computeNodeType = new NodeType(); - computeNodeType.setDerived_from(ToscaNodeType.CONTRAIL_COMPUTE.getDisplayName()); - String computeNodeTypeId = new ContrailTranslationHelper() - .getComputeNodeTypeId(translateTo.getTranslatedId(), translateTo.getResource()); - DataModelUtil - .addNodeType(globalSubstitutionServiceTemplate, computeNodeTypeId, computeNodeType); - } - - private void addSubstitutedNodeType(TranslateTo translateTo, - ServiceTemplate globalSubstitutionServiceTemplate) { - NodeType substitutedNodeType = new NodeType(); - substitutedNodeType - .setDerived_from(ToscaNodeType.CONTRAIL_ABSTRACT_SUBSTITUTE.getDisplayName()); - DataModelUtil.addNodeType(globalSubstitutionServiceTemplate, - getContrailSubstitutedNodeTypeId(translateTo.getTranslatedId()), substitutedNodeType); - } - - private ServiceTemplate getGlobalSubstitutionTypesServiceTemplate(TranslateTo translateTo) { - ServiceTemplate globalSubstitutionServiceTemplate = - translateTo.getContext().getTranslatedServiceTemplates() - .get(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME); - if (globalSubstitutionServiceTemplate == null) { - globalSubstitutionServiceTemplate = new ServiceTemplate(); - Metadata templateMetadata = new Metadata(); - templateMetadata.setTemplate_name(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME); - globalSubstitutionServiceTemplate.setMetadata(templateMetadata); - globalSubstitutionServiceTemplate.setImports(GlobalTypesGenerator.getGlobalTypesImportList()); - globalSubstitutionServiceTemplate - .setTosca_definitions_version(ToscaConstants.TOSCA_DEFINITIONS_VERSION); - translateTo.getContext().getTranslatedServiceTemplates() - .put(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME, - globalSubstitutionServiceTemplate); - } - return globalSubstitutionServiceTemplate; - } -} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationContrailV2NetworkPolicyImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationContrailV2NetworkPolicyImpl.java deleted file mode 100644 index 72a25985a8..0000000000 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationContrailV2NetworkPolicyImpl.java +++ /dev/null @@ -1,49 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.translator.services.heattotosca.impl; - -import org.openecomp.sdc.tosca.datatypes.ToscaNodeType; -import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; -import org.openecomp.sdc.tosca.services.DataModelUtil; -import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; -import org.openecomp.sdc.translator.services.heattotosca.mapping.TranslatorHeatToToscaPropertyConverter; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -public class ResourceTranslationContrailV2NetworkPolicyImpl extends ResourceTranslationBase { - - protected static Logger logger = - LoggerFactory.getLogger(ResourceTranslationContrailV2NetworkPolicyImpl.class); - - @Override - protected void translate(TranslateTo translateTo) { - - NodeTemplate nodeTemplate = new NodeTemplate(); - nodeTemplate.setType(ToscaNodeType.CONTRAILV2_NETWORK_RULE.getDisplayName()); - nodeTemplate.setProperties(TranslatorHeatToToscaPropertyConverter - .getToscaPropertiesSimpleConversion(translateTo.getResource().getProperties(), - nodeTemplate.getProperties(), translateTo.getHeatFileName(), - translateTo.getHeatOrchestrationTemplate(), translateTo.getResource().getType(), - nodeTemplate, translateTo.getContext())); - DataModelUtil.addNodeTemplate(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), - nodeTemplate); - } -} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationContrailV2VirtualNetworkImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationContrailV2VirtualNetworkImpl.java deleted file mode 100644 index d81f3196a3..0000000000 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationContrailV2VirtualNetworkImpl.java +++ /dev/null @@ -1,209 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.translator.services.heattotosca.impl; - -import org.apache.commons.collections.CollectionUtils; -import org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes; -import org.openecomp.sdc.heat.datatypes.model.Resource; -import org.openecomp.sdc.tosca.datatypes.ToscaCapabilityType; -import org.openecomp.sdc.tosca.datatypes.ToscaNodeType; -import org.openecomp.sdc.tosca.datatypes.ToscaRelationshipType; -import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; -import org.openecomp.sdc.tosca.datatypes.model.RequirementAssignment; -import org.openecomp.sdc.tosca.services.DataModelUtil; -import org.openecomp.sdc.tosca.services.ToscaConstants; -import org.openecomp.sdc.translator.datatypes.heattotosca.AttachedResourceId; -import org.openecomp.sdc.translator.datatypes.heattotosca.ResourceReferenceType; -import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; -import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; -import org.openecomp.sdc.translator.services.heattotosca.ResourceTranslationFactory; -import org.openecomp.sdc.translator.services.heattotosca.mapping.TranslatorHeatToToscaPropertyConverter; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.List; -import java.util.Map; -import java.util.Optional; - -public class ResourceTranslationContrailV2VirtualNetworkImpl extends ResourceTranslationBase { - - protected static Logger logger = - LoggerFactory.getLogger(ResourceTranslationContrailV2VirtualNetworkImpl.class); - - @Override - public void translate(TranslateTo translateTo) { - - NodeTemplate nodeTemplate = new NodeTemplate(); - nodeTemplate.setType(ToscaNodeType.CONTRAILV2_VIRTUAL_NETWORK.getDisplayName()); - nodeTemplate.setProperties(TranslatorHeatToToscaPropertyConverter - .getToscaPropertiesSimpleConversion(translateTo.getResource().getProperties(), - nodeTemplate.getProperties(), translateTo.getHeatFileName(), - translateTo.getHeatOrchestrationTemplate(), translateTo.getResource().getType(), - nodeTemplate, translateTo.getContext())); - Optional resourceTranslatedId = getResourceTranslatedId(translateTo.getHeatFileName(), - translateTo.getHeatOrchestrationTemplate(), translateTo.getResourceId(), - translateTo.getContext()); - if (resourceTranslatedId.isPresent()) { - DataModelUtil.addNodeTemplate(translateTo.getServiceTemplate(), resourceTranslatedId.get(), - nodeTemplate); - } - linkToPolicyNodeTemplate(translateTo); - } - - private void linkToPolicyNodeTemplate(TranslateTo translateTo) { - List networkPolicyIdList = extractNetworkPolicyIdList(translateTo); - if (CollectionUtils.isEmpty(networkPolicyIdList)) { - return; - } - for (AttachedResourceId attachedResourceId : networkPolicyIdList) { - NodeTemplate policyNodeTemplate = DataModelUtil - .getNodeTemplate(translateTo.getServiceTemplate(), - (String) attachedResourceId.getTranslatedId()); - DataModelUtil - .addRequirementAssignment(policyNodeTemplate, ToscaConstants.NETWORK_REQUIREMENT_ID, - createRequirementAssignment(translateTo.getTranslatedId())); - } - } - - private List extractNetworkPolicyIdList(TranslateTo translateTo) { - - Object propertyValue = translateTo.getResource().getProperties().get("network_policy_refs"); - if (propertyValue != null) { - return extractNetworkPolicyId(propertyValue, translateTo); - } else { - return null; - } - } - - private List extractNetworkPolicyId(Object propertyValue, - TranslateTo translateTo) { - List attachedResourceIdList = new ArrayList<>(); - - if (propertyValue instanceof List) { - for (Object value : (List) propertyValue) { - attachedResourceIdList.addAll(extractNetworkPolicyId(value, translateTo)); - } - } else { - AttachedResourceId resourceId = parsNetworkPolicyId(propertyValue, translateTo); - if (resourceId != null) { - attachedResourceIdList.add(resourceId); - } - } - return attachedResourceIdList; - } - - private AttachedResourceId parsNetworkPolicyId(Object propertyValue, TranslateTo translateTo) { - - Optional translatedPolicyResourceId; - String policyResourceId = extractResourceId(propertyValue, translateTo); - if (policyResourceId == null) { - return null; - } - - Resource policyResource = HeatToToscaUtil - .getResource(translateTo.getHeatOrchestrationTemplate(), policyResourceId, - translateTo.getHeatFileName()); - if (!policyResource.getType() - .equals(HeatResourcesTypes.CONTRAIL_V2_NETWORK_RULE_RESOURCE_TYPE.getHeatResource())) { - return null; - } - translatedPolicyResourceId = ResourceTranslationFactory.getInstance(policyResource) - .translateResource(translateTo.getHeatFileName(), translateTo.getServiceTemplate(), - translateTo.getHeatOrchestrationTemplate(), policyResource, policyResourceId, - translateTo.getContext()); - if (!translatedPolicyResourceId.isPresent()) { - logger.warn("Heat resource: '" + translateTo.getResourceId() + "' with type: '" - + translateTo.getResource().getType() - + "' property network_policy_refs is referenced to an " - + "unsupported resource the connection will be ignored in TOSCA translation."); - return null; - } - return - new AttachedResourceId(translatedPolicyResourceId.get(), policyResourceId, - ResourceReferenceType.GET_ATTR); - } - - private String extractResourceId(Object propertyValue, TranslateTo translateTo) { - - Object value; - if (propertyValue instanceof Map) { - if (((Map) propertyValue).containsKey("get_attr")) { - value = ((Map) propertyValue).get("get_attr"); - if (value instanceof List) { - if (((List) value).size() == 2 && ((List) value).get(1).equals("fq_name")) { - if (((List) value).get(0) instanceof String) { - return (String) ((List) value).get(0); - } else { - logger.warn("Heat resource: '" + translateTo.getResourceId() + "' with type: '" - + translateTo.getResource().getType() - + "' has property with invalid format of 'get_attr' function " - + "with 'fq_name' value, therefore this property" - + " will be ignored in TOSCA translation."); - } - } - } - } else if (((Map) propertyValue).containsKey("get_resource")) { - value = ((Map) propertyValue).get("get_resource"); - if (value instanceof String) { - return (String) value; - } else { - logger.warn("Heat resource: '" + translateTo.getResourceId() + "' with type: '" - + translateTo.getResource().getType() - + "' has property invalid format of 'get_resource' function, therefore" - + " this property will be ignored in TOSCA translation."); - } - } else { - Collection valCollection = ((Map) propertyValue).values(); - for (Object entryValue : valCollection) { - String ret = extractResourceId(entryValue, translateTo); - if (ret != null) { - return ret; - } - - } - } - } else if (propertyValue instanceof List) { - for (Object prop : (List) propertyValue) { - String ret = extractResourceId(prop, translateTo); - if (ret != null) { - return ret; - } - } - } - logger.warn("Heat resource: '" + translateTo.getResourceId() + "' with type: '" - + translateTo.getResource().getType() - + "' invalid format of property value, therefore " - + "this resource will be ignored in TOSCA translation."); - return null; - } - - private RequirementAssignment createRequirementAssignment(String translatedNetworkResourceId) { - RequirementAssignment requirement = new RequirementAssignment(); - requirement.setCapability(ToscaCapabilityType.ATTACHMENT.getDisplayName()); - requirement.setNode(translatedNetworkResourceId); - requirement.setRelationship(ToscaRelationshipType.ATTACHES_TO.getDisplayName()); - return requirement; - } - - -} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationContrailV2VmInterfaceImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationContrailV2VmInterfaceImpl.java deleted file mode 100644 index 14403df002..0000000000 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationContrailV2VmInterfaceImpl.java +++ /dev/null @@ -1,126 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.translator.services.heattotosca.impl; - -import org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes; -import org.openecomp.sdc.heat.datatypes.model.Resource; -import org.openecomp.sdc.tosca.datatypes.ToscaNodeType; -import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; -import org.openecomp.sdc.tosca.services.DataModelUtil; -import org.openecomp.sdc.translator.datatypes.heattotosca.AttachedResourceId; -import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; -import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslatedHeatResource; -import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; -import org.openecomp.sdc.translator.services.heattotosca.mapping.TranslatorHeatToToscaPropertyConverter; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.Arrays; -import java.util.List; -import java.util.Objects; -import java.util.Optional; - - -public class ResourceTranslationContrailV2VmInterfaceImpl extends ResourceTranslationBase { - protected static Logger logger = - LoggerFactory.getLogger(ResourceTranslationContrailV2VmInterfaceImpl.class); - - @Override - protected void translate(TranslateTo translateTo) { - NodeTemplate nodeTemplate = new NodeTemplate(); - nodeTemplate.setType(ToscaNodeType.CONTRAILV2_VIRTUAL_MACHINE_INTERFACE.getDisplayName()); - - nodeTemplate.setProperties(TranslatorHeatToToscaPropertyConverter - .getToscaPropertiesSimpleConversion(translateTo.getResource().getProperties(), - nodeTemplate.getProperties(), translateTo.getHeatFileName(), - translateTo.getHeatOrchestrationTemplate(), translateTo.getResource().getType(), - nodeTemplate, translateTo.getContext())); - handleNetworkRequirement(translateTo, nodeTemplate); - Optional resourceTranslatedId = getResourceTranslatedId(translateTo.getHeatFileName(), - translateTo.getHeatOrchestrationTemplate(), translateTo.getResourceId(), - translateTo.getContext()); - if (resourceTranslatedId.isPresent()) { - DataModelUtil.addNodeTemplate(translateTo.getServiceTemplate(), resourceTranslatedId.get(), - nodeTemplate); - } - } - - private void handleNetworkRequirement(TranslateTo translateTo, NodeTemplate nodeTemplate) { - Object virtualNetworkRefs = - translateTo.getResource().getProperties().get("virtual_network_refs"); - if (Objects.isNull(virtualNetworkRefs) || !(virtualNetworkRefs instanceof List) - || ((List) virtualNetworkRefs).size() == 0) { - return; - } - List acceptableResourceTypes = Arrays - .asList(HeatResourcesTypes.NEUTRON_NET_RESOURCE_TYPE.getHeatResource(), - HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_NETWORK_RESOURCE_TYPE.getHeatResource()); - List virtualNetworkRefList = (List) virtualNetworkRefs; - if (virtualNetworkRefList.size() > 1) { - logger.warn("Heat resource: '" + translateTo.getResourceId() + "' with type: '" - + translateTo.getResource().getType() - + "' include 'virtual_network_refs' property with more than one network values," - + " only the first network will be translated, " - + "all rest will be ignored in TOSCA translation."); - } - Object virtualNetworkRef = virtualNetworkRefList.get(0); - String networkResourceId = - HeatToToscaUtil.extractContrailGetResourceAttachedHeatResourceId(virtualNetworkRef); - if (Objects.nonNull(networkResourceId)) { // get_resource - Resource networkResource = HeatToToscaUtil - .getResource(translateTo.getHeatOrchestrationTemplate(), networkResourceId, - translateTo.getHeatFileName()); - if (acceptableResourceTypes.contains(networkResource.getType())) { - Optional resourceTranslatedId = - getResourceTranslatedId(translateTo.getHeatFileName(), - translateTo.getHeatOrchestrationTemplate(), networkResourceId, - translateTo.getContext()); - if (resourceTranslatedId.isPresent()) { - addLinkReqFromPortToNetwork(nodeTemplate, resourceTranslatedId.get()); - } - } else { - logger.warn("Heat resource: '" + translateTo.getResourceId() + "' with type: '" - + translateTo.getResource().getType() - + "' include 'virtual_network_refs' property which is connect" - + " to unsupported/incorrect resource with type '" - + networkResource.getType() - + "', therefore, this connection will be ignored in TOSCA translation."); - } - } else { - Optional attachedResourceId = HeatToToscaUtil - .extractAttachedResourceId(translateTo.getHeatFileName(), - translateTo.getHeatOrchestrationTemplate(), translateTo.getContext(), - virtualNetworkRef); - if (attachedResourceId.isPresent() && attachedResourceId.get().isGetParam()) { - TranslatedHeatResource translatedSharedResourceId = - translateTo.getContext().getHeatSharedResourcesByParam() - .get(attachedResourceId.get().getEntityId()); - if (Objects.nonNull(translatedSharedResourceId) - && !HeatToToscaUtil.isHeatFileNested(translateTo, translateTo.getHeatFileName())) { - addLinkReqFromPortToNetwork(nodeTemplate, translatedSharedResourceId.getTranslatedId()); - } - } - } - - - } - -} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationContrailVirtualNetworkImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationContrailVirtualNetworkImpl.java deleted file mode 100644 index 3a3a532d59..0000000000 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationContrailVirtualNetworkImpl.java +++ /dev/null @@ -1,51 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.translator.services.heattotosca.impl; - -import org.openecomp.sdc.tosca.datatypes.ToscaNodeType; -import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; -import org.openecomp.sdc.tosca.services.DataModelUtil; -import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; -import org.openecomp.sdc.translator.services.heattotosca.mapping.TranslatorHeatToToscaPropertyConverter; - -import java.util.Optional; - -public class ResourceTranslationContrailVirtualNetworkImpl extends ResourceTranslationBase { - - @Override - public void translate(TranslateTo translateTo) { - - NodeTemplate nodeTemplate = new NodeTemplate(); - nodeTemplate.setType(ToscaNodeType.CONTRAIL_VIRTUAL_NETWORK.getDisplayName()); - nodeTemplate.setProperties(TranslatorHeatToToscaPropertyConverter - .getToscaPropertiesSimpleConversion(translateTo.getResource().getProperties(), - nodeTemplate.getProperties(), translateTo.getHeatFileName(), - translateTo.getHeatOrchestrationTemplate(), translateTo.getResource().getType(), - nodeTemplate, translateTo.getContext())); - Optional resourceTranslatedId = getResourceTranslatedId(translateTo.getHeatFileName(), - translateTo.getHeatOrchestrationTemplate(), translateTo.getResourceId(), - translateTo.getContext()); - if (resourceTranslatedId.isPresent()) { - DataModelUtil.addNodeTemplate(translateTo.getServiceTemplate(), resourceTranslatedId.get(), - nodeTemplate); - } - } -} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationDefaultImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationDefaultImpl.java deleted file mode 100644 index 1182b60a6a..0000000000 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationDefaultImpl.java +++ /dev/null @@ -1,41 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.translator.services.heattotosca.impl; - -import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; - -public class ResourceTranslationDefaultImpl extends ResourceTranslationBase { - - @Override - protected String generateTranslatedId(TranslateTo translateTo) { - return null; - } - - @Override - public void translate(TranslateTo translateTo) { - //no translation is needed, this default is used for unsupported resources - logger.warn("Heat resource: '" + translateTo.getResourceId() + "' with type: '" - + translateTo.getResource().getType() - + "' is not supported, will be ignored in TOSCA translation"); - - } - -} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationNestedImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationNestedImpl.java deleted file mode 100644 index 2573b6849d..0000000000 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationNestedImpl.java +++ /dev/null @@ -1,781 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.translator.services.heattotosca.impl; - -import org.apache.commons.collections4.CollectionUtils; -import org.apache.commons.collections4.MapUtils; -import org.openecomp.core.utilities.file.FileUtils; -import org.openecomp.sdc.heat.datatypes.manifest.FileData; -import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate; -import org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes; -import org.openecomp.sdc.heat.datatypes.model.Resource; -import org.openecomp.sdc.heat.services.HeatConstants; -import org.openecomp.sdc.tosca.datatypes.ToscaCapabilityType; -import org.openecomp.sdc.tosca.datatypes.ToscaNodeType; -import org.openecomp.sdc.tosca.datatypes.ToscaRelationshipType; -import org.openecomp.sdc.tosca.datatypes.model.AttributeDefinition; -import org.openecomp.sdc.tosca.datatypes.model.CapabilityDefinition; -import org.openecomp.sdc.tosca.datatypes.model.Metadata; -import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; -import org.openecomp.sdc.tosca.datatypes.model.NodeType; -import org.openecomp.sdc.tosca.datatypes.model.ParameterDefinition; -import org.openecomp.sdc.tosca.datatypes.model.PropertyDefinition; -import org.openecomp.sdc.tosca.datatypes.model.PropertyType; -import org.openecomp.sdc.tosca.datatypes.model.RequirementAssignment; -import org.openecomp.sdc.tosca.datatypes.model.RequirementDefinition; -import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; -import org.openecomp.sdc.tosca.datatypes.model.SubstitutionMapping; -import org.openecomp.sdc.tosca.datatypes.model.Template; -import org.openecomp.sdc.tosca.datatypes.model.TopologyTemplate; -import org.openecomp.sdc.tosca.services.DataModelUtil; -import org.openecomp.sdc.tosca.services.ToscaConstants; -import org.openecomp.sdc.tosca.services.ToscaUtil; -import org.openecomp.sdc.translator.datatypes.heattotosca.AttachedResourceId; -import org.openecomp.sdc.translator.datatypes.heattotosca.to.ResourceFileDataAndIDs; -import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; -import org.openecomp.sdc.translator.services.heattotosca.Constants; -import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; -import org.openecomp.sdc.translator.services.heattotosca.TranslationContext; -import org.openecomp.sdc.translator.services.heattotosca.TranslationService; -import org.openecomp.sdc.translator.services.heattotosca.globaltypes.GlobalTypesGenerator; -import org.openecomp.sdc.translator.services.heattotosca.globaltypes.GlobalTypesUtil; -import org.openecomp.sdc.translator.services.heattotosca.mapping.TranslatorHeatToToscaPropertyConverter; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - -public class ResourceTranslationNestedImpl extends ResourceTranslationBase { - - protected static Logger logger = LoggerFactory.getLogger(ResourceTranslationNestedImpl.class); - - @Override - public void translate(TranslateTo translateTo) { - FileData nestedFileData = - getFileData(translateTo.getResource().getType(), translateTo.getContext()); - String templateName = FileUtils.getFileWithoutExtention(translateTo.getResource().getType()); - String substitutionNodeTypeKey = ToscaConstants.NODES_SUBSTITUTION_PREFIX + templateName; - - if (!translateTo.getContext().getTranslatedServiceTemplates() - .containsKey(translateTo.getResource().getType())) { - - //substitution template - ServiceTemplate nestedSubstitutionServiceTemplate = new ServiceTemplate(); - Metadata templateMetadata = new Metadata(); - templateMetadata.setTemplate_name(templateName); - nestedSubstitutionServiceTemplate.setMetadata(templateMetadata); - nestedSubstitutionServiceTemplate - .setTosca_definitions_version(ToscaConstants.TOSCA_DEFINITIONS_VERSION); - nestedSubstitutionServiceTemplate.setTopology_template(new TopologyTemplate()); - nestedSubstitutionServiceTemplate.setImports(GlobalTypesGenerator.getGlobalTypesImportList()); - nestedSubstitutionServiceTemplate.getImports() - .put(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME, GlobalTypesUtil - .createServiceTemplateImport(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME)); - - TranslationService translationService = new TranslationService(); - - translationService.translateHeatFile(nestedSubstitutionServiceTemplate, nestedFileData, - translateTo.getContext()); - - //global substitution template - ServiceTemplate globalSubstitutionServiceTemplate; - globalSubstitutionServiceTemplate = translateTo.getContext().getTranslatedServiceTemplates() - .get(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME); - if (globalSubstitutionServiceTemplate == null) { - globalSubstitutionServiceTemplate = new ServiceTemplate(); - templateMetadata = new Metadata(); - templateMetadata.setTemplate_name(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME); - globalSubstitutionServiceTemplate.setMetadata(templateMetadata); - globalSubstitutionServiceTemplate - .setImports(GlobalTypesGenerator.getGlobalTypesImportList()); - globalSubstitutionServiceTemplate - .setTosca_definitions_version(ToscaConstants.TOSCA_DEFINITIONS_VERSION); - } - translateTo.getServiceTemplate().getImports() - .put(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME, GlobalTypesUtil - .createServiceTemplateImport(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME)); - - - //substitution node type - NodeType substitutionNodeType = new NodeType(); - substitutionNodeType.setDerived_from(ToscaNodeType.ABSTRACT_SUBSTITUTE.getDisplayName()); - substitutionNodeType.setDescription(nestedSubstitutionServiceTemplate.getDescription()); - substitutionNodeType - .setProperties(manageSubstitutionNodeTypeProperties(nestedSubstitutionServiceTemplate)); - substitutionNodeType - .setAttributes(manageSubstitutionNodeTypeAttributes(nestedSubstitutionServiceTemplate)); - DataModelUtil.addNodeType(globalSubstitutionServiceTemplate, substitutionNodeTypeKey, - substitutionNodeType); - Map>> substitutionMapping = - manageSubstitutionNodeTypeCapabilitiesAndRequirements(substitutionNodeType, - nestedSubstitutionServiceTemplate, translateTo); - //calculate substitution mapping after capability and requirement expose calculation - nestedSubstitutionServiceTemplate.getTopology_template().setSubstitution_mappings( - manageSubstitutionTemplateSubstitutionMapping(substitutionNodeTypeKey, - substitutionNodeType, substitutionMapping)); - - //add new service template - translateTo.getContext().getTranslatedServiceTemplates() - .put(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME, - globalSubstitutionServiceTemplate); - translateTo.getContext().getTranslatedServiceTemplates() - .put(translateTo.getResource().getType(), nestedSubstitutionServiceTemplate); - } - - NodeTemplate substitutionNodeTemplate = new NodeTemplate(); - List directiveList = new ArrayList<>(); - directiveList.add(ToscaConstants.NODE_TEMPLATE_DIRECTIVE_SUBSTITUTABLE); - substitutionNodeTemplate.setDirectives(directiveList); - substitutionNodeTemplate.setType(substitutionNodeTypeKey); - substitutionNodeTemplate.setProperties( - managerSubstitutionNodeTemplateProperties(translateTo, substitutionNodeTemplate, - templateName)); - manageSubstitutionNodeTemplateConnectionPoint(translateTo, nestedFileData, - substitutionNodeTemplate); - DataModelUtil.addNodeTemplate(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), - substitutionNodeTemplate); - } - - private void manageSubstitutionNodeTemplateConnectionPoint(TranslateTo translateTo, - FileData nestedFileData, - NodeTemplate substitutionNodeTemplate) { - ServiceTemplate globalSubstitutionTemplate = - translateTo.getContext().getTranslatedServiceTemplates() - .get(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME); - NodeType nodeType = globalSubstitutionTemplate.getNode_types().get( - ToscaConstants.NODES_SUBSTITUTION_PREFIX - + FileUtils.getFileWithoutExtention(translateTo.getResource().getType())); - handlePortToNetConnections(translateTo, nestedFileData, substitutionNodeTemplate, nodeType); - handleSecurityRulesToPortConnections(translateTo, nestedFileData, substitutionNodeTemplate, - nodeType); - handleNovaToVolConnection(translateTo, nestedFileData, substitutionNodeTemplate, nodeType); - handleContrailV2VmInterfaceToNetworkConnection(translateTo, nestedFileData, - substitutionNodeTemplate, nodeType); - } - - private void handleContrailV2VmInterfaceToNetworkConnection(TranslateTo translateTo, - FileData nestedFileData, - NodeTemplate substitutionNodeTemplate, - NodeType nodeType) { - ContrailV2VmInterfaceToNetResourceConnection linker = - new ContrailV2VmInterfaceToNetResourceConnection(this, translateTo, nestedFileData, - substitutionNodeTemplate, nodeType); - linker.connect(); - } - - private void handleNovaToVolConnection(TranslateTo translateTo, FileData nestedFileData, - NodeTemplate substitutionNodeTemplate, NodeType nodeType) { - NovaToVolResourceConnection linker = - new NovaToVolResourceConnection(this, translateTo, nestedFileData, substitutionNodeTemplate, - nodeType); - linker.connect(); - } - - private void handleSecurityRulesToPortConnections(TranslateTo translateTo, - FileData nestedFileData, - NodeTemplate substitutionNodeTemplate, - NodeType nodeType) { - SecurityRulesToPortResourceConnection linker = - new SecurityRulesToPortResourceConnection(this, translateTo, nestedFileData, - substitutionNodeTemplate, nodeType); - linker.connect(); - } - - private void handlePortToNetConnections(TranslateTo translateTo, FileData nestedFileData, - NodeTemplate substitutionNodeTemplate, - NodeType nodeType) { - PortToNetResourceConnection linker = - new PortToNetResourceConnection(this, translateTo, nestedFileData, substitutionNodeTemplate, - nodeType); - linker.connect(); - } - - private List> getVolumeRequirements(NodeType nodeType) { - List> volumeRequirementsList = new ArrayList<>(); - List> requirementsList = nodeType.getRequirements(); - - for (int i = 0; requirementsList != null && i < requirementsList.size(); i++) { - RequirementDefinition req; - for (Map.Entry entry : requirementsList.get(i).entrySet()) { - req = entry.getValue(); - if (isVolumeRequirement(req, ToscaCapabilityType.ATTACHMENT.getDisplayName(), - ToscaNodeType.BLOCK_STORAGE.getDisplayName(), - ToscaRelationshipType.NATIVE_ATTACHES_TO.getDisplayName())) { - Map volumeRequirementsMap = new HashMap<>(); - volumeRequirementsMap.put(entry.getKey(), entry.getValue()); - volumeRequirementsList.add(volumeRequirementsMap); - } - - } - } - return volumeRequirementsList; - } - - private boolean isVolumeRequirement(RequirementDefinition req, String capability, String node, - String relationship) { - return req.getCapability().equals(capability) && req.getRelationship().equals(relationship) - && req.getNode().equals(node); - } - - private String getVolumeIdProperty(HeatOrchestrationTemplate heatOrchestrationTemplate, - String resourceId) { - - String novaResourceId; - String volumeId = null; - for (Resource resource : heatOrchestrationTemplate.getResources().values()) { - if (resource.getType() - .equals(HeatResourcesTypes.CINDER_VOLUME_ATTACHMENT_RESOURCE_TYPE.getHeatResource())) { - Optional optNovaResourceId = - getToscaPropertyValueSource(HeatConstants.INSTANCE_UUID_PROPERTY_NAME, resource, - "get_resource"); - if (optNovaResourceId.isPresent()) { - novaResourceId = optNovaResourceId.get(); - if (novaResourceId.equals(resourceId)) { - Optional optVolumeId = - getToscaPropertyValueSource(HeatConstants.VOLUME_ID_PROPERTY_NAME, resource, - "get_param"); - if (optVolumeId.isPresent()) { - volumeId = optVolumeId.get(); - } - } else { - logger.warn("property:" + HeatConstants.VOLUME_ID_PROPERTY_NAME + " of resource type:" - + resource.getType() + " should contain 'get_param' function"); - } - } - } - } - return volumeId; - } - - private String getTranslatedVolumeIdByVolumeIdProperty(String volumeId, TranslateTo translateTo) { - Optional volumeIdInfo = - HeatToToscaUtil.extractAttachedResourceId(translateTo, volumeId); - if (volumeIdInfo.isPresent()) { - if (volumeIdInfo.get().isGetResource()) { - return null;//(String) volumeIdInfo.get().getTranslatedId(); - } else if (volumeIdInfo.get().isGetParam()) { - List allFilesData = translateTo.getContext().getManifest().getContent().getData(); - Optional> fileDataList = HeatToToscaUtil - .buildListOfFilesToSearch(translateTo.getHeatFileName(), allFilesData, - FileData.Type.HEAT_VOL); - if (fileDataList.isPresent()) { - Optional resourceFileDataAndIDs = - getFileDataContainingResource(fileDataList.get(), - (String) volumeIdInfo.get().getEntityId(), translateTo.getContext(), - FileData.Type.HEAT_VOL); - if (resourceFileDataAndIDs.isPresent()) { - return resourceFileDataAndIDs.get().getTranslatedResourceId(); - } else { - logger.warn("The attached volume based on volume_id property: " + volumeId + " in " - + translateTo.getResourceId() - + " can't be found, searching for volume resource id - " - + volumeIdInfo.get().getEntityId()); - return null; - } - } else { - return null; - } - } else { - logger.warn("property:" + volumeId + " of resource :" + volumeIdInfo.get().getEntityId() - + " should contain 'get_param' or 'get_resource' function"); - return null; - } - } else { - logger.warn("property:" + volumeId + " of resource :" + translateTo.getResource().toString() - + " is not exist"); - return null; - } - } - - private Optional getToscaPropertyValueSource(String propertyName, Resource resource, - String key) { - Object propertyInstanceUuIdValue; - propertyInstanceUuIdValue = resource.getProperties().get(propertyName); - if (propertyInstanceUuIdValue instanceof Map) { - return Optional.ofNullable((String) ((Map) propertyInstanceUuIdValue).get(key)); - } else { - logger.warn("property:" + propertyName + " of resource type:" + resource.getType() - + " should have a value in key value format"); - - } - return Optional.empty(); - - } - - private Map>> - manageSubstitutionNodeTypeCapabilitiesAndRequirements( - NodeType substitutionNodeType, ServiceTemplate substitutionServiceTemplate, - TranslateTo translateTo) { - - Map nodeTemplates = - substitutionServiceTemplate.getTopology_template().getNode_templates(); - String templateName; - NodeTemplate template; - String type; - Map>> substitutionMapping = new HashMap<>(); - if (nodeTemplates == null) { - return substitutionMapping; - } - - Map> capabilitySubstitutionMapping = new HashMap<>(); - Map> requirementSubstitutionMapping = new HashMap<>(); - substitutionMapping.put("capability", capabilitySubstitutionMapping); - substitutionMapping.put("requirement", requirementSubstitutionMapping); - List> nodeTypeRequirementsDefinition; - Map nodeTemplateRequirementsAssignment; - List> exposedRequirementsDefinition; - Map> fullFilledRequirementsDefinition = - new HashMap<>(); - Map nodeTypeCapabilitiesDefinition = new HashMap<>(); - Map exposedCapabilitiesDefinition; - - for (Map.Entry entry : nodeTemplates.entrySet()) { - templateName = entry.getKey(); - template = entry.getValue(); - type = template.getType(); - - // get requirements - nodeTypeRequirementsDefinition = - getNodeTypeRequirements(type, templateName, substitutionServiceTemplate, - requirementSubstitutionMapping, translateTo.getContext()); - nodeTemplateRequirementsAssignment = getNodeTemplateRequirements(template); - fullFilledRequirementsDefinition.put(templateName, nodeTemplateRequirementsAssignment); - //set substitution node type requirements - exposedRequirementsDefinition = calculateExposedRequirements(nodeTypeRequirementsDefinition, - nodeTemplateRequirementsAssignment); - addSubstitutionNodeTypeRequirements(substitutionNodeType, exposedRequirementsDefinition, - templateName); - - //get capabilities - getNodeTypeCapabilities(nodeTypeCapabilitiesDefinition, capabilitySubstitutionMapping, type, - templateName, substitutionServiceTemplate, translateTo.getContext()); - - } - - exposedCapabilitiesDefinition = calculateExposedCapabilities(nodeTypeCapabilitiesDefinition, - fullFilledRequirementsDefinition); - addSubstitutionNodeTypeCapabilities(substitutionNodeType, exposedCapabilitiesDefinition); - return substitutionMapping; - } - - private Map calculateExposedCapabilities( - Map nodeTypeCapabilitiesDefinition, - Map> fullFilledRequirementsDefinitionMap) { - - String capabilityKey; - String capability; - String node; - CapabilityDefinition capabilityDefinition; - CapabilityDefinition clonedCapabilityDefinition; - for (Map.Entry> entry - : fullFilledRequirementsDefinitionMap.entrySet()) { - for (Map.Entry fullFilledEntry : entry.getValue().entrySet()) { - - capability = fullFilledEntry.getValue().getCapability(); - fullFilledEntry.getValue().getOccurrences(); - node = fullFilledEntry.getValue().getNode(); - capabilityKey = capability + "_" + node; - capabilityDefinition = nodeTypeCapabilitiesDefinition.get(capabilityKey); - if (capabilityDefinition != null) { - clonedCapabilityDefinition = capabilityDefinition.clone(); - nodeTypeCapabilitiesDefinition.put(capabilityKey, capabilityDefinition.clone()); - if (evaluateCapabilityFullFilament(clonedCapabilityDefinition)) { - nodeTypeCapabilitiesDefinition.remove(capabilityKey); - } else { - nodeTypeCapabilitiesDefinition.put(capabilityKey, clonedCapabilityDefinition); - } - } - } - } - - Map exposedCapabilitiesDefinition = new HashMap<>(); - for (Map.Entry entry : nodeTypeCapabilitiesDefinition - .entrySet()) { - exposedCapabilitiesDefinition.put(entry.getKey(), entry.getValue()); - } - return exposedCapabilitiesDefinition; - } - - private boolean evaluateCapabilityFullFilament(CapabilityDefinition capabilityDefinition) { - Object[] occurrences = capabilityDefinition.getOccurrences(); - if (occurrences == null) { - capabilityDefinition.setOccurrences(new Object[]{"0", ToscaConstants.UNBOUNDED}); - return false; - } - if (occurrences[1].equals(ToscaConstants.UNBOUNDED)) { - return false; - } - - if (occurrences[1].equals(1)) { - return true; - } - occurrences[1] = (Integer) occurrences[1] - 1; - return false; - } - - private boolean evaluateRequirementFullFilament(RequirementDefinition requirementDefinition) { - Object[] occurrences = requirementDefinition.getOccurrences(); - if (occurrences == null) { - requirementDefinition.setOccurrences(new Object[]{"0", ToscaConstants.UNBOUNDED}); - return false; - } - if (occurrences[1].equals(ToscaConstants.UNBOUNDED)) { - return false; - } - - if (occurrences[1].equals(1)) { - return true; - } - occurrences[1] = (Integer) occurrences[1] - 1; - return false; - } - - private void getNodeTypeCapabilities( - Map nodeTypeCapabilitiesDefinition, - Map> capabilitySubstitutionMapping, String type, String templateName, - ServiceTemplate serviceTemplate, TranslationContext context) { - NodeType nodeType = getNodeTypeWithFlatHierarchy(type, serviceTemplate, context); - String capabilityKey; - List capabilityMapping; - if (nodeType.getCapabilities() != null) { - for (Map.Entry capabilityNodeEntry : nodeType.getCapabilities() - .entrySet()) { - capabilityKey = capabilityNodeEntry.getKey() + "_" + templateName; - nodeTypeCapabilitiesDefinition.put(capabilityKey, capabilityNodeEntry.getValue().clone()); - capabilityMapping = new ArrayList<>(); - capabilityMapping.add(templateName); - capabilityMapping.add(capabilityNodeEntry.getKey()); - capabilitySubstitutionMapping.put(capabilityKey, capabilityMapping); - } - } - - String derivedFrom = nodeType.getDerived_from(); - if (derivedFrom != null) { - getNodeTypeCapabilities(nodeTypeCapabilitiesDefinition, capabilitySubstitutionMapping, - derivedFrom, templateName, serviceTemplate, context); - } - } - - private List> calculateExposedRequirements( - List> nodeTypeRequirementsDefinitionList, - Map nodeTemplateRequirementsAssignment) { - if (nodeTypeRequirementsDefinitionList == null) { - return null; - } - for (Map.Entry entry : nodeTemplateRequirementsAssignment - .entrySet()) { - if (entry.getValue().getNode() != null) { - RequirementDefinition requirementDefinition = - getRequirementDefinition(nodeTypeRequirementsDefinitionList, entry.getKey()); - RequirementDefinition cloneRequirementDefinition; - if (requirementDefinition != null) { - cloneRequirementDefinition = requirementDefinition.clone(); - if (!evaluateRequirementFullFilament(cloneRequirementDefinition)) { - this.mergeEntryInList(entry.getKey(), cloneRequirementDefinition, - nodeTypeRequirementsDefinitionList); - } else { - removeRequirementsDefinition(nodeTypeRequirementsDefinitionList, entry.getKey()); - } - } - } else { - for (Map nodeTypeRequirementsMap - : nodeTypeRequirementsDefinitionList) { - Object max = nodeTypeRequirementsMap.get(entry.getKey()).getOccurrences() != null - && nodeTypeRequirementsMap.get(entry.getKey()).getOccurrences().length > 0 - ? nodeTypeRequirementsMap.get(entry.getKey()).getOccurrences()[1] : 1; - Object min = nodeTypeRequirementsMap.get(entry.getKey()).getOccurrences() != null - && nodeTypeRequirementsMap.get(entry.getKey()).getOccurrences().length > 0 - ? nodeTypeRequirementsMap.get(entry.getKey()).getOccurrences()[0] : 1; - nodeTypeRequirementsMap.get(entry.getKey()).setOccurrences(new Object[]{min, max}); - } - } - } - return nodeTypeRequirementsDefinitionList; - } - - private void removeRequirementsDefinition( - List> nodeTypeRequirementsDefinitionList, - String requirementKey) { - for (Map reqMap : nodeTypeRequirementsDefinitionList) { - reqMap.remove(requirementKey); - } - } - - private RequirementDefinition getRequirementDefinition( - List> nodeTypeRequirementsDefinitionList, - String requirementKey) { - for (Map requirementMap : nodeTypeRequirementsDefinitionList) { - if (requirementMap.containsKey(requirementKey)) { - return requirementMap.get(requirementKey); - } - } - return null; - } - - private Map getNodeTemplateRequirements(NodeTemplate template) { - List> templateRequirements = template.getRequirements(); - - Map nodeTemplateRequirementsDefinition = new HashMap<>(); - if (CollectionUtils.isEmpty(templateRequirements)) { - return nodeTemplateRequirementsDefinition; - } - for (Map requirementAssignmentMap : templateRequirements) { - for (Map.Entry requirementEntry : requirementAssignmentMap - .entrySet()) { - nodeTemplateRequirementsDefinition - .put(requirementEntry.getKey(), requirementEntry.getValue()); - } - } - return nodeTemplateRequirementsDefinition; - } - - private List> getNodeTypeRequirements(String type, - String templateName, - ServiceTemplate serviceTemplate, - Map> requirementSubstitutionMapping, - TranslationContext context) { - List> requirementList = null; - NodeType nodeType = getNodeTypeWithFlatHierarchy(type, serviceTemplate, context); - String derivedFrom = nodeType.getDerived_from(); - List requirementMapping; - if (derivedFrom != null) { - requirementList = getNodeTypeRequirements(derivedFrom, templateName, serviceTemplate, - requirementSubstitutionMapping, context); - } - if (requirementList == null) { - requirementList = new ArrayList<>(); - } - - if (nodeType.getRequirements() != null) { - for (Map requirementMap : nodeType.getRequirements()) { - for (Map.Entry requirementNodeEntry : requirementMap - .entrySet()) { - if (requirementNodeEntry.getValue().getOccurrences() == null) { - requirementNodeEntry.getValue().setOccurrences(new Object[]{1, 1}); - } - Map requirementDef = new HashMap<>(); - requirementDef.put(requirementNodeEntry.getKey(), requirementNodeEntry.getValue()); - addRequirementToList(requirementList, requirementDef); - requirementMapping = new ArrayList<>(); - requirementMapping.add(templateName); - requirementMapping.add(requirementNodeEntry.getKey()); - requirementSubstitutionMapping - .put(requirementNodeEntry.getKey() + "_" + templateName, requirementMapping); - if (requirementNodeEntry.getValue().getNode() == null) { - requirementNodeEntry.getValue().setOccurrences(new Object[]{1, 1}); - } - } - } - } - - return requirementList; - } - - private void addRequirementToList(List> requirementList, - Map requirementDef) { - for (Map.Entry entry : requirementDef.entrySet()) { - this.mergeEntryInList(entry.getKey(), entry.getValue(), requirementList); - } - } - - private void addSubstitutionNodeTypeCapabilities(NodeType substitutionNodeType, - Map capabilities) { - if (capabilities == null || capabilities.entrySet().size() == 0) { - return; - } - - if (MapUtils.isEmpty(substitutionNodeType.getCapabilities())) { - substitutionNodeType.setCapabilities(new HashMap<>()); - } - if (capabilities.size() > 0) { - substitutionNodeType.setCapabilities(new HashMap<>()); - } - for (Map.Entry entry : capabilities.entrySet()) { - substitutionNodeType.getCapabilities().put(entry.getKey(), entry.getValue()); - } - } - - private void addSubstitutionNodeTypeRequirements(NodeType substitutionNodeType, - List> requirementsList, - String templateName) { - if (requirementsList == null || requirementsList.size() == 0) { - return; - } - - if (substitutionNodeType.getRequirements() == null) { - substitutionNodeType.setRequirements(new ArrayList<>()); - } - - for (Map requirementDef : requirementsList) { - for (Map.Entry entry : requirementDef.entrySet()) { - Map requirementMap = new HashMap<>(); - requirementMap.put(entry.getKey() + "_" + templateName, entry.getValue().clone()); - substitutionNodeType.getRequirements().add(requirementMap); - } - } - } - - - private SubstitutionMapping manageSubstitutionTemplateSubstitutionMapping(String nodeTypeKey, - NodeType substitutionNodeType, - Map>> mapping) { - SubstitutionMapping substitutionMapping = new SubstitutionMapping(); - substitutionMapping.setNode_type(nodeTypeKey); - substitutionMapping.setCapabilities( - manageCapabilityMapping(substitutionNodeType.getCapabilities(), mapping.get("capability"))); - substitutionMapping.setRequirements( - manageRequirementMapping(substitutionNodeType.getRequirements(), - mapping.get("requirement"))); - return substitutionMapping; - } - - private Map> manageCapabilityMapping( - Map capabilities, - Map> capabilitySubstitutionMapping) { - if (capabilities == null) { - return null; - } - - Map> capabilityMapping = new HashMap<>(); - String capabilityKey; - List capabilityMap; - for (Map.Entry entry : capabilities.entrySet()) { - capabilityKey = entry.getKey(); - capabilityMap = capabilitySubstitutionMapping.get(capabilityKey); - capabilityMapping.put(capabilityKey, capabilityMap); - } - return capabilityMapping; - } - - private Map> manageRequirementMapping( - List> requirementList, - Map> requirementSubstitutionMapping) { - if (requirementList == null) { - return null; - } - Map> requirementMapping = new HashMap<>(); - String requirementKey; - List requirementMap; - for (Map requirementDefMap : requirementList) { - for (Map.Entry entry : requirementDefMap.entrySet()) { - requirementKey = entry.getKey(); - requirementMap = requirementSubstitutionMapping.get(requirementKey); - requirementMapping.put(requirementKey, requirementMap); - } - } - return requirementMapping; - } - - - private Map manageSubstitutionNodeTypeAttributes( - ServiceTemplate substitutionServiceTemplate) { - - Map substitutionNodeTypeAttributes = new HashMap<>(); - Map attributes = - substitutionServiceTemplate.getTopology_template().getOutputs(); - if (attributes == null) { - return null; - } - AttributeDefinition attributeDefinition; - String toscaAttributeName; - - for (Map.Entry entry : attributes.entrySet()) { - attributeDefinition = new AttributeDefinition(); - toscaAttributeName = entry.getKey(); - ParameterDefinition parameterDefinition = - substitutionServiceTemplate.getTopology_template().getOutputs().get(toscaAttributeName); - if (parameterDefinition.getType() != null && !parameterDefinition.getType().isEmpty()) { - attributeDefinition.setType(parameterDefinition.getType()); - } else { - attributeDefinition.setType(PropertyType.STRING.getDisplayName()); - } - attributeDefinition.setDescription(parameterDefinition.getDescription()); - attributeDefinition.set_default(parameterDefinition.get_default()); - attributeDefinition.setEntry_schema(parameterDefinition.getEntry_schema()); - attributeDefinition.setStatus(parameterDefinition.getStatus()); - substitutionNodeTypeAttributes.put(toscaAttributeName, attributeDefinition); - } - return substitutionNodeTypeAttributes; - } - - private Map manageSubstitutionNodeTypeProperties( - ServiceTemplate substitutionServiceTemplate) { - Map substitutionNodeTypeProperties = new HashMap<>(); - Map properties = - substitutionServiceTemplate.getTopology_template().getInputs(); - if (properties == null) { - return null; - } - - PropertyDefinition propertyDefinition; - String toscaPropertyName; - for (Map.Entry entry : properties.entrySet()) { - toscaPropertyName = entry.getKey(); - propertyDefinition = new PropertyDefinition(); - ParameterDefinition parameterDefinition = - substitutionServiceTemplate.getTopology_template().getInputs().get(toscaPropertyName); - propertyDefinition.setType(parameterDefinition.getType()); - propertyDefinition.setDescription(parameterDefinition.getDescription()); - propertyDefinition.setRequired(parameterDefinition.getRequired()); - propertyDefinition.set_default(parameterDefinition.get_default()); - propertyDefinition.setConstraints(parameterDefinition.getConstraints()); - propertyDefinition.setEntry_schema(parameterDefinition.getEntry_schema()); - propertyDefinition.setStatus(parameterDefinition.getStatus()); - substitutionNodeTypeProperties.put(toscaPropertyName, propertyDefinition); - } - return substitutionNodeTypeProperties; - } - - private Map managerSubstitutionNodeTemplateProperties(TranslateTo translateTo, - Template template, - String templateName) { - Map substitutionProperties = new HashMap<>(); - Map heatProperties = translateTo.getResource().getProperties(); - if (Objects.nonNull(heatProperties)) { - for (Map.Entry entry : heatProperties.entrySet()) { - - Object property = TranslatorHeatToToscaPropertyConverter - .getToscaPropertyValue(entry.getKey(), entry.getValue(), null, - translateTo.getHeatFileName(), translateTo.getHeatOrchestrationTemplate(), template, - translateTo.getContext()); - substitutionProperties.put(entry.getKey(), property); - } - } - - return addAbstractSubstitutionProperty(templateName, substitutionProperties); - } - - private Map addAbstractSubstitutionProperty(String templateName, - Map substitutionProperties) { - Map innerProps = new HashMap<>(); - innerProps.put(ToscaConstants.SUBSTITUTE_SERVICE_TEMPLATE_PROPERTY_NAME, - ToscaUtil.getServiceTemplateFileName(templateName)); - substitutionProperties.put(ToscaConstants.SERVICE_TEMPLATE_FILTER_PROPERTY_NAME, innerProps); - return substitutionProperties; - } - - -} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationNeutronNetImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationNeutronNetImpl.java deleted file mode 100644 index 0b4ed61753..0000000000 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationNeutronNetImpl.java +++ /dev/null @@ -1,52 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.translator.services.heattotosca.impl; - -import org.openecomp.sdc.tosca.datatypes.ToscaNodeType; -import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; -import org.openecomp.sdc.tosca.services.DataModelUtil; -import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; -import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; -import org.openecomp.sdc.translator.services.heattotosca.mapping.TranslatorHeatToToscaPropertyConverter; - -public class ResourceTranslationNeutronNetImpl extends ResourceTranslationBase { - - @Override - public void translate(TranslateTo translateTo) { - - NodeTemplate nodeTemplate = new NodeTemplate(); - nodeTemplate.setType(ToscaNodeType.NEUTRON_NET.getDisplayName()); - nodeTemplate.setProperties(TranslatorHeatToToscaPropertyConverter - .getToscaPropertiesSimpleConversion(translateTo.getResource().getProperties(), - nodeTemplate.getProperties(), translateTo.getHeatFileName(), - translateTo.getHeatOrchestrationTemplate(), translateTo.getResource().getType(), - nodeTemplate, translateTo.getContext())); - - HeatToToscaUtil.mapBoolean(nodeTemplate, "port_security_enabled"); - HeatToToscaUtil.mapBoolean(nodeTemplate, "shared"); - HeatToToscaUtil.mapBoolean(nodeTemplate, "admin_state_up"); - - DataModelUtil.addNodeTemplate(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), - nodeTemplate); - } - - -} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationNeutronPortImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationNeutronPortImpl.java deleted file mode 100644 index 343462d266..0000000000 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationNeutronPortImpl.java +++ /dev/null @@ -1,233 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.translator.services.heattotosca.impl; - -import org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes; -import org.openecomp.sdc.heat.datatypes.model.Resource; -import org.openecomp.sdc.tosca.datatypes.ToscaCapabilityType; -import org.openecomp.sdc.tosca.datatypes.ToscaNodeType; -import org.openecomp.sdc.tosca.datatypes.ToscaRelationshipType; -import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; -import org.openecomp.sdc.tosca.datatypes.model.RequirementAssignment; -import org.openecomp.sdc.tosca.services.DataModelUtil; -import org.openecomp.sdc.tosca.services.ToscaConstants; -import org.openecomp.sdc.translator.datatypes.heattotosca.AttachedResourceId; -import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; -import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslatedHeatResource; -import org.openecomp.sdc.translator.services.heattotosca.Constants; -import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; -import org.openecomp.sdc.translator.services.heattotosca.ResourceTranslationFactory; -import org.openecomp.sdc.translator.services.heattotosca.mapping.TranslatorHeatToToscaPropertyConverter; - -import java.util.Arrays; -import java.util.Collections; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - - -public class ResourceTranslationNeutronPortImpl extends ResourceTranslationBase { - - @Override - public void translate(TranslateTo translateTo) { - - NodeTemplate nodeTemplate = new NodeTemplate(); - nodeTemplate.setType(ToscaNodeType.NEUTRON_PORT.getDisplayName()); - - nodeTemplate.setProperties(TranslatorHeatToToscaPropertyConverter - .getToscaPropertiesSimpleConversion(translateTo.getResource().getProperties(), - nodeTemplate.getProperties(), translateTo.getHeatFileName(), - translateTo.getHeatOrchestrationTemplate(), translateTo.getResource().getType(), - nodeTemplate, translateTo.getContext())); - handleNetworkRequirement(translateTo, nodeTemplate); - String resourceTranslatedId = handleSecurityRulesRequirement(translateTo); - DataModelUtil - .addNodeTemplate(translateTo.getServiceTemplate(), resourceTranslatedId, nodeTemplate); - } - - private String handleSecurityRulesRequirement(TranslateTo translateTo) { - String resourceTranslatedId = translateTo.getTranslatedId(); - Map properties = translateTo.getResource().getProperties(); - Optional securityGroups = - Optional.ofNullable(properties.get(Constants.SECURITY_GROUPS_PROPERTY_NAME)); - if (securityGroups.isPresent() && securityGroups.get() instanceof List) { - List securityGroupsList = (List) securityGroups.get(); - securityGroupsList.forEach(resourceValue -> { - Optional securityGroupResourceId = HeatToToscaUtil - .extractAttachedResourceId(translateTo.getHeatFileName(), - translateTo.getHeatOrchestrationTemplate(), translateTo.getContext(), - resourceValue); - if (securityGroupResourceId.isPresent()) { - handleSecurityGroupResourceId(translateTo, resourceTranslatedId, - securityGroupResourceId.get()); - } - }); - } - return resourceTranslatedId; - } - - private void handleSecurityGroupResourceId(TranslateTo translateTo, String resourceTranslatedId, - AttachedResourceId securityGroupResourceId) { - List supportedSecurityGroupsTypes = Collections - .singletonList(HeatResourcesTypes.NEUTRON_SECURITY_GROUP_RESOURCE_TYPE.getHeatResource()); - if (securityGroupResourceId.isGetResource()) { - handleGetResource(translateTo, resourceTranslatedId, securityGroupResourceId, - supportedSecurityGroupsTypes); - } else if (securityGroupResourceId.isGetParam()) { - handleGetParam(translateTo, resourceTranslatedId, securityGroupResourceId, - supportedSecurityGroupsTypes); - } - } - - private void handleGetParam(TranslateTo translateTo, String resourceTranslatedId, - AttachedResourceId securityGroupResourceId, - List supportedSecurityGroupsTypes) { - TranslatedHeatResource translatedSharedResourceId = - translateTo.getContext().getHeatSharedResourcesByParam() - .get(securityGroupResourceId.getEntityId()); - if (Objects.nonNull(translatedSharedResourceId) - && !HeatToToscaUtil.isHeatFileNested(translateTo, translateTo.getHeatFileName())) { - if (validateResourceTypeSupportedForReqCreation(translateTo, supportedSecurityGroupsTypes, - translatedSharedResourceId.getHeatResource(), "security_groups")) { - return; - } - final NodeTemplate securityGroupNodeTemplate = DataModelUtil - .getNodeTemplate(translateTo.getServiceTemplate(), - translatedSharedResourceId.getTranslatedId()); - RequirementAssignment requirement = new RequirementAssignment(); - requirement.setCapability(ToscaCapabilityType.ATTACHMENT.getDisplayName()); - requirement.setNode(resourceTranslatedId); - requirement.setRelationship(ToscaRelationshipType.ATTACHES_TO.getDisplayName()); - DataModelUtil - .addRequirementAssignment(securityGroupNodeTemplate, ToscaConstants.PORT_REQUIREMENT_ID, - requirement); - } - } - - private void handleGetResource(TranslateTo translateTo, String resourceTranslatedId, - AttachedResourceId securityGroupResourceId, - List supportedSecurityGroupsTypes) { - String resourceId = (String) securityGroupResourceId.getEntityId(); - Resource securityGroupResource = HeatToToscaUtil - .getResource(translateTo.getHeatOrchestrationTemplate(), resourceId, - translateTo.getHeatFileName()); - Optional securityGroupTranslatedId = - ResourceTranslationFactory.getInstance(securityGroupResource) - .translateResource(translateTo.getHeatFileName(), translateTo.getServiceTemplate(), - translateTo.getHeatOrchestrationTemplate(), securityGroupResource, resourceId, - translateTo.getContext()); - if (securityGroupTranslatedId.isPresent()) { - if (validateResourceTypeSupportedForReqCreation(translateTo, supportedSecurityGroupsTypes, - securityGroupResource, "security_groups")) { - return; - } - final NodeTemplate securityGroupNodeTemplate = DataModelUtil - .getNodeTemplate(translateTo.getServiceTemplate(), securityGroupTranslatedId.get()); - RequirementAssignment requirement = new RequirementAssignment(); - requirement.setCapability(ToscaCapabilityType.ATTACHMENT.getDisplayName()); - requirement.setNode(resourceTranslatedId); - requirement.setRelationship(ToscaRelationshipType.ATTACHES_TO.getDisplayName()); - DataModelUtil - .addRequirementAssignment(securityGroupNodeTemplate, ToscaConstants.PORT_REQUIREMENT_ID, - requirement); - } - } - - private void handleNetworkRequirement(TranslateTo translateTo, NodeTemplate nodeTemplate) { - Optional networkResourceId = - HeatToToscaUtil.extractAttachedResourceId(translateTo, "network"); - if (networkResourceId.isPresent()) { - AttachedResourceId attachedResourceId = networkResourceId.get(); - addRequirementAssignmentForNetworkResource(translateTo, nodeTemplate, attachedResourceId); - } else { - networkResourceId = HeatToToscaUtil.extractAttachedResourceId(translateTo, "network_id"); - if (networkResourceId.isPresent()) { - AttachedResourceId attachedResourceId = networkResourceId.get(); - addRequirementAssignmentForNetworkResource(translateTo, nodeTemplate, attachedResourceId); - } - } - } - - private void addRequirementAssignmentForNetworkResource(TranslateTo translateTo, - NodeTemplate nodeTemplate, - AttachedResourceId attachedResourceId) { - String networkTranslatedId; - List supportedNetworkTypes = - Arrays.asList(HeatResourcesTypes.NEUTRON_NET_RESOURCE_TYPE.getHeatResource(), - HeatResourcesTypes.CONTRAIL_VIRTUAL_NETWORK_RESOURCE_TYPE.getHeatResource(), - HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_NETWORK_RESOURCE_TYPE.getHeatResource()); - if (attachedResourceId.isGetResource()) { - Resource networkHeatResource = translateTo.getHeatOrchestrationTemplate().getResources() - .get(attachedResourceId.getEntityId()); - if (validateResourceTypeSupportedForReqCreation(translateTo, supportedNetworkTypes, - networkHeatResource, "network'\\'network_id")) { - return; - } - networkTranslatedId = (String) attachedResourceId.getTranslatedId(); - addRequirementAssignment(nodeTemplate, networkTranslatedId); - } else if (attachedResourceId.isGetParam()) { - TranslatedHeatResource translatedSharedResourceId = - translateTo.getContext().getHeatSharedResourcesByParam() - .get(attachedResourceId.getEntityId()); - if (Objects.nonNull(translatedSharedResourceId) - && !HeatToToscaUtil.isHeatFileNested(translateTo, translateTo.getHeatFileName())) { - if (validateResourceTypeSupportedForReqCreation(translateTo, supportedNetworkTypes, - translatedSharedResourceId.getHeatResource(), "network'\\'network_id")) { - return; - } - addRequirementAssignment(nodeTemplate, translatedSharedResourceId.getTranslatedId()); - } - } - } - - private void addRequirementAssignment(NodeTemplate nodeTemplate, String translatedId) { - RequirementAssignment requirement = new RequirementAssignment(); - requirement.setCapability(ToscaCapabilityType.NETWORK_LINKABLE.getDisplayName()); - requirement.setRelationship(ToscaRelationshipType.NETWORK_LINK_TO.getDisplayName()); - requirement.setNode(translatedId); - DataModelUtil - .addRequirementAssignment(nodeTemplate, ToscaConstants.LINK_REQUIREMENT_ID, requirement); - } - - - private boolean validateResourceTypeSupportedForReqCreation(TranslateTo translateTo, - List supportedTypes, - Resource heatResource, - final String propertyName) { - if (!isResourceTypeValidForRequirement(heatResource, supportedTypes)) { - logger.warn( - "'" + propertyName + "' property of port resource('" + translateTo.getResourceId() - + "') is pointing to a resource of type '" + heatResource.getType() + "' " - + "which is not supported for this requirement. " - + "Supported types are: " + supportedTypes.toString()); - return true; - } - return false; - } - - private boolean isResourceTypeValidForRequirement(Resource networkHeatResource, - List supportedNetworkTypes) { - return Objects.nonNull(networkHeatResource) - && supportedNetworkTypes.contains(networkHeatResource.getType()); - } - -} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationNeutronSecurityGroupImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationNeutronSecurityGroupImpl.java deleted file mode 100644 index cacaf4c5c7..0000000000 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationNeutronSecurityGroupImpl.java +++ /dev/null @@ -1,47 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.translator.services.heattotosca.impl; - -import org.openecomp.sdc.tosca.datatypes.ToscaNodeType; -import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; -import org.openecomp.sdc.tosca.services.DataModelUtil; -import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; -import org.openecomp.sdc.translator.services.heattotosca.mapping.TranslatorHeatToToscaPropertyConverter; - -public class ResourceTranslationNeutronSecurityGroupImpl extends ResourceTranslationBase { - - @Override - public void translate(TranslateTo translateTo) { - - NodeTemplate nodeTemplate = new NodeTemplate(); - nodeTemplate.setType(ToscaNodeType.NEUTRON_SECURITY_RULES.getDisplayName()); - nodeTemplate.setProperties(TranslatorHeatToToscaPropertyConverter - .getToscaPropertiesSimpleConversion(translateTo.getResource().getProperties(), - nodeTemplate.getProperties(), translateTo.getHeatFileName(), - translateTo.getHeatOrchestrationTemplate(), translateTo.getResource().getType(), - nodeTemplate, translateTo.getContext())); - - DataModelUtil.addNodeTemplate(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), - nodeTemplate); - } - - -} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationNeutronSubnetImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationNeutronSubnetImpl.java deleted file mode 100644 index 8306f57146..0000000000 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationNeutronSubnetImpl.java +++ /dev/null @@ -1,170 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.translator.services.heattotosca.impl; - -import org.openecomp.sdc.common.errors.CoreException; -import org.openecomp.sdc.heat.datatypes.HeatBoolean; -import org.openecomp.sdc.heat.datatypes.model.Resource; -import org.openecomp.sdc.tosca.datatypes.ToscaFunctions; -import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; -import org.openecomp.sdc.tosca.datatypes.model.ParameterDefinition; -import org.openecomp.sdc.tosca.datatypes.model.PropertyType; -import org.openecomp.sdc.tosca.services.DataModelUtil; -import org.openecomp.sdc.tosca.services.ToscaConstants; -import org.openecomp.sdc.translator.datatypes.heattotosca.AttachedResourceId; -import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; - -import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; -import org.openecomp.sdc.translator.services.heattotosca.ResourceTranslationFactory; -import org.openecomp.sdc.translator.services.heattotosca.errors.MissingMandatoryPropertyErrorBuilder; -import org.openecomp.sdc.translator.services.heattotosca.mapping.TranslatorHeatToToscaPropertyConverter; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.HashMap; -import java.util.Map; -import java.util.Optional; - -public class ResourceTranslationNeutronSubnetImpl extends ResourceTranslationBase { - protected static Logger logger = - LoggerFactory.getLogger(ResourceTranslationNeutronSubnetImpl.class); - - @Override - protected String generateTranslatedId(TranslateTo translateTo) { - Optional subnetNetwork = getAttachedNetworkResource(translateTo); - - if (!subnetNetwork.get().isGetResource()) { - logger.warn("Heat resource: '" + translateTo.getResourceId() + "' with type: '" - + translateTo.getResource().getType() - + "' include 'network_id/'network'' property without 'get_resource' function," - + " therefore this resource will be ignored in TOSCA translation."); - return null; - } - return (String) subnetNetwork.get().getTranslatedId(); - } - - @Override - public void translate(TranslateTo translateTo) { - - Optional subnetNetwork = getAttachedNetworkResource(translateTo); - - if (!subnetNetwork.get().isGetResource()) { - return; - } - - Resource networkResource = HeatToToscaUtil - .getResource(translateTo.getHeatOrchestrationTemplate(), - (String) subnetNetwork.get().getEntityId(), translateTo.getHeatFileName()); - Optional translatedNetworkId = ResourceTranslationFactory.getInstance(networkResource) - .translateResource(translateTo.getHeatFileName(), translateTo.getServiceTemplate(), - translateTo.getHeatOrchestrationTemplate(), networkResource, - (String) subnetNetwork.get().getEntityId(), translateTo.getContext()); - if (translatedNetworkId.isPresent()) { - NodeTemplate networkNodeTemplate = DataModelUtil - .getNodeTemplate(translateTo.getServiceTemplate(), translatedNetworkId.get()); - - Map> subNetMap = - (Map>) networkNodeTemplate.getProperties().get("subnets"); - if (subNetMap == null) { - subNetMap = new HashMap<>(); - networkNodeTemplate.getProperties().put("subnets", subNetMap); - TranslatorHeatToToscaPropertyConverter - .setSimpleProperty(translateTo.getResource().getProperties(), - translateTo.getHeatFileName(), translateTo.getResource().getType(), - translateTo.getHeatOrchestrationTemplate(), translateTo.getContext(), - networkNodeTemplate.getProperties(), "enable_dhcp", - ToscaConstants.DHCP_ENABLED_PROPERTY_NAME, networkNodeTemplate); //dhcp_enabled - TranslatorHeatToToscaPropertyConverter - .setSimpleProperty(translateTo.getResource().getProperties(), - translateTo.getHeatFileName(), translateTo.getResource().getType(), - translateTo.getHeatOrchestrationTemplate(), translateTo.getContext(), - networkNodeTemplate.getProperties(), "ip_version", null, networkNodeTemplate); - handleDhcpProperty(translateTo, networkNodeTemplate); - } - - Map properties; - properties = TranslatorHeatToToscaPropertyConverter - .getToscaPropertiesSimpleConversion(translateTo.getResource().getProperties(), null, - translateTo.getHeatFileName(), translateTo.getHeatOrchestrationTemplate(), - translateTo.getResource().getType(), networkNodeTemplate, translateTo.getContext()); - - subNetMap.put(translateTo.getResourceId(), properties); - } - } - - private void handleDhcpProperty(TranslateTo translateTo, NodeTemplate networkNodeTemplate) { - Object dhcpEnabled = - networkNodeTemplate.getProperties().get(ToscaConstants.DHCP_ENABLED_PROPERTY_NAME); - if (dhcpEnabled instanceof Map) { - Object dhcpEnabledParameterName = - ((Map) dhcpEnabled).get(ToscaFunctions.GET_INPUT.getDisplayName()); - if (dhcpEnabledParameterName != null) { - ParameterDefinition dhcpParameterDefinition = null; - if (translateTo.getServiceTemplate().getTopology_template().getInputs() != null) { - dhcpParameterDefinition = - translateTo.getServiceTemplate().getTopology_template().getInputs() - .get(dhcpEnabledParameterName); - } - if (dhcpParameterDefinition == null) { - logger.warn("Missing input parameter " + dhcpEnabledParameterName); - } else { - Object defaultVal = dhcpParameterDefinition.get_default(); - if (defaultVal != null) { - try { - Boolean booleanValue = HeatBoolean.eval(defaultVal); - dhcpParameterDefinition.set_default(booleanValue); - } catch (CoreException coreException) { - //if value is not valid value for boolean set with dhcp_enabled default value = true - dhcpParameterDefinition.set_default(true); - logger.warn("Parameter '" + dhcpEnabledParameterName + "' used for " - + ToscaConstants.DHCP_ENABLED_PROPERTY_NAME - + " boolean property, but it's value is not a valid boolean value, therefore " - + ToscaConstants.DHCP_ENABLED_PROPERTY_NAME - + " property will be set with default value of 'true'."); - } - dhcpParameterDefinition.setType(PropertyType.BOOLEAN.getDisplayName()); - } - } - } - } - } - - private Optional getAttachedNetworkResource(TranslateTo translateTo) { - Optional subnetNetwork = Optional.empty(); - Optional attachedNetworkId = - HeatToToscaUtil.extractAttachedResourceId(translateTo, "network_id"); - if (!attachedNetworkId.isPresent()) { - Optional attachedNetwork = - HeatToToscaUtil.extractAttachedResourceId(translateTo, "network"); - if (!attachedNetwork.isPresent()) { - throw new CoreException( - new MissingMandatoryPropertyErrorBuilder("network_id/'network'").build()); - } else { - subnetNetwork = attachedNetwork; - } - } else { - subnetNetwork = attachedNetworkId; - } - return subnetNetwork; - } -} - - diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationNovaServerGroupsImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationNovaServerGroupsImpl.java deleted file mode 100644 index 7bc0a10957..0000000000 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationNovaServerGroupsImpl.java +++ /dev/null @@ -1,119 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.translator.services.heattotosca.impl; - -import org.apache.commons.collections4.CollectionUtils; -import org.openecomp.sdc.heat.datatypes.model.Resource; -import org.openecomp.sdc.tosca.datatypes.ToscaGroupType; -import org.openecomp.sdc.tosca.datatypes.ToscaPolicyType; -import org.openecomp.sdc.tosca.datatypes.model.GroupDefinition; -import org.openecomp.sdc.tosca.datatypes.model.PolicyDefinition; -import org.openecomp.sdc.tosca.services.DataModelUtil; -import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; -import org.openecomp.sdc.translator.services.heattotosca.mapping.TranslatorHeatToToscaPropertyConverter; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.List; -import java.util.Map; -import java.util.Objects; - -public class ResourceTranslationNovaServerGroupsImpl extends ResourceTranslationBase { - private static final String AFFINITY = "affinity"; - private static final String ANTI_AFFINITY = "anti-affinity"; - private static List supportedPolicies = Arrays.asList(AFFINITY, ANTI_AFFINITY); - - @Override - protected void translate(TranslateTo translateTo) { - String resourceId = translateTo.getResourceId(); - List toscaPolicyTypes = getToscaPolicies(translateTo.getResource(), resourceId); - if (!CollectionUtils.isEmpty(toscaPolicyTypes)) { - addGroupToTopology(translateTo, resourceId); - addPoliciesToTopology(translateTo, resourceId, toscaPolicyTypes); - } - } - - private void addPoliciesToTopology(TranslateTo translateTo, String resourceId, - List toscaPolicyTypes) { - logger.info("******** Start creating policies for resource '%s' ********", resourceId); - for (int i = 0; i < toscaPolicyTypes.size(); i++) { - String policy = toscaPolicyTypes.get(i); - logger.info("******** Creating policy '%s' ********", policy); - PolicyDefinition policyDefinition = new PolicyDefinition(); - policyDefinition.setType(policy); - policyDefinition.setTargets(Arrays.asList(resourceId)); - policyDefinition.setProperties(TranslatorHeatToToscaPropertyConverter - .getToscaPropertiesSimpleConversion(translateTo.getResource().getProperties(), - policyDefinition.getProperties(), translateTo.getHeatFileName(), - translateTo.getHeatOrchestrationTemplate(), translateTo.getResource().getType(), - policyDefinition, translateTo.getContext())); - policyDefinition.getProperties().put( - policy.equals(ToscaPolicyType.PLACEMENT_ANTILOCATE.getDisplayName()) ? "container_type" - : AFFINITY, "host"); - String policyId = resourceId + (toscaPolicyTypes.size() > 1 ? i : ""); - DataModelUtil - .addPolicyDefinition(translateTo.getServiceTemplate(), policyId, policyDefinition); - logger.info("******** Policy '%s' created ********", policy); - } - - logger - .info("******** All policies for resource '%s' created successfully ********", resourceId); - } - - private void addGroupToTopology(TranslateTo translateTo, String resourceId) { - logger.info("******** Start creating group for resource '%s' ********", resourceId); - GroupDefinition group = new GroupDefinition(); - group.setMembers(new ArrayList<>()); - group.setType(ToscaGroupType.ROOT.getDisplayName()); - DataModelUtil - .addGroupDefinitionToTopologyTemplate(translateTo.getServiceTemplate(), resourceId, group); - logger.info("******** Creating group '%s' for resource '%s' ********", resourceId, resourceId); - } - - private List getToscaPolicies(Resource resource, String resourceId) { - - Map properties = resource.getProperties(); - if (Objects.isNull(properties) || Objects.isNull(properties.get("policies"))) { - return Arrays.asList(ToscaPolicyType.PLACEMENT_ANTILOCATE.getDisplayName()); - } - - List policies = (List) properties.get("policies"); - List retList = new ArrayList<>(); - policies.forEach(policy -> { - if (!supportedPolicies.contains(policy)) { - logger.warn("Resource '" + resourceId + "'(" + resource.getType() - + ") contains unsupported policy '" + policy.toString() - + "'. This resource is been ignored during the translation"); - } else { - retList.add(getToscaPolicyByHotPolicy((String) policy)); - } - }); - return retList; - } - - private String getToscaPolicyByHotPolicy(String name) { - if (Objects.equals(name, AFFINITY)) { - return ToscaPolicyType.PLACEMENT_COLOCATE.getDisplayName(); - } else { - return ToscaPolicyType.PLACEMENT_ANTILOCATE.getDisplayName(); - } - } -} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationNovaServerImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationNovaServerImpl.java deleted file mode 100644 index 59e0691b2b..0000000000 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationNovaServerImpl.java +++ /dev/null @@ -1,419 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.translator.services.heattotosca.impl; - -import org.apache.commons.collections4.CollectionUtils; -import org.apache.commons.collections4.MapUtils; -import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate; -import org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes; -import org.openecomp.sdc.heat.datatypes.model.Resource; -import org.openecomp.sdc.tosca.datatypes.ToscaCapabilityType; -import org.openecomp.sdc.tosca.datatypes.ToscaNodeType; -import org.openecomp.sdc.tosca.datatypes.ToscaRelationshipType; -import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; -import org.openecomp.sdc.tosca.datatypes.model.NodeType; -import org.openecomp.sdc.tosca.datatypes.model.RelationshipTemplate; -import org.openecomp.sdc.tosca.datatypes.model.RequirementAssignment; -import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; -import org.openecomp.sdc.tosca.services.DataModelUtil; -import org.openecomp.sdc.tosca.services.ToscaConstants; -import org.openecomp.sdc.translator.datatypes.heattotosca.AttachedResourceId; -import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; -import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslatedHeatResource; -import org.openecomp.sdc.translator.services.heattotosca.Constants; -import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; -import org.openecomp.sdc.translator.services.heattotosca.ResourceTranslationFactory; -import org.openecomp.sdc.translator.services.heattotosca.TranslationContext; -import org.openecomp.sdc.translator.services.heattotosca.helper.NameExtractorService; -import org.openecomp.sdc.translator.services.heattotosca.helper.PropertyRegexMatcher; -import org.openecomp.sdc.translator.services.heattotosca.helper.impl.NameExtractorServiceImpl; -import org.openecomp.sdc.translator.services.heattotosca.mapping.TranslatorHeatToToscaPropertyConverter; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.ArrayList; -import java.util.Arrays; -import java.util.Collections; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; - -public class ResourceTranslationNovaServerImpl extends ResourceTranslationBase { - protected static Logger logger = LoggerFactory.getLogger(ResourceTranslationNovaServerImpl.class); - - @Override - protected void translate(TranslateTo translateTo) { - TranslationContext context = translateTo.getContext(); - Map properties = translateTo.getResource().getProperties(); - String heatFileName = translateTo.getHeatFileName(); - - ServiceTemplate serviceTemplate = translateTo.getServiceTemplate(); - - String nodeTypeRef = - createLocalNodeType(serviceTemplate, translateTo.getResource().getProperties(), - translateTo.getTranslatedId()); - - NodeTemplate novaNodeTemplate = new NodeTemplate(); - novaNodeTemplate.setType(nodeTypeRef); - HeatOrchestrationTemplate heatOrchestrationTemplate = - translateTo.getHeatOrchestrationTemplate(); - novaNodeTemplate.setProperties(TranslatorHeatToToscaPropertyConverter - .getToscaPropertiesSimpleConversion(properties, novaNodeTemplate.getProperties(), - heatFileName, heatOrchestrationTemplate, translateTo.getResource().getType(), - novaNodeTemplate, context)); - - manageNovaServerNetwork(heatFileName, serviceTemplate, heatOrchestrationTemplate, - translateTo.getResource(), translateTo.getTranslatedId(), context, novaNodeTemplate); - manageNovaServerBlockDeviceMapping(heatFileName, serviceTemplate, novaNodeTemplate, - heatOrchestrationTemplate, translateTo.getResource(), translateTo.getResourceId(), - translateTo.getTranslatedId(), context); - - manageNovaServerGroupMapping(translateTo, context, properties, heatFileName, serviceTemplate, - heatOrchestrationTemplate); - DataModelUtil.addNodeTemplate(serviceTemplate, translateTo.getTranslatedId(), novaNodeTemplate); - } - - private void manageNovaServerGroupMapping(TranslateTo translateTo, TranslationContext context, - Map properties, String heatFileName, - ServiceTemplate serviceTemplate, - HeatOrchestrationTemplate heatOrchestrationTemplate) { - if (isSchedulerHintsPropExist(properties)) { - Object schedulerHints = properties.get("scheduler_hints"); - if (schedulerHints instanceof Map) { - addServerGroupHintsToPoliciesProups(translateTo, context, heatFileName, serviceTemplate, - heatOrchestrationTemplate, (Map) schedulerHints); - } else { - logger.warn("'scheduler_hints' property of resource '" + translateTo.getResourceId() - + "' is not valid. This property should be a map"); - } - } - } - - private void addServerGroupHintsToPoliciesProups(TranslateTo translateTo, - TranslationContext context, String heatFileName, - ServiceTemplate serviceTemplate, - HeatOrchestrationTemplate heatOrchestrationTemplate, - Map schedulerHints) { - for (Object hint : schedulerHints.values()) { - Optional attachedResourceId = HeatToToscaUtil - .extractAttachedResourceId(heatFileName, heatOrchestrationTemplate, context, hint); - if (attachedResourceId.isPresent()) { - AttachedResourceId serverGroupResourceId = attachedResourceId.get(); - Object serverGroupResourceToTranslate = serverGroupResourceId.getEntityId(); - if (serverGroupResourceId.isGetResource()) { - boolean isHintOfTypeNovaServerGroup = - isHintOfTypeNovaServerGroup(heatOrchestrationTemplate, - serverGroupResourceToTranslate); - if (isHintOfTypeNovaServerGroup) { - addNovaServerToPolicyGroup(translateTo, context, heatFileName, serviceTemplate, - heatOrchestrationTemplate, (String) serverGroupResourceToTranslate); - } - } else if (serverGroupResourceId.isGetParam()) { - TranslatedHeatResource translatedServerGroupResource = - context.getHeatSharedResourcesByParam().get(serverGroupResourceToTranslate); - if (Objects.nonNull(translatedServerGroupResource) - && !HeatToToscaUtil.isHeatFileNested(translateTo, translateTo.getHeatFileName())) { - serviceTemplate.getTopology_template().getGroups() - .get(translatedServerGroupResource.getTranslatedId()).getMembers() - .add(translateTo.getTranslatedId()); - } - } - } - } - } - - private boolean isHintOfTypeNovaServerGroup(HeatOrchestrationTemplate heatOrchestrationTemplate, - Object resourceToTranslate) { - return heatOrchestrationTemplate.getResources().get(resourceToTranslate).getType() - .equals(HeatResourcesTypes.NOVA_SERVER_GROUP_RESOURCE_TYPE.getHeatResource()); - } - - private void addNovaServerToPolicyGroup(TranslateTo translateTo, TranslationContext context, - String heatFileName, ServiceTemplate serviceTemplate, - HeatOrchestrationTemplate heatOrchestrationTemplate, - String resourceToTranslate) { - Resource serverGroup = - HeatToToscaUtil.getResource(heatOrchestrationTemplate, resourceToTranslate, heatFileName); - Optional serverGroupTranslatedId = ResourceTranslationFactory.getInstance(serverGroup) - .translateResource(heatFileName, serviceTemplate, heatOrchestrationTemplate, serverGroup, - resourceToTranslate, context); - if (serverGroupTranslatedId.isPresent()) { - serviceTemplate.getTopology_template().getGroups().get(serverGroupTranslatedId.get()) - .getMembers().add(translateTo.getTranslatedId()); - } - } - - private boolean isSchedulerHintsPropExist(Map properties) { - return !MapUtils.isEmpty(properties) && Objects.nonNull(properties.get("scheduler_hints")); - } - - private void manageNovaServerBlockDeviceMapping(String heatFileName, - ServiceTemplate serviceTemplate, - NodeTemplate novaNodeTemplate, - HeatOrchestrationTemplate heatOrchestrationTemplate, - Resource resource, String resourceId, - String novaServerTranslatedId, - TranslationContext context) { - - List> blockDeviceMappingList = getBlockDeviceMappingList(resource); - if (CollectionUtils.isEmpty(blockDeviceMappingList)) { - return; - } - - Object volumeIdObject; - Object snapshotIdObject; - String volumeResourceId; - int index = 0; - for (Map blockDeviceMapping : blockDeviceMappingList) { - volumeIdObject = blockDeviceMapping.get("volume_id"); - snapshotIdObject = blockDeviceMapping.get("snapshot_id"); - - if (volumeIdObject == null && snapshotIdObject == null) { - logger.warn("Resource '" + resourceId - + "' has block_device_mapping property with empty/missing volume_id and snapshot_id " - + "properties. Entry number " - + (index + 1) + ", this entry will be ignored in TOSCA translation."); - index++; - continue; - } - if (volumeIdObject == null) { - String deviceName = (String) blockDeviceMapping.get("device_name"); - String relationshipId = novaServerTranslatedId + "_" + index; - - Optional attachedSnapshotId = HeatToToscaUtil - .extractAttachedResourceId(heatFileName, heatOrchestrationTemplate, context, - snapshotIdObject); - volumeResourceId = novaServerTranslatedId + "_" + attachedSnapshotId.get().getEntityId(); - createVolumeAttachesToRelationship(serviceTemplate, deviceName, novaServerTranslatedId, - volumeResourceId, relationshipId); - createCinderVolumeNodeTemplate(serviceTemplate, volumeResourceId, heatFileName, - blockDeviceMapping, heatOrchestrationTemplate, context); - connectNovaServerToVolume(novaNodeTemplate, volumeResourceId, relationshipId); - } else { - Optional attachedVolumeId = HeatToToscaUtil - .extractAttachedResourceId(heatFileName, heatOrchestrationTemplate, context, - volumeIdObject); - if (attachedVolumeId.get().isGetResource()) { - connectNovaServerToVolume(novaNodeTemplate, - (String) attachedVolumeId.get().getTranslatedId(), null); - } - } - index++; - } - } - - private void connectNovaServerToVolume(NodeTemplate novaNodeTemplate, String volumeResourceId, - String relationshipId) { - RequirementAssignment requirementAssignment = new RequirementAssignment(); - requirementAssignment.setCapability(ToscaCapabilityType.ATTACHMENT.getDisplayName()); - requirementAssignment.setNode(volumeResourceId); - if (relationshipId != null) { - requirementAssignment.setRelationship(relationshipId); - } else { - requirementAssignment - .setRelationship(ToscaRelationshipType.NATIVE_ATTACHES_TO.getDisplayName()); - } - DataModelUtil - .addRequirementAssignment(novaNodeTemplate, ToscaConstants.LOCAL_STORAGE_REQUIREMENT_ID, - requirementAssignment); - } - - private void createCinderVolumeNodeTemplate(ServiceTemplate serviceTemplate, - String volumeResourceId, String heatFileName, - Map blockDeviceMapping, - HeatOrchestrationTemplate heatOrchestrationTemplate, - TranslationContext context) { - NodeTemplate cinderVolumeNodeTemplate = new NodeTemplate(); - cinderVolumeNodeTemplate.setType(ToscaNodeType.CINDER_VOLUME.getDisplayName()); - cinderVolumeNodeTemplate.setProperties(TranslatorHeatToToscaPropertyConverter - .getToscaPropertiesSimpleConversion(blockDeviceMapping, null, heatFileName, - heatOrchestrationTemplate, - HeatResourcesTypes.CINDER_VOLUME_RESOURCE_TYPE.getHeatResource(), - cinderVolumeNodeTemplate, context)); - DataModelUtil.addNodeTemplate(serviceTemplate, volumeResourceId, cinderVolumeNodeTemplate); - } - - private void createVolumeAttachesToRelationship(ServiceTemplate serviceTemplate, - String deviceName, String novaServerTranslatedId, - String volumeId, String relationshipId) { - RelationshipTemplate relationshipTemplate = new RelationshipTemplate(); - relationshipTemplate.setType(ToscaRelationshipType.CINDER_VOLUME_ATTACHES_TO.getDisplayName()); - Map properties = new HashMap<>(); - properties.put("instance_uuid", novaServerTranslatedId); - properties.put("volume_id", volumeId); - if (deviceName != null) { - properties.put("device", deviceName); - } - relationshipTemplate.setProperties(properties); - - DataModelUtil.addRelationshipTemplate(serviceTemplate, relationshipId, relationshipTemplate); - } - - private List> getBlockDeviceMappingList(Resource resource) { - - if (Objects.isNull(resource.getProperties())) { - return Collections.emptyList(); - } - List> blockDeviceMappingList = - (List>) resource.getProperties().get("block_device_mapping"); - List> blockDeviceMappingV2List = - (List>) resource.getProperties().get("block_device_mapping_v2"); - - if (blockDeviceMappingList != null && blockDeviceMappingV2List != null) { - blockDeviceMappingList.addAll(blockDeviceMappingV2List); - } else if (CollectionUtils.isEmpty(blockDeviceMappingList) - && CollectionUtils.isEmpty(blockDeviceMappingV2List)) { - return null; - - } else { - blockDeviceMappingList = - blockDeviceMappingList != null ? blockDeviceMappingList : blockDeviceMappingV2List; - } - return blockDeviceMappingList; - } - - private void manageNovaServerNetwork(String heatFileName, ServiceTemplate serviceTemplate, - HeatOrchestrationTemplate heatOrchestrationTemplate, - Resource resource, String translatedId, - TranslationContext context, NodeTemplate novaNodeTemplate) { - - if (resource.getProperties() == null) { - return; - } - List> heatNetworkList = - (List>) resource.getProperties().get("networks"); - - if (CollectionUtils.isEmpty(heatNetworkList)) { - return; - } - - for (Map heatNetwork : heatNetworkList) { - getOrTranslatePortTemplate(heatFileName, heatOrchestrationTemplate, - heatNetwork.get(Constants.PORT_PROPERTY_NAME), serviceTemplate, translatedId, context, - novaNodeTemplate); - } - - } - - private void getOrTranslatePortTemplate(String heatFileName, - HeatOrchestrationTemplate heatOrchestrationTemplate, - Object port, ServiceTemplate serviceTemplate, - String novaServerResourceId, TranslationContext context, - NodeTemplate novaNodeTemplate) { - Optional attachedPortId = HeatToToscaUtil - .extractAttachedResourceId(heatFileName, heatOrchestrationTemplate, context, port); - - if (!attachedPortId.isPresent()) { - return; - } - - if (attachedPortId.get().isGetResource()) { - String resourceId = (String) attachedPortId.get().getEntityId(); - Resource portResource = - HeatToToscaUtil.getResource(heatOrchestrationTemplate, resourceId, heatFileName); - if (!Arrays.asList(HeatResourcesTypes.NEUTRON_PORT_RESOURCE_TYPE.getHeatResource(), - HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_MACHINE_INTERFACE_RESOURCE_TYPE.getHeatResource()) - .contains(portResource.getType())) { - logger.warn("NovaServer connect to port resource with id : " + resourceId + " and type : " - + portResource.getType() - + ". This resource type is not supported, therefore the connection to the port is " - + "ignored. " - + "Supported types are: " - + HeatResourcesTypes.NEUTRON_PORT_RESOURCE_TYPE.getHeatResource() + ", " - + HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_MACHINE_INTERFACE_RESOURCE_TYPE - .getHeatResource()); - return; - } else if (HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_MACHINE_INTERFACE_RESOURCE_TYPE - .getHeatResource().equals(portResource.getType())) { - Map properties = portResource.getProperties(); - if (!MapUtils.isEmpty(properties) && Objects.nonNull(properties.get("port_tuple_refs"))) { - novaNodeTemplate.getProperties().put("contrail_service_instance_ind", true); - } - } - Optional translatedPortId = ResourceTranslationFactory.getInstance(portResource) - .translateResource(heatFileName, serviceTemplate, heatOrchestrationTemplate, portResource, - resourceId, context); - if (translatedPortId.isPresent()) { - NodeTemplate portNodeTemplate = - DataModelUtil.getNodeTemplate(serviceTemplate, translatedPortId.get()); - addBindingReqFromPortToCompute(novaServerResourceId, portNodeTemplate); - } else { - logger.warn("NovaServer connect to port resource with id : " + resourceId + " and type : " - + portResource.getType() - + ". This resource type is not supported, therefore the connection to the port is " - + "ignored."); - } - } - } - - /** - * Create local node type string. - * - * @param serviceTemplate the service template - * @param properties the properties - * @param resourceTranslatedId the resource translated id - * @return the string - */ - public String createLocalNodeType(ServiceTemplate serviceTemplate, Map properties, - String resourceTranslatedId) { - NameExtractorService nodeTypeNameExtractor = new NameExtractorServiceImpl(); - List propertyRegexMatchers = - getPropertiesAndRegexMatchers(nodeTypeNameExtractor); - Optional extractedNodeTypeName = nodeTypeNameExtractor - .extractNodeTypeNameByPropertiesPriority(properties, propertyRegexMatchers); - - String nodeTypeName = ToscaConstants.NODES_PREFIX - + (extractedNodeTypeName.isPresent() ? extractedNodeTypeName.get() - : resourceTranslatedId.replace(".", "_")); - if (!isNodeTypeCreated(serviceTemplate, nodeTypeName)) { - DataModelUtil.addNodeType(serviceTemplate, nodeTypeName, createNodeType()); - } - return nodeTypeName; - } - - private List getPropertiesAndRegexMatchers( - NameExtractorService nodeTypeNameExtractor) { - List propertyRegexMatchers = new ArrayList<>(); - propertyRegexMatchers.add(nodeTypeNameExtractor - .getPropertyRegexMatcher(Constants.NAME_PROPERTY_NAME, - Arrays.asList(".+_name$", ".+_names$", ".+_name_[0-9]+"), "_name")); - propertyRegexMatchers.add(nodeTypeNameExtractor - .getPropertyRegexMatcher("image", Collections.singletonList(".+_image_name$"), - "_image_name")); - propertyRegexMatchers.add(nodeTypeNameExtractor - .getPropertyRegexMatcher("flavor", Collections.singletonList(".+_flavor_name$"), - "_flavor_name")); - return propertyRegexMatchers; - } - - private boolean isNodeTypeCreated(ServiceTemplate serviceTemplate, String nodeTypeName) { - return !MapUtils.isEmpty(serviceTemplate.getNode_types()) - && Objects.nonNull(serviceTemplate.getNode_types().get(nodeTypeName)); - } - - private NodeType createNodeType() { - NodeType nodeType = new NodeType(); - nodeType.setDerived_from(ToscaNodeType.NOVA_SERVER.getDisplayName()); - return nodeType; - } -} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationResourceGroupImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationResourceGroupImpl.java deleted file mode 100644 index 4665249351..0000000000 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/ResourceTranslationResourceGroupImpl.java +++ /dev/null @@ -1,202 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.translator.services.heattotosca.impl; - -import org.openecomp.sdc.common.errors.CoreException; -import org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes; -import org.openecomp.sdc.heat.datatypes.model.Resource; -import org.openecomp.sdc.heat.services.HeatConstants; -import org.openecomp.sdc.tosca.datatypes.ToscaFunctions; -import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; -import org.openecomp.sdc.tosca.services.DataModelUtil; -import org.openecomp.sdc.tosca.services.ToscaConstants; -import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; -import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; -import org.openecomp.sdc.translator.services.heattotosca.ResourceTranslationFactory; -import org.openecomp.sdc.translator.services.heattotosca.errors.InvalidPropertyValueErrorBuilder; -import org.openecomp.sdc.translator.services.heattotosca.mapping.TranslatorHeatToToscaPropertyConverter; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Optional; - -public class ResourceTranslationResourceGroupImpl extends ResourceTranslationBase { - - @Override - protected void translate(TranslateTo translateTo) { - final String heatFileName = translateTo.getHeatFileName(); - Object resourceDef = - translateTo.getResource().getProperties().get(HeatConstants.RESOURCE_DEF_PROPERTY_NAME); - Resource nestedResource = new Resource(); - Object typeDefinition = ((Map) resourceDef).get("type"); - if (!(typeDefinition instanceof String)) { - logger.warn("Resource '" + translateTo.getResourceId() + "' of type'" - + HeatResourcesTypes.RESOURCE_GROUP_RESOURCE_TYPE.getHeatResource() - + "' with resourceDef which is not pointing to nested heat file " - + "is not supported and will be ignored in the translation "); - return; - } - String type = (String) typeDefinition; - if (!HeatToToscaUtil.isYmlFileType(type)) { - logger.warn("Resource '" + translateTo.getResourceId() + "' of type'" - + HeatResourcesTypes.RESOURCE_GROUP_RESOURCE_TYPE.getHeatResource() - + "' with resourceDef which is not pointing to nested heat " - + "file is not supported and will be ignored in the translation "); - return; - } - - nestedResource.setType(type); - nestedResource.setProperties((Map) ((Map) resourceDef).get("properties")); - nestedResource.setMetadata(((Map) resourceDef).get("metadata")); - - Optional substitutionNodeTemplateId = - ResourceTranslationFactory.getInstance(nestedResource) - .translateResource(heatFileName, translateTo.getServiceTemplate(), - translateTo.getHeatOrchestrationTemplate(), nestedResource, - translateTo.getResourceId(), translateTo.getContext()); - if (substitutionNodeTemplateId.isPresent()) { - NodeTemplate substitutionNodeTemplate = DataModelUtil - .getNodeTemplate(translateTo.getServiceTemplate(), substitutionNodeTemplateId.get()); - Map serviceTemplateFilter = (Map) substitutionNodeTemplate.getProperties() - .get(ToscaConstants.SERVICE_TEMPLATE_FILTER_PROPERTY_NAME); - - populateServiceTemplateFilterProperties(translateTo, substitutionNodeTemplate, - serviceTemplateFilter); - handlingIndexVar(translateTo, substitutionNodeTemplate); - DataModelUtil - .addNodeTemplate(translateTo.getServiceTemplate(), substitutionNodeTemplateId.get(), - substitutionNodeTemplate); - } - - } - - private void handlingIndexVar(TranslateTo translateTo, NodeTemplate substitutionNodeTemplate) { - String indexVarValue = getIndexVarValue(translateTo); - replacePropertiesIndexVarValue(indexVarValue, substitutionNodeTemplate.getProperties()); - } - - private Map getNewIndexVarValue() { - final Map newIndexVarValue = new HashMap<>(); - List indexVarValList = new ArrayList<>(); - indexVarValList.add(ToscaConstants.MODELABLE_ENTITY_NAME_SELF); - indexVarValList.add(ToscaConstants.SERVICE_TEMPLATE_FILTER_PROPERTY_NAME); - indexVarValList.add(ToscaConstants.INDEX_VALUE_PROPERTY_NAME); - newIndexVarValue.put(ToscaFunctions.GET_PROPERTY.getDisplayName(), indexVarValList); - return newIndexVarValue; - } - - private void replacePropertiesIndexVarValue(String indexVarValue, - Map properties) { - if (properties == null || properties.isEmpty()) { - return; - } - - for (Map.Entry propertyEntry : properties.entrySet()) { - Object propertyValue = propertyEntry.getValue(); - Object newPropertyValue = getUpdatedPropertyValueWithIndex(indexVarValue, propertyValue); - if (newPropertyValue != null) { - properties.put(propertyEntry.getKey(), newPropertyValue); - } - } - } - - private Object getUpdatedPropertyValueWithIndex(String indexVarValue, Object propertyValue) { - if (propertyValue instanceof String && propertyValue != null) { - if (propertyValue.equals(indexVarValue)) { - return getNewIndexVarValue(); - } - if (((String) propertyValue).contains(indexVarValue)) { - Map> concatMap = new HashMap<>(); - List concatList = new ArrayList<>(); - String value = (String) propertyValue; - - while (value.contains(indexVarValue)) { - if (value.indexOf(indexVarValue) == 0) { - concatList.add(getNewIndexVarValue()); - value = value.substring(indexVarValue.length()); - } else { - int end = value.indexOf(indexVarValue); - concatList.add(value.substring(0, end)); - value = value.substring(end); - } - } - if (!value.isEmpty()) { - concatList.add(value); - } - - concatMap.put(ToscaFunctions.CONCAT.getDisplayName(), concatList); - return concatMap; - } - return propertyValue; //no update is needed - } else if (propertyValue instanceof Map && !((Map) propertyValue).isEmpty()) { - replacePropertiesIndexVarValue(indexVarValue, (Map) propertyValue); - return propertyValue; - } else if (propertyValue instanceof List && !((List) propertyValue).isEmpty()) { - List newPropertyValueList = new ArrayList<>(); - for (Object entry : ((List) propertyValue)) { - newPropertyValueList.add(getUpdatedPropertyValueWithIndex(indexVarValue, entry)); - } - return newPropertyValueList; - } - return propertyValue; - } - - private String getIndexVarValue(TranslateTo translateTo) { - Object indexVar = - translateTo.getResource().getProperties().get(HeatConstants.INDEX_PROPERTY_NAME); - if (indexVar == null) { - return HeatConstants.RESOURCE_GROUP_INDEX_VAR_DEFAULT_VALUE; - } - - if (indexVar instanceof String) { - return (String) indexVar; - } else { - throw new CoreException( - new InvalidPropertyValueErrorBuilder("index_var", indexVar.toString(), "String").build()); - } - } - - private void populateServiceTemplateFilterProperties(TranslateTo translateTo, - NodeTemplate substitutionNodeTemplate, - Map serviceTemplateFilter) { - boolean mandatory = false; - Object countValue = TranslatorHeatToToscaPropertyConverter - .getToscaPropertyValue(ToscaConstants.COUNT_PROPERTY_NAME, - translateTo.getResource().getProperties().get(ToscaConstants.COUNT_PROPERTY_NAME), null, - translateTo.getHeatFileName(), translateTo.getHeatOrchestrationTemplate(), - substitutionNodeTemplate, translateTo.getContext()); - - if (countValue != null) { - serviceTemplateFilter.put(ToscaConstants.COUNT_PROPERTY_NAME, countValue); - } else { - serviceTemplateFilter.put(ToscaConstants.COUNT_PROPERTY_NAME, 1); - } - if (countValue instanceof Integer && (Integer) countValue > 0) { - mandatory = true; - } - if (countValue == null) { - mandatory = true; - } - serviceTemplateFilter.put("mandatory", mandatory); - } -} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/SecurityRulesToPortResourceConnection.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/SecurityRulesToPortResourceConnection.java deleted file mode 100644 index 3c6fef7ffb..0000000000 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/SecurityRulesToPortResourceConnection.java +++ /dev/null @@ -1,203 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.translator.services.heattotosca.impl; - - -import org.openecomp.sdc.heat.datatypes.manifest.FileData; -import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate; -import org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes; -import org.openecomp.sdc.heat.datatypes.model.Resource; -import org.openecomp.sdc.tosca.datatypes.ToscaCapabilityType; -import org.openecomp.sdc.tosca.datatypes.ToscaNodeType; -import org.openecomp.sdc.tosca.datatypes.ToscaRelationshipType; -import org.openecomp.sdc.tosca.datatypes.model.CapabilityDefinition; -import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; -import org.openecomp.sdc.tosca.datatypes.model.NodeType; -import org.openecomp.sdc.tosca.datatypes.model.RequirementDefinition; -import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; -import org.openecomp.sdc.tosca.services.DataModelUtil; -import org.openecomp.sdc.tosca.services.ToscaConstants; -import org.openecomp.sdc.translator.datatypes.heattotosca.AttachedResourceId; -import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; -import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslatedHeatResource; -import org.openecomp.sdc.translator.services.heattotosca.Constants; -import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; -import org.openecomp.sdc.translator.services.heattotosca.ResourceTranslationFactory; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Optional; -import java.util.function.Predicate; - - -class SecurityRulesToPortResourceConnection extends BaseResourceConnection { - SecurityRulesToPortResourceConnection(ResourceTranslationNestedImpl resourceTranslationNested, - TranslateTo translateTo, FileData nestedFileData, - NodeTemplate substitutionNodeTemplate, NodeType nodeType) { - super(resourceTranslationNested, translateTo, nestedFileData, substitutionNodeTemplate, - nodeType); - } - - @Override - protected boolean isDesiredNodeTemplateType(NodeTemplate nodeTemplate) { - return nodeTemplate.getType().equals(ToscaNodeType.NEUTRON_PORT.getDisplayName()); - } - - @Override - protected List> getPredicatesListForConnectionPoints() { - ArrayList> predicates = new ArrayList<>(); - predicates.add(cap -> cap.getType().equals(ToscaCapabilityType.ATTACHMENT.getDisplayName())); - return predicates; - } - - @Override - protected Optional> getConnectorParamName( - String heatResourceId,Resource heatResource, - HeatOrchestrationTemplate nestedHeatOrchestrationTemplate) { - Object securityGroups = - heatResource.getProperties().get(Constants.SECURITY_GROUPS_PROPERTY_NAME); - List paramsList = new ArrayList<>(); - if (securityGroups instanceof List) { - ((List) securityGroups).forEach(group -> { - Optional attachedResourceId = HeatToToscaUtil - .extractAttachedResourceId(nestedFileData.getFile(), nestedHeatOrchestrationTemplate, - translateTo.getContext(), group); - if (attachedResourceId.isPresent()) { - paramsList.add((String) attachedResourceId.get().getEntityId()); - } - }); - return Optional.of(paramsList); - } - return Optional.empty(); - } - - @Override - protected String getDesiredResourceType() { - return HeatResourcesTypes.NEUTRON_PORT_RESOURCE_TYPE.getHeatResource(); - } - - @Override - protected List> getAllConnectionPoints() { - List> exposedRequirementsList = new ArrayList<>(); - List> predicates = getPredicatesListForConnectionPoints(); - Map capabilities = this.nodeType.getCapabilities(); - if (capabilities == null) { - return exposedRequirementsList; - } - capabilities.entrySet() - .stream() - .filter(entry -> predicates - .stream() - .anyMatch(p -> p.test(entry.getValue()))) - .forEach(entry -> { - Map exposedRequirementsMap = new HashMap<>(); - exposedRequirementsMap.put(entry.getKey(), entry.getValue()); - exposedRequirementsList.add(exposedRequirementsMap); - }); - - return exposedRequirementsList; - } - - @Override - void addRequirementToConnectResources(Map.Entry entry, - List paramNames) { - paramNames.forEach(p -> { - Optional attachedResourceId = - HeatToToscaUtil.extractAttachedResourceId(translateTo, p); - String securityRulesNodeId; - if (!attachedResourceId.isPresent()) { - return; - } - Map.Entry requirementDefinition = - createRequirementDefinition(entry.getKey()); - AttachedResourceId securityGroupAttachedId = attachedResourceId.get(); - if (securityGroupAttachedId.isGetResource()) { - String securityGroupResourceId = (String) attachedResourceId.get().getEntityId(); - Resource securityGroupResource = HeatToToscaUtil - .getResource(translateTo.getHeatOrchestrationTemplate(), securityGroupResourceId, - translateTo.getHeatFileName()); - Optional translatedSecurityRuleId = - ResourceTranslationFactory.getInstance(securityGroupResource) - .translateResource(translateTo.getHeatFileName(), translateTo.getServiceTemplate(), - translateTo.getHeatOrchestrationTemplate(), securityGroupResource, - securityGroupResourceId, translateTo.getContext()); - if (translatedSecurityRuleId.isPresent()) { - NodeTemplate securityRuleNodeTemplate = DataModelUtil - .getNodeTemplate(translateTo.getServiceTemplate(), translatedSecurityRuleId.get()); - createRequirementAssignment(requirementDefinition, translateTo.getTranslatedId(), - securityRuleNodeTemplate); - } else { - logger.warn( - securityGroupResource.getType() + "connection to " + securityGroupResource.getType() - + " is not supported/invalid, therefore this connection " - + "will be ignored in the TOSCA translation"); - } - } else if (securityGroupAttachedId.isGetParam()) { - TranslatedHeatResource shareResource = - translateTo.getContext().getHeatSharedResourcesByParam() - .get(securityGroupAttachedId.getEntityId()); - if (Objects.nonNull(shareResource) - && !HeatToToscaUtil.isHeatFileNested(translateTo, translateTo.getHeatFileName())) { - NodeTemplate sharedNodeTemplate = DataModelUtil - .getNodeTemplate(translateTo.getServiceTemplate(), shareResource.getTranslatedId()); - createRequirementAssignment(requirementDefinition, translateTo.getTranslatedId(), - sharedNodeTemplate); - } - } - }); - } - - @Override - protected String getTranslatedResourceIdFromSubstitutionMapping( - ServiceTemplate nestedServiceTemplate, Map.Entry entry) { - List substitutionMapping = - nestedServiceTemplate.getTopology_template().getSubstitution_mappings().getCapabilities() - .get(entry.getKey()); - return substitutionMapping.get(0); - } - - private Map.Entry createRequirementDefinition(String key) { - RequirementDefinition definition = new RequirementDefinition(); - definition.setCapability(key); - definition.setRelationship(ToscaRelationshipType.ATTACHES_TO.getDisplayName()); - return new Map.Entry() { - @Override - public String getKey() { - return ToscaConstants.PORT_REQUIREMENT_ID; - } - - @Override - public RequirementDefinition getValue() { - return definition; - } - - @Override - public RequirementDefinition setValue(RequirementDefinition value) { - return null; - } - }; - } - - -} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetAttrImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetAttrImpl.java new file mode 100644 index 0000000000..cc188d71a6 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetAttrImpl.java @@ -0,0 +1,491 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.translator.services.heattotosca.impl.functiontranslation; + +import org.openecomp.core.utilities.yaml.YamlUtil; +import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate; +import org.openecomp.sdc.heat.datatypes.model.Resource; +import org.openecomp.sdc.heat.services.HeatConstants; +import org.openecomp.sdc.tosca.datatypes.ToscaFunctions; +import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; +import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; +import org.openecomp.sdc.tosca.datatypes.model.Template; +import org.openecomp.sdc.translator.datatypes.heattotosca.TranslationContext; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.EntityConsolidationData; +import org.openecomp.sdc.translator.services.heattotosca.ConfigConstants; +import org.openecomp.sdc.translator.services.heattotosca.ConsolidationDataUtil; +import org.openecomp.sdc.translator.services.heattotosca.Constants; +import org.openecomp.sdc.translator.services.heattotosca.FunctionTranslation; +import org.openecomp.sdc.translator.services.heattotosca.FunctionTranslationFactory; +import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; +import org.openecomp.sdc.translator.services.heattotosca.NameExtractor; +import org.openecomp.sdc.translator.services.heattotosca.helper.FunctionTranslationHelper; +import org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation.ResourceTranslationBase; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; +import java.util.stream.Collectors; + +public class FunctionTranslationGetAttrImpl implements FunctionTranslation { + + + @Override + public Object translateFunction(ServiceTemplate serviceTemplate, + String resourceId, String propertyName, String functionKey, + Object functionValue, String heatFileName, + HeatOrchestrationTemplate heatOrchestrationTemplate, + Template toscaTemplate, TranslationContext context) { + Object returnValue = new HashMap<>(); + List attributeFunctionExpression = + translateGetAttributeFunctionExpression(serviceTemplate, resourceId, functionValue, + propertyName, heatFileName, heatOrchestrationTemplate, (NodeTemplate) toscaTemplate, + context); + if (FunctionTranslationHelper.isResourceSupported(attributeFunctionExpression.get(0).toString()) + && FunctionTranslationHelper.isAttributeSupported(attributeFunctionExpression.get(0) + .toString())) { + ((Map) returnValue) + .put(ToscaFunctions.GET_ATTRIBUTE.getDisplayName(), attributeFunctionExpression); + } else { + returnValue = attributeFunctionExpression; + } + + return returnValue; + } + + private static List translateGetAttributeFunctionExpression( + ServiceTemplate serviceTemplate, + String resourceId, + Object functionValue, + String propertyName, + String heatFileName, + HeatOrchestrationTemplate heatOrchestrationTemplate, + NodeTemplate nodeTemplate, + TranslationContext context) { + + List attributeParamList = (List) functionValue; + List toscaAttributeParamList = new ArrayList<>(); + + Optional targetResourceTranslatedId = Optional.empty(); + String targetResourceId = null; + if( attributeParamList.get(0) instanceof String) { + targetResourceId = (String) attributeParamList.get(0); + targetResourceTranslatedId = + handleResourceName(targetResourceId, heatFileName, heatOrchestrationTemplate, + context); + } + if (!targetResourceTranslatedId.isPresent()) { + //unsupported resource + toscaAttributeParamList + .add( + FunctionTranslationHelper.getUnsupportedResourcePrefix() + attributeParamList.get(0)); + return toscaAttributeParamList; + } else { + toscaAttributeParamList.add(targetResourceTranslatedId.get()); + } + + Optional> toscaAttList = + handleAttributeName(attributeParamList, heatOrchestrationTemplate, propertyName, + heatFileName, serviceTemplate, + context); + if (!toscaAttList.isPresent()) { + //Unsupported attribute + toscaAttributeParamList.clear(); + toscaAttributeParamList + .add(FunctionTranslationHelper.getUnsupportedAttributePrefix() + attributeParamList.get(0) + + "." + attributeParamList.get(1)); + return toscaAttributeParamList; + } else { + toscaAttributeParamList.addAll(toscaAttList.get()); + + handleGetAttrConsolidationData(serviceTemplate, resourceId, propertyName, heatFileName, + heatOrchestrationTemplate, context, targetResourceId, + targetResourceTranslatedId, + toscaAttList.get()); + } + + Optional> toscaIndexOrKey = handleAttributeIndexOrKey(serviceTemplate, + resourceId, propertyName, HeatToToscaUtil + .getResourceType((String) attributeParamList.get(0), heatOrchestrationTemplate, + heatFileName), attributeParamList, context, heatFileName, + heatOrchestrationTemplate); + toscaIndexOrKey.ifPresent(toscaAttributeParamList::addAll); + + return toscaAttributeParamList; + } + + private static void handleGetAttrConsolidationData( + ServiceTemplate serviceTemplate, + String resourceId, String propertyName, + String heatFileName, + HeatOrchestrationTemplate heatOrchestrationTemplate, + TranslationContext context, + String targetResourceId, + Optional targetResourceTranslatedId, + List toscaAttList) { + + Optional resourceTranslatedId = Optional.empty(); + if (resourceId != null) { + resourceTranslatedId = + handleResourceName(resourceId, heatFileName, heatOrchestrationTemplate, + context); + resourceTranslatedId + .ifPresent(resourceTranslatedIdValue -> handleGetAttrOutConsolidationData(serviceTemplate, + propertyName, + heatOrchestrationTemplate, context, resourceId, targetResourceTranslatedId.get(), + resourceTranslatedIdValue, toscaAttList, heatFileName)); + } + + if (targetResourceTranslatedId.isPresent()) { + handleGetAttrInConsolidationData(serviceTemplate, resourceId, resourceTranslatedId, + propertyName, heatOrchestrationTemplate, context, targetResourceId, + targetResourceTranslatedId.get(), toscaAttList, heatFileName); + } + } + + private static void handleGetAttrOutConsolidationData( + ServiceTemplate serviceTemplate, + String propertyName, + HeatOrchestrationTemplate heatOrchestrationTemplate, + TranslationContext context, + String resourceId, + String targetTranslatedResourceId, + String resourceTranslatedId, + List toscaAttList, + String heatFileName) { + if (serviceTemplate != null) { + Optional entityConsolidationData = + getEntityConsolidationData(serviceTemplate, heatOrchestrationTemplate, context, + resourceId, resourceTranslatedId, heatFileName); + if (entityConsolidationData.isPresent()) { + String attName = (String) toscaAttList.get(0); + handleNodeGetAttrOut(targetTranslatedResourceId, propertyName, heatOrchestrationTemplate, + context, resourceId, entityConsolidationData.get(), attName); + } + } + } + + private static void handleGetAttrInConsolidationData( + ServiceTemplate serviceTemplate, + String resourceId, + Optional resourceTranslatedId, + String propertyName, + HeatOrchestrationTemplate heatOrchestrationTemplate, + TranslationContext context, + String targetResourceId, + String targetResourceTranslatedId, + List toscaAttList, + String heatFileName) { + + if (serviceTemplate != null) { + Optional entityConsolidationData = + getEntityConsolidationData(serviceTemplate, heatOrchestrationTemplate, context, + targetResourceId, targetResourceTranslatedId, heatFileName); + if (entityConsolidationData.isPresent()) { + String attName = (String) toscaAttList.get(0); + if (resourceTranslatedId.isPresent()) { + handleNodeGetAttrIn(resourceTranslatedId.get(), propertyName, heatOrchestrationTemplate, + context, + resourceId, entityConsolidationData.get(), attName); + } else { + ConsolidationDataUtil + .updateOutputGetAttributeInConsolidationData(entityConsolidationData.get(), + propertyName, attName); + } + } + } + } + + private static void handleNodeGetAttrOut(String nodeTemplateId, String propertyName, + HeatOrchestrationTemplate heatOrchestrationTemplate, + TranslationContext context, String resourceId, + EntityConsolidationData entityConsolidationData, + String attName) { + Resource resource = heatOrchestrationTemplate.getResources().get(resourceId); + boolean isNestedResource = HeatToToscaUtil.isNestedResource(resource); + String toscaPropertyName = propertyName; + if (!isNestedResource) { + toscaPropertyName = HeatToToscaUtil.getToscaPropertyName(context, resource + .getType(), propertyName); + } + ConsolidationDataUtil + .updateNodeGetAttributeOut(entityConsolidationData, + nodeTemplateId, toscaPropertyName, attName); + } + + private static void handleNodeGetAttrIn(String nodeTemplateId, String propertyName, + HeatOrchestrationTemplate heatOrchestrationTemplate, + TranslationContext context, String resourceId, + EntityConsolidationData entityConsolidationData, + String attName) { + Resource resource = heatOrchestrationTemplate.getResources().get(resourceId); + boolean isNestedResource = HeatToToscaUtil.isNestedResource(resource); + String toscaPropertyName = propertyName; + if (!isNestedResource) { + toscaPropertyName = HeatToToscaUtil.getToscaPropertyName(context, resource + .getType(), propertyName); + } + ConsolidationDataUtil + .updateNodeGetAttributeIn(entityConsolidationData, + nodeTemplateId, toscaPropertyName, attName); + } + + private static Optional getEntityConsolidationData( + ServiceTemplate serviceTemplate, + HeatOrchestrationTemplate heatOrchestrationTemplate, + TranslationContext context, + String resourceId, + String resourceTranslatedId, + String heatFileName) { + Resource resource = heatOrchestrationTemplate.getResources().get(resourceId); + if (ConsolidationDataUtil.isComputeResource(heatOrchestrationTemplate, resourceId)) { + String resourceType = heatOrchestrationTemplate.getResources().get(resourceId).getType(); + NameExtractor nodeTypeNameExtractor = + context.getNameExtractorImpl(resourceType); + String computeType = + nodeTypeNameExtractor.extractNodeTypeName( + resource, resourceId, context.getTranslatedIds().get(heatFileName).get(resourceId)); + + return Optional.of( + ConsolidationDataUtil.getComputeTemplateConsolidationData(context, serviceTemplate, + computeType, resourceId)); + } else if (ConsolidationDataUtil.isPortResource(heatOrchestrationTemplate, resourceId)) { + return Optional.of(ConsolidationDataUtil + .getPortTemplateConsolidationData(context, serviceTemplate, resourceId)); + } else if (HeatToToscaUtil.isNestedResource(resource)) { + return Optional.of(ConsolidationDataUtil + .getNestedTemplateConsolidationData(context, serviceTemplate, resourceId)); + } + return Optional.empty(); + } + + private static Optional> handleAttributeIndexOrKey( + ServiceTemplate serviceTemplate, + String resourceId, String propertyName, + String resourceType, + List attributeParamList, + TranslationContext context, + String heatFileName, + HeatOrchestrationTemplate heatOrchestrationTemplate) { + + List attributeIndexOrKey = new ArrayList<>(); + if (attributeParamList.size() < 3) { + return Optional.empty(); + } + + Object attributeName = attributeParamList.get(1); + for (int i = 2; i < attributeParamList.size(); i++) { + + if (isInteger(attributeParamList.get(i))) { + attributeIndexOrKey.add(attributeParamList.get(i)); + } else if (attributeParamList.get(i) instanceof Map) { + attributeIndexOrKey.add(getToscaAttributeValue(serviceTemplate, resourceId, + propertyName, attributeParamList.get(i), resourceType, heatFileName, + heatOrchestrationTemplate, null, context)); + + } else { + Object toscaAttributeName = resourceType == null ? null : context + .getElementMapping(resourceType, Constants.ATTR, + getAttributeFullPath(attributeParamList, i)); + if (toscaAttributeName == null) { + toscaAttributeName = attributeParamList.get(i); + } + attributeIndexOrKey.add(toscaAttributeName); + } + } + + return Optional.of(attributeIndexOrKey); + } + + private static String getAttributeFullPath(List attributeParamList, int attributeIndex) { + if (attributeParamList.size() < 3) { + return null; + } + StringBuffer attributeFullPath = new StringBuffer(); + attributeFullPath.append(attributeParamList.get(1)); + for (int j = 2; j <= attributeIndex; j++) { + if (isInteger(attributeParamList.get(j))) { + continue; + } + attributeFullPath.append(ConfigConstants.TRANS_MAPPING_DELIMITER_CHAR); + attributeFullPath.append(attributeParamList.get(j)); + } + return attributeFullPath.toString(); + } + + private static boolean isInteger(Object inputNumber) { + if (inputNumber == null) { + return false; + } + + try { + Integer.parseInt(String.valueOf(inputNumber)); + return true; + } catch (NumberFormatException exception) { + return false; + } + } + + private static Optional handleResourceName(String resourceId, String heatFileName, + HeatOrchestrationTemplate + heatOrchestrationTemplate, + TranslationContext context) { + return ResourceTranslationBase + .getResourceTranslatedId(heatFileName, heatOrchestrationTemplate, resourceId, context); + } + + private static Optional> handleAttributeName(List attributeParamList, + HeatOrchestrationTemplate + heatOrchestrationTemplate, + String propertyName, + String heatFileName, + ServiceTemplate serviceTemplate, + TranslationContext context) { + String resourceId = (String) attributeParamList.get(0); + Resource resource = + HeatToToscaUtil.getResource(heatOrchestrationTemplate, resourceId, heatFileName); + + if (attributeParamList.size() == 1) { + return getResourceTranslatedAttributesList(resource, context); + } + + if(!(attributeParamList.get(1) instanceof String)){ + //todo - once dynamic attr name will be supported the commented line will be support it in + // the first translation phase. +// Object toscaAttributeValue = getToscaAttributeValue(serviceTemplate, resourceId, propertyName, +// attributeParamList.get(1), resource +// .getType(), heatFileName, heatOrchestrationTemplate, null, context); +// List dynamicAttrValue = new ArrayList<>(); +// dynamicAttrValue.add(toscaAttributeValue); +// return Optional.of(dynamicAttrValue); + return Optional.empty(); + } + + if (HeatToToscaUtil.isNestedResource(resource)) { + return getNestedResourceTranslatedAttribute((String) attributeParamList.get(1)); + } else { + return getResourceTranslatedAttribute(resource, (String) attributeParamList.get(1), context); + } + } + + private static Optional> getNestedResourceTranslatedAttribute(String attributeName) { + List translatedAttributesList = new ArrayList<>(); + + if (attributeName.startsWith(HeatConstants.GET_ATTR_FROM_RESOURCE_GROUP_PREFIX)) { + String[] attributeSplit = attributeName.split("\\."); + if (attributeSplit.length == 2) { + translatedAttributesList.add(attributeSplit[1]); + } else if (attributeSplit.length == 3) { + translatedAttributesList.add(attributeSplit[2]); + translatedAttributesList.add(Integer.valueOf(attributeSplit[1])); + } else { + return Optional.empty(); + } + } else { + translatedAttributesList.add(attributeName); + } + return Optional.of(translatedAttributesList); + } + + private static Optional> getResourceTranslatedAttributesList(Resource resource, + TranslationContext + context) { + List translatedAttributes = new ArrayList<>(); + if (HeatToToscaUtil.isNestedResource(resource)) { + Optional nestedFile = HeatToToscaUtil.getNestedFile(resource); + if (!nestedFile.isPresent()) { + return Optional.empty(); + } + HeatOrchestrationTemplate nestedHeatOrchestrationTemplate = new YamlUtil() + .yamlToObject(context.getFiles().getFileContent(nestedFile.get()), + HeatOrchestrationTemplate.class); + translatedAttributes.addAll(nestedHeatOrchestrationTemplate.getOutputs().keySet()); + return Optional.of(translatedAttributes); + + } else { + Map resourceMappingAttributes = + context.getElementMapping(resource.getType(), Constants.ATTR); + if (resourceMappingAttributes == null) { + return Optional.empty(); + } + Set mappingAttributes = new HashSet<>(); + mappingAttributes + .addAll(resourceMappingAttributes.values().stream().collect(Collectors.toList())); + translatedAttributes.addAll(mappingAttributes); + return Optional.of(translatedAttributes); + } + } + + private static Optional> getResourceTranslatedAttribute(Resource resource, + String attributeName, + TranslationContext context) { + List translatedAttributesList = new ArrayList<>(); + String translatedAttribute = + context.getElementMapping(resource.getType(), Constants.ATTR, attributeName); + if (translatedAttribute != null) { + translatedAttributesList.add(translatedAttribute); + return Optional.of(translatedAttributesList); + } else { //unsupported attribute + return Optional.empty(); + } + } + + private static Object getToscaAttributeValue(ServiceTemplate serviceTemplate, + String resourceId, String propertyName, + Object attributeVal, String resourceType, + String heatFileName, + HeatOrchestrationTemplate heatOrchestrationTemplate, + Template template, TranslationContext context) { + if (attributeVal instanceof Map && !((Map) attributeVal).isEmpty()) { + Map.Entry functionMapEntry = + (Map.Entry) ((Map) attributeVal).entrySet().iterator().next(); + if (FunctionTranslationFactory.getInstance(functionMapEntry.getKey()).isPresent()) { + return FunctionTranslationFactory.getInstance(functionMapEntry.getKey()).get() + .translateFunction(serviceTemplate, resourceId, propertyName, + functionMapEntry.getKey(), functionMapEntry + .getValue(), heatFileName, heatOrchestrationTemplate, template, context); + } + Map attrValueMap = new HashMap<>(); + for (Map.Entry entry : ((Map) attributeVal).entrySet()) { + attrValueMap.put(entry.getKey(), + getToscaAttributeValue(serviceTemplate, resourceId, propertyName, entry.getValue(), + resourceType, heatFileName, heatOrchestrationTemplate, template, context)); + } + return attrValueMap; + } else if (attributeVal instanceof List && !((List) attributeVal).isEmpty()) { + List propertyValueArray = new ArrayList<>(); + for (int i = 0; i < ((List) attributeVal).size(); i++) { + propertyValueArray.add( + getToscaAttributeValue(serviceTemplate, resourceId, propertyName, + ((List) attributeVal).get(i), resourceType, heatFileName, + heatOrchestrationTemplate, template, context)); + } + return propertyValueArray; + } + return attributeVal; + } + + +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetFileImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetFileImpl.java new file mode 100644 index 0000000000..bc0926c9d0 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetFileImpl.java @@ -0,0 +1,87 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.translator.services.heattotosca.impl.functiontranslation; + +import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate; +import org.openecomp.sdc.tosca.datatypes.ToscaArtifactType; +import org.openecomp.sdc.tosca.datatypes.ToscaFunctions; +import org.openecomp.sdc.tosca.datatypes.model.ArtifactDefinition; +import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; +import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; +import org.openecomp.sdc.tosca.datatypes.model.Template; +import org.openecomp.sdc.tosca.services.ToscaConstants; +import org.openecomp.sdc.tosca.services.ToscaFileOutputService; +import org.openecomp.sdc.tosca.services.impl.ToscaFileOutputServiceCsarImpl; +import org.openecomp.sdc.translator.services.heattotosca.FunctionTranslation; +import org.openecomp.sdc.translator.datatypes.heattotosca.TranslationContext; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * @author SHIRIA + * @since December 15, 2016. + */ +public class FunctionTranslationGetFileImpl implements FunctionTranslation { + @Override + public Object translateFunction(ServiceTemplate serviceTemplate, + String resourceId, String propertyName, String functionKey, + Object functionValue, String heatFileName, + HeatOrchestrationTemplate heatOrchestrationTemplate, + Template toscaTemplate, TranslationContext context) { + String file = ((String) functionValue).replace("file:///", ""); + Object returnValue; + final String artifactId = file.split("\\.")[0]; + + returnValue = new HashMap<>(); + List artifactParameters = new ArrayList(); + artifactParameters.add(0, ToscaConstants.MODELABLE_ENTITY_NAME_SELF); + ((Map) returnValue).put(ToscaFunctions.GET_ARTIFACT.getDisplayName(), artifactParameters); + artifactParameters.add(1, artifactId); + + ToscaFileOutputService toscaFileOutputService = new ToscaFileOutputServiceCsarImpl(); + if (toscaTemplate != null) { + if (toscaTemplate instanceof NodeTemplate) { + NodeTemplate nodeTemplate = (NodeTemplate) toscaTemplate; + ArtifactDefinition artifactDefinition = + createArtifactDefinition(file, toscaFileOutputService); + if (nodeTemplate.getArtifacts() == null) { + nodeTemplate.setArtifacts(new HashMap<>()); + } + nodeTemplate.getArtifacts().put(artifactId, artifactDefinition); + } + } + return returnValue; + } + + private static ArtifactDefinition createArtifactDefinition(Object function, + ToscaFileOutputService + toscaFileOutputService) { + ArtifactDefinition artifactDefinition = new ArtifactDefinition(); + artifactDefinition.setType(ToscaArtifactType.NATIVE_DEPLOYMENT); + artifactDefinition + .setFile("../" + toscaFileOutputService.getArtifactsFolderName() + "/" + function); + return artifactDefinition; + } + +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetParamImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetParamImpl.java new file mode 100644 index 0000000000..877659ee10 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetParamImpl.java @@ -0,0 +1,128 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.translator.services.heattotosca.impl.functiontranslation; + +import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate; +import org.openecomp.sdc.heat.datatypes.model.HeatPseudoParameters; +import org.openecomp.sdc.tosca.datatypes.ToscaFunctions; +import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; +import org.openecomp.sdc.tosca.datatypes.model.Template; +import org.openecomp.sdc.translator.services.heattotosca.FunctionTranslation; +import org.openecomp.sdc.translator.services.heattotosca.FunctionTranslationFactory; +import org.openecomp.sdc.translator.datatypes.heattotosca.TranslationContext; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + +/** + * @author SHIRIA + * @since December 15, 2016. + */ +public class FunctionTranslationGetParamImpl implements FunctionTranslation { + @Override + public Object translateFunction(ServiceTemplate serviceTemplate, String resourceId, + String propertyName, String functionKey, + Object functionValue, String heatFileName, + HeatOrchestrationTemplate heatOrchestrationTemplate, + Template toscaTemplate, TranslationContext context) { + Map returnValue = new HashMap<>(); + returnValue.put(ToscaFunctions.GET_INPUT.getDisplayName(), + translateGetParamFunctionExpression(serviceTemplate, resourceId, propertyName, + functionValue, heatFileName, heatOrchestrationTemplate, context)); + return returnValue; + } + + private static Object translateGetParamFunctionExpression(ServiceTemplate serviceTemplate, + String resourceId, + String propertyName,Object functionValue, + String heatFileName, + HeatOrchestrationTemplate + heatOrchestrationTemplate, + TranslationContext context) { + Object returnValue = null; + if (functionValue instanceof String) { + returnValue = functionValue; + if (HeatPseudoParameters.getPseudoParameterNames().contains(functionValue)) { + context + .addUsedHeatPseudoParams(heatFileName, (String) functionValue, (String) functionValue); + } + } else if (functionValue instanceof List) { + returnValue = new ArrayList<>(); + for (int i = 0; i < ((List) functionValue).size(); i++) { + Object paramValue = ((List) functionValue).get(i); + if ((paramValue instanceof Map && !((Map) paramValue).isEmpty())) { + Map paramMap = (Map) paramValue; + ((List) returnValue).add(translatedInnerMap(serviceTemplate, resourceId, + propertyName, paramMap, heatFileName, heatOrchestrationTemplate, context)); + } else { + ((List) returnValue).add(paramValue); + } + } + } + + return returnValue; + } + + private static Object translatedInnerMap(ServiceTemplate serviceTemplate, String resourceId, + String propertyName, Map paramMap, + String heatFileName,HeatOrchestrationTemplate + heatOrchestrationTemplate, + TranslationContext context) { + + Map translatedInnerMapValue = new HashMap<>(); + for (Map.Entry entry : paramMap.entrySet()) { + if (FunctionTranslationFactory.getInstance(entry.getKey()).isPresent()) { + return FunctionTranslationFactory.getInstance(entry.getKey()).get() + .translateFunction(serviceTemplate, resourceId, propertyName, entry.getKey(), + entry.getValue(), heatFileName, heatOrchestrationTemplate, null, context); + } else { + translatedInnerMapValue.put(entry.getKey(), + translatedInnerValue(serviceTemplate, resourceId, propertyName,entry.getValue(), + heatFileName, heatOrchestrationTemplate, context)); + + } + } + return translatedInnerMapValue; + } + + private static Object translatedInnerValue(ServiceTemplate serviceTemplate, String resourceId, + String propertyName,Object value, String heatFileName, + HeatOrchestrationTemplate heatOrchestrationTemplate, + TranslationContext context) { + if (value instanceof String) { + return value; + } else if (value instanceof Map) { + return translatedInnerMap(serviceTemplate, resourceId, propertyName,(Map) + value, heatFileName, heatOrchestrationTemplate, context); + } else if (value instanceof List) { + List returnedList = new ArrayList(); + for (int i = 0; i < ((List) value).size(); i++) { + returnedList.add(translatedInnerValue(serviceTemplate, resourceId, propertyName, + ((List) value).get(i), heatFileName, heatOrchestrationTemplate, context)); + } + return returnedList; + } + + return value; + } +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetResourceImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetResourceImpl.java new file mode 100644 index 0000000000..b2d11e3804 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/functiontranslation/FunctionTranslationGetResourceImpl.java @@ -0,0 +1,52 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.translator.services.heattotosca.impl.functiontranslation; + +import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate; +import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; +import org.openecomp.sdc.tosca.datatypes.model.Template; +import org.openecomp.sdc.translator.services.heattotosca.FunctionTranslation; +import org.openecomp.sdc.translator.datatypes.heattotosca.TranslationContext; +import org.openecomp.sdc.translator.services.heattotosca.helper.FunctionTranslationHelper; +import org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation.ResourceTranslationBase; + +import java.util.Optional; + +/** + * @author SHIRIA + * @since December 15, 2016. + */ +public class FunctionTranslationGetResourceImpl implements FunctionTranslation { + @Override + public Object translateFunction(ServiceTemplate serviceTemplate, String resourceId, + String propertyName, String functionKey, + Object functionValue, String heatFileName, + HeatOrchestrationTemplate heatOrchestrationTemplate, + Template toscaTemplate, TranslationContext context) { + Object returnValue; + Optional resourceTranslatedId = ResourceTranslationBase + .getResourceTranslatedId(heatFileName, heatOrchestrationTemplate, (String) functionValue, + context); + returnValue = resourceTranslatedId + .orElseGet(() -> FunctionTranslationHelper.getUnsupportedResourcePrefix() + functionValue); + return returnValue; + } +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/nameextractor/NameExtractorContrailComputeImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/nameextractor/NameExtractorContrailComputeImpl.java new file mode 100644 index 0000000000..637aff9406 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/nameextractor/NameExtractorContrailComputeImpl.java @@ -0,0 +1,49 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.translator.services.heattotosca.impl.nameextractor; + +import org.openecomp.sdc.heat.datatypes.model.Resource; +import org.openecomp.sdc.tosca.datatypes.ToscaNodeType; +import org.openecomp.sdc.translator.datatypes.heattotosca.PropertyRegexMatcher; +import org.openecomp.sdc.translator.services.heattotosca.NameExtractor; +import org.openecomp.sdc.translator.services.heattotosca.NameExtractorUtil; +import org.openecomp.sdc.translator.services.heattotosca.helper.ContrailTranslationHelper; + +import java.util.List; +import java.util.Optional; + +public class NameExtractorContrailComputeImpl implements NameExtractor { + + @Override + public String extractNodeTypeName(Resource resource, String resourceId, String translatedId) { + ContrailTranslationHelper contrailTranslationHelper = new ContrailTranslationHelper(); + List propertyRegexMatchers = + contrailTranslationHelper.getPropertyRegexMatchersForComputeNodeType(); + Optional extractedNodeTypeName = + NameExtractorUtil.extractNodeTypeNameByPropertiesPriority(resource.getProperties(), + propertyRegexMatchers); + + return ToscaNodeType.VFC_NODE_TYPE_PREFIX + "heat." + + (extractedNodeTypeName.isPresent() ? extractedNodeTypeName.get() + : "compute_" + translatedId); + } + +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/nameextractor/NameExtractorNovaServerImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/nameextractor/NameExtractorNovaServerImpl.java new file mode 100644 index 0000000000..52ceafa454 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/nameextractor/NameExtractorNovaServerImpl.java @@ -0,0 +1,50 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.translator.services.heattotosca.impl.nameextractor; + +import org.openecomp.sdc.heat.datatypes.model.Resource; +import org.openecomp.sdc.tosca.datatypes.ToscaNodeType; +import org.openecomp.sdc.translator.datatypes.heattotosca.PropertyRegexMatcher; +import org.openecomp.sdc.translator.services.heattotosca.NameExtractor; +import org.openecomp.sdc.translator.services.heattotosca.NameExtractorUtil; +import org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation.ResourceTranslationNovaServerImpl; + +import java.util.List; +import java.util.Optional; + +public class NameExtractorNovaServerImpl implements NameExtractor { + + @Override + public String extractNodeTypeName(Resource resource, String resourceId, String translatedId) { + ResourceTranslationNovaServerImpl novaServerTranslator = + new ResourceTranslationNovaServerImpl(); + List propertyRegexMatchers = + novaServerTranslator.getPropertyRegexMatchersForNovaNodeType(); + + Optional extractedNodeTypeName = NameExtractorUtil + .extractNodeTypeNameByPropertiesPriority(resource.getProperties(), propertyRegexMatchers); + + return ToscaNodeType.VFC_NODE_TYPE_PREFIX + "heat." + + (extractedNodeTypeName.isPresent() ? extractedNodeTypeName.get() + : translatedId.replace(".", "_")); + } + +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/BaseResourceConnection.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/BaseResourceConnection.java new file mode 100644 index 0000000000..b9fed89133 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/BaseResourceConnection.java @@ -0,0 +1,338 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; + +import org.apache.commons.collections4.MapUtils; +import org.openecomp.core.utilities.yaml.YamlUtil; +import org.openecomp.sdc.common.errors.CoreException; +import org.openecomp.sdc.common.errors.ErrorCategory; +import org.openecomp.sdc.common.errors.ErrorCode; +import org.openecomp.sdc.datatypes.error.ErrorLevel; +import org.openecomp.sdc.heat.datatypes.manifest.FileData; +import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate; +import org.openecomp.sdc.heat.datatypes.model.Resource; +import org.openecomp.sdc.logging.api.Logger; +import org.openecomp.sdc.logging.api.LoggerFactory; +import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; +import org.openecomp.sdc.logging.context.impl.MdcDataErrorMessage; +import org.openecomp.sdc.logging.types.LoggerConstants; +import org.openecomp.sdc.logging.types.LoggerErrorCode; +import org.openecomp.sdc.logging.types.LoggerErrorDescription; +import org.openecomp.sdc.logging.types.LoggerTragetServiceName; +import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; +import org.openecomp.sdc.tosca.datatypes.model.NodeType; +import org.openecomp.sdc.tosca.datatypes.model.RequirementAssignment; +import org.openecomp.sdc.tosca.datatypes.model.RequirementDefinition; +import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; +import org.openecomp.sdc.tosca.services.DataModelUtil; +import org.openecomp.sdc.tosca.services.ToscaAnalyzerService; +import org.openecomp.sdc.tosca.services.impl.ToscaAnalyzerServiceImpl; +import org.openecomp.sdc.translator.datatypes.heattotosca.AttachedResourceId; +import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; +import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslatedHeatResource; +import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; +import org.openecomp.sdc.translator.services.heattotosca.errors.TranslatorErrorCodes; + +import java.util.ArrayList; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.function.Predicate; + +abstract class BaseResourceConnection { + protected static Logger logger = (Logger) LoggerFactory.getLogger(BaseResourceConnection.class); + protected static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); + protected TranslateTo translateTo; + FileData nestedFileData; + NodeTemplate substitutionNodeTemplate; + NodeType nodeType; + ResourceTranslationBase resourceTranslationBase; + + BaseResourceConnection(ResourceTranslationBase resourceTranslationBase, TranslateTo translateTo, + FileData nestedFileData, NodeTemplate substitutionNodeTemplate, + NodeType nodeType) { + this.translateTo = translateTo; + this.nestedFileData = nestedFileData; + this.substitutionNodeTemplate = substitutionNodeTemplate; + this.nodeType = nodeType; + this.resourceTranslationBase = resourceTranslationBase; + } + + abstract boolean isDesiredNodeTemplateType(NodeTemplate nodeTemplate); + + abstract List> getPredicatesListForConnectionPoints(); + + abstract Optional> getConnectorPropertyParamName(String heatResourceId, + Resource heatResource, + HeatOrchestrationTemplate + nestedHeatOrchestrationTemplate, + String nestedHeatFileName); + + abstract String getDesiredResourceType(); + + abstract String getMappedNodeTranslatedResourceId(ServiceTemplate nestedServiceTemplate, + Map.Entry connectionPointEntry); + + abstract Map.Entry getMappedConnectionPointEntry(ServiceTemplate nestedServiceTemplate, + Map.Entry + connectionPointEntry); + + abstract void addRequirementToConnectResources(Map.Entry connectionPointEntry, + List paramNames); + + abstract List> getAllConnectionPoints(); + + abstract boolean validateResourceTypeSupportedForReqCreation(String nestedResourceId, + final String nestedPropertyName, + String connectionPointId, + Resource connectedResource, + List supportedTypes); + + void connect() { + ServiceTemplate nestedServiceTemplate = translateTo.getContext().getTranslatedServiceTemplates() + .get(translateTo.getResource().getType()); + List paramNames; + HeatOrchestrationTemplate nestedHeatOrchestrationTemplate = new YamlUtil() + .yamlToObject(translateTo.getContext().getFileContent(nestedFileData.getFile()), + HeatOrchestrationTemplate.class); + List> exposedConnectionPoints = getAllConnectionPoints(); + for (Map connectionPointsMap : exposedConnectionPoints) { + for (Map.Entry connectionPointEntry : connectionPointsMap.entrySet()) { + paramNames = + getConnectionParameterName(nestedServiceTemplate, nestedHeatOrchestrationTemplate, + nestedFileData.getFile(), connectionPointEntry); + if (paramNames != null && !paramNames.isEmpty()) { + addRequirementToConnectResources(connectionPointEntry, paramNames); + } + } + } + } + + private List getConnectionParameterName(ServiceTemplate nestedServiceTemplate, + HeatOrchestrationTemplate + nestedHeatOrchestrationTemplate, + String nestedHeatFileName, + Map.Entry connectionPointEntry) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + List connectionParameterNameList = new ArrayList<>(); + String mappedTranslatedResourceId = + getMappedNodeTranslatedResourceId(nestedServiceTemplate, connectionPointEntry); + NodeTemplate mappedNodeTemplate = + nestedServiceTemplate.getTopology_template().getNode_templates() + .get(mappedTranslatedResourceId); + if (isDesiredNodeTemplateType(mappedNodeTemplate)) { + return getResourcesConnectionParameterName(mappedTranslatedResourceId, + nestedHeatOrchestrationTemplate, nestedHeatFileName); + } + + ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl(); + if (toscaAnalyzerService.isSubstitutableNodeTemplate(mappedNodeTemplate)) { + Optional mappedSubstituteServiceTemplateName = toscaAnalyzerService + .getSubstituteServiceTemplateName(mappedTranslatedResourceId, mappedNodeTemplate); + if (mappedSubstituteServiceTemplateName.isPresent()) { + String mappedNestedHeatFileName = translateTo.getContext().getNestedHeatFileName() + .get(mappedSubstituteServiceTemplateName.get()); + if (Objects.isNull(mappedNestedHeatFileName)) { + return null; + } + HeatOrchestrationTemplate mappedNestedHeatOrchestrationTemplate = new YamlUtil() + .yamlToObject(translateTo.getContext().getFileContent(mappedNestedHeatFileName), + HeatOrchestrationTemplate.class); + ServiceTemplate mappedNestedServiceTemplate = + translateTo.getContext().getTranslatedServiceTemplates().get(mappedNestedHeatFileName); + List nestedPropertyNames = getConnectionParameterName(mappedNestedServiceTemplate, + mappedNestedHeatOrchestrationTemplate, mappedNestedHeatFileName, + getMappedConnectionPointEntry(nestedServiceTemplate, connectionPointEntry)); + + if (nestedPropertyNames != null && !nestedPropertyNames.isEmpty()) { + for (String propertyName : nestedPropertyNames) { + Object propertyValue = mappedNodeTemplate.getProperties().get(propertyName); + if (propertyValue instanceof Map && ((Map) propertyValue).containsKey("get_input")) { + Object paramName = ((Map) propertyValue).get("get_input"); + if (paramName instanceof String) { + connectionParameterNameList.add((String) paramName); + } + } + } + } + + mdcDataDebugMessage.debugExitMessage(null, null); + return connectionParameterNameList; + } + } + + mdcDataDebugMessage.debugExitMessage(null, null); + return null; + } + + private List getResourcesConnectionParameterName(String translatedResourceId, + HeatOrchestrationTemplate + nestedHeatOrchestrationTemplate, + String nestedHeatFileName) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + List params = new ArrayList<>(); + Optional>> heatResources = + getResourceByTranslatedResourceId(translatedResourceId, nestedHeatOrchestrationTemplate); + if (heatResources.isPresent()) { + for (Map.Entry resourceEntry : heatResources.get()) { + Resource heatResource = resourceEntry.getValue(); + if (!MapUtils.isEmpty(heatResource.getProperties())) { + Optional> connectorParamName = + getConnectorPropertyParamName(resourceEntry.getKey(), heatResource, + nestedHeatOrchestrationTemplate, nestedHeatFileName); + connectorParamName.ifPresent(params::addAll); + } + } + } + + mdcDataDebugMessage.debugExitMessage(null, null); + return params; + } + + protected Optional>> getResourceByTranslatedResourceId( + String translatedResourceId, HeatOrchestrationTemplate nestedHeatOrchestrationTemplate) { + Optional>> resourceByTranslatedResourceId = + resourceTranslationBase.getResourceByTranslatedResourceId(nestedFileData.getFile(), + nestedHeatOrchestrationTemplate, translatedResourceId, translateTo, + getDesiredResourceType()); + if (!resourceByTranslatedResourceId.isPresent()) { + MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, + LoggerTragetServiceName.GET_RESOURCE, ErrorLevel.ERROR.name(), + LoggerErrorCode.DATA_ERROR.getErrorCode(), LoggerErrorDescription.TRANSLATE_HEAT); + throw new CoreException((new ErrorCode.ErrorCodeBuilder()).withMessage( + "Failed to get original resource from heat for translate resource id '" + + translatedResourceId + "'") + .withId(TranslatorErrorCodes.HEAT_TO_TOSCA_MAPPING_COLLISION) + .withCategory(ErrorCategory.APPLICATION).build()); + } + return resourceByTranslatedResourceId; + } + + RequirementAssignment createRequirementAssignment(Map.Entry + requirementEntry, String node, + NodeTemplate nodeTemplate) { + + mdcDataDebugMessage.debugEntryMessage(null, null); + RequirementAssignment requirementAssignment = null; + if (Objects.nonNull(node)) { + requirementAssignment = new RequirementAssignment(); + requirementAssignment.setRelationship(requirementEntry.getValue().getRelationship()); + requirementAssignment.setCapability(requirementEntry.getValue().getCapability()); + requirementAssignment.setNode(node); + DataModelUtil + .addRequirementAssignment(nodeTemplate, requirementEntry.getKey(), requirementAssignment); + } + mdcDataDebugMessage.debugExitMessage(null, null); + return requirementAssignment; + } + + + Optional getConnectionTranslatedNodeUsingGetParamFunc( + Map.Entry connectionPointEntry, String paramName, + List supportedNodeTypes) { + + Optional attachedResourceId = + HeatToToscaUtil.extractAttachedResourceId(translateTo, paramName); + if (!attachedResourceId.isPresent()) { + return Optional.empty(); + } + AttachedResourceId resourceId = attachedResourceId.get(); + if (resourceId.isGetParam() && resourceId.getEntityId() instanceof String) { + TranslatedHeatResource shareResource = + translateTo.getContext().getHeatSharedResourcesByParam().get(resourceId.getEntityId()); + if (Objects.nonNull(shareResource) + && !HeatToToscaUtil.isHeatFileNested(translateTo, translateTo.getHeatFileName())) { + if (validateResourceTypeSupportedForReqCreation(translateTo.getResourceId(), paramName, + connectionPointEntry.getKey(), shareResource.getHeatResource(), supportedNodeTypes)) { + return Optional.of(shareResource.getTranslatedId()); + } + } + } + return Optional.empty(); + } + + Optional getConnectionTranslatedHeatResourceUsingGetParamFunc( + Map.Entry connectionPointEntry, String paramName, + List supportedNodeTypes) { + + Optional attachedResourceId = + HeatToToscaUtil.extractAttachedResourceId(translateTo, paramName); + if (!attachedResourceId.isPresent()) { + return Optional.empty(); + } + AttachedResourceId resourceId = attachedResourceId.get(); + if (resourceId.isGetParam() && resourceId.getEntityId() instanceof String) { + TranslatedHeatResource shareResource = + translateTo.getContext().getHeatSharedResourcesByParam().get(resourceId.getEntityId()); + if (Objects.nonNull(shareResource) + && !HeatToToscaUtil.isHeatFileNested(translateTo, translateTo.getHeatFileName())) { + if (validateResourceTypeSupportedForReqCreation(translateTo.getResourceId(), paramName, + connectionPointEntry.getKey(), shareResource.getHeatResource(), supportedNodeTypes)) { + return Optional.of(shareResource); + } + } + } + return Optional.empty(); + } + + + Optional getConnectionTranslatedNodeUsingGetResourceFunc( + Map.Entry connectionPointEntry, String paramName, Object paramValue, + List supportedNodeTypes) { + Optional getResourceAttachedResourceId = + HeatToToscaUtil.extractContrailGetResourceAttachedHeatResourceId(paramValue); + if (getResourceAttachedResourceId.isPresent()) { // get resource + Resource resource = translateTo.getHeatOrchestrationTemplate().getResources() + .get(getResourceAttachedResourceId.get()); + if (validateResourceTypeSupportedForReqCreation(translateTo.getResourceId(), paramName, + connectionPointEntry.getKey(), resource, supportedNodeTypes)) { + return ResourceTranslationBase.getResourceTranslatedId(translateTo.getHeatFileName(), + translateTo.getHeatOrchestrationTemplate(), getResourceAttachedResourceId.get(), + translateTo.getContext()); + } + } + + return Optional.empty(); + } + + Optional getConnectionResourceUsingGetResourceFunc( + Map.Entry connectionPointEntry, String paramName, Object paramValue, + List supportedNodeTypes) { + Optional getResourceAttachedResourceId = + HeatToToscaUtil.extractContrailGetResourceAttachedHeatResourceId(paramValue); + if (getResourceAttachedResourceId.isPresent()) { // get resource + Resource resource = translateTo.getHeatOrchestrationTemplate().getResources() + .get(getResourceAttachedResourceId.get()); + if (validateResourceTypeSupportedForReqCreation(translateTo.getResourceId(), paramName, + connectionPointEntry.getKey(), resource, supportedNodeTypes)) { + return getResourceAttachedResourceId; + } + } + return Optional.empty(); + } +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ContrailPortToNetResourceConnection.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ContrailPortToNetResourceConnection.java new file mode 100644 index 0000000000..efa0ddd8a9 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ContrailPortToNetResourceConnection.java @@ -0,0 +1,191 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; + + +import org.openecomp.sdc.common.utils.CommonUtil; +import org.openecomp.sdc.heat.datatypes.manifest.FileData; +import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate; +import org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes; +import org.openecomp.sdc.heat.datatypes.model.Resource; +import org.openecomp.sdc.heat.services.HeatConstants; +import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; +import org.openecomp.sdc.tosca.datatypes.ToscaCapabilityType; +import org.openecomp.sdc.tosca.datatypes.ToscaNodeType; +import org.openecomp.sdc.tosca.datatypes.ToscaRelationshipType; +import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel; +import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; +import org.openecomp.sdc.tosca.datatypes.model.NodeType; +import org.openecomp.sdc.tosca.datatypes.model.RequirementDefinition; +import org.openecomp.sdc.tosca.services.ToscaAnalyzerService; +import org.openecomp.sdc.tosca.services.impl.ToscaAnalyzerServiceImpl; +import org.openecomp.sdc.translator.datatypes.heattotosca.AttachedResourceId; +import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; +import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.function.Predicate; + +public class ContrailPortToNetResourceConnection extends ResourceConnectionUsingRequirementHelper { + private MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); + + public ContrailPortToNetResourceConnection(ResourceTranslationBase resourceTranslationBase, + TranslateTo translateTo, FileData nestedFileData, + NodeTemplate substitutionNodeTemplate, + NodeType nodeType) { + super(resourceTranslationBase, translateTo, nestedFileData, substitutionNodeTemplate, nodeType); + } + + @Override + protected boolean isDesiredNodeTemplateType(NodeTemplate nodeTemplate) { + ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl(); + ToscaServiceModel toscaServiceModel = + HeatToToscaUtil.getToscaServiceModel(translateTo.getContext()); + return toscaAnalyzerService + .isTypeOf(nodeTemplate, ToscaNodeType.CONTRAIL_ABSTRACT_SUBSTITUTE, + translateTo.getContext().getTranslatedServiceTemplates() + .get(translateTo.getResource().getType()), toscaServiceModel); + } + + @Override + protected List> getPredicatesListForConnectionPoints() { + ArrayList> predicates = new ArrayList<>(); + predicates.add( + req -> req.getCapability().equals(ToscaCapabilityType.NATIVE_NETWORK_LINKABLE) + && (req.getNode() == null || req.getNode().equals(ToscaNodeType.NATIVE_ROOT)) + && req.getRelationship() + .equals(ToscaRelationshipType.NATIVE_NETWORK_LINK_TO)); + return predicates; + } + + @Override + protected Optional> getConnectorPropertyParamName(String heatResourceId, + Resource heatResource, + HeatOrchestrationTemplate + nestedHeatOrchestrationTemplate, + String nestedHeatFileName) { + + mdcDataDebugMessage.debugEntryMessage(null, null); + + Object interfaceListProperty = + heatResource.getProperties().get(HeatConstants.INTERFACE_LIST_PROPERTY_NAME); + if (interfaceListProperty == null) { + return Optional.empty(); + } + List paramsList = new ArrayList<>(); + if (interfaceListProperty instanceof List) { + for (int index = 0; index < ((List) interfaceListProperty).size(); index++) { + Object interfaceEntry = ((List) interfaceListProperty).get(index); + if (interfaceEntry instanceof Map) { + Optional attachedVirtualNetwork = HeatToToscaUtil + .extractAttachedResourceId(nestedHeatFileName, nestedHeatOrchestrationTemplate, + translateTo.getContext(), + ((Map) interfaceEntry).get(HeatConstants.VIRTUAL_NETWORK_PROPERTY_NAME)); + if (attachedVirtualNetwork.isPresent() && attachedVirtualNetwork.get().isGetParam() + && attachedVirtualNetwork.get().getEntityId() instanceof String) { + paramsList.add((String) attachedVirtualNetwork.get().getEntityId()); + } + } + } + + mdcDataDebugMessage.debugExitMessage(null, null); + return Optional.of(paramsList); + } else if (interfaceListProperty instanceof Map) { + Optional attachedVirtualNetwork = HeatToToscaUtil + .extractAttachedResourceId(nestedHeatFileName, nestedHeatOrchestrationTemplate, + translateTo.getContext(), + ((Map) interfaceListProperty).get(HeatConstants.VIRTUAL_NETWORK_PROPERTY_NAME)); + if (attachedVirtualNetwork.isPresent() && attachedVirtualNetwork.get().isGetParam() + && attachedVirtualNetwork.get().getEntityId() instanceof String) { + paramsList.add((String) attachedVirtualNetwork.get().getEntityId()); + return Optional.of(paramsList); + } + } + + mdcDataDebugMessage.debugExitMessage(null, null); + return Optional.empty(); + } + + @Override + protected String getDesiredResourceType() { + return HeatResourcesTypes.CONTRAIL_SERVICE_INSTANCE.getHeatResource(); + } + + @Override + protected void addRequirementToConnectResources( + Map.Entry requirementDefinitionEntry, + List paramNames) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + if (paramNames == null || paramNames.isEmpty()) { + return; + } + Integer index = Integer.valueOf( + requirementDefinitionEntry.getKey().substring("link_port_".length()).substring(0, 1)); + + String paramName = paramNames.get( + index); // port can connect to one network only and we are + // expecting to get only one param(unlike security rules to port) + Object paramValue = translateTo.getResource().getProperties().get(paramName); + List supportedNetworkTypes = + Arrays.asList(HeatResourcesTypes.NEUTRON_NET_RESOURCE_TYPE.getHeatResource(), + HeatResourcesTypes.CONTRAIL_VIRTUAL_NETWORK_RESOURCE_TYPE.getHeatResource()); + + addRequirementToConnectResource(requirementDefinitionEntry, paramName, paramValue, + supportedNetworkTypes); + + mdcDataDebugMessage.debugExitMessage(null, null); + } + + @Override + boolean validateResourceTypeSupportedForReqCreation(String nestedResourceId, + final String nestedPropertyName, + String connectionPointId, + Resource connectedResource, + List supportedTypes) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + if (!resourceTranslationBase.isResourceTypeSupported(connectedResource, supportedTypes)) { + logger.warn("Nested resource '" + nestedResourceId + "' property '" + nestedPropertyName + + "' is pointing to a resource with type '" + connectedResource.getType() + + "' which is not supported for requirement '" + connectionPointId + + "' that connect contrail port to network. Supported types are: '" + + supportedTypes.toString() + + "', therefore, this TOSCA requirement will not be connected."); + + mdcDataDebugMessage.debugExitMessage(null, null); + return false; + } + + mdcDataDebugMessage.debugExitMessage(null, null); + return true; + } + + +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ContrailV2VlanToInterfaceResourceConnection.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ContrailV2VlanToInterfaceResourceConnection.java new file mode 100644 index 0000000000..a757730cb1 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ContrailV2VlanToInterfaceResourceConnection.java @@ -0,0 +1,172 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; + +import org.openecomp.sdc.common.utils.CommonUtil; +import org.openecomp.sdc.heat.datatypes.manifest.FileData; +import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate; +import org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes; +import org.openecomp.sdc.heat.datatypes.model.Resource; +import org.openecomp.sdc.heat.services.HeatConstants; +import org.openecomp.sdc.tosca.datatypes.ToscaCapabilityType; +import org.openecomp.sdc.tosca.datatypes.ToscaNodeType; +import org.openecomp.sdc.tosca.datatypes.ToscaRelationshipType; +import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; +import org.openecomp.sdc.tosca.datatypes.model.NodeType; +import org.openecomp.sdc.tosca.datatypes.model.RequirementDefinition; +import org.openecomp.sdc.translator.datatypes.heattotosca.AttachedResourceId; +import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; +import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; +import org.openecomp.sdc.translator.services.heattotosca.helper.ContrailV2VirtualMachineInterfaceHelper; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.function.Predicate; + +public class ContrailV2VlanToInterfaceResourceConnection + extends ResourceConnectionUsingRequirementHelper { + + public ContrailV2VlanToInterfaceResourceConnection( + ResourceTranslationBase resourceTranslationBase, TranslateTo translateTo, + FileData nestedFileData, NodeTemplate substitutionNodeTemplate, NodeType nodeType) { + super(resourceTranslationBase, translateTo, nestedFileData, substitutionNodeTemplate, nodeType); + } + + @Override + protected boolean isDesiredNodeTemplateType(NodeTemplate nodeTemplate) { + return nodeTemplate.getType() + .equals(ToscaNodeType.CONTRAILV2_VLAN_SUB_INTERFACE); + } + + @Override + protected List> getPredicatesListForConnectionPoints() { + ArrayList> predicates = new ArrayList<>(); + predicates.add( + req -> req.getCapability().equals(ToscaCapabilityType.NATIVE_NETWORK_BINDABLE) + && (req.getNode() == null || req.getNode().equals(ToscaNodeType.NETWORK_PORT)) + && req.getRelationship() + .equals(ToscaRelationshipType.NATIVE_NETWORK_BINDS_TO)); + return predicates; + } + + @Override + protected Optional> getConnectorPropertyParamName(String heatResourceId, + Resource heatResource, + HeatOrchestrationTemplate + nestedHeatOrchestrationTemplate, + String nestedHeatFileName) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + List interfaces = new ArrayList<>(); + Object interfaceRefs = heatResource.getProperties().get(HeatConstants.VMI_REFS_PROPERTY_NAME); + if (Objects.isNull(interfaceRefs) || !(interfaceRefs instanceof List) + || ((List) interfaceRefs).size() == 0) { + return Optional.empty(); + } + if (((List) interfaceRefs).size() > 1) { + logger.warn("Heat resource: '" + translateTo.getResourceId() + "' with nested heat file: '" + + translateTo.getResource().getType() + + "' has resource '" + heatResourceId + "' with type '" + + HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_MACHINE_INTERFACE_RESOURCE_TYPE.getHeatResource() + + "' which include '" + HeatConstants.VMI_REFS_PROPERTY_NAME + + "' property with more than one interface values, " + + "only the first interface will be connected, all rest will be ignored in TOSCA " + + "translation."); + } + Object interfaceRef = ((List) interfaceRefs).get(0); + Optional attachedInterfaceResource = HeatToToscaUtil + .extractAttachedResourceId(nestedFileData.getFile(), nestedHeatOrchestrationTemplate, + translateTo.getContext(), interfaceRef); + if (attachedInterfaceResource.isPresent() && attachedInterfaceResource.get().isGetParam() + && attachedInterfaceResource.get().getEntityId() instanceof String) { + interfaces.add((String) attachedInterfaceResource.get().getEntityId()); + } + + mdcDataDebugMessage.debugExitMessage(null, null); + return Optional.of(interfaces); + } + + @Override + protected String getDesiredResourceType() { + return HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_MACHINE_INTERFACE_RESOURCE_TYPE.getHeatResource(); + } + + @Override + protected void addRequirementToConnectResources( + Map.Entry requirementDefinitionEntry, + List paramNames) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + if (paramNames == null || paramNames.isEmpty()) { + return; + } + for (String paramName : paramNames) { + Object paramValue = translateTo.getResource().getProperties().get(paramName); + List supportedInterfaceTypes = + Arrays.asList(HeatResourcesTypes.NEUTRON_PORT_RESOURCE_TYPE.getHeatResource(), + HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_MACHINE_INTERFACE_RESOURCE_TYPE + .getHeatResource()); + + addRequirementToConnectResource(requirementDefinitionEntry, paramName, paramValue, + supportedInterfaceTypes); + } + + mdcDataDebugMessage.debugExitMessage(null, null); + } + + @Override + boolean validateResourceTypeSupportedForReqCreation(String nestedResourceId, + final String nestedPropertyName, + String connectionPointId, + Resource connectedResource, + List supportedTypes) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + if (!resourceTranslationBase.isResourceTypeSupported(connectedResource, supportedTypes) + || (new ContrailV2VirtualMachineInterfaceHelper() + .isVlanSubInterfaceResource(connectedResource))) { + logger.warn("Nested resource '" + nestedResourceId + "' property '" + nestedPropertyName + + "' is pointing to a " + (true == (new ContrailV2VirtualMachineInterfaceHelper() + .isVlanSubInterfaceResource(connectedResource)) ? "Vlan Sub interface " : "") + + "resource with type '" + connectedResource.getType() + "' which" + + " is not supported for requirement '" + connectionPointId + + "' that connect vmi vlan sub interface to interface. Supported types are: '" + + supportedTypes.toString() + "' (excluding Vlan), therefore, this TOSCA requirement will" + + " not be connected."); + + mdcDataDebugMessage.debugExitMessage(null, null); + return false; + } + + mdcDataDebugMessage.debugExitMessage(null, null); + return true; + } +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ContrailV2VmInterfaceToNetResourceConnection.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ContrailV2VmInterfaceToNetResourceConnection.java new file mode 100644 index 0000000000..944afb0fc3 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ContrailV2VmInterfaceToNetResourceConnection.java @@ -0,0 +1,166 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; + +import org.openecomp.sdc.common.utils.CommonUtil; +import org.openecomp.sdc.heat.datatypes.manifest.FileData; +import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate; +import org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes; +import org.openecomp.sdc.heat.datatypes.model.Resource; +import org.openecomp.sdc.tosca.datatypes.ToscaCapabilityType; +import org.openecomp.sdc.tosca.datatypes.ToscaNodeType; +import org.openecomp.sdc.tosca.datatypes.ToscaRelationshipType; +import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; +import org.openecomp.sdc.tosca.datatypes.model.NodeType; +import org.openecomp.sdc.tosca.datatypes.model.RequirementDefinition; +import org.openecomp.sdc.translator.datatypes.heattotosca.AttachedResourceId; +import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; +import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.function.Predicate; + +public class ContrailV2VmInterfaceToNetResourceConnection + extends ResourceConnectionUsingRequirementHelper { + + public ContrailV2VmInterfaceToNetResourceConnection( + ResourceTranslationBase resourceTranslationBase, TranslateTo translateTo, + FileData nestedFileData, NodeTemplate substitutionNodeTemplate, NodeType nodeType) { + super(resourceTranslationBase, translateTo, nestedFileData, substitutionNodeTemplate, nodeType); + } + + @Override + protected boolean isDesiredNodeTemplateType(NodeTemplate nodeTemplate) { + return (nodeTemplate.getType() + .equals(ToscaNodeType.CONTRAILV2_VIRTUAL_MACHINE_INTERFACE) + || nodeTemplate.getType() + .equals(ToscaNodeType.CONTRAILV2_VLAN_SUB_INTERFACE)); + } + + @Override + protected List> getPredicatesListForConnectionPoints() { + ArrayList> predicates = new ArrayList<>(); + predicates.add( + req -> req.getCapability().equals(ToscaCapabilityType.NATIVE_NETWORK_LINKABLE) + && (req.getNode() == null || req.getNode().equals(ToscaNodeType.NATIVE_ROOT)) + && req.getRelationship() + .equals(ToscaRelationshipType.NATIVE_NETWORK_LINK_TO)); + return predicates; + } + + @Override + protected Optional> getConnectorPropertyParamName(String heatResourceId, + Resource heatResource, + HeatOrchestrationTemplate + nestedHeatOrchestrationTemplate, + String nestedHeatFileName) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + List networks = new ArrayList<>(); + Object virtualNetworkRefs = heatResource.getProperties().get("virtual_network_refs"); + if (Objects.isNull(virtualNetworkRefs) || !(virtualNetworkRefs instanceof List) + || ((List) virtualNetworkRefs).size() == 0) { + return Optional.empty(); + } + if (((List) virtualNetworkRefs).size() > 1) { + logger.warn("Heat resource: '" + translateTo.getResourceId() + "' with nested heat file: '" + + translateTo.getResource().getType() + + "' has resource '" + heatResourceId + "' with type '" + + HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_MACHINE_INTERFACE_RESOURCE_TYPE.getHeatResource() + + "' which include 'virtual_network_refs' property with more than one network values, " + + "only the first network will be translated, all rest will be ignored in TOSCA " + + "translation."); + } + Object virtualNetworkRef = ((List) virtualNetworkRefs).get(0); + Optional network = HeatToToscaUtil + .extractAttachedResourceId(nestedFileData.getFile(), nestedHeatOrchestrationTemplate, + translateTo.getContext(), virtualNetworkRef); + if (network.isPresent() && network.get().isGetParam() + && network.get().getEntityId() instanceof String) { + networks.add((String) network.get().getEntityId()); + } + + mdcDataDebugMessage.debugExitMessage(null, null); + return Optional.of(networks); + } + + @Override + protected String getDesiredResourceType() { + return HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_MACHINE_INTERFACE_RESOURCE_TYPE.getHeatResource(); + } + + @Override + protected void addRequirementToConnectResources( + Map.Entry requirementDefinitionEntry, + List paramNames) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + if (paramNames == null || paramNames.isEmpty()) { + return; + } + for (String paramName : paramNames) { + Object paramValue = translateTo.getResource().getProperties().get(paramName); + List supportedNetworkTypes = + Arrays.asList(HeatResourcesTypes.NEUTRON_NET_RESOURCE_TYPE.getHeatResource(), + HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_NETWORK_RESOURCE_TYPE.getHeatResource()); + + addRequirementToConnectResource(requirementDefinitionEntry, paramName, paramValue, + supportedNetworkTypes); + } + + mdcDataDebugMessage.debugExitMessage(null, null); + } + + @Override + boolean validateResourceTypeSupportedForReqCreation(String nestedResourceId, + final String nestedPropertyName, + String connectionPointId, + Resource connectedResource, + List supportedTypes) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + if (!resourceTranslationBase.isResourceTypeSupported(connectedResource, supportedTypes)) { + logger.warn("Nested resource '" + nestedResourceId + "' property '" + nestedPropertyName + + "' is pointing to a resource with type '" + connectedResource.getType() + + "' which is not supported for requirement '" + connectionPointId + + "' that connect virtual machine interface to network. Supported types are: '" + + supportedTypes.toString() + + "', therefore, this TOSCA requirement will not be connected."); + + mdcDataDebugMessage.debugExitMessage(null, null); + return false; + } + + mdcDataDebugMessage.debugExitMessage(null, null); + return true; + } +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/NovaToVolResourceConnection.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/NovaToVolResourceConnection.java new file mode 100644 index 0000000000..496341e11f --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/NovaToVolResourceConnection.java @@ -0,0 +1,269 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; + +import org.apache.commons.collections4.CollectionUtils; +import org.openecomp.sdc.common.errors.CoreException; +import org.openecomp.sdc.datatypes.error.ErrorLevel; +import org.openecomp.sdc.heat.datatypes.manifest.FileData; +import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate; +import org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes; +import org.openecomp.sdc.heat.datatypes.model.Resource; +import org.openecomp.sdc.logging.context.impl.MdcDataErrorMessage; +import org.openecomp.sdc.logging.types.LoggerConstants; +import org.openecomp.sdc.logging.types.LoggerErrorCode; +import org.openecomp.sdc.logging.types.LoggerErrorDescription; +import org.openecomp.sdc.logging.types.LoggerTragetServiceName; +import org.openecomp.sdc.tosca.datatypes.ToscaCapabilityType; +import org.openecomp.sdc.tosca.datatypes.ToscaNodeType; +import org.openecomp.sdc.tosca.datatypes.ToscaRelationshipType; +import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel; +import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; +import org.openecomp.sdc.tosca.datatypes.model.NodeType; +import org.openecomp.sdc.tosca.datatypes.model.RequirementDefinition; +import org.openecomp.sdc.tosca.services.ToscaAnalyzerService; +import org.openecomp.sdc.tosca.services.impl.ToscaAnalyzerServiceImpl; +import org.openecomp.sdc.translator.datatypes.heattotosca.AttachedResourceId; +import org.openecomp.sdc.translator.datatypes.heattotosca.TranslationContext; +import org.openecomp.sdc.translator.datatypes.heattotosca.to.ResourceFileDataAndIDs; +import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; +import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslatedHeatResource; +import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; +import org.openecomp.sdc.translator.services.heattotosca.errors.MissingMandatoryPropertyErrorBuilder; +import org.openecomp.sdc.translator.services.heattotosca.helper.VolumeTranslationHelper; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.function.Predicate; +import java.util.stream.Collectors; + +class NovaToVolResourceConnection extends ResourceConnectionUsingRequirementHelper { + + public NovaToVolResourceConnection(ResourceTranslationBase resourceTranslationBase, + TranslateTo translateTo, FileData nestedFileData, + NodeTemplate substitutionNodeTemplate, NodeType nodeType) { + super(resourceTranslationBase, translateTo, nestedFileData, substitutionNodeTemplate, nodeType); + } + + @Override + boolean isDesiredNodeTemplateType(NodeTemplate nodeTemplate) { + ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl(); + ToscaServiceModel toscaServiceModel = + HeatToToscaUtil.getToscaServiceModel(translateTo.getContext()); + return toscaAnalyzerService.isTypeOf(nodeTemplate, ToscaNodeType.NOVA_SERVER, + translateTo.getContext().getTranslatedServiceTemplates() + .get(translateTo.getResource().getType()), toscaServiceModel); + } + + @Override + List> getPredicatesListForConnectionPoints() { + ArrayList> predicates = new ArrayList<>(); + predicates + .add(req -> req.getCapability().equals(ToscaCapabilityType.NATIVE_ATTACHMENT) + && req.getNode().equals(ToscaNodeType.NATIVE_BLOCK_STORAGE) + && req.getRelationship() + .equals(ToscaRelationshipType.NATIVE_ATTACHES_TO)); + return predicates; + } + + @Override + Optional> getConnectorPropertyParamName(String heatResourceId, Resource heatResource, + HeatOrchestrationTemplate + nestedHeatOrchestrationTemplate, + String nestedHeatFileName) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + Optional volumeId = HeatToToscaUtil + .extractAttachedResourceId(nestedFileData.getFile(), nestedHeatOrchestrationTemplate, + translateTo.getContext(), heatResource.getProperties().get("volume_id")); + if (volumeId.isPresent() && volumeId.get().isGetParam() + && volumeId.get().getEntityId() instanceof String) { + mdcDataDebugMessage.debugExitMessage(null, null); + return Optional.of(Collections.singletonList((String) volumeId.get().getEntityId())); + } else { + mdcDataDebugMessage.debugExitMessage(null, null); + return Optional.empty(); + } + } + + @Override + String getDesiredResourceType() { + return HeatResourcesTypes.CINDER_VOLUME_ATTACHMENT_RESOURCE_TYPE.getHeatResource(); + } + + @Override + void addRequirementToConnectResources( + Map.Entry requirementDefinitionEntry, + List paramNames) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + if (paramNames == null || paramNames.isEmpty()) { + return; + } + + List supportedVolumeTypes = + Collections.singletonList(HeatResourcesTypes.CINDER_VOLUME_RESOURCE_TYPE.getHeatResource()); + + for (String paramName : paramNames) { + Object paramValue = translateTo.getResource().getProperties().get(paramName); + addRequirementToConnectResource(requirementDefinitionEntry, paramName, paramValue, + supportedVolumeTypes); + } + + mdcDataDebugMessage.debugExitMessage(null, null); + } + + @Override + boolean validateResourceTypeSupportedForReqCreation(String nestedResourceId, + String nestedPropertyName, + String connectionPointId, + Resource connectedResource, + List supportedTypes) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + if (!resourceTranslationBase.isResourceTypeSupported(connectedResource, supportedTypes)) { + logger.warn("Nested resource '" + nestedResourceId + "' property '" + nestedPropertyName + + "' is pointing to a resource with type '" + connectedResource.getType() + + "' which is not supported for requirement '" + connectionPointId + + "' that connect VolumeAttachment to Volume. Supported types are: '" + + supportedTypes.toString() + + "', therefore, this TOSCA requirement will not be connected."); + + mdcDataDebugMessage.debugExitMessage(null, null); + return false; + } + + mdcDataDebugMessage.debugExitMessage(null, null); + return true; + } + + @Override + protected Optional>> getResourceByTranslatedResourceId( + String translatedResourceId, HeatOrchestrationTemplate nestedHeatOrchestrationTemplate) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + List>> predicates = + buildPredicates(nestedFileData.getFile(), nestedHeatOrchestrationTemplate, + translatedResourceId); + List> list = + nestedHeatOrchestrationTemplate.getResources().entrySet() + .stream() + .filter(entry -> predicates + .stream() + .allMatch(p -> p.test(entry))) + .collect(Collectors.toList()); + if (CollectionUtils.isEmpty(list)) { + mdcDataDebugMessage.debugExitMessage(null, null); + return Optional.empty(); + } else { + mdcDataDebugMessage.debugExitMessage(null, null); + return Optional.of(list); + } + } + + @Override + Optional getConnectionTranslatedNodeUsingGetParamFunc( + Map.Entry requirementDefinitionEntry, String paramName, + List supportedTargetNodeTypes) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + Optional targetTranslatedNodeId = super + .getConnectionTranslatedNodeUsingGetParamFunc(requirementDefinitionEntry, paramName, + supportedTargetNodeTypes); + if (targetTranslatedNodeId.isPresent()) { + return targetTranslatedNodeId; + } else { + Optional attachedResourceId = + HeatToToscaUtil.extractAttachedResourceId(translateTo, paramName); + if (!attachedResourceId.isPresent()) { + return Optional.empty(); + } + AttachedResourceId resourceId = attachedResourceId.get(); + if (resourceId.isGetParam() && resourceId.getEntityId() instanceof String) { + TranslatedHeatResource shareResource = + translateTo.getContext().getHeatSharedResourcesByParam().get(resourceId.getEntityId()); + if (Objects.isNull(shareResource)) { + List allFilesData = + translateTo.getContext().getManifest().getContent().getData(); + Optional fileData = + HeatToToscaUtil.getFileData(translateTo.getHeatFileName(), allFilesData); + if (fileData.isPresent()) { + Optional fileDataContainingResource = + new VolumeTranslationHelper(logger) + .getFileDataContainingVolume(fileData.get().getData(), + (String) resourceId.getEntityId(), translateTo, FileData.Type.HEAT_VOL); + if (fileDataContainingResource.isPresent()) { + mdcDataDebugMessage.debugExitMessage(null, null); + return Optional.of(fileDataContainingResource.get().getTranslatedResourceId()); + } + } + } + } + + mdcDataDebugMessage.debugExitMessage(null, null); + return Optional.empty(); + } + } + + private List>> buildPredicates( + String fileName, + HeatOrchestrationTemplate heatOrchestrationTemplate, + String novaTranslatedResourceId) { + List>> list = new ArrayList<>(); + list.add(entry -> entry.getValue().getType().equals(getDesiredResourceType())); + list.add(entry -> { + Object instanceUuidProp = entry.getValue().getProperties().get("instance_uuid"); + TranslationContext context = translateTo.getContext(); + Optional instanceUuid = HeatToToscaUtil + .extractAttachedResourceId(fileName, heatOrchestrationTemplate, context, + instanceUuidProp); + if (instanceUuid.isPresent()) { + Optional resourceTranslatedId = + ResourceTranslationBase.getResourceTranslatedId(fileName, heatOrchestrationTemplate, + (String) instanceUuid.get().getTranslatedId(), context); + return resourceTranslatedId.isPresent() + && resourceTranslatedId.get().equals(novaTranslatedResourceId); + + } else { + MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, + LoggerTragetServiceName.GET_RESOURCE, ErrorLevel.ERROR.name(), + LoggerErrorCode.DATA_ERROR.getErrorCode(), + LoggerErrorDescription.MISSING_MANDATORY_PROPERTY); + throw new CoreException(new MissingMandatoryPropertyErrorBuilder("instance_uuid").build()); + } + }); + return list; + } +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/PortToNetResourceConnection.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/PortToNetResourceConnection.java new file mode 100644 index 0000000000..d3e8676ca1 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/PortToNetResourceConnection.java @@ -0,0 +1,159 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; + +import org.openecomp.sdc.common.utils.CommonUtil; +import org.openecomp.sdc.heat.datatypes.manifest.FileData; +import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate; +import org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes; +import org.openecomp.sdc.heat.datatypes.model.Resource; +import org.openecomp.sdc.tosca.datatypes.ToscaCapabilityType; +import org.openecomp.sdc.tosca.datatypes.ToscaNodeType; +import org.openecomp.sdc.tosca.datatypes.ToscaRelationshipType; +import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; +import org.openecomp.sdc.tosca.datatypes.model.NodeType; +import org.openecomp.sdc.tosca.datatypes.model.RequirementDefinition; +import org.openecomp.sdc.translator.datatypes.heattotosca.AttachedResourceId; +import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; +import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.function.Predicate; + +public class PortToNetResourceConnection extends ResourceConnectionUsingRequirementHelper { + + public PortToNetResourceConnection(ResourceTranslationBase resourceTranslationBase, + TranslateTo translateTo, FileData nestedFileData, + NodeTemplate substitutionNodeTemplate, NodeType nodeType) { + super(resourceTranslationBase, translateTo, nestedFileData, substitutionNodeTemplate, nodeType); + } + + @Override + protected boolean isDesiredNodeTemplateType(NodeTemplate nodeTemplate) { + return nodeTemplate.getType().equals(ToscaNodeType.NEUTRON_PORT); + } + + @Override + protected List> getPredicatesListForConnectionPoints() { + ArrayList> predicates = new ArrayList<>(); + predicates.add( + req -> req.getCapability().equals(ToscaCapabilityType.NATIVE_NETWORK_LINKABLE) + && (req.getNode() == null || req.getNode().equals(ToscaNodeType.NATIVE_ROOT)) + && req.getRelationship().equals( + ToscaRelationshipType.NATIVE_NETWORK_LINK_TO)); + return predicates; + } + + @Override + protected Optional> getConnectorPropertyParamName(String heatResourceId, + Resource heatResource, + HeatOrchestrationTemplate + nestedHeatOrchestrationTemplate, + String nestedHeatFileName) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + Optional network = HeatToToscaUtil + .extractAttachedResourceId(nestedHeatFileName, nestedHeatOrchestrationTemplate, + translateTo.getContext(), heatResource.getProperties().get("network")); + if (network.isPresent() && network.get().isGetParam() + && network.get().getEntityId() instanceof String) { + return Optional.of(Collections.singletonList((String) network.get().getEntityId())); + } else { + network = HeatToToscaUtil + .extractAttachedResourceId(nestedHeatFileName, nestedHeatOrchestrationTemplate, + translateTo.getContext(), heatResource.getProperties().get("network_id")); + if (network.isPresent() + && network.get().isGetParam() + && network.get().getEntityId() instanceof String) { + mdcDataDebugMessage.debugExitMessage(null, null); + return Optional.of(Collections.singletonList((String) network.get().getEntityId())); + } else { + mdcDataDebugMessage.debugExitMessage(null, null); + return Optional.empty(); + } + } + } + + @Override + protected String getDesiredResourceType() { + return HeatResourcesTypes.NEUTRON_PORT_RESOURCE_TYPE.getHeatResource(); + } + + @Override + protected void addRequirementToConnectResources( + Map.Entry requirementDefinitionEntry, + List paramNames) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + if (paramNames == null || paramNames.isEmpty()) { + return; + } + String paramName = paramNames.get( + 0); // port can connect to one network only and we are + // expecting to have only one param(unlike security rules to port) + Object paramValue = translateTo.getResource().getProperties().get(paramName); + List supportedNetworkTypes = + Arrays.asList(HeatResourcesTypes.NEUTRON_NET_RESOURCE_TYPE.getHeatResource(), + HeatResourcesTypes.CONTRAIL_VIRTUAL_NETWORK_RESOURCE_TYPE.getHeatResource(), + HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_NETWORK_RESOURCE_TYPE.getHeatResource()); + + addRequirementToConnectResource(requirementDefinitionEntry, paramName, paramValue, + supportedNetworkTypes); + + mdcDataDebugMessage.debugExitMessage(null, null); + } + + @Override + boolean validateResourceTypeSupportedForReqCreation(String nestedResourceId, + final String nestedPropertyName, + String connectionPointId, + Resource connectedResource, + List supportedTypes) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + if (!resourceTranslationBase.isResourceTypeSupported(connectedResource, supportedTypes)) { + logger.warn("Nested resource '" + nestedResourceId + "' property '" + nestedPropertyName + + "' is pointing to a resource with type '" + connectedResource.getType() + + "' which is not supported for requirement '" + connectionPointId + + "' that connect port to network. Supported types are: '" + supportedTypes.toString() + + "', therefore, this TOSCA requirement will not be connected."); + + mdcDataDebugMessage.debugExitMessage(null, null); + return false; + } + + mdcDataDebugMessage.debugExitMessage(null, null); + return true; + } + + +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceConnectionUsingCapabilityHelper.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceConnectionUsingCapabilityHelper.java new file mode 100644 index 0000000000..231190a16f --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceConnectionUsingCapabilityHelper.java @@ -0,0 +1,210 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; + +import org.openecomp.sdc.common.utils.CommonUtil; +import org.openecomp.sdc.heat.datatypes.manifest.FileData; +import org.openecomp.sdc.heat.datatypes.model.Resource; +import org.openecomp.sdc.tosca.datatypes.model.CapabilityDefinition; +import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; +import org.openecomp.sdc.tosca.datatypes.model.NodeType; +import org.openecomp.sdc.tosca.datatypes.model.RequirementAssignment; +import org.openecomp.sdc.tosca.datatypes.model.RequirementDefinition; +import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; +import org.openecomp.sdc.tosca.services.DataModelUtil; +import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; +import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslatedHeatResource; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.ConsolidationData; +import org.openecomp.sdc.translator.services.heattotosca.ConsolidationDataUtil; +import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; +import org.openecomp.sdc.translator.services.heattotosca.ResourceTranslationFactory; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.function.Predicate; + +public abstract class ResourceConnectionUsingCapabilityHelper + extends BaseResourceConnection { + public ResourceConnectionUsingCapabilityHelper(ResourceTranslationBase resourceTranslationBase, + TranslateTo translateTo, FileData nestedFileData, + NodeTemplate substitutionNodeTemplate, + NodeType nodeType) { + super(resourceTranslationBase, translateTo, nestedFileData, substitutionNodeTemplate, nodeType); + } + + abstract Map.Entry createRequirementDefinition( + String capabilityKey); + + @Override + String getMappedNodeTranslatedResourceId(ServiceTemplate nestedServiceTemplate, + Map.Entry connectionPointEntry) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + List substitutionMapping = + nestedServiceTemplate.getTopology_template().getSubstitution_mappings().getCapabilities() + .get(connectionPointEntry.getKey()); + + mdcDataDebugMessage.debugExitMessage(null, null); + return substitutionMapping.get(0); + } + + @Override + Map.Entry getMappedConnectionPointEntry( + ServiceTemplate nestedServiceTemplate, + Map.Entry connectionPointEntry) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + List substitutionMapping = + nestedServiceTemplate.getTopology_template().getSubstitution_mappings().getCapabilities() + .get(connectionPointEntry.getKey()); + String mappedNodeTranslatedId = substitutionMapping.get(0); + String mappedCapabilityId = substitutionMapping.get(1); + NodeTemplate mappedNodeTemplate = + nestedServiceTemplate.getTopology_template().getNode_templates() + .get(mappedNodeTranslatedId); + NodeType substituteNodeType = + translateTo.getContext().getGlobalSubstitutionServiceTemplate().getNode_types() + .get(mappedNodeTemplate.getType()); + Optional capabilityDefinition = + DataModelUtil.getCapabilityDefinition(substituteNodeType, mappedCapabilityId); + + mdcDataDebugMessage.debugExitMessage(null, null); + return new Map.Entry() { + @Override + public String getKey() { + return mappedCapabilityId; + } + + @Override + public CapabilityDefinition getValue() { + return capabilityDefinition.get(); + } + + @Override + public CapabilityDefinition setValue(CapabilityDefinition value) { + return null; + } + }; + } + + @Override + protected List> getAllConnectionPoints() { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + List> exposedRequirementsList = new ArrayList<>(); + List> predicates = getPredicatesListForConnectionPoints(); + Map capabilities = this.nodeType.getCapabilities(); + if (capabilities == null) { + return exposedRequirementsList; + } + capabilities.entrySet() + .stream() + .filter(entry -> predicates + .stream() + .anyMatch(p -> p.test(entry.getValue()))) + .forEach(entry -> { + Map exposedRequirementsMap = new HashMap<>(); + exposedRequirementsMap.put(entry.getKey(), entry.getValue()); + exposedRequirementsList.add(exposedRequirementsMap); + }); + + mdcDataDebugMessage.debugExitMessage(null, null); + return exposedRequirementsList; + } + + void addRequirementToConnectResource(Map.Entry connectionPointEntry, + List supportedSourceNodeTypes, String paramName) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + Object paramValue = translateTo.getResource().getProperties().get(paramName); + if (paramValue == null) { + logger.warn("'" + paramName + "' property is not define in nested resource '" + + translateTo.getResourceId() + "' for the nested heat file, therefore, '" + + connectionPointEntry.getKey() + "' TOSCA capability will not be connected."); + mdcDataDebugMessage.debugExitMessage(null, null); + return; + } + + Map.Entry requirementDefinition = + createRequirementDefinition(connectionPointEntry.getKey()); + + Optional sourceResourceId = + getConnectionResourceUsingGetResourceFunc(connectionPointEntry, paramName, paramValue, + supportedSourceNodeTypes); + if (sourceResourceId.isPresent()) { + Resource sourceResource = HeatToToscaUtil + .getResource(translateTo.getHeatOrchestrationTemplate(), sourceResourceId.get(), + translateTo.getHeatFileName()); + Optional translatedSourceNodeId = + ResourceTranslationFactory.getInstance(sourceResource) + .translateResource(translateTo.getHeatFileName(), translateTo.getServiceTemplate(), + translateTo.getHeatOrchestrationTemplate(), sourceResource, + sourceResourceId.get(), translateTo.getContext()); + if (translatedSourceNodeId.isPresent()) { + NodeTemplate sourceNodeTemplate = DataModelUtil + .getNodeTemplate(translateTo.getServiceTemplate(), translatedSourceNodeId.get()); + RequirementAssignment requirementAssignment = createRequirementAssignment( + requirementDefinition, translateTo.getTranslatedId(), sourceNodeTemplate); + ConsolidationDataUtil.updateNodesConnectedData(translateTo, translateTo.getResourceId(), + translateTo.getResource(), sourceResource, translatedSourceNodeId.get(), + requirementDefinition.getKey(), requirementAssignment); + } else { + logger.warn( + "'" + sourceResource.getType() + "' connection to '" + connectionPointEntry.getKey() + + "' capability of type '" + connectionPointEntry.getValue().getType() + + "' is not supported/invalid, therefore this connection will be ignored in the " + + "TOSCA translation"); + } + } else { + Optional sharedSourceTranslatedHeatResource = + getConnectionTranslatedHeatResourceUsingGetParamFunc(connectionPointEntry, paramName, + supportedSourceNodeTypes); + if (sharedSourceTranslatedHeatResource.isPresent()) { + NodeTemplate sharedSourceNodeTemplate = DataModelUtil + .getNodeTemplate(translateTo.getServiceTemplate(), + sharedSourceTranslatedHeatResource.get().getTranslatedId()); + RequirementAssignment requirementAssignment = createRequirementAssignment( + requirementDefinition, translateTo.getTranslatedId(), sharedSourceNodeTemplate); + + ConsolidationDataUtil.updateNodesConnectedData(translateTo, translateTo.getResourceId(), + translateTo.getResource(), sharedSourceTranslatedHeatResource.get().getHeatResource(), + sharedSourceTranslatedHeatResource.get().getTranslatedId(), + requirementDefinition.getKey(), + requirementAssignment); + } + } + + mdcDataDebugMessage.debugExitMessage(null, null); + } + +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceConnectionUsingRequirementHelper.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceConnectionUsingRequirementHelper.java new file mode 100644 index 0000000000..6ddd0c7334 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceConnectionUsingRequirementHelper.java @@ -0,0 +1,163 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; + +import org.openecomp.sdc.common.utils.CommonUtil; +import org.openecomp.sdc.heat.datatypes.manifest.FileData; +import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; +import org.openecomp.sdc.tosca.datatypes.model.NodeType; +import org.openecomp.sdc.tosca.datatypes.model.RequirementDefinition; +import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; +import org.openecomp.sdc.tosca.services.DataModelUtil; +import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.function.Predicate; + +public abstract class ResourceConnectionUsingRequirementHelper + extends BaseResourceConnection { + public ResourceConnectionUsingRequirementHelper(ResourceTranslationBase resourceTranslationBase, + TranslateTo translateTo, FileData nestedFileData, + NodeTemplate substitutionNodeTemplate, + NodeType nodeType) { + super(resourceTranslationBase, translateTo, nestedFileData, substitutionNodeTemplate, nodeType); + } + + @Override + String getMappedNodeTranslatedResourceId(ServiceTemplate nestedServiceTemplate, + Map.Entry connectionPointEntry) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + List substitutionMapping = + nestedServiceTemplate.getTopology_template().getSubstitution_mappings().getRequirements() + .get(connectionPointEntry.getKey()); + + mdcDataDebugMessage.debugExitMessage(null, null); + return substitutionMapping.get(0); + } + + @Override + Map.Entry getMappedConnectionPointEntry( + ServiceTemplate nestedServiceTemplate, + Map.Entry connectionPointEntry) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + List substitutionMapping = + nestedServiceTemplate.getTopology_template().getSubstitution_mappings().getRequirements() + .get(connectionPointEntry.getKey()); + String mappedNodeTranslatedId = substitutionMapping.get(0); + String mappedReqId = substitutionMapping.get(1); + NodeTemplate mappedNodeTemplate = + nestedServiceTemplate.getTopology_template().getNode_templates() + .get(mappedNodeTranslatedId); + NodeType substituteNodeType = + translateTo.getContext().getGlobalSubstitutionServiceTemplate().getNode_types() + .get(mappedNodeTemplate.getType()); + Optional requirementDefinition = + DataModelUtil.getRequirementDefinition(substituteNodeType, mappedReqId); + + mdcDataDebugMessage.debugExitMessage(null, null); + return new Map.Entry() { + @Override + public String getKey() { + return mappedReqId; + } + + @Override + public RequirementDefinition getValue() { + return requirementDefinition.get(); + } + + @Override + public RequirementDefinition setValue(RequirementDefinition value) { + return null; + } + }; + } + + @Override + List> getAllConnectionPoints() { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + List> exposedRequirementsList = new ArrayList<>(); + List> predicates = getPredicatesListForConnectionPoints(); + List> requirements = this.nodeType.getRequirements(); + if (requirements == null) { + return exposedRequirementsList; + } + requirements.stream() + .map(Map::entrySet) + .forEach(x -> x.stream() + .filter(entry -> predicates + .stream() + .anyMatch(p -> p.test(entry.getValue()))) + .forEach(entry -> { + Map exposedRequirementsMap = new HashMap<>(); + exposedRequirementsMap.put(entry.getKey(), entry.getValue()); + exposedRequirementsList.add(exposedRequirementsMap); + })); + + mdcDataDebugMessage.debugExitMessage(null, null); + return exposedRequirementsList; + } + + void addRequirementToConnectResource( + Map.Entry requirementDefinitionEntry, String paramName, + Object paramValue, List supportedNetworkTypes) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + if (paramValue == null) { + logger.warn("'" + paramName + "' property is not define in nested resource '" + + translateTo.getResourceId() + "' for the nested heat file, therefore, '" + + requirementDefinitionEntry.getKey() + "' TOSCA requirement will not be connected."); + return; + } + Optional targetTranslatedNodeId = + getConnectionTranslatedNodeUsingGetResourceFunc(requirementDefinitionEntry, paramName, + paramValue, supportedNetworkTypes); + if (targetTranslatedNodeId.isPresent()) { + createRequirementAssignment(requirementDefinitionEntry, targetTranslatedNodeId.get(), + substitutionNodeTemplate); + } else { + targetTranslatedNodeId = + getConnectionTranslatedNodeUsingGetParamFunc(requirementDefinitionEntry, paramName, + supportedNetworkTypes); + targetTranslatedNodeId + .ifPresent(targetTranslatedId -> createRequirementAssignment(requirementDefinitionEntry, + targetTranslatedId, substitutionNodeTemplate)); + } + + mdcDataDebugMessage.debugExitMessage(null, null); + } +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationBase.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationBase.java new file mode 100644 index 0000000000..385a0fb0f5 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationBase.java @@ -0,0 +1,354 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; + +import org.apache.commons.collections4.CollectionUtils; +import org.openecomp.sdc.common.errors.CoreException; +import org.openecomp.sdc.datatypes.error.ErrorLevel; +import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate; +import org.openecomp.sdc.heat.datatypes.model.Resource; +import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; +import org.openecomp.sdc.logging.context.impl.MdcDataErrorMessage; +import org.openecomp.sdc.logging.types.LoggerConstants; +import org.openecomp.sdc.logging.types.LoggerErrorCode; +import org.openecomp.sdc.logging.types.LoggerErrorDescription; +import org.openecomp.sdc.logging.types.LoggerTragetServiceName; +import org.openecomp.sdc.tosca.datatypes.ToscaCapabilityType; +import org.openecomp.sdc.tosca.datatypes.ToscaRelationshipType; +import org.openecomp.sdc.tosca.datatypes.ToscaTopologyTemplateElements; +import org.openecomp.sdc.tosca.datatypes.model.RequirementAssignment; +import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; +import org.openecomp.sdc.tosca.services.DataModelUtil; +import org.openecomp.sdc.tosca.services.ToscaConstants; +import org.openecomp.sdc.translator.datatypes.heattotosca.TranslationContext; +import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; +import org.openecomp.sdc.translator.services.heattotosca.ConsolidationDataUtil; +import org.openecomp.sdc.translator.services.heattotosca.ConsolidationEntityType; +import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; +import org.openecomp.sdc.translator.services.heattotosca.ResourceTranslationFactory; +import org.openecomp.sdc.translator.services.heattotosca.errors.ResourceNotFoundInHeatFileErrorBuilder; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.function.Predicate; +import java.util.stream.Collectors; + +public abstract class ResourceTranslationBase { + + protected static Logger logger = (Logger) LoggerFactory.getLogger(ResourceTranslationBase.class); + protected static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); + + protected abstract void translate(TranslateTo translateTo); + + /** + * Translate resource. + * + * @param heatFileName the heat file name + * @param serviceTemplate the service template + * @param heatOrchestrationTemplate the heat orchestration template + * @param resource the resource + * @param resourceId the resource id + * @param context the context + * @return the translated id if this resource is supported, or empty value if not supported + */ + public Optional translateResource(String heatFileName, ServiceTemplate serviceTemplate, + HeatOrchestrationTemplate heatOrchestrationTemplate, + Resource resource, String resourceId, + TranslationContext context) { + + mdcDataDebugMessage.debugEntryMessage("file, resource", heatFileName, resourceId); + Optional translatedId = + getResourceTranslatedId(heatFileName, heatOrchestrationTemplate, resourceId, context); + context.getTranslatedResources().putIfAbsent(heatFileName, new HashSet<>()); + if (context.getTranslatedResources().get(heatFileName).contains(resourceId)) { + return translatedId; + } + if (!translatedId.isPresent()) { + return Optional.empty(); + } + logger.debug("Translate- file:" + heatFileName + " resource Id:" + resourceId + + " translated resource id:" + translatedId.get()); + TranslateTo translateTo = new TranslateTo(heatFileName, serviceTemplate, + heatOrchestrationTemplate, resource, resourceId, translatedId.get(), context); + translate(translateTo); + context.getTranslatedResources().get(heatFileName).add(resourceId); + + if (DataModelUtil.isNodeTemplate(translatedId.get(), serviceTemplate)) { + if (!context.getHeatStackGroupMembers().containsKey(heatFileName)) { + context.getHeatStackGroupMembers().put(heatFileName, new HashSet<>()); + } + context.getHeatStackGroupMembers().get(heatFileName).add(translatedId.get()); + updateResourceDependency(translateTo); + } + + mdcDataDebugMessage.debugExitMessage("file, resource", heatFileName, resourceId); + return translatedId; + } + + /** + * Gets resource translated id. + * + * @param heatFileName the heat file name + * @param heatOrchestrationTemplate the heat orchestration template + * @param resourceId the resource id + * @param context the context + * @return the resource translated id + */ + public static Optional getResourceTranslatedId(String heatFileName, + HeatOrchestrationTemplate + heatOrchestrationTemplate, + String resourceId, + TranslationContext context) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + if (!context.getTranslatedIds().containsKey(heatFileName)) { + context.getTranslatedIds().put(heatFileName, new HashMap<>()); + } + + Map translatedIdsPerFile = context.getTranslatedIds().get(heatFileName); + String translatedId = translatedIdsPerFile.get(resourceId); + if (translatedId != null) { + return Optional.of(translatedId); + } + + Resource resource = heatOrchestrationTemplate.getResources().get(resourceId); + if (resource == null) { + MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, + LoggerTragetServiceName.GET_RESOURCE, ErrorLevel.ERROR.name(), + LoggerErrorCode.DATA_ERROR.getErrorCode(), LoggerErrorDescription.TRANSLATE_HEAT); + throw new CoreException( + new ResourceNotFoundInHeatFileErrorBuilder(resourceId, heatFileName).build()); + } + TranslateTo translateTo = + generateTranslationTo(heatFileName, null, heatOrchestrationTemplate, resource, resourceId, + null, context); + translatedId = + ResourceTranslationFactory.getInstance(resource).generateTranslatedId(translateTo); + if (translatedId != null) { + context.getTranslatedIds().get(heatFileName).put(resourceId, translatedId); + } + + mdcDataDebugMessage.debugExitMessage(null, null); + return Optional.ofNullable(translatedId); + } + + + /** + * Gets resource translated element template. + * + * @param heatFileName the heat file name + * @param heatOrchestrationTemplate the heat orchestration template + * @param resourceId the resource id + * @param context the context + * @return the resource translated element template + */ + public static Optional getResourceTranslatedElementTemplate( + String heatFileName, + HeatOrchestrationTemplate heatOrchestrationTemplate, + String resourceId, TranslationContext context) { + + mdcDataDebugMessage.debugEntryMessage(null, null); + + Resource resource = heatOrchestrationTemplate.getResources().get(resourceId); + if (resource == null) { + MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, + LoggerTragetServiceName.GET_RESOURCE, ErrorLevel.ERROR.name(), + LoggerErrorCode.DATA_ERROR.getErrorCode(), LoggerErrorDescription.TRANSLATE_HEAT); + throw new CoreException( + new ResourceNotFoundInHeatFileErrorBuilder(resourceId, heatFileName).build()); + } + TranslateTo translateTo = + generateTranslationTo(heatFileName, null, heatOrchestrationTemplate, resource, resourceId, + null, context); + + Optional translatedElementTemplate = + ResourceTranslationFactory.getInstance(resource) + .getTranslatedToscaTopologyElement(translateTo); + + mdcDataDebugMessage.debugExitMessage(null, null); + return translatedElementTemplate; + } + + protected String generateTranslatedId(TranslateTo translateTo) { + if (isEssentialRequirementsValid(translateTo)) { + return translateTo.getResourceId(); + } else { + return null; + } + + } + + protected Optional getTranslatedToscaTopologyElement( + TranslateTo translateTo) { + if (isEssentialRequirementsValid(translateTo)) { + return Optional.of(ToscaTopologyTemplateElements.NODE_TEMPLATE); + } else { + return Optional.empty(); + } + } + + protected boolean isEssentialRequirementsValid(TranslateTo translateTo) { + return true; + } + + private static TranslateTo generateTranslationTo(String heatFileName, + ServiceTemplate serviceTemplate, + HeatOrchestrationTemplate + heatOrchestrationTemplate, + Resource resource, String resourceId, + String translatedId, + TranslationContext context) { + TranslateTo to = new TranslateTo(); + to.setHeatFileName(heatFileName); + to.setServiceTemplate(serviceTemplate); + to.setHeatOrchestrationTemplate(heatOrchestrationTemplate); + to.setResource(resource); + to.setResourceId(resourceId); + to.setTranslatedId(translatedId); + to.setContext(context); + return to; + } + + private void updateResourceDependency(TranslateTo translateTo) { + + String heatFileName = translateTo.getHeatFileName(); + mdcDataDebugMessage.debugEntryMessage("file", heatFileName); + + Resource resource = translateTo.getResource(); + HeatOrchestrationTemplate heatOrchestrationTemplate = translateTo + .getHeatOrchestrationTemplate(); + String translatedId = translateTo.getTranslatedId(); + ServiceTemplate serviceTemplate = translateTo.getServiceTemplate(); + TranslationContext context = translateTo.getContext(); + if (resource.getDepends_on() == null) { + return; + } + + if (resource.getDepends_on() instanceof List) { + List dependsOnList = (List) resource.getDepends_on(); + for (String dependsOnResourceId : dependsOnList) { + addDependOnRequirement(dependsOnResourceId, translateTo); + } + } else { + String dependsOnResourceId = (String) resource.getDepends_on(); + addDependOnRequirement(dependsOnResourceId, translateTo); + } + + mdcDataDebugMessage.debugExitMessage("file", heatFileName); + } + + private void addDependOnRequirement(String dependsOnResourceId, TranslateTo translateTo) { + + mdcDataDebugMessage.debugEntryMessage(null, null); + String nodeTemplateId = translateTo.getTranslatedId(); + ServiceTemplate serviceTemplate = translateTo.getServiceTemplate(); + String heatFileName = translateTo.getHeatFileName(); + HeatOrchestrationTemplate heatOrchestrationTemplate = translateTo + .getHeatOrchestrationTemplate(); + TranslationContext context = translateTo.getContext(); + RequirementAssignment requirementAssignment = new RequirementAssignment(); + Optional resourceTranslatedId = + getResourceTranslatedId(heatFileName, heatOrchestrationTemplate, dependsOnResourceId, + context); + + Optional resourceTranslatedElementTemplate = + getResourceTranslatedElementTemplate(heatFileName, heatOrchestrationTemplate, + dependsOnResourceId, context); + + if (resourceTranslatedId.isPresent() + && (resourceTranslatedElementTemplate.isPresent() && resourceTranslatedElementTemplate + .get() == ToscaTopologyTemplateElements.NODE_TEMPLATE)) { + Resource sourceResource = translateTo.getResource(); + Resource targetResource = HeatToToscaUtil + .getResource(heatOrchestrationTemplate, dependsOnResourceId, + translateTo.getHeatFileName()); + if (HeatToToscaUtil + .isValidDependsOnCandidate(heatOrchestrationTemplate, sourceResource, targetResource, + ConsolidationEntityType.OTHER, translateTo.getContext())) { + requirementAssignment.setNode(resourceTranslatedId.get()); + requirementAssignment.setCapability(ToscaCapabilityType.NATIVE_NODE); + requirementAssignment.setRelationship(ToscaRelationshipType.NATIVE_DEPENDS_ON); + DataModelUtil.addRequirementAssignment( + serviceTemplate.getTopology_template().getNode_templates().get(nodeTemplateId), + ToscaConstants.DEPENDS_ON_REQUIREMENT_ID, requirementAssignment); + Resource dependsOnResource = targetResource; + ConsolidationDataUtil + .updateNodesConnectedData(translateTo, dependsOnResourceId, dependsOnResource, + sourceResource, nodeTemplateId, ToscaConstants.DEPENDS_ON_REQUIREMENT_ID, + requirementAssignment); + } + } + mdcDataDebugMessage.debugExitMessage(null, null); + } + + Optional>> getResourceByTranslatedResourceId( + String heatFileName, + HeatOrchestrationTemplate heatOrchestrationTemplate, + String translatedResourceId, + TranslateTo translateTo, + String heatResourceType) { + mdcDataDebugMessage.debugEntryMessage(null, null); + List> list = heatOrchestrationTemplate.getResources().entrySet() + .stream() + .filter(entry -> getPredicatesForTranslatedIdToResourceId(heatFileName, + heatOrchestrationTemplate, translatedResourceId, translateTo.getContext(), + heatResourceType) + .stream() + .allMatch(p -> p.test(entry))) + .collect(Collectors.toList()); + if (CollectionUtils.isEmpty(list)) { + mdcDataDebugMessage.debugExitMessage(null, null); + return Optional.empty(); + } else { + mdcDataDebugMessage.debugExitMessage(null, null); + return Optional.of(list); + } + } + + private List>> getPredicatesForTranslatedIdToResourceId( + String heatFileName, HeatOrchestrationTemplate heatOrchestrationTemplate, + String translatedResourceId, TranslationContext context, String heatResourceType) { + List>> list = new ArrayList<>(); + list.add(entry -> + entry.getValue().getType().equals(heatResourceType)); + list.add(entry -> { + Optional resourceTranslatedId = + getResourceTranslatedId(heatFileName, heatOrchestrationTemplate, entry.getKey(), context); + return resourceTranslatedId.isPresent() + && resourceTranslatedId.get().equals(translatedResourceId); + }); + return list; + } + + boolean isResourceTypeSupported(Resource resource, List supporteTypes) { + return Objects.nonNull(resource) && supporteTypes.contains(resource.getType()); + } + +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationCinderVolumeAttachmentImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationCinderVolumeAttachmentImpl.java new file mode 100644 index 0000000000..4cf817bcae --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationCinderVolumeAttachmentImpl.java @@ -0,0 +1,268 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; + +import static org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil.getResource; + +import org.apache.commons.lang3.StringUtils; +import org.openecomp.sdc.common.errors.CoreException; +import org.openecomp.sdc.datatypes.error.ErrorLevel; +import org.openecomp.sdc.heat.datatypes.manifest.FileData; +import org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes; +import org.openecomp.sdc.heat.datatypes.model.Resource; +import org.openecomp.sdc.heat.services.HeatConstants; +import org.openecomp.sdc.logging.api.Logger; +import org.openecomp.sdc.logging.api.LoggerFactory; +import org.openecomp.sdc.logging.context.impl.MdcDataErrorMessage; +import org.openecomp.sdc.logging.types.LoggerConstants; +import org.openecomp.sdc.logging.types.LoggerErrorCode; +import org.openecomp.sdc.logging.types.LoggerErrorDescription; +import org.openecomp.sdc.logging.types.LoggerTragetServiceName; +import org.openecomp.sdc.tosca.datatypes.ToscaRelationshipType; +import org.openecomp.sdc.tosca.datatypes.ToscaTopologyTemplateElements; +import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; +import org.openecomp.sdc.tosca.datatypes.model.RelationshipTemplate; +import org.openecomp.sdc.tosca.datatypes.model.RequirementAssignment; +import org.openecomp.sdc.tosca.services.DataModelUtil; +import org.openecomp.sdc.tosca.services.ToscaConstants; +import org.openecomp.sdc.translator.datatypes.heattotosca.AttachedResourceId; +import org.openecomp.sdc.translator.datatypes.heattotosca.to.ResourceFileDataAndIDs; +import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; +import org.openecomp.sdc.translator.services.heattotosca.ConsolidationDataUtil; +import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; +import org.openecomp.sdc.translator.services.heattotosca.ResourceTranslationFactory; +import org.openecomp.sdc.translator.services.heattotosca.errors.MissingMandatoryPropertyErrorBuilder; +import org.openecomp.sdc.translator.services.heattotosca.helper.VolumeTranslationHelper; +import org.openecomp.sdc.translator.services.heattotosca.mapping.TranslatorHeatToToscaPropertyConverter; + +import java.util.List; +import java.util.Optional; + +public class ResourceTranslationCinderVolumeAttachmentImpl extends ResourceTranslationBase { + protected static Logger logger = + (Logger) LoggerFactory.getLogger(ResourceTranslationCinderVolumeAttachmentImpl.class); + private String volumeIdPropertyName = "volume_id"; + private String toscaCapabilityAttachment = "tosca.capabilities.Attachment"; + + @Override + protected void translate(TranslateTo translateTo) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + RelationshipTemplate relationTemplate = new RelationshipTemplate(); + relationTemplate.setType(ToscaRelationshipType.CINDER_VOLUME_ATTACHES_TO); + String relationshipTemplateId = translateTo.getTranslatedId(); + String heatFileName = translateTo.getHeatFileName(); + relationTemplate.setProperties(TranslatorHeatToToscaPropertyConverter + .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(),translateTo + .getResourceId(),translateTo.getResource().getProperties(), + relationTemplate.getProperties(), heatFileName, + translateTo.getHeatOrchestrationTemplate(), translateTo.getResource().getType(), + relationTemplate, translateTo.getContext())); + + AttachedResourceId attachedVolumeId = getAttachedResourceId(translateTo, volumeIdPropertyName); + String instanceUuid = HeatConstants.INSTANCE_UUID_PROPERTY_NAME; + AttachedResourceId attachedNovaServerId = getAttachedResourceId(translateTo, instanceUuid); + + if (attachedNovaServerId.isGetResource()) { + handleNovaGetResource(translateTo, relationTemplate, relationshipTemplateId, heatFileName, + attachedVolumeId, (String) attachedNovaServerId.getEntityId()); + } else { + logger.warn("Heat resource: '" + translateTo.getResourceId() + "' with type: '" + + translateTo.getResource().getType() + + "' include 'instance_uuid' property without 'get_resource' function, therefore this " + + "resource will be ignored in TOSCA translation."); + } + + mdcDataDebugMessage.debugExitMessage(null, null); + } + + @Override + protected Optional getTranslatedToscaTopologyElement( + TranslateTo translateTo) { + if (isEssentialRequirementsValid(translateTo)) { + return Optional.of(ToscaTopologyTemplateElements.RELATIONSHIP_TEMPLATE); + } else { + return Optional.empty(); + } + } + + private AttachedResourceId getAttachedResourceId(TranslateTo translateTo, String propertyName) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + Optional attachedResourceId = + HeatToToscaUtil.extractAttachedResourceId(translateTo, propertyName); + if (!attachedResourceId.isPresent()) { + MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, + LoggerTragetServiceName.GET_RESOURCE, ErrorLevel.ERROR.name(), + LoggerErrorCode.DATA_ERROR.getErrorCode(), + LoggerErrorDescription.MISSING_MANDATORY_PROPERTY); + throw new CoreException(new MissingMandatoryPropertyErrorBuilder(propertyName).build()); + } + + mdcDataDebugMessage.debugExitMessage(null, null); + return attachedResourceId.get(); + } + + private void handleNovaGetResource(TranslateTo translateTo, RelationshipTemplate relationTemplate, + String relationshipTemplateId, String heatFileName, + AttachedResourceId volResourceId, String novaResourceId) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + RequirementAssignment requirement = new RequirementAssignment(); + requirement.setCapability(toscaCapabilityAttachment); + if (volResourceId.isGetResource()) { + Resource volServerResource = getResource(translateTo.getHeatOrchestrationTemplate(), + (String) volResourceId.getTranslatedId(), heatFileName); + if (!StringUtils.equals(HeatResourcesTypes.CINDER_VOLUME_RESOURCE_TYPE.getHeatResource(), + volServerResource.getType())) { + logger.warn("Volume attachment with id '" + translateTo.getResourceId() + + "' is pointing to unsupported resource type(" + volServerResource.getType() + + ") through the property 'volume_id'." + + " The connection to the volume is ignored. " + + "Supported types are: " + + HeatResourcesTypes.CINDER_VOLUME_RESOURCE_TYPE.getHeatResource()); + + mdcDataDebugMessage.debugExitMessage(null, null); + return; + } + requirement.setNode((String) volResourceId.getTranslatedId()); + requirement.setRelationship(relationshipTemplateId); + DataModelUtil + .addRelationshipTemplate(translateTo.getServiceTemplate(), relationshipTemplateId, + relationTemplate); + } else if (volResourceId.isGetParam() && volResourceId.getEntityId() instanceof String) { + String volumeResourceIdParamName = (String) volResourceId.getEntityId(); + if (translateTo.getContext().getHeatSharedResourcesByParam() + .containsKey(volumeResourceIdParamName) && !isHeatFileNested(translateTo, heatFileName)) { + Resource volServerResource = + translateTo.getContext().getHeatSharedResourcesByParam().get(volumeResourceIdParamName) + .getHeatResource(); + if (!StringUtils.equals(HeatResourcesTypes.CINDER_VOLUME_RESOURCE_TYPE.getHeatResource(), + volServerResource.getType())) { + logger.warn("Volume attachment with id '" + translateTo.getResourceId() + + "' is pointing to unsupported resource type(" + volServerResource.getType() + + ") through the property 'volume_id'." + + " The connection to the volume is ignored. " + + "Supported types are: " + + HeatResourcesTypes.CINDER_VOLUME_RESOURCE_TYPE.getHeatResource()); + + mdcDataDebugMessage.debugExitMessage(null, null); + return; + } + requirement.setNode( + translateTo.getContext().getHeatSharedResourcesByParam().get(volumeResourceIdParamName) + .getTranslatedId()); + requirement.setRelationship(relationshipTemplateId); + DataModelUtil + .addRelationshipTemplate(translateTo.getServiceTemplate(), relationshipTemplateId, + relationTemplate); + } else { + handleUnsharedVolume(translateTo, relationTemplate, relationshipTemplateId, heatFileName, + requirement, volumeResourceIdParamName); + } + } + Resource novaServerResource = + getResource(translateTo.getHeatOrchestrationTemplate(), novaResourceId, heatFileName); + if (!StringUtils.equals(HeatResourcesTypes.NOVA_SERVER_RESOURCE_TYPE.getHeatResource(), + novaServerResource.getType())) { + logger.warn("Volume attachment with id '" + translateTo.getResourceId() + + "' is pointing to unsupported resource type(" + novaServerResource.getType() + + ") through the property 'instance_uuid'." + + " The connection to the nova server is ignored. " + + "Supported types are: " + + HeatResourcesTypes.NOVA_SERVER_RESOURCE_TYPE.getHeatResource()); + + mdcDataDebugMessage.debugExitMessage(null, null); + return; + } + Optional translatedNovaServerId = + ResourceTranslationFactory.getInstance(novaServerResource) + .translateResource(heatFileName, translateTo.getServiceTemplate(), + translateTo.getHeatOrchestrationTemplate(), novaServerResource, novaResourceId, + translateTo.getContext()); + + if (translatedNovaServerId.isPresent() && StringUtils.isNotEmpty(requirement.getNode())) { + NodeTemplate novaServerNodeTemplate = DataModelUtil + .getNodeTemplate(translateTo.getServiceTemplate(), translatedNovaServerId.get()); + DataModelUtil.addRequirementAssignment(novaServerNodeTemplate, ToscaConstants + .LOCAL_STORAGE_REQUIREMENT_ID, requirement); + //Add volume information to consolidation data + ConsolidationDataUtil.updateComputeConsolidationDataVolumes(translateTo, + novaServerNodeTemplate.getType(), translatedNovaServerId.get(), ToscaConstants + .LOCAL_STORAGE_REQUIREMENT_ID, requirement); + } + + mdcDataDebugMessage.debugExitMessage(null, null); + } + + private void handleUnsharedVolume(TranslateTo translateTo, RelationshipTemplate relationTemplate, + String relationshipTemplateId, String heatFileName, + RequirementAssignment requirement, String volumeResourceId) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + List allFilesData = translateTo.getContext().getManifest().getContent().getData(); + Optional fileData = HeatToToscaUtil.getFileData(heatFileName, allFilesData); + if (fileData.isPresent()) { + Optional fileDataContainingResource = + new VolumeTranslationHelper(logger) + .getFileDataContainingVolume(fileData.get().getData(), volumeResourceId, translateTo, + FileData.Type.HEAT_VOL); + fileDataContainingResource.ifPresent( + resourceFileDataAndIDs -> addRelationshipToServiceTemplate(translateTo, relationTemplate, + relationshipTemplateId, requirement, resourceFileDataAndIDs)); + } + + mdcDataDebugMessage.debugExitMessage(null, null); + } + + private boolean isHeatFileNested(TranslateTo translateTo, String heatFileName) { + return translateTo.getContext().getNestedHeatsFiles().contains(heatFileName); + } + + private void addRelationshipToServiceTemplate(TranslateTo translateTo, + RelationshipTemplate relationTemplate, + String relationshipTemplateId, + RequirementAssignment requirement, + ResourceFileDataAndIDs resourceFileDataAndIDs) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + String translatedId = resourceFileDataAndIDs.getTranslatedResourceId(); + String toscaVolIdPropName = + HeatToToscaUtil.getToscaPropertyName(translateTo, HeatConstants.VOL_ID_PROPERTY_NAME); + relationTemplate.getProperties().put(toscaVolIdPropName, translatedId); + requirement.setNode(translatedId); + requirement.setRelationship(relationshipTemplateId); + DataModelUtil.addRelationshipTemplate(translateTo.getServiceTemplate(), relationshipTemplateId, + relationTemplate); + + mdcDataDebugMessage.debugExitMessage(null, null); + } +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationCinderVolumeImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationCinderVolumeImpl.java new file mode 100644 index 0000000000..04e71cc2c7 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationCinderVolumeImpl.java @@ -0,0 +1,92 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; + +import org.openecomp.sdc.common.utils.CommonUtil; +import org.openecomp.sdc.heat.datatypes.HeatBoolean; +import org.openecomp.sdc.heat.services.HeatConstants; +import org.openecomp.sdc.tosca.datatypes.ToscaNodeType; +import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; +import org.openecomp.sdc.tosca.services.DataModelUtil; +import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; +import org.openecomp.sdc.translator.services.heattotosca.Constants; +import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; +import org.openecomp.sdc.translator.services.heattotosca.mapping.TranslatorHeatToToscaPropertyConverter; + +import java.util.Map; + + +public class ResourceTranslationCinderVolumeImpl extends ResourceTranslationBase { + + @Override + public void translate(TranslateTo translateTo) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + NodeTemplate nodeTemplate = new NodeTemplate(); + nodeTemplate.setType(ToscaNodeType.CINDER_VOLUME); + nodeTemplate.setProperties(TranslatorHeatToToscaPropertyConverter + .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(),translateTo. + getResourceId(),translateTo.getResource().getProperties(), + nodeTemplate.getProperties(), translateTo.getHeatFileName(), + translateTo.getHeatOrchestrationTemplate(), translateTo.getResource().getType(), + nodeTemplate, translateTo.getContext())); + handleSizeProperty(nodeTemplate.getProperties()); + String toscaReadOnlyPropName = + HeatToToscaUtil.getToscaPropertyName(translateTo, HeatConstants.READ_ONLY_PROPERTY_NAME); + Object readOnlyPropVal = nodeTemplate.getProperties().get(toscaReadOnlyPropName); + if (readOnlyPropVal != null && !(readOnlyPropVal instanceof Map)) { + nodeTemplate.getProperties().put(toscaReadOnlyPropName, HeatBoolean.eval(readOnlyPropVal)); + } + DataModelUtil.addNodeTemplate(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), + nodeTemplate); + + mdcDataDebugMessage.debugExitMessage(null, null); + } + + + private void handleSizeProperty(Map nodeTemplateProperties) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + Object size = nodeTemplateProperties.get("size"); + if (size == null) { + return; + } + + if (size instanceof Map) { + Map propMap = (Map) size; + for (Map.Entry entry : propMap.entrySet()) { + String val = "(" + entry.getKey() + " : " + entry.getValue() + ") * 1024"; + nodeTemplateProperties.put("size", val); + + mdcDataDebugMessage.debugExitMessage(null, null); + return; + } + } else { + nodeTemplateProperties.put("size", size + "*1024"); + } + + mdcDataDebugMessage.debugExitMessage(null, null); + } +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailAttachPolicyImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailAttachPolicyImpl.java new file mode 100644 index 0000000000..d729c04cca --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailAttachPolicyImpl.java @@ -0,0 +1,194 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; + +import org.openecomp.sdc.logging.api.Logger; +import org.openecomp.sdc.logging.api.LoggerFactory; +import org.openecomp.sdc.common.errors.CoreException; +import org.openecomp.sdc.datatypes.error.ErrorLevel; +import org.openecomp.sdc.heat.datatypes.model.Resource; +import org.openecomp.sdc.logging.context.impl.MdcDataErrorMessage; +import org.openecomp.sdc.logging.types.LoggerConstants; +import org.openecomp.sdc.logging.types.LoggerErrorCode; +import org.openecomp.sdc.logging.types.LoggerErrorDescription; +import org.openecomp.sdc.logging.types.LoggerTragetServiceName; +import org.openecomp.sdc.tosca.datatypes.ToscaCapabilityType; +import org.openecomp.sdc.tosca.datatypes.ToscaRelationshipType; +import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; +import org.openecomp.sdc.tosca.datatypes.model.RequirementAssignment; +import org.openecomp.sdc.tosca.datatypes.ToscaTopologyTemplateElements; +import org.openecomp.sdc.tosca.services.DataModelUtil; +import org.openecomp.sdc.tosca.services.ToscaConstants; +import org.openecomp.sdc.translator.datatypes.heattotosca.AttachedResourceId; +import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; +import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; +import org.openecomp.sdc.translator.services.heattotosca.ResourceTranslationFactory; +import org.openecomp.sdc.translator.services.heattotosca.errors.MissingMandatoryPropertyErrorBuilder; + +import java.util.Optional; + +public class ResourceTranslationContrailAttachPolicyImpl extends ResourceTranslationBase { + protected static Logger logger = + (Logger) LoggerFactory.getLogger(ResourceTranslationContrailAttachPolicyImpl.class); + + @Override + protected void translate(TranslateTo translateTo) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + String heatFileName = translateTo.getHeatFileName(); + String translatedNetworkResourceId = getTranslatedNetworkResourceId(translateTo); + if (translatedNetworkResourceId == null) { + mdcDataDebugMessage.debugExitMessage(null, null); + return; + } + + NodeTemplate policyNodeTemplate = getTranslatedPolicyNodeTemplate(translateTo, heatFileName); + if (policyNodeTemplate != null) { + DataModelUtil + .addRequirementAssignment(policyNodeTemplate, ToscaConstants.NETWORK_REQUIREMENT_ID, + createRequirementAssignment(translatedNetworkResourceId)); + } + + mdcDataDebugMessage.debugExitMessage(null, null); + } + + @Override + protected String generateTranslatedId(TranslateTo translateTo) { + return extractAttachedResourceIdHandleMissing(translateTo, "network").getEntityId() + .toString(); + } + + @Override + protected Optional getTranslatedToscaTopologyElement( + TranslateTo translateTo) { + return Optional.empty(); + } + + private NodeTemplate getTranslatedPolicyNodeTemplate(TranslateTo translateTo, + String heatFileName) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + AttachedResourceId attachedPolicyResourceId = + extractAttachedResourceIdHandleMissing(translateTo, "policy"); + NodeTemplate policyNodeTemplate = new NodeTemplate(); + Optional policyResourceId = + HeatToToscaUtil.getContrailAttachedHeatResourceId(attachedPolicyResourceId); + if (policyResourceId.isPresent()) { + policyNodeTemplate = getPolicyNodeTemplate(translateTo, heatFileName, policyResourceId.get()); + } else { + logger.warn("Heat resource: '" + translateTo.getResourceId() + "' with type: '" + + translateTo.getResource().getType() + + "' include 'policy' property without 'get_attr' of 'fq_name'/'get_resource' function," + + " therefore this resource will be ignored in TOSCA translation."); + } + + mdcDataDebugMessage.debugExitMessage(null, null); + return policyNodeTemplate; + } + + private NodeTemplate getPolicyNodeTemplate(TranslateTo translateTo, String heatFileName, + String policyResourceId) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + Resource policyResource = HeatToToscaUtil + .getResource(translateTo.getHeatOrchestrationTemplate(), policyResourceId, heatFileName); + Optional translatedPolicyResourceId = + ResourceTranslationFactory.getInstance(policyResource) + .translateResource(heatFileName, translateTo.getServiceTemplate(), + translateTo.getHeatOrchestrationTemplate(), policyResource, policyResourceId, + translateTo.getContext()); + if (!translatedPolicyResourceId.isPresent()) { + logger.warn("Heat resource: '" + translateTo.getResourceId() + "' with type: '" + + translateTo.getResource().getType() + + "' include unsupported policy resource, therefore this resource will be ignored in " + + "TOSCA translation. "); + + mdcDataDebugMessage.debugExitMessage(null, null); + return null; + } + + mdcDataDebugMessage.debugExitMessage(null, null); + return DataModelUtil + .getNodeTemplate(translateTo.getServiceTemplate(), translatedPolicyResourceId.get()); + } + + private String getTranslatedNetworkResourceId(TranslateTo translateTo) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + AttachedResourceId attachedNetworkResourceId = + extractAttachedResourceIdHandleMissing(translateTo, "network"); + + String translatedNetworkResourceId = null; + if (attachedNetworkResourceId.isGetResource()) { + translatedNetworkResourceId = (String) attachedNetworkResourceId.getTranslatedId(); + } else { + logger.warn("Heat resource: '" + translateTo.getResourceId() + "' with type: '" + + translateTo.getResource().getType() + + "' include 'network' property without 'get_resource' function, therefore this " + + "resource will be ignored in TOSCA translation."); + } + + mdcDataDebugMessage.debugExitMessage(null, null); + return translatedNetworkResourceId; + } + + private RequirementAssignment createRequirementAssignment(String translatedNetworkResourceId) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + RequirementAssignment requirement = new RequirementAssignment(); + requirement.setCapability(ToscaCapabilityType.NATIVE_ATTACHMENT); + requirement.setNode(translatedNetworkResourceId); + requirement.setRelationship(ToscaRelationshipType.ATTACHES_TO); + mdcDataDebugMessage.debugExitMessage(null, null); + return requirement; + } + + private AttachedResourceId extractAttachedResourceIdHandleMissing( + TranslateTo translateTo, String propertyName) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + Optional attachedResourceId = + HeatToToscaUtil.extractAttachedResourceId(translateTo, propertyName); + + if (!attachedResourceId.isPresent()) { + MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, + LoggerTragetServiceName.CREATE_REQUIREMENT_ASSIGNMENT, ErrorLevel.ERROR.name(), + LoggerErrorCode.DATA_ERROR.getErrorCode(), + LoggerErrorDescription.MISSING_MANDATORY_PROPERTY); + throw new CoreException(new MissingMandatoryPropertyErrorBuilder(propertyName).build()); + } + + mdcDataDebugMessage.debugExitMessage(null, null); + return attachedResourceId.get(); + } +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailNetworkPolicyImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailNetworkPolicyImpl.java new file mode 100644 index 0000000000..374858be0c --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailNetworkPolicyImpl.java @@ -0,0 +1,58 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; + +import org.openecomp.sdc.common.utils.CommonUtil; +import org.openecomp.sdc.logging.api.Logger; +import org.openecomp.sdc.logging.api.LoggerFactory; +import org.openecomp.sdc.tosca.datatypes.ToscaNodeType; +import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; +import org.openecomp.sdc.tosca.services.DataModelUtil; +import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; +import org.openecomp.sdc.translator.services.heattotosca.mapping.TranslatorHeatToToscaPropertyConverter; + +public class ResourceTranslationContrailNetworkPolicyImpl extends ResourceTranslationBase { + + protected static Logger logger = + (Logger) LoggerFactory.getLogger(ResourceTranslationContrailNetworkPolicyImpl.class); + + @Override + protected void translate(TranslateTo translateTo) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + NodeTemplate nodeTemplate = new NodeTemplate(); + nodeTemplate.setType(ToscaNodeType.CONTRAIL_NETWORK_RULE); + + nodeTemplate.setProperties(TranslatorHeatToToscaPropertyConverter + .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(),translateTo. + getResourceId(),translateTo.getResource().getProperties(), + nodeTemplate.getProperties(), translateTo.getHeatFileName(), + translateTo.getHeatOrchestrationTemplate(), translateTo.getResource().getType(), + nodeTemplate, translateTo.getContext())); + + DataModelUtil.addNodeTemplate(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), + nodeTemplate); + + mdcDataDebugMessage.debugExitMessage(null, null); + } +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailServiceInstanceImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailServiceInstanceImpl.java new file mode 100644 index 0000000000..eed7953cda --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailServiceInstanceImpl.java @@ -0,0 +1,863 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; + +import org.openecomp.sdc.common.errors.CoreException; +import org.openecomp.sdc.datatypes.error.ErrorLevel; +import org.openecomp.sdc.heat.datatypes.HeatBoolean; +import org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes; +import org.openecomp.sdc.heat.datatypes.model.Resource; +import org.openecomp.sdc.heat.services.HeatConstants; +import org.openecomp.sdc.logging.api.Logger; +import org.openecomp.sdc.logging.api.LoggerFactory; +import org.openecomp.sdc.logging.context.impl.MdcDataErrorMessage; +import org.openecomp.sdc.logging.types.LoggerConstants; +import org.openecomp.sdc.logging.types.LoggerErrorCode; +import org.openecomp.sdc.logging.types.LoggerErrorDescription; +import org.openecomp.sdc.logging.types.LoggerTragetServiceName; +import org.openecomp.sdc.tosca.datatypes.ToscaCapabilityType; +import org.openecomp.sdc.tosca.datatypes.ToscaFunctions; +import org.openecomp.sdc.tosca.datatypes.ToscaGroupType; +import org.openecomp.sdc.tosca.datatypes.ToscaNodeType; +import org.openecomp.sdc.tosca.datatypes.ToscaRelationshipType; +import org.openecomp.sdc.tosca.datatypes.model.AttributeDefinition; +import org.openecomp.sdc.tosca.datatypes.model.GroupDefinition; +import org.openecomp.sdc.tosca.datatypes.model.Import; +import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; +import org.openecomp.sdc.tosca.datatypes.model.NodeType; +import org.openecomp.sdc.tosca.datatypes.model.ParameterDefinition; +import org.openecomp.sdc.tosca.datatypes.model.PropertyDefinition; +import org.openecomp.sdc.tosca.datatypes.model.RequirementAssignment; +import org.openecomp.sdc.tosca.datatypes.model.RequirementDefinition; +import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; +import org.openecomp.sdc.tosca.datatypes.model.SubstitutionMapping; +import org.openecomp.sdc.tosca.datatypes.model.TopologyTemplate; +import org.openecomp.sdc.tosca.services.DataModelUtil; +import org.openecomp.sdc.tosca.services.ToscaAnalyzerService; +import org.openecomp.sdc.tosca.services.ToscaConstants; +import org.openecomp.sdc.tosca.services.ToscaUtil; +import org.openecomp.sdc.tosca.services.impl.ToscaAnalyzerServiceImpl; +import org.openecomp.sdc.tosca.services.impl.ToscaFileOutputServiceCsarImpl; +import org.openecomp.sdc.translator.datatypes.heattotosca.AttachedResourceId; +import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; +import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslatedHeatResource; +import org.openecomp.sdc.translator.services.heattotosca.Constants; +import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; +import org.openecomp.sdc.translator.services.heattotosca.ResourceTranslationFactory; +import org.openecomp.sdc.translator.services.heattotosca.errors.MissingMandatoryPropertyErrorBuilder; +import org.openecomp.sdc.translator.services.heattotosca.globaltypes.GlobalTypesGenerator; +import org.openecomp.sdc.translator.services.heattotosca.helper.ContrailTranslationHelper; +import org.openecomp.sdc.translator.services.heattotosca.mapping.TranslatorHeatToToscaPropertyConverter; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +public class ResourceTranslationContrailServiceInstanceImpl extends ResourceTranslationBase { + protected static Logger logger = + (Logger) LoggerFactory.getLogger(ResourceTranslationContrailServiceInstanceImpl.class); + + @Override + public void translate(TranslateTo translateTo) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + Resource serviceInstanceResource = translateTo.getResource(); + AttachedResourceId contrailServiceTemplateAttached = + getServiceTemplateAttachedId(translateTo, serviceInstanceResource); + if (contrailServiceTemplateAttached.isGetResource()) { + String contrailServiceTemplateResourceId = + (String) contrailServiceTemplateAttached.getEntityId(); + Resource contrailServiceTemplateResource = HeatToToscaUtil + .getResource(translateTo.getHeatOrchestrationTemplate(), + contrailServiceTemplateResourceId, translateTo.getHeatFileName()); + if (!contrailServiceTemplateResource.getType() + .equals(HeatResourcesTypes.CONTRAIL_SERVICE_TEMPLATE.getHeatResource())) { + logger.warn("resource id '" + translateTo.getResourceId() + "' with type '" + + translateTo.getResource().getType() + + "+ has reference to resource '" + contrailServiceTemplateResourceId + "' with type '" + + contrailServiceTemplateResource.getType() + + "' in property service_template. Invalid type, resource type should be type of '" + + HeatResourcesTypes.CONTRAIL_SERVICE_TEMPLATE.getHeatResource() + + "', therefore this resource will be ignored in TOSCA translation."); + + mdcDataDebugMessage.debugExitMessage(null, null); + return; + } + Optional contrailServiceTemplateTranslatedId = + ResourceTranslationFactory.getInstance(contrailServiceTemplateResource) + .translateResource(translateTo.getHeatFileName(), translateTo.getServiceTemplate(), + translateTo.getHeatOrchestrationTemplate(), contrailServiceTemplateResource, + contrailServiceTemplateResourceId, translateTo.getContext()); + if (!contrailServiceTemplateTranslatedId.isPresent()) { + logger.warn("Resource id '" + translateTo.getResourceId() + "' with type '" + + translateTo.getResource().getType() + + "' has reference to unsupported resource '" + contrailServiceTemplateResourceId + + "' with type '" + contrailServiceTemplateResource.getType() + + "' in property 'service_template'" + + ", therefore this resource will be ignored in TOSCA translation."); + + mdcDataDebugMessage.debugExitMessage(null, null); + return; + /*throw new CoreException(new ReferenceToUnsupportedResourceErrorBuilder + (translateTo.getResourceId(), translateTo.getResource().getType(), + contrailServiceTemplateResourceId, contrailServiceTemplateResource + .getType(), "service_template").build());*/ + } + + ServiceTemplate globalSubstitutionServiceTemplate = + translateTo.getContext().getTranslatedServiceTemplates().get( + Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME); + String contrailStId = ResourceTranslationContrailServiceTemplateImpl + .getContrailSubstitutedNodeTypeId(contrailServiceTemplateTranslatedId.get()); + NodeType substitutedNodeType = + DataModelUtil.getNodeType(globalSubstitutionServiceTemplate, contrailStId); + + int numberOfPorts = getServiceInstanceNumberOfPorts(serviceInstanceResource); + if (substitutedNodeType.getRequirements() != null + && substitutedNodeType.getRequirements().size() != numberOfPorts) { + logger.warn("More than one ServiceInstance pointing to the same ServiceTemplate '" + + contrailServiceTemplateResourceId + " ' with different number of interfaces." + + ", therefore this resource will be ignored in TOSCA translation."); + + mdcDataDebugMessage.debugExitMessage(null, null); + return; + } + + addNetworkLinkRequirements(substitutedNodeType, numberOfPorts); + NodeTemplate substitutedNodeTemplate = + createSubstitutedNodeTemplate(translateTo, contrailServiceTemplateResource, contrailStId, + numberOfPorts); + + String computeNodeTypeId = new ContrailTranslationHelper() + .getComputeNodeTypeId(contrailServiceTemplateResource, contrailServiceTemplateResourceId, + contrailServiceTemplateTranslatedId.get(), translateTo.getContext()); + boolean orderedInterfaces = getOrderedInterfaces(contrailServiceTemplateResource); + ServiceTemplate nestedServiceTemplate = + createNestedServiceTemplate(translateTo, computeNodeTypeId, contrailStId, + substitutedNodeTemplate, orderedInterfaces); + addAbstractSubstitutionProperty(translateTo, substitutedNodeTemplate.getProperties(), + nestedServiceTemplate, contrailServiceTemplateResource); + translateTo.getContext().getTranslatedServiceTemplates().put(new ContrailTranslationHelper() + .getSubstitutionContrailServiceTemplateMetadata(translateTo.getHeatFileName(), + translateTo.getTranslatedId()), nestedServiceTemplate); + + } else { + logger.warn("Heat resource: '" + translateTo.getResourceId() + "' with type: '" + + translateTo.getResource().getType() + + "' include 'service_template' property without 'get_resource' function, currently not" + + " supported, therefore this resource will be ignored in TOSCA translation."); + } + + mdcDataDebugMessage.debugExitMessage(null, null); + } + + private void addAbstractSubstitutionProperty(TranslateTo translateTo, + Map substitutionProperties, + ServiceTemplate nestedServiceTemplate, + Resource contrailServiceTemplateResource) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + Map innerProps = new HashMap<>(); + innerProps.put(ToscaConstants.SUBSTITUTE_SERVICE_TEMPLATE_PROPERTY_NAME, + ToscaUtil.getServiceTemplateFileName(nestedServiceTemplate)); + + Object countValue = handleScaleOutProperty(translateTo, innerProps); + handleServiceScalingProperty(translateTo, innerProps, contrailServiceTemplateResource); + + boolean mandatory = false; + if (countValue instanceof Integer && (Integer) countValue > 0) { + mandatory = true; + } + if (countValue == null) { + mandatory = true; + } + innerProps.put("mandatory", mandatory); + substitutionProperties.put(ToscaConstants.SERVICE_TEMPLATE_FILTER_PROPERTY_NAME, innerProps); + + mdcDataDebugMessage.debugExitMessage(null, null); + } + + private Object handleScaleOutProperty(TranslateTo translateTo, Map innerProps) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + Object scaleOutPropertyValue = + translateTo.getResource().getProperties().get(HeatConstants.SCALE_OUT_PROPERTY_NAME); + Object countValue = null; + if (scaleOutPropertyValue != null && scaleOutPropertyValue instanceof Map) { + countValue = TranslatorHeatToToscaPropertyConverter + .getToscaPropertyValue(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), + Constants.MAX_INSTANCES_PROPERTY_NAME, + ((Map) scaleOutPropertyValue).get(Constants.MAX_INSTANCES_PROPERTY_NAME), null, + translateTo.getHeatFileName(), translateTo.getHeatOrchestrationTemplate(), null, + translateTo.getContext()); + if (countValue != null) { + innerProps.put(ToscaConstants.COUNT_PROPERTY_NAME, countValue); + } else { + innerProps.put(ToscaConstants.COUNT_PROPERTY_NAME, 1); + } + } else { + innerProps.put(ToscaConstants.COUNT_PROPERTY_NAME, 1); + } + + mdcDataDebugMessage.debugExitMessage(null, null); + return countValue; + } + + private void handleServiceScalingProperty(TranslateTo translateTo, Map innerProps, + Resource contrailServiceTemplateResource) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + Object serviceScalingPropertyValue = contrailServiceTemplateResource.getProperties() + .get(HeatConstants.SERVICE_SCALING_PROPERTY_NAME); + Object serviceScalingValue = null; + if (serviceScalingPropertyValue != null) { + serviceScalingValue = TranslatorHeatToToscaPropertyConverter + .getToscaPropertyValue(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), + HeatConstants.SERVICE_SCALING_PROPERTY_NAME, serviceScalingPropertyValue, null, + translateTo.getHeatFileName(), translateTo.getHeatOrchestrationTemplate(), null, + translateTo.getContext()); + if (serviceScalingValue != null) { + innerProps.put(ToscaConstants.SCALING_ENABLED_PROPERTY_NAME, + (HeatBoolean.isValueBoolean(serviceScalingValue)) ? HeatBoolean + .eval(serviceScalingValue) : serviceScalingValue); + } + } + + mdcDataDebugMessage.debugExitMessage(null, null); + } + + private boolean getOrderedInterfaces(Resource contrailServiceTemplate) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + Object orderedInterfaces = contrailServiceTemplate.getProperties().get("ordered_interfaces"); + if (orderedInterfaces == null) { + mdcDataDebugMessage.debugExitMessage(null, null); + return false; + } + if (orderedInterfaces instanceof String) { + mdcDataDebugMessage.debugExitMessage(null, null); + return HeatBoolean.eval(orderedInterfaces); + } + //if get_param, set default value to true + mdcDataDebugMessage.debugExitMessage(null, null); + return true; + } + + private ServiceTemplate createNestedServiceTemplate(TranslateTo translateTo, + String computeNodeTypeId, + String substitutedNodeTypeId, + NodeTemplate substitutedNodeTemplate, + boolean orderedInterfaces) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + ServiceTemplate nestedSubstitutionServiceTemplate = new ServiceTemplate(); + setNestedServiceTemplateGeneralDetails(translateTo, nestedSubstitutionServiceTemplate); + String heatStackGroupKey = addHeatStackGroup(translateTo, nestedSubstitutionServiceTemplate); + addSubstitutionMappingEntry(nestedSubstitutionServiceTemplate, substitutedNodeTypeId); + + handleInputParameters(nestedSubstitutionServiceTemplate, translateTo); + String computeNodeTemplateId = + handleComputeNodeTemplate(translateTo, computeNodeTypeId, nestedSubstitutionServiceTemplate, + heatStackGroupKey); + handleOutputParameters(nestedSubstitutionServiceTemplate, computeNodeTemplateId, translateTo); + handleServiceInstanceInterfaces(translateTo, nestedSubstitutionServiceTemplate, + substitutedNodeTemplate, heatStackGroupKey, orderedInterfaces, computeNodeTemplateId); + + mdcDataDebugMessage.debugExitMessage(null, null); + return nestedSubstitutionServiceTemplate; + } + + private void handleOutputParameters(ServiceTemplate nestedSubstitutionServiceTemplate, + String nodeTemplateId, TranslateTo translateTo) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + if (nodeTemplateId == null) { + return; + } + ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl(); + + Optional contrailAbstractNodeType = + toscaAnalyzerService.fetchNodeType(ToscaNodeType.CONTRAIL_ABSTRACT_SUBSTITUTE, translateTo + .getContext().getGlobalServiceTemplates().values()); + + if (!contrailAbstractNodeType.isPresent()) { + return; + } + Map contrailAbstractAttributes = + contrailAbstractNodeType.get().getAttributes(); + Map nestedSubstitutionServiceTemplateOutputs = new HashMap<>(); + + if (contrailAbstractAttributes == null) { + return; + } + + for (String attributeKey : contrailAbstractAttributes.keySet()) { + AttributeDefinition abstractAttributeDef = contrailAbstractAttributes.get(attributeKey); + if (abstractAttributeDef != null) { + Map outputValue = new HashMap<>(); + List outputGetAttributeList = new ArrayList<>(); + outputGetAttributeList.add(nodeTemplateId); + outputGetAttributeList.add(attributeKey); + outputValue.put(ToscaFunctions.GET_ATTRIBUTE.getDisplayName(), outputGetAttributeList); + nestedSubstitutionServiceTemplateOutputs.put(attributeKey, + DataModelUtil.convertAttributeDefToParameterDef(abstractAttributeDef, outputValue)); + } + } + if (!nestedSubstitutionServiceTemplateOutputs.isEmpty()) { + nestedSubstitutionServiceTemplate.getTopology_template() + .setOutputs(nestedSubstitutionServiceTemplateOutputs); + } + + mdcDataDebugMessage.debugExitMessage(null, null); + } + + private void handleServiceInstanceInterfaces(TranslateTo translateTo, + ServiceTemplate nestedSubstitutionServiceTemplate, + NodeTemplate substitutedNodeTemplate, + String heatStackGroupKey, boolean orderedInterfaces, + String computeNodeTemplateId) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + Resource serviceInstanceResource = translateTo.getResource(); + Object interfaceListProperty = + serviceInstanceResource.getProperties().get(HeatConstants.INTERFACE_LIST_PROPERTY_NAME); + if (interfaceListProperty == null) { + return; + } + if (interfaceListProperty instanceof List) { + for (int index = 0; index < ((List) interfaceListProperty).size(); index++) { + Object interfaceEntry = ((List) interfaceListProperty).get(index); + handleInterface(translateTo, interfaceEntry, index, nestedSubstitutionServiceTemplate, + heatStackGroupKey, substitutedNodeTemplate, orderedInterfaces, computeNodeTemplateId); + } + } else if (interfaceListProperty instanceof Map) { + handleInterface(translateTo, interfaceListProperty, null, nestedSubstitutionServiceTemplate, + heatStackGroupKey, substitutedNodeTemplate, orderedInterfaces, computeNodeTemplateId); + } + + mdcDataDebugMessage.debugExitMessage(null, null); + } + + private void handleInterface(TranslateTo translateTo, Object interfacePropertyValue, + Integer index, + ServiceTemplate nestedSubstitutionServiceTemplate, + String heatStackGroupKey, NodeTemplate substitutedNodeTemplate, + boolean orderedInterfaces, String computeNodeTemplateId) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + if (index == null) { + index = new Integer(0); + } + NodeTemplate portNodeTemplate = + createPortNodeTemplate(index, orderedInterfaces, computeNodeTemplateId); + String portNodeTemplateId = Constants.SERVICE_INSTANCE_PORT_PREFIX + index; + String portReqMappingKey = Constants.SERVICE_INSTANCE_LINK_PREFIX + portNodeTemplateId; + + DataModelUtil + .addNodeTemplate(nestedSubstitutionServiceTemplate, portNodeTemplateId, portNodeTemplate); + updateSubstitutionMappingRequirement(nestedSubstitutionServiceTemplate, portReqMappingKey, + portNodeTemplateId); + updateHeatStackGroup(nestedSubstitutionServiceTemplate, heatStackGroupKey, portNodeTemplateId); + connectPortToNetwork(translateTo, interfacePropertyValue, substitutedNodeTemplate, + portReqMappingKey); + + mdcDataDebugMessage.debugExitMessage(null, null); + } + + private void connectPortToNetwork(TranslateTo translateTo, Object interfacePropertyValue, + NodeTemplate substitutedNodeTemplate, + String portReqMappingKey) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + List validNetworksForConnections = Arrays + .asList(HeatResourcesTypes.NEUTRON_NET_RESOURCE_TYPE.getHeatResource(), + HeatResourcesTypes.CONTRAIL_VIRTUAL_NETWORK_RESOURCE_TYPE.getHeatResource()); + + if (interfacePropertyValue instanceof Map) { + Object virtualNetworkValue = + ((Map) interfacePropertyValue).get(HeatConstants.VIRTUAL_NETWORK_PROPERTY_NAME); + if (virtualNetworkValue != null) { + Optional networkAttachedResourceId = HeatToToscaUtil + .extractAttachedResourceId(translateTo.getHeatFileName(), + translateTo.getHeatOrchestrationTemplate(), translateTo.getContext(), + virtualNetworkValue); + if (networkAttachedResourceId.isPresent()) { + Optional networkResourceId = + HeatToToscaUtil.getContrailAttachedHeatResourceId(networkAttachedResourceId.get()); + if (networkResourceId.isPresent()) { + Resource networkResource = HeatToToscaUtil + .getResource(translateTo.getHeatOrchestrationTemplate(), networkResourceId.get(), + translateTo.getHeatFileName()); + if (validNetworksForConnections.contains(networkResource.getType())) { + Optional networkTranslatedId = + getResourceTranslatedId(translateTo.getHeatFileName(), + translateTo.getHeatOrchestrationTemplate(), networkResourceId.get(), + translateTo.getContext()); + networkTranslatedId + .ifPresent( + translatedId -> addLinkToNetworkRequirementAssignment(substitutedNodeTemplate, + translatedId, portReqMappingKey)); + + } else { + logger.warn("Heat resource " + translateTo.getResourceId() + " with type " + + translateTo.getResource().getType() + + " has connection to invalid/not supported network resource, therefore, this " + + "connection will be ignored in the translation."); + } + } else if (networkAttachedResourceId.get().isGetParam() + && networkAttachedResourceId.get().getEntityId() instanceof String) { + TranslatedHeatResource + translatedSharedResourceId = + translateTo.getContext().getHeatSharedResourcesByParam() + .get(networkAttachedResourceId.get().getEntityId()); + if (Objects.nonNull(translatedSharedResourceId) + && !HeatToToscaUtil.isHeatFileNested(translateTo, translateTo.getHeatFileName())) { + addLinkToNetworkRequirementAssignment(substitutedNodeTemplate, + translatedSharedResourceId.getTranslatedId(), portReqMappingKey); + } + } else { + logger.warn("Heat resource: '" + translateTo.getResourceId() + "' with type: '" + + translateTo.getResource().getType() + + "' include 'virtual_network' property with value '" + + virtualNetworkValue.toString() + + "', the connection to this network wasn't found/not supported therefore this " + + "connection will be ignored in TOSCA translation for this property."); + } + } + } else { + logger.warn("Heat resource: '" + translateTo.getResourceId() + "' with type: '" + + translateTo.getResource().getType() + + "' missing 'virtual_network' property in 'interface_list' entry, therefore, no " + + "network connection is define for this entry."); + //throw new CoreException(new + // MissingMandatoryPropertyErrorBuilder("virtual_network").build()); + } + } + + mdcDataDebugMessage.debugExitMessage(null, null); + } + + private NodeTemplate createPortNodeTemplate(Integer index, boolean orderedInterfaces, + String computeNodeTemplateId) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + NodeTemplate portNodeTemplate = new NodeTemplate(); + portNodeTemplate.setType(ToscaNodeType.CONTRAIL_PORT); + Map portProperties = new HashMap<>(); + portProperties.put("static_routes", DataModelUtil + .createGetInputPropertyValueFromListParameter("interface_list", index, "static_routes")); + portProperties.put("virtual_network", DataModelUtil + .createGetInputPropertyValueFromListParameter("interface_list", index, "virtual_network")); + portProperties.put("allowed_address_pairs", DataModelUtil + .createGetInputPropertyValueFromListParameter("interface_list", index, + "allowed_address_pairs")); + portProperties.put("ip_address", DataModelUtil + .createGetInputPropertyValueFromListParameter("interface_list", index, "ip_address")); + portProperties.put("static_route", + DataModelUtil.createGetInputPropertyValueFromListParameter("static_routes_list", index)); + portProperties.put("shared_ip", + DataModelUtil.createGetInputPropertyValueFromListParameter("shared_ip_list", index)); + portProperties.put("interface_type", DataModelUtil + .createGetInputPropertyValueFromListParameter("service_interface_type_list", index)); + if (orderedInterfaces) { + portProperties.put("order", index); + } + portNodeTemplate.setProperties(portProperties); + HeatToToscaUtil.addBindingReqFromPortToCompute(computeNodeTemplateId, portNodeTemplate); + + mdcDataDebugMessage.debugExitMessage(null, null); + return portNodeTemplate; + } + + + private void addLinkToNetworkRequirementAssignment(NodeTemplate nodeTemplate, + String connectedNodeTranslatedId, + String requirementId) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + if (nodeTemplate == null || connectedNodeTranslatedId == null) { + return; + } + + RequirementAssignment requirement = new RequirementAssignment(); + requirement.setCapability(ToscaCapabilityType.NATIVE_NETWORK_LINKABLE); + requirement.setRelationship(ToscaRelationshipType.NATIVE_NETWORK_LINK_TO); + requirement.setNode(connectedNodeTranslatedId); + DataModelUtil.addRequirementAssignment(nodeTemplate, requirementId, requirement); + + mdcDataDebugMessage.debugExitMessage(null, null); + } + + private void updateHeatStackGroup(ServiceTemplate serviceTemplate, String heatStackGroupKey, + String memberId) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + serviceTemplate.getTopology_template().getGroups().get(heatStackGroupKey).getMembers() + .add(memberId); + + mdcDataDebugMessage.debugExitMessage(null, null); + } + + private void updateSubstitutionMappingRequirement(ServiceTemplate serviceTemplate, + String portReqMappingKey, + String portNodeTemplateId) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + List portReqMappingValue = new ArrayList<>(); + portReqMappingValue.add(portNodeTemplateId); + portReqMappingValue.add(ToscaConstants.LINK_REQUIREMENT_ID); + DataModelUtil + .addSubstitutionMappingReq(serviceTemplate, portReqMappingKey, portReqMappingValue); + + mdcDataDebugMessage.debugExitMessage(null, null); + } + + private void addSubstitutionMappingEntry(ServiceTemplate nestedSubstitutionServiceTemplate, + String substitutedNodeTypeId) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + SubstitutionMapping substitutionMappings = new SubstitutionMapping(); + substitutionMappings.setNode_type(substitutedNodeTypeId); + DataModelUtil.addSubstitutionMapping(nestedSubstitutionServiceTemplate, substitutionMappings); + + mdcDataDebugMessage.debugExitMessage(null, null); + } + + private void handleInputParameters(ServiceTemplate nestedSubstitutionServiceTemplate, + TranslateTo translateTo) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl(); + + Optional contrailAbstractNodeType = + toscaAnalyzerService.fetchNodeType(ToscaNodeType.CONTRAIL_ABSTRACT_SUBSTITUTE, translateTo + .getContext().getGlobalServiceTemplates().values()); + Map nestedSubstitutionServiceTemplateInputs = new HashMap<>(); + if (contrailAbstractNodeType.isPresent()) { + Map contrailAbstractProperties = + contrailAbstractNodeType.get().getProperties(); + + for (String propertyKey : contrailAbstractProperties.keySet()) { + PropertyDefinition abstractPropertyDef = contrailAbstractProperties.get(propertyKey); + if (abstractPropertyDef != null) { + nestedSubstitutionServiceTemplateInputs + .put(propertyKey, + DataModelUtil.convertPropertyDefToParameterDef(abstractPropertyDef)); + + } + } + } + if (!nestedSubstitutionServiceTemplateInputs.isEmpty()) { + nestedSubstitutionServiceTemplate.getTopology_template() + .setInputs(nestedSubstitutionServiceTemplateInputs); + } + + mdcDataDebugMessage.debugExitMessage(null, null); + } + + private String handleComputeNodeTemplate(TranslateTo translateTo, String computeNodeTypeId, + ServiceTemplate nestedSubstitutionServiceTemplate, + String heatStackGroupKey) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl(); + Optional contrailComputeNodeType = toscaAnalyzerService + .fetchNodeType(ToscaNodeType.CONTRAIL_COMPUTE, + translateTo.getContext().getGlobalServiceTemplates().values()); + + Map computeNodeTemplateProperties = null; + if (contrailComputeNodeType.isPresent()) { + Map contrailComputeProperties = + contrailComputeNodeType.get().getProperties(); + computeNodeTemplateProperties = new HashMap<>(); + + if (contrailComputeProperties != null) { + for (String computePropertyKey : contrailComputeProperties.keySet()) { + Map getInputProperty = new HashMap<>(); + getInputProperty.put(ToscaFunctions.GET_INPUT.getDisplayName(), computePropertyKey); + computeNodeTemplateProperties.put(computePropertyKey, getInputProperty); + } + } + } + + NodeTemplate computeNodeTemplate = new NodeTemplate(); + computeNodeTemplate.setType(computeNodeTypeId); + if (!computeNodeTemplateProperties.isEmpty()) { + computeNodeTemplate.setProperties(computeNodeTemplateProperties); + } + String computeNodeTemplateId = translateTo.getTranslatedId(); + DataModelUtil.addNodeTemplate(nestedSubstitutionServiceTemplate, computeNodeTemplateId, + computeNodeTemplate); + nestedSubstitutionServiceTemplate.getTopology_template().getGroups().get(heatStackGroupKey) + .getMembers().add(computeNodeTemplateId); + + mdcDataDebugMessage.debugExitMessage(null, null); + return computeNodeTemplateId; + } + + private String addHeatStackGroup(TranslateTo translateTo, ServiceTemplate serviceTemplate) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + GroupDefinition serviceInstanceGroupDefinition = new GroupDefinition(); + serviceInstanceGroupDefinition.setType(ToscaGroupType.HEAT_STACK); + Map groupProperties = new HashMap<>(); + groupProperties.put("heat_file", + "../" + (new ToscaFileOutputServiceCsarImpl()).getArtifactsFolderName() + "/" + + translateTo.getHeatFileName()); + serviceInstanceGroupDefinition.setProperties(groupProperties); + serviceInstanceGroupDefinition.setMembers(new ArrayList<>()); + String heatStackGroupKey = translateTo.getTranslatedId() + "_group"; + DataModelUtil.addGroupDefinitionToTopologyTemplate(serviceTemplate, heatStackGroupKey, + serviceInstanceGroupDefinition); + + mdcDataDebugMessage.debugExitMessage(null, null); + return heatStackGroupKey; + } + + + private void setNestedServiceTemplateGeneralDetails(TranslateTo translateTo, + ServiceTemplate + nestedSubstitutionServiceTemplate) { + mdcDataDebugMessage.debugEntryMessage(null, null); + + Map nestedTemplateMetadata = new HashMap<>(); + String nestedTemplateName = new ContrailTranslationHelper() + .getSubstitutionContrailServiceTemplateMetadata(translateTo.getHeatFileName(), + translateTo.getResourceId()); + nestedTemplateMetadata.put(ToscaConstants.ST_METADATA_TEMPLATE_NAME, nestedTemplateName); + nestedSubstitutionServiceTemplate.setMetadata(nestedTemplateMetadata); + nestedSubstitutionServiceTemplate + .setTosca_definitions_version(ToscaConstants.TOSCA_DEFINITIONS_VERSION); + nestedSubstitutionServiceTemplate.setTopology_template(new TopologyTemplate()); + List> globalTypesImportList = + GlobalTypesGenerator.getGlobalTypesImportList(); + globalTypesImportList.addAll( + HeatToToscaUtil.createImportList(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME)); + nestedSubstitutionServiceTemplate.setImports(globalTypesImportList); + mdcDataDebugMessage.debugExitMessage(null, null); + } + + private NodeTemplate createSubstitutedNodeTemplate(TranslateTo translateTo, + Resource contrailServiceTemplateResource, + String contrailServiceTemplateTranslatedId, + int numberOfPorts) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + boolean isImportAddedToServiceTemplate = + DataModelUtil + .isImportAddedToServiceTemplate(translateTo.getServiceTemplate().getImports(), Constants + .GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME); + if (!isImportAddedToServiceTemplate) { + translateTo.getServiceTemplate().getImports() + .addAll(HeatToToscaUtil + .createImportList(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME)); + } + NodeTemplate substitutesNodeTemplate = new NodeTemplate(); + substitutesNodeTemplate.setType(contrailServiceTemplateTranslatedId); + List directiveList = new ArrayList<>(); + directiveList.add(ToscaConstants.NODE_TEMPLATE_DIRECTIVE_SUBSTITUTABLE); + substitutesNodeTemplate.setDirectives(directiveList); + substitutesNodeTemplate.setProperties(TranslatorHeatToToscaPropertyConverter + .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(), translateTo. + getResourceId(), translateTo.getResource().getProperties(), + substitutesNodeTemplate.getProperties(), translateTo.getHeatFileName(), + translateTo.getHeatOrchestrationTemplate(), + HeatResourcesTypes.CONTRAIL_SERVICE_INSTANCE.getHeatResource(), substitutesNodeTemplate, + translateTo.getContext())); + substitutesNodeTemplate.setProperties(TranslatorHeatToToscaPropertyConverter + .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(), translateTo. + getResourceId(), contrailServiceTemplateResource.getProperties(), + substitutesNodeTemplate.getProperties(), translateTo.getHeatFileName(), + translateTo.getHeatOrchestrationTemplate(), + HeatResourcesTypes.CONTRAIL_SERVICE_TEMPLATE.getHeatResource(), substitutesNodeTemplate, + translateTo.getContext())); + HeatToToscaUtil.mapBoolean(substitutesNodeTemplate, HeatToToscaUtil + .getToscaPropertyName(translateTo.getContext(), contrailServiceTemplateResource.getType(), + HeatConstants.AVAILABILITY_ZONE_ENABLE_PROPERTY_NAME)); + HeatToToscaUtil.mapBoolean(substitutesNodeTemplate, HeatToToscaUtil + .getToscaPropertyName(translateTo.getContext(), contrailServiceTemplateResource.getType(), + HeatConstants.ORDERED_INTERFACES_PROPERTY_NAME)); + + Object sharedIpListPropertyValue = + contrailServiceTemplateResource.getProperties() + .get(HeatConstants.SHARED_IP_LIST_PROPERTY_NAME); + String toscaSharedIpListPropertyName = HeatToToscaUtil + .getToscaPropertyName(translateTo.getContext(), contrailServiceTemplateResource.getType(), + HeatConstants.SHARED_IP_LIST_PROPERTY_NAME); + Optional>> sharedIpTranslatedSplitFun = + new ContrailTranslationHelper() + .translateFnSplitFunction(sharedIpListPropertyValue, numberOfPorts, true); + if (sharedIpTranslatedSplitFun.isPresent()) { + substitutesNodeTemplate.getProperties() + .put(toscaSharedIpListPropertyName, sharedIpTranslatedSplitFun.get()); + } else { + HeatToToscaUtil.mapBooleanList(substitutesNodeTemplate, toscaSharedIpListPropertyName); + } + + Object staticRouteListPropertyValue = + contrailServiceTemplateResource.getProperties() + .get(HeatConstants.STATIC_ROUTES_LIST_PROPERTY_NAME); + String toscaStaticRoutesListPropertyName = HeatToToscaUtil + .getToscaPropertyName(translateTo.getContext(), contrailServiceTemplateResource.getType(), + HeatConstants.STATIC_ROUTES_LIST_PROPERTY_NAME); + Optional>> staticRouteTranslatedSplitFun = + new ContrailTranslationHelper() + .translateFnSplitFunction(staticRouteListPropertyValue, numberOfPorts, true); + if (staticRouteTranslatedSplitFun.isPresent()) { + substitutesNodeTemplate.getProperties() + .put(toscaStaticRoutesListPropertyName, staticRouteTranslatedSplitFun.get()); + } else { + HeatToToscaUtil.mapBooleanList(substitutesNodeTemplate, toscaStaticRoutesListPropertyName); + } + + Object serviceInterfaceTypeListPropertyValue = + contrailServiceTemplateResource.getProperties() + .get(HeatConstants.SERVICE_INTERFCAE_TYPE_LIST_PROPERTY_NAME); + String toscaServiceInterfaceTypeListPropertyName = HeatToToscaUtil + .getToscaPropertyName(translateTo.getContext(), contrailServiceTemplateResource.getType(), + HeatConstants.SERVICE_INTERFCAE_TYPE_LIST_PROPERTY_NAME); + Optional>> serviceInterfaceTypeTranslatedSplitFun = + new ContrailTranslationHelper() + .translateFnSplitFunction(serviceInterfaceTypeListPropertyValue, numberOfPorts, false); + serviceInterfaceTypeTranslatedSplitFun + .ifPresent(translatedSplitFun -> substitutesNodeTemplate.getProperties() + .put(toscaServiceInterfaceTypeListPropertyName, translatedSplitFun)); + + String substitutedNodeTemplateId = translateTo.getTranslatedId(); + DataModelUtil.addNodeTemplate(translateTo.getServiceTemplate(), substitutedNodeTemplateId, + substitutesNodeTemplate); + + mdcDataDebugMessage.debugExitMessage(null, null); + return substitutesNodeTemplate; + } + + private void addNetworkLinkRequirements(NodeType nodeType, int numberOfPorts) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + if (nodeType.getRequirements() == null) { + List> requirementList = new ArrayList<>(); + for (int i = 0; i < numberOfPorts; i++) { + Map requirementDefinitionMap = new HashMap<>(); + requirementDefinitionMap.put(ToscaConstants.LINK_REQUIREMENT_ID + "_port_" + i, + DataModelUtil.createRequirement(ToscaCapabilityType.NATIVE_NETWORK_LINKABLE, + ToscaNodeType.NATIVE_ROOT, + ToscaRelationshipType.NATIVE_NETWORK_LINK_TO, null)); + requirementList.add(requirementDefinitionMap); + } + if (numberOfPorts > 0) { + nodeType.setRequirements(requirementList); + } + } + + mdcDataDebugMessage.debugExitMessage(null, null); + } + + private int getServiceInstanceNumberOfPorts(Resource serviceInstanceResource) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + int numberOfPorts; + Object interfaceTypeProperty = + serviceInstanceResource.getProperties().get(HeatConstants.INTERFACE_LIST_PROPERTY_NAME); + if (interfaceTypeProperty == null) { + numberOfPorts = 0; + } else if (interfaceTypeProperty instanceof List) { + numberOfPorts = ((List) interfaceTypeProperty).size(); + } else if (interfaceTypeProperty instanceof Map) { + numberOfPorts = 1; + } else { + numberOfPorts = 0; + } + + mdcDataDebugMessage.debugExitMessage(null, null); + return numberOfPorts; + } + + private AttachedResourceId getServiceTemplateAttachedId(TranslateTo translateTo, + Resource serviceInstanceResource) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + Object serviceTemplateProperty = + serviceInstanceResource.getProperties().get("service_template"); + Optional serviceTemplateId = HeatToToscaUtil + .extractAttachedResourceId(translateTo.getHeatFileName(), + translateTo.getHeatOrchestrationTemplate(), translateTo.getContext(), + serviceTemplateProperty); + if (serviceTemplateId.isPresent()) { + mdcDataDebugMessage.debugExitMessage(null, null); + return serviceTemplateId.get(); + } else { + MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, + LoggerTragetServiceName.GET_SERVICE_TEMPLATE, ErrorLevel.ERROR.name(), + LoggerErrorCode.DATA_ERROR.getErrorCode(), + LoggerErrorDescription.MISSING_MANDATORY_PROPERTY); + throw new CoreException(new MissingMandatoryPropertyErrorBuilder("service_template").build()); + } + } + + +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailServiceTemplateImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailServiceTemplateImpl.java new file mode 100644 index 0000000000..8b862e585f --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailServiceTemplateImpl.java @@ -0,0 +1,141 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; + +import org.openecomp.sdc.common.errors.CoreException; +import org.openecomp.sdc.datatypes.error.ErrorLevel; +import org.openecomp.sdc.logging.context.impl.MdcDataErrorMessage; +import org.openecomp.sdc.logging.types.LoggerConstants; +import org.openecomp.sdc.logging.types.LoggerErrorCode; +import org.openecomp.sdc.logging.types.LoggerErrorDescription; +import org.openecomp.sdc.logging.types.LoggerTragetServiceName; +import org.openecomp.sdc.tosca.datatypes.ToscaNodeType; +import org.openecomp.sdc.tosca.datatypes.ToscaTopologyTemplateElements; +import org.openecomp.sdc.tosca.datatypes.model.NodeType; +import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; +import org.openecomp.sdc.tosca.services.DataModelUtil; +import org.openecomp.sdc.tosca.services.ToscaConstants; +import org.openecomp.sdc.translator.datatypes.heattotosca.TranslationContext; +import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; +import org.openecomp.sdc.translator.services.heattotosca.Constants; +import org.openecomp.sdc.translator.services.heattotosca.errors.MissingMandatoryPropertyErrorBuilder; +import org.openecomp.sdc.translator.services.heattotosca.globaltypes.GlobalTypesGenerator; +import org.openecomp.sdc.translator.services.heattotosca.helper.ContrailTranslationHelper; + +import java.util.HashMap; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + +public class ResourceTranslationContrailServiceTemplateImpl extends ResourceTranslationBase { + + static String getContrailSubstitutedNodeTypeId(String serviceTemplateTranslatedId) { + return ToscaNodeType.ABSTRACT_NODE_TYPE_PREFIX + "heat." + serviceTemplateTranslatedId; + } + + @Override + public void translate(TranslateTo translateTo) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + ServiceTemplate globalSubstitutionServiceTemplate = + getGlobalSubstitutionTypesServiceTemplate(translateTo); + addSubstitutedNodeType(translateTo, globalSubstitutionServiceTemplate); + addComputeNodeType(translateTo, globalSubstitutionServiceTemplate, translateTo.getContext()); + mdcDataDebugMessage.debugExitMessage(null, null); + } + + @Override + protected boolean isEssentialRequirementsValid(TranslateTo translateTo) { + Map properties = translateTo.getResource().getProperties(); + if (Objects.isNull(properties) || Objects.isNull(properties.get("image_name"))) { + MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, + LoggerTragetServiceName.GENERATE_TRANSLATED_ID, ErrorLevel.ERROR.name(), + LoggerErrorCode.DATA_ERROR.getErrorCode(), + LoggerErrorDescription.MISSING_MANDATORY_PROPERTY); + throw new CoreException(new MissingMandatoryPropertyErrorBuilder("image_name").build()); + } + return true; + } + + private void addComputeNodeType(TranslateTo translateTo, + ServiceTemplate globalSubstitutionServiceTemplate, + TranslationContext context) { + mdcDataDebugMessage.debugEntryMessage(null, null); + NodeType computeNodeType = new NodeType(); + computeNodeType.setDerived_from(ToscaNodeType.CONTRAIL_COMPUTE); + String computeNodeTypeId = new ContrailTranslationHelper() + .getComputeNodeTypeId(translateTo.getResource(), translateTo.getResourceId(), + translateTo.getTranslatedId(), context); + DataModelUtil + .addNodeType(globalSubstitutionServiceTemplate, computeNodeTypeId, computeNodeType); + + mdcDataDebugMessage.debugExitMessage(null, null); + } + + private void addSubstitutedNodeType(TranslateTo translateTo, + ServiceTemplate globalSubstitutionServiceTemplate) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + NodeType substitutedNodeType = new NodeType(); + substitutedNodeType + .setDerived_from(ToscaNodeType.CONTRAIL_ABSTRACT_SUBSTITUTE); + DataModelUtil.addNodeType(globalSubstitutionServiceTemplate, + getContrailSubstitutedNodeTypeId(translateTo.getTranslatedId()), substitutedNodeType); + + mdcDataDebugMessage.debugExitMessage(null, null); + } + + @Override + protected Optional getTranslatedToscaTopologyElement( + TranslateTo translateTo) { + return Optional.empty(); + } + + private ServiceTemplate getGlobalSubstitutionTypesServiceTemplate(TranslateTo translateTo) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + ServiceTemplate globalSubstitutionServiceTemplate = + translateTo.getContext().getTranslatedServiceTemplates().get( + Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME); + if (globalSubstitutionServiceTemplate == null) { + globalSubstitutionServiceTemplate = new ServiceTemplate(); + Map templateMetadata = new HashMap<>(); + templateMetadata.put(ToscaConstants.ST_METADATA_TEMPLATE_NAME, Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME); + globalSubstitutionServiceTemplate.setMetadata(templateMetadata); + globalSubstitutionServiceTemplate.setImports(GlobalTypesGenerator.getGlobalTypesImportList()); + globalSubstitutionServiceTemplate + .setTosca_definitions_version(ToscaConstants.TOSCA_DEFINITIONS_VERSION); + translateTo.getContext().getTranslatedServiceTemplates() + .put(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME, + globalSubstitutionServiceTemplate); + } + + mdcDataDebugMessage.debugExitMessage(null, null); + return globalSubstitutionServiceTemplate; + } + +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailV2NetworkPolicyImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailV2NetworkPolicyImpl.java new file mode 100644 index 0000000000..71efc18816 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailV2NetworkPolicyImpl.java @@ -0,0 +1,56 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; + +import org.openecomp.sdc.common.utils.CommonUtil; +import org.openecomp.sdc.logging.api.Logger; +import org.openecomp.sdc.logging.api.LoggerFactory; +import org.openecomp.sdc.tosca.datatypes.ToscaNodeType; +import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; +import org.openecomp.sdc.tosca.services.DataModelUtil; +import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; +import org.openecomp.sdc.translator.services.heattotosca.mapping.TranslatorHeatToToscaPropertyConverter; + +public class ResourceTranslationContrailV2NetworkPolicyImpl extends ResourceTranslationBase { + + protected static Logger logger = + (Logger) LoggerFactory.getLogger(ResourceTranslationContrailV2NetworkPolicyImpl.class); + + @Override + protected void translate(TranslateTo translateTo) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + NodeTemplate nodeTemplate = new NodeTemplate(); + nodeTemplate.setType(ToscaNodeType.CONTRAILV2_NETWORK_RULE); + nodeTemplate.setProperties(TranslatorHeatToToscaPropertyConverter + .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(),translateTo. + getResourceId(),translateTo.getResource().getProperties(), + nodeTemplate.getProperties(), translateTo.getHeatFileName(), + translateTo.getHeatOrchestrationTemplate(), translateTo.getResource().getType(), + nodeTemplate, translateTo.getContext())); + DataModelUtil.addNodeTemplate(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), + nodeTemplate); + + mdcDataDebugMessage.debugExitMessage(null, null); + } +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailV2VirtualNetworkImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailV2VirtualNetworkImpl.java new file mode 100644 index 0000000000..d39d0f1c45 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailV2VirtualNetworkImpl.java @@ -0,0 +1,240 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; + +import org.apache.commons.collections.CollectionUtils; +import org.openecomp.sdc.common.utils.CommonUtil; +import org.openecomp.sdc.logging.api.Logger; +import org.openecomp.sdc.logging.api.LoggerFactory; +import org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes; +import org.openecomp.sdc.heat.datatypes.model.Resource; +import org.openecomp.sdc.tosca.datatypes.ToscaCapabilityType; +import org.openecomp.sdc.tosca.datatypes.ToscaNodeType; +import org.openecomp.sdc.tosca.datatypes.ToscaRelationshipType; +import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; +import org.openecomp.sdc.tosca.datatypes.model.RequirementAssignment; +import org.openecomp.sdc.tosca.services.DataModelUtil; +import org.openecomp.sdc.tosca.services.ToscaConstants; +import org.openecomp.sdc.translator.datatypes.heattotosca.AttachedResourceId; +import org.openecomp.sdc.translator.datatypes.heattotosca.ReferenceType; +import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; +import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; +import org.openecomp.sdc.translator.services.heattotosca.ResourceTranslationFactory; +import org.openecomp.sdc.translator.services.heattotosca.mapping.TranslatorHeatToToscaPropertyConverter; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +public class ResourceTranslationContrailV2VirtualNetworkImpl extends ResourceTranslationBase { + + protected static Logger logger = + (Logger) LoggerFactory.getLogger(ResourceTranslationContrailV2VirtualNetworkImpl.class); + + @Override + public void translate(TranslateTo translateTo) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + NodeTemplate nodeTemplate = new NodeTemplate(); + nodeTemplate.setType(ToscaNodeType.CONTRAILV2_VIRTUAL_NETWORK); + nodeTemplate.setProperties(TranslatorHeatToToscaPropertyConverter + .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(),translateTo. + getResourceId(),translateTo.getResource().getProperties(), + nodeTemplate.getProperties(), translateTo.getHeatFileName(), + translateTo.getHeatOrchestrationTemplate(), translateTo.getResource().getType(), + nodeTemplate, translateTo.getContext())); + DataModelUtil.addNodeTemplate(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), + nodeTemplate); + linkToPolicyNodeTemplate(translateTo); + + mdcDataDebugMessage.debugExitMessage(null, null); + } + + private void linkToPolicyNodeTemplate(TranslateTo translateTo) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + List networkPolicyIdList = extractNetworkPolicyIdList(translateTo); + if (CollectionUtils.isEmpty(networkPolicyIdList)) { + return; + } + for (AttachedResourceId attachedResourceId : networkPolicyIdList) { + NodeTemplate policyNodeTemplate = DataModelUtil + .getNodeTemplate(translateTo.getServiceTemplate(), + (String) attachedResourceId.getTranslatedId()); + DataModelUtil + .addRequirementAssignment(policyNodeTemplate, ToscaConstants.NETWORK_REQUIREMENT_ID, + createRequirementAssignment(translateTo.getTranslatedId())); + } + + mdcDataDebugMessage.debugExitMessage(null, null); + } + + private List extractNetworkPolicyIdList(TranslateTo translateTo) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + Object propertyValue = translateTo.getResource().getProperties().get("network_policy_refs"); + if (propertyValue != null) { + mdcDataDebugMessage.debugExitMessage(null, null); + return extractNetworkPolicyId(propertyValue, translateTo); + } else { + mdcDataDebugMessage.debugExitMessage(null, null); + return null; + } + } + + private List extractNetworkPolicyId(Object propertyValue, + TranslateTo translateTo) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + List attachedResourceIdList = new ArrayList<>(); + + if (propertyValue instanceof List) { + for (Object value : (List) propertyValue) { + attachedResourceIdList.addAll(extractNetworkPolicyId(value, translateTo)); + } + } else { + AttachedResourceId resourceId = parsNetworkPolicyId(propertyValue, translateTo); + if (resourceId != null) { + attachedResourceIdList.add(resourceId); + } + } + + mdcDataDebugMessage.debugExitMessage(null, null); + return attachedResourceIdList; + } + + private AttachedResourceId parsNetworkPolicyId(Object propertyValue, TranslateTo translateTo) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + Optional translatedPolicyResourceId; + String policyResourceId = extractResourceId(propertyValue, translateTo); + if (policyResourceId == null) { + mdcDataDebugMessage.debugExitMessage(null, null); + return null; + } + + Resource policyResource = HeatToToscaUtil + .getResource(translateTo.getHeatOrchestrationTemplate(), policyResourceId, + translateTo.getHeatFileName()); + if (!policyResource.getType() + .equals(HeatResourcesTypes.CONTRAIL_V2_NETWORK_RULE_RESOURCE_TYPE.getHeatResource())) { + mdcDataDebugMessage.debugExitMessage(null, null); + return null; + } + translatedPolicyResourceId = ResourceTranslationFactory.getInstance(policyResource) + .translateResource(translateTo.getHeatFileName(), translateTo.getServiceTemplate(), + translateTo.getHeatOrchestrationTemplate(), policyResource, policyResourceId, + translateTo.getContext()); + if (!translatedPolicyResourceId.isPresent()) { + logger.warn("Heat resource: '" + translateTo.getResourceId() + "' with type: '" + + translateTo.getResource().getType() + + "' property network_policy_refs is referenced to an unsupported resource the " + + "connection will be ignored in TOSCA translation."); + mdcDataDebugMessage.debugExitMessage(null, null); + return null; + } + AttachedResourceId attachedResourceId = + new AttachedResourceId(translatedPolicyResourceId.get(), policyResourceId, + ReferenceType.GET_ATTR); + mdcDataDebugMessage.debugExitMessage(null, null); + return attachedResourceId; + } + + private String extractResourceId(Object propertyValue, TranslateTo translateTo) { + + Object value; + if (propertyValue instanceof Map) { + if (((Map) propertyValue).containsKey("get_attr")) { + value = ((Map) propertyValue).get("get_attr"); + if (value instanceof List) { + if (((List) value).size() == 2 && ((List) value).get(1).equals("fq_name")) { + if (((List) value).get(0) instanceof String) { + return (String) ((List) value).get(0); + } else { + logger.warn("Heat resource: '" + translateTo.getResourceId() + "' with type: '" + + translateTo.getResource().getType() + + "' has property with invalid format of 'get_attr' function with 'fq_name' " + + "value, therefore this property will be ignored in TOSCA translation."); + } + } + } + } else if (((Map) propertyValue).containsKey("get_resource")) { + value = ((Map) propertyValue).get("get_resource"); + if (value instanceof String) { + return (String) value; + } else { + logger.warn("Heat resource: '" + translateTo.getResourceId() + "' with type: '" + + translateTo.getResource().getType() + + "' has property invalid format of 'get_resource' function, therefore this property" + + " will be ignored in TOSCA translation."); + } + } else { + Collection valCollection = ((Map) propertyValue).values(); + for (Object entryValue : valCollection) { + String ret = extractResourceId(entryValue, translateTo); + if (ret != null) { + return ret; + } + + } + } + } else if (propertyValue instanceof List) { + for (Object prop : (List) propertyValue) { + String ret = extractResourceId(prop, translateTo); + if (ret != null) { + return ret; + } + } + } + logger.warn("Heat resource: '" + translateTo.getResourceId() + "' with type: '" + + translateTo.getResource().getType() + + "' invalid format of property value, therefore this resource will be ignored in TOSCA " + + "translation."); + return null; + } + + private RequirementAssignment createRequirementAssignment(String translatedNetworkResourceId) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + RequirementAssignment requirement = new RequirementAssignment(); + requirement.setCapability(ToscaCapabilityType.NATIVE_ATTACHMENT); + requirement.setNode(translatedNetworkResourceId); + requirement.setRelationship(ToscaRelationshipType.ATTACHES_TO); + mdcDataDebugMessage.debugExitMessage(null, null); + return requirement; + } + + +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailV2VlanSubInterfaceImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailV2VlanSubInterfaceImpl.java new file mode 100644 index 0000000000..e0e6c459a1 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailV2VlanSubInterfaceImpl.java @@ -0,0 +1,132 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; + +import org.openecomp.sdc.common.utils.CommonUtil; +import org.openecomp.sdc.logging.api.Logger; +import org.openecomp.sdc.logging.api.LoggerFactory; +import org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes; +import org.openecomp.sdc.heat.datatypes.model.Resource; +import org.openecomp.sdc.heat.services.HeatConstants; +import org.openecomp.sdc.tosca.datatypes.ToscaNodeType; +import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; +import org.openecomp.sdc.tosca.services.DataModelUtil; +import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; +import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; +import org.openecomp.sdc.translator.services.heattotosca.helper.ContrailV2VirtualMachineInterfaceHelper; +import org.openecomp.sdc.translator.services.heattotosca.mapping.TranslatorHeatToToscaPropertyConverter; + +import java.util.Arrays; +import java.util.List; +import java.util.Objects; +import java.util.Optional; + + +public class ResourceTranslationContrailV2VlanSubInterfaceImpl extends ResourceTranslationBase { + protected static Logger logger = + (Logger) LoggerFactory.getLogger(ResourceTranslationContrailV2VlanSubInterfaceImpl.class); + + @Override + protected void translate(TranslateTo translateTo) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + NodeTemplate nodeTemplate = new NodeTemplate(); + nodeTemplate.setType(ToscaNodeType.CONTRAILV2_VLAN_SUB_INTERFACE); + + nodeTemplate.setProperties(TranslatorHeatToToscaPropertyConverter + .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(),translateTo. + getResourceId(),translateTo.getResource().getProperties(), + nodeTemplate.getProperties(), translateTo.getHeatFileName(), + translateTo.getHeatOrchestrationTemplate(), translateTo.getResource().getType(), + nodeTemplate, translateTo.getContext())); + + new ContrailV2VirtualMachineInterfaceHelper() + .connectVmiToNetwork(this, translateTo, nodeTemplate); + connectSubInterfaceToInterface(translateTo, nodeTemplate); + DataModelUtil.addNodeTemplate(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), + nodeTemplate); + + mdcDataDebugMessage.debugExitMessage(null, null); + } + + //connection to shared interface is not supported + private void connectSubInterfaceToInterface(TranslateTo translateTo, + NodeTemplate vlanSubInterfaceNodeTemplate) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + Object interfaceRefs = + translateTo.getResource().getProperties().get(HeatConstants.VMI_REFS_PROPERTY_NAME); + if (Objects.isNull(interfaceRefs) || !(interfaceRefs instanceof List) + || ((List) interfaceRefs).size() == 0) { + return; + } + List acceptableResourceTypes = Arrays + .asList(HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_MACHINE_INTERFACE_RESOURCE_TYPE + .getHeatResource(), + HeatResourcesTypes.NEUTRON_PORT_RESOURCE_TYPE.getHeatResource()); + if (((List) interfaceRefs).size() > 1) { + logger.warn("Heat resource: '" + translateTo.getResourceId() + "' with type: '" + + translateTo.getResource().getType() + + "' include '" + HeatConstants.VMI_REFS_PROPERTY_NAME + + "' property with more than one interface values, only " + + "the first interface will be connected, " + + "all rest will be ignored in TOSCA translation."); + } + Object interfaceRef = ((List) interfaceRefs).get(0); + + Optional interfaceResourceId = + HeatToToscaUtil.extractContrailGetResourceAttachedHeatResourceId(interfaceRef); + if (interfaceResourceId.isPresent()) { // get_resource + Resource interfaceResource = HeatToToscaUtil + .getResource(translateTo.getHeatOrchestrationTemplate(), interfaceResourceId.get(), + translateTo.getHeatFileName()); + + if (acceptableResourceTypes.contains(interfaceResource.getType()) + && !(new ContrailV2VirtualMachineInterfaceHelper() + .isVlanSubInterfaceResource(interfaceResource))) { + Optional interfaceResourceTranslatedId = + getResourceTranslatedId(translateTo.getHeatFileName(), + translateTo.getHeatOrchestrationTemplate(), interfaceResourceId.get(), + translateTo.getContext()); + interfaceResourceTranslatedId.ifPresent(interfaceResourceTranslatedIdVal -> HeatToToscaUtil + .addBindingReqFromSubInterfaceToInterface(vlanSubInterfaceNodeTemplate, + interfaceResourceTranslatedIdVal)); + } else { + logger.warn("Heat resource: '" + translateTo.getResourceId() + "' with type: '" + + translateTo.getResource().getType() + + "' include '" + HeatConstants.VMI_REFS_PROPERTY_NAME + + "' property which is connect to unsupported/incorrect " + + (true == (new ContrailV2VirtualMachineInterfaceHelper() + .isVlanSubInterfaceResource(interfaceResource)) ? "Vlan Sub interface " : "") + + "resource '" + interfaceResourceId.get() + "' with type '" + + interfaceResource.getType() + + "', therefore, this connection will be ignored in TOSCA translation."); + } + } + + mdcDataDebugMessage.debugExitMessage(null, null); + } + +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailV2VmInterfaceImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailV2VmInterfaceImpl.java new file mode 100644 index 0000000000..1736bbef96 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailV2VmInterfaceImpl.java @@ -0,0 +1,138 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; + +import org.openecomp.sdc.heat.services.HeatConstants; +import org.openecomp.sdc.logging.api.Logger; +import org.openecomp.sdc.logging.api.LoggerFactory; +import org.openecomp.sdc.tosca.datatypes.ToscaNodeType; +import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; +import org.openecomp.sdc.tosca.services.DataModelUtil; +import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; +import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; +import org.openecomp.sdc.translator.services.heattotosca.helper.ContrailV2VirtualMachineInterfaceHelper; +import org.openecomp.sdc.translator.services.heattotosca.mapping.TranslatorHeatToToscaPropertyConverter; + +import java.util.List; +import java.util.Map; + + +public class ResourceTranslationContrailV2VmInterfaceImpl extends ResourceTranslationBase { + protected static Logger logger = + (Logger) LoggerFactory.getLogger(ResourceTranslationContrailV2VmInterfaceImpl.class); + + @Override + protected String generateTranslatedId(TranslateTo translateTo) { + if (new ContrailV2VirtualMachineInterfaceHelper().isVlanSubInterfaceResource(translateTo + .getResource())) { + return null; + } else { + return super.generateTranslatedId(translateTo); + } + } + + @Override + protected void translate(TranslateTo translateTo) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + if (new ContrailV2VirtualMachineInterfaceHelper().isVlanSubInterfaceResource(translateTo + .getResource())) { + translateVlanSubInterfaceResource(translateTo); + } else { + translateVirtualMachineInterfaceResource(translateTo); + } + + mdcDataDebugMessage.debugExitMessage(null, null); + } + + + private void translateVirtualMachineInterfaceResource(TranslateTo translateTo) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + NodeTemplate nodeTemplate = new NodeTemplate(); + nodeTemplate.setType(ToscaNodeType.CONTRAILV2_VIRTUAL_MACHINE_INTERFACE); + nodeTemplate.setProperties(TranslatorHeatToToscaPropertyConverter + .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(),translateTo. + getResourceId(),translateTo.getResource().getProperties(), + nodeTemplate.getProperties(), translateTo.getHeatFileName(), + translateTo.getHeatOrchestrationTemplate(), translateTo.getResource().getType(), + nodeTemplate, translateTo.getContext())); + String toscaVmiRefsPropertyName = + HeatToToscaUtil.getToscaPropertyName(translateTo, HeatConstants.VMI_REFS_PROPERTY_NAME); + if (nodeTemplate.getProperties().containsKey(toscaVmiRefsPropertyName)) { + nodeTemplate.getProperties().remove(toscaVmiRefsPropertyName); + } + + handleVmiMacAddressesInProperties(translateTo, nodeTemplate); + + new ContrailV2VirtualMachineInterfaceHelper() + .connectVmiToNetwork(this, translateTo, nodeTemplate); + DataModelUtil.addNodeTemplate(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), + nodeTemplate); + + mdcDataDebugMessage.debugExitMessage(null, null); + } + + private void handleVmiMacAddressesInProperties(TranslateTo translateTo, + NodeTemplate nodeTemplate) { + String toscaVmiMacAddressesName = + HeatToToscaUtil.getToscaPropertyName(translateTo, HeatConstants.VMI_MAC_ADDRESSES); + String toscaVmiMacAddressesMacAddressesName = + HeatToToscaUtil.getToscaPropertyName(translateTo, HeatConstants.VMI_MAC_ADDRESSES_MAC_ADDRESSES); + + if(nodeTemplate.getProperties().containsKey(toscaVmiMacAddressesName)){ + Object macAddressesValue = nodeTemplate.getProperties().get(toscaVmiMacAddressesName); + if(macAddressesValue instanceof Map && ((Map)macAddressesValue).containsKey + (toscaVmiMacAddressesMacAddressesName)){ + updateMacAddressesMacAddressesInProperties(nodeTemplate, toscaVmiMacAddressesName, + toscaVmiMacAddressesMacAddressesName, + (Map) macAddressesValue); + } + } + } + + private void updateMacAddressesMacAddressesInProperties(NodeTemplate nodeTemplate, + String toscaVmiMacAddressesName, + String toscaVmiMacAddressesMacAddressesName, + Map macAddressesValue) { + Object macAddressesMacAddressesValue = + macAddressesValue.get(toscaVmiMacAddressesMacAddressesName); + if(macAddressesMacAddressesValue instanceof List){ + nodeTemplate.getProperties().put(toscaVmiMacAddressesName, macAddressesMacAddressesValue); + }else{ + nodeTemplate.getProperties().remove(toscaVmiMacAddressesName); + } + } + + private void translateVlanSubInterfaceResource(TranslateTo translateTo) { + + mdcDataDebugMessage.debugEntryMessage(null, null); + + new ResourceTranslationContrailV2VlanSubInterfaceImpl().translate(translateTo); + + mdcDataDebugMessage.debugExitMessage(null, null); + } + +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailVirtualNetworkImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailVirtualNetworkImpl.java new file mode 100644 index 0000000000..a6fc9ac2c1 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationContrailVirtualNetworkImpl.java @@ -0,0 +1,51 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; + +import org.openecomp.sdc.common.utils.CommonUtil; +import org.openecomp.sdc.tosca.datatypes.ToscaNodeType; +import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; +import org.openecomp.sdc.tosca.services.DataModelUtil; +import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; +import org.openecomp.sdc.translator.services.heattotosca.mapping.TranslatorHeatToToscaPropertyConverter; + +public class ResourceTranslationContrailVirtualNetworkImpl extends ResourceTranslationBase { + + @Override + public void translate(TranslateTo translateTo) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + NodeTemplate nodeTemplate = new NodeTemplate(); + nodeTemplate.setType(ToscaNodeType.CONTRAIL_VIRTUAL_NETWORK); + nodeTemplate.setProperties(TranslatorHeatToToscaPropertyConverter + .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(),translateTo. + getResourceId(),translateTo.getResource().getProperties(), + nodeTemplate.getProperties(), translateTo.getHeatFileName(), + translateTo.getHeatOrchestrationTemplate(), translateTo.getResource().getType(), + nodeTemplate, translateTo.getContext())); + DataModelUtil.addNodeTemplate(translateTo.getServiceTemplate(), + translateTo.getTranslatedId(),nodeTemplate); + + mdcDataDebugMessage.debugExitMessage(null, null); + } +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationDefaultImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationDefaultImpl.java new file mode 100644 index 0000000000..15a3c178b9 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationDefaultImpl.java @@ -0,0 +1,55 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; + +import org.openecomp.sdc.tosca.datatypes.ToscaTopologyTemplateElements; +import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; + +import java.util.Optional; + +public class ResourceTranslationDefaultImpl extends ResourceTranslationBase { + + @Override + public void translate(TranslateTo translateTo) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + //no translation is needed, this default is used for unsupported resources + logger.warn("Heat resource: '" + translateTo.getResourceId() + "' with type: '" + + translateTo.getResource().getType() + + "' is not supported, will be ignored in TOSCA translation"); + + mdcDataDebugMessage.debugExitMessage(null, null); + } + + @Override + protected String generateTranslatedId(TranslateTo translateTo) { + return null; + } + + @Override + protected Optional getTranslatedToscaTopologyElement( + TranslateTo translateTo) { + return Optional.empty(); + } + +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNestedImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNestedImpl.java new file mode 100644 index 0000000000..843d9fabc6 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNestedImpl.java @@ -0,0 +1,236 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; + +import org.openecomp.core.utilities.file.FileUtils; +import org.openecomp.sdc.heat.datatypes.manifest.FileData; +import org.openecomp.sdc.logging.api.Logger; +import org.openecomp.sdc.logging.api.LoggerFactory; +import org.openecomp.sdc.tosca.datatypes.ToscaNodeType; +import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; +import org.openecomp.sdc.tosca.datatypes.model.NodeType; +import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; +import org.openecomp.sdc.tosca.services.DataModelUtil; +import org.openecomp.sdc.tosca.services.ToscaUtil; +import org.openecomp.sdc.tosca.services.impl.ToscaAnalyzerServiceImpl; +import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; +import org.openecomp.sdc.translator.services.heattotosca.ConsolidationDataUtil; +import org.openecomp.sdc.translator.services.heattotosca.Constants; +import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; +import org.openecomp.sdc.translator.services.heattotosca.TranslationService; + +public class ResourceTranslationNestedImpl extends ResourceTranslationBase { + + protected static Logger logger = + (Logger) LoggerFactory.getLogger(ResourceTranslationNestedImpl.class); + + @Override + public void translate(TranslateTo translateTo) { + mdcDataDebugMessage.debugEntryMessage(null, null); + + FileData nestedFileData = + HeatToToscaUtil.getFileData(translateTo.getResource().getType(), translateTo.getContext()); + if (nestedFileData == null) { + logger.warn("Nested File '" + translateTo.getResource().getType() + + "' is not exist, therefore, the nested resource with the ID '" + + translateTo.getResourceId() + "' will be ignored in TOSCA translation"); + return; + } + String templateName = FileUtils.getFileWithoutExtention(translateTo.getResource().getType()); + String substitutionNodeTypeKey = ToscaNodeType.ABSTRACT_NODE_TYPE_PREFIX + "heat." + + templateName; + + if (!translateTo.getContext().getTranslatedServiceTemplates() + .containsKey(translateTo.getResource().getType())) { + + //substitution service template + ServiceTemplate nestedSubstitutionServiceTemplate = + createSubstitutionServiceTemplate(translateTo, nestedFileData, templateName); + + //global substitution service template + ServiceTemplate globalSubstitutionServiceTemplate = new HeatToToscaUtil() + .fetchGlobalSubstitutionServiceTemplate(translateTo.getServiceTemplate(), + translateTo.getContext()); + + //substitution node type + NodeType substitutionNodeType = new ToscaAnalyzerServiceImpl() + .createInitSubstitutionNodeType(nestedSubstitutionServiceTemplate, + ToscaNodeType.ABSTRACT_SUBSTITUTE); + DataModelUtil.addNodeType(globalSubstitutionServiceTemplate, substitutionNodeTypeKey, + substitutionNodeType); + //substitution mapping + HeatToToscaUtil + .handleSubstitutionMapping(translateTo.getContext(), substitutionNodeTypeKey, + nestedSubstitutionServiceTemplate, substitutionNodeType); + + //add new nested service template + translateTo.getContext().getTranslatedServiceTemplates() + .put(translateTo.getResource().getType(), nestedSubstitutionServiceTemplate); + } + + NodeTemplate substitutionNodeTemplate = + HeatToToscaUtil.createAbstractSubstitutionNodeTemplate(translateTo, templateName, + substitutionNodeTypeKey); + manageSubstitutionNodeTemplateConnectionPoint(translateTo, nestedFileData, + substitutionNodeTemplate, substitutionNodeTypeKey); + DataModelUtil.addNodeTemplate(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), + substitutionNodeTemplate); + + //Add nested node template id to consolidation data + ConsolidationDataUtil.updateNestedNodeTemplateId(translateTo); + + mdcDataDebugMessage.debugExitMessage(null, null); + } + + private ServiceTemplate createSubstitutionServiceTemplate(TranslateTo translateTo, + FileData nestedFileData, + String templateName) { + ServiceTemplate nestedSubstitutionServiceTemplate = + HeatToToscaUtil.createInitSubstitutionServiceTemplate(templateName); + translateTo.getContext() + .addNestedHeatFileName(ToscaUtil.getServiceTemplateFileName(templateName), + translateTo.getResource().getType()); + new TranslationService().translateHeatFile(nestedSubstitutionServiceTemplate, nestedFileData, + translateTo.getContext()); + return nestedSubstitutionServiceTemplate; + } + + + private void manageSubstitutionNodeTemplateConnectionPoint(TranslateTo translateTo, + FileData nestedFileData, + NodeTemplate substitutionNodeTemplate, + String substitutionNodeTypeId) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + ServiceTemplate globalSubstitutionTemplate = + translateTo.getContext().getTranslatedServiceTemplates() + .get(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME); + NodeType nodeType = globalSubstitutionTemplate.getNode_types().get(substitutionNodeTypeId); + handlePortToNetConnections(translateTo, nestedFileData, substitutionNodeTemplate, nodeType); + handleSecurityRulesToPortConnections(translateTo, nestedFileData, substitutionNodeTemplate, + nodeType); + handleNovaToVolConnection(translateTo, nestedFileData, substitutionNodeTemplate, nodeType); + handleContrailV2VmInterfaceToNetworkConnection(translateTo, nestedFileData, + substitutionNodeTemplate, nodeType); + handleContrailPortToNetConnections(translateTo, nestedFileData, substitutionNodeTemplate, + nodeType); + handleVlanSubInterfaceToInterfaceConnections(translateTo, nestedFileData, + substitutionNodeTemplate, nodeType); + + mdcDataDebugMessage.debugExitMessage(null, null); + } + + private void handleVlanSubInterfaceToInterfaceConnections(TranslateTo translateTo, + FileData nestedFileData, + NodeTemplate substitutionNodeTemplate, + NodeType nodeType) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + ContrailV2VlanToInterfaceResourceConnection linker = + new ContrailV2VlanToInterfaceResourceConnection(this, translateTo, nestedFileData, + substitutionNodeTemplate, nodeType); + linker.connect(); + + mdcDataDebugMessage.debugExitMessage(null, null); + } + + + private void handleContrailV2VmInterfaceToNetworkConnection(TranslateTo translateTo, + FileData nestedFileData, + NodeTemplate substitutionNodeTemplate, + NodeType nodeType) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + ContrailV2VmInterfaceToNetResourceConnection linker = + new ContrailV2VmInterfaceToNetResourceConnection(this, translateTo, nestedFileData, + substitutionNodeTemplate, nodeType); + linker.connect(); + + mdcDataDebugMessage.debugExitMessage(null, null); + } + + private void handleNovaToVolConnection(TranslateTo translateTo, FileData nestedFileData, + NodeTemplate substitutionNodeTemplate, NodeType nodeType) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + NovaToVolResourceConnection linker = + new NovaToVolResourceConnection(this, translateTo, nestedFileData, substitutionNodeTemplate, + nodeType); + linker.connect(); + + mdcDataDebugMessage.debugExitMessage(null, null); + } + + private void handleSecurityRulesToPortConnections(TranslateTo translateTo, + FileData nestedFileData, + NodeTemplate substitutionNodeTemplate, + NodeType nodeType) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + SecurityRulesToPortResourceConnection linker = + new SecurityRulesToPortResourceConnection(this, translateTo, nestedFileData, + substitutionNodeTemplate, nodeType); + linker.connect(); + + mdcDataDebugMessage.debugExitMessage(null, null); + } + + private void handlePortToNetConnections(TranslateTo translateTo, FileData nestedFileData, + NodeTemplate substitutionNodeTemplate, + NodeType nodeType) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + PortToNetResourceConnection linker = + new PortToNetResourceConnection(this, translateTo, nestedFileData, substitutionNodeTemplate, + nodeType); + linker.connect(); + + mdcDataDebugMessage.debugExitMessage(null, null); + } + + private void handleContrailPortToNetConnections(TranslateTo translateTo, FileData nestedFileData, + NodeTemplate substitutionNodeTemplate, + NodeType nodeType) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + ContrailPortToNetResourceConnection linker = + new ContrailPortToNetResourceConnection(this, translateTo, nestedFileData, + substitutionNodeTemplate, nodeType); + linker.connect(); + + mdcDataDebugMessage.debugExitMessage(null, null); + } + +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNeutronNetImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNeutronNetImpl.java new file mode 100644 index 0000000000..49fdcaafa9 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNeutronNetImpl.java @@ -0,0 +1,63 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; + +import org.openecomp.sdc.heat.services.HeatConstants; +import org.openecomp.sdc.tosca.datatypes.ToscaNodeType; +import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; +import org.openecomp.sdc.tosca.services.DataModelUtil; +import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; +import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; +import org.openecomp.sdc.translator.services.heattotosca.mapping.TranslatorHeatToToscaPropertyConverter; + + +public class ResourceTranslationNeutronNetImpl extends ResourceTranslationBase { + + @Override + public void translate(TranslateTo translateTo) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + NodeTemplate nodeTemplate = new NodeTemplate(); + nodeTemplate.setType(ToscaNodeType.NEUTRON_NET); + nodeTemplate.setProperties(TranslatorHeatToToscaPropertyConverter + .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(),translateTo. + getResourceId(),translateTo.getResource().getProperties(), + nodeTemplate.getProperties(), translateTo.getHeatFileName(), + translateTo.getHeatOrchestrationTemplate(), translateTo.getResource().getType(), + nodeTemplate, translateTo.getContext())); + + HeatToToscaUtil.mapBoolean(nodeTemplate, HeatToToscaUtil + .getToscaPropertyName(translateTo, HeatConstants.PORT_SECURITY_ENABLED_PROPERTY_NAME)); + HeatToToscaUtil.mapBoolean(nodeTemplate, HeatToToscaUtil + .getToscaPropertyName(translateTo, HeatConstants.SHARED_PROPERTY_NAME)); + HeatToToscaUtil.mapBoolean(nodeTemplate, HeatToToscaUtil + .getToscaPropertyName(translateTo, HeatConstants.ADMIN_STATE_UP_PROPERTY_NAME)); + + DataModelUtil.addNodeTemplate(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), + nodeTemplate); + + mdcDataDebugMessage.debugExitMessage(null, null); + } + + +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNeutronPortImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNeutronPortImpl.java new file mode 100644 index 0000000000..f1bd6790c2 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNeutronPortImpl.java @@ -0,0 +1,296 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; + +import org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes; +import org.openecomp.sdc.heat.datatypes.model.Resource; +import org.openecomp.sdc.tosca.datatypes.ToscaCapabilityType; +import org.openecomp.sdc.tosca.datatypes.ToscaNodeType; +import org.openecomp.sdc.tosca.datatypes.ToscaRelationshipType; +import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; +import org.openecomp.sdc.tosca.datatypes.model.RequirementAssignment; +import org.openecomp.sdc.tosca.services.DataModelUtil; +import org.openecomp.sdc.tosca.services.ToscaConstants; +import org.openecomp.sdc.translator.datatypes.heattotosca.AttachedResourceId; +import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; +import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslatedHeatResource; +import org.openecomp.sdc.translator.services.heattotosca.ConsolidationDataUtil; +import org.openecomp.sdc.translator.services.heattotosca.Constants; +import org.openecomp.sdc.translator.services.heattotosca.ConsolidationEntityType; +import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; +import org.openecomp.sdc.translator.services.heattotosca.ResourceTranslationFactory; +import org.openecomp.sdc.translator.services.heattotosca.helper.ResourceTranslationNeutronPortHelper; +import org.openecomp.sdc.translator.services.heattotosca.mapping.TranslatorHeatToToscaPropertyConverter; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + + +public class ResourceTranslationNeutronPortImpl extends ResourceTranslationBase { + + @Override + public void translate(TranslateTo translateTo) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + NodeTemplate nodeTemplate = new NodeTemplate(); + nodeTemplate.setType(ToscaNodeType.NEUTRON_PORT); + nodeTemplate.setProperties(TranslatorHeatToToscaPropertyConverter + .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(), translateTo. + getResourceId(), translateTo.getResource().getProperties(), + nodeTemplate.getProperties(), translateTo.getHeatFileName(), + translateTo.getHeatOrchestrationTemplate(), translateTo.getResource().getType(), + nodeTemplate, translateTo.getContext())); + new ResourceTranslationNeutronPortHelper().setAdditionalProperties(nodeTemplate + .getProperties()); + handleNetworkRequirement(translateTo, nodeTemplate); + String resourceTranslatedId = handleSecurityRulesRequirement(translateTo); + DataModelUtil + .addNodeTemplate(translateTo.getServiceTemplate(), resourceTranslatedId, nodeTemplate); + + mdcDataDebugMessage.debugExitMessage(null, null); + } + + private String handleSecurityRulesRequirement(TranslateTo translateTo) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + String resourceTranslatedId = translateTo.getTranslatedId(); + Map properties = translateTo.getResource().getProperties(); + Optional securityGroups = + Optional.ofNullable(properties.get(Constants.SECURITY_GROUPS_PROPERTY_NAME)); + if (securityGroups.isPresent() && securityGroups.get() instanceof List) { + List securityGroupsList = (List) securityGroups.get(); + securityGroupsList.forEach(resourceValue -> { + Optional securityGroupResourceId = HeatToToscaUtil + .extractAttachedResourceId(translateTo.getHeatFileName(), + translateTo.getHeatOrchestrationTemplate(), translateTo.getContext(), + resourceValue); + securityGroupResourceId.ifPresent( + attachedResourceId -> handleSecurityGroupResourceId(translateTo, resourceTranslatedId, + attachedResourceId)); + }); + } + + mdcDataDebugMessage.debugExitMessage(null, null); + return resourceTranslatedId; + } + + private void handleSecurityGroupResourceId(TranslateTo translateTo, String resourceTranslatedId, + AttachedResourceId securityGroupResourceId) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + List supportedSecurityGroupsTypes = Collections + .singletonList(HeatResourcesTypes.NEUTRON_SECURITY_GROUP_RESOURCE_TYPE.getHeatResource()); + if (securityGroupResourceId.isGetResource()) { + handleGetResource(translateTo, resourceTranslatedId, securityGroupResourceId, + supportedSecurityGroupsTypes); + } else if (securityGroupResourceId.isGetParam()) { + handleGetParam(translateTo, resourceTranslatedId, securityGroupResourceId, + supportedSecurityGroupsTypes); + } + + mdcDataDebugMessage.debugExitMessage(null, null); + } + + private void handleGetParam(TranslateTo translateTo, String resourceTranslatedId, + AttachedResourceId securityGroupResourceId, + List supportedSecurityGroupsTypes) { + mdcDataDebugMessage.debugEntryMessage(null, null); + + if (!(securityGroupResourceId.getEntityId() instanceof String)) { + mdcDataDebugMessage.debugExitMessage(null, null); + return; + } + TranslatedHeatResource translatedSharedResourceId = + translateTo.getContext().getHeatSharedResourcesByParam() + .get(securityGroupResourceId.getEntityId()); + if (Objects.nonNull(translatedSharedResourceId) + && !HeatToToscaUtil.isHeatFileNested(translateTo, translateTo.getHeatFileName())) { + if (validateResourceTypeSupportedForReqCreation(translateTo, supportedSecurityGroupsTypes, + translatedSharedResourceId.getHeatResource(), "security_groups")) { + mdcDataDebugMessage.debugExitMessage(null, null); + return; + } + final NodeTemplate securityGroupNodeTemplate = DataModelUtil + .getNodeTemplate(translateTo.getServiceTemplate(), + translatedSharedResourceId.getTranslatedId()); + RequirementAssignment requirement = new RequirementAssignment(); + requirement.setCapability(ToscaCapabilityType.NATIVE_ATTACHMENT); + requirement.setNode(resourceTranslatedId); + requirement.setRelationship(ToscaRelationshipType.ATTACHES_TO); + DataModelUtil + .addRequirementAssignment(securityGroupNodeTemplate, ToscaConstants.PORT_REQUIREMENT_ID, + requirement); + + ConsolidationDataUtil + .updateNodesConnectedIn(translateTo, translatedSharedResourceId.getTranslatedId(), + ConsolidationEntityType.PORT, translateTo.getResourceId(), + ToscaConstants.PORT_REQUIREMENT_ID, requirement); + } + + mdcDataDebugMessage.debugExitMessage(null, null); + } + + private void handleGetResource(TranslateTo translateTo, String resourceTranslatedId, + AttachedResourceId securityGroupResourceId, + List supportedSecurityGroupsTypes) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + String resourceId = (String) securityGroupResourceId.getEntityId(); + Resource securityGroupResource = HeatToToscaUtil + .getResource(translateTo.getHeatOrchestrationTemplate(), resourceId, + translateTo.getHeatFileName()); + Optional securityGroupTranslatedId = + ResourceTranslationFactory.getInstance(securityGroupResource) + .translateResource(translateTo.getHeatFileName(), translateTo.getServiceTemplate(), + translateTo.getHeatOrchestrationTemplate(), securityGroupResource, resourceId, + translateTo.getContext()); + if (securityGroupTranslatedId.isPresent()) { + if (validateResourceTypeSupportedForReqCreation(translateTo, supportedSecurityGroupsTypes, + securityGroupResource, "security_groups")) { + mdcDataDebugMessage.debugExitMessage(null, null); + return; + } + final NodeTemplate securityGroupNodeTemplate = DataModelUtil + .getNodeTemplate(translateTo.getServiceTemplate(), securityGroupTranslatedId.get()); + RequirementAssignment requirement = new RequirementAssignment(); + requirement.setCapability(ToscaCapabilityType.NATIVE_ATTACHMENT); + requirement.setNode(resourceTranslatedId); + requirement.setRelationship(ToscaRelationshipType.ATTACHES_TO); + DataModelUtil + .addRequirementAssignment(securityGroupNodeTemplate, ToscaConstants.PORT_REQUIREMENT_ID, + requirement); + + ConsolidationDataUtil.updateNodesConnectedIn(translateTo, securityGroupTranslatedId.get(), + ConsolidationEntityType.PORT, translateTo.getResourceId(), + ToscaConstants.PORT_REQUIREMENT_ID, requirement); + } + + mdcDataDebugMessage.debugExitMessage(null, null); + } + + private void handleNetworkRequirement(TranslateTo translateTo, NodeTemplate nodeTemplate) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + Optional networkResourceId = + HeatToToscaUtil.extractAttachedResourceId(translateTo, "network"); + if (networkResourceId.isPresent()) { + AttachedResourceId attachedResourceId = networkResourceId.get(); + addRequirementAssignmentForNetworkResource(translateTo, nodeTemplate, attachedResourceId); + } else { + networkResourceId = HeatToToscaUtil.extractAttachedResourceId(translateTo, "network_id"); + if (networkResourceId.isPresent()) { + AttachedResourceId attachedResourceId = networkResourceId.get(); + addRequirementAssignmentForNetworkResource(translateTo, nodeTemplate, attachedResourceId); + } + } + + mdcDataDebugMessage.debugExitMessage(null, null); + } + + private void addRequirementAssignmentForNetworkResource(TranslateTo translateTo, + NodeTemplate nodeTemplate, + AttachedResourceId attachedResourceId) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + String networkTranslatedId; + List supportedNetworkTypes = + Arrays.asList(HeatResourcesTypes.NEUTRON_NET_RESOURCE_TYPE.getHeatResource(), + HeatResourcesTypes.CONTRAIL_VIRTUAL_NETWORK_RESOURCE_TYPE.getHeatResource(), + HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_NETWORK_RESOURCE_TYPE.getHeatResource()); + if (attachedResourceId.isGetResource()) { + Resource networkHeatResource = translateTo.getHeatOrchestrationTemplate().getResources() + .get(attachedResourceId.getEntityId()); + if (validateResourceTypeSupportedForReqCreation(translateTo, supportedNetworkTypes, + networkHeatResource, "network'\\'network_id")) { + return; + } + networkTranslatedId = (String) attachedResourceId.getTranslatedId(); + RequirementAssignment requirementAssignment = HeatToToscaUtil.addLinkReqFromPortToNetwork( + nodeTemplate, networkTranslatedId); + + ConsolidationDataUtil.updateNodesConnectedOut(translateTo, networkTranslatedId, + ConsolidationEntityType.PORT, ToscaConstants.LINK_REQUIREMENT_ID, requirementAssignment); + + } else if (attachedResourceId.isGetParam() + && attachedResourceId.getEntityId() instanceof String) { + TranslatedHeatResource translatedSharedResourceId = + translateTo.getContext().getHeatSharedResourcesByParam() + .get(attachedResourceId.getEntityId()); + if (Objects.nonNull(translatedSharedResourceId) + && !HeatToToscaUtil.isHeatFileNested(translateTo, translateTo.getHeatFileName())) { + if (validateResourceTypeSupportedForReqCreation(translateTo, supportedNetworkTypes, + translatedSharedResourceId.getHeatResource(), "network'\\'network_id")) { + return; + } + RequirementAssignment requirementAssignment = HeatToToscaUtil.addLinkReqFromPortToNetwork( + nodeTemplate, translatedSharedResourceId.getTranslatedId()); + + ConsolidationDataUtil.updateNodesConnectedOut(translateTo, + translatedSharedResourceId.getTranslatedId(), ConsolidationEntityType.PORT, + ToscaConstants.LINK_REQUIREMENT_ID, requirementAssignment); + } + } + + mdcDataDebugMessage.debugExitMessage(null, null); + } + + + private boolean validateResourceTypeSupportedForReqCreation(TranslateTo translateTo, + List supportedTypes, + Resource heatResource, + final String propertyName) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + if (!isResourceTypeSupported(heatResource, supportedTypes)) { + logger.warn( + "'" + propertyName + "' property of port resource('" + translateTo.getResourceId() + + "') is pointing to a resource of type '" + heatResource.getType() + "' " + + "which is not supported for this requirement. " + + "Supported types are: " + supportedTypes.toString()); + + mdcDataDebugMessage.debugExitMessage(null, null); + return true; + } + mdcDataDebugMessage.debugExitMessage(null, null); + return false; + } + + +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNeutronSecurityGroupImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNeutronSecurityGroupImpl.java new file mode 100644 index 0000000000..96e79aca60 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNeutronSecurityGroupImpl.java @@ -0,0 +1,55 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; + +import org.openecomp.sdc.common.utils.CommonUtil; +import org.openecomp.sdc.tosca.datatypes.ToscaNodeType; +import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; +import org.openecomp.sdc.tosca.services.DataModelUtil; +import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; +import org.openecomp.sdc.translator.services.heattotosca.mapping.TranslatorHeatToToscaPropertyConverter; + + +public class ResourceTranslationNeutronSecurityGroupImpl extends ResourceTranslationBase { + + @Override + public void translate(TranslateTo translateTo) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + NodeTemplate nodeTemplate = new NodeTemplate(); + nodeTemplate.setType(ToscaNodeType.NEUTRON_SECURITY_RULES); + nodeTemplate.setProperties(TranslatorHeatToToscaPropertyConverter + .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(),translateTo. + getResourceId(),translateTo.getResource().getProperties(), + nodeTemplate.getProperties(), translateTo.getHeatFileName(), + translateTo.getHeatOrchestrationTemplate(), translateTo.getResource().getType(), + nodeTemplate, translateTo.getContext())); + + DataModelUtil.addNodeTemplate(translateTo.getServiceTemplate(), translateTo.getTranslatedId(), + nodeTemplate); + + mdcDataDebugMessage.debugExitMessage(null, null); + } + + +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNeutronSubnetImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNeutronSubnetImpl.java new file mode 100644 index 0000000000..76a8c447d1 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNeutronSubnetImpl.java @@ -0,0 +1,203 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; + +import org.openecomp.sdc.common.errors.CoreException; +import org.openecomp.sdc.datatypes.error.ErrorLevel; +import org.openecomp.sdc.heat.datatypes.HeatBoolean; +import org.openecomp.sdc.heat.datatypes.model.Resource; +import org.openecomp.sdc.logging.api.Logger; +import org.openecomp.sdc.logging.api.LoggerFactory; +import org.openecomp.sdc.logging.context.impl.MdcDataErrorMessage; +import org.openecomp.sdc.logging.types.LoggerConstants; +import org.openecomp.sdc.logging.types.LoggerErrorCode; +import org.openecomp.sdc.logging.types.LoggerErrorDescription; +import org.openecomp.sdc.logging.types.LoggerTragetServiceName; +import org.openecomp.sdc.tosca.datatypes.ToscaFunctions; +import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; +import org.openecomp.sdc.tosca.datatypes.model.ParameterDefinition; +import org.openecomp.sdc.tosca.datatypes.model.PropertyType; +import org.openecomp.sdc.tosca.services.DataModelUtil; +import org.openecomp.sdc.tosca.services.ToscaConstants; +import org.openecomp.sdc.translator.datatypes.heattotosca.AttachedResourceId; +import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; +import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; +import org.openecomp.sdc.translator.services.heattotosca.ResourceTranslationFactory; +import org.openecomp.sdc.translator.services.heattotosca.errors.MissingMandatoryPropertyErrorBuilder; +import org.openecomp.sdc.translator.services.heattotosca.mapping.TranslatorHeatToToscaPropertyConverter; + +import java.util.HashMap; +import java.util.Map; +import java.util.Optional; + +public class ResourceTranslationNeutronSubnetImpl extends ResourceTranslationBase { + protected static Logger logger = + (Logger) LoggerFactory.getLogger(ResourceTranslationNeutronSubnetImpl.class); + + @Override + public void translate(TranslateTo translateTo) { + mdcDataDebugMessage.debugEntryMessage(null, null); + + Optional subnetNetwork = getAttachedNetworkResource(translateTo); + + if (!subnetNetwork.isPresent() || !subnetNetwork.get().isGetResource()) { + return; + } + + Resource networkResource = HeatToToscaUtil + .getResource(translateTo.getHeatOrchestrationTemplate(), + (String) subnetNetwork.get().getEntityId(), translateTo.getHeatFileName()); + Optional translatedNetworkId = ResourceTranslationFactory.getInstance(networkResource) + .translateResource(translateTo.getHeatFileName(), translateTo.getServiceTemplate(), + translateTo.getHeatOrchestrationTemplate(), networkResource, + (String) subnetNetwork.get().getEntityId(), translateTo.getContext()); + if (translatedNetworkId.isPresent()) { + NodeTemplate networkNodeTemplate = DataModelUtil + .getNodeTemplate(translateTo.getServiceTemplate(), translatedNetworkId.get()); + + Map> subNetMap = + (Map>) networkNodeTemplate.getProperties().get("subnets"); + if (subNetMap == null) { + subNetMap = new HashMap<>(); + networkNodeTemplate.getProperties().put("subnets", subNetMap); + TranslatorHeatToToscaPropertyConverter + .setSimpleProperty(translateTo.getServiceTemplate(),translateTo.getTranslatedId(), + translateTo.getResource().getProperties(), + translateTo.getHeatFileName(), translateTo.getResource().getType(), + translateTo.getHeatOrchestrationTemplate(), translateTo.getContext(), + networkNodeTemplate.getProperties(), "enable_dhcp", + ToscaConstants.DHCP_ENABLED_PROPERTY_NAME, networkNodeTemplate); //dhcp_enabled + TranslatorHeatToToscaPropertyConverter + .setSimpleProperty(translateTo.getServiceTemplate(),translateTo.getTranslatedId(), + translateTo.getResource().getProperties(), + translateTo.getHeatFileName(), translateTo.getResource().getType(), + translateTo.getHeatOrchestrationTemplate(), translateTo.getContext(), + networkNodeTemplate.getProperties(), "ip_version", null, networkNodeTemplate); + handleDhcpProperty(translateTo, networkNodeTemplate); + } + + Map properties; + properties = TranslatorHeatToToscaPropertyConverter + .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(),translateTo. + getResourceId(),translateTo.getResource().getProperties(), null, + translateTo.getHeatFileName(), translateTo.getHeatOrchestrationTemplate(), + translateTo.getResource().getType(), networkNodeTemplate, translateTo.getContext()); + + subNetMap.put(translateTo.getResourceId(), properties); + } + + mdcDataDebugMessage.debugExitMessage(null, null); + } + + @Override + protected String generateTranslatedId(TranslateTo translateTo) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + Optional subnetNetwork = getAttachedNetworkResource(translateTo); + + if (!subnetNetwork.isPresent() || !subnetNetwork.get().isGetResource()) { + logger.warn("Heat resource: '" + translateTo.getResourceId() + "' with type: '" + + translateTo.getResource().getType() + + "' include 'network_id/'network'' property without 'get_resource' function, therefore" + + " this resource will be ignored in TOSCA translation."); + + mdcDataDebugMessage.debugExitMessage(null, null); + return null; + } + + mdcDataDebugMessage.debugExitMessage(null, null); + return (String) subnetNetwork.get().getTranslatedId(); + } + + private void handleDhcpProperty(TranslateTo translateTo, NodeTemplate networkNodeTemplate) { + mdcDataDebugMessage.debugEntryMessage(null, null); + + Object dhcpEnabled = + networkNodeTemplate.getProperties().get(ToscaConstants.DHCP_ENABLED_PROPERTY_NAME); + if (dhcpEnabled instanceof Map) { + Object dhcpEnabledParameterName = + ((Map) dhcpEnabled).get(ToscaFunctions.GET_INPUT.getDisplayName()); + if (dhcpEnabledParameterName != null) { + ParameterDefinition dhcpParameterDefinition = null; + if (translateTo.getServiceTemplate().getTopology_template().getInputs() != null) { + dhcpParameterDefinition = + translateTo.getServiceTemplate().getTopology_template().getInputs() + .get(dhcpEnabledParameterName); + } + if (dhcpParameterDefinition == null) { + logger.warn("Missing input parameter " + dhcpEnabledParameterName); + } else { + Object defaultVal = dhcpParameterDefinition.get_default(); + if (defaultVal != null) { + try { + Boolean booleanValue = HeatBoolean.eval(defaultVal); + dhcpParameterDefinition.set_default(booleanValue); + } catch (CoreException coreException) { + //if value is not valid value for boolean set with dhcp_enabled default value = true + dhcpParameterDefinition.set_default(true); + logger.warn("Parameter '" + dhcpEnabledParameterName + "' used for " + + ToscaConstants.DHCP_ENABLED_PROPERTY_NAME + + " boolean property, but it's value is not a valid boolean value, therefore " + + ToscaConstants.DHCP_ENABLED_PROPERTY_NAME + + " property will be set with default value of 'true'."); + } + dhcpParameterDefinition.setType(PropertyType.BOOLEAN.getDisplayName()); + } + } + } + } + + mdcDataDebugMessage.debugExitMessage(null, null); + } + + private Optional getAttachedNetworkResource(TranslateTo translateTo) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + Optional subnetNetwork = Optional.empty(); + Optional attachedNetworkId = + HeatToToscaUtil.extractAttachedResourceId(translateTo, "network_id"); + if (!attachedNetworkId.isPresent()) { + Optional attachedNetwork = + HeatToToscaUtil.extractAttachedResourceId(translateTo, "network"); + if (!attachedNetwork.isPresent()) { + MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, + LoggerTragetServiceName.GET_RESOURCE, ErrorLevel.ERROR.name(), + LoggerErrorCode.DATA_ERROR.getErrorCode(), + LoggerErrorDescription.MISSING_MANDATORY_PROPERTY); + throw new CoreException( + new MissingMandatoryPropertyErrorBuilder("network_id/'network'").build()); + } else { + subnetNetwork = attachedNetwork; + } + } else { + subnetNetwork = attachedNetworkId; + } + + mdcDataDebugMessage.debugExitMessage(null, null); + return subnetNetwork; + } +} + + diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNovaServerGroupsImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNovaServerGroupsImpl.java new file mode 100644 index 0000000000..875903f8a2 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNovaServerGroupsImpl.java @@ -0,0 +1,208 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; + +import org.apache.commons.collections4.CollectionUtils; +import org.openecomp.sdc.heat.datatypes.model.Resource; +import org.openecomp.sdc.tosca.datatypes.ToscaGroupType; +import org.openecomp.sdc.tosca.datatypes.ToscaPolicyType; +import org.openecomp.sdc.tosca.datatypes.model.GroupDefinition; +import org.openecomp.sdc.tosca.datatypes.model.PolicyDefinition; +import org.openecomp.sdc.tosca.datatypes.ToscaTopologyTemplateElements; +import org.openecomp.sdc.tosca.services.DataModelUtil; +import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; +import org.openecomp.sdc.translator.services.heattotosca.mapping.TranslatorHeatToToscaPropertyConverter; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + + +public class ResourceTranslationNovaServerGroupsImpl extends ResourceTranslationBase { + private static final String AFFINITY = "affinity"; + private static final String ANTI_AFFINITY = "anti-affinity"; + private static List supportedPolicies = Arrays.asList(AFFINITY, ANTI_AFFINITY); + + @Override + protected String generateTranslatedId(TranslateTo translateTo) { + return isEssentialRequirementsValid(translateTo) ? getTranslatedGroupId( + translateTo.getResourceId()) : null; + } + + @Override + protected boolean isEssentialRequirementsValid(TranslateTo translateTo) { + return validatePolicyType(translateTo); + } + + @Override + protected Optional getTranslatedToscaTopologyElement( + TranslateTo translateTo) { + if (isEssentialRequirementsValid(translateTo)) { + return Optional.of(ToscaTopologyTemplateElements.GROUP); + } else { + return Optional.empty(); + } + } + + private boolean validatePolicyType(TranslateTo translateTo) { + Map properties = translateTo.getResource().getProperties(); + if (Objects.isNull(properties) || Objects.isNull(properties.get("policies"))) { + return true; + } + + Object policies = properties.get("policies"); + if (!(policies instanceof List)) { + return false; + } + + for (Object policy : (List) policies) { + if (!isValidPolicyType(policy, translateTo.getResourceId(), translateTo.getResource())) { + return false; + } + } + return true; + } + + private boolean isValidPolicyType(Object policy, String resourceId, Resource resource) { + if (!(policy instanceof String)) { + return false; + } + + if ((policy instanceof String) && !supportedPolicies.contains(policy)) { + logger.warn("Resource '" + resourceId + "'(" + resource.getType() + + ") contains unsupported policy '" + policy.toString() + + "'. This resource is been ignored during the translation"); + return false; + } + + return true; + } + + @Override + protected void translate(TranslateTo translateTo) { + mdcDataDebugMessage.debugEntryMessage(null, null); + + String resourceId = translateTo.getResourceId(); + List toscaPolicyTypes = getToscaPolicies(translateTo.getResource(), resourceId); + if (!CollectionUtils.isEmpty(toscaPolicyTypes)) { + String translatedGroupId = addGroupToTopology(translateTo, resourceId); + addPoliciesToTopology(translateTo, translatedGroupId, toscaPolicyTypes); + } + + mdcDataDebugMessage.debugExitMessage(null, null); + } + + private void addPoliciesToTopology(TranslateTo translateTo, String policyTargetEntityId, + List toscaPolicyTypes) { + mdcDataDebugMessage.debugEntryMessage(null, null); + + logger.info("******** Start creating policies for resource '%s' ********", + translateTo.getResourceId()); + for (int i = 0; i < toscaPolicyTypes.size(); i++) { + String policy = toscaPolicyTypes.get(i); + logger.info("******** Creating policy '%s' ********", policy); + PolicyDefinition policyDefinition = new PolicyDefinition(); + policyDefinition.setType(policy); + policyDefinition.setTargets(Arrays.asList(policyTargetEntityId)); + policyDefinition.setProperties(TranslatorHeatToToscaPropertyConverter + .getToscaPropertiesSimpleConversion(translateTo.getServiceTemplate(), + translateTo.getResourceId(),translateTo.getResource().getProperties(), + policyDefinition.getProperties(), translateTo.getHeatFileName(), + translateTo.getHeatOrchestrationTemplate(), translateTo.getResource().getType(), + policyDefinition, translateTo.getContext())); + policyDefinition.getProperties().put( + policy.equals(ToscaPolicyType.PLACEMENT_ANTILOCATE) ? "container_type" + : AFFINITY, "host"); + String policyId = getTranslatedPolicyId(translateTo, toscaPolicyTypes, i); + DataModelUtil + .addPolicyDefinition(translateTo.getServiceTemplate(), policyId, policyDefinition); + logger.info("******** Policy '%s' created ********", policy); + } + + logger + .info("******** All policies for resource '%s' created successfully ********", + translateTo.getResourceId()); + + mdcDataDebugMessage.debugExitMessage(null, null); + } + + private String getTranslatedPolicyId(TranslateTo translateTo, List toscaPolicyTypes, + int policyIndex) { + mdcDataDebugMessage.debugEntryMessage(null, null); + + mdcDataDebugMessage.debugExitMessage(null, null); + return translateTo.getResourceId() + (toscaPolicyTypes.size() > 1 ? policyIndex : "") + + "_policy"; + } + + private String addGroupToTopology(TranslateTo translateTo, String resourceId) { + mdcDataDebugMessage.debugEntryMessage(null, null); + + logger.info("******** Start creating group for resource '%s' ********", resourceId); + GroupDefinition group = new GroupDefinition(); + group.setMembers(new ArrayList<>()); + group.setType(ToscaGroupType.NATIVE_ROOT); + String translatedGroupId = getTranslatedGroupId(resourceId); + DataModelUtil + .addGroupDefinitionToTopologyTemplate(translateTo.getServiceTemplate(), + translatedGroupId, group); + logger.info("******** Creating group '%s' for resource '%s' ********", resourceId, resourceId); + + mdcDataDebugMessage.debugExitMessage(null, null); + return translatedGroupId; + } + + private String getTranslatedGroupId(String resourceId) { + return resourceId + "_group"; + } + + private List getToscaPolicies(Resource resource, String resourceId) { + mdcDataDebugMessage.debugEntryMessage(null, null); + + Map properties = resource.getProperties(); + if (Objects.isNull(properties) || Objects.isNull(properties.get("policies"))) { + return Arrays.asList(ToscaPolicyType.PLACEMENT_ANTILOCATE); + } + + List policies = (List) properties.get("policies"); + List retList = new ArrayList<>(); + policies.forEach(policy -> { + if (isValidPolicyType(policy, resourceId, resource)) { + retList.add(getToscaPolicyByHotPolicy(policy)); + } + }); + + mdcDataDebugMessage.debugExitMessage(null, null); + return retList; + } + + private String getToscaPolicyByHotPolicy(Object policy) { + if (Objects.equals(policy, AFFINITY)) { + return ToscaPolicyType.PLACEMENT_COLOCATE; + } else { + return ToscaPolicyType.PLACEMENT_ANTILOCATE; + } + } + +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNovaServerImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNovaServerImpl.java new file mode 100644 index 0000000000..499ac5f80a --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationNovaServerImpl.java @@ -0,0 +1,546 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; + +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.collections4.MapUtils; +import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate; +import org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes; +import org.openecomp.sdc.heat.datatypes.model.Resource; +import org.openecomp.sdc.heat.services.HeatConstants; +import org.openecomp.sdc.logging.api.Logger; +import org.openecomp.sdc.logging.api.LoggerFactory; +import org.openecomp.sdc.tosca.datatypes.ToscaCapabilityType; +import org.openecomp.sdc.tosca.datatypes.ToscaNodeType; +import org.openecomp.sdc.tosca.datatypes.ToscaRelationshipType; +import org.openecomp.sdc.tosca.datatypes.model.GroupDefinition; +import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; +import org.openecomp.sdc.tosca.datatypes.model.NodeType; +import org.openecomp.sdc.tosca.datatypes.model.RelationshipTemplate; +import org.openecomp.sdc.tosca.datatypes.model.RequirementAssignment; +import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; +import org.openecomp.sdc.tosca.services.DataModelUtil; +import org.openecomp.sdc.tosca.services.ToscaConstants; +import org.openecomp.sdc.translator.datatypes.heattotosca.AttachedResourceId; +import org.openecomp.sdc.translator.datatypes.heattotosca.PropertyRegexMatcher; +import org.openecomp.sdc.translator.datatypes.heattotosca.TranslationContext; +import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; +import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslatedHeatResource; + +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.ComputeTemplateConsolidationData; +import org.openecomp.sdc.translator.services.heattotosca.ConfigConstants; +import org.openecomp.sdc.translator.services.heattotosca.ConsolidationDataUtil; +import org.openecomp.sdc.translator.services.heattotosca.Constants; +import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; +import org.openecomp.sdc.translator.services.heattotosca.NameExtractor; +import org.openecomp.sdc.translator.services.heattotosca.ResourceTranslationFactory; + +import org.openecomp.sdc.translator.services.heattotosca.mapping.TranslatorHeatToToscaPropertyConverter; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collections; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + + +public class ResourceTranslationNovaServerImpl extends ResourceTranslationBase { + protected static Logger logger = + (Logger) LoggerFactory.getLogger(ResourceTranslationNovaServerImpl.class); + + @Override + protected void translate(TranslateTo translateTo) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + TranslationContext context = translateTo.getContext(); + Map properties = translateTo.getResource().getProperties(); + String heatFileName = translateTo.getHeatFileName(); + + ServiceTemplate serviceTemplate = translateTo.getServiceTemplate(); + String nodeTypeRef = createLocalNodeType(serviceTemplate, translateTo.getResource(), + translateTo.getResourceId(), translateTo.getTranslatedId(), context); + + //create compute in consolidation data + ConsolidationDataUtil.getComputeTemplateConsolidationData(context, serviceTemplate, + nodeTypeRef, translateTo.getTranslatedId()); + + NodeTemplate novaNodeTemplate = new NodeTemplate(); + novaNodeTemplate.setType(nodeTypeRef); + HeatOrchestrationTemplate heatOrchestrationTemplate = + translateTo.getHeatOrchestrationTemplate(); + novaNodeTemplate.setProperties(TranslatorHeatToToscaPropertyConverter + .getToscaPropertiesSimpleConversion(serviceTemplate, translateTo.getResourceId(), + properties, novaNodeTemplate.getProperties(), heatFileName, + heatOrchestrationTemplate, translateTo.getResource().getType(), + novaNodeTemplate, context)); + + HeatToToscaUtil.mapBoolean(novaNodeTemplate, HeatToToscaUtil + .getToscaPropertyName(translateTo, HeatConstants.CONFIG_DRIVE_PROPERTY_NAME)); + + manageNovaServerNetwork(translateTo, novaNodeTemplate); + manageNovaServerBlockDeviceMapping(translateTo, novaNodeTemplate); + manageNovaServerGroupMapping(translateTo, context, properties, heatFileName, serviceTemplate, + novaNodeTemplate, heatOrchestrationTemplate); + DataModelUtil.addNodeTemplate(serviceTemplate, translateTo.getTranslatedId(), novaNodeTemplate); + + mdcDataDebugMessage.debugExitMessage(null, null); + } + + private void manageNovaServerGroupMapping(TranslateTo translateTo, TranslationContext context, + Map properties, String heatFileName, + ServiceTemplate serviceTemplate, + NodeTemplate novaNodeTemplate, + HeatOrchestrationTemplate heatOrchestrationTemplate) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + if (isSchedulerHintsPropExist(properties)) { + Object schedulerHints = properties.get("scheduler_hints"); + if (schedulerHints instanceof Map) { + addServerGroupHintsToPoliciesGroups(translateTo, context, heatFileName, serviceTemplate, + novaNodeTemplate, heatOrchestrationTemplate, (Map) schedulerHints); + } else { + logger.warn("'scheduler_hints' property of resource '" + translateTo.getResourceId() + + "' is not valid. This property should be a map"); + } + } + + mdcDataDebugMessage.debugExitMessage(null, null); + } + + private void addServerGroupHintsToPoliciesGroups(TranslateTo translateTo, + TranslationContext context, String heatFileName, + ServiceTemplate serviceTemplate, + NodeTemplate novaNodeTemplate, + HeatOrchestrationTemplate + heatOrchestrationTemplate, + Map schedulerHints) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + for (Object hint : schedulerHints.values()) { + Optional attachedResourceId = HeatToToscaUtil + .extractAttachedResourceId(heatFileName, heatOrchestrationTemplate, context, hint); + if (attachedResourceId.isPresent()) { + AttachedResourceId serverGroupResourceId = attachedResourceId.get(); + Object serverGroupResourceToTranslate = serverGroupResourceId.getEntityId(); + if (serverGroupResourceId.isGetResource()) { + boolean isHintOfTypeNovaServerGroup = + isHintOfTypeNovaServerGroup(heatOrchestrationTemplate, + serverGroupResourceToTranslate); + if (isHintOfTypeNovaServerGroup) { + addNovaServerToPolicyGroup(translateTo, context, heatFileName, serviceTemplate, + heatOrchestrationTemplate, (String) serverGroupResourceToTranslate, + novaNodeTemplate); + } + } else if (serverGroupResourceId.isGetParam() + && serverGroupResourceToTranslate instanceof String) { + TranslatedHeatResource + translatedServerGroupResource = + context.getHeatSharedResourcesByParam().get(serverGroupResourceToTranslate); + if (Objects.nonNull(translatedServerGroupResource) + && !HeatToToscaUtil.isHeatFileNested(translateTo, translateTo.getHeatFileName()) + && isResourceTypeServerGroup(translatedServerGroupResource)) { + Map groups = + serviceTemplate.getTopology_template().getGroups(); + if(MapUtils.isNotEmpty(groups) && Objects.nonNull(groups.get(translatedServerGroupResource + .getTranslatedId()))) { + groups + .get(translatedServerGroupResource.getTranslatedId()).getMembers() + .add(translateTo.getTranslatedId()); + //Add group Id to compute consolidation data + updateComputeConsolidationDataGroup(translateTo, novaNodeTemplate, + translatedServerGroupResource.getTranslatedId()); + } + } + } + } + } + + mdcDataDebugMessage.debugExitMessage(null, null); + } + + private boolean isResourceTypeServerGroup(TranslatedHeatResource translatedServerGroupResource) { + return translatedServerGroupResource.getHeatResource().getType().equals(HeatResourcesTypes.NOVA_SERVER_GROUP_RESOURCE_TYPE.getHeatResource()); + } + + private void updateComputeConsolidationDataGroup(TranslateTo translateTo, + NodeTemplate novaNodeTemplate, + String groupId) { + TranslationContext translationContext = translateTo.getContext(); + ServiceTemplate serviceTemplate = translateTo.getServiceTemplate(); + ComputeTemplateConsolidationData computeTemplateConsolidationData = ConsolidationDataUtil + .getComputeTemplateConsolidationData(translationContext, serviceTemplate, + novaNodeTemplate.getType(), + translateTo.getTranslatedId()); + ConsolidationDataUtil.updateGroupIdInConsolidationData(computeTemplateConsolidationData, + groupId); + } + + private boolean isHintOfTypeNovaServerGroup(HeatOrchestrationTemplate heatOrchestrationTemplate, + Object resourceToTranslate) { + return heatOrchestrationTemplate.getResources().get(resourceToTranslate).getType() + .equals(HeatResourcesTypes.NOVA_SERVER_GROUP_RESOURCE_TYPE.getHeatResource()); + } + + private void addNovaServerToPolicyGroup(TranslateTo translateTo, TranslationContext context, + String heatFileName, ServiceTemplate serviceTemplate, + HeatOrchestrationTemplate heatOrchestrationTemplate, + String resourceToTranslate, + NodeTemplate novaNodeTemplate) { + mdcDataDebugMessage.debugEntryMessage(null, null); + + Resource serverGroup = + HeatToToscaUtil.getResource(heatOrchestrationTemplate, resourceToTranslate, heatFileName); + Optional serverGroupTranslatedId = ResourceTranslationFactory.getInstance(serverGroup) + .translateResource(heatFileName, serviceTemplate, heatOrchestrationTemplate, serverGroup, + resourceToTranslate, context); + if (serverGroupTranslatedId.isPresent()) { + serviceTemplate.getTopology_template().getGroups().get(serverGroupTranslatedId.get()) + .getMembers().add(translateTo.getTranslatedId()); + updateComputeConsolidationDataGroup(translateTo, novaNodeTemplate, + serverGroupTranslatedId.get()); + + } + mdcDataDebugMessage.debugExitMessage(null, null); + } + + private boolean isSchedulerHintsPropExist(Map properties) { + return !MapUtils.isEmpty(properties) && Objects.nonNull(properties.get("scheduler_hints")); + } + + private void manageNovaServerBlockDeviceMapping(TranslateTo translateTo, + NodeTemplate novaNodeTemplate) { + mdcDataDebugMessage.debugEntryMessage(null, null); + String heatFileName = translateTo.getHeatFileName(); + TranslationContext context = translateTo.getContext(); + ServiceTemplate serviceTemplate = translateTo.getServiceTemplate(); + Resource resource = translateTo.getResource(); + String resourceId = translateTo.getResourceId(); + String novaServerTranslatedId = translateTo.getTranslatedId(); + HeatOrchestrationTemplate heatOrchestrationTemplate = translateTo + .getHeatOrchestrationTemplate(); + List> blockDeviceMappingList = getBlockDeviceMappingList(resource); + if (CollectionUtils.isEmpty(blockDeviceMappingList)) { + return; + } + + Object volumeIdObject; + Object snapshotIdObject; + String volumeResourceId; + int index = 0; + for (Map blockDeviceMapping : blockDeviceMappingList) { + volumeIdObject = blockDeviceMapping.get("volume_id"); + snapshotIdObject = blockDeviceMapping.get("snapshot_id"); + + if (volumeIdObject == null && snapshotIdObject == null) { + logger.warn("Resource '" + resourceId + + "' has block_device_mapping property with empty/missing volume_id and snapshot_id " + + "properties. Entry number " + + (index + 1) + ", this entry will be ignored in TOSCA translation."); + index++; + continue; + } + if (volumeIdObject == null) { + Optional attachedSnapshotId = HeatToToscaUtil + .extractAttachedResourceId(heatFileName, heatOrchestrationTemplate, context, + snapshotIdObject); + if (attachedSnapshotId.isPresent()) { + volumeResourceId = novaServerTranslatedId + "_" + attachedSnapshotId.get().getEntityId(); + String deviceName = (String) blockDeviceMapping.get("device_name"); + String relationshipId = novaServerTranslatedId + "_" + index; + + createVolumeAttachesToRelationship(serviceTemplate, deviceName, novaServerTranslatedId, + volumeResourceId, relationshipId); + createCinderVolumeNodeTemplate(serviceTemplate, translateTo.getResourceId(), + volumeResourceId, heatFileName, blockDeviceMapping, heatOrchestrationTemplate, + context); + connectNovaServerToVolume(novaNodeTemplate, volumeResourceId, relationshipId, + translateTo); + } + } else { + Optional attachedVolumeId = HeatToToscaUtil + .extractAttachedResourceId(heatFileName, heatOrchestrationTemplate, context, + volumeIdObject); + if (attachedVolumeId.isPresent() && attachedVolumeId.get().isGetResource()) { + connectNovaServerToVolume(novaNodeTemplate, + (String) attachedVolumeId.get().getTranslatedId(), null, translateTo); + } + } + index++; + } + + mdcDataDebugMessage.debugExitMessage(null, null); + } + + private void connectNovaServerToVolume(NodeTemplate novaNodeTemplate, String volumeResourceId, + String relationshipId, TranslateTo translateTo) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + RequirementAssignment requirementAssignment = new RequirementAssignment(); + requirementAssignment.setCapability(ToscaCapabilityType.NATIVE_ATTACHMENT); + requirementAssignment.setNode(volumeResourceId); + if (relationshipId != null) { + requirementAssignment.setRelationship(relationshipId); + } else { + requirementAssignment + .setRelationship(ToscaRelationshipType.NATIVE_ATTACHES_TO); + } + DataModelUtil + .addRequirementAssignment(novaNodeTemplate, ToscaConstants.LOCAL_STORAGE_REQUIREMENT_ID, + requirementAssignment); + //Add volume consolidation data + ConsolidationDataUtil.updateComputeConsolidationDataVolumes(translateTo, novaNodeTemplate + .getType(), translateTo.getTranslatedId(), ToscaConstants.LOCAL_STORAGE_REQUIREMENT_ID, + requirementAssignment); + + mdcDataDebugMessage.debugExitMessage(null, null); + } + + private void createCinderVolumeNodeTemplate(ServiceTemplate serviceTemplate, String resourceId, + String volumeResourceId, String heatFileName, + Map blockDeviceMapping, + HeatOrchestrationTemplate heatOrchestrationTemplate, + TranslationContext context) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + NodeTemplate cinderVolumeNodeTemplate = new NodeTemplate(); + cinderVolumeNodeTemplate.setType(ToscaNodeType.CINDER_VOLUME); + cinderVolumeNodeTemplate.setProperties(TranslatorHeatToToscaPropertyConverter + .getToscaPropertiesSimpleConversion(serviceTemplate, resourceId, blockDeviceMapping, null, + heatFileName, heatOrchestrationTemplate, + HeatResourcesTypes.CINDER_VOLUME_RESOURCE_TYPE.getHeatResource(), + cinderVolumeNodeTemplate, context)); + DataModelUtil.addNodeTemplate(serviceTemplate, volumeResourceId, cinderVolumeNodeTemplate); + + mdcDataDebugMessage.debugExitMessage(null, null); + } + + private void createVolumeAttachesToRelationship(ServiceTemplate serviceTemplate, + String deviceName, String novaServerTranslatedId, + String volumeId, String relationshipId) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + RelationshipTemplate relationshipTemplate = new RelationshipTemplate(); + relationshipTemplate.setType(ToscaRelationshipType.CINDER_VOLUME_ATTACHES_TO); + Map properties = new HashMap<>(); + properties.put("instance_uuid", novaServerTranslatedId); + properties.put("volume_id", volumeId); + if (deviceName != null) { + properties.put("device", deviceName); + } + relationshipTemplate.setProperties(properties); + + DataModelUtil.addRelationshipTemplate(serviceTemplate, relationshipId, relationshipTemplate); + + mdcDataDebugMessage.debugExitMessage(null, null); + } + + private List> getBlockDeviceMappingList(Resource resource) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + if (Objects.isNull(resource.getProperties())) { + return Collections.emptyList(); + } + List> blockDeviceMappingList = + (List>) resource.getProperties().get("block_device_mapping"); + List> blockDeviceMappingV2List = + (List>) resource.getProperties().get("block_device_mapping_v2"); + + if (blockDeviceMappingList != null && blockDeviceMappingV2List != null) { + blockDeviceMappingList.addAll(blockDeviceMappingV2List); + } else if (CollectionUtils.isEmpty(blockDeviceMappingList) + && CollectionUtils.isEmpty(blockDeviceMappingV2List)) { + + mdcDataDebugMessage.debugExitMessage(null, null); + return null; + + } else { + blockDeviceMappingList = + blockDeviceMappingList != null ? blockDeviceMappingList : blockDeviceMappingV2List; + } + + mdcDataDebugMessage.debugExitMessage(null, null); + return blockDeviceMappingList; + } + + private void manageNovaServerNetwork(TranslateTo translateTo, + NodeTemplate novaNodeTemplate) { + + + String heatFileName = translateTo.getHeatFileName(); + ServiceTemplate serviceTemplate = translateTo.getServiceTemplate(); + HeatOrchestrationTemplate heatOrchestrationTemplate = translateTo + .getHeatOrchestrationTemplate(); + Resource resource = translateTo.getResource(); + String translatedId = translateTo.getTranslatedId(); + TranslationContext context = translateTo.getContext(); + + mdcDataDebugMessage.debugEntryMessage(null, null); + + if (resource.getProperties() == null) { + return; + } + List> heatNetworkList = + (List>) resource.getProperties().get("networks"); + + if (CollectionUtils.isEmpty(heatNetworkList)) { + return; + } + + for (Map heatNetwork : heatNetworkList) { + getOrTranslatePortTemplate(translateTo, heatNetwork.get( + Constants.PORT_PROPERTY_NAME), translatedId, novaNodeTemplate); + } + + mdcDataDebugMessage.debugExitMessage(null, null); + + } + + private void getOrTranslatePortTemplate(TranslateTo translateTo, + Object port, + String novaServerResourceId, + NodeTemplate novaNodeTemplate) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + String heatFileName = translateTo.getHeatFileName(); + HeatOrchestrationTemplate heatOrchestrationTemplate = translateTo + .getHeatOrchestrationTemplate(); + ServiceTemplate serviceTemplate = translateTo.getServiceTemplate(); + TranslationContext context = translateTo.getContext(); + + Optional attachedPortId = HeatToToscaUtil + .extractAttachedResourceId(heatFileName, heatOrchestrationTemplate, context, port); + + if (!attachedPortId.isPresent()) { + return; + } + + if (attachedPortId.get().isGetResource()) { + String resourceId = (String) attachedPortId.get().getEntityId(); + Resource portResource = + HeatToToscaUtil.getResource(heatOrchestrationTemplate, resourceId, heatFileName); + if (!Arrays.asList(HeatResourcesTypes.NEUTRON_PORT_RESOURCE_TYPE.getHeatResource(), + HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_MACHINE_INTERFACE_RESOURCE_TYPE.getHeatResource()) + .contains(portResource.getType())) { + logger.warn("NovaServer connect to port resource with id : " + resourceId + " and type : " + + portResource.getType() + + ". This resource type is not supported, therefore the connection to the port is " + + "ignored. Supported types are: " + + HeatResourcesTypes.NEUTRON_PORT_RESOURCE_TYPE.getHeatResource() + ", " + + HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_MACHINE_INTERFACE_RESOURCE_TYPE + .getHeatResource()); + mdcDataDebugMessage.debugExitMessage(null, null); + return; + } else if (HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_MACHINE_INTERFACE_RESOURCE_TYPE + .getHeatResource().equals(portResource.getType())) { + Map properties = portResource.getProperties(); + if (!MapUtils.isEmpty(properties) && Objects.nonNull(properties.get("port_tuple_refs"))) { + novaNodeTemplate.getProperties().put("contrail_service_instance_ind", true); + } + } + Optional translatedPortId = ResourceTranslationFactory.getInstance(portResource) + .translateResource(heatFileName, serviceTemplate, heatOrchestrationTemplate, portResource, + resourceId, context); + if (translatedPortId.isPresent()) { + NodeTemplate portNodeTemplate = + DataModelUtil.getNodeTemplate(serviceTemplate, translatedPortId.get()); + HeatToToscaUtil.addBindingReqFromPortToCompute(novaServerResourceId, portNodeTemplate); + + // Add ports + ConsolidationDataUtil.updatePortInConsolidationData(translateTo, novaNodeTemplate.getType(), + translatedPortId.get()); + } else { + logger.warn("NovaServer connect to port resource with id : " + resourceId + " and type : " + + portResource.getType() + + ". This resource type is not supported, therefore the connection to the port is " + + "ignored."); + } + } + + mdcDataDebugMessage.debugExitMessage(null, null); + } + + + private String createLocalNodeType(ServiceTemplate serviceTemplate, Resource resource, String + resourceId, + String translatedId, TranslationContext context) { + mdcDataDebugMessage.debugEntryMessage(null, null); + NameExtractor nodeTypeNameExtractor = context.getNameExtractorImpl(resource.getType()); + String nodeTypeName = + nodeTypeNameExtractor.extractNodeTypeName(resource, resourceId, translatedId); + + if (!isNodeTypeCreated(serviceTemplate, nodeTypeName)) { + DataModelUtil.addNodeType(serviceTemplate, nodeTypeName, createNodeType()); + } + + mdcDataDebugMessage.debugExitMessage(null, null); + return nodeTypeName; + } + + /** + * Get property Regx matcher list. + * + * @return Regex exprission per nova resource property, while nova node type name is consider when + * setting the name value. + */ + public List getPropertyRegexMatchersForNovaNodeType() { + List propertyRegexMatchers = new ArrayList<>(); + propertyRegexMatchers + .add(new PropertyRegexMatcher(Constants.NAME_PROPERTY_NAME, + Arrays.asList(".+_name$", ".+_names$", ".+_name_[0-9]+"), "_name")); + propertyRegexMatchers + .add(new PropertyRegexMatcher("image", Collections.singletonList(".+_image_name$"), + "_image_name")); + propertyRegexMatchers + .add(new PropertyRegexMatcher("flavor", Collections.singletonList(".+_flavor_name$"), + "_flavor_name")); + return propertyRegexMatchers; + } + + private boolean isNodeTypeCreated(ServiceTemplate serviceTemplate, String nodeTypeName) { + return !MapUtils.isEmpty(serviceTemplate.getNode_types()) + && Objects.nonNull(serviceTemplate.getNode_types().get(nodeTypeName)); + } + + private NodeType createNodeType() { + NodeType nodeType = new NodeType(); + nodeType.setDerived_from(ToscaNodeType.NOVA_SERVER); + return nodeType; + } +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationResourceGroupImpl.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationResourceGroupImpl.java new file mode 100644 index 0000000000..5d25c7ef25 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/ResourceTranslationResourceGroupImpl.java @@ -0,0 +1,253 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; + +import org.openecomp.sdc.common.errors.CoreException; +import org.openecomp.sdc.common.utils.CommonUtil; +import org.openecomp.sdc.datatypes.error.ErrorLevel; +import org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes; +import org.openecomp.sdc.heat.datatypes.model.Resource; +import org.openecomp.sdc.heat.services.HeatConstants; +import org.openecomp.sdc.logging.context.impl.MdcDataErrorMessage; +import org.openecomp.sdc.logging.types.LoggerConstants; +import org.openecomp.sdc.logging.types.LoggerErrorCode; +import org.openecomp.sdc.logging.types.LoggerErrorDescription; +import org.openecomp.sdc.logging.types.LoggerTragetServiceName; +import org.openecomp.sdc.tosca.datatypes.ToscaFunctions; +import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; +import org.openecomp.sdc.tosca.services.DataModelUtil; +import org.openecomp.sdc.tosca.services.ToscaConstants; +import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; +import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; +import org.openecomp.sdc.translator.services.heattotosca.ResourceTranslationFactory; +import org.openecomp.sdc.translator.services.heattotosca.errors.InvalidPropertyValueErrorBuilder; +import org.openecomp.sdc.translator.services.heattotosca.mapping.TranslatorHeatToToscaPropertyConverter; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; +import java.util.Optional; + +public class ResourceTranslationResourceGroupImpl extends ResourceTranslationBase { + + @Override + protected void translate(TranslateTo translateTo) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + final String heatFileName = translateTo.getHeatFileName(); + Object resourceDef = + translateTo.getResource().getProperties().get(HeatConstants.RESOURCE_DEF_PROPERTY_NAME); + Resource nestedResource = new Resource(); + Object typeDefinition = ((Map) resourceDef).get("type"); + if (!(typeDefinition instanceof String)) { + logger.warn("Resource '" + translateTo.getResourceId() + "' of type'" + + HeatResourcesTypes.RESOURCE_GROUP_RESOURCE_TYPE.getHeatResource() + + "' with resourceDef which is not pointing to nested heat file is not supported and " + + "will be ignored in the translation "); + return; + } + String type = (String) typeDefinition; + if (!HeatToToscaUtil.isYmlFileType(type)) { + logger.warn("Resource '" + translateTo.getResourceId() + "' of type'" + + HeatResourcesTypes.RESOURCE_GROUP_RESOURCE_TYPE.getHeatResource() + + "' with resourceDef which is not pointing to nested heat file is not supported and " + + "will be ignored in the translation "); + + mdcDataDebugMessage.debugExitMessage(null, null); + return; + } + + nestedResource.setType(type); + nestedResource.setProperties((Map) ((Map) resourceDef).get("properties")); + nestedResource.setMetadata(((Map) resourceDef).get("metadata")); + + Optional substitutionNodeTemplateId = + ResourceTranslationFactory.getInstance(nestedResource) + .translateResource(heatFileName, translateTo.getServiceTemplate(), + translateTo.getHeatOrchestrationTemplate(), nestedResource, + translateTo.getResourceId(), translateTo.getContext()); + if (substitutionNodeTemplateId.isPresent()) { + NodeTemplate substitutionNodeTemplate = DataModelUtil + .getNodeTemplate(translateTo.getServiceTemplate(), substitutionNodeTemplateId.get()); + Map serviceTemplateFilter = (Map) substitutionNodeTemplate.getProperties() + .get(ToscaConstants.SERVICE_TEMPLATE_FILTER_PROPERTY_NAME); + + populateServiceTemplateFilterProperties(translateTo, substitutionNodeTemplate, + serviceTemplateFilter); + handlingIndexVar(translateTo, substitutionNodeTemplate); + DataModelUtil + .addNodeTemplate(translateTo.getServiceTemplate(), substitutionNodeTemplateId.get(), + substitutionNodeTemplate); + } + + mdcDataDebugMessage.debugExitMessage(null, null); + } + + private void handlingIndexVar(TranslateTo translateTo, NodeTemplate substitutionNodeTemplate) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + String indexVarValue = getIndexVarValue(translateTo); + replacePropertiesIndexVarValue(indexVarValue, substitutionNodeTemplate.getProperties()); + + mdcDataDebugMessage.debugExitMessage(null, null); + } + + private Map getNewIndexVarValue() { + final Map newIndexVarValue = new HashMap<>(); + List indexVarValList = new ArrayList<>(); + indexVarValList.add(ToscaConstants.MODELABLE_ENTITY_NAME_SELF); + indexVarValList.add(ToscaConstants.SERVICE_TEMPLATE_FILTER_PROPERTY_NAME); + indexVarValList.add(ToscaConstants.INDEX_VALUE_PROPERTY_NAME); + newIndexVarValue.put(ToscaFunctions.GET_PROPERTY.getDisplayName(), indexVarValList); + return newIndexVarValue; + } + + private void replacePropertiesIndexVarValue(String indexVarValue, + Map properties) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + if (properties == null || properties.isEmpty()) { + return; + } + + for (Map.Entry propertyEntry : properties.entrySet()) { + Object propertyValue = propertyEntry.getValue(); + Object newPropertyValue = getUpdatedPropertyValueWithIndex(indexVarValue, propertyValue); + if (newPropertyValue != null) { + properties.put(propertyEntry.getKey(), newPropertyValue); + } + } + + mdcDataDebugMessage.debugExitMessage(null, null); + } + + private Object getUpdatedPropertyValueWithIndex(String indexVarValue, Object propertyValue) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + if (propertyValue instanceof String && propertyValue != null) { + if (propertyValue.equals(indexVarValue)) { + return getNewIndexVarValue(); + } + if (((String) propertyValue).contains(indexVarValue)) { + Map> concatMap = new HashMap<>(); + List concatList = new ArrayList<>(); + String value = (String) propertyValue; + + while (value.contains(indexVarValue)) { + if (value.indexOf(indexVarValue) == 0) { + concatList.add(getNewIndexVarValue()); + value = value.substring(indexVarValue.length()); + } else { + int end = value.indexOf(indexVarValue); + concatList.add(value.substring(0, end)); + value = value.substring(end); + } + } + if (!value.isEmpty()) { + concatList.add(value); + } + + concatMap.put(ToscaFunctions.CONCAT.getDisplayName(), concatList); + return concatMap; + } + + mdcDataDebugMessage.debugExitMessage(null, null); + return propertyValue; //no update is needed + } else if (propertyValue instanceof Map && !((Map) propertyValue).isEmpty()) { + replacePropertiesIndexVarValue(indexVarValue, (Map) propertyValue); + return propertyValue; + } else if (propertyValue instanceof List && !((List) propertyValue).isEmpty()) { + List newPropertyValueList = new ArrayList<>(); + for (Object entry : ((List) propertyValue)) { + newPropertyValueList.add(getUpdatedPropertyValueWithIndex(indexVarValue, entry)); + } + + mdcDataDebugMessage.debugExitMessage(null, null); + return newPropertyValueList; + } + + mdcDataDebugMessage.debugExitMessage(null, null); + return propertyValue; + } + + private String getIndexVarValue(TranslateTo translateTo) { + + mdcDataDebugMessage.debugEntryMessage(null, null); + + Object indexVar = + translateTo.getResource().getProperties().get(HeatConstants.INDEX_PROPERTY_NAME); + if (indexVar == null) { + return HeatConstants.RESOURCE_GROUP_INDEX_VAR_DEFAULT_VALUE; + } + + if (indexVar instanceof String) { + + mdcDataDebugMessage.debugExitMessage(null, null); + return (String) indexVar; + } else { + MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_DB, + LoggerTragetServiceName.GET_RESOURCE, ErrorLevel.ERROR.name(), + LoggerErrorCode.DATA_ERROR.getErrorCode(), LoggerErrorDescription.INVALID_PROPERTY); + throw new CoreException( + new InvalidPropertyValueErrorBuilder("index_var", indexVar.toString(), "String").build()); + } + } + + private void populateServiceTemplateFilterProperties(TranslateTo translateTo, + NodeTemplate substitutionNodeTemplate, + Map serviceTemplateFilter) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + boolean mandatory = false; + Object countValue = TranslatorHeatToToscaPropertyConverter + .getToscaPropertyValue(translateTo.getServiceTemplate(),translateTo.getResourceId(), + ToscaConstants.COUNT_PROPERTY_NAME, translateTo.getResource().getProperties().get + (ToscaConstants.COUNT_PROPERTY_NAME), null, + translateTo.getHeatFileName(), translateTo.getHeatOrchestrationTemplate(), + substitutionNodeTemplate, translateTo.getContext()); + + if (countValue != null) { + serviceTemplateFilter.put(ToscaConstants.COUNT_PROPERTY_NAME, countValue); + } else { + serviceTemplateFilter.put(ToscaConstants.COUNT_PROPERTY_NAME, 1); + } + if (countValue instanceof Integer && (Integer) countValue > 0) { + mandatory = true; + } + if (countValue == null) { + mandatory = true; + } + serviceTemplateFilter.put("mandatory", mandatory); + + mdcDataDebugMessage.debugExitMessage(null, null); + } +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/SecurityRulesToPortResourceConnection.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/SecurityRulesToPortResourceConnection.java new file mode 100644 index 0000000000..3d183b1ad9 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation/SecurityRulesToPortResourceConnection.java @@ -0,0 +1,182 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation; + +import org.openecomp.sdc.heat.datatypes.manifest.FileData; + +import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate; +import org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes; +import org.openecomp.sdc.heat.datatypes.model.Resource; +import org.openecomp.sdc.tosca.datatypes.ToscaCapabilityType; +import org.openecomp.sdc.tosca.datatypes.ToscaNodeType; +import org.openecomp.sdc.tosca.datatypes.ToscaRelationshipType; +import org.openecomp.sdc.tosca.datatypes.model.CapabilityDefinition; +import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; +import org.openecomp.sdc.tosca.datatypes.model.NodeType; +import org.openecomp.sdc.tosca.datatypes.model.RequirementDefinition; +import org.openecomp.sdc.tosca.services.ToscaConstants; +import org.openecomp.sdc.translator.datatypes.heattotosca.AttachedResourceId; +import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo; +import org.openecomp.sdc.translator.services.heattotosca.Constants; +import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.function.Predicate; + + +class SecurityRulesToPortResourceConnection extends ResourceConnectionUsingCapabilityHelper { + SecurityRulesToPortResourceConnection(ResourceTranslationNestedImpl resourceTranslationNested, + TranslateTo translateTo, FileData nestedFileData, + NodeTemplate substitutionNodeTemplate, NodeType nodeType) { + super(resourceTranslationNested, translateTo, nestedFileData, substitutionNodeTemplate, + nodeType); + } + + @Override + protected boolean isDesiredNodeTemplateType(NodeTemplate nodeTemplate) { + return nodeTemplate.getType().equals(ToscaNodeType.NEUTRON_PORT); + } + + @Override + protected List> getPredicatesListForConnectionPoints() { + ArrayList> predicates = new ArrayList<>(); + predicates.add(cap -> cap.getType().equals(ToscaCapabilityType.NATIVE_ATTACHMENT)); + return predicates; + } + + @Override + protected Optional> getConnectorPropertyParamName(String heatResourceId, + Resource heatResource, + HeatOrchestrationTemplate + nestedHeatOrchestrationTemplate, + String nestedHeatFileName) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + Object securityGroups = + heatResource.getProperties().get(Constants.SECURITY_GROUPS_PROPERTY_NAME); + List paramsList = new ArrayList<>(); + if (securityGroups instanceof List) { + ((List) securityGroups).forEach(group -> { + Optional attachedResourceId = HeatToToscaUtil + .extractAttachedResourceId(nestedFileData.getFile(), nestedHeatOrchestrationTemplate, + translateTo.getContext(), group); + if (attachedResourceId.isPresent() + && attachedResourceId.get().isGetParam() + && attachedResourceId.get().getEntityId() instanceof String) { + paramsList.add((String) attachedResourceId.get().getEntityId()); + } + }); + + mdcDataDebugMessage.debugExitMessage(null, null); + return Optional.of(paramsList); + } + + mdcDataDebugMessage.debugExitMessage(null, null); + return Optional.empty(); + } + + @Override + protected String getDesiredResourceType() { + return HeatResourcesTypes.NEUTRON_PORT_RESOURCE_TYPE.getHeatResource(); + } + + @Override + void addRequirementToConnectResources( + Map.Entry connectionPointEntry, List paramNames) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + if (paramNames == null || paramNames.isEmpty()) { + return; + } + List supportedSecurityRulesTypes = Collections + .singletonList(HeatResourcesTypes.NEUTRON_SECURITY_GROUP_RESOURCE_TYPE.getHeatResource()); + + for (String paramName : paramNames) { + addRequirementToConnectResource(connectionPointEntry, supportedSecurityRulesTypes, paramName); + } + + mdcDataDebugMessage.debugExitMessage(null, null); + } + + @Override + boolean validateResourceTypeSupportedForReqCreation(String nestedResourceId, + String nestedPropertyName, + String connectionPointId, + Resource connectedResource, + List supportedTypes) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + if (!resourceTranslationBase.isResourceTypeSupported(connectedResource, supportedTypes)) { + logger.warn("Nested resource '" + nestedResourceId + "' property '" + nestedPropertyName + + "' is pointing to resource with type '" + connectedResource.getType() + + "' which is not supported for capability '" + connectionPointId + + "' connection, (security rules to port connection). Supported types are: '" + + supportedTypes.toString() + "', therefore, this TOSCA capability will not be " + + "connected."); + + mdcDataDebugMessage.debugExitMessage(null, null); + return false; + } + + mdcDataDebugMessage.debugExitMessage(null, null); + return true; + } + + @Override + Map.Entry createRequirementDefinition(String capabilityKey) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + RequirementDefinition definition = new RequirementDefinition(); + definition.setCapability(capabilityKey); + definition.setRelationship(ToscaRelationshipType.ATTACHES_TO); + mdcDataDebugMessage.debugExitMessage(null, null); + return new Map.Entry() { + @Override + public String getKey() { + return ToscaConstants.PORT_REQUIREMENT_ID; + } + + @Override + public RequirementDefinition getValue() { + return definition; + } + + @Override + public RequirementDefinition setValue(RequirementDefinition value) { + return null; + } + }; + } + + +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/unifiedcomposition/UnifiedCompositionCatalogInstance.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/unifiedcomposition/UnifiedCompositionCatalogInstance.java new file mode 100644 index 0000000000..9742a44f52 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/unifiedcomposition/UnifiedCompositionCatalogInstance.java @@ -0,0 +1,28 @@ +package org.openecomp.sdc.translator.services.heattotosca.impl.unifiedcomposition; + +import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; +import org.openecomp.sdc.translator.datatypes.heattotosca.TranslationContext; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.composition.UnifiedCompositionData; +import org.openecomp.sdc.translator.services.heattotosca.UnifiedComposition; +import org.openecomp.sdc.translator.services.heattotosca.UnifiedCompositionService; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +public class UnifiedCompositionCatalogInstance implements UnifiedComposition { + @Override + public void createUnifiedComposition(ServiceTemplate serviceTemplate, + ServiceTemplate nestedServiceTemplate, + List unifiedComposotionDataList, + TranslationContext context) { + + UnifiedCompositionSingleSubstitution unifiedCompositionSingleSubstitution = + new UnifiedCompositionSingleSubstitution(); + + unifiedCompositionSingleSubstitution + .createUnifiedComposition(serviceTemplate, null, unifiedComposotionDataList, context); + } + + +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/unifiedcomposition/UnifiedCompositionNestedSingleCompute.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/unifiedcomposition/UnifiedCompositionNestedSingleCompute.java new file mode 100644 index 0000000000..03d7eb02df --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/unifiedcomposition/UnifiedCompositionNestedSingleCompute.java @@ -0,0 +1,38 @@ +package org.openecomp.sdc.translator.services.heattotosca.impl.unifiedcomposition; + +import org.apache.commons.collections4.CollectionUtils; +import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; +import org.openecomp.sdc.translator.datatypes.heattotosca.TranslationContext; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.composition.UnifiedCompositionData; +import org.openecomp.sdc.translator.services.heattotosca.UnifiedComposition; +import org.openecomp.sdc.translator.services.heattotosca.UnifiedCompositionService; + +import java.util.ArrayList; +import java.util.List; + +public class UnifiedCompositionNestedSingleCompute implements UnifiedComposition { + @Override + public void createUnifiedComposition(ServiceTemplate serviceTemplate, + ServiceTemplate nestedServiceTemplate, + List unifiedCompositionDataList, + TranslationContext context) { + UnifiedCompositionService unifiedCompositionService = new UnifiedCompositionService(); + if (CollectionUtils.isEmpty(unifiedCompositionDataList)) { + return; + } + + for (int i = 0; i < unifiedCompositionDataList.size(); i++) { + List nestedUnifiedCompositionDataList = new ArrayList<>(); + nestedUnifiedCompositionDataList.add(unifiedCompositionDataList.get(i)); + + unifiedCompositionService + .handleUnifiedNestedDefinition(serviceTemplate, nestedServiceTemplate, + unifiedCompositionDataList, context); + unifiedCompositionService + .updateUnifiedNestedConnectivity(serviceTemplate, nestedServiceTemplate, + nestedUnifiedCompositionDataList, context); + unifiedCompositionService + .cleanUnifiedNestedEntities(serviceTemplate, nestedUnifiedCompositionDataList, context); + } + } +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/unifiedcomposition/UnifiedCompositionScalingInstances.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/unifiedcomposition/UnifiedCompositionScalingInstances.java new file mode 100644 index 0000000000..fe287a4014 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/unifiedcomposition/UnifiedCompositionScalingInstances.java @@ -0,0 +1,48 @@ +package org.openecomp.sdc.translator.services.heattotosca.impl.unifiedcomposition; + +import org.apache.commons.collections4.CollectionUtils; +import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; +import org.openecomp.sdc.translator.datatypes.heattotosca.TranslationContext; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.composition.UnifiedCompositionData; +import org.openecomp.sdc.translator.services.heattotosca.UnifiedComposition; +import org.openecomp.sdc.translator.services.heattotosca.UnifiedCompositionService; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + +public class UnifiedCompositionScalingInstances implements UnifiedComposition { + + private UnifiedCompositionService unifiedCompositionService = new UnifiedCompositionService(); + + @Override + public void createUnifiedComposition(ServiceTemplate serviceTemplate, + ServiceTemplate nestedServiceTemplate, + List unifiedCompositionDataList, + TranslationContext context) { + if (CollectionUtils.isEmpty(unifiedCompositionDataList)) { + return; + } + + Integer index = null; + Optional substitutionServiceTemplate = + unifiedCompositionService.createUnifiedSubstitutionServiceTemplate(serviceTemplate, + unifiedCompositionDataList, context, index); + + if (!substitutionServiceTemplate.isPresent()) { + return; + } + + String abstractNodeTemplateId = unifiedCompositionService + .createAbstractSubstituteNodeTemplate(serviceTemplate, substitutionServiceTemplate.get(), + unifiedCompositionDataList, context, index); + + unifiedCompositionService + .updateCompositionConnectivity(serviceTemplate, unifiedCompositionDataList, context); + + unifiedCompositionService + .cleanUnifiedCompositionEntities(serviceTemplate, unifiedCompositionDataList, context); + + unifiedCompositionService.cleanNodeTypes(serviceTemplate, unifiedCompositionDataList, context); + } +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/unifiedcomposition/UnifiedCompositionSingleSubstitution.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/unifiedcomposition/UnifiedCompositionSingleSubstitution.java new file mode 100644 index 0000000000..c3965a5f52 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/unifiedcomposition/UnifiedCompositionSingleSubstitution.java @@ -0,0 +1,65 @@ +package org.openecomp.sdc.translator.services.heattotosca.impl.unifiedcomposition; + +import org.apache.commons.collections4.CollectionUtils; +import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; +import org.openecomp.sdc.translator.datatypes.heattotosca.TranslationContext; +import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.composition.UnifiedCompositionData; +import org.openecomp.sdc.translator.services.heattotosca.UnifiedComposition; +import org.openecomp.sdc.translator.services.heattotosca.UnifiedCompositionService; + +import java.util.ArrayList; +import java.util.List; +import java.util.Optional; + + +/** + * The type Unified composition single substitution. + */ +public class UnifiedCompositionSingleSubstitution implements UnifiedComposition { + + // There is no consolidation in SingleSubstitution implemetation. + // In case of single substitution, if there is more than one entry in the + // unifiedComposotionDataList, they all should contain the same compute type but the + // consolidation between them was canceled. + // For different compute type, this implementation will be called more than once, each time + // per diff compute type, while sending one entry in the unifiedComposotionDataList. + @Override + public void createUnifiedComposition(ServiceTemplate serviceTemplate, + ServiceTemplate nestedServiceTemplate, + List unifiedCompositionDataList, + TranslationContext context) { + UnifiedCompositionService unifiedCompositionService = new UnifiedCompositionService(); + if (CollectionUtils.isEmpty(unifiedCompositionDataList)) { + return; + } + + for (int i = 0; i < unifiedCompositionDataList.size(); i++) { + List singleSubstitutionUnifiedList = new ArrayList<>(); + singleSubstitutionUnifiedList.add(unifiedCompositionDataList.get(i)); + + Integer index = unifiedCompositionDataList.size() > 1 ? i : null; + Optional substitutionServiceTemplate = + unifiedCompositionService.createUnifiedSubstitutionServiceTemplate(serviceTemplate, + singleSubstitutionUnifiedList, context, index); + + if (!substitutionServiceTemplate.isPresent()) { + continue; + } + + String abstractNodeTemplateId = unifiedCompositionService + .createAbstractSubstituteNodeTemplate(serviceTemplate, substitutionServiceTemplate.get(), + singleSubstitutionUnifiedList, context, index); + + unifiedCompositionService + .updateCompositionConnectivity(serviceTemplate, singleSubstitutionUnifiedList, context); + + unifiedCompositionService + .cleanUnifiedCompositionEntities(serviceTemplate, singleSubstitutionUnifiedList, context); + + } + + unifiedCompositionService + .cleanNodeTypes(serviceTemplate, unifiedCompositionDataList, context); + + } +} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/mapping/TranslatorHeatToToscaFunctionConverter.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/mapping/TranslatorHeatToToscaFunctionConverter.java deleted file mode 100644 index 0aa5c5ff96..0000000000 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/mapping/TranslatorHeatToToscaFunctionConverter.java +++ /dev/null @@ -1,410 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.translator.services.heattotosca.mapping; - -import org.openecomp.core.utilities.yaml.YamlUtil; -import org.openecomp.sdc.heat.datatypes.HeatBoolean; -import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate; -import org.openecomp.sdc.heat.datatypes.model.Resource; -import org.openecomp.sdc.heat.services.HeatConstants; -import org.openecomp.sdc.tosca.datatypes.ToscaArtifactType; -import org.openecomp.sdc.tosca.datatypes.ToscaFunctions; -import org.openecomp.sdc.tosca.datatypes.model.ArtifactDefinition; -import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; -import org.openecomp.sdc.tosca.datatypes.model.Template; -import org.openecomp.sdc.tosca.services.ToscaConstants; -import org.openecomp.sdc.tosca.services.ToscaFileOutputService; -import org.openecomp.sdc.tosca.services.impl.ToscaFileOutputServiceCsarImpl; -import org.openecomp.sdc.translator.services.heattotosca.Constants; -import org.openecomp.sdc.translator.services.heattotosca.HeatToToscaUtil; -import org.openecomp.sdc.translator.services.heattotosca.TranslationContext; -import org.openecomp.sdc.translator.services.heattotosca.impl.ResourceTranslationBase; - -import java.util.ArrayList; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Optional; -import java.util.Set; -import java.util.stream.Collectors; - - -public class TranslatorHeatToToscaFunctionConverter { - private static final String UNSUPPORTED_RESOURCE = "UNSUPPORTED_RESOURCE_"; - private static final String UNSUPPORTED_ATTRIBUTE = "UNSUPPORTED_ATTRIBUTE_"; - - protected static Set functionNameSet; - - static { - functionNameSet = new HashSet<>(); - functionNameSet.add("get_param"); - functionNameSet.add("get_attr"); - functionNameSet.add("get_resource"); - functionNameSet.add("get_file"); - } - - /** - * Gets tosca function. - * - * @param functionName the function name - * @param function the function - * @param heatFileName the heat file name - * @param heatOrchestrationTemplate the heat orchestration template - * @param template the template - * @param context the context - * @return the tosca function - */ - public static Object getToscaFunction(String functionName, Object function, String heatFileName, - HeatOrchestrationTemplate heatOrchestrationTemplate, - Template template, TranslationContext context) { - Object returnValue = null; - if ("get_param".equals(functionName)) { - returnValue = - handleGetParamFunction(function, heatFileName, heatOrchestrationTemplate, context); - } else if ("get_attr".equals(functionName)) { - returnValue = - handleGetAttrFunction(function, heatFileName, heatOrchestrationTemplate, context); - } else if ("get_resource".equals(functionName)) { - returnValue = - handleGetResourceFunction(function, heatFileName, heatOrchestrationTemplate, context); - } else if ("get_file".equals(functionName)) { - returnValue = handleGetFileFunction(function, template); - } - return returnValue; - } - - private static Object handleGetFileFunction(Object function, Template template) { - String file = ((String) function).replace("file:///", ""); - Object returnValue; - final String artifactId = file.split("\\.")[0]; - - returnValue = new HashMap<>(); - List artifactParameters = new ArrayList(); - artifactParameters.add(0, ToscaConstants.MODELABLE_ENTITY_NAME_SELF); - ((Map) returnValue).put(ToscaFunctions.GET_ARTIFACT.getDisplayName(), artifactParameters); - artifactParameters.add(1, artifactId); - - ToscaFileOutputService toscaFileOutputService = new ToscaFileOutputServiceCsarImpl(); - if (template != null) { - if (template instanceof NodeTemplate) { - NodeTemplate nodeTemplate = (NodeTemplate) template; - ArtifactDefinition artifactDefinition = - createArtifactDefinition(file, toscaFileOutputService); - if (nodeTemplate.getArtifacts() == null) { - nodeTemplate.setArtifacts(new HashMap<>()); - } - nodeTemplate.getArtifacts().put(artifactId, artifactDefinition); - } - } - return returnValue; - } - - private static Object handleGetResourceFunction(Object function, String heatFileName, - HeatOrchestrationTemplate - heatOrchestrationTemplate, - TranslationContext context) { - Object returnValue; - Optional resourceTranslatedId = ResourceTranslationBase - .getResourceTranslatedId(heatFileName, heatOrchestrationTemplate, (String) function, - context); - if (resourceTranslatedId.isPresent()) { - returnValue = resourceTranslatedId.get(); - } else { - returnValue = UNSUPPORTED_RESOURCE + function; - } - return returnValue; - } - - private static Object handleGetAttrFunction(Object function, String heatFileName, - HeatOrchestrationTemplate heatOrchestrationTemplate, - TranslationContext context) { - Object returnValue = new HashMap<>(); - List attributeFunctionExpression = - translateGetAttributeFunctionExpression(function, heatFileName, heatOrchestrationTemplate, - context); - if (isResourceSupported(attributeFunctionExpression.get(0).toString()) - && isAttributeSupported(attributeFunctionExpression.get(0).toString())) { - ((Map) returnValue) - .put(ToscaFunctions.GET_ATTRIBUTE.getDisplayName(), attributeFunctionExpression); - } else { - returnValue = attributeFunctionExpression; - } - return returnValue; - } - - private static Object handleGetParamFunction(Object function, String heatFileName, - HeatOrchestrationTemplate heatOrchestrationTemplate, - TranslationContext context) { - Map returnValue = new HashMap<>(); - returnValue.put(ToscaFunctions.GET_INPUT.getDisplayName(), - translateGetParamFunctionExpression(function, heatFileName, heatOrchestrationTemplate, - context)); - return returnValue; - } - - private static ArtifactDefinition createArtifactDefinition(Object function, - ToscaFileOutputService - toscaFileOutputService) { - ArtifactDefinition artifactDefinition = new ArtifactDefinition(); - artifactDefinition.setType(ToscaArtifactType.DEPLOYMENT.getDisplayName()); - artifactDefinition - .setFile("../" + toscaFileOutputService.getArtifactsFolderName() + "/" + function); - return artifactDefinition; - } - - private static Object translateGetParamFunctionExpression(Object function, String heatFileName, - HeatOrchestrationTemplate - heatOrchestrationTemplate, - TranslationContext context) { - Object returnValue = null; - if (function instanceof String) { - returnValue = function; - } else { - if (function instanceof List) { - returnValue = new ArrayList<>(); - for (int i = 0; i < ((List) function).size(); i++) { - Object paramValue = ((List) function).get(i); - if ((paramValue instanceof Map && !((Map) paramValue).isEmpty())) { - Map paramMap = (Map) paramValue; - Map.Entry entry = paramMap.entrySet().iterator().next(); - ((List) returnValue).add( - getToscaFunction(entry.getKey(), entry.getValue(), heatFileName, - heatOrchestrationTemplate, null, context)); - } else { - ((List) returnValue).add(paramValue); - } - } - } - } - - return returnValue; - } - - private static List translateGetAttributeFunctionExpression( - Object function,String heatFileName, - HeatOrchestrationTemplate heatOrchestrationTemplate, - TranslationContext context) { - List attributeParamList = (List) function; - List toscaAttributeParamList = new ArrayList<>(); - - Optional resourceTranslatedId = - handleResourceName(attributeParamList.get(0), heatFileName, heatOrchestrationTemplate, - context); - if (!resourceTranslatedId.isPresent()) { - //unsupported resource - toscaAttributeParamList.add(UNSUPPORTED_RESOURCE + attributeParamList.get(0)); - return toscaAttributeParamList; - } else { - toscaAttributeParamList.add(resourceTranslatedId.get()); - } - - Optional> toscaAttList = - handleAttributeName(attributeParamList, heatOrchestrationTemplate, heatFileName, context); - if (!toscaAttList.isPresent()) { - //Unsupported attribute - toscaAttributeParamList.clear(); - toscaAttributeParamList - .add(UNSUPPORTED_ATTRIBUTE + attributeParamList.get(0) + "." + attributeParamList.get(1)); - return toscaAttributeParamList; - } else { - toscaAttributeParamList.addAll(toscaAttList.get()); - } - - Optional> toscaIndexOrKey = handleAttributeIndexOrKey(attributeParamList); - if (toscaIndexOrKey.isPresent()) { - toscaAttributeParamList.addAll(toscaIndexOrKey.get()); - } - - return toscaAttributeParamList; - } - - private static Optional> handleAttributeIndexOrKey(List attributeParamList) { - List attributeIndexOrKey = new ArrayList<>(); - if (attributeParamList.size() < 2) { - return Optional.empty(); - } - - for (int i = 2; i < attributeParamList.size(); i++) { - attributeIndexOrKey.add(attributeParamList.get(i)); - } - - return Optional.of(attributeIndexOrKey); - } - - private static Optional> handleAttributeName(List attributeParamList, - HeatOrchestrationTemplate - heatOrchestrationTemplate, - String heatFileName, - TranslationContext context) { - String resourceId = attributeParamList.get(0); - Resource resource = - HeatToToscaUtil.getResource(heatOrchestrationTemplate, resourceId, heatFileName); - - if (attributeParamList.size() == 1) { - return getResourceTranslatedAttributesList(resource, context); - } - - if (HeatToToscaUtil.isNestedResource(resource)) { - return getNestedResourceTranslatedAttribute(attributeParamList.get(1)); - } else { - return getResourceTranslatedAttribute(resource, attributeParamList.get(1), context); - } - } - - private static Optional> getResourceTranslatedAttribute(Resource resource, - String attributeName, - TranslationContext context) { - List translatedAttributesList = new ArrayList<>(); - String translatedAttribute = - context.getElementMapping(resource.getType(), Constants.ATTR, attributeName); - if (translatedAttribute != null) { - translatedAttributesList.add(translatedAttribute); - return Optional.of(translatedAttributesList); - } else { //unsupported attribute - return Optional.empty(); - } - } - - private static Optional> getNestedResourceTranslatedAttribute(String attributeName) { - List translatedAttributesList = new ArrayList<>(); - - if (attributeName.startsWith(HeatConstants.GET_ATT_FROM_RESOURCE_GROUP_PREFIX)) { - String[] attributeSplit = attributeName.split("\\."); - if (attributeSplit.length == 2) { - translatedAttributesList.add(attributeSplit[1]); - } else if (attributeSplit.length == 3) { - translatedAttributesList.add(attributeSplit[2]); - translatedAttributesList.add(Integer.valueOf(attributeSplit[1])); - } else { - return Optional.empty(); - } - } else { - translatedAttributesList.add(attributeName); - } - return Optional.of(translatedAttributesList); - } - - private static Optional> getResourceTranslatedAttributesList(Resource resource, - TranslationContext - context) { - List translatedAttributes = new ArrayList<>(); - if (HeatToToscaUtil.isNestedResource(resource)) { - Optional nestedFile = HeatToToscaUtil.getNestedFile(resource); - if (!nestedFile.isPresent()) { - return Optional.empty(); - } - HeatOrchestrationTemplate nestedHeatOrchestrationTemplate = new YamlUtil() - .yamlToObject(context.getFiles().getFileContent(nestedFile.get()), - HeatOrchestrationTemplate.class); - translatedAttributes.addAll(nestedHeatOrchestrationTemplate.getOutputs().keySet()); - return Optional.of(translatedAttributes); - - } else { - Map resourceMappingAttributes = - context.getElementMapping(resource.getType(), Constants.ATTR); - Set mappingAttributes = new HashSet<>(); - mappingAttributes - .addAll(resourceMappingAttributes.values().stream().collect(Collectors.toList())); - translatedAttributes.addAll(mappingAttributes); - return Optional.of(translatedAttributes); - } - } - - private static Optional handleResourceName(String resourceId, String heatFileName, - HeatOrchestrationTemplate - heatOrchestrationTemplate, - TranslationContext context) { - return ResourceTranslationBase - .getResourceTranslatedId(heatFileName, heatOrchestrationTemplate, resourceId, context); - } - - public static boolean isResourceSupported(String translatedResourceId) { - return !translatedResourceId.startsWith(UNSUPPORTED_RESOURCE); - } - - public static boolean isAttributeSupported(String translatedAttName) { - return !translatedAttName.startsWith(UNSUPPORTED_ATTRIBUTE); - } - - /** - * Translate fn split function optional. - * - * @param propertyValue the property value - * @param listSize the list size - * @param includeBooleanValue the include boolean value - * @return the optional - */ - public static Optional>> translateFnSplitFunction( - Object propertyValue,int listSize, - boolean includeBooleanValue) { - List> tokenPropertyValueList = new ArrayList<>(); - - if (propertyValue instanceof Map && !((Map) propertyValue).isEmpty()) { - Map propMap = (Map) propertyValue; - Map.Entry entry = propMap.entrySet().iterator().next(); - Object entity = entry.getValue(); - String key = entry.getKey(); - String tokenChar; - - if (key.equals("Fn::Split") && entity instanceof List) { - tokenChar = (String) ((List) entity).get(0); - Object refParameter = ((List) entity).get(1); - - for (int substringIndex = 0; substringIndex < listSize; substringIndex++) { - Map tokenPropertyValue = new HashMap<>(); - tokenPropertyValue.put("token", new ArrayList<>()); - - if (refParameter instanceof Map && ((Map) refParameter).get("Ref") != null) { - Map stringWithToken = new HashMap<>(); - ((Map) stringWithToken) - .put(ToscaFunctions.GET_INPUT.getDisplayName(), ((Map) refParameter).get("Ref")); - tokenPropertyValue.get("token").add(stringWithToken); - } else if (refParameter instanceof String) { - if (includeBooleanValue) { - StringBuffer booleanBuffer = new StringBuffer(); - String[] booleanValueList = ((String) refParameter).split(tokenChar); - for (int i = 0; i < booleanValueList.length; i++) { - if (i == 0) { - booleanBuffer.append(HeatBoolean.eval(booleanValueList[i])); - } else { - booleanBuffer.append(tokenChar); - booleanBuffer.append(HeatBoolean.eval(booleanValueList[i])); - } - } - tokenPropertyValue.get("token").add(booleanBuffer.toString()); - } else { - tokenPropertyValue.get("token").add(refParameter); - } - } - tokenPropertyValue.get("token").add(tokenChar); - tokenPropertyValue.get("token").add(substringIndex); - tokenPropertyValueList.add(tokenPropertyValue); - } - - return Optional.of(tokenPropertyValueList); - - } - } - - return Optional.empty(); - } -} diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/mapping/TranslatorHeatToToscaParameterConverter.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/mapping/TranslatorHeatToToscaParameterConverter.java index 07ab6d1542..23a4d7317b 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/mapping/TranslatorHeatToToscaParameterConverter.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/mapping/TranslatorHeatToToscaParameterConverter.java @@ -20,15 +20,20 @@ package org.openecomp.sdc.translator.services.heattotosca.mapping; +import org.apache.commons.collections4.MapUtils; import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate; import org.openecomp.sdc.heat.datatypes.model.Output; import org.openecomp.sdc.heat.datatypes.model.Parameter; import org.openecomp.sdc.tosca.datatypes.model.Constraint; import org.openecomp.sdc.tosca.datatypes.model.EntrySchema; +import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate; import org.openecomp.sdc.tosca.datatypes.model.ParameterDefinition; +import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; +import org.openecomp.sdc.tosca.datatypes.model.Template; import org.openecomp.sdc.tosca.datatypes.model.heatextend.ParameterDefinitionExt; -import org.openecomp.sdc.translator.services.heattotosca.TranslationContext; - +import org.openecomp.sdc.translator.datatypes.heattotosca.TranslationContext; +import org.openecomp.sdc.translator.services.heattotosca.ConsolidationDataUtil; +import org.openecomp.sdc.translator.services.heattotosca.FunctionTranslationFactory; import java.util.ArrayList; import java.util.Arrays; @@ -36,6 +41,7 @@ import java.util.HashMap; import java.util.List; import java.util.Map; + public class TranslatorHeatToToscaParameterConverter { @@ -65,16 +71,18 @@ public class TranslatorHeatToToscaParameterConverter { * @param context the context * @return the map */ - public static Map parameterConverter( + public static Map parameterConverter(ServiceTemplate serviceTemplate, Map parameters, HeatOrchestrationTemplate heatOrchestrationTemplate, String heatFileName, TranslationContext context) { Map parameterDefinitionMap = new HashMap<>(); for (Map.Entry entry : parameters.entrySet()) { - //parameterDefinitionMap.put(entry.getKey()+"_"+ FileUtils - // .getFileWithoutExtention(heatFileName),getToscaParameter(entry.getValue(), - // heatOrchestrationTemplate, heatFileName, context)); + //parameterDefinitionMap.put(entry.getKey()+"_"+ FileUtils.getFileWithoutExtention + // (heatFileName),getToscaParameter(entry.getValue(), heatOrchestrationTemplate, + // heatFileName, context)); parameterDefinitionMap.put(entry.getKey(), - getToscaParameter(entry.getValue(), heatOrchestrationTemplate, heatFileName, context)); + getToscaParameter(serviceTemplate,entry.getKey(), entry.getValue(), + heatOrchestrationTemplate, + heatFileName, context)); } return parameterDefinitionMap; } @@ -88,16 +96,16 @@ public class TranslatorHeatToToscaParameterConverter { * @param context the context * @return the map */ - public static Map parameterOutputConverter( + public static Map parameterOutputConverter(ServiceTemplate + serviceTemplate, Map parameters, HeatOrchestrationTemplate heatOrchestrationTemplate, String heatFileName, TranslationContext context) { Map parameterDefinitionMap = new HashMap<>(); for (Map.Entry entry : parameters.entrySet()) { - //parameterDefinitionMap.put(entry.getKey()+"_"+FileUtils - // .getFileWithoutExtention(heatFileName),getToscaOutputParameter(entry.getValue(), - // heatOrchestrationTemplate, heatFileName, context)); parameterDefinitionMap.put(entry.getKey(), - getToscaOutputParameter(entry.getValue(), heatOrchestrationTemplate, heatFileName, + getToscaOutputParameter(serviceTemplate,entry.getKey(),entry.getValue(), + heatOrchestrationTemplate, + heatFileName, context)); } return parameterDefinitionMap; @@ -112,9 +120,11 @@ public class TranslatorHeatToToscaParameterConverter { * @param context the context * @return the tosca parameter */ - public static ParameterDefinitionExt getToscaParameter(Parameter heatParameter, + public static ParameterDefinitionExt getToscaParameter(ServiceTemplate serviceTemplate, + String parameterName, + Parameter heatParameter, HeatOrchestrationTemplate - heatOrchestrationTemplate, + heatOrchestrationTemplate, String heatFileName, TranslationContext context) { @@ -124,8 +134,8 @@ public class TranslatorHeatToToscaParameterConverter { toscaParameter.setLabel(heatParameter.getLabel()); toscaParameter.setDescription(heatParameter.getDescription()); toscaParameter.set_default( - getToscaParameterDefaultValue(heatParameter.get_default(), toscaParameter.getType(), - heatFileName, heatOrchestrationTemplate, context)); + getToscaParameterDefaultValue(serviceTemplate, parameterName, heatParameter.get_default(), + toscaParameter.getType(), heatFileName, heatOrchestrationTemplate, context)); toscaParameter.setHidden(heatParameter.isHidden()); toscaParameter.setImmutable(heatParameter.isImmutable()); toscaParameter.setConstraints(getToscaConstrains(heatParameter.getConstraints())); @@ -141,16 +151,19 @@ public class TranslatorHeatToToscaParameterConverter { * @param context the context * @return the tosca output parameter */ - public static ParameterDefinitionExt getToscaOutputParameter(Output heatOutputParameter, + public static ParameterDefinitionExt getToscaOutputParameter(ServiceTemplate serviceTemplate, + String parameterName, + Output heatOutputParameter, HeatOrchestrationTemplate - heatOrchestrationTemplate, + heatOrchestrationTemplate, String heatFileName, TranslationContext context) { ParameterDefinitionExt toscaParameter = new ParameterDefinitionExt(); toscaParameter.setDescription(heatOutputParameter.getDescription()); toscaParameter.setValue( - getToscaParameterDefaultValue(heatOutputParameter.getValue(), toscaParameter.getType(), + getToscaParameterDefaultValue(serviceTemplate,parameterName,heatOutputParameter.getValue(), + toscaParameter.getType(), heatFileName, heatOrchestrationTemplate, context)); return toscaParameter; } @@ -158,44 +171,53 @@ public class TranslatorHeatToToscaParameterConverter { /** * Gets tosca parameter default value. * - * @param defaultObj the a default + * @param obj the a default * @param type the type * @param heatFileName the heat file name * @param heatOrchestrationTemplate the heat orchestration template * @param context the context * @return the tosca parameter default value */ - public static Object getToscaParameterDefaultValue(Object defaultObj, String type, + public static Object getToscaParameterDefaultValue(ServiceTemplate serviceTemplate, + String parameterName, + Object obj, String type, String heatFileName, HeatOrchestrationTemplate - heatOrchestrationTemplate, + heatOrchestrationTemplate, TranslationContext context) { - if (defaultObj == null) { + if (obj == null) { return null; } + Object toscaDefaultValue = obj; if ("list".equals(type)) { - if (defaultObj instanceof String) { - return Arrays.asList(((String) defaultObj).split(",")); + if (obj instanceof String) { + return Arrays.asList(((String) obj).split(",")); } else { - return defaultObj; + return toscaDefaultValue; } } - return getToscaParameterValue(defaultObj, heatFileName, heatOrchestrationTemplate, + return getToscaParameterValue(serviceTemplate,parameterName,toscaDefaultValue, heatFileName, + heatOrchestrationTemplate, context); } - private static Object getToscaParameterValue(Object paramValue, String heatFileName, + private static Object getToscaParameterValue(ServiceTemplate serviceTemplate, + String parameterName, + Object paramValue, String heatFileName, HeatOrchestrationTemplate heatOrchestrationTemplate, TranslationContext context) { if (paramValue instanceof Map) { + if(MapUtils.isEmpty((Map) paramValue)){ + return new HashMap<>(); + } Map.Entry functionMapEntry = (Map.Entry) ((Map) paramValue).entrySet().iterator().next(); - if (TranslatorHeatToToscaFunctionConverter.functionNameSet - .contains(functionMapEntry.getKey())) { - return TranslatorHeatToToscaFunctionConverter - .getToscaFunction(functionMapEntry.getKey(), functionMapEntry.getValue(), heatFileName, + if (FunctionTranslationFactory.getInstance(functionMapEntry.getKey()).isPresent()) { + return FunctionTranslationFactory.getInstance(functionMapEntry.getKey()).get() + .translateFunction(serviceTemplate, null, parameterName, functionMapEntry.getKey(), + functionMapEntry.getValue(),heatFileName, heatOrchestrationTemplate, null, context); } } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/mapping/TranslatorHeatToToscaPropertyConverter.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/mapping/TranslatorHeatToToscaPropertyConverter.java index d1079c2dc5..e22d21dae0 100644 --- a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/mapping/TranslatorHeatToToscaPropertyConverter.java +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/mapping/TranslatorHeatToToscaPropertyConverter.java @@ -21,9 +21,12 @@ package org.openecomp.sdc.translator.services.heattotosca.mapping; import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate; +import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate; import org.openecomp.sdc.tosca.datatypes.model.Template; +import org.openecomp.sdc.translator.datatypes.heattotosca.TranslationContext; +import org.openecomp.sdc.translator.services.heattotosca.ConfigConstants; import org.openecomp.sdc.translator.services.heattotosca.Constants; -import org.openecomp.sdc.translator.services.heattotosca.TranslationContext; +import org.openecomp.sdc.translator.services.heattotosca.FunctionTranslationFactory; import java.util.ArrayList; import java.util.HashMap; @@ -45,16 +48,18 @@ public class TranslatorHeatToToscaPropertyConverter { * @return the tosca properties simple conversion */ //Convert property assuming the property type in heat is same as the property type in tosca - public static Map getToscaPropertiesSimpleConversion( - Map heatProperties, Map toscaProperties, String heatFileName, - HeatOrchestrationTemplate heatOrchestrationTemplate, String resourceType, Template template, - TranslationContext context) { + public static Map getToscaPropertiesSimpleConversion(ServiceTemplate + serviceTemplate, + String resourceId,Map heatProperties, Map toscaProperties, + String heatFileName, HeatOrchestrationTemplate heatOrchestrationTemplate, String + resourceType, Template template, TranslationContext context) { toscaProperties = toscaProperties != null ? toscaProperties : new HashMap<>(); for (String heatPropertyName : context.getElementSet(resourceType, Constants.PROP)) { - setSimpleProperty(heatProperties, heatFileName, resourceType, heatOrchestrationTemplate, + setSimpleProperty(serviceTemplate, resourceId, heatProperties, heatFileName, resourceType, + heatOrchestrationTemplate, context, toscaProperties, heatPropertyName, null, template); } return toscaProperties; @@ -73,7 +78,9 @@ public class TranslatorHeatToToscaPropertyConverter { * @param toscaPropertyName the tosca property name * @param template the template */ - public static void setSimpleProperty(Map heatProperties, String heatFileName, + public static void setSimpleProperty(ServiceTemplate serviceTemplate,String resourceId, + Map heatProperties, + String heatFileName, String resourceType, HeatOrchestrationTemplate heatOrchestrationTemplate, TranslationContext context, @@ -90,10 +97,14 @@ public class TranslatorHeatToToscaPropertyConverter { if (toscaPropertyName == null) { toscaPropertyName = resourceType == null ? heatPropertyName : context.getElementMapping(resourceType, Constants.PROP, heatPropertyName); + if (toscaPropertyName == null) { + return; + } } toscaProperties.put(toscaPropertyName, - getToscaPropertyValue(heatPropertyName, propertyValue, resourceType, heatFileName, - heatOrchestrationTemplate, template, context)); + getToscaPropertyValue(serviceTemplate, resourceId,heatPropertyName, propertyValue, + resourceType, + heatFileName, heatOrchestrationTemplate, template, context)); } @@ -109,26 +120,30 @@ public class TranslatorHeatToToscaPropertyConverter { * @param context the context * @return the tosca property value */ - public static Object getToscaPropertyValue(String propertyName, Object propertyValue, - String resourceType, String heatFileName, + public static Object getToscaPropertyValue(ServiceTemplate serviceTemplate, String resourceId, + String propertyName, Object propertyValue, + String resourceType, String heatFileName, HeatOrchestrationTemplate heatOrchestrationTemplate, Template template, TranslationContext context) { if (propertyValue instanceof Map && !((Map) propertyValue).isEmpty()) { Map.Entry functionMapEntry = (Map.Entry) ((Map) propertyValue).entrySet().iterator().next(); - if (TranslatorHeatToToscaFunctionConverter.functionNameSet - .contains(functionMapEntry.getKey())) { - return TranslatorHeatToToscaFunctionConverter - .getToscaFunction(functionMapEntry.getKey(), functionMapEntry.getValue(), heatFileName, - heatOrchestrationTemplate, template, context); + if (FunctionTranslationFactory.getInstance(functionMapEntry.getKey()).isPresent()) { + return FunctionTranslationFactory.getInstance(functionMapEntry.getKey()).get() + .translateFunction(serviceTemplate, resourceId, propertyName ,functionMapEntry + .getKey(), functionMapEntry + .getValue(), heatFileName, heatOrchestrationTemplate, template, context); } Map propertyValueMap = new HashMap<>(); for (Map.Entry entry : ((Map) propertyValue).entrySet()) { String toscaPropertyName = resourceType == null ? null : context - .getElementMapping(resourceType, Constants.PROP, propertyName + "." + entry.getKey()); + .getElementMapping(resourceType, Constants.PROP, propertyName + + ConfigConstants.TRANS_MAPPING_DELIMITER_CHAR + entry.getKey()); toscaPropertyName = toscaPropertyName != null ? toscaPropertyName : entry.getKey(); propertyValueMap.put(toscaPropertyName, - getToscaPropertyValue(propertyName, entry.getValue(), resourceType, heatFileName, + getToscaPropertyValue(serviceTemplate, resourceId, + propertyName + ConfigConstants.TRANS_MAPPING_DELIMITER_CHAR + + entry.getKey(), entry.getValue(), resourceType, heatFileName, heatOrchestrationTemplate, template, context)); } return propertyValueMap; @@ -136,8 +151,9 @@ public class TranslatorHeatToToscaPropertyConverter { List propertyValueArray = new ArrayList<>(); for (int i = 0; i < ((List) propertyValue).size(); i++) { propertyValueArray.add( - getToscaPropertyValue(propertyName, ((List) propertyValue).get(i), resourceType, - heatFileName, heatOrchestrationTemplate, template, context)); + getToscaPropertyValue(serviceTemplate, resourceId, propertyName, ((List) + propertyValue).get(i), + resourceType, heatFileName, heatOrchestrationTemplate, template, context)); } return propertyValueArray; } diff --git a/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/utils/ResourceWalker.java b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/utils/ResourceWalker.java new file mode 100644 index 0000000000..7e8ef16631 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/utils/ResourceWalker.java @@ -0,0 +1,144 @@ +package org.openecomp.sdc.translator.utils; + +import org.apache.commons.io.IOUtils; +import org.openecomp.sdc.common.errors.CoreException; +import org.openecomp.sdc.common.errors.ErrorCategory; +import org.openecomp.sdc.common.errors.ErrorCode; +import org.openecomp.sdc.datatypes.error.ErrorLevel; +import org.openecomp.sdc.logging.context.impl.MdcDataErrorMessage; +import org.openecomp.sdc.logging.types.LoggerConstants; +import org.openecomp.sdc.logging.types.LoggerErrorCode; +import org.openecomp.sdc.logging.types.LoggerErrorDescription; +import org.openecomp.sdc.logging.types.LoggerTragetServiceName; + +import java.io.BufferedReader; +import java.io.File; +import java.io.FileInputStream; +import java.io.FileNotFoundException; +import java.io.IOException; +import java.io.InputStream; +import java.io.InputStreamReader; +import java.net.URI; +import java.net.URISyntaxException; +import java.net.URL; +import java.util.Enumeration; +import java.util.HashMap; +import java.util.Map; +import java.util.function.BiConsumer; +import java.util.function.Predicate; +import java.util.zip.ZipEntry; +import java.util.zip.ZipFile; + +/** + * @author EVITALIY. + * @since 02 Apr 17 + */ +public class ResourceWalker { + + public static Map readResourcesFromDirectory(String resourceDirectoryToStart) + throws + Exception { + Map filesContent = new HashMap<>(); + traverse(resourceDirectoryToStart, (fileName, stream) -> { + BufferedReader reader = new BufferedReader(new InputStreamReader(stream)); + try { + filesContent.put(fileName, IOUtils.toString(reader)); + } catch (IOException exception) { + MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_API, + LoggerTragetServiceName.READ_RESOURCE_FILE, ErrorLevel.ERROR.name(), + LoggerErrorCode.DATA_ERROR.getErrorCode(), + LoggerErrorDescription.RESOURCE_FILE_READ_ERROR + + " File name = " + fileName); + throw new CoreException((new ErrorCode.ErrorCodeBuilder()) + .withMessage(LoggerErrorDescription.RESOURCE_FILE_READ_ERROR + + " File name = " + fileName) + .withId("Resource Read Error").withCategory(ErrorCategory.APPLICATION).build(), + exception); + } + }); + return filesContent; + } + + private static void traverse(String start, BiConsumer handler) throws + Exception { + + URL url = ResourceWalker.class.getClassLoader().getResource(start); + if (url == null) { + throw new FileNotFoundException("Resource not found: " + start); + } + + switch (url.getProtocol().toLowerCase()) { + + case "file": + traverseFile(new File(url.getPath()), handler); + break; + case "zip": + case "jar": + String path = url.getPath(); + int resourcePosition = path.lastIndexOf("!/" + start); + traverseArchive(path.substring(0, resourcePosition), start, handler); + break; + default: + throw new IllegalArgumentException("Unknown protocol"); + } + } + + private static void traverseArchive(String file, String resource, BiConsumer + handler) + throws URISyntaxException, IOException { + + // There is what looks like a bug in Java: + // if "abc" is a directory in an archive, + // both "abc" and "abc/" will be found successfully. + // However, calling isDirectory() will return "true" for "abc/", + // but "false" for "abc". + try (ZipFile zip = new ZipFile(new URI(file).getPath())) { + + Predicate predicate = buildPredicate(resource); + Enumeration entries = zip.entries(); + while (entries.hasMoreElements()) { + handleZipEntry(predicate, zip, entries.nextElement(), handler); + } + } + } + + private static Predicate buildPredicate(String resource) { + + if (resource.endsWith("/")) { + return zipEntry -> + zipEntry.getName().startsWith(resource) && !zipEntry.isDirectory(); + } else { + return zipEntry -> { + String name = zipEntry.getName(); + return (name.equals(resource) || name.startsWith(resource + "/")) + && !zipEntry.isDirectory(); + }; + } + } + + private static void handleZipEntry(Predicate predicate, ZipFile zip, ZipEntry zipEntry, + BiConsumer handler) + throws IOException { + + if (predicate.test(zipEntry)) { + + try (InputStream input = zip.getInputStream(zipEntry)) { + handler.accept(zipEntry.getName(), input); + } + } + } + + private static void traverseFile(File file, BiConsumer handler) throws + IOException { + + if (file.isDirectory()) { + for (File sub : file.listFiles()) { + traverseFile(sub, handler); + } + } else { + try (FileInputStream stream = new FileInputStream(file)) { + handler.accept(file.getName(), stream); + } + } + } +} -- cgit 1.2.3-korg