2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright © 2017-2019 AT&T Intellectual Property. All rights reserved.
6 * Copyright © 2017-2019 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
12 * http://www.apache.org/licenses/LICENSE-2.0
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=========================================================
22 package org.onap.aai.babel.xml.generator.api;
24 import java.io.IOException;
25 import java.nio.file.Files;
26 import java.nio.file.Path;
27 import java.util.ArrayList;
28 import java.util.List;
30 import java.util.Optional;
31 import org.apache.commons.io.FileUtils;
32 import org.apache.commons.lang3.StringUtils;
33 import org.onap.aai.babel.logging.ApplicationMsgs;
34 import org.onap.aai.babel.logging.LogHelper;
35 import org.onap.aai.babel.parser.ArtifactGeneratorToscaParser;
36 import org.onap.aai.babel.xml.generator.XmlArtifactGenerationException;
37 import org.onap.aai.babel.xml.generator.data.AdditionalParams;
38 import org.onap.aai.babel.xml.generator.data.Artifact;
39 import org.onap.aai.babel.xml.generator.data.ArtifactType;
40 import org.onap.aai.babel.xml.generator.data.GenerationData;
41 import org.onap.aai.babel.xml.generator.data.GeneratorUtil;
42 import org.onap.aai.babel.xml.generator.data.GroupType;
43 import org.onap.aai.babel.xml.generator.data.WidgetConfigurationUtil;
44 import org.onap.aai.babel.xml.generator.model.Model;
45 import org.onap.aai.babel.xml.generator.model.Resource;
46 import org.onap.aai.babel.xml.generator.model.Service;
47 import org.onap.aai.babel.xml.generator.model.Widget;
48 import org.onap.aai.babel.xml.generator.model.Widget.Type;
49 import org.onap.aai.cl.api.Logger;
50 import org.onap.sdc.tosca.parser.api.ISdcCsarHelper;
51 import org.onap.sdc.tosca.parser.exceptions.SdcToscaParserException;
52 import org.onap.sdc.tosca.parser.impl.SdcToscaParserFactory;
53 import org.onap.sdc.toscaparser.api.Group;
54 import org.onap.sdc.toscaparser.api.NodeTemplate;
55 import org.onap.sdc.toscaparser.api.elements.Metadata;
58 public class AaiArtifactGenerator implements ArtifactGenerator {
60 private static Logger log = LogHelper.INSTANCE;
62 private static final String MDC_PARAM_MODEL_INFO = "ARTIFACT_MODEL_INFO";
63 private static final String GENERATOR_AAI_GENERATED_ARTIFACT_EXTENSION = "xml";
64 private static final String GENERATOR_AAI_ERROR_MISSING_SERVICE_TOSCA =
65 "Service tosca missing from list of input artifacts";
66 private static final String GENERATOR_AAI_ERROR_MISSING_SERVICE_VERSION =
67 "Cannot generate artifacts. Service version is not specified";
68 private static final String GENERATOR_AAI_INVALID_SERVICE_VERSION =
69 "Cannot generate artifacts. Service version is incorrect";
71 private AaiModelGenerator modelGenerator = new AaiModelGeneratorImpl();
74 public GenerationData generateArtifact(byte[] csarArchive, List<Artifact> input,
75 Map<String, String> additionalParams) {
76 String configLocation = System.getProperty(ArtifactGeneratorToscaParser.PROPERTY_TOSCA_MAPPING_FILE);
77 if (configLocation == null) {
78 throw new IllegalArgumentException(
79 String.format(ArtifactGeneratorToscaParser.GENERATOR_AAI_CONFIGLOCATION_NOT_FOUND,
80 ArtifactGeneratorToscaParser.PROPERTY_TOSCA_MAPPING_FILE));
84 ArtifactGeneratorToscaParser.initWidgetConfiguration();
85 ArtifactGeneratorToscaParser.initToscaMappingsConfiguration(configLocation);
86 } catch (IOException e) {
87 log.error(ApplicationMsgs.LOAD_PROPERTIES, e);
88 return createErrorData(e);
94 csarPath = createTempFile(csarArchive);
95 } catch (IOException e) {
96 log.error(ApplicationMsgs.TEMP_FILE_ERROR, e);
97 return createErrorData(e);
101 ISdcCsarHelper csarHelper =
102 SdcToscaParserFactory.getInstance().getSdcCsarHelper(csarPath.toAbsolutePath().toString());
103 return generateAllArtifacts(validateServiceVersion(additionalParams), csarHelper);
104 } catch (SdcToscaParserException | XmlArtifactGenerationException e) {
105 log.error(ApplicationMsgs.INVALID_CSAR_FILE, e);
106 return createErrorData(e);
108 FileUtils.deleteQuietly(csarPath.toFile());
112 private GenerationData createErrorData(Exception e) {
113 GenerationData generationData = new GenerationData();
114 generationData.add(ArtifactType.AAI.name(), e.getMessage());
115 return generationData;
119 * Generate model artifacts for the Service and its associated Resources.
121 * @param serviceVersion
123 * interface to the TOSCA parser
124 * @return the generated Artifacts (containing XML models)
125 * @throws XmlArtifactGenerationException
127 private GenerationData generateAllArtifacts(final String serviceVersion, ISdcCsarHelper csarHelper)
128 throws XmlArtifactGenerationException {
129 List<NodeTemplate> serviceNodeTemplates = csarHelper.getServiceNodeTemplates();
130 if (serviceNodeTemplates == null) {
131 throw new IllegalArgumentException(GENERATOR_AAI_ERROR_MISSING_SERVICE_TOSCA);
134 Service serviceModel = createServiceModel(serviceVersion, csarHelper.getServiceMetadataAllProperties());
136 MDC.put(MDC_PARAM_MODEL_INFO, serviceModel.getModelName() + "," + getArtifactLabel(serviceModel));
138 List<Resource> resources = generateResourceModels(csarHelper, serviceNodeTemplates, serviceModel);
140 // Generate the A&AI XML model for the Service.
141 final String serviceArtifact = modelGenerator.generateModelFor(serviceModel);
143 // Build a Babel Artifact to be returned to the caller.
144 GenerationData generationData = new GenerationData();
145 generationData.add(getServiceArtifact(serviceModel, serviceArtifact));
147 // For each Resource, generate the A&AI XML model and then create an additional Artifact for that model.
148 for (Resource resource : resources) {
149 generateResourceArtifact(generationData, resource);
150 for (Resource childResource : resource.getResources()) {
151 boolean isProvidingService =
152 (boolean) Optional.ofNullable(childResource.getProperties().get("providingService")) //
154 if (!isProvidingService) {
155 generateResourceArtifact(generationData, childResource);
160 return generationData;
164 * Create a Service from the provided metadata
166 * @param serviceVersion
170 private Service createServiceModel(final String serviceVersion, Map<String, String> properties) {
171 log.debug("Processing (TOSCA) Service object");
172 Service serviceModel = new Service();
173 serviceModel.setModelVersion(serviceVersion);
174 serviceModel.populateModelIdentificationInformation(properties);
180 * @param serviceNodeTemplates
181 * @param serviceModel
182 * @return the generated Models
183 * @throws XmlArtifactGenerationException
185 private List<Resource> generateResourceModels(ISdcCsarHelper csarHelper, List<NodeTemplate> serviceNodeTemplates,
186 Service serviceModel) throws XmlArtifactGenerationException {
187 final List<Group> serviceGroups = csarHelper.getGroupsOfTopologyTemplate();
188 final ArtifactGeneratorToscaParser parser = new ArtifactGeneratorToscaParser(csarHelper);
190 List<Resource> resources = new ArrayList<>();
192 for (NodeTemplate nodeTemplate : serviceNodeTemplates) {
193 if (nodeTemplate.getMetaData() != null) {
194 generateModelFromNodeTemplate(csarHelper, serviceModel, resources, serviceGroups, parser, nodeTemplate);
196 log.warn(ApplicationMsgs.MISSING_SERVICE_METADATA, nodeTemplate.getName());
203 private void generateModelFromNodeTemplate(ISdcCsarHelper csarHelper, Service serviceModel,
204 List<Resource> resources, final List<Group> serviceGroups, ArtifactGeneratorToscaParser parser,
205 NodeTemplate nodeTemplate) throws XmlArtifactGenerationException {
206 Resource model = getModelFor(parser, nodeTemplate);
209 if (nodeTemplate.getMetaData() != null) {
210 model.populateModelIdentificationInformation(nodeTemplate.getMetaData().getAllProperties());
213 parser.addRelatedModel(serviceModel, model);
214 if (model.isResource()) {
215 generateResourceModel(csarHelper, resources, parser, nodeTemplate);
218 for (Group group : serviceGroups) {
219 ArrayList<String> members = group.getMembers();
220 if (members != null && members.contains(nodeTemplate.getName())
221 && WidgetConfigurationUtil.isSupportedInstanceGroup(group.getType())) {
222 log.debug(String.format("Adding group %s (type %s) with members %s", group.getName(),
223 group.getType(), members));
225 Resource groupModel = parser.createInstanceGroupModel(
226 parser.mergeProperties(group.getMetadata().getAllProperties(), group.getProperties()));
227 serviceModel.addResource(groupModel);
228 resources.add(groupModel);
234 private Resource getModelFor(ArtifactGeneratorToscaParser parser, NodeTemplate nodeTemplate) {
235 String nodeTypeName = nodeTemplate.getType();
237 log.debug("Processing resource " + nodeTypeName + ": " + nodeTemplate.getMetaData().getValue("UUID"));
239 Resource model = Model.getModelFor(nodeTypeName, nodeTemplate.getMetaData().getValue("type"));
242 Metadata metadata = nodeTemplate.getMetaData();
243 if (metadata != null && parser.hasAllottedResource(metadata.getAllProperties())
244 && model.getWidgetType() == Type.VF) {
245 model = new Resource(Type.ALLOTTED_RESOURCE, true);
252 private void generateResourceModel(ISdcCsarHelper csarHelper, List<Resource> resources,
253 ArtifactGeneratorToscaParser parser, NodeTemplate nodeTemplate) throws XmlArtifactGenerationException {
254 Resource resourceModel = getModelFor(parser, nodeTemplate);
255 if (resourceModel == null) {
256 log.info(ApplicationMsgs.DISTRIBUTION_EVENT, "Could not generate resource model");
260 Map<String, String> serviceMetadata = nodeTemplate.getMetaData().getAllProperties();
261 resourceModel.populateModelIdentificationInformation(serviceMetadata);
263 parser.processResourceModels(resourceModel, csarHelper.getNodeTemplateChildren(nodeTemplate));
265 if (csarHelper.getServiceVfList() != null) {
266 parser.processVfModules(resources, resourceModel, nodeTemplate);
269 if (parser.hasSubCategoryTunnelXConnect(serviceMetadata) && parser.hasAllottedResource(serviceMetadata)) {
270 resourceModel.addWidget(Widget.getWidget(Type.TUNNEL_XCONNECT));
273 resources.addAll(parser.processInstanceGroups(resourceModel, nodeTemplate));
274 resources.add((Resource) resourceModel);
278 * @param generationData
280 * @throws XmlArtifactGenerationException
282 private void generateResourceArtifact(GenerationData generationData, Resource resource)
283 throws XmlArtifactGenerationException {
284 if (!isContained(generationData, getArtifactName(resource))) {
285 log.info(ApplicationMsgs.DISTRIBUTION_EVENT, "Generating resource model");
286 generationData.add(getResourceArtifact(resource, modelGenerator.generateModelFor(resource)));
290 private Path createTempFile(byte[] bytes) throws IOException {
291 log.debug("Creating temp file on file system for the csar");
292 Path path = Files.createTempFile("temp", ".csar");
293 Files.write(path, bytes);
298 * Create the artifact label for an AAI model.
301 * @return the artifact label as String
303 private String getArtifactLabel(Model model) {
304 StringBuilder artifactName = new StringBuilder(ArtifactType.AAI.name());
305 artifactName.append("-");
306 artifactName.append(model.getModelType().name().toLowerCase());
307 artifactName.append("-");
308 artifactName.append(hashCodeUuId(model.getModelNameVersionId()));
309 return (artifactName.toString()).replaceAll("[^a-zA-Z0-9 +]+", "-");
313 * Method to generate the artifact name for an AAI model.
317 * @return Model artifact name
319 private String getArtifactName(Model model) {
320 StringBuilder artifactName = new StringBuilder(ArtifactType.AAI.name());
321 artifactName.append("-");
323 String truncatedArtifactName = truncateName(model.getModelName());
324 artifactName.append(truncatedArtifactName);
326 artifactName.append("-");
327 artifactName.append(model.getModelType().name().toLowerCase());
328 artifactName.append("-");
329 artifactName.append(model.getModelVersion());
331 artifactName.append(".");
332 artifactName.append(GENERATOR_AAI_GENERATED_ARTIFACT_EXTENSION);
333 return artifactName.toString();
337 * Create Resource artifact model from the AAI xml model string.
339 * @param resourceModel
340 * Model of the resource artifact
341 * @param aaiResourceModel
342 * AAI model as string
343 * @return Generated {@link Artifact} model for the resource
345 private Artifact getResourceArtifact(Model resourceModel, String aaiResourceModel) {
346 final String resourceArtifactLabel = getArtifactLabel(resourceModel);
347 MDC.put(MDC_PARAM_MODEL_INFO, resourceModel.getModelName() + "," + resourceArtifactLabel);
348 final byte[] bytes = aaiResourceModel.getBytes();
350 Artifact artifact = new Artifact(ArtifactType.MODEL_INVENTORY_PROFILE.name(), GroupType.DEPLOYMENT.name(),
351 GeneratorUtil.checkSum(bytes), GeneratorUtil.encode(bytes));
352 artifact.setName(getArtifactName(resourceModel));
353 artifact.setLabel(resourceArtifactLabel);
354 artifact.setDescription(ArtifactGeneratorToscaParser.getArtifactDescription(resourceModel));
359 * @param generationData
360 * @param artifactName
363 private boolean isContained(GenerationData generationData, final String artifactName) {
364 return generationData.getResultData().stream()
365 .anyMatch(artifact -> StringUtils.equals(artifact.getName(), artifactName));
369 * Create Service artifact model from the AAI XML model.
371 * @param serviceModel
372 * Model of the service artifact
373 * @param aaiServiceModel
374 * AAI model as string
375 * @return Generated {@link Artifact} model for the service
377 private Artifact getServiceArtifact(Service serviceModel, String aaiServiceModel) {
378 Artifact artifact = new Artifact(ArtifactType.MODEL_INVENTORY_PROFILE.name(), GroupType.DEPLOYMENT.name(),
379 GeneratorUtil.checkSum(aaiServiceModel.getBytes()), GeneratorUtil.encode(aaiServiceModel.getBytes()));
380 String serviceArtifactName = getArtifactName(serviceModel);
381 String serviceArtifactLabel = getArtifactLabel(serviceModel);
382 artifact.setName(serviceArtifactName);
383 artifact.setLabel(serviceArtifactLabel);
384 String description = ArtifactGeneratorToscaParser.getArtifactDescription(serviceModel);
385 artifact.setDescription(description);
389 private int hashCodeUuId(String uuId) {
391 for (int i = 0; i < uuId.length(); i++) {
392 hashcode = 31 * hashcode + uuId.charAt(i);
397 private String truncateName(String name) {
398 String truncatedName = name;
399 if (name.length() >= 200) {
400 truncatedName = name.substring(0, 199);
402 return truncatedName;
405 private String validateServiceVersion(Map<String, String> additionalParams) {
406 String serviceVersion = additionalParams.get(AdditionalParams.SERVICE_VERSION.getName());
407 if (serviceVersion == null) {
408 throw new IllegalArgumentException(GENERATOR_AAI_ERROR_MISSING_SERVICE_VERSION);
410 String versionRegex = "^[1-9]\\d*(\\.0)$";
411 if (!(serviceVersion.matches(versionRegex))) {
412 throw new IllegalArgumentException(String.format(GENERATOR_AAI_INVALID_SERVICE_VERSION));
415 return serviceVersion;