d6d0a1e97a063ab32ac8e8d6bfdcc34b499b2530
[aai/babel.git] / src / main / java / org / onap / aai / babel / xml / generator / api / AaiArtifactGenerator.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.xml.generator.api;
22
23 import java.io.IOException;
24 import java.nio.file.Files;
25 import java.nio.file.Path;
26 import java.util.ArrayList;
27 import java.util.List;
28 import java.util.Map;
29 import org.apache.commons.io.FileUtils;
30 import org.apache.commons.lang3.StringUtils;
31 import org.onap.aai.babel.logging.ApplicationMsgs;
32 import org.onap.aai.babel.logging.LogHelper;
33 import org.onap.aai.babel.parser.ArtifactGeneratorToscaParser;
34 import org.onap.aai.babel.xml.generator.data.AdditionalParams;
35 import org.onap.aai.babel.xml.generator.data.Artifact;
36 import org.onap.aai.babel.xml.generator.data.ArtifactType;
37 import org.onap.aai.babel.xml.generator.data.GenerationData;
38 import org.onap.aai.babel.xml.generator.data.GeneratorUtil;
39 import org.onap.aai.babel.xml.generator.data.GroupType;
40 import org.onap.aai.babel.xml.generator.data.WidgetConfigurationUtil;
41 import org.onap.aai.babel.xml.generator.model.Model;
42 import org.onap.aai.babel.xml.generator.model.ProvidingService;
43 import org.onap.aai.babel.xml.generator.model.Resource;
44 import org.onap.aai.babel.xml.generator.model.Service;
45 import org.onap.aai.babel.xml.generator.model.TunnelXconnectWidget;
46 import org.onap.aai.cl.api.Logger;
47 import org.onap.sdc.tosca.parser.api.ISdcCsarHelper;
48 import org.onap.sdc.tosca.parser.impl.SdcToscaParserFactory;
49 import org.onap.sdc.toscaparser.api.Group;
50 import org.onap.sdc.toscaparser.api.NodeTemplate;
51 import org.slf4j.MDC;
52
53 public class AaiArtifactGenerator implements ArtifactGenerator {
54
55     private static Logger log = LogHelper.INSTANCE;
56
57     private static final String MDC_PARAM_MODEL_INFO = "ARTIFACT_MODEL_INFO";
58     private static final String GENERATOR_AAI_GENERATED_ARTIFACT_EXTENSION = "xml";
59     private static final String GENERATOR_AAI_ERROR_MISSING_SERVICE_TOSCA =
60             "Service tosca missing from list of input artifacts";
61     private static final String GENERATOR_AAI_ERROR_MISSING_SERVICE_VERSION =
62             "Cannot generate artifacts. Service version is not specified";
63     private static final String GENERATOR_AAI_INVALID_SERVICE_VERSION =
64             "Cannot generate artifacts. Service version is incorrect";
65
66     private AaiModelGenerator modelGenerator = new AaiModelGeneratorImpl();
67
68     @Override
69     public GenerationData generateArtifact(byte[] csarArchive, List<Artifact> input,
70             Map<String, String> additionalParams) {
71         Path csarPath;
72
73         try {
74             csarPath = createTempFile(csarArchive);
75         } catch (IOException e) {
76             log.error(ApplicationMsgs.TEMP_FILE_ERROR, e);
77             return createErrorData(e);
78         }
79
80         try {
81             ArtifactGeneratorToscaParser.initWidgetConfiguration();
82             ArtifactGeneratorToscaParser.initGroupFilterConfiguration();
83             ISdcCsarHelper csarHelper =
84                     SdcToscaParserFactory.getInstance().getSdcCsarHelper(csarPath.toAbsolutePath().toString());
85             return generateAllArtifacts(validateServiceVersion(additionalParams), csarHelper);
86         } catch (Exception e) {
87             log.error(ApplicationMsgs.INVALID_CSAR_FILE, e);
88             return createErrorData(e);
89         } finally {
90             FileUtils.deleteQuietly(csarPath.toFile());
91         }
92     }
93
94     private GenerationData createErrorData(Exception e) {
95         GenerationData generationData = new GenerationData();
96         generationData.add(ArtifactType.AAI.name(), e.getMessage());
97         return generationData;
98     }
99
100     /**
101      * Generate model artifacts for the Service and its associated Resources.
102      *
103      * @param serviceVersion
104      * @param csarHelper
105      *            interface to the TOSCA parser
106      * @return the generated Artifacts (containing XML models)
107      */
108     private GenerationData generateAllArtifacts(final String serviceVersion, ISdcCsarHelper csarHelper) {
109         List<NodeTemplate> serviceNodeTemplates = csarHelper.getServiceNodeTemplates();
110         if (serviceNodeTemplates == null) {
111             throw new IllegalArgumentException(GENERATOR_AAI_ERROR_MISSING_SERVICE_TOSCA);
112         }
113
114         Service serviceModel = createServiceModel(serviceVersion, csarHelper.getServiceMetadataAllProperties());
115
116         MDC.put(MDC_PARAM_MODEL_INFO, serviceModel.getModelName() + "," + getArtifactLabel(serviceModel));
117
118         List<Resource> resources = generateResourceModels(csarHelper, serviceNodeTemplates, serviceModel);
119
120         // Generate the A&AI XML model for the Service.
121         final String serviceArtifact = modelGenerator.generateModelFor(serviceModel);
122
123         // Build a Babel Artifact to be returned to the caller.
124         GenerationData generationData = new GenerationData();
125         generationData.add(getServiceArtifact(serviceModel, serviceArtifact));
126
127         // For each Resource, generate the A&AI XML model and then create an additional Artifact for that model.
128         for (Resource resource : resources) {
129             generateResourceArtifact(generationData, resource);
130             for (Resource childResource : resource.getResources()) {
131                 if (!(childResource instanceof ProvidingService)) {
132                     generateResourceArtifact(generationData, childResource);
133                 }
134             }
135         }
136
137         return generationData;
138     }
139
140     /**
141      * Create a Service from the provided metadata
142      *
143      * @param serviceVersion
144      * @param properties
145      * @return
146      */
147     private Service createServiceModel(final String serviceVersion, Map<String, String> properties) {
148         log.debug("Processing (TOSCA) Service object");
149         Service serviceModel = new Service();
150         serviceModel.setModelVersion(serviceVersion);
151         serviceModel.populateModelIdentificationInformation(properties);
152         return serviceModel;
153     }
154
155     /**
156      * @param csarHelper
157      * @param serviceNodeTemplates
158      * @param serviceModel
159      * @return the generated Models
160      */
161     private List<Resource> generateResourceModels(ISdcCsarHelper csarHelper, List<NodeTemplate> serviceNodeTemplates,
162             Service serviceModel) {
163         final List<Group> serviceGroups = csarHelper.getGroupsOfTopologyTemplate();
164         final ArtifactGeneratorToscaParser parser = new ArtifactGeneratorToscaParser(csarHelper);
165
166         List<Resource> resources = new ArrayList<>();
167
168         for (NodeTemplate nodeTemplate : serviceNodeTemplates) {
169             if (nodeTemplate.getMetaData() != null) {
170                 generateModelFromNodeTemplate(csarHelper, serviceModel, resources, serviceGroups, parser, nodeTemplate);
171             } else {
172                 log.warn(ApplicationMsgs.MISSING_SERVICE_METADATA, nodeTemplate.getName());
173             }
174         }
175
176         return resources;
177     }
178
179     private void generateModelFromNodeTemplate(ISdcCsarHelper csarHelper, Service serviceModel,
180             List<Resource> resources, final List<Group> serviceGroups, ArtifactGeneratorToscaParser parser,
181             NodeTemplate nodeTemplate) {
182         String nodeTypeName = parser.normaliseNodeTypeName(nodeTemplate);
183         Model model = Model.getModelFor(nodeTypeName, nodeTemplate.getMetaData().getValue("type"));
184         if (model != null) {
185             if (nodeTemplate.getMetaData() != null) {
186                 model.populateModelIdentificationInformation(nodeTemplate.getMetaData().getAllProperties());
187             }
188
189             parser.addRelatedModel(serviceModel, model);
190             if (model instanceof Resource) {
191                 generateResourceModel(csarHelper, resources, parser, nodeTemplate, nodeTypeName);
192             }
193         } else {
194             for (Group group : serviceGroups) {
195                 if (group.getMembers().contains(nodeTemplate.getName())
196                         && WidgetConfigurationUtil.isSupportedInstanceGroup(group.getType())) {
197                     log.debug(String.format("Adding group %s (type %s) with members %s", group.getName(),
198                             group.getType(), group.getMembers()));
199
200                     Resource groupModel = parser.createInstanceGroupModel(
201                             parser.mergeProperties(group.getMetadata().getAllProperties(), group.getProperties()));
202                     serviceModel.addResource(groupModel);
203                     resources.add(groupModel);
204                 }
205             }
206         }
207     }
208
209     private void generateResourceModel(ISdcCsarHelper csarHelper, List<Resource> resources,
210             ArtifactGeneratorToscaParser parser, NodeTemplate nodeTemplate, String nodeTypeName) {
211         log.debug("Processing resource " + nodeTypeName + ": " + nodeTemplate.getMetaData().getValue("UUID"));
212         Model resourceModel = Model.getModelFor(nodeTypeName, nodeTemplate.getMetaData().getValue("type"));
213
214         Map<String, String> serviceMetadata = nodeTemplate.getMetaData().getAllProperties();
215         resourceModel.populateModelIdentificationInformation(serviceMetadata);
216
217         parser.processResourceModels(resourceModel, csarHelper.getNodeTemplateChildren(nodeTemplate));
218
219         if (csarHelper.getServiceVfList() != null) {
220             parser.processVfModules(resources, resourceModel, nodeTemplate);
221         }
222
223         if (parser.hasSubCategoryTunnelXConnect(serviceMetadata) && parser.hasAllottedResource(serviceMetadata)) {
224             resourceModel.addWidget(new TunnelXconnectWidget());
225         }
226
227         resources.addAll(parser.processInstanceGroups(resourceModel, nodeTemplate));
228         resources.add((Resource) resourceModel);
229     }
230
231     /**
232      * @param generationData
233      * @param resource
234      */
235     private void generateResourceArtifact(GenerationData generationData, Resource resource) {
236         if (!isContained(generationData, getArtifactName(resource))) {
237             log.info(ApplicationMsgs.DISTRIBUTION_EVENT, "Generating resource model");
238             generationData.add(getResourceArtifact(resource, modelGenerator.generateModelFor(resource)));
239         }
240     }
241
242     private Path createTempFile(byte[] bytes) throws IOException {
243         log.debug("Creating temp file on file system for the csar");
244         Path path = Files.createTempFile("temp", ".csar");
245         Files.write(path, bytes);
246         return path;
247     }
248
249     /**
250      * Create the artifact label for an AAI model.
251      *
252      * @param model
253      * @return the artifact label as String
254      */
255     private String getArtifactLabel(Model model) {
256         StringBuilder artifactName = new StringBuilder(ArtifactType.AAI.name());
257         artifactName.append("-");
258         artifactName.append(model.getModelType().name().toLowerCase());
259         artifactName.append("-");
260         artifactName.append(hashCodeUuId(model.getModelNameVersionId()));
261         return (artifactName.toString()).replaceAll("[^a-zA-Z0-9 +]+", "-");
262     }
263
264     /**
265      * Method to generate the artifact name for an AAI model.
266      *
267      * @param model
268      *            AAI artifact model
269      * @return Model artifact name
270      */
271     private String getArtifactName(Model model) {
272         StringBuilder artifactName = new StringBuilder(ArtifactType.AAI.name());
273         artifactName.append("-");
274
275         String truncatedArtifactName = truncateName(model.getModelName());
276         artifactName.append(truncatedArtifactName);
277
278         artifactName.append("-");
279         artifactName.append(model.getModelType().name().toLowerCase());
280         artifactName.append("-");
281         artifactName.append(model.getModelVersion());
282
283         artifactName.append(".");
284         artifactName.append(GENERATOR_AAI_GENERATED_ARTIFACT_EXTENSION);
285         return artifactName.toString();
286     }
287
288     /**
289      * Create Resource artifact model from the AAI xml model string.
290      *
291      * @param resourceModel
292      *            Model of the resource artifact
293      * @param aaiResourceModel
294      *            AAI model as string
295      * @return Generated {@link Artifact} model for the resource
296      */
297     private Artifact getResourceArtifact(Model resourceModel, String aaiResourceModel) {
298         final String resourceArtifactLabel = getArtifactLabel(resourceModel);
299         MDC.put(MDC_PARAM_MODEL_INFO, resourceModel.getModelName() + "," + resourceArtifactLabel);
300         final byte[] bytes = aaiResourceModel.getBytes();
301
302         Artifact artifact = new Artifact(ArtifactType.MODEL_INVENTORY_PROFILE.name(), GroupType.DEPLOYMENT.name(),
303                 GeneratorUtil.checkSum(bytes), GeneratorUtil.encode(bytes));
304         artifact.setName(getArtifactName(resourceModel));
305         artifact.setLabel(resourceArtifactLabel);
306         artifact.setDescription(ArtifactGeneratorToscaParser.getArtifactDescription(resourceModel));
307         return artifact;
308     }
309
310     /**
311      * @param generationData
312      * @param artifactName
313      * @return
314      */
315     private boolean isContained(GenerationData generationData, final String artifactName) {
316         return generationData.getResultData().stream()
317                 .anyMatch(artifact -> StringUtils.equals(artifact.getName(), artifactName));
318     }
319
320     /**
321      * Create Service artifact model from the AAI XML model.
322      *
323      * @param serviceModel
324      *            Model of the service artifact
325      * @param aaiServiceModel
326      *            AAI model as string
327      * @return Generated {@link Artifact} model for the service
328      */
329     private Artifact getServiceArtifact(Service serviceModel, String aaiServiceModel) {
330         Artifact artifact = new Artifact(ArtifactType.MODEL_INVENTORY_PROFILE.name(), GroupType.DEPLOYMENT.name(),
331                 GeneratorUtil.checkSum(aaiServiceModel.getBytes()), GeneratorUtil.encode(aaiServiceModel.getBytes()));
332         String serviceArtifactName = getArtifactName(serviceModel);
333         String serviceArtifactLabel = getArtifactLabel(serviceModel);
334         artifact.setName(serviceArtifactName);
335         artifact.setLabel(serviceArtifactLabel);
336         String description = ArtifactGeneratorToscaParser.getArtifactDescription(serviceModel);
337         artifact.setDescription(description);
338         return artifact;
339     }
340
341     private int hashCodeUuId(String uuId) {
342         int hashcode = 0;
343         for (int i = 0; i < uuId.length(); i++) {
344             hashcode = 31 * hashcode + uuId.charAt(i);
345         }
346         return hashcode;
347     }
348
349     private String truncateName(String name) {
350         String truncatedName = name;
351         if (name.length() >= 200) {
352             truncatedName = name.substring(0, 199);
353         }
354         return truncatedName;
355     }
356
357     private String validateServiceVersion(Map<String, String> additionalParams) {
358         String serviceVersion = additionalParams.get(AdditionalParams.SERVICE_VERSION.getName());
359         if (serviceVersion == null) {
360             throw new IllegalArgumentException(GENERATOR_AAI_ERROR_MISSING_SERVICE_VERSION);
361         } else {
362             String versionRegex = "^[1-9]\\d*(\\.0)$";
363             if (!(serviceVersion.matches(versionRegex))) {
364                 throw new IllegalArgumentException(String.format(GENERATOR_AAI_INVALID_SERVICE_VERSION));
365             }
366         }
367         return serviceVersion;
368     }
369 }