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<MainYamlWithDependencies, 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().mainYaml;
265 dependencies = toscaRepresentation.left().value().dependencies.orElse(null);
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<MainYamlWithDependencies, 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<MainYamlWithDependencies, ResponseFormat> toscaRepresentation =
330 shouldBeFetchedFromCassandra ?
331 fetchToscaRepresentation(artifactDef) :
332 generateToscaRepresentation(component);
334 return toscaRepresentation.left().bind(iff(
335 myd -> !myd.dependencies.isPresent(),
336 myd -> fetchToscaTemplateDependencies(myd.mainYaml, 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<MainYamlWithDependencies, 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 -> MainYamlWithDependencies.make(mainYml, tt));
355 private Either<MainYamlWithDependencies, 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));
359 }).left().map(MainYamlWithDependencies::make);
362 private Either<MainYamlWithDependencies, 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(MainYamlWithDependencies::make);
369 // TODO: Refactor the ToscaRepresentation class in order to remove the following one
370 // This will be done in a separate change
371 private static class MainYamlWithDependencies {
373 private final byte[] mainYaml;
374 private final Optional<List<Triple<String, String, Component>>> dependencies;
376 private MainYamlWithDependencies(byte[] mainYaml,
377 Optional<List<Triple<String, String, Component>>> dependencies) {
378 this.mainYaml = mainYaml;
379 this.dependencies = dependencies;
382 public static MainYamlWithDependencies make(byte[] mainYaml) {
383 return new MainYamlWithDependencies(mainYaml, Optional.empty());
386 public static MainYamlWithDependencies make(ToscaRepresentation tr) {
387 return new MainYamlWithDependencies(tr.getMainYaml().getBytes(), Optional.ofNullable(tr.getDependencies()));
390 public static MainYamlWithDependencies make(byte[] mainYaml, ToscaTemplate tt) {
391 return new MainYamlWithDependencies(mainYaml, Optional.ofNullable(tt.getDependencies()));
396 * Create a list of all derived nodes found on the package
398 * @param dependencies all node dependencies
399 * @return a list of nodes
401 private List<String> findNonRootNodesFromPackage(final List<Triple<String, String, Component>> dependencies) {
402 final List<String> nodes = new ArrayList<>();
403 if (CollectionUtils.isNotEmpty(dependencies)) {
404 final String NATIVE_ROOT = "tosca.nodes.Root";
405 dependencies.forEach(dependency -> {
406 if (dependency.getRight() instanceof Resource) {
407 final Resource resource = (Resource) dependency.getRight();
408 if (CollectionUtils.isNotEmpty(resource.getDerivedList())) {
409 resource.getDerivedList().stream()
410 .filter(node -> !nodes.contains(node) && !NATIVE_ROOT.equalsIgnoreCase(node))
411 .forEach(node -> nodes.add(node));
420 * Writes a new zip entry
422 * @param zipInputStream the zip entry to be read
423 * @return a map of the given zip entry
425 private Map<String, Object> readYamlZipEntry(final ZipInputStream zipInputStream) throws IOException {
426 final int initSize = 2048;
427 final StringBuilder zipEntry = new StringBuilder();
428 final byte[] buffer = new byte[initSize];
430 while ((read = zipInputStream.read(buffer, 0, initSize)) >= 0) {
431 zipEntry.append(new String(buffer, 0, read));
434 return (Map<String, Object>) new Yaml().load(zipEntry.toString());
438 * Filters and removes all duplicated nodes found
440 * @param nodesFromPackage a List of all derived nodes found on the given package
441 * @param nodesFromArtifactFile represents the nodes.yml file stored in Cassandra
442 * @return a nodes Map updated
444 private Map<String, Object> updateNodeYml(final List<String> nodesFromPackage,
445 final Map<String, Object> nodesFromArtifactFile) {
447 if (MapUtils.isNotEmpty(nodesFromArtifactFile)) {
448 final String nodeTypeBlock = ToscaTagNamesEnum.NODE_TYPES.getElementName();
449 final Map<String, Object> nodeTypes = (Map<String, Object>) nodesFromArtifactFile.get(nodeTypeBlock);
450 nodesFromPackage.stream()
451 .filter(nodeTypes::containsKey)
452 .forEach(nodeTypes::remove);
454 nodesFromArtifactFile.replace(nodeTypeBlock, nodeTypes);
457 return nodesFromArtifactFile;
461 * Updates the zip entry from the given parameters
463 * @param byteArrayOutputStream an output stream in which the data is written into a byte array.
464 * @param nodesYaml a Map of nodes to be written
466 private void updateZipEntry(final ByteArrayOutputStream byteArrayOutputStream,
467 final Map<String, Object> nodesYaml) throws IOException {
468 if (MapUtils.isNotEmpty(nodesYaml)) {
469 byteArrayOutputStream.write(new YamlUtil().objectToYaml(nodesYaml).getBytes());
473 private Either<ZipOutputStream, ResponseFormat> getZipOutputStreamResponseFormatEither(
475 List<Triple<String, String, Component>> dependencies
476 ) throws IOException {
478 ComponentCache innerComponentsCache = ComponentCache
479 .overwritable(overwriteIfSameVersions())
480 .onMerge((oldValue, newValue) -> {
481 log.warn("Overwriting component invariantID {} of version {} with a newer version {}",
482 oldValue.id, oldValue.getComponentVersion(), newValue.getComponentVersion()
486 if (dependencies != null && !dependencies.isEmpty()) {
487 for (Triple<String, String, Component> d : dependencies) {
488 String cassandraId = d.getMiddle();
489 Component childComponent = d.getRight();
491 Either<byte[], ResponseFormat> entryData = getEntryData(cassandraId, childComponent)
492 .right().map(x -> componentsUtils.getResponseFormat(x));
494 if (entryData.isRight()) {
495 return Either.right(entryData.right().value());
498 //fill innerComponentsCache
499 String fileName = d.getLeft();
500 innerComponentsCache.put(cassandraId, fileName, childComponent);
501 addInnerComponentsToCache(innerComponentsCache, childComponent);
504 //add inner components to CSAR
505 return addInnerComponentsToCSAR(zip, innerComponentsCache);
510 private Either<ZipOutputStream, ResponseFormat> addInnerComponentsToCSAR(
512 ComponentCache innerComponentsCache
513 ) throws IOException {
514 for (ImmutableTriple<String, String, Component> ict : innerComponentsCache.iterable()) {
515 Component innerComponent = ict.getRight();
517 String icFileName = ict.getMiddle();
518 // add component to zip
519 Either<Tuple2<byte[], ZipEntry>, ResponseFormat> zipEntry = toZipEntry(ict);
520 // TODO: this should not be done, we should instead compose this either further,
521 // but in order to keep this refactoring small, we'll stop here.
522 if (zipEntry.isRight()) {
523 return Either.right(zipEntry.right().value());
525 Tuple2<byte[], ZipEntry> value = zipEntry.left().value();
526 zip.putNextEntry(value._2);
528 // add component interface to zip
529 if (!ModelConverter.isAtomicComponent(innerComponent)) {
530 writeComponentInterface(innerComponent, zip, icFileName, true);
536 private Either<Tuple2<byte[], ZipEntry>, ResponseFormat> toZipEntry(
537 ImmutableTriple<String, String, Component> cachedEntry
539 String cassandraId = cachedEntry.getLeft();
540 String fileName = cachedEntry.getMiddle();
541 Component innerComponent = cachedEntry.getRight();
542 return getEntryData(cassandraId, innerComponent)
543 .right().map(status -> {
544 log.debug("Failed adding to zip component {}, error {}", cassandraId, status);
545 return componentsUtils.getResponseFormat(status);
546 }).left().map(content -> new Tuple2<>(content, new ZipEntry(DEFINITIONS_PATH + fileName)));
550 * Writes to a CSAR zip from casandra schema data
552 * @param zipOutputStream stores the input stream content
553 * @param schemaFileZip zip data from Cassandra
554 * @param nodesFromPackage list of all nodes found on the onboarded package
556 private void addSchemaFilesFromCassandra(final ZipOutputStream zipOutputStream,
557 final byte[] schemaFileZip,
558 final List<String> nodesFromPackage) {
559 final int initSize = 2048;
560 log.debug("Starting copy from Schema file zip to CSAR zip");
561 try (final ZipInputStream zipInputStream = new ZipInputStream(new ByteArrayInputStream(schemaFileZip));
562 final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
563 final BufferedOutputStream bufferedOutputStream =
564 new BufferedOutputStream(byteArrayOutputStream, initSize)) {
567 while ((entry = zipInputStream.getNextEntry()) != null) {
568 ZipUtils.checkForZipSlipInRead(entry);
569 final String entryName = entry.getName();
570 int readSize = initSize;
571 final byte[] entryData = new byte[initSize];
572 if (shouldZipEntryBeHandled(entryName)) {
573 if (NODES_YML.equalsIgnoreCase(entryName)) {
574 handleNode(zipInputStream, byteArrayOutputStream, nodesFromPackage);
576 while ((readSize = zipInputStream.read(entryData, 0, readSize)) != -1) {
577 bufferedOutputStream.write(entryData, 0, readSize);
579 bufferedOutputStream.flush();
581 byteArrayOutputStream.flush();
582 zipOutputStream.putNextEntry(new ZipEntry(DEFINITIONS_PATH + entryName));
583 zipOutputStream.write(byteArrayOutputStream.toByteArray());
584 zipOutputStream.flush();
585 byteArrayOutputStream.reset();
588 } catch (final Exception e) {
589 log.error("Error while writing the SDC schema file to the CSAR", e);
590 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
592 log.debug("Finished copy from Schema file zip to CSAR zip");
596 * Checks if the zip entry should or should not be added to the CSAR based on the given global type list
598 * @param entryName the zip entry name
599 * @return true if the zip entry should be handled
601 private boolean shouldZipEntryBeHandled(final String entryName) {
602 return globalCsarImports.stream()
603 .anyMatch(entry -> entry.contains(entryName));
607 * Handles the nodes.yml zip entry, updating the nodes.yml to avoid duplicated nodes on it.
609 * @param zipInputStream the zip entry to be read
610 * @param byteArrayOutputStream an output stream in which the data is written into a byte array.
611 * @param nodesFromPackage list of all nodes found on the onboarded package
613 private void handleNode(final ZipInputStream zipInputStream,
614 final ByteArrayOutputStream byteArrayOutputStream,
615 final List<String> nodesFromPackage) throws IOException {
617 final Map<String, Object> nodesFromArtifactFile = readYamlZipEntry(zipInputStream);
618 final Map<String, Object> nodesYaml = updateNodeYml(nodesFromPackage, nodesFromArtifactFile);
619 updateZipEntry(byteArrayOutputStream, nodesYaml);
622 private void addInnerComponentsToCache(ComponentCache componentCache, Component childComponent) {
623 javaListToVavrList(childComponent.getComponentInstances())
624 .filter(ci -> componentCache.notCached(ci.getComponentUid()))
626 // all resource must be only once!
627 Either<Resource, StorageOperationStatus> resource =
628 toscaOperationFacade.getToscaElement(ci.getComponentUid());
629 Component componentRI = checkAndAddComponent(componentCache, ci, resource);
630 //if not atomic - insert inner components as well
631 // TODO: This could potentially create a StackOverflowException if the call stack
632 // happens to be too large. Tail-recursive optimization should be used here.
633 if (!ModelConverter.isAtomicComponent(componentRI)) {
634 addInnerComponentsToCache(componentCache, componentRI);
639 // TODO: Move this function in FJToVavrHelper.java once Change 108540 is merged
640 private io.vavr.collection.List<ComponentInstance> javaListToVavrList(
641 List<ComponentInstance> componentInstances
644 .of(componentInstances)
645 .map(io.vavr.collection.List::ofAll)
646 .getOrElse(io.vavr.collection.List::empty);
649 private Component checkAndAddComponent(ComponentCache componentCache, ComponentInstance ci, Either<Resource, StorageOperationStatus> resource) {
650 if (resource.isRight()) {
651 log.debug("Failed to fetch resource with id {} for instance {}", ci.getComponentUid(), ci.getName());
653 Component componentRI = resource.left().value();
655 Map<String, ArtifactDefinition> childToscaArtifacts = componentRI.getToscaArtifacts();
656 ArtifactDefinition childArtifactDefinition = childToscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE);
657 if (childArtifactDefinition != null) {
660 childArtifactDefinition.getEsId(),
661 childArtifactDefinition.getArtifactName(),
668 private Either<ZipOutputStream, ResponseFormat> writeComponentInterface(
672 boolean isAssociatedComponent
674 // TODO: This should not be done but we need this to keep the refactoring small enough to be easily reviewable
675 return writeComponentInterface(component, fileName, isAssociatedComponent, ZipWriter.live(zip))
676 .map(void0 -> Either.<ZipOutputStream, ResponseFormat>left(zip))
678 log.error("#writeComponentInterface - zip writing failed with error: ", th);
679 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
683 private Try<Void> writeComponentInterface(
686 boolean isAssociatedComponent,
689 Either<String, ToscaError> yml = toscaExportUtils
690 .exportComponentInterface(component, isAssociatedComponent)
691 .left().map(ToscaRepresentation::getMainYaml);
693 return fromEither(yml, ToscaErrorException::new)
694 .flatMap(zw.write(DEFINITIONS_PATH + ToscaExportHandler.getInterfaceFilename(fileName)));
697 public static class ToscaErrorException extends Exception {
699 ToscaErrorException(ToscaError error) {
700 super("Error while exporting component's interface (toscaError:" + error + ")");
704 private Either<byte[], ActionStatus> getEntryData(String cassandraId, Component childComponent) {
705 if (cassandraId == null || cassandraId.isEmpty()) {
706 return toscaExportUtils.exportComponent(childComponent)
707 .right().map(toscaErrorToActionStatus(childComponent))
708 .left().map(toscaRepresentation -> toscaRepresentation.getMainYaml().getBytes());
710 return getFromCassandra(cassandraId);
714 private F<ToscaError, ActionStatus> toscaErrorToActionStatus(Component childComponent) {
715 return toscaError -> {
716 log.debug("Failed to export tosca template for child component {} error {}",
717 childComponent.getUniqueId(), toscaError);
718 return componentsUtils.convertFromToscaError(toscaError);
722 private Either<byte[], ResponseFormat> getLatestSchemaFilesFromCassandra() {
723 String fto = getVersionFirstThreeOctets();
724 return sdcSchemaFilesCassandraDao.getSpecificSchemaFiles(fto, CONFORMANCE_LEVEL)
725 .right().map(schemaFilesFetchDBError(fto))
728 () -> schemaFileFetchError(fto),
729 s -> Either.left(s.iterator().next().getPayloadAsArray())
734 private static <A, B> F<A, B> iff(Predicate<A> p, Supplier<B> s, Function<A, B> orElse) {
735 return a -> p.test(a) ? s.get() : orElse.apply(a);
738 private F<CassandraOperationStatus, ResponseFormat> schemaFilesFetchDBError(String firstThreeOctets) {
741 "Failed to get the schema files SDC-Version: {} Conformance-Level {}. Please fix DB table accordingly.",
742 firstThreeOctets, CONFORMANCE_LEVEL);
743 StorageOperationStatus sos = DaoStatusConverter.convertCassandraStatusToStorageStatus(cos);
744 return componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(sos));
748 private Either<byte[], ResponseFormat> schemaFileFetchError(String firstThreeOctets) {
749 log.debug("Failed to get the schema files SDC-Version: {} Conformance-Level {}",
750 firstThreeOctets, CONFORMANCE_LEVEL);
752 componentsUtils.getResponseFormat(
753 ActionStatus.TOSCA_SCHEMA_FILES_NOT_FOUND, firstThreeOctets, CONFORMANCE_LEVEL
758 private Either<byte[], ActionStatus> getFromCassandra(String cassandraId) {
759 return artifactCassandraDao.getArtifact(cassandraId)
760 .right().map(cos -> {
761 log.debug("Failed to fetch artifact from Cassandra by id {} error {} ", cassandraId, cos);
762 StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(cos);
763 return componentsUtils.convertFromStorageResponse(storageStatus);
764 }).left().map(DAOArtifactData::getDataAsArray);
767 private String createCsarBlock0(String metaFileVersion, String toscaConformanceLevel) {
768 return String.format(BLOCK_0_TEMPLATE, metaFileVersion, toscaConformanceLevel);
771 private String createToscaBlock0(String metaFileVersion, String csarVersion, String createdBy, String entryDef) {
772 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";
773 return String.format(block0template, metaFileVersion, csarVersion, createdBy, entryDef);
777 * Extracts artifacts of VFCs from CSAR
780 * @return Map of <String, List<ArtifactDefinition>> the contains Lists of artifacts according vfcToscaNamespace
782 public static Map<String, List<ArtifactDefinition>> extractVfcsArtifactsFromCsar(Map<String, byte[]> csar) {
784 Map<String, List<ArtifactDefinition>> artifacts = new HashMap<>();
786 log.debug("************* Going to extract VFCs artifacts from Csar. ");
787 Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>();
788 csar.entrySet().stream()
789 // filter CSAR entry by node type artifact path
790 .filter(e -> Pattern.compile(VFC_NODE_TYPE_ARTIFACTS_PATH_PATTERN).matcher(e.getKey()).matches())
791 // extract ArtifactDefinition from CSAR entry for each entry with matching artifact path
793 extractVfcArtifact(e, collectedWarningMessages).ifPresent(ip ->
794 addExtractedVfcArtifact(ip, artifacts)
797 // add counter suffix to artifact labels
798 handleWarningMessages(collectedWarningMessages);
805 * Print warnings to log
807 * @param collectedWarningMessages
809 public static void handleWarningMessages(Map<String, Set<List<String>>> collectedWarningMessages) {
810 collectedWarningMessages.entrySet().stream()
812 .forEach(e -> e.getValue().stream()
813 // add each warning message to log
814 .forEach(args -> log.warn(e.getKey(), args.toArray())));
818 private static void addExtractedVfcArtifact(
819 ImmutablePair<String, ArtifactDefinition> extractedVfcArtifact,
820 Map<String, List<ArtifactDefinition>> artifacts
822 String vfcToscaNamespace = extractedVfcArtifact.getKey();
824 artifacts.computeIfAbsent(vfcToscaNamespace, k -> new ArrayList<>());
825 artifacts.get(vfcToscaNamespace).add(extractedVfcArtifact.getValue());
828 private static Optional<ImmutablePair<String, ArtifactDefinition>> extractVfcArtifact(
829 Entry<String, byte[]> entry,
830 Map<String, Set<List<String>>> collectedWarningMessages
832 String[] parsedCsarArtifactPath = entry.getKey().split(PATH_DELIMITER);
833 String groupType = parsedCsarArtifactPath[2].toUpperCase();
835 return detectArtifactGroupType(groupType, collectedWarningMessages)
837 .map(buildArtifactDefinitionFromCsarArtifactPath(entry, collectedWarningMessages, parsedCsarArtifactPath))
839 ad -> Optional.of(new ImmutablePair<>(parsedCsarArtifactPath[1], ad)),
840 b -> Optional.empty()
844 private static Either<ArtifactGroupTypeEnum, Boolean> detectArtifactGroupType(String groupType, Map<String, Set<List<String>>> collectedWarningMessages) {
845 Either<ArtifactGroupTypeEnum, Boolean> result;
847 ArtifactGroupTypeEnum artifactGroupType = ArtifactGroupTypeEnum.findType(groupType.toUpperCase());
848 if (artifactGroupType == null || (artifactGroupType != ArtifactGroupTypeEnum.INFORMATIONAL && artifactGroupType != ArtifactGroupTypeEnum.DEPLOYMENT)) {
849 String warningMessage = "Warning - unrecognized artifact group type {} was received.";
850 List<String> messageArguments = new ArrayList<>();
851 messageArguments.add(groupType);
852 if (!collectedWarningMessages.containsKey(warningMessage)) {
853 Set<List<String>> messageArgumentLists = new HashSet<>();
854 messageArgumentLists.add(messageArguments);
855 collectedWarningMessages.put(warningMessage, messageArgumentLists);
857 collectedWarningMessages.get(warningMessage).add(messageArguments);
860 result = Either.right(false);
863 result = Either.left(artifactGroupType);
865 } catch (Exception e) {
866 log.debug("detectArtifactGroupType failed with exception", e);
867 result = Either.right(false);
872 private static F<ArtifactGroupTypeEnum, ArtifactDefinition> buildArtifactDefinitionFromCsarArtifactPath(
873 Entry<String, byte[]> entry,
874 Map<String, Set<List<String>>> collectedWarningMessages,
875 String[] parsedCsarArtifactPath
877 return artifactGroupType -> {
878 ArtifactDefinition artifact;
879 artifact = new ArtifactDefinition();
880 artifact.setArtifactGroupType(artifactGroupType);
881 artifact.setArtifactType(
882 detectArtifactTypeVFC(artifactGroupType, parsedCsarArtifactPath[3], parsedCsarArtifactPath[1],
883 collectedWarningMessages));
884 artifact.setArtifactName(
885 ValidationUtils.normalizeFileName(parsedCsarArtifactPath[parsedCsarArtifactPath.length - 1]));
886 artifact.setPayloadData(Base64.encodeBase64String(entry.getValue()));
887 artifact.setArtifactDisplayName(artifact.getArtifactName().lastIndexOf('.') > 0 ? artifact.getArtifactName()
888 .substring(0, artifact.getArtifactName().lastIndexOf('.')) : artifact.getArtifactName());
889 artifact.setArtifactLabel(ValidationUtils.normalizeArtifactLabel(artifact.getArtifactName()));
890 artifact.setDescription(ARTIFACT_CREATED_FROM_CSAR);
891 artifact.setIsFromCsar(true);
892 artifact.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(entry.getValue()));
898 public static final class NonMetaArtifactInfo {
900 private String artifactUniqueId;
901 private final String path;
902 private final String artifactName;
903 private final String displayName;
904 private final String artifactLabel;
905 private final String artifactType;
906 private final ArtifactGroupTypeEnum artifactGroupType;
907 private final String payloadData;
908 private final String artifactChecksum;
909 private final boolean isFromCsar;
911 public NonMetaArtifactInfo(final String artifactName, final String path, final String artifactType,
912 final ArtifactGroupTypeEnum artifactGroupType, final byte[] payloadData,
913 final String artifactUniqueId, final boolean isFromCsar) {
916 this.isFromCsar = isFromCsar;
917 this.artifactName = ValidationUtils.normalizeFileName(artifactName);
918 this.artifactType = artifactType;
919 this.artifactGroupType = artifactGroupType;
920 final int pointIndex = artifactName.lastIndexOf('.');
921 if (pointIndex > 0) {
922 displayName = artifactName.substring(0, pointIndex);
924 displayName = artifactName;
926 this.artifactLabel = ValidationUtils.normalizeArtifactLabel(artifactName);
927 if (payloadData == null) {
928 this.payloadData = null;
929 this.artifactChecksum = null;
931 this.payloadData = Base64.encodeBase64String(payloadData);
932 this.artifactChecksum = GeneralUtility.calculateMD5Base64EncodedByByteArray(payloadData);
934 this.artifactUniqueId = artifactUniqueId;
940 * This method checks the artifact GroupType & Artifact Type. <br>
941 * if there is any problem warning messages are added to collectedWarningMessages
943 * @param artifactPath
944 * @param collectedWarningMessages
947 public static Either<NonMetaArtifactInfo, Boolean> validateNonMetaArtifact(
950 Map<String, Set<List<String>>> collectedWarningMessages
953 String[] parsedArtifactPath = artifactPath.split(PATH_DELIMITER);
954 String groupType = parsedArtifactPath[1];
955 String receivedTypeName = parsedArtifactPath[2];
956 String artifactFileNameType = parsedArtifactPath[3];
958 return detectArtifactGroupType(groupType, collectedWarningMessages)
959 .left().bind(artifactGroupType -> {
960 String artifactType =
961 detectArtifactTypeVF(artifactGroupType, receivedTypeName, collectedWarningMessages);
963 return Either.left(new NonMetaArtifactInfo(
964 artifactFileNameType, artifactPath, artifactType,
965 artifactGroupType, payloadData, null, true
968 } catch (Exception e) {
969 log.debug("detectArtifactGroupType failed with exception", e);
970 return Either.right(false);
974 private static String detectArtifactTypeVFC(ArtifactGroupTypeEnum artifactGroupType, String receivedTypeName, String parentVfName, Map<String, Set<List<String>>> collectedWarningMessages) {
975 String warningMessage = "Warning - artifact type {} that was provided for VFC {} is not recognized.";
976 return detectArtifactType(artifactGroupType, receivedTypeName, warningMessage, collectedWarningMessages, parentVfName);
979 private static String detectArtifactTypeVF(ArtifactGroupTypeEnum artifactGroupType, String receivedTypeName, Map<String, Set<List<String>>> collectedWarningMessages) {
980 String warningMessage = "Warning - artifact type {} that was provided for VF is not recognized.";
981 return detectArtifactType(artifactGroupType, receivedTypeName, warningMessage, collectedWarningMessages);
984 private static String detectArtifactType(final ArtifactGroupTypeEnum artifactGroupType,
985 final String receivedTypeName, final String warningMessage,
986 final Map<String, Set<List<String>>> collectedWarningMessages,
987 final String... arguments) {
988 final ArtifactConfiguration artifactConfiguration =
989 ArtifactConfigManager.getInstance()
990 .find(receivedTypeName, artifactGroupType, ComponentType.RESOURCE)
993 if (artifactConfiguration == null) {
994 final List<String> messageArguments = new ArrayList<>();
995 messageArguments.add(receivedTypeName);
996 messageArguments.addAll(Arrays.asList(arguments));
997 if (!collectedWarningMessages.containsKey(warningMessage)) {
998 final Set<List<String>> messageArgumentLists = new HashSet<>();
999 messageArgumentLists.add(messageArguments);
1000 collectedWarningMessages.put(warningMessage, messageArgumentLists);
1002 collectedWarningMessages.get(warningMessage).add(messageArguments);
1006 return artifactConfiguration == null ? ArtifactTypeEnum.OTHER.getType() : receivedTypeName;
1009 private Either<ZipOutputStream, ResponseFormat> writeAllFilesToCsar(Component mainComponent, CsarDefinition csarDefinition, ZipOutputStream zipstream, boolean isInCertificationRequest) throws IOException{
1010 ComponentArtifacts componentArtifacts = csarDefinition.getComponentArtifacts();
1012 Either<ZipOutputStream, ResponseFormat> writeComponentArtifactsToSpecifiedPath = writeComponentArtifactsToSpecifiedPath(mainComponent, componentArtifacts, zipstream, ARTIFACTS_PATH, isInCertificationRequest);
1014 if(writeComponentArtifactsToSpecifiedPath.isRight()){
1015 return Either.right(writeComponentArtifactsToSpecifiedPath.right().value());
1018 ComponentTypeArtifacts mainTypeAndCIArtifacts = componentArtifacts.getMainTypeAndCIArtifacts();
1019 writeComponentArtifactsToSpecifiedPath = writeArtifactsInfoToSpecifiedPath(mainComponent, mainTypeAndCIArtifacts.getComponentArtifacts(), zipstream, ARTIFACTS_PATH, isInCertificationRequest);
1021 if(writeComponentArtifactsToSpecifiedPath.isRight()){
1022 return Either.right(writeComponentArtifactsToSpecifiedPath.right().value());
1025 Map<String, ArtifactsInfo> componentInstancesArtifacts = mainTypeAndCIArtifacts.getComponentInstancesArtifacts();
1026 Set<String> keySet = componentInstancesArtifacts.keySet();
1028 String currentPath = ARTIFACTS_PATH + RESOURCES_PATH;
1029 for (String keyAssetName : keySet) {
1030 ArtifactsInfo artifactsInfo = componentInstancesArtifacts.get(keyAssetName);
1031 String pathWithAssetName = currentPath + keyAssetName + PATH_DELIMITER;
1032 writeComponentArtifactsToSpecifiedPath = writeArtifactsInfoToSpecifiedPath(mainComponent, artifactsInfo, zipstream, pathWithAssetName, isInCertificationRequest);
1034 if(writeComponentArtifactsToSpecifiedPath.isRight()){
1035 return Either.right(writeComponentArtifactsToSpecifiedPath.right().value());
1038 writeComponentArtifactsToSpecifiedPath = writeOperationsArtifactsToCsar(mainComponent, zipstream);
1040 if (writeComponentArtifactsToSpecifiedPath.isRight()) {
1041 return Either.right(writeComponentArtifactsToSpecifiedPath.right().value());
1043 return Either.left(zipstream);
1046 private Either<ZipOutputStream, ResponseFormat> writeOperationsArtifactsToCsar(Component component,
1047 ZipOutputStream zipstream) {
1048 if (checkComponentBeforeOperation(component)) {
1049 return Either.left(zipstream);
1051 final Map<String, InterfaceDefinition> interfaces = ((Resource) component).getInterfaces();
1052 for (Map.Entry<String, InterfaceDefinition> interfaceEntry : interfaces.entrySet()) {
1053 for (OperationDataDefinition operation : interfaceEntry.getValue().getOperations().values()) {
1055 if (checkComponentBeforeWrite(component, interfaceEntry, operation)) {
1058 final String artifactUUID = operation.getImplementation().getArtifactUUID();
1059 if (artifactUUID == null) {
1062 final Either<byte[], ActionStatus> artifactFromCassandra = getFromCassandra(artifactUUID);
1063 final String artifactName = operation.getImplementation().getArtifactName();
1064 if (artifactFromCassandra.isRight()) {
1065 log.error(ARTIFACT_NAME_UNIQUE_ID, artifactName, artifactUUID);
1066 log.error("Failed to get {} payload from DB reason: {}", artifactName,
1067 artifactFromCassandra.right().value());
1068 return Either.right(componentsUtils.getResponseFormat(
1069 ActionStatus.ARTIFACT_PAYLOAD_NOT_FOUND_DURING_CSAR_CREATION, "Resource",
1070 component.getUniqueId(), artifactName, artifactUUID));
1072 final byte[] payloadData = artifactFromCassandra.left().value();
1073 zipstream.putNextEntry(new ZipEntry(OperationArtifactUtil.createOperationArtifactPath(
1074 component, null, operation, true)));
1075 zipstream.write(payloadData);
1076 } catch (IOException e) {
1077 log.error("Component Name {}, Interface Name {}, Operation Name {}", component.getNormalizedName(),
1078 interfaceEntry.getKey(), operation.getName());
1079 log.error("Error while writing the operation's artifacts to the CSAR " + "{}", e);
1080 return Either.right(componentsUtils
1081 .getResponseFormat(ActionStatus.ERROR_DURING_CSAR_CREATION, "Resource",
1082 component.getUniqueId()));
1086 return Either.left(zipstream);
1089 private boolean checkComponentBeforeWrite(Component component, Entry<String, InterfaceDefinition> interfaceEntry, OperationDataDefinition operation) {
1090 final ArtifactDataDefinition implementation = operation.getImplementation();
1091 if (Objects.isNull(implementation)) {
1092 log.debug("Component Name {}, Interface Id {}, Operation Name {} - no Operation Implementation found",
1093 component.getNormalizedName(), interfaceEntry.getValue().getUniqueId(),
1094 operation.getName());
1097 final String artifactName = implementation.getArtifactName();
1098 if (Objects.isNull(artifactName)) {
1099 log.debug("Component Name {}, Interface Id {}, Operation Name {} - no artifact found",
1100 component.getNormalizedName(), interfaceEntry.getValue().getUniqueId(),
1101 operation.getName());
1104 if (OperationArtifactUtil.artifactNameIsALiteralValue(artifactName)) {
1105 log.debug("Component Name {}, Interface Id {}, Operation Name {} - artifact name is a literal value rather than an SDC artifact",
1106 component.getNormalizedName(), interfaceEntry.getValue().getUniqueId(),
1107 operation.getName());
1113 private boolean checkComponentBeforeOperation(Component component) {
1114 if (component instanceof Service) {
1117 if (Objects.isNull(((Resource) component).getInterfaces())) {
1118 log.debug("Component Name {}- no interfaces found", component.getNormalizedName());
1124 private Either<ZipOutputStream, ResponseFormat> writeComponentArtifactsToSpecifiedPath(Component mainComponent, ComponentArtifacts componentArtifacts, ZipOutputStream zipstream,
1125 String currentPath, boolean isInCertificationRequest) throws IOException {
1126 Map<String, ComponentTypeArtifacts> componentTypeArtifacts = componentArtifacts.getComponentTypeArtifacts();
1128 //<Inner Asset TOSCA name (e.g. VFC name)> folder name: <Inner Asset TOSCA name (e.g. VFC name)>_v<version>.
1129 //E.g. "org.openecomp.resource.vf.vipr_atm_v1.0"
1130 Set<String> componentTypeArtifactsKeys = componentTypeArtifacts.keySet();
1131 for (String keyAssetName : componentTypeArtifactsKeys) {
1132 ComponentTypeArtifacts componentInstanceArtifacts = componentTypeArtifacts.get(keyAssetName);
1133 ArtifactsInfo componentArtifacts2 = componentInstanceArtifacts.getComponentArtifacts();
1134 String pathWithAssetName = currentPath + keyAssetName + PATH_DELIMITER;
1135 Either<ZipOutputStream, ResponseFormat> writeArtifactsInfoToSpecifiedPath = writeArtifactsInfoToSpecifiedPath(mainComponent, componentArtifacts2, zipstream, pathWithAssetName, isInCertificationRequest);
1137 if(writeArtifactsInfoToSpecifiedPath.isRight()){
1138 return writeArtifactsInfoToSpecifiedPath;
1142 return Either.left(zipstream);
1145 private Either<ZipOutputStream, ResponseFormat> writeArtifactsInfoToSpecifiedPath(final Component mainComponent,
1146 final ArtifactsInfo currArtifactsInfo,
1147 final ZipOutputStream zip,
1149 final boolean isInCertificationRequest) throws IOException {
1151 final Map<ArtifactGroupTypeEnum, Map<String, List<ArtifactDefinition>>> artifactsInfo =
1152 currArtifactsInfo.getArtifactsInfo();
1153 for (final ArtifactGroupTypeEnum artifactGroupTypeEnum : artifactsInfo.keySet()) {
1154 final String groupTypeFolder =
1155 path + WordUtils.capitalizeFully(artifactGroupTypeEnum.getType()) + PATH_DELIMITER;
1157 final Map<String, List<ArtifactDefinition>> artifactTypesMap = artifactsInfo.get(artifactGroupTypeEnum);
1159 for (final String artifactType : artifactTypesMap.keySet()) {
1160 final List<ArtifactDefinition> artifactDefinitionList = artifactTypesMap.get(artifactType);
1161 String artifactTypeFolder = groupTypeFolder + artifactType + PATH_DELIMITER;
1163 if (ArtifactTypeEnum.WORKFLOW.getType().equals(artifactType) && path
1164 .contains(ARTIFACTS_PATH + RESOURCES_PATH)) {
1165 // Ignore this packaging as BPMN artifacts needs to be packaged in different manner
1168 if (ArtifactTypeEnum.WORKFLOW.getType().equals(artifactType)) {
1169 artifactTypeFolder += OperationArtifactUtil.BPMN_ARTIFACT_PATH + File.separator;
1172 // TODO: We should not do this but in order to keep this refactoring small enough,
1173 // we'll leave this as is for now
1174 List<ArtifactDefinition> collect =
1175 filterArtifactDefinitionToZip(mainComponent, artifactDefinitionList, isInCertificationRequest)
1176 .collect(Collectors.toList());
1177 for (ArtifactDefinition ad : collect) {
1178 zip.putNextEntry(new ZipEntry(artifactTypeFolder + ad.getArtifactName()));
1179 zip.write(ad.getPayloadData());
1183 return Either.left(zip);
1186 private Stream<ArtifactDefinition> filterArtifactDefinitionToZip(Component mainComponent,
1187 List<ArtifactDefinition> artifactDefinitionList, boolean isInCertificationRequest) {
1188 return artifactDefinitionList
1190 .filter(shouldBeInZip(isInCertificationRequest, mainComponent))
1191 .map(this::fetchPayLoadData)
1192 .filter(Either::isLeft)
1193 .map(e -> e.left().value());
1196 private Predicate<ArtifactDefinition> shouldBeInZip(boolean isInCertificationRequest, Component component) {
1197 return artifactDefinition ->
1198 !(!isInCertificationRequest
1199 && component.isService()
1200 && artifactDefinition.isHeatEnvType()
1201 || artifactDefinition.hasNoMandatoryEsId());
1204 private Either<ArtifactDefinition, ActionStatus> fetchPayLoadData(ArtifactDefinition ad) {
1205 byte[] payloadData = ad.getPayloadData();
1206 if(payloadData == null) {
1207 return getFromCassandra(ad.getEsId())
1211 }).right().map(as -> {
1212 log.debug(ARTIFACT_NAME_UNIQUE_ID, ad.getArtifactName(), ad.getUniqueId());
1213 log.debug("Failed to get {} payload from DB reason: {}", ad.getArtifactName(), as);
1217 return Either.left(ad);
1221 /************************************ Artifacts Structure ******************************************************************/
1223 * The artifacts Definition saved by their structure
1225 private class ArtifactsInfo {
1226 //Key is the type of artifacts(Informational/Deployment)
1227 //Value is a map between an artifact type and a list of all artifacts of this type
1228 private Map<ArtifactGroupTypeEnum, Map<String, List<ArtifactDefinition>>> artifactsInfoField;
1230 public ArtifactsInfo() {
1231 this.artifactsInfoField = new EnumMap<>(ArtifactGroupTypeEnum.class);
1234 public Map<ArtifactGroupTypeEnum, Map<String, List<ArtifactDefinition>>> getArtifactsInfo() {
1235 return artifactsInfoField;
1238 public void addArtifactsToGroup(ArtifactGroupTypeEnum artifactGroup,
1239 Map<String, List<ArtifactDefinition>> artifactsDefinition) {
1240 if (artifactsInfoField.get(artifactGroup) == null) {
1241 artifactsInfoField.put(artifactGroup, artifactsDefinition);
1243 Map<String, List<ArtifactDefinition>> artifactTypeEnumListMap =
1244 artifactsInfoField.get(artifactGroup);
1245 artifactTypeEnumListMap.putAll(artifactsDefinition);
1246 artifactsInfoField.put(artifactGroup, artifactTypeEnumListMap);
1251 public boolean isEmpty() {
1252 return artifactsInfoField.isEmpty();
1255 public boolean isNotEmpty() {
1262 * The artifacts of the component and of all its composed instances
1265 private class ComponentTypeArtifacts {
1266 private ArtifactsInfo componentArtifacts; //component artifacts (describes the Informational Deployment folders)
1267 private Map<String, ArtifactsInfo> componentInstancesArtifacts; //artifacts of the composed instances mapped by the resourceInstance normalized name (describes the Resources folder)
1269 public ComponentTypeArtifacts() {
1270 componentArtifacts = new ArtifactsInfo();
1271 componentInstancesArtifacts = new HashMap<>();
1274 public ArtifactsInfo getComponentArtifacts() {
1275 return componentArtifacts;
1277 public void setComponentArtifacts(ArtifactsInfo artifactsInfo) {
1278 this.componentArtifacts = artifactsInfo;
1280 public Map<String, ArtifactsInfo> getComponentInstancesArtifacts() {
1281 return componentInstancesArtifacts;
1283 public void setComponentInstancesArtifacts(Map<String, ArtifactsInfo> componentInstancesArtifacts) {
1284 this.componentInstancesArtifacts = componentInstancesArtifacts;
1287 public void addComponentInstancesArtifacts(String normalizedName, ArtifactsInfo artifactsInfo) {
1288 componentInstancesArtifacts.put(normalizedName, artifactsInfo);
1293 private class ComponentArtifacts {
1294 //artifacts of the component and CI's artifacts contained in it's composition (represents Informational, Deployment & Resource folders of main component)
1295 private ComponentTypeArtifacts mainTypeAndCIArtifacts;
1296 //artifacts of all component types mapped by their tosca name
1297 private Map<String, ComponentTypeArtifacts> componentTypeArtifacts;
1299 public ComponentArtifacts(){
1300 mainTypeAndCIArtifacts = new ComponentTypeArtifacts();
1301 componentTypeArtifacts = new HashMap<>();
1304 public ComponentTypeArtifacts getMainTypeAndCIArtifacts() {
1305 return mainTypeAndCIArtifacts;
1308 public void setMainTypeAndCIArtifacts(ComponentTypeArtifacts componentInstanceArtifacts) {
1309 this.mainTypeAndCIArtifacts = componentInstanceArtifacts;
1312 public Map<String, ComponentTypeArtifacts> getComponentTypeArtifacts() {
1313 return componentTypeArtifacts;
1316 public void setComponentTypeArtifacts(Map<String, ComponentTypeArtifacts> componentTypeArtifacts) {
1317 this.componentTypeArtifacts = componentTypeArtifacts;
1321 private class CsarDefinition {
1322 private ComponentArtifacts componentArtifacts;
1324 // add list of tosca artifacts and meta describes CSAR zip root
1326 public CsarDefinition(ComponentArtifacts componentArtifacts) {
1327 this.componentArtifacts = componentArtifacts;
1330 public ComponentArtifacts getComponentArtifacts() {
1331 return componentArtifacts;
1335 /************************************ Artifacts Structure END******************************************************************/
1337 private Either<CsarDefinition,ResponseFormat> collectComponentCsarDefinition(Component component){
1338 ComponentArtifacts componentArtifacts = new ComponentArtifacts();
1339 Component updatedComponent = component;
1341 //get service to receive the AII artifacts uploaded to the service
1342 if (updatedComponent.getComponentType() == ComponentTypeEnum.SERVICE) {
1343 Either<Service, StorageOperationStatus> getServiceResponse = toscaOperationFacade.getToscaElement(updatedComponent.getUniqueId());
1345 if(getServiceResponse.isRight()){
1346 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getServiceResponse.right().value());
1347 return Either.right(componentsUtils.getResponseFormat(actionStatus));
1350 updatedComponent = getServiceResponse.left().value();
1353 //find the artifacts of the main component, it would have its composed instances artifacts in a separate folder
1354 ComponentTypeArtifacts componentInstanceArtifacts = new ComponentTypeArtifacts();
1355 ArtifactsInfo artifactsInfo = collectComponentArtifacts(updatedComponent);
1356 componentInstanceArtifacts.setComponentArtifacts(artifactsInfo);
1357 componentArtifacts.setMainTypeAndCIArtifacts(componentInstanceArtifacts);
1359 Map<String,ComponentTypeArtifacts> resourceTypeArtifacts = componentArtifacts.getComponentTypeArtifacts(); //artifacts mapped by the component type(tosca name+version)
1360 //get the component instances
1361 List<ComponentInstance> componentInstances = updatedComponent.getComponentInstances();
1362 if (componentInstances!=null){
1363 for (ComponentInstance componentInstance:componentInstances){
1364 //call recursive to find artifacts for all the path
1365 Either<Boolean, ResponseFormat> collectComponentInstanceArtifacts = collectComponentInstanceArtifacts(
1366 updatedComponent, componentInstance, resourceTypeArtifacts, componentInstanceArtifacts);
1367 if (collectComponentInstanceArtifacts.isRight()){
1368 return Either.right(collectComponentInstanceArtifacts.right().value());
1373 if(log.isDebugEnabled()){
1374 printResult(componentArtifacts,updatedComponent.getName());
1377 return Either.left(new CsarDefinition(componentArtifacts));
1380 private void printResult(ComponentArtifacts componentArtifacts, String name) {
1381 StringBuilder result = new StringBuilder();
1382 result.append("Artifacts of main component " + name + "\n");
1383 ComponentTypeArtifacts componentInstanceArtifacts = componentArtifacts.getMainTypeAndCIArtifacts();
1384 printArtifacts(componentInstanceArtifacts);
1385 result.append("Type Artifacts\n");
1386 for (Map.Entry<String, ComponentTypeArtifacts> typeArtifacts:componentArtifacts.getComponentTypeArtifacts().entrySet()){
1387 result.append("Folder " + typeArtifacts.getKey() + "\n");
1388 result.append(printArtifacts(typeArtifacts.getValue()));
1391 if(log.isDebugEnabled()){
1392 log.debug(result.toString());
1396 private String printArtifacts(ComponentTypeArtifacts componentInstanceArtifacts) {
1397 StringBuilder result = new StringBuilder();
1398 ArtifactsInfo artifactsInfo = componentInstanceArtifacts.getComponentArtifacts();
1399 Map<ArtifactGroupTypeEnum, Map<String, List<ArtifactDefinition>>> componentArtifacts = artifactsInfo.getArtifactsInfo();
1400 printArtifacts(componentArtifacts);
1401 result = result.append("Resources\n");
1402 for (Map.Entry<String, ArtifactsInfo> resourceInstance:componentInstanceArtifacts.getComponentInstancesArtifacts().entrySet()){
1403 result.append("Folder" + resourceInstance.getKey() + "\n");
1404 result.append(printArtifacts(resourceInstance.getValue().getArtifactsInfo()));
1407 return result.toString();
1410 private String printArtifacts(Map<ArtifactGroupTypeEnum, Map<String, List<ArtifactDefinition>>> componetArtifacts) {
1411 StringBuilder result = new StringBuilder();
1412 for (Map.Entry<ArtifactGroupTypeEnum, Map<String, List<ArtifactDefinition>>> artifactGroup:componetArtifacts.entrySet()){
1413 result.append(" " + artifactGroup.getKey().getType());
1414 for (Map.Entry<String, List<ArtifactDefinition>> groupArtifacts:artifactGroup.getValue().entrySet()){
1415 result.append(" " + groupArtifacts.getKey());
1416 for (ArtifactDefinition artifact:groupArtifacts.getValue()){
1417 result.append(" " + artifact.getArtifactDisplayName());
1422 return result.toString();
1425 private ComponentTypeArtifacts collectComponentTypeArtifacts(
1426 Component fetchedComponent
1428 ArtifactsInfo componentArtifacts = collectComponentArtifacts(fetchedComponent);
1429 ComponentTypeArtifacts componentArtifactsInfo = new ComponentTypeArtifacts();
1430 if (componentArtifacts.isNotEmpty()) {
1431 componentArtifactsInfo.setComponentArtifacts(componentArtifacts);
1433 return componentArtifactsInfo;
1436 private Either<Boolean, ResponseFormat> collectComponentInstanceArtifacts(Component parentComponent,ComponentInstance componentInstance,
1437 Map<String, ComponentTypeArtifacts> resourcesTypeArtifacts,ComponentTypeArtifacts instanceArtifactsLocation) {
1438 //1. get the component instance component
1439 String componentUid;
1440 if (componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy) {
1441 componentUid = componentInstance.getSourceModelUid();
1444 componentUid = componentInstance.getComponentUid();
1446 Either<Component, StorageOperationStatus> component = toscaOperationFacade.getToscaElement(componentUid);
1447 if (component.isRight()) {
1448 log.error("Failed to fetch resource with id {} for instance {}",componentUid, parentComponent.getUUID());
1449 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ASSET_NOT_FOUND_DURING_CSAR_CREATION,
1450 parentComponent.getComponentType().getValue(), parentComponent.getUUID(),
1451 componentInstance.getOriginType().getComponentType().getValue(), componentUid));
1453 Component fetchedComponent = component.left().value();
1455 //2. fill the artifacts for the current component parent type
1456 String toscaComponentName =
1457 componentInstance.getToscaComponentName() + "_v" + componentInstance.getComponentVersion();
1459 // if there are no artifacts for this component type we need to fetch and build them
1460 ComponentTypeArtifacts componentParentArtifacts = Optional
1461 .ofNullable(resourcesTypeArtifacts.get(toscaComponentName))
1462 .orElseGet(() -> collectComponentTypeArtifacts(fetchedComponent));
1464 if (componentParentArtifacts.getComponentArtifacts().isNotEmpty()) {
1465 resourcesTypeArtifacts.put(toscaComponentName, componentParentArtifacts);
1468 //3. find the artifacts specific to the instance
1469 Map<String, List<ArtifactDefinition>> componentInstanceSpecificInformationalArtifacts =
1470 getComponentInstanceSpecificArtifacts(componentInstance.getArtifacts(),
1471 componentParentArtifacts.getComponentArtifacts().getArtifactsInfo(), ArtifactGroupTypeEnum.INFORMATIONAL);
1472 Map<String, List<ArtifactDefinition>> componentInstanceSpecificDeploymentArtifacts =
1473 getComponentInstanceSpecificArtifacts(componentInstance.getDeploymentArtifacts(),
1474 componentParentArtifacts.getComponentArtifacts().getArtifactsInfo(), ArtifactGroupTypeEnum.DEPLOYMENT);
1476 //4. add the instances artifacts to the component type
1477 ArtifactsInfo artifactsInfo = new ArtifactsInfo();
1478 if (!componentInstanceSpecificInformationalArtifacts.isEmpty()){
1479 artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.INFORMATIONAL, componentInstanceSpecificInformationalArtifacts);
1481 if (!componentInstanceSpecificDeploymentArtifacts.isEmpty()){
1482 artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.DEPLOYMENT, componentInstanceSpecificDeploymentArtifacts);
1484 if (!artifactsInfo.isEmpty()){
1485 instanceArtifactsLocation.addComponentInstancesArtifacts(componentInstance.getNormalizedName(), artifactsInfo);
1488 //5. do the same for all the component instances
1489 List<ComponentInstance> componentInstances = fetchedComponent.getComponentInstances();
1490 if (componentInstances!=null){
1491 for (ComponentInstance childComponentInstance:componentInstances){
1492 Either<Boolean, ResponseFormat> collectComponentInstanceArtifacts = collectComponentInstanceArtifacts(
1493 fetchedComponent, childComponentInstance, resourcesTypeArtifacts, componentParentArtifacts);
1494 if (collectComponentInstanceArtifacts.isRight()){
1495 return collectComponentInstanceArtifacts;
1500 return Either.left(true);
1503 public String getVersionFirstThreeOctets() {
1504 return versionFirstThreeOctets;
1507 public void setVersionFirstThreeOctets(String versionFirstThreeOctetes) {
1508 this.versionFirstThreeOctets = versionFirstThreeOctetes;
1510 private Map<String, List<ArtifactDefinition>> getComponentInstanceSpecificArtifacts(Map<String, ArtifactDefinition> componentArtifacts,
1511 Map<ArtifactGroupTypeEnum, Map<String, List<ArtifactDefinition>>> componentTypeArtifacts, ArtifactGroupTypeEnum artifactGroupTypeEnum) {
1512 Map<String, List<ArtifactDefinition>> parentArtifacts = componentTypeArtifacts.get(artifactGroupTypeEnum); //the artfiacts of the component itself and not the instance
1514 Map<String, List<ArtifactDefinition>> artifactsByTypeOfComponentInstance = new HashMap<>();
1515 if (componentArtifacts!=null){
1516 for (ArtifactDefinition artifact:componentArtifacts.values()){
1517 List<ArtifactDefinition> parentArtifactsByType = null;
1518 if (parentArtifacts!=null){
1519 parentArtifactsByType = parentArtifacts.get(artifact.getArtifactType());
1521 //the artifact is of instance
1522 if (parentArtifactsByType == null || !parentArtifactsByType.contains(artifact)){
1523 List<ArtifactDefinition> typeArtifacts = artifactsByTypeOfComponentInstance.get(artifact.getArtifactType());
1524 if (typeArtifacts == null){
1525 typeArtifacts = new ArrayList<>();
1526 artifactsByTypeOfComponentInstance.put(artifact.getArtifactType(), typeArtifacts);
1528 typeArtifacts.add(artifact);
1533 return artifactsByTypeOfComponentInstance;
1536 private ArtifactsInfo collectComponentArtifacts(Component component) {
1537 Map<String, ArtifactDefinition> informationalArtifacts = component.getArtifacts();
1538 Map<String, List<ArtifactDefinition>> informationalArtifactsByType = collectGroupArtifacts(informationalArtifacts);
1539 Map<String, ArtifactDefinition> deploymentArtifacts = component.getDeploymentArtifacts();
1540 Map<String, List<ArtifactDefinition>> deploymentArtifactsByType = collectGroupArtifacts(deploymentArtifacts);
1541 Map<String, ArtifactDefinition> interfaceOperationArtifacts =
1542 OperationArtifactUtil.getDistinctInterfaceOperationArtifactsByName(component);
1543 Map<String, List<ArtifactDefinition>> interfaceOperationArtifactsByType = collectGroupArtifacts(
1544 interfaceOperationArtifacts);
1545 ArtifactsInfo artifactsInfo = new ArtifactsInfo();
1546 if (!informationalArtifactsByType.isEmpty()){
1547 artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.INFORMATIONAL, informationalArtifactsByType);
1549 if (!deploymentArtifactsByType.isEmpty() ){
1550 artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.DEPLOYMENT, deploymentArtifactsByType);
1552 //Add component interface operation artifacts
1553 if(MapUtils.isNotEmpty(interfaceOperationArtifacts)) {
1554 artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.DEPLOYMENT, interfaceOperationArtifactsByType);
1557 return artifactsInfo;
1560 private Map<String, List<ArtifactDefinition>> collectGroupArtifacts(
1561 final Map<String, ArtifactDefinition> componentArtifacts) {
1562 final Map<String, List<ArtifactDefinition>> artifactsByType = new HashMap<>();
1563 for (final ArtifactDefinition artifact : componentArtifacts.values()) {
1564 if (artifact.getArtifactUUID() != null) {
1565 artifactsByType.putIfAbsent(artifact.getArtifactType(), new ArrayList<>());
1566 final List<ArtifactDefinition> typeArtifacts = artifactsByType.get(artifact.getArtifactType());
1567 typeArtifacts.add(artifact);
1570 return artifactsByType;