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