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