d9e035157864dfa433482e7f7b1781747f1b9e90
[sdc.git] /
1 package org.openecomp.sdc.validation.util;
2
3
4 import org.apache.commons.collections4.CollectionUtils;
5 import org.openecomp.core.utilities.json.JsonUtil;
6 import org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder;
7 import org.openecomp.core.validation.types.GlobalValidationContext;
8 import org.openecomp.sdc.common.errors.Messages;
9 import org.openecomp.sdc.common.utils.SdcCommon;
10 import org.openecomp.sdc.datatypes.error.ErrorLevel;
11 import org.openecomp.sdc.heat.datatypes.manifest.ManifestContent;
12 import org.openecomp.sdc.heat.datatypes.model.Environment;
13 import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate;
14 import org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes;
15 import org.openecomp.sdc.heat.datatypes.model.Resource;
16 import org.openecomp.sdc.heat.datatypes.model.ResourceReferenceFunctions;
17 import org.openecomp.sdc.heat.services.HeatStructureUtil;
18 import org.openecomp.sdc.logging.api.Logger;
19 import org.openecomp.sdc.logging.api.LoggerFactory;
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   private final static Logger log = (Logger) LoggerFactory.getLogger(ValidationUtil.class.getName());
41
42   public static void removeExposedResourcesCalledByGetResource(String fileName,
43                                                                Set<String> actualExposedResources,
44                                                                HeatOrchestrationTemplate
45                                                                    heatOrchestrationTemplate,
46                                                                GlobalValidationContext globalContext) {
47     Map<String, Resource> resourcesMap = heatOrchestrationTemplate.getResources();
48
49     for (Map.Entry<String, Resource> resourceEntry : resourcesMap.entrySet()) {
50       Set<String> referencedResources =
51           HeatStructureUtil.getReferencedValuesByFunctionName(fileName, ResourceReferenceFunctions
52               .GET_RESOURCE
53               .getFunction(), resourceEntry.getValue().getProperties(), globalContext);
54
55       removeExposedResourcesCalledByGetResource(referencedResources, actualExposedResources,
56           resourcesMap);
57     }
58   }
59
60   private static void removeExposedResourcesCalledByGetResource(Set<String> referencedResources,
61                                                                 Set<String>
62                                                                     actualExposedResources,
63                                                                 Map<String, Resource> resourcesMap) {
64     for (String referencedResourceName : referencedResources) {
65       Resource currResource = resourcesMap.get(referencedResourceName);
66       if (Objects.nonNull(currResource)) {
67         if (isExpectedToBeExposed(currResource.getType())) {
68           actualExposedResources.add(referencedResourceName);
69         }
70       }
71     }
72   }
73
74   public static boolean isExpectedToBeExposed(String type) {
75     return HeatResourcesTypes.isResourceExpectedToBeExposed(type);
76   }
77
78   public static String getWantedNameFromPropertyValueGetParam(Object value) {
79     Set<String> paramName = HeatStructureUtil
80         .getReferencedValuesByFunctionName(null, ResourceReferenceFunctions.GET_PARAM.getFunction(),
81             value, null);
82     if (paramName != null && CollectionUtils.isNotEmpty(paramName)) {
83       return (String) paramName.toArray()[0];
84     }
85     return null;
86   }
87
88   public static boolean evalPattern(Object paramVal, String[] regexList) {
89     String value = "";
90     if (paramVal instanceof String) {
91       value = ((String) paramVal);
92     }
93     if (paramVal instanceof Integer) {
94       value = paramVal.toString();
95     }
96     return evalPattern(value, regexList);
97   }
98
99   private static boolean evalPattern(String paramVal, String[] regexList) {
100
101     for (String regex : regexList) {
102       if (Pattern.matches(regex, paramVal)) {
103         return true;
104       }
105     }
106
107     return false;
108   }
109
110   public static String getMessagePartAccordingToResourceType(Map.Entry<String, Resource>
111                                                              resourceEntry) {
112     HeatResourcesTypes resourcesType =
113         HeatResourcesTypes.findByHeatResource(resourceEntry.getValue().getType());
114     if (resourcesType == HeatResourcesTypes.NOVA_SERVER_RESOURCE_TYPE) {
115       return "Server";
116     } else if (resourcesType == HeatResourcesTypes.CONTRAIL_SERVICE_TEMPLATE) {
117       return "Service Template";
118     } else if (resourcesType == HeatResourcesTypes.CONTRAIL_SERVICE_INSTANCE) {
119       return "Service Instance";
120     } else {
121       return "";
122     }
123   }
124
125   public static Environment validateEnvContent(String envFileName,
126                                          GlobalValidationContext globalContext) {
127
128     mdcDataDebugMessage.debugEntryMessage("file", envFileName);
129
130     Environment envContent;
131     try {
132       Optional<InputStream> fileContent = globalContext.getFileContent(envFileName);
133       if (fileContent.isPresent()) {
134         envContent = new YamlUtil().yamlToObject(fileContent.get(), Environment.class);
135       } else {
136         MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_API,
137             LoggerTragetServiceName.VALIDATE_ENV_FILE, ErrorLevel.ERROR.name(),
138             LoggerErrorCode.DATA_ERROR.getErrorCode(), LoggerErrorDescription.EMPTY_FILE);
139         throw new Exception("The file '" + envFileName + "' has no content");
140       }
141     } catch (Exception exception) {
142       log.debug("",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(globalContext.getMessageCode(),
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       log.debug("",exception);
192       MdcDataErrorMessage.createErrorMessageAndUpdateMdc(LoggerConstants.TARGET_ENTITY_API,
193           LoggerTragetServiceName.VALIDATE_MANIFEST_CONTENT, ErrorLevel.ERROR.name(),
194           LoggerErrorCode.DATA_ERROR.getErrorCode(), LoggerErrorDescription.INVALID_MANIFEST);
195       throw new RuntimeException("Can't load manifest file for Heat Validator");
196     }
197
198     return manifestContent;
199   }
200
201   public static String getParserExceptionReason(Exception exception) {
202     String reason;
203
204     if (exception.getCause() != null && exception.getCause().getCause() != null) {
205       reason = exception.getCause().getCause().getMessage();
206     } else if (exception.getCause() != null) {
207       reason = exception.getCause().getMessage();
208     } else {
209       reason = Messages.GENERAL_HEAT_PARSER_ERROR.getErrorMessage();
210     }
211     return reason;
212   }
213
214   public static HeatOrchestrationTemplate checkHeatOrchestrationPreCondition(String fileName,
215                                                                          GlobalValidationContext globalContext) {
216
217     mdcDataDebugMessage.debugEntryMessage("file", fileName);
218
219     HeatOrchestrationTemplate heatOrchestrationTemplate;
220     try {
221       Optional<InputStream> fileContent = globalContext.getFileContent(fileName);
222       if (fileContent.isPresent()) {
223         heatOrchestrationTemplate =
224             new YamlUtil().yamlToObject(fileContent.get(), HeatOrchestrationTemplate.class);
225       } else {
226         heatOrchestrationTemplate = null;
227       }
228     } catch (Exception exception) {
229       globalContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder
230               .getErrorWithParameters(globalContext.getMessageCode(),
231                       Messages.INVALID_HEAT_FORMAT_REASON.getErrorMessage()
232                       , getParserExceptionReason(exception)),
233           LoggerTragetServiceName.VALIDATE_HEAT_FORMAT,
234           LoggerErrorDescription.INVALID_HEAT_FORMAT);
235       mdcDataDebugMessage.debugExitMessage("file", fileName);
236       return null;
237     }
238     mdcDataDebugMessage.debugExitMessage("file", fileName);
239     return heatOrchestrationTemplate;
240   }
241
242
243 }