6635604a39c0e6d01980e5d9b9df5e946604a15d
[sdc.git] /
1 /*
2  * Copyright © 2018 European Support Limited
3  *
4  * Licensed under the Apache License, Version 2.0 (the "License");
5  * you may not use this file except in compliance with the License.
6  * You may obtain a copy of the License at
7  *
8  *      http://www.apache.org/licenses/LICENSE-2.0
9  *
10  * Unless required by applicable law or agreed to in writing, software
11  * distributed under the License is distributed on an "AS IS" BASIS,
12  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13  * See the License for the specific language governing permissions and
14  * limitations under the License.
15 */
16
17 package org.openecomp.sdc.validation.util;
18
19 import static java.util.Objects.nonNull;
20
21 import java.io.InputStream;
22 import java.util.Map;
23 import java.util.Objects;
24 import java.util.Optional;
25 import java.util.Set;
26 import java.util.regex.Pattern;
27 import org.apache.commons.collections4.CollectionUtils;
28
29 import org.onap.sdc.tosca.services.YamlUtil;
30 import org.openecomp.core.utilities.json.JsonUtil;
31 import org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder;
32 import org.openecomp.core.validation.types.GlobalValidationContext;
33 import org.openecomp.sdc.common.errors.Messages;
34 import org.openecomp.sdc.common.errors.SdcRuntimeException;
35 import org.openecomp.sdc.common.utils.SdcCommon;
36 import org.openecomp.sdc.datatypes.error.ErrorLevel;
37 import org.openecomp.sdc.heat.datatypes.manifest.ManifestContent;
38 import org.openecomp.sdc.heat.datatypes.model.Environment;
39 import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate;
40 import org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes;
41 import org.openecomp.sdc.heat.datatypes.model.Resource;
42 import org.openecomp.sdc.heat.datatypes.model.ResourceReferenceFunctions;
43 import org.openecomp.sdc.heat.services.HeatStructureUtil;
44 import org.openecomp.sdc.logging.api.Logger;
45 import org.openecomp.sdc.logging.api.LoggerFactory;
46
47 public class ValidationUtil {
48   private static final Logger LOG = LoggerFactory.getLogger(ValidationUtil.class.getName());
49
50   private ValidationUtil(){}
51
52   public static void removeExposedResourcesCalledByGetResource(String fileName,
53                                                                Set<String> actualExposedResources,
54                                                                HeatOrchestrationTemplate
55                                                                    heatOrchestrationTemplate,
56                                                                GlobalValidationContext globalContext) {
57     Map<String, Resource> resourcesMap = heatOrchestrationTemplate.getResources();
58
59     for (Map.Entry<String, Resource> resourceEntry : resourcesMap.entrySet()) {
60       Set<String> referencedResources =
61           HeatStructureUtil.getReferencedValuesByFunctionName(fileName, ResourceReferenceFunctions
62               .GET_RESOURCE
63               .getFunction(), resourceEntry.getValue().getProperties(), globalContext);
64
65       removeExposedResourcesCalledByGetResource(referencedResources, actualExposedResources,
66           resourcesMap);
67     }
68   }
69
70   private static void removeExposedResourcesCalledByGetResource(Set<String> referencedResources,
71                                                                 Set<String>
72                                                                     actualExposedResources,
73                                                                 Map<String, Resource> resourcesMap) {
74     for (String referencedResourceName : referencedResources) {
75       Resource currResource = resourcesMap.get(referencedResourceName);
76       if (Objects.nonNull(currResource) && isExpectedToBeExposed(currResource.getType())) {
77           actualExposedResources.add(referencedResourceName);
78       }
79     }
80   }
81
82   public static boolean isExpectedToBeExposed(String type) {
83     return HeatResourcesTypes.isResourceExpectedToBeExposed(type);
84   }
85
86   public static String getWantedNameFromPropertyValueGetParam(Object value) {
87     Set<String> paramName = HeatStructureUtil
88         .getReferencedValuesByFunctionName(null, ResourceReferenceFunctions.GET_PARAM.getFunction(),
89             value, null);
90     if (paramName != null && CollectionUtils.isNotEmpty(paramName)) {
91       return (String) paramName.toArray()[0];
92     }
93     return null;
94   }
95
96   public static boolean evalPattern(Object paramVal, String[] regexList) {
97     String value = "";
98     if (paramVal instanceof String) {
99       value = (String) paramVal;
100     }
101     if (paramVal instanceof Integer) {
102       value = paramVal.toString();
103     }
104     return evalPattern(value, regexList);
105   }
106
107   private static boolean evalPattern(String paramVal, String[] regexList) {
108
109     for (String regex : regexList) {
110       if (Pattern.matches(regex, paramVal)) {
111         return true;
112       }
113     }
114
115     return false;
116   }
117
118   public static String getMessagePartAccordingToResourceType(Map.Entry<String, Resource>
119                                                              resourceEntry) {
120     HeatResourcesTypes resourcesType =
121         HeatResourcesTypes.findByHeatResource(resourceEntry.getValue().getType());
122     if (resourcesType == HeatResourcesTypes.NOVA_SERVER_RESOURCE_TYPE) {
123       return "Server";
124     } else if (resourcesType == HeatResourcesTypes.CONTRAIL_SERVICE_TEMPLATE) {
125       return "Service Template";
126     } else if (resourcesType == HeatResourcesTypes.CONTRAIL_SERVICE_INSTANCE) {
127       return "Service Instance";
128     } else {
129       return "";
130     }
131   }
132
133   public static Environment validateEnvContent(String envFileName,
134                                          GlobalValidationContext globalContext) {
135     Environment envContent;
136     try {
137       Optional<InputStream> fileContent = globalContext.getFileContent(envFileName);
138       if (fileContent.isPresent()) {
139         envContent = new YamlUtil().yamlToObject(fileContent.get(), Environment.class);
140       } else {
141         throw new Exception("The file '" + envFileName + "' has no content");
142       }
143     } catch (Exception exception) {
144       LOG.error("Invalid envFile name : " + envFileName, exception);
145       return null;
146     }
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     String propertyValue = getWantedNameFromPropertyValueGetParam(nameValue);
156     if (nonNull(propertyValue) && !evalPattern(propertyValue, regexList)) {
157         globalContext.addMessage(
158             fileName,
159             ErrorLevel.WARNING,
160             ErrorMessagesFormatBuilder.getErrorWithParameters(globalContext.getMessageCode(),
161                 Messages.PARAMETER_NAME_NOT_ALIGNED_WITH_GUIDELINES.getErrorMessage(),
162                 getMessagePartAccordingToResourceType(resourceEntry), propertyName, propertyValue,
163                 resourceEntry.getKey()));
164         return true;
165       }
166     return false;
167   }
168
169   public static ManifestContent validateManifest(GlobalValidationContext globalContext) {
170     Optional<InputStream> manifest = globalContext.getFileContent(SdcCommon.MANIFEST_NAME);
171     if (!manifest.isPresent()) {
172       throw new RuntimeException("Can't load manifest file for Heat Validator");
173     }
174     ManifestContent manifestContent;
175     try {
176       manifestContent = JsonUtil.json2Object(manifest.get(), ManifestContent.class);
177     } catch (Exception exception) {
178       throw new SdcRuntimeException("Can't load manifest file for Heat Validator", exception);
179     }
180
181     return manifestContent;
182   }
183
184   public static String getParserExceptionReason(Exception exception) {
185     String reason;
186
187     if (exception.getCause() != null && exception.getCause().getCause() != null) {
188       reason = exception.getCause().getCause().getMessage();
189     } else if (exception.getCause() != null) {
190       reason = exception.getCause().getMessage();
191     } else {
192       reason = Messages.GENERAL_HEAT_PARSER_ERROR.getErrorMessage();
193     }
194     return reason;
195   }
196
197   public static HeatOrchestrationTemplate checkHeatOrchestrationPreCondition(String fileName,
198                                                                          GlobalValidationContext globalContext) {
199     HeatOrchestrationTemplate heatOrchestrationTemplate;
200     try {
201       Optional<InputStream> fileContent = globalContext.getFileContent(fileName);
202       if (fileContent.isPresent()) {
203         heatOrchestrationTemplate =
204             new YamlUtil().yamlToObject(fileContent.get(), HeatOrchestrationTemplate.class);
205       } else {
206         heatOrchestrationTemplate = null;
207       }
208     } catch (Exception exception) {
209       globalContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder
210               .getErrorWithParameters(globalContext.getMessageCode(),
211                       Messages.INVALID_HEAT_FORMAT_REASON.getErrorMessage()
212                       , getParserExceptionReason(exception)));
213       return null;
214     }
215     return heatOrchestrationTemplate;
216   }
217
218
219 }