Generate models for child resources
[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.HashMap;
27 import java.util.List;
28 import java.util.Map;
29
30 import org.apache.commons.io.FileUtils;
31 import org.apache.commons.lang3.StringUtils;
32 import org.onap.aai.babel.logging.ApplicationMsgs;
33 import org.onap.aai.babel.logging.LogHelper;
34 import org.onap.aai.babel.parser.ArtifactGeneratorToscaParser;
35 import org.onap.aai.babel.xml.generator.data.AdditionalParams;
36 import org.onap.aai.babel.xml.generator.data.Artifact;
37 import org.onap.aai.babel.xml.generator.data.ArtifactType;
38 import org.onap.aai.babel.xml.generator.data.GenerationData;
39 import org.onap.aai.babel.xml.generator.data.GeneratorUtil;
40 import org.onap.aai.babel.xml.generator.data.GroupType;
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.cl.api.Logger;
46 import org.onap.sdc.tosca.parser.api.ISdcCsarHelper;
47 import org.onap.sdc.tosca.parser.impl.SdcToscaParserFactory;
48 import org.onap.sdc.toscaparser.api.NodeTemplate;
49 import org.slf4j.MDC;
50
51 public class AaiArtifactGenerator implements ArtifactGenerator {
52
53     private static Logger log = LogHelper.INSTANCE;
54
55     private static final String MDC_PARAM_MODEL_INFO = "ARTIFACT_MODEL_INFO";
56     private static final String GENERATOR_AAI_GENERATED_ARTIFACT_EXTENSION = "xml";
57     private static final String GENERATOR_AAI_ERROR_MISSING_SERVICE_TOSCA =
58             "Service tosca missing from list of input artifacts";
59     private static final String GENERATOR_AAI_ERROR_MISSING_SERVICE_VERSION =
60             "Cannot generate artifacts. Service version is not specified";
61     private static final String GENERATOR_AAI_INVALID_SERVICE_VERSION =
62             "Cannot generate artifacts. Service version is incorrect";
63
64     private AaiModelGenerator modelGenerator = new AaiModelGeneratorImpl();
65
66     @Override
67     public GenerationData generateArtifact(byte[] csarArchive, List<Artifact> input,
68             Map<String, String> additionalParams) {
69         Path csarPath;
70
71         try {
72             csarPath = createTempFile(csarArchive);
73         } catch (IOException e) {
74             log.error(ApplicationMsgs.TEMP_FILE_ERROR, e);
75             return createErrorData(e);
76         }
77
78         try {
79             ArtifactGeneratorToscaParser.initWidgetConfiguration();
80             ArtifactGeneratorToscaParser.initGroupFilterConfiguration();
81             ISdcCsarHelper csarHelper =
82                     SdcToscaParserFactory.getInstance().getSdcCsarHelper(csarPath.toAbsolutePath().toString());
83             return generateService(validateServiceVersion(additionalParams), csarHelper);
84         } catch (Exception e) {
85             log.error(ApplicationMsgs.INVALID_CSAR_FILE, e);
86             return createErrorData(e);
87         } finally {
88             FileUtils.deleteQuietly(csarPath.toFile());
89         }
90     }
91
92     private GenerationData createErrorData(Exception e) {
93         GenerationData generationData = new GenerationData();
94         generationData.add(ArtifactType.AAI.name(), e.getMessage());
95         return generationData;
96     }
97
98     /**
99      * Generate model artifacts for the Service and its associated Resources.
100      *
101      * @param serviceVersion
102      * @param csarHelper TOSCA parser
103      * @return the generated Artifacts
104      */
105     private GenerationData generateService(final String serviceVersion, ISdcCsarHelper csarHelper) {
106         List<NodeTemplate> serviceNodes = csarHelper.getServiceNodeTemplates();
107         if (serviceNodes == null) {
108             throw new IllegalArgumentException(GENERATOR_AAI_ERROR_MISSING_SERVICE_TOSCA);
109         }
110
111         // Populate basic service model metadata
112         Service serviceModel = new Service();
113         serviceModel.setModelVersion(serviceVersion);
114         serviceModel.populateModelIdentificationInformation(csarHelper.getServiceMetadataAllProperties());
115
116         Map<String, String> idTypeStore = new HashMap<>();
117
118         ArtifactGeneratorToscaParser parser = new ArtifactGeneratorToscaParser(csarHelper);
119         if (!serviceNodes.isEmpty()) {
120             parser.processServiceTosca(serviceModel, idTypeStore, serviceNodes);
121         }
122
123         // Process the resource TOSCA files
124         List<Resource> resources = parser.processResourceToscas(serviceNodes, idTypeStore);
125
126         MDC.put(MDC_PARAM_MODEL_INFO, serviceModel.getModelName() + "," + getArtifactLabel(serviceModel));
127         String aaiServiceModel = modelGenerator.generateModelFor(serviceModel);
128
129         GenerationData generationData = new GenerationData();
130         generationData.add(getServiceArtifact(serviceModel, aaiServiceModel));
131
132         // Generate AAI XML resource model
133         for (Resource resource : resources) {
134             generateResourceArtifact(generationData, resource);
135             for (Resource childResource : resource.getResources()) {
136                 if (!(childResource instanceof ProvidingService)) {
137                     generateResourceArtifact(generationData, childResource);
138                 }
139             }
140         }
141
142         return generationData;
143     }
144
145     /**
146      * @param generationData
147      * @param resource
148      */
149     private void generateResourceArtifact(GenerationData generationData, Resource resource) {
150         if (!isContained(generationData, getArtifactName(resource))) {
151             log.info(ApplicationMsgs.DISTRIBUTION_EVENT, "Generating resource model");
152             Artifact resourceArtifact = getResourceArtifact(resource, modelGenerator.generateModelFor(resource));
153             generationData.add(resourceArtifact);
154         }
155     }
156
157     private Path createTempFile(byte[] bytes) throws IOException {
158         log.debug("Creating temp file on file system for the csar");
159         Path path = Files.createTempFile("temp", ".csar");
160         Files.write(path, bytes);
161         return path;
162     }
163
164     /**
165      * Create the artifact label for an AAI model.
166      *
167      * @param model
168      * @return the artifact label as String
169      */
170     private String getArtifactLabel(Model model) {
171         StringBuilder artifactName = new StringBuilder(ArtifactType.AAI.name());
172         artifactName.append("-");
173         artifactName.append(model.getModelType().name().toLowerCase());
174         artifactName.append("-");
175         artifactName.append(hashCodeUuId(model.getModelNameVersionId()));
176         return (artifactName.toString()).replaceAll("[^a-zA-Z0-9 +]+", "-");
177     }
178
179     /**
180      * Method to generate the artifact name for an AAI model.
181      *
182      * @param model AAI artifact model
183      * @return Model artifact name
184      */
185     private String getArtifactName(Model model) {
186         StringBuilder artifactName = new StringBuilder(ArtifactType.AAI.name());
187         artifactName.append("-");
188
189         String truncatedArtifactName = truncateName(model.getModelName());
190         artifactName.append(truncatedArtifactName);
191
192         artifactName.append("-");
193         artifactName.append(model.getModelType().name().toLowerCase());
194         artifactName.append("-");
195         artifactName.append(model.getModelVersion());
196
197         artifactName.append(".");
198         artifactName.append(GENERATOR_AAI_GENERATED_ARTIFACT_EXTENSION);
199         return artifactName.toString();
200     }
201
202     /**
203      * Create Resource artifact model from the AAI xml model string.
204      *
205      * @param resourceModel Model of the resource artifact
206      * @param aaiResourceModel AAI model as string
207      * @return Generated {@link Artifact} model for the resource
208      */
209     private Artifact getResourceArtifact(Model resourceModel, String aaiResourceModel) {
210         final String resourceArtifactLabel = getArtifactLabel(resourceModel);
211         MDC.put(MDC_PARAM_MODEL_INFO, resourceModel.getModelName() + "," + resourceArtifactLabel);
212         final byte[] bytes = aaiResourceModel.getBytes();
213
214         Artifact artifact = new Artifact(ArtifactType.MODEL_INVENTORY_PROFILE.name(), GroupType.DEPLOYMENT.name(),
215                 GeneratorUtil.checkSum(bytes), GeneratorUtil.encode(bytes));
216         artifact.setName(getArtifactName(resourceModel));
217         artifact.setLabel(resourceArtifactLabel);
218         artifact.setDescription(ArtifactGeneratorToscaParser.getArtifactDescription(resourceModel));
219         return artifact;
220     }
221
222     /**
223      * @param generationData
224      * @param artifactName
225      * @return
226      */
227     private boolean isContained(GenerationData generationData, final String artifactName) {
228         return generationData.getResultData().stream()
229                 .anyMatch(artifact -> StringUtils.equals(artifact.getName(), artifactName));
230     }
231
232     /**
233      * Create Service artifact model from the AAI xml model string.
234      *
235      * @param serviceModel Model of the service artifact
236      * @param aaiServiceModel AAI model as string
237      * @return Generated {@link Artifact} model for the service
238      */
239     private Artifact getServiceArtifact(Service serviceModel, String aaiServiceModel) {
240         Artifact artifact = new Artifact(ArtifactType.MODEL_INVENTORY_PROFILE.name(), GroupType.DEPLOYMENT.name(),
241                 GeneratorUtil.checkSum(aaiServiceModel.getBytes()), GeneratorUtil.encode(aaiServiceModel.getBytes()));
242         String serviceArtifactName = getArtifactName(serviceModel);
243         String serviceArtifactLabel = getArtifactLabel(serviceModel);
244         artifact.setName(serviceArtifactName);
245         artifact.setLabel(serviceArtifactLabel);
246         String description = ArtifactGeneratorToscaParser.getArtifactDescription(serviceModel);
247         artifact.setDescription(description);
248         return artifact;
249     }
250
251     private int hashCodeUuId(String uuId) {
252         int hashcode = 0;
253         for (int i = 0; i < uuId.length(); i++) {
254             hashcode = 31 * hashcode + uuId.charAt(i);
255         }
256         return hashcode;
257     }
258
259     private String truncateName(String name) {
260         String truncatedName = name;
261         if (name.length() >= 200) {
262             truncatedName = name.substring(0, 199);
263         }
264         return truncatedName;
265     }
266
267     private String validateServiceVersion(Map<String, String> additionalParams) {
268         String serviceVersion = additionalParams.get(AdditionalParams.SERVICE_VERSION.getName());
269         if (serviceVersion == null) {
270             throw new IllegalArgumentException(GENERATOR_AAI_ERROR_MISSING_SERVICE_VERSION);
271         } else {
272             String versionRegex = "^[1-9]\\d*(\\.0)$";
273             if (!(serviceVersion.matches(versionRegex))) {
274                 throw new IllegalArgumentException(String.format(GENERATOR_AAI_INVALID_SERVICE_VERSION));
275             }
276         }
277         return serviceVersion;
278     }
279 }