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