summaryrefslogtreecommitdiffstats
path: root/openecomp-be/lib/openecomp-sdc-validation-lib/openecomp-sdc-validation-impl/src/main/java/org/openecomp/sdc/validation/impl/validators/namingconvention/VirtualMachineInterfaceGuidelineValidator.java
blob: 4347d6cef95232ebbe18c6b82d13ade266eb5ba8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
package org.openecomp.sdc.validation.impl.validators.namingconvention;

import static org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_MACHINE_INTERFACE_RESOURCE_TYPE;
import static org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes.NEUTRON_PORT_RESOURCE_TYPE;
import static org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes.NOVA_SERVER_RESOURCE_TYPE;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.Optional;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;

import org.openecomp.core.validation.ErrorMessageCode;
import org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder;
import org.openecomp.core.validation.types.GlobalValidationContext;
import org.openecomp.sdc.datatypes.error.ErrorLevel;
import org.openecomp.sdc.heat.datatypes.DefinedHeatParameterTypes;
import org.openecomp.sdc.heat.datatypes.model.Resource;
import org.openecomp.sdc.heat.services.HeatConstants;
import org.openecomp.sdc.heat.services.HeatResourceUtil;
import org.openecomp.sdc.heat.services.HeatStructureUtil;
import org.openecomp.sdc.validation.ResourceValidator;
import org.openecomp.sdc.validation.ValidationContext;
import org.openecomp.sdc.validation.type.NamingConventionValidationContext;

public class VirtualMachineInterfaceGuidelineValidator implements ResourceValidator {
  private static final ErrorMessageCode ERROR_CODE_VLAN_GUIDELINE1 = new ErrorMessageCode
      ("VlANG1");
  private static final ErrorMessageCode ERROR_CODE_VLAN_GUIDELINE2 = new ErrorMessageCode
      ("VlANG2");
  private static final ErrorMessageCode ERROR_CODE_VLAN_GUIDELINE3 = new ErrorMessageCode
      ("VlANG3");


  @Override
  public void validate(String fileName, Map.Entry<String, Resource> resourceEntry,
                       GlobalValidationContext globalContext, ValidationContext validationContext) {
      NamingConventionValidationContext namingConventionValidationContext =
          (NamingConventionValidationContext) validationContext;
      Optional<Object> tagPropertyValue = getVlanTagPropertyValue(resourceEntry.getValue());

      if (tagPropertyValue.isPresent()) {
        validateModeledByResourceGroup(fileName, resourceEntry, globalContext,
            namingConventionValidationContext);
        validateSingleVirtualMachineInterfaceInFile(fileName, globalContext,
            namingConventionValidationContext);
        validateSubInterfaceNamingConvention(fileName, resourceEntry, globalContext);
      }
  }

  private void validateModeledByResourceGroup(String fileName,
                                              Map.Entry<String, Resource> resourceEntry,
                                              GlobalValidationContext globalContext,
                                              NamingConventionValidationContext namingConventionValidationContext) {

    Object refsPropertyValue = resourceEntry.getValue().getProperties().get(HeatConstants.VMI_REFS_PROPERTY_NAME);
    if (Objects.isNull(refsPropertyValue)) {
      addViolationToContext(fileName, globalContext, ErrorLevel.WARNING, ERROR_CODE_VLAN_GUIDELINE1,
          Messages.VLAN_GUIDELINE_VALIDATION_NOT_MODELED_THROUGH_RESOURCE_GROUP, resourceEntry.getKey());
      return;
    }
    final boolean modeledThroughResourceGroup = isModeledThroughResourceGroup(fileName, globalContext,
            namingConventionValidationContext, refsPropertyValue);
    if (!modeledThroughResourceGroup) {
      addViolationToContext(fileName, globalContext, ErrorLevel.WARNING, ERROR_CODE_VLAN_GUIDELINE1,
          Messages.VLAN_GUIDELINE_VALIDATION_NOT_MODELED_THROUGH_RESOURCE_GROUP, resourceEntry.getKey());
    }

  }


  private void validateSubInterfaceNamingConvention(String fileName, Map.Entry<String, Resource> resourceEntry,
                                                    GlobalValidationContext globalContext) {
    final String resourceId = resourceEntry.getKey();
    final Optional<String> networkRole = HeatResourceUtil.extractNetworkRoleFromSubInterfaceId(resourceId, resourceEntry
            .getValue().getType());
    if (!networkRole.isPresent()) {
      addViolationToContext(fileName, globalContext, ErrorLevel.WARNING, ERROR_CODE_VLAN_GUIDELINE3,
          Messages.VLAN_GUIDELINE_VALIDATION_NAMING_CONVENTION, resourceId);
    }
  }

