Fix issues creating control loop model
[sdc.git] / catalog-model / src / main / java / org / openecomp / sdc / be / model / jsonjanusgraph / operations / ToscaOperationFacade.java
index 205a48e..d477b8c 100644 (file)
@@ -39,10 +39,13 @@ import java.util.LinkedList;
 import java.util.List;
 import java.util.Map;
 import java.util.Map.Entry;
+import java.util.Objects;
 import java.util.Optional;
 import java.util.Set;
 import java.util.function.BiPredicate;
+import java.util.function.Predicate;
 import java.util.stream.Collectors;
+import java.util.stream.StreamSupport;
 import org.apache.commons.collections.CollectionUtils;
 import org.apache.commons.collections.MapUtils;
 import org.apache.commons.lang3.StringUtils;
@@ -54,7 +57,7 @@ import org.openecomp.sdc.be.config.Configuration;
 import org.openecomp.sdc.be.config.ConfigurationManager;
 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
 import org.openecomp.sdc.be.dao.jsongraph.GraphVertex;
-import org.openecomp.sdc.be.dao.jsongraph.HealingJanusGraphDao;
+import org.openecomp.sdc.be.dao.janusgraph.HealingJanusGraphDao;
 import org.openecomp.sdc.be.dao.jsongraph.types.EdgeLabelEnum;
 import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
 import org.openecomp.sdc.be.dao.jsongraph.types.VertexTypeEnum;
@@ -112,7 +115,6 @@ import org.openecomp.sdc.be.model.catalog.CatalogComponent;
 import org.openecomp.sdc.be.model.jsonjanusgraph.config.ContainerInstanceTypesData;
 import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.TopologyTemplate;
 import org.openecomp.sdc.be.model.jsonjanusgraph.datamodel.ToscaElement;
-import org.openecomp.sdc.be.model.jsonjanusgraph.operations.exception.OperationException;
 import org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter;
 import org.openecomp.sdc.be.model.operations.StorageException;
 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
@@ -137,6 +139,7 @@ public class ToscaOperationFacade {
     private static final String FAILED_TO_GET_UPDATED_RESOURCE_STATUS_IS = "Failed to get updated resource {}. Status is {}. ";
     private static final String FAILED_TO_ADD_THE_PROPERTY_TO_THE_RESOURCE_STATUS_IS = "Failed to add the property {} to the resource {}. Status is {}. ";
     private static final String SERVICE = "service";
+    private static final String VF = "VF";
     private static final String NOT_SUPPORTED_COMPONENT_TYPE = "Not supported component type {}";
     private static final String COMPONENT_CREATED_SUCCESSFULLY = "Component created successfully!!!";
     private static final String COULDNT_FETCH_COMPONENT_WITH_AND_UNIQUE_ID_ERROR = "Couldn't fetch component with and unique id {}, error: {}";
@@ -348,19 +351,56 @@ public class ToscaOperationFacade {
         return ModelConverter.isAtomicComponent(component) ? nodeTypeOperation : topologyTemplateOperation;
     }
 
-    public <T extends Component> Either<T, StorageOperationStatus> getLatestByToscaResourceName(String toscaResourceName) {
-        return getLatestByName(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName);
+    public <T extends Component> Either<T, StorageOperationStatus> getLatestByToscaResourceNameAndModel(final String toscaResourceName,
+                                                                                                        final String model) {
+        return getLatestByNameAndModel(toscaResourceName, JsonParseFlagEnum.ParseMetadata, new ComponentParametersView(), model);
+    }
+
+    private <T extends Component> Either<T, StorageOperationStatus> getLatestByNameAndModel(final String nodeName,
+                                                                                            final JsonParseFlagEnum parseFlag,
+                                                                                            final ComponentParametersView filter,
+                                                                                            final String model) {
+        Either<T, StorageOperationStatus> result;
+        final Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
+        final Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
+        propertiesToMatch.put(GraphPropertyEnum.TOSCA_RESOURCE_NAME, nodeName);
+        propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
+        propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
+        final Either<List<GraphVertex>, JanusGraphOperationStatus> highestResources = janusGraphDao
+            .getByCriteria(null, propertiesToMatch, propertiesNotToMatch, parseFlag, model);
+        if (highestResources.isRight()) {
+            final JanusGraphOperationStatus status = highestResources.right().value();
+            log.debug("failed to find resource with name {}. status={} ", nodeName, status);
+            result = Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status));
+            return result;
+        }
+        final List<GraphVertex> resources = highestResources.left().value();
+        double version = 0.0;
+        GraphVertex highestResource = null;
+        for (final GraphVertex vertex : resources) {
+            final Object versionObj = vertex.getMetadataProperty(GraphPropertyEnum.VERSION);
+            double resourceVersion = Double.parseDouble((String) versionObj);
+            if (resourceVersion > version) {
+                version = resourceVersion;
+                highestResource = vertex;
+            }
+        }
+        return getToscaElementByOperation(highestResource, filter);
+    }
+
+    public <T extends Component> Either<T, StorageOperationStatus> getLatestByToscaResourceName(String toscaResourceName, String modelName) {
+        return getLatestByName(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName, modelName);
     }
 
     public <T extends Component> Either<T, StorageOperationStatus> getFullLatestComponentByToscaResourceName(String toscaResourceName) {
         ComponentParametersView fetchAllFilter = new ComponentParametersView();
         fetchAllFilter.setIgnoreServicePath(true);
         fetchAllFilter.setIgnoreCapabiltyProperties(false);
-        return getLatestByName(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName, JsonParseFlagEnum.ParseAll, fetchAllFilter);
+        return getLatestByName(GraphPropertyEnum.TOSCA_RESOURCE_NAME, toscaResourceName, JsonParseFlagEnum.ParseAll, fetchAllFilter, null);
     }
 
