Implement PNFD Model driven conversion
[sdc.git] / openecomp-be / lib / openecomp-tosca-converter-lib / openecomp-tosca-converter-core / src / main / java / org / openecomp / core / converter / impl / pnfd / PnfdTransformationEngine.java
1 /*
2  * ============LICENSE_START=======================================================
3  *  Copyright (C) 2019 Nordix Foundation
4  *  ================================================================================
5  *  Licensed under the Apache License, Version 2.0 (the "License");
6  *  you may not use this file except in compliance with the License.
7  *  You may obtain a copy of the License at
8  *
9  *        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.
15  *
16  *  SPDX-License-Identifier: Apache-2.0
17  *  ============LICENSE_END=========================================================
18  */
19
20 package org.openecomp.core.converter.impl.pnfd;
21
22 import java.io.InputStream;
23 import java.util.Collections;
24 import java.util.HashMap;
25 import java.util.List;
26 import java.util.Map;
27 import java.util.Set;
28 import java.util.stream.Collectors;
29 import org.apache.commons.collections.CollectionUtils;
30 import org.apache.commons.collections.MapUtils;
31 import org.onap.sdc.tosca.datatypes.model.ServiceTemplate;
32 import org.onap.sdc.tosca.datatypes.model.TopologyTemplate;
33 import org.openecomp.core.converter.ServiceTemplateReaderService;
34 import org.openecomp.core.converter.impl.pnfd.factory.PnfdBlockParserFactory;
35 import org.openecomp.core.converter.impl.pnfd.parser.ConversionQueryYamlParser;
36 import org.openecomp.core.converter.pnfd.model.Transformation;
37 import org.openecomp.core.converter.pnfd.model.TransformationBlock;
38 import org.openecomp.core.converter.pnfd.model.TransformationDescription;
39 import org.openecomp.sdc.logging.api.Logger;
40 import org.openecomp.sdc.logging.api.LoggerFactory;
41
42 /**
43  * Engine that manages the PNF Descriptor transformation process.
44  */
45 public class PnfdTransformationEngine {
46
47     private static final Logger LOGGER = LoggerFactory.getLogger(PnfdTransformationEngine.class);
48
49     private final ServiceTemplate templateTo;
50     private final ServiceTemplateReaderService templateFrom;
51     private final PnfdTransformationDescriptorReader pnfdTransformationDescriptorReader =
52         new PnfdTransformationDescriptorReader();
53     private TransformationDescription transformationDescription;
54     private Map<TransformationBlock, List<Transformation>> transformationGroupByBlockMap;
55     private final String descriptorResourcePath;
56
57     public PnfdTransformationEngine(final ServiceTemplateReaderService templateFrom, final ServiceTemplate templateTo) {
58         this(templateFrom, templateTo, "pnfdTransformationTemplate/model-driven-conversion.yaml");
59     }
60
61     //used for tests purposes
62     PnfdTransformationEngine(final ServiceTemplateReaderService templateFrom, final ServiceTemplate templateTo,
63             final String descriptorResourcePath) {
64         this.templateFrom = templateFrom;
65         this.templateTo = templateTo;
66         this.descriptorResourcePath = descriptorResourcePath;
67     }
68
69     /**
70      * Runs the transformation process.
71      */
72     public void transform() {
73         readDefinition();
74         initializeTopologyTemplate();
75         executeTransformations();
76     }
77
78     /**
79      * Initializes the topology template and its node template set.
80      */
81     private void initializeTopologyTemplate() {
82         TopologyTemplate topologyTemplate = templateTo.getTopology_template();
83         if (topologyTemplate == null) {
84             topologyTemplate = new TopologyTemplate();
85             templateTo.setTopology_template(topologyTemplate);
86         }
87         if (topologyTemplate.getNode_templates() == null) {
88             topologyTemplate.setNode_templates(new HashMap<>());
89         }
90     }
91
92     /**
93      * Reads the transformation description yaml file.
94      */
95     private void readDefinition() {
96         transformationDescription = pnfdTransformationDescriptorReader.parse(getDefinitionFileInputStream());
97     }
98
99     /**
100      * Execute all transformations specified in the descriptor.
101      */
102     private void executeTransformations() {
103         final Set<Transformation> transformationSet = transformationDescription.getTransformationSet();
104         if (CollectionUtils.isEmpty(transformationSet)) {
105             return;
106         }
107         transformationGroupByBlockMap = transformationSet.stream()
108             .filter(Transformation::isValid)
109             .collect(Collectors.groupingBy(Transformation::getBlock));
110         final Map<String, String> inputsToConvertMap = executeNodeTemplateTransformations();
111         executeGetInputFunctionTransformations(inputsToConvertMap);
112     }
113
114     /**
115      * Parses all topology_template node_template.
116      * @return
117      *  A map containing any input that was called with a get_input TOSCA function and its getInputFunction
118      *  transformation name
119      */
120     private Map<String, String> executeNodeTemplateTransformations() {
121         final List<Transformation> transformationList = transformationGroupByBlockMap
122             .get(TransformationBlock.NODE_TEMPLATE);
123         if (CollectionUtils.isEmpty(transformationList)) {
124             return Collections.emptyMap();
125         }
126
127         final Map<String, String> inputsToConvertMap = new HashMap<>();
128         transformationList.forEach(transformation ->
129             PnfdBlockParserFactory.getInstance().get(transformation).ifPresent(pnfParser -> {
130                 pnfParser.parse(templateFrom, templateTo);
131                 if (pnfParser.getInputAndTransformationNameMap().isPresent()) {
132                     inputsToConvertMap.putAll(pnfParser.getInputAndTransformationNameMap().get());
133                 }
134             }));
135         return inputsToConvertMap;
136     }
137
138     /**
139      * Parses all topology_template inputs called with a get_input TOSCA function.
140      * @param inputsToConvertMap    A map containing the topology_template input name and its conversion definition name
141      */
142     private void executeGetInputFunctionTransformations(final Map<String, String> inputsToConvertMap) {
143         final List<Transformation> transformationListOfGetInputFunction = transformationGroupByBlockMap
144             .get(TransformationBlock.GET_INPUT_FUNCTION);
145
146         if(MapUtils.isEmpty(inputsToConvertMap) || CollectionUtils.isEmpty(transformationListOfGetInputFunction)) {
147             return;
148         }
149
150         final Map<String, List<Transformation>> transformationByName = transformationListOfGetInputFunction.stream()
151             .collect(Collectors.groupingBy(Transformation::getName));
152
153         inputsToConvertMap.forEach((inputName, transformationName) -> {
154             final List<Transformation> transformationList = transformationByName.get(transformationName);
155             if (!CollectionUtils.isEmpty(transformationList)) {
156                 final Transformation transformation = transformationList.stream()
157                     .findFirst().orElse(null);
158                 if (transformation != null) {
159                     final Map<String, Object> conversionQueryMap = new HashMap<>();
160                     conversionQueryMap.put(inputName, null);
161                     transformation.setConversionQuery(ConversionQueryYamlParser.parse(conversionQueryMap));
162                     PnfdBlockParserFactory.getInstance().get(transformation)
163                         .ifPresent(pnfParser -> pnfParser.parse(templateFrom, templateTo));
164                 }
165             }
166         });
167     }
168
169     /**
170      * Gets the transformation definition yaml file path.
171      * @return The transformation definition yaml path.
172      */
173     private InputStream getDefinitionFileInputStream() {
174         final InputStream resourceAsStream = getClass().getClassLoader().getResourceAsStream(descriptorResourcePath);
175         if (resourceAsStream  == null) {
176             if (LOGGER.isErrorEnabled()) {
177                 LOGGER.error(String.format("Could not find resource '%s'", descriptorResourcePath));
178             }
179             return null;
180         }
181         return resourceAsStream;
182     }
183 }