diff options
Diffstat (limited to 'openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main')
25 files changed, 3465 insertions, 1644 deletions
diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/util/HeatValidationService.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/util/HeatValidationService.java index 920724ed3b..5dc7bef641 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/util/HeatValidationService.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/util/HeatValidationService.java @@ -24,29 +24,40 @@ import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.MapUtils; import org.openecomp.core.utilities.yaml.YamlUtil; import org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder; -import org.openecomp.core.validation.errors.Messages; import org.openecomp.core.validation.types.GlobalValidationContext; +import org.openecomp.sdc.common.errors.Messages; import org.openecomp.sdc.datatypes.error.ErrorLevel; +import org.openecomp.sdc.heat.datatypes.DefinedHeatParameterTypes; import org.openecomp.sdc.heat.datatypes.model.Environment; import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate; import org.openecomp.sdc.heat.datatypes.model.Output; +import org.openecomp.sdc.heat.datatypes.model.Parameter; import org.openecomp.sdc.heat.datatypes.model.Resource; import org.openecomp.sdc.heat.datatypes.model.ResourceReferenceFunctions; import org.openecomp.sdc.heat.services.HeatStructureUtil; +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.validation.impl.validators.HeatValidator; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - +import java.io.InputStream; import java.util.Collection; import java.util.List; import java.util.Map; import java.util.Objects; +import java.util.Optional; import java.util.Set; + public class HeatValidationService { - private static final Logger logger = LoggerFactory.getLogger(HeatValidator.class); + private static final Logger logger = (Logger) LoggerFactory.getLogger(HeatValidator.class); + private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); /** * Check artifacts existence. @@ -57,17 +68,22 @@ public class HeatValidationService { */ public static void checkArtifactsExistence(String fileName, Set<String> artifactsNames, GlobalValidationContext globalContext) { + + + mdcDataDebugMessage.debugEntryMessage("file", fileName); artifactsNames .stream() .filter(artifactName -> !globalContext.getFileContextMap().containsKey(artifactName)) .forEach(artifactName -> { - globalContext - .addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder + globalContext.addMessage(fileName, + ErrorLevel.ERROR, ErrorMessagesFormatBuilder .getErrorWithParameters(Messages.MISSING_ARTIFACT.getErrorMessage(), - artifactName)); + artifactName), LoggerTragetServiceName.VALIDATE_ARTIFACTS_EXISTENCE, + LoggerErrorDescription.MISSING_FILE); }); - } + mdcDataDebugMessage.debugExitMessage("file", fileName); + } /** * Check resource existence from resources map. @@ -81,11 +97,14 @@ public class HeatValidationService { Set<String> resourcesNames, Collection<?> valuesToSearchIn, GlobalValidationContext globalContext) { + + + mdcDataDebugMessage.debugEntryMessage("file", fileName); + if (CollectionUtils.isNotEmpty(valuesToSearchIn)) { for (Object value : valuesToSearchIn) { if (value instanceof Resource) { Resource resource = (Resource) value; - //checkResourceDependsOn(fileName,resource,resourcesNames,globalContext); Collection<Object> resourcePropertiesValues = resource.getProperties() == null ? null : resource.getProperties().values(); @@ -101,35 +120,49 @@ public class HeatValidationService { } } } - } + mdcDataDebugMessage.debugExitMessage("file", fileName); + } private static void handleReferencedResources(String fileName, Object valueToSearchReferencesIn, Set<String> resourcesNames, GlobalValidationContext globalContext) { + + + mdcDataDebugMessage.debugEntryMessage("file", fileName); + Set<String> referencedResourcesNames = HeatStructureUtil .getReferencedValuesByFunctionName(fileName, ResourceReferenceFunctions.GET_RESOURCE.getFunction(), valueToSearchReferencesIn, globalContext); if (CollectionUtils.isNotEmpty(referencedResourcesNames)) { - HeatValidationService - .checkIfResourceReferenceExist(fileName, resourcesNames, referencedResourcesNames, - globalContext); + checkIfResourceReferenceExist(fileName, resourcesNames, referencedResourcesNames, + globalContext); } - } + mdcDataDebugMessage.debugExitMessage("file", fileName); + } private static void checkIfResourceReferenceExist(String fileName, Set<String> referencedResourcesNames, Set<String> referencedResources, GlobalValidationContext globalContext) { + + + mdcDataDebugMessage.debugEntryMessage("file", fileName); + referencedResources.stream() .filter(referencedResource -> !referencedResourcesNames.contains(referencedResource)) .forEach(referencedResource -> { - globalContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder - .getErrorWithParameters(Messages.REFERENCED_RESOURCE_NOT_FOUND.getErrorMessage(), - referencedResource)); + globalContext.addMessage(fileName, + ErrorLevel.ERROR, ErrorMessagesFormatBuilder + .getErrorWithParameters(Messages.REFERENCED_RESOURCE_NOT_FOUND.getErrorMessage(), + referencedResource), + LoggerTragetServiceName.VALIDATE_RESOURCE_REFERENCE_EXISTENCE, + LoggerErrorDescription.RESOURCE_NOT_FOUND); }); + + mdcDataDebugMessage.debugExitMessage("file", fileName); } /** @@ -162,36 +195,152 @@ public class HeatValidationService { /** * Check nested parameters. * - * @param callingNestedFileName the calling nested file name + * @param parentFileName the calling nested file name * @param nestedFileName the nested file name * @param resourceName the resource name * @param globalContext the global context * @param resourceFileProperties the resource file properties */ - public static void checkNestedParameters(String callingNestedFileName, String nestedFileName, - String resourceName, - GlobalValidationContext globalContext, - Set<String> resourceFileProperties) { - HeatOrchestrationTemplate heatOrchestrationTemplate; + public static void checkNestedParameters(String parentFileName, String nestedFileName, + String resourceName, Resource resource, + Set<String> resourceFileProperties, + Optional<String> indexVarValue, + GlobalValidationContext globalContext) { + + + mdcDataDebugMessage.debugEntryMessage("file", parentFileName); + + HeatOrchestrationTemplate parentHeatOrchestrationTemplate; + HeatOrchestrationTemplate nestedHeatOrchestrationTemplate; try { - heatOrchestrationTemplate = new YamlUtil() - .yamlToObject(globalContext.getFileContent(nestedFileName), - HeatOrchestrationTemplate.class); - } catch (Exception e0) { + Optional<InputStream> fileContent = globalContext.getFileContent(nestedFileName); + if (fileContent.isPresent()) { + nestedHeatOrchestrationTemplate = + new YamlUtil().yamlToObject(fileContent.get(), HeatOrchestrationTemplate.class); + } else { + MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_API, + LoggerTragetServiceName.VALIDATE_PROPERTIES_MATCH_NESTED_PARAMETERS, + ErrorLevel.ERROR.name(), LoggerErrorCode.DATA_ERROR.getErrorCode(), + LoggerErrorDescription.EMPTY_FILE); + throw new Exception("The file '" + nestedFileName + "' has no content"); + } + } catch (Exception exception) { + mdcDataDebugMessage.debugExitMessage("file", parentFileName); return; } - Set<String> nestedParametersNames = heatOrchestrationTemplate.getParameters() == null ? null - : heatOrchestrationTemplate.getParameters().keySet(); + + try { + Optional<InputStream> fileContent = globalContext.getFileContent(parentFileName); + if (fileContent.isPresent()) { + parentHeatOrchestrationTemplate = + new YamlUtil().yamlToObject(fileContent.get(), HeatOrchestrationTemplate.class); + } else { + MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_API, + LoggerTragetServiceName.VALIDATE_PROPERTIES_MATCH_NESTED_PARAMETERS, + ErrorLevel.ERROR.name(), LoggerErrorCode.DATA_ERROR.getErrorCode(), + LoggerErrorDescription.EMPTY_FILE); + throw new Exception("The file '" + parentFileName + "' has no content"); + } + } catch (Exception exception) { + mdcDataDebugMessage.debugExitMessage("file", parentFileName); + return; + } + Map<String, Parameter> parentParameters = parentHeatOrchestrationTemplate.getParameters(); + Map<String, Parameter> nestedParameters = nestedHeatOrchestrationTemplate.getParameters(); + Set<String> nestedParametersNames = + nestedParameters == null ? null : nestedHeatOrchestrationTemplate.getParameters().keySet(); + + checkNoMissingParameterInNested(parentFileName, nestedFileName, resourceName, + resourceFileProperties, nestedParametersNames, globalContext); + checkNestedInputValuesAlignWithType(parentFileName, nestedFileName, parentParameters, + nestedParameters, resourceName, resource, indexVarValue, globalContext); + + mdcDataDebugMessage.debugExitMessage("file", parentFileName); + + } + + private static void checkNoMissingParameterInNested(String parentFileName, String nestedFileName, + String resourceName, + Set<String> resourceFileProperties, + Set<String> nestedParametersNames, + GlobalValidationContext globalContext) { + + mdcDataDebugMessage.debugEntryMessage("nested file", nestedFileName); if (CollectionUtils.isNotEmpty(nestedParametersNames)) { resourceFileProperties .stream() .filter(propertyName -> !nestedParametersNames.contains(propertyName)) .forEach(propertyName -> globalContext - .addMessage(callingNestedFileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder - .getErrorWithParameters(Messages.MISSING_PARAMETER_IN_NESTED.getErrorMessage(), - nestedFileName, resourceName, propertyName))); + .addMessage(parentFileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder + .getErrorWithParameters(Messages + .MISSING_PARAMETER_IN_NESTED.getErrorMessage(), + nestedFileName, resourceName, propertyName), + LoggerTragetServiceName.VALIDATE_PROPERTIES_MATCH_NESTED_PARAMETERS, + LoggerErrorDescription.MISSING_PARAMETER_IN_NESTED)); } + + mdcDataDebugMessage.debugExitMessage("nested file", nestedFileName); + } + + + private static void checkNestedInputValuesAlignWithType(String parentFileName, + String nestedFileName, + Map<String, Parameter> parentParameters, + Map<String, Parameter> nestedParameters, + String resourceName, Resource resource, + Optional<String> indexVarValue, + GlobalValidationContext globalContext) { + + + mdcDataDebugMessage.debugEntryMessage("nested file", nestedFileName); + + Map<String, Object> properties = resource.getProperties(); + for (Map.Entry<String, Object> propertyEntry : properties.entrySet()) { + String parameterName = propertyEntry.getKey(); + Object parameterInputValue = propertyEntry.getValue(); + + if (Objects.nonNull(parameterInputValue)) { + if (parameterInputValue instanceof String) { + if (indexVarValue.isPresent() && indexVarValue.get().equals(parameterInputValue)) { + parameterInputValue = 3; //indexVarValue is actually number value in runtime + } + validateStaticValueForNestedInputParameter(parentFileName, nestedFileName, resourceName, + parameterName, parameterInputValue, nestedParameters.get(parameterName), + globalContext); + } + } + } + + mdcDataDebugMessage.debugExitMessage("nested file", nestedFileName); + } + + private static void validateStaticValueForNestedInputParameter(String parentFileName, + String nestedFileName, + String resourceName, + String parameterName, + Object staticValue, + Parameter parameterInNested, + GlobalValidationContext + globalContext) { + + + mdcDataDebugMessage.debugEntryMessage("nested file", nestedFileName); + + if (parameterInNested == null) { + return; + } + if (!DefinedHeatParameterTypes + .isValueIsFromGivenType(staticValue, parameterInNested.getType())) { + globalContext.addMessage(parentFileName, ErrorLevel.WARNING, ErrorMessagesFormatBuilder + .getErrorWithParameters(Messages + .WRONG_VALUE_TYPE_ASSIGNED_NESTED_INPUT.getErrorMessage(), + resourceName, parameterName, nestedFileName), + LoggerTragetServiceName.VALIDATE_PROPERTIES_MATCH_NESTED_PARAMETERS, + LoggerErrorDescription.WRONG_VALUE_ASSIGNED_NESTED_PARAMETER); + } + + mdcDataDebugMessage.debugExitMessage("nested file", nestedFileName); } @@ -207,14 +356,28 @@ public class HeatValidationService { public static boolean isNestedLoopExistInFile(String callingFileName, String nestedFileName, List<String> filesInLoop, GlobalValidationContext globalContext) { + + + mdcDataDebugMessage.debugEntryMessage("file", callingFileName); + HeatOrchestrationTemplate nestedHeatOrchestrationTemplate; try { - nestedHeatOrchestrationTemplate = new YamlUtil() - .yamlToObject(globalContext.getFileContent(nestedFileName), - HeatOrchestrationTemplate.class); - } catch (Exception e0) { + Optional<InputStream> fileContent = globalContext.getFileContent(nestedFileName); + if (fileContent.isPresent()) { + nestedHeatOrchestrationTemplate = + new YamlUtil().yamlToObject(fileContent.get(), HeatOrchestrationTemplate.class); + } else { + MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_API, + LoggerTragetServiceName.VALIDATE_NESTING_LOOPS, ErrorLevel.ERROR.name(), + LoggerErrorCode.DATA_ERROR.getErrorCode(), LoggerErrorDescription.EMPTY_FILE); + throw new Exception("The file '" + nestedFileName + "' has no content"); + } + + } catch (Exception exception) { logger.warn("HEAT Validator will not be executed on file " + nestedFileName + " due to illegal HEAT format"); + + mdcDataDebugMessage.debugExitMessage("file", callingFileName); return false; } filesInLoop.add(nestedFileName); @@ -226,11 +389,14 @@ public class HeatValidationService { String resourceType = resource.getType(); if (Objects.nonNull(resourceType) && isNestedResource(resourceType)) { + mdcDataDebugMessage.debugExitMessage("file", callingFileName); return resourceType.equals(callingFileName) || !filesInLoop.contains(resourceType) && isNestedLoopExistInFile(callingFileName, resourceType, filesInLoop, globalContext); } } } + + mdcDataDebugMessage.debugExitMessage("file", callingFileName); return false; } @@ -245,9 +411,11 @@ public class HeatValidationService { */ @SuppressWarnings("unchecked") public static void loopOverOutputMapAndValidateGetAttrFromNested(String fileName, - Map<String, Output> outputMap, - HeatOrchestrationTemplate heatOrchestrationTemplate, - GlobalValidationContext globalContext) { + Map<String, Output> outputMap, + HeatOrchestrationTemplate + heatOrchestrationTemplate, + GlobalValidationContext + globalContext) { for (Output output : outputMap.values()) { Object outputValue = output.getValue(); if (outputValue != null && outputValue instanceof Map) { @@ -256,42 +424,64 @@ public class HeatValidationService { (List<String>) outputValueMap.get(ResourceReferenceFunctions.GET_ATTR.getFunction()); if (!CollectionUtils.isEmpty(getAttrValue)) { String resourceName = getAttrValue.get(0); - String propertyName = getAttrValue.get(1); + Object attNameObject = getAttrValue.get(1); + if (!(attNameObject instanceof String)) { + return; + } + String attName = getAttrValue.get(1); String resourceType = getResourceTypeFromResourcesMap(resourceName, heatOrchestrationTemplate); if (Objects.nonNull(resourceType) - && HeatValidationService.isNestedResource(resourceType)) { - Map<String, Output> nestedOutputMap; - HeatOrchestrationTemplate nestedHeatOrchestrationTemplate; - try { - nestedHeatOrchestrationTemplate = new YamlUtil() - .yamlToObject(globalContext.getFileContent(resourceType), - HeatOrchestrationTemplate.class); - } catch (Exception e0) { - return; - } - nestedOutputMap = nestedHeatOrchestrationTemplate.getOutputs(); - - if (MapUtils.isEmpty(nestedOutputMap) || !nestedOutputMap.containsKey(propertyName)) { - globalContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder - .getErrorWithParameters(Messages.GET_ATTR_NOT_FOUND.getErrorMessage(), - propertyName, resourceName)); + && isNestedResource(resourceType)) { + handleGetAttrNestedResource(fileName, globalContext, resourceName, attName, + resourceType); } } } } } - } + private static void handleGetAttrNestedResource(String fileName, + GlobalValidationContext globalContext, + String resourceName, String attName, + String resourceType) { + Map<String, Output> nestedOutputMap; + HeatOrchestrationTemplate nestedHeatOrchestrationTemplate; + try { + Optional<InputStream> fileContent = globalContext.getFileContent(resourceType); + if (fileContent.isPresent()) { + nestedHeatOrchestrationTemplate = + new YamlUtil().yamlToObject(fileContent.get(), HeatOrchestrationTemplate.class); + } else { + MdcDataErrorMessage + .createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_API, + LoggerTragetServiceName.VALIDATE_GET_ATTR_FROM_NESTED, + ErrorLevel.ERROR.name(), LoggerErrorCode.DATA_ERROR.getErrorCode(), + LoggerErrorDescription.EMPTY_FILE); + throw new Exception("The file '" + resourceType + "' has no content"); + } + } catch (Exception exception) { + return; + } + nestedOutputMap = nestedHeatOrchestrationTemplate.getOutputs(); + + if (MapUtils.isEmpty(nestedOutputMap) || !nestedOutputMap.containsKey(attName)) { + globalContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder + .getErrorWithParameters(Messages.GET_ATTR_NOT_FOUND.getErrorMessage(), + attName, resourceName), + LoggerTragetServiceName.VALIDATE_GET_ATTR_FROM_NESTED, + LoggerErrorDescription.GET_ATTR_NOT_FOUND); + } + } public static boolean isNestedResource(String resourceType) { return resourceType.contains(".yaml") || resourceType.contains(".yml"); } - private static String getResourceTypeFromResourcesMap(String resourceName, - HeatOrchestrationTemplate heatOrchestrationTemplate) { + HeatOrchestrationTemplate + heatOrchestrationTemplate) { return heatOrchestrationTemplate.getResources().get(resourceName).getType(); } @@ -305,11 +495,23 @@ public class HeatValidationService { */ public static Environment validateEnvContent(String fileName, String envFileName, GlobalValidationContext globalContext) { + + + mdcDataDebugMessage.debugEntryMessage("env file", envFileName); + Environment envContent = null; try { - envContent = - new YamlUtil().yamlToObject(globalContext.getFileContent(envFileName), Environment.class); - } catch (Exception e0) { + Optional<InputStream> fileContent = globalContext.getFileContent(envFileName); + if (fileContent.isPresent()) { + envContent = new YamlUtil().yamlToObject(fileContent.get(), Environment.class); + } else { + MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_API, + LoggerTragetServiceName.VALIDATE_ENV_FILE, ErrorLevel.ERROR.name(), + LoggerErrorCode.DATA_ERROR.getErrorCode(), LoggerErrorDescription.EMPTY_FILE); + throw new Exception("The file '" + envFileName + "' has no content"); + } + } catch (Exception exception) { + mdcDataDebugMessage.debugExitMessage("env file", envFileName); return null; } return envContent; diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/util/ResourceValidationHeatValidator.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/util/ResourceValidationHeatValidator.java deleted file mode 100644 index 3457bed1e9..0000000000 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/util/ResourceValidationHeatValidator.java +++ /dev/null @@ -1,617 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.validation.impl.util; - -import org.apache.commons.collections4.CollectionUtils; -import org.apache.commons.collections4.MapUtils; -import org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder; -import org.openecomp.core.validation.errors.Messages; -import org.openecomp.core.validation.types.GlobalValidationContext; -import org.openecomp.sdc.datatypes.error.ErrorLevel; -import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate; -import org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes; -import org.openecomp.sdc.heat.datatypes.model.Output; -import org.openecomp.sdc.heat.datatypes.model.PolicyTypes; -import org.openecomp.sdc.heat.datatypes.model.PropertiesMapKeyTypes; -import org.openecomp.sdc.heat.datatypes.model.Resource; -import org.openecomp.sdc.heat.datatypes.model.ResourceReferenceFunctions; -import org.openecomp.sdc.heat.datatypes.model.ResourceTypeToMessageString; -import org.openecomp.sdc.heat.services.HeatStructureUtil; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Collections; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Set; - - -public class ResourceValidationHeatValidator { - - /** - * Validate resource type. - * - * @param fileName the file name - * @param baseFileName the base file name - * @param securityGroupsNamesFromBaseFileOutputs the security groups names from base file outputs - * @param heatOrchestrationTemplate the heat orchestration template - * @param globalContext the global context - */ - public static void validateResourceType(String fileName, String baseFileName, - Set<String> securityGroupsNamesFromBaseFileOutputs, - HeatOrchestrationTemplate heatOrchestrationTemplate, - GlobalValidationContext globalContext) { - Map<String, Resource> resourceMap = - heatOrchestrationTemplate.getResources() == null ? new HashMap<>() - : heatOrchestrationTemplate.getResources(); - Map<String, Integer> numberOfVisitsInPort = new HashMap<>(); - Set<String> resourcesNames = resourceMap.keySet(); - Set<String> sharedResourcesFromOutputMap = - getSharedResourcesNamesFromOutputs(fileName, heatOrchestrationTemplate.getOutputs(), - globalContext); - boolean isBaseFile = baseFileName != null && fileName.equals(baseFileName); - - Map<HeatResourcesTypes, List<String>> resourceTypeToNamesListMap = HeatResourcesTypes - .getListForResourceType(HeatResourcesTypes.NOVA_SERVER_GROUP_RESOURCE_TYPE, - HeatResourcesTypes.NEUTRON_SECURITY_GROUP_RESOURCE_TYPE, - HeatResourcesTypes.CONTRAIL_NETWORK_RULE_RESOURCE_TYPE); - - initResourceTypeListWithItsResourcesNames(fileName, resourceTypeToNamesListMap, resourceMap, - sharedResourcesFromOutputMap, globalContext); - initVisitedPortsMap(fileName, resourceMap, numberOfVisitsInPort, globalContext); - - - for (Map.Entry<String, Resource> resourceEntry : resourceMap.entrySet()) { - String resourceType = resourceEntry.getValue().getType(); - validateSecurityGroupsFromBaseOutput(fileName, resourceEntry, isBaseFile, - securityGroupsNamesFromBaseFileOutputs, globalContext); - checkResourceDependsOn(fileName, resourceEntry.getValue(), resourcesNames, globalContext); - - if (Objects.isNull(resourceType)) { - globalContext.addMessage(fileName, ErrorLevel.WARNING, ErrorMessagesFormatBuilder - .getErrorWithParameters(Messages.INVALID_RESOURCE_TYPE.getErrorMessage(), "null", - resourceEntry.getKey())); - } else { - HeatResourcesTypes heatResourceType = HeatResourcesTypes.findByHeatResource(resourceType); - - if (heatResourceType != null) { - switch (heatResourceType) { - case NOVA_SERVER_RESOURCE_TYPE: - validateNovaServerResourceType(fileName, resourceEntry, numberOfVisitsInPort, - resourceTypeToNamesListMap - .get(HeatResourcesTypes.NOVA_SERVER_GROUP_RESOURCE_TYPE), - heatOrchestrationTemplate, globalContext); - break; - - case NOVA_SERVER_GROUP_RESOURCE_TYPE: - validateNovaServerGroupPolicy(fileName, resourceEntry, globalContext); - break; - - case RESOURCE_GROUP_RESOURCE_TYPE: - validateResourceGroupType(fileName, resourceEntry, globalContext); - break; - - case NEUTRON_PORT_RESOURCE_TYPE: - validateNeutronPortType(fileName, resourceEntry, resourceTypeToNamesListMap - .get(HeatResourcesTypes.NEUTRON_SECURITY_GROUP_RESOURCE_TYPE), globalContext); - break; - - case CONTRAIL_NETWORK_ATTACH_RULE_RESOURCE_TYPE: - validateContrailAttachPolicyType(resourceEntry, resourceTypeToNamesListMap - .get(HeatResourcesTypes.CONTRAIL_NETWORK_RULE_RESOURCE_TYPE)); - break; - default: - } - } else { - if (HeatValidationService.isNestedResource(resourceType)) { - handleNestedResourceType(fileName, resourceEntry.getKey(), resourceEntry.getValue(), - globalContext); - } - } - } - } - - checkForEmptyResourceNamesInMap(fileName, - CollectionUtils.isEmpty(securityGroupsNamesFromBaseFileOutputs), resourceTypeToNamesListMap, - globalContext); - handleOrphanPorts(fileName, numberOfVisitsInPort, globalContext); - } - - - private static void validateNovaServerResourceType(String fileName, - Map.Entry<String, Resource> resourceEntry, - Map<String, Integer> numberOfVisitsInPort, - List<String> serverGroupResourcesNames, - HeatOrchestrationTemplate - heatOrchestrationTemplate, - GlobalValidationContext globalContext) { - validateAssignedValueForImageOrFlavorFromNova(fileName, resourceEntry, globalContext); - validateNovaServerPortBinding(fileName, resourceEntry.getValue(), numberOfVisitsInPort, - globalContext); - validateAllServerGroupsPointedByServerExistAndDefined(fileName, resourceEntry, - serverGroupResourcesNames, heatOrchestrationTemplate, globalContext); - - } - - - private static void handleNestedResourceType(String fileName, String resourceName, - Resource resource, - GlobalValidationContext globalContext) { - validateAllPropertiesMatchNestedParameters(fileName, resourceName, resource, globalContext); - validateLoopsOfNestingFromFile(fileName, resource.getType(), globalContext); - } - - - private static void validateResourceGroupType(String fileName, - Map.Entry<String, Resource> resourceEntry, - GlobalValidationContext globalContext) { - Resource resourceDef = HeatStructureUtil - .getResourceDef(fileName, resourceEntry.getKey(), resourceEntry.getValue(), globalContext); - // validateResourceGroupTypeIsSupported(fileName, resourceEntry.getKey(),resourceDef.getType(), - // globalContext); - if (resourceDef != null) { - if (Objects.nonNull(resourceDef.getType()) - && HeatValidationService.isNestedResource(resourceDef.getType())) { - handleNestedResourceType(fileName, resourceDef.getType(), resourceDef, globalContext); - } - } - } - - - private static void validateAllPropertiesMatchNestedParameters(String fileName, - String resourceName, - Resource resource, - GlobalValidationContext - globalContext) { - - String resourceType = resource.getType(); - if (globalContext.getFileContextMap().containsKey(resourceType)) { - Set<String> propertiesNames = - resource.getProperties() == null ? null : resource.getProperties().keySet(); - if (CollectionUtils.isNotEmpty(propertiesNames)) { - HeatValidationService - .checkNestedParameters(fileName, resourceType, resourceName, globalContext, - propertiesNames); - } - } else { - globalContext.addMessage(resourceType, ErrorLevel.ERROR, ErrorMessagesFormatBuilder - .getErrorWithParameters(Messages.MISSING_NESTED_FILE.getErrorMessage(), resourceType)); - } - } - - - private static void validateAssignedValueForImageOrFlavorFromNova(String fileName, - Map.Entry<String, Resource> - resourceEntry, - GlobalValidationContext - globalContext) { - - Resource resource = resourceEntry.getValue(); - Map<String, Object> propertiesMap = resource.getProperties(); - if (propertiesMap.get(PropertiesMapKeyTypes.IMAGE.getKeyMap()) == null - && propertiesMap.get(PropertiesMapKeyTypes.FLAVOR.getKeyMap()) == null) { - globalContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder - .getErrorWithParameters(Messages.MISSING_IMAGE_AND_FLAVOR.getErrorMessage(), - resourceEntry.getKey())); - } - } - - - private static void validateLoopsOfNestingFromFile(String fileName, String resourceType, - GlobalValidationContext globalContext) { - List<String> filesInLoop = new ArrayList<>(Collections.singletonList(fileName)); - if (HeatValidationService - .isNestedLoopExistInFile(fileName, resourceType, filesInLoop, globalContext)) { - globalContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder - .getErrorWithParameters(Messages.NESTED_LOOP.getErrorMessage(), - HeatValidationService.drawFilesLoop(filesInLoop))); - } - } - - - /* validation 22*/ - @SuppressWarnings("unchecked") - private static void validateNovaServerPortBinding(String fileName, Resource resource, - Map<String, Integer> numberOfVisitsInPort, - GlobalValidationContext globalContext) { - - Map<String, Object> propertiesMap = resource.getProperties(); - List<Object> networksList = - (List<Object>) propertiesMap.get(PropertiesMapKeyTypes.NETWORKS.getKeyMap()); - - if (CollectionUtils.isNotEmpty(networksList)) { - networksList - .stream() - .filter(networkObject -> networkObject instanceof Map) - .forEach(networkObject -> { - Map<String, Object> portValueMap = - (Map<String, Object>) ((Map) networkObject).get("port"); - if (MapUtils.isNotEmpty(portValueMap)) { - checkPortBindingFromMap(fileName, portValueMap, numberOfVisitsInPort, globalContext); - } - }); - } - } - - /* validation 23*/ - @SuppressWarnings("unchecked") - private static void validateAllServerGroupsPointedByServerExistAndDefined(String fileName, - Map.Entry<String, Resource> resourceEntry, - List<String> serverGroupNamesList, - HeatOrchestrationTemplate heatOrchestrationTemplate, - GlobalValidationContext globalContext) { - Map<String, Resource> resourcesMap = heatOrchestrationTemplate.getResources(); - - Map<String, Object> resourceProperties = resourceEntry.getValue().getProperties(); - Map<String, Object> schedulerHintsMap = resourceProperties == null ? null - : (Map<String, Object>) resourceProperties - .get(ResourceReferenceFunctions.SCHEDULER_HINTS.getFunction()); - - if (MapUtils.isNotEmpty(schedulerHintsMap)) { - for (Object serverGroupMap : schedulerHintsMap.values()) { - Map<String, Object> currentServerMap = (Map<String, Object>) serverGroupMap; - String serverResourceName = currentServerMap == null ? null - : (String) currentServerMap.get(ResourceReferenceFunctions.GET_RESOURCE.getFunction()); - Resource serverResource = serverResourceName == null || resourcesMap == null ? null - : resourcesMap.get(serverResourceName); - if (serverResource != null && !serverResource.getType() - .equals(HeatResourcesTypes.NOVA_SERVER_GROUP_RESOURCE_TYPE.getHeatResource())) { - globalContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder - .getErrorWithParameters(Messages.SERVER_NOT_DEFINED_FROM_NOVA.getErrorMessage(), - serverResourceName, resourceEntry.getKey())); - } else { - serverGroupNamesList.remove(serverResourceName); - } - } - } - } - - - /* validation 24*/ - @SuppressWarnings("unchecked") - private static void validateNovaServerGroupPolicy(String fileName, - Map.Entry<String, Resource> resourceEntry, - GlobalValidationContext globalContext) { - - Resource resource = resourceEntry.getValue(); - List<String> policiesList = resource.getProperties() == null ? null - : (List<String>) resource.getProperties().get("policies"); - - if (CollectionUtils.isNotEmpty(policiesList)) { - if (policiesList.size() == 1) { - String policy = policiesList.get(0); - if (!PolicyTypes.isGivenPolicyValid(policy)) { - globalContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder - .getErrorWithParameters(Messages.WRONG_POLICY_IN_SERVER_GROUP.getErrorMessage(), - resourceEntry.getKey())); - } - } else { - globalContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder - .getErrorWithParameters(Messages.WRONG_POLICY_IN_SERVER_GROUP.getErrorMessage(), - resourceEntry.getKey())); - } - } - } - - - private static void validateNeutronPortType(String filename, - Map.Entry<String, Resource> resourceEntry, - List<String> securityGroupResourceNameList, - GlobalValidationContext globalContext) { - validateAllSecurityGroupsAreUsed(filename, resourceEntry, securityGroupResourceNameList, - globalContext); - - } - - - @SuppressWarnings("unchecked") - private static void validateAllSecurityGroupsAreUsed(String filename, - Map.Entry<String, Resource> resourceEntry, - List<String> securityGroupResourceNameList, - GlobalValidationContext globalContext) { - Map<String, Object> propertiesMap = resourceEntry.getValue().getProperties(); - - if (MapUtils.isEmpty(propertiesMap)) { - return; - } - - Object securityGroupsValue = propertiesMap.get("security_groups"); - - if (Objects.isNull(securityGroupsValue)) { - return; - } - - if (securityGroupsValue instanceof List) { - List<Object> securityGroupsListFromCurrResource = - (List<Object>) propertiesMap.get("security_groups"); - for (Object securityGroup : securityGroupsListFromCurrResource) { - removeSecurityGroupNamesFromListByGivenFunction(filename, - ResourceReferenceFunctions.GET_RESOURCE.getFunction(), securityGroup, - securityGroupResourceNameList, globalContext); - } - } - } - - - private static void validateSecurityGroupsFromBaseOutput(String filename, - Map.Entry<String, Resource> resourceEntry, - boolean isBaseFile, - Set<String> securityGroupNamesFromBaseOutput, - GlobalValidationContext globalContext) { - if (!isBaseFile && CollectionUtils.isNotEmpty(securityGroupNamesFromBaseOutput)) { - Map<String, Object> propertiesMap = resourceEntry.getValue().getProperties(); - - if (MapUtils.isEmpty(propertiesMap)) { - return; - } - - for (Map.Entry<String, Object> propertyEntry : propertiesMap.entrySet()) { - removeSecurityGroupNamesFromListByGivenFunction(filename, - ResourceReferenceFunctions.GET_PARAM.getFunction(), propertyEntry.getValue(), - securityGroupNamesFromBaseOutput, globalContext); - } - } - } - - - private static void removeSecurityGroupNamesFromListByGivenFunction(String filename, - String functionName, - Object securityGroup, - Collection<String> securityGroupResourceNameList, - GlobalValidationContext globalContext) { - Set<String> securityGroupsNamesFromFunction = HeatStructureUtil - .getReferencedValuesByFunctionName(filename, functionName, securityGroup, globalContext); - securityGroupsNamesFromFunction.forEach(securityGroupResourceNameList::remove); - } - - - @SuppressWarnings("unchecked") - private static void validateContrailAttachPolicyType(Map.Entry<String, Resource> resourceEntry, - List<String> networkPolicyResourceNames) { - Map<String, Object> propertiesMap = resourceEntry.getValue().getProperties(); - - if (MapUtils.isNotEmpty(propertiesMap)) { - Map<String, Object> policyMap = (Map<String, Object>) propertiesMap.get("policy"); - if (MapUtils.isNotEmpty(policyMap)) { - List<Object> securityGroupList = - (List<Object>) policyMap.get(ResourceReferenceFunctions.GET_ATTR.getFunction()); - //noinspection SuspiciousMethodCalls - if (CollectionUtils.isNotEmpty(securityGroupList)) { - //noinspection SuspiciousMethodCalls - networkPolicyResourceNames.remove(securityGroupList.get(0)); - } - } - } - } - - - private static void getResourceNamesListFromSpecificResource(String filename, - List<String> resourcesNames, - HeatResourcesTypes heatResourcesType, - Map<String, Resource> resourcesMap, - Set<String> sharedResourcesFromOutputMap, - GlobalValidationContext globalContext) { - - for (Map.Entry<String, Resource> resourceEntry : resourcesMap.entrySet()) { - String resourceType = resourceEntry.getValue().getType(); - if (Objects.isNull(resourceType)) { - globalContext.addMessage(filename, ErrorLevel.WARNING, ErrorMessagesFormatBuilder - .getErrorWithParameters(Messages.INVALID_RESOURCE_TYPE.getErrorMessage(), null, - resourceEntry.getKey())); - } else { - if (resourceType.equals(heatResourcesType.getHeatResource()) - && !isSharedResource(resourceEntry.getKey(), sharedResourcesFromOutputMap)) { - resourcesNames.add(resourceEntry.getKey()); - } - } - } - } - - - private static boolean isSharedResource(String resourceName, - Set<String> sharedResourcesFromOutputMap) { - return !CollectionUtils.isEmpty(sharedResourcesFromOutputMap) - && sharedResourcesFromOutputMap.contains(resourceName); - } - - /** - * Handle not empty resource names list. - * - * @param fileName the file name - * @param resourcesNameList the resources name list - * @param securityOrServerGroup the security or server group - * @param globalContext the global context - */ - public static void handleNotEmptyResourceNamesList(String fileName, - Collection<String> resourcesNameList, - String securityOrServerGroup, - GlobalValidationContext globalContext) { - if (CollectionUtils.isNotEmpty(resourcesNameList)) { - resourcesNameList.forEach(name -> - globalContext - .addMessage( - fileName, - ErrorLevel.WARNING, - ErrorMessagesFormatBuilder - .getErrorWithParameters( - Messages.SERVER_OR_SECURITY_GROUP_NOT_IN_USE.getErrorMessage(), - securityOrServerGroup, name))); - } - } - - - private static void initVisitedPortsMap(String filename, Map<String, Resource> resourceMap, - Map<String, Integer> numberOfVisitsInPort, - GlobalValidationContext globalContext) { - for (Map.Entry<String, Resource> resourceEntry : resourceMap.entrySet()) { - String resourceType = resourceEntry.getValue().getType(); - - if (Objects.isNull(resourceType)) { - globalContext.addMessage(filename, ErrorLevel.WARNING, ErrorMessagesFormatBuilder - .getErrorWithParameters(Messages.INVALID_RESOURCE_TYPE.getErrorMessage(), "null", - resourceEntry.getKey())); - } else { - if (resourceType.equals(HeatResourcesTypes.NEUTRON_PORT_RESOURCE_TYPE.getHeatResource())) { - numberOfVisitsInPort.put(resourceEntry.getKey(), 0); - } - } - } - } - - private static boolean checkIfPortWasVisited(String resourcePortName, - Map<String, Integer> numberOfVisitsInPort) { - return numberOfVisitsInPort.containsKey(resourcePortName) - && numberOfVisitsInPort.get(resourcePortName) == 1; - } - - - private static void incrementNumberOfVisitsInPort(String resourcePortName, - Map<String, Integer> numberOfVisitsInPort) { - if (numberOfVisitsInPort.containsKey(resourcePortName)) { - numberOfVisitsInPort.put(resourcePortName, numberOfVisitsInPort.get(resourcePortName) + 1); - } - } - - - private static void handleOrphanPorts(String fileName, Map<String, Integer> numberOfVisitsInPort, - GlobalValidationContext globalContext) { - numberOfVisitsInPort - .entrySet() - .stream() - .filter(entry -> entry.getValue() == 0) - .forEach(entry -> - globalContext - .addMessage( - fileName, - ErrorLevel.WARNING, - ErrorMessagesFormatBuilder - .getErrorWithParameters( - Messages.PORT_NO_BIND_TO_ANY_NOVA_SERVER.getErrorMessage(), - entry.getKey()))); - } - - @SuppressWarnings("unchecked") - private static void checkResourceDependsOn(String fileName, Resource resource, - Set<String> resourcesNames, - GlobalValidationContext globalContext) { - Object dependencies = resource.getDepends_on(); - if (dependencies instanceof Collection) { - ((Collection<String>) dependencies) - .stream() - .filter(resource_id -> !resourcesNames.contains(resource_id)) - .forEach(resource_id -> globalContext.addMessage(fileName, ErrorLevel.ERROR, - ErrorMessagesFormatBuilder - .getErrorWithParameters(Messages.MISSING_RESOURCE_IN_DEPENDS_ON.getErrorMessage(), - (String) resource_id))); - } else if (dependencies instanceof String) { - if (!resourcesNames.contains(dependencies)) { - globalContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder - .getErrorWithParameters(Messages.MISSING_RESOURCE_IN_DEPENDS_ON.getErrorMessage(), - (String) dependencies)); - } - } - } - - - private static void checkPortBindingFromMap(String fileName, Map<String, Object> portValueMap, - Map<String, Integer> numberOfVisitsInPort, - GlobalValidationContext globalContext) { - String resourcePortName = - (String) portValueMap.get(ResourceReferenceFunctions.GET_RESOURCE.getFunction()); - if (checkIfPortWasVisited(resourcePortName, numberOfVisitsInPort)) { - globalContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder - .getErrorWithParameters(Messages.MORE_THAN_ONE_BIND_FROM_NOVA_TO_PORT.getErrorMessage(), - (String) portValueMap.get(ResourceReferenceFunctions.GET_RESOURCE.getFunction()))); - } else { - incrementNumberOfVisitsInPort(resourcePortName, numberOfVisitsInPort); - } - } - - - private static void initResourceTypeListWithItsResourcesNames(String filename, - Map<HeatResourcesTypes, List<String>> resourcesTypesListMap, - Map<String, Resource> resourcesMap, - Set<String> sharedResourcesFromOutputsMap, - GlobalValidationContext globalContext) { - for (Map.Entry<HeatResourcesTypes, List<String>> resourcesTypesToListEntry - : resourcesTypesListMap.entrySet()) { - HeatResourcesTypes currentType = resourcesTypesToListEntry.getKey(); - List<String> currNamesList = new ArrayList<>(); - getResourceNamesListFromSpecificResource(filename, currNamesList, currentType, resourcesMap, - sharedResourcesFromOutputsMap, globalContext); - resourcesTypesListMap.put(currentType, currNamesList); - } - } - - - private static void checkForEmptyResourceNamesInMap(String fileName, - boolean isBaseFileContainPorts, - Map<HeatResourcesTypes, List<String>> resourcesTypesListMap, - GlobalValidationContext globalContext) { - if (isBaseFileContainPorts) { - for (Map.Entry<HeatResourcesTypes, List<String>> resourcesTypesListEntry - : resourcesTypesListMap.entrySet()) { - handleNotEmptyResourceNamesList(fileName, resourcesTypesListEntry.getValue(), - ResourceTypeToMessageString - .getTypeForMessageFromResourceType(resourcesTypesListEntry.getKey()), - globalContext); - } - } - } - - - private static Set<String> getSharedResourcesNamesFromOutputs(String filename, - Map<String, Output> outputsMap, - GlobalValidationContext globalContext) { - Set<String> sharedResources = new HashSet<>(); - - if (MapUtils.isEmpty(outputsMap)) { - return null; - } - - for (Map.Entry<String, Output> outputEntry : outputsMap.entrySet()) { - Output output = outputEntry.getValue(); - Object valueObject = output.getValue(); - if (valueObject instanceof Map) { - Map<String, Object> outputValueMap = (Map<String, Object>) valueObject; - Object getResourceValue = - outputValueMap.get(ResourceReferenceFunctions.GET_RESOURCE.getFunction()); - if (Objects.nonNull(getResourceValue)) { - if (getResourceValue instanceof String) { - String resourceName = - (String) outputValueMap.get(ResourceReferenceFunctions.GET_RESOURCE.getFunction()); - sharedResources.add(resourceName); - } else { - globalContext.addMessage(filename, ErrorLevel.ERROR, ErrorMessagesFormatBuilder - .getErrorWithParameters(Messages.INVALID_GET_RESOURCE_SYNTAX.getErrorMessage(), - getResourceValue.toString())); - } - } - - } - } - - return sharedResources; - } -} diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/util/YamlValidatorUtil.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/util/YamlValidatorUtil.java new file mode 100644 index 0000000000..8eb8d50774 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/util/YamlValidatorUtil.java @@ -0,0 +1,52 @@ +/*- + * ============LICENSE_START======================================================= + * SDC + * ================================================================================ + * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. + * ================================================================================ + * Licensed under the Apache License, Version 2.0 (the "License"); + * you may not use this file except in compliance with the License. + * You may obtain a copy of the License at + * + * http://www.apache.org/licenses/LICENSE-2.0 + * + * Unless required by applicable law or agreed to in writing, software + * distributed under the License is distributed on an "AS IS" BASIS, + * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. + * See the License for the specific language governing permissions and + * limitations under the License. + * ============LICENSE_END========================================================= + */ + +package org.openecomp.sdc.validation.impl.util; + +import org.openecomp.sdc.common.errors.Messages; +import org.yaml.snakeyaml.error.MarkedYAMLException; +import org.yaml.snakeyaml.parser.ParserException; + +/** + * @author Avrahamg + * @since December 08, 2016 + */ +public class YamlValidatorUtil { + public static String getParserExceptionReason(Exception exception) { + String reason = null; + + if (exception.getCause() instanceof MarkedYAMLException) { + if (exception.getCause() != null) { + if (exception.getCause().getCause() instanceof ParserException) { + reason = exception.getCause().getCause().getMessage(); + } else { + reason = exception.getCause().getMessage(); + } + } + } else if (exception instanceof MarkedYAMLException) { + + reason = exception.getMessage(); + + } else { + reason = Messages.GENERAL_YAML_PARSER_ERROR.getErrorMessage(); + } + return reason; + } +} diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/ContrailValidator.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/ContrailValidator.java new file mode 100644 index 0000000000..3e7d83457f --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/ContrailValidator.java @@ -0,0 +1,201 @@ +/*- + * ============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.validation.impl.validators; + +import org.apache.commons.collections4.MapUtils; +import org.openecomp.core.utilities.yaml.YamlUtil; +import org.openecomp.sdc.validation.Validator; +import org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder; +import org.openecomp.core.validation.types.GlobalValidationContext; +import org.openecomp.sdc.common.errors.Messages; +import org.openecomp.sdc.datatypes.error.ErrorLevel; +import org.openecomp.sdc.heat.datatypes.manifest.FileData; +import org.openecomp.sdc.heat.datatypes.manifest.ManifestContent; +import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate; +import org.openecomp.sdc.heat.datatypes.model.Resource; +import org.openecomp.sdc.heat.services.HeatConstants; +import org.openecomp.sdc.heat.services.manifest.ManifestUtil; +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.types.LoggerErrorDescription; +import org.openecomp.sdc.logging.types.LoggerTragetServiceName; +import org.openecomp.sdc.validation.tos.ContrailResourcesMappingTo; +import org.openecomp.sdc.validation.util.ValidationUtil; + +import java.io.InputStream; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; + + +public class ContrailValidator implements Validator { + public static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); + protected static Logger logger = (Logger) LoggerFactory.getLogger(ContrailValidator.class); + + @Override + public void validate(GlobalValidationContext globalContext) { + mdcDataDebugMessage.debugEntryMessage(null, null); + + ManifestContent manifestContent; + try { + manifestContent = ValidationUtil.checkValidationPreCondition(globalContext); + } catch (Exception exception) { + return; + } + Map<String, FileData.Type> fileTypeMap = ManifestUtil.getFileTypeMap(manifestContent); + ContrailResourcesMappingTo contrailResourcesMappingTo = new ContrailResourcesMappingTo(); + + globalContext.getFiles().stream() + .filter(fileName -> FileData.isHeatFile(fileTypeMap.get(fileName))) + .forEach(fileName -> validate(fileName, fileTypeMap, + contrailResourcesMappingTo, globalContext)); + + mdcDataDebugMessage.debugExitMessage(null, null); + } + + + private void validate(String fileName, Map<String, FileData.Type> fileTypeMap, + ContrailResourcesMappingTo contrailResourcesMappingTo, + GlobalValidationContext globalContext) { + handleContrailV1AndContrailV2ResourceMerging(fileName, fileTypeMap, contrailResourcesMappingTo, + globalContext); + validateNoContrailResourceTypeIsInUse(fileName, globalContext); + } + + + private void handleContrailV1AndContrailV2ResourceMerging(String fileName, + Map<String, FileData.Type> fileTypeMap, + ContrailResourcesMappingTo contrailResourcesMappingTo, + GlobalValidationContext globalContext) { + + + mdcDataDebugMessage.debugEntryMessage("file", fileName); + + Optional<ContrailResourcesMappingTo> fileContrailResourcesMappingTo = + collectHeatFileContrailResources(globalContext, fileName); + if (fileContrailResourcesMappingTo.isPresent()) { + contrailResourcesMappingTo.addAll(fileContrailResourcesMappingTo.get()); + } + addContrailMergeValidationMessageToGlobalContext(globalContext, contrailResourcesMappingTo); + + mdcDataDebugMessage.debugExitMessage("file", fileName); + } + + private void addContrailMergeValidationMessageToGlobalContext( + GlobalValidationContext globalContext, + ContrailResourcesMappingTo contrailResourcesMappingTo) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + + if (!MapUtils.isEmpty(contrailResourcesMappingTo.getContrailV1Resources()) + && !MapUtils.isEmpty(contrailResourcesMappingTo.getContrailV2Resources())) { + globalContext.addMessage( + contrailResourcesMappingTo.getContrailV1Resources().keySet().iterator().next(), + ErrorLevel.WARNING, ErrorMessagesFormatBuilder.getErrorWithParameters( + Messages.MERGE_OF_CONTRAIL2_AND_CONTRAIL3_RESOURCES.getErrorMessage(), + contrailResourcesMappingTo.fetchContrailV1Resources(), + contrailResourcesMappingTo.fetchContrailV2Resources()), + LoggerTragetServiceName.MERGE_OF_CONTRAIL_2_AND_3, + LoggerErrorDescription.MERGE_CONTRAIL_2_AND_3); + } + + mdcDataDebugMessage.debugExitMessage(null, null); + } + + private Optional<ContrailResourcesMappingTo> collectHeatFileContrailResources( + GlobalValidationContext globalContext, String fileName) { + Optional<InputStream> fileContent = globalContext.getFileContent(fileName); + if (!fileContent.isPresent()) { + globalContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder + .getErrorWithParameters(Messages.INVALID_HEAT_FORMAT_REASON.getErrorMessage(), + "The file '" + fileName + "' has no content"), + LoggerTragetServiceName.VALIDATE_HEAT_FORMAT, LoggerErrorDescription.INVALID_HEAT_FORMAT); + return Optional.empty(); + } + return fetchContrailResourcesMapping(fileName, fileContent.get(), globalContext); + } + + private Optional<ContrailResourcesMappingTo> fetchContrailResourcesMapping(String fileName, + InputStream fileContent, + GlobalValidationContext globalContext) { + + + mdcDataDebugMessage.debugEntryMessage("file", fileName); + + ContrailResourcesMappingTo contrailResourcesMappingTo = new ContrailResourcesMappingTo(); + HeatOrchestrationTemplate heatOrchestrationTemplate; + try { + heatOrchestrationTemplate = + new YamlUtil().yamlToObject(fileContent, HeatOrchestrationTemplate.class); + } catch (Exception ignored) { + // the HeatValidator should handle file that is failing to parse + mdcDataDebugMessage.debugExitMessage("file", fileName); + return Optional.empty(); + } + if( !MapUtils.isEmpty(heatOrchestrationTemplate.getResources())) { + heatOrchestrationTemplate.getResources().entrySet() + .forEach(entry -> { + if (entry.getValue().getType().startsWith(HeatConstants.CONTRAIL_RESOURCE_PREFIX)) { + contrailResourcesMappingTo.addContrailV1Resource(fileName, entry.getKey()); + } else if (entry.getValue().getType() + .startsWith(HeatConstants.CONTRAIL_V2_RESOURCE_PREFIX)) { + contrailResourcesMappingTo.addContrailV2Resource(fileName, entry.getKey()); + } + }); + } + + mdcDataDebugMessage.debugExitMessage("file", fileName); + return Optional.of(contrailResourcesMappingTo); + } + + + private void validateNoContrailResourceTypeIsInUse(String fileName, + GlobalValidationContext globalContext) { + + mdcDataDebugMessage.debugEntryMessage("file", fileName); + + HeatOrchestrationTemplate heatOrchestrationTemplate = + ValidationUtil.checkHeatOrchestrationPreCondition(fileName, globalContext); + + if (heatOrchestrationTemplate == null) { + return; + } + + Map<String, Resource> resourcesMap = heatOrchestrationTemplate.getResources(); + + if( ! MapUtils.isEmpty(resourcesMap)) { + for (Map.Entry<String, Resource> resourceEntry : resourcesMap.entrySet()) { + String type = resourceEntry.getValue().getType(); + if (Objects.nonNull(type) && type.startsWith(HeatConstants.CONTRAIL_RESOURCE_PREFIX)) { + globalContext.addMessage(fileName, ErrorLevel.WARNING, ErrorMessagesFormatBuilder + .getErrorWithParameters(Messages.CONTRAIL_2_IN_USE.getErrorMessage(), + resourceEntry.getKey()), LoggerTragetServiceName.CONTRAIL_2_IN_USE, + LoggerErrorDescription.CONTRAIL_2_IN_USE); + } + } + } + + mdcDataDebugMessage.debugExitMessage("file", fileName); + } + +} diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/EcompGuideLineValidator.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/EcompGuideLineValidator.java deleted file mode 100644 index 5be56e4b38..0000000000 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/EcompGuideLineValidator.java +++ /dev/null @@ -1,784 +0,0 @@ -/*- - * ============LICENSE_START======================================================= - * SDC - * ================================================================================ - * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved. - * ================================================================================ - * Licensed under the Apache License, Version 2.0 (the "License"); - * you may not use this file except in compliance with the License. - * You may obtain a copy of the License at - * - * http://www.apache.org/licenses/LICENSE-2.0 - * - * Unless required by applicable law or agreed to in writing, software - * distributed under the License is distributed on an "AS IS" BASIS, - * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. - * See the License for the specific language governing permissions and - * limitations under the License. - * ============LICENSE_END========================================================= - */ - -package org.openecomp.sdc.validation.impl.validators; - -import org.apache.commons.collections4.CollectionUtils; -import org.apache.commons.collections4.MapUtils; -import org.openecomp.core.utilities.CommonMethods; -import org.openecomp.core.utilities.yaml.YamlUtil; -import org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder; -import org.openecomp.core.validation.errors.Messages; -import org.openecomp.core.validation.interfaces.Validator; -import org.openecomp.core.validation.types.GlobalValidationContext; -import org.openecomp.sdc.common.utils.AsdcCommon; -import org.openecomp.sdc.datatypes.error.ErrorLevel; -import org.openecomp.sdc.datatypes.model.heat.ForbiddenHeatResourceTypes; -import org.openecomp.sdc.heat.datatypes.DefinedHeatParameterTypes; -import org.openecomp.sdc.heat.datatypes.manifest.FileData; -import org.openecomp.sdc.heat.datatypes.manifest.ManifestContent; -import org.openecomp.sdc.heat.datatypes.model.Environment; -import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate; -import org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes; -import org.openecomp.sdc.heat.datatypes.model.Resource; -import org.openecomp.sdc.heat.datatypes.model.ResourceReferenceFunctions; -import org.openecomp.sdc.heat.services.HeatStructureUtil; -import org.openecomp.sdc.heat.services.manifest.ManifestUtil; - -import java.util.ArrayList; -import java.util.Collection; -import java.util.Comparator; -import java.util.HashMap; -import java.util.HashSet; -import java.util.List; -import java.util.Map; -import java.util.Objects; -import java.util.Set; -import java.util.TreeMap; -import java.util.regex.Pattern; - -public class EcompGuideLineValidator extends HeatValidator implements Validator { - @Override - public void validate(GlobalValidationContext globalContext) { - - ManifestContent manifestContent; - try { - manifestContent = checkValidationPreCondition(globalContext); - } catch (Exception exception) { - return; - } - - //global validations - Set<String> baseFiles = validateManifest(manifestContent, globalContext); - - Map<String, FileData.Type> fileTypeMap = ManifestUtil.getFileTypeMap(manifestContent); - Map<String, FileData> fileEnvMap = ManifestUtil.getFileAndItsEnv(manifestContent); - globalContext - .getFiles() - .stream() - .filter(fileName -> FileData - .isHeatFile(fileTypeMap.get(fileName))) - .forEach(fileName -> validate(fileName, - fileEnvMap.get(fileName) != null ? fileEnvMap.get(fileName).getFile() : null, - fileTypeMap, baseFiles, globalContext)); - } - - private void validate(String fileName, String envFileName, Map<String, FileData.Type> fileTypeMap, - Set<String> baseFiles, GlobalValidationContext globalContext) { - HeatOrchestrationTemplate heatOrchestrationTemplate = - checkHeatOrchestrationPreCondition(fileName, globalContext); - if (heatOrchestrationTemplate == null) { - return; - } - - validateBaseFile(fileName, baseFiles, heatOrchestrationTemplate, globalContext); - validateHeatVolumeFile(fileName, fileTypeMap, heatOrchestrationTemplate, globalContext); - validateHeatNamingConvention(fileName, heatOrchestrationTemplate, globalContext); - validateHeatNovaResource(fileName, envFileName, heatOrchestrationTemplate, globalContext); - validateResourceTypeIsForbidden(fileName, heatOrchestrationTemplate, globalContext); - validateFixedIpsNamingConvention(fileName, heatOrchestrationTemplate, globalContext); - } - - private void validateHeatNovaResource(String fileName, String envFileName, - HeatOrchestrationTemplate heatOrchestrationTemplate, - GlobalValidationContext globalContext) { - Map<String, String> uniqueResourcePortNetworkRole = new HashMap<>(); - //if no resources exist return - if (heatOrchestrationTemplate.getResources() == null - || heatOrchestrationTemplate.getResources().size() == 0) { - return; - } - - heatOrchestrationTemplate - .getResources() - .entrySet() - .stream() - .filter(entry -> entry.getValue().getType() - .equals(HeatResourcesTypes.NOVA_SERVER_RESOURCE_TYPE.getHeatResource())) - .forEach(entry -> validateNovaServerResourceType(entry.getKey(), fileName, envFileName, - entry, uniqueResourcePortNetworkRole, heatOrchestrationTemplate, globalContext)); - } - - private void validateNovaServerResourceType(String resourceId, String fileName, - String envFileName, - Map.Entry<String, Resource> resourceEntry, - Map<String, String> uniqueResourcePortNetworkRole, - HeatOrchestrationTemplate heatOrchestrationTemplate, - GlobalValidationContext globalValidationContext) { - validateNovaServerResourceMetaData(fileName, resourceId, - heatOrchestrationTemplate.getResources().get(resourceId), globalValidationContext); - validateNovaServerResourceNetworkUniqueRole(fileName, resourceId, heatOrchestrationTemplate, - globalValidationContext); - validateNovaServerNamingConvention(fileName, envFileName, resourceEntry, - globalValidationContext); - validateNovaServerAvailabilityZoneName(fileName, resourceEntry, globalValidationContext); - validateImageAndFlavorFromNovaServer(fileName, resourceEntry, globalValidationContext); - } - - @SuppressWarnings("unchecked") - private void validateNovaServerResourceMetaData(String fileName, String resourceId, - Resource resource, - GlobalValidationContext globalValidationContext) { - Map<String, Object> novaServerProp = resource.getProperties(); - Object novaServerPropMetadata; - if (MapUtils.isNotEmpty(novaServerProp)) { - novaServerPropMetadata = novaServerProp.get("metadata"); - if (novaServerPropMetadata == null) { - globalValidationContext.addMessage( - fileName, - ErrorLevel.WARNING, - ErrorMessagesFormatBuilder - .getErrorWithParameters(Messages.MISSING_NOVA_SERVER_METADATA.getErrorMessage(), - resourceId)); - } else if (novaServerPropMetadata instanceof Map) { - TreeMap<String, Object> propertyMap = new TreeMap(new Comparator<String>() { - - @Override - public int compare(String o1, String o2) { - return o1.compareToIgnoreCase(o2); - } - - @Override - public boolean equals(Object obj) { - return false; - } - }); - propertyMap.putAll((Map) novaServerPropMetadata); - if (!propertyMap.containsKey("vf_module_id")) { - globalValidationContext.addMessage(fileName, ErrorLevel.WARNING, - ErrorMessagesFormatBuilder.getErrorWithParameters( - Messages.MISSING_NOVA_SERVER_VF_MODULE_ID.getErrorMessage(), resourceId)); - } - if (!propertyMap.containsKey("vnf_id")) { - globalValidationContext.addMessage(fileName, ErrorLevel.WARNING, - ErrorMessagesFormatBuilder - .getErrorWithParameters(Messages.MISSING_NOVA_SERVER_VNF_ID.getErrorMessage(), - resourceId)); - } - } - } - } - - private void validateNovaServerResourceNetworkUniqueRole(String fileName, String resourceId, - HeatOrchestrationTemplate - heatOrchestrationTemplate, - GlobalValidationContext - globalValidationContext) { - - String network; - String role; - Map<String, String> uniqueResourcePortNetworkRole = new HashMap<>(); - - Object propertyNetworkValue = - heatOrchestrationTemplate.getResources().get(resourceId).getProperties().get("networks"); - if (propertyNetworkValue != null && propertyNetworkValue instanceof List) { - List<String> portResourceIdList = - getNovaNetworkPortResourceList(fileName, (List) propertyNetworkValue, - globalValidationContext); - for (String portResourceId : portResourceIdList) { - Resource portResource = heatOrchestrationTemplate.getResources().get(portResourceId); - if (portResource != null && portResource.getType() - .equals(HeatResourcesTypes.NEUTRON_PORT_RESOURCE_TYPE.getHeatResource())) { - Map portNetwork = - getPortNetwork(fileName, resourceId, portResource, globalValidationContext); - if (Objects.nonNull(portNetwork)) { - network = (String) portNetwork.get("get_param"); - if (Objects.nonNull(network)) { - role = getNetworkRole(network); - if (role != null && uniqueResourcePortNetworkRole.containsKey(role)) { - globalValidationContext.addMessage(fileName, ErrorLevel.WARNING, - ErrorMessagesFormatBuilder.getErrorWithParameters( - Messages.RESOURCE_CONNECTED_TO_TWO_EXTERNAL_NETWORKS_WITH_SAME_ROLE - .getErrorMessage(), resourceId, role)); - } else { - uniqueResourcePortNetworkRole.put(role, portResourceId); - } - } - } - } - } - } - } - - - private Map getPortNetwork(String fileName, String resourceId, Resource portResource, - GlobalValidationContext globalValidationContext) { - Object portNetwork = portResource.getProperties().get("network_id"); - if (portNetwork == null) { - portNetwork = portResource.getProperties().get("network"); - } - if (!(portNetwork instanceof Map)) { - globalValidationContext.addMessage(fileName, ErrorLevel.WARNING, ErrorMessagesFormatBuilder - .getErrorWithParameters(Messages.MISSING_GET_PARAM.getErrorMessage(), - "network or network_id", resourceId)); - return null; - } - return (Map) portNetwork; - } - - private List<String> getNovaNetworkPortResourceList(String filename, List propertyNetworkValue, - GlobalValidationContext globalContext) { - List<String> portResourceIdList = new ArrayList<>(); - for (Object propValue : propertyNetworkValue) { - Object portPropValue = ((Map) propValue).get("port"); - Collection<String> portResourceIds = HeatStructureUtil - .getReferencedValuesByFunctionName(filename, "get_resource", portPropValue, - globalContext); - if (portResourceIds != null) { - portResourceIdList.addAll(portResourceIds); - } - } - - return portResourceIdList; - } - - private String getNetworkRole(String network) { - if (network == null) { - return null; - } - if (network.contains("_net_id")) { - return network.substring(0, network.indexOf("_net_id")); - } else if (network.contains("net_name")) { - return network.substring(0, network.indexOf("_net_name")); - } else if (network.contains("net_fqdn")) { - return network.substring(0, network.indexOf("_net_fqdn")); - } - return null; - } - - private void validateHeatNamingConvention(String fileName, - HeatOrchestrationTemplate heatOrchestrationTemplate, - GlobalValidationContext globalContext) { - validatePortNetworkNamingConvention(fileName, heatOrchestrationTemplate, globalContext); - } - - private void validatePortNetworkNamingConvention(String fileName, - HeatOrchestrationTemplate - heatOrchestrationTemplate, - GlobalValidationContext globalContext) { - if (MapUtils.isEmpty(heatOrchestrationTemplate.getResources())) { - return; - } - String[] regexList = new String[]{".*_net_id", ".*_net_name", ".*_net_fqdn"}; - - heatOrchestrationTemplate - .getResources() - .entrySet() - .stream() - .filter(entry -> entry.getValue().getType() != null && entry.getValue().getType() - .equals(HeatResourcesTypes.NEUTRON_PORT_RESOURCE_TYPE.getHeatResource())) - .forEach(entry -> entry.getValue() - .getProperties() - .entrySet() - .stream() - .filter(propertyEntry -> propertyEntry != null - && (propertyEntry.getKey().toLowerCase().equals("network".toLowerCase()) - || - propertyEntry.getKey().equals("network_id"))) - .forEach(propertyEntry -> validateParamNamingConvention(fileName, entry.getKey(), - propertyEntry.getValue(), regexList, - Messages.NETWORK_PARAM_NOT_ALIGNED_WITH_GUIDE_LINE, globalContext))); - } - - private void validateParamNamingConvention(String fileName, String resourceId, - Object propertyValue, String[] regexList, - Messages message, - GlobalValidationContext globalContext) { - Object paramName; - if (propertyValue instanceof Map) { - paramName = ((Map) propertyValue).get("get_param"); - if (paramName instanceof String) { - if (!evalPattern((String) paramName, regexList)) { - globalContext.addMessage(fileName, ErrorLevel.WARNING, ErrorMessagesFormatBuilder - .getErrorWithParameters(message.getErrorMessage(), (String) paramName, resourceId)); - } - } - } else { - globalContext.addMessage(fileName, ErrorLevel.WARNING, ErrorMessagesFormatBuilder - .getErrorWithParameters(Messages.MISSING_GET_PARAM.getErrorMessage(), - "network or network_id", resourceId)); - } - } - - private boolean evalPattern(Object paramVal, String[] regexList) { - String value = ""; - if (paramVal instanceof String) { - value = ((String) paramVal); - } - if (paramVal instanceof Integer) { - value = paramVal.toString(); - } - return evalPattern(value, regexList); - } - - private boolean evalPattern(String paramVal, String[] regexList) { - - for (String regex : regexList) { - if (Pattern.matches(regex, paramVal)) { - return true; - } - } - - return false; - } - - - private void validateHeatVolumeFile(String fileName, Map<String, FileData.Type> fileTypeMap, - HeatOrchestrationTemplate heatOrchestrationTemplate, - GlobalValidationContext globalContext) { - //if not heat volume return - if (!fileTypeMap.get(fileName).equals(FileData.Type.HEAT_VOL)) { - return; - } - - //if no resources exist return - if (heatOrchestrationTemplate.getResources() == null - || heatOrchestrationTemplate.getResources().size() == 0) { - return; - } - - Set<String> expectedExposedResources = new HashSet<>(); - Set<String> actualExposedResources = new HashSet<>(); - heatOrchestrationTemplate.getResources() - .entrySet() - .stream() - .filter(entry -> entry.getValue().getType() - .equals(HeatResourcesTypes.CINDER_VOLUME_RESOURCE_TYPE.getHeatResource())) - .forEach(entry -> expectedExposedResources.add(entry.getKey())); - - if (heatOrchestrationTemplate.getOutputs() != null) { - - heatOrchestrationTemplate.getOutputs().entrySet() - .stream() - .filter(entry -> isPropertyValueGetResource(fileName, entry.getValue().getValue(), - globalContext)) - .forEach(entry -> actualExposedResources.add( - getResourceIdFromPropertyValue(fileName, entry.getValue().getValue(), - globalContext))); - } - - actualExposedResources.stream().forEach(expectedExposedResources::remove); - - if (expectedExposedResources.size() > 0) { - expectedExposedResources - .stream() - .forEach(name -> globalContext.addMessage(fileName, ErrorLevel.WARNING, - ErrorMessagesFormatBuilder - .getErrorWithParameters(Messages.VOLUME_HEAT_NOT_EXPOSED.getErrorMessage(), - name))); - } - } - - private void validateBaseFile(String fileName, Set<String> baseFiles, - HeatOrchestrationTemplate heatOrchestrationTemplate, - GlobalValidationContext globalContext) { - - //if not base return - if (baseFiles == null || !baseFiles.contains(fileName)) { - return; - } - - //if no resources exist return - if (heatOrchestrationTemplate.getResources() == null - || heatOrchestrationTemplate.getResources().size() == 0) { - return; - } - - Set<String> expectedExposedResources = new HashSet<>(); - Set<String> actualExposedResources = new HashSet<>(); - heatOrchestrationTemplate.getResources() - .entrySet() - .stream() - .filter(entry -> isExpectedToBeExposed(entry.getValue().getType())) - .forEach(entry -> expectedExposedResources.add(entry.getKey())); - - if (heatOrchestrationTemplate.getOutputs() != null) { - - heatOrchestrationTemplate.getOutputs().entrySet() - .stream() - .filter(entry -> isPropertyValueGetResource(fileName, entry.getValue().getValue(), - globalContext)) - .forEach(entry -> actualExposedResources.add( - getResourceIdFromPropertyValue(fileName, entry.getValue().getValue(), - globalContext))); - } - actualExposedResources.stream().forEach(expectedExposedResources::remove); - - if (expectedExposedResources.size() > 0) { - expectedExposedResources - .stream() - .forEach(name -> globalContext.addMessage(fileName, ErrorLevel.WARNING, - ErrorMessagesFormatBuilder - .getErrorWithParameters(Messages.RESOURCE_NOT_DEFINED_IN_OUTPUT.getErrorMessage(), - name))); - } - } - - private void validateResourceTypeIsForbidden(String fileName, - HeatOrchestrationTemplate heatOrchestrationTemplate, - GlobalValidationContext globalContext) { - if (MapUtils.isEmpty(heatOrchestrationTemplate.getResources())) { - return; - } - - heatOrchestrationTemplate.getResources() - .entrySet() - .stream() - .filter(entry -> - ForbiddenHeatResourceTypes.findByForbiddenHeatResource(entry.getValue().getType()) - != null) - .filter(entry -> ForbiddenHeatResourceTypes - .findByForbiddenHeatResource(entry.getValue().getType()) - .equals(ForbiddenHeatResourceTypes.HEAT_FLOATING_IP_TYPE)) - .forEach(entry -> globalContext.addMessage(fileName, ErrorLevel.WARNING, - ErrorMessagesFormatBuilder - .getErrorWithParameters(Messages.FLOATING_IP_NOT_IN_USE.getErrorMessage(), - entry.getKey()))); - } - - - private void validateFixedIpsNamingConvention(String fileName, - HeatOrchestrationTemplate heatOrchestrationTemplate, - GlobalValidationContext globalContext) { - if (MapUtils.isEmpty(heatOrchestrationTemplate.getResources())) { - return; - } - - heatOrchestrationTemplate.getResources() - .entrySet() - .stream() - .filter(entry -> HeatResourcesTypes.findByHeatResource(entry.getValue().getType()) != null) - .filter(entry -> HeatResourcesTypes.findByHeatResource(entry.getValue().getType()) - .equals(HeatResourcesTypes.NEUTRON_PORT_RESOURCE_TYPE)) - .forEach(entry -> checkNeutronPortFixedIpsName(fileName, entry, globalContext)); - } - - private void validateImageAndFlavorFromNovaServer(String fileName, - Map.Entry<String, Resource> resourceEntry, - GlobalValidationContext globalContext) { - if (MapUtils.isEmpty(resourceEntry.getValue().getProperties())) { - return; - } - - String[] imageOrFlavorAsParameters = new String[]{"image", "flavor"}; - Map<String, Object> propertiesMap = resourceEntry.getValue().getProperties(); - - for (String imageOrFlavor : imageOrFlavorAsParameters) { - checkImageAndFlavorNames(fileName, imageOrFlavor, resourceEntry.getKey(), propertiesMap, - globalContext); - } - } - - private void checkImageAndFlavorNames(String fileName, String imageOrFlavor, String resourceId, - Map<String, Object> propertiesMap, - GlobalValidationContext globalContext) { - Object nameValue = - propertiesMap.get(imageOrFlavor) == null ? null : propertiesMap.get(imageOrFlavor); - String[] regexList = new String[]{".*_" + imageOrFlavor + "_name"}; - - if (Objects.nonNull(nameValue)) { - if (nameValue instanceof Map) { - String imageOrFlavorName = getWantedNameFromPropertyValueGetParam(nameValue); - if (Objects.nonNull(imageOrFlavorName)) { - if (!evalPattern(imageOrFlavorName, regexList)) { - globalContext.addMessage(fileName, ErrorLevel.WARNING, ErrorMessagesFormatBuilder - .getErrorWithParameters( - Messages.WRONG_IMAGE_OR_FLAVOR_NAME_NOVA_SERVER.getErrorMessage(), - imageOrFlavor, resourceId)); - } - } - } else { - globalContext.addMessage(fileName, ErrorLevel.WARNING, ErrorMessagesFormatBuilder - .getErrorWithParameters(Messages.MISSING_GET_PARAM.getErrorMessage(), imageOrFlavor, - resourceId)); - } - } - } - - - @SuppressWarnings("unchecked") - private void checkNeutronPortFixedIpsName(String fileName, - Map.Entry<String, Resource> resourceEntry, - GlobalValidationContext globalContext) { - String[] regexList = - new String[]{"[^_]+_[^_]+_ips", "[^_]+_[^_]+_v6_ips", "[^_]+_[^_]+_ip_(\\d+)", - "[^_]+_[^_]+_v6_ip_(\\d+)"}; - - if (MapUtils.isEmpty(resourceEntry.getValue().getProperties())) { - return; - } - - Map<String, Object> propertiesMap = resourceEntry.getValue().getProperties(); - Object fixedIps = propertiesMap.get("fixed_ips"); - if (Objects.nonNull(fixedIps) && fixedIps instanceof List) { - List<Object> fixedIpsList = (List<Object>) fixedIps; - for (Object fixedIpsObject : fixedIpsList) { - Map.Entry<String, Object> fixedIpsEntry = - ((Map<String, Object>) fixedIpsObject).entrySet().iterator().next(); - if (Objects.nonNull(fixedIpsEntry)) { - if (fixedIpsEntry.getValue() instanceof Map) { - String fixedIpsName = getWantedNameFromPropertyValueGetParam(fixedIpsEntry.getValue()); - if (Objects.nonNull(fixedIpsName)) { - if (!evalPattern(fixedIpsName, regexList)) { - globalContext.addMessage(fileName, ErrorLevel.WARNING, ErrorMessagesFormatBuilder - .getErrorWithParameters( - Messages.FIXED_IPS_NOT_ALIGNED_WITH_GUIDE_LINES.getErrorMessage(), - resourceEntry.getKey())); - } - } - } else { - globalContext.addMessage(fileName, ErrorLevel.WARNING, ErrorMessagesFormatBuilder - .getErrorWithParameters(Messages.MISSING_GET_PARAM.getErrorMessage(), "fixed_ips", - resourceEntry.getKey())); - } - } - } - } - } - - - private void validateNovaServerNamingConvention(String fileName, String envFileName, - Map.Entry<String, Resource> resourceEntry, - GlobalValidationContext globalContext) { - if (MapUtils.isEmpty(resourceEntry.getValue().getProperties())) { - return; - } - - checkIfNovaNameByGuidelines(fileName, envFileName, resourceEntry, globalContext); - } - - private void checkIfNovaNameByGuidelines(String fileName, String envFileName, - Map.Entry<String, Resource> resourceEntry, - GlobalValidationContext globalContext) { - if (MapUtils.isEmpty(resourceEntry.getValue().getProperties())) { - return; - } - - Object novaServerName = resourceEntry.getValue().getProperties().get("name"); - Map novaNameMap; - String novaName; - if (Objects.nonNull(novaServerName)) { - if (novaServerName instanceof Map) { - novaNameMap = (Map) novaServerName; - Object novaNameGetParam = - novaNameMap.get(ResourceReferenceFunctions.GET_PARAM.getFunction()) == null ? null - : novaNameMap.get(ResourceReferenceFunctions.GET_PARAM.getFunction()); - if (Objects.nonNull(novaNameGetParam)) { - checkNovaNameGetParamValueMap(fileName, novaNameGetParam, resourceEntry, globalContext); - novaName = novaNameGetParam instanceof List ? (String) ((List) novaNameGetParam).get(0) - : (String) novaNameGetParam; - checkIfNovaNameParameterInEnvIsStringOrList(fileName, envFileName, resourceEntry, - novaName, globalContext); - } - } else { - globalContext.addMessage(fileName, ErrorLevel.WARNING, ErrorMessagesFormatBuilder - .getErrorWithParameters(Messages.MISSING_GET_PARAM.getErrorMessage(), - "nova server name", resourceEntry.getKey())); - } - } - - } - - private void checkIfNovaNameParameterInEnvIsStringOrList(String fileName, String envFileName, - Map.Entry<String, Resource> - resourceEntry, - String novaServerName, - GlobalValidationContext globalContext) { - if (Objects.nonNull(envFileName)) { - Environment environment = validateEnvContent(envFileName, globalContext); - - if (environment != null && MapUtils.isNotEmpty(environment.getParameters())) { - Object novaServerNameEnvValue = - environment.getParameters().containsKey(novaServerName) ? environment.getParameters() - .get(novaServerName) : null; - if (Objects.nonNull(novaServerNameEnvValue)) { - if (!DefinedHeatParameterTypes - .isNovaServerEnvValueIsFromRightType(novaServerNameEnvValue)) { - globalContext.addMessage(fileName, ErrorLevel.WARNING, ErrorMessagesFormatBuilder - .getErrorWithParameters( - Messages.NOVA_SERVER_NAME_NOT_ALIGNED_WITH_GUIDE_LINES.getErrorMessage(), - resourceEntry.getKey())); - } - } - } - } - } - - - private void validateNovaServerAvailabilityZoneName(String fileName, - Map.Entry<String, Resource> resourceEntry, - GlobalValidationContext globalContext) { - String[] regexList = new String[]{"availability_zone_(\\d+)"}; - - if (MapUtils.isEmpty(resourceEntry.getValue().getProperties())) { - return; - } - - Object availabilityZoneMap = - resourceEntry.getValue().getProperties().containsKey("availability_zone") ? resourceEntry - .getValue().getProperties().get("availability_zone") : null; - - if (Objects.nonNull(availabilityZoneMap)) { - if (availabilityZoneMap instanceof Map) { - String availabilityZoneName = getWantedNameFromPropertyValueGetParam(availabilityZoneMap); - - if (availabilityZoneName != null) { - if (!evalPattern(availabilityZoneName, regexList)) { - globalContext.addMessage(fileName, ErrorLevel.WARNING, ErrorMessagesFormatBuilder - .getErrorWithParameters( - Messages.AVAILABILITY_ZONE_NOT_ALIGNED_WITH_GUIDE_LINES.getErrorMessage(), - resourceEntry.getKey())); - } - } - } else { - globalContext.addMessage(fileName, ErrorLevel.WARNING, ErrorMessagesFormatBuilder - .getErrorWithParameters(Messages.MISSING_GET_PARAM.getErrorMessage(), - "availability_zone", resourceEntry.getKey())); - } - } - - } - - @SuppressWarnings("unchecked") - private void checkNovaNameGetParamValueMap(String fileName, Object getParamValue, - Map.Entry<String, Resource> resourceEntry, - GlobalValidationContext globalContext) { - if (getParamValue instanceof List) { - List<Object> getParamNameList = (List) getParamValue; - String[] regexName = new String[]{".*_names"}; - isNovaNameAsListLegal(fileName, getParamNameList, regexName, resourceEntry, globalContext); - } else if (getParamValue instanceof String) { - String[] regexName = new String[]{".*_name_(\\d+)"}; - isNovaNameAsStringLegal(fileName, (String) getParamValue, regexName, resourceEntry, - globalContext); - } - - } - - - private void isNovaNameAsListLegal(String fileName, List<Object> getParamNameList, - String[] regexName, Map.Entry<String, Resource> resourceEntry, - GlobalValidationContext globalContext) { - - if (getParamNameList.size() != 2 || !evalPattern(getParamNameList.get(0), regexName)) { - globalContext.addMessage(fileName, ErrorLevel.WARNING, ErrorMessagesFormatBuilder - .getErrorWithParameters( - Messages.NOVA_SERVER_NAME_NOT_ALIGNED_WITH_GUIDE_LINES.getErrorMessage(), - resourceEntry.getKey())); - } - } - - private boolean isNovaNameAsStringLegal(String fileName, String novaName, String[] regexName, - Map.Entry<String, Resource> resourceEntry, - GlobalValidationContext globalContext) { - if (!evalPattern(novaName, regexName)) { - globalContext.addMessage(fileName, ErrorLevel.WARNING, ErrorMessagesFormatBuilder - .getErrorWithParameters( - Messages.NOVA_SERVER_NAME_NOT_ALIGNED_WITH_GUIDE_LINES.getErrorMessage(), - resourceEntry.getKey())); - return false; - } - return true; - } - - private String getWantedNameFromPropertyValueGetParam(Object value) { - Set<String> paramName = HeatStructureUtil - .getReferencedValuesByFunctionName(null, ResourceReferenceFunctions.GET_PARAM.getFunction(), - value, null); - if (paramName != null && CollectionUtils.isNotEmpty(paramName)) { - return (String) paramName.toArray()[0]; - } - return null; - } - - private String getResourceIdFromPropertyValue(String filename, Object value, - GlobalValidationContext globalContext) { - Set<String> referenceValues = HeatStructureUtil.getReferencedValuesByFunctionName(filename, - ResourceReferenceFunctions.GET_RESOURCE.getFunction(), value, globalContext); - if (referenceValues != null && CollectionUtils.isNotEmpty(referenceValues)) { - return (String) referenceValues.toArray()[0]; - } - return null; - } - - private boolean isPropertyValueGetResource(String filename, Object value, - GlobalValidationContext globalContext) { - Set<String> referenceValues = HeatStructureUtil.getReferencedValuesByFunctionName(filename, - ResourceReferenceFunctions.GET_RESOURCE.getFunction(), value, globalContext); - return referenceValues != null && (referenceValues.size() > 0); - } - - private boolean isExpectedToBeExposed(String type) { - return HeatResourcesTypes.isResourceExpectedToBeExposed(type); - } - - private Set<String> validateManifest(ManifestContent manifestContent, - GlobalValidationContext globalContext) { - Set<String> baseFiles = ManifestUtil.getBaseFiles(manifestContent); - if (baseFiles == null || baseFiles.size() == 0) { - globalContext.addMessage( - AsdcCommon.MANIFEST_NAME, - ErrorLevel.WARNING, - ErrorMessagesFormatBuilder - .getErrorWithParameters(Messages.MISSIN_BASE_HEAT_FILE.getErrorMessage())); - } else if (baseFiles.size() > 1) { - String baseFileList = getElementListAsString(baseFiles); - globalContext.addMessage( - AsdcCommon.MANIFEST_NAME, - ErrorLevel.WARNING, - ErrorMessagesFormatBuilder - .getErrorWithParameters(Messages.MULTI_BASE_HEAT_FILE.getErrorMessage(), - baseFileList)); - } - return baseFiles; - } - - private String getElementListAsString(Set<String> elementCollection) { - - return "[" + CommonMethods.collectionToCommaSeparatedString(elementCollection) + "]"; - } - - - private Environment validateEnvContent(String envFileName, - GlobalValidationContext globalContext) { - Environment envContent; - try { - envContent = - new YamlUtil().yamlToObject(globalContext.getFileContent(envFileName), Environment.class); - } catch (Exception exception) { - return null; - } - return envContent; - } - - private HeatOrchestrationTemplate checkHeatOrchestrationPreCondition(String fileName, - GlobalValidationContext - globalContext) { - HeatOrchestrationTemplate heatOrchestrationTemplate; - try { - heatOrchestrationTemplate = new YamlUtil() - .yamlToObject(globalContext.getFileContent(fileName), HeatOrchestrationTemplate.class); - - } catch (Exception exception) { - return null; - } - return heatOrchestrationTemplate; - } -}
\ No newline at end of file diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/ForbiddenResourceGuideLineValidator.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/ForbiddenResourceGuideLineValidator.java new file mode 100644 index 0000000000..2531150eab --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/ForbiddenResourceGuideLineValidator.java @@ -0,0 +1,125 @@ +package org.openecomp.sdc.validation.impl.validators; + +import org.apache.commons.collections4.MapUtils; +import org.openecomp.sdc.validation.Validator; +import org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder; +import org.openecomp.core.validation.types.GlobalValidationContext; +import org.openecomp.sdc.common.errors.Messages; +import org.openecomp.sdc.datatypes.error.ErrorLevel; +import org.openecomp.sdc.heat.datatypes.manifest.FileData; +import org.openecomp.sdc.heat.datatypes.manifest.ManifestContent; +import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate; +import org.openecomp.sdc.heat.datatypes.model.Resource; +import org.openecomp.sdc.heat.services.manifest.ManifestUtil; +import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; +import org.openecomp.sdc.logging.types.LoggerErrorDescription; +import org.openecomp.sdc.logging.types.LoggerTragetServiceName; +import org.openecomp.sdc.validation.util.ValidationUtil; + +import java.util.HashMap; +import java.util.HashSet; +import java.util.Map; +import java.util.Objects; +import java.util.Set; + +/** + * Created by TALIO on 2/15/2017. + */ +public class ForbiddenResourceGuideLineValidator implements Validator { + private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); + private static Set<String> forbiddenResources = new HashSet<>(); + + @Override + public void init(Map<String, Object> properties) { + Map<String, Map<String, Object>> forbiddenResourcesMap = + (Map<String, Map<String, Object>>) properties.get("forbiddenResourceTypes"); + + forbiddenResourcesMap.entrySet().stream() + .filter(entry -> isResourceEnabled(entry.getValue().get("enable"))) + .forEach(entry -> forbiddenResources.add(entry.getKey())); + + + + + } + + private boolean isResourceEnabled(Object enableValue){ + if(Objects.isNull(enableValue)){ + return true; + } + + if(enableValue instanceof Boolean){ + return (Boolean)enableValue; + } + + return Boolean.valueOf((String) enableValue); + } + + + @Override + public void validate(GlobalValidationContext globalContext) { + ManifestContent manifestContent; + try { + manifestContent = ValidationUtil.checkValidationPreCondition(globalContext); + } catch (Exception exception) { + return; + } + + Map<String, FileData.Type> fileTypeMap = ManifestUtil.getFileTypeMap(manifestContent); + + globalContext.getFiles().stream() + .filter(fileName -> FileData + .isHeatFile(fileTypeMap.get(fileName))) + .forEach(fileName -> validate(fileName, globalContext)); + } + + private void validate(String fileName, GlobalValidationContext globalContext) { + HeatOrchestrationTemplate + heatOrchestrationTemplate = ValidationUtil.checkHeatOrchestrationPreCondition(fileName, globalContext); + if (heatOrchestrationTemplate == null) { + return; + } + + validateResourceTypeIsForbidden(fileName, heatOrchestrationTemplate, globalContext); + } + + private void validateResourceTypeIsForbidden(String fileName, + HeatOrchestrationTemplate heatOrchestrationTemplate, + GlobalValidationContext globalContext) { + + mdcDataDebugMessage.debugEntryMessage("file", fileName); + + Map<String, Resource> resourcesMap = heatOrchestrationTemplate.getResources(); + if (MapUtils.isEmpty(resourcesMap)) { + mdcDataDebugMessage.debugExitMessage("file", fileName); + return; + } + + for (Map.Entry<String, Resource> resourceEntry : resourcesMap.entrySet()) { + String resourceType = resourceEntry.getValue().getType(); + if (Objects.isNull(resourceType)) { + globalContext.addMessage(fileName, ErrorLevel.WARNING, ErrorMessagesFormatBuilder + .getErrorWithParameters(Messages.INVALID_RESOURCE_TYPE.getErrorMessage(), "null", + resourceEntry.getKey()), LoggerTragetServiceName.VALIDATE_RESOURCE_TYPE, + LoggerErrorDescription.INVALID_RESOURCE_TYPE); + } else { + if(isResourceForbidden(resourceType)){ + globalContext.addMessage( + fileName, + ErrorLevel.WARNING, + ErrorMessagesFormatBuilder + .getErrorWithParameters(Messages.FORBIDDEN_RESOURCE_IN_USE.getErrorMessage(), + resourceType, + resourceEntry.getKey()), + LoggerTragetServiceName.VALIDATE_FORBIDDEN_RESOURCE, + LoggerErrorDescription.FLOATING_IP_IN_USE); + } + } + } + mdcDataDebugMessage.debugExitMessage("file", fileName); + } + + private boolean isResourceForbidden(String resourceType){ + return forbiddenResources.contains(resourceType); + } +} diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/HeatResourceValidator.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/HeatResourceValidator.java new file mode 100644 index 0000000000..2712dab11c --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/HeatResourceValidator.java @@ -0,0 +1,341 @@ +package org.openecomp.sdc.validation.impl.validators; + +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.collections4.MapUtils; +import org.openecomp.core.validation.types.GlobalValidationContext; +import org.openecomp.sdc.heat.datatypes.manifest.ManifestContent; +import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate; +import org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes; +import org.openecomp.sdc.heat.datatypes.model.Output; +import org.openecomp.sdc.heat.datatypes.model.Resource; +import org.openecomp.sdc.heat.datatypes.model.ResourceReferenceFunctions; +import org.openecomp.sdc.heat.services.HeatStructureUtil; +import org.openecomp.sdc.heat.services.manifest.ManifestUtil; +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.validation.ValidationContext; +import org.openecomp.sdc.validation.base.ResourceBaseValidator; +import org.openecomp.sdc.validation.type.ConfigConstants; +import org.openecomp.sdc.validation.type.HeatResourceValidationContext; +import org.openecomp.sdc.validation.util.ValidationUtil; + +import java.util.ArrayList; +import java.util.Collection; +import java.util.HashMap; +import java.util.HashSet; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.Set; + +public class HeatResourceValidator extends ResourceBaseValidator { + public static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); + private static Logger logger = (Logger) LoggerFactory.getLogger(ResourceBaseValidator.class); + + @Override + public void init(Map<String, Object> properties) { + super.init((Map<String, Object>) properties.get(ConfigConstants.Resource_Base_Validator)); + } + + @Override + public ValidationContext createValidationContext(String fileName, + String envFileName, + HeatOrchestrationTemplate heatOrchestrationTemplate, + GlobalValidationContext globalContext) { + ManifestContent manifestContent = new ManifestContent(); + try { + manifestContent = ValidationUtil.checkValidationPreCondition(globalContext); + } catch (Exception exception) { + + } + Set<String> baseFiles = ManifestUtil.getBaseFiles(manifestContent); + String baseFileName = CollectionUtils.isEmpty(baseFiles) ? null : baseFiles.iterator().next(); + HeatOrchestrationTemplate baseHot = + ValidationUtil.checkHeatOrchestrationPreCondition(baseFileName, globalContext); + Set<String> securityGroupsNamesFromBaseFileOutputs = baseFileName == null ? new HashSet<>() + : checkForBaseFilePortsExistenceAndReturnSecurityGroupNamesFromOutputsIfNot + (baseFileName, baseHot, globalContext); + + Map<String, Resource> resourcesMap = + heatOrchestrationTemplate.getResources() == null ? new HashMap<>() + : heatOrchestrationTemplate.getResources(); + + Map<String, Output> outputMap = heatOrchestrationTemplate.getOutputs() == null ? new HashMap<>() + : heatOrchestrationTemplate.getOutputs(); + + Map<String, Map<String, Map<String, List<String>>>> + typeToPointingResourcesMap = new HashMap<>(); + + initTypeRelationsMap + (fileName, resourcesMap, outputMap, + securityGroupsNamesFromBaseFileOutputs, typeToPointingResourcesMap, globalContext); + + return new HeatResourceValidationContext + (heatOrchestrationTemplate, typeToPointingResourcesMap, envFileName); + } + + private void initTypeRelationsMap(String fileName, + Map<String, Resource> resourceMap, + Map<String, Output> outputMap, + Set<String> securityGroupsNamesFromBaseFileOutputs, + Map<String, Map<String, Map<String, List<String>>>> typeToPointingResourcesMap, + GlobalValidationContext globalContext) { + + initTypeRelationsMapFromResourcesMap + (fileName, resourceMap, securityGroupsNamesFromBaseFileOutputs, + typeToPointingResourcesMap, globalContext); + + initTypeRelationsMapFromOutputsMap + (fileName, resourceMap, outputMap, + typeToPointingResourcesMap, globalContext); + } + + private void initTypeRelationsMapFromOutputsMap(String fileName, + Map<String, Resource> resourceMap, + Map<String, Output> outputMap, + Map<String, Map<String, Map<String, List<String>>>> typeToPointingResourcesMap, + GlobalValidationContext globalContext) { + for (Map.Entry<String, Output> outputEntry : outputMap.entrySet()) { + Object outputValue = outputEntry.getValue().getValue(); + Set<String> referencedResources = HeatStructureUtil + .getReferencedValuesByFunctionName(fileName, + ResourceReferenceFunctions.GET_RESOURCE.getFunction(), outputValue, globalContext); + + updateRelationsMapWithOutputsReferences + (outputEntry, resourceMap, referencedResources, typeToPointingResourcesMap); + + + } + } + + private void updateRelationsMapWithOutputsReferences(Map.Entry<String, Output> outputEntry, + Map<String, Resource> resourceMap, + Set<String> referencedResources, + Map<String, Map<String, Map<String, List<String>>>> typeToPointingResourcesMap) { + + for (String pointedResourceName : referencedResources) { + Resource pointedResource = resourceMap.get(pointedResourceName); + + if (Objects.nonNull(pointedResource)) { + initCurrentResourceTypeInMap(pointedResourceName, pointedResource.getType(), + "output", typeToPointingResourcesMap); + + typeToPointingResourcesMap + .get(pointedResource.getType()).get(pointedResourceName) + .get("output").add(outputEntry.getKey()); + } + } + } + + private void initTypeRelationsMapFromResourcesMap(String fileName, + Map<String, Resource> resourceMap, + Set<String> securityGroupsNamesFromBaseFileOutputs, + Map<String, Map<String, Map<String, List<String>>>> typeToPointingResourcesMap, + GlobalValidationContext globalContext) { + for (Map.Entry<String, Resource> resourceEntry : resourceMap.entrySet()) { + Resource pointingResource = resourceEntry.getValue(); + Map<String, Object> properties = + pointingResource.getProperties() == null ? new HashMap<>() : pointingResource.getProperties(); + + Set<String> referencedResourcesByGetResource = + getResourcesIdsPointedByCurrentResource(fileName, ResourceReferenceFunctions.GET_RESOURCE, + properties, globalContext); + + Set<String> referencedResourcesByGetAttr = + handleGetAttrBetweenResources(properties); + + referencedResourcesByGetResource.addAll(referencedResourcesByGetAttr); + + updateRelationsMapWithCurrentResourceReferences + (resourceMap, resourceEntry, referencedResourcesByGetResource, + typeToPointingResourcesMap); + } + } + + private void updateRelationsMapWithSecurityGroupsFromBaseFileOutput(String fileName, + Map<String, Resource> resourcesMap, + Map.Entry<String, Resource> resourceEntry, + Map<String, Object> properties, + Set<String> securityGroupsNamesFromBaseFileOutputs, + Map<String, Map<String, Map<String, List<String>>>> typeToPointingResourcesMap, + GlobalValidationContext globalContext) { + + Set<String> candidateSecurityGroupUsedFromBaseFile = getResourcesIdsPointedByCurrentResource + (fileName, ResourceReferenceFunctions.GET_PARAM, properties, globalContext); + removeNonSecurityGroupNamesFromList + (candidateSecurityGroupUsedFromBaseFile, securityGroupsNamesFromBaseFileOutputs); + + for (String usedSecurityGroupId : candidateSecurityGroupUsedFromBaseFile) { + updateMapWithRelationsBetweenResources + (usedSecurityGroupId, + HeatResourcesTypes.NEUTRON_SECURITY_GROUP_RESOURCE_TYPE.getHeatResource(), + resourceEntry, typeToPointingResourcesMap); + + } + } + + private void removeNonSecurityGroupNamesFromList( + Set<String> candidateSecurityGroupUsedFromBaseFile, + Set<String> securityGroupsNamesFromBaseFileOutputs) { + + Set<String> nonSecurityGroupNames = new HashSet<>(); + for (String candidateSecurityGroup : candidateSecurityGroupUsedFromBaseFile) { + if (!securityGroupsNamesFromBaseFileOutputs.contains(candidateSecurityGroup)) { + nonSecurityGroupNames.add(candidateSecurityGroup); + } + } + + candidateSecurityGroupUsedFromBaseFile.removeAll(nonSecurityGroupNames); + } + + private void updateRelationsMapWithCurrentResourceReferences(Map<String, Resource> resourceMap, + Map.Entry<String, Resource> currentResourceEntry, + Set<String> referencedResourcesFromCurrentResource, + Map<String, Map<String, Map<String, List<String>>>> typeToPointingResourcesMap) { + + for (String pointedResourceName : referencedResourcesFromCurrentResource) { + Resource pointedResource = resourceMap.get(pointedResourceName); + if (Objects.nonNull(pointedResource)) { + String pointedResourceType = pointedResource.getType(); + + updateMapWithRelationsBetweenResources + (pointedResourceName, pointedResourceType, + currentResourceEntry, typeToPointingResourcesMap); + } + } + } + + private void updateMapWithRelationsBetweenResources(String pointedResourceName, + String pointedResourceType, + Map.Entry<String, Resource> currentResourceEntry, + Map<String, Map<String, Map<String, List<String>>>> typeToPointingResourcesMap) { + + initCurrentResourceTypeInMap(pointedResourceName, pointedResourceType, + currentResourceEntry.getValue().getType(), typeToPointingResourcesMap); + + typeToPointingResourcesMap.get(pointedResourceType).get(pointedResourceName).get + (currentResourceEntry.getValue().getType()).add(currentResourceEntry.getKey()); + } + + private void initCurrentResourceTypeInMap(String resourceName, String resourceType, + String pointingResourceType, + Map<String, Map<String, Map<String, List<String>>>> typeToPointingResourcesMap) { + + typeToPointingResourcesMap.putIfAbsent(resourceType, new HashMap<>()); + typeToPointingResourcesMap.get(resourceType).putIfAbsent(resourceName, new HashMap<>()); + typeToPointingResourcesMap.get(resourceType).get(resourceName).putIfAbsent + (pointingResourceType, new ArrayList<>()); + } + + private Set<String> handleGetAttrBetweenResources(Map<String, Object> properties){ + Set<String> referencedResourcesByGetAttr = new HashSet<>(); + for(Map.Entry<String, Object> proprtyEntry : properties.entrySet()){ + referencedResourcesByGetAttr.addAll(getGetAttrReferencesInCaseOfContrail(proprtyEntry + .getValue())); + } + + return referencedResourcesByGetAttr; + } + + + private Set<String> getGetAttrReferencesInCaseOfContrail(Object propertyValue){ + Object value; + Set<String> getAttrReferences = new HashSet<>(); + + 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) { + getAttrReferences.add((String) ((List) value).get(0)); + return getAttrReferences; + } else { + logger.warn("invalid format of 'get_attr' function - " + propertyValue.toString()); + } + } + } + }else { + Collection<Object> valCollection = ((Map) propertyValue).values(); + for (Object entryValue : valCollection) { + getAttrReferences.addAll(getGetAttrReferencesInCaseOfContrail(entryValue)); + } + } + } else if (propertyValue instanceof List) { + for (Object prop : (List) propertyValue) { + getAttrReferences.addAll(getGetAttrReferencesInCaseOfContrail(prop)); + } + } + + return getAttrReferences; + } + + + private Set<String> getResourcesIdsPointedByCurrentResource(String fileName, + ResourceReferenceFunctions function, + Map<String, Object> properties, + GlobalValidationContext globalContext) { + + Set<String> referencedResources = new HashSet<>(); + for (Map.Entry<String, Object> propertyEntry : properties.entrySet()) { + referencedResources + .addAll(HeatStructureUtil + .getReferencedValuesByFunctionName(fileName, + function.getFunction(), + propertyEntry.getValue(), + globalContext)); + } + + return referencedResources; + } + + private Set<String> checkForBaseFilePortsExistenceAndReturnSecurityGroupNamesFromOutputsIfNot( + String baseFileName, HeatOrchestrationTemplate heatOrchestrationTemplate, + GlobalValidationContext globalContext) { + Set<String> securityGroupsNamesFromOutputsMap = new HashSet<>(); + + if (heatOrchestrationTemplate != null) { + Map<String, Resource> resourceMap = heatOrchestrationTemplate.getResources(); + if (!isPortResourceExistInBaseFile(resourceMap)) { + getSecurityGroupsReferencedResourcesFromOutputs(securityGroupsNamesFromOutputsMap, + heatOrchestrationTemplate.getOutputs(), resourceMap); + } + } + return securityGroupsNamesFromOutputsMap; + } + + private boolean isPortResourceExistInBaseFile(Map<String, Resource> resourceMap) { + for (Map.Entry<String, Resource> resourceEntry : resourceMap.entrySet()) { + if (resourceEntry.getValue().getType() + .equals(HeatResourcesTypes.NEUTRON_PORT_RESOURCE_TYPE.getHeatResource())) { + return true; + } + } + + return false; + } + + private void getSecurityGroupsReferencedResourcesFromOutputs( + Set<String> securityGroupsNamesFromOutputsMap, Map<String, Output> outputMap, + Map<String, Resource> resourceMap) { + + if (MapUtils.isNotEmpty(outputMap)) { + for (Map.Entry<String, Output> outputEntry : outputMap.entrySet()) { + Object outputValue = outputEntry.getValue().getValue(); + if (Objects.nonNull(outputValue) && outputValue instanceof Map) { + String resourceName = (String) ((Map) outputValue) + .get(ResourceReferenceFunctions.GET_RESOURCE.getFunction()); + if (Objects.nonNull(resourceName)) { + Resource resource = resourceMap.get(resourceName); + if (Objects.nonNull(resource) && resource.getType().equals( + HeatResourcesTypes.NEUTRON_SECURITY_GROUP_RESOURCE_TYPE.getHeatResource())) { + securityGroupsNamesFromOutputsMap.add(outputEntry.getKey()); + } + } + } + } + } + } +} diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/HeatValidator.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/HeatValidator.java index c287394a54..ddc1bb49b9 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/HeatValidator.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/HeatValidator.java @@ -22,13 +22,10 @@ package org.openecomp.sdc.validation.impl.validators; import org.apache.commons.collections4.CollectionUtils; import org.apache.commons.collections4.MapUtils; -import org.openecomp.core.utilities.json.JsonUtil; -import org.openecomp.core.utilities.yaml.YamlUtil; +import org.openecomp.sdc.validation.Validator; import org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder; -import org.openecomp.core.validation.errors.Messages; -import org.openecomp.core.validation.interfaces.Validator; import org.openecomp.core.validation.types.GlobalValidationContext; -import org.openecomp.sdc.common.utils.AsdcCommon; +import org.openecomp.sdc.common.errors.Messages; import org.openecomp.sdc.datatypes.error.ErrorLevel; import org.openecomp.sdc.heat.datatypes.DefinedHeatParameterTypes; import org.openecomp.sdc.heat.datatypes.manifest.FileData; @@ -43,12 +40,14 @@ import org.openecomp.sdc.heat.datatypes.model.Resource; import org.openecomp.sdc.heat.datatypes.model.ResourceReferenceFunctions; import org.openecomp.sdc.heat.services.HeatStructureUtil; import org.openecomp.sdc.heat.services.manifest.ManifestUtil; +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.types.LoggerErrorDescription; +import org.openecomp.sdc.logging.types.LoggerTragetServiceName; import org.openecomp.sdc.validation.impl.util.HeatValidationService; -import org.openecomp.sdc.validation.impl.util.ResourceValidationHeatValidator; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +import org.openecomp.sdc.validation.util.ValidationUtil; -import java.io.InputStream; import java.util.Collection; import java.util.HashSet; import java.util.Map; @@ -56,14 +55,17 @@ import java.util.Objects; import java.util.Set; public class HeatValidator implements Validator { + public static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); + protected static Logger logger = (Logger) LoggerFactory.getLogger(HeatValidator.class); - protected static Logger logger = LoggerFactory.getLogger(HeatValidator.class); - - /* validation 9*/ private static void validateAllRequiredArtifactsExist(String fileName, - HeatOrchestrationTemplate heatOrchestrationTemplate, - Set<String> artifacts, - GlobalValidationContext globalContext) { + HeatOrchestrationTemplate + heatOrchestrationTemplate, + Set<String> artifacts, + GlobalValidationContext globalContext) { + + mdcDataDebugMessage.debugEntryMessage("file", fileName); + Collection<Resource> resourcesValues = heatOrchestrationTemplate.getResources() == null ? null : heatOrchestrationTemplate.getResources().values(); @@ -85,13 +87,17 @@ public class HeatValidator implements Validator { } } - + mdcDataDebugMessage.debugExitMessage("file", fileName); } /* validation 14 */ + private static void validateAllResourceReferencesExist(String fileName, - HeatOrchestrationTemplate heatOrchestrationTemplate, - GlobalValidationContext globalContext) { + HeatOrchestrationTemplate + heatOrchestrationTemplate, + GlobalValidationContext globalContext) { + + mdcDataDebugMessage.debugEntryMessage("file", fileName); Set<String> resourcesNames = heatOrchestrationTemplate.getResources() == null ? null : heatOrchestrationTemplate.getResources().keySet(); @@ -107,12 +113,19 @@ public class HeatValidator implements Validator { .checkResourceExistenceFromResourcesMap(fileName, resourcesNames, outputsValues, globalContext); + mdcDataDebugMessage.debugExitMessage("file", fileName); + } /* validation 16 */ + private static void validateGetParamPointToParameter(String fileName, - HeatOrchestrationTemplate heatOrchestrationTemplate, - GlobalValidationContext globalContext) { + HeatOrchestrationTemplate + heatOrchestrationTemplate, + GlobalValidationContext globalContext) { + + mdcDataDebugMessage.debugEntryMessage("file", fileName); + Set<String> parametersNames = heatOrchestrationTemplate.getParameters() == null ? null : heatOrchestrationTemplate.getParameters().keySet(); Map<String, Resource> resourcesMap = heatOrchestrationTemplate.getResources(); @@ -125,8 +138,6 @@ public class HeatValidator implements Validator { Collection<Object> propertiesValues = properties.values(); if (CollectionUtils.isNotEmpty(propertiesValues)) { for (Object propertyObject : propertiesValues) { - //Set<String> referencedParameterNames = HeatValidationService - // .getParameterNameFromGetParamMap(propertyObject); Set<String> referencedParameterNames = HeatStructureUtil .getReferencedValuesByFunctionName(fileName, "get_param", propertyObject, globalContext); @@ -138,21 +149,31 @@ public class HeatValidator implements Validator { } } } + + mdcDataDebugMessage.debugExitMessage("file", fileName); } + private static void validateReferenceParams(String fileName, String resourceName, Set<String> parametersNamesFromFile, Set<String> referencedParametersNames, GlobalValidationContext globalContext) { + + mdcDataDebugMessage.debugEntryMessage("file", fileName); + for (String parameterName : referencedParametersNames) { if (!isHeatPseudoParameter(parameterName) && !parametersNamesFromFile.contains(parameterName)) { globalContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder - .getErrorWithParameters(Messages.REFERENCED_PARAMETER_NOT_FOUND.getErrorMessage(), - parameterName, resourceName)); + .getErrorWithParameters(Messages.REFERENCED_PARAMETER_NOT_FOUND.getErrorMessage(), + parameterName, resourceName), + LoggerTragetServiceName.VALIDATE_PARAMETER_REFERENCE_EXITENCE, + LoggerErrorDescription.PARAMETER_NOT_FOUND); } } + + mdcDataDebugMessage.debugExitMessage("file", fileName); } private static boolean isHeatPseudoParameter(String parameterName) { @@ -160,9 +181,13 @@ public class HeatValidator implements Validator { } /* validation 18*/ + private static void validateGetAttr(String fileName, HeatOrchestrationTemplate heatOrchestrationTemplate, GlobalValidationContext globalContext) { + + mdcDataDebugMessage.debugEntryMessage("file", fileName); + Map<String, Output> outputMap; outputMap = heatOrchestrationTemplate.getOutputs(); @@ -170,6 +195,8 @@ public class HeatValidator implements Validator { HeatValidationService.loopOverOutputMapAndValidateGetAttrFromNested(fileName, outputMap, heatOrchestrationTemplate, globalContext); } + + mdcDataDebugMessage.debugExitMessage("file", fileName); } /* validation 17 + */ @@ -177,12 +204,16 @@ public class HeatValidator implements Validator { HeatOrchestrationTemplate heatOrchestrationTemplate, GlobalValidationContext globalContext) { + + mdcDataDebugMessage.debugEntryMessage("file", fileName); + Environment envContent; if (!envFileName.contains(".env")) { globalContext.addMessage(envFileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder - .getErrorWithParameters(Messages.WRONG_ENV_FILE_EXTENSION.getErrorMessage(), - envFileName)); + .getErrorWithParameters(Messages + .WRONG_ENV_FILE_EXTENSION.getErrorMessage(), envFileName), + LoggerTragetServiceName.VALIDATE_ENV_FILE, LoggerErrorDescription.WRONG_FILE_EXTENSION); } envContent = HeatValidationService.validateEnvContent(fileName, envFileName, globalContext); @@ -193,12 +224,19 @@ public class HeatValidator implements Validator { heatOrchestrationTemplate); } + mdcDataDebugMessage.debugExitMessage("file", fileName); + } private static void validateEnvContentIsSubSetOfHeatParameters(String envFile, - Environment envContent, - GlobalValidationContext globalContext, - HeatOrchestrationTemplate heatOrchestrationTemplate) { + Environment envContent, + GlobalValidationContext + globalContext, + HeatOrchestrationTemplate + heatOrchestrationTemplate) { + + mdcDataDebugMessage.debugEntryMessage("file", envFile); + Set<String> parametersNames = heatOrchestrationTemplate.getParameters() == null ? null : heatOrchestrationTemplate.getParameters().keySet(); @@ -208,24 +246,35 @@ public class HeatValidator implements Validator { String envParameter = envEntry.getKey(); if (!parametersNames.contains(envParameter)) { globalContext.addMessage(envFile, ErrorLevel.ERROR, ErrorMessagesFormatBuilder - .getErrorWithParameters( - Messages.ENV_INCLUDES_PARAMETER_NOT_IN_HEAT.getErrorMessage(), envFile, - envParameter)); + .getErrorWithParameters( + Messages.ENV_INCLUDES_PARAMETER_NOT_IN_HEAT.getErrorMessage(), envFile, + envParameter), LoggerTragetServiceName.VALIDATE_ENV_FILE, + LoggerErrorDescription.ENV_PARAMETER_NOT_IN_HEAT); } } } else { for (Map.Entry<String, Object> envEntry : envContent.getParameters().entrySet()) { globalContext.addMessage(envFile, ErrorLevel.ERROR, ErrorMessagesFormatBuilder - .getErrorWithParameters(Messages.ENV_INCLUDES_PARAMETER_NOT_IN_HEAT.getErrorMessage(), - envFile, envEntry.getKey())); + .getErrorWithParameters(Messages + .ENV_INCLUDES_PARAMETER_NOT_IN_HEAT.getErrorMessage(), + envFile, envEntry.getKey()), LoggerTragetServiceName.VALIDATE_ENV_FILE, + LoggerErrorDescription.ENV_PARAMETER_NOT_IN_HEAT); } } } + + mdcDataDebugMessage.debugExitMessage("file", envFile); } + private static void validateParameterDefaultTypeAlignWithType(String fileName, - HeatOrchestrationTemplate heatOrchestrationTemplate, - GlobalValidationContext globalContext) { + HeatOrchestrationTemplate + heatOrchestrationTemplate, + GlobalValidationContext + globalContext) { + + mdcDataDebugMessage.debugEntryMessage("file", fileName); + Map<String, Parameter> parametersMap = heatOrchestrationTemplate.getParameters() == null ? null : heatOrchestrationTemplate.getParameters(); @@ -239,19 +288,28 @@ public class HeatValidator implements Validator { DefinedHeatParameterTypes.isValueIsFromGivenType(parameterDefault, parameterType); if (!isValueMatchDefault) { globalContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder - .getErrorWithParameters( - Messages.PARAMETER_DEFAULT_VALUE_NOT_ALIGN_WITH_TYPE.getErrorMessage(), - parameterEntry.getKey(), parameterType)); + .getErrorWithParameters( + Messages.PARAMETER_DEFAULT_VALUE_NOT_ALIGN_WITH_TYPE.getErrorMessage(), + parameterEntry.getKey(), parameterType), + LoggerTragetServiceName.VALIDATE_PARAMTER_DEFAULT_MATCH_TYPE, + LoggerErrorDescription.PARAMETER_DEFAULT_VALUE_NOT_ALIGNED_WITH_TYPE); } } } } + + mdcDataDebugMessage.debugExitMessage("file", fileName); } + private static void validateEnvParametersMatchDefinedHeatParameterTypes(String envFile, - Environment envContent, - GlobalValidationContext globalContext, - HeatOrchestrationTemplate heatOrchestrationTemplate) { + Environment envContent, + GlobalValidationContext globalContext, + HeatOrchestrationTemplate heatOrchestrationTemplate) { + + + mdcDataDebugMessage.debugEntryMessage("file", envFile); + Map<String, Parameter> heatParameters = heatOrchestrationTemplate.getParameters(); if (MapUtils.isNotEmpty(heatParameters) && MapUtils.isNotEmpty(envContent.getParameters())) { @@ -262,25 +320,29 @@ public class HeatValidator implements Validator { if (parameterFromHeatFile != null) { String parameterType = parameterFromHeatFile.getType(); if (!DefinedHeatParameterTypes.isEmptyValueInEnv(parameterEnvValue) - && !DefinedHeatParameterTypes.isValueIsFromGivenType(parameterEnvValue, - parameterType)) { + && !DefinedHeatParameterTypes + .isValueIsFromGivenType(parameterEnvValue, parameterType)) { globalContext.addMessage(envFile, ErrorLevel.ERROR, ErrorMessagesFormatBuilder - .getErrorWithParameters( - Messages.PARAMETER_ENV_VALUE_NOT_ALIGN_WITH_TYPE.getErrorMessage(), - parameterName)); + .getErrorWithParameters( + Messages.PARAMETER_ENV_VALUE_NOT_ALIGN_WITH_TYPE.getErrorMessage(), + parameterName), LoggerTragetServiceName.VALIDATE_ENV_PARAMETER_MATCH_TYPE, + LoggerErrorDescription.PARAMETER_DEFAULT_VALUE_NOT_ALIGNED_WITH_TYPE); } } } } + + mdcDataDebugMessage.debugExitMessage("file", envFile); } @Override - public void validate(GlobalValidationContext globalContext) { + public void validate(GlobalValidationContext globalContext) { + mdcDataDebugMessage.debugEntryMessage(null, null); ManifestContent manifestContent; try { - manifestContent = checkValidationPreCondition(globalContext); - } catch (Exception e0) { + manifestContent = ValidationUtil.checkValidationPreCondition(globalContext); + } catch (Exception exception) { return; } String baseFileName; @@ -299,8 +361,8 @@ public class HeatValidator implements Validator { globalContext.getFiles().stream() .filter(fileName -> FileData.isHeatFile(fileTypeMap.get(fileName))).forEach( - fileName -> validate(fileName, - fileEnvMap.get(fileName) == null ? null : fileEnvMap.get(fileName).getFile(), + fileName -> validate(fileName, fileEnvMap.get(fileName) == null ? null : fileEnvMap.get( + fileName).getFile(), baseFileName == null ? null : baseFileName, artifacts, securityGroupsNamesFromBaseFileOutputs, globalContext)); @@ -310,35 +372,34 @@ public class HeatValidator implements Validator { globalContext.getFiles().stream() .filter(fileName -> manifestArtifacts.contains(fileName) && !artifacts.contains(fileName)) .forEach(fileName -> globalContext.addMessage(fileName, ErrorLevel.WARNING, - Messages.ARTIFACT_FILE_NOT_REFERENCED.getErrorMessage())); + Messages.ARTIFACT_FILE_NOT_REFERENCED.getErrorMessage(), + LoggerTragetServiceName.CHECK_FOR_ORPHAN_ARTIFACTS, + LoggerErrorDescription.ARTIFACT_NOT_REFERENCED)); - ResourceValidationHeatValidator - .handleNotEmptyResourceNamesList(baseFileName, securityGroupsNamesFromBaseFileOutputs, - "SecurityGroup", globalContext); + mdcDataDebugMessage.debugExitMessage(null, null); } private void validate(String fileName, String envFileName, String baseFileName, Set<String> artifacts, Set<String> securityGroupsNamesFromBaseFileOutputs, GlobalValidationContext globalContext) { - HeatOrchestrationTemplate heatOrchestrationTemplate = - checkHeatOrchestrationPreCondition(fileName, globalContext); + HeatOrchestrationTemplate + heatOrchestrationTemplate = ValidationUtil.checkHeatOrchestrationPreCondition(fileName, globalContext); if (heatOrchestrationTemplate != null) { if (!(fileName.contains(".yaml") || fileName.contains(".yml"))) { globalContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder - .getErrorWithParameters(Messages.WRONG_HEAT_FILE_EXTENSION.getErrorMessage(), - fileName)); + .getErrorWithParameters(Messages + .WRONG_HEAT_FILE_EXTENSION.getErrorMessage(), fileName), + LoggerTragetServiceName.CHECK_FOR_VALID_FILE_EXTENTION, + LoggerErrorDescription.WRONG_FILE_EXTENSION); } validateHeatBaseStructure(fileName, heatOrchestrationTemplate, globalContext); - - ResourceValidationHeatValidator - .validateResourceType(fileName, baseFileName, securityGroupsNamesFromBaseFileOutputs, - heatOrchestrationTemplate, globalContext); validateParameterDefaultTypeAlignWithType(fileName, heatOrchestrationTemplate, globalContext); validateAllResourceReferencesExist(fileName, heatOrchestrationTemplate, globalContext); + validateResourceDependsOn(fileName, heatOrchestrationTemplate, globalContext); validateGetParamPointToParameter(fileName, heatOrchestrationTemplate, globalContext); validateGetAttr(fileName, heatOrchestrationTemplate, globalContext); validateAllRequiredArtifactsExist(fileName, heatOrchestrationTemplate, artifacts, @@ -350,60 +411,80 @@ public class HeatValidator implements Validator { } } - private void validateHeatBaseStructure(String fileName, + private void validateResourceDependsOn(String fileName, HeatOrchestrationTemplate heatOrchestrationTemplate, GlobalValidationContext globalContext) { - if (heatOrchestrationTemplate.getHeat_template_version() == null) { - globalContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder - .getErrorWithParameters(Messages.INVALID_HEAT_FORMAT_REASON.getErrorMessage(), - "missing template version")); - } - if (heatOrchestrationTemplate.getResources() == null - || heatOrchestrationTemplate.getResources().size() == 0) { - globalContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder - .getErrorWithParameters(Messages.INVALID_HEAT_FORMAT_REASON.getErrorMessage(), - "heat file must have minimum one resource")); + Map<String, Resource> resourcesMap = heatOrchestrationTemplate.getResources(); + if(MapUtils.isEmpty(resourcesMap)){ + return; } + + Set<String> resourcesNames = resourcesMap.keySet(); + + resourcesMap.entrySet().stream() + .forEach(entry -> checkResourceDependsOn(fileName, entry.getValue(), resourcesNames, globalContext)); } - protected ManifestContent checkValidationPreCondition(GlobalValidationContext globalContext) { - InputStream manifest = globalContext.getFileContent(AsdcCommon.MANIFEST_NAME); - if (manifest == null) { - throw new RuntimeException("Can't load manifest file for Heat Validator"); - } - ManifestContent manifestContent; - try { - manifestContent = JsonUtil.json2Object(manifest, ManifestContent.class); - } catch (Exception e0) { - throw new RuntimeException("Can't load manifest file for Heat Validator"); + @SuppressWarnings("unchecked") + private static void checkResourceDependsOn(String fileName, Resource resource, + Set<String> resourcesNames, + GlobalValidationContext globalContext) { + + + mdcDataDebugMessage.debugEntryMessage("file", fileName); + + Object dependencies = resource.getDepends_on(); + if (dependencies instanceof Collection) { + ((Collection<String>) dependencies) + .stream() + .filter(resource_id -> !resourcesNames.contains(resource_id)) + .forEach(resource_id -> globalContext.addMessage(fileName, ErrorLevel.ERROR, + ErrorMessagesFormatBuilder + .getErrorWithParameters(Messages.MISSING_RESOURCE_IN_DEPENDS_ON.getErrorMessage(), + (String) resource_id), LoggerTragetServiceName.CHECK_RESOURCE_DEPENDS_ON, + LoggerErrorDescription.MISSING_RESOURCE_DEPENDS_ON)); + } else if (dependencies instanceof String) { + if (!resourcesNames.contains(dependencies)) { + globalContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder + .getErrorWithParameters(Messages.MISSING_RESOURCE_IN_DEPENDS_ON.getErrorMessage(), + (String) dependencies), LoggerTragetServiceName.CHECK_RESOURCE_DEPENDS_ON, + LoggerErrorDescription.MISSING_RESOURCE_DEPENDS_ON); + } } - return manifestContent; + mdcDataDebugMessage.debugExitMessage("file", fileName); } - private HeatOrchestrationTemplate checkHeatOrchestrationPreCondition(String fileName, - GlobalValidationContext globalContext) { - HeatOrchestrationTemplate heatOrchestrationTemplate; - try { - heatOrchestrationTemplate = new YamlUtil() - .yamlToObject(globalContext.getFileContent(fileName), HeatOrchestrationTemplate.class); - } catch (Exception e0) { + private void validateHeatBaseStructure(String fileName, + HeatOrchestrationTemplate heatOrchestrationTemplate, + GlobalValidationContext globalContext) { + + + mdcDataDebugMessage.debugEntryMessage("file", fileName); + + if (heatOrchestrationTemplate.getHeat_template_version() == null) { globalContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder - .getErrorWithParameters(Messages.INVALID_HEAT_FORMAT_REASON.getErrorMessage(), - getParserExceptionReason(e0))); - return null; + .getErrorWithParameters(Messages.INVALID_HEAT_FORMAT_REASON.getErrorMessage(), + "missing template version"), LoggerTragetServiceName.VALIDATE_HEAT_FORMAT, + LoggerErrorDescription.INVALID_HEAT_FORMAT); + } + if (heatOrchestrationTemplate.getResources() == null + || heatOrchestrationTemplate.getResources().size() == 0) { + globalContext.addMessage(fileName, ErrorLevel.WARNING, ErrorMessagesFormatBuilder + .getErrorWithParameters(Messages.INVALID_HEAT_FORMAT_REASON.getErrorMessage(), + "The heat file does not contain any resources"), + LoggerTragetServiceName.VALIDATE_HEAT_FORMAT, LoggerErrorDescription.INVALID_HEAT_FORMAT); } - return heatOrchestrationTemplate; + mdcDataDebugMessage.debugExitMessage("file", fileName); } - private Set<String> checkForBaseFilePortsExistenceAndReturnSecurityGroupNamesFromOutputsIfNot( String baseFileName, GlobalValidationContext globalContext) { Set<String> securityGroupsNamesFromOutputsMap = new HashSet<>(); HeatOrchestrationTemplate heatOrchestrationTemplate = - checkHeatOrchestrationPreCondition(baseFileName, globalContext); + ValidationUtil.checkHeatOrchestrationPreCondition(baseFileName, globalContext); if (heatOrchestrationTemplate != null) { Map<String, Resource> resourceMap = heatOrchestrationTemplate.getResources(); @@ -412,7 +493,6 @@ public class HeatValidator implements Validator { heatOrchestrationTemplate.getOutputs(), resourceMap); } } - return securityGroupsNamesFromOutputsMap; } @@ -450,20 +530,4 @@ public class HeatValidator implements Validator { return false; } - - - private String getParserExceptionReason(Exception e0) { - String reason; - - if (e0.getCause() != null && e0.getCause().getCause() != null) { - reason = e0.getCause().getCause().getMessage(); - } else if (e0.getCause() != null) { - reason = e0.getCause().getMessage(); - } else { - reason = Messages.GENERAL_HEAT_PARSER_ERROR.getErrorMessage(); - } - return reason; - } - - } diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/ManifestValidator.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/ManifestValidator.java index 4ce40f0007..43cafb494c 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/ManifestValidator.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/ManifestValidator.java @@ -21,38 +21,54 @@ package org.openecomp.sdc.validation.impl.validators; import org.openecomp.core.utilities.json.JsonUtil; +import org.openecomp.sdc.validation.Validator; import org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder; -import org.openecomp.core.validation.errors.Messages; -import org.openecomp.core.validation.interfaces.Validator; import org.openecomp.core.validation.types.GlobalValidationContext; -import org.openecomp.sdc.common.utils.AsdcCommon; +import org.openecomp.sdc.common.errors.Messages; +import org.openecomp.sdc.common.utils.SdcCommon; import org.openecomp.sdc.datatypes.error.ErrorLevel; import org.openecomp.sdc.heat.datatypes.manifest.FileData; import org.openecomp.sdc.heat.datatypes.manifest.ManifestContent; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; +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 java.io.InputStream; import java.util.ArrayList; import java.util.List; +import java.util.Optional; -public class ManifestValidator implements Validator { - - private static Logger logger = LoggerFactory.getLogger(YamlValidator.class); +public class ManifestValidator implements Validator { + public static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); + private static Logger logger = (Logger) LoggerFactory.getLogger(YamlValidator.class); @Override public void validate(GlobalValidationContext globalContext) { + mdcDataDebugMessage.debugEntryMessage(null, null); - - InputStream content = globalContext.getFileContent(AsdcCommon.MANIFEST_NAME); + Optional<InputStream> content = globalContext.getFileContent(SdcCommon.MANIFEST_NAME); ManifestContent manifestContent; try { - manifestContent = JsonUtil.json2Object(content, ManifestContent.class); - } catch (RuntimeException re) { - globalContext.addMessage(AsdcCommon.MANIFEST_NAME, ErrorLevel.ERROR, - Messages.INVALID_MANIFEST_FILE.getErrorMessage()); + if (content.isPresent()) { + manifestContent = JsonUtil.json2Object(content.get(), ManifestContent.class); + } else { + MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_API, + LoggerTragetServiceName.VALIDATE_MANIFEST_CONTENT, ErrorLevel.ERROR.name(), + LoggerErrorCode.DATA_ERROR.getErrorCode(), LoggerErrorDescription.EMPTY_FILE); + throw new Exception("The manifest file '" + SdcCommon.MANIFEST_NAME + "' has no content"); + } + } catch (Exception re) { + globalContext.addMessage(SdcCommon.MANIFEST_NAME, ErrorLevel.ERROR, + Messages.INVALID_MANIFEST_FILE.getErrorMessage(), + LoggerTragetServiceName.VALIDATE_MANIFEST_CONTENT, + LoggerErrorDescription.INVALID_MANIFEST); return; } @@ -60,22 +76,32 @@ public class ManifestValidator implements Validator { manifestFiles.stream().filter(name -> !globalContext.getFileContextMap().containsKey(name) ).forEach(name -> globalContext - .addMessage(name, ErrorLevel.ERROR, Messages.MISSING_FILE_IN_ZIP.getErrorMessage())); + .addMessage(name, ErrorLevel.ERROR, Messages.MISSING_FILE_IN_ZIP.getErrorMessage(), + LoggerTragetServiceName.VALIDATE_FILE_IN_ZIP, LoggerErrorDescription.MISSING_FILE)); globalContext.getFileContextMap().keySet().stream().filter(name -> - !manifestFiles.contains(name) && !AsdcCommon.MANIFEST_NAME.equals(name) + !manifestFiles.contains(name) && !SdcCommon.MANIFEST_NAME.equals(name) ).forEach(name -> globalContext.addMessage(name, ErrorLevel.WARNING, - Messages.MISSING_FILE_IN_MANIFEST.getErrorMessage()) + Messages.MISSING_FILE_IN_MANIFEST.getErrorMessage(), + LoggerTragetServiceName.VALIDATE_FILE_IN_MANIFEST, LoggerErrorDescription.MISSING_FILE) ); + mdcDataDebugMessage.debugExitMessage(null, null); } + private List<String> getManifestFileList(ManifestContent manifestContent, GlobalValidationContext context) { + + + mdcDataDebugMessage.debugEntryMessage(null, null); + ManifestScanner manifestScanner = new ManifestScanner(); manifestScanner.init(context); manifestScanner.scan(null, manifestContent.getData(), context); + + mdcDataDebugMessage.debugExitMessage(null, null); return manifestScanner.getFileList(); } @@ -98,7 +124,9 @@ public class ManifestValidator implements Validator { && childFileData.getType().equals(FileData.Type.HEAT_ENV)) { globalContext.addMessage(childFileData.getFile(), ErrorLevel.ERROR, ErrorMessagesFormatBuilder - .getErrorWithParameters(Messages.ENV_NOT_ASSOCIATED_TO_HEAT.getErrorMessage())); + .getErrorWithParameters(Messages.ENV_NOT_ASSOCIATED_TO_HEAT.getErrorMessage()), + LoggerTragetServiceName.SCAN_MANIFEST_STRUCTURE, + "env file is not associated to HEAT file"); } } } @@ -109,9 +137,7 @@ public class ManifestValidator implements Validator { if (data == null) { return; } - data.stream().forEach(chileFileData -> { - scan(chileFileData, chileFileData.getData(), globalContext); - }); + data.forEach(chileFileData -> scan(chileFileData, chileFileData.getData(), globalContext)); } @@ -122,28 +148,32 @@ public class ManifestValidator implements Validator { private void validateFileTypeVsFileName(FileData fileData) { String fileName = fileData.getFile(); if (fileName == null) { - this.globalValidationContext.addMessage(AsdcCommon.MANIFEST_NAME, ErrorLevel.ERROR, - Messages.MISSING_FILE_NAME_IN_MANIFEST.getErrorMessage()); + this.globalValidationContext.addMessage(SdcCommon.MANIFEST_NAME, ErrorLevel.ERROR, + Messages.MISSING_FILE_NAME_IN_MANIFEST.getErrorMessage(), + LoggerTragetServiceName.VALIDATE_FILE_TYPE_AND_NAME, "Missing file name in manifest"); } FileData.Type type = fileData.getType(); if (type == null) { this.globalValidationContext - .addMessage(fileName, ErrorLevel.ERROR, Messages.INVALID_FILE_TYPE.getErrorMessage()); + .addMessage(fileName, ErrorLevel.ERROR, Messages.INVALID_FILE_TYPE.getErrorMessage(), + LoggerTragetServiceName.VALIDATE_FILE_TYPE_AND_NAME, "Invalid file type"); } else if (type.equals(FileData.Type.HEAT_NET) || type.equals(FileData.Type.HEAT_VOL) || type.equals(FileData.Type.HEAT)) { if (fileName != null && !fileName.endsWith(".yml") && !fileName.endsWith(".yaml")) { this.globalValidationContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder .getErrorWithParameters(Messages.WRONG_HEAT_FILE_EXTENSION.getErrorMessage(), - fileName)); + fileName), LoggerTragetServiceName.VALIDATE_FILE_TYPE_AND_NAME, + "Wrong HEAT file extention"); } } else if (type.equals(FileData.Type.HEAT_ENV)) { if (fileName != null && !fileName.endsWith(".env")) { this.globalValidationContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder .getErrorWithParameters(Messages.WRONG_ENV_FILE_EXTENSION.getErrorMessage(), - fileName)); + fileName), LoggerTragetServiceName.VALIDATE_FILE_TYPE_AND_NAME, + "Wrong env file extention"); } } } diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/NamingConventionGuideLineValidator.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/NamingConventionGuideLineValidator.java new file mode 100644 index 0000000000..724b7e4735 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/NamingConventionGuideLineValidator.java @@ -0,0 +1,29 @@ +package org.openecomp.sdc.validation.impl.validators; + +import org.openecomp.sdc.validation.ValidationContext; +import org.openecomp.core.validation.types.GlobalValidationContext; +import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate; +import org.openecomp.sdc.validation.base.ResourceBaseValidator; +import org.openecomp.sdc.validation.type.ConfigConstants; +import org.openecomp.sdc.validation.type.NamingConventionValidationContext; + +import java.util.Map; + +/** + * Created by TALIO on 2/15/2017. + */ +public class NamingConventionGuideLineValidator extends ResourceBaseValidator { + + @Override + public void init(Map<String, Object> properties){ + super.init((Map<String, Object>) properties.get(ConfigConstants.Resource_Base_Validator)); + } + + @Override + public ValidationContext createValidationContext(String fileName, String envFileName, + HeatOrchestrationTemplate + heatOrchestrationTemplate, + GlobalValidationContext globalContext){ + return new NamingConventionValidationContext(heatOrchestrationTemplate, envFileName); + } +} diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/SharedResourceGuideLineValidator.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/SharedResourceGuideLineValidator.java new file mode 100644 index 0000000000..f3af7d7e48 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/SharedResourceGuideLineValidator.java @@ -0,0 +1,199 @@ +package org.openecomp.sdc.validation.impl.validators; + +import org.apache.commons.collections4.CollectionUtils; +import org.openecomp.sdc.validation.Validator; +import org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder; +import org.openecomp.core.validation.types.GlobalValidationContext; +import org.openecomp.sdc.common.errors.Messages; +import org.openecomp.sdc.datatypes.error.ErrorLevel; +import org.openecomp.sdc.heat.datatypes.manifest.FileData; +import org.openecomp.sdc.heat.datatypes.manifest.ManifestContent; +import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate; +import org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes; +import org.openecomp.sdc.heat.datatypes.model.ResourceReferenceFunctions; +import org.openecomp.sdc.heat.services.HeatStructureUtil; +import org.openecomp.sdc.heat.services.manifest.ManifestUtil; +import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; +import org.openecomp.sdc.logging.types.LoggerErrorDescription; +import org.openecomp.sdc.logging.types.LoggerTragetServiceName; +import org.openecomp.sdc.validation.util.ValidationUtil; + +import java.util.HashSet; +import java.util.Map; +import java.util.Set; + +/** + * Created by TALIO on 2/15/2017. + */ +public class SharedResourceGuideLineValidator implements Validator { + public static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); + + @Override + public void validate(GlobalValidationContext globalContext) { + ManifestContent manifestContent; + try { + manifestContent = ValidationUtil.checkValidationPreCondition(globalContext); + } catch (Exception exception) { + return; + } + + Set<String> baseFiles = ValidationUtil.validateManifest(manifestContent, globalContext); + + Map<String, FileData.Type> fileTypeMap = ManifestUtil.getFileTypeMap(manifestContent); + Map<String, FileData> fileEnvMap = ManifestUtil.getFileAndItsEnv(manifestContent); + globalContext.getFiles().stream() + .filter(fileName -> FileData + .isHeatFile(fileTypeMap.get(fileName))) + .forEach(fileName -> validate(fileName, + fileEnvMap.get(fileName) != null ? fileEnvMap.get(fileName).getFile() : null, + fileTypeMap, baseFiles, globalContext)); + + + } + + private void validate(String fileName, String envFileName, Map<String, FileData.Type> fileTypeMap, + Set<String> baseFiles, GlobalValidationContext globalContext) { + HeatOrchestrationTemplate + heatOrchestrationTemplate = ValidationUtil.checkHeatOrchestrationPreCondition(fileName, globalContext); + if (heatOrchestrationTemplate == null) { + return; + } + + validateBaseFile(fileName, baseFiles, heatOrchestrationTemplate, globalContext); + validateHeatVolumeFile(fileName, fileTypeMap, heatOrchestrationTemplate, globalContext); + } + + + private void validateBaseFile(String fileName, Set<String> baseFiles, + HeatOrchestrationTemplate heatOrchestrationTemplate, + GlobalValidationContext globalContext) { + + + mdcDataDebugMessage.debugEntryMessage("file", fileName); + //if not base return + if (baseFiles == null || !baseFiles.contains(fileName)) { + mdcDataDebugMessage.debugExitMessage("file", fileName); + return; + } + + //if no resources exist return + if (heatOrchestrationTemplate.getResources() == null + || heatOrchestrationTemplate.getResources().size() == 0) { + mdcDataDebugMessage.debugExitMessage("file", fileName); + return; + } + + Set<String> expectedExposedResources = new HashSet<>(); + Set<String> actualExposedResources = new HashSet<>(); + heatOrchestrationTemplate.getResources() + .entrySet() + .stream() + .filter(entry -> ValidationUtil.isExpectedToBeExposed(entry.getValue().getType())) + .forEach(entry -> expectedExposedResources.add(entry.getKey())); + + if (heatOrchestrationTemplate.getOutputs() != null) { + + heatOrchestrationTemplate.getOutputs().entrySet() + .stream() + .filter(entry -> isPropertyValueGetResource(fileName, entry.getValue().getValue(), + globalContext)) + .forEach(entry -> actualExposedResources.add( + getResourceIdFromPropertyValue(fileName, entry.getValue().getValue(), + globalContext))); + } + + ValidationUtil.removeExposedResourcesCalledByGetResource(fileName, actualExposedResources, + heatOrchestrationTemplate, globalContext); + + actualExposedResources.forEach(expectedExposedResources::remove); + + if (expectedExposedResources.size() > 0) { + expectedExposedResources + .stream() + .forEach(name -> globalContext.addMessage( + fileName, + ErrorLevel.WARNING, ErrorMessagesFormatBuilder + .getErrorWithParameters(Messages.RESOURCE_NOT_DEFINED_IN_OUTPUT.getErrorMessage(), + name), + LoggerTragetServiceName.VALIDATE_BASE_FILE, + LoggerErrorDescription.RESOURCE_NOT_DEFINED_AS_OUTPUT)); + } + + mdcDataDebugMessage.debugExitMessage("file", fileName); + } + + private void validateHeatVolumeFile(String fileName, Map<String, FileData.Type> fileTypeMap, + HeatOrchestrationTemplate heatOrchestrationTemplate, + GlobalValidationContext globalContext) { + + + mdcDataDebugMessage.debugEntryMessage("file", fileName); + + //if not heat volume return + if (!fileTypeMap.get(fileName).equals(FileData.Type.HEAT_VOL)) { + mdcDataDebugMessage.debugExitMessage("file", fileName); + return; + } + + //if no resources exist return + if (heatOrchestrationTemplate.getResources() == null + || heatOrchestrationTemplate.getResources().size() == 0) { + mdcDataDebugMessage.debugExitMessage("file", fileName); + return; + } + + Set<String> expectedExposedResources = new HashSet<>(); + Set<String> actualExposedResources = new HashSet<>(); + heatOrchestrationTemplate.getResources() + .entrySet() + .stream() + .filter(entry -> entry.getValue().getType() + .equals(HeatResourcesTypes.CINDER_VOLUME_RESOURCE_TYPE.getHeatResource())) + .forEach(entry -> expectedExposedResources.add(entry.getKey())); + + if (heatOrchestrationTemplate.getOutputs() != null) { + + heatOrchestrationTemplate.getOutputs().entrySet() + .stream() + .filter(entry -> isPropertyValueGetResource(fileName, entry.getValue().getValue(), + globalContext)) + .forEach(entry -> actualExposedResources.add( + getResourceIdFromPropertyValue(fileName, entry.getValue().getValue(), + globalContext))); + } + + actualExposedResources.forEach(expectedExposedResources::remove); + + if (expectedExposedResources.size() > 0) { + expectedExposedResources + .stream() + .forEach(name -> globalContext.addMessage( + fileName, + ErrorLevel.WARNING, ErrorMessagesFormatBuilder + .getErrorWithParameters(Messages.VOLUME_HEAT_NOT_EXPOSED.getErrorMessage(), name), + LoggerTragetServiceName.VALIDATE_VOLUME_FILE, + LoggerErrorDescription.VOLUME_FILE_NOT_EXPOSED)); + } + + mdcDataDebugMessage.debugExitMessage("file", fileName); + } + + + private boolean isPropertyValueGetResource(String filename, Object value, + GlobalValidationContext globalContext) { + Set<String> referenceValues = HeatStructureUtil.getReferencedValuesByFunctionName(filename, + ResourceReferenceFunctions.GET_RESOURCE.getFunction(), value, globalContext); + return referenceValues != null && (referenceValues.size() > 0); + } + + private String getResourceIdFromPropertyValue(String filename, Object value, + GlobalValidationContext globalContext) { + Set<String> referenceValues = HeatStructureUtil.getReferencedValuesByFunctionName(filename, + ResourceReferenceFunctions.GET_RESOURCE.getFunction(), value, globalContext); + if (referenceValues != null && CollectionUtils.isNotEmpty(referenceValues)) { + return (String) referenceValues.toArray()[0]; + } + return null; + } + +} diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/YamlValidator.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/YamlValidator.java index 4d05b2b066..4ae00ea2d9 100644 --- a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/YamlValidator.java +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/YamlValidator.java @@ -21,76 +21,63 @@ package org.openecomp.sdc.validation.impl.validators; import org.openecomp.core.utilities.yaml.YamlUtil; +import org.openecomp.sdc.validation.Validator; import org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder; -import org.openecomp.core.validation.errors.Messages; -import org.openecomp.core.validation.interfaces.Validator; import org.openecomp.core.validation.types.GlobalValidationContext; +import org.openecomp.sdc.common.errors.Messages; import org.openecomp.sdc.datatypes.error.ErrorLevel; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; -import org.yaml.snakeyaml.error.MarkedYAMLException; -import org.yaml.snakeyaml.parser.ParserException; +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.types.LoggerErrorDescription; +import org.openecomp.sdc.logging.types.LoggerTragetServiceName; +import org.openecomp.sdc.validation.impl.util.YamlValidatorUtil; import java.io.InputStream; import java.util.Collection; import java.util.Map; +import java.util.Optional; public class YamlValidator implements Validator { - - private static final Logger logger = LoggerFactory.getLogger(YamlValidator.class); + public static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); + private static final Logger logger = (Logger) LoggerFactory.getLogger(YamlValidator.class); @Override public void validate(GlobalValidationContext globalContext) { + mdcDataDebugMessage.debugEntryMessage(null, null); Collection<String> files = globalContext.files( (fileName, globalValidationContext) -> (fileName.endsWith(".yaml") || fileName.endsWith(".yml") || fileName.endsWith(".env"))); files.stream().forEach(fileName -> validate(fileName, globalContext)); + + mdcDataDebugMessage.debugExitMessage(null, null); } private void validate(String fileName, GlobalValidationContext globalContext) { - InputStream rowContent = globalContext.getFileContent(fileName); - if (rowContent == null) { + Optional<InputStream> rowContent = globalContext.getFileContent(fileName); + if (!rowContent.isPresent()) { globalContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder - .getErrorWithParameters(Messages.INVALID_YAML_FORMAT_REASON.getErrorMessage(), - Messages.EMPTY_YAML_FILE.getErrorMessage())); + .getErrorWithParameters(Messages.INVALID_YAML_FORMAT_REASON.getErrorMessage(), + Messages.EMPTY_YAML_FILE.getErrorMessage()), + LoggerTragetServiceName.VALIDATE_YAML_CONTENT, + LoggerErrorDescription.INVALID_YAML_FORMAT); return; /* no need to continue validation */ } try { - convert(rowContent, Map.class); + convert(rowContent.get(), Map.class); } catch (Exception exception) { globalContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder - .getErrorWithParameters(Messages.INVALID_YAML_FORMAT_REASON.getErrorMessage(), - getParserExceptionReason(exception))); - logger.error("Exception in yaml parser. message:" + exception.getMessage()); + .getErrorWithParameters(Messages.INVALID_YAML_FORMAT_REASON.getErrorMessage(), + YamlValidatorUtil.getParserExceptionReason(exception)), + LoggerTragetServiceName.VALIDATE_YAML_CONTENT, + LoggerErrorDescription.INVALID_YAML_FORMAT); } } - private String getParserExceptionReason(Exception exception) { - String reason = null; - - if (exception.getCause() instanceof MarkedYAMLException) { - if (exception.getCause() != null) { - if (exception.getCause().getCause() instanceof ParserException) { - reason = exception.getCause().getCause().getMessage(); - } else { - reason = exception.getCause().getMessage(); - } - } - } else if (exception instanceof MarkedYAMLException) { - - reason = exception.getMessage(); - - } else { - reason = Messages.GENERAL_YAML_PARSER_ERROR.getErrorMessage(); - } - return reason; - } - - private <T> T convert(InputStream content, Class<T> type) { return new YamlUtil().yamlToObject(content, type); } diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/heatresource/ContrailNetworkPolicyResourceValidator.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/heatresource/ContrailNetworkPolicyResourceValidator.java new file mode 100644 index 0000000000..8ca5e69061 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/heatresource/ContrailNetworkPolicyResourceValidator.java @@ -0,0 +1,92 @@ +package org.openecomp.sdc.validation.impl.validators.heatresource; + +import org.apache.commons.collections4.MapUtils; +import org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder; +import org.openecomp.core.validation.types.GlobalValidationContext; +import org.openecomp.sdc.common.errors.Messages; +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.logging.context.impl.MdcDataDebugMessage; +import org.openecomp.sdc.logging.types.LoggerErrorDescription; +import org.openecomp.sdc.logging.types.LoggerTragetServiceName; +import org.openecomp.sdc.validation.ResourceValidator; +import org.openecomp.sdc.validation.ValidationContext; +import org.openecomp.sdc.validation.type.HeatResourceValidationContext; +import org.openecomp.sdc.validation.type.ValidatorConstants; + +import java.util.List; +import java.util.Map; + +/** + * Created by TALIO on 2/28/2017. + */ +public class ContrailNetworkPolicyResourceValidator implements ResourceValidator { + private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); + + @Override + public void validate(String fileName, Map.Entry<String, Resource> resourceEntry, + GlobalValidationContext globalContext, ValidationContext validationContext) { + validateNetworkPolicyIsUsed + (fileName, resourceEntry, globalContext, (HeatResourceValidationContext)validationContext); + + } + + private static void validateNetworkPolicyIsUsed(String fileName, + Map.Entry<String, Resource> resourceEntry, + GlobalValidationContext globalContext, + HeatResourceValidationContext validationContext) { + mdcDataDebugMessage.debugEntryMessage("file", fileName); + + Map<String, Map<String, List<String>>> referencedNetworkAttachPoliciesResources = + validationContext.getFileLevelResourceDependencies() + .get(HeatResourcesTypes.CONTRAIL_NETWORK_RULE_RESOURCE_TYPE.getHeatResource()); + + if (MapUtils.isEmpty(referencedNetworkAttachPoliciesResources)) { + globalContext + .addMessage( + fileName, + ErrorLevel.WARNING, + ErrorMessagesFormatBuilder + .getErrorWithParameters( + Messages.RESOURCE_NOT_IN_USE.getErrorMessage(), + ValidatorConstants.Network_Policy, resourceEntry.getKey()), + LoggerTragetServiceName.VALIDATE_ATTACH_POLICY_IN_USE, + LoggerErrorDescription.NETWORK_ATTACH_POLICY_NOT_IN_USE); + return; + } + + handleNetworkAttachPolicyReferences + (fileName, resourceEntry, referencedNetworkAttachPoliciesResources, globalContext); + + mdcDataDebugMessage.debugExitMessage("file", fileName); + + } + + private static void handleNetworkAttachPolicyReferences(String fileName, + Map.Entry<String, Resource> resourceEntry, + Map<String, Map<String, List<String>>> pointedNetworkAttachPolicies, + GlobalValidationContext globalContext) { + + Map<String, List<String>> resourcesPointingToCurrNetworkAttachPolicy = + pointedNetworkAttachPolicies.get(resourceEntry.getKey()); + if (isNetworkAttachPolicyNotInUse(resourcesPointingToCurrNetworkAttachPolicy)) { + globalContext + .addMessage( + fileName, + ErrorLevel.WARNING, + ErrorMessagesFormatBuilder + .getErrorWithParameters( + Messages.RESOURCE_NOT_IN_USE.getErrorMessage(), + ValidatorConstants.Network_Policy, resourceEntry.getKey()), + LoggerTragetServiceName.VALIDATE_ATTACH_POLICY_IN_USE, + LoggerErrorDescription.NETWORK_ATTACH_POLICY_NOT_IN_USE); + } + } + + private static boolean isNetworkAttachPolicyNotInUse( + Map<String, List<String>> resourcesPointingToCurrNetworkAttachPolicy) { + return MapUtils.isEmpty(resourcesPointingToCurrNetworkAttachPolicy); + } + +} diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/heatresource/NestedResourceValidator.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/heatresource/NestedResourceValidator.java new file mode 100644 index 0000000000..aa7b91826c --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/heatresource/NestedResourceValidator.java @@ -0,0 +1,94 @@ +package org.openecomp.sdc.validation.impl.validators.heatresource; + +import org.apache.commons.collections4.CollectionUtils; +import org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder; +import org.openecomp.core.validation.types.GlobalValidationContext; +import org.openecomp.sdc.common.errors.Messages; +import org.openecomp.sdc.datatypes.error.ErrorLevel; +import org.openecomp.sdc.heat.datatypes.model.Resource; +import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; +import org.openecomp.sdc.logging.types.LoggerErrorDescription; +import org.openecomp.sdc.logging.types.LoggerTragetServiceName; +import org.openecomp.sdc.validation.ResourceValidator; +import org.openecomp.sdc.validation.ValidationContext; +import org.openecomp.sdc.validation.impl.util.HeatValidationService; + +import java.util.ArrayList; +import java.util.Collections; +import java.util.List; +import java.util.Map; +import java.util.Optional; +import java.util.Set; + +/** + * Created by TALIO on 2/22/2017. + */ +public class NestedResourceValidator implements ResourceValidator { + private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); + + @Override + public void validate(String fileName, Map.Entry<String, Resource> resourceEntry, + GlobalValidationContext globalContext, ValidationContext validationContext){ + + handleNestedResourceType(fileName, resourceEntry.getKey(), resourceEntry.getValue(), + Optional.empty(), globalContext); + } + + private static void handleNestedResourceType(String fileName, String resourceName, + Resource resource, Optional<String> indexVarValue, + GlobalValidationContext globalContext) { + + mdcDataDebugMessage.debugEntryMessage("file", fileName); + + validateAllPropertiesMatchNestedParameters(fileName, resourceName, resource, indexVarValue, + globalContext); + validateLoopsOfNestingFromFile(fileName, resource.getType(), globalContext); + + mdcDataDebugMessage.debugExitMessage("file", fileName); + } + + public static void validateAllPropertiesMatchNestedParameters(String fileName, + String resourceName, + Resource resource, + Optional<String> indexVarValue, + GlobalValidationContext + globalContext) { + + mdcDataDebugMessage.debugEntryMessage("file", fileName); + + String resourceType = resource.getType(); + if (globalContext.getFileContextMap().containsKey(resourceType)) { + Set<String> propertiesNames = + resource.getProperties() == null ? null : resource.getProperties().keySet(); + if (CollectionUtils.isNotEmpty(propertiesNames)) { + HeatValidationService + .checkNestedParameters(fileName, resourceType, resourceName, resource, propertiesNames, + indexVarValue, globalContext); + } + } else { + globalContext.addMessage(resourceType, ErrorLevel.ERROR, ErrorMessagesFormatBuilder + .getErrorWithParameters(Messages.MISSING_NESTED_FILE.getErrorMessage(), resourceType), + LoggerTragetServiceName.VALIDATE_PROPERTIES_MATCH_NESTED_PARAMETERS, + LoggerErrorDescription.MISSING_FILE); + } + + mdcDataDebugMessage.debugExitMessage("file", fileName); + } + + public static void validateLoopsOfNestingFromFile(String fileName, String resourceType, + GlobalValidationContext globalContext) { + + mdcDataDebugMessage.debugEntryMessage("file", fileName); + + List<String> filesInLoop = new ArrayList<>(Collections.singletonList(fileName)); + if (HeatValidationService + .isNestedLoopExistInFile(fileName, resourceType, filesInLoop, globalContext)) { + globalContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder + .getErrorWithParameters(Messages.NESTED_LOOP.getErrorMessage(), + HeatValidationService.drawFilesLoop(filesInLoop)), + LoggerTragetServiceName.VALIDATE_NESTING_LOOPS, LoggerErrorDescription.NESTED_LOOP); + } + + mdcDataDebugMessage.debugExitMessage("file", fileName); + } +} diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/heatresource/NeutronPortResourceValidator.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/heatresource/NeutronPortResourceValidator.java new file mode 100644 index 0000000000..09afec3faf --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/heatresource/NeutronPortResourceValidator.java @@ -0,0 +1,166 @@ +package org.openecomp.sdc.validation.impl.validators.heatresource; + +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.collections4.MapUtils; +import org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder; +import org.openecomp.core.validation.types.GlobalValidationContext; +import org.openecomp.sdc.common.errors.Messages; +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.datatypes.model.ResourceReferenceFunctions; +import org.openecomp.sdc.heat.services.HeatStructureUtil; +import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; +import org.openecomp.sdc.logging.types.LoggerErrorDescription; +import org.openecomp.sdc.logging.types.LoggerTragetServiceName; +import org.openecomp.sdc.validation.ResourceValidator; +import org.openecomp.sdc.validation.ValidationContext; +import org.openecomp.sdc.validation.type.HeatResourceValidationContext; + +import java.util.Collection; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Set; + +/** + * Created by TALIO on 2/22/2017. + */ +public class NeutronPortResourceValidator implements ResourceValidator { + private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); + + @Override + public void validate(String fileName, Map.Entry<String, Resource> resourceEntry, + GlobalValidationContext globalContext, ValidationContext validationContext) { + + validateNovaServerPortBinding + (fileName, resourceEntry, (HeatResourceValidationContext)validationContext, globalContext); + } + + + @SuppressWarnings("unchecked") + private static void validateNovaServerPortBinding(String fileName, + Map.Entry<String, Resource> resourceEntry, + HeatResourceValidationContext heatResourceValidationContext, + GlobalValidationContext globalContext) { + + mdcDataDebugMessage.debugEntryMessage("file", fileName); + + Map<String, Map<String, List<String>>> portIdToPointingResources = + heatResourceValidationContext.getFileLevelResourceDependencies() + .get(HeatResourcesTypes.NEUTRON_PORT_RESOURCE_TYPE.getHeatResource()); + + if(MapUtils.isEmpty(portIdToPointingResources)){ + globalContext + .addMessage(fileName, ErrorLevel.WARNING, + ErrorMessagesFormatBuilder + .getErrorWithParameters( + Messages.PORT_NO_BIND_TO_ANY_NOVA_SERVER.getErrorMessage(), + resourceEntry.getKey()), LoggerTragetServiceName.CHECK_FOR_ORPHAN_PORTS, + LoggerErrorDescription.NO_BIND_FROM_PORT_TO_NOVA); + + return; + } + + for (Map.Entry<String, Map<String, List<String>>> portEntry : + portIdToPointingResources.entrySet()) { + checkPortBindingFromMap(fileName, portEntry, globalContext); + } + + mdcDataDebugMessage.debugExitMessage("file", fileName); + } + + private static void checkPortBindingFromMap(String fileName, + Map.Entry<String, Map<String, List<String>>> portEntry, + GlobalValidationContext globalContext) { + Map<String, List<String>> pointingResourcesToCurrPort = portEntry.getValue(); + List<String> pointingNovaServers = pointingResourcesToCurrPort + .get(HeatResourcesTypes.NOVA_SERVER_RESOURCE_TYPE.getHeatResource()); + + if (CollectionUtils.isEmpty(pointingNovaServers)) { + return; + } + + handleErrorEventsForPortBinding(fileName, portEntry, globalContext, pointingNovaServers); + + + } + + private static void handleErrorEventsForPortBinding(String fileName, + Map.Entry<String, Map<String, List<String>>> portEntry, + GlobalValidationContext globalContext, + List<String> pointingNovaServers) { + if (isThereMoreThanOneBindFromNovaToPort(pointingNovaServers)) { + globalContext + .addMessage(fileName, ErrorLevel.ERROR, + ErrorMessagesFormatBuilder + .getErrorWithParameters( + Messages.MORE_THAN_ONE_BIND_FROM_NOVA_TO_PORT.getErrorMessage(), + portEntry.getKey()), + LoggerTragetServiceName.VALIDATE_NOVA_SERVER_PORT_BINDING, + LoggerErrorDescription.PORT_BINDS_MORE_THAN_ONE_NOVA); + } + + if(isNoNovaPointingToPort(pointingNovaServers)){ + globalContext + .addMessage(fileName, ErrorLevel.WARNING, + ErrorMessagesFormatBuilder + .getErrorWithParameters( + Messages.PORT_NO_BIND_TO_ANY_NOVA_SERVER.getErrorMessage(), + portEntry.getKey()), LoggerTragetServiceName.CHECK_FOR_ORPHAN_PORTS, + LoggerErrorDescription.NO_BIND_FROM_PORT_TO_NOVA); + } + } + + private static boolean isNoNovaPointingToPort(List<String> pointingNovaServers) { + return pointingNovaServers.size() == 0; + } + + private static boolean isThereMoreThanOneBindFromNovaToPort(List<String> pointingNovaServers) { + return pointingNovaServers.size() > 1; + } + + @SuppressWarnings("unchecked") + private static void validateAllSecurityGroupsAreUsed(String filename, + Map.Entry<String, Resource> resourceEntry, + List<String> securityGroupResourceNameList, + GlobalValidationContext globalContext) { + + mdcDataDebugMessage.debugEntryMessage("file", filename); + + Map<String, Object> propertiesMap = resourceEntry.getValue().getProperties(); + + if (MapUtils.isEmpty(propertiesMap)) { + return; + } + + Object securityGroupsValue = propertiesMap.get("security_groups"); + + if (Objects.isNull(securityGroupsValue)) { + return; + } + + if (securityGroupsValue instanceof List) { + List<Object> securityGroupsListFromCurrResource = + (List<Object>) propertiesMap.get("security_groups"); + for (Object securityGroup : securityGroupsListFromCurrResource) { + removeSecurityGroupNamesFromListByGivenFunction(filename, + ResourceReferenceFunctions.GET_RESOURCE.getFunction(), securityGroup, + securityGroupResourceNameList, globalContext); + } + } + + mdcDataDebugMessage.debugExitMessage("file", filename); + } + + private static void removeSecurityGroupNamesFromListByGivenFunction(String filename, + String functionName, + Object securityGroup, + Collection<String> + securityGroupResourceNameList, + GlobalValidationContext globalContext) { + Set<String> securityGroupsNamesFromFunction = HeatStructureUtil + .getReferencedValuesByFunctionName(filename, functionName, securityGroup, globalContext); + securityGroupsNamesFromFunction.forEach(securityGroupResourceNameList::remove); + } +} diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/heatresource/NeutronSecurityGroupResourceValidator.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/heatresource/NeutronSecurityGroupResourceValidator.java new file mode 100644 index 0000000000..d7e16152f9 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/heatresource/NeutronSecurityGroupResourceValidator.java @@ -0,0 +1,67 @@ +package org.openecomp.sdc.validation.impl.validators.heatresource; + +import org.apache.commons.collections4.MapUtils; +import org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder; +import org.openecomp.core.validation.types.GlobalValidationContext; +import org.openecomp.sdc.common.errors.Messages; +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.logging.types.LoggerErrorDescription; +import org.openecomp.sdc.logging.types.LoggerTragetServiceName; +import org.openecomp.sdc.validation.ResourceValidator; +import org.openecomp.sdc.validation.ValidationContext; +import org.openecomp.sdc.validation.type.HeatResourceValidationContext; +import org.openecomp.sdc.validation.type.ValidatorConstants; + +import java.util.List; +import java.util.Map; + +/** + * Created by TALIO on 2/27/2017. + */ +public class NeutronSecurityGroupResourceValidator implements ResourceValidator { + @Override + public void validate(String fileName, Map.Entry<String, Resource> resourceEntry, + GlobalValidationContext globalContext, ValidationContext validationContext) { + + HeatResourceValidationContext heatResourceValidationContext = + (HeatResourceValidationContext) validationContext; + validateSecurityGroupIsUsed(fileName, resourceEntry, heatResourceValidationContext, globalContext); + } + + public void validateSecurityGroupIsUsed(String fileName, Map.Entry<String, Resource> resourceEntry, + HeatResourceValidationContext + heatResourceValidationContext, + GlobalValidationContext globalContext) { + + Map<String, Map<String, List<String>>> securityGroupsPointedByOtherResources = + heatResourceValidationContext.getFileLevelResourceDependencies(). + get(HeatResourcesTypes.NEUTRON_SECURITY_GROUP_RESOURCE_TYPE.getHeatResource()); + + if (MapUtils.isEmpty(securityGroupsPointedByOtherResources)) { + return; + } + + Map<String, List<String>> resourcesPointingCurrSecurityGroup = + securityGroupsPointedByOtherResources.get(resourceEntry.getKey()); + + if(isSecurityGroupNotInUse(resourcesPointingCurrSecurityGroup)){ + globalContext.addMessage( + fileName, + ErrorLevel.WARNING, + ErrorMessagesFormatBuilder + .getErrorWithParameters( + Messages.RESOURCE_NOT_IN_USE.getErrorMessage(), + ValidatorConstants.Security_Group, resourceEntry.getKey()), + LoggerTragetServiceName.VALIDATE_ALL_SERVER_GROUP_OR_SECURITY_GROUP_IN_USE, + LoggerErrorDescription.SERVER_GROUP_SECURITY_GROUP_NOT_IN_USE); + } + + } + + public boolean isSecurityGroupNotInUse(Map<String, List<String>> + referencingResourcesToCurrSecurityGroup){ + return MapUtils.isEmpty(referencingResourcesToCurrSecurityGroup); + } +} diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/heatresource/NovaServerGroupResourceValidator.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/heatresource/NovaServerGroupResourceValidator.java new file mode 100644 index 0000000000..f56d941ba4 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/heatresource/NovaServerGroupResourceValidator.java @@ -0,0 +1,128 @@ +package org.openecomp.sdc.validation.impl.validators.heatresource; + +import org.apache.commons.collections4.MapUtils; +import org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder; +import org.openecomp.core.validation.types.GlobalValidationContext; +import org.openecomp.sdc.common.errors.Messages; +import org.openecomp.sdc.datatypes.error.ErrorLevel; +import org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes; +import org.openecomp.sdc.heat.datatypes.model.PolicyTypes; +import org.openecomp.sdc.heat.datatypes.model.Resource; +import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; +import org.openecomp.sdc.logging.types.LoggerErrorDescription; +import org.openecomp.sdc.logging.types.LoggerTragetServiceName; +import org.openecomp.sdc.validation.ResourceValidator; +import org.openecomp.sdc.validation.ValidationContext; +import org.openecomp.sdc.validation.type.HeatResourceValidationContext; +import org.openecomp.sdc.validation.type.ValidatorConstants; + +import java.util.List; +import java.util.Map; +import java.util.Objects; + +/** + * Created by TALIO on 2/22/2017. + */ +public class NovaServerGroupResourceValidator implements ResourceValidator { + private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); + + public void validate(String fileName, Map.Entry<String, Resource> resourceEntry, + GlobalValidationContext globalContext, ValidationContext validationContext) { + validateNovaServerGroupPolicy(fileName, resourceEntry, globalContext); + validateServerGroupIsUsed + (fileName, resourceEntry, globalContext, (HeatResourceValidationContext) validationContext); + } + + @SuppressWarnings("unchecked") + private static void validateNovaServerGroupPolicy(String fileName, + Map.Entry<String, Resource> resourceEntry, + GlobalValidationContext globalContext) { + + mdcDataDebugMessage.debugEntryMessage("file", fileName); + + Resource resource = resourceEntry.getValue(); + Object policies = + resource.getProperties() == null ? null : resource.getProperties().get("policies"); + + if (Objects.nonNull(policies) && policies instanceof List) { + List<Object> policiesList = (List<Object>) policies; + if (policiesList.size() == 1) { + Object policy = policiesList.get(0); + if (!isGivenPolicyValid(policy)) { + globalContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder + .getErrorWithParameters(Messages.WRONG_POLICY_IN_SERVER_GROUP.getErrorMessage(), + resourceEntry.getKey()), + LoggerTragetServiceName.VALIDATE_NOVA_SEVER_GROUP_POLICY, + LoggerErrorDescription.WRONG_POLICY_SERVER_GROUP); + } + } else { + globalContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder + .getErrorWithParameters(Messages.WRONG_POLICY_IN_SERVER_GROUP.getErrorMessage(), + resourceEntry.getKey()), + LoggerTragetServiceName.VALIDATE_NOVA_SEVER_GROUP_POLICY, + LoggerErrorDescription.WRONG_POLICY_SERVER_GROUP); + } + } + + mdcDataDebugMessage.debugExitMessage("file", fileName); + } + + private static boolean isGivenPolicyValid(Object policy) { + if (policy instanceof Map) { + return true; + } + if (policy instanceof String) { + return PolicyTypes.isGivenPolicyValid((String) policy); + } + return false; + } + + public void validateServerGroupIsUsed(String fileName, + Map.Entry<String, Resource> resourceEntry, + GlobalValidationContext globalContext, + HeatResourceValidationContext validationContext) { + + Map<String, Map<String, List<String>>> pointedServerGroups = + validationContext.getFileLevelResourceDependencies().get(HeatResourcesTypes + .NOVA_SERVER_GROUP_RESOURCE_TYPE.getHeatResource()); + + if (MapUtils.isEmpty(pointedServerGroups)) { + globalContext + .addMessage( + fileName, + ErrorLevel.WARNING, + ErrorMessagesFormatBuilder + .getErrorWithParameters( + Messages.RESOURCE_NOT_IN_USE.getErrorMessage(), + ValidatorConstants.Server_Group, resourceEntry.getKey()), + LoggerTragetServiceName.VALIDATE_ALL_SERVER_GROUP_OR_SECURITY_GROUP_IN_USE, + LoggerErrorDescription.SERVER_GROUP_SECURITY_GROUP_NOT_IN_USE); + return; + } + + handleServerGroupReferences(fileName, resourceEntry, pointedServerGroups, globalContext); + + + } + + private void handleServerGroupReferences(String fileName, Map.Entry<String, Resource> + resourceEntry, Map<String, Map<String, List<String>>> pointedServerGroups, + GlobalValidationContext globalContext) { + Map<String, List<String>> resourcesPointingToCurrServerGroup = + pointedServerGroups.get(resourceEntry.getKey()); + + if (MapUtils.isEmpty(resourcesPointingToCurrServerGroup)) { + globalContext + .addMessage( + fileName, + ErrorLevel.WARNING, + ErrorMessagesFormatBuilder + .getErrorWithParameters( + Messages.RESOURCE_NOT_IN_USE.getErrorMessage(), + ValidatorConstants.Server_Group, resourceEntry.getKey()), + LoggerTragetServiceName.VALIDATE_ALL_SERVER_GROUP_OR_SECURITY_GROUP_IN_USE, + LoggerErrorDescription.SERVER_GROUP_SECURITY_GROUP_NOT_IN_USE); + } + + } +} diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/heatresource/NovaServerResourceValidator.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/heatresource/NovaServerResourceValidator.java new file mode 100644 index 0000000000..5dc42c9b9a --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/heatresource/NovaServerResourceValidator.java @@ -0,0 +1,118 @@ +package org.openecomp.sdc.validation.impl.validators.heatresource; + +import org.apache.commons.collections4.MapUtils; +import org.openecomp.sdc.validation.ResourceValidator; +import org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder; +import org.openecomp.core.validation.types.GlobalValidationContext; +import org.openecomp.sdc.common.errors.Messages; +import org.openecomp.sdc.datatypes.error.ErrorLevel; +import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate; +import org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes; +import org.openecomp.sdc.heat.datatypes.model.PropertiesMapKeyTypes; +import org.openecomp.sdc.heat.datatypes.model.Resource; +import org.openecomp.sdc.heat.datatypes.model.ResourceReferenceFunctions; +import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; +import org.openecomp.sdc.logging.types.LoggerErrorDescription; +import org.openecomp.sdc.logging.types.LoggerTragetServiceName; +import org.openecomp.sdc.validation.ValidationContext; +import org.openecomp.sdc.validation.type.HeatResourceValidationContext; + +import java.util.Map; + +/** + * Created by TALIO on 2/22/2017. + */ +public class NovaServerResourceValidator implements ResourceValidator { + private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); + + public void validate(String fileName, Map.Entry<String, Resource> resourceEntry, + GlobalValidationContext globalContext, ValidationContext validationContext) { + + HeatResourceValidationContext heatResourceValidationContext = (HeatResourceValidationContext) + validationContext; + validateNovaServerResourceType + (fileName, resourceEntry, heatResourceValidationContext, globalContext); + } + + private static void validateNovaServerResourceType(String fileName, + Map.Entry<String, Resource> resourceEntry, + HeatResourceValidationContext heatResourceValidationContext, + GlobalValidationContext globalContext) { + + mdcDataDebugMessage.debugEntryMessage("file", fileName); + + validateAssignedValueForImageOrFlavorFromNova(fileName, resourceEntry, globalContext); + validateAllServerGroupsPointedByServerExistAndDefined + (fileName, resourceEntry, + heatResourceValidationContext.getHeatOrchestrationTemplate(), globalContext); + + mdcDataDebugMessage.debugExitMessage("file", fileName); + + } + + private static void validateAssignedValueForImageOrFlavorFromNova(String fileName, + Map.Entry<String, Resource> + resourceEntry, + GlobalValidationContext + globalContext) { + + mdcDataDebugMessage.debugEntryMessage("file", fileName); + + Resource resource = resourceEntry.getValue(); + Map<String, Object> propertiesMap = resource.getProperties(); + if (propertiesMap.get(PropertiesMapKeyTypes.IMAGE.getKeyMap()) == null + && propertiesMap.get(PropertiesMapKeyTypes.FLAVOR.getKeyMap()) == null) { + globalContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder + .getErrorWithParameters(Messages.MISSING_IMAGE_AND_FLAVOR.getErrorMessage(), + resourceEntry.getKey()), + LoggerTragetServiceName.VALIDATE_ASSIGNED_VALUES_FOR_NOVA_IMAGE_FLAVOR, + LoggerErrorDescription.MISSING_NOVA_PROPERTIES); + } + + mdcDataDebugMessage.debugExitMessage("file", fileName); + } + + @SuppressWarnings("unchecked") + private static void validateAllServerGroupsPointedByServerExistAndDefined(String fileName, + Map.Entry<String, Resource> resourceEntry, + HeatOrchestrationTemplate heatOrchestrationTemplate, + GlobalValidationContext globalContext) { + + mdcDataDebugMessage.debugEntryMessage("file", fileName); + + Map<String, Resource> resourcesMap = heatOrchestrationTemplate.getResources(); + Map<String, Object> resourceProperties = resourceEntry.getValue().getProperties(); + Map<String, Object> schedulerHintsMap = + resourceProperties == null ? null : (Map<String, Object>) resourceProperties.get( + ResourceReferenceFunctions.SCHEDULER_HINTS.getFunction()); + + if (MapUtils.isEmpty(schedulerHintsMap)) { + return; + } + + for (Object serverGroupValue : schedulerHintsMap.values()) { + if(!(serverGroupValue instanceof Map)){ + continue; + } + Map<String, Object> currentServerMap = (Map<String, Object>) serverGroupValue; + String serverResourceName = + currentServerMap == null ? null : (String) currentServerMap + .get(ResourceReferenceFunctions.GET_RESOURCE.getFunction()); + Resource serverResource = + serverResourceName == null || resourcesMap == null ? null + : resourcesMap.get(serverResourceName); + + if (serverResource != null && !serverResource.getType() + .equals(HeatResourcesTypes.NOVA_SERVER_GROUP_RESOURCE_TYPE.getHeatResource())) { + globalContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder + .getErrorWithParameters(Messages.SERVER_NOT_DEFINED_FROM_NOVA.getErrorMessage(), + serverResourceName, resourceEntry.getKey()), + LoggerTragetServiceName.VALIDATE_SERVER_GROUP_EXISTENCE, + LoggerErrorDescription.SERVER_NOT_DEFINED_NOVA); + } + } + + mdcDataDebugMessage.debugExitMessage("file", fileName); + } + +} diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/heatresource/ResourceGroupResourceValidator.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/heatresource/ResourceGroupResourceValidator.java new file mode 100644 index 0000000000..c94875c9f2 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/heatresource/ResourceGroupResourceValidator.java @@ -0,0 +1,136 @@ +package org.openecomp.sdc.validation.impl.validators.heatresource; + +import org.apache.commons.collections4.CollectionUtils; +import org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder; +import org.openecomp.core.validation.types.GlobalValidationContext; +import org.openecomp.sdc.common.errors.Messages; +import org.openecomp.sdc.datatypes.error.ErrorLevel; +import org.openecomp.sdc.heat.datatypes.model.Resource; +import org.openecomp.sdc.heat.services.HeatConstants; +import org.openecomp.sdc.heat.services.tree.HeatTreeManagerUtil; +import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; +import org.openecomp.sdc.logging.types.LoggerErrorDescription; +import org.openecomp.sdc.logging.types.LoggerTragetServiceName; +import org.openecomp.sdc.validation.ResourceValidator; +import org.openecomp.sdc.validation.ValidationContext; +import org.openecomp.sdc.validation.impl.util.HeatValidationService; + +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.Set; + +/** + * Created by TALIO on 2/22/2017. + */ +public class ResourceGroupResourceValidator implements ResourceValidator { + private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); + + @Override + public void validate(String fileName, Map.Entry<String, Resource> resourceEntry, + GlobalValidationContext globalContext, ValidationContext validationContext) { + validateResourceGroupType(fileName, resourceEntry, globalContext); + } + + private static void validateResourceGroupType(String fileName, + Map.Entry<String, Resource> resourceEntry, + GlobalValidationContext globalContext) { + + mdcDataDebugMessage.debugEntryMessage("file", fileName); + + Resource resourceDef = HeatTreeManagerUtil + .getResourceDef(fileName, resourceEntry.getKey(), resourceEntry.getValue(), globalContext); + if (resourceDef != null) { + if (Objects.nonNull(resourceDef.getType()) + && HeatValidationService.isNestedResource(resourceDef.getType())) { + Optional<String> indexVarValue = + getResourceGroupIndexVarValue(resourceEntry, fileName, globalContext); + handleNestedResourceType(fileName, resourceEntry.getKey(), resourceDef, indexVarValue, + globalContext); + } + } + + mdcDataDebugMessage.debugExitMessage("file", fileName); + } + + private static Optional<String> getResourceGroupIndexVarValue( + Map.Entry<String, Resource> resourceEntry, String fileName, + GlobalValidationContext globalContext) { + Object indexVar = + resourceEntry.getValue().getProperties().get(HeatConstants.INDEX_PROPERTY_NAME); + if (indexVar == null) { + return Optional.of(HeatConstants.RESOURCE_GROUP_INDEX_VAR_DEFAULT_VALUE); + } + + if (indexVar instanceof String) { + return Optional.of((String) indexVar); + } else { + globalContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder + .getErrorWithParameters(Messages.RESOURCE_GROUP_INVALID_INDEX_VAR.getErrorMessage(), + resourceEntry.getKey()), LoggerTragetServiceName.VALIDATE_RESOURCE_GROUP_TYPE, + LoggerErrorDescription.INVALID_INDEX_VAR); + return Optional.empty(); + } + } + + private static void handleNestedResourceType(String fileName, String resourceName, + Resource resource, Optional<String> indexVarValue, + GlobalValidationContext globalContext) { + + mdcDataDebugMessage.debugEntryMessage("file", fileName); + + validateAllPropertiesMatchNestedParameters(fileName, resourceName, resource, indexVarValue, + globalContext); + validateLoopsOfNestingFromFile(fileName, resource.getType(), globalContext); + + mdcDataDebugMessage.debugExitMessage("file", fileName); + } + + private static void validateAllPropertiesMatchNestedParameters(String fileName, + String resourceName, + Resource resource, + Optional<String> indexVarValue, + GlobalValidationContext + globalContext) { + + mdcDataDebugMessage.debugEntryMessage("file", fileName); + + String resourceType = resource.getType(); + if (globalContext.getFileContextMap().containsKey(resourceType)) { + Set<String> propertiesNames = + resource.getProperties() == null ? null : resource.getProperties().keySet(); + if (CollectionUtils.isNotEmpty(propertiesNames)) { + HeatValidationService + .checkNestedParameters(fileName, resourceType, resourceName, resource, propertiesNames, + indexVarValue, globalContext); + } + } else { + globalContext.addMessage(resourceType, ErrorLevel.ERROR, ErrorMessagesFormatBuilder + .getErrorWithParameters(Messages.MISSING_NESTED_FILE.getErrorMessage(), resourceType), + LoggerTragetServiceName.VALIDATE_PROPERTIES_MATCH_NESTED_PARAMETERS, + LoggerErrorDescription.MISSING_FILE); + } + + mdcDataDebugMessage.debugExitMessage("file", fileName); + } + + private static void validateLoopsOfNestingFromFile(String fileName, String resourceType, + GlobalValidationContext globalContext) { + + mdcDataDebugMessage.debugEntryMessage("file", fileName); + + List<String> filesInLoop = new ArrayList<>(Collections.singletonList(fileName)); + if (HeatValidationService + .isNestedLoopExistInFile(fileName, resourceType, filesInLoop, globalContext)) { + globalContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder + .getErrorWithParameters(Messages.NESTED_LOOP.getErrorMessage(), + HeatValidationService.drawFilesLoop(filesInLoop)), + LoggerTragetServiceName.VALIDATE_NESTING_LOOPS, LoggerErrorDescription.NESTED_LOOP); + } + + mdcDataDebugMessage.debugExitMessage("file", fileName); + } +} diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/namingconvention/ContrailServiceInstanceNamingConventionValidator.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/namingconvention/ContrailServiceInstanceNamingConventionValidator.java new file mode 100644 index 0000000000..957658e8cc --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/namingconvention/ContrailServiceInstanceNamingConventionValidator.java @@ -0,0 +1,81 @@ +package org.openecomp.sdc.validation.impl.validators.namingconvention; + +import org.apache.commons.collections4.MapUtils; +import org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder; +import org.openecomp.core.validation.types.GlobalValidationContext; +import org.openecomp.sdc.common.errors.Messages; +import org.openecomp.sdc.datatypes.error.ErrorLevel; +import org.openecomp.sdc.heat.datatypes.model.Resource; +import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; +import org.openecomp.sdc.logging.types.LoggerErrorDescription; +import org.openecomp.sdc.logging.types.LoggerTragetServiceName; +import org.openecomp.sdc.validation.ResourceValidator; +import org.openecomp.sdc.validation.ValidationContext; +import org.openecomp.sdc.validation.util.ValidationUtil; + +import java.util.Map; + +import static java.util.Objects.nonNull; + +/** + * Created by TALIO on 2/24/2017. + */ +public class ContrailServiceInstanceNamingConventionValidator implements ResourceValidator { + private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); + + @Override + public void validate(String fileName, Map.Entry<String, Resource> resourceEntry, + GlobalValidationContext globalContext, ValidationContext validationContext) { + validateAvailabilityZoneName(fileName, resourceEntry, globalContext); + } + + private void validateAvailabilityZoneName(String fileName, + Map.Entry<String, Resource> resourceEntry, + GlobalValidationContext globalContext) { + + + mdcDataDebugMessage.debugEntryMessage("file", fileName); + + String[] regexList = new String[]{"availability_zone_(\\d+)"}; + + if (MapUtils.isEmpty(resourceEntry.getValue().getProperties())) { + mdcDataDebugMessage.debugExitMessage("file", fileName); + return; + } + + Object availabilityZoneMap = + resourceEntry.getValue().getProperties().containsKey("availability_zone") ? resourceEntry + .getValue().getProperties().get("availability_zone") : null; + + if (nonNull(availabilityZoneMap)) { + if (availabilityZoneMap instanceof Map) { + String availabilityZoneName = ValidationUtil.getWantedNameFromPropertyValueGetParam + (availabilityZoneMap); + + if (availabilityZoneName != null) { + if (!ValidationUtil.evalPattern(availabilityZoneName, regexList)) { + globalContext.addMessage( + fileName, + ErrorLevel.WARNING, ErrorMessagesFormatBuilder.getErrorWithParameters( + Messages.PARAMETER_NAME_NOT_ALIGNED_WITH_GUIDELINES.getErrorMessage(), + ValidationUtil.getMessagePartAccordingToResourceType(resourceEntry), + "Availability Zone", + availabilityZoneName, resourceEntry.getKey()), + LoggerTragetServiceName.VALIDATE_AVAILABILITY_ZONE_NAME, + LoggerErrorDescription.NAME_NOT_ALIGNED_WITH_GUIDELINES); + } + } + } else { + globalContext.addMessage( + fileName, + ErrorLevel.WARNING, ErrorMessagesFormatBuilder + .getErrorWithParameters(Messages.MISSING_GET_PARAM.getErrorMessage(), + "availability_zone", resourceEntry.getKey()), + LoggerTragetServiceName.VALIDATE_AVAILABILITY_ZONE_NAME, + LoggerErrorDescription.MISSING_GET_PARAM); + } + } + mdcDataDebugMessage.debugExitMessage("file", fileName); + } + +} diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/namingconvention/ContrailServiceTemplateNamingConventionValidator.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/namingconvention/ContrailServiceTemplateNamingConventionValidator.java new file mode 100644 index 0000000000..05f2e4fcc7 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/namingconvention/ContrailServiceTemplateNamingConventionValidator.java @@ -0,0 +1,209 @@ +package org.openecomp.sdc.validation.impl.validators.namingconvention; + +import org.apache.commons.collections4.CollectionUtils; +import org.apache.commons.collections4.MapUtils; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.apache.commons.lang3.tuple.Pair; +import org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder; +import org.openecomp.core.validation.types.GlobalValidationContext; +import org.openecomp.sdc.common.errors.Messages; +import org.openecomp.sdc.datatypes.error.ErrorLevel; +import org.openecomp.sdc.heat.datatypes.model.Resource; +import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; +import org.openecomp.sdc.logging.types.LoggerErrorDescription; +import org.openecomp.sdc.logging.types.LoggerTragetServiceName; +import org.openecomp.sdc.validation.ResourceValidator; +import org.openecomp.sdc.validation.ValidationContext; +import org.openecomp.sdc.validation.util.ValidationUtil; + +import java.util.Arrays; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.Optional; +import java.util.regex.Pattern; + +import static java.util.Objects.nonNull; + +/** + * Created by TALIO on 2/24/2017. + */ +public class ContrailServiceTemplateNamingConventionValidator implements ResourceValidator { + private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); + + @Override + public void validate(String fileName, Map.Entry<String, Resource> resourceEntry, + GlobalValidationContext globalContext, ValidationContext validationContext) { + validateServiceTemplateImageAndFlavor(fileName, resourceEntry, globalContext); + } + + private void validateServiceTemplateImageAndFlavor(String fileName, + Map.Entry<String, Resource> entry, + GlobalValidationContext globalContext) { + + mdcDataDebugMessage.debugEntryMessage("file", fileName); + + if (MapUtils.isEmpty(entry.getValue().getProperties())) { + return; + } + + Pair<String, String> imagePair = new ImmutablePair<>("image_name", ".*_image_name"); + Pair<String, String> flavorPair = new ImmutablePair<>("flavor", ".*_flavor_name"); + List<Pair<String, String>> imageFlavorPairs = Arrays.asList(imagePair, flavorPair); + + Map<String, Object> propertiesMap = entry.getValue().getProperties(); + + boolean errorExistValidatingImageOrFlavor = false; + for (Pair<String, String> imageOrFlavor : imageFlavorPairs) { + boolean errorExistWhenValidatingImageOrFlavorNames = + isErrorExistWhenValidatingImageOrFlavorNames(fileName, imageOrFlavor, entry, + propertiesMap, globalContext); + errorExistValidatingImageOrFlavor = + errorExistValidatingImageOrFlavor || errorExistWhenValidatingImageOrFlavorNames; + } + + if (!errorExistValidatingImageOrFlavor) { + validateServiceTemplatePropertiesValuesVmtypesAreIdentical(fileName, entry, globalContext, + propertiesMap); + } + + mdcDataDebugMessage.debugExitMessage("file", fileName); + } + + private void validateServiceTemplatePropertiesValuesVmtypesAreIdentical(String fileName, + Map.Entry<String, Resource> entry, + GlobalValidationContext globalContext, + Map<String, Object> propertiesMap) { + + mdcDataDebugMessage.debugEntryMessage("file", fileName); + + Pair<String, String> vmTypeImagePair = new ImmutablePair<>("image_name", "\\_image\\_name"); + Pair<String, String> vmTypeFlavorPair = new ImmutablePair<>("flavor", "\\_flavor\\_name"); + validatePropertiesValuesVmtypesAreIdentical(Arrays.asList(vmTypeImagePair, vmTypeFlavorPair), + fileName, entry, propertiesMap, globalContext); + + mdcDataDebugMessage.debugExitMessage("file", fileName); + } + + private void validatePropertiesValuesVmtypesAreIdentical(List<Pair> propertiesToMatch, + String fileName, + Map.Entry<String, Resource> resourceEntry, + Map<String, Object> propertiesMap, + GlobalValidationContext globalContext) { + + + mdcDataDebugMessage.debugEntryMessage("file", fileName); + + if (CollectionUtils.isEmpty(propertiesToMatch)) { + return; + } + + String previousPropertyValueValue = null; + for (Pair propertyToMatch : propertiesToMatch) { + Optional<String> propertyVmType = + extractVmTypeFromProperty(fileName, resourceEntry, propertiesMap, globalContext, + propertyToMatch); + if (propertyVmType.isPresent()) { + String currentPropVmType = propertyVmType.get(); + previousPropertyValueValue = + handleFirstIteration(previousPropertyValueValue, currentPropVmType); + if (addWarningIfCurrentVmTypeIsDifferentFromPrevious(fileName, resourceEntry, globalContext, + previousPropertyValueValue, currentPropVmType)) { + mdcDataDebugMessage.debugExitMessage("file", fileName); + return; + } + } + } + + mdcDataDebugMessage.debugExitMessage("file", fileName); + } + + private boolean addWarningIfCurrentVmTypeIsDifferentFromPrevious(String fileName, + Map.Entry<String, Resource> resourceEntry, + GlobalValidationContext globalContext, + String previousPropertyValueValue, + String currentPropVmType) { + if (!Objects.equals(previousPropertyValueValue, currentPropVmType)) { + globalContext.addMessage(fileName, ErrorLevel.WARNING, ErrorMessagesFormatBuilder + .getErrorWithParameters( + Messages.CONTRAIL_VM_TYPE_NAME_NOT_ALIGNED_WITH_NAMING_CONVENSION + .getErrorMessage(), resourceEntry.getKey()), + LoggerTragetServiceName.VALIDATE_CONTRAIL_VM_NAME, + LoggerErrorDescription.NAME_NOT_ALIGNED_WITH_GUIDELINES); + return true; + } + + return false; + } + + private boolean isErrorExistWhenValidatingImageOrFlavorNames(String fileName, + Pair<String, String> propertyNameAndRegex, + Map.Entry<String, Resource> resourceEntry, + Map<String, Object> propertiesMap, + GlobalValidationContext globalContext) { + String propertyName = propertyNameAndRegex.getKey(); + Object nameValue = + propertiesMap.get(propertyName) == null ? null : propertiesMap.get(propertyName); + String[] regexList = new String[]{propertyNameAndRegex.getValue()}; + + if (nonNull(nameValue)) { + if (nameValue instanceof Map) { + if (ValidationUtil.validateMapPropertyValue(fileName, resourceEntry, globalContext, + propertyName, + nameValue, regexList)) { + return true; + } + } else { + globalContext.addMessage( + fileName, + ErrorLevel.WARNING, ErrorMessagesFormatBuilder + .getErrorWithParameters(Messages.MISSING_GET_PARAM.getErrorMessage(), propertyName, + resourceEntry.getKey()), + LoggerTragetServiceName.VALIDATE_IMAGE_AND_FLAVOR_NAME, + LoggerErrorDescription.MISSING_GET_PARAM); + return true; + } + + return false; + } + return false; + } + + + private Optional<String> extractVmTypeFromProperty(String fileName, + Map.Entry<String, Resource> resourceEntry, + Map<String, Object> propertiesMap, + GlobalValidationContext globalContext, + Pair propertyKeyRegex) { + String propertyName = (String) propertyKeyRegex.getKey(); + Object propertyVal = propertiesMap.get(propertyName); + if (nonNull(propertyVal)) { + if (propertyVal instanceof Map) { + String propertyValFromGetParam = ValidationUtil.getWantedNameFromPropertyValueGetParam + (propertyVal); + if (nonNull(propertyValFromGetParam)) { + Pattern pattern = Pattern.compile("" + propertyKeyRegex.getValue()); + return Optional.ofNullable(pattern.split(propertyValFromGetParam)[0]); + } + } else { + globalContext.addMessage( + fileName, + ErrorLevel.WARNING, ErrorMessagesFormatBuilder + .getErrorWithParameters(Messages.MISSING_GET_PARAM.getErrorMessage(), propertyName, + resourceEntry.getKey()), + LoggerTragetServiceName.VALIDATE_VM_SYNC_IN_IMAGE_FLAVOR, + LoggerErrorDescription.MISSING_GET_PARAM); + return Optional.empty(); + } + } + return Optional.empty(); + } + + private String handleFirstIteration(String previousPropertyValueValue, String currentPropVmType) { + if (Objects.isNull(previousPropertyValueValue)) { + previousPropertyValueValue = currentPropVmType; + } + + return previousPropertyValueValue; + } +} diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/namingconvention/NeutronPortNamingConventionValidator.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/namingconvention/NeutronPortNamingConventionValidator.java new file mode 100644 index 0000000000..3401e15bd8 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/namingconvention/NeutronPortNamingConventionValidator.java @@ -0,0 +1,177 @@ +package org.openecomp.sdc.validation.impl.validators.namingconvention; + +import org.apache.commons.collections4.MapUtils; +import org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder; +import org.openecomp.core.validation.types.GlobalValidationContext; +import org.openecomp.sdc.common.errors.Messages; +import org.openecomp.sdc.datatypes.error.ErrorLevel; +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.MdcDataDebugMessage; +import org.openecomp.sdc.logging.types.LoggerErrorDescription; +import org.openecomp.sdc.logging.types.LoggerTragetServiceName; +import org.openecomp.sdc.validation.ResourceValidator; +import org.openecomp.sdc.validation.ValidationContext; +import org.openecomp.sdc.validation.type.NamingConventionValidationContext; +import org.openecomp.sdc.validation.util.ValidationUtil; + +import java.util.List; +import java.util.Map; + +import static java.util.Objects.nonNull; + +/** + * Created by TALIO on 2/23/2017. + */ +public class NeutronPortNamingConventionValidator implements ResourceValidator { + private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); + + @Override + public void validate(String fileName, Map.Entry<String, Resource> resourceEntry, + GlobalValidationContext globalContext, ValidationContext validationContext) { + + NamingConventionValidationContext namingConventionValidationContext = + (NamingConventionValidationContext)validationContext; + validatePortNetworkNamingConvention(fileName, namingConventionValidationContext.getHeatOrchestrationTemplate(), globalContext); + validateFixedIpsNamingConvention(fileName, namingConventionValidationContext.getHeatOrchestrationTemplate(), globalContext); + } + + private void validatePortNetworkNamingConvention(String fileName, + HeatOrchestrationTemplate heatOrchestrationTemplate, + GlobalValidationContext globalContext) { + + mdcDataDebugMessage.debugEntryMessage("file", fileName); + + if (MapUtils.isEmpty(heatOrchestrationTemplate.getResources())) { + mdcDataDebugMessage.debugExitMessage("file", fileName); + return; + } + String[] regexList = new String[]{".*_net_id", ".*_net_name", ".*_net_fqdn"}; + + heatOrchestrationTemplate + .getResources() + .entrySet() + .stream() + .filter(entry -> entry.getValue().getType() + .equals(HeatResourcesTypes.NEUTRON_PORT_RESOURCE_TYPE.getHeatResource())) + .forEach(entry -> entry.getValue() + .getProperties() + .entrySet() + .stream() + .filter(propertyEntry -> + propertyEntry.getKey().toLowerCase().equals("network".toLowerCase()) + || propertyEntry.getKey().equals("network_id")) + .forEach(propertyEntry -> validateParamNamingConvention(fileName, entry.getKey(), + propertyEntry.getValue(), "Port", "Network", regexList, + Messages.PARAMETER_NAME_NOT_ALIGNED_WITH_GUIDELINES, globalContext))); + + mdcDataDebugMessage.debugExitMessage("file", fileName); + } + + private void validateFixedIpsNamingConvention(String fileName, + HeatOrchestrationTemplate heatOrchestrationTemplate, + GlobalValidationContext globalContext) { + + mdcDataDebugMessage.debugEntryMessage("file", fileName); + + if (MapUtils.isEmpty(heatOrchestrationTemplate.getResources())) { + mdcDataDebugMessage.debugExitMessage("file", fileName); + return; + } + + heatOrchestrationTemplate.getResources() + .entrySet() + .stream() + .filter(entry -> HeatResourcesTypes.findByHeatResource(entry.getValue().getType()) != null) + .filter(entry -> HeatResourcesTypes.findByHeatResource(entry.getValue().getType()) + .equals(HeatResourcesTypes.NEUTRON_PORT_RESOURCE_TYPE)) + .forEach(entry -> checkNeutronPortFixedIpsName(fileName, entry, globalContext)); + + mdcDataDebugMessage.debugExitMessage("file", fileName); + } + + private void checkNeutronPortFixedIpsName(String fileName, + Map.Entry<String, Resource> resourceEntry, + GlobalValidationContext globalContext) { + String[] regexList = + new String[]{"[^_]+_[^_]+_ips", "[^_]+_[^_]+_v6_ips", "[^_]+_[^_]+_ip_(\\d+)", + "[^_]+_[^_]+_v6_ip_(\\d+)"}; + + if (MapUtils.isEmpty(resourceEntry.getValue().getProperties())) { + return; + } + + Map<String, Object> propertiesMap = resourceEntry.getValue().getProperties(); + Object fixedIps = propertiesMap.get("fixed_ips"); + if (nonNull(fixedIps) && fixedIps instanceof List) { + List<Object> fixedIpsList = (List<Object>) fixedIps; + for (Object fixedIpsObject : fixedIpsList) { + Map.Entry<String, Object> fixedIpsEntry = + ((Map<String, Object>) fixedIpsObject).entrySet().iterator().next(); + if (nonNull(fixedIpsEntry)) { + if (fixedIpsEntry.getValue() instanceof Map) { + String fixedIpsName = ValidationUtil.getWantedNameFromPropertyValueGetParam + (fixedIpsEntry + .getValue()); + if (nonNull(fixedIpsName)) { + if (!ValidationUtil.evalPattern(fixedIpsName, regexList)) { + globalContext.addMessage( + fileName, + ErrorLevel.WARNING, ErrorMessagesFormatBuilder.getErrorWithParameters( + Messages.PARAMETER_NAME_NOT_ALIGNED_WITH_GUIDELINES.getErrorMessage(), + "Port", "Fixed_IPS", fixedIpsName, resourceEntry.getKey()), + LoggerTragetServiceName.VALIDATE_FIXED_IPS_NAME, + LoggerErrorDescription.NAME_NOT_ALIGNED_WITH_GUIDELINES); + } + } + } else { + globalContext.addMessage( + fileName, + ErrorLevel.WARNING, ErrorMessagesFormatBuilder + .getErrorWithParameters(Messages.MISSING_GET_PARAM.getErrorMessage(), + "fixed_ips", resourceEntry.getKey()), + LoggerTragetServiceName.VALIDATE_FIXED_IPS_NAME, + LoggerErrorDescription.MISSING_GET_PARAM); + } + } + } + } + } + + private void validateParamNamingConvention(String fileName, String resourceId, + Object propertyValue, String resourceType, + String wrongPropertyFormat, String[] regexList, + Messages message, + GlobalValidationContext globalContext) { + + mdcDataDebugMessage.debugEntryMessage("file", fileName); + + Object paramName; + if (propertyValue instanceof Map) { + paramName = ((Map) propertyValue).get("get_param"); + if (paramName instanceof String) { + if (!ValidationUtil.evalPattern((String) paramName, regexList)) { + globalContext.addMessage( + fileName, + ErrorLevel.WARNING, ErrorMessagesFormatBuilder + .getErrorWithParameters(message.getErrorMessage(), resourceType, + wrongPropertyFormat, (String) paramName, resourceId), + LoggerTragetServiceName.VALIDATE_PORT_NETWORK_NAME, + LoggerErrorDescription.NAME_NOT_ALIGNED_WITH_GUIDELINES); + } + } + } else { + globalContext.addMessage( + fileName, + ErrorLevel.WARNING, + ErrorMessagesFormatBuilder + .getErrorWithParameters(Messages.MISSING_GET_PARAM.getErrorMessage(), + "network or network_id", resourceId), + LoggerTragetServiceName.VALIDATE_PORT_NETWORK_NAME, + LoggerErrorDescription.MISSING_GET_PARAM); + } + + mdcDataDebugMessage.debugExitMessage("file", fileName); + } +} diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/namingconvention/NovaServerNamingConventionGuideLineValidator.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/namingconvention/NovaServerNamingConventionGuideLineValidator.java new file mode 100644 index 0000000000..cf2751bef7 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/namingconvention/NovaServerNamingConventionGuideLineValidator.java @@ -0,0 +1,596 @@ +package org.openecomp.sdc.validation.impl.validators.namingconvention; + +import org.apache.commons.collections4.MapUtils; +import org.apache.commons.lang3.tuple.ImmutablePair; +import org.apache.commons.lang3.tuple.Pair; +import org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder; +import org.openecomp.core.validation.types.GlobalValidationContext; +import org.openecomp.sdc.common.errors.Messages; +import org.openecomp.sdc.datatypes.error.ErrorLevel; +import org.openecomp.sdc.heat.datatypes.DefinedHeatParameterTypes; +import org.openecomp.sdc.heat.datatypes.model.Environment; +import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate; +import org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes; +import org.openecomp.sdc.heat.datatypes.model.Resource; +import org.openecomp.sdc.heat.datatypes.model.ResourceReferenceFunctions; +import org.openecomp.sdc.heat.services.HeatStructureUtil; +import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage; +import org.openecomp.sdc.logging.types.LoggerErrorDescription; +import org.openecomp.sdc.logging.types.LoggerTragetServiceName; +import org.openecomp.sdc.validation.ResourceValidator; +import org.openecomp.sdc.validation.ValidationContext; +import org.openecomp.sdc.validation.type.NamingConventionValidationContext; +import org.openecomp.sdc.validation.util.ValidationUtil; + +import java.util.ArrayList; +import java.util.Arrays; +import java.util.Collection; +import java.util.Comparator; +import java.util.HashMap; +import java.util.LinkedList; +import java.util.List; +import java.util.Map; +import java.util.Objects; +import java.util.TreeMap; + +import static java.util.Objects.nonNull; + +/** + * Created by TALIO on 2/23/2017. + */ +public class NovaServerNamingConventionGuideLineValidator implements ResourceValidator { + private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage(); + + @Override + public void validate(String fileName, Map.Entry<String, Resource> resourceEntry, + GlobalValidationContext globalContext, ValidationContext validationContext) { + + NamingConventionValidationContext namingConventionValidationContext = + (NamingConventionValidationContext)validationContext; + validateHeatNovaResource(fileName, namingConventionValidationContext.getEnvFileName(), + namingConventionValidationContext.getHeatOrchestrationTemplate(), + globalContext); + } + + private void validateHeatNovaResource(String fileName, String envFileName, + HeatOrchestrationTemplate heatOrchestrationTemplate, + GlobalValidationContext globalContext) { + + + mdcDataDebugMessage.debugEntryMessage("file", fileName); + + Map<String, String> uniqueResourcePortNetworkRole = new HashMap<>(); + //if no resources exist return + if (MapUtils.isEmpty(heatOrchestrationTemplate.getResources())) { + return; + } + + heatOrchestrationTemplate + .getResources() + .entrySet() + .stream() + .filter(entry -> entry.getValue().getType() + .equals(HeatResourcesTypes.NOVA_SERVER_RESOURCE_TYPE.getHeatResource())) + .forEach( entry -> validateNovaServerResourceType(entry.getKey(), fileName, envFileName, + entry, uniqueResourcePortNetworkRole, heatOrchestrationTemplate, globalContext)); + + mdcDataDebugMessage.debugExitMessage("file", fileName); + } + + private void validateNovaServerResourceType(String resourceId, String fileName, + String envFileName, + Map.Entry<String, Resource> resourceEntry, + Map<String, String> uniqueResourcePortNetworkRole, + HeatOrchestrationTemplate heatOrchestrationTemplate, + GlobalValidationContext globalContext) { + + mdcDataDebugMessage.debugEntryMessage("file", fileName); + + validateNovaServerResourceMetaData(fileName, resourceId, + heatOrchestrationTemplate.getResources().get(resourceId), globalContext); + validateNovaServerResourceNetworkUniqueRole(fileName, resourceId, uniqueResourcePortNetworkRole, + heatOrchestrationTemplate, globalContext); + validateAvailabilityZoneName(fileName, resourceEntry, globalContext); + validateNovaServerNameImageAndFlavor(fileName, envFileName, resourceEntry, globalContext); + + mdcDataDebugMessage.debugExitMessage("file", fileName); + } + + @SuppressWarnings("unchecked") + private void validateNovaServerResourceMetaData(String fileName, String resourceId, + Resource resource, + GlobalValidationContext globalValidationContext) { + + mdcDataDebugMessage.debugEntryMessage("file", fileName); + + Map<String, Object> novaServerProp = resource.getProperties(); + Object novaServerPropMetadata; + if (MapUtils.isNotEmpty(novaServerProp)) { + novaServerPropMetadata = novaServerProp.get("metadata"); + if (novaServerPropMetadata == null) { + globalValidationContext.addMessage( + fileName, + ErrorLevel.WARNING, + ErrorMessagesFormatBuilder + .getErrorWithParameters(Messages.MISSING_NOVA_SERVER_METADATA.getErrorMessage(), + resourceId), + LoggerTragetServiceName.VALIDATE_NOVA_META_DATA_NAME, + LoggerErrorDescription.MISSING_NOVA_PROPERTIES); + } else if (novaServerPropMetadata instanceof Map) { + TreeMap<String, Object> propertyMap = new TreeMap(new Comparator<String>() { + + @Override + public int compare(String o1, String o2) { + return o1.compareToIgnoreCase(o2); + } + + @Override + public boolean equals(Object obj) { + return false; + } + }); + propertyMap.putAll((Map) novaServerPropMetadata); + if (!propertyMap.containsKey("vf_module_id")) { + globalValidationContext.addMessage( + fileName, + ErrorLevel.WARNING, + ErrorMessagesFormatBuilder.getErrorWithParameters( + Messages.MISSING_NOVA_SERVER_VF_MODULE_ID.getErrorMessage(), resourceId), + LoggerTragetServiceName.VALIDATE_NOVA_META_DATA_NAME, + LoggerErrorDescription.MISSING_NOVA_PROPERTIES); + } + if (!propertyMap.containsKey("vnf_id")) { + globalValidationContext.addMessage( + fileName, ErrorLevel.WARNING, + ErrorMessagesFormatBuilder + .getErrorWithParameters(Messages.MISSING_NOVA_SERVER_VNF_ID.getErrorMessage(), + resourceId), + LoggerTragetServiceName.VALIDATE_NOVA_META_DATA_NAME, + LoggerErrorDescription.MISSING_NOVA_PROPERTIES); + } + } + } + + mdcDataDebugMessage.debugExitMessage("file", fileName); + } + + private void validateNovaServerResourceNetworkUniqueRole(String fileName, String resourceId, + Map<String, String> uniqueResourcePortNetworkRole, + HeatOrchestrationTemplate heatOrchestrationTemplate, + GlobalValidationContext globalValidationContext) { + + + mdcDataDebugMessage.debugEntryMessage("file", fileName); + + Object network; + String role = null; + + Object propertyNetworkValue = + heatOrchestrationTemplate.getResources().get(resourceId).getProperties().get("networks"); + if (propertyNetworkValue != null && propertyNetworkValue instanceof List) { + List<String> portResourceIdList = + getNovaNetworkPortResourceList(fileName, (List) propertyNetworkValue, + globalValidationContext); + for (String portResourceId : portResourceIdList) { + Resource portResource = heatOrchestrationTemplate.getResources().get(portResourceId); + if (portResource != null && portResource.getType() + .equals(HeatResourcesTypes.NEUTRON_PORT_RESOURCE_TYPE.getHeatResource())) { + Map portNetwork = + getPortNetwork(fileName, resourceId, portResource, globalValidationContext); + if (Objects.nonNull(portNetwork)) { + network = portNetwork.get("get_param"); + if (Objects.nonNull(network)) { + if (network instanceof String ){ + role = getNetworkRole((String)network); + }else if (network instanceof List){ + role = getNetworkRole((String)((List) network).get(0)); + } + if (role != null && uniqueResourcePortNetworkRole.containsKey(role)) { + globalValidationContext.addMessage( + fileName, + ErrorLevel.WARNING, + ErrorMessagesFormatBuilder.getErrorWithParameters( + Messages.RESOURCE_CONNECTED_TO_TWO_EXTERNAL_NETWORKS_WITH_SAME_ROLE + .getErrorMessage(), resourceId, role), + LoggerTragetServiceName.VALIDATE_RESOURCE_NETWORK_UNIQUE_ROLW, + LoggerErrorDescription.RESOURCE_UNIQUE_NETWORK_ROLE); + } else { + uniqueResourcePortNetworkRole.put(role, portResourceId); + } + } + } + } + } + } + + mdcDataDebugMessage.debugExitMessage("file", fileName); + } + + private List<String> getNovaNetworkPortResourceList(String filename, List propertyNetworkValue, + GlobalValidationContext globalContext) { + List<String> portResourceIdList = new ArrayList<>(); + for (Object propValue : propertyNetworkValue) { + Object portPropValue = ((Map) propValue).get("port"); + Collection<String> portResourceIds = HeatStructureUtil + .getReferencedValuesByFunctionName(filename, "get_resource", portPropValue, + globalContext); + if (portResourceIds != null) { + portResourceIdList.addAll(portResourceIds); + } + } + + return portResourceIdList; + } + + private String getNetworkRole(String network) { + if (network == null) { + return null; + } + if (network.contains("_net_id")) { + return network.substring(0, network.indexOf("_net_id")); + } else if (network.contains("net_name")) { + return network.substring(0, network.indexOf("_net_name")); + } else if (network.contains("net_fqdn")) { + return network.substring(0, network.indexOf("_net_fqdn")); + } + return null; + } + + private Map getPortNetwork(String fileName, String resourceId, Resource portResource, + GlobalValidationContext globalValidationContext) { + Object portNetwork = portResource.getProperties().get("network_id"); + if (portNetwork == null) { + portNetwork = portResource.getProperties().get("network"); + } + if (!(portNetwork instanceof Map)) { + globalValidationContext.addMessage( + fileName, + ErrorLevel.WARNING, + ErrorMessagesFormatBuilder + .getErrorWithParameters(Messages.MISSING_GET_PARAM.getErrorMessage(), + "network or network_id", resourceId), + LoggerTragetServiceName.VALIDATE_RESOURCE_NETWORK_UNIQUE_ROLW, + LoggerErrorDescription.MISSING_GET_PARAM); + return null; + } + return (Map) portNetwork; + } + + private void validateAvailabilityZoneName(String fileName, + Map.Entry<String, Resource> resourceEntry, + GlobalValidationContext globalContext) { + + + mdcDataDebugMessage.debugEntryMessage("file", fileName); + + String[] regexList = new String[]{"availability_zone_(\\d+)"}; + + if (MapUtils.isEmpty(resourceEntry.getValue().getProperties())) { + mdcDataDebugMessage.debugExitMessage("file", fileName); + return; + } + + Object availabilityZoneMap = + resourceEntry.getValue().getProperties().containsKey("availability_zone") ? resourceEntry + .getValue().getProperties().get("availability_zone") : null; + + if (nonNull(availabilityZoneMap)) { + if (availabilityZoneMap instanceof Map) { + String availabilityZoneName = ValidationUtil.getWantedNameFromPropertyValueGetParam + (availabilityZoneMap); + + if (availabilityZoneName != null) { + if (!ValidationUtil.evalPattern(availabilityZoneName, regexList)) { + globalContext.addMessage( + fileName, + ErrorLevel.WARNING, ErrorMessagesFormatBuilder.getErrorWithParameters( + Messages.PARAMETER_NAME_NOT_ALIGNED_WITH_GUIDELINES.getErrorMessage(), + ValidationUtil.getMessagePartAccordingToResourceType(resourceEntry), + "Availability Zone", + availabilityZoneName, resourceEntry.getKey()), + LoggerTragetServiceName.VALIDATE_AVAILABILITY_ZONE_NAME, + LoggerErrorDescription.NAME_NOT_ALIGNED_WITH_GUIDELINES); + } + } + } else { + globalContext.addMessage( + fileName, + ErrorLevel.WARNING, ErrorMessagesFormatBuilder + .getErrorWithParameters(Messages.MISSING_GET_PARAM.getErrorMessage(), + "availability_zone", resourceEntry.getKey()), + LoggerTragetServiceName.VALIDATE_AVAILABILITY_ZONE_NAME, + LoggerErrorDescription.MISSING_GET_PARAM); + } + } + mdcDataDebugMessage.debugExitMessage("file", fileName); + } + + private void validateNovaServerNameImageAndFlavor(String fileName, String envFileName, + Map.Entry<String, Resource> resourceEntry, + GlobalValidationContext globalContext) { + + mdcDataDebugMessage.debugEntryMessage("file", fileName); + + String novaName = + validateNovaServerNamingConvention(fileName, envFileName, resourceEntry, globalContext); + Map<String, String> legalNovaNamingConventionMap = + validateImageAndFlavorFromNovaServer(fileName, resourceEntry, globalContext); + + if (Objects.nonNull(novaName)) { + legalNovaNamingConventionMap.put("name", novaName); + } + + if (legalNovaNamingConventionMap.keySet().size() > 1) { + validateNovaServerNameImageAndFlavorSync(fileName, resourceEntry, + legalNovaNamingConventionMap, globalContext); + } + + mdcDataDebugMessage.debugExitMessage("file", fileName); + } + + private String validateNovaServerNamingConvention(String fileName, String envFileName, + Map.Entry<String, Resource> resourceEntry, + GlobalValidationContext globalContext) { + + mdcDataDebugMessage.debugEntryMessage("file", fileName); + + if (MapUtils.isEmpty(resourceEntry.getValue().getProperties())) { + mdcDataDebugMessage.debugExitMessage("file", fileName); + return null; + } + + mdcDataDebugMessage.debugExitMessage("file", fileName); + return checkIfNovaNameByGuidelines(fileName, envFileName, resourceEntry, globalContext); + } + + private Map<String, String> validateImageAndFlavorFromNovaServer(String fileName, + Map.Entry<String, Resource> resourceEntry, + GlobalValidationContext globalContext) { + + mdcDataDebugMessage.debugEntryMessage("file", fileName); + + if (MapUtils.isEmpty(resourceEntry.getValue().getProperties())) { + mdcDataDebugMessage.debugExitMessage("file", fileName); + return null; + } + + Pair<String, String> imagePair = new ImmutablePair<>("image", ".*_image_name"); + Pair<String, String> flavorPair = new ImmutablePair<>("flavor", ".*_flavor_name"); + List<Pair<String, String>> imageFlavorPairs = Arrays.asList(imagePair, flavorPair); + Map<String, Object> propertiesMap = resourceEntry.getValue().getProperties(); + Map<String, String> imageAndFlavorLegalNames = new HashMap<>(); + + for (Pair<String, String> imageOrFlavor : imageFlavorPairs) { + boolean isErrorInImageOrFlavor = + isErrorExistWhenValidatingImageOrFlavorNames(fileName, imageOrFlavor, resourceEntry, + propertiesMap, globalContext); + if (!isErrorInImageOrFlavor) { + Object nameValue = propertiesMap.get(imageOrFlavor.getKey()) == null ? null + : propertiesMap.get(imageOrFlavor.getKey()); + String imageOrFlavorName = ValidationUtil.getWantedNameFromPropertyValueGetParam(nameValue); + imageAndFlavorLegalNames.put(imageOrFlavor.getKey(), imageOrFlavorName); + } + } + + mdcDataDebugMessage.debugExitMessage("file", fileName); + return imageAndFlavorLegalNames; + } + + private String checkIfNovaNameByGuidelines(String fileName, String envFileName, + Map.Entry<String, Resource> resourceEntry, + GlobalValidationContext globalContext) { + if (MapUtils.isEmpty(resourceEntry.getValue().getProperties())) { + return null; + } + Object novaNameGetParam = getNovaServerName(resourceEntry); + String novaName = null; + if (nonNull(novaNameGetParam)) { + novaName = + checkNovaNameGetParamValueMap(fileName, novaNameGetParam, resourceEntry, globalContext); + checkIfNovaNameParameterInEnvIsStringOrList(fileName, envFileName, resourceEntry, novaName, + globalContext); + } else { + globalContext.addMessage( + fileName, + ErrorLevel.WARNING, ErrorMessagesFormatBuilder + .getErrorWithParameters(Messages.MISSING_GET_PARAM.getErrorMessage(), + "nova server name", resourceEntry.getKey()), + LoggerTragetServiceName.VALIDATE_NOVA_SERVER_NAME, + LoggerErrorDescription.MISSING_GET_PARAM); + } + + return novaName; + } + + private boolean isErrorExistWhenValidatingImageOrFlavorNames(String fileName, + Pair<String, String> propertyNameAndRegex, + Map.Entry<String, Resource> resourceEntry, + Map<String, Object> propertiesMap, + GlobalValidationContext globalContext) { + String propertyName = propertyNameAndRegex.getKey(); + Object nameValue = + propertiesMap.get(propertyName) == null ? null : propertiesMap.get(propertyName); + String[] regexList = new String[]{propertyNameAndRegex.getValue()}; + + if (nonNull(nameValue)) { + if (nameValue instanceof Map) { + if (ValidationUtil.validateMapPropertyValue(fileName, resourceEntry, globalContext, + propertyName, + nameValue, regexList)) { + return true; + } + } else { + globalContext.addMessage( + fileName, + ErrorLevel.WARNING, ErrorMessagesFormatBuilder + .getErrorWithParameters(Messages.MISSING_GET_PARAM.getErrorMessage(), propertyName, + resourceEntry.getKey()), + LoggerTragetServiceName.VALIDATE_IMAGE_AND_FLAVOR_NAME, + LoggerErrorDescription.MISSING_GET_PARAM); + return true; + } + + return false; + } + return false; + } + + private Object getNovaServerName(Map.Entry<String, Resource> resourceEntry) { + Object novaServerName = resourceEntry.getValue().getProperties().get("name"); + Map novaNameMap; + if (nonNull(novaServerName)) { + if (novaServerName instanceof Map) { + novaNameMap = (Map) novaServerName; + return novaNameMap.get(ResourceReferenceFunctions.GET_PARAM.getFunction()) == null ? null + : novaNameMap.get(ResourceReferenceFunctions.GET_PARAM.getFunction()); + } + } + return null; + } + + @SuppressWarnings("unchecked") + private String checkNovaNameGetParamValueMap(String fileName, Object getParamValue, + Map.Entry<String, Resource> resourceEntry, + GlobalValidationContext globalContext) { + if (getParamValue instanceof List) { + List<Object> getParamNameList = (List) getParamValue; + String[] regexName = new String[]{".*_names"}; + return isNovaNameAsListLegal(fileName, getParamNameList, regexName, resourceEntry, + globalContext); + } else if (getParamValue instanceof String) { + String[] regexName = new String[]{".*_name_(\\d+)"}; + return isNovaNameAsStringLegal(fileName, (String) getParamValue, regexName, resourceEntry, + globalContext); + } + + return null; + } + + private void checkIfNovaNameParameterInEnvIsStringOrList(String fileName, String envFileName, + Map.Entry<String, Resource> resourceEntry, + String novaServerName, + GlobalValidationContext globalContext) { + if (nonNull(envFileName)) { + Environment environment = ValidationUtil.validateEnvContent(envFileName, globalContext); + + if (environment != null && MapUtils.isNotEmpty(environment.getParameters())) { + Object novaServerNameEnvValue = + environment.getParameters().containsKey(novaServerName) ? environment.getParameters() + .get(novaServerName) : null; + if (Objects.nonNull(novaServerNameEnvValue)) { + if (!DefinedHeatParameterTypes + .isNovaServerEnvValueIsFromRightType(novaServerNameEnvValue)) { + globalContext.addMessage( + fileName, + ErrorLevel.WARNING, ErrorMessagesFormatBuilder.getErrorWithParameters( + Messages.PARAMETER_NAME_NOT_ALIGNED_WITH_GUIDELINES.getErrorMessage(), "Server", + "Name", novaServerNameEnvValue.toString(), resourceEntry.getKey()), + LoggerTragetServiceName.VALIDATE_NOVA_SERVER_NAME, + LoggerErrorDescription.NAME_NOT_ALIGNED_WITH_GUIDELINES); + } + } + } + } + } + + private String isNovaNameAsListLegal(String fileName, List<Object> getParamNameList, + String[] regexName, + Map.Entry<String, Resource> resourceEntry, + GlobalValidationContext globalContext) { + + if (getParamNameList.size() != 2 || !ValidationUtil.evalPattern(getParamNameList.get(0), + regexName)) { + globalContext.addMessage( + fileName, + ErrorLevel.WARNING, + ErrorMessagesFormatBuilder.getErrorWithParameters( + Messages.PARAMETER_NAME_NOT_ALIGNED_WITH_GUIDELINES.getErrorMessage(), "Server", + "name", getParamNameList.toString(), resourceEntry.getKey()), + LoggerTragetServiceName.VALIDATE_NOVA_SERVER_NAME, + LoggerErrorDescription.NAME_NOT_ALIGNED_WITH_GUIDELINES); + return null; + } + + return (String) getParamNameList.get(0); + } + + private String isNovaNameAsStringLegal(String fileName, String novaName, String[] regexName, + Map.Entry<String, Resource> resourceEntry, + GlobalValidationContext globalContext) { + if (!ValidationUtil.evalPattern(novaName, regexName)) { + globalContext.addMessage( + fileName, + ErrorLevel.WARNING, + ErrorMessagesFormatBuilder.getErrorWithParameters( + Messages.PARAMETER_NAME_NOT_ALIGNED_WITH_GUIDELINES.getErrorMessage(), "Server", + "name", novaName, resourceEntry.getKey()), + LoggerTragetServiceName.VALIDATE_NOVA_SERVER_NAME, + LoggerErrorDescription.NAME_NOT_ALIGNED_WITH_GUIDELINES); + return null; + } + return novaName; + } + + private void validateNovaServerNameImageAndFlavorSync(String fileName, + Map.Entry<String, Resource> resourceEntry, + Map<String, String> legalNovaNamingConventionNames, + GlobalValidationContext globalContext) { + + mdcDataDebugMessage.debugEntryMessage("file", fileName); + + List<String> vmNames = new LinkedList<>(); + + for (Map.Entry<String, String> nameEntry : legalNovaNamingConventionNames.entrySet()) { + vmNames.add(getVmName(nameEntry.getValue(), nameEntry.getKey())); + } + + vmNames.removeIf(VMName -> VMName == null); + + if (!isVmNameSync(vmNames)) { + globalContext.addMessage( + fileName, + ErrorLevel.WARNING, + ErrorMessagesFormatBuilder.getErrorWithParameters( + Messages.NOVA_NAME_IMAGE_FLAVOR_NOT_CONSISTENT.getErrorMessage(), + resourceEntry.getKey()), + LoggerTragetServiceName.VALIDATE_IMAGE_AND_FLAVOR_NAME, + LoggerErrorDescription.NAME_NOT_ALIGNED_WITH_GUIDELINES); + } + mdcDataDebugMessage.debugExitMessage("file", fileName); + } + + private String getVmName(String nameToGetVmNameFrom, String stringToGetIndexOf) { + int vmIndex = + nameToGetVmNameFrom == null ? -1 : nameToGetVmNameFrom.indexOf(stringToGetIndexOf); + String vmName = vmIndex < 0 ? null + : trimNonAlphaNumericCharactersFromEndOfString(nameToGetVmNameFrom.substring(0, vmIndex)); + + return vmName; + + } + + private boolean isVmNameSync(List<String> namesToCompare) { + int size = namesToCompare.size(); + for (int i = 0; i < size - 1; i++) { + if (!namesToCompare.get(i).equals(namesToCompare.get(i + 1))) { + return false; + } + } + return true; + } + + private String trimNonAlphaNumericCharactersFromEndOfString(String toTrim) { + int stringSize = toTrim.length(); + int stringLength = stringSize - 1; + String[] regexList = new String[]{"[^a-zA-Z0-9]"}; + + while (stringLength >= 0) { + if (!ValidationUtil.evalPattern(String.valueOf(toTrim.charAt(stringLength)), regexList)) { + break; + } + stringLength--; + } + + return toTrim.substring(0, stringLength + 1); + } +} diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/tos/ContrailResourcesMappingTo.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/tos/ContrailResourcesMappingTo.java new file mode 100644 index 0000000000..f351af0992 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/tos/ContrailResourcesMappingTo.java @@ -0,0 +1,118 @@ +/*- + * ============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.validation.tos; + +import org.apache.commons.collections4.MapUtils; + +import java.util.ArrayList; +import java.util.HashMap; +import java.util.List; +import java.util.Map; + + +public class ContrailResourcesMappingTo { + private Map<String, List<String>> contrailV1Resources; + private Map<String, List<String>> contrailV2Resources; + + /** + * Add ContrailV1Resource. + * + * @param fileName the file name + * @param resourceName the resource name + */ + public void addContrailV1Resource(String fileName, String resourceName) { + if (MapUtils.isEmpty(contrailV1Resources)) { + contrailV1Resources = new HashMap<>(); + } + contrailV1Resources.putIfAbsent(fileName, new ArrayList<>()); + contrailV1Resources.get(fileName).add(resourceName); + } + + /** + * Add ContrailV1Resource. + * + * @param fileName the file name + * @param resourceName the resource name + */ + public void addContrailV2Resource(String fileName, String resourceName) { + if (MapUtils.isEmpty(contrailV2Resources)) { + contrailV2Resources = new HashMap<>(); + } + contrailV2Resources.putIfAbsent(fileName, new ArrayList<>()); + contrailV2Resources.get(fileName).add(resourceName); + } + + public void addAll(ContrailResourcesMappingTo contrailResourcesMappingTo) { + addContrailV1Resources(contrailResourcesMappingTo.getContrailV1Resources()); + addContrailV2Resources(contrailResourcesMappingTo.getContrailV2Resources()); + } + + public String fetchContrailV1Resources() { + return fetchContrailResources(contrailV1Resources); + } + + public String fetchContrailV2Resources() { + return fetchContrailResources(contrailV2Resources); + } + + private void addContrailV1Resources(Map<String, List<String>> contrailV1Resources) { + if (!MapUtils.isEmpty(contrailV1Resources)) { + for (Map.Entry<String, List<String>> fileResourcesEntry : contrailV1Resources.entrySet()) { + for (String resourceName : fileResourcesEntry.getValue()) { + this.addContrailV1Resource(fileResourcesEntry.getKey(), resourceName); + } + } + } + } + + private void addContrailV2Resources(Map<String, List<String>> contrailV2Resources) { + if (!MapUtils.isEmpty(contrailV2Resources)) { + for (Map.Entry<String, List<String>> fileResourcesEntry : contrailV2Resources.entrySet()) { + for (String resourceName : fileResourcesEntry.getValue()) { + this.addContrailV2Resource(fileResourcesEntry.getKey(), resourceName); + } + } + } + } + + private String fetchContrailResources(Map<String, List<String>> contrailResources) { + StringBuilder buffer = new StringBuilder(); + if (MapUtils.isEmpty(contrailResources)) { + return ""; + } + for (Map.Entry<String, List<String>> fileResourcesEntry : contrailResources.entrySet()) { + buffer.append(" file '").append(fileResourcesEntry.getKey()).append("' , resources :"); + for (String resourceName : fileResourcesEntry.getValue()) { + buffer.append("'").append(resourceName).append("', "); + } + } + buffer.deleteCharAt(buffer.lastIndexOf(",")); + return buffer.toString(); + } + + public Map<String, List<String>> getContrailV1Resources() { + return contrailV1Resources; + } + + public Map<String, List<String>> getContrailV2Resources() { + return contrailV2Resources; + } +} diff --git a/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/type/ValidatorConstants.java b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/type/ValidatorConstants.java new file mode 100644 index 0000000000..d512fb6cb3 --- /dev/null +++ b/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/type/ValidatorConstants.java @@ -0,0 +1,10 @@ +package org.openecomp.sdc.validation.type; + +/** + * Created by TALIO on 2/22/2017. + */ +public class ValidatorConstants { + public static final String Security_Group = "SecurityGroup"; + public static final String Server_Group = "ServerGroup"; + public static final String Network_Policy = "NetworkPolicy"; +} |