2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (c) 2017-2019 AT&T Intellectual Property. All rights reserved.
6 * Copyright (c) 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.WidgetType;
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.tosca.parser.exceptions.SdcToscaParserException;
53 import org.onap.sdc.tosca.parser.impl.SdcToscaParserFactory;
54 import org.onap.sdc.toscaparser.api.Group;
55 import org.onap.sdc.toscaparser.api.NodeTemplate;
56 import org.onap.sdc.toscaparser.api.elements.Metadata;
59 public class AaiArtifactGenerator implements ArtifactGenerator {
61 private static Logger log = LogHelper.INSTANCE;
63 private static final String MDC_PARAM_MODEL_INFO = "ARTIFACT_MODEL_INFO";
64 private static final String GENERATOR_AAI_GENERATED_ARTIFACT_EXTENSION = "xml";
65 private static final String GENERATOR_AAI_ERROR_MISSING_SERVICE_TOSCA =
66 "Service tosca missing from list of input artifacts";
67 private static final String GENERATOR_AAI_ERROR_MISSING_SERVICE_VERSION =
68 "Cannot generate artifacts. Service version is not specified";
69 private static final String GENERATOR_AAI_INVALID_SERVICE_VERSION =
70 "Cannot generate artifacts. Service version is incorrect";
72 private AaiModelGenerator modelGenerator = new AaiModelGenerator();
75 public GenerationData generateArtifact(byte[] csarArchive, List<Artifact> input,
76 Map<String, String> additionalParams) {
77 String configLocation = System.getProperty(ArtifactGeneratorToscaParser.PROPERTY_TOSCA_MAPPING_FILE);
78 if (configLocation == null) {
79 throw new IllegalArgumentException(
80 String.format(ArtifactGeneratorToscaParser.GENERATOR_AAI_CONFIGLOCATION_NOT_FOUND,
81 ArtifactGeneratorToscaParser.PROPERTY_TOSCA_MAPPING_FILE));
85 ArtifactGeneratorToscaParser.initToscaMappingsConfiguration(configLocation);
86 } catch (IOException e) {
87 log.error(ApplicationMsgs.LOAD_PROPERTIES, e, configLocation);
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
126 * if the configured widget mappings do not support processed widget type(s)
128 public GenerationData generateAllArtifacts(final String serviceVersion, ISdcCsarHelper csarHelper)
129 throws XmlArtifactGenerationException {
130 List<NodeTemplate> serviceNodeTemplates = csarHelper.getServiceNodeTemplates();
131 if (serviceNodeTemplates == null) {
132 throw new IllegalArgumentException(GENERATOR_AAI_ERROR_MISSING_SERVICE_TOSCA);
135 Service serviceModel = createServiceModel(serviceVersion, csarHelper.getServiceMetadataAllProperties());
137 MDC.put(MDC_PARAM_MODEL_INFO, serviceModel.getModelName() + "," + getArtifactLabel(serviceModel));
139 List<Resource> resources = generateResourceModels(csarHelper, serviceNodeTemplates, serviceModel);
141 // Generate the A&AI XML model for the Service.
142 final String serviceArtifact = modelGenerator.generateModelFor(serviceModel);
144 // Build a Babel Artifact to be returned to the caller.
145 GenerationData generationData = new GenerationData();
146 generationData.add(getServiceArtifact(serviceModel, serviceArtifact));
148 // For each Resource, generate the A&AI XML model and then create an additional Artifact for that model.
149 for (Resource resource : resources) {
150 generateResourceArtifact(generationData, resource);
151 for (Resource childResource : resource.getResources()) {
152 boolean isProvidingService =
153 (boolean) Optional.ofNullable(childResource.getProperties().get("providingService")) //
155 if (!isProvidingService) {
156 generateResourceArtifact(generationData, childResource);
161 return generationData;
165 * Create a Service from the provided metadata
167 * @param serviceVersion
171 private Service createServiceModel(final String serviceVersion, Map<String, String> properties) {
172 log.debug("Processing (TOSCA) Service object");
173 Service serviceModel = new Service();
174 serviceModel.setModelVersion(serviceVersion);
175 serviceModel.populateModelIdentificationInformation(properties);
181 * @param serviceNodeTemplates
182 * @param serviceModel
183 * @return the generated Models
184 * @throws XmlArtifactGenerationException
185 * if the configured widget mappings do not support processed widget type(s)
187 private List<Resource> generateResourceModels(ISdcCsarHelper csarHelper, List<NodeTemplate> serviceNodeTemplates,
188 Service serviceModel) throws XmlArtifactGenerationException {
189 final List<Group> serviceGroups = csarHelper.getGroupsOfTopologyTemplate();
190 final ArtifactGeneratorToscaParser parser = new ArtifactGeneratorToscaParser(csarHelper);
192 List<Resource> resources = new ArrayList<>();
194 for (NodeTemplate nodeTemplate : serviceNodeTemplates) {
195 if (nodeTemplate.getMetaData() != null) {
196 generateModelFromNodeTemplate(csarHelper, serviceModel, resources, serviceGroups, parser, nodeTemplate);
198 log.warn(ApplicationMsgs.MISSING_SERVICE_METADATA, nodeTemplate.getName());
207 * @param serviceModel
209 * @param serviceGroups
211 * @param nodeTemplate
212 * @throws XmlArtifactGenerationException
213 * if the configured widget mappings do not support processed widget type(s)
215 private void generateModelFromNodeTemplate(ISdcCsarHelper csarHelper, Service serviceModel,
216 List<Resource> resources, final List<Group> serviceGroups, ArtifactGeneratorToscaParser parser,
217 NodeTemplate nodeTemplate) throws XmlArtifactGenerationException {
218 Resource model = getModelFor(parser, nodeTemplate);
221 if (nodeTemplate.getMetaData() != null) {
222 model.populateModelIdentificationInformation(nodeTemplate.getMetaData().getAllProperties());
225 parser.addRelatedModel(serviceModel, model);
226 if (model.getModelType() == ModelType.RESOURCE) {
227 generateResourceModel(csarHelper, resources, parser, nodeTemplate);
230 for (Group group : serviceGroups) {
231 ArrayList<String> members = group.getMembers();
232 if (members != null && members.contains(nodeTemplate.getName())
233 && WidgetConfigurationUtil.isSupportedInstanceGroup(group.getType())) {
234 log.debug(String.format("Adding group %s (type %s) with members %s", group.getName(),
235 group.getType(), members));
237 Resource groupModel = parser.createInstanceGroupModel(
238 parser.mergeProperties(group.getMetadata().getAllProperties(), group.getProperties()));
239 serviceModel.addResource(groupModel);
240 resources.add(groupModel);
246 private Resource getModelFor(ArtifactGeneratorToscaParser parser, NodeTemplate nodeTemplate) {
247 String nodeTypeName = nodeTemplate.getType();
249 log.debug("Processing resource " + nodeTypeName + ": " + nodeTemplate.getMetaData().getValue("UUID"));
251 Resource model = Model.getModelFor(nodeTypeName, nodeTemplate.getMetaData().getValue("type"));
254 Metadata metadata = nodeTemplate.getMetaData();
255 if (metadata != null && parser.hasAllottedResource(metadata.getAllProperties())
256 && model.hasWidgetType("VF")) {
257 model = new Resource(WidgetType.valueOf("ALLOTTED_RESOURCE"), true);
268 * @param nodeTemplate
269 * @throws XmlArtifactGenerationException
270 * if the configured widget mappings do not support processed widget type(s)
272 private void generateResourceModel(ISdcCsarHelper csarHelper, List<Resource> resources,
273 ArtifactGeneratorToscaParser parser, NodeTemplate nodeTemplate) throws XmlArtifactGenerationException {
274 Resource resourceModel = getModelFor(parser, nodeTemplate);
275 if (resourceModel == null) {
276 log.info(ApplicationMsgs.DISTRIBUTION_EVENT, "Could not generate resource model");
280 Map<String, String> serviceMetadata = nodeTemplate.getMetaData().getAllProperties();
281 resourceModel.populateModelIdentificationInformation(serviceMetadata);
283 parser.processResourceModels(resourceModel, csarHelper.getNodeTemplateChildren(nodeTemplate));
285 if (csarHelper.getServiceVfList() != null) {
286 parser.processVfModules(resources, resourceModel, nodeTemplate);
289 if (parser.hasSubCategoryTunnelXConnect(serviceMetadata) && parser.hasAllottedResource(serviceMetadata)) {
290 resourceModel.addWidget(Widget.createWidget("TUNNEL_XCONNECT"));
293 resources.addAll(parser.processInstanceGroups(resourceModel, nodeTemplate));
294 resources.add(resourceModel);
298 * @param generationData
300 * @throws XmlArtifactGenerationException
302 private void generateResourceArtifact(GenerationData generationData, Resource resource)
303 throws XmlArtifactGenerationException {
304 if (!isContained(generationData, getArtifactName(resource))) {
305 log.info(ApplicationMsgs.DISTRIBUTION_EVENT, "Generating resource model");
306 generationData.add(getResourceArtifact(resource, modelGenerator.generateModelFor(resource)));
310 private Path createTempFile(byte[] bytes) throws IOException {
311 log.debug("Creating temp file on file system for the csar");
312 Path path = Files.createTempFile("temp", ".csar");
313 Files.write(path, bytes);
318 * Create the artifact label for an AAI model.
321 * @return the artifact label as String
323 private String getArtifactLabel(Model model) {
324 StringBuilder artifactName = new StringBuilder(ArtifactType.AAI.name());
325 artifactName.append("-");
326 artifactName.append(model.getModelTypeName());
327 artifactName.append("-");
328 artifactName.append(hashCodeUuId(model.getModelNameVersionId()));
329 return (artifactName.toString()).replaceAll("[^a-zA-Z0-9 +]+", "-");
333 * Method to generate the artifact name for an AAI model.
337 * @return Model artifact name
339 private String getArtifactName(Model model) {
340 StringBuilder artifactName = new StringBuilder(ArtifactType.AAI.name());
341 artifactName.append("-");
343 String truncatedArtifactName = truncateName(model.getModelName());
344 artifactName.append(truncatedArtifactName);
346 artifactName.append("-");
347 artifactName.append(model.getModelTypeName());
348 artifactName.append("-");
349 artifactName.append(model.getModelVersion());
351 artifactName.append(".");
352 artifactName.append(GENERATOR_AAI_GENERATED_ARTIFACT_EXTENSION);
353 return artifactName.toString();
357 * Create Resource artifact model from the AAI xml model string.
359 * @param resourceModel
360 * Model of the resource artifact
361 * @param aaiResourceModel
362 * AAI model as string
363 * @return Generated {@link Artifact} model for the resource
365 private Artifact getResourceArtifact(Resource resourceModel, String aaiResourceModel) {
366 final String resourceArtifactLabel = getArtifactLabel(resourceModel);
367 MDC.put(MDC_PARAM_MODEL_INFO, resourceModel.getModelName() + "," + resourceArtifactLabel);
368 final byte[] bytes = aaiResourceModel.getBytes();
370 Artifact artifact = new Artifact(ArtifactType.MODEL_INVENTORY_PROFILE.name(), GroupType.DEPLOYMENT.name(),
371 GeneratorUtil.checkSum(bytes), GeneratorUtil.encode(bytes));
372 artifact.setName(getArtifactName(resourceModel));
373 artifact.setLabel(resourceArtifactLabel);
374 artifact.setDescription("AAI Resource Model");
379 * @param generationData
380 * @param artifactName
383 private boolean isContained(GenerationData generationData, final String artifactName) {
384 return generationData.getResultData().stream()
385 .anyMatch(artifact -> StringUtils.equals(artifact.getName(), artifactName));
389 * Create Service artifact model from the AAI XML model.
391 * @param serviceModel
392 * Model of the service artifact
393 * @param aaiServiceModel
394 * AAI model as string
395 * @return Generated {@link Artifact} model for the service
397 private Artifact getServiceArtifact(Service serviceModel, String aaiServiceModel) {
398 Artifact artifact = new Artifact(ArtifactType.MODEL_INVENTORY_PROFILE.name(), GroupType.DEPLOYMENT.name(),
399 GeneratorUtil.checkSum(aaiServiceModel.getBytes()), GeneratorUtil.encode(aaiServiceModel.getBytes()));
400 String serviceArtifactName = getArtifactName(serviceModel);
401 String serviceArtifactLabel = getArtifactLabel(serviceModel);
402 artifact.setName(serviceArtifactName);
403 artifact.setLabel(serviceArtifactLabel);
404 artifact.setDescription("AAI Service Model");
408 private int hashCodeUuId(String uuId) {
410 for (int i = 0; i < uuId.length(); i++) {
411 hashcode = 31 * hashcode + uuId.charAt(i);
416 private String truncateName(String name) {
417 String truncatedName = name;
418 if (name.length() >= 200) {
419 truncatedName = name.substring(0, 199);
421 return truncatedName;
424 private String validateServiceVersion(Map<String, String> additionalParams) {
425 String serviceVersion = additionalParams.get(AdditionalParams.SERVICE_VERSION.getName());
426 if (serviceVersion == null) {
427 throw new IllegalArgumentException(GENERATOR_AAI_ERROR_MISSING_SERVICE_VERSION);
429 String versionRegex = "^[1-9]\\d*(\\.0)$";
430 if (!(serviceVersion.matches(versionRegex))) {
431 throw new IllegalArgumentException(String.format(GENERATOR_AAI_INVALID_SERVICE_VERSION));
434 return serviceVersion;