c036e39c217d3f43bf36474380ba7b42295a0944
[sdc.git] / openecomp-be / lib / openecomp-sdc-translator-lib / openecomp-sdc-translator-core / src / main / java / org / openecomp / sdc / translator / datatypes / heattotosca / TranslationContext.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.translator.datatypes.heattotosca;
22
23 import org.openecomp.config.api.Configuration;
24 import org.openecomp.config.api.ConfigurationManager;
25 import org.openecomp.core.utilities.CommonMethods;
26 import org.openecomp.core.utilities.file.FileContentHandler;
27 import org.openecomp.sdc.common.utils.SdcCommon;
28 import org.openecomp.sdc.datatypes.configuration.ImplementationConfiguration;
29 import org.openecomp.sdc.heat.datatypes.manifest.FileData;
30 import org.openecomp.sdc.heat.datatypes.manifest.ManifestFile;
31 import org.openecomp.sdc.heat.datatypes.model.Resource;
32 import org.openecomp.sdc.tosca.datatypes.model.NodeTemplate;
33 import org.openecomp.sdc.tosca.datatypes.model.ServiceTemplate;
34 import org.openecomp.sdc.tosca.services.ToscaUtil;
35 import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslatedHeatResource;
36 import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.composition.UnifiedCompositionEntity;
37 import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.composition.UnifiedSubstitutionData;
38 import org.openecomp.sdc.translator.datatypes.heattotosca.unifiedmodel.consolidation.ConsolidationData;
39 import org.openecomp.sdc.translator.services.heattotosca.ConfigConstants;
40 import org.openecomp.sdc.translator.services.heattotosca.Constants;
41 import org.openecomp.sdc.translator.services.heattotosca.NameExtractor;
42 import org.openecomp.sdc.translator.services.heattotosca.globaltypes.GlobalTypesGenerator;
43
44 import java.io.InputStream;
45 import java.util.ArrayList;
46 import java.util.Collection;
47 import java.util.HashMap;
48 import java.util.HashSet;
49 import java.util.List;
50 import java.util.Map;
51 import java.util.Objects;
52 import java.util.Optional;
53 import java.util.Set;
54
55
56 public class TranslationContext {
57
58
59   private static Map<String, Map<String, Map<String, String>>> translationMapping;
60   private static Map<String, ServiceTemplate> globalServiceTemplates;
61   private static Map<String, ImplementationConfiguration> nameExtractorImplMap;
62   private static Map<String, ImplementationConfiguration> supportedConsolidationComputeResources;
63   private static Map<String, ImplementationConfiguration> supportedConsolidationPortResources;
64   private static List enrichPortResourceProperties;
65
66   static {
67     Configuration config = ConfigurationManager.lookup();
68     String propertyFileName = SdcCommon.HEAT_TO_TOSCA_MAPPING_CONF;
69     translationMapping =
70         config.generateMap(ConfigConstants.MAPPING_NAMESPACE, ConfigConstants.RESOURCE_MAPPING_KEY);
71     try {
72       globalServiceTemplates = GlobalTypesGenerator.getGlobalTypesServiceTemplate();
73     } catch (Exception e) {
74       throw new RuntimeException("Failed to load GlobalTypes", e);
75     }
76     nameExtractorImplMap = config.populateMap(ConfigConstants.TRANSLATOR_NAMESPACE,
77         ConfigConstants.NAMING_CONVENTION_EXTRACTOR_IMPL_KEY, ImplementationConfiguration.class);
78     supportedConsolidationComputeResources = config.populateMap(ConfigConstants
79         .MANDATORY_UNIFIED_MODEL_NAMESPACE, ConfigConstants
80         .SUPPORTED_CONSOLIDATION_COMPUTE_RESOURCES_KEY, ImplementationConfiguration.class);
81     supportedConsolidationPortResources = config.populateMap(ConfigConstants
82         .MANDATORY_UNIFIED_MODEL_NAMESPACE, ConfigConstants
83         .SUPPORTED_CONSOLIDATION_PORT_RESOURCES_KEY, ImplementationConfiguration.class);
84     enrichPortResourceProperties = config.getAsStringValues(ConfigConstants
85         .MANDATORY_UNIFIED_MODEL_NAMESPACE, ConfigConstants
86         .ENRICH_PORT_RESOURCE_PROP);
87
88   }
89
90   private Map<String, UnifiedSubstitutionData> unifiedSubstitutionData = new HashMap<>();
91   private ManifestFile manifest;
92
93   public static List getEnrichPortResourceProperties() {
94     return enrichPortResourceProperties;
95   }
96
97   private FileContentHandler files = new FileContentHandler();
98   private Map<String, FileData.Type> manifestFiles = new HashMap<>();
99   //Key - file name, value - file type
100   private Set<String> nestedHeatsFiles = new HashSet<>();
101   private FileContentHandler externalArtifacts = new FileContentHandler();
102   // Key - heat file name,value - set of heat resource ids which were translated
103   private Map<String, Set<String>> translatedResources = new HashMap<>();
104   // Key - heat file name, value - translated Node template id
105   private Map<String, Set<String>> heatStackGroupMembers = new HashMap<>();
106   // Key - heat file name, value - Map with Key - heat resource Id, Value - tosca entity template id
107   private Map<String, Map<String, String>> translatedIds = new HashMap<>();
108   // key - service template type, value - translated service templates
109   private Map<String, ServiceTemplate> translatedServiceTemplates = new HashMap<>();
110   //key - heat param name, value - shared resource data
111   private Map<String, TranslatedHeatResource> heatSharedResourcesByParam = new HashMap<>();
112   //key - translated substitute service template file name, value - source nested heat file name
113   private Map<String, String> nestedHeatFileName = new HashMap<>();
114   //Key - heat file name,value - Map eith key - heat pseudo param name,
115   // value - translated tosca parameter name
116   private Map<String, Map<String, String>> usedHeatPseudoParams = new HashMap<>();
117   //Consolidation data gathered for Unified TOSCA model
118   private ConsolidationData consolidationData = new ConsolidationData();
119
120   public static Map<String, ImplementationConfiguration>
121   getSupportedConsolidationComputeResources() {
122     return supportedConsolidationComputeResources;
123   }
124
125   public static void setSupportedConsolidationComputeResources(
126       Map<String, ImplementationConfiguration> supportedConsolidationComputeResources) {
127     TranslationContext.supportedConsolidationComputeResources =
128         supportedConsolidationComputeResources;
129   }
130
131   public static Map<String, ImplementationConfiguration> getSupportedConsolidationPortResources() {
132     return supportedConsolidationPortResources;
133   }
134
135   public static void setSupportedConsolidationPortResources(
136       Map<String, ImplementationConfiguration> supportedConsolidationPortResources) {
137     TranslationContext.supportedConsolidationPortResources = supportedConsolidationPortResources;
138   }
139
140   /**
141    * Get nameExtractor implemetation class instance.
142    *
143    * @param extractorImplKey configuration key for the implementation class
144    * @return implemetation class instance
145    */
146   public static NameExtractor getNameExtractorImpl(String extractorImplKey) {
147     String nameExtractorImplClassName =
148         nameExtractorImplMap.get(extractorImplKey).getImplementationClass();
149
150     return CommonMethods.newInstance(nameExtractorImplClassName, NameExtractor.class);
151   }
152
153   public Map<String, UnifiedSubstitutionData> getUnifiedSubstitutionData() {
154     return unifiedSubstitutionData;
155   }
156
157   public void setUnifiedSubstitutionData(
158       Map<String, UnifiedSubstitutionData> unifiedSubstitutionData) {
159     this.unifiedSubstitutionData = unifiedSubstitutionData;
160   }
161
162   public void addCleanedNodeTemplate(String serviceTemplateName,
163                                      String nodeTemplateId,
164                                      UnifiedCompositionEntity unifiedCompositionEntity,
165                                      NodeTemplate nodeTemplate) {
166     this.unifiedSubstitutionData.putIfAbsent(serviceTemplateName, new UnifiedSubstitutionData());
167     this.unifiedSubstitutionData
168         .get(serviceTemplateName)
169         .addCleanedNodeTemplate(nodeTemplateId, unifiedCompositionEntity, nodeTemplate);
170   }
171
172   public NodeTemplate getCleanedNodeTemplate(String serviceTemplateName,
173                                              String nodeTemplateId) {
174     return this.unifiedSubstitutionData.get(serviceTemplateName)
175         .getCleanedNodeTemplate(nodeTemplateId);
176   }
177
178   public void addUnifiedNestedNodeTemplateId(String serviceTemplateName,
179                                              String nestedNodeTemplateId,
180                                              String unifiedNestedNodeTemplateId) {
181     this.unifiedSubstitutionData.putIfAbsent(serviceTemplateName, new UnifiedSubstitutionData());
182     this.unifiedSubstitutionData.get(serviceTemplateName)
183         .addUnifiedNestedNodeTemplateId(nestedNodeTemplateId, unifiedNestedNodeTemplateId);
184   }
185
186   public Optional<String> getUnifiedNestedNodeTemplateId(String serviceTemplateName,
187                                                          String nestedNodeTemplateId) {
188     return this.unifiedSubstitutionData.get(serviceTemplateName) == null ? Optional.empty()
189             :this.unifiedSubstitutionData.get(serviceTemplateName).getUnifiedNestedNodeTemplateId(nestedNodeTemplateId);
190   }
191
192   public void addUnifiedNestedNodeTypeId(String serviceTemplateName,
193                                              String nestedNodeTypeId,
194                                              String unifiedNestedNodeTypeId){
195     this.unifiedSubstitutionData.putIfAbsent(serviceTemplateName, new UnifiedSubstitutionData());
196     this.unifiedSubstitutionData.get(serviceTemplateName).addUnifiedNestedNodeTypeId(nestedNodeTypeId, unifiedNestedNodeTypeId);
197   }
198
199   public Optional<String> getUnifiedNestedNodeTypeId(String serviceTemplateName,
200                                                      String nestedNodeTemplateId) {
201     return this.unifiedSubstitutionData.get(serviceTemplateName) == null ? Optional.empty()
202             : this.unifiedSubstitutionData.get(serviceTemplateName).getUnifiedNestedNodeTypeId(nestedNodeTemplateId);
203   }
204
205   public ConsolidationData getConsolidationData() {
206     return consolidationData;
207   }
208
209   public void setConsolidationData(ConsolidationData consolidationData) {
210     this.consolidationData = consolidationData;
211   }
212
213   public void addManifestFile(String fileName, FileData.Type fileType) {
214     this.manifestFiles.put(fileName, fileType);
215   }
216
217   public Set<String> getNestedHeatsFiles() {
218     return nestedHeatsFiles;
219   }
220
221   public Map<String, Set<String>> getHeatStackGroupMembers() {
222     return heatStackGroupMembers;
223   }
224
225   public FileContentHandler getFiles() {
226     return files;
227   }
228
229   public void setFiles(Map<String, byte[]> files) {
230     this.files.putAll(files);
231   }
232
233   public InputStream getFileContent(String fileName) {
234     return files.getFileContent(fileName);
235   }
236
237   public void addFile(String name, byte[] content) {
238     files.addFile(name, content);
239   }
240
241   public ManifestFile getManifest() {
242     return manifest;
243   }
244
245   public void setManifest(ManifestFile manifest) {
246     this.manifest = manifest;
247   }
248
249   public Map<String, Set<String>> getTranslatedResources() {
250     return translatedResources;
251   }
252
253   public Map<String, Map<String, String>> getTranslatedIds() {
254     return translatedIds;
255   }
256
257   public Set<String> getAllTranslatedResourceIdsFromDiffNestedFiles(String
258                                                                         nestedHeatFileNameToSkip){
259     Set<String> allTranslatedResourceIds = new HashSet<>();
260
261     this.translatedIds.entrySet().stream().filter(
262         heatFileNameToTranslatedIdsEntry -> !heatFileNameToTranslatedIdsEntry.getKey()
263             .equals(nestedHeatFileNameToSkip)).forEach(heatFileNameToTranslatedIdsEntry -> {
264       allTranslatedResourceIds.addAll(heatFileNameToTranslatedIdsEntry.getValue().keySet());
265     });
266
267     return allTranslatedResourceIds;
268   }
269
270   // get tosca name from mapping configuration file
271   //element type - parameter/attribute
272   // element name - heat parameter/attribute name
273   //return value - tosca parameter/attribute name
274   public String getElementMapping(String resourceType, String elementType, String elementName) {
275     if (Objects.isNull(translationMapping.get(resourceType))) {
276       return null;
277     }
278     if (Objects.isNull(translationMapping.get(resourceType).get(elementType))) {
279       return null;
280     }
281     return translationMapping.get(resourceType).get(elementType).get(elementName);
282   }
283
284   public Map<String, String> getElementMapping(String resourceType, String elementType) {
285     if (Objects.isNull(translationMapping.get(resourceType))) {
286       return null;
287     }
288     return translationMapping.get(resourceType).get(elementType);
289   }
290
291   public Set<String> getElementSet(String resourceType, String elementType) {
292     if (Objects.isNull(translationMapping.get(resourceType))) {
293       return new HashSet<>();
294     }
295     if (Objects.isNull(translationMapping.get(resourceType).get(elementType))) {
296       return new HashSet<>();
297     }
298     return translationMapping.get(resourceType).get(elementType).keySet();
299   }
300
301   public Map<String, ServiceTemplate> getTranslatedServiceTemplates() {
302     return translatedServiceTemplates;
303   }
304
305   public ServiceTemplate getGlobalSubstitutionServiceTemplate() {
306     return getTranslatedServiceTemplates().get(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME);
307   }
308
309   public FileContentHandler getExternalArtifacts() {
310     return externalArtifacts;
311   }
312
313   public void addExternalArtifacts(String name, byte[] content) {
314     this.externalArtifacts.addFile(name, content);
315   }
316
317   public Map<String, TranslatedHeatResource> getHeatSharedResourcesByParam() {
318     return heatSharedResourcesByParam;
319   }
320
321   public void addHeatSharedResourcesByParam(String parameterName, String resourceId,
322                                             Resource resource) {
323     this.addHeatSharedResourcesByParam(parameterName,
324         new TranslatedHeatResource(resourceId, resource));
325   }
326
327   private void addHeatSharedResourcesByParam(String parameterName,
328                                             TranslatedHeatResource translatedHeatResource) {
329     this.heatSharedResourcesByParam.put(parameterName, translatedHeatResource);
330   }
331
332   public Map<String, ServiceTemplate> getGlobalServiceTemplates() {
333     return globalServiceTemplates;
334   }
335
336   public Map<String, String> getNestedHeatFileName() {
337     return nestedHeatFileName;
338   }
339
340   public void addNestedHeatFileName(String substituteServiceTempalteName,
341                                     String nestedHeatFileName) {
342     this.nestedHeatFileName.put(substituteServiceTempalteName, nestedHeatFileName);
343   }
344
345   public Map<String, Map<String, String>> getUsedHeatPseudoParams() {
346     return usedHeatPseudoParams;
347   }
348
349   public void addUsedHeatPseudoParams(String heatFileName, String heatPseudoParam, String
350       translatedToscaParam) {
351     if (Objects.isNull(this.usedHeatPseudoParams.get(heatFileName))) {
352       this.usedHeatPseudoParams.put(heatFileName, new HashMap<>());
353     }
354     this.usedHeatPseudoParams.get(heatFileName).put(heatPseudoParam, translatedToscaParam);
355   }
356
357   /**
358    * Add the unified substitution data info in context. Contains a mapping of original node
359    * template id and the new node template id in the abstract substitute
360    *
361    * @param serviceTemplateFileName the service template file name
362    * @param originalNodeTemplateId  the original node template id
363    * @param abstractNodeTemplateId  the node template id in the abstract substitute
364    */
365   public void addUnifiedSubstitutionData(String serviceTemplateFileName,
366                                          String originalNodeTemplateId,
367                                          String abstractNodeTemplateId) {
368
369     Map<String, String> nodeAbstractNodeTemplateIdMap = this.getUnifiedSubstitutionData()
370         .computeIfAbsent(serviceTemplateFileName, k -> new UnifiedSubstitutionData())
371         .getNodesRelatedAbstractNode();
372
373     if (nodeAbstractNodeTemplateIdMap == null) {
374       nodeAbstractNodeTemplateIdMap = new HashMap<>();
375     }
376     nodeAbstractNodeTemplateIdMap.put(originalNodeTemplateId, abstractNodeTemplateId);
377     this.getUnifiedSubstitutionData().get(serviceTemplateFileName).setNodesRelatedAbstractNode(
378         nodeAbstractNodeTemplateIdMap);
379   }
380
381   /**
382    * Add the unified substitution data info in context. Contains a mapping of original node
383    * template id and the new node template id in the abstract substitute
384    *
385    * @param serviceTemplateFileName                   the service template file name
386    * @param originalNodeTemplateId                    the original node template id
387    * @param substitutionServiceTemplateNodeTemplateId the node template id in the substitution
388    *                                                  service template
389    */
390   public void addSubstitutionServiceTemplateUnifiedSubstitutionData(String serviceTemplateFileName,
391                                                 String originalNodeTemplateId,
392                                                 String substitutionServiceTemplateNodeTemplateId) {
393
394     Map<String, String> nodesRelatedSubstitutionServiceTemplateNodeTemplateIdMap = this
395         .getUnifiedSubstitutionData()
396         .computeIfAbsent(serviceTemplateFileName, k -> new UnifiedSubstitutionData())
397         .getNodesRelatedSubstitutionServiceTemplateNode();
398
399     if (nodesRelatedSubstitutionServiceTemplateNodeTemplateIdMap == null) {
400       nodesRelatedSubstitutionServiceTemplateNodeTemplateIdMap = new HashMap<>();
401     }
402     nodesRelatedSubstitutionServiceTemplateNodeTemplateIdMap.put(originalNodeTemplateId,
403         substitutionServiceTemplateNodeTemplateId);
404     this.getUnifiedSubstitutionData().get(serviceTemplateFileName)
405         .setNodesRelatedSubstitutionServiceTemplateNode(
406             nodesRelatedSubstitutionServiceTemplateNodeTemplateIdMap);
407   }
408
409   /**
410    * Get unified abstract node template which is mapped to the input node template id.
411    *
412    * @param serviceTemplate the service template
413    * @param nodeTemplateId  the node template id
414    */
415   public String getUnifiedAbstractNodeTemplateId(ServiceTemplate serviceTemplate,
416                                                  String nodeTemplateId) {
417     UnifiedSubstitutionData unifiedSubstitutionData =
418         this.unifiedSubstitutionData.get(ToscaUtil.getServiceTemplateFileName(serviceTemplate));
419     return unifiedSubstitutionData.getNodesRelatedAbstractNode().get(nodeTemplateId);
420   }
421
422   /**
423    * Get unified node template in the substitution service template which is mapped to the
424    * original input node template id.
425    *
426    * @param serviceTemplate the service template
427    * @param nodeTemplateId  the node template id
428    */
429   public String getUnifiedSubstitutionNodeTemplateId(ServiceTemplate serviceTemplate,
430                                                      String nodeTemplateId) {
431     UnifiedSubstitutionData unifiedSubstitutionData =
432         this.unifiedSubstitutionData.get(ToscaUtil.getServiceTemplateFileName(serviceTemplate));
433     return unifiedSubstitutionData.getNodesRelatedSubstitutionServiceTemplateNode()
434         .get(nodeTemplateId);
435   }
436
437   public int getHandledNestedComputeNodeTemplateIndex(String serviceTemplateName,
438                                                       String computeType){
439     return this.unifiedSubstitutionData.get(serviceTemplateName)
440         .getHandledNestedComputeNodeTemplateIndex(computeType);
441   }
442
443   public void updateHandledComputeType(String serviceTemplateName,
444                                        String nestedServiceTemplateFileName,
445                                        String handledComputeType){
446     this.unifiedSubstitutionData.putIfAbsent(serviceTemplateName, new UnifiedSubstitutionData());
447     this.unifiedSubstitutionData.get(serviceTemplateName)
448         .addHandledComputeType(nestedServiceTemplateFileName, handledComputeType);
449   }
450
451   public boolean isNestedServiceTemplateWasHandled(String serviceTemplateName,
452                                                    String nestedServiceTemplateFileName){
453     if(Objects.isNull(this.unifiedSubstitutionData.get(serviceTemplateName))){
454       return false;
455     }
456     return this.unifiedSubstitutionData.get(serviceTemplateName)
457         .isNestedServiceTemplateWasHandled(nestedServiceTemplateFileName);
458   }
459
460   public void addNestedFileToUsedNestedComputeType(String serviceTemplateName,
461                                                    String nestedServiceTemplateFileName,
462                                                    String computeType){
463     this.unifiedSubstitutionData.putIfAbsent(serviceTemplateName, new UnifiedSubstitutionData());
464
465     this.unifiedSubstitutionData.get(serviceTemplateName).addNestedFileToUsedNestedComputeType
466         (computeType, nestedServiceTemplateFileName);
467   }
468
469   public int getGlobalNodeTypeIndex(String serviceTemplateName,
470                                     String computeType){
471     if(Objects.isNull(this.unifiedSubstitutionData.get(serviceTemplateName))){
472       return 0;
473     }
474     return this.unifiedSubstitutionData.get(serviceTemplateName).getGlobalNodeTypeIndex
475         (computeType);
476   }
477
478
479 }