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