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