2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.openecomp.sdc.be.tosca;
24 import fj.data.Either;
25 import java.io.BufferedOutputStream;
26 import java.io.ByteArrayInputStream;
28 import java.io.IOException;
29 import java.util.ArrayList;
30 import java.util.Arrays;
31 import java.util.EnumMap;
32 import java.util.HashMap;
33 import java.util.HashSet;
34 import java.util.List;
36 import java.util.Map.Entry;
37 import java.util.Objects;
39 import java.util.regex.Matcher;
40 import java.util.regex.Pattern;
41 import java.util.zip.ZipEntry;
42 import java.util.zip.ZipInputStream;
43 import java.util.zip.ZipOutputStream;
44 import org.apache.commons.codec.binary.Base64;
45 import org.apache.commons.collections.CollectionUtils;
46 import org.apache.commons.collections.MapUtils;
47 import org.apache.commons.io.output.ByteArrayOutputStream;
48 import org.apache.commons.lang.WordUtils;
49 import org.apache.commons.lang3.tuple.ImmutablePair;
50 import org.apache.commons.lang3.tuple.ImmutableTriple;
51 import org.apache.commons.lang3.tuple.Triple;
52 import org.onap.sdc.tosca.services.YamlUtil;
53 import org.openecomp.sdc.be.components.impl.ImportUtils;
54 import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException;
55 import org.openecomp.sdc.be.config.Configuration.ArtifactTypeConfig;
56 import org.openecomp.sdc.be.config.ConfigurationManager;
57 import org.openecomp.sdc.be.dao.api.ActionStatus;
58 import org.openecomp.sdc.be.dao.cassandra.ArtifactCassandraDao;
59 import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus;
60 import org.openecomp.sdc.be.dao.cassandra.SdcSchemaFilesCassandraDao;
61 import org.openecomp.sdc.be.datatypes.elements.OperationDataDefinition;
62 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
63 import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
64 import org.openecomp.sdc.be.impl.ComponentsUtils;
65 import org.openecomp.sdc.be.model.ArtifactDefinition;
66 import org.openecomp.sdc.be.model.Component;
67 import org.openecomp.sdc.be.model.ComponentInstance;
68 import org.openecomp.sdc.be.model.InterfaceDefinition;
69 import org.openecomp.sdc.be.model.LifecycleStateEnum;
70 import org.openecomp.sdc.be.model.Product;
71 import org.openecomp.sdc.be.model.Resource;
72 import org.openecomp.sdc.be.model.Service;
73 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade;
74 import org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter;
75 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
76 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
77 import org.openecomp.sdc.be.plugins.CsarEntryGenerator;
78 import org.openecomp.sdc.be.resources.data.DAOArtifactData;
79 import org.openecomp.sdc.be.resources.data.SdcSchemaFilesData;
80 import org.openecomp.sdc.be.tosca.model.ToscaTemplate;
81 import org.openecomp.sdc.be.tosca.utils.OperationArtifactUtil;
82 import org.openecomp.sdc.be.utils.CommonBeUtils;
83 import org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum;
84 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
85 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
86 import org.openecomp.sdc.common.impl.ExternalConfiguration;
87 import org.openecomp.sdc.common.log.elements.LoggerSupportability;
88 import org.openecomp.sdc.common.log.enums.LoggerSupportabilityActions;
89 import org.openecomp.sdc.common.log.enums.StatusCode;
90 import org.openecomp.sdc.common.log.wrappers.Logger;
91 import org.openecomp.sdc.common.util.GeneralUtility;
92 import org.openecomp.sdc.common.util.ValidationUtils;
93 import org.openecomp.sdc.common.zip.ZipUtils;
94 import org.openecomp.sdc.exception.ResponseFormat;
95 import org.springframework.beans.factory.annotation.Autowired;
96 import org.yaml.snakeyaml.Yaml;
102 @org.springframework.stereotype.Component("csar-utils")
103 public class CsarUtils {
104 private static final Logger log = Logger.getLogger(CsarUtils.class);
105 private static final LoggerSupportability loggerSupportability = LoggerSupportability.getLogger(CsarUtils.class.getName());
106 private static final String PATH_DELIMITER = "/";
108 private SdcSchemaFilesCassandraDao sdcSchemaFilesCassandraDao;
110 private ArtifactCassandraDao artifactCassandraDao;
112 private ComponentsUtils componentsUtils;
114 private ToscaExportHandler toscaExportUtils;
116 protected ToscaOperationFacade toscaOperationFacade;
118 @Autowired(required = false)
119 private List<CsarEntryGenerator> generators;
121 private static final String CONFORMANCE_LEVEL = ConfigurationManager.getConfigurationManager().getConfiguration().getToscaConformanceLevel();
122 private static final String SDC_VERSION = ExternalConfiguration.getAppVersion();
123 public static final String ARTIFACTS_PATH = "Artifacts/";
124 private static final String RESOURCES_PATH = "Resources/";
125 private static final String DEFINITIONS_PATH = "Definitions/";
126 public static final String WORKFLOW_ARTIFACT_DIR = "Workflows"+File.separator+"BPMN"+File.separator;
127 public static final String DEPLOYMENT_ARTIFACTS_DIR = "Deployment"+File.separator;
128 private static final String CSAR_META_VERSION = "1.0";
129 private static final String CSAR_META_PATH_FILE_NAME = "csar.meta";
130 private static final String TOSCA_META_PATH_FILE_NAME = "TOSCA-Metadata/TOSCA.meta";
131 private static final String TOSCA_META_VERSION = "1.0";
132 private static final String CSAR_VERSION = "1.1";
133 public static final String ARTIFACTS = "Artifacts";
134 private static final String DEFINITION = "Definitions";
135 private static final String DEL_PATTERN = "([/\\\\]+)";
136 private static final String WORD_PATTERN = "\\w\\_\\-\\.\\s]+)";
137 public static final String VALID_ENGLISH_ARTIFACT_NAME = "([" + WORD_PATTERN;
138 private static final String VALID_ENGLISH_ARTIFACT_NAME_WITH_DIGITS = "([\\d" + WORD_PATTERN;
139 private static final String ARTIFACT_NAME_UNIQUE_ID = "ArtifactName {}, unique ID {}";
141 private static final String VFC_NODE_TYPE_ARTIFACTS_PATH_PATTERN = ARTIFACTS + DEL_PATTERN +
142 ImportUtils.Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX +
143 VALID_ENGLISH_ARTIFACT_NAME_WITH_DIGITS + DEL_PATTERN +
144 VALID_ENGLISH_ARTIFACT_NAME_WITH_DIGITS + DEL_PATTERN +
145 VALID_ENGLISH_ARTIFACT_NAME_WITH_DIGITS + DEL_PATTERN +
146 VALID_ENGLISH_ARTIFACT_NAME_WITH_DIGITS;
148 public static final String VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN = ARTIFACTS + DEL_PATTERN+
149 // Artifact Group (i.e Deployment/Informational)
150 VALID_ENGLISH_ARTIFACT_NAME + DEL_PATTERN +
152 VALID_ENGLISH_ARTIFACT_NAME + DEL_PATTERN +
153 // Artifact Any File Name
156 public static final String SERVICE_TEMPLATE_PATH_PATTERN = DEFINITION + DEL_PATTERN+
157 // Service Template File Name
158 VALID_ENGLISH_ARTIFACT_NAME;
160 public static final String ARTIFACT_CREATED_FROM_CSAR = "Artifact created from csar";
161 private static final String BLOCK_0_TEMPLATE = "SDC-TOSCA-Meta-File-Version: %s\nSDC-TOSCA-Definitions-Version: %s\n";
163 private String versionFirstThreeOctets;
166 if(SDC_VERSION != null && !SDC_VERSION.isEmpty()){
167 Matcher matcher = Pattern.compile("(?!\\.)(\\d+(\\.\\d+)+)(?![\\d\\.])").matcher(SDC_VERSION);
169 setVersionFirstThreeOctets(matcher.group(0));
171 setVersionFirstThreeOctets("");
179 * @param isInCertificationRequest
182 public Either<byte[], ResponseFormat> createCsar(Component component, boolean getFromCS, boolean isInCertificationRequest) {
183 loggerSupportability.log(LoggerSupportabilityActions.GENERATE_CSAR, StatusCode.STARTED,"Starting to create Csar for component {} ",component.getName());
184 final String createdBy = component.getCreatorFullName();
186 Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts();
187 ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE);
188 fileName = artifactDefinition.getArtifactName();
190 String toscaConformanceLevel = ConfigurationManager.getConfigurationManager().getConfiguration().getToscaConformanceLevel();
191 String csarBlock0 = createCsarBlock0(CSAR_META_VERSION, toscaConformanceLevel);
192 byte[] csarBlock0Byte = csarBlock0.getBytes();
194 final String toscaBlock0 = createToscaBlock0(TOSCA_META_VERSION, CSAR_VERSION, createdBy, fileName);
195 byte[] toscaBlock0Byte = toscaBlock0.getBytes();
197 Either<byte[], ResponseFormat> generateCsarZipResponse = generateCsarZip(csarBlock0Byte, toscaBlock0Byte, component, getFromCS, isInCertificationRequest);
199 if (generateCsarZipResponse.isRight()) {
200 return Either.right(generateCsarZipResponse.right().value());
202 loggerSupportability.log(LoggerSupportabilityActions.GENERATE_CSAR, StatusCode.COMPLETE,"Ended create Csar for component {} ",component.getName());
203 return Either.left(generateCsarZipResponse.left().value());
206 private Either<byte[], ResponseFormat> generateCsarZip(byte[] csarBlock0Byte, byte[] toscaBlock0Byte, Component component, boolean getFromCS, boolean isInCertificationRequest) {
207 try (ByteArrayOutputStream out = new ByteArrayOutputStream();
208 ZipOutputStream zip = new ZipOutputStream(out)) {
209 zip.putNextEntry(new ZipEntry(CSAR_META_PATH_FILE_NAME));
210 zip.write(csarBlock0Byte);
211 zip.putNextEntry(new ZipEntry(TOSCA_META_PATH_FILE_NAME));
212 zip.write(toscaBlock0Byte);
213 Either<ZipOutputStream, ResponseFormat> populateZip = populateZip(component, getFromCS, zip, isInCertificationRequest);
214 if (populateZip.isRight()) {
215 log.debug("Failed to populate CSAR zip file {}. Please fix DB table accordingly ", populateZip.right().value());
216 return Either.right(populateZip.right().value());
220 byte[] byteArray = out.toByteArray();
222 return Either.left(byteArray);
223 } catch (IOException e) {
224 log.debug("Failed with IOexception to create CSAR zip for component {}. Please fix DB table accordingly ", component.getUniqueId(), e);
226 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
227 return Either.right(responseFormat);
231 private Either<ZipOutputStream, ResponseFormat> populateZip(Component component, boolean getFromCS, ZipOutputStream zip, boolean isInCertificationRequest) throws IOException {
233 LifecycleStateEnum lifecycleState = component.getLifecycleState();
234 String componentYaml;
235 Either<ToscaRepresentation, ToscaError> exportComponent;
237 // <file name, cassandraId, component>
238 List<Triple<String, String, Component>> dependencies = null;
240 Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts();
241 ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE);
242 String fileName = artifactDefinition.getArtifactName();
244 if (getFromCS || !(lifecycleState == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN || lifecycleState == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT)) {
245 String cassandraId = artifactDefinition.getEsId();
246 Either<byte[], ActionStatus> fromCassandra = getFromCassandra(cassandraId);
247 if (fromCassandra.isRight()) {
248 log.debug(ARTIFACT_NAME_UNIQUE_ID, artifactDefinition.getArtifactName(), artifactDefinition.getUniqueId());
249 ResponseFormat responseFormat = componentsUtils.getResponseFormat(fromCassandra.right().value());
250 return Either.right(responseFormat);
252 mainYaml = fromCassandra.left().value();
255 exportComponent = toscaExportUtils.exportComponent(component);
256 if (exportComponent.isRight()) {
257 log.debug("exportComponent failed", exportComponent.right().value());
258 ActionStatus convertedFromToscaError = componentsUtils.convertFromToscaError(exportComponent.right().value());
259 ResponseFormat responseFormat = componentsUtils.getResponseFormat(convertedFromToscaError);
260 return Either.right(responseFormat);
262 ToscaRepresentation exportResult = exportComponent.left().value();
263 componentYaml = exportResult.getMainYaml();
264 mainYaml = componentYaml.getBytes();
265 dependencies = exportResult.getDependencies();
268 zip.putNextEntry(new ZipEntry(DEFINITIONS_PATH + fileName));
270 //US798487 - Abstraction of complex types
271 if (!ModelConverter.isAtomicComponent(component)){
272 log.debug("Component {} is complex - generating abstract type for it..", component.getName());
273 writeComponentInterface(component, zip, fileName, false);
276 if (dependencies == null) {
277 Either<ToscaTemplate, ToscaError> dependenciesRes = toscaExportUtils.getDependencies(component);
278 if (dependenciesRes.isRight()) {
279 log.debug("Failed to retrieve dependencies for component {}, error {}", component.getUniqueId(),
280 dependenciesRes.right().value());
281 ActionStatus convertFromToscaError = componentsUtils.convertFromToscaError(dependenciesRes.right().value());
282 ResponseFormat responseFormat = componentsUtils.getResponseFormat(convertFromToscaError);
283 return Either.right(responseFormat);
285 dependencies = dependenciesRes.left().value().getDependencies();
288 //UID <cassandraId,filename,component>
289 Map<String, ImmutableTriple<String,String, Component>> innerComponentsCache = new HashMap<>();
291 Either<ZipOutputStream, ResponseFormat> responseFormat = getZipOutputStreamResponseFormatEither(zip, dependencies, innerComponentsCache);
292 if (responseFormat != null) return responseFormat;
294 //retrieve SDC.zip from Cassandra
295 Either<byte[], ResponseFormat> latestSchemaFilesFromCassandra = getLatestSchemaFilesFromCassandra();
297 if(latestSchemaFilesFromCassandra.isRight()){
298 log.error("Error retrieving SDC Schema files from cassandra");
299 return Either.right(latestSchemaFilesFromCassandra.right().value());
302 final byte[] schemaFileZip = latestSchemaFilesFromCassandra.left().value();
304 final List<String> nodesFromPackage = findNonRootNodesFromPackage(dependencies);
306 //add files from retrieved SDC.zip to Definitions folder in CSAR
307 addSchemaFilesFromCassandra(zip, schemaFileZip, nodesFromPackage);
309 Either<CsarDefinition, ResponseFormat> collectedComponentCsarDefinition = collectComponentCsarDefinition(component);
311 if (collectedComponentCsarDefinition.isRight()) {
312 return Either.right(collectedComponentCsarDefinition.right().value());
315 if (generators != null) {
316 for (CsarEntryGenerator generator: generators) {
317 log.debug("Invoking CsarEntryGenerator: {}", generator.getClass().getName());
318 for (Entry<String, byte[]> pluginGeneratedFile : generator.generateCsarEntries(component).entrySet()) {
319 zip.putNextEntry(new ZipEntry(pluginGeneratedFile.getKey()));
320 zip.write(pluginGeneratedFile.getValue());
325 return writeAllFilesToCsar(component, collectedComponentCsarDefinition.left().value(), zip, isInCertificationRequest);
329 * Create a list of all derived nodes found on the package
331 * @param dependencies all node dependencies
332 * @return a list of nodes
334 private List<String> findNonRootNodesFromPackage(final List<Triple<String, String, Component>> dependencies) {
335 final List<String> nodes = new ArrayList<>();
336 if (CollectionUtils.isNotEmpty(dependencies)) {
337 final String NATIVE_ROOT = "tosca.nodes.Root";
338 dependencies.forEach(dependency -> {
339 if (dependency.getRight() instanceof Resource) {
340 final Resource resource = (Resource) dependency.getRight();
341 if (CollectionUtils.isNotEmpty(resource.getDerivedList())) {
342 resource.getDerivedList().stream()
343 .filter(node -> !nodes.contains(node) && !NATIVE_ROOT.equalsIgnoreCase(node))
344 .forEach(node -> nodes.add(node));
353 * Writes a new zip entry
355 * @param zipInputStream the zip entry to be read
356 * @return a map of the given zip entry
358 private Map<String, Object> readYamlZipEntry(final ZipInputStream zipInputStream) throws IOException {
359 final int initSize = 2048;
360 final StringBuilder zipEntry = new StringBuilder();
361 final byte[] buffer = new byte[initSize];
363 while ((read = zipInputStream.read(buffer, 0, initSize)) >= 0) {
364 zipEntry.append(new String(buffer, 0, read));
367 return (Map<String, Object>) new Yaml().load(zipEntry.toString());
371 * Filters and removes all duplicated nodes found
373 * @param nodesFromPackage a List of all derived nodes found on the given package
374 * @param nodesFromArtifactFile represents the nodes.yml file stored in Cassandra
375 * @return a nodes Map updated
377 private Map<String, Object> updateNodeYml(final List<String> nodesFromPackage,
378 final Map<String, Object> nodesFromArtifactFile) {
380 if (MapUtils.isNotEmpty(nodesFromArtifactFile)) {
381 final String nodeTypeBlock = ToscaTagNamesEnum.NODE_TYPES.getElementName();
382 final Map<String, Object> nodeTypes = (Map<String, Object>) nodesFromArtifactFile.get(nodeTypeBlock);
383 nodesFromPackage.stream()
384 .filter(nodeTypes::containsKey)
385 .forEach(nodeTypes::remove);
387 nodesFromArtifactFile.replace(nodeTypeBlock, nodeTypes);
390 return nodesFromArtifactFile;
394 * Updates the zip entry from the given parameters
396 * @param byteArrayOutputStream an output stream in which the data is written into a byte array.
397 * @param nodesYaml a Map of nodes to be written
399 private void updateZipEntry(final ByteArrayOutputStream byteArrayOutputStream,
400 final Map<String, Object> nodesYaml) throws IOException {
401 if (MapUtils.isNotEmpty(nodesYaml)) {
402 byteArrayOutputStream.write(new YamlUtil().objectToYaml(nodesYaml).getBytes());
406 private Either<ZipOutputStream, ResponseFormat> getZipOutputStreamResponseFormatEither(ZipOutputStream zip, List<Triple<String, String, Component>> dependencies, Map<String, ImmutableTriple<String, String, Component>> innerComponentsCache) throws IOException {
408 if (dependencies != null && !dependencies.isEmpty()) {
409 for (Triple<String, String, Component> d : dependencies) {
410 String cassandraId = d.getMiddle();
411 Component childComponent = d.getRight();
412 Either<byte[], ActionStatus> entryData = getEntryData(cassandraId, childComponent);
414 if (entryData.isRight()) {
415 ResponseFormat responseFormat = componentsUtils.getResponseFormat(entryData.right().value());
416 return Either.right(responseFormat);
419 //fill innerComponentsCache
420 fileName = d.getLeft();
421 addComponentToCache(innerComponentsCache, cassandraId, fileName, childComponent);
422 addInnerComponentsToCache(innerComponentsCache, childComponent);
425 //add inner components to CSAR
426 Either<ZipOutputStream, ResponseFormat> responseFormat = addInnerComponentsToCSAR(zip, innerComponentsCache);
427 if (responseFormat != null) return responseFormat;
432 private Either<ZipOutputStream, ResponseFormat> addInnerComponentsToCSAR(ZipOutputStream zip, Map<String, ImmutableTriple<String, String, Component>> innerComponentsCache) throws IOException {
433 for (Entry<String, ImmutableTriple<String, String, Component>> innerComponentTripleEntry : innerComponentsCache.entrySet()) {
435 ImmutableTriple<String, String, Component> innerComponentTriple = innerComponentTripleEntry.getValue();
437 Component innerComponent = innerComponentTriple.getRight();
438 String icFileName = innerComponentTriple.getMiddle();
440 // add component to zip
441 Either<byte[], ActionStatus> entryData = getEntryData(innerComponentTriple.getLeft(), innerComponent);
442 if (entryData.isRight()) {
443 ResponseFormat responseFormat = componentsUtils.getResponseFormat(entryData.right().value());
444 log.debug("Failed adding to zip component {}, error {}", innerComponentTriple.getLeft(),
445 entryData.right().value());
446 return Either.right(responseFormat);
448 byte[] content = entryData.left().value();
449 zip.putNextEntry(new ZipEntry(DEFINITIONS_PATH + icFileName));
452 // add component interface to zip
453 if (!ModelConverter.isAtomicComponent(innerComponent)) {
454 writeComponentInterface(innerComponent, zip, icFileName, true);
460 private void addSchemaFilesFromCassandra(final ZipOutputStream zip,
461 final byte[] schemaFileZip,
462 final List<String> nodesFromPackage) {
463 final int initSize = 2048;
464 log.debug("Starting copy from Schema file zip to CSAR zip");
465 try (final ZipInputStream zipStream = new ZipInputStream(new ByteArrayInputStream(schemaFileZip));
466 final ByteArrayOutputStream out = new ByteArrayOutputStream();
467 final BufferedOutputStream bos = new BufferedOutputStream(out, initSize)) {
470 while ((entry = zipStream.getNextEntry()) != null) {
471 ZipUtils.checkForZipSlipInRead(entry);
472 final String entryName = entry.getName();
473 int readSize = initSize;
474 final byte[] entryData = new byte[initSize];
475 if (entryName.equalsIgnoreCase("nodes.yml")) {
476 handleNode(zipStream, out, nodesFromPackage);
478 while ((readSize = zipStream.read(entryData, 0, readSize)) != -1) {
479 bos.write(entryData, 0, readSize);
484 zip.putNextEntry(new ZipEntry(DEFINITIONS_PATH + entryName));
485 zip.write(out.toByteArray());
489 } catch (final Exception e) {
490 log.error("Error while writing the SDC schema file to the CSAR", e);
491 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
493 log.debug("Finished copy from Schema file zip to CSAR zip");
497 * Handles the nodes.yml zip entry, updating the nodes.yml to avoid duplicated nodes on it.
499 * @param zipInputStream the zip entry to be read
500 * @param byteArrayOutputStream an output stream in which the data is written into a byte array.
501 * @param nodesFromPackage list of all nodes found on the onboarded package
503 private void handleNode(final ZipInputStream zipInputStream,
504 final ByteArrayOutputStream byteArrayOutputStream,
505 final List<String> nodesFromPackage) throws IOException {
507 final Map<String, Object> nodesFromArtifactFile = readYamlZipEntry(zipInputStream);
508 final Map<String, Object> nodesYaml = updateNodeYml(nodesFromPackage, nodesFromArtifactFile);
509 updateZipEntry(byteArrayOutputStream, nodesYaml);
512 private void addInnerComponentsToCache(Map<String, ImmutableTriple<String, String, Component>> componentCache,
513 Component childComponent) {
515 List<ComponentInstance> instances = childComponent.getComponentInstances();
517 if(instances != null) {
518 instances.forEach(ci -> {
519 ImmutableTriple<String, String, Component> componentRecord = componentCache.get(ci.getComponentUid());
520 if (componentRecord == null) {
521 // all resource must be only once!
522 Either<Resource, StorageOperationStatus> resource = toscaOperationFacade.getToscaElement(ci.getComponentUid());
523 Component componentRI = checkAndAddComponent(componentCache, ci, resource);
525 //if not atomic - insert inner components as well
526 if(!ModelConverter.isAtomicComponent(componentRI)) {
527 addInnerComponentsToCache(componentCache, componentRI);
534 private Component checkAndAddComponent(Map<String, ImmutableTriple<String, String, Component>> componentCache, ComponentInstance ci, Either<Resource, StorageOperationStatus> resource) {
535 if (resource.isRight()) {
536 log.debug("Failed to fetch resource with id {} for instance {}", ci.getComponentUid(), ci.getName());
538 Component componentRI = resource.left().value();
540 Map<String, ArtifactDefinition> childToscaArtifacts = componentRI.getToscaArtifacts();
541 ArtifactDefinition childArtifactDefinition = childToscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE);
542 if (childArtifactDefinition != null) {
544 addComponentToCache(componentCache, childArtifactDefinition.getEsId(), childArtifactDefinition.getArtifactName(), componentRI);
549 private void addComponentToCache(Map<String, ImmutableTriple<String, String, Component>> componentCache,
550 String id, String fileName, Component component) {
552 ImmutableTriple<String, String, Component> cachedComponent = componentCache.get(component.getInvariantUUID());
553 if (cachedComponent == null || CommonBeUtils.compareAsdcComponentVersions(component.getVersion(), cachedComponent.getRight().getVersion())) {
554 componentCache.put(component.getInvariantUUID(),
555 new ImmutableTriple<>(id, fileName, component));
557 if(cachedComponent != null) {
558 //overwriting component with newer version
559 log.warn("Overwriting component invariantID {} of version {} with a newer version {}", id, cachedComponent.getRight().getVersion(), component.getVersion());
563 private Either<ZipOutputStream, ResponseFormat> writeComponentInterface(Component component, ZipOutputStream zip,
564 String fileName, boolean isAssociatedComponent) {
566 Either<ToscaRepresentation, ToscaError> componentInterface = toscaExportUtils
567 .exportComponentInterface(component, isAssociatedComponent);
568 ToscaRepresentation componentInterfaceYaml = componentInterface.left().value();
569 String mainYaml = componentInterfaceYaml.getMainYaml();
570 String interfaceFileName = DEFINITIONS_PATH + ToscaExportHandler.getInterfaceFilename(fileName);
572 zip.putNextEntry(new ZipEntry(interfaceFileName));
573 zip.write(mainYaml.getBytes());
575 } catch (Exception e) {
576 log.error("#writeComponentInterface - zip writing failed with error: ", e);
577 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
580 return Either.left(zip);
583 private Either<byte[], ActionStatus> getEntryData(String cassandraId, Component childComponent) {
585 if (cassandraId == null || cassandraId.isEmpty()) {
586 Either<ToscaRepresentation, ToscaError> exportRes = toscaExportUtils.exportComponent(childComponent);
587 if (exportRes.isRight()) {
588 log.debug("Failed to export tosca template for child component {} error {}",
589 childComponent.getUniqueId(), exportRes.right().value());
590 return Either.right(componentsUtils.convertFromToscaError(exportRes.right().value()));
592 content = exportRes.left().value().getMainYaml().getBytes();
594 Either<byte[], ActionStatus> fromCassandra = getFromCassandra(cassandraId);
595 if (fromCassandra.isRight()) {
596 return Either.right(fromCassandra.right().value());
598 content = fromCassandra.left().value();
601 return Either.left(content);
604 private Either<byte[], ResponseFormat> getLatestSchemaFilesFromCassandra() {
605 Either<List<SdcSchemaFilesData>, CassandraOperationStatus> specificSchemaFiles = sdcSchemaFilesCassandraDao.getSpecificSchemaFiles(getVersionFirstThreeOctets(), CONFORMANCE_LEVEL);
607 if(specificSchemaFiles.isRight()){
608 log.debug("Failed to get the schema files SDC-Version: {} Conformance-Level {}. Please fix DB table accordingly.", getVersionFirstThreeOctets(), CONFORMANCE_LEVEL);
609 StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(specificSchemaFiles.right().value());
610 ActionStatus convertedFromStorageResponse = componentsUtils.convertFromStorageResponse(storageStatus);
611 return Either.right(componentsUtils.getResponseFormat(convertedFromStorageResponse));
614 List<SdcSchemaFilesData> listOfSchemas = specificSchemaFiles.left().value();
616 if(listOfSchemas.isEmpty()){
617 log.debug("Failed to get the schema files SDC-Version: {} Conformance-Level {}", getVersionFirstThreeOctets(), CONFORMANCE_LEVEL);
618 return Either.right(componentsUtils.getResponseFormat(ActionStatus.TOSCA_SCHEMA_FILES_NOT_FOUND, getVersionFirstThreeOctets(), CONFORMANCE_LEVEL));
621 SdcSchemaFilesData schemaFile = listOfSchemas.iterator().next();
623 return Either.left(schemaFile.getPayloadAsArray());
626 private Either<byte[], ActionStatus> getFromCassandra(String cassandraId) {
627 Either<DAOArtifactData, CassandraOperationStatus> artifactResponse = artifactCassandraDao.getArtifact(cassandraId);
629 if (artifactResponse.isRight()) {
630 log.debug("Failed to fetch artifact from Cassandra by id {} error {} ", cassandraId, artifactResponse.right().value());
632 StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(artifactResponse.right().value());
633 ActionStatus convertedFromStorageResponse = componentsUtils.convertFromStorageResponse(storageStatus);
634 return Either.right(convertedFromStorageResponse);
636 DAOArtifactData artifactData = artifactResponse.left().value();
637 return Either.left(artifactData.getDataAsArray());
640 private String createCsarBlock0(String metaFileVersion, String toscaConformanceLevel) {
641 return String.format(BLOCK_0_TEMPLATE, metaFileVersion, toscaConformanceLevel);
644 private String createToscaBlock0(String metaFileVersion, String csarVersion, String createdBy, String entryDef) {
645 final String block0template = "TOSCA-Meta-File-Version: %s\nCSAR-Version: %s\nCreated-By: %s\nEntry-Definitions: Definitions/%s\n\nName: csar.meta\nContent-Type: text/plain\n";
646 return String.format(block0template, metaFileVersion, csarVersion, createdBy, entryDef);
650 * Extracts artifacts of VFCs from CSAR
653 * @return Map of <String, List<ArtifactDefinition>> the contains Lists of artifacts according vfcToscaNamespace
655 public static Map<String, List<ArtifactDefinition>> extractVfcsArtifactsFromCsar(Map<String, byte[]> csar) {
657 Map<String, List<ArtifactDefinition>> artifacts = new HashMap<>();
659 log.debug("************* Going to extract VFCs artifacts from Csar. ");
660 Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>();
661 csar.entrySet().stream()
662 // filter CSAR entry by node type artifact path
663 .filter(e -> Pattern.compile(VFC_NODE_TYPE_ARTIFACTS_PATH_PATTERN).matcher(e.getKey()).matches())
664 // extract ArtifactDefinition from CSAR entry for each entry with matching artifact path
665 .forEach(e -> addExtractedVfcArtifact(extractVfcArtifact(e, collectedWarningMessages), artifacts));
666 // add counter suffix to artifact labels
667 handleWarningMessages(collectedWarningMessages);
674 * Print warnings to log
676 * @param collectedWarningMessages
678 public static void handleWarningMessages(Map<String, Set<List<String>>> collectedWarningMessages) {
679 collectedWarningMessages.entrySet().stream()
681 .forEach(e -> e.getValue().stream()
682 // add each warning message to log
683 .forEach(args -> log.warn(e.getKey(), args.toArray())));
687 private static void addExtractedVfcArtifact(ImmutablePair<String, ArtifactDefinition> extractedVfcArtifact, Map<String, List<ArtifactDefinition>> artifacts) {
688 if (extractedVfcArtifact != null) {
689 List<ArtifactDefinition> currArtifactsList;
690 String vfcToscaNamespace = extractedVfcArtifact.getKey();
691 if (artifacts.containsKey(vfcToscaNamespace)) {
692 currArtifactsList = artifacts.get(vfcToscaNamespace);
694 currArtifactsList = new ArrayList<>();
695 artifacts.put(vfcToscaNamespace, currArtifactsList);
697 currArtifactsList.add(extractedVfcArtifact.getValue());
701 private static ImmutablePair<String, ArtifactDefinition> extractVfcArtifact(Entry<String, byte[]> entry, Map<String, Set<List<String>>> collectedWarningMessages) {
702 ArtifactDefinition artifact;
703 String[] parsedCsarArtifactPath = entry.getKey().split(PATH_DELIMITER);
704 Either<ArtifactGroupTypeEnum, Boolean> eitherArtifactGroupType = detectArtifactGroupType(parsedCsarArtifactPath[2].toUpperCase(), collectedWarningMessages);
705 if (eitherArtifactGroupType.isLeft()) {
706 artifact = buildArtifactDefinitionFromCsarArtifactPath(entry, collectedWarningMessages, parsedCsarArtifactPath, eitherArtifactGroupType.left().value());
710 return new ImmutablePair<>(parsedCsarArtifactPath[1], artifact);
713 private static Either<ArtifactGroupTypeEnum, Boolean> detectArtifactGroupType(String groupType, Map<String, Set<List<String>>> collectedWarningMessages) {
714 Either<ArtifactGroupTypeEnum, Boolean> result;
716 ArtifactGroupTypeEnum artifactGroupType = ArtifactGroupTypeEnum.findType(groupType.toUpperCase());
717 if (artifactGroupType == null || (artifactGroupType != ArtifactGroupTypeEnum.INFORMATIONAL && artifactGroupType != ArtifactGroupTypeEnum.DEPLOYMENT)) {
718 String warningMessage = "Warning - unrecognized artifact group type {} was received.";
719 List<String> messageArguments = new ArrayList<>();
720 messageArguments.add(groupType);
721 if (!collectedWarningMessages.containsKey(warningMessage)) {
722 Set<List<String>> messageArgumentLists = new HashSet<>();
723 messageArgumentLists.add(messageArguments);
724 collectedWarningMessages.put(warningMessage, messageArgumentLists);
726 collectedWarningMessages.get(warningMessage).add(messageArguments);
729 result = Either.right(false);
732 result = Either.left(artifactGroupType);
734 } catch (Exception e) {
735 log.debug("detectArtifactGroupType failed with exception", e);
736 result = Either.right(false);
741 private static ArtifactDefinition buildArtifactDefinitionFromCsarArtifactPath(Entry<String, byte[]> entry, Map<String, Set<List<String>>> collectedWarningMessages, String[] parsedCsarArtifactPath, ArtifactGroupTypeEnum artifactGroupType) {
742 ArtifactDefinition artifact;
743 artifact = new ArtifactDefinition();
744 artifact.setArtifactGroupType(artifactGroupType);
745 artifact.setArtifactType(detectArtifactTypeVFC(artifactGroupType, parsedCsarArtifactPath[3], parsedCsarArtifactPath[1], collectedWarningMessages));
746 artifact.setArtifactName(ValidationUtils.normalizeFileName(parsedCsarArtifactPath[parsedCsarArtifactPath.length - 1]));
747 artifact.setPayloadData(Base64.encodeBase64String(entry.getValue()));
748 artifact.setArtifactDisplayName(artifact.getArtifactName().lastIndexOf('.') > 0 ? artifact.getArtifactName().substring(0, artifact.getArtifactName().lastIndexOf('.')) : artifact.getArtifactName());
749 artifact.setArtifactLabel(ValidationUtils.normalizeArtifactLabel(artifact.getArtifactName()));
750 artifact.setDescription(ARTIFACT_CREATED_FROM_CSAR);
751 artifact.setIsFromCsar(true);
752 artifact.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(entry.getValue()));
756 public static final class NonMetaArtifactInfo {
757 private final String path;
758 private final String artifactName;
759 private final String displayName;
760 private final String artifactLabel;
761 private final ArtifactTypeEnum artifactType;
762 private final ArtifactGroupTypeEnum artifactGroupType;
763 private String payloadData;
764 private String artifactChecksum;
765 private String artifactUniqueId;
766 private final boolean isFromCsar;
768 public NonMetaArtifactInfo(String artifactName, String path, ArtifactTypeEnum artifactType, ArtifactGroupTypeEnum artifactGroupType, byte[] payloadData, String artifactUniqueId, boolean isFromCsar) {
771 this.isFromCsar = isFromCsar;
772 this.artifactName = ValidationUtils.normalizeFileName(artifactName);
773 this.artifactType = artifactType;
774 this.artifactGroupType = artifactGroupType;
775 final int pointIndex = artifactName.lastIndexOf('.');
776 if (pointIndex > 0) {
777 displayName = artifactName.substring(0, pointIndex);
779 displayName = artifactName;
781 this.artifactLabel = ValidationUtils.normalizeArtifactLabel(artifactName);
782 if (payloadData != null) {
783 this.payloadData = Base64.encodeBase64String(payloadData);
784 this.artifactChecksum = GeneralUtility.calculateMD5Base64EncodedByByteArray(payloadData);
786 this.artifactUniqueId = artifactUniqueId;
789 public String getPath() {
793 public String getArtifactName() {
797 public ArtifactTypeEnum getArtifactType() {
801 public String getDisplayName() {
805 public ArtifactGroupTypeEnum getArtifactGroupType() {
806 return artifactGroupType;
809 public String getArtifactLabel() {
810 return artifactLabel;
813 public boolean isFromCsar(){
817 public String getPayloadData() {
821 public String getArtifactChecksum() {
822 return artifactChecksum;
825 public String getArtifactUniqueId() {
826 return artifactUniqueId;
829 public void setArtifactUniqueId(String artifactUniqueId) {
830 this.artifactUniqueId = artifactUniqueId;
836 * This method checks the artifact GroupType & Artifact Type. <br>
837 * if there is any problem warning messages are added to collectedWarningMessages
839 * @param artifactPath
840 * @param collectedWarningMessages
843 public static Either<NonMetaArtifactInfo, Boolean> validateNonMetaArtifact(String artifactPath, byte[] payloadData, Map<String, Set<List<String>>> collectedWarningMessages) {
844 Either<NonMetaArtifactInfo, Boolean> ret;
846 String[] parsedArtifactPath = artifactPath.split(PATH_DELIMITER);
847 // Validate Artifact Group Type
848 Either<ArtifactGroupTypeEnum, Boolean> eitherGroupType = detectArtifactGroupType(parsedArtifactPath[1], collectedWarningMessages);
849 if (eitherGroupType.isLeft()) {
850 final ArtifactGroupTypeEnum groupTypeEnum = eitherGroupType.left().value();
852 // Validate Artifact Type
853 String artifactType = parsedArtifactPath[2];
854 artifactType = detectArtifactTypeVF(groupTypeEnum, artifactType, collectedWarningMessages);
856 String artifactFileNameType = parsedArtifactPath[3];
857 ret = Either.left(new NonMetaArtifactInfo(artifactFileNameType, artifactPath, ArtifactTypeEnum.findType(artifactType), groupTypeEnum, payloadData, null, true));
860 ret = Either.right(eitherGroupType.right().value());
862 } catch (Exception e) {
863 log.debug("detectArtifactGroupType failed with exception", e);
864 ret = Either.right(false);
870 private static String detectArtifactTypeVFC(ArtifactGroupTypeEnum artifactGroupType, String receivedTypeName, String parentVfName, Map<String, Set<List<String>>> collectedWarningMessages) {
871 String warningMessage = "Warning - artifact type {} that was provided for VFC {} is not recognized.";
872 return detectArtifactType(artifactGroupType, receivedTypeName, warningMessage, collectedWarningMessages, parentVfName);
875 private static String detectArtifactTypeVF(ArtifactGroupTypeEnum artifactGroupType, String receivedTypeName, Map<String, Set<List<String>>> collectedWarningMessages) {
876 String warningMessage = "Warning - artifact type {} that was provided for VF is not recognized.";
877 return detectArtifactType(artifactGroupType, receivedTypeName, warningMessage, collectedWarningMessages);
880 private static String detectArtifactType(ArtifactGroupTypeEnum artifactGroupType, String receivedTypeName, String warningMessage, Map<String, Set<List<String>>> collectedWarningMessages, String... arguments) {
882 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(receivedTypeName);
883 Map<String, ArtifactTypeConfig> resourceValidTypeArtifacts = null;
885 if(artifactGroupType != null){
886 switch (artifactGroupType) {
888 resourceValidTypeArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration()
889 .getResourceInformationalArtifacts();
892 resourceValidTypeArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration()
893 .getResourceDeploymentArtifacts();
900 Set<String> validArtifactTypes = null;
901 if(resourceValidTypeArtifacts != null){
902 validArtifactTypes = resourceValidTypeArtifacts.keySet();
905 if (validArtifactTypes == null || artifactType == null || !validArtifactTypes.contains(artifactType.getType())) {
906 List<String> messageArguments = new ArrayList<>();
907 messageArguments.add(receivedTypeName);
908 messageArguments.addAll(Arrays.asList(arguments));
909 if (!collectedWarningMessages.containsKey(warningMessage)) {
910 Set<List<String>> messageArgumentLists = new HashSet<>();
911 messageArgumentLists.add(messageArguments);
912 collectedWarningMessages.put(warningMessage, messageArgumentLists);
914 collectedWarningMessages.get(warningMessage).add(messageArguments);
918 return artifactType == null ? ArtifactTypeEnum.OTHER.getType() : artifactType.getType();
921 private Either<ZipOutputStream, ResponseFormat> writeAllFilesToCsar(Component mainComponent, CsarDefinition csarDefinition, ZipOutputStream zipstream, boolean isInCertificationRequest) throws IOException{
922 ComponentArtifacts componentArtifacts = csarDefinition.getComponentArtifacts();
924 Either<ZipOutputStream, ResponseFormat> writeComponentArtifactsToSpecifiedPath = writeComponentArtifactsToSpecifiedPath(mainComponent, componentArtifacts, zipstream, ARTIFACTS_PATH, isInCertificationRequest);
926 if(writeComponentArtifactsToSpecifiedPath.isRight()){
927 return Either.right(writeComponentArtifactsToSpecifiedPath.right().value());
930 ComponentTypeArtifacts mainTypeAndCIArtifacts = componentArtifacts.getMainTypeAndCIArtifacts();
931 writeComponentArtifactsToSpecifiedPath = writeArtifactsInfoToSpecifiedtPath(mainComponent, mainTypeAndCIArtifacts.getComponentArtifacts(), zipstream, ARTIFACTS_PATH, isInCertificationRequest);
933 if(writeComponentArtifactsToSpecifiedPath.isRight()){
934 return Either.right(writeComponentArtifactsToSpecifiedPath.right().value());
937 Map<String, ArtifactsInfo> componentInstancesArtifacts = mainTypeAndCIArtifacts.getComponentInstancesArtifacts();
938 Set<String> keySet = componentInstancesArtifacts.keySet();
940 String currentPath = ARTIFACTS_PATH + RESOURCES_PATH;
941 for (String keyAssetName : keySet) {
942 ArtifactsInfo artifactsInfo = componentInstancesArtifacts.get(keyAssetName);
943 String pathWithAssetName = currentPath + keyAssetName + PATH_DELIMITER;
944 writeComponentArtifactsToSpecifiedPath = writeArtifactsInfoToSpecifiedtPath(mainComponent, artifactsInfo, zipstream, pathWithAssetName, isInCertificationRequest);
946 if(writeComponentArtifactsToSpecifiedPath.isRight()){
947 return Either.right(writeComponentArtifactsToSpecifiedPath.right().value());
950 writeComponentArtifactsToSpecifiedPath = writeOperationsArtifactsToCsar(mainComponent, zipstream);
952 if (writeComponentArtifactsToSpecifiedPath.isRight()) {
953 return Either.right(writeComponentArtifactsToSpecifiedPath.right().value());
955 return Either.left(zipstream);
958 private Either<ZipOutputStream, ResponseFormat> writeOperationsArtifactsToCsar(Component component,
959 ZipOutputStream zipstream) {
960 if (checkComponentBeforeOperation(component)) return Either.left(zipstream);
961 final Map<String, InterfaceDefinition> interfaces = ((Resource) component).getInterfaces();
962 for (Map.Entry<String, InterfaceDefinition> interfaceEntry : interfaces.entrySet()) {
963 for (OperationDataDefinition operation : interfaceEntry.getValue().getOperations().values()) {
965 if (checkComponentBeforeWrite(component, interfaceEntry, operation)) continue;
966 final String artifactUUID = operation.getImplementation().getArtifactUUID();
967 final Either<byte[], ActionStatus> artifactFromCassandra = getFromCassandra(artifactUUID);
968 final String artifactName = operation.getImplementation().getArtifactName();
969 if (artifactFromCassandra.isRight()) {
970 log.error(ARTIFACT_NAME_UNIQUE_ID, artifactName, artifactUUID);
971 log.error("Failed to get {} payload from DB reason: {}", artifactName,
972 artifactFromCassandra.right().value());
973 return Either.right(componentsUtils.getResponseFormat(
974 ActionStatus.ARTIFACT_PAYLOAD_NOT_FOUND_DURING_CSAR_CREATION, "Resource",
975 component.getUniqueId(), artifactName, artifactUUID));
977 final byte[] payloadData = artifactFromCassandra.left().value();
978 zipstream.putNextEntry(new ZipEntry(OperationArtifactUtil.createOperationArtifactPath(
979 component, null, operation,true)));
980 zipstream.write(payloadData);
981 } catch (IOException e) {
982 log.error("Component Name {}, Interface Name {}, Operation Name {}", component.getNormalizedName(),
983 interfaceEntry.getKey(), operation.getName());
984 log.error("Error while writing the operation's artifacts to the CSAR " + "{}", e);
985 return Either.right(componentsUtils
986 .getResponseFormat(ActionStatus.ERROR_DURING_CSAR_CREATION, "Resource",
987 component.getUniqueId()));
991 return Either.left(zipstream);
994 private boolean checkComponentBeforeWrite(Component component, Entry<String, InterfaceDefinition> interfaceEntry, OperationDataDefinition operation) {
995 if (Objects.isNull(operation.getImplementation())) {
996 log.debug("Component Name {}, Interface Id {}, Operation Name {} - no Operation Implementation found",
997 component.getNormalizedName(), interfaceEntry.getValue().getUniqueId(),
998 operation.getName());
1001 if (Objects.isNull(operation.getImplementation().getArtifactName())) {
1002 log.debug("Component Name {}, Interface Id {}, Operation Name {} - no artifact found",
1003 component.getNormalizedName(), interfaceEntry.getValue().getUniqueId(),
1004 operation.getName());
1010 private boolean checkComponentBeforeOperation(Component component) {
1011 if (component instanceof Service) {
1014 if (Objects.isNull(((Resource) component).getInterfaces())) {
1015 log.debug("Component Name {}- no interfaces found", component.getNormalizedName());
1021 private Either<ZipOutputStream, ResponseFormat> writeComponentArtifactsToSpecifiedPath(Component mainComponent, ComponentArtifacts componentArtifacts, ZipOutputStream zipstream,
1022 String currentPath, boolean isInCertificationRequest) throws IOException {
1023 Map<String, ComponentTypeArtifacts> componentTypeArtifacts = componentArtifacts.getComponentTypeArtifacts();
1025 //<Inner Asset TOSCA name (e.g. VFC name)> folder name: <Inner Asset TOSCA name (e.g. VFC name)>_v<version>.
1026 //E.g. "org.openecomp.resource.vf.vipr_atm_v1.0"
1027 Set<String> componentTypeArtifactsKeys = componentTypeArtifacts.keySet();
1028 for (String keyAssetName : componentTypeArtifactsKeys) {
1029 ComponentTypeArtifacts componentInstanceArtifacts = componentTypeArtifacts.get(keyAssetName);
1030 ArtifactsInfo componentArtifacts2 = componentInstanceArtifacts.getComponentArtifacts();
1031 String pathWithAssetName = currentPath + keyAssetName + PATH_DELIMITER;
1032 Either<ZipOutputStream, ResponseFormat> writeArtifactsInfoToSpecifiedPath = writeArtifactsInfoToSpecifiedtPath(mainComponent, componentArtifacts2, zipstream, pathWithAssetName, isInCertificationRequest);
1034 if(writeArtifactsInfoToSpecifiedPath.isRight()){
1035 return writeArtifactsInfoToSpecifiedPath;
1039 return Either.left(zipstream);
1042 private Either<ZipOutputStream, ResponseFormat> writeArtifactsInfoToSpecifiedtPath(Component mainComponent, ArtifactsInfo currArtifactsInfo, ZipOutputStream zip, String path, boolean isInCertificationRequest) throws IOException {
1043 Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> artifactsInfo = currArtifactsInfo
1044 .getArtifactsInfo();
1045 Set<ArtifactGroupTypeEnum> groupTypeEnumKeySet = artifactsInfo.keySet();
1047 for (ArtifactGroupTypeEnum artifactGroupTypeEnum : groupTypeEnumKeySet) {
1048 String groupTypeFolder = path + WordUtils.capitalizeFully(artifactGroupTypeEnum.getType()) + PATH_DELIMITER;
1050 Map<ArtifactTypeEnum, List<ArtifactDefinition>> artifactTypesMap = artifactsInfo.get(artifactGroupTypeEnum);
1051 Set<ArtifactTypeEnum> artifactTypeEnumKeySet = artifactTypesMap.keySet();
1053 for (ArtifactTypeEnum artifactTypeEnum : artifactTypeEnumKeySet) {
1054 List<ArtifactDefinition> artifactDefinitionList = artifactTypesMap.get(artifactTypeEnum);
1055 String artifactTypeFolder = groupTypeFolder + artifactTypeEnum.toString() + PATH_DELIMITER;
1057 if(artifactTypeEnum == ArtifactTypeEnum.WORKFLOW && path.contains(ARTIFACTS_PATH + RESOURCES_PATH)){
1058 // Ignore this packaging as BPMN artifacts needs to be packaged in different manner
1061 if (artifactTypeEnum == ArtifactTypeEnum.WORKFLOW) {
1062 artifactTypeFolder += OperationArtifactUtil.BPMN_ARTIFACT_PATH + File.separator;
1065 Either<ZipOutputStream, ResponseFormat> writeArtifactDefinition = writeArtifactDefinition(mainComponent, zip, artifactDefinitionList, artifactTypeFolder, isInCertificationRequest);
1067 if(writeArtifactDefinition.isRight()){
1068 return writeArtifactDefinition;
1073 return Either.left(zip);
1076 private Either<ZipOutputStream, ResponseFormat> writeArtifactDefinition(Component mainComponent, ZipOutputStream zip, List<ArtifactDefinition> artifactDefinitionList,
1077 String artifactPathAndFolder, boolean isInCertificationRequest) throws IOException {
1079 ComponentTypeEnum componentType = mainComponent.getComponentType();
1080 String heatEnvType = ArtifactTypeEnum.HEAT_ENV.getType();
1082 for (ArtifactDefinition artifactDefinition : artifactDefinitionList) {
1083 if (!isInCertificationRequest && componentType == ComponentTypeEnum.SERVICE
1084 && artifactDefinition.getArtifactType().equals(heatEnvType) ||
1085 //this is placeholder
1086 (artifactDefinition.getEsId() == null && artifactDefinition.getMandatory())){
1090 byte[] payloadData = artifactDefinition.getPayloadData();
1091 String artifactFileName = artifactDefinition.getArtifactName();
1093 if (payloadData == null) {
1094 Either<byte[], ActionStatus> fromCassandra = getFromCassandra(artifactDefinition.getEsId());
1096 if (fromCassandra.isRight()) {
1097 log.debug(ARTIFACT_NAME_UNIQUE_ID, artifactDefinition.getArtifactName(), artifactDefinition.getUniqueId());
1098 log.debug("Failed to get {} payload from DB reason: {}", artifactFileName, fromCassandra.right().value());
1101 payloadData = fromCassandra.left().value();
1103 zip.putNextEntry(new ZipEntry(artifactPathAndFolder + artifactFileName));
1104 zip.write(payloadData);
1107 return Either.left(zip);
1110 /************************************ Artifacts Structure ******************************************************************/
1112 * The artifacts Definition saved by their structure
1114 private class ArtifactsInfo {
1115 //Key is the type of artifacts(Informational/Deployment)
1116 //Value is a map between an artifact type and a list of all artifacts of this type
1117 private Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> artifactsInfoField;
1119 public ArtifactsInfo() {
1120 this.artifactsInfoField = new EnumMap<>(ArtifactGroupTypeEnum.class);
1123 public Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> getArtifactsInfo() {
1124 return artifactsInfoField;
1127 public List<ArtifactDefinition> getFlatArtifactsListByType(ArtifactTypeEnum artifactType){
1128 List<ArtifactDefinition> artifacts = new ArrayList<>();
1129 for (List<ArtifactDefinition> artifactsByType:artifactsInfoField.get(artifactType).values()){
1130 artifacts.addAll(artifactsByType);
1135 public void addArtifactsToGroup(ArtifactGroupTypeEnum artifactGroup,Map<ArtifactTypeEnum, List<ArtifactDefinition>> artifactsDefinition){
1136 if (artifactsInfoField.get(artifactGroup) == null) {
1137 artifactsInfoField.put(artifactGroup, artifactsDefinition);
1139 Map<ArtifactTypeEnum, List<ArtifactDefinition>> artifactTypeEnumListMap =
1140 artifactsInfoField.get(artifactGroup);
1141 artifactTypeEnumListMap.putAll(artifactsDefinition);
1142 artifactsInfoField.put(artifactGroup, artifactTypeEnumListMap);
1147 public boolean isEmpty() {
1148 return artifactsInfoField.isEmpty();
1154 * The artifacts of the component and of all its composed instances
1157 private class ComponentTypeArtifacts {
1158 private ArtifactsInfo componentArtifacts; //component artifacts (describes the Informational Deployment folders)
1159 private Map<String, ArtifactsInfo> componentInstancesArtifacts; //artifacts of the composed instances mapped by the resourceInstance normalized name (describes the Resources folder)
1161 public ComponentTypeArtifacts() {
1162 componentArtifacts = new ArtifactsInfo();
1163 componentInstancesArtifacts = new HashMap<>();
1166 public ArtifactsInfo getComponentArtifacts() {
1167 return componentArtifacts;
1169 public void setComponentArtifacts(ArtifactsInfo artifactsInfo) {
1170 this.componentArtifacts = artifactsInfo;
1172 public Map<String, ArtifactsInfo> getComponentInstancesArtifacts() {
1173 return componentInstancesArtifacts;
1175 public void setComponentInstancesArtifacts(Map<String, ArtifactsInfo> componentInstancesArtifacts) {
1176 this.componentInstancesArtifacts = componentInstancesArtifacts;
1179 public void addComponentInstancesArtifacts(String normalizedName, ArtifactsInfo artifactsInfo) {
1180 componentInstancesArtifacts.put(normalizedName, artifactsInfo);
1185 private class ComponentArtifacts {
1186 //artifacts of the component and CI's artifacts contained in it's composition (represents Informational, Deployment & Resource folders of main component)
1187 private ComponentTypeArtifacts mainTypeAndCIArtifacts;
1188 //artifacts of all component types mapped by their tosca name
1189 private Map<String, ComponentTypeArtifacts> componentTypeArtifacts;
1191 public ComponentArtifacts(){
1192 mainTypeAndCIArtifacts = new ComponentTypeArtifacts();
1193 componentTypeArtifacts = new HashMap<>();
1196 public ComponentTypeArtifacts getMainTypeAndCIArtifacts() {
1197 return mainTypeAndCIArtifacts;
1200 public void setMainTypeAndCIArtifacts(ComponentTypeArtifacts componentInstanceArtifacts) {
1201 this.mainTypeAndCIArtifacts = componentInstanceArtifacts;
1204 public Map<String, ComponentTypeArtifacts> getComponentTypeArtifacts() {
1205 return componentTypeArtifacts;
1208 public void setComponentTypeArtifacts(Map<String, ComponentTypeArtifacts> componentTypeArtifacts) {
1209 this.componentTypeArtifacts = componentTypeArtifacts;
1213 private class CsarDefinition {
1214 private ComponentArtifacts componentArtifacts;
1216 // add list of tosca artifacts and meta describes CSAR zip root
1218 public CsarDefinition(ComponentArtifacts componentArtifacts) {
1219 this.componentArtifacts = componentArtifacts;
1222 public ComponentArtifacts getComponentArtifacts() {
1223 return componentArtifacts;
1227 /************************************ Artifacts Structure END******************************************************************/
1229 private Either<CsarDefinition,ResponseFormat> collectComponentCsarDefinition(Component component){
1230 ComponentArtifacts componentArtifacts = new ComponentArtifacts();
1231 Component updatedComponent = component;
1233 //get service to receive the AII artifacts uploaded to the service
1234 if (updatedComponent.getComponentType() == ComponentTypeEnum.SERVICE) {
1235 Either<Service, StorageOperationStatus> getServiceResponse = toscaOperationFacade.getToscaElement(updatedComponent.getUniqueId());
1237 if(getServiceResponse.isRight()){
1238 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getServiceResponse.right().value());
1239 return Either.right(componentsUtils.getResponseFormat(actionStatus));
1242 updatedComponent = getServiceResponse.left().value();
1245 //find the artifacts of the main component, it would have its composed instances artifacts in a separate folder
1246 ComponentTypeArtifacts componentInstanceArtifacts = new ComponentTypeArtifacts();
1247 ArtifactsInfo artifactsInfo = collectComponentArtifacts(updatedComponent);
1248 componentInstanceArtifacts.setComponentArtifacts(artifactsInfo);
1249 componentArtifacts.setMainTypeAndCIArtifacts(componentInstanceArtifacts);
1251 Map<String,ComponentTypeArtifacts> resourceTypeArtifacts = componentArtifacts.getComponentTypeArtifacts(); //artifacts mapped by the component type(tosca name+version)
1252 //get the component instances
1253 List<ComponentInstance> componentInstances = updatedComponent.getComponentInstances();
1254 if (componentInstances!=null){
1255 for (ComponentInstance componentInstance:componentInstances){
1256 //call recursive to find artifacts for all the path
1257 Either<Boolean, ResponseFormat> collectComponentInstanceArtifacts = collectComponentInstanceArtifacts(
1258 updatedComponent, componentInstance, resourceTypeArtifacts, componentInstanceArtifacts);
1259 if (collectComponentInstanceArtifacts.isRight()){
1260 return Either.right(collectComponentInstanceArtifacts.right().value());
1265 if(log.isDebugEnabled()){
1266 printResult(componentArtifacts,updatedComponent.getName());
1269 return Either.left(new CsarDefinition(componentArtifacts));
1272 private void printResult(ComponentArtifacts componentArtifacts, String name) {
1273 StringBuilder result = new StringBuilder();
1274 result.append("Artifacts of main component " + name + "\n");
1275 ComponentTypeArtifacts componentInstanceArtifacts = componentArtifacts.getMainTypeAndCIArtifacts();
1276 printArtifacts(componentInstanceArtifacts);
1277 result.append("Type Artifacts\n");
1278 for (Map.Entry<String, ComponentTypeArtifacts> typeArtifacts:componentArtifacts.getComponentTypeArtifacts().entrySet()){
1279 result.append("Folder " + typeArtifacts.getKey() + "\n");
1280 result.append(printArtifacts(typeArtifacts.getValue()));
1283 if(log.isDebugEnabled()){
1284 log.debug(result.toString());
1288 private String printArtifacts(ComponentTypeArtifacts componentInstanceArtifacts) {
1289 StringBuilder result = new StringBuilder();
1290 ArtifactsInfo artifactsInfo = componentInstanceArtifacts.getComponentArtifacts();
1291 Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> componetArtifacts = artifactsInfo.getArtifactsInfo();
1292 printArtifacts(componetArtifacts);
1293 result = result.append("Resources\n");
1294 for (Map.Entry<String, ArtifactsInfo> resourceInstance:componentInstanceArtifacts.getComponentInstancesArtifacts().entrySet()){
1295 result.append("Folder" + resourceInstance.getKey() + "\n");
1296 result.append(printArtifacts(resourceInstance.getValue().getArtifactsInfo()));
1299 return result.toString();
1302 private String printArtifacts(Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> componetArtifacts) {
1303 StringBuilder result = new StringBuilder();
1304 for (Map.Entry<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> artifactGroup:componetArtifacts.entrySet()){
1305 result.append(" " + artifactGroup.getKey().getType());
1306 for (Map.Entry<ArtifactTypeEnum, List<ArtifactDefinition>> groupArtifacts:artifactGroup.getValue().entrySet()){
1307 result.append(" " + groupArtifacts.getKey().getType());
1308 for (ArtifactDefinition artifact:groupArtifacts.getValue()){
1309 result.append(" " + artifact.getArtifactDisplayName());
1314 return result.toString();
1317 private ComponentTypeArtifacts collectComponentTypeArtifacts(Map<String, ComponentTypeArtifacts> resourcesArtifacts, ComponentInstance componentInstance,
1318 Component fetchedComponent) {
1319 String toscaComponentName = componentInstance.getToscaComponentName() + "_v" + componentInstance.getComponentVersion();
1321 ComponentTypeArtifacts componentArtifactsInfo = resourcesArtifacts.get(toscaComponentName);
1322 //if there are no artifacts for this component type we need to fetch and build them
1323 if (componentArtifactsInfo==null){
1324 ArtifactsInfo componentArtifacts = collectComponentArtifacts(fetchedComponent);
1325 componentArtifactsInfo = new ComponentTypeArtifacts();
1326 if (!componentArtifacts.isEmpty()){
1327 componentArtifactsInfo.setComponentArtifacts(componentArtifacts);
1328 resourcesArtifacts.put(toscaComponentName, componentArtifactsInfo);
1331 return componentArtifactsInfo;
1334 private Either<Boolean, ResponseFormat> collectComponentInstanceArtifacts(Component parentComponent,ComponentInstance componentInstance,
1335 Map<String, ComponentTypeArtifacts> resourcesTypeArtifacts,ComponentTypeArtifacts instanceArtifactsLocation) {
1336 //1. get the component instance component
1337 String componentUid;
1338 if (componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy) {
1339 componentUid = componentInstance.getSourceModelUid();
1342 componentUid = componentInstance.getComponentUid();
1344 Either<Component, StorageOperationStatus> component = toscaOperationFacade.getToscaElement(componentUid);
1345 if (component.isRight()) {
1346 log.error("Failed to fetch resource with id {} for instance {}",componentUid, parentComponent.getUUID());
1347 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ASSET_NOT_FOUND_DURING_CSAR_CREATION,
1348 parentComponent.getComponentType().getValue(), parentComponent.getUUID(),
1349 componentInstance.getOriginType().getComponentType().getValue(), componentUid));
1351 Component fetchedComponent = component.left().value();
1353 //2. fill the artifacts for the current component parent type
1354 ComponentTypeArtifacts componentParentArtifacts = collectComponentTypeArtifacts(resourcesTypeArtifacts, componentInstance, fetchedComponent);
1356 //3. find the artifacts specific to the instance
1357 Map<ArtifactTypeEnum, List<ArtifactDefinition>> componentInstanceSpecificInformationalArtifacts =
1358 getComponentInstanceSpecificArtifacts(componentInstance.getArtifacts(),
1359 componentParentArtifacts.getComponentArtifacts().getArtifactsInfo(), ArtifactGroupTypeEnum.INFORMATIONAL);
1360 Map<ArtifactTypeEnum, List<ArtifactDefinition>> componentInstanceSpecificDeploymentArtifacts =
1361 getComponentInstanceSpecificArtifacts(componentInstance.getDeploymentArtifacts(),
1362 componentParentArtifacts.getComponentArtifacts().getArtifactsInfo(), ArtifactGroupTypeEnum.DEPLOYMENT);
1364 //4. add the instances artifacts to the component type
1365 ArtifactsInfo artifactsInfo = new ArtifactsInfo();
1366 if (!componentInstanceSpecificInformationalArtifacts.isEmpty()){
1367 artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.INFORMATIONAL, componentInstanceSpecificInformationalArtifacts);
1369 if (!componentInstanceSpecificDeploymentArtifacts.isEmpty()){
1370 artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.DEPLOYMENT, componentInstanceSpecificDeploymentArtifacts);
1372 if (!artifactsInfo.isEmpty()){
1373 instanceArtifactsLocation.addComponentInstancesArtifacts(componentInstance.getNormalizedName(), artifactsInfo);
1376 //5. do the same for all the component instances
1377 List<ComponentInstance> componentInstances = fetchedComponent.getComponentInstances();
1378 if (componentInstances!=null){
1379 for (ComponentInstance childComponentInstance:componentInstances){
1380 Either<Boolean, ResponseFormat> collectComponentInstanceArtifacts = collectComponentInstanceArtifacts(
1381 fetchedComponent, childComponentInstance, resourcesTypeArtifacts, componentParentArtifacts);
1382 if (collectComponentInstanceArtifacts.isRight()){
1383 return collectComponentInstanceArtifacts;
1388 return Either.left(true);
1391 public String getVersionFirstThreeOctets() {
1392 return versionFirstThreeOctets;
1395 public void setVersionFirstThreeOctets(String versionFirstThreeOctetes) {
1396 this.versionFirstThreeOctets = versionFirstThreeOctetes;
1398 private Map<ArtifactTypeEnum, List<ArtifactDefinition>> getComponentInstanceSpecificArtifacts(Map<String, ArtifactDefinition> componentArtifacts,
1399 Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> componentTypeArtifacts, ArtifactGroupTypeEnum artifactGroupTypeEnum) {
1400 Map<ArtifactTypeEnum, List<ArtifactDefinition>> parentArtifacts = componentTypeArtifacts.get(artifactGroupTypeEnum); //the artfiacts of the component itself and not the instance
1402 Map<ArtifactTypeEnum, List<ArtifactDefinition>> artifactsByTypeOfComponentInstance = new EnumMap<>(ArtifactTypeEnum.class);
1403 if (componentArtifacts!=null){
1404 for (ArtifactDefinition artifact:componentArtifacts.values()){
1405 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifact.getArtifactType());
1406 List<ArtifactDefinition> parentArtifactsByType = null;
1407 if (parentArtifacts!=null){
1408 parentArtifactsByType = parentArtifacts.get(artifactType);
1410 //the artifact is of instance
1411 if (parentArtifactsByType == null || !parentArtifactsByType.contains(artifact)){
1412 List<ArtifactDefinition> typeArtifacts = artifactsByTypeOfComponentInstance.get(artifactType);
1413 if (typeArtifacts == null){
1414 typeArtifacts = new ArrayList<>();
1415 artifactsByTypeOfComponentInstance.put(artifactType, typeArtifacts);
1417 typeArtifacts.add(artifact);
1422 return artifactsByTypeOfComponentInstance;
1425 private ArtifactsInfo collectComponentArtifacts(Component component) {
1426 Map<String, ArtifactDefinition> informationalArtifacts = component.getArtifacts();
1427 Map<ArtifactTypeEnum, List<ArtifactDefinition>> informationalArtifactsByType = collectGroupArtifacts(informationalArtifacts);
1428 Map<String, ArtifactDefinition> deploymentArtifacts = component.getDeploymentArtifacts();
1429 Map<ArtifactTypeEnum, List<ArtifactDefinition>> deploymentArtifactsByType = collectGroupArtifacts(deploymentArtifacts);
1430 Map<String, ArtifactDefinition> interfaceOperationArtifacts =
1431 OperationArtifactUtil.getDistinctInterfaceOperationArtifactsByName(component);
1432 Map<ArtifactTypeEnum, List<ArtifactDefinition>> interfaceOperationArtifactsByType = collectGroupArtifacts(
1433 interfaceOperationArtifacts);
1434 ArtifactsInfo artifactsInfo = new ArtifactsInfo();
1435 if (!informationalArtifactsByType.isEmpty()){
1436 artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.INFORMATIONAL, informationalArtifactsByType);
1438 if (!deploymentArtifactsByType.isEmpty() ){
1439 artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.DEPLOYMENT, deploymentArtifactsByType);
1441 //Add component interface operation artifacts
1442 if(MapUtils.isNotEmpty(interfaceOperationArtifacts)) {
1443 artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.DEPLOYMENT, interfaceOperationArtifactsByType);
1446 return artifactsInfo;
1449 private Map<ArtifactTypeEnum, List<ArtifactDefinition>> collectGroupArtifacts(Map<String, ArtifactDefinition> componentArtifacts) {
1450 Map<ArtifactTypeEnum, List<ArtifactDefinition>> artifactsByType = new EnumMap<>(ArtifactTypeEnum.class);
1451 for (ArtifactDefinition artifact:componentArtifacts.values()){
1452 if (artifact.getArtifactUUID()!=null){
1453 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifact.getArtifactType());
1454 List<ArtifactDefinition> typeArtifacts = artifactsByType.get(artifactType);
1455 if (typeArtifacts==null){
1456 typeArtifacts = new ArrayList<>();
1457 artifactsByType.put(artifactType, typeArtifacts);
1459 typeArtifacts.add(artifact);
1462 return artifactsByType;