diff options
Diffstat (limited to 'openecomp-be/lib/openecomp-sdc-translator-lib/openecomp-sdc-translator-core/src/main/java/org/openecomp/sdc/translator/services/heattotosca/impl/resourcetranslation')
30 files changed, 6352 insertions, 0 deletions
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<T> { + 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<Predicate<T>> getPredicatesListForConnectionPoints(); + + abstract Optional<List<String>> getConnectorPropertyParamName(String heatResourceId, + Resource heatResource, + HeatOrchestrationTemplate + nestedHeatOrchestrationTemplate, + String nestedHeatFileName); + + abstract String getDesiredResourceType(); + + abstract String getMappedNodeTranslatedResourceId(ServiceTemplate nestedServiceTemplate, + Map.Entry<String, T> connectionPointEntry); + + abstract Map.Entry<String, T> getMappedConnectionPointEntry(ServiceTemplate nestedServiceTemplate, + Map.Entry<String, T> + connectionPointEntry); + + abstract void addRequirementToConnectResources(Map.Entry<String, T> connectionPointEntry, + List<String> paramNames); + + abstract List<Map<String, T>> getAllConnectionPoints(); + + abstract boolean validateResourceTypeSupportedForReqCreation(String nestedResourceId, + final String nestedPropertyName, + String connectionPointId, + Resource connectedResource, + List<String> supportedTypes); + + void connect() { + ServiceTemplate nestedServiceTemplate = translateTo.getContext().getTranslatedServiceTemplates() + .get(translateTo.getResource().getType()); + List<String> paramNames; + HeatOrchestrationTemplate nestedHeatOrchestrationTemplate = new YamlUtil() + .yamlToObject(translateTo.getContext().getFileContent(nestedFileData.getFile()), + HeatOrchestrationTemplate.class); + List<Map<String, T>> exposedConnectionPoints = getAllConnectionPoints(); + for (Map<String, T> connectionPointsMap : exposedConnectionPoints) { + for (Map.Entry<String, T> connectionPointEntry : connectionPointsMap.entrySet()) { + paramNames = + getConnectionParameterName(nestedServiceTemplate, nestedHeatOrchestrationTemplate, + nestedFileData.getFile(), connectionPointEntry); + if (paramNames != null && !paramNames.isEmpty()) { + addRequirementToConnectResources(connectionPointEntry, paramNames); + } + } + } + } + + private List<String> getConnectionParameterName(ServiceTemplate nestedServiceTemplate, + HeatOrchestrationTemplate + nestedHeatOrchestrationTemplate, + String nestedHeatFileName, + Map.Entry<String, T> connectionPointEntry) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + List<String> 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<String> 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<String> 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<String> getResourcesConnectionParameterName(String translatedResourceId, + HeatOrchestrationTemplate + nestedHeatOrchestrationTemplate, + String nestedHeatFileName) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + List<String> params = new ArrayList<>(); + Optional<List<Map.Entry<String, Resource>>> heatResources = + getResourceByTranslatedResourceId(translatedResourceId, nestedHeatOrchestrationTemplate); + if (heatResources.isPresent()) { + for (Map.Entry<String, Resource> resourceEntry : heatResources.get()) { + Resource heatResource = resourceEntry.getValue(); + if (!MapUtils.isEmpty(heatResource.getProperties())) { + Optional<List<String>> connectorParamName = + getConnectorPropertyParamName(resourceEntry.getKey(), heatResource, + nestedHeatOrchestrationTemplate, nestedHeatFileName); + connectorParamName.ifPresent(params::addAll); + } + } + } + + mdcDataDebugMessage.debugExitMessage(null, null); + return params; + } + + protected Optional<List<Map.Entry<String, Resource>>> getResourceByTranslatedResourceId( + String translatedResourceId, HeatOrchestrationTemplate nestedHeatOrchestrationTemplate) { + Optional<List<Map.Entry<String, Resource>>> 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<String, RequirementDefinition> + 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<String> getConnectionTranslatedNodeUsingGetParamFunc( + Map.Entry<String, T> connectionPointEntry, String paramName, + List<String> supportedNodeTypes) { + + Optional<AttachedResourceId> 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<TranslatedHeatResource> getConnectionTranslatedHeatResourceUsingGetParamFunc( + Map.Entry<String, T> connectionPointEntry, String paramName, + List<String> supportedNodeTypes) { + + Optional<AttachedResourceId> 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<String> getConnectionTranslatedNodeUsingGetResourceFunc( + Map.Entry<String, T> connectionPointEntry, String paramName, Object paramValue, + List<String> supportedNodeTypes) { + Optional<String> 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<String> getConnectionResourceUsingGetResourceFunc( + Map.Entry<String, T> connectionPointEntry, String paramName, Object paramValue, + List<String> supportedNodeTypes) { + Optional<String> 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<Predicate<RequirementDefinition>> getPredicatesListForConnectionPoints() { + ArrayList<Predicate<RequirementDefinition>> 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<List<String>> 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<String> 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<AttachedResourceId> 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<AttachedResourceId> 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<String, RequirementDefinition> requirementDefinitionEntry, + List<String> 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<String> 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<String> 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<Predicate<RequirementDefinition>> getPredicatesListForConnectionPoints() { + ArrayList<Predicate<RequirementDefinition>> 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<List<String>> getConnectorPropertyParamName(String heatResourceId, + Resource heatResource, + HeatOrchestrationTemplate + nestedHeatOrchestrationTemplate, + String nestedHeatFileName) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + List<String> 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<AttachedResourceId> 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<String, RequirementDefinition> requirementDefinitionEntry, + List<String> paramNames) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + if (paramNames == null || paramNames.isEmpty()) { + return; + } + for (String paramName : paramNames) { + Object paramValue = translateTo.getResource().getProperties().get(paramName); + List<String> 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<String> 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<Predicate<RequirementDefinition>> getPredicatesListForConnectionPoints() { + ArrayList<Predicate<RequirementDefinition>> 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<List<String>> getConnectorPropertyParamName(String heatResourceId, + Resource heatResource, + HeatOrchestrationTemplate + nestedHeatOrchestrationTemplate, + String nestedHeatFileName) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + List<String> 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<AttachedResourceId> 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<String, RequirementDefinition> requirementDefinitionEntry, + List<String> paramNames) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + if (paramNames == null || paramNames.isEmpty()) { + return; + } + for (String paramName : paramNames) { + Object paramValue = translateTo.getResource().getProperties().get(paramName); + List<String> 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<String> 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<Predicate<RequirementDefinition>> getPredicatesListForConnectionPoints() { + ArrayList<Predicate<RequirementDefinition>> 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<List<String>> getConnectorPropertyParamName(String heatResourceId, Resource heatResource, + HeatOrchestrationTemplate + nestedHeatOrchestrationTemplate, + String nestedHeatFileName) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + Optional<AttachedResourceId> 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<String, RequirementDefinition> requirementDefinitionEntry, + List<String> paramNames) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + if (paramNames == null || paramNames.isEmpty()) { + return; + } + + List<String> 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<String> 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<List<Map.Entry<String, Resource>>> getResourceByTranslatedResourceId( + String translatedResourceId, HeatOrchestrationTemplate nestedHeatOrchestrationTemplate) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + List<Predicate<Map.Entry<String, Resource>>> predicates = + buildPredicates(nestedFileData.getFile(), nestedHeatOrchestrationTemplate, + translatedResourceId); + List<Map.Entry<String, Resource>> 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<String> getConnectionTranslatedNodeUsingGetParamFunc( + Map.Entry<String, RequirementDefinition> requirementDefinitionEntry, String paramName, + List<String> supportedTargetNodeTypes) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + Optional<String> targetTranslatedNodeId = super + .getConnectionTranslatedNodeUsingGetParamFunc(requirementDefinitionEntry, paramName, + supportedTargetNodeTypes); + if (targetTranslatedNodeId.isPresent()) { + return targetTranslatedNodeId; + } else { + Optional<AttachedResourceId> 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<FileData> allFilesData = + translateTo.getContext().getManifest().getContent().getData(); + Optional<FileData> fileData = + HeatToToscaUtil.getFileData(translateTo.getHeatFileName(), allFilesData); + if (fileData.isPresent()) { + Optional<ResourceFileDataAndIDs> 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<Predicate<Map.Entry<String, Resource>>> buildPredicates( + String fileName, + HeatOrchestrationTemplate heatOrchestrationTemplate, + String novaTranslatedResourceId) { + List<Predicate<Map.Entry<String, Resource>>> 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<AttachedResourceId> instanceUuid = HeatToToscaUtil + .extractAttachedResourceId(fileName, heatOrchestrationTemplate, context, + instanceUuidProp); + if (instanceUuid.isPresent()) { + Optional<String> 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<Predicate<RequirementDefinition>> getPredicatesListForConnectionPoints() { + ArrayList<Predicate<RequirementDefinition>> 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<List<String>> getConnectorPropertyParamName(String heatResourceId, + Resource heatResource, + HeatOrchestrationTemplate + nestedHeatOrchestrationTemplate, + String nestedHeatFileName) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + Optional<AttachedResourceId> 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<String, RequirementDefinition> requirementDefinitionEntry, + List<String> 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<String> 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<String> 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<CapabilityDefinition> { + public ResourceConnectionUsingCapabilityHelper(ResourceTranslationBase resourceTranslationBase, + TranslateTo translateTo, FileData nestedFileData, + NodeTemplate substitutionNodeTemplate, + NodeType nodeType) { + super(resourceTranslationBase, translateTo, nestedFileData, substitutionNodeTemplate, nodeType); + } + + abstract Map.Entry<String, RequirementDefinition> createRequirementDefinition( + String capabilityKey); + + @Override + String getMappedNodeTranslatedResourceId(ServiceTemplate nestedServiceTemplate, + Map.Entry<String, + CapabilityDefinition> connectionPointEntry) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + List<String> substitutionMapping = + nestedServiceTemplate.getTopology_template().getSubstitution_mappings().getCapabilities() + .get(connectionPointEntry.getKey()); + + mdcDataDebugMessage.debugExitMessage(null, null); + return substitutionMapping.get(0); + } + + @Override + Map.Entry<String, CapabilityDefinition> getMappedConnectionPointEntry( + ServiceTemplate nestedServiceTemplate, + Map.Entry<String, CapabilityDefinition> connectionPointEntry) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + List<String> 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> capabilityDefinition = + DataModelUtil.getCapabilityDefinition(substituteNodeType, mappedCapabilityId); + + mdcDataDebugMessage.debugExitMessage(null, null); + return new Map.Entry<String, CapabilityDefinition>() { + @Override + public String getKey() { + return mappedCapabilityId; + } + + @Override + public CapabilityDefinition getValue() { + return capabilityDefinition.get(); + } + + @Override + public CapabilityDefinition setValue(CapabilityDefinition value) { + return null; + } + }; + } + + @Override + protected List<Map<String, CapabilityDefinition>> getAllConnectionPoints() { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + List<Map<String, CapabilityDefinition>> exposedRequirementsList = new ArrayList<>(); + List<Predicate<CapabilityDefinition>> predicates = getPredicatesListForConnectionPoints(); + Map<String, CapabilityDefinition> 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<String, CapabilityDefinition> exposedRequirementsMap = new HashMap<>(); + exposedRequirementsMap.put(entry.getKey(), entry.getValue()); + exposedRequirementsList.add(exposedRequirementsMap); + }); + + mdcDataDebugMessage.debugExitMessage(null, null); + return exposedRequirementsList; + } + + void addRequirementToConnectResource(Map.Entry<String, CapabilityDefinition> connectionPointEntry, + List<String> 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<String, RequirementDefinition> requirementDefinition = + createRequirementDefinition(connectionPointEntry.getKey()); + + Optional<String> sourceResourceId = + getConnectionResourceUsingGetResourceFunc(connectionPointEntry, paramName, paramValue, + supportedSourceNodeTypes); + if (sourceResourceId.isPresent()) { + Resource sourceResource = HeatToToscaUtil + .getResource(translateTo.getHeatOrchestrationTemplate(), sourceResourceId.get(), + translateTo.getHeatFileName()); + Optional<String> 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<TranslatedHeatResource> 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<RequirementDefinition> { + 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<String, + RequirementDefinition> connectionPointEntry) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + List<String> substitutionMapping = + nestedServiceTemplate.getTopology_template().getSubstitution_mappings().getRequirements() + .get(connectionPointEntry.getKey()); + + mdcDataDebugMessage.debugExitMessage(null, null); + return substitutionMapping.get(0); + } + + @Override + Map.Entry<String, RequirementDefinition> getMappedConnectionPointEntry( + ServiceTemplate nestedServiceTemplate, + Map.Entry<String, RequirementDefinition> connectionPointEntry) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + List<String> 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> requirementDefinition = + DataModelUtil.getRequirementDefinition(substituteNodeType, mappedReqId); + + mdcDataDebugMessage.debugExitMessage(null, null); + return new Map.Entry<String, RequirementDefinition>() { + @Override + public String getKey() { + return mappedReqId; + } + + @Override + public RequirementDefinition getValue() { + return requirementDefinition.get(); + } + + @Override + public RequirementDefinition setValue(RequirementDefinition value) { + return null; + } + }; + } + + @Override + List<Map<String, RequirementDefinition>> getAllConnectionPoints() { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + List<Map<String, RequirementDefinition>> exposedRequirementsList = new ArrayList<>(); + List<Predicate<RequirementDefinition>> predicates = getPredicatesListForConnectionPoints(); + List<Map<String, RequirementDefinition>> 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<String, RequirementDefinition> exposedRequirementsMap = new HashMap<>(); + exposedRequirementsMap.put(entry.getKey(), entry.getValue()); + exposedRequirementsList.add(exposedRequirementsMap); + })); + + mdcDataDebugMessage.debugExitMessage(null, null); + return exposedRequirementsList; + } + + void addRequirementToConnectResource( + Map.Entry<String, RequirementDefinition> requirementDefinitionEntry, String paramName, + Object paramValue, List<String> 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<String> 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<String> translateResource(String heatFileName, ServiceTemplate serviceTemplate, + HeatOrchestrationTemplate heatOrchestrationTemplate, + Resource resource, String resourceId, + TranslationContext context) { + + mdcDataDebugMessage.debugEntryMessage("file, resource", heatFileName, resourceId); + Optional<String> 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<String> 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<String, String> 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<ToscaTopologyTemplateElements> 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<ToscaTopologyTemplateElements> 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<ToscaTopologyTemplateElements> 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<String> dependsOnList = (List<String>) 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<String> resourceTranslatedId = + getResourceTranslatedId(heatFileName, heatOrchestrationTemplate, dependsOnResourceId, + context); + + Optional<ToscaTopologyTemplateElements> 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<List<Map.Entry<String, Resource>>> getResourceByTranslatedResourceId( + String heatFileName, + HeatOrchestrationTemplate heatOrchestrationTemplate, + String translatedResourceId, + TranslateTo translateTo, + String heatResourceType) { + mdcDataDebugMessage.debugEntryMessage(null, null); + List<Map.Entry<String, Resource>> 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<Predicate<Map.Entry<String, Resource>>> getPredicatesForTranslatedIdToResourceId( + String heatFileName, HeatOrchestrationTemplate heatOrchestrationTemplate, + String translatedResourceId, TranslationContext context, String heatResourceType) { + List<Predicate<Map.Entry<String, Resource>>> list = new ArrayList<>(); + list.add(entry -> + entry.getValue().getType().equals(heatResourceType)); + list.add(entry -> { + Optional<String> resourceTranslatedId = + getResourceTranslatedId(heatFileName, heatOrchestrationTemplate, entry.getKey(), context); + return resourceTranslatedId.isPresent() + && resourceTranslatedId.get().equals(translatedResourceId); + }); + return list; + } + + boolean isResourceTypeSupported(Resource resource, List<String> 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<ToscaTopologyTemplateElements> 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> 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<String> 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<FileData> allFilesData = translateTo.getContext().getManifest().getContent().getData(); + Optional<FileData> fileData = HeatToToscaUtil.getFileData(heatFileName, allFilesData); + if (fileData.isPresent()) { + Optional<ResourceFileDataAndIDs> 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<String, Object> nodeTemplateProperties) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + Object size = nodeTemplateProperties.get("size"); + if (size == null) { + return; + } + + if (size instanceof Map) { + Map<String, Object> 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<ToscaTopologyTemplateElements> 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<String> 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<String> 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> 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<String> 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<String, Object> substitutionProperties, + ServiceTemplate nestedServiceTemplate, + Resource contrailServiceTemplateResource) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + Map<String, Object> 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<String, Object> 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<String, Object> 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<NodeType> contrailAbstractNodeType = + toscaAnalyzerService.fetchNodeType(ToscaNodeType.CONTRAIL_ABSTRACT_SUBSTITUTE, translateTo + .getContext().getGlobalServiceTemplates().values()); + + if (!contrailAbstractNodeType.isPresent()) { + return; + } + Map<String, AttributeDefinition> contrailAbstractAttributes = + contrailAbstractNodeType.get().getAttributes(); + Map<String, ParameterDefinition> nestedSubstitutionServiceTemplateOutputs = new HashMap<>(); + + if (contrailAbstractAttributes == null) { + return; + } + + for (String attributeKey : contrailAbstractAttributes.keySet()) { + AttributeDefinition abstractAttributeDef = contrailAbstractAttributes.get(attributeKey); + if (abstractAttributeDef != null) { + Map<String, List> 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<String> 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<AttachedResourceId> networkAttachedResourceId = HeatToToscaUtil + .extractAttachedResourceId(translateTo.getHeatFileName(), + translateTo.getHeatOrchestrationTemplate(), translateTo.getContext(), + virtualNetworkValue); + if (networkAttachedResourceId.isPresent()) { + Optional<String> networkResourceId = + HeatToToscaUtil.getContrailAttachedHeatResourceId(networkAttachedResourceId.get()); + if (networkResourceId.isPresent()) { + Resource networkResource = HeatToToscaUtil + .getResource(translateTo.getHeatOrchestrationTemplate(), networkResourceId.get(), + translateTo.getHeatFileName()); + if (validNetworksForConnections.contains(networkResource.getType())) { + Optional<String> 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<String, Object> 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<String> 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<NodeType> contrailAbstractNodeType = + toscaAnalyzerService.fetchNodeType(ToscaNodeType.CONTRAIL_ABSTRACT_SUBSTITUTE, translateTo + .getContext().getGlobalServiceTemplates().values()); + Map<String, ParameterDefinition> nestedSubstitutionServiceTemplateInputs = new HashMap<>(); + if (contrailAbstractNodeType.isPresent()) { + Map<String, PropertyDefinition> 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<NodeType> contrailComputeNodeType = toscaAnalyzerService + .fetchNodeType(ToscaNodeType.CONTRAIL_COMPUTE, + translateTo.getContext().getGlobalServiceTemplates().values()); + + Map<String, Object> computeNodeTemplateProperties = null; + if (contrailComputeNodeType.isPresent()) { + Map<String, PropertyDefinition> 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<String, Object> 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<String, String> 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<Map<String, Import>> 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<String> 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<List<Map<String, List>>> 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<List<Map<String, List>>> 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<List<Map<String, List>>> 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<Map<String, RequirementDefinition>> requirementList = new ArrayList<>(); + for (int i = 0; i < numberOfPorts; i++) { + Map<String, RequirementDefinition> 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<AttachedResourceId> 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<String, Object> 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<ToscaTopologyTemplateElements> 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<String, String> 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<AttachedResourceId> 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<AttachedResourceId> 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<AttachedResourceId> extractNetworkPolicyId(Object propertyValue, + TranslateTo translateTo) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + List<AttachedResourceId> 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<String> 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<Object> 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<String> 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<String> 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<String> 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<String, Object>)macAddressesValue).containsKey + (toscaVmiMacAddressesMacAddressesName)){ + updateMacAddressesMacAddressesInProperties(nodeTemplate, toscaVmiMacAddressesName, + toscaVmiMacAddressesMacAddressesName, + (Map<String, Object>) macAddressesValue); + } + } + } + + private void updateMacAddressesMacAddressesInProperties(NodeTemplate nodeTemplate, + String toscaVmiMacAddressesName, + String toscaVmiMacAddressesMacAddressesName, + Map<String, Object> 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<ToscaTopologyTemplateElements> 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<String, Object> properties = translateTo.getResource().getProperties(); + Optional<Object> 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<AttachedResourceId> 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<String> 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<String> 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<String> supportedSecurityGroupsTypes) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + String resourceId = (String) securityGroupResourceId.getEntityId(); + Resource securityGroupResource = HeatToToscaUtil + .getResource(translateTo.getHeatOrchestrationTemplate(), resourceId, + translateTo.getHeatFileName()); + Optional<String> 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<AttachedResourceId> 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<String> 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<String> 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<AttachedResourceId> subnetNetwork = getAttachedNetworkResource(translateTo); + + if (!subnetNetwork.isPresent() || !subnetNetwork.get().isGetResource()) { + return; + } + + Resource networkResource = HeatToToscaUtil + .getResource(translateTo.getHeatOrchestrationTemplate(), + (String) subnetNetwork.get().getEntityId(), translateTo.getHeatFileName()); + Optional<String> 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<String, Map<String, Object>> subNetMap = + (Map<String, Map<String, Object>>) 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<String, Object> 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<AttachedResourceId> 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<AttachedResourceId> getAttachedNetworkResource(TranslateTo translateTo) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + Optional<AttachedResourceId> subnetNetwork = Optional.empty(); + Optional<AttachedResourceId> attachedNetworkId = + HeatToToscaUtil.extractAttachedResourceId(translateTo, "network_id"); + if (!attachedNetworkId.isPresent()) { + Optional<AttachedResourceId> 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<String> 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<ToscaTopologyTemplateElements> getTranslatedToscaTopologyElement( + TranslateTo translateTo) { + if (isEssentialRequirementsValid(translateTo)) { + return Optional.of(ToscaTopologyTemplateElements.GROUP); + } else { + return Optional.empty(); + } + } + + private boolean validatePolicyType(TranslateTo translateTo) { + Map<String, Object> 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<String> 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<String> 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<String> 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<String> getToscaPolicies(Resource resource, String resourceId) { + mdcDataDebugMessage.debugEntryMessage(null, null); + + Map<String, Object> properties = resource.getProperties(); + if (Objects.isNull(properties) || Objects.isNull(properties.get("policies"))) { + return Arrays.asList(ToscaPolicyType.PLACEMENT_ANTILOCATE); + } + + List<Object> policies = (List) properties.get("policies"); + List<String> 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<String, Object> 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<String, Object> 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<String, Object>) 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<String, Object> schedulerHints) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + for (Object hint : schedulerHints.values()) { + Optional<AttachedResourceId> 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<String, GroupDefinition> 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<String> 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<String, Object> 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<Map<String, Object>> blockDeviceMappingList = getBlockDeviceMappingList(resource); + if (CollectionUtils.isEmpty(blockDeviceMappingList)) { + return; + } + + Object volumeIdObject; + Object snapshotIdObject; + String volumeResourceId; + int index = 0; + for (Map<String, Object> 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<AttachedResourceId> 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<AttachedResourceId> 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<String, Object> 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<String, Object> 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<Map<String, Object>> getBlockDeviceMappingList(Resource resource) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + if (Objects.isNull(resource.getProperties())) { + return Collections.emptyList(); + } + List<Map<String, Object>> blockDeviceMappingList = + (List<Map<String, Object>>) resource.getProperties().get("block_device_mapping"); + List<Map<String, Object>> blockDeviceMappingV2List = + (List<Map<String, Object>>) 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<Map<String, Object>> heatNetworkList = + (List<Map<String, Object>>) resource.getProperties().get("networks"); + + if (CollectionUtils.isEmpty(heatNetworkList)) { + return; + } + + for (Map<String, Object> 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<AttachedResourceId> 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<String, Object> properties = portResource.getProperties(); + if (!MapUtils.isEmpty(properties) && Objects.nonNull(properties.get("port_tuple_refs"))) { + novaNodeTemplate.getProperties().put("contrail_service_instance_ind", true); + } + } + Optional<String> 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<PropertyRegexMatcher> getPropertyRegexMatchersForNovaNodeType() { + List<PropertyRegexMatcher> 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<String, Object>) ((Map) resourceDef).get("properties")); + nestedResource.setMetadata(((Map) resourceDef).get("metadata")); + + Optional<String> 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<String, Object>) 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<String, List> getNewIndexVarValue() { + final Map<String, List> 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<String, Object> properties) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + if (properties == null || properties.isEmpty()) { + return; + } + + for (Map.Entry<String, Object> 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<String, List<Object>> concatMap = new HashMap<>(); + List<Object> 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<String, Object>) 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<Predicate<CapabilityDefinition>> getPredicatesListForConnectionPoints() { + ArrayList<Predicate<CapabilityDefinition>> predicates = new ArrayList<>(); + predicates.add(cap -> cap.getType().equals(ToscaCapabilityType.NATIVE_ATTACHMENT)); + return predicates; + } + + @Override + protected Optional<List<String>> getConnectorPropertyParamName(String heatResourceId, + Resource heatResource, + HeatOrchestrationTemplate + nestedHeatOrchestrationTemplate, + String nestedHeatFileName) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + Object securityGroups = + heatResource.getProperties().get(Constants.SECURITY_GROUPS_PROPERTY_NAME); + List<String> paramsList = new ArrayList<>(); + if (securityGroups instanceof List) { + ((List) securityGroups).forEach(group -> { + Optional<AttachedResourceId> 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<String, CapabilityDefinition> connectionPointEntry, List<String> paramNames) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + if (paramNames == null || paramNames.isEmpty()) { + return; + } + List<String> 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<String> 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<String, RequirementDefinition> 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<String, RequirementDefinition>() { + @Override + public String getKey() { + return ToscaConstants.PORT_REQUIREMENT_ID; + } + + @Override + public RequirementDefinition getValue() { + return definition; + } + + @Override + public RequirementDefinition setValue(RequirementDefinition value) { + return null; + } + }; + } + + +} |