2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2023 Nordix Foundation. 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=========================================================
20 package org.openecomp.sdc.be.tosca;
22 import static org.openecomp.sdc.be.dao.api.ActionStatus.ARTIFACT_PAYLOAD_NOT_FOUND_DURING_CSAR_CREATION;
23 import static org.openecomp.sdc.be.dao.api.ActionStatus.ERROR_DURING_CSAR_CREATION;
24 import static org.openecomp.sdc.be.tosca.ComponentCache.MergeStrategy.overwriteIfSameVersions;
25 import static org.openecomp.sdc.be.tosca.FJToVavrHelper.Try0.fromEither;
26 import static org.openecomp.sdc.be.tosca.FJToVavrHelper.Try0.javaListToVavrList;
27 import static org.openecomp.sdc.common.api.Constants.ADDITIONAL_TYPE_DEFINITIONS;
29 import com.google.common.primitives.Bytes;
31 import fj.data.Either;
32 import io.vavr.Tuple2;
33 import io.vavr.control.Try;
34 import java.io.BufferedOutputStream;
35 import java.io.ByteArrayInputStream;
37 import java.io.IOException;
38 import java.nio.charset.StandardCharsets;
39 import java.nio.file.Path;
40 import java.nio.file.Paths;
41 import java.text.SimpleDateFormat;
42 import java.util.ArrayList;
43 import java.util.Collections;
44 import java.util.Date;
45 import java.util.EnumMap;
46 import java.util.HashMap;
47 import java.util.HashSet;
48 import java.util.List;
50 import java.util.Map.Entry;
51 import java.util.Objects;
52 import java.util.Optional;
54 import java.util.TimeZone;
55 import java.util.function.Function;
56 import java.util.function.Predicate;
57 import java.util.function.Supplier;
58 import java.util.regex.Matcher;
59 import java.util.regex.Pattern;
60 import java.util.stream.Collectors;
61 import java.util.stream.Stream;
62 import java.util.zip.ZipEntry;
63 import java.util.zip.ZipInputStream;
64 import java.util.zip.ZipOutputStream;
65 import org.apache.commons.collections.CollectionUtils;
66 import org.apache.commons.collections.MapUtils;
67 import org.apache.commons.io.output.ByteArrayOutputStream;
68 import org.apache.commons.lang.StringUtils;
69 import org.apache.commons.lang3.tuple.ImmutableTriple;
70 import org.apache.commons.lang3.tuple.Triple;
71 import org.apache.commons.text.WordUtils;
72 import org.onap.sdc.tosca.services.YamlUtil;
73 import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException;
74 import org.openecomp.sdc.be.config.CategoryBaseTypeConfig;
75 import org.openecomp.sdc.be.config.ConfigurationManager;
76 import org.openecomp.sdc.be.dao.api.ActionStatus;
77 import org.openecomp.sdc.be.dao.cassandra.ArtifactCassandraDao;
78 import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus;
79 import org.openecomp.sdc.be.dao.cassandra.SdcSchemaFilesCassandraDao;
80 import org.openecomp.sdc.be.data.model.ToscaImportByModel;
81 import org.openecomp.sdc.be.datatypes.components.ResourceMetadataDataDefinition;
82 import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
83 import org.openecomp.sdc.be.datatypes.elements.OperationDataDefinition;
84 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
85 import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
86 import org.openecomp.sdc.be.impl.ComponentsUtils;
87 import org.openecomp.sdc.be.model.ArtifactDefinition;
88 import org.openecomp.sdc.be.model.Component;
89 import org.openecomp.sdc.be.model.ComponentInstance;
90 import org.openecomp.sdc.be.model.InterfaceDefinition;
91 import org.openecomp.sdc.be.model.LifecycleStateEnum;
92 import org.openecomp.sdc.be.model.Resource;
93 import org.openecomp.sdc.be.model.Service;
94 import org.openecomp.sdc.be.model.category.CategoryDefinition;
95 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade;
96 import org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter;
97 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
98 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
99 import org.openecomp.sdc.be.model.operations.impl.ModelOperation;
100 import org.openecomp.sdc.be.plugins.CsarEntryGenerator;
101 import org.openecomp.sdc.be.resources.data.DAOArtifactData;
102 import org.openecomp.sdc.be.tosca.utils.OperationArtifactUtil;
103 import org.openecomp.sdc.be.utils.TypeUtils;
104 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
105 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
106 import org.openecomp.sdc.common.impl.ExternalConfiguration;
107 import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode;
108 import org.openecomp.sdc.common.util.GeneralUtility;
109 import org.openecomp.sdc.common.zip.ZipUtils;
110 import org.openecomp.sdc.exception.ResponseFormat;
111 import org.slf4j.Logger;
112 import org.slf4j.LoggerFactory;
113 import org.springframework.beans.factory.annotation.Autowired;
114 import org.yaml.snakeyaml.DumperOptions;
115 import org.yaml.snakeyaml.DumperOptions.FlowStyle;
116 import org.yaml.snakeyaml.Yaml;
119 * Generates a Network Service CSAR based on a SERVICE component and wraps it in a SDC CSAR entry.
121 @org.springframework.stereotype.Component("commonCsarGenerator")
122 public class CommonCsarGenerator {
124 private static final Logger LOGGER = LoggerFactory.getLogger(CommonCsarGenerator.class);
125 public static final String ARTIFACTS_PATH = "Artifacts/";
126 private static final String RESOURCES_PATH = "Resources/";
127 private static final String PATH_DELIMITER = "/";
128 private static final String SERVICE_MANIFEST = "NS.mf";
129 private static final String ARTIFACT_NAME_UNIQUE_ID = "ArtifactName {}, unique ID {}";
130 private static final String TOSCA_META_PATH_FILE_NAME = "TOSCA-Metadata/TOSCA.meta";
131 private static final String TOSCA_META_VERSION = "1.0";
132 private static final String CSAR_VERSION = "1.1";
133 private static final String SDC_VERSION = ExternalConfiguration.getAppVersion();
134 public static final String NODES_YML = "nodes.yml";
135 private static final String CONFORMANCE_LEVEL = ConfigurationManager.getConfigurationManager().getConfiguration().getToscaConformanceLevel();
136 private final ToscaOperationFacade toscaOperationFacade;
137 private final ComponentsUtils componentsUtils;
138 private final ToscaExportHandler toscaExportUtils;
139 private final List<CsarEntryGenerator> generators;
140 private final ArtifactCassandraDao artifactCassandraDao;
141 private final String versionFirstThreeOctets;
142 private final SdcSchemaFilesCassandraDao sdcSchemaFilesCassandraDao;
143 private final ModelOperation modelOperation;
146 public CommonCsarGenerator(
147 final ToscaOperationFacade toscaOperationFacade,
148 final ComponentsUtils componentsUtils,
149 final ToscaExportHandler toscaExportUtils,
150 final List<CsarEntryGenerator> generators,
151 final ArtifactCassandraDao artifactCassandraDao,
152 final SdcSchemaFilesCassandraDao sdcSchemaFilesCassandraDao,
153 final ModelOperation modelOperation) {
154 this.toscaOperationFacade = toscaOperationFacade;
155 this.componentsUtils = componentsUtils;
156 this.toscaExportUtils = toscaExportUtils;
157 this.generators = generators;
158 this.artifactCassandraDao = artifactCassandraDao;
159 this.versionFirstThreeOctets = readVersionFirstThreeOctets();
160 this.sdcSchemaFilesCassandraDao = sdcSchemaFilesCassandraDao;
161 this.modelOperation = modelOperation;
164 private String readVersionFirstThreeOctets() {
165 if (StringUtils.isEmpty(SDC_VERSION)) {
168 // change regex to avoid DoS sonar issue
169 Matcher matcher = Pattern.compile("(?!\\.)(\\d{1,9}(\\.\\d{1,9}){1,9})(?![\\d\\.])").matcher(SDC_VERSION);
171 return matcher.group(0);
175 * Generates a Network Service CSAR based on a SERVICE component that has category configured in
176 * CategoriesToGenerateNsd enum and wraps it in a SDC CSAR entry.
178 * @param component the component to create the NS CSAR from
179 * @return an entry to be added in the Component CSAR by SDC
181 public Either<ZipOutputStream, ResponseFormat> generateCsarZip(Component component,
184 boolean isInCertificationRequest,
185 boolean isAsdPackage,
186 String definitionsPath,
187 boolean addDependencies,
188 boolean isSkipImports) throws IOException {
189 ArtifactDefinition artifactDef = component.getToscaArtifacts().get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE);
190 Either<ToscaRepresentation, ResponseFormat> toscaRepresentation = fetchToscaRepresentation(component, getFromCS, artifactDef, isSkipImports);
192 // This should not be done but in order to keep the refactoring small enough we stop here.
193 // TODO: Refactor the rest of this function
195 List<Triple<String, String, Component>> dependencies;
196 if (toscaRepresentation.isLeft()) {
197 mainYaml = toscaRepresentation.left().value().getMainYaml();
198 dependencies = toscaRepresentation.left().value().getDependencies().getOrElse(new ArrayList<>());
200 return Either.right(toscaRepresentation.right().value());
202 final String fileName = artifactDef.getArtifactName();
203 final byte[] toscaBlock0Byte =
204 createToscaBlock0(TOSCA_META_VERSION, CSAR_VERSION, component.getCreatorFullName(), fileName, isAsdPackage, definitionsPath).getBytes();
205 zip.putNextEntry(new ZipEntry(TOSCA_META_PATH_FILE_NAME));
206 zip.write(toscaBlock0Byte);
207 zip.putNextEntry(new ZipEntry(definitionsPath + fileName));
209 LifecycleStateEnum lifecycleState = component.getLifecycleState();
210 if (addDependencies) {
211 addServiceMf(component, zip, lifecycleState, isInCertificationRequest, fileName, mainYaml, definitionsPath);
212 //US798487 - Abstraction of complex types
213 if (hasToWriteComponentSubstitutionType(component)) {
214 LOGGER.debug("Component {} is complex - generating abstract type for it..", component.getName());
215 dependencies.addAll(writeComponentInterface(component, zip, fileName, definitionsPath));
217 //UID <cassandraId,filename,component>
218 Either<ZipOutputStream, ResponseFormat> zipOutputStreamOrResponseFormat =
219 getZipOutputStreamResponseFormatEither(zip, dependencies, definitionsPath);
220 if (zipOutputStreamOrResponseFormat != null && zipOutputStreamOrResponseFormat.isRight()) {
221 return zipOutputStreamOrResponseFormat;
224 if (component.getModel() == null) {
225 //retrieve SDC.zip from Cassandra
226 Either<byte[], ResponseFormat> latestSchemaFiles = getLatestSchemaFilesFromCassandra();
227 if (latestSchemaFiles.isRight()) {
228 LOGGER.error("Error retrieving SDC Schema files from cassandra");
229 return Either.right(latestSchemaFiles.right().value());
231 final byte[] schemaFileZip = latestSchemaFiles.left().value();
232 final List<String> nodesFromPackage = findNonRootNodesFromPackage(dependencies);
233 //add files from retrieved SDC.zip to Definitions folder in CSAR
234 addSchemaFilesFromCassandra(zip, schemaFileZip, nodesFromPackage, definitionsPath);
236 //retrieve schema files by model from Cassandra
237 addSchemaFilesByModel(zip, component.getModel(), definitionsPath, addDependencies,
238 dependencies.stream().map(d -> d.getRight()).collect(Collectors.toList()));
240 Either<CsarDefinition, ResponseFormat> collectedComponentCsarDefinition = collectComponentCsarDefinition(component);
241 if (collectedComponentCsarDefinition.isRight()) {
242 return Either.right(collectedComponentCsarDefinition.right().value());
244 if (generators != null) {
245 for (CsarEntryGenerator generator : generators) {
246 LOGGER.debug("Invoking CsarEntryGenerator: {}", generator.getClass().getName());
247 for (Map.Entry<String, byte[]> pluginGeneratedFile : generator.generateCsarEntries(component).entrySet()) {
248 zip.putNextEntry(new ZipEntry(pluginGeneratedFile.getKey()));
249 zip.write(pluginGeneratedFile.getValue());
253 return writeAllFilesToCsar(component, collectedComponentCsarDefinition.left().value(), zip, isInCertificationRequest);
256 private Either<ToscaRepresentation, ResponseFormat> fetchToscaRepresentation(Component component, boolean getFromCS,
257 ArtifactDefinition artifactDef, boolean isSkipImports) {
258 LifecycleStateEnum lifecycleState = component.getLifecycleState();
259 boolean shouldBeFetchedFromCassandra =
260 getFromCS || !(lifecycleState == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN || lifecycleState == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
261 Either<ToscaRepresentation, ResponseFormat> toscaRepresentation =
262 shouldBeFetchedFromCassandra ? fetchToscaRepresentation(artifactDef) : generateToscaRepresentation(component, isSkipImports);
263 return toscaRepresentation.left()
264 .bind(iff(myd -> !myd.getDependencies().isDefined(), myd -> fetchToscaTemplateDependencies(myd.getMainYaml(), component)));
267 private Either<ToscaRepresentation, ResponseFormat> fetchToscaTemplateDependencies(byte[] mainYml, Component component) {
268 return toscaExportUtils.getDependencies(component).right().map(toscaError -> {
269 LOGGER.debug("Failed to retrieve dependencies for component {}, error {}", component.getUniqueId(), toscaError);
270 return componentsUtils.getResponseFormat(componentsUtils.convertFromToscaError(toscaError));
271 }).left().map(tt -> ToscaRepresentation.make(mainYml, tt));
274 private Either<ToscaRepresentation, ResponseFormat> fetchToscaRepresentation(ArtifactDefinition artifactDef) {
275 return getFromCassandra(artifactDef.getEsId()).right().map(as -> {
276 LOGGER.debug(ARTIFACT_NAME_UNIQUE_ID, artifactDef.getArtifactName(), artifactDef.getUniqueId());
277 return componentsUtils.getResponseFormat(as);
278 }).left().map(ToscaRepresentation::make);
281 private Either<byte[], ActionStatus> getFromCassandra(String cassandraId) {
282 return artifactCassandraDao.getArtifact(cassandraId).right().map(operationstatus -> {
283 LOGGER.info("Failed to fetch artifact from Cassandra by id {} error {}.", cassandraId, operationstatus);
284 StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(operationstatus);
285 return componentsUtils.convertFromStorageResponse(storageStatus);
286 }).left().map(DAOArtifactData::getDataAsArray);
289 private static <L, R> F<L, Either<L, R>> iff(Predicate<L> p, Function<L, Either<L, R>> ifTrue) {
290 return l -> p.test(l) ? ifTrue.apply(l) : Either.left(l);
293 private static <A, B> F<A, B> iff(Predicate<A> p, Supplier<B> s, Function<A, B> orElse) {
294 return a -> p.test(a) ? s.get() : orElse.apply(a);
297 private void addServiceMf(Component component, ZipOutputStream zip, LifecycleStateEnum lifecycleState, boolean isInCertificationRequest,
298 String fileName, byte[] mainYaml, String definitionsPath) throws IOException {
300 if ((component.getComponentType() == ComponentTypeEnum.SERVICE) && (lifecycleState != LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT)) {
301 String serviceName = component.getName();
302 String createdBy = component.getCreatorUserId();
303 String serviceVersion;
304 if (isInCertificationRequest) {
305 int tmp = Integer.valueOf(component.getVersion().split("\\.")[0]) + 1;
306 serviceVersion = String.valueOf(tmp) + ".0";
308 serviceVersion = component.getVersion();
310 SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd'T'hh:mm:ss'Z'");
311 format.setTimeZone(TimeZone.getTimeZone("UTC"));
312 Date date = new Date();
313 String releaseTime = format.format(date);
314 if (component.getCategories() == null || component.getCategories().get(0) == null) {
317 String serviceType = component.getCategories().get(0).getName();
318 String description = component.getDescription();
319 String serviceTemplate = definitionsPath + fileName;
320 String hash = GeneralUtility.calculateMD5Base64EncodedByByteArray(mainYaml);
321 String nsMfBlock0 = createNsMfBlock0(serviceName, createdBy, serviceVersion, releaseTime, serviceType, description, serviceTemplate,
323 byte[] nsMfBlock0Byte = nsMfBlock0.getBytes();
324 zip.putNextEntry(new ZipEntry(SERVICE_MANIFEST));
325 zip.write(nsMfBlock0Byte);
329 private String createNsMfBlock0(String serviceName, String createdBy, String serviceVersion, String releaseTime, String serviceType,
330 String description, String serviceTemplate, String hash) {
331 final String block0template = "metadata??\n" + "ns_product_name: %s\n" + "ns_provider_id: %s\n" + "ns_package_version: %s\n" +
332 "ns_release_data_time: %s\n" + "ns_type: %s\n" + "ns_package_description: %s\n\n" + "Source: %s\n" + "Algorithm: MD5\n" + "Hash: %s\n\n";
333 return String.format(block0template, serviceName, createdBy, serviceVersion, releaseTime, serviceType, description, serviceTemplate, hash);
336 private boolean hasToWriteComponentSubstitutionType(final Component component) {
337 final Map<String, CategoryBaseTypeConfig> serviceNodeTypesConfig =
338 ConfigurationManager.getConfigurationManager().getConfiguration().getServiceBaseNodeTypes();
339 List<CategoryDefinition> categories = component.getCategories();
340 if (CollectionUtils.isNotEmpty(categories) && MapUtils.isNotEmpty(serviceNodeTypesConfig)
341 && serviceNodeTypesConfig.get(categories.get(0).getName()) != null) {
342 boolean doNotExtendBaseType = serviceNodeTypesConfig.get(categories.get(0).getName()).isDoNotExtendBaseType();
343 if (doNotExtendBaseType) {
347 if (component instanceof Service) {
348 return !ModelConverter.isAtomicComponent(component) && ((Service) component).isSubstituteCandidate();
350 return !ModelConverter.isAtomicComponent(component);
353 private Either<ZipOutputStream, ResponseFormat> writeComponentInterface(Either<ToscaRepresentation, ToscaError> interfaceRepresentation,
354 ZipOutputStream zip, String fileName, String definitionsPath) {
355 // TODO: This should not be done but we need this to keep the refactoring small enough to be easily reviewable
356 return writeComponentInterface(interfaceRepresentation, fileName, ZipWriter.live(zip), definitionsPath)
357 .map(void0 -> Either.<ZipOutputStream, ResponseFormat>left(zip)).recover(th -> {
358 LOGGER.error("#writeComponentInterface - zip writing failed with error: ", th);
359 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
363 private Try<Void> writeComponentInterface(
364 Either<ToscaRepresentation, ToscaError> interfaceRepresentation, String fileName, ZipWriter zw, String definitionsPath) {
365 Either<byte[], ToscaError> yml = interfaceRepresentation.left()
366 .map(ToscaRepresentation::getMainYaml);
367 return fromEither(yml, ToscaErrorException::new).flatMap(zw.write(definitionsPath + ToscaExportHandler.getInterfaceFilename(fileName)));
370 private List<Triple<String, String, Component>> writeComponentInterface(final Component component, final ZipOutputStream zip,
371 final String fileName, final String definitionsPath) {
372 final Either<ToscaRepresentation, ToscaError> interfaceRepresentation = toscaExportUtils.exportComponentInterface(component, false);
373 writeComponentInterface(interfaceRepresentation, zip, fileName, definitionsPath);
374 return interfaceRepresentation.left().value().getDependencies().getOrElse(new ArrayList<>());
377 private Either<ZipOutputStream, ResponseFormat> getZipOutputStreamResponseFormatEither(ZipOutputStream zip,
378 List<Triple<String, String, Component>> dependencies,
379 String definitionsPath)
382 innerComponentsCache = ComponentCache.overwritable(overwriteIfSameVersions()).onMerge((oldValue, newValue) ->
383 LOGGER.warn("Overwriting component invariantID {} of version {} with a newer version {}", oldValue.getId(),
384 oldValue.getComponentVersion(),
385 newValue.getComponentVersion()));
386 if (dependencies != null && !dependencies.isEmpty()) {
387 for (Triple<String, String, Component> d : dependencies) {
388 String cassandraId = d.getMiddle();
389 Component childComponent = d.getRight();
390 Either<byte[], ResponseFormat> entryData = getEntryData(cassandraId, childComponent).right().map(componentsUtils::getResponseFormat);
391 if (entryData.isRight()) {
392 return Either.right(entryData.right().value());
394 //fill innerComponentsCache
395 String fileName = d.getLeft();
396 innerComponentsCache.put(cassandraId, fileName, childComponent);
397 addInnerComponentsToCache(innerComponentsCache, childComponent);
399 //add inner components to CSAR
400 return addInnerComponentsToCSAR(zip, innerComponentsCache, definitionsPath);
405 private Either<ZipOutputStream, ResponseFormat> addInnerComponentsToCSAR(ZipOutputStream zip, ComponentCache innerComponentsCache,
406 String definitionsPath)
408 for (ImmutableTriple<String, String, Component> ict : innerComponentsCache.iterable()) {
409 Component innerComponent = ict.getRight();
410 String icFileName = ict.getMiddle();
411 // add component to zip
412 Either<Tuple2<byte[], ZipEntry>, ResponseFormat> zipEntry = toZipEntry(ict, definitionsPath);
413 // TODO: this should not be done, we should instead compose this either further,
415 // but in order to keep this refactoring small, we'll stop here.
416 if (zipEntry.isRight()) {
417 return Either.right(zipEntry.right().value());
419 Tuple2<byte[], ZipEntry> value = zipEntry.left().value();
420 zip.putNextEntry(value._2);
422 // add component interface to zip
423 if (hasToWriteComponentSubstitutionType(innerComponent)) {
424 writeComponentInterface(innerComponent, zip, icFileName, definitionsPath);
430 private Either<Tuple2<byte[], ZipEntry>, ResponseFormat> toZipEntry(ImmutableTriple<String, String, Component> cachedEntry,
431 String definitionsPath) {
432 String cassandraId = cachedEntry.getLeft();
433 String fileName = cachedEntry.getMiddle();
434 Component innerComponent = cachedEntry.getRight();
435 return getEntryData(cassandraId, innerComponent).right().map(status -> {
436 LOGGER.debug("Failed adding to zip component {}, error {}", cassandraId, status);
437 return componentsUtils.getResponseFormat(status);
438 }).left().map(content -> new Tuple2<>(content, new ZipEntry(definitionsPath + fileName)));
441 private void addInnerComponentsToCache(ComponentCache componentCache, Component childComponent) {
442 javaListToVavrList(childComponent.getComponentInstances()).filter(ci -> componentCache.notCached(ci.getComponentUid())).forEach(ci -> {
443 // all resource must be only once!
444 Either<Resource, StorageOperationStatus> resource = toscaOperationFacade.getToscaElement(ci.getComponentUid());
445 Component componentRI = checkAndAddComponent(componentCache, ci, resource);
446 //if not atomic - insert inner components as well
448 // TODO: This could potentially create a StackOverflowException if the call stack
450 // happens to be too large. Tail-recursive optimization should be used here.
451 if (!ModelConverter.isAtomicComponent(componentRI)) {
452 addInnerComponentsToCache(componentCache, componentRI);
457 private Component checkAndAddComponent(ComponentCache componentCache, ComponentInstance ci, Either<Resource, StorageOperationStatus> resource) {
458 if (resource.isRight()) {
459 LOGGER.debug("Failed to fetch resource with id {} for instance {}", ci.getComponentUid(), ci.getName());
461 Component componentRI = resource.left().value();
462 Map<String, ArtifactDefinition> childToscaArtifacts = componentRI.getToscaArtifacts();
463 ArtifactDefinition childArtifactDefinition = childToscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE);
464 if (childArtifactDefinition != null) {
466 componentCache.put(childArtifactDefinition.getEsId(), childArtifactDefinition.getArtifactName(), componentRI);
471 private Either<byte[], ActionStatus> getEntryData(String cassandraId, Component childComponent) {
472 if (cassandraId == null || cassandraId.isEmpty()) {
473 return toscaExportUtils.exportComponent(childComponent).right().map(toscaErrorToActionStatus(childComponent)).left()
474 .map(ToscaRepresentation::getMainYaml);
476 return getFromCassandra(cassandraId);
480 private F<ToscaError, ActionStatus> toscaErrorToActionStatus(Component childComponent) {
481 return toscaError -> {
482 LOGGER.debug("Failed to export tosca template for child component {} error {}", childComponent.getUniqueId(), toscaError);
483 return componentsUtils.convertFromToscaError(toscaError);
487 private Either<byte[], ResponseFormat> getLatestSchemaFilesFromCassandra() {
488 String fto = versionFirstThreeOctets;
489 return sdcSchemaFilesCassandraDao.getSpecificSchemaFiles(fto, CONFORMANCE_LEVEL).right().map(schemaFilesFetchDBError(fto)).left()
490 .bind(iff(List::isEmpty, () -> schemaFileFetchError(fto), s -> Either.left(s.iterator().next().getPayloadAsArray())));
493 private F<CassandraOperationStatus, ResponseFormat> schemaFilesFetchDBError(String firstThreeOctets) {
495 LOGGER.debug("Failed to get the schema files SDC-Version: {} Conformance-Level {}. Please fix DB table accordingly.", firstThreeOctets,
497 StorageOperationStatus sos = DaoStatusConverter.convertCassandraStatusToStorageStatus(cos);
498 return componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(sos));
502 private Either<byte[], ResponseFormat> schemaFileFetchError(String firstThreeOctets) {
503 LOGGER.debug("Failed to get the schema files SDC-Version: {} Conformance-Level {}", firstThreeOctets, CONFORMANCE_LEVEL);
504 return Either.right(componentsUtils.getResponseFormat(ActionStatus.TOSCA_SCHEMA_FILES_NOT_FOUND, firstThreeOctets, CONFORMANCE_LEVEL));
508 * Create a list of all derived nodes found on the package
510 * @param dependencies all node dependencies
511 * @return a list of nodes
513 private List<String> findNonRootNodesFromPackage(final List<Triple<String, String, Component>> dependencies) {
514 final List<String> nodes = new ArrayList<>();
515 if (CollectionUtils.isNotEmpty(dependencies)) {
516 final String NATIVE_ROOT = "tosca.nodes.Root";
517 dependencies.forEach(dependency -> {
518 if (dependency.getRight() instanceof Resource) {
519 final Resource resource = (Resource) dependency.getRight();
520 if (CollectionUtils.isNotEmpty(resource.getDerivedList())) {
521 resource.getDerivedList().stream().filter(node -> !nodes.contains(node) && !NATIVE_ROOT.equalsIgnoreCase(node))
522 .forEach(node -> nodes.add(node));
531 * Writes to a CSAR zip from casandra schema data
533 * @param zipOutputStream stores the input stream content
534 * @param schemaFileZip zip data from Cassandra
535 * @param nodesFromPackage list of all nodes found on the onboarded package
537 private void addSchemaFilesFromCassandra(final ZipOutputStream zipOutputStream, final byte[] schemaFileZip, final List<String> nodesFromPackage,
538 final String definitionsPath) {
539 final int initSize = 2048;
540 LOGGER.debug("Starting copy from Schema file zip to CSAR zip");
541 try (final ZipInputStream zipInputStream = new ZipInputStream(new ByteArrayInputStream(schemaFileZip));
542 final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
543 final BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(byteArrayOutputStream, initSize)) {
545 while ((entry = zipInputStream.getNextEntry()) != null) {
546 ZipUtils.checkForZipSlipInRead(entry);
547 final String entryName = entry.getName();
548 int readSize = initSize;
549 final byte[] entryData = new byte[initSize];
550 if (shouldZipEntryBeHandled(entryName)) {
551 if (NODES_YML.equalsIgnoreCase(entryName)) {
552 handleNode(zipInputStream, byteArrayOutputStream, nodesFromPackage);
554 while ((readSize = zipInputStream.read(entryData, 0, readSize)) != -1) {
555 bufferedOutputStream.write(entryData, 0, readSize);
557 bufferedOutputStream.flush();
559 byteArrayOutputStream.flush();
560 zipOutputStream.putNextEntry(new ZipEntry(definitionsPath + entryName));
561 zipOutputStream.write(byteArrayOutputStream.toByteArray());
562 zipOutputStream.flush();
563 byteArrayOutputStream.reset();
566 } catch (final Exception e) {
567 LOGGER.error("Error while writing the SDC schema file to the CSAR", e);
568 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
570 LOGGER.debug("Finished copy from Schema file zip to CSAR zip");
574 * Handles the nodes.yml zip entry, updating the nodes.yml to avoid duplicated nodes on it.
576 * @param zipInputStream the zip entry to be read
577 * @param byteArrayOutputStream an output stream in which the data is written into a byte array.
578 * @param nodesFromPackage list of all nodes found on the onboarded package
580 private void handleNode(final ZipInputStream zipInputStream, final ByteArrayOutputStream byteArrayOutputStream,
581 final List<String> nodesFromPackage) throws IOException {
582 final Map<String, Object> nodesFromArtifactFile = readYamlZipEntry(zipInputStream);
583 final Map<String, Object> nodesYaml = updateNodeYml(nodesFromPackage, nodesFromArtifactFile);
584 updateZipEntry(byteArrayOutputStream, nodesYaml);
588 * Updates the zip entry from the given parameters
590 * @param byteArrayOutputStream an output stream in which the data is written into a byte array.
591 * @param nodesYaml a Map of nodes to be written
593 private void updateZipEntry(final ByteArrayOutputStream byteArrayOutputStream, final Map<String, Object> nodesYaml) throws IOException {
594 if (MapUtils.isNotEmpty(nodesYaml)) {
595 byteArrayOutputStream.write(new YamlUtil().objectToYaml(nodesYaml).getBytes());
600 * Filters and removes all duplicated nodes found
602 * @param nodesFromPackage a List of all derived nodes found on the given package
603 * @param nodesFromArtifactFile represents the nodes.yml file stored in Cassandra
604 * @return a nodes Map updated
606 private Map<String, Object> updateNodeYml(final List<String> nodesFromPackage, final Map<String, Object> nodesFromArtifactFile) {
607 if (MapUtils.isNotEmpty(nodesFromArtifactFile)) {
608 final String nodeTypeBlock = TypeUtils.ToscaTagNamesEnum.NODE_TYPES.getElementName();
609 final Map<String, Object> nodeTypes = (Map<String, Object>) nodesFromArtifactFile.get(nodeTypeBlock);
610 nodesFromPackage.stream().filter(nodeTypes::containsKey).forEach(nodeTypes::remove);
611 nodesFromArtifactFile.replace(nodeTypeBlock, nodeTypes);
613 return nodesFromArtifactFile;
617 * Writes a new zip entry
619 * @param zipInputStream the zip entry to be read
620 * @return a map of the given zip entry
622 private Map<String, Object> readYamlZipEntry(final ZipInputStream zipInputStream) throws IOException {
623 final int initSize = 2048;
624 final StringBuilder zipEntry = new StringBuilder();
625 final byte[] buffer = new byte[initSize];
627 while ((read = zipInputStream.read(buffer, 0, initSize)) >= 0) {
628 zipEntry.append(new String(buffer, 0, read));
630 return (Map<String, Object>) new Yaml().load(zipEntry.toString());
634 * Checks if the zip entry should or should not be added to the CSAR based on the given global type list
636 * @param entryName the zip entry name
637 * @return true if the zip entry should be handled
639 private boolean shouldZipEntryBeHandled(final String entryName) {
640 return ConfigurationManager.getConfigurationManager().getConfiguration().getGlobalCsarImports().stream()
641 .anyMatch(entry -> entry.contains(entryName));
644 private void addSchemaFilesByModel(final ZipOutputStream zipOutputStream, final String modelName,
645 final String definitionsPath, final boolean isSingleImportsFile,
646 final List<Component> dependencies) {
648 final Set<Path> writtenEntryPathList = new HashSet<>();
649 final Path defsPath = Path.of(definitionsPath);
650 final Map<Path, byte[]> contentToMerge = new HashMap<>();
651 final List<ToscaImportByModel> modelDefaultImportList = modelOperation.findAllModelImports(modelName, true);
652 for (final ToscaImportByModel toscaImportByModel : modelDefaultImportList) {
653 var importPath = Path.of(toscaImportByModel.getFullPath());
654 if (!isSingleImportsFile) {
655 if (ADDITIONAL_TYPE_DEFINITIONS.equals(Paths.get(String.valueOf(importPath)).normalize().toString())) {
656 final Path entryPath = defsPath.resolve(importPath);
657 contentToMerge.put(entryPath, toscaImportByModel.getContent().getBytes(StandardCharsets.UTF_8));
659 if (writtenEntryPathList.contains(defsPath.resolve(importPath))) {
660 importPath = ToscaDefaultImportHelper.addModelAsFilePrefix(importPath, toscaImportByModel.getModelId());
662 final Path entryPath = defsPath.resolve(importPath);
663 writtenEntryPathList.add(entryPath);
664 contentToMerge.put(entryPath, toscaImportByModel.getContent().getBytes(StandardCharsets.UTF_8));
667 if (writtenEntryPathList.contains(defsPath.resolve(importPath))) {
668 importPath = ToscaDefaultImportHelper.addModelAsFilePrefix(importPath, toscaImportByModel.getModelId());
670 final Path entryPath = defsPath.resolve(importPath);
671 zipOutputStream.putNextEntry(new ZipEntry(entryPath.toString()));
672 writtenEntryPathList.add(entryPath);
673 final byte[] content = toscaImportByModel.getContent().getBytes(StandardCharsets.UTF_8);
674 zipOutputStream.write(content, 0, content.length);
675 zipOutputStream.closeEntry();
678 if (!isSingleImportsFile) {
679 byte[] mergingContent = new byte[0];
680 for (Map.Entry<Path, byte[]> entry : contentToMerge.entrySet()) {
681 if (ADDITIONAL_TYPE_DEFINITIONS.equals(Paths.get(String.valueOf(entry.getKey())).normalize().toString())) {
682 mergingContent = mergeContent(mergingContent, entry.getValue());
684 final var zipEntry = new ZipEntry(entry.getKey().toString());
685 zipOutputStream.putNextEntry(zipEntry);
686 writtenEntryPathList.add(entry.getKey());
687 mergingContent = mergeContent(mergingContent, entry.getValue());
688 mergingContent = updateMergingContentFromDependencies(mergingContent, dependencies);
689 zipOutputStream.write(mergingContent, 0, mergingContent.length);
690 zipOutputStream.closeEntry();
694 } catch (final IOException e) {
695 LOGGER.error(String.valueOf(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR), CsarUtils.class.getName(),
696 "Error while writing the schema files by model to the CSAR", e);
697 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.CSAR_TOSCA_IMPORTS_ERROR));
701 private byte[] updateMergingContentFromDependencies(final byte[] mergingContent, final List<Component> dependencies) {
702 final DumperOptions options = new DumperOptions();
703 options.setDefaultFlowStyle(FlowStyle.BLOCK);
704 final Yaml yaml = new Yaml(options);
705 final Map<String, Object> stringObjectMap = (Map<String, Object>) yaml.load(new String(mergingContent));
706 final Map<String, Object> nodeTypes = (Map<String, Object>) stringObjectMap.get("node_types");
707 for (final Component dependency : dependencies) {
708 final Map<String, Object> dependencyAsMap = yaml.load(yaml.dumpAsMap(dependency));
709 final String toscaResourceName = ((ResourceMetadataDataDefinition) dependency.getComponentMetadataDefinition()
710 .getMetadataDataDefinition()).getToscaResourceName();
711 final Map<String, Object> nodeType = (Map<String, Object>) nodeTypes.get(toscaResourceName);
712 final Map<String, Object> propertiesFromDependency = (Map<String, Object>) ((List) dependencyAsMap.get("properties"))
713 .stream().collect(Collectors.toMap(s -> ((Map<String, Object>) s).get("name"), s -> s));
714 if (MapUtils.isNotEmpty(nodeType) && MapUtils.isNotEmpty(propertiesFromDependency)) {
715 final Map<String, Object> propertiesFromMergingContent = (Map<String, Object>) nodeType.get("properties");
716 final Map<String, Object> updatedMap = updatePropertiesFromDependency(propertiesFromMergingContent, propertiesFromDependency);
717 nodeType.replace("properties", updatedMap);
718 nodeTypes.replace(toscaResourceName, nodeType);
721 stringObjectMap.replace("node_types", nodeTypes);
722 return yaml.dumpAsMap(stringObjectMap).getBytes();
725 private Map<String, Object> updatePropertiesFromDependency(final Map<String, Object> propertiesFromMergingContent,
726 final Map<String, Object> propertiesFromDependency) {
727 final Map<String, Object> result = new HashMap<>();
728 for (final Entry<String, Object> entry : propertiesFromDependency.entrySet()) {
729 final Map<String, Object> propertiesMap = new HashMap<>();
730 final String key = entry.getKey();
731 final Object value = entry.getValue();
732 if (propertiesFromMergingContent instanceof Map) {
733 final Object object = propertiesFromMergingContent.get(key);
734 if (object instanceof Map) {
735 ((Map<String, Object>) object).keySet().forEach(s ->
736 propertiesMap.put(s, getValue(s, (Map<String, Object>) value))
739 propertiesMap.putAll(createProperties(value));
742 propertiesMap.putAll(createProperties(value));
744 result.put(key, propertiesMap);
749 private Object getValue(final String key, Map<String, Object> value) {
750 final String mappedKey = mapKey(key);
751 if (mappedKey.equals("schemaType")) {
752 return Collections.singletonMap("type", value.get(mappedKey));
754 return value.get(mappedKey);
757 private String mapKey(final String key) {
758 if (key.equals("entry_schema")) {
761 if (key.equals("default")) {
762 return "defaultValue";
767 private Map<String, Object> createProperties(final Object value) {
768 final Map<String, Object> propertiesMap = new HashMap<>();
769 propertiesMap.put("type", ((Map<String, Object>) value).get("type"));
770 propertiesMap.put("required", ((Map<String, Object>) value).get("required"));
771 final Object entrySchema = ((Map<String, Object>) value).get("entry_schema");
772 if (entrySchema != null) {
773 propertiesMap.put("entry_schema", entrySchema);
775 return propertiesMap;
778 private byte[] mergeContent(final byte[] first, final byte[] second) {
779 byte[] merged = new byte[0];
780 final Map<String, Object> firstMap = new Yaml().load(new String(first));
781 final Map<String, Object> secondMap = new Yaml().load(new String(second));
782 if (MapUtils.isNotEmpty(secondMap)) {
783 final DumperOptions options = new DumperOptions();
784 options.setDefaultFlowStyle(FlowStyle.BLOCK);
785 final Yaml yaml = new Yaml(options);
786 for (final Entry<String, Object> secondMapEntry : secondMap.entrySet()) {
787 final Map<String, Object> newMap = new HashMap<>();
788 if (secondMapEntry.getKey().endsWith("_types")) {
789 if (MapUtils.isNotEmpty(firstMap) && firstMap.containsKey(secondMapEntry.getKey())) {
790 final Map<String, Object> secondMapEntryValue = (Map<String, Object>) secondMapEntry.getValue();
791 final Map<String, Object> firstMapValue = (Map<String, Object>) firstMap.get(secondMapEntry.getKey());
792 secondMapEntryValue.putAll(firstMapValue);
793 newMap.put(secondMapEntry.getKey(), secondMapEntryValue);
795 newMap.put(secondMapEntry.getKey(), secondMapEntry.getValue());
798 newMap.put(secondMapEntry.getKey(), secondMapEntry.getValue());
800 merged = Bytes.concat(merged, yaml.dumpAsMap(newMap).getBytes());
806 private Either<CsarDefinition, ResponseFormat> collectComponentCsarDefinition(Component component) {
807 ComponentArtifacts componentArtifacts = new ComponentArtifacts();
808 Component updatedComponent = component;
810 //get service to receive the AII artifacts uploaded to the service
811 if (updatedComponent.getComponentType() == ComponentTypeEnum.SERVICE) {
812 Either<Service, StorageOperationStatus> getServiceResponse = toscaOperationFacade.getToscaElement(updatedComponent.getUniqueId());
814 if (getServiceResponse.isRight()) {
815 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getServiceResponse.right().value());
816 return Either.right(componentsUtils.getResponseFormat(actionStatus));
819 updatedComponent = getServiceResponse.left().value();
822 //find the artifacts of the main component, it would have its composed instances artifacts in a separate folder
823 ComponentTypeArtifacts componentInstanceArtifacts = new ComponentTypeArtifacts();
824 ArtifactsInfo artifactsInfo = collectComponentArtifacts(updatedComponent);
825 componentInstanceArtifacts.setComponentArtifacts(artifactsInfo);
826 componentArtifacts.setMainTypeAndCIArtifacts(componentInstanceArtifacts);
828 Map<String, ComponentTypeArtifacts> resourceTypeArtifacts = componentArtifacts
829 .getComponentTypeArtifacts(); //artifacts mapped by the component type(tosca name+version)
830 //get the component instances
831 List<ComponentInstance> componentInstances = updatedComponent.getComponentInstances();
832 if (componentInstances != null) {
833 for (ComponentInstance componentInstance : componentInstances) {
834 //call recursive to find artifacts for all the path
835 Either<Boolean, ResponseFormat> collectComponentInstanceArtifacts = collectComponentInstanceArtifacts(
836 updatedComponent, componentInstance, resourceTypeArtifacts, componentInstanceArtifacts);
837 if (collectComponentInstanceArtifacts.isRight()) {
838 return Either.right(collectComponentInstanceArtifacts.right().value());
843 if (LOGGER.isDebugEnabled()) {
844 printResult(componentArtifacts, updatedComponent.getName());
847 return Either.left(new CsarDefinition(componentArtifacts));
850 private void printResult(ComponentArtifacts componentArtifacts, String name) {
851 StringBuilder result = new StringBuilder();
852 result.append("Artifacts of main component " + name + "\n");
853 ComponentTypeArtifacts componentInstanceArtifacts = componentArtifacts.getMainTypeAndCIArtifacts();
854 printArtifacts(componentInstanceArtifacts);
855 result.append("Type Artifacts\n");
856 for (Map.Entry<String, ComponentTypeArtifacts> typeArtifacts : componentArtifacts.getComponentTypeArtifacts().entrySet()) {
857 result.append("Folder " + typeArtifacts.getKey() + "\n");
858 result.append(printArtifacts(typeArtifacts.getValue()));
861 if (LOGGER.isDebugEnabled()) {
862 LOGGER.debug(result.toString());
866 private String printArtifacts(ComponentTypeArtifacts componentInstanceArtifacts) {
867 StringBuilder result = new StringBuilder();
868 ArtifactsInfo artifactsInfo = componentInstanceArtifacts.getComponentArtifacts();
869 Map<ArtifactGroupTypeEnum, Map<String, List<ArtifactDefinition>>> componentArtifacts = artifactsInfo.getArtifactsInfo();
870 printArtifacts(componentArtifacts);
871 result = result.append("Resources\n");
872 for (Map.Entry<String, ArtifactsInfo> resourceInstance : componentInstanceArtifacts.getComponentInstancesArtifacts().entrySet()) {
873 result.append("Folder" + resourceInstance.getKey() + "\n");
874 result.append(printArtifacts(resourceInstance.getValue().getArtifactsInfo()));
877 return result.toString();
880 private String printArtifacts(Map<ArtifactGroupTypeEnum, Map<String, List<ArtifactDefinition>>> componetArtifacts) {
881 StringBuilder result = new StringBuilder();
882 for (Map.Entry<ArtifactGroupTypeEnum, Map<String, List<ArtifactDefinition>>> artifactGroup : componetArtifacts.entrySet()) {
883 result.append(" " + artifactGroup.getKey().getType());
884 for (Map.Entry<String, List<ArtifactDefinition>> groupArtifacts : artifactGroup.getValue().entrySet()) {
885 result.append(" " + groupArtifacts.getKey());
886 for (ArtifactDefinition artifact : groupArtifacts.getValue()) {
887 result.append(" " + artifact.getArtifactDisplayName());
892 return result.toString();
895 private Either<Boolean, ResponseFormat> collectComponentInstanceArtifacts(Component parentComponent, ComponentInstance componentInstance,
896 Map<String, ComponentTypeArtifacts> resourcesTypeArtifacts,
897 ComponentTypeArtifacts instanceArtifactsLocation) {
898 //1. get the component instance component
900 if (componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy) {
901 componentUid = componentInstance.getSourceModelUid();
903 componentUid = componentInstance.getComponentUid();
905 Either<Component, StorageOperationStatus> component = toscaOperationFacade.getToscaElement(componentUid);
906 if (component.isRight()) {
907 LOGGER.error("Failed to fetch resource with id {} for instance {}", componentUid, parentComponent.getUUID());
908 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ASSET_NOT_FOUND_DURING_CSAR_CREATION,
909 parentComponent.getComponentType().getValue(), parentComponent.getUUID(),
910 componentInstance.getOriginType().getComponentType().getValue(), componentUid));
912 Component fetchedComponent = component.left().value();
914 //2. fill the artifacts for the current component parent type
915 String toscaComponentName =
916 componentInstance.getToscaComponentName() + "_v" + componentInstance.getComponentVersion();
918 // if there are no artifacts for this component type we need to fetch and build them
919 ComponentTypeArtifacts componentParentArtifacts = Optional
920 .ofNullable(resourcesTypeArtifacts.get(toscaComponentName))
921 .orElseGet(() -> collectComponentTypeArtifacts(fetchedComponent));
923 if (componentParentArtifacts.getComponentArtifacts().isNotEmpty()) {
924 resourcesTypeArtifacts.put(toscaComponentName, componentParentArtifacts);
927 //3. find the artifacts specific to the instance
928 Map<String, List<ArtifactDefinition>> componentInstanceSpecificInformationalArtifacts =
929 getComponentInstanceSpecificArtifacts(componentInstance.getArtifacts(),
930 componentParentArtifacts.getComponentArtifacts().getArtifactsInfo(), ArtifactGroupTypeEnum.INFORMATIONAL);
931 Map<String, List<ArtifactDefinition>> componentInstanceSpecificDeploymentArtifacts =
932 getComponentInstanceSpecificArtifacts(componentInstance.getDeploymentArtifacts(),
933 componentParentArtifacts.getComponentArtifacts().getArtifactsInfo(), ArtifactGroupTypeEnum.DEPLOYMENT);
935 //4. add the instances artifacts to the component type
936 ArtifactsInfo artifactsInfo = new ArtifactsInfo();
937 if (!componentInstanceSpecificInformationalArtifacts.isEmpty()) {
938 artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.INFORMATIONAL, componentInstanceSpecificInformationalArtifacts);
940 if (!componentInstanceSpecificDeploymentArtifacts.isEmpty()) {
941 artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.DEPLOYMENT, componentInstanceSpecificDeploymentArtifacts);
943 if (!artifactsInfo.isEmpty()) {
944 instanceArtifactsLocation.addComponentInstancesArtifacts(componentInstance.getNormalizedName(), artifactsInfo);
947 //5. do the same for all the component instances
948 List<ComponentInstance> componentInstances = fetchedComponent.getComponentInstances();
949 if (componentInstances != null) {
950 for (ComponentInstance childComponentInstance : componentInstances) {
951 Either<Boolean, ResponseFormat> collectComponentInstanceArtifacts = collectComponentInstanceArtifacts(
952 fetchedComponent, childComponentInstance, resourcesTypeArtifacts, componentParentArtifacts);
953 if (collectComponentInstanceArtifacts.isRight()) {
954 return collectComponentInstanceArtifacts;
959 return Either.left(true);
962 private Map<String, List<ArtifactDefinition>> getComponentInstanceSpecificArtifacts(Map<String, ArtifactDefinition> componentArtifacts,
963 Map<ArtifactGroupTypeEnum, Map<String, List<ArtifactDefinition>>> componentTypeArtifacts,
964 ArtifactGroupTypeEnum artifactGroupTypeEnum) {
965 Map<String, List<ArtifactDefinition>> parentArtifacts = componentTypeArtifacts
966 .get(artifactGroupTypeEnum); //the artfiacts of the component itself and not the instance
968 Map<String, List<ArtifactDefinition>> artifactsByTypeOfComponentInstance = new HashMap<>();
969 if (componentArtifacts != null) {
970 for (ArtifactDefinition artifact : componentArtifacts.values()) {
971 List<ArtifactDefinition> parentArtifactsByType = null;
972 if (parentArtifacts != null) {
973 parentArtifactsByType = parentArtifacts.get(artifact.getArtifactType());
975 //the artifact is of instance
976 if (parentArtifactsByType == null || !parentArtifactsByType.contains(artifact)) {
977 List<ArtifactDefinition> typeArtifacts = artifactsByTypeOfComponentInstance.get(artifact.getArtifactType());
978 if (typeArtifacts == null) {
979 typeArtifacts = new ArrayList<>();
980 artifactsByTypeOfComponentInstance.put(artifact.getArtifactType(), typeArtifacts);
982 typeArtifacts.add(artifact);
987 return artifactsByTypeOfComponentInstance;
990 private ComponentTypeArtifacts collectComponentTypeArtifacts(Component fetchedComponent) {
991 ArtifactsInfo componentArtifacts = collectComponentArtifacts(fetchedComponent);
992 ComponentTypeArtifacts componentArtifactsInfo = new ComponentTypeArtifacts();
993 if (componentArtifacts.isNotEmpty()) {
994 componentArtifactsInfo.setComponentArtifacts(componentArtifacts);
996 return componentArtifactsInfo;
999 private ArtifactsInfo collectComponentArtifacts(Component component) {
1000 Map<String, ArtifactDefinition> informationalArtifacts = component.getArtifacts();
1001 Map<String, List<ArtifactDefinition>> informationalArtifactsByType = collectGroupArtifacts(informationalArtifacts);
1002 Map<String, ArtifactDefinition> deploymentArtifacts = component.getDeploymentArtifacts();
1003 Map<String, List<ArtifactDefinition>> deploymentArtifactsByType = collectGroupArtifacts(deploymentArtifacts);
1004 ArtifactsInfo artifactsInfo = new ArtifactsInfo();
1005 if (!informationalArtifactsByType.isEmpty()) {
1006 artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.INFORMATIONAL, informationalArtifactsByType);
1008 if (!deploymentArtifactsByType.isEmpty()) {
1009 artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.DEPLOYMENT, deploymentArtifactsByType);
1012 return artifactsInfo;
1015 private Map<String, List<ArtifactDefinition>> collectGroupArtifacts(
1016 final Map<String, ArtifactDefinition> componentArtifacts) {
1017 final Map<String, List<ArtifactDefinition>> artifactsByType = new HashMap<>();
1018 for (final ArtifactDefinition artifact : componentArtifacts.values()) {
1019 if (artifact.getArtifactUUID() != null) {
1020 artifactsByType.putIfAbsent(artifact.getArtifactType(), new ArrayList<>());
1021 final List<ArtifactDefinition> typeArtifacts = artifactsByType.get(artifact.getArtifactType());
1022 typeArtifacts.add(artifact);
1025 return artifactsByType;
1028 private Either<ZipOutputStream, ResponseFormat> writeAllFilesToCsar(Component mainComponent, CsarDefinition csarDefinition,
1029 ZipOutputStream zipstream, boolean isInCertificationRequest)
1030 throws IOException {
1031 ComponentArtifacts componentArtifacts = csarDefinition.getComponentArtifacts();
1032 Either<ZipOutputStream, ResponseFormat> writeComponentArtifactsToSpecifiedPath = writeComponentArtifactsToSpecifiedPath(mainComponent,
1033 componentArtifacts, zipstream, ARTIFACTS_PATH, isInCertificationRequest);
1034 if (writeComponentArtifactsToSpecifiedPath.isRight()) {
1035 return Either.right(writeComponentArtifactsToSpecifiedPath.right().value());
1037 ComponentTypeArtifacts mainTypeAndCIArtifacts = componentArtifacts.getMainTypeAndCIArtifacts();
1038 writeComponentArtifactsToSpecifiedPath = writeArtifactsInfoToSpecifiedPath(mainComponent, mainTypeAndCIArtifacts.getComponentArtifacts(),
1039 zipstream, ARTIFACTS_PATH, isInCertificationRequest);
1040 if (writeComponentArtifactsToSpecifiedPath.isRight()) {
1041 return Either.right(writeComponentArtifactsToSpecifiedPath.right().value());
1043 Map<String, ArtifactsInfo> componentInstancesArtifacts = mainTypeAndCIArtifacts.getComponentInstancesArtifacts();
1044 String currentPath = ARTIFACTS_PATH + RESOURCES_PATH;
1045 for (String keyAssetName : componentInstancesArtifacts.keySet()) {
1046 ArtifactsInfo artifactsInfo = componentInstancesArtifacts.get(keyAssetName);
1047 String pathWithAssetName = currentPath + keyAssetName + PATH_DELIMITER;
1048 writeComponentArtifactsToSpecifiedPath = writeArtifactsInfoToSpecifiedPath(mainComponent, artifactsInfo, zipstream, pathWithAssetName,
1049 isInCertificationRequest);
1050 if (writeComponentArtifactsToSpecifiedPath.isRight()) {
1051 return Either.right(writeComponentArtifactsToSpecifiedPath.right().value());
1054 writeComponentArtifactsToSpecifiedPath = writeOperationsArtifactsToCsar(mainComponent, zipstream);
1055 if (writeComponentArtifactsToSpecifiedPath.isRight()) {
1056 return Either.right(writeComponentArtifactsToSpecifiedPath.right().value());
1058 return Either.left(zipstream);
1061 private Either<ZipOutputStream, ResponseFormat> writeOperationsArtifactsToCsar(Component component, ZipOutputStream zipstream) {
1062 if (checkComponentBeforeOperation(component)) {
1063 return Either.left(zipstream);
1065 for (Map.Entry<String, InterfaceDefinition> interfaceEntry : ((Resource) component).getInterfaces().entrySet()) {
1066 for (OperationDataDefinition operation : interfaceEntry.getValue().getOperations().values()) {
1068 if (checkComponentBeforeWrite(component, interfaceEntry, operation)) {
1071 final String artifactUUID = operation.getImplementation().getArtifactUUID();
1072 if (artifactUUID == null) {
1075 final Either<byte[], ActionStatus> artifactFromCassandra = getFromCassandra(artifactUUID);
1076 final String artifactName = operation.getImplementation().getArtifactName();
1077 if (artifactFromCassandra.isRight()) {
1078 LOGGER.error(ARTIFACT_NAME_UNIQUE_ID, artifactName, artifactUUID);
1079 LOGGER.error("Failed to get {} payload from DB reason: {}", artifactName, artifactFromCassandra.right().value());
1080 return Either.right(componentsUtils.getResponseFormat(
1081 ARTIFACT_PAYLOAD_NOT_FOUND_DURING_CSAR_CREATION, "Resource", component.getUniqueId(), artifactName, artifactUUID));
1083 zipstream.putNextEntry(new ZipEntry(OperationArtifactUtil.createOperationArtifactPath(component, null, operation, true)));
1084 zipstream.write(artifactFromCassandra.left().value());
1085 } catch (IOException e) {
1086 LOGGER.error("Component Name {}, Interface Name {}, Operation Name {}", component.getNormalizedName(), interfaceEntry.getKey(),
1087 operation.getName());
1088 LOGGER.error("Error while writing the operation's artifacts to the CSAR", e);
1089 return Either.right(componentsUtils.getResponseFormat(ERROR_DURING_CSAR_CREATION, "Resource", component.getUniqueId()));
1093 return Either.left(zipstream);
1096 private boolean checkComponentBeforeWrite(Component component, Map.Entry<String, InterfaceDefinition> interfaceEntry,
1097 OperationDataDefinition operation) {
1098 final ArtifactDataDefinition implementation = operation.getImplementation();
1099 if (implementation == null) {
1100 LOGGER.debug("Component Name {}, Interface Id {}, Operation Name {} - no Operation Implementation found", component.getNormalizedName(),
1101 interfaceEntry.getValue().getUniqueId(), operation.getName());
1104 final String artifactName = implementation.getArtifactName();
1105 if (artifactName == null) {
1106 LOGGER.debug("Component Name {}, Interface Id {}, Operation Name {} - no artifact found", component.getNormalizedName(),
1107 interfaceEntry.getValue().getUniqueId(), operation.getName());
1110 if (OperationArtifactUtil.artifactNameIsALiteralValue(artifactName)) {
1111 LOGGER.debug("Component Name {}, Interface Id {}, Operation Name {} - artifact name is a literal value rather than an SDC artifact",
1112 component.getNormalizedName(), interfaceEntry.getValue().getUniqueId(), operation.getName());
1118 private boolean checkComponentBeforeOperation(Component component) {
1119 if (component instanceof Service) {
1122 if (Objects.isNull(((Resource) component).getInterfaces())) {
1123 LOGGER.debug("Component Name {}- no interfaces found", component.getNormalizedName());
1129 private Either<ZipOutputStream, ResponseFormat> writeArtifactsInfoToSpecifiedPath(final Component mainComponent,
1130 final ArtifactsInfo currArtifactsInfo,
1131 final ZipOutputStream zip, final String path,
1132 final boolean isInCertificationRequest) throws IOException {
1133 final Map<ArtifactGroupTypeEnum, Map<String, List<ArtifactDefinition>>> artifactsInfo = currArtifactsInfo.getArtifactsInfo();
1134 for (final ArtifactGroupTypeEnum artifactGroupTypeEnum : artifactsInfo.keySet()) {
1135 final String groupTypeFolder = path + WordUtils.capitalizeFully(artifactGroupTypeEnum.getType()) + PATH_DELIMITER;
1136 final Map<String, List<ArtifactDefinition>> artifactTypesMap = artifactsInfo.get(artifactGroupTypeEnum);
1137 for (final String artifactType : artifactTypesMap.keySet()) {
1138 final List<ArtifactDefinition> artifactDefinitionList = artifactTypesMap.get(artifactType);
1139 String artifactTypeFolder = groupTypeFolder + artifactType + PATH_DELIMITER;
1140 if (ArtifactTypeEnum.WORKFLOW.getType().equals(artifactType) && path.contains(ARTIFACTS_PATH + RESOURCES_PATH)) {
1141 // Ignore this packaging as BPMN artifacts needs to be packaged in different manner
1144 if (ArtifactTypeEnum.WORKFLOW.getType().equals(artifactType)) {
1145 artifactTypeFolder += OperationArtifactUtil.BPMN_ARTIFACT_PATH + File.separator;
1146 } else if (ArtifactTypeEnum.ONBOARDED_PACKAGE.getType().equals(artifactType)) {
1147 // renaming legacy folder ONBOARDED_PACKAGE to the new folder ETSI_PACKAGE
1148 artifactTypeFolder = artifactTypeFolder
1149 .replace(ArtifactTypeEnum.ONBOARDED_PACKAGE.getType(), ArtifactTypeEnum.ETSI_PACKAGE.getType());
1151 // TODO: We should not do this but in order to keep this refactoring small enough,
1153 // we'll leave this as is for now
1154 List<ArtifactDefinition> collect = filterArtifactDefinitionToZip(mainComponent, artifactDefinitionList, isInCertificationRequest)
1155 .collect(Collectors.toList());
1156 for (ArtifactDefinition ad : collect) {
1157 zip.putNextEntry(new ZipEntry(artifactTypeFolder + ad.getArtifactName()));
1158 zip.write(ad.getPayloadData());
1162 return Either.left(zip);
1165 private Stream<ArtifactDefinition> filterArtifactDefinitionToZip(Component mainComponent, List<ArtifactDefinition> artifactDefinitionList,
1166 boolean isInCertificationRequest) {
1167 return artifactDefinitionList.stream().filter(shouldBeInZip(isInCertificationRequest, mainComponent)).map(this::fetchPayLoadData)
1168 .filter(Either::isLeft).map(e -> e.left().value());
1171 private Predicate<ArtifactDefinition> shouldBeInZip(boolean isInCertificationRequest, Component component) {
1172 return artifactDefinition -> !(!isInCertificationRequest && component.isService() && artifactDefinition.isHeatEnvType() || artifactDefinition
1173 .hasNoMandatoryEsId());
1176 private Either<ArtifactDefinition, ActionStatus> fetchPayLoadData(ArtifactDefinition ad) {
1177 byte[] payloadData = ad.getPayloadData();
1178 if (payloadData == null) {
1179 return getFromCassandra(ad.getEsId()).left().map(pd -> {
1182 }).right().map(as -> {
1183 LOGGER.debug(ARTIFACT_NAME_UNIQUE_ID, ad.getArtifactName(), ad.getUniqueId());
1184 LOGGER.debug("Failed to get {} payload from DB reason: {}", ad.getArtifactName(), as);
1188 return Either.left(ad);
1192 private Either<ZipOutputStream, ResponseFormat> writeComponentArtifactsToSpecifiedPath(Component mainComponent,
1193 ComponentArtifacts componentArtifacts,
1194 ZipOutputStream zipstream, String currentPath,
1195 boolean isInCertificationRequest) throws IOException {
1196 Map<String, ComponentTypeArtifacts> componentTypeArtifacts = componentArtifacts.getComponentTypeArtifacts();
1199 //<Inner Asset TOSCA name (e.g. VFC name)> folder name: <Inner Asset TOSCA name (e.g. VFC name)>_v<version>.
1201 //E.g. "org.openecomp.resource.vf.vipr_atm_v1.0"
1202 Set<String> componentTypeArtifactsKeys = componentTypeArtifacts.keySet();
1203 for (String keyAssetName : componentTypeArtifactsKeys) {
1204 ComponentTypeArtifacts componentInstanceArtifacts = componentTypeArtifacts.get(keyAssetName);
1205 ArtifactsInfo componentArtifacts2 = componentInstanceArtifacts.getComponentArtifacts();
1206 String pathWithAssetName = currentPath + keyAssetName + PATH_DELIMITER;
1207 Either<ZipOutputStream, ResponseFormat> writeArtifactsInfoToSpecifiedPath = writeArtifactsInfoToSpecifiedPath(mainComponent,
1208 componentArtifacts2, zipstream, pathWithAssetName, isInCertificationRequest);
1209 if (writeArtifactsInfoToSpecifiedPath.isRight()) {
1210 return writeArtifactsInfoToSpecifiedPath;
1213 return Either.left(zipstream);
1216 private Either<ToscaRepresentation, ResponseFormat> generateToscaRepresentation(Component component, boolean isSkipImports) {
1217 return toscaExportUtils.exportComponent(component, isSkipImports).right().map(toscaError -> {
1218 LOGGER.debug("exportComponent failed {}", toscaError);
1219 return componentsUtils.getResponseFormat(componentsUtils.convertFromToscaError(toscaError));
1223 private String createToscaBlock0(String metaFileVersion, String csarVersion, String createdBy, String entryDef, boolean isAsdPackage,
1224 String definitionsPath) {
1225 final String block0template = "TOSCA-Meta-File-Version: %s\nCSAR-Version: %s\nCreated-By: %s\nEntry-Definitions: "
1226 + definitionsPath + "%s\n%s\nName: csar.meta\nContent-Type: text/plain\n";
1227 return String.format(block0template, metaFileVersion, csarVersion, createdBy, entryDef, isAsdPackage ? "entry_definition_type: asd" : "");
1230 private class CsarDefinition {
1232 private ComponentArtifacts componentArtifacts;
1234 // add list of tosca artifacts and meta describes CSAR zip root
1235 public CsarDefinition(ComponentArtifacts componentArtifacts) {
1236 this.componentArtifacts = componentArtifacts;
1239 public ComponentArtifacts getComponentArtifacts() {
1240 return componentArtifacts;
1244 private class ComponentArtifacts {
1246 //artifacts of the component and CI's artifacts contained in it's composition (represents Informational, Deployment & Resource folders of main component)
1247 private ComponentTypeArtifacts mainTypeAndCIArtifacts;
1248 //artifacts of all component types mapped by their tosca name
1249 private Map<String, ComponentTypeArtifacts> componentTypeArtifacts;
1251 public ComponentArtifacts() {
1252 mainTypeAndCIArtifacts = new ComponentTypeArtifacts();
1253 componentTypeArtifacts = new HashMap<>();
1256 public ComponentTypeArtifacts getMainTypeAndCIArtifacts() {
1257 return mainTypeAndCIArtifacts;
1260 public void setMainTypeAndCIArtifacts(ComponentTypeArtifacts componentInstanceArtifacts) {
1261 this.mainTypeAndCIArtifacts = componentInstanceArtifacts;
1264 public Map<String, ComponentTypeArtifacts> getComponentTypeArtifacts() {
1265 return componentTypeArtifacts;
1270 * The artifacts of the component and of all its composed instances
1272 private class ComponentTypeArtifacts {
1274 private ArtifactsInfo componentArtifacts; //component artifacts (describes the Informational Deployment folders)
1276 private Map<String, ArtifactsInfo> componentInstancesArtifacts; //artifacts of the composed instances mapped by the resourceInstance normalized name (describes the Resources folder)
1278 public ComponentTypeArtifacts() {
1279 componentArtifacts = new ArtifactsInfo();
1280 componentInstancesArtifacts = new HashMap<>();
1283 public ArtifactsInfo getComponentArtifacts() {
1284 return componentArtifacts;
1287 public void setComponentArtifacts(ArtifactsInfo artifactsInfo) {
1288 this.componentArtifacts = artifactsInfo;
1291 public Map<String, ArtifactsInfo> getComponentInstancesArtifacts() {
1292 return componentInstancesArtifacts;
1295 public void addComponentInstancesArtifacts(String normalizedName, ArtifactsInfo artifactsInfo) {
1296 componentInstancesArtifacts.put(normalizedName, artifactsInfo);
1301 * The artifacts Definition saved by their structure
1303 private class ArtifactsInfo {
1304 //Key is the type of artifacts(Informational/Deployment)
1306 //Value is a map between an artifact type and a list of all artifacts of this type
1307 private Map<ArtifactGroupTypeEnum, Map<String, List<ArtifactDefinition>>> artifactsInfoField;
1309 public ArtifactsInfo() {
1310 this.artifactsInfoField = new EnumMap<>(ArtifactGroupTypeEnum.class);
1313 public Map<ArtifactGroupTypeEnum, Map<String, List<ArtifactDefinition>>> getArtifactsInfo() {
1314 return artifactsInfoField;
1317 public void addArtifactsToGroup(ArtifactGroupTypeEnum artifactGroup, Map<String, List<ArtifactDefinition>> artifactsDefinition) {
1318 if (artifactsInfoField.get(artifactGroup) == null) {
1319 artifactsInfoField.put(artifactGroup, artifactsDefinition);
1321 Map<String, List<ArtifactDefinition>> artifactTypeEnumListMap = artifactsInfoField.get(artifactGroup);
1322 artifactTypeEnumListMap.putAll(artifactsDefinition);
1323 artifactsInfoField.put(artifactGroup, artifactTypeEnumListMap);
1327 public boolean isEmpty() {
1328 return artifactsInfoField.isEmpty();
1331 public boolean isNotEmpty() {
1336 public static class ToscaErrorException extends Exception {
1338 ToscaErrorException(ToscaError error) {
1339 super("Error while exporting component's interface (toscaError:" + error + ")");