  private void validateSingleVirtualMachineInterfaceInFile(String fileName,
                                                           GlobalValidationContext globalContext,
                                                           NamingConventionValidationContext
                                                               namingConventionValidationContext) {
    Set<String> forbiddenTypes = Stream.of(NOVA_SERVER_RESOURCE_TYPE.getHeatResource(),
        NEUTRON_PORT_RESOURCE_TYPE.getHeatResource()).collect(Collectors.toSet());

    final Map<String, Resource> resources =
        namingConventionValidationContext.getHeatOrchestrationTemplate().getResources();

    if ((countVlanResources(resources) > 1) || fileContainsNonVlanResources(resources,
        forbiddenTypes)) {
      addViolationToContext(fileName, globalContext, ErrorLevel.ERROR, ERROR_CODE_VLAN_GUIDELINE2,
          Messages.VLAN_GUIDELINE_VALIDATION_SINGLE_VLAN, fileName);
    }


  }

  private boolean fileContainsNonVlanResources(Map<String, Resource> resources,
                                               Set<String> forbiddenTypes) {
    for (Map.Entry<String, Resource> resourceEntry : resources.entrySet()) {
      if (forbiddenTypes.contains(resourceEntry.getValue().getType())) {
        return true;
      }
    }
    return false;
  }

  private int countVlanResources(Map<String, Resource> resources) {
    int numVlanResources = 0;
    for (Map.Entry<String, Resource> resourceEntry : resources.entrySet()) {
      final String resourceType = resourceEntry.getValue().getType();
      if (resourceType.equals
          (CONTRAIL_V2_VIRTUAL_MACHINE_INTERFACE_RESOURCE_TYPE.getHeatResource())) {
        numVlanResources++;
      }
    }

    return numVlanResources;
  }


  private void addViolationToContext(String fileName, GlobalValidationContext globalContext,
                                     ErrorLevel error, ErrorMessageCode errorCodeVlanGuideline1,
                                     Messages vlanGuidelineValidationNotModeledThroughResourceGroup,
                                     String key) {
    globalContext.addMessage(fileName, error, ErrorMessagesFormatBuilder
        .getErrorWithParameters(errorCodeVlanGuideline1,
            vlanGuidelineValidationNotModeledThroughResourceGroup.getErrorMessage(),
            key));
  }


  private Optional<Object> getVlanTagPropertyValue(Resource resource) {
    Object vmiProperties = resource.getProperties().get(HeatConstants.VMI_PROPERTIES_PROPERTY_NAME);
    if (Objects.nonNull(vmiProperties) && vmiProperties instanceof Map) {
      return Optional.ofNullable(((Map) vmiProperties)
          .get(HeatConstants.VMI_SUB_INTERFACE_VLAN_TAG_PROPERTY_NAME));
    }
    return Optional.empty();
  }


  /**
   * This method verifies whether the propertyValue is a list containing a single get_param
   * whose value is string
   *
   * @param fileName                          on which the validation is currently run
   * @param globalContext                     global validation context
   * @param namingConventionValidationContext heat resource validation context
   * @param propertyValue                     the value which is examined
   * @return whether  the propertyValue is a list containing a single get_param
   * whose value is string
   */
  private static boolean isModeledThroughResourceGroup(String fileName, GlobalValidationContext
      globalContext, NamingConventionValidationContext namingConventionValidationContext,
                                                       Object propertyValue) {
    final boolean isList = propertyValue instanceof List;
    if (!isList || ((List) propertyValue).size() != 1) {
      return false;
    }

    final Object listValue = ((List) propertyValue).get(0);

    final Set<String> getParamValues =
        HeatStructureUtil.getReferencedValuesByFunctionName(fileName, "get_param",
            listValue, globalContext);
    if (getParamValues.isEmpty()) {
      return false; //this is not a get_param
    }

    //validating get_param value
    return (getParamValues.size() == 1) &&
        validateGetParamValueOfType(getParamValues, namingConventionValidationContext,
            DefinedHeatParameterTypes.STRING.getType());

  }

  private static boolean validateGetParamValueOfType(Set<String> values,
                                                     NamingConventionValidationContext
                                                         namingConventionValidationContext,
                                                     String type) {

    return values.stream().anyMatch(e -> Objects.equals(
        namingConventionValidationContext.getHeatOrchestrationTemplate().getParameters().get(e)
            .getType(), type));
  }



  private enum Messages {
    VLAN_GUIDELINE_VALIDATION_NOT_MODELED_THROUGH_RESOURCE_GROUP("VLAN Resource will not be " +
        "translated as the VLAN Sub-interface [%s] is not modeled as resource group"),
    VLAN_GUIDELINE_VALIDATION_SINGLE_VLAN("There should not be any Compute Server Node, Port, " +
        "Parent Port in nested file [%s]"),
    VLAN_GUIDELINE_VALIDATION_NAMING_CONVENTION(
        "Network role associated with VLAN Sub-interface id[%s] is not following the naming convention");

    private final String errorMessage;

    Messages(String errorMessage) {
      this.errorMessage = errorMessage;
    }

    String getErrorMessage() {
      return errorMessage;
    }
  }


}