[SDC] Onboarding 1710 rebase.
[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  * ============LICENSE_START=======================================================
3  * SDC
4  * ================================================================================
5  * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6  * ================================================================================
7  * Licensed under the Apache License, Version 2.0 (the "License");
8  * you may not use this file except in compliance with the License.
9  * You may obtain a copy of the License at
10  * 
11  *      http://www.apache.org/licenses/LICENSE-2.0
12  * 
13  * Unless required by applicable law or agreed to in writing, software
14  * distributed under the License is distributed on an "AS IS" BASIS,
15  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16  * See the License for the specific language governing permissions and
17  * limitations under the License.
18  * ============LICENSE_END=========================================================
19  */
20
21 package org.openecomp.sdc.validation.impl.validators;
22
23 import org.apache.commons.collections4.MapUtils;
24 import org.openecomp.sdc.tosca.services.YamlUtil;
25 import org.openecomp.sdc.validation.Validator;
26 import org.openecomp.core.validation.errors.ErrorMessagesFormatBuilder;
27 import org.openecomp.core.validation.types.GlobalValidationContext;
28 import org.openecomp.sdc.common.errors.Messages;
29 import org.openecomp.sdc.datatypes.error.ErrorLevel;
30 import org.openecomp.sdc.heat.datatypes.manifest.FileData;
31 import org.openecomp.sdc.heat.datatypes.manifest.ManifestContent;
32 import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate;
33 import org.openecomp.sdc.heat.datatypes.model.Resource;
34 import org.openecomp.sdc.heat.services.HeatConstants;
35 import org.openecomp.sdc.heat.services.manifest.ManifestUtil;
36 import org.openecomp.sdc.logging.api.Logger;
37 import org.openecomp.sdc.logging.api.LoggerFactory;
38 import org.openecomp.sdc.logging.context.impl.MdcDataDebugMessage;
39 import org.openecomp.sdc.logging.types.LoggerErrorDescription;
40 import org.openecomp.sdc.logging.types.LoggerTragetServiceName;
41 import org.openecomp.sdc.validation.tos.ContrailResourcesMappingTo;
42 import org.openecomp.sdc.validation.util.ValidationUtil;
43
44 import java.io.InputStream;
45 import java.util.Map;
46 import java.util.Objects;
47 import java.util.Optional;
48
49
50 public class ContrailValidator implements Validator {
51   public static MdcDataDebugMessage mdcDataDebugMessage = new MdcDataDebugMessage();
52   protected static Logger logger = (Logger) LoggerFactory.getLogger(ContrailValidator.class);
53
54   @Override
55   public void validate(GlobalValidationContext globalContext) {
56     mdcDataDebugMessage.debugEntryMessage(null, null);
57
58     ManifestContent manifestContent;
59     try {
60       manifestContent = ValidationUtil.checkValidationPreCondition(globalContext);
61     } catch (Exception exception) {
62       return;
63     }
64     Map<String, FileData.Type> fileTypeMap = ManifestUtil.getFileTypeMap(manifestContent);
65     ContrailResourcesMappingTo contrailResourcesMappingTo = new ContrailResourcesMappingTo();
66
67     globalContext.getFiles().stream()
68         .filter(fileName -> FileData.isHeatFile(fileTypeMap.get(fileName)))
69         .forEach(fileName -> validate(fileName, fileTypeMap,
70             contrailResourcesMappingTo, globalContext));
71
72     mdcDataDebugMessage.debugExitMessage(null, null);
73   }
74
75
76   private void validate(String fileName, Map<String, FileData.Type> fileTypeMap,
77                         ContrailResourcesMappingTo contrailResourcesMappingTo,
78                         GlobalValidationContext globalContext) {
79     handleContrailV1AndContrailV2ResourceMerging(fileName, fileTypeMap, contrailResourcesMappingTo,
80         globalContext);
81     validateNoContrailResourceTypeIsInUse(fileName, globalContext);
82   }
83
84
85   private void handleContrailV1AndContrailV2ResourceMerging(String fileName,
86                Map<String, FileData.Type> fileTypeMap,
87                ContrailResourcesMappingTo contrailResourcesMappingTo,
88                GlobalValidationContext globalContext) {
89
90
91     mdcDataDebugMessage.debugEntryMessage("file", fileName);
92
93     Optional<ContrailResourcesMappingTo> fileContrailResourcesMappingTo =
94         collectHeatFileContrailResources(globalContext, fileName);
95     if (fileContrailResourcesMappingTo.isPresent()) {
96       contrailResourcesMappingTo.addAll(fileContrailResourcesMappingTo.get());
97     }
98     addContrailMergeValidationMessageToGlobalContext(globalContext, contrailResourcesMappingTo);
99
100     mdcDataDebugMessage.debugExitMessage("file", fileName);
101   }
102
103   private void addContrailMergeValidationMessageToGlobalContext(
104       GlobalValidationContext globalContext,
105       ContrailResourcesMappingTo contrailResourcesMappingTo) {
106
107
108     mdcDataDebugMessage.debugEntryMessage(null, null);
109
110     if (!MapUtils.isEmpty(contrailResourcesMappingTo.getContrailV1Resources())
111         && !MapUtils.isEmpty(contrailResourcesMappingTo.getContrailV2Resources())) {
112       globalContext.addMessage(
113           contrailResourcesMappingTo.getContrailV1Resources().keySet().iterator().next(),
114           ErrorLevel.WARNING, ErrorMessagesFormatBuilder.getErrorWithParameters(
115               Messages.MERGE_OF_CONTRAIL2_AND_CONTRAIL3_RESOURCES.getErrorMessage(),
116               contrailResourcesMappingTo.fetchContrailV1Resources(),
117               contrailResourcesMappingTo.fetchContrailV2Resources()),
118           LoggerTragetServiceName.MERGE_OF_CONTRAIL_2_AND_3,
119           LoggerErrorDescription.MERGE_CONTRAIL_2_AND_3);
120     }
121
122     mdcDataDebugMessage.debugExitMessage(null, null);
123   }
124
125   private Optional<ContrailResourcesMappingTo> collectHeatFileContrailResources(
126       GlobalValidationContext globalContext, String fileName) {
127     Optional<InputStream> fileContent = globalContext.getFileContent(fileName);
128     if (!fileContent.isPresent()) {
129       globalContext.addMessage(fileName, ErrorLevel.ERROR, ErrorMessagesFormatBuilder
130               .getErrorWithParameters(Messages.INVALID_HEAT_FORMAT_REASON.getErrorMessage(),
131                   "The file '" + fileName + "' has no content"),
132           LoggerTragetServiceName.VALIDATE_HEAT_FORMAT, LoggerErrorDescription.INVALID_HEAT_FORMAT);
133       return Optional.empty();
134     }
135     return fetchContrailResourcesMapping(fileName, fileContent.get(), globalContext);
136   }
137
138   private Optional<ContrailResourcesMappingTo> fetchContrailResourcesMapping(String fileName,
139           InputStream fileContent,
140           GlobalValidationContext globalContext) {
141
142
143     mdcDataDebugMessage.debugEntryMessage("file", fileName);
144
145     ContrailResourcesMappingTo contrailResourcesMappingTo = new ContrailResourcesMappingTo();
146     HeatOrchestrationTemplate heatOrchestrationTemplate;
147     try {
148       heatOrchestrationTemplate =
149           new YamlUtil().yamlToObject(fileContent, HeatOrchestrationTemplate.class);
150     } catch (Exception ignored) {
151       // the HeatValidator should handle file that is failing to parse
152       mdcDataDebugMessage.debugExitMessage("file", fileName);
153       return Optional.empty();
154     }
155     if( !MapUtils.isEmpty(heatOrchestrationTemplate.getResources())) {
156       heatOrchestrationTemplate.getResources().entrySet()
157           .forEach(entry -> {
158             if (entry.getValue().getType().startsWith(HeatConstants.CONTRAIL_RESOURCE_PREFIX)) {
159               contrailResourcesMappingTo.addContrailV1Resource(fileName, entry.getKey());
160             } else if (entry.getValue().getType()
161                 .startsWith(HeatConstants.CONTRAIL_V2_RESOURCE_PREFIX)) {
162               contrailResourcesMappingTo.addContrailV2Resource(fileName, entry.getKey());
163             }
164           });
165     }
166
167     mdcDataDebugMessage.debugExitMessage("file", fileName);
168     return Optional.of(contrailResourcesMappingTo);
169   }
170
171
172   private void validateNoContrailResourceTypeIsInUse(String fileName,
173                                                      GlobalValidationContext globalContext) {
174
175     mdcDataDebugMessage.debugEntryMessage("file", fileName);
176
177     HeatOrchestrationTemplate heatOrchestrationTemplate =
178         ValidationUtil.checkHeatOrchestrationPreCondition(fileName, globalContext);
179
180     if (heatOrchestrationTemplate == null) {
181       return;
182     }
183
184     Map<String, Resource> resourcesMap = heatOrchestrationTemplate.getResources();
185
186     if( ! MapUtils.isEmpty(resourcesMap)) {
187       for (Map.Entry<String, Resource> resourceEntry : resourcesMap.entrySet()) {
188         String type = resourceEntry.getValue().getType();
189         if (Objects.nonNull(type) && type.startsWith(HeatConstants.CONTRAIL_RESOURCE_PREFIX)) {
190           globalContext.addMessage(fileName, ErrorLevel.WARNING, ErrorMessagesFormatBuilder
191                   .getErrorWithParameters(Messages.CONTRAIL_2_IN_USE.getErrorMessage(),
192                       resourceEntry.getKey()), LoggerTragetServiceName.CONTRAIL_2_IN_USE,
193               LoggerErrorDescription.CONTRAIL_2_IN_USE);
194         }
195       }
196     }
197
198     mdcDataDebugMessage.debugExitMessage("file", fileName);
199   }
200
201 }