1bdde24253f62a984f70c56dff3e6af5f93deef6
[sdc.git] / openecomp-be / lib / openecomp-sdc-validation-lib / openecomp-sdc-validation-impl / src / main / java / org / openecomp / sdc / validation / impl / validators / ContrailValidator.java
1 /*
2  * Copyright © 2016-2017 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.impl.validators;
18
19 import org.apache.commons.collections4.MapUtils;
20 import org.openecomp.core.validation.ErrorMessageCode;
21 import org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder;
22 import org.openecomp.core.validation.types.GlobalValidationContext;
23 import org.openecomp.sdc.common.errors.Messages;
24 import org.openecomp.sdc.datatypes.error.ErrorLevel;
25 import org.openecomp.sdc.heat.datatypes.manifest.FileData;
26 import org.openecomp.sdc.heat.datatypes.manifest.ManifestContent;
27 import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate;
28 import org.openecomp.sdc.heat.datatypes.model.Resource;
29 import org.openecomp.sdc.heat.services.HeatConstants;
30 import org.openecomp.sdc.heat.services.manifest.ManifestUtil;
31 import org.openecomp.sdc.logging.api.Logger;
32 import org.openecomp.sdc.logging.api.LoggerFactory;
33 import org.openecomp.sdc.tosca.services.YamlUtil;
34 import org.openecomp.sdc.validation.Validator;
35 import org.openecomp.sdc.validation.tos.ContrailResourcesMappingTo;
36 import org.openecomp.sdc.validation.util.ValidationUtil;
37
38 import java.io.InputStream;
39 import java.util.Map;
40 import java.util.Objects;
41 import java.util.Optional;
42
43
44 public class ContrailValidator implements Validator {
45   private static final Logger LOGGER = LoggerFactory.getLogger(ContrailValidator.class);
46   private static final ErrorMessageCode ERROR_CODE_CTL_1 = new ErrorMessageCode("CTL1");
47   private static final ErrorMessageCode ERROR_CODE_CTL_2 = new ErrorMessageCode("CTL2");
48   private static final ErrorMessageCode ERROR_CODE_CTL_3 = new ErrorMessageCode("CTL3");
49   private static final ErrorMessageCode ERROR_CODE_CTL_4 = new ErrorMessageCode("CTL4");
50
51   @Override
52   public void validate(GlobalValidationContext globalContext) {
53     ManifestContent manifestContent;
54     try {
55       manifestContent = ValidationUtil.validateManifest(globalContext);
56     } catch (Exception exception) {
57       LOGGER.debug("",exception);
58       return;
59     }
60     Map<String, FileData.Type> fileTypeMap = ManifestUtil.getFileTypeMap(manifestContent);
61     ContrailResourcesMappingTo contrailResourcesMappingTo = new ContrailResourcesMappingTo();
62
63     globalContext.getFiles().stream()
64         .filter(fileName -> FileData.isHeatFile(fileTypeMap.get(fileName)))
65         .forEach(fileName -> validate(fileName,
66             contrailResourcesMappingTo, globalContext));
67   }
68
69
70   private void validate(String fileName,
71                         ContrailResourcesMappingTo contrailResourcesMappingTo,
72                         GlobalValidationContext globalContext) {
73     handleContrailV1AndContrailV2ResourceMerging(fileName, contrailResourcesMappingTo,
74         globalContext);
75     validateNoContrailResourceTypeIsInUse(fileName, globalContext);
76   }
77
78
79   private void handleContrailV1AndContrailV2ResourceMerging(String fileName,
80                ContrailResourcesMappingTo contrailResourcesMappingTo,
81                GlobalValidationContext globalContext) {
82     Optional<ContrailResourcesMappingTo> fileContrailResourcesMappingTo =
83         collectHeatFileContrailResources(globalContext, fileName);
84     fileContrailResourcesMappingTo.ifPresent(contrailResourcesMappingTo::addAll);
85     addContrailMergeValidationMessageToGlobalContext(globalContext, contrailResourcesMappingTo);
86   }
87
88   private void addContrailMergeValidationMessageToGlobalContext(
89       GlobalValidationContext globalContext,
90       ContrailResourcesMappingTo contrailResourcesMappingTo) {
91     if (!MapUtils.isEmpty(contrailResourcesMappingTo.getContrailV1Resources())
92         && !MapUtils.isEmpty(contrailResourcesMappingTo.getContrailV2Resources())) {
93       globalContext.addMessage(
94           contrailResourcesMappingTo.getContrailV1Resources().keySet().iterator().next(),
95           ErrorLevel.WARNING, ErrorMessagesFormatBuilder.getErrorWithParameters(
96                   ERROR_CODE_CTL_2, Messages.MERGE_OF_CONTRAIL2_AND_CONTRAIL3_RESOURCES.getErrorMessage(),
97               contrailResourcesMappingTo.fetchContrailV1Resources(),
98               contrailResourcesMappingTo.fetchContrailV2Resources()));
99     }
100   }
101
102   private Optional<ContrailResourcesMappingTo> collectHeatFileContrailResources(
103       GlobalValidationContext globalContext, String fileName) {
104     Optional<InputStream> fileContent = globalContext.getFileContent(fileName);
105     if (!fileContent.isPresent()) {
106       globalContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder
107           .getErrorWithParameters(ERROR_CODE_CTL_1, Messages.INVALID_HEAT_FORMAT_REASON
108                   .getErrorMessage(),
109           "The file '" + fileName + "' has no content"));
110       return Optional.empty();
111     }
112     return fetchContrailResourcesMapping(fileName, fileContent.get());
113   }
114
115   private Optional<ContrailResourcesMappingTo> fetchContrailResourcesMapping(String fileName,
116           InputStream fileContent ) {
117     ContrailResourcesMappingTo contrailResourcesMappingTo = new ContrailResourcesMappingTo();
118     HeatOrchestrationTemplate heatOrchestrationTemplate;
119     try {
120       heatOrchestrationTemplate =
121           new YamlUtil().yamlToObject(fileContent, HeatOrchestrationTemplate.class);
122     } catch (Exception ignored) {
123       LOGGER.debug("",ignored);
124       // the HeatValidator should handle file that is failing to parse
125       return Optional.empty();
126     }
127     if( !MapUtils.isEmpty(heatOrchestrationTemplate.getResources())) {
128       heatOrchestrationTemplate.getResources().entrySet()
129           .forEach(entry -> {
130             if (entry.getValue().getType().startsWith(HeatConstants.CONTRAIL_RESOURCE_PREFIX)) {
131               contrailResourcesMappingTo.addContrailV1Resource(fileName, entry.getKey());
132             } else if (entry.getValue().getType()
133                 .startsWith(HeatConstants.CONTRAIL_V2_RESOURCE_PREFIX)) {
134               contrailResourcesMappingTo.addContrailV2Resource(fileName, entry.getKey());
135             }
136           });
137     }
138     return Optional.of(contrailResourcesMappingTo);
139   }
140
141
142   private void validateNoContrailResourceTypeIsInUse(String fileName,
143                                                      GlobalValidationContext globalContext) {
144     globalContext.setMessageCode(ERROR_CODE_CTL_4);
145     HeatOrchestrationTemplate heatOrchestrationTemplate =
146         ValidationUtil.checkHeatOrchestrationPreCondition(fileName, globalContext);
147
148     if (heatOrchestrationTemplate == null) {
149       return;
150     }
151     validateResourcePrefix(fileName, globalContext, heatOrchestrationTemplate);
152   }
153
154   private void validateResourcePrefix(String fileName, GlobalValidationContext globalContext,
155                                       HeatOrchestrationTemplate heatOrchestrationTemplate) {
156     Map<String, Resource> resourcesMap = heatOrchestrationTemplate.getResources();
157     if(!MapUtils.isEmpty(resourcesMap)) {
158       for (Map.Entry<String, Resource> resourceEntry : resourcesMap.entrySet()) {
159         String type = resourceEntry.getValue().getType();
160         if (Objects.nonNull(type) && type.startsWith(HeatConstants.CONTRAIL_RESOURCE_PREFIX)) {
161           globalContext.addMessage(fileName, ErrorLevel.WARNING, ErrorMessagesFormatBuilder
162               .getErrorWithParameters(ERROR_CODE_CTL_3, Messages.CONTRAIL_2_IN_USE.getErrorMessage(),
163               resourceEntry.getKey()));
164         }
165       }
166     }
167   }
168
169 }