db1d9eac880bd1cc66f79ac0e4d6fefc364890ed
[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.errors.SdcRuntimeException;
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.logging.api.Logger;
20 import org.openecomp.sdc.logging.api.LoggerFactory;
21 import org.openecomp.sdc.logging.types.LoggerErrorDescription;
22 import org.openecomp.sdc.logging.types.LoggerTragetServiceName;
23 import org.openecomp.sdc.tosca.services.YamlUtil;
24
25 import java.io.InputStream;
26 import java.util.Map;
27 import java.util.Objects;
28 import java.util.Optional;
29 import java.util.Set;
30 import java.util.regex.Pattern;
31
32 import static java.util.Objects.nonNull;
33
34 public class ValidationUtil {
35   private static final Logger LOG = LoggerFactory.getLogger(ValidationUtil.class.getName());
36
37   private ValidationUtil(){}
38
39   public static void removeExposedResourcesCalledByGetResource(String fileName,
40                                                                Set<String> actualExposedResources,
41                                                                HeatOrchestrationTemplate
42                                                                    heatOrchestrationTemplate,
43                                                                GlobalValidationContext globalContext) {
44     Map<String, Resource> resourcesMap = heatOrchestrationTemplate.getResources();
45
46     for (Map.Entry<String, Resource> resourceEntry : resourcesMap.entrySet()) {
47       Set<String> referencedResources =
48           HeatStructureUtil.getReferencedValuesByFunctionName(fileName, ResourceReferenceFunctions
49               .GET_RESOURCE
50               .getFunction(), resourceEntry.getValue().getProperties(), globalContext);
51
52       removeExposedResourcesCalledByGetResource(referencedResources, actualExposedResources,
53           resourcesMap);
54     }
55   }
56
57   private static void removeExposedResourcesCalledByGetResource(Set<String> referencedResources,
58                                                                 Set<String>
59                                                                     actualExposedResources,
60                                                                 Map<String, Resource> resourcesMap) {
61     for (String referencedResourceName : referencedResources) {
62       Resource currResource = resourcesMap.get(referencedResourceName);
63       if (Objects.nonNull(currResource) && isExpectedToBeExposed(currResource.getType())) {
64           actualExposedResources.add(referencedResourceName);
65       }
66     }
67   }
68
69   public static boolean isExpectedToBeExposed(String type) {
70     return HeatResourcesTypes.isResourceExpectedToBeExposed(type);
71   }
72
73   public static String getWantedNameFromPropertyValueGetParam(Object value) {
74     Set<String> paramName = HeatStructureUtil
75         .getReferencedValuesByFunctionName(null, ResourceReferenceFunctions.GET_PARAM.getFunction(),
76             value, null);
77     if (paramName != null && CollectionUtils.isNotEmpty(paramName)) {
78       return (String) paramName.toArray()[0];
79     }
80     return null;
81   }
82
83   public static boolean evalPattern(Object paramVal, String[] regexList) {
84     String value = "";
85     if (paramVal instanceof String) {
86       value = (String) paramVal;
87     }
88     if (paramVal instanceof Integer) {
89       value = paramVal.toString();
90     }
91     return evalPattern(value, regexList);
92   }
93
94   private static boolean evalPattern(String paramVal, String[] regexList) {
95
96     for (String regex : regexList) {
97       if (Pattern.matches(regex, paramVal)) {
98         return true;
99       }
100     }
101
102     return false;
103   }
104
105   public static String getMessagePartAccordingToResourceType(Map.Entry<String, Resource>
106                                                              resourceEntry) {
107     HeatResourcesTypes resourcesType =
108         HeatResourcesTypes.findByHeatResource(resourceEntry.getValue().getType());
109     if (resourcesType == HeatResourcesTypes.NOVA_SERVER_RESOURCE_TYPE) {
110       return "Server";
111     } else if (resourcesType == HeatResourcesTypes.CONTRAIL_SERVICE_TEMPLATE) {
112       return "Service Template";
113     } else if (resourcesType == HeatResourcesTypes.CONTRAIL_SERVICE_INSTANCE) {
114       return "Service Instance";
115     } else {
116       return "";
117     }
118   }
119
120   public static Environment validateEnvContent(String envFileName,
121                                          GlobalValidationContext globalContext) {
122     Environment envContent;
123     try {
124       Optional<InputStream> fileContent = globalContext.getFileContent(envFileName);
125       if (fileContent.isPresent()) {
126         envContent = new YamlUtil().yamlToObject(fileContent.get(), Environment.class);
127       } else {
128         throw new Exception("The file '" + envFileName + "' has no content");
129       }
130     } catch (Exception exception) {
131       LOG.debug("",exception);
132       return null;
133     }
134     return envContent;
135   }
136
137   public static boolean validateMapPropertyValue(String fileName,
138                                            Map.Entry<String, Resource> resourceEntry,
139                                            GlobalValidationContext globalContext,
140                                            String propertyName, Object nameValue,
141                                            String[] regexList) {
142     String propertyValue = getWantedNameFromPropertyValueGetParam(nameValue);
143     if (nonNull(propertyValue) && !evalPattern(propertyValue, regexList)) {
144         globalContext.addMessage(
145             fileName,
146             ErrorLevel.WARNING,
147             ErrorMessagesFormatBuilder.getErrorWithParameters(globalContext.getMessageCode(),
148                 Messages.PARAMETER_NAME_NOT_ALIGNED_WITH_GUIDELINES.getErrorMessage(),
149                 getMessagePartAccordingToResourceType(resourceEntry), propertyName, propertyValue,
150                 resourceEntry.getKey()),
151             LoggerTragetServiceName.VALIDATE_IMAGE_AND_FLAVOR_NAME,
152             LoggerErrorDescription.NAME_NOT_ALIGNED_WITH_GUIDELINES);
153         return true;
154       }
155     return false;
156   }
157
158   public static ManifestContent validateManifest(GlobalValidationContext globalContext) {
159     Optional<InputStream> manifest = globalContext.getFileContent(SdcCommon.MANIFEST_NAME);
160     if (!manifest.isPresent()) {
161       throw new RuntimeException("Can't load manifest file for Heat Validator");
162     }
163     ManifestContent manifestContent;
164     try {
165       manifestContent = JsonUtil.json2Object(manifest.get(), ManifestContent.class);
166     } catch (Exception exception) {
167       LOG.debug("",exception);
168       throw new SdcRuntimeException("Can't load manifest file for Heat Validator");
169     }
170
171     return manifestContent;
172   }
173
174   public static String getParserExceptionReason(Exception exception) {
175     String reason;
176
177     if (exception.getCause() != null && exception.getCause().getCause() != null) {
178       reason = exception.getCause().getCause().getMessage();
179     } else if (exception.getCause() != null) {
180       reason = exception.getCause().getMessage();
181     } else {
182       reason = Messages.GENERAL_HEAT_PARSER_ERROR.getErrorMessage();
183     }
184     return reason;
185   }
186
187   public static HeatOrchestrationTemplate checkHeatOrchestrationPreCondition(String fileName,
188                                                                          GlobalValidationContext globalContext) {
189     HeatOrchestrationTemplate heatOrchestrationTemplate;
190     try {
191       Optional<InputStream> fileContent = globalContext.getFileContent(fileName);
192       if (fileContent.isPresent()) {
193         heatOrchestrationTemplate =
194             new YamlUtil().yamlToObject(fileContent.get(), HeatOrchestrationTemplate.class);
195       } else {
196         heatOrchestrationTemplate = null;
197       }
198     } catch (Exception exception) {
199       globalContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder
200               .getErrorWithParameters(globalContext.getMessageCode(),
201                       Messages.INVALID_HEAT_FORMAT_REASON.getErrorMessage()
202                       , getParserExceptionReason(exception)),
203           LoggerTragetServiceName.VALIDATE_HEAT_FORMAT,
204           LoggerErrorDescription.INVALID_HEAT_FORMAT);
205       return null;
206     }
207     return heatOrchestrationTemplate;
208   }
209
210
211 }