ee15df65cf65c9cf1503e3a8d21fb55d16c2e782
[sdc.git] / openecomp-be / lib / openecomp-sdc-validation-lib / openecomp-sdc-validation-sdk / src / main / java / org / openecomp / sdc / validation / util / ValidationUtil.java
1 package org.openecomp.sdc.validation.util;
2
3
4 import org.apache.commons.collections4.CollectionUtils;
5 import org.openecomp.core.utilities.CommonMethods;
6 import org.openecomp.core.utilities.json.JsonUtil;
7 import org.openecomp.core.utilities.yaml.YamlUtil;
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.common.utils.SdcCommon;
12 import org.openecomp.sdc.datatypes.configuration.ImplementationConfiguration;
13 import org.openecomp.sdc.datatypes.error.ErrorLevel;
14 import org.openecomp.sdc.heat.datatypes.manifest.ManifestContent;
15 import org.openecomp.sdc.heat.datatypes.model.Environment;
16 import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate;
17 import org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes;
18 import org.openecomp.sdc.heat.datatypes.model.Resource;
19 import org.openecomp.sdc.heat.datatypes.model.ResourceReferenceFunctions;
20 import org.openecomp.sdc.heat.services.HeatStructureUtil;
21 import org.openecomp.sdc.heat.services.manifest.ManifestUtil;
22 import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage;
23 import org.openecomp.sdc.logging.context.impl.MdcDataErrorMessage;
24 import org.openecomp.sdc.logging.types.LoggerConstants;
25 import org.openecomp.sdc.logging.types.LoggerErrorCode;
26 import org.openecomp.sdc.logging.types.LoggerErrorDescription;
27 import org.openecomp.sdc.logging.types.LoggerTragetServiceName;
28 import org.openecomp.sdc.validation.ResourceValidator;
29
30 import java.io.InputStream;
31 import java.util.Map;
32 import java.util.Objects;
33 import java.util.Optional;
34 import java.util.Set;
35 import java.util.regex.Pattern;
36
37 import static java.util.Objects.nonNull;
38
39 public class ValidationUtil {
40
41   private static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage();
42
43   public static void removeExposedResourcesCalledByGetResource(String fileName,
44                                                                Set<String> actualExposedResources,
45                                                                HeatOrchestrationTemplate
46                                                                    heatOrchestrationTemplate,
47                                                                GlobalValidationContext globalContext) {
48     Map<String, Resource> resourcesMap = heatOrchestrationTemplate.getResources();
49
50     for (Map.Entry<String, Resource> resourceEntry : resourcesMap.entrySet()) {
51       Set<String> referencedResources =
52           HeatStructureUtil.getReferencedValuesByFunctionName(fileName, ResourceReferenceFunctions
53               .GET_RESOURCE
54               .getFunction(), resourceEntry.getValue().getProperties(), globalContext);
55
56       removeExposedResourcesCalledByGetResource(referencedResources, actualExposedResources,
57           resourcesMap);
58     }
59   }
60
61   private static void removeExposedResourcesCalledByGetResource(Set<String> referencedResources,
62                                                                 Set<String>
63                                                                     actualExposedResources,
64                                                                 Map<String, Resource> resourcesMap) {
65     for (String referencedResourceName : referencedResources) {
66       Resource currResource = resourcesMap.get(referencedResourceName);
67       if (Objects.nonNull(currResource)) {
68         if (isExpectedToBeExposed(currResource.getType())) {
69           actualExposedResources.add(referencedResourceName);
70         }
71       }
72     }
73   }
74
75   public static boolean isExpectedToBeExposed(String type) {
76     return HeatResourcesTypes.isResourceExpectedToBeExposed(type);
77   }
78
79   public static String getWantedNameFromPropertyValueGetParam(Object value) {
80     Set<String> paramName = HeatStructureUtil
81         .getReferencedValuesByFunctionName(null, ResourceReferenceFunctions.GET_PARAM.getFunction(),
82             value, null);
83     if (paramName != null && CollectionUtils.isNotEmpty(paramName)) {
84       return (String) paramName.toArray()[0];
85     }
86     return null;
87   }
88
89   public static boolean evalPattern(Object paramVal, String[] regexList) {
90     String value = "";
91     if (paramVal instanceof String) {
92       value = ((String) paramVal);
93     }
94     if (paramVal instanceof Integer) {
95       value = paramVal.toString();
96     }
97     return evalPattern(value, regexList);
98   }
99
100   private static boolean evalPattern(String paramVal, String[] regexList) {
101
102     for (String regex : regexList) {
103       if (Pattern.matches(regex, paramVal)) {
104         return true;
105       }
106     }
107
108     return false;
109   }
110
111   public static String getMessagePartAccordingToResourceType(Map.Entry<String, Resource>
112                                                              resourceEntry) {
113     HeatResourcesTypes resourcesType =
114         HeatResourcesTypes.findByHeatResource(resourceEntry.getValue().getType());
115     if (resourcesType == HeatResourcesTypes.NOVA_SERVER_RESOURCE_TYPE) {
116       return "Server";
117     } else if (resourcesType == HeatResourcesTypes.CONTRAIL_SERVICE_TEMPLATE) {
118       return "Service Template";
119     } else if (resourcesType == HeatResourcesTypes.CONTRAIL_SERVICE_INSTANCE) {
120       return "Service Instance";
121     } else {
122       return "";
123     }
124   }
125
126   public static Environment validateEnvContent(String envFileName,
127                                          GlobalValidationContext globalContext) {
128
129     mdcDataDebugMessage.debugEntryMessage("file", envFileName);
130
131     Environment envContent;
132     try {
133       Optional<InputStream> fileContent = globalContext.getFileContent(envFileName);
134       if (fileContent.isPresent()) {
135         envContent = new YamlUtil().yamlToObject(fileContent.get(), Environment.class);
136       } else {
137         MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_API,
138             LoggerTragetServiceName.VALIDATE_ENV_FILE, ErrorLevel.ERROR.name(),
139             LoggerErrorCode.DATA_ERROR.getErrorCode(), LoggerErrorDescription.EMPTY_FILE);
140         throw new Exception("The file '" + envFileName + "' has no content");
141       }
142     } catch (Exception exception) {
143       mdcDataDebugMessage.debugExitMessage("file", envFileName);
144       return null;
145     }
146     mdcDataDebugMessage.debugExitMessage("file", envFileName);
147     return envContent;
148   }
149
150   public static boolean validateMapPropertyValue(String fileName,
151                                            Map.Entry<String, Resource> resourceEntry,
152                                            GlobalValidationContext globalContext,
153                                            String propertyName, Object nameValue,
154                                            String[] regexList) {
155
156     mdcDataDebugMessage.debugEntryMessage("file", fileName);
157
158     String propertyValue = getWantedNameFromPropertyValueGetParam(nameValue);
159     if (nonNull(propertyValue)) {
160       if (!evalPattern(propertyValue, regexList)) {
161         globalContext.addMessage(
162             fileName,
163             ErrorLevel.WARNING,
164             ErrorMessagesFormatBuilder.getErrorWithParameters(
165                 Messages.PARAMETER_NAME_NOT_ALIGNED_WITH_GUIDELINES.getErrorMessage(),
166                 getMessagePartAccordingToResourceType(resourceEntry), propertyName, propertyValue,
167                 resourceEntry.getKey()),
168             LoggerTragetServiceName.VALIDATE_IMAGE_AND_FLAVOR_NAME,
169             LoggerErrorDescription.NAME_NOT_ALIGNED_WITH_GUIDELINES);
170         mdcDataDebugMessage.debugExitMessage("file", fileName);
171         return true;
172       }
173     }
174
175     mdcDataDebugMessage.debugExitMessage("file", fileName);
176     return false;
177   }
178
179   public static ManifestContent checkValidationPreCondition(GlobalValidationContext globalContext) {
180     Optional<InputStream> manifest = globalContext.getFileContent(SdcCommon.MANIFEST_NAME);
181     if (!manifest.isPresent()) {
182       MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_API,
183           LoggerTragetServiceName.VALIDATE_MANIFEST_CONTENT, ErrorLevel.ERROR.name(),
184           LoggerErrorCode.DATA_ERROR.getErrorCode(), LoggerErrorDescription.MISSING_FILE);
185       throw new RuntimeException("Can't load manifest file for Heat Validator");
186     }
187     ManifestContent manifestContent;
188     try {
189       manifestContent = JsonUtil.json2Object(manifest.get(), ManifestContent.class);
190     } catch (Exception exception) {
191       MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_API,
192           LoggerTragetServiceName.VALIDATE_MANIFEST_CONTENT, ErrorLevel.ERROR.name(),
193           LoggerErrorCode.DATA_ERROR.getErrorCode(), LoggerErrorDescription.INVALID_MANIFEST);
194       throw new RuntimeException("Can't load manifest file for Heat Validator");
195     }
196
197     return manifestContent;
198   }
199
200   public static String getParserExceptionReason(Exception exception) {
201     String reason;
202
203     if (exception.getCause() != null && exception.getCause().getCause() != null) {
204       reason = exception.getCause().getCause().getMessage();
205     } else if (exception.getCause() != null) {
206       reason = exception.getCause().getMessage();
207     } else {
208       reason = Messages.GENERAL_HEAT_PARSER_ERROR.getErrorMessage();
209     }
210     return reason;
211   }
212
213   public static HeatOrchestrationTemplate checkHeatOrchestrationPreCondition(String fileName,
214                                                                          GlobalValidationContext globalContext) {
215
216     mdcDataDebugMessage.debugEntryMessage("file", fileName);
217
218     HeatOrchestrationTemplate heatOrchestrationTemplate;
219     try {
220       Optional<InputStream> fileContent = globalContext.getFileContent(fileName);
221       if (fileContent.isPresent()) {
222         heatOrchestrationTemplate =
223             new YamlUtil().yamlToObject(fileContent.get(), HeatOrchestrationTemplate.class);
224       } else {
225         heatOrchestrationTemplate = null;
226       }
227     } catch (Exception exception) {
228       globalContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder
229               .getErrorWithParameters(Messages.INVALID_HEAT_FORMAT_REASON.getErrorMessage(),
230                   getParserExceptionReason(exception)),
231           LoggerTragetServiceName.VALIDATE_HEAT_FORMAT,
232           LoggerErrorDescription.INVALID_HEAT_FORMAT);
233       mdcDataDebugMessage.debugExitMessage("file", fileName);
234       return null;
235     }
236     mdcDataDebugMessage.debugExitMessage("file", fileName);
237     return heatOrchestrationTemplate;
238   }
239
240   public static Set<String> validateManifest(ManifestContent manifestContent,
241                                       GlobalValidationContext globalContext) {
242
243     mdcDataDebugMessage.debugEntryMessage("file", SdcCommon.MANIFEST_NAME);
244
245     Set<String> baseFiles = ManifestUtil.getBaseFiles(manifestContent);
246     if (baseFiles == null || baseFiles.size() == 0) {
247       globalContext.addMessage(
248           SdcCommon.MANIFEST_NAME,
249           ErrorLevel.WARNING,
250           ErrorMessagesFormatBuilder
251               .getErrorWithParameters(Messages.MISSIN_BASE_HEAT_FILE.getErrorMessage()),
252           LoggerTragetServiceName.VALIDATE_BASE_FILE,
253           LoggerErrorDescription.MISSING_BASE_HEAT);
254     } else if (baseFiles.size() > 1) {
255       String baseFileList = getElementListAsString(baseFiles);
256       globalContext.addMessage(
257           SdcCommon.MANIFEST_NAME,
258           ErrorLevel.WARNING,
259           ErrorMessagesFormatBuilder
260               .getErrorWithParameters(Messages.MULTI_BASE_HEAT_FILE.getErrorMessage(),
261                   baseFileList),
262           LoggerTragetServiceName.VALIDATE_BASE_FILE,
263           LoggerErrorDescription.MULTI_BASE_HEAT);
264     }
265
266     mdcDataDebugMessage.debugExitMessage("file", SdcCommon.MANIFEST_NAME);
267     return baseFiles;
268   }
269
270   private static String getElementListAsString(Set<String> elementCollection) {
271
272     return "["
273         + CommonMethods.collectionToCommaSeparatedString(elementCollection)
274         +  "]";
275   }
276
277 }