280b723dd87d2f5c259c47228beaa7c9f86e77a8
[sdc.git] /
1 package org.openecomp.sdc.validation.impl.validators.namingconvention;
2
3 import org.apache.commons.collections4.CollectionUtils;
4 import org.apache.commons.collections4.MapUtils;
5 import org.apache.commons.lang3.tuple.ImmutablePair;
6 import org.apache.commons.lang3.tuple.Pair;
7 import org.openecomp.core.validation.ErrorMessageCode;
8 import org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder;
9 import org.openecomp.core.validation.types.GlobalValidationContext;
10 import org.openecomp.sdc.common.errors.Messages;
11 import org.openecomp.sdc.datatypes.error.ErrorLevel;
12 import org.openecomp.sdc.heat.datatypes.model.Resource;
13 import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage;
14 import org.openecomp.sdc.logging.types.LoggerErrorDescription;
15 import org.openecomp.sdc.logging.types.LoggerTragetServiceName;
16 import org.openecomp.sdc.validation.ResourceValidator;
17 import org.openecomp.sdc.validation.ValidationContext;
18 import org.openecomp.sdc.validation.util.ValidationUtil;
19
20 import java.util.Arrays;
21 import java.util.List;
22 import java.util.Map;
23 import java.util.Objects;
24 import java.util.Optional;
25 import java.util.regex.Pattern;
26
27 import static java.util.Objects.nonNull;
28
29 /**
30  * Created by TALIO on 2/24/2017.
31  */
32 public class ContrailServiceTemplateNamingConventionValidator implements ResourceValidator {
33   private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage();
34   private static final ErrorMessageCode ERROR_CODE_NST1 = new ErrorMessageCode("NST1");
35   private static final ErrorMessageCode ERROR_CODE_NST2 = new ErrorMessageCode("NST2");
36   private static final ErrorMessageCode ERROR_CODE_NST3 = new ErrorMessageCode("NST3");
37
38   @Override
39   public void validate(String fileName, Map.Entry<String, Resource> resourceEntry,
40                        GlobalValidationContext globalContext, ValidationContext validationContext) {
41     validateServiceTemplateImageAndFlavor(fileName, resourceEntry, globalContext);
42   }
43
44   private void validateServiceTemplateImageAndFlavor(String fileName,
45                                                      Map.Entry<String, Resource> entry,
46                                                      GlobalValidationContext globalContext) {
47
48     mdcDataDebugMessage.debugEntryMessage("file", fileName);
49
50     if (MapUtils.isEmpty(entry.getValue().getProperties())) {
51       return;
52     }
53
54     Pair<String, String> imagePair = new ImmutablePair<>("image_name", ".*_image_name");
55     Pair<String, String> flavorPair = new ImmutablePair<>("flavor", ".*_flavor_name");
56     List<Pair<String, String>> imageFlavorPairs = Arrays.asList(imagePair, flavorPair);
57
58     Map<String, Object> propertiesMap = entry.getValue().getProperties();
59
60     boolean errorExistValidatingImageOrFlavor = false;
61     for (Pair<String, String> imageOrFlavor : imageFlavorPairs) {
62       boolean errorExistWhenValidatingImageOrFlavorNames =
63               isErrorExistWhenValidatingImageOrFlavorNames(fileName, imageOrFlavor, entry,
64                       propertiesMap, globalContext);
65       errorExistValidatingImageOrFlavor =
66               errorExistValidatingImageOrFlavor || errorExistWhenValidatingImageOrFlavorNames;
67     }
68
69     if (!errorExistValidatingImageOrFlavor) {
70       validateServiceTemplatePropertiesValuesVmtypesAreIdentical(fileName, entry, globalContext,
71               propertiesMap);
72     }
73
74     mdcDataDebugMessage.debugExitMessage("file", fileName);
75   }
76
77   private void validateServiceTemplatePropertiesValuesVmtypesAreIdentical(String fileName,
78                                                                           Map.Entry<String, Resource> entry,
79                                                                           GlobalValidationContext globalContext,
80                                                                           Map<String, Object> propertiesMap) {
81
82     mdcDataDebugMessage.debugEntryMessage("file", fileName);
83
84     Pair<String, String> vmTypeImagePair = new ImmutablePair<>("image_name", "\\_image\\_name");
85     Pair<String, String> vmTypeFlavorPair = new ImmutablePair<>("flavor", "\\_flavor\\_name");
86     validatePropertiesValuesVmtypesAreIdentical(Arrays.asList(vmTypeImagePair, vmTypeFlavorPair),
87             fileName, entry, propertiesMap, globalContext);
88
89     mdcDataDebugMessage.debugExitMessage("file", fileName);
90   }
91
92   private void validatePropertiesValuesVmtypesAreIdentical(List<Pair> propertiesToMatch,
93                                                            String fileName,
94                                                            Map.Entry<String, Resource> resourceEntry,
95                                                            Map<String, Object> propertiesMap,
96                                                            GlobalValidationContext globalContext) {
97
98
99     mdcDataDebugMessage.debugEntryMessage("file", fileName);
100
101     if (CollectionUtils.isEmpty(propertiesToMatch)) {
102       return;
103     }
104
105     String previousPropertyValueValue = null;
106     for (Pair propertyToMatch : propertiesToMatch) {
107       Optional<String> propertyVmType =
108               extractVmTypeFromProperty(fileName, resourceEntry, propertiesMap, globalContext,
109                       propertyToMatch);
110       if (propertyVmType.isPresent()) {
111         String currentPropVmType = propertyVmType.get();
112         previousPropertyValueValue =
113                 handleFirstIteration(previousPropertyValueValue, currentPropVmType);
114         if (addWarningIfCurrentVmTypeIsDifferentFromPrevious(fileName, resourceEntry, globalContext,
115                 previousPropertyValueValue, currentPropVmType)) {
116           mdcDataDebugMessage.debugExitMessage("file", fileName);
117           return;
118         }
119       }
120     }
121
122     mdcDataDebugMessage.debugExitMessage("file", fileName);
123   }
124
125   private boolean addWarningIfCurrentVmTypeIsDifferentFromPrevious(String fileName,
126                                                                    Map.Entry<String, Resource> resourceEntry,
127                                                                    GlobalValidationContext globalContext,
128                                                                    String previousPropertyValueValue,
129                                                                    String currentPropVmType) {
130     if (!Objects.equals(previousPropertyValueValue, currentPropVmType)) {
131       globalContext.addMessage(fileName, ErrorLevel.WARNING, ErrorMessagesFormatBuilder
132                       .getErrorWithParameters(
133                               ERROR_CODE_NST1, Messages.CONTRAIL_VM_TYPE_NAME_NOT_ALIGNED_WITH_NAMING_CONVENSION
134                                       .getErrorMessage(),
135                               resourceEntry.getKey()),
136               LoggerTragetServiceName.VALIDATE_CONTRAIL_VM_NAME,
137               LoggerErrorDescription.NAME_NOT_ALIGNED_WITH_GUIDELINES);
138       return true;
139     }
140
141     return false;
142   }
143
144   private boolean isErrorExistWhenValidatingImageOrFlavorNames(String fileName,
145                                                                Pair<String, String> propertyNameAndRegex,
146                                                                Map.Entry<String, Resource> resourceEntry,
147                                                                Map<String, Object> propertiesMap,
148                                                                GlobalValidationContext globalContext) {
149     String propertyName = propertyNameAndRegex.getKey();
150     Object nameValue =
151             propertiesMap.get(propertyName) == null ? null : propertiesMap.get(propertyName);
152     String[] regexList = new String[]{propertyNameAndRegex.getValue()};
153     if (nonNull(nameValue)) {
154       if (nameValue instanceof Map) {
155         globalContext.setMessageCode(ERROR_CODE_NST3);
156         if (ValidationUtil.validateMapPropertyValue(fileName, resourceEntry, globalContext,
157                 propertyName,
158                 nameValue, regexList)) {
159           return true;
160         }
161       } else {
162         globalContext.addMessage(
163                 fileName,
164                 ErrorLevel.WARNING, ErrorMessagesFormatBuilder
165                         .getErrorWithParameters(
166                                 ERROR_CODE_NST2, Messages.MISSING_GET_PARAM.getErrorMessage(),
167                                 propertyName,
168                                 resourceEntry.getKey()),
169                 LoggerTragetServiceName.VALIDATE_IMAGE_AND_FLAVOR_NAME,
170                 LoggerErrorDescription.MISSING_GET_PARAM);
171         return true;
172       }
173
174       return false;
175     }
176     return false;
177   }
178
179
180   private Optional<String> extractVmTypeFromProperty(String fileName,
181                                                      Map.Entry<String, Resource> resourceEntry,
182                                                      Map<String, Object> propertiesMap,
183                                                      GlobalValidationContext globalContext,
184                                                      Pair propertyKeyRegex) {
185     String propertyName = (String) propertyKeyRegex.getKey();
186     Object propertyVal = propertiesMap.get(propertyName);
187     if (nonNull(propertyVal)) {
188       if (propertyVal instanceof Map) {
189         String propertyValFromGetParam = ValidationUtil.getWantedNameFromPropertyValueGetParam
190                 (propertyVal);
191         if (nonNull(propertyValFromGetParam)) {
192           Pattern pattern = Pattern.compile("" + propertyKeyRegex.getValue());
193           return Optional.ofNullable(pattern.split(propertyValFromGetParam)[0]);
194         }
195       } else {
196         globalContext.addMessage(
197                 fileName,
198                 ErrorLevel.WARNING, ErrorMessagesFormatBuilder
199                         .getErrorWithParameters(
200                                 ERROR_CODE_NST2, Messages.MISSING_GET_PARAM.getErrorMessage(),
201                                 propertyName,
202                                 resourceEntry.getKey()),
203                 LoggerTragetServiceName.VALIDATE_VM_SYNC_IN_IMAGE_FLAVOR,
204                 LoggerErrorDescription.MISSING_GET_PARAM);
205         return Optional.empty();
206       }
207     }
208     return Optional.empty();
209   }
210
211   private String handleFirstIteration(String previousPropertyValueValue, String currentPropVmType) {
212     if (Objects.isNull(previousPropertyValueValue)) {
213       previousPropertyValueValue = currentPropVmType;
214     }
215
216     return previousPropertyValueValue;
217   }
218 }