2 * Copyright © 2016-2018 European Support Limited
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
8 * http://www.apache.org/licenses/LICENSE-2.0
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.
17 package org.openecomp.sdc.translator.services.heattotosca;
19 import static org.openecomp.sdc.heat.services.HeatResourceUtil.extractNetworkRoleFromSubInterfaceId;
20 import static org.openecomp.sdc.translator.services.heattotosca.impl.functiontranslation.FunctionTranslator.getFunctionTranslateTo;
22 import java.io.IOException;
23 import java.io.InputStream;
24 import java.util.ArrayList;
25 import java.util.Collection;
26 import java.util.HashMap;
27 import java.util.HashSet;
28 import java.util.List;
30 import java.util.Objects;
31 import java.util.Optional;
33 import java.util.stream.Collectors;
35 import org.apache.commons.collections4.CollectionUtils;
36 import org.apache.commons.collections4.MapUtils;
37 import org.apache.commons.io.FilenameUtils;
38 import org.onap.sdc.tosca.datatypes.model.AttributeDefinition;
39 import org.onap.sdc.tosca.datatypes.model.CapabilityDefinition;
40 import org.onap.sdc.tosca.datatypes.model.Import;
41 import org.onap.sdc.tosca.datatypes.model.NodeTemplate;
42 import org.onap.sdc.tosca.datatypes.model.NodeType;
43 import org.onap.sdc.tosca.datatypes.model.ParameterDefinition;
44 import org.onap.sdc.tosca.datatypes.model.PropertyDefinition;
45 import org.onap.sdc.tosca.datatypes.model.PropertyType;
46 import org.onap.sdc.tosca.datatypes.model.RequirementAssignment;
47 import org.onap.sdc.tosca.datatypes.model.RequirementDefinition;
48 import org.onap.sdc.tosca.datatypes.model.ServiceTemplate;
49 import org.onap.sdc.tosca.datatypes.model.Template;
50 import org.onap.sdc.tosca.datatypes.model.TopologyTemplate;
51 import org.onap.sdc.tosca.services.ToscaExtensionYamlUtil;
52 import org.onap.sdc.tosca.services.YamlUtil;
53 import org.openecomp.core.translator.api.HeatToToscaTranslator;
54 import org.openecomp.core.translator.datatypes.TranslatorOutput;
55 import org.openecomp.core.translator.factory.HeatToToscaTranslatorFactory;
56 import org.openecomp.core.utilities.file.FileContentHandler;
57 import org.openecomp.core.utilities.file.FileUtils;
58 import org.openecomp.core.utilities.orchestration.OnboardingTypesEnum;
59 import org.openecomp.core.validation.util.MessageContainerUtil;
60 import org.openecomp.sdc.common.errors.CoreException;
61 import org.openecomp.sdc.common.errors.SdcRuntimeException;
62 import org.openecomp.sdc.common.utils.SdcCommon;
63 import org.openecomp.sdc.datatypes.error.ErrorLevel;
64 import org.openecomp.sdc.datatypes.error.ErrorMessage;
65 import org.openecomp.sdc.heat.datatypes.HeatBoolean;
66 import org.openecomp.sdc.heat.datatypes.manifest.FileData;
67 import org.openecomp.sdc.heat.datatypes.model.HeatOrchestrationTemplate;
68 import org.openecomp.sdc.heat.datatypes.model.HeatResourcesTypes;
69 import org.openecomp.sdc.heat.datatypes.model.Resource;
70 import org.openecomp.sdc.heat.datatypes.model.ResourceReferenceFunctions;
71 import org.openecomp.sdc.heat.datatypes.structure.HeatStructureTree;
72 import org.openecomp.sdc.heat.datatypes.structure.ValidationStructureList;
73 import org.openecomp.sdc.heat.services.HeatConstants;
74 import org.openecomp.sdc.heat.services.tree.HeatTreeManager;
75 import org.openecomp.sdc.heat.services.tree.HeatTreeManagerUtil;
76 import org.openecomp.sdc.logging.api.Logger;
77 import org.openecomp.sdc.logging.api.LoggerFactory;
78 import org.openecomp.sdc.tosca.datatypes.ToscaCapabilityType;
79 import org.openecomp.sdc.tosca.datatypes.ToscaElementTypes;
80 import org.openecomp.sdc.tosca.datatypes.ToscaFunctions;
81 import org.openecomp.sdc.tosca.datatypes.ToscaNodeType;
82 import org.openecomp.sdc.tosca.datatypes.ToscaRelationshipType;
83 import org.openecomp.sdc.tosca.datatypes.ToscaServiceModel;
84 import org.openecomp.sdc.tosca.services.DataModelUtil;
85 import org.openecomp.sdc.tosca.services.ToscaAnalyzerService;
86 import org.openecomp.sdc.tosca.services.ToscaConstants;
87 import org.openecomp.sdc.tosca.services.ToscaUtil;
88 import org.openecomp.sdc.tosca.services.impl.ToscaAnalyzerServiceImpl;
89 import org.openecomp.sdc.translator.datatypes.heattotosca.AttachedPropertyVal;
90 import org.openecomp.sdc.translator.datatypes.heattotosca.AttachedResourceId;
91 import org.openecomp.sdc.translator.datatypes.heattotosca.ReferenceType;
92 import org.openecomp.sdc.translator.datatypes.heattotosca.TranslationContext;
93 import org.openecomp.sdc.translator.datatypes.heattotosca.to.FileDataCollection;
94 import org.openecomp.sdc.translator.datatypes.heattotosca.to.TranslateTo;
95 import org.openecomp.sdc.translator.services.heattotosca.errors.ResourceNotFoundInHeatFileErrorBuilder;
96 import org.openecomp.sdc.translator.services.heattotosca.globaltypes.GlobalTypesGenerator;
97 import org.openecomp.sdc.translator.services.heattotosca.helper.ContrailV2VirtualMachineInterfaceHelper;
98 import org.openecomp.sdc.translator.services.heattotosca.impl.functiontranslation.FunctionTranslator;
99 import org.openecomp.sdc.translator.services.heattotosca.impl.resourcetranslation.ResourceTranslationBase;
100 import org.openecomp.sdc.translator.services.heattotosca.mapping.TranslatorHeatToToscaPropertyConverter;
103 * The type Heat to tosca util.
105 public class HeatToToscaUtil {
107 private static final Logger LOGGER = LoggerFactory.getLogger(HeatToToscaUtil.class);
108 private static final String FQ_NAME = "fq_name";
109 private static final String GET_PARAM = "get_param";
110 private static final String GET_ATTR = "get_attr";
111 private static final String GET_RESOURCE = "get_resource";
112 private static final String UNDERSCORE = "_";
115 * Load and translate template data translator output.
117 * @param fileNameContentMap the file name content map
118 * @return the translator output
120 public static TranslatorOutput loadAndTranslateTemplateData(FileContentHandler fileNameContentMap) {
121 HeatToToscaTranslator heatToToscaTranslator = HeatToToscaTranslatorFactory.getInstance().createInterface();
123 try (InputStream fileContent = fileNameContentMap.getFileContent(SdcCommon.MANIFEST_NAME)) {
124 heatToToscaTranslator.addManifest(SdcCommon.MANIFEST_NAME, FileUtils.toByteArray(fileContent));
125 } catch (IOException e) {
126 throw new SdcRuntimeException("Failed to read manifest", e);
129 fileNameContentMap.getFileList().stream().filter(fileName -> !(fileName.equals(SdcCommon.MANIFEST_NAME)))
130 .forEach(fileName -> heatToToscaTranslator.addFile(fileName,
131 FileUtils.toByteArray(fileNameContentMap.getFileContent(fileName))));
133 Map<String, List<ErrorMessage>> errors = heatToToscaTranslator.validate();
134 if (MapUtils.isNotEmpty(MessageContainerUtil.getMessageByLevel(ErrorLevel.ERROR, errors))) {
135 TranslatorOutput translatorOutput = new TranslatorOutput();
136 translatorOutput.setErrorMessages(errors);
137 return translatorOutput;
140 try (InputStream structureFile = getHeatStructureTreeFile(fileNameContentMap)) {
141 heatToToscaTranslator.addExternalArtifacts(SdcCommon.HEAT_META, structureFile);
142 return heatToToscaTranslator.translate();
143 } catch (IOException e) {
144 // rethrow as a RuntimeException to keep the signature backward compatible
145 throw new SdcRuntimeException("Failed to read Heat template tree", e);
150 private static InputStream getHeatStructureTreeFile(FileContentHandler fileNameContentMap) {
151 HeatTreeManager heatTreeManager = HeatTreeManagerUtil.initHeatTreeManager(fileNameContentMap);
152 heatTreeManager.createTree();
153 HeatStructureTree tree = heatTreeManager.getTree();
154 ValidationStructureList validationStructureList = new ValidationStructureList(tree);
155 return FileUtils.convertToInputStream(validationStructureList, FileUtils.FileExtension.JSON);
159 * Build list of files to search optional.
161 * @param heatFileName the heat file name
162 * @param filesDataList the files data list
163 * @param types the types
164 * @return the optional
166 public static Optional<List<FileData>> buildListOfFilesToSearch(String heatFileName, List<FileData> filesDataList,
167 FileData.Type... types) {
168 List<FileData> list = new ArrayList<>(filesDataList);
169 Optional<FileData> resourceFileData = HeatToToscaUtil.getFileData(heatFileName, filesDataList);
170 if (resourceFileData.isPresent() && Objects.nonNull(resourceFileData.get().getData())) {
171 list.addAll(resourceFileData.get().getData());
173 return Optional.ofNullable(HeatToToscaUtil.getFilteredListOfFileDataByTypes(list, types));
177 * Gets filtered list of file data by types.
179 * @param filesToSearch the files to search
180 * @param types the types
181 * @return the filtered list of file data by types
183 public static List<FileData> getFilteredListOfFileDataByTypes(List<FileData> filesToSearch,
184 FileData.Type... types) {
185 return filesToSearch.stream().filter(FileData.buildFileDataPredicateByType(types)).collect(Collectors.toList());
189 * Gets file data from the list according to the input heat file name.
191 * @param heatFileName the heat file name
192 * @param fileDataList the file data list
193 * @return the file data
195 public static Optional<FileData> getFileData(String heatFileName, Collection<FileData> fileDataList) {
196 for (FileData file : fileDataList) {
197 if (file.getFile().equals(heatFileName)) {
198 return Optional.of(file);
201 return Optional.empty();
205 * Gets file data which is supported by the translator, from the context according the input heat
208 * @param heatFileName the heat file name
209 * @param context the translation context
210 * @return the file data
212 public static FileData getFileData(String heatFileName, TranslationContext context) {
213 List<FileData> fileDataList = context.getManifest().getContent().getData();
214 for (FileData fileData : fileDataList) {
215 if (TranslationService.getTypesToProcessByTranslator().contains(fileData.getType()) && fileData.getFile()
216 .equals(heatFileName)) {
223 static FileDataCollection getFileCollectionsByFilter(List<FileData> fileDataList, Set<FileData.Type> typeFilter,
224 TranslationContext translationContext) {
225 FileDataCollection fileDataCollection = new FileDataCollection();
226 Map<String, FileData> filteredFiles = filterFileDataListByType(fileDataList, typeFilter);
227 Set<String> referenced = new HashSet<>();
228 for (FileData fileData : filteredFiles.values()) {
229 String fileName = fileData.getFile();
231 if (FileData.isHeatFile(fileData.getType())) {
232 if (fileData.getBase() != null && fileData.getBase()) {
233 fileDataCollection.addBaseFiles(fileData);
235 HeatOrchestrationTemplate heatOrchestrationTemplate = new YamlUtil().yamlToObject(
236 translationContext.getFileContent(fileName), HeatOrchestrationTemplate.class);
237 if (MapUtils.isNotEmpty(heatOrchestrationTemplate.getResources())) {
238 referenced.addAll(applyFilterOnFileCollection(heatOrchestrationTemplate, translationContext,
239 fileDataCollection, filteredFiles));
243 fileDataCollection.addArtifactFiles(fileData);
244 filteredFiles.remove(fileData.getFile());
248 referenced.addAll(getAssociatedFiles(filteredFiles.values()));
249 referenced.forEach(filteredFiles::remove);
251 if (!CollectionUtils.isEmpty(fileDataCollection.getBaseFile())) {
252 for (FileData fileData : fileDataCollection.getBaseFile()) {
253 filteredFiles.remove(fileData.getFile());
256 fileDataCollection.setAddOnFiles(filteredFiles.values());
257 return fileDataCollection;
260 private static Set<String> getAssociatedFiles(Collection<FileData> filteredFiles) {
261 Set<String> associatedFiles = new HashSet<>();
262 filteredFiles.stream().filter(file -> file.getParentFile() != null
263 && FileData.Type.canBeAssociated(file.getType()))
264 .forEach(file -> associatedFiles.add(file.getFile()));
265 return associatedFiles;
268 private static Set<String> applyFilterOnFileCollection(HeatOrchestrationTemplate heatOrchestrationTemplate,
269 TranslationContext translationContext,
270 FileDataCollection fileDataCollection,
271 Map<String, FileData> filteredFiles) {
272 Set<String> nestedFiles = new HashSet<>();
273 List<String> filenames = extractFilenamesFromFileDataList(filteredFiles.values());
274 for (Resource resource : heatOrchestrationTemplate.getResources().values()) {
275 String resourceType = resource.getType();
276 if (filenames.contains(resourceType)) {
277 handleNestedFile(translationContext, fileDataCollection, filteredFiles, resourceType);
278 nestedFiles.add(resourceType);
279 } else if (resourceType.equals(HeatResourcesTypes.RESOURCE_GROUP_RESOURCE_TYPE.getHeatResource())) {
280 Optional<String> nestedFile = handleResourceGrpNestedFile(resource, translationContext,
281 fileDataCollection, filteredFiles, filenames);
282 nestedFile.ifPresent(nestedFiles::add);
288 private static Optional<String> handleResourceGrpNestedFile(Resource resource, TranslationContext
289 translationContext, FileDataCollection fileDataCollection,
290 Map<String, FileData> filteredFiles, List<String> filenames) {
291 Object resourceDef = resource.getProperties().get(HeatConstants.RESOURCE_DEF_PROPERTY_NAME);
292 Object innerTypeDef = ((Map) resourceDef).get(HeatConstants.RESOURCE_DEF_TYPE_PROPERTY_NAME);
293 if (innerTypeDef instanceof String) {
294 String internalResourceType = (String) innerTypeDef;
295 if (filenames.contains(internalResourceType)) {
296 handleNestedFile(translationContext, fileDataCollection, filteredFiles,
297 internalResourceType);
298 return Optional.of(internalResourceType);
301 return Optional.empty();
304 private static void handleNestedFile(TranslationContext translationContext, FileDataCollection fileDataCollection,
305 Map<String, FileData> filteredFiles,
306 String nestedFileName) {
307 fileDataCollection.addNestedFiles(filteredFiles.get(nestedFileName));
308 translationContext.getNestedHeatsFiles().add(nestedFileName);
311 private static Map<String, FileData> filterFileDataListByType(List<FileData> fileDataList,
312 Set<FileData.Type> typesToGet) {
313 Map<String, FileData> filtered = new HashMap<>();
314 filterFileDataListByType(fileDataList, filtered, typesToGet, null);
318 private static void filterFileDataListByType(List<FileData> fileDataList, Map<String, FileData> filtered,
319 Set<FileData.Type> typesToGet, String parentFileName) {
320 fileDataList.stream().filter(file -> typesToGet.contains(file.getType()))
322 filtered.put(file.getFile(), file);
323 file.setParentFile(parentFileName);
326 Set<FileData.Type> canBeAssociatedTypes = typesToGet.stream()
327 .filter(FileData.Type::canBeAssociated).collect(Collectors.toSet());
329 fileDataList.stream().filter(file -> Objects.nonNull(file.getData()))
330 .forEach(file -> filterFileDataListByType(file.getData(), filtered,
331 canBeAssociatedTypes, file.getFile()));
334 private static List<String> extractFilenamesFromFileDataList(Collection<FileData> fileDataList) {
335 return fileDataList.stream().map(FileData::getFile).collect(Collectors.toList());
339 * Extract attached resource id optional.
341 * @param translateTo the translate to
342 * @param propertyName the property name
343 * @return the optional
345 public static Optional<AttachedResourceId> extractAttachedResourceId(TranslateTo translateTo, String propertyName) {
346 Object propertyValue = translateTo.getResource().getProperties().get(propertyName);
347 if (propertyValue == null) {
348 return Optional.empty();
350 return extractAttachedResourceId(translateTo.getHeatFileName(), translateTo.getHeatOrchestrationTemplate(),
351 translateTo.getContext(), propertyValue);
355 * Extract attached resource id optional.
357 * @param heatFileName the heat file name
358 * @param heatOrchestrationTemplate the heat orchestration template
359 * @param context the context
360 * @param propertyValue the property value
361 * @return the optional
363 public static Optional<AttachedResourceId> extractAttachedResourceId(String heatFileName,
364 HeatOrchestrationTemplate heatOrchestrationTemplate,
365 TranslationContext context,
366 Object propertyValue) {
369 Object translatedId = null;
371 if (Objects.isNull(propertyValue)) {
372 return Optional.empty();
375 ReferenceType referenceType = ReferenceType.OTHER;
376 if (propertyValue instanceof Map && !((Map) propertyValue).isEmpty()) {
377 Map<String, Object> propMap = (Map) propertyValue;
378 Map.Entry<String, Object> entry = propMap.entrySet().iterator().next();
379 entity = entry.getValue();
380 String key = entry.getKey();
381 referenceType = getReferenceTypeFromAttachedResouce(key);
383 if (FunctionTranslationFactory.getInstance(entry.getKey()).isPresent()) {
384 FunctionTranslator functionTranslator = new FunctionTranslator(getFunctionTranslateTo(null, null,
385 heatFileName, heatOrchestrationTemplate, context), null, entry.getValue(), null);
386 translatedId = FunctionTranslationFactory.getInstance(entry.getKey()).get()
387 .translateFunction(functionTranslator);
388 if (translatedId instanceof String
389 && !new FunctionTranslator().isResourceSupported((String) translatedId)) {
394 translatedId = propertyValue;
395 entity = propertyValue;
398 return Optional.of(new AttachedResourceId(translatedId, entity, referenceType));
401 private static ReferenceType getReferenceTypeFromAttachedResouce(String key) {
402 ReferenceType referenceType;
405 referenceType = ReferenceType.GET_RESOURCE;
408 referenceType = ReferenceType.GET_PARAM;
411 referenceType = ReferenceType.GET_ATTR;
414 referenceType = ReferenceType.OTHER;
418 return referenceType;
422 * Gets contrail attached heat resource id.
424 * @param attachedResource the attached resource
425 * @return the contrail attached heat resource id
427 public static Optional<String> getContrailAttachedHeatResourceId(AttachedResourceId attachedResource) {
428 if (attachedResource == null) {
429 return Optional.empty();
432 if (attachedResource.isGetResource()) {
433 return Optional.of((String) attachedResource.getEntityId());
436 if (attachedResource.isGetAttr()) {
437 return getResourceId(attachedResource.getEntityId());
439 return Optional.empty();
443 * Extract property optional.
445 * @param propertyValue the property value
446 * @return the optional
448 private static Optional<AttachedPropertyVal> extractProperty(Object propertyValue) {
449 Object attachedPropertyVal;
450 if (Objects.isNull(propertyValue)) {
451 return Optional.empty();
454 ReferenceType referenceType = ReferenceType.OTHER;
455 if (propertyValue instanceof Map && !((Map) propertyValue).isEmpty()) {
456 Map<String, Object> propMap = (Map) propertyValue;
457 Map.Entry<String, Object> entry = propMap.entrySet().iterator().next();
458 attachedPropertyVal = entry.getValue();
459 String key = entry.getKey();
462 referenceType = ReferenceType.GET_RESOURCE;
465 referenceType = ReferenceType.GET_PARAM;
468 referenceType = ReferenceType.GET_ATTR;
475 attachedPropertyVal = propertyValue;
477 return Optional.of(new AttachedPropertyVal(attachedPropertyVal, referenceType));
483 * @param nodeTemplate the node template
484 * @param propertyKey the property key
486 public static void mapBoolean(NodeTemplate nodeTemplate, String propertyKey) {
487 Object value = nodeTemplate.getProperties().get(propertyKey);
488 if (value != null && !(value instanceof Map)) {
489 nodeTemplate.getProperties().put(propertyKey, HeatBoolean.eval(value));
496 * @param nodeTemplate the node template
497 * @param propertyListKey the property list key
499 public static void mapBooleanList(NodeTemplate nodeTemplate, String propertyListKey) {
500 Object listValue = nodeTemplate.getProperties().get(propertyListKey);
501 if (listValue instanceof List) {
502 List booleanList = (List) listValue;
503 for (int i = 0; i < booleanList.size(); i++) {
504 Object value = booleanList.get(i);
505 if (value != null && !(value instanceof Map)) {
506 booleanList.set(i, HeatBoolean.eval(value));
514 * Is yml file type boolean.
516 * @param filename the filename
517 * @return the boolean
519 public static boolean isYmlFileType(String filename) {
520 String extension = FilenameUtils.getExtension(filename);
521 return "yaml".equalsIgnoreCase(extension) || "yml".equalsIgnoreCase(extension);
525 * Is nested resource boolean.
527 * @param resource the resource
528 * @return the boolean
530 public static boolean isNestedResource(Resource resource) {
531 String resourceType = resource.getType();
533 if (resourceType.equals(HeatResourcesTypes.RESOURCE_GROUP_RESOURCE_TYPE.getHeatResource())) {
534 Object resourceDef = resource.getProperties().get(HeatConstants.RESOURCE_DEF_PROPERTY_NAME);
535 if (!(((Map) resourceDef).get(HeatConstants.RESOURCE_DEF_TYPE_PROPERTY_NAME) instanceof String)) {
536 //currently only resource group which is poinitng to nested heat file is supported
537 //dynamic type is currently not supported
540 String internalResourceType =
541 (String) ((Map) resourceDef).get(HeatConstants.RESOURCE_DEF_TYPE_PROPERTY_NAME);
542 if (isYamlFile(internalResourceType)) {
545 } else if (isYamlFile(resourceType)) {
552 * Checks if the current HEAT resource if of type sub interface.
554 * @param resource the resource
555 * @return true if the resource is of sub interface type and false otherwise
557 public static boolean isSubInterfaceResource(Resource resource, TranslationContext context) {
558 //Check if resource group is a nested resource
559 if (!isNestedResource(resource)) {
562 Optional<String> nestedHeatFileName = HeatToToscaUtil.getNestedHeatFileName(resource);
563 return nestedHeatFileName.filter(fileName -> isNestedVlanResource(fileName, context)).isPresent();
566 private static boolean isNestedVlanResource(String nestedHeatFileName, TranslationContext translationContext) {
567 HeatOrchestrationTemplate nestedHeatOrchestrationTemplate = new YamlUtil().yamlToObject(
568 translationContext.getFileContent(nestedHeatFileName), HeatOrchestrationTemplate.class);
569 return Objects.nonNull(nestedHeatOrchestrationTemplate.getResources()) && nestedHeatOrchestrationTemplate
570 .getResources().values()
572 new ContrailV2VirtualMachineInterfaceHelper()::isVlanSubInterfaceResource);
575 public static Optional<String> getSubInterfaceParentPortNodeTemplateId(TranslateTo subInterfaceTo) {
576 String subInterfaceResourceType = getSubInterfaceResourceType(subInterfaceTo.getResource());
577 HeatOrchestrationTemplate nestedHeatOrchestrationTemplate = new YamlUtil().yamlToObject(
578 subInterfaceTo.getContext().getFileContent(subInterfaceResourceType), HeatOrchestrationTemplate.class);
579 if (Objects.isNull(nestedHeatOrchestrationTemplate.getResources())) {
580 return Optional.empty();
582 for (Map.Entry<String, Resource> resourceEntry : nestedHeatOrchestrationTemplate.getResources().entrySet()) {
583 Resource resource = resourceEntry.getValue();
584 if (isVmiRefsPropertyExists(resource)) {
585 Object toscaPropertyValue = TranslatorHeatToToscaPropertyConverter
586 .getToscaPropertyValue(subInterfaceTo.getServiceTemplate(),
587 resourceEntry.getKey(),
588 HeatConstants.VMI_REFS_PROPERTY_NAME,
589 resource.getProperties()
590 .get(HeatConstants.VMI_REFS_PROPERTY_NAME),
591 resource.getType(), subInterfaceResourceType,
592 nestedHeatOrchestrationTemplate, null,
593 subInterfaceTo.getContext());
594 return getParentNodeTemplateIdFromPropertyValue(toscaPropertyValue, subInterfaceTo);
597 return Optional.empty();
600 private static boolean isVmiRefsPropertyExists(Resource resource) {
601 return HeatResourcesTypes.CONTRAIL_V2_VIRTUAL_MACHINE_INTERFACE_RESOURCE_TYPE.getHeatResource()
602 .equals(resource.getType())
603 && MapUtils.isNotEmpty(resource.getProperties()) && resource.getProperties().containsKey(
604 HeatConstants.VMI_REFS_PROPERTY_NAME);
607 public static String getSubInterfaceResourceType(Resource resource) {
608 if (!HeatToToscaUtil.isYamlFile(resource.getType())) {
609 return ((Map) resource.getProperties().get(HeatConstants.RESOURCE_DEF_PROPERTY_NAME))
610 .get(HeatConstants.RESOURCE_DEF_TYPE_PROPERTY_NAME).toString();
612 return resource.getType();
615 private static Optional<String> getParentNodeTemplateIdFromPropertyValue(Object toscaPropertyValue,
616 TranslateTo subInterfaceTo) {
617 if (toscaPropertyValue instanceof List && ((List) toscaPropertyValue).get(0) instanceof Map) {
618 Resource subInterfaceResource = subInterfaceTo.getResource();
619 Map<String, String> toscaPropertyValueMap = (Map) ((List) toscaPropertyValue).get(0);
620 String parentPortPropertyInput = toscaPropertyValueMap.get(ToscaFunctions.GET_INPUT.getDisplayName());
621 Map<String, Object> resourceDefPropertiesMap;
622 if (!isYamlFile(subInterfaceResource.getType())) {
623 resourceDefPropertiesMap =
624 (Map) ((Map) subInterfaceResource.getProperties().get(HeatConstants.RESOURCE_DEF_PROPERTY_NAME))
625 .get(HeatConstants.RESOURCE_DEF_PROPERTIES);
627 resourceDefPropertiesMap = subInterfaceResource.getProperties();
629 Object parentPortObj = resourceDefPropertiesMap.get(parentPortPropertyInput);
630 if (parentPortObj instanceof Map) {
631 Map<String, String> parentPortPropertyValue = (Map) parentPortObj;
632 if (parentPortPropertyValue.keySet().contains(ResourceReferenceFunctions.GET_RESOURCE.getFunction())) {
633 return ResourceTranslationBase.getResourceTranslatedId(subInterfaceTo.getHeatFileName(),
634 subInterfaceTo.getHeatOrchestrationTemplate(),
635 parentPortPropertyValue.get(ResourceReferenceFunctions.GET_RESOURCE.getFunction()),
636 subInterfaceTo.getContext());
640 return Optional.empty();
644 * Checks if the nested resource represents a VFC or a complex VFC (Heat file should contain at
645 * least one or more compute nodes).
647 * @param resource the resource
648 * @param context the context
649 * @return true if the resource represents a VFC and false otherwise.
651 public static boolean isNestedVfcResource(Resource resource, TranslationContext context) {
652 Optional<String> nestedHeatFileName = HeatToToscaUtil.getNestedHeatFileName(resource);
653 HeatOrchestrationTemplate nestedHeatOrchestrationTemplate = new YamlUtil().yamlToObject(
654 context.getFileContent(nestedHeatFileName.get()), HeatOrchestrationTemplate.class);
655 if (Objects.nonNull(nestedHeatOrchestrationTemplate.getResources())) {
656 for (String innerResourceId : nestedHeatOrchestrationTemplate.getResources().keySet()) {
657 if (ConsolidationDataUtil.isComputeResource(nestedHeatOrchestrationTemplate, innerResourceId)) {
666 * Get nested heat file name in case of nested resource.
668 * @param resource the resource
669 * @return the nested heat file name
671 private static Optional<String> getNestedHeatFileName(Resource resource) {
672 if (!isNestedResource(resource)) {
673 return Optional.empty();
676 String resourceType = resource.getType();
678 if (resourceType.equals(HeatResourcesTypes.RESOURCE_GROUP_RESOURCE_TYPE.getHeatResource())) {
679 Object resourceDef = resource.getProperties().get(HeatConstants.RESOURCE_DEF_PROPERTY_NAME);
680 String internalResourceType =
681 (String) ((Map) resourceDef).get(HeatConstants.RESOURCE_DEF_TYPE_PROPERTY_NAME);
682 return Optional.of(internalResourceType);
684 return Optional.of(resourceType);
690 * @param resource the resource
691 * @return the nested file
693 public static Optional<String> getNestedFile(Resource resource) {
694 if (!isNestedResource(resource)) {
695 return Optional.empty();
697 String resourceType = resource.getType();
698 if (resourceType.equals(HeatResourcesTypes.RESOURCE_GROUP_RESOURCE_TYPE.getHeatResource())) {
699 Object resourceDef = resource.getProperties().get(HeatConstants.RESOURCE_DEF_PROPERTY_NAME);
700 String internalResourceType =
701 (String) ((Map) resourceDef).get(HeatConstants.RESOURCE_DEF_TYPE_PROPERTY_NAME);
702 return Optional.of(internalResourceType);
704 return Optional.of(resourceType);
708 public static boolean isYamlFile(String fileName) {
709 return fileName.endsWith(".yaml") || fileName.endsWith(".yml");
715 * @param heatOrchestrationTemplate the heat orchestration template
716 * @param resourceId the resource id
717 * @param heatFileName the heat file name
718 * @return the resource
720 public static Resource getResource(HeatOrchestrationTemplate heatOrchestrationTemplate, String resourceId,
721 String heatFileName) {
722 Resource resource = heatOrchestrationTemplate.getResources().get(resourceId);
723 if (resource == null) {
724 throw new CoreException(new ResourceNotFoundInHeatFileErrorBuilder(resourceId, heatFileName).build());
733 * @param resourceId the resource id
734 * @param heatOrchestrationTemplate heat orchestration template
735 * @param heatFileName heat file name
736 * @return resource type
738 public static String getResourceType(String resourceId, HeatOrchestrationTemplate heatOrchestrationTemplate,
739 String heatFileName) {
740 return HeatToToscaUtil.getResource(heatOrchestrationTemplate, resourceId, heatFileName).getType();
744 * Is heat file nested boolean.
746 * @param translateTo the translate to
747 * @param heatFileName the heat file name
748 * @return the boolean
750 public static boolean isHeatFileNested(TranslateTo translateTo, String heatFileName) {
751 return isHeatFileNested(translateTo.getContext(), heatFileName);
754 public static boolean isHeatFileNested(TranslationContext context, String heatFileName) {
755 return context.getNestedHeatsFiles().contains(heatFileName);
759 * Extract contrail get resource attached heat resource id optional.
761 * @param propertyValue the property value
762 * @return the optional
764 public static Optional<String> extractContrailGetResourceAttachedHeatResourceId(Object propertyValue) {
765 if (propertyValue instanceof Map) {
766 if (((Map) propertyValue).containsKey(GET_ATTR)) {
767 return getResourceId(((Map) propertyValue).get(GET_ATTR));
768 } else if (((Map) propertyValue).containsKey(GET_RESOURCE)) {
769 return getHeatResourceIdFromResource((Map) propertyValue);
771 Collection valCollection = ((Map) propertyValue).values();
772 return evaluateHeatResourceId(valCollection);
774 } else if (propertyValue instanceof List) {
775 return evaluateHeatResourceId((List) propertyValue);
777 return Optional.empty();
780 private static Optional<String> getResourceId(Object data) {
781 if (data instanceof List && CollectionUtils.size(data) > 1 && FQ_NAME.equals(((List) data).get(1))
782 && ((List) data).get(0) instanceof String) {
783 return Optional.of((String) ((List) data).get(0));
785 LOGGER.warn("invalid format of 'get_attr' function - " + data.toString());
786 return Optional.empty();
790 private static Optional<String> getHeatResourceIdFromResource(Map propertyValue) {
791 Object value = propertyValue.get(GET_RESOURCE);
792 if (value instanceof String) {
793 return Optional.of((String) value);
795 LOGGER.warn("invalid format of 'get_resource' function - " + propertyValue.toString());
796 return Optional.empty();
800 private static Optional<String> evaluateHeatResourceId(Collection propertyValue) {
801 for (Object prop : propertyValue) {
802 Optional<String> ret = extractContrailGetResourceAttachedHeatResourceId(prop);
803 if (ret.isPresent()) {
807 return Optional.empty();
811 * Gets tosca service model.
813 * @param context translation context
814 * @return the tosca service model
816 public static ToscaServiceModel getToscaServiceModel(TranslationContext context) {
817 Map<String, String> metadata = new HashMap<>();
818 metadata.put(ToscaConstants.ST_METADATA_TEMPLATE_NAME, Constants.MAIN_TEMPLATE_NAME);
819 return getToscaServiceModel(context, metadata);
823 * Gets tosca service model.
825 * @param context translation context
826 * @param entryDefinitionMetadata template name of the entry definition servie template
827 * @return the tosca service model
829 private static ToscaServiceModel getToscaServiceModel(TranslationContext context,
830 Map<String, String> entryDefinitionMetadata) {
831 Map<String, ServiceTemplate> serviceTemplates = new HashMap<>(context.getGlobalServiceTemplates());
832 Collection<ServiceTemplate> tmpServiceTemplates = context.getTranslatedServiceTemplates().values();
833 for (ServiceTemplate serviceTemplate : tmpServiceTemplates) {
834 ToscaUtil.addServiceTemplateToMapWithKeyFileName(serviceTemplates, serviceTemplate);
836 return new ToscaServiceModel(null, serviceTemplates,
837 ToscaUtil.getServiceTemplateFileName(entryDefinitionMetadata));
841 * Gets service template from context.
843 * @param serviceTemplateFileName the service template file name
844 * @param context the context
845 * @return the service template from context
847 public static Optional<ServiceTemplate> getServiceTemplateFromContext(String serviceTemplateFileName,
848 TranslationContext context) {
849 for (ServiceTemplate serviceTemplate : context.getTranslatedServiceTemplates().values()) {
850 if (ToscaUtil.getServiceTemplateFileName(serviceTemplate).equals(serviceTemplateFileName)) {
851 return Optional.of(serviceTemplate);
854 return Optional.empty();
858 * Adding link requerment from port node template to network node template.
860 * @param portNodeTemplate port node template
861 * @param networkTranslatedId network node template id
863 public static RequirementAssignment addLinkReqFromPortToNetwork(NodeTemplate portNodeTemplate,
864 String networkTranslatedId) {
865 RequirementAssignment requirement = new RequirementAssignment();
866 requirement.setCapability(ToscaCapabilityType.NATIVE_NETWORK_LINKABLE);
867 requirement.setRelationship(ToscaRelationshipType.NATIVE_NETWORK_LINK_TO);
868 requirement.setNode(networkTranslatedId);
869 DataModelUtil.addRequirementAssignment(portNodeTemplate, ToscaConstants.LINK_REQUIREMENT_ID, requirement);
874 * Adding binding requerment from sub interface node template to interface (port) node template.
876 * @param subInterfaceNodeTemplate sub interface template
877 * @param interfaceTranslatedId interface node template id
879 public static void addBindingReqFromSubInterfaceToInterface(NodeTemplate subInterfaceNodeTemplate,
880 String interfaceTranslatedId) {
881 RequirementAssignment requirement = new RequirementAssignment();
882 requirement.setCapability(ToscaCapabilityType.NATIVE_NETWORK_BINDABLE);
883 requirement.setRelationship(ToscaRelationshipType.NATIVE_NETWORK_BINDS_TO);
884 requirement.setNode(interfaceTranslatedId);
886 .addRequirementAssignment(subInterfaceNodeTemplate, ToscaConstants.BINDING_REQUIREMENT_ID, requirement);
890 * Get property Parameter Name Value.
892 * @param property property
893 * @return Parameter name in case the property include "get_param" function
895 public static Optional<String> getPropertyParameterNameValue(Object property) {
896 if (Objects.isNull(property)) {
897 return Optional.empty();
899 Optional<AttachedPropertyVal> extractedProperty = extractProperty(property);
900 if (extractedProperty.isPresent()) {
901 return getParameterName(extractedProperty.get());
903 return Optional.empty();
906 private static Optional<String> getParameterName(AttachedPropertyVal extractedProperty) {
907 if (!extractedProperty.isGetParam()) {
908 return Optional.empty();
910 Object getParamFuncValue = extractedProperty.getPropertyValue();
911 if (getParamFuncValue instanceof String) {
912 return Optional.of((String) getParamFuncValue);
914 return Optional.of((String) ((List) getParamFuncValue).get(0));
918 public static String getToscaPropertyName(TranslationContext context, String heatResourceType,
919 String heatPropertyName) {
920 return context.getElementMapping(heatResourceType, Constants.PROP, heatPropertyName);
924 * Gets tosca property name.
926 * @param translateTo the translate to
927 * @param heatPropertyName the heat property name
928 * @return the tosca property name
930 public static String getToscaPropertyName(TranslateTo translateTo, String heatPropertyName) {
931 return translateTo.getContext()
932 .getElementMapping(translateTo.getResource().getType(), Constants.PROP, heatPropertyName);
936 * Gets tosca attribute name.
938 * @param context the context
939 * @param heatResourceType the heat resource type
940 * @param heatAttrName the heat attr name
941 * @return the tosca attribute name
943 public static String getToscaAttributeName(TranslationContext context, String heatResourceType,
944 String heatAttrName) {
945 return context.getElementMapping(heatResourceType, Constants.ATTR, heatAttrName);
949 * Gets tosca attribute name.
951 * @param translateTo the translate to
952 * @param heatAttrName the heat attr name
953 * @return the tosca attribute name
955 public static String getToscaAttributeName(TranslateTo translateTo, String heatAttrName) {
956 return translateTo.getContext()
957 .getElementMapping(translateTo.getResource().getType(), Constants.ATTR, heatAttrName);
961 * Create init substitution service template service template.
963 * @param templateName the template name
964 * @return the service template
966 public static ServiceTemplate createInitSubstitutionServiceTemplate(String templateName) {
967 ServiceTemplate nestedSubstitutionServiceTemplate = new ServiceTemplate();
968 Map<String, String> templateMetadata = new HashMap<>();
969 templateMetadata.put(ToscaConstants.ST_METADATA_TEMPLATE_NAME, templateName);
970 nestedSubstitutionServiceTemplate.setMetadata(templateMetadata);
971 nestedSubstitutionServiceTemplate.setTosca_definitions_version(ToscaConstants.TOSCA_DEFINITIONS_VERSION);
972 nestedSubstitutionServiceTemplate.setTopology_template(new TopologyTemplate());
973 List<Map<String, Import>> globalTypesImportList = GlobalTypesGenerator.getGlobalTypesImportList();
974 globalTypesImportList
975 .addAll(HeatToToscaUtil.createImportList(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME));
976 nestedSubstitutionServiceTemplate.setImports(globalTypesImportList);
977 return nestedSubstitutionServiceTemplate;
981 * Create init global substitution service template service template.
983 * @return the service template
985 private static ServiceTemplate createInitGlobalSubstitutionServiceTemplate() {
986 ServiceTemplate globalSubstitutionServiceTemplate = new ServiceTemplate();
987 Map<String, String> templateMetadata = new HashMap<>();
989 .put(ToscaConstants.ST_METADATA_TEMPLATE_NAME, Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME);
990 globalSubstitutionServiceTemplate.setMetadata(templateMetadata);
991 globalSubstitutionServiceTemplate.setImports(GlobalTypesGenerator.getGlobalTypesImportList());
992 globalSubstitutionServiceTemplate.setTosca_definitions_version(ToscaConstants.TOSCA_DEFINITIONS_VERSION);
993 return globalSubstitutionServiceTemplate;
997 * Create substitution node type node type.
999 * @param substitutionServiceTemplate the substitution service template
1000 * @return the node type
1002 public NodeType createSubstitutionNodeType(ServiceTemplate substitutionServiceTemplate) {
1003 NodeType substitutionNodeType = new NodeType();
1004 substitutionNodeType.setDerived_from(ToscaNodeType.ABSTRACT_SUBSTITUTE);
1005 substitutionNodeType.setDescription(substitutionServiceTemplate.getDescription());
1006 substitutionNodeType.setProperties(manageSubstitutionNodeTypeProperties(substitutionServiceTemplate));
1007 substitutionNodeType.setAttributes(manageSubstitutionNodeTypeAttributes(substitutionServiceTemplate));
1008 return substitutionNodeType;
1011 private Map<String, PropertyDefinition> manageSubstitutionNodeTypeProperties(ServiceTemplate substitutionServiceTemplate) {
1012 Map<String, PropertyDefinition> substitutionNodeTypeProperties = new HashMap<>();
1013 Map<String, ParameterDefinition> properties = substitutionServiceTemplate.getTopology_template().getInputs();
1014 if (properties == null) {
1018 PropertyDefinition propertyDefinition;
1019 String toscaPropertyName;
1020 for (Map.Entry<String, ParameterDefinition> entry : properties.entrySet()) {
1021 toscaPropertyName = entry.getKey();
1022 propertyDefinition = new PropertyDefinition();
1023 ParameterDefinition parameterDefinition =
1024 substitutionServiceTemplate.getTopology_template().getInputs().get(toscaPropertyName);
1025 propertyDefinition.setType(parameterDefinition.getType());
1026 propertyDefinition.setDescription(parameterDefinition.getDescription());
1027 propertyDefinition.setRequired(parameterDefinition.getRequired());
1028 propertyDefinition.set_default(parameterDefinition.get_default());
1029 propertyDefinition.setConstraints(parameterDefinition.getConstraints());
1030 propertyDefinition.setEntry_schema(parameterDefinition.getEntry_schema());
1031 propertyDefinition.setStatus(parameterDefinition.getStatus());
1032 substitutionNodeTypeProperties.put(toscaPropertyName, propertyDefinition);
1034 return substitutionNodeTypeProperties;
1037 private Map<String, AttributeDefinition> manageSubstitutionNodeTypeAttributes(ServiceTemplate substitutionServiceTemplate) {
1038 Map<String, AttributeDefinition> substitutionNodeTypeAttributes = new HashMap<>();
1039 Map<String, ParameterDefinition> attributes = substitutionServiceTemplate.getTopology_template().getOutputs();
1040 if (attributes == null) {
1043 AttributeDefinition attributeDefinition;
1044 String toscaAttributeName;
1046 for (Map.Entry<String, ParameterDefinition> entry : attributes.entrySet()) {
1047 attributeDefinition = new AttributeDefinition();
1048 toscaAttributeName = entry.getKey();
1049 ParameterDefinition parameterDefinition =
1050 substitutionServiceTemplate.getTopology_template().getOutputs().get(toscaAttributeName);
1051 if (parameterDefinition.getType() != null && !parameterDefinition.getType().isEmpty()) {
1052 attributeDefinition.setType(parameterDefinition.getType());
1054 attributeDefinition.setType(PropertyType.STRING.getDisplayName());
1056 attributeDefinition.setDescription(parameterDefinition.getDescription());
1057 attributeDefinition.set_default(parameterDefinition.get_default());
1058 attributeDefinition.setEntry_schema(parameterDefinition.getEntry_schema());
1059 attributeDefinition.setStatus(parameterDefinition.getStatus());
1060 substitutionNodeTypeAttributes.put(toscaAttributeName, attributeDefinition);
1062 return substitutionNodeTypeAttributes;
1067 * Create and add substitution mapping to the nested substitution service template, and update
1068 * the subtitution node type accordingly with the exposed requerments and capabilities
1070 * @param context the translation context
1071 * @param substitutionNodeTypeKey the substitution node type key
1072 * @param nestedSubstitutionServiceTemplate the nested substitution service template
1073 * @param substitutionNodeType the substitution node type
1075 public static void handleSubstitutionMapping(TranslationContext context, String substitutionNodeTypeKey,
1076 ServiceTemplate nestedSubstitutionServiceTemplate,
1077 NodeType substitutionNodeType) {
1078 Map<String, Map<String, List<String>>> substitutionMapping =
1079 getSubstitutionNodeTypeExposedConnectionPoints(substitutionNodeType, nestedSubstitutionServiceTemplate,
1081 //add substitution mapping after capability and requirement expose calculation
1082 nestedSubstitutionServiceTemplate.getTopology_template().setSubstitution_mappings(DataModelUtil
1083 .createSubstitutionTemplateSubMapping(
1084 substitutionNodeTypeKey,
1085 substitutionNodeType,
1086 substitutionMapping));
1090 * Gets node type with flat hierarchy.
1092 * @param nodeTypeId the node type id
1093 * @param serviceTemplate the service template
1094 * @param context the context
1095 * @return the node type with flat hierarchy
1097 public static NodeType getNodeTypeWithFlatHierarchy(String nodeTypeId, ServiceTemplate serviceTemplate,
1098 TranslationContext context) {
1099 ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl();
1100 ToscaServiceModel toscaServiceModel =
1101 HeatToToscaUtil.getToscaServiceModel(context, serviceTemplate.getMetadata());
1102 return (NodeType) toscaAnalyzerService.getFlatEntity(ToscaElementTypes.NODE_TYPE, nodeTypeId, serviceTemplate,
1103 toscaServiceModel).getFlatEntity();
1108 * Create abstract substitution node template.
1110 * @param translateTo the translate to
1111 * @param templateName the template name
1112 * @param substitutionNodeTypeKey the substitution node type key
1113 * @return the abstract substitute node template
1115 public static NodeTemplate createAbstractSubstitutionNodeTemplate(TranslateTo translateTo, String templateName,
1116 String substitutionNodeTypeKey) {
1117 NodeTemplate substitutionNodeTemplate = new NodeTemplate();
1118 List<String> directiveList = new ArrayList<>();
1119 directiveList.add(ToscaConstants.NODE_TEMPLATE_DIRECTIVE_SUBSTITUTABLE);
1120 substitutionNodeTemplate.setDirectives(directiveList);
1121 substitutionNodeTemplate.setType(substitutionNodeTypeKey);
1122 substitutionNodeTemplate.setProperties(
1123 managerSubstitutionNodeTemplateProperties(translateTo, substitutionNodeTemplate, templateName));
1124 return substitutionNodeTemplate;
1129 * Checks if the source and target resource is a valid candidate for adding tosca dependency
1132 * @param sourceResource the source resource
1133 * @param targetResource the target resource
1134 * @param dependencyEntity the dependency entity
1135 * @return true if the candidate resources are a valid combination for the dependency relationship
1136 * and false otherwise
1138 public static boolean isValidDependsOnCandidate(Resource sourceResource, Resource targetResource,
1139 ConsolidationEntityType dependencyEntity,
1140 TranslationContext context) {
1141 dependencyEntity.setEntityType(sourceResource, targetResource, context);
1142 ConsolidationEntityType sourceEntityType = dependencyEntity.getSourceEntityType();
1143 ConsolidationEntityType targetEntityType = dependencyEntity.getTargetEntityType();
1145 return ConsolidationTypesConnectivity.isDependsOnRelationshipValid(sourceEntityType, targetEntityType);
1148 private static Map<String, Object> managerSubstitutionNodeTemplateProperties(TranslateTo translateTo,
1150 String templateName) {
1151 Map<String, Object> substitutionProperties = new HashMap<>();
1152 Map<String, Object> heatProperties = translateTo.getResource().getProperties();
1153 if (Objects.nonNull(heatProperties)) {
1154 for (Map.Entry<String, Object> entry : heatProperties.entrySet()) {
1155 Object property = TranslatorHeatToToscaPropertyConverter
1156 .getToscaPropertyValue(translateTo.getServiceTemplate(),
1157 translateTo.getTranslatedId(), entry.getKey(), entry.getValue(), null,
1158 translateTo.getHeatFileName(),
1159 translateTo.getHeatOrchestrationTemplate(), template,
1160 translateTo.getContext());
1161 substitutionProperties.put(entry.getKey(), property);
1164 return addAbstractSubstitutionProperty(templateName, substitutionProperties);
1167 private static Map<String, Object> addAbstractSubstitutionProperty(String templateName,
1168 Map<String, Object> substitutionProperties) {
1169 Map<String, Object> innerProps = new HashMap<>();
1170 innerProps.put(ToscaConstants.SUBSTITUTE_SERVICE_TEMPLATE_PROPERTY_NAME,
1171 ToscaUtil.getServiceTemplateFileName(templateName));
1172 substitutionProperties.put(ToscaConstants.SERVICE_TEMPLATE_FILTER_PROPERTY_NAME, innerProps);
1173 return substitutionProperties;
1176 private static Map<String, Map<String, List<String>>> getSubstitutionNodeTypeExposedConnectionPoints(NodeType substitutionNodeType,
1177 ServiceTemplate substitutionServiceTemplate,
1178 TranslationContext context) {
1179 Map<String, NodeTemplate> nodeTemplates =
1180 substitutionServiceTemplate.getTopology_template().getNode_templates();
1181 String nodeTemplateId;
1182 NodeTemplate nodeTemplate;
1184 Map<String, Map<String, List<String>>> substitutionMapping = new HashMap<>();
1185 if (nodeTemplates == null) {
1186 return substitutionMapping;
1189 Map<String, List<String>> capabilitySubstitutionMapping = new HashMap<>();
1190 Map<String, List<String>> requirementSubstitutionMapping = new HashMap<>();
1191 substitutionMapping.put("capability", capabilitySubstitutionMapping);
1192 substitutionMapping.put("requirement", requirementSubstitutionMapping);
1193 List<Map<String, RequirementDefinition>> nodeTypeRequirementsDefinition;
1194 Map<String, RequirementAssignment> nodeTemplateRequirementsAssignment;
1195 List<Map<String, RequirementDefinition>> exposedRequirementsDefinition;
1196 Map<String, Map<String, RequirementAssignment>> fullFilledRequirementsDefinition = new HashMap<>();
1197 Map<String, CapabilityDefinition> nodeTypeCapabilitiesDefinition = new HashMap<>();
1198 Map<String, CapabilityDefinition> exposedCapabilitiesDefinition;
1199 ToscaAnalyzerService toscaAnalyzerService = new ToscaAnalyzerServiceImpl();
1201 for (Map.Entry<String, NodeTemplate> entry : nodeTemplates.entrySet()) {
1202 nodeTemplateId = entry.getKey();
1203 nodeTemplate = entry.getValue();
1204 nodeType = nodeTemplate.getType();
1207 nodeTypeRequirementsDefinition = getNodeTypeReqs(nodeType, nodeTemplateId, substitutionServiceTemplate,
1208 requirementSubstitutionMapping, context);
1209 nodeTemplateRequirementsAssignment = DataModelUtil.getNodeTemplateRequirements(nodeTemplate);
1210 fullFilledRequirementsDefinition.put(nodeTemplateId, nodeTemplateRequirementsAssignment);
1211 //set substitution node type requirements
1212 exposedRequirementsDefinition = toscaAnalyzerService
1213 .calculateExposedRequirements(nodeTypeRequirementsDefinition,
1214 nodeTemplateRequirementsAssignment);
1215 DataModelUtil.addSubstitutionNodeTypeRequirements(substitutionNodeType, exposedRequirementsDefinition,
1219 addNodeTypeCapabilitiesToSubMapping(nodeTypeCapabilitiesDefinition, capabilitySubstitutionMapping, nodeType,
1220 nodeTemplateId, substitutionServiceTemplate, context);
1223 exposedCapabilitiesDefinition = toscaAnalyzerService
1224 .calculateExposedCapabilities(nodeTypeCapabilitiesDefinition,
1225 fullFilledRequirementsDefinition);
1226 DataModelUtil.addNodeTypeCapabilitiesDef(substitutionNodeType, exposedCapabilitiesDefinition);
1227 return substitutionMapping;
1230 private static void addNodeTypeCapabilitiesToSubMapping(Map<String, CapabilityDefinition> nodeTypeCapabilitiesDefinition,
1231 Map<String, List<String>> capabilitySubstitutionMapping,
1232 String type, String templateName,
1233 ServiceTemplate serviceTemplate,
1234 TranslationContext context) {
1235 NodeType flatNodeType = getNodeTypeWithFlatHierarchy(type, serviceTemplate, context);
1237 if (flatNodeType.getCapabilities() != null) {
1238 flatNodeType.getCapabilities().entrySet().stream().forEach(
1239 capabilityNodeEntry -> addCapabilityToSubMapping(templateName, capabilityNodeEntry,
1240 nodeTypeCapabilitiesDefinition, capabilitySubstitutionMapping));
1244 private static void addCapabilityToSubMapping(String templateName,
1245 Map.Entry<String, CapabilityDefinition> capabilityNodeEntry,
1246 Map<String, CapabilityDefinition> nodeTypeCapabilitiesDefinition,
1247 Map<String, List<String>> capabilitySubstitutionMapping) {
1248 String capabilityKey;
1249 List<String> capabilityMapping;
1250 capabilityKey = capabilityNodeEntry.getKey() + UNDERSCORE + templateName;
1251 nodeTypeCapabilitiesDefinition.put(capabilityKey, capabilityNodeEntry.getValue().clone());
1252 capabilityMapping = new ArrayList<>();
1253 capabilityMapping.add(templateName);
1254 capabilityMapping.add(capabilityNodeEntry.getKey());
1255 capabilitySubstitutionMapping.put(capabilityKey, capabilityMapping);
1258 private static List<Map<String, RequirementDefinition>> getNodeTypeReqs(String type, String templateName,
1259 ServiceTemplate serviceTemplate,
1260 Map<String, List<String>> requirementSubstitutionMapping,
1261 TranslationContext context) {
1262 List<Map<String, RequirementDefinition>> requirementList = new ArrayList<>();
1263 NodeType flatNodeType = getNodeTypeWithFlatHierarchy(type, serviceTemplate, context);
1264 List<String> requirementMapping;
1266 if (flatNodeType.getRequirements() == null) {
1267 return requirementList;
1270 for (Map<String, RequirementDefinition> requirementMap : flatNodeType.getRequirements()) {
1271 for (Map.Entry<String, RequirementDefinition> requirementNodeEntry : requirementMap.entrySet()) {
1272 ToscaExtensionYamlUtil toscaExtensionYamlUtil = new ToscaExtensionYamlUtil();
1273 RequirementDefinition requirementNodeEntryValue = toscaExtensionYamlUtil.yamlToObject(
1274 toscaExtensionYamlUtil.objectToYaml(requirementNodeEntry.getValue()),
1275 RequirementDefinition.class);
1276 if (Objects.isNull(requirementNodeEntryValue.getOccurrences())) {
1277 requirementNodeEntryValue.setOccurrences(new Object[] {1, 1});
1279 Map<String, RequirementDefinition> requirementDef = new HashMap<>();
1280 requirementDef.put(requirementNodeEntry.getKey(), requirementNodeEntryValue);
1281 DataModelUtil.addRequirementToList(requirementList, requirementDef);
1282 requirementMapping = new ArrayList<>();
1283 requirementMapping.add(templateName);
1284 requirementMapping.add(requirementNodeEntry.getKey());
1285 requirementSubstitutionMapping
1286 .put(requirementNodeEntry.getKey() + UNDERSCORE + templateName, requirementMapping);
1287 if (Objects.isNull(requirementNodeEntryValue.getNode())) {
1288 requirementNodeEntryValue.setOccurrences(new Object[] {1, 1});
1292 return requirementList;
1296 * Fetch global substitution service template service template.
1298 * @param serviceTemplate the service template
1299 * @param context the context
1300 * @return the service template
1302 public static ServiceTemplate fetchGlobalSubstitutionServiceTemplate(ServiceTemplate serviceTemplate,
1303 TranslationContext context) {
1304 ServiceTemplate globalSubstitutionServiceTemplate =
1305 context.getTranslatedServiceTemplates().get(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME);
1306 if (globalSubstitutionServiceTemplate == null) {
1307 globalSubstitutionServiceTemplate = HeatToToscaUtil.createInitGlobalSubstitutionServiceTemplate();
1308 context.getTranslatedServiceTemplates()
1309 .put(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME, globalSubstitutionServiceTemplate);
1311 boolean isImportAddedToServiceTemplate = DataModelUtil
1312 .isImportAddedToServiceTemplate(serviceTemplate.getImports(),
1313 Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME);
1314 if (!isImportAddedToServiceTemplate) {
1315 serviceTemplate.getImports()
1316 .addAll(HeatToToscaUtil.createImportList(Constants.GLOBAL_SUBSTITUTION_TYPES_TEMPLATE_NAME));
1318 return globalSubstitutionServiceTemplate;
1321 public static List<Map<String, Import>> createImportList(String templateName) {
1322 List<Map<String, Import>> imports = new ArrayList<>();
1323 Map<String, Import> importsMap = new HashMap<>();
1324 importsMap.put(templateName, HeatToToscaUtil.createServiceTemplateImport(templateName));
1325 imports.add(importsMap);
1330 * Create service template import import.
1332 * @param serviceTemplate the service template
1333 * @return the import
1335 public static Import createServiceTemplateImport(ServiceTemplate serviceTemplate) {
1336 Import serviceTemplateImport = new Import();
1337 serviceTemplateImport.setFile(ToscaUtil.getServiceTemplateFileName(serviceTemplate));
1338 return serviceTemplateImport;
1342 * Create service template import import.
1344 * @param metadataTemplateName the service template name
1345 * @return the import
1347 private static Import createServiceTemplateImport(String metadataTemplateName) {
1348 Import serviceTemplateImport = new Import();
1349 serviceTemplateImport.setFile(ToscaUtil.getServiceTemplateFileName(metadataTemplateName));
1350 return serviceTemplateImport;
1353 public static ToscaServiceModel createToscaServiceModel(ServiceTemplate entryDefinitionServiceTemplate,
1354 TranslationContext translationContext) {
1355 return new ToscaServiceModel(getCsarArtifactFiles(translationContext), getServiceTemplates(translationContext),
1356 ToscaUtil.getServiceTemplateFileName(entryDefinitionServiceTemplate));
1359 private static FileContentHandler getCsarArtifactFiles(TranslationContext translationContext) {
1360 FileContentHandler artifactFiles = new FileContentHandler();
1361 artifactFiles.setFiles(translationContext.getFiles());
1362 artifactFiles.setFiles(translationContext.getExternalArtifacts());
1364 HeatTreeManager heatTreeManager = HeatTreeManagerUtil.initHeatTreeManager(translationContext.getFiles());
1365 heatTreeManager.createTree();
1366 ValidationStructureList validationStructureList = new ValidationStructureList(heatTreeManager.getTree());
1367 byte[] validationStructureFile =
1368 FileUtils.convertToBytes(validationStructureList, FileUtils.FileExtension.JSON);
1369 artifactFiles.addFile("HEAT.meta", validationStructureFile);
1370 return artifactFiles;
1374 private static Map<String, ServiceTemplate> getServiceTemplates(TranslationContext translationContext) {
1375 List<ServiceTemplate> serviceTemplates = new ArrayList<>();
1376 serviceTemplates.addAll(GlobalTypesGenerator.getGlobalTypesServiceTemplate(OnboardingTypesEnum.ZIP).values());
1377 serviceTemplates.addAll(translationContext.getTranslatedServiceTemplates().values());
1378 Map<String, ServiceTemplate> serviceTemplatesMap = new HashMap<>();
1380 for (ServiceTemplate template : serviceTemplates) {
1381 serviceTemplatesMap.put(ToscaUtil.getServiceTemplateFileName(template), template);
1383 return serviceTemplatesMap;
1386 public static String getNestedResourceTypePrefix(TranslateTo translateTo) {
1387 if (isSubInterfaceResource(translateTo.getResource(), translateTo.getContext()) && isSubInterfaceBoundToPort(
1389 return ToscaNodeType.VLAN_SUB_INTERFACE_RESOURCE_TYPE_PREFIX;
1391 return ToscaNodeType.NESTED_HEAT_RESOURCE_TYPE_PREFIX;
1394 private static boolean isSubInterfaceBoundToPort(TranslateTo translateTo) {
1395 return HeatToToscaUtil.getSubInterfaceParentPortNodeTemplateId(translateTo).isPresent();
1398 //Method evaluate the network role from sub interface node template id, designed considering
1399 // only single sub interface present in nested file else it will return null
1400 public static Optional<String> getNetworkRoleFromSubInterfaceId(Resource resource,
1401 TranslationContext translationContext) {
1402 Optional<String> networkRole = Optional.empty();
1403 Optional<String> nestedHeatFileName = HeatToToscaUtil.getNestedHeatFileName(resource);
1405 if (!nestedHeatFileName.isPresent()) {
1409 HeatOrchestrationTemplate nestedHeatOrchestrationTemplate = new YamlUtil().yamlToObject(
1410 translationContext.getFileContent(nestedHeatFileName.get()), HeatOrchestrationTemplate.class);
1412 if (MapUtils.isNotEmpty(nestedHeatOrchestrationTemplate.getResources())) {
1413 ContrailV2VirtualMachineInterfaceHelper contrailV2VirtualMachineInterfaceHelper =
1414 new ContrailV2VirtualMachineInterfaceHelper();
1415 Optional<Map.Entry<String, Resource>> vlanSubInterfaceResource =
1416 nestedHeatOrchestrationTemplate.getResources().entrySet().stream()
1417 .filter(resourceEntry -> contrailV2VirtualMachineInterfaceHelper
1418 .isVlanSubInterfaceResource(
1419 resourceEntry.getValue()))
1421 if (vlanSubInterfaceResource.isPresent()) {
1422 Map.Entry<String, Resource> vlanSubInterfaceResourceEntry = vlanSubInterfaceResource.get();
1423 networkRole = extractNetworkRoleFromSubInterfaceId(vlanSubInterfaceResourceEntry.getKey(),
1424 vlanSubInterfaceResourceEntry.getValue().getType());