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