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