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 static org.openecomp.sdc.be.tosca.ComponentCache.MergeStrategy.overwriteIfSameVersions;
27 import fj.data.Either;
28 import io.vavr.Tuple2;
29 import io.vavr.control.Try;
30 import io.vavr.control.Option;
31 import java.io.BufferedOutputStream;
32 import java.io.ByteArrayInputStream;
34 import java.io.IOException;
35 import java.util.ArrayList;
36 import java.util.Arrays;
37 import java.util.EnumMap;
38 import java.util.HashMap;
39 import java.util.HashSet;
40 import java.util.List;
42 import java.util.Map.Entry;
43 import java.util.Objects;
44 import java.util.Optional;
46 import java.util.function.Function;
47 import java.util.function.Predicate;
48 import java.util.function.Supplier;
49 import java.util.regex.Matcher;
50 import java.util.regex.Pattern;
51 import java.util.stream.Collectors;
52 import java.util.stream.Stream;
53 import java.util.zip.ZipEntry;
54 import java.util.zip.ZipInputStream;
55 import java.util.zip.ZipOutputStream;
58 import org.apache.commons.codec.binary.Base64;
59 import org.apache.commons.collections.CollectionUtils;
60 import org.apache.commons.collections.MapUtils;
61 import org.apache.commons.io.output.ByteArrayOutputStream;
62 import org.apache.commons.lang.WordUtils;
63 import org.apache.commons.lang3.tuple.ImmutablePair;
64 import org.apache.commons.lang3.tuple.ImmutableTriple;
65 import org.apache.commons.lang3.tuple.Triple;
66 import org.onap.sdc.tosca.services.YamlUtil;
67 import org.openecomp.sdc.be.components.impl.ImportUtils;
68 import org.openecomp.sdc.be.components.impl.ImportUtils.Constants;
69 import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException;
70 import org.openecomp.sdc.be.config.ArtifactConfigManager;
71 import org.openecomp.sdc.be.config.ArtifactConfiguration;
72 import org.openecomp.sdc.be.config.ComponentType;
73 import org.openecomp.sdc.be.config.ConfigurationManager;
74 import org.openecomp.sdc.be.dao.api.ActionStatus;
75 import org.openecomp.sdc.be.dao.cassandra.ArtifactCassandraDao;
76 import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus;
77 import org.openecomp.sdc.be.dao.cassandra.SdcSchemaFilesCassandraDao;
78 import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
79 import org.openecomp.sdc.be.datatypes.elements.OperationDataDefinition;
80 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
81 import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
82 import org.openecomp.sdc.be.impl.ComponentsUtils;
83 import org.openecomp.sdc.be.model.ArtifactDefinition;
84 import org.openecomp.sdc.be.model.Component;
85 import org.openecomp.sdc.be.model.ComponentInstance;
86 import org.openecomp.sdc.be.model.InterfaceDefinition;
87 import org.openecomp.sdc.be.model.LifecycleStateEnum;
88 import org.openecomp.sdc.be.model.Resource;
89 import org.openecomp.sdc.be.model.Service;
90 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade;
91 import org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter;
92 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
93 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
94 import org.openecomp.sdc.be.plugins.CsarEntryGenerator;
95 import org.openecomp.sdc.be.resources.data.DAOArtifactData;
96 import org.openecomp.sdc.be.tosca.model.ToscaTemplate;
97 import org.openecomp.sdc.be.tosca.utils.OperationArtifactUtil;
98 import org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum;
99 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
100 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
101 import org.openecomp.sdc.common.impl.ExternalConfiguration;
102 import org.openecomp.sdc.common.log.elements.LoggerSupportability;
103 import org.openecomp.sdc.common.log.enums.LoggerSupportabilityActions;
104 import org.openecomp.sdc.common.log.enums.StatusCode;
105 import org.openecomp.sdc.common.log.wrappers.Logger;
106 import org.openecomp.sdc.common.util.GeneralUtility;
107 import org.openecomp.sdc.common.util.ValidationUtils;
108 import org.openecomp.sdc.common.zip.ZipUtils;
109 import org.openecomp.sdc.exception.ResponseFormat;
110 import org.springframework.beans.factory.annotation.Autowired;
111 import org.yaml.snakeyaml.Yaml;
113 import static org.openecomp.sdc.be.tosca.FJToVavrHelper.Try0.fromEither;
119 @org.springframework.stereotype.Component("csar-utils")
120 public class CsarUtils {
121 private static final Logger log = Logger.getLogger(CsarUtils.class);
122 private static final LoggerSupportability loggerSupportability = LoggerSupportability.getLogger(CsarUtils.class.getName());
123 private static final String PATH_DELIMITER = "/";
124 public static final String NODES_YML = "nodes.yml";
126 private SdcSchemaFilesCassandraDao sdcSchemaFilesCassandraDao;
128 private ArtifactCassandraDao artifactCassandraDao;
130 private ComponentsUtils componentsUtils;
132 private ToscaExportHandler toscaExportUtils;
134 protected ToscaOperationFacade toscaOperationFacade;
136 @Autowired(required = false)
137 private List<CsarEntryGenerator> generators;
139 private static final List<String> globalCsarImports = ConfigurationManager.getConfigurationManager()
140 .getConfiguration().getGlobalCsarImports();
141 private static final String CONFORMANCE_LEVEL = ConfigurationManager.getConfigurationManager().getConfiguration().getToscaConformanceLevel();
142 private static final String SDC_VERSION = ExternalConfiguration.getAppVersion();
143 public static final String ARTIFACTS_PATH = "Artifacts/";
144 private static final String RESOURCES_PATH = "Resources/";
145 private static final String DEFINITIONS_PATH = "Definitions/";
146 public static final String WORKFLOW_ARTIFACT_DIR = "Workflows"+File.separator+"BPMN"+File.separator;
147 public static final String DEPLOYMENT_ARTIFACTS_DIR = "Deployment"+File.separator;
148 private static final String CSAR_META_VERSION = "1.0";
149 private static final String CSAR_META_PATH_FILE_NAME = "csar.meta";
150 private static final String TOSCA_META_PATH_FILE_NAME = "TOSCA-Metadata/TOSCA.meta";
151 private static final String TOSCA_META_VERSION = "1.0";
152 private static final String CSAR_VERSION = "1.1";
153 public static final String ARTIFACTS = "Artifacts";
154 private static final String DEFINITION = "Definitions";
155 private static final String DEL_PATTERN = "([/\\\\]+)";
156 private static final String WORD_PATTERN = "\\w\\_\\-\\.\\s]+)";
157 public static final String VALID_ENGLISH_ARTIFACT_NAME = "([" + WORD_PATTERN;
158 private static final String VALID_ENGLISH_ARTIFACT_NAME_WITH_DIGITS = "([\\d" + WORD_PATTERN;
159 private static final String ARTIFACT_NAME_UNIQUE_ID = "ArtifactName {}, unique ID {}";
161 private static final String VFC_NODE_TYPE_ARTIFACTS_PATH_PATTERN = ARTIFACTS + DEL_PATTERN +
162 ImportUtils.Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX +
163 VALID_ENGLISH_ARTIFACT_NAME_WITH_DIGITS + DEL_PATTERN +
164 VALID_ENGLISH_ARTIFACT_NAME_WITH_DIGITS + DEL_PATTERN +
165 VALID_ENGLISH_ARTIFACT_NAME_WITH_DIGITS + DEL_PATTERN +
166 VALID_ENGLISH_ARTIFACT_NAME_WITH_DIGITS;
168 public static final String VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN = ARTIFACTS + DEL_PATTERN+
169 // Artifact Group (i.e Deployment/Informational)
170 VALID_ENGLISH_ARTIFACT_NAME + DEL_PATTERN +
172 VALID_ENGLISH_ARTIFACT_NAME + DEL_PATTERN +
173 // Artifact Any File Name
176 public static final String SERVICE_TEMPLATE_PATH_PATTERN = DEFINITION + DEL_PATTERN+
177 // Service Template File Name
178 VALID_ENGLISH_ARTIFACT_NAME;
180 public static final String ARTIFACT_CREATED_FROM_CSAR = "Artifact created from csar";
181 private static final String BLOCK_0_TEMPLATE = "SDC-TOSCA-Meta-File-Version: %s\nSDC-TOSCA-Definitions-Version: %s\n";
183 private String versionFirstThreeOctets;
186 if(SDC_VERSION != null && !SDC_VERSION.isEmpty()){
187 Matcher matcher = Pattern.compile("(?!\\.)(\\d+(\\.\\d+)+)(?![\\d\\.])").matcher(SDC_VERSION);
189 setVersionFirstThreeOctets(matcher.group(0));
191 setVersionFirstThreeOctets("");
199 * @param isInCertificationRequest
202 public Either<byte[], ResponseFormat> createCsar(Component component, boolean getFromCS, boolean isInCertificationRequest) {
203 loggerSupportability.log(LoggerSupportabilityActions.GENERATE_CSAR, StatusCode.STARTED,"Starting to create Csar for component {} ",component.getName());
204 final String createdBy = component.getCreatorFullName();
206 Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts();
207 ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE);
208 fileName = artifactDefinition.getArtifactName();
210 String toscaConformanceLevel = ConfigurationManager.getConfigurationManager().getConfiguration().getToscaConformanceLevel();
211 String csarBlock0 = createCsarBlock0(CSAR_META_VERSION, toscaConformanceLevel);
212 byte[] csarBlock0Byte = csarBlock0.getBytes();
214 final String toscaBlock0 = createToscaBlock0(TOSCA_META_VERSION, CSAR_VERSION, createdBy, fileName);
215 byte[] toscaBlock0Byte = toscaBlock0.getBytes();
217 return generateCsarZip(csarBlock0Byte, toscaBlock0Byte, component, getFromCS, isInCertificationRequest)
218 .left().map(responseFormat -> {
219 loggerSupportability.log(LoggerSupportabilityActions.GENERATE_CSAR, StatusCode.COMPLETE,
220 "Ended create Csar for component {} ", component.getName());
221 return responseFormat;
225 private Either<byte[], ResponseFormat> generateCsarZip(byte[] csarBlock0Byte, byte[] toscaBlock0Byte, Component component, boolean getFromCS, boolean isInCertificationRequest) {
226 try (ByteArrayOutputStream out = new ByteArrayOutputStream();
227 ZipOutputStream zip = new ZipOutputStream(out)) {
228 zip.putNextEntry(new ZipEntry(CSAR_META_PATH_FILE_NAME));
229 zip.write(csarBlock0Byte);
230 zip.putNextEntry(new ZipEntry(TOSCA_META_PATH_FILE_NAME));
231 zip.write(toscaBlock0Byte);
232 Either<ZipOutputStream, ResponseFormat> populateZip = populateZip(component, getFromCS, zip, isInCertificationRequest);
233 if (populateZip.isRight()) {
234 log.debug("Failed to populate CSAR zip file {}. Please fix DB table accordingly ", populateZip.right().value());
235 return Either.right(populateZip.right().value());
239 byte[] byteArray = out.toByteArray();
241 return Either.left(byteArray);
242 } catch (IOException e) {
243 log.debug("Failed with IOexception to create CSAR zip for component {}. Please fix DB table accordingly ", component.getUniqueId(), e);
245 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
246 return Either.right(responseFormat);
250 private Either<ZipOutputStream, ResponseFormat> populateZip(Component component, boolean getFromCS, ZipOutputStream zip, boolean isInCertificationRequest) throws IOException {
252 ArtifactDefinition artifactDef = component
254 .get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE);
256 Either<ToscaRepresentation, ResponseFormat> toscaRepresentation =
257 fetchToscaRepresentation(component, getFromCS, artifactDef);
259 // This should not be done but in order to keep the refactoring small enough we stop here.
260 // TODO: Refactor the rest of this function
262 List<Triple<String, String, Component>> dependencies;
263 if(toscaRepresentation.isLeft()) {
264 mainYaml = toscaRepresentation.left().value().getMainYaml();
265 dependencies = toscaRepresentation.left().value().getDependencies().getOrElse(new ArrayList<>());
267 return Either.right(toscaRepresentation.right().value());
270 String fileName = artifactDef.getArtifactName();
271 zip.putNextEntry(new ZipEntry(DEFINITIONS_PATH + fileName));
274 //US798487 - Abstraction of complex types
275 if (!ModelConverter.isAtomicComponent(component)){
276 log.debug("Component {} is complex - generating abstract type for it..", component.getName());
277 writeComponentInterface(component, zip, fileName, false);
280 //UID <cassandraId,filename,component>
281 Either<ZipOutputStream, ResponseFormat> responseFormat = getZipOutputStreamResponseFormatEither(zip, dependencies);
282 if (responseFormat != null) return responseFormat;
284 //retrieve SDC.zip from Cassandra
285 Either<byte[], ResponseFormat> latestSchemaFilesFromCassandra = getLatestSchemaFilesFromCassandra();
287 if(latestSchemaFilesFromCassandra.isRight()){
288 log.error("Error retrieving SDC Schema files from cassandra");
289 return Either.right(latestSchemaFilesFromCassandra.right().value());
292 final byte[] schemaFileZip = latestSchemaFilesFromCassandra.left().value();
294 final List<String> nodesFromPackage = findNonRootNodesFromPackage(dependencies);
296 //add files from retrieved SDC.zip to Definitions folder in CSAR
297 addSchemaFilesFromCassandra(zip, schemaFileZip, nodesFromPackage);
299 Either<CsarDefinition, ResponseFormat> collectedComponentCsarDefinition = collectComponentCsarDefinition(component);
301 if (collectedComponentCsarDefinition.isRight()) {
302 return Either.right(collectedComponentCsarDefinition.right().value());
305 if (generators != null) {
306 for (CsarEntryGenerator generator: generators) {
307 log.debug("Invoking CsarEntryGenerator: {}", generator.getClass().getName());
308 for (Entry<String, byte[]> pluginGeneratedFile : generator.generateCsarEntries(component).entrySet()) {
309 zip.putNextEntry(new ZipEntry(pluginGeneratedFile.getKey()));
310 zip.write(pluginGeneratedFile.getValue());
315 return writeAllFilesToCsar(component, collectedComponentCsarDefinition.left().value(), zip, isInCertificationRequest);
318 private Either<ToscaRepresentation, ResponseFormat> fetchToscaRepresentation(
321 ArtifactDefinition artifactDef
323 LifecycleStateEnum lifecycleState = component.getLifecycleState();
325 boolean shouldBeFetchedFromCassandra = getFromCS ||
326 !(lifecycleState == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN ||
327 lifecycleState == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
329 Either<ToscaRepresentation, ResponseFormat> toscaRepresentation =
330 shouldBeFetchedFromCassandra ?
331 fetchToscaRepresentation(artifactDef) :
332 generateToscaRepresentation(component);
334 return toscaRepresentation.left().bind(iff(
335 myd -> !myd.getDependencies().isDefined(),
336 myd -> fetchToscaTemplateDependencies(myd.getMainYaml(), component)
340 private static <L, R> F<L, Either<L, R>> iff(Predicate<L> p, Function<L, Either<L, R>> ifTrue) {
341 return l -> p.test(l) ? ifTrue.apply(l) : Either.left(l);
344 private Either<ToscaRepresentation, ResponseFormat> fetchToscaTemplateDependencies(
348 return toscaExportUtils.getDependencies(component).right().map(toscaError -> {
349 log.debug("Failed to retrieve dependencies for component {}, error {}",
350 component.getUniqueId(), toscaError);
351 return componentsUtils.getResponseFormat(componentsUtils.convertFromToscaError(toscaError));
352 }).left().map(tt -> ToscaRepresentation.make(mainYml, tt));
355 private Either<ToscaRepresentation, ResponseFormat> generateToscaRepresentation(Component component) {
356 return toscaExportUtils.exportComponent(component).right().map(toscaError -> {
357 log.debug("exportComponent failed {}", toscaError);
358 return componentsUtils.getResponseFormat(componentsUtils.convertFromToscaError(toscaError));
362 private Either<ToscaRepresentation, ResponseFormat> fetchToscaRepresentation(ArtifactDefinition artifactDef) {
363 return getFromCassandra(artifactDef.getEsId()).right().map(as -> {
364 log.debug(ARTIFACT_NAME_UNIQUE_ID, artifactDef.getArtifactName(), artifactDef.getUniqueId());
365 return componentsUtils.getResponseFormat(as);
366 }).left().map(ToscaRepresentation::make);
370 * Create a list of all derived nodes found on the package
372 * @param dependencies all node dependencies
373 * @return a list of nodes
375 private List<String> findNonRootNodesFromPackage(final List<Triple<String, String, Component>> dependencies) {
376 final List<String> nodes = new ArrayList<>();
377 if (CollectionUtils.isNotEmpty(dependencies)) {
378 final String NATIVE_ROOT = "tosca.nodes.Root";
379 dependencies.forEach(dependency -> {
380 if (dependency.getRight() instanceof Resource) {
381 final Resource resource = (Resource) dependency.getRight();
382 if (CollectionUtils.isNotEmpty(resource.getDerivedList())) {
383 resource.getDerivedList().stream()
384 .filter(node -> !nodes.contains(node) && !NATIVE_ROOT.equalsIgnoreCase(node))
385 .forEach(node -> nodes.add(node));
394 * Writes a new zip entry
396 * @param zipInputStream the zip entry to be read
397 * @return a map of the given zip entry
399 private Map<String, Object> readYamlZipEntry(final ZipInputStream zipInputStream) throws IOException {
400 final int initSize = 2048;
401 final StringBuilder zipEntry = new StringBuilder();
402 final byte[] buffer = new byte[initSize];
404 while ((read = zipInputStream.read(buffer, 0, initSize)) >= 0) {
405 zipEntry.append(new String(buffer, 0, read));
408 return (Map<String, Object>) new Yaml().load(zipEntry.toString());
412 * Filters and removes all duplicated nodes found
414 * @param nodesFromPackage a List of all derived nodes found on the given package
415 * @param nodesFromArtifactFile represents the nodes.yml file stored in Cassandra
416 * @return a nodes Map updated
418 private Map<String, Object> updateNodeYml(final List<String> nodesFromPackage,
419 final Map<String, Object> nodesFromArtifactFile) {
421 if (MapUtils.isNotEmpty(nodesFromArtifactFile)) {
422 final String nodeTypeBlock = ToscaTagNamesEnum.NODE_TYPES.getElementName();
423 final Map<String, Object> nodeTypes = (Map<String, Object>) nodesFromArtifactFile.get(nodeTypeBlock);
424 nodesFromPackage.stream()
425 .filter(nodeTypes::containsKey)
426 .forEach(nodeTypes::remove);
428 nodesFromArtifactFile.replace(nodeTypeBlock, nodeTypes);
431 return nodesFromArtifactFile;
435 * Updates the zip entry from the given parameters
437 * @param byteArrayOutputStream an output stream in which the data is written into a byte array.
438 * @param nodesYaml a Map of nodes to be written
440 private void updateZipEntry(final ByteArrayOutputStream byteArrayOutputStream,
441 final Map<String, Object> nodesYaml) throws IOException {
442 if (MapUtils.isNotEmpty(nodesYaml)) {
443 byteArrayOutputStream.write(new YamlUtil().objectToYaml(nodesYaml).getBytes());
447 private Either<ZipOutputStream, ResponseFormat> getZipOutputStreamResponseFormatEither(
449 List<Triple<String, String, Component>> dependencies
450 ) throws IOException {
452 ComponentCache innerComponentsCache = ComponentCache
453 .overwritable(overwriteIfSameVersions())
454 .onMerge((oldValue, newValue) -> {
455 log.warn("Overwriting component invariantID {} of version {} with a newer version {}",
456 oldValue.id, oldValue.getComponentVersion(), newValue.getComponentVersion()
460 if (dependencies != null && !dependencies.isEmpty()) {
461 for (Triple<String, String, Component> d : dependencies) {
462 String cassandraId = d.getMiddle();
463 Component childComponent = d.getRight();
465 Either<byte[], ResponseFormat> entryData = getEntryData(cassandraId, childComponent)
466 .right().map(x -> componentsUtils.getResponseFormat(x));
468 if (entryData.isRight()) {
469 return Either.right(entryData.right().value());
472 //fill innerComponentsCache
473 String fileName = d.getLeft();
474 innerComponentsCache.put(cassandraId, fileName, childComponent);
475 addInnerComponentsToCache(innerComponentsCache, childComponent);
478 //add inner components to CSAR
479 return addInnerComponentsToCSAR(zip, innerComponentsCache);
484 private Either<ZipOutputStream, ResponseFormat> addInnerComponentsToCSAR(
486 ComponentCache innerComponentsCache
487 ) throws IOException {
488 for (ImmutableTriple<String, String, Component> ict : innerComponentsCache.iterable()) {
489 Component innerComponent = ict.getRight();
491 String icFileName = ict.getMiddle();
492 // add component to zip
493 Either<Tuple2<byte[], ZipEntry>, ResponseFormat> zipEntry = toZipEntry(ict);
494 // TODO: this should not be done, we should instead compose this either further,
495 // but in order to keep this refactoring small, we'll stop here.
496 if (zipEntry.isRight()) {
497 return Either.right(zipEntry.right().value());
499 Tuple2<byte[], ZipEntry> value = zipEntry.left().value();
500 zip.putNextEntry(value._2);
502 // add component interface to zip
503 if (!ModelConverter.isAtomicComponent(innerComponent)) {
504 writeComponentInterface(innerComponent, zip, icFileName, true);
510 private Either<Tuple2<byte[], ZipEntry>, ResponseFormat> toZipEntry(
511 ImmutableTriple<String, String, Component> cachedEntry
513 String cassandraId = cachedEntry.getLeft();
514 String fileName = cachedEntry.getMiddle();
515 Component innerComponent = cachedEntry.getRight();
516 return getEntryData(cassandraId, innerComponent)
517 .right().map(status -> {
518 log.debug("Failed adding to zip component {}, error {}", cassandraId, status);
519 return componentsUtils.getResponseFormat(status);
520 }).left().map(content -> new Tuple2<>(content, new ZipEntry(DEFINITIONS_PATH + fileName)));
524 * Writes to a CSAR zip from casandra schema data
526 * @param zipOutputStream stores the input stream content
527 * @param schemaFileZip zip data from Cassandra
528 * @param nodesFromPackage list of all nodes found on the onboarded package
530 private void addSchemaFilesFromCassandra(final ZipOutputStream zipOutputStream,
531 final byte[] schemaFileZip,
532 final List<String> nodesFromPackage) {
533 final int initSize = 2048;
534 log.debug("Starting copy from Schema file zip to CSAR zip");
535 try (final ZipInputStream zipInputStream = new ZipInputStream(new ByteArrayInputStream(schemaFileZip));
536 final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
537 final BufferedOutputStream bufferedOutputStream =
538 new BufferedOutputStream(byteArrayOutputStream, initSize)) {
541 while ((entry = zipInputStream.getNextEntry()) != null) {
542 ZipUtils.checkForZipSlipInRead(entry);
543 final String entryName = entry.getName();
544 int readSize = initSize;
545 final byte[] entryData = new byte[initSize];
546 if (shouldZipEntryBeHandled(entryName)) {
547 if (NODES_YML.equalsIgnoreCase(entryName)) {
548 handleNode(zipInputStream, byteArrayOutputStream, nodesFromPackage);
550 while ((readSize = zipInputStream.read(entryData, 0, readSize)) != -1) {
551 bufferedOutputStream.write(entryData, 0, readSize);
553 bufferedOutputStream.flush();
555 byteArrayOutputStream.flush();
556 zipOutputStream.putNextEntry(new ZipEntry(DEFINITIONS_PATH + entryName));
557 zipOutputStream.write(byteArrayOutputStream.toByteArray());
558 zipOutputStream.flush();
559 byteArrayOutputStream.reset();
562 } catch (final Exception e) {
563 log.error("Error while writing the SDC schema file to the CSAR", e);
564 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
566 log.debug("Finished copy from Schema file zip to CSAR zip");
570 * Checks if the zip entry should or should not be added to the CSAR based on the given global type list
572 * @param entryName the zip entry name
573 * @return true if the zip entry should be handled
575 private boolean shouldZipEntryBeHandled(final String entryName) {
576 return globalCsarImports.stream()
577 .anyMatch(entry -> entry.contains(entryName));
581 * Handles the nodes.yml zip entry, updating the nodes.yml to avoid duplicated nodes on it.
583 * @param zipInputStream the zip entry to be read
584 * @param byteArrayOutputStream an output stream in which the data is written into a byte array.
585 * @param nodesFromPackage list of all nodes found on the onboarded package
587 private void handleNode(final ZipInputStream zipInputStream,
588 final ByteArrayOutputStream byteArrayOutputStream,
589 final List<String> nodesFromPackage) throws IOException {
591 final Map<String, Object> nodesFromArtifactFile = readYamlZipEntry(zipInputStream);
592 final Map<String, Object> nodesYaml = updateNodeYml(nodesFromPackage, nodesFromArtifactFile);
593 updateZipEntry(byteArrayOutputStream, nodesYaml);
596 private void addInnerComponentsToCache(ComponentCache componentCache, Component childComponent) {
597 javaListToVavrList(childComponent.getComponentInstances())
598 .filter(ci -> componentCache.notCached(ci.getComponentUid()))
600 // all resource must be only once!
601 Either<Resource, StorageOperationStatus> resource =
602 toscaOperationFacade.getToscaElement(ci.getComponentUid());
603 Component componentRI = checkAndAddComponent(componentCache, ci, resource);
604 //if not atomic - insert inner components as well
605 // TODO: This could potentially create a StackOverflowException if the call stack
606 // happens to be too large. Tail-recursive optimization should be used here.
607 if (!ModelConverter.isAtomicComponent(componentRI)) {
608 addInnerComponentsToCache(componentCache, componentRI);
613 // TODO: Move this function in FJToVavrHelper.java once Change 108540 is merged
614 private io.vavr.collection.List<ComponentInstance> javaListToVavrList(
615 List<ComponentInstance> componentInstances
618 .of(componentInstances)
619 .map(io.vavr.collection.List::ofAll)
620 .getOrElse(io.vavr.collection.List::empty);
623 private Component checkAndAddComponent(ComponentCache componentCache, ComponentInstance ci, Either<Resource, StorageOperationStatus> resource) {
624 if (resource.isRight()) {
625 log.debug("Failed to fetch resource with id {} for instance {}", ci.getComponentUid(), ci.getName());
627 Component componentRI = resource.left().value();
629 Map<String, ArtifactDefinition> childToscaArtifacts = componentRI.getToscaArtifacts();
630 ArtifactDefinition childArtifactDefinition = childToscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE);
631 if (childArtifactDefinition != null) {
634 childArtifactDefinition.getEsId(),
635 childArtifactDefinition.getArtifactName(),
642 private Either<ZipOutputStream, ResponseFormat> writeComponentInterface(
646 boolean isAssociatedComponent
648 // TODO: This should not be done but we need this to keep the refactoring small enough to be easily reviewable
649 return writeComponentInterface(component, fileName, isAssociatedComponent, ZipWriter.live(zip))
650 .map(void0 -> Either.<ZipOutputStream, ResponseFormat>left(zip))
652 log.error("#writeComponentInterface - zip writing failed with error: ", th);
653 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
657 private Try<Void> writeComponentInterface(
660 boolean isAssociatedComponent,
663 Either<byte[], ToscaError> yml = toscaExportUtils
664 .exportComponentInterface(component, isAssociatedComponent)
665 .left().map(ToscaRepresentation::getMainYaml);
667 return fromEither(yml, ToscaErrorException::new)
668 .flatMap(zw.write(DEFINITIONS_PATH + ToscaExportHandler.getInterfaceFilename(fileName)));
671 public static class ToscaErrorException extends Exception {
673 ToscaErrorException(ToscaError error) {
674 super("Error while exporting component's interface (toscaError:" + error + ")");
678 private Either<byte[], ActionStatus> getEntryData(String cassandraId, Component childComponent) {
679 if (cassandraId == null || cassandraId.isEmpty()) {
680 return toscaExportUtils.exportComponent(childComponent)
681 .right().map(toscaErrorToActionStatus(childComponent))
682 .left().map(ToscaRepresentation::getMainYaml);
684 return getFromCassandra(cassandraId);
688 private F<ToscaError, ActionStatus> toscaErrorToActionStatus(Component childComponent) {
689 return toscaError -> {
690 log.debug("Failed to export tosca template for child component {} error {}",
691 childComponent.getUniqueId(), toscaError);
692 return componentsUtils.convertFromToscaError(toscaError);
696 private Either<byte[], ResponseFormat> getLatestSchemaFilesFromCassandra() {
697 String fto = getVersionFirstThreeOctets();
698 return sdcSchemaFilesCassandraDao.getSpecificSchemaFiles(fto, CONFORMANCE_LEVEL)
699 .right().map(schemaFilesFetchDBError(fto))
702 () -> schemaFileFetchError(fto),
703 s -> Either.left(s.iterator().next().getPayloadAsArray())
708 private static <A, B> F<A, B> iff(Predicate<A> p, Supplier<B> s, Function<A, B> orElse) {
709 return a -> p.test(a) ? s.get() : orElse.apply(a);
712 private F<CassandraOperationStatus, ResponseFormat> schemaFilesFetchDBError(String firstThreeOctets) {
715 "Failed to get the schema files SDC-Version: {} Conformance-Level {}. Please fix DB table accordingly.",
716 firstThreeOctets, CONFORMANCE_LEVEL);
717 StorageOperationStatus sos = DaoStatusConverter.convertCassandraStatusToStorageStatus(cos);
718 return componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(sos));
722 private Either<byte[], ResponseFormat> schemaFileFetchError(String firstThreeOctets) {
723 log.debug("Failed to get the schema files SDC-Version: {} Conformance-Level {}",
724 firstThreeOctets, CONFORMANCE_LEVEL);
726 componentsUtils.getResponseFormat(
727 ActionStatus.TOSCA_SCHEMA_FILES_NOT_FOUND, firstThreeOctets, CONFORMANCE_LEVEL
732 private Either<byte[], ActionStatus> getFromCassandra(String cassandraId) {
733 return artifactCassandraDao.getArtifact(cassandraId)
734 .right().map(cos -> {
735 log.debug("Failed to fetch artifact from Cassandra by id {} error {} ", cassandraId, cos);
736 StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(cos);
737 return componentsUtils.convertFromStorageResponse(storageStatus);
738 }).left().map(DAOArtifactData::getDataAsArray);
741 private String createCsarBlock0(String metaFileVersion, String toscaConformanceLevel) {
742 return String.format(BLOCK_0_TEMPLATE, metaFileVersion, toscaConformanceLevel);
745 private String createToscaBlock0(String metaFileVersion, String csarVersion, String createdBy, String entryDef) {
746 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";
747 return String.format(block0template, metaFileVersion, csarVersion, createdBy, entryDef);
751 * Extracts artifacts of VFCs from CSAR
754 * @return Map of <String, List<ArtifactDefinition>> the contains Lists of artifacts according vfcToscaNamespace
756 public static Map<String, List<ArtifactDefinition>> extractVfcsArtifactsFromCsar(Map<String, byte[]> csar) {
758 Map<String, List<ArtifactDefinition>> artifacts = new HashMap<>();
760 log.debug("************* Going to extract VFCs artifacts from Csar. ");
761 Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>();
762 csar.entrySet().stream()
763 // filter CSAR entry by node type artifact path
764 .filter(e -> Pattern.compile(VFC_NODE_TYPE_ARTIFACTS_PATH_PATTERN).matcher(e.getKey()).matches())
765 // extract ArtifactDefinition from CSAR entry for each entry with matching artifact path
767 extractVfcArtifact(e, collectedWarningMessages).ifPresent(ip ->
768 addExtractedVfcArtifact(ip, artifacts)
771 // add counter suffix to artifact labels
772 handleWarningMessages(collectedWarningMessages);
779 * Print warnings to log
781 * @param collectedWarningMessages
783 public static void handleWarningMessages(Map<String, Set<List<String>>> collectedWarningMessages) {
784 collectedWarningMessages.entrySet().stream()
786 .forEach(e -> e.getValue().stream()
787 // add each warning message to log
788 .forEach(args -> log.warn(e.getKey(), args.toArray())));
792 private static void addExtractedVfcArtifact(
793 ImmutablePair<String, ArtifactDefinition> extractedVfcArtifact,
794 Map<String, List<ArtifactDefinition>> artifacts
796 String vfcToscaNamespace = extractedVfcArtifact.getKey();
798 artifacts.computeIfAbsent(vfcToscaNamespace, k -> new ArrayList<>());
799 artifacts.get(vfcToscaNamespace).add(extractedVfcArtifact.getValue());
802 private static Optional<ImmutablePair<String, ArtifactDefinition>> extractVfcArtifact(
803 Entry<String, byte[]> entry,
804 Map<String, Set<List<String>>> collectedWarningMessages
806 String[] parsedCsarArtifactPath = entry.getKey().split(PATH_DELIMITER);
807 String groupType = parsedCsarArtifactPath[2].toUpperCase();
809 return detectArtifactGroupType(groupType, collectedWarningMessages)
811 .map(buildArtifactDefinitionFromCsarArtifactPath(entry, collectedWarningMessages, parsedCsarArtifactPath))
813 ad -> Optional.of(new ImmutablePair<>(parsedCsarArtifactPath[1], ad)),
814 b -> Optional.empty()
818 private static Either<ArtifactGroupTypeEnum, Boolean> detectArtifactGroupType(String groupType, Map<String, Set<List<String>>> collectedWarningMessages) {
819 Either<ArtifactGroupTypeEnum, Boolean> result;
821 ArtifactGroupTypeEnum artifactGroupType = ArtifactGroupTypeEnum.findType(groupType.toUpperCase());
822 if (artifactGroupType == null || (artifactGroupType != ArtifactGroupTypeEnum.INFORMATIONAL && artifactGroupType != ArtifactGroupTypeEnum.DEPLOYMENT)) {
823 String warningMessage = "Warning - unrecognized artifact group type {} was received.";
824 List<String> messageArguments = new ArrayList<>();
825 messageArguments.add(groupType);
826 if (!collectedWarningMessages.containsKey(warningMessage)) {
827 Set<List<String>> messageArgumentLists = new HashSet<>();
828 messageArgumentLists.add(messageArguments);
829 collectedWarningMessages.put(warningMessage, messageArgumentLists);
831 collectedWarningMessages.get(warningMessage).add(messageArguments);
834 result = Either.right(false);
837 result = Either.left(artifactGroupType);
839 } catch (Exception e) {
840 log.debug("detectArtifactGroupType failed with exception", e);
841 result = Either.right(false);
846 private static F<ArtifactGroupTypeEnum, ArtifactDefinition> buildArtifactDefinitionFromCsarArtifactPath(
847 Entry<String, byte[]> entry,
848 Map<String, Set<List<String>>> collectedWarningMessages,
849 String[] parsedCsarArtifactPath
851 return artifactGroupType -> {
852 ArtifactDefinition artifact;
853 artifact = new ArtifactDefinition();
854 artifact.setArtifactGroupType(artifactGroupType);
855 artifact.setArtifactType(
856 detectArtifactTypeVFC(artifactGroupType, parsedCsarArtifactPath[3], parsedCsarArtifactPath[1],
857 collectedWarningMessages));
858 artifact.setArtifactName(
859 ValidationUtils.normalizeFileName(parsedCsarArtifactPath[parsedCsarArtifactPath.length - 1]));
860 artifact.setPayloadData(Base64.encodeBase64String(entry.getValue()));
861 artifact.setArtifactDisplayName(artifact.getArtifactName().lastIndexOf('.') > 0 ? artifact.getArtifactName()
862 .substring(0, artifact.getArtifactName().lastIndexOf('.')) : artifact.getArtifactName());
863 artifact.setArtifactLabel(ValidationUtils.normalizeArtifactLabel(artifact.getArtifactName()));
864 artifact.setDescription(ARTIFACT_CREATED_FROM_CSAR);
865 artifact.setIsFromCsar(true);
866 artifact.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(entry.getValue()));
872 public static final class NonMetaArtifactInfo {
874 private String artifactUniqueId;
875 private final String path;
876 private final String artifactName;
877 private final String displayName;
878 private final String artifactLabel;
879 private final String artifactType;
880 private final ArtifactGroupTypeEnum artifactGroupType;
881 private final String payloadData;
882 private final String artifactChecksum;
883 private final boolean isFromCsar;
885 public NonMetaArtifactInfo(final String artifactName, final String path, final String artifactType,
886 final ArtifactGroupTypeEnum artifactGroupType, final byte[] payloadData,
887 final String artifactUniqueId, final boolean isFromCsar) {
890 this.isFromCsar = isFromCsar;
891 this.artifactName = ValidationUtils.normalizeFileName(artifactName);
892 this.artifactType = artifactType;
893 this.artifactGroupType = artifactGroupType;
894 final int pointIndex = artifactName.lastIndexOf('.');
895 if (pointIndex > 0) {
896 displayName = artifactName.substring(0, pointIndex);
898 displayName = artifactName;
900 this.artifactLabel = ValidationUtils.normalizeArtifactLabel(artifactName);
901 if (payloadData == null) {
902 this.payloadData = null;
903 this.artifactChecksum = null;
905 this.payloadData = Base64.encodeBase64String(payloadData);
906 this.artifactChecksum = GeneralUtility.calculateMD5Base64EncodedByByteArray(payloadData);
908 this.artifactUniqueId = artifactUniqueId;
914 * This method checks the artifact GroupType & Artifact Type. <br>
915 * if there is any problem warning messages are added to collectedWarningMessages
917 * @param artifactPath
918 * @param collectedWarningMessages
921 public static Either<NonMetaArtifactInfo, Boolean> validateNonMetaArtifact(
924 Map<String, Set<List<String>>> collectedWarningMessages
927 String[] parsedArtifactPath = artifactPath.split(PATH_DELIMITER);
928 String groupType = parsedArtifactPath[1];
929 String receivedTypeName = parsedArtifactPath[2];
930 String artifactFileNameType = parsedArtifactPath[3];
932 return detectArtifactGroupType(groupType, collectedWarningMessages)
933 .left().bind(artifactGroupType -> {
934 String artifactType =
935 detectArtifactTypeVF(artifactGroupType, receivedTypeName, collectedWarningMessages);
937 return Either.left(new NonMetaArtifactInfo(
938 artifactFileNameType, artifactPath, artifactType,
939 artifactGroupType, payloadData, null, true
942 } catch (Exception e) {
943 log.debug("detectArtifactGroupType failed with exception", e);
944 return Either.right(false);
948 private static String detectArtifactTypeVFC(ArtifactGroupTypeEnum artifactGroupType, String receivedTypeName, String parentVfName, Map<String, Set<List<String>>> collectedWarningMessages) {
949 String warningMessage = "Warning - artifact type {} that was provided for VFC {} is not recognized.";
950 return detectArtifactType(artifactGroupType, receivedTypeName, warningMessage, collectedWarningMessages, parentVfName);
953 private static String detectArtifactTypeVF(ArtifactGroupTypeEnum artifactGroupType, String receivedTypeName, Map<String, Set<List<String>>> collectedWarningMessages) {
954 String warningMessage = "Warning - artifact type {} that was provided for VF is not recognized.";
955 return detectArtifactType(artifactGroupType, receivedTypeName, warningMessage, collectedWarningMessages);
958 private static String detectArtifactType(final ArtifactGroupTypeEnum artifactGroupType,
959 final String receivedTypeName, final String warningMessage,
960 final Map<String, Set<List<String>>> collectedWarningMessages,
961 final String... arguments) {
962 final ArtifactConfiguration artifactConfiguration =
963 ArtifactConfigManager.getInstance()
964 .find(receivedTypeName, artifactGroupType, ComponentType.RESOURCE)
967 if (artifactConfiguration == null) {
968 final List<String> messageArguments = new ArrayList<>();
969 messageArguments.add(receivedTypeName);
970 messageArguments.addAll(Arrays.asList(arguments));
971 if (!collectedWarningMessages.containsKey(warningMessage)) {
972 final Set<List<String>> messageArgumentLists = new HashSet<>();
973 messageArgumentLists.add(messageArguments);
974 collectedWarningMessages.put(warningMessage, messageArgumentLists);
976 collectedWarningMessages.get(warningMessage).add(messageArguments);
980 return artifactConfiguration == null ? ArtifactTypeEnum.OTHER.getType() : receivedTypeName;
983 private Either<ZipOutputStream, ResponseFormat> writeAllFilesToCsar(Component mainComponent, CsarDefinition csarDefinition, ZipOutputStream zipstream, boolean isInCertificationRequest) throws IOException{
984 ComponentArtifacts componentArtifacts = csarDefinition.getComponentArtifacts();
986 Either<ZipOutputStream, ResponseFormat> writeComponentArtifactsToSpecifiedPath = writeComponentArtifactsToSpecifiedPath(mainComponent, componentArtifacts, zipstream, ARTIFACTS_PATH, isInCertificationRequest);
988 if(writeComponentArtifactsToSpecifiedPath.isRight()){
989 return Either.right(writeComponentArtifactsToSpecifiedPath.right().value());
992 ComponentTypeArtifacts mainTypeAndCIArtifacts = componentArtifacts.getMainTypeAndCIArtifacts();
993 writeComponentArtifactsToSpecifiedPath = writeArtifactsInfoToSpecifiedPath(mainComponent, mainTypeAndCIArtifacts.getComponentArtifacts(), zipstream, ARTIFACTS_PATH, isInCertificationRequest);
995 if(writeComponentArtifactsToSpecifiedPath.isRight()){
996 return Either.right(writeComponentArtifactsToSpecifiedPath.right().value());
999 Map<String, ArtifactsInfo> componentInstancesArtifacts = mainTypeAndCIArtifacts.getComponentInstancesArtifacts();
1000 Set<String> keySet = componentInstancesArtifacts.keySet();
1002 String currentPath = ARTIFACTS_PATH + RESOURCES_PATH;
1003 for (String keyAssetName : keySet) {
1004 ArtifactsInfo artifactsInfo = componentInstancesArtifacts.get(keyAssetName);
1005 String pathWithAssetName = currentPath + keyAssetName + PATH_DELIMITER;
1006 writeComponentArtifactsToSpecifiedPath = writeArtifactsInfoToSpecifiedPath(mainComponent, artifactsInfo, zipstream, pathWithAssetName, isInCertificationRequest);
1008 if(writeComponentArtifactsToSpecifiedPath.isRight()){
1009 return Either.right(writeComponentArtifactsToSpecifiedPath.right().value());
1012 writeComponentArtifactsToSpecifiedPath = writeOperationsArtifactsToCsar(mainComponent, zipstream);
1014 if (writeComponentArtifactsToSpecifiedPath.isRight()) {
1015 return Either.right(writeComponentArtifactsToSpecifiedPath.right().value());
1017 return Either.left(zipstream);
1020 private Either<ZipOutputStream, ResponseFormat> writeOperationsArtifactsToCsar(Component component,
1021 ZipOutputStream zipstream) {
1022 if (checkComponentBeforeOperation(component)) {
1023 return Either.left(zipstream);
1025 final Map<String, InterfaceDefinition> interfaces = ((Resource) component).getInterfaces();
1026 for (Map.Entry<String, InterfaceDefinition> interfaceEntry : interfaces.entrySet()) {
1027 for (OperationDataDefinition operation : interfaceEntry.getValue().getOperations().values()) {
1029 if (checkComponentBeforeWrite(component, interfaceEntry, operation)) {
1032 final String artifactUUID = operation.getImplementation().getArtifactUUID();
1033 if (artifactUUID == null) {
1036 final Either<byte[], ActionStatus> artifactFromCassandra = getFromCassandra(artifactUUID);
1037 final String artifactName = operation.getImplementation().getArtifactName();
1038 if (artifactFromCassandra.isRight()) {
1039 log.error(ARTIFACT_NAME_UNIQUE_ID, artifactName, artifactUUID);
1040 log.error("Failed to get {} payload from DB reason: {}", artifactName,
1041 artifactFromCassandra.right().value());
1042 return Either.right(componentsUtils.getResponseFormat(
1043 ActionStatus.ARTIFACT_PAYLOAD_NOT_FOUND_DURING_CSAR_CREATION, "Resource",
1044 component.getUniqueId(), artifactName, artifactUUID));
1046 final byte[] payloadData = artifactFromCassandra.left().value();
1047 zipstream.putNextEntry(new ZipEntry(OperationArtifactUtil.createOperationArtifactPath(
1048 component, null, operation, true)));
1049 zipstream.write(payloadData);
1050 } catch (IOException e) {
1051 log.error("Component Name {}, Interface Name {}, Operation Name {}", component.getNormalizedName(),
1052 interfaceEntry.getKey(), operation.getName());
1053 log.error("Error while writing the operation's artifacts to the CSAR " + "{}", e);
1054 return Either.right(componentsUtils
1055 .getResponseFormat(ActionStatus.ERROR_DURING_CSAR_CREATION, "Resource",
1056 component.getUniqueId()));
1060 return Either.left(zipstream);
1063 private boolean checkComponentBeforeWrite(Component component, Entry<String, InterfaceDefinition> interfaceEntry, OperationDataDefinition operation) {
1064 final ArtifactDataDefinition implementation = operation.getImplementation();
1065 if (Objects.isNull(implementation)) {
1066 log.debug("Component Name {}, Interface Id {}, Operation Name {} - no Operation Implementation found",
1067 component.getNormalizedName(), interfaceEntry.getValue().getUniqueId(),
1068 operation.getName());
1071 final String artifactName = implementation.getArtifactName();
1072 if (Objects.isNull(artifactName)) {
1073 log.debug("Component Name {}, Interface Id {}, Operation Name {} - no artifact found",
1074 component.getNormalizedName(), interfaceEntry.getValue().getUniqueId(),
1075 operation.getName());
1078 if (OperationArtifactUtil.artifactNameIsALiteralValue(artifactName)) {
1079 log.debug("Component Name {}, Interface Id {}, Operation Name {} - artifact name is a literal value rather than an SDC artifact",
1080 component.getNormalizedName(), interfaceEntry.getValue().getUniqueId(),
1081 operation.getName());
1087 private boolean checkComponentBeforeOperation(Component component) {
1088 if (component instanceof Service) {
1091 if (Objects.isNull(((Resource) component).getInterfaces())) {
1092 log.debug("Component Name {}- no interfaces found", component.getNormalizedName());
1098 private Either<ZipOutputStream, ResponseFormat> writeComponentArtifactsToSpecifiedPath(Component mainComponent, ComponentArtifacts componentArtifacts, ZipOutputStream zipstream,
1099 String currentPath, boolean isInCertificationRequest) throws IOException {
1100 Map<String, ComponentTypeArtifacts> componentTypeArtifacts = componentArtifacts.getComponentTypeArtifacts();
1102 //<Inner Asset TOSCA name (e.g. VFC name)> folder name: <Inner Asset TOSCA name (e.g. VFC name)>_v<version>.
1103 //E.g. "org.openecomp.resource.vf.vipr_atm_v1.0"
1104 Set<String> componentTypeArtifactsKeys = componentTypeArtifacts.keySet();
1105 for (String keyAssetName : componentTypeArtifactsKeys) {
1106 ComponentTypeArtifacts componentInstanceArtifacts = componentTypeArtifacts.get(keyAssetName);
1107 ArtifactsInfo componentArtifacts2 = componentInstanceArtifacts.getComponentArtifacts();
1108 String pathWithAssetName = currentPath + keyAssetName + PATH_DELIMITER;
1109 Either<ZipOutputStream, ResponseFormat> writeArtifactsInfoToSpecifiedPath = writeArtifactsInfoToSpecifiedPath(mainComponent, componentArtifacts2, zipstream, pathWithAssetName, isInCertificationRequest);
1111 if(writeArtifactsInfoToSpecifiedPath.isRight()){
1112 return writeArtifactsInfoToSpecifiedPath;
1116 return Either.left(zipstream);
1119 private Either<ZipOutputStream, ResponseFormat> writeArtifactsInfoToSpecifiedPath(final Component mainComponent,
1120 final ArtifactsInfo currArtifactsInfo,
1121 final ZipOutputStream zip,
1123 final boolean isInCertificationRequest) throws IOException {
1125 final Map<ArtifactGroupTypeEnum, Map<String, List<ArtifactDefinition>>> artifactsInfo =
1126 currArtifactsInfo.getArtifactsInfo();
1127 for (final ArtifactGroupTypeEnum artifactGroupTypeEnum : artifactsInfo.keySet()) {
1128 final String groupTypeFolder =
1129 path + WordUtils.capitalizeFully(artifactGroupTypeEnum.getType()) + PATH_DELIMITER;
1131 final Map<String, List<ArtifactDefinition>> artifactTypesMap = artifactsInfo.get(artifactGroupTypeEnum);
1133 for (final String artifactType : artifactTypesMap.keySet()) {
1134 final List<ArtifactDefinition> artifactDefinitionList = artifactTypesMap.get(artifactType);
1135 String artifactTypeFolder = groupTypeFolder + artifactType + PATH_DELIMITER;
1137 if (ArtifactTypeEnum.WORKFLOW.getType().equals(artifactType) && path
1138 .contains(ARTIFACTS_PATH + RESOURCES_PATH)) {
1139 // Ignore this packaging as BPMN artifacts needs to be packaged in different manner
1142 if (ArtifactTypeEnum.WORKFLOW.getType().equals(artifactType)) {
1143 artifactTypeFolder += OperationArtifactUtil.BPMN_ARTIFACT_PATH + File.separator;
1146 // TODO: We should not do this but in order to keep this refactoring small enough,
1147 // we'll leave this as is for now
1148 List<ArtifactDefinition> collect =
1149 filterArtifactDefinitionToZip(mainComponent, artifactDefinitionList, isInCertificationRequest)
1150 .collect(Collectors.toList());
1151 for (ArtifactDefinition ad : collect) {
1152 zip.putNextEntry(new ZipEntry(artifactTypeFolder + ad.getArtifactName()));
1153 zip.write(ad.getPayloadData());
1157 return Either.left(zip);
1160 private Stream<ArtifactDefinition> filterArtifactDefinitionToZip(Component mainComponent,
1161 List<ArtifactDefinition> artifactDefinitionList, boolean isInCertificationRequest) {
1162 return artifactDefinitionList
1164 .filter(shouldBeInZip(isInCertificationRequest, mainComponent))
1165 .map(this::fetchPayLoadData)
1166 .filter(Either::isLeft)
1167 .map(e -> e.left().value());
1170 private Predicate<ArtifactDefinition> shouldBeInZip(boolean isInCertificationRequest, Component component) {
1171 return artifactDefinition ->
1172 !(!isInCertificationRequest
1173 && component.isService()
1174 && artifactDefinition.isHeatEnvType()
1175 || artifactDefinition.hasNoMandatoryEsId());
1178 private Either<ArtifactDefinition, ActionStatus> fetchPayLoadData(ArtifactDefinition ad) {
1179 byte[] payloadData = ad.getPayloadData();
1180 if(payloadData == null) {
1181 return getFromCassandra(ad.getEsId())
1185 }).right().map(as -> {
1186 log.debug(ARTIFACT_NAME_UNIQUE_ID, ad.getArtifactName(), ad.getUniqueId());
1187 log.debug("Failed to get {} payload from DB reason: {}", ad.getArtifactName(), as);
1191 return Either.left(ad);
1195 /************************************ Artifacts Structure ******************************************************************/
1197 * The artifacts Definition saved by their structure
1199 private class ArtifactsInfo {
1200 //Key is the type of artifacts(Informational/Deployment)
1201 //Value is a map between an artifact type and a list of all artifacts of this type
1202 private Map<ArtifactGroupTypeEnum, Map<String, List<ArtifactDefinition>>> artifactsInfoField;
1204 public ArtifactsInfo() {
1205 this.artifactsInfoField = new EnumMap<>(ArtifactGroupTypeEnum.class);
1208 public Map<ArtifactGroupTypeEnum, Map<String, List<ArtifactDefinition>>> getArtifactsInfo() {
1209 return artifactsInfoField;
1212 public void addArtifactsToGroup(ArtifactGroupTypeEnum artifactGroup,
1213 Map<String, List<ArtifactDefinition>> artifactsDefinition) {
1214 if (artifactsInfoField.get(artifactGroup) == null) {
1215 artifactsInfoField.put(artifactGroup, artifactsDefinition);
1217 Map<String, List<ArtifactDefinition>> artifactTypeEnumListMap =
1218 artifactsInfoField.get(artifactGroup);
1219 artifactTypeEnumListMap.putAll(artifactsDefinition);
1220 artifactsInfoField.put(artifactGroup, artifactTypeEnumListMap);
1225 public boolean isEmpty() {
1226 return artifactsInfoField.isEmpty();
1229 public boolean isNotEmpty() {
1236 * The artifacts of the component and of all its composed instances
1239 private class ComponentTypeArtifacts {
1240 private ArtifactsInfo componentArtifacts; //component artifacts (describes the Informational Deployment folders)
1241 private Map<String, ArtifactsInfo> componentInstancesArtifacts; //artifacts of the composed instances mapped by the resourceInstance normalized name (describes the Resources folder)
1243 public ComponentTypeArtifacts() {
1244 componentArtifacts = new ArtifactsInfo();
1245 componentInstancesArtifacts = new HashMap<>();
1248 public ArtifactsInfo getComponentArtifacts() {
1249 return componentArtifacts;
1251 public void setComponentArtifacts(ArtifactsInfo artifactsInfo) {
1252 this.componentArtifacts = artifactsInfo;
1254 public Map<String, ArtifactsInfo> getComponentInstancesArtifacts() {
1255 return componentInstancesArtifacts;
1257 public void setComponentInstancesArtifacts(Map<String, ArtifactsInfo> componentInstancesArtifacts) {
1258 this.componentInstancesArtifacts = componentInstancesArtifacts;
1261 public void addComponentInstancesArtifacts(String normalizedName, ArtifactsInfo artifactsInfo) {
1262 componentInstancesArtifacts.put(normalizedName, artifactsInfo);
1267 private class ComponentArtifacts {
1268 //artifacts of the component and CI's artifacts contained in it's composition (represents Informational, Deployment & Resource folders of main component)
1269 private ComponentTypeArtifacts mainTypeAndCIArtifacts;
1270 //artifacts of all component types mapped by their tosca name
1271 private Map<String, ComponentTypeArtifacts> componentTypeArtifacts;
1273 public ComponentArtifacts(){
1274 mainTypeAndCIArtifacts = new ComponentTypeArtifacts();
1275 componentTypeArtifacts = new HashMap<>();
1278 public ComponentTypeArtifacts getMainTypeAndCIArtifacts() {
1279 return mainTypeAndCIArtifacts;
1282 public void setMainTypeAndCIArtifacts(ComponentTypeArtifacts componentInstanceArtifacts) {
1283 this.mainTypeAndCIArtifacts = componentInstanceArtifacts;
1286 public Map<String, ComponentTypeArtifacts> getComponentTypeArtifacts() {
1287 return componentTypeArtifacts;
1290 public void setComponentTypeArtifacts(Map<String, ComponentTypeArtifacts> componentTypeArtifacts) {
1291 this.componentTypeArtifacts = componentTypeArtifacts;
1295 private class CsarDefinition {
1296 private ComponentArtifacts componentArtifacts;
1298 // add list of tosca artifacts and meta describes CSAR zip root
1300 public CsarDefinition(ComponentArtifacts componentArtifacts) {
1301 this.componentArtifacts = componentArtifacts;
1304 public ComponentArtifacts getComponentArtifacts() {
1305 return componentArtifacts;
1309 /************************************ Artifacts Structure END******************************************************************/
1311 private Either<CsarDefinition,ResponseFormat> collectComponentCsarDefinition(Component component){
1312 ComponentArtifacts componentArtifacts = new ComponentArtifacts();
1313 Component updatedComponent = component;
1315 //get service to receive the AII artifacts uploaded to the service
1316 if (updatedComponent.getComponentType() == ComponentTypeEnum.SERVICE) {
1317 Either<Service, StorageOperationStatus> getServiceResponse = toscaOperationFacade.getToscaElement(updatedComponent.getUniqueId());
1319 if(getServiceResponse.isRight()){
1320 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getServiceResponse.right().value());
1321 return Either.right(componentsUtils.getResponseFormat(actionStatus));
1324 updatedComponent = getServiceResponse.left().value();
1327 //find the artifacts of the main component, it would have its composed instances artifacts in a separate folder
1328 ComponentTypeArtifacts componentInstanceArtifacts = new ComponentTypeArtifacts();
1329 ArtifactsInfo artifactsInfo = collectComponentArtifacts(updatedComponent);
1330 componentInstanceArtifacts.setComponentArtifacts(artifactsInfo);
1331 componentArtifacts.setMainTypeAndCIArtifacts(componentInstanceArtifacts);
1333 Map<String,ComponentTypeArtifacts> resourceTypeArtifacts = componentArtifacts.getComponentTypeArtifacts(); //artifacts mapped by the component type(tosca name+version)
1334 //get the component instances
1335 List<ComponentInstance> componentInstances = updatedComponent.getComponentInstances();
1336 if (componentInstances!=null){
1337 for (ComponentInstance componentInstance:componentInstances){
1338 //call recursive to find artifacts for all the path
1339 Either<Boolean, ResponseFormat> collectComponentInstanceArtifacts = collectComponentInstanceArtifacts(
1340 updatedComponent, componentInstance, resourceTypeArtifacts, componentInstanceArtifacts);
1341 if (collectComponentInstanceArtifacts.isRight()){
1342 return Either.right(collectComponentInstanceArtifacts.right().value());
1347 if(log.isDebugEnabled()){
1348 printResult(componentArtifacts,updatedComponent.getName());
1351 return Either.left(new CsarDefinition(componentArtifacts));
1354 private void printResult(ComponentArtifacts componentArtifacts, String name) {
1355 StringBuilder result = new StringBuilder();
1356 result.append("Artifacts of main component " + name + "\n");
1357 ComponentTypeArtifacts componentInstanceArtifacts = componentArtifacts.getMainTypeAndCIArtifacts();
1358 printArtifacts(componentInstanceArtifacts);
1359 result.append("Type Artifacts\n");
1360 for (Map.Entry<String, ComponentTypeArtifacts> typeArtifacts:componentArtifacts.getComponentTypeArtifacts().entrySet()){
1361 result.append("Folder " + typeArtifacts.getKey() + "\n");
1362 result.append(printArtifacts(typeArtifacts.getValue()));
1365 if(log.isDebugEnabled()){
1366 log.debug(result.toString());
1370 private String printArtifacts(ComponentTypeArtifacts componentInstanceArtifacts) {
1371 StringBuilder result = new StringBuilder();
1372 ArtifactsInfo artifactsInfo = componentInstanceArtifacts.getComponentArtifacts();
1373 Map<ArtifactGroupTypeEnum, Map<String, List<ArtifactDefinition>>> componentArtifacts = artifactsInfo.getArtifactsInfo();
1374 printArtifacts(componentArtifacts);
1375 result = result.append("Resources\n");
1376 for (Map.Entry<String, ArtifactsInfo> resourceInstance:componentInstanceArtifacts.getComponentInstancesArtifacts().entrySet()){
1377 result.append("Folder" + resourceInstance.getKey() + "\n");
1378 result.append(printArtifacts(resourceInstance.getValue().getArtifactsInfo()));
1381 return result.toString();
1384 private String printArtifacts(Map<ArtifactGroupTypeEnum, Map<String, List<ArtifactDefinition>>> componetArtifacts) {
1385 StringBuilder result = new StringBuilder();
1386 for (Map.Entry<ArtifactGroupTypeEnum, Map<String, List<ArtifactDefinition>>> artifactGroup:componetArtifacts.entrySet()){
1387 result.append(" " + artifactGroup.getKey().getType());
1388 for (Map.Entry<String, List<ArtifactDefinition>> groupArtifacts:artifactGroup.getValue().entrySet()){
1389 result.append(" " + groupArtifacts.getKey());
1390 for (ArtifactDefinition artifact:groupArtifacts.getValue()){
1391 result.append(" " + artifact.getArtifactDisplayName());
1396 return result.toString();
1399 private ComponentTypeArtifacts collectComponentTypeArtifacts(
1400 Component fetchedComponent
1402 ArtifactsInfo componentArtifacts = collectComponentArtifacts(fetchedComponent);
1403 ComponentTypeArtifacts componentArtifactsInfo = new ComponentTypeArtifacts();
1404 if (componentArtifacts.isNotEmpty()) {
1405 componentArtifactsInfo.setComponentArtifacts(componentArtifacts);
1407 return componentArtifactsInfo;
1410 private Either<Boolean, ResponseFormat> collectComponentInstanceArtifacts(Component parentComponent,ComponentInstance componentInstance,
1411 Map<String, ComponentTypeArtifacts> resourcesTypeArtifacts,ComponentTypeArtifacts instanceArtifactsLocation) {
1412 //1. get the component instance component
1413 String componentUid;
1414 if (componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy) {
1415 componentUid = componentInstance.getSourceModelUid();
1418 componentUid = componentInstance.getComponentUid();
1420 Either<Component, StorageOperationStatus> component = toscaOperationFacade.getToscaElement(componentUid);
1421 if (component.isRight()) {
1422 log.error("Failed to fetch resource with id {} for instance {}",componentUid, parentComponent.getUUID());
1423 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ASSET_NOT_FOUND_DURING_CSAR_CREATION,
1424 parentComponent.getComponentType().getValue(), parentComponent.getUUID(),
1425 componentInstance.getOriginType().getComponentType().getValue(), componentUid));
1427 Component fetchedComponent = component.left().value();
1429 //2. fill the artifacts for the current component parent type
1430 String toscaComponentName =
1431 componentInstance.getToscaComponentName() + "_v" + componentInstance.getComponentVersion();
1433 // if there are no artifacts for this component type we need to fetch and build them
1434 ComponentTypeArtifacts componentParentArtifacts = Optional
1435 .ofNullable(resourcesTypeArtifacts.get(toscaComponentName))
1436 .orElseGet(() -> collectComponentTypeArtifacts(fetchedComponent));
1438 if (componentParentArtifacts.getComponentArtifacts().isNotEmpty()) {
1439 resourcesTypeArtifacts.put(toscaComponentName, componentParentArtifacts);
1442 //3. find the artifacts specific to the instance
1443 Map<String, List<ArtifactDefinition>> componentInstanceSpecificInformationalArtifacts =
1444 getComponentInstanceSpecificArtifacts(componentInstance.getArtifacts(),
1445 componentParentArtifacts.getComponentArtifacts().getArtifactsInfo(), ArtifactGroupTypeEnum.INFORMATIONAL);
1446 Map<String, List<ArtifactDefinition>> componentInstanceSpecificDeploymentArtifacts =
1447 getComponentInstanceSpecificArtifacts(componentInstance.getDeploymentArtifacts(),
1448 componentParentArtifacts.getComponentArtifacts().getArtifactsInfo(), ArtifactGroupTypeEnum.DEPLOYMENT);
1450 //4. add the instances artifacts to the component type
1451 ArtifactsInfo artifactsInfo = new ArtifactsInfo();
1452 if (!componentInstanceSpecificInformationalArtifacts.isEmpty()){
1453 artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.INFORMATIONAL, componentInstanceSpecificInformationalArtifacts);
1455 if (!componentInstanceSpecificDeploymentArtifacts.isEmpty()){
1456 artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.DEPLOYMENT, componentInstanceSpecificDeploymentArtifacts);
1458 if (!artifactsInfo.isEmpty()){
1459 instanceArtifactsLocation.addComponentInstancesArtifacts(componentInstance.getNormalizedName(), artifactsInfo);
1462 //5. do the same for all the component instances
1463 List<ComponentInstance> componentInstances = fetchedComponent.getComponentInstances();
1464 if (componentInstances!=null){
1465 for (ComponentInstance childComponentInstance:componentInstances){
1466 Either<Boolean, ResponseFormat> collectComponentInstanceArtifacts = collectComponentInstanceArtifacts(
1467 fetchedComponent, childComponentInstance, resourcesTypeArtifacts, componentParentArtifacts);
1468 if (collectComponentInstanceArtifacts.isRight()){
1469 return collectComponentInstanceArtifacts;
1474 return Either.left(true);
1477 public String getVersionFirstThreeOctets() {
1478 return versionFirstThreeOctets;
1481 public void setVersionFirstThreeOctets(String versionFirstThreeOctetes) {
1482 this.versionFirstThreeOctets = versionFirstThreeOctetes;
1484 private Map<String, List<ArtifactDefinition>> getComponentInstanceSpecificArtifacts(Map<String, ArtifactDefinition> componentArtifacts,
1485 Map<ArtifactGroupTypeEnum, Map<String, List<ArtifactDefinition>>> componentTypeArtifacts, ArtifactGroupTypeEnum artifactGroupTypeEnum) {
1486 Map<String, List<ArtifactDefinition>> parentArtifacts = componentTypeArtifacts.get(artifactGroupTypeEnum); //the artfiacts of the component itself and not the instance
1488 Map<String, List<ArtifactDefinition>> artifactsByTypeOfComponentInstance = new HashMap<>();
1489 if (componentArtifacts!=null){
1490 for (ArtifactDefinition artifact:componentArtifacts.values()){
1491 List<ArtifactDefinition> parentArtifactsByType = null;
1492 if (parentArtifacts!=null){
1493 parentArtifactsByType = parentArtifacts.get(artifact.getArtifactType());
1495 //the artifact is of instance
1496 if (parentArtifactsByType == null || !parentArtifactsByType.contains(artifact)){
1497 List<ArtifactDefinition> typeArtifacts = artifactsByTypeOfComponentInstance.get(artifact.getArtifactType());
1498 if (typeArtifacts == null){
1499 typeArtifacts = new ArrayList<>();
1500 artifactsByTypeOfComponentInstance.put(artifact.getArtifactType(), typeArtifacts);
1502 typeArtifacts.add(artifact);
1507 return artifactsByTypeOfComponentInstance;
1510 private ArtifactsInfo collectComponentArtifacts(Component component) {
1511 Map<String, ArtifactDefinition> informationalArtifacts = component.getArtifacts();
1512 Map<String, List<ArtifactDefinition>> informationalArtifactsByType = collectGroupArtifacts(informationalArtifacts);
1513 Map<String, ArtifactDefinition> deploymentArtifacts = component.getDeploymentArtifacts();
1514 Map<String, List<ArtifactDefinition>> deploymentArtifactsByType = collectGroupArtifacts(deploymentArtifacts);
1515 Map<String, ArtifactDefinition> interfaceOperationArtifacts =
1516 OperationArtifactUtil.getDistinctInterfaceOperationArtifactsByName(component);
1517 Map<String, List<ArtifactDefinition>> interfaceOperationArtifactsByType = collectGroupArtifacts(
1518 interfaceOperationArtifacts);
1519 ArtifactsInfo artifactsInfo = new ArtifactsInfo();
1520 if (!informationalArtifactsByType.isEmpty()){
1521 artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.INFORMATIONAL, informationalArtifactsByType);
1523 if (!deploymentArtifactsByType.isEmpty() ){
1524 artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.DEPLOYMENT, deploymentArtifactsByType);
1526 //Add component interface operation artifacts
1527 if(MapUtils.isNotEmpty(interfaceOperationArtifacts)) {
1528 artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.DEPLOYMENT, interfaceOperationArtifactsByType);
1531 return artifactsInfo;
1534 private Map<String, List<ArtifactDefinition>> collectGroupArtifacts(
1535 final Map<String, ArtifactDefinition> componentArtifacts) {
1536 final Map<String, List<ArtifactDefinition>> artifactsByType = new HashMap<>();
1537 for (final ArtifactDefinition artifact : componentArtifacts.values()) {
1538 if (artifact.getArtifactUUID() != null) {
1539 artifactsByType.putIfAbsent(artifact.getArtifactType(), new ArrayList<>());
1540 final List<ArtifactDefinition> typeArtifacts = artifactsByType.get(artifact.getArtifactType());
1541 typeArtifacts.add(artifact);
1544 return artifactsByType;