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