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;
25 import fj.data.Either;
26 import java.io.BufferedOutputStream;
27 import java.io.ByteArrayInputStream;
29 import java.io.IOException;
30 import java.util.ArrayList;
31 import java.util.Arrays;
32 import java.util.EnumMap;
33 import java.util.HashMap;
34 import java.util.HashSet;
35 import java.util.List;
37 import java.util.Map.Entry;
38 import java.util.Objects;
39 import java.util.Optional;
41 import java.util.function.Function;
42 import java.util.function.Predicate;
43 import java.util.function.Supplier;
44 import java.util.regex.Matcher;
45 import java.util.regex.Pattern;
46 import java.util.zip.ZipEntry;
47 import java.util.zip.ZipInputStream;
48 import java.util.zip.ZipOutputStream;
51 import org.apache.commons.codec.binary.Base64;
52 import org.apache.commons.collections.CollectionUtils;
53 import org.apache.commons.collections.MapUtils;
54 import org.apache.commons.io.output.ByteArrayOutputStream;
55 import org.apache.commons.lang.WordUtils;
56 import org.apache.commons.lang3.tuple.ImmutablePair;
57 import org.apache.commons.lang3.tuple.ImmutableTriple;
58 import org.apache.commons.lang3.tuple.Triple;
59 import org.onap.sdc.tosca.services.YamlUtil;
60 import org.openecomp.sdc.be.components.impl.ImportUtils;
61 import org.openecomp.sdc.be.components.impl.ImportUtils.Constants;
62 import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException;
63 import org.openecomp.sdc.be.config.ArtifactConfigManager;
64 import org.openecomp.sdc.be.config.ArtifactConfiguration;
65 import org.openecomp.sdc.be.config.ComponentType;
66 import org.openecomp.sdc.be.config.ConfigurationManager;
67 import org.openecomp.sdc.be.dao.api.ActionStatus;
68 import org.openecomp.sdc.be.dao.cassandra.ArtifactCassandraDao;
69 import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus;
70 import org.openecomp.sdc.be.dao.cassandra.SdcSchemaFilesCassandraDao;
71 import org.openecomp.sdc.be.datatypes.elements.OperationDataDefinition;
72 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
73 import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
74 import org.openecomp.sdc.be.impl.ComponentsUtils;
75 import org.openecomp.sdc.be.model.ArtifactDefinition;
76 import org.openecomp.sdc.be.model.Component;
77 import org.openecomp.sdc.be.model.ComponentInstance;
78 import org.openecomp.sdc.be.model.InterfaceDefinition;
79 import org.openecomp.sdc.be.model.LifecycleStateEnum;
80 import org.openecomp.sdc.be.model.Resource;
81 import org.openecomp.sdc.be.model.Service;
82 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade;
83 import org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter;
84 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
85 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
86 import org.openecomp.sdc.be.plugins.CsarEntryGenerator;
87 import org.openecomp.sdc.be.resources.data.DAOArtifactData;
88 import org.openecomp.sdc.be.tosca.model.ToscaTemplate;
89 import org.openecomp.sdc.be.tosca.utils.OperationArtifactUtil;
90 import org.openecomp.sdc.be.utils.CommonBeUtils;
91 import org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum;
92 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
93 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
94 import org.openecomp.sdc.common.impl.ExternalConfiguration;
95 import org.openecomp.sdc.common.log.elements.LoggerSupportability;
96 import org.openecomp.sdc.common.log.enums.LoggerSupportabilityActions;
97 import org.openecomp.sdc.common.log.enums.StatusCode;
98 import org.openecomp.sdc.common.log.wrappers.Logger;
99 import org.openecomp.sdc.common.util.GeneralUtility;
100 import org.openecomp.sdc.common.util.ValidationUtils;
101 import org.openecomp.sdc.common.zip.ZipUtils;
102 import org.openecomp.sdc.exception.ResponseFormat;
103 import org.springframework.beans.factory.annotation.Autowired;
104 import org.yaml.snakeyaml.Yaml;
110 @org.springframework.stereotype.Component("csar-utils")
111 public class CsarUtils {
112 private static final Logger log = Logger.getLogger(CsarUtils.class);
113 private static final LoggerSupportability loggerSupportability = LoggerSupportability.getLogger(CsarUtils.class.getName());
114 private static final String PATH_DELIMITER = "/";
116 private SdcSchemaFilesCassandraDao sdcSchemaFilesCassandraDao;
118 private ArtifactCassandraDao artifactCassandraDao;
120 private ComponentsUtils componentsUtils;
122 private ToscaExportHandler toscaExportUtils;
124 protected ToscaOperationFacade toscaOperationFacade;
126 @Autowired(required = false)
127 private List<CsarEntryGenerator> generators;
129 private static final String CONFORMANCE_LEVEL = ConfigurationManager.getConfigurationManager().getConfiguration().getToscaConformanceLevel();
130 private static final String SDC_VERSION = ExternalConfiguration.getAppVersion();
131 public static final String ARTIFACTS_PATH = "Artifacts/";
132 private static final String RESOURCES_PATH = "Resources/";
133 private static final String DEFINITIONS_PATH = "Definitions/";
134 public static final String WORKFLOW_ARTIFACT_DIR = "Workflows"+File.separator+"BPMN"+File.separator;
135 public static final String DEPLOYMENT_ARTIFACTS_DIR = "Deployment"+File.separator;
136 private static final String CSAR_META_VERSION = "1.0";
137 private static final String CSAR_META_PATH_FILE_NAME = "csar.meta";
138 private static final String TOSCA_META_PATH_FILE_NAME = "TOSCA-Metadata/TOSCA.meta";
139 private static final String TOSCA_META_VERSION = "1.0";
140 private static final String CSAR_VERSION = "1.1";
141 public static final String ARTIFACTS = "Artifacts";
142 private static final String DEFINITION = "Definitions";
143 private static final String DEL_PATTERN = "([/\\\\]+)";
144 private static final String WORD_PATTERN = "\\w\\_\\-\\.\\s]+)";
145 public static final String VALID_ENGLISH_ARTIFACT_NAME = "([" + WORD_PATTERN;
146 private static final String VALID_ENGLISH_ARTIFACT_NAME_WITH_DIGITS = "([\\d" + WORD_PATTERN;
147 private static final String ARTIFACT_NAME_UNIQUE_ID = "ArtifactName {}, unique ID {}";
149 private static final String VFC_NODE_TYPE_ARTIFACTS_PATH_PATTERN = ARTIFACTS + DEL_PATTERN +
150 ImportUtils.Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX +
151 VALID_ENGLISH_ARTIFACT_NAME_WITH_DIGITS + DEL_PATTERN +
152 VALID_ENGLISH_ARTIFACT_NAME_WITH_DIGITS + DEL_PATTERN +
153 VALID_ENGLISH_ARTIFACT_NAME_WITH_DIGITS + DEL_PATTERN +
154 VALID_ENGLISH_ARTIFACT_NAME_WITH_DIGITS;
156 public static final String VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN = ARTIFACTS + DEL_PATTERN+
157 // Artifact Group (i.e Deployment/Informational)
158 VALID_ENGLISH_ARTIFACT_NAME + DEL_PATTERN +
160 VALID_ENGLISH_ARTIFACT_NAME + DEL_PATTERN +
161 // Artifact Any File Name
164 public static final String SERVICE_TEMPLATE_PATH_PATTERN = DEFINITION + DEL_PATTERN+
165 // Service Template File Name
166 VALID_ENGLISH_ARTIFACT_NAME;
168 public static final String ARTIFACT_CREATED_FROM_CSAR = "Artifact created from csar";
169 private static final String BLOCK_0_TEMPLATE = "SDC-TOSCA-Meta-File-Version: %s\nSDC-TOSCA-Definitions-Version: %s\n";
171 private String versionFirstThreeOctets;
174 if(SDC_VERSION != null && !SDC_VERSION.isEmpty()){
175 Matcher matcher = Pattern.compile("(?!\\.)(\\d+(\\.\\d+)+)(?![\\d\\.])").matcher(SDC_VERSION);
177 setVersionFirstThreeOctets(matcher.group(0));
179 setVersionFirstThreeOctets("");
187 * @param isInCertificationRequest
190 public Either<byte[], ResponseFormat> createCsar(Component component, boolean getFromCS, boolean isInCertificationRequest) {
191 loggerSupportability.log(LoggerSupportabilityActions.GENERATE_CSAR, StatusCode.STARTED,"Starting to create Csar for component {} ",component.getName());
192 final String createdBy = component.getCreatorFullName();
194 Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts();
195 ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE);
196 fileName = artifactDefinition.getArtifactName();
198 String toscaConformanceLevel = ConfigurationManager.getConfigurationManager().getConfiguration().getToscaConformanceLevel();
199 String csarBlock0 = createCsarBlock0(CSAR_META_VERSION, toscaConformanceLevel);
200 byte[] csarBlock0Byte = csarBlock0.getBytes();
202 final String toscaBlock0 = createToscaBlock0(TOSCA_META_VERSION, CSAR_VERSION, createdBy, fileName);
203 byte[] toscaBlock0Byte = toscaBlock0.getBytes();
205 return generateCsarZip(csarBlock0Byte, toscaBlock0Byte, component, getFromCS, isInCertificationRequest)
206 .left().map(responseFormat -> {
207 loggerSupportability.log(LoggerSupportabilityActions.GENERATE_CSAR, StatusCode.COMPLETE,
208 "Ended create Csar for component {} ", component.getName());
209 return responseFormat;
213 private Either<byte[], ResponseFormat> generateCsarZip(byte[] csarBlock0Byte, byte[] toscaBlock0Byte, Component component, boolean getFromCS, boolean isInCertificationRequest) {
214 try (ByteArrayOutputStream out = new ByteArrayOutputStream();
215 ZipOutputStream zip = new ZipOutputStream(out)) {
216 zip.putNextEntry(new ZipEntry(CSAR_META_PATH_FILE_NAME));
217 zip.write(csarBlock0Byte);
218 zip.putNextEntry(new ZipEntry(TOSCA_META_PATH_FILE_NAME));
219 zip.write(toscaBlock0Byte);
220 Either<ZipOutputStream, ResponseFormat> populateZip = populateZip(component, getFromCS, zip, isInCertificationRequest);
221 if (populateZip.isRight()) {
222 log.debug("Failed to populate CSAR zip file {}. Please fix DB table accordingly ", populateZip.right().value());
223 return Either.right(populateZip.right().value());
227 byte[] byteArray = out.toByteArray();
229 return Either.left(byteArray);
230 } catch (IOException e) {
231 log.debug("Failed with IOexception to create CSAR zip for component {}. Please fix DB table accordingly ", component.getUniqueId(), e);
233 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
234 return Either.right(responseFormat);
238 private Either<ZipOutputStream, ResponseFormat> populateZip(Component component, boolean getFromCS, ZipOutputStream zip, boolean isInCertificationRequest) throws IOException {
240 ArtifactDefinition artifactDef = component
242 .get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE);
244 LifecycleStateEnum lifecycleState = component.getLifecycleState();
245 // Assigning to null is a bad practice but in order to keep the refactoring small enough we keep this for now.
246 Either<MainYamlWithDependencies, ResponseFormat> result = null;
247 if (getFromCS || !(lifecycleState == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN || lifecycleState == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT)) {
248 result = getArtifactFromCassandra(artifactDef);
250 result = exportComponent(component);
253 // TODO: Refactor the rest of this function
255 List<Triple<String, String, Component>> dependencies = null;
256 // This should not be done but in order to keep the refactoring small enough we stop here.
257 if(result.isLeft()) {
258 mainYaml = result.left().value().mainYaml;
259 dependencies = result.left().value().dependencies.orElse(null);
261 return Either.right(result.right().value());
264 String fileName = artifactDef.getArtifactName();
265 zip.putNextEntry(new ZipEntry(DEFINITIONS_PATH + fileName));
267 //US798487 - Abstraction of complex types
268 if (!ModelConverter.isAtomicComponent(component)){
269 log.debug("Component {} is complex - generating abstract type for it..", component.getName());
270 writeComponentInterface(component, zip, fileName, false);
273 if (dependencies == null) {
274 Either<ToscaTemplate, ToscaError> dependenciesRes = toscaExportUtils.getDependencies(component);
275 if (dependenciesRes.isRight()) {
276 log.debug("Failed to retrieve dependencies for component {}, error {}", component.getUniqueId(),
277 dependenciesRes.right().value());
278 ActionStatus convertFromToscaError = componentsUtils.convertFromToscaError(dependenciesRes.right().value());
279 ResponseFormat responseFormat = componentsUtils.getResponseFormat(convertFromToscaError);
280 return Either.right(responseFormat);
282 dependencies = dependenciesRes.left().value().getDependencies();
285 //UID <cassandraId,filename,component>
286 Map<String, ImmutableTriple<String,String, Component>> innerComponentsCache = new HashMap<>();
288 Either<ZipOutputStream, ResponseFormat> responseFormat = getZipOutputStreamResponseFormatEither(zip, dependencies, innerComponentsCache);
289 if (responseFormat != null) return responseFormat;
291 //retrieve SDC.zip from Cassandra
292 Either<byte[], ResponseFormat> latestSchemaFilesFromCassandra = getLatestSchemaFilesFromCassandra();
294 if(latestSchemaFilesFromCassandra.isRight()){
295 log.error("Error retrieving SDC Schema files from cassandra");
296 return Either.right(latestSchemaFilesFromCassandra.right().value());
299 final byte[] schemaFileZip = latestSchemaFilesFromCassandra.left().value();
301 final List<String> nodesFromPackage = findNonRootNodesFromPackage(dependencies);
303 //add files from retrieved SDC.zip to Definitions folder in CSAR
304 addSchemaFilesFromCassandra(zip, schemaFileZip, nodesFromPackage);
306 Either<CsarDefinition, ResponseFormat> collectedComponentCsarDefinition = collectComponentCsarDefinition(component);
308 if (collectedComponentCsarDefinition.isRight()) {
309 return Either.right(collectedComponentCsarDefinition.right().value());
312 if (generators != null) {
313 for (CsarEntryGenerator generator: generators) {
314 log.debug("Invoking CsarEntryGenerator: {}", generator.getClass().getName());
315 for (Entry<String, byte[]> pluginGeneratedFile : generator.generateCsarEntries(component).entrySet()) {
316 zip.putNextEntry(new ZipEntry(pluginGeneratedFile.getKey()));
317 zip.write(pluginGeneratedFile.getValue());
322 return writeAllFilesToCsar(component, collectedComponentCsarDefinition.left().value(), zip, isInCertificationRequest);
325 private Either<MainYamlWithDependencies, ResponseFormat> exportComponent(Component component) {
326 return toscaExportUtils.exportComponent(component).right().map(toscaError -> {
327 log.debug("exportComponent failed", toscaError);
328 return componentsUtils.getResponseFormat(componentsUtils.convertFromToscaError(toscaError));
329 }).left().map(MainYamlWithDependencies::make);
332 private Either<MainYamlWithDependencies, ResponseFormat> getArtifactFromCassandra(ArtifactDefinition artifactDef) {
333 return getFromCassandra(artifactDef.getEsId()).right().map(as -> {
334 log.debug(ARTIFACT_NAME_UNIQUE_ID, artifactDef.getArtifactName(), artifactDef.getUniqueId());
335 return componentsUtils.getResponseFormat(as);
336 }).left().map(MainYamlWithDependencies::make);
339 private static class MainYamlWithDependencies {
341 private final byte[] mainYaml;
342 private final Optional<List<Triple<String, String, Component>>> dependencies;
344 private MainYamlWithDependencies(byte[] mainYaml,
345 Optional<List<Triple<String, String, Component>>> dependencies) {
346 this.mainYaml = mainYaml;
347 this.dependencies = dependencies;
350 static public MainYamlWithDependencies make(byte[] mainYaml) {
351 return new MainYamlWithDependencies(mainYaml, Optional.empty());
354 static public MainYamlWithDependencies make(ToscaRepresentation tr) {
355 return new MainYamlWithDependencies(tr.getMainYaml().getBytes(), Optional.ofNullable(tr.getDependencies()));
360 * Create a list of all derived nodes found on the package
362 * @param dependencies all node dependencies
363 * @return a list of nodes
365 private List<String> findNonRootNodesFromPackage(final List<Triple<String, String, Component>> dependencies) {
366 final List<String> nodes = new ArrayList<>();
367 if (CollectionUtils.isNotEmpty(dependencies)) {
368 final String NATIVE_ROOT = "tosca.nodes.Root";
369 dependencies.forEach(dependency -> {
370 if (dependency.getRight() instanceof Resource) {
371 final Resource resource = (Resource) dependency.getRight();
372 if (CollectionUtils.isNotEmpty(resource.getDerivedList())) {
373 resource.getDerivedList().stream()
374 .filter(node -> !nodes.contains(node) && !NATIVE_ROOT.equalsIgnoreCase(node))
375 .forEach(node -> nodes.add(node));
384 * Writes a new zip entry
386 * @param zipInputStream the zip entry to be read
387 * @return a map of the given zip entry
389 private Map<String, Object> readYamlZipEntry(final ZipInputStream zipInputStream) throws IOException {
390 final int initSize = 2048;
391 final StringBuilder zipEntry = new StringBuilder();
392 final byte[] buffer = new byte[initSize];
394 while ((read = zipInputStream.read(buffer, 0, initSize)) >= 0) {
395 zipEntry.append(new String(buffer, 0, read));
398 return (Map<String, Object>) new Yaml().load(zipEntry.toString());
402 * Filters and removes all duplicated nodes found
404 * @param nodesFromPackage a List of all derived nodes found on the given package
405 * @param nodesFromArtifactFile represents the nodes.yml file stored in Cassandra
406 * @return a nodes Map updated
408 private Map<String, Object> updateNodeYml(final List<String> nodesFromPackage,
409 final Map<String, Object> nodesFromArtifactFile) {
411 if (MapUtils.isNotEmpty(nodesFromArtifactFile)) {
412 final String nodeTypeBlock = ToscaTagNamesEnum.NODE_TYPES.getElementName();
413 final Map<String, Object> nodeTypes = (Map<String, Object>) nodesFromArtifactFile.get(nodeTypeBlock);
414 nodesFromPackage.stream()
415 .filter(nodeTypes::containsKey)
416 .forEach(nodeTypes::remove);
418 nodesFromArtifactFile.replace(nodeTypeBlock, nodeTypes);
421 return nodesFromArtifactFile;
425 * Updates the zip entry from the given parameters
427 * @param byteArrayOutputStream an output stream in which the data is written into a byte array.
428 * @param nodesYaml a Map of nodes to be written
430 private void updateZipEntry(final ByteArrayOutputStream byteArrayOutputStream,
431 final Map<String, Object> nodesYaml) throws IOException {
432 if (MapUtils.isNotEmpty(nodesYaml)) {
433 byteArrayOutputStream.write(new YamlUtil().objectToYaml(nodesYaml).getBytes());
437 private Either<ZipOutputStream, ResponseFormat> getZipOutputStreamResponseFormatEither(
439 List<Triple<String, String, Component>> dependencies,
440 Map<String, ImmutableTriple<String, String, Component>> innerComponentsCache
441 ) throws IOException {
442 if (dependencies != null && !dependencies.isEmpty()) {
443 for (Triple<String, String, Component> d : dependencies) {
444 String cassandraId = d.getMiddle();
445 Component childComponent = d.getRight();
447 Either<byte[], ResponseFormat> entryData = getEntryData(cassandraId, childComponent)
448 .right().map(x -> componentsUtils.getResponseFormat(x));
450 if (entryData.isRight()) {
451 return Either.right(entryData.right().value());
454 //fill innerComponentsCache
455 String fileName = d.getLeft();
456 // TODO: Extract the cache related functions to their own class
457 addComponentToCache(innerComponentsCache, cassandraId, fileName, childComponent);
458 addInnerComponentsToCache(innerComponentsCache, childComponent);
461 //add inner components to CSAR
462 Either<ZipOutputStream, ResponseFormat> responseFormat = addInnerComponentsToCSAR(zip, innerComponentsCache);
463 if (responseFormat != null) return responseFormat;
468 private Either<ZipOutputStream, ResponseFormat> addInnerComponentsToCSAR(ZipOutputStream zip, Map<String, ImmutableTriple<String, String, Component>> innerComponentsCache) throws IOException {
469 for (Entry<String, ImmutableTriple<String, String, Component>> innerComponentTripleEntry : innerComponentsCache.entrySet()) {
471 ImmutableTriple<String, String, Component> innerComponentTriple = innerComponentTripleEntry.getValue();
473 Component innerComponent = innerComponentTriple.getRight();
474 String icFileName = innerComponentTriple.getMiddle();
476 // add component to zip
477 Either<byte[], ActionStatus> entryData = getEntryData(innerComponentTriple.getLeft(), innerComponent);
478 if (entryData.isRight()) {
479 ResponseFormat responseFormat = componentsUtils.getResponseFormat(entryData.right().value());
480 log.debug("Failed adding to zip component {}, error {}", innerComponentTriple.getLeft(),
481 entryData.right().value());
482 return Either.right(responseFormat);
484 byte[] content = entryData.left().value();
485 zip.putNextEntry(new ZipEntry(DEFINITIONS_PATH + icFileName));
488 // add component interface to zip
489 if (!ModelConverter.isAtomicComponent(innerComponent)) {
490 writeComponentInterface(innerComponent, zip, icFileName, true);
496 private void addSchemaFilesFromCassandra(final ZipOutputStream zip,
497 final byte[] schemaFileZip,
498 final List<String> nodesFromPackage) {
499 final int initSize = 2048;
500 log.debug("Starting copy from Schema file zip to CSAR zip");
501 try (final ZipInputStream zipStream = new ZipInputStream(new ByteArrayInputStream(schemaFileZip));
502 final ByteArrayOutputStream out = new ByteArrayOutputStream();
503 final BufferedOutputStream bos = new BufferedOutputStream(out, initSize)) {
506 while ((entry = zipStream.getNextEntry()) != null) {
507 ZipUtils.checkForZipSlipInRead(entry);
508 final String entryName = entry.getName();
509 int readSize = initSize;
510 final byte[] entryData = new byte[initSize];
511 if (entryName.equalsIgnoreCase("nodes.yml")) {
512 handleNode(zipStream, out, nodesFromPackage);
514 while ((readSize = zipStream.read(entryData, 0, readSize)) != -1) {
515 bos.write(entryData, 0, readSize);
520 zip.putNextEntry(new ZipEntry(DEFINITIONS_PATH + entryName));
521 zip.write(out.toByteArray());
525 } catch (final Exception e) {
526 log.error("Error while writing the SDC schema file to the CSAR", e);
527 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
529 log.debug("Finished copy from Schema file zip to CSAR zip");
533 * Handles the nodes.yml zip entry, updating the nodes.yml to avoid duplicated nodes on it.
535 * @param zipInputStream the zip entry to be read
536 * @param byteArrayOutputStream an output stream in which the data is written into a byte array.
537 * @param nodesFromPackage list of all nodes found on the onboarded package
539 private void handleNode(final ZipInputStream zipInputStream,
540 final ByteArrayOutputStream byteArrayOutputStream,
541 final List<String> nodesFromPackage) throws IOException {
543 final Map<String, Object> nodesFromArtifactFile = readYamlZipEntry(zipInputStream);
544 final Map<String, Object> nodesYaml = updateNodeYml(nodesFromPackage, nodesFromArtifactFile);
545 updateZipEntry(byteArrayOutputStream, nodesYaml);
548 private void addInnerComponentsToCache(Map<String, ImmutableTriple<String, String, Component>> componentCache,
549 Component childComponent) {
551 List<ComponentInstance> instances = childComponent.getComponentInstances();
553 if(instances != null) {
554 instances.forEach(ci -> {
555 ImmutableTriple<String, String, Component> componentRecord = componentCache.get(ci.getComponentUid());
556 if (componentRecord == null) {
557 // all resource must be only once!
558 Either<Resource, StorageOperationStatus> resource = toscaOperationFacade.getToscaElement(ci.getComponentUid());
559 Component componentRI = checkAndAddComponent(componentCache, ci, resource);
561 //if not atomic - insert inner components as well
562 if(!ModelConverter.isAtomicComponent(componentRI)) {
563 addInnerComponentsToCache(componentCache, componentRI);
570 private Component checkAndAddComponent(Map<String, ImmutableTriple<String, String, Component>> componentCache, ComponentInstance ci, Either<Resource, StorageOperationStatus> resource) {
571 if (resource.isRight()) {
572 log.debug("Failed to fetch resource with id {} for instance {}", ci.getComponentUid(), ci.getName());
574 Component componentRI = resource.left().value();
576 Map<String, ArtifactDefinition> childToscaArtifacts = componentRI.getToscaArtifacts();
577 ArtifactDefinition childArtifactDefinition = childToscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE);
578 if (childArtifactDefinition != null) {
580 addComponentToCache(componentCache, childArtifactDefinition.getEsId(), childArtifactDefinition.getArtifactName(), componentRI);
585 private void addComponentToCache(Map<String, ImmutableTriple<String, String, Component>> componentCache,
586 String id, String fileName, Component component) {
588 String uuid = component.getInvariantUUID();
589 String version = component.getVersion();
591 Supplier<ImmutableTriple<String, String, Component>> sup =
592 () -> new ImmutableTriple<>(id, fileName, component);
594 componentCache.put(uuid, updateWith(componentCache, uuid,
595 cc -> overwriteIfSameVersions(id, version, cc, sup),
600 private static <K, V> V updateWith(Map<K, V> kvs, K k, Function<V, V> f, Supplier<V> orElse) {
601 return Optional.ofNullable(kvs.get(k)).map(f).orElseGet(orElse);
604 private ImmutableTriple<String, String, Component> overwriteIfSameVersions(
605 String id, String version,
606 ImmutableTriple<String, String, Component> cc,
607 Supplier<ImmutableTriple<String, String, Component>> newValue
609 if (CommonBeUtils.compareAsdcComponentVersions(version, cc.getRight().getVersion())) {
610 log.warn("Overwriting component invariantID {} of version {} with a newer version {}", id,
611 cc.getRight().getVersion(),
613 return newValue.get();
618 private Either<ZipOutputStream, ResponseFormat> writeComponentInterface(
622 boolean isAssociatedComponent
625 Either<String, ToscaError> mainYaml = toscaExportUtils
626 .exportComponentInterface(component, isAssociatedComponent)
627 .left().map(ToscaRepresentation::getMainYaml);
629 // TODO: This should be done outside this function to keep this testable.
630 // We can probably achieve this once the other refactorings related to SDC-2812 are merged
631 String interfaceFileName = DEFINITIONS_PATH + ToscaExportHandler.getInterfaceFilename(fileName);
632 zip.putNextEntry(new ZipEntry(interfaceFileName));
633 zip.write(mainYaml.left().value().getBytes());
635 } catch (Exception e) {
636 log.error("#writeComponentInterface - zip writing failed with error: ", e);
637 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
639 return Either.left(zip);
642 private Either<byte[], ActionStatus> getEntryData(String cassandraId, Component childComponent) {
643 if (cassandraId == null || cassandraId.isEmpty()) {
644 return toscaExportUtils.exportComponent(childComponent)
645 .right().map(toscaErrorToActionStatus(childComponent))
646 .left().map(toscaRepresentation -> toscaRepresentation.getMainYaml().getBytes());
648 return getFromCassandra(cassandraId);
652 private F<ToscaError, ActionStatus> toscaErrorToActionStatus(Component childComponent) {
653 return toscaError -> {
654 log.debug("Failed to export tosca template for child component {} error {}",
655 childComponent.getUniqueId(), toscaError);
656 return componentsUtils.convertFromToscaError(toscaError);
660 private Either<byte[], ResponseFormat> getLatestSchemaFilesFromCassandra() {
661 String fto = getVersionFirstThreeOctets();
662 return sdcSchemaFilesCassandraDao.getSpecificSchemaFiles(fto, CONFORMANCE_LEVEL)
663 .right().map(schemaFilesFetchDBError(fto))
666 () -> schemaFileFetchError(fto),
667 s -> Either.left(s.iterator().next().getPayloadAsArray())
672 private static <A, B> F<A, B> iff(Predicate<A> p, Supplier<B> s, Function<A, B> orElse) {
673 return a -> p.test(a) ? s.get() : orElse.apply(a);
676 private F<CassandraOperationStatus, ResponseFormat> schemaFilesFetchDBError(String firstThreeOctets) {
679 "Failed to get the schema files SDC-Version: {} Conformance-Level {}. Please fix DB table accordingly.",
680 firstThreeOctets, CONFORMANCE_LEVEL);
681 StorageOperationStatus sos = DaoStatusConverter.convertCassandraStatusToStorageStatus(cos);
682 return componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(sos));
686 private Either<byte[], ResponseFormat> schemaFileFetchError(String firstThreeOctets) {
687 log.debug("Failed to get the schema files SDC-Version: {} Conformance-Level {}",
688 firstThreeOctets, CONFORMANCE_LEVEL);
690 componentsUtils.getResponseFormat(
691 ActionStatus.TOSCA_SCHEMA_FILES_NOT_FOUND, firstThreeOctets, CONFORMANCE_LEVEL
696 private Either<byte[], ActionStatus> getFromCassandra(String cassandraId) {
697 return artifactCassandraDao.getArtifact(cassandraId)
698 .right().map(cos -> {
699 log.debug("Failed to fetch artifact from Cassandra by id {} error {} ", cassandraId, cos);
700 StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(cos);
701 return componentsUtils.convertFromStorageResponse(storageStatus);
702 }).left().map(DAOArtifactData::getDataAsArray);
705 private String createCsarBlock0(String metaFileVersion, String toscaConformanceLevel) {
706 return String.format(BLOCK_0_TEMPLATE, metaFileVersion, toscaConformanceLevel);
709 private String createToscaBlock0(String metaFileVersion, String csarVersion, String createdBy, String entryDef) {
710 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";
711 return String.format(block0template, metaFileVersion, csarVersion, createdBy, entryDef);
715 * Extracts artifacts of VFCs from CSAR
718 * @return Map of <String, List<ArtifactDefinition>> the contains Lists of artifacts according vfcToscaNamespace
720 public static Map<String, List<ArtifactDefinition>> extractVfcsArtifactsFromCsar(Map<String, byte[]> csar) {
722 Map<String, List<ArtifactDefinition>> artifacts = new HashMap<>();
724 log.debug("************* Going to extract VFCs artifacts from Csar. ");
725 Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>();
726 csar.entrySet().stream()
727 // filter CSAR entry by node type artifact path
728 .filter(e -> Pattern.compile(VFC_NODE_TYPE_ARTIFACTS_PATH_PATTERN).matcher(e.getKey()).matches())
729 // extract ArtifactDefinition from CSAR entry for each entry with matching artifact path
730 .forEach(e -> addExtractedVfcArtifact(extractVfcArtifact(e, collectedWarningMessages), artifacts));
731 // add counter suffix to artifact labels
732 handleWarningMessages(collectedWarningMessages);
739 * Print warnings to log
741 * @param collectedWarningMessages
743 public static void handleWarningMessages(Map<String, Set<List<String>>> collectedWarningMessages) {
744 collectedWarningMessages.entrySet().stream()
746 .forEach(e -> e.getValue().stream()
747 // add each warning message to log
748 .forEach(args -> log.warn(e.getKey(), args.toArray())));
752 private static void addExtractedVfcArtifact(ImmutablePair<String, ArtifactDefinition> extractedVfcArtifact, Map<String, List<ArtifactDefinition>> artifacts) {
753 if (extractedVfcArtifact != null) {
754 List<ArtifactDefinition> currArtifactsList;
755 String vfcToscaNamespace = extractedVfcArtifact.getKey();
756 if (artifacts.containsKey(vfcToscaNamespace)) {
757 currArtifactsList = artifacts.get(vfcToscaNamespace);
759 currArtifactsList = new ArrayList<>();
760 artifacts.put(vfcToscaNamespace, currArtifactsList);
762 currArtifactsList.add(extractedVfcArtifact.getValue());
766 private static ImmutablePair<String, ArtifactDefinition> extractVfcArtifact(Entry<String, byte[]> entry, Map<String, Set<List<String>>> collectedWarningMessages) {
767 ArtifactDefinition artifact;
768 String[] parsedCsarArtifactPath = entry.getKey().split(PATH_DELIMITER);
769 Either<ArtifactGroupTypeEnum, Boolean> eitherArtifactGroupType = detectArtifactGroupType(parsedCsarArtifactPath[2].toUpperCase(), collectedWarningMessages);
770 if (eitherArtifactGroupType.isLeft()) {
771 artifact = buildArtifactDefinitionFromCsarArtifactPath(entry, collectedWarningMessages, parsedCsarArtifactPath, eitherArtifactGroupType.left().value());
775 return new ImmutablePair<>(parsedCsarArtifactPath[1], artifact);
778 private static Either<ArtifactGroupTypeEnum, Boolean> detectArtifactGroupType(String groupType, Map<String, Set<List<String>>> collectedWarningMessages) {
779 Either<ArtifactGroupTypeEnum, Boolean> result;
781 ArtifactGroupTypeEnum artifactGroupType = ArtifactGroupTypeEnum.findType(groupType.toUpperCase());
782 if (artifactGroupType == null || (artifactGroupType != ArtifactGroupTypeEnum.INFORMATIONAL && artifactGroupType != ArtifactGroupTypeEnum.DEPLOYMENT)) {
783 String warningMessage = "Warning - unrecognized artifact group type {} was received.";
784 List<String> messageArguments = new ArrayList<>();
785 messageArguments.add(groupType);
786 if (!collectedWarningMessages.containsKey(warningMessage)) {
787 Set<List<String>> messageArgumentLists = new HashSet<>();
788 messageArgumentLists.add(messageArguments);
789 collectedWarningMessages.put(warningMessage, messageArgumentLists);
791 collectedWarningMessages.get(warningMessage).add(messageArguments);
794 result = Either.right(false);
797 result = Either.left(artifactGroupType);
799 } catch (Exception e) {
800 log.debug("detectArtifactGroupType failed with exception", e);
801 result = Either.right(false);
806 private static ArtifactDefinition buildArtifactDefinitionFromCsarArtifactPath(Entry<String, byte[]> entry, Map<String, Set<List<String>>> collectedWarningMessages, String[] parsedCsarArtifactPath, ArtifactGroupTypeEnum artifactGroupType) {
807 ArtifactDefinition artifact;
808 artifact = new ArtifactDefinition();
809 artifact.setArtifactGroupType(artifactGroupType);
810 artifact.setArtifactType(detectArtifactTypeVFC(artifactGroupType, parsedCsarArtifactPath[3], parsedCsarArtifactPath[1], collectedWarningMessages));
811 artifact.setArtifactName(ValidationUtils.normalizeFileName(parsedCsarArtifactPath[parsedCsarArtifactPath.length - 1]));
812 artifact.setPayloadData(Base64.encodeBase64String(entry.getValue()));
813 artifact.setArtifactDisplayName(artifact.getArtifactName().lastIndexOf('.') > 0 ? artifact.getArtifactName().substring(0, artifact.getArtifactName().lastIndexOf('.')) : artifact.getArtifactName());
814 artifact.setArtifactLabel(ValidationUtils.normalizeArtifactLabel(artifact.getArtifactName()));
815 artifact.setDescription(ARTIFACT_CREATED_FROM_CSAR);
816 artifact.setIsFromCsar(true);
817 artifact.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(entry.getValue()));
822 public static final class NonMetaArtifactInfo {
824 private String artifactUniqueId;
825 private final String path;
826 private final String artifactName;
827 private final String displayName;
828 private final String artifactLabel;
829 private final String artifactType;
830 private final ArtifactGroupTypeEnum artifactGroupType;
831 private final String payloadData;
832 private final String artifactChecksum;
833 private final boolean isFromCsar;
835 public NonMetaArtifactInfo(final String artifactName, final String path, final String artifactType,
836 final ArtifactGroupTypeEnum artifactGroupType, final byte[] payloadData,
837 final String artifactUniqueId, final boolean isFromCsar) {
840 this.isFromCsar = isFromCsar;
841 this.artifactName = ValidationUtils.normalizeFileName(artifactName);
842 this.artifactType = artifactType;
843 this.artifactGroupType = artifactGroupType;
844 final int pointIndex = artifactName.lastIndexOf('.');
845 if (pointIndex > 0) {
846 displayName = artifactName.substring(0, pointIndex);
848 displayName = artifactName;
850 this.artifactLabel = ValidationUtils.normalizeArtifactLabel(artifactName);
851 if (payloadData == null) {
852 this.payloadData = null;
853 this.artifactChecksum = null;
855 this.payloadData = Base64.encodeBase64String(payloadData);
856 this.artifactChecksum = GeneralUtility.calculateMD5Base64EncodedByByteArray(payloadData);
858 this.artifactUniqueId = artifactUniqueId;
864 * This method checks the artifact GroupType & Artifact Type. <br>
865 * if there is any problem warning messages are added to collectedWarningMessages
867 * @param artifactPath
868 * @param collectedWarningMessages
871 public static Either<NonMetaArtifactInfo, Boolean> validateNonMetaArtifact(
874 Map<String, Set<List<String>>> collectedWarningMessages
877 String[] parsedArtifactPath = artifactPath.split(PATH_DELIMITER);
878 String groupType = parsedArtifactPath[1];
879 String receivedTypeName = parsedArtifactPath[2];
880 String artifactFileNameType = parsedArtifactPath[3];
882 return detectArtifactGroupType(groupType, collectedWarningMessages)
883 .left().bind(artifactGroupType -> {
884 String artifactType =
885 detectArtifactTypeVF(artifactGroupType, receivedTypeName, collectedWarningMessages);
887 return Either.left(new NonMetaArtifactInfo(
888 artifactFileNameType, artifactPath, artifactType,
889 artifactGroupType, payloadData, null, true
892 } catch (Exception e) {
893 log.debug("detectArtifactGroupType failed with exception", e);
894 return Either.right(false);
898 private static String detectArtifactTypeVFC(ArtifactGroupTypeEnum artifactGroupType, String receivedTypeName, String parentVfName, Map<String, Set<List<String>>> collectedWarningMessages) {
899 String warningMessage = "Warning - artifact type {} that was provided for VFC {} is not recognized.";
900 return detectArtifactType(artifactGroupType, receivedTypeName, warningMessage, collectedWarningMessages, parentVfName);
903 private static String detectArtifactTypeVF(ArtifactGroupTypeEnum artifactGroupType, String receivedTypeName, Map<String, Set<List<String>>> collectedWarningMessages) {
904 String warningMessage = "Warning - artifact type {} that was provided for VF is not recognized.";
905 return detectArtifactType(artifactGroupType, receivedTypeName, warningMessage, collectedWarningMessages);
908 private static String detectArtifactType(final ArtifactGroupTypeEnum artifactGroupType,
909 final String receivedTypeName, final String warningMessage,
910 final Map<String, Set<List<String>>> collectedWarningMessages,
911 final String... arguments) {
912 final ArtifactConfiguration artifactConfiguration =
913 ArtifactConfigManager.getInstance()
914 .find(receivedTypeName, artifactGroupType, ComponentType.RESOURCE)
917 if (artifactConfiguration == null) {
918 final List<String> messageArguments = new ArrayList<>();
919 messageArguments.add(receivedTypeName);
920 messageArguments.addAll(Arrays.asList(arguments));
921 if (!collectedWarningMessages.containsKey(warningMessage)) {
922 final Set<List<String>> messageArgumentLists = new HashSet<>();
923 messageArgumentLists.add(messageArguments);
924 collectedWarningMessages.put(warningMessage, messageArgumentLists);
926 collectedWarningMessages.get(warningMessage).add(messageArguments);
930 return artifactConfiguration == null ? ArtifactTypeEnum.OTHER.getType() : receivedTypeName;
933 private Either<ZipOutputStream, ResponseFormat> writeAllFilesToCsar(Component mainComponent, CsarDefinition csarDefinition, ZipOutputStream zipstream, boolean isInCertificationRequest) throws IOException{
934 ComponentArtifacts componentArtifacts = csarDefinition.getComponentArtifacts();
936 Either<ZipOutputStream, ResponseFormat> writeComponentArtifactsToSpecifiedPath = writeComponentArtifactsToSpecifiedPath(mainComponent, componentArtifacts, zipstream, ARTIFACTS_PATH, isInCertificationRequest);
938 if(writeComponentArtifactsToSpecifiedPath.isRight()){
939 return Either.right(writeComponentArtifactsToSpecifiedPath.right().value());
942 ComponentTypeArtifacts mainTypeAndCIArtifacts = componentArtifacts.getMainTypeAndCIArtifacts();
943 writeComponentArtifactsToSpecifiedPath = writeArtifactsInfoToSpecifiedPath(mainComponent, mainTypeAndCIArtifacts.getComponentArtifacts(), zipstream, ARTIFACTS_PATH, isInCertificationRequest);
945 if(writeComponentArtifactsToSpecifiedPath.isRight()){
946 return Either.right(writeComponentArtifactsToSpecifiedPath.right().value());
949 Map<String, ArtifactsInfo> componentInstancesArtifacts = mainTypeAndCIArtifacts.getComponentInstancesArtifacts();
950 Set<String> keySet = componentInstancesArtifacts.keySet();
952 String currentPath = ARTIFACTS_PATH + RESOURCES_PATH;
953 for (String keyAssetName : keySet) {
954 ArtifactsInfo artifactsInfo = componentInstancesArtifacts.get(keyAssetName);
955 String pathWithAssetName = currentPath + keyAssetName + PATH_DELIMITER;
956 writeComponentArtifactsToSpecifiedPath = writeArtifactsInfoToSpecifiedPath(mainComponent, artifactsInfo, zipstream, pathWithAssetName, isInCertificationRequest);
958 if(writeComponentArtifactsToSpecifiedPath.isRight()){
959 return Either.right(writeComponentArtifactsToSpecifiedPath.right().value());
962 writeComponentArtifactsToSpecifiedPath = writeOperationsArtifactsToCsar(mainComponent, zipstream);
964 if (writeComponentArtifactsToSpecifiedPath.isRight()) {
965 return Either.right(writeComponentArtifactsToSpecifiedPath.right().value());
967 return Either.left(zipstream);
970 private Either<ZipOutputStream, ResponseFormat> writeOperationsArtifactsToCsar(Component component,
971 ZipOutputStream zipstream) {
972 if (checkComponentBeforeOperation(component)) return Either.left(zipstream);
973 final Map<String, InterfaceDefinition> interfaces = ((Resource) component).getInterfaces();
974 for (Map.Entry<String, InterfaceDefinition> interfaceEntry : interfaces.entrySet()) {
975 for (OperationDataDefinition operation : interfaceEntry.getValue().getOperations().values()) {
977 if (checkComponentBeforeWrite(component, interfaceEntry, operation)) continue;
978 final String artifactUUID = operation.getImplementation().getArtifactUUID();
979 final Either<byte[], ActionStatus> artifactFromCassandra = getFromCassandra(artifactUUID);
980 final String artifactName = operation.getImplementation().getArtifactName();
981 if (artifactFromCassandra.isRight()) {
982 log.error(ARTIFACT_NAME_UNIQUE_ID, artifactName, artifactUUID);
983 log.error("Failed to get {} payload from DB reason: {}", artifactName,
984 artifactFromCassandra.right().value());
985 return Either.right(componentsUtils.getResponseFormat(
986 ActionStatus.ARTIFACT_PAYLOAD_NOT_FOUND_DURING_CSAR_CREATION, "Resource",
987 component.getUniqueId(), artifactName, artifactUUID));
989 final byte[] payloadData = artifactFromCassandra.left().value();
990 zipstream.putNextEntry(new ZipEntry(OperationArtifactUtil.createOperationArtifactPath(
991 component, null, operation,true)));
992 zipstream.write(payloadData);
993 } catch (IOException e) {
994 log.error("Component Name {}, Interface Name {}, Operation Name {}", component.getNormalizedName(),
995 interfaceEntry.getKey(), operation.getName());
996 log.error("Error while writing the operation's artifacts to the CSAR " + "{}", e);
997 return Either.right(componentsUtils
998 .getResponseFormat(ActionStatus.ERROR_DURING_CSAR_CREATION, "Resource",
999 component.getUniqueId()));
1003 return Either.left(zipstream);
1006 private boolean checkComponentBeforeWrite(Component component, Entry<String, InterfaceDefinition> interfaceEntry, OperationDataDefinition operation) {
1007 if (Objects.isNull(operation.getImplementation())) {
1008 log.debug("Component Name {}, Interface Id {}, Operation Name {} - no Operation Implementation found",
1009 component.getNormalizedName(), interfaceEntry.getValue().getUniqueId(),
1010 operation.getName());
1013 if (Objects.isNull(operation.getImplementation().getArtifactName())) {
1014 log.debug("Component Name {}, Interface Id {}, Operation Name {} - no artifact found",
1015 component.getNormalizedName(), interfaceEntry.getValue().getUniqueId(),
1016 operation.getName());
1019 if (operation.getImplementation().getArtifactName().startsWith(Constants.ESCAPED_DOUBLE_QUOTE) && operation.getImplementation().getArtifactName().endsWith(Constants.ESCAPED_DOUBLE_QUOTE)) {
1020 log.debug("Component Name {}, Interface Id {}, Operation Name {} - artifact name is a literal value rather than an SDC artifact",
1021 component.getNormalizedName(), interfaceEntry.getValue().getUniqueId(),
1022 operation.getName());
1028 private boolean checkComponentBeforeOperation(Component component) {
1029 if (component instanceof Service) {
1032 if (Objects.isNull(((Resource) component).getInterfaces())) {
1033 log.debug("Component Name {}- no interfaces found", component.getNormalizedName());
1039 private Either<ZipOutputStream, ResponseFormat> writeComponentArtifactsToSpecifiedPath(Component mainComponent, ComponentArtifacts componentArtifacts, ZipOutputStream zipstream,
1040 String currentPath, boolean isInCertificationRequest) throws IOException {
1041 Map<String, ComponentTypeArtifacts> componentTypeArtifacts = componentArtifacts.getComponentTypeArtifacts();
1043 //<Inner Asset TOSCA name (e.g. VFC name)> folder name: <Inner Asset TOSCA name (e.g. VFC name)>_v<version>.
1044 //E.g. "org.openecomp.resource.vf.vipr_atm_v1.0"
1045 Set<String> componentTypeArtifactsKeys = componentTypeArtifacts.keySet();
1046 for (String keyAssetName : componentTypeArtifactsKeys) {
1047 ComponentTypeArtifacts componentInstanceArtifacts = componentTypeArtifacts.get(keyAssetName);
1048 ArtifactsInfo componentArtifacts2 = componentInstanceArtifacts.getComponentArtifacts();
1049 String pathWithAssetName = currentPath + keyAssetName + PATH_DELIMITER;
1050 Either<ZipOutputStream, ResponseFormat> writeArtifactsInfoToSpecifiedPath = writeArtifactsInfoToSpecifiedPath(mainComponent, componentArtifacts2, zipstream, pathWithAssetName, isInCertificationRequest);
1052 if(writeArtifactsInfoToSpecifiedPath.isRight()){
1053 return writeArtifactsInfoToSpecifiedPath;
1057 return Either.left(zipstream);
1060 private Either<ZipOutputStream, ResponseFormat> writeArtifactsInfoToSpecifiedPath(final Component mainComponent,
1061 final ArtifactsInfo currArtifactsInfo,
1062 final ZipOutputStream zip,
1064 final boolean isInCertificationRequest) throws IOException {
1065 final Map<ArtifactGroupTypeEnum, Map<String, List<ArtifactDefinition>>> artifactsInfo =
1066 currArtifactsInfo.getArtifactsInfo();
1067 for (final ArtifactGroupTypeEnum artifactGroupTypeEnum : artifactsInfo.keySet()) {
1068 final String groupTypeFolder = path + WordUtils.capitalizeFully(artifactGroupTypeEnum.getType()) + PATH_DELIMITER;
1070 final Map<String, List<ArtifactDefinition>> artifactTypesMap = artifactsInfo.get(artifactGroupTypeEnum);
1072 for (final String artifactType : artifactTypesMap.keySet()) {
1073 final List<ArtifactDefinition> artifactDefinitionList = artifactTypesMap.get(artifactType);
1074 String artifactTypeFolder = groupTypeFolder + artifactType + PATH_DELIMITER;
1076 if(ArtifactTypeEnum.WORKFLOW.getType().equals(artifactType) && path.contains(ARTIFACTS_PATH + RESOURCES_PATH)){
1077 // Ignore this packaging as BPMN artifacts needs to be packaged in different manner
1080 if (ArtifactTypeEnum.WORKFLOW.getType().equals(artifactType)) {
1081 artifactTypeFolder += OperationArtifactUtil.BPMN_ARTIFACT_PATH + File.separator;
1084 Either<ZipOutputStream, ResponseFormat> writeArtifactDefinition =
1085 writeArtifactDefinition(mainComponent, zip, artifactDefinitionList, artifactTypeFolder, isInCertificationRequest);
1087 if (writeArtifactDefinition.isRight()) {
1088 return writeArtifactDefinition;
1093 return Either.left(zip);
1096 private Either<ZipOutputStream, ResponseFormat> writeArtifactDefinition(Component mainComponent, ZipOutputStream zip, List<ArtifactDefinition> artifactDefinitionList,
1097 String artifactPathAndFolder, boolean isInCertificationRequest) throws IOException {
1099 ComponentTypeEnum componentType = mainComponent.getComponentType();
1100 String heatEnvType = ArtifactTypeEnum.HEAT_ENV.getType();
1102 for (ArtifactDefinition artifactDefinition : artifactDefinitionList) {
1103 if (!isInCertificationRequest && componentType == ComponentTypeEnum.SERVICE
1104 && artifactDefinition.getArtifactType().equals(heatEnvType) ||
1105 //this is placeholder
1106 (artifactDefinition.getEsId() == null && artifactDefinition.getMandatory())){
1110 byte[] payloadData = artifactDefinition.getPayloadData();
1111 String artifactFileName = artifactDefinition.getArtifactName();
1113 if (payloadData == null) {
1114 Either<byte[], ActionStatus> fromCassandra = getFromCassandra(artifactDefinition.getEsId());
1116 if (fromCassandra.isRight()) {
1117 log.debug(ARTIFACT_NAME_UNIQUE_ID, artifactDefinition.getArtifactName(), artifactDefinition.getUniqueId());
1118 log.debug("Failed to get {} payload from DB reason: {}", artifactFileName, fromCassandra.right().value());
1121 payloadData = fromCassandra.left().value();
1123 zip.putNextEntry(new ZipEntry(artifactPathAndFolder + artifactFileName));
1124 zip.write(payloadData);
1127 return Either.left(zip);
1130 /************************************ Artifacts Structure ******************************************************************/
1132 * The artifacts Definition saved by their structure
1134 private class ArtifactsInfo {
1135 //Key is the type of artifacts(Informational/Deployment)
1136 //Value is a map between an artifact type and a list of all artifacts of this type
1137 private Map<ArtifactGroupTypeEnum, Map<String, List<ArtifactDefinition>>> artifactsInfoField;
1139 public ArtifactsInfo() {
1140 this.artifactsInfoField = new EnumMap<>(ArtifactGroupTypeEnum.class);
1143 public Map<ArtifactGroupTypeEnum, Map<String, List<ArtifactDefinition>>> getArtifactsInfo() {
1144 return artifactsInfoField;
1147 public void addArtifactsToGroup(ArtifactGroupTypeEnum artifactGroup,
1148 Map<String, List<ArtifactDefinition>> artifactsDefinition) {
1149 if (artifactsInfoField.get(artifactGroup) == null) {
1150 artifactsInfoField.put(artifactGroup, artifactsDefinition);
1152 Map<String, List<ArtifactDefinition>> artifactTypeEnumListMap =
1153 artifactsInfoField.get(artifactGroup);
1154 artifactTypeEnumListMap.putAll(artifactsDefinition);
1155 artifactsInfoField.put(artifactGroup, artifactTypeEnumListMap);
1160 public boolean isEmpty() {
1161 return artifactsInfoField.isEmpty();
1164 public boolean isNotEmpty() {
1171 * The artifacts of the component and of all its composed instances
1174 private class ComponentTypeArtifacts {
1175 private ArtifactsInfo componentArtifacts; //component artifacts (describes the Informational Deployment folders)
1176 private Map<String, ArtifactsInfo> componentInstancesArtifacts; //artifacts of the composed instances mapped by the resourceInstance normalized name (describes the Resources folder)
1178 public ComponentTypeArtifacts() {
1179 componentArtifacts = new ArtifactsInfo();
1180 componentInstancesArtifacts = new HashMap<>();
1183 public ArtifactsInfo getComponentArtifacts() {
1184 return componentArtifacts;
1186 public void setComponentArtifacts(ArtifactsInfo artifactsInfo) {
1187 this.componentArtifacts = artifactsInfo;
1189 public Map<String, ArtifactsInfo> getComponentInstancesArtifacts() {
1190 return componentInstancesArtifacts;
1192 public void setComponentInstancesArtifacts(Map<String, ArtifactsInfo> componentInstancesArtifacts) {
1193 this.componentInstancesArtifacts = componentInstancesArtifacts;
1196 public void addComponentInstancesArtifacts(String normalizedName, ArtifactsInfo artifactsInfo) {
1197 componentInstancesArtifacts.put(normalizedName, artifactsInfo);
1202 private class ComponentArtifacts {
1203 //artifacts of the component and CI's artifacts contained in it's composition (represents Informational, Deployment & Resource folders of main component)
1204 private ComponentTypeArtifacts mainTypeAndCIArtifacts;
1205 //artifacts of all component types mapped by their tosca name
1206 private Map<String, ComponentTypeArtifacts> componentTypeArtifacts;
1208 public ComponentArtifacts(){
1209 mainTypeAndCIArtifacts = new ComponentTypeArtifacts();
1210 componentTypeArtifacts = new HashMap<>();
1213 public ComponentTypeArtifacts getMainTypeAndCIArtifacts() {
1214 return mainTypeAndCIArtifacts;
1217 public void setMainTypeAndCIArtifacts(ComponentTypeArtifacts componentInstanceArtifacts) {
1218 this.mainTypeAndCIArtifacts = componentInstanceArtifacts;
1221 public Map<String, ComponentTypeArtifacts> getComponentTypeArtifacts() {
1222 return componentTypeArtifacts;
1225 public void setComponentTypeArtifacts(Map<String, ComponentTypeArtifacts> componentTypeArtifacts) {
1226 this.componentTypeArtifacts = componentTypeArtifacts;
1230 private class CsarDefinition {
1231 private ComponentArtifacts componentArtifacts;
1233 // add list of tosca artifacts and meta describes CSAR zip root
1235 public CsarDefinition(ComponentArtifacts componentArtifacts) {
1236 this.componentArtifacts = componentArtifacts;
1239 public ComponentArtifacts getComponentArtifacts() {
1240 return componentArtifacts;
1244 /************************************ Artifacts Structure END******************************************************************/
1246 private Either<CsarDefinition,ResponseFormat> collectComponentCsarDefinition(Component component){
1247 ComponentArtifacts componentArtifacts = new ComponentArtifacts();
1248 Component updatedComponent = component;
1250 //get service to receive the AII artifacts uploaded to the service
1251 if (updatedComponent.getComponentType() == ComponentTypeEnum.SERVICE) {
1252 Either<Service, StorageOperationStatus> getServiceResponse = toscaOperationFacade.getToscaElement(updatedComponent.getUniqueId());
1254 if(getServiceResponse.isRight()){
1255 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getServiceResponse.right().value());
1256 return Either.right(componentsUtils.getResponseFormat(actionStatus));
1259 updatedComponent = getServiceResponse.left().value();
1262 //find the artifacts of the main component, it would have its composed instances artifacts in a separate folder
1263 ComponentTypeArtifacts componentInstanceArtifacts = new ComponentTypeArtifacts();
1264 ArtifactsInfo artifactsInfo = collectComponentArtifacts(updatedComponent);
1265 componentInstanceArtifacts.setComponentArtifacts(artifactsInfo);
1266 componentArtifacts.setMainTypeAndCIArtifacts(componentInstanceArtifacts);
1268 Map<String,ComponentTypeArtifacts> resourceTypeArtifacts = componentArtifacts.getComponentTypeArtifacts(); //artifacts mapped by the component type(tosca name+version)
1269 //get the component instances
1270 List<ComponentInstance> componentInstances = updatedComponent.getComponentInstances();
1271 if (componentInstances!=null){
1272 for (ComponentInstance componentInstance:componentInstances){
1273 //call recursive to find artifacts for all the path
1274 Either<Boolean, ResponseFormat> collectComponentInstanceArtifacts = collectComponentInstanceArtifacts(
1275 updatedComponent, componentInstance, resourceTypeArtifacts, componentInstanceArtifacts);
1276 if (collectComponentInstanceArtifacts.isRight()){
1277 return Either.right(collectComponentInstanceArtifacts.right().value());
1282 if(log.isDebugEnabled()){
1283 printResult(componentArtifacts,updatedComponent.getName());
1286 return Either.left(new CsarDefinition(componentArtifacts));
1289 private void printResult(ComponentArtifacts componentArtifacts, String name) {
1290 StringBuilder result = new StringBuilder();
1291 result.append("Artifacts of main component " + name + "\n");
1292 ComponentTypeArtifacts componentInstanceArtifacts = componentArtifacts.getMainTypeAndCIArtifacts();
1293 printArtifacts(componentInstanceArtifacts);
1294 result.append("Type Artifacts\n");
1295 for (Map.Entry<String, ComponentTypeArtifacts> typeArtifacts:componentArtifacts.getComponentTypeArtifacts().entrySet()){
1296 result.append("Folder " + typeArtifacts.getKey() + "\n");
1297 result.append(printArtifacts(typeArtifacts.getValue()));
1300 if(log.isDebugEnabled()){
1301 log.debug(result.toString());
1305 private String printArtifacts(ComponentTypeArtifacts componentInstanceArtifacts) {
1306 StringBuilder result = new StringBuilder();
1307 ArtifactsInfo artifactsInfo = componentInstanceArtifacts.getComponentArtifacts();
1308 Map<ArtifactGroupTypeEnum, Map<String, List<ArtifactDefinition>>> componentArtifacts = artifactsInfo.getArtifactsInfo();
1309 printArtifacts(componentArtifacts);
1310 result = result.append("Resources\n");
1311 for (Map.Entry<String, ArtifactsInfo> resourceInstance:componentInstanceArtifacts.getComponentInstancesArtifacts().entrySet()){
1312 result.append("Folder" + resourceInstance.getKey() + "\n");
1313 result.append(printArtifacts(resourceInstance.getValue().getArtifactsInfo()));
1316 return result.toString();
1319 private String printArtifacts(Map<ArtifactGroupTypeEnum, Map<String, List<ArtifactDefinition>>> componetArtifacts) {
1320 StringBuilder result = new StringBuilder();
1321 for (Map.Entry<ArtifactGroupTypeEnum, Map<String, List<ArtifactDefinition>>> artifactGroup:componetArtifacts.entrySet()){
1322 result.append(" " + artifactGroup.getKey().getType());
1323 for (Map.Entry<String, List<ArtifactDefinition>> groupArtifacts:artifactGroup.getValue().entrySet()){
1324 result.append(" " + groupArtifacts.getKey());
1325 for (ArtifactDefinition artifact:groupArtifacts.getValue()){
1326 result.append(" " + artifact.getArtifactDisplayName());
1331 return result.toString();
1334 private ComponentTypeArtifacts collectComponentTypeArtifacts(
1335 Component fetchedComponent
1337 ArtifactsInfo componentArtifacts = collectComponentArtifacts(fetchedComponent);
1338 ComponentTypeArtifacts componentArtifactsInfo = new ComponentTypeArtifacts();
1339 if (componentArtifacts.isNotEmpty()) {
1340 componentArtifactsInfo.setComponentArtifacts(componentArtifacts);
1342 return componentArtifactsInfo;
1345 private Either<Boolean, ResponseFormat> collectComponentInstanceArtifacts(Component parentComponent,ComponentInstance componentInstance,
1346 Map<String, ComponentTypeArtifacts> resourcesTypeArtifacts,ComponentTypeArtifacts instanceArtifactsLocation) {
1347 //1. get the component instance component
1348 String componentUid;
1349 if (componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy) {
1350 componentUid = componentInstance.getSourceModelUid();
1353 componentUid = componentInstance.getComponentUid();
1355 Either<Component, StorageOperationStatus> component = toscaOperationFacade.getToscaElement(componentUid);
1356 if (component.isRight()) {
1357 log.error("Failed to fetch resource with id {} for instance {}",componentUid, parentComponent.getUUID());
1358 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ASSET_NOT_FOUND_DURING_CSAR_CREATION,
1359 parentComponent.getComponentType().getValue(), parentComponent.getUUID(),
1360 componentInstance.getOriginType().getComponentType().getValue(), componentUid));
1362 Component fetchedComponent = component.left().value();
1364 //2. fill the artifacts for the current component parent type
1365 String toscaComponentName =
1366 componentInstance.getToscaComponentName() + "_v" + componentInstance.getComponentVersion();
1368 // if there are no artifacts for this component type we need to fetch and build them
1369 ComponentTypeArtifacts componentParentArtifacts = Optional
1370 .ofNullable(resourcesTypeArtifacts.get(toscaComponentName))
1371 .orElseGet(() -> collectComponentTypeArtifacts(fetchedComponent));
1373 if (componentParentArtifacts.getComponentArtifacts().isNotEmpty()) {
1374 resourcesTypeArtifacts.put(toscaComponentName, componentParentArtifacts);
1377 //3. find the artifacts specific to the instance
1378 Map<String, List<ArtifactDefinition>> componentInstanceSpecificInformationalArtifacts =
1379 getComponentInstanceSpecificArtifacts(componentInstance.getArtifacts(),
1380 componentParentArtifacts.getComponentArtifacts().getArtifactsInfo(), ArtifactGroupTypeEnum.INFORMATIONAL);
1381 Map<String, List<ArtifactDefinition>> componentInstanceSpecificDeploymentArtifacts =
1382 getComponentInstanceSpecificArtifacts(componentInstance.getDeploymentArtifacts(),
1383 componentParentArtifacts.getComponentArtifacts().getArtifactsInfo(), ArtifactGroupTypeEnum.DEPLOYMENT);
1385 //4. add the instances artifacts to the component type
1386 ArtifactsInfo artifactsInfo = new ArtifactsInfo();
1387 if (!componentInstanceSpecificInformationalArtifacts.isEmpty()){
1388 artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.INFORMATIONAL, componentInstanceSpecificInformationalArtifacts);
1390 if (!componentInstanceSpecificDeploymentArtifacts.isEmpty()){
1391 artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.DEPLOYMENT, componentInstanceSpecificDeploymentArtifacts);
1393 if (!artifactsInfo.isEmpty()){
1394 instanceArtifactsLocation.addComponentInstancesArtifacts(componentInstance.getNormalizedName(), artifactsInfo);
1397 //5. do the same for all the component instances
1398 List<ComponentInstance> componentInstances = fetchedComponent.getComponentInstances();
1399 if (componentInstances!=null){
1400 for (ComponentInstance childComponentInstance:componentInstances){
1401 Either<Boolean, ResponseFormat> collectComponentInstanceArtifacts = collectComponentInstanceArtifacts(
1402 fetchedComponent, childComponentInstance, resourcesTypeArtifacts, componentParentArtifacts);
1403 if (collectComponentInstanceArtifacts.isRight()){
1404 return collectComponentInstanceArtifacts;
1409 return Either.left(true);
1412 public String getVersionFirstThreeOctets() {
1413 return versionFirstThreeOctets;
1416 public void setVersionFirstThreeOctets(String versionFirstThreeOctetes) {
1417 this.versionFirstThreeOctets = versionFirstThreeOctetes;
1419 private Map<String, List<ArtifactDefinition>> getComponentInstanceSpecificArtifacts(Map<String, ArtifactDefinition> componentArtifacts,
1420 Map<ArtifactGroupTypeEnum, Map<String, List<ArtifactDefinition>>> componentTypeArtifacts, ArtifactGroupTypeEnum artifactGroupTypeEnum) {
1421 Map<String, List<ArtifactDefinition>> parentArtifacts = componentTypeArtifacts.get(artifactGroupTypeEnum); //the artfiacts of the component itself and not the instance
1423 Map<String, List<ArtifactDefinition>> artifactsByTypeOfComponentInstance = new HashMap<>();
1424 if (componentArtifacts!=null){
1425 for (ArtifactDefinition artifact:componentArtifacts.values()){
1426 List<ArtifactDefinition> parentArtifactsByType = null;
1427 if (parentArtifacts!=null){
1428 parentArtifactsByType = parentArtifacts.get(artifact.getArtifactType());
1430 //the artifact is of instance
1431 if (parentArtifactsByType == null || !parentArtifactsByType.contains(artifact)){
1432 List<ArtifactDefinition> typeArtifacts = artifactsByTypeOfComponentInstance.get(artifact.getArtifactType());
1433 if (typeArtifacts == null){
1434 typeArtifacts = new ArrayList<>();
1435 artifactsByTypeOfComponentInstance.put(artifact.getArtifactType(), typeArtifacts);
1437 typeArtifacts.add(artifact);
1442 return artifactsByTypeOfComponentInstance;
1445 private ArtifactsInfo collectComponentArtifacts(Component component) {
1446 Map<String, ArtifactDefinition> informationalArtifacts = component.getArtifacts();
1447 Map<String, List<ArtifactDefinition>> informationalArtifactsByType = collectGroupArtifacts(informationalArtifacts);
1448 Map<String, ArtifactDefinition> deploymentArtifacts = component.getDeploymentArtifacts();
1449 Map<String, List<ArtifactDefinition>> deploymentArtifactsByType = collectGroupArtifacts(deploymentArtifacts);
1450 Map<String, ArtifactDefinition> interfaceOperationArtifacts =
1451 OperationArtifactUtil.getDistinctInterfaceOperationArtifactsByName(component);
1452 Map<String, List<ArtifactDefinition>> interfaceOperationArtifactsByType = collectGroupArtifacts(
1453 interfaceOperationArtifacts);
1454 ArtifactsInfo artifactsInfo = new ArtifactsInfo();
1455 if (!informationalArtifactsByType.isEmpty()){
1456 artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.INFORMATIONAL, informationalArtifactsByType);
1458 if (!deploymentArtifactsByType.isEmpty() ){
1459 artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.DEPLOYMENT, deploymentArtifactsByType);
1461 //Add component interface operation artifacts
1462 if(MapUtils.isNotEmpty(interfaceOperationArtifacts)) {
1463 artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.DEPLOYMENT, interfaceOperationArtifactsByType);
1466 return artifactsInfo;
1469 private Map<String, List<ArtifactDefinition>> collectGroupArtifacts(
1470 final Map<String, ArtifactDefinition> componentArtifacts) {
1471 final Map<String, List<ArtifactDefinition>> artifactsByType = new HashMap<>();
1472 for (final ArtifactDefinition artifact : componentArtifacts.values()) {
1473 if (artifact.getArtifactUUID() != null) {
1474 artifactsByType.putIfAbsent(artifact.getArtifactType(), new ArrayList<>());
1475 final List<ArtifactDefinition> typeArtifacts = artifactsByType.get(artifact.getArtifactType());
1476 typeArtifacts.add(artifact);
1479 return artifactsByType;