70e78ec50f7bc502c15f28260c6b9969409c2d01
[aai/babel.git] / src / main / java / org / onap / aai / babel / parser / ArtifactGeneratorToscaParser.java
1 /**
2  * ============LICENSE_START=======================================================
3  * org.onap.aai
4  * ================================================================================
5  * Copyright © 2017-2018 AT&T Intellectual Property. All rights reserved.
6  * Copyright © 2017-2018 European Software Marketing Ltd.
7  * ================================================================================
8  * Licensed under the Apache License, Version 2.0 (the "License");
9  * you may not use this file except in compliance with the License.
10  * You may obtain a copy of the License at
11  *
12  *       http://www.apache.org/licenses/LICENSE-2.0
13  *
14  * Unless required by applicable law or agreed to in writing, software
15  * distributed under the License is distributed on an "AS IS" BASIS,
16  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
17  * See the License for the specific language governing permissions and
18  * limitations under the License.
19  * ============LICENSE_END=========================================================
20  */
21 package org.onap.aai.babel.parser;
22
23 import static org.onap.aai.babel.xml.generator.data.GeneratorConstants.GENERATOR_AAI_CONFIGFILE_NOT_FOUND;
24 import static org.onap.aai.babel.xml.generator.data.GeneratorConstants.GENERATOR_AAI_CONFIGLOCATION_NOT_FOUND;
25 import static org.onap.aai.babel.xml.generator.data.GeneratorConstants.GENERATOR_AAI_PROVIDING_SERVICE_METADATA_MISSING;
26 import static org.onap.aai.babel.xml.generator.data.GeneratorConstants.GENERATOR_AAI_PROVIDING_SERVICE_MISSING;
27
28 import java.io.File;
29 import java.io.FileInputStream;
30 import java.io.IOException;
31 import java.util.LinkedList;
32 import java.util.List;
33 import java.util.Map;
34 import java.util.Properties;
35 import java.util.stream.Collectors;
36
37 import org.onap.aai.babel.logging.LogHelper;
38 import org.onap.aai.babel.xml.generator.data.GeneratorConstants;
39 import org.onap.aai.babel.xml.generator.data.WidgetConfigurationUtil;
40 import org.onap.aai.babel.xml.generator.model.AllotedResource;
41 import org.onap.aai.babel.xml.generator.model.L3NetworkWidget;
42 import org.onap.aai.babel.xml.generator.model.Model;
43 import org.onap.aai.babel.xml.generator.model.ProvidingService;
44 import org.onap.aai.babel.xml.generator.model.Resource;
45 import org.onap.aai.babel.xml.generator.model.Service;
46 import org.onap.aai.babel.xml.generator.model.TunnelXconnectWidget;
47 import org.onap.aai.babel.xml.generator.model.VfModule;
48 import org.onap.aai.babel.xml.generator.model.Widget;
49 import org.onap.aai.babel.xml.generator.types.ModelType;
50 import org.onap.aai.cl.api.Logger;
51 import org.onap.sdc.tosca.parser.api.ISdcCsarHelper;
52 import org.onap.sdc.toscaparser.api.Group;
53 import org.onap.sdc.toscaparser.api.NodeTemplate;
54 import org.onap.sdc.toscaparser.api.Property;
55
56 public class ArtifactGeneratorToscaParser {
57
58     public static final String GENERATOR_AAI_ERROR_INVALID_ID =
59             "Invalid value for mandatory attribute <%s> in Artifact: <%s>";
60     private static final String ALLOTTED_RESOURCE = "Allotted Resource";
61     private static final String TUNNEL_XCONNECT = "Tunnel XConnect";
62     private static Logger log = LogHelper.INSTANCE;
63
64     private ISdcCsarHelper csarHelper;
65
66     /**
67      * Constructs using csarHelper
68      *
69      * @param csarHelper The csar helper
70      */
71     public ArtifactGeneratorToscaParser(ISdcCsarHelper csarHelper) {
72         this.csarHelper = csarHelper;
73     }
74
75     /**
76      * Returns the artifact description
77      *
78      * @param model the artifact model
79      * @return the artifact model's description
80      */
81     public static String getArtifactDescription(Model model) {
82         String artifactDesc = model.getModelDescription();
83         if (model.getModelType().equals(ModelType.SERVICE)) {
84             artifactDesc = "AAI Service Model";
85         } else if (model.getModelType().equals(ModelType.RESOURCE)) {
86             artifactDesc = "AAI Resource Model";
87         }
88         return artifactDesc;
89     }
90
91     /**
92      * Initialises the widget configuration.
93      *
94      * @throws IOException
95      */
96     public static void initWidgetConfiguration() throws IOException {
97         log.debug("Getting Widget Configuration");
98         String configLocation = System.getProperty(GeneratorConstants.PROPERTY_ARTIFACT_GENERATOR_CONFIG_FILE);
99         if (configLocation != null) {
100             File file = new File(configLocation);
101             if (file.exists()) {
102                 Properties properties = new Properties();
103                 properties.load(new FileInputStream(file));
104                 WidgetConfigurationUtil.setConfig(properties);
105             } else {
106                 throw new IllegalArgumentException(String.format(GENERATOR_AAI_CONFIGFILE_NOT_FOUND, configLocation));
107             }
108         } else {
109             throw new IllegalArgumentException(GENERATOR_AAI_CONFIGLOCATION_NOT_FOUND);
110         }
111     }
112
113     /**
114      * Generates a Resource List using input Service Node Templates
115      *
116      * @param serviceNodes input Service Node Templates
117      * @param idTypeStore ID->Type mapping
118      * @return the processed resource models
119      */
120     public List<Resource> processResourceToscas(List<NodeTemplate> serviceNodes, Map<String, String> idTypeStore) {
121         List<Resource> resources = new LinkedList<>();
122         for (NodeTemplate serviceNode : serviceNodes) {
123             List<NodeTemplate> resourceNodes = csarHelper.getNodeTemplateChildren(serviceNode);
124
125             String resourceUuId = serviceNode.getMetaData().getValue("UUID");
126             String mapValue = idTypeStore.get(resourceUuId);
127             if (mapValue != null) {
128                 Model model = Model.getModelFor(idTypeStore.get(serviceNode.getMetaData().getValue("UUID")));
129
130                 log.debug("Inside Resource artifact generation for resource");
131                 Map<String, String> serviceMetadata = serviceNode.getMetaData().getAllProperties();
132                 model.populateModelIdentificationInformation(serviceMetadata);
133
134                 // Found model from the type store so removing the same
135                 idTypeStore.remove(model.getModelNameVersionId());
136                 processVfTosca(idTypeStore, model, resourceNodes);
137
138                 // Process group information from tosca for vfModules
139                 if (csarHelper.getServiceVfList() != null) {
140                     processVfModules(resources, model, serviceNode);
141                 }
142
143                 if (hasSubCategoryTunnelXConnect(serviceMetadata) && hasAllottedResource(serviceMetadata)) {
144                     model.addWidget(new TunnelXconnectWidget());
145                 }
146                 resources.add((Resource) model);
147             }
148         }
149         return resources;
150     }
151
152     private void processVfModules(List<Resource> resources, Model model, NodeTemplate serviceNode) {
153         // Get the customisation UUID for each VF node and use it to get its Groups
154         String uuid = csarHelper.getNodeTemplateCustomizationUuid(serviceNode);
155
156         // Populate a Map of Group against NodeTemplates that are members of the Group
157         List<Group> serviceGroups = csarHelper.getVfModulesByVf(uuid);
158
159         // Process each VF Group
160         for (Group serviceGroup : serviceGroups) {
161             Model groupModel = Model.getModelFor(serviceGroup.getType());
162             if (groupModel instanceof VfModule) {
163                 processVfModule(resources, model, serviceGroup, serviceNode, (VfModule) groupModel);
164             }
165         }
166
167     }
168
169     private void processVfModule(List<Resource> resources, Model model, Group groupDefinition, NodeTemplate serviceNode,
170             VfModule groupModel) {
171         // Populate group with metadata properties
172         groupModel.populateModelIdentificationInformation(groupDefinition.getMetadata().getAllProperties());
173         // Populate group with non-metadata properties
174         Map<String, Property> groupProperties = groupDefinition.getProperties();
175         Map<String, String> properties = populateStringProperties(groupProperties);
176         groupModel.populateModelIdentificationInformation(properties);
177         processVfModuleGroup(resources, model, groupDefinition, serviceNode, groupModel);
178     }
179
180     private void processVfModuleGroup(List<Resource> resources, Model model, Group groupDefinition,
181             NodeTemplate serviceNode, VfModule groupModel) {
182         // Get names of the members of the service group
183         List<NodeTemplate> members = csarHelper.getMembersOfVfModule(serviceNode, groupDefinition);
184         if (members != null && !members.isEmpty()) {
185             List<String> memberNames = members.stream().map(NodeTemplate::getName).collect(Collectors.toList());
186             groupModel.setMembers(memberNames);
187             for (NodeTemplate nodeTemplate : members) {
188                 processNodeTemplate(groupModel, nodeTemplate);
189             }
190         }
191
192         model.addResource(groupModel); // Added group (VfModule) to the (VF) model
193         // Check if we have already encountered the same VfModule across all the artifacts
194         if (!resources.contains(groupModel)) {
195             resources.add(groupModel);
196         }
197     }
198
199     private static void processNodeTemplate(Model group, NodeTemplate nodeTemplate) {
200         Model resourceNode;
201         // L3-network inside vf-module to be generated as Widget a special handling.
202         if (nodeTemplate.getType().contains("org.openecomp.resource.vl")) {
203             resourceNode = new L3NetworkWidget();
204         } else {
205             resourceNode = Model.getModelFor(nodeTemplate.getType());
206         }
207         if (resourceNode != null && !(resourceNode instanceof Resource)) {
208             Widget widget = (Widget) resourceNode;
209             widget.addKey(nodeTemplate.getName());
210             // Add the widget element encountered to the Group model
211             group.addWidget(widget);
212         }
213     }
214
215     /**
216      * Process the service tosca
217      *
218      * @param service model of the service artifact
219      * @param idTypeStore ID->Type mapping
220      * @param nodeTemplates a list of service nodes
221      *
222      */
223     public void processServiceTosca(Service service, Map<String, String> idTypeStore,
224             List<NodeTemplate> nodeTemplates) {
225         log.debug("Inside Service Tosca ");
226         // Get the resource/widgets in the service according to the node-template types
227         for (NodeTemplate node : nodeTemplates) {
228             Model model = Model.getModelFor(correctNodeType(node));
229             if (model != null) {
230                 model.populateModelIdentificationInformation(node.getMetaData().getAllProperties());
231                 if (model instanceof Resource) {
232                     // Keeping track of resource types and
233                     // their uuid for identification during resource tosca processing
234                     idTypeStore.put(model.getModelNameVersionId(), correctNodeType(node));
235                     service.addResource((Resource) model);
236                 } else {
237                     service.addWidget((Widget) model);
238                 }
239             }
240         }
241     }
242
243     private String correctNodeType(NodeTemplate nodeType) {
244         String correctedNodeType = nodeType.getType();
245         if (hasAllottedResource(nodeType.getMetaData().getAllProperties())) {
246             if (nodeType.getType().contains("org.openecomp.resource.vf.")) {
247                 correctedNodeType = "org.openecomp.resource.vf.allottedResource";
248             }
249             if (nodeType.getType().contains("org.openecomp.resource.vfc.")) {
250                 correctedNodeType = "org.openecomp.resource.vfc.AllottedResource";
251             }
252         }
253         return correctedNodeType;
254     }
255
256     private boolean hasAllottedResource(Map<String, String> metadata) {
257         return ALLOTTED_RESOURCE.equals(metadata.get(GeneratorConstants.CATEGORY));
258     }
259
260     private boolean hasSubCategoryTunnelXConnect(Map<String, String> metadata) {
261         return TUNNEL_XCONNECT.equals(metadata.get(GeneratorConstants.SUBCATEGORY));
262     }
263
264     /**
265      * Create a Map of property name against String property value from the input Map
266      *
267      * @param inputMap The input Map
268      * @return Map of property name against String property value
269      */
270     private Map<String, String> populateStringProperties(Map<String, Property> inputMap) {
271         return inputMap.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey,
272                 e -> e.getValue().getValue() == null ? "" : e.getValue().getValue().toString()));
273     }
274
275     private void processVfTosca(Map<String, String> idTypeStore, Model model, List<NodeTemplate> resourceNodes) {
276         boolean flag = false;
277
278         for (NodeTemplate resourceNodeTemplate : resourceNodes) {
279             Model resourceNode = Model.getModelFor(correctNodeType(resourceNodeTemplate));
280             if (resourceNode instanceof ProvidingService) {
281                 flag = true;
282                 Map<String, Property> nodeProperties = resourceNodeTemplate.getProperties();
283                 if (nodeProperties.get("providing_service_uuid") == null
284                         || nodeProperties.get("providing_service_invariant_uuid") == null) {
285                     throw new IllegalArgumentException(
286                             String.format(GENERATOR_AAI_PROVIDING_SERVICE_METADATA_MISSING, model.getModelId()));
287                 }
288                 Map<String, String> properties = populateStringProperties(nodeProperties);
289                 properties.put(GeneratorConstants.VERSION, "1.0");
290                 resourceNode.populateModelIdentificationInformation(properties);
291                 model.addResource((Resource) resourceNode);
292             } else if (resourceNode instanceof Resource && !(resourceNode.getWidgetType().equals(Widget.Type.L3_NET))) {
293                 idTypeStore.put(resourceNode.getModelNameVersionId(), correctNodeType(resourceNodeTemplate));
294                 model.addResource((Resource) resourceNode);
295             }
296         }
297
298         if (model instanceof AllotedResource && !flag) {
299             throw new IllegalArgumentException(
300                     String.format(GENERATOR_AAI_PROVIDING_SERVICE_MISSING, model.getModelId()));
301         }
302     }
303 }