-    public <T extends Component> Either<T, StorageOperationStatus> getLatestByName(String resourceName) {
-        return getLatestByName(GraphPropertyEnum.NAME, resourceName);
+    public <T extends Component> Either<T, StorageOperationStatus> getLatestByName(String resourceName, String modelName) {
+        return getLatestByName(GraphPropertyEnum.NAME, resourceName, modelName);
     }
 
     public StorageOperationStatus validateCsarUuidUniqueness(String csarUUID) {
@@ -419,7 +459,7 @@ public class ToscaOperationFacade {
         props.put(GraphPropertyEnum.STATE, LifecycleStateEnum.CERTIFIED.name());
         Map<String, Entry<JanusGraphPredicate, Object>> predicateCriteria = getVendorVersionPredicate(vendorRelease);
         Either<List<GraphVertex>, JanusGraphOperationStatus> getLatestRes = janusGraphDao
-            .getByCriteria(vertexType, props, null, predicateCriteria, parseFlag);
+            .getByCriteria(vertexType, props, null, predicateCriteria, parseFlag, null);
         if (getLatestRes.isRight() || CollectionUtils.isEmpty(getLatestRes.left().value())) {
             getLatestRes = janusGraphDao.getByCriteria(vertexType, props, parseFlag);
         }
@@ -446,7 +486,7 @@ public class ToscaOperationFacade {
         });
     }
 
-    public <T extends Component> Either<T, StorageOperationStatus> getByToscaResourceNameAndVersion(final String toscaResourceName, final String version) {
+    public <T extends Component> Either<T, StorageOperationStatus> getByToscaResourceNameAndVersion(final String toscaResourceName, final String version, final String model) {
         Either<T, StorageOperationStatus> result;
 
         Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class);
@@ -457,7 +497,7 @@ public class ToscaOperationFacade {
         hasNotProperties.put(GraphPropertyEnum.IS_DELETED, true);
 
         Either<List<GraphVertex>, JanusGraphOperationStatus> getResourceRes = janusGraphDao
-            .getByCriteria(VertexTypeEnum.NODE_TYPE, hasProperties, hasNotProperties, JsonParseFlagEnum.ParseAll);
+            .getByCriteria(VertexTypeEnum.NODE_TYPE, hasProperties, hasNotProperties, JsonParseFlagEnum.ParseAll, model);
         if (getResourceRes.isRight()) {
             JanusGraphOperationStatus status = getResourceRes.right().value();
             log.debug("failed to find resource with toscaResourceName {}, version {}. Status is {} ", toscaResourceName, version, status);
@@ -483,6 +523,28 @@ public class ToscaOperationFacade {
         return predicateCriteria;
     }
 
+    public boolean isNodeAssociatedToModel(final String model, final Resource resource) {
+        final List<GraphVertex> modelElementVertices = getResourceModelElementVertices(resource);
+        if (model == null) {
+            return modelElementVertices.isEmpty();
+        }
+        return modelElementVertices.stream().anyMatch(graphVertex -> graphVertex.getMetadataProperty(GraphPropertyEnum.NAME).equals(model));
+    }
+
+    public List<GraphVertex> getResourceModelElementVertices(final Resource resource) {
+        final Either<GraphVertex, JanusGraphOperationStatus> vertex =
+            janusGraphDao.getVertexById(resource.getUniqueId(), JsonParseFlagEnum.NoParse);
+        if (vertex.isRight() || Objects.isNull(vertex.left().value())) {
+            return Collections.emptyList();
+        }
+        final Either<List<GraphVertex>, JanusGraphOperationStatus> nodeModelVertices =
+            janusGraphDao.getParentVertices(vertex.left().value(), EdgeLabelEnum.MODEL_ELEMENT, JsonParseFlagEnum.NoParse);
+        if (nodeModelVertices.isRight() || nodeModelVertices.left().value() == null) {
+            return Collections.emptyList();
+        }
+        return nodeModelVertices.left().value();
+    }
+
     private boolean isValidForVendorRelease(final GraphVertex resource, final String vendorRelease) {
         if (!vendorRelease.equals("1.0")) {
             try {
@@ -733,13 +795,13 @@ public class ToscaOperationFacade {
     }
 
     private <T extends Component> Either<T, StorageOperationStatus> getLatestByName(GraphPropertyEnum property, String nodeName,
-                                                                                    JsonParseFlagEnum parseFlag) {
-        return getLatestByName(property, nodeName, parseFlag, new ComponentParametersView());
+                                                                                    JsonParseFlagEnum parseFlag, String modelName) {
+        return getLatestByName(property, nodeName, parseFlag, new ComponentParametersView(), modelName);
     }
-    // endregion
 
     private <T extends Component> Either<T, StorageOperationStatus> getLatestByName(GraphPropertyEnum property, String nodeName,
-                                                                                    JsonParseFlagEnum parseFlag, ComponentParametersView filter) {
+                                                                                    JsonParseFlagEnum parseFlag, ComponentParametersView filter,
+                                                                                    String model) {
         Either<T, StorageOperationStatus> result;
         Map<GraphPropertyEnum, Object> propertiesToMatch = new EnumMap<>(GraphPropertyEnum.class);
         Map<GraphPropertyEnum, Object> propertiesNotToMatch = new EnumMap<>(GraphPropertyEnum.class);
@@ -747,7 +809,7 @@ public class ToscaOperationFacade {
         propertiesToMatch.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
         propertiesNotToMatch.put(GraphPropertyEnum.IS_DELETED, true);
         Either<List<GraphVertex>, JanusGraphOperationStatus> highestResources = janusGraphDao
-            .getByCriteria(null, propertiesToMatch, propertiesNotToMatch, parseFlag);
+            .getByCriteria(null, propertiesToMatch, propertiesNotToMatch, parseFlag, model);
         if (highestResources.isRight()) {
             JanusGraphOperationStatus status = highestResources.right().value();
             log.debug("failed to find resource with name {}. status={} ", nodeName, status);
@@ -769,8 +831,8 @@ public class ToscaOperationFacade {
     }
 
     // region - Component Get By ..
-    private <T extends Component> Either<T, StorageOperationStatus> getLatestByName(GraphPropertyEnum property, String nodeName) {
-        return getLatestByName(property, nodeName, JsonParseFlagEnum.ParseMetadata);
+    private <T extends Component> Either<T, StorageOperationStatus> getLatestByName(GraphPropertyEnum property, String nodeName, String modelName) {
+        return getLatestByName(property, nodeName, JsonParseFlagEnum.ParseMetadata, modelName);
     }
 
     public <T extends Component> Either<List<T>, StorageOperationStatus> getBySystemName(ComponentTypeEnum componentType, String systemName) {
@@ -841,8 +903,8 @@ public class ToscaOperationFacade {
     }
 
     public <T extends Component> Either<T, StorageOperationStatus> getComponentByNameAndVendorRelease(final ComponentTypeEnum componentType,
-                                                                                                      final String name, final String vendorRelease,
-                                                                                                      final JsonParseFlagEnum parseFlag) {
+        final String name, final String vendorRelease,
+        final JsonParseFlagEnum parseFlag, final String modelName) {
         Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class);
         Map<GraphPropertyEnum, Object> hasNotProperties = new EnumMap<>(GraphPropertyEnum.class);
         hasProperties.put(GraphPropertyEnum.NAME, name);
@@ -851,8 +913,8 @@ public class ToscaOperationFacade {
             hasProperties.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
         }
         Map<String, Entry<JanusGraphPredicate, Object>> predicateCriteria = getVendorVersionPredicate(vendorRelease);
-        Either<List<GraphVertex>, JanusGraphOperationStatus> getResourceRes = janusGraphDao
-            .getByCriteria(null, hasProperties, hasNotProperties, predicateCriteria, parseFlag);
+        Either<List<GraphVertex>, JanusGraphOperationStatus> getResourceRes = janusGraphDao.getByCriteria(null, hasProperties, hasNotProperties,
+            predicateCriteria, parseFlag, modelName);
         if (getResourceRes.isRight()) {
             JanusGraphOperationStatus status = getResourceRes.right().value();
             log.debug("failed to find resource with name {}, version {}. Status is {} ", name, predicateCriteria, status);
@@ -1808,6 +1870,36 @@ public class ToscaOperationFacade {
         updateInstancesCapAndReqOnComponentFromDB(component);
         return storageOperationStatus;
     }
+    
+    public StorageOperationStatus updateCalculatedCapabilitiesRequirements(final Map<ComponentInstance, Map<String, List<CapabilityDefinition>>> instCapabilties,
+            final Map<ComponentInstance, Map<String, List<RequirementDefinition>>> instReg,
+            final Component component) {
+        StorageOperationStatus storageOperationStatus = StorageOperationStatus.OK;
+        if (instCapabilties != null) {
+            for (Entry<ComponentInstance, Map<String, List<CapabilityDefinition>>> entry : instCapabilties.entrySet()) {
+                final Map<String, List<CapabilityDefinition>> cap = entry.getValue();
+                for (List<CapabilityDefinition> capabilityList: cap.values()) {
+                    for (CapabilityDefinition capability: capabilityList) {
+                        nodeTemplateOperation.updateComponentInstanceCapabilities(component.getUniqueId(), entry.getKey().getUniqueId(), capability);
+                    }
+                }
+            }
+        }
+        if (instReg != null) {
+            for (Entry<ComponentInstance, Map<String, List<RequirementDefinition>>> entry : instReg.entrySet()) {
+                final Map<String, List<RequirementDefinition>> req = entry.getValue();
+                for (List<RequirementDefinition> requirementList: req.values()) {
+                    for (RequirementDefinition requirement: requirementList) {
+                        storageOperationStatus = nodeTemplateOperation.updateComponentInstanceRequirement(component.getUniqueId(), entry.getKey().getUniqueId(), requirement);
+                        if (storageOperationStatus != StorageOperationStatus.OK) {
+                            return storageOperationStatus;
+                        }
+                    }
+                }
+            }
+        }
+        return storageOperationStatus;
+    }
 
     private void updateInstancesCapAndReqOnComponentFromDB(Component component) {
         ComponentParametersView componentParametersView = new ComponentParametersView(true);
@@ -1826,41 +1918,43 @@ public class ToscaOperationFacade {
     }
 
     private Either<List<Service>, StorageOperationStatus> getLatestVersionNonCheckoutServicesMetadataOnly(Map<GraphPropertyEnum, Object> hasProps,
-                                                                                                          Map<GraphPropertyEnum, Object> hasNotProps) {
+                                                                                                          Map<GraphPropertyEnum, Object> hasNotProps,
+                                                                                                          String modelName) {
         List<Service> services = new ArrayList<>();
         List<LifecycleStateEnum> states = new ArrayList<>();
         // include props
         hasProps.put(GraphPropertyEnum.COMPONENT_TYPE, ComponentTypeEnum.SERVICE.name());
         hasProps.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
+        if (modelName != null) {
+            hasProps.put(GraphPropertyEnum.MODEL, modelName);
+        }
         // exclude props
         states.add(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
         hasNotProps.put(GraphPropertyEnum.STATE, states);
         hasNotProps.put(GraphPropertyEnum.IS_DELETED, true);
         hasNotProps.put(GraphPropertyEnum.IS_ARCHIVED, true);
-        return fetchServicesByCriteria(services, hasProps, hasNotProps);
+        return fetchServicesByCriteria(services, hasProps, hasNotProps, modelName);
     }
 
-    private Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractToscaElementsMetadataOnly(boolean isAbstract,
-                                                                                                                 ComponentTypeEnum componentTypeEnum,
-                                                                                                                 String internalComponentType,
-                                                                                                                 VertexTypeEnum vertexType) {
+    private Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractToscaElementsMetadataOnly(final boolean isAbstract,
+                                                                                                                 final ComponentTypeEnum componentTypeEnum,
+                                                                                                                 final String internalComponentType,
+                                                                                                                 final VertexTypeEnum vertexType,
+                                                                                                                 final String modelName,
+                                                                                                                 final boolean includeNormativeExtensionModels) {
         List<Service> services = null;
         Map<GraphPropertyEnum, Object> hasProps = new EnumMap<>(GraphPropertyEnum.class);
         Map<GraphPropertyEnum, Object> hasNotProps = new EnumMap<>(GraphPropertyEnum.class);
-        fillPropsMap(hasProps, hasNotProps, internalComponentType, componentTypeEnum, isAbstract, vertexType);
+        fillPropsMap(hasProps, hasNotProps, internalComponentType, componentTypeEnum, isAbstract, vertexType, modelName);
         Either<List<GraphVertex>, JanusGraphOperationStatus> getRes = janusGraphDao
-            .getByCriteria(vertexType, hasProps, hasNotProps, JsonParseFlagEnum.ParseMetadata);
-        if (getRes.isRight()) {
-            if (getRes.right().value().equals(JanusGraphOperationStatus.NOT_FOUND)) {
-                return Either.left(new ArrayList<>());
-            } else {
-                return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getRes.right().value()));
-            }
+            .getByCriteria(vertexType, hasProps, hasNotProps, JsonParseFlagEnum.ParseMetadata, modelName, includeNormativeExtensionModels);
+        if (getRes.isRight() && !JanusGraphOperationStatus.NOT_FOUND.equals(getRes.right().value())) {
+            return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getRes.right().value()));
         }
         // region -> Fetch non checked-out services
         if (internalComponentType != null && internalComponentType.toLowerCase().trim().equals(SERVICE) && VertexTypeEnum.NODE_TYPE == vertexType) {
             Either<List<Service>, StorageOperationStatus> result = getLatestVersionNonCheckoutServicesMetadataOnly(
-                new EnumMap<>(GraphPropertyEnum.class), new EnumMap<>(GraphPropertyEnum.class));
+                new EnumMap<>(GraphPropertyEnum.class), new EnumMap<>(GraphPropertyEnum.class), modelName);
             if (result.isRight()) {
                 log.debug("Failed to fetch services for");
                 return Either.right(result.right().value());
@@ -1874,15 +1968,17 @@ public class ToscaOperationFacade {
         List<Component> nonAbstractLatestComponents = new ArrayList<>();
         ComponentParametersView params = new ComponentParametersView(true);
         params.setIgnoreAllVersions(false);
-        for (GraphVertex vertexComponent : getRes.left().value()) {
-            Either<ToscaElement, StorageOperationStatus> componentRes = topologyTemplateOperation
-                .getLightComponent(vertexComponent, componentTypeEnum, params);
-            if (componentRes.isRight()) {
-                log.debug("Failed to fetch light element for {} error {}", vertexComponent.getUniqueId(), componentRes.right().value());
-                return Either.right(componentRes.right().value());
-            } else {
-                Component component = ModelConverter.convertFromToscaElement(componentRes.left().value());
-                nonAbstractLatestComponents.add(component);
+        if (getRes.isLeft()) {
+            for (GraphVertex vertexComponent : getRes.left().value()) {
+                Either<ToscaElement, StorageOperationStatus> componentRes = topologyTemplateOperation
+                    .getLightComponent(vertexComponent, componentTypeEnum, params);
+                if (componentRes.isRight()) {
+                    log.debug("Failed to fetch light element for {} error {}", vertexComponent.getUniqueId(), componentRes.right().value());
+                    return Either.right(componentRes.right().value());
+                } else {
+                    Component component = ModelConverter.convertFromToscaElement(componentRes.left().value());
+                    nonAbstractLatestComponents.add(component);
+                }
             }
         }
         if (CollectionUtils.isNotEmpty(services)) {
@@ -1976,7 +2072,7 @@ public class ToscaOperationFacade {
     private Either<List<String>, StorageOperationStatus> getComponentUids(boolean isAbstract, ComponentTypeEnum componentTypeEnum,
                                                                           String internalComponentType) {
         Either<List<Component>, StorageOperationStatus> getToscaElementsRes = getLatestVersionNotAbstractMetadataOnly(isAbstract, componentTypeEnum,
-            internalComponentType);
+            internalComponentType, null, false);
         if (getToscaElementsRes.isRight()) {
             return Either.right(getToscaElementsRes.right().value());
         }
@@ -2006,16 +2102,11 @@ public class ToscaOperationFacade {
         }
         return result;
     }
-
     public Either<Boolean, StorageOperationStatus> validateComponentNameUniqueness(String name, ResourceTypeEnum resourceType,
                                                                                    ComponentTypeEnum componentType) {
-        VertexTypeEnum vertexType = ModelConverter.isAtomicComponent(resourceType) ? VertexTypeEnum.NODE_TYPE : VertexTypeEnum.TOPOLOGY_TEMPLATE;
         String normalizedName = ValidationUtils.normaliseComponentName(name);
-        Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class);
-        properties.put(GraphPropertyEnum.NORMALIZED_NAME, normalizedName);
-        properties.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
         Either<List<GraphVertex>, JanusGraphOperationStatus> vertexEither = janusGraphDao
-            .getByCriteria(vertexType, properties, JsonParseFlagEnum.NoParse);
+            .getByCriteria(getVertexTypeEnum(resourceType), propertiesToMatch(normalizedName, componentType), JsonParseFlagEnum.NoParse);
         if (vertexEither.isRight() && vertexEither.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
             log.debug("failed to get vertex from graph with property normalizedName: {}", normalizedName);
             return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(vertexEither.right().value()));
@@ -2023,12 +2114,47 @@ public class ToscaOperationFacade {
         return Either.left(CollectionUtils.isEmpty(vertexEither.isLeft() ? vertexEither.left().value() : null));
     }
 
+    public Either<Boolean, StorageOperationStatus> validateComponentNameAndModelExists(final String resourceName, final String model,
+                                                                                       final ResourceTypeEnum resourceType,
+                                                                                       final ComponentTypeEnum componentType) {
+        Either<Boolean, StorageOperationStatus> result = validateComponentNameAndModelUniqueness(resourceName, model, resourceType, componentType);
+        if (result.isLeft()) {
+            result = Either.left(!result.left().value());
+        }
+        return result;
+    }
+
+    private Either<Boolean, StorageOperationStatus> validateComponentNameAndModelUniqueness(final String resourceName, final String modelName,
+                                                                                            final ResourceTypeEnum resourceType,
+                                                                                            final ComponentTypeEnum componentType) {
+        final String normalizedName = ValidationUtils.normaliseComponentName(resourceName);
+        final Either<List<GraphVertex>, JanusGraphOperationStatus> vertexEither = janusGraphDao
+            .getByCriteria(getVertexTypeEnum(resourceType), propertiesToMatch(normalizedName, componentType), null, null, JsonParseFlagEnum.NoParse, modelName);
+        if (vertexEither.isRight() && vertexEither.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
+            log.debug("failed to get vertex from graph with property normalizedName: {} and model: {}", normalizedName, modelName);
+            return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(vertexEither.right().value()));
+        }
+        return Either.left(CollectionUtils.isEmpty(vertexEither.isLeft() ? vertexEither.left().value().stream()
+            .collect(Collectors.toList()) : null));
+    }
+
+    private VertexTypeEnum getVertexTypeEnum(final ResourceTypeEnum resourceType) {
+        return ModelConverter.isAtomicComponent(resourceType) ? VertexTypeEnum.NODE_TYPE : VertexTypeEnum.TOPOLOGY_TEMPLATE;
+    }
+
+    private Map<GraphPropertyEnum, Object> propertiesToMatch(final String normalizedName, final ComponentTypeEnum componentType) {
+        final Map<GraphPropertyEnum, Object> properties = new EnumMap<>(GraphPropertyEnum.class);
+        properties.put(GraphPropertyEnum.NORMALIZED_NAME, normalizedName);
+        properties.put(GraphPropertyEnum.COMPONENT_TYPE, componentType.name());
+        return properties;
+    }
+
     private void fillNodeTypePropsMap(final Map<GraphPropertyEnum, Object> hasProps, final Map<GraphPropertyEnum, Object> hasNotProps,
-                                      final String internalComponentType) {
+                                      final String internalComponentType, String modelName) {
         final Configuration configuration = ConfigurationManager.getConfigurationManager().getConfiguration();
         final List<String> allowedTypes;
         if (ComponentTypeEnum.SERVICE.getValue().equalsIgnoreCase(internalComponentType)) {
-            allowedTypes = containerInstanceTypesData.getComponentAllowedList(ComponentTypeEnum.SERVICE, null);
+            allowedTypes = containerInstanceTypesData.getServiceAllowedList(modelName);
         } else {
             final ResourceTypeEnum resourceType = ResourceTypeEnum.getTypeIgnoreCase(internalComponentType);
             allowedTypes = containerInstanceTypesData.getComponentAllowedList(ComponentTypeEnum.RESOURCE, resourceType);
@@ -2062,15 +2188,16 @@ public class ToscaOperationFacade {
     }
 
     private void fillPropsMap(Map<GraphPropertyEnum, Object> hasProps, Map<GraphPropertyEnum, Object> hasNotProps, String internalComponentType,
-                              ComponentTypeEnum componentTypeEnum, boolean isAbstract, VertexTypeEnum internalVertexType) {
+                              ComponentTypeEnum componentTypeEnum, boolean isAbstract, VertexTypeEnum internalVertexType, String modelName) {
         hasNotProps.put(GraphPropertyEnum.STATE, LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name());
         hasNotProps.put(GraphPropertyEnum.IS_DELETED, true);
         hasNotProps.put(GraphPropertyEnum.IS_ARCHIVED, true);
         hasProps.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
+
         if (VertexTypeEnum.NODE_TYPE == internalVertexType) {
             hasProps.put(GraphPropertyEnum.IS_ABSTRACT, isAbstract);
             if (internalComponentType != null) {
-                fillNodeTypePropsMap(hasProps, hasNotProps, internalComponentType);
+                fillNodeTypePropsMap(hasProps, hasNotProps, internalComponentType, modelName);
             }
         } else {
             fillTopologyTemplatePropsMap(hasProps, hasNotProps, componentTypeEnum);
@@ -2082,20 +2209,22 @@ public class ToscaOperationFacade {
         if (ComponentTypeEnum.RESOURCE == componentTypeEnum) {
             internalVertexTypes.add(VertexTypeEnum.NODE_TYPE);
         }
-        if (ComponentTypeEnum.SERVICE == componentTypeEnum || SERVICE.equalsIgnoreCase(internalComponentType)) {
+        if (ComponentTypeEnum.SERVICE == componentTypeEnum || SERVICE.equalsIgnoreCase(internalComponentType) || VF.equalsIgnoreCase(internalComponentType)) {
             internalVertexTypes.add(VertexTypeEnum.TOPOLOGY_TEMPLATE);
         }
         return internalVertexTypes;
     }
 
     public Either<List<Component>, StorageOperationStatus> getLatestVersionNotAbstractMetadataOnly(boolean isAbstract,
-                                                                                                   ComponentTypeEnum componentTypeEnum,
-                                                                                                   String internalComponentType) {
+                                                                                                   final ComponentTypeEnum componentTypeEnum,
+                                                                                                   final String internalComponentType,
+                                                                                                   final String modelName,
+                                                                                                   final boolean includeNormativeExtensionModels) {
         List<VertexTypeEnum> internalVertexTypes = getInternalVertexTypes(componentTypeEnum, internalComponentType);
         List<Component> result = new ArrayList<>();
         for (VertexTypeEnum vertexType : internalVertexTypes) {
             Either<List<Component>, StorageOperationStatus> listByVertexType = getLatestVersionNotAbstractToscaElementsMetadataOnly(isAbstract,
-                componentTypeEnum, internalComponentType, vertexType);
+                componentTypeEnum, internalComponentType, vertexType, modelName, includeNormativeExtensionModels);
             if (listByVertexType.isRight()) {
                 return listByVertexType;
             }
@@ -2229,7 +2358,7 @@ public class ToscaOperationFacade {
     }
 
     public <T extends Component> Either<T, StorageOperationStatus> getLatestByNameAndVersion(String name, String version,
-                                                                                             JsonParseFlagEnum parseFlag) {
+                                                                                             JsonParseFlagEnum parseFlag, String model) {
         Either<T, StorageOperationStatus> result;
         Map<GraphPropertyEnum, Object> hasProperties = new EnumMap<>(GraphPropertyEnum.class);
         Map<GraphPropertyEnum, Object> hasNotProperties = new EnumMap<>(GraphPropertyEnum.class);
@@ -2238,7 +2367,7 @@ public class ToscaOperationFacade {
         hasProperties.put(GraphPropertyEnum.IS_HIGHEST_VERSION, true);
         hasNotProperties.put(GraphPropertyEnum.IS_DELETED, true);
         Either<List<GraphVertex>, JanusGraphOperationStatus> getResourceRes = janusGraphDao
-            .getByCriteria(null, hasProperties, hasNotProperties, parseFlag);
+            .getByCriteria(null, hasProperties, hasNotProperties, parseFlag, model);
         if (getResourceRes.isRight()) {
             JanusGraphOperationStatus status = getResourceRes.right().value();
             log.debug("failed to find resource with name {}, version {}. Status is {} ", name, version, status);
@@ -2304,10 +2433,10 @@ public class ToscaOperationFacade {
                     log.debug("getLatestResourceByCsarOrName - getByCriteria(by system name) returned 2 latest CERTIFIED versions");
                     return Either.right(StorageOperationStatus.GENERAL_ERROR);
                 }
-                if (resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID) != null && !((String) resourceMetadataData
-                    .getJsonMetadataField(JsonPresentationFields.CSAR_UUID)).equals(csarUUID)) {
+                final Object csarUuid = resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID);
+                if (csarUuid != null && !csarUuid.equals(csarUUID)) {
                     log.debug("getLatestResourceByCsarOrName - same system name {} but different csarUUID. exist {} and new {} ", systemName,
-                        resourceMetadataData.getJsonMetadataField(JsonPresentationFields.CSAR_UUID), csarUUID);
+                        csarUuid, csarUUID);
                     // correct error will be returned from create flow. with all
 
                     // correct audit records!!!!!
@@ -2341,10 +2470,10 @@ public class ToscaOperationFacade {
         return null;
     }
 
-    public Either<Boolean, StorageOperationStatus> validateToscaResourceNameExtends(String templateNameCurrent, String templateNameExtends) {
+    public Either<Boolean, StorageOperationStatus> validateToscaResourceNameExtends(String templateNameCurrent, String templateNameExtends, String model) {
         String currentTemplateNameChecked = templateNameExtends;
         while (currentTemplateNameChecked != null && !currentTemplateNameChecked.equalsIgnoreCase(templateNameCurrent)) {
-            Either<Resource, StorageOperationStatus> latestByToscaResourceName = getLatestByToscaResourceName(currentTemplateNameChecked);
+            Either<Resource, StorageOperationStatus> latestByToscaResourceName = getLatestByToscaResourceName(currentTemplateNameChecked, model);
             if (latestByToscaResourceName.isRight()) {
                 return latestByToscaResourceName.right().value() == StorageOperationStatus.NOT_FOUND ? Either.left(false)
                     : Either.right(latestByToscaResourceName.right().value());
@@ -2445,7 +2574,7 @@ public class ToscaOperationFacade {
             for (DistributionStatusEnum state : distStatus) {
                 propertiesToMatch.put(GraphPropertyEnum.DISTRIBUTION_STATUS, state.name());
                 Either<List<Service>, StorageOperationStatus> fetchServicesByCriteria = fetchServicesByCriteria(servicesAll, propertiesToMatch,
-                    propertiesNotToMatch);
+                    propertiesNotToMatch, null);
                 if (fetchServicesByCriteria.isRight()) {
                     return fetchServicesByCriteria;
                 } else {
@@ -2454,15 +2583,16 @@ public class ToscaOperationFacade {
             }
             return Either.left(servicesAll);
         } else {
-            return fetchServicesByCriteria(servicesAll, propertiesToMatch, propertiesNotToMatch);
+            return fetchServicesByCriteria(servicesAll, propertiesToMatch, propertiesNotToMatch, null);
         }
     }
 
     private Either<List<Service>, StorageOperationStatus> fetchServicesByCriteria(List<Service> servicesAll,
                                                                                   Map<GraphPropertyEnum, Object> propertiesToMatch,
-                                                                                  Map<GraphPropertyEnum, Object> propertiesNotToMatch) {
+                                                                                  Map<GraphPropertyEnum, Object> propertiesNotToMatch,
+                                                                                  String modelName) {
         Either<List<GraphVertex>, JanusGraphOperationStatus> getRes = janusGraphDao
-            .getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll);
+            .getByCriteria(VertexTypeEnum.TOPOLOGY_TEMPLATE, propertiesToMatch, propertiesNotToMatch, JsonParseFlagEnum.ParseAll, modelName);
         if (getRes.isRight()) {
             if (getRes.right().value() != JanusGraphOperationStatus.NOT_FOUND) {
                 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
@@ -2471,7 +2601,7 @@ public class ToscaOperationFacade {
                 return Either.right(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(getRes.right().value()));
             }
         } else {
-            for (GraphVertex vertex : getRes.left().value()) {
+            for (final GraphVertex vertex : getRes.left().value()) {
                 Either<ToscaElement, StorageOperationStatus> getServiceRes = topologyTemplateOperation
                     .getLightComponent(vertex, ComponentTypeEnum.SERVICE, new ComponentParametersView(true));
                 if (getServiceRes.isRight()) {
@@ -2486,6 +2616,27 @@ public class ToscaOperationFacade {
         return Either.left(servicesAll);
     }
 
+    private List<GraphVertex> getVerticesForModel(final String modelName, final List<GraphVertex> graphVertexList) {
+        final Predicate<? super GraphVertex> filterPredicate =
+            StringUtils.isEmpty(modelName) ? this::vertexNotConnectedToAnyModel
+                : graphVertex -> vertexValidForModel(graphVertex, modelName).isPresent();
+        return StreamSupport.stream(graphVertexList.spliterator(), false).filter(filterPredicate).collect(Collectors.toList());
+    }
+
+    private boolean vertexNotConnectedToAnyModel(final GraphVertex vertex) {
+        return !vertex.getVertex().edges(Direction.OUT, EdgeLabelEnum.MODEL.name()).hasNext();
+    }
+
+    private Optional<GraphVertex> vertexValidForModel(final GraphVertex vertex, final String model) {
+        final Either<List<GraphVertex>, JanusGraphOperationStatus> nodeModelVertices = janusGraphDao
+            .getParentVertices(vertex, EdgeLabelEnum.MODEL, JsonParseFlagEnum.NoParse);
+        if (nodeModelVertices.isRight() || Objects.isNull(nodeModelVertices.left().value())) {
+            return Optional.empty();
+        }
+        return nodeModelVertices.left().value().stream().filter(graphVertex -> graphVertex.getMetadataProperty(GraphPropertyEnum.MODEL).equals(model))
+            .findFirst();
+    }
+
     public void rollback() {
         janusGraphDao.rollback();
     }
@@ -3242,6 +3393,6 @@ public class ToscaOperationFacade {
     }
 
     public <T extends Component> Either<T, StorageOperationStatus> getLatestByServiceName(String serviceName) {
-        return getLatestByName(GraphPropertyEnum.NAME, serviceName);
+        return getLatestByName(GraphPropertyEnum.NAME, serviceName, null);
     }
 }