2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.openecomp.sdc.be.tosca;
24 import fj.data.Either;
25 import java.io.BufferedOutputStream;
26 import java.io.ByteArrayInputStream;
28 import java.io.IOException;
29 import java.util.ArrayList;
30 import java.util.Arrays;
31 import java.util.EnumMap;
32 import java.util.HashMap;
33 import java.util.HashSet;
34 import java.util.List;
36 import java.util.Map.Entry;
37 import java.util.Objects;
39 import java.util.regex.Matcher;
40 import java.util.regex.Pattern;
41 import java.util.zip.ZipEntry;
42 import java.util.zip.ZipInputStream;
43 import java.util.zip.ZipOutputStream;
44 import org.apache.commons.codec.binary.Base64;
45 import org.apache.commons.collections.CollectionUtils;
46 import org.apache.commons.collections.MapUtils;
47 import org.apache.commons.io.output.ByteArrayOutputStream;
48 import org.apache.commons.lang.WordUtils;
49 import org.apache.commons.lang3.tuple.ImmutablePair;
50 import org.apache.commons.lang3.tuple.ImmutableTriple;
51 import org.apache.commons.lang3.tuple.Triple;
52 import org.onap.sdc.tosca.services.YamlUtil;
53 import org.openecomp.sdc.be.components.impl.ImportUtils;
54 import org.openecomp.sdc.be.components.impl.ImportUtils.Constants;
55 import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException;
56 import org.openecomp.sdc.be.config.Configuration.ArtifactTypeConfig;
57 import org.openecomp.sdc.be.config.ConfigurationManager;
58 import org.openecomp.sdc.be.dao.api.ActionStatus;
59 import org.openecomp.sdc.be.dao.cassandra.ArtifactCassandraDao;
60 import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus;
61 import org.openecomp.sdc.be.dao.cassandra.SdcSchemaFilesCassandraDao;
62 import org.openecomp.sdc.be.datatypes.elements.OperationDataDefinition;
63 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
64 import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
65 import org.openecomp.sdc.be.impl.ComponentsUtils;
66 import org.openecomp.sdc.be.model.ArtifactDefinition;
67 import org.openecomp.sdc.be.model.Component;
68 import org.openecomp.sdc.be.model.ComponentInstance;
69 import org.openecomp.sdc.be.model.InterfaceDefinition;
70 import org.openecomp.sdc.be.model.LifecycleStateEnum;
71 import org.openecomp.sdc.be.model.Product;
72 import org.openecomp.sdc.be.model.Resource;
73 import org.openecomp.sdc.be.model.Service;
74 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade;
75 import org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter;
76 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
77 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
78 import org.openecomp.sdc.be.plugins.CsarEntryGenerator;
79 import org.openecomp.sdc.be.resources.data.DAOArtifactData;
80 import org.openecomp.sdc.be.resources.data.SdcSchemaFilesData;
81 import org.openecomp.sdc.be.tosca.model.ToscaTemplate;
82 import org.openecomp.sdc.be.tosca.utils.OperationArtifactUtil;
83 import org.openecomp.sdc.be.utils.CommonBeUtils;
84 import org.openecomp.sdc.be.utils.TypeUtils.ToscaTagNamesEnum;
85 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
86 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
87 import org.openecomp.sdc.common.impl.ExternalConfiguration;
88 import org.openecomp.sdc.common.log.elements.LoggerSupportability;
89 import org.openecomp.sdc.common.log.enums.LoggerSupportabilityActions;
90 import org.openecomp.sdc.common.log.enums.StatusCode;
91 import org.openecomp.sdc.common.log.wrappers.Logger;
92 import org.openecomp.sdc.common.util.GeneralUtility;
93 import org.openecomp.sdc.common.util.ValidationUtils;
94 import org.openecomp.sdc.common.zip.ZipUtils;
95 import org.openecomp.sdc.exception.ResponseFormat;
96 import org.springframework.beans.factory.annotation.Autowired;
97 import org.yaml.snakeyaml.Yaml;
103 @org.springframework.stereotype.Component("csar-utils")
104 public class CsarUtils {
105 private static final Logger log = Logger.getLogger(CsarUtils.class);
106 private static final LoggerSupportability loggerSupportability = LoggerSupportability.getLogger(CsarUtils.class.getName());
107 private static final String PATH_DELIMITER = "/";
109 private SdcSchemaFilesCassandraDao sdcSchemaFilesCassandraDao;
111 private ArtifactCassandraDao artifactCassandraDao;
113 private ComponentsUtils componentsUtils;
115 private ToscaExportHandler toscaExportUtils;
117 protected ToscaOperationFacade toscaOperationFacade;
119 @Autowired(required = false)
120 private List<CsarEntryGenerator> generators;
122 private static final String CONFORMANCE_LEVEL = ConfigurationManager.getConfigurationManager().getConfiguration().getToscaConformanceLevel();
123 private static final String SDC_VERSION = ExternalConfiguration.getAppVersion();
124 public static final String ARTIFACTS_PATH = "Artifacts/";
125 private static final String RESOURCES_PATH = "Resources/";
126 private static final String DEFINITIONS_PATH = "Definitions/";
127 public static final String WORKFLOW_ARTIFACT_DIR = "Workflows"+File.separator+"BPMN"+File.separator;
128 public static final String DEPLOYMENT_ARTIFACTS_DIR = "Deployment"+File.separator;
129 private static final String CSAR_META_VERSION = "1.0";
130 private static final String CSAR_META_PATH_FILE_NAME = "csar.meta";
131 private static final String TOSCA_META_PATH_FILE_NAME = "TOSCA-Metadata/TOSCA.meta";
132 private static final String TOSCA_META_VERSION = "1.0";
133 private static final String CSAR_VERSION = "1.1";
134 public static final String ARTIFACTS = "Artifacts";
135 private static final String DEFINITION = "Definitions";
136 private static final String DEL_PATTERN = "([/\\\\]+)";
137 private static final String WORD_PATTERN = "\\w\\_\\-\\.\\s]+)";
138 public static final String VALID_ENGLISH_ARTIFACT_NAME = "([" + WORD_PATTERN;
139 private static final String VALID_ENGLISH_ARTIFACT_NAME_WITH_DIGITS = "([\\d" + WORD_PATTERN;
140 private static final String ARTIFACT_NAME_UNIQUE_ID = "ArtifactName {}, unique ID {}";
142 private static final String VFC_NODE_TYPE_ARTIFACTS_PATH_PATTERN = ARTIFACTS + DEL_PATTERN +
143 ImportUtils.Constants.USER_DEFINED_RESOURCE_NAMESPACE_PREFIX +
144 VALID_ENGLISH_ARTIFACT_NAME_WITH_DIGITS + DEL_PATTERN +
145 VALID_ENGLISH_ARTIFACT_NAME_WITH_DIGITS + DEL_PATTERN +
146 VALID_ENGLISH_ARTIFACT_NAME_WITH_DIGITS + DEL_PATTERN +
147 VALID_ENGLISH_ARTIFACT_NAME_WITH_DIGITS;
149 public static final String VF_NODE_TYPE_ARTIFACTS_PATH_PATTERN = ARTIFACTS + DEL_PATTERN+
150 // Artifact Group (i.e Deployment/Informational)
151 VALID_ENGLISH_ARTIFACT_NAME + DEL_PATTERN +
153 VALID_ENGLISH_ARTIFACT_NAME + DEL_PATTERN +
154 // Artifact Any File Name
157 public static final String SERVICE_TEMPLATE_PATH_PATTERN = DEFINITION + DEL_PATTERN+
158 // Service Template File Name
159 VALID_ENGLISH_ARTIFACT_NAME;
161 public static final String ARTIFACT_CREATED_FROM_CSAR = "Artifact created from csar";
162 private static final String BLOCK_0_TEMPLATE = "SDC-TOSCA-Meta-File-Version: %s\nSDC-TOSCA-Definitions-Version: %s\n";
164 private String versionFirstThreeOctets;
167 if(SDC_VERSION != null && !SDC_VERSION.isEmpty()){
168 Matcher matcher = Pattern.compile("(?!\\.)(\\d+(\\.\\d+)+)(?![\\d\\.])").matcher(SDC_VERSION);
170 setVersionFirstThreeOctets(matcher.group(0));
172 setVersionFirstThreeOctets("");
180 * @param isInCertificationRequest
183 public Either<byte[], ResponseFormat> createCsar(Component component, boolean getFromCS, boolean isInCertificationRequest) {
184 loggerSupportability.log(LoggerSupportabilityActions.GENERATE_CSAR, StatusCode.STARTED,"Starting to create Csar for component {} ",component.getName());
185 final String createdBy = component.getCreatorFullName();
187 Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts();
188 ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE);
189 fileName = artifactDefinition.getArtifactName();
191 String toscaConformanceLevel = ConfigurationManager.getConfigurationManager().getConfiguration().getToscaConformanceLevel();
192 String csarBlock0 = createCsarBlock0(CSAR_META_VERSION, toscaConformanceLevel);
193 byte[] csarBlock0Byte = csarBlock0.getBytes();
195 final String toscaBlock0 = createToscaBlock0(TOSCA_META_VERSION, CSAR_VERSION, createdBy, fileName);
196 byte[] toscaBlock0Byte = toscaBlock0.getBytes();
198 Either<byte[], ResponseFormat> generateCsarZipResponse = generateCsarZip(csarBlock0Byte, toscaBlock0Byte, component, getFromCS, isInCertificationRequest);
200 if (generateCsarZipResponse.isRight()) {
201 return Either.right(generateCsarZipResponse.right().value());
203 loggerSupportability.log(LoggerSupportabilityActions.GENERATE_CSAR, StatusCode.COMPLETE,"Ended create Csar for component {} ",component.getName());
204 return Either.left(generateCsarZipResponse.left().value());
207 private Either<byte[], ResponseFormat> generateCsarZip(byte[] csarBlock0Byte, byte[] toscaBlock0Byte, Component component, boolean getFromCS, boolean isInCertificationRequest) {
208 try (ByteArrayOutputStream out = new ByteArrayOutputStream();
209 ZipOutputStream zip = new ZipOutputStream(out)) {
210 zip.putNextEntry(new ZipEntry(CSAR_META_PATH_FILE_NAME));
211 zip.write(csarBlock0Byte);
212 zip.putNextEntry(new ZipEntry(TOSCA_META_PATH_FILE_NAME));
213 zip.write(toscaBlock0Byte);
214 Either<ZipOutputStream, ResponseFormat> populateZip = populateZip(component, getFromCS, zip, isInCertificationRequest);
215 if (populateZip.isRight()) {
216 log.debug("Failed to populate CSAR zip file {}. Please fix DB table accordingly ", populateZip.right().value());
217 return Either.right(populateZip.right().value());
221 byte[] byteArray = out.toByteArray();
223 return Either.left(byteArray);
224 } catch (IOException e) {
225 log.debug("Failed with IOexception to create CSAR zip for component {}. Please fix DB table accordingly ", component.getUniqueId(), e);
227 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
228 return Either.right(responseFormat);
232 private Either<ZipOutputStream, ResponseFormat> populateZip(Component component, boolean getFromCS, ZipOutputStream zip, boolean isInCertificationRequest) throws IOException {
234 LifecycleStateEnum lifecycleState = component.getLifecycleState();
235 String componentYaml;
236 Either<ToscaRepresentation, ToscaError> exportComponent;
238 // <file name, cassandraId, component>
239 List<Triple<String, String, Component>> dependencies = null;
241 Map<String, ArtifactDefinition> toscaArtifacts = component.getToscaArtifacts();
242 ArtifactDefinition artifactDefinition = toscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE);
243 String fileName = artifactDefinition.getArtifactName();
245 if (getFromCS || !(lifecycleState == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN || lifecycleState == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT)) {
246 String cassandraId = artifactDefinition.getEsId();
247 Either<byte[], ActionStatus> fromCassandra = getFromCassandra(cassandraId);
248 if (fromCassandra.isRight()) {
249 log.debug(ARTIFACT_NAME_UNIQUE_ID, artifactDefinition.getArtifactName(), artifactDefinition.getUniqueId());
250 ResponseFormat responseFormat = componentsUtils.getResponseFormat(fromCassandra.right().value());
251 return Either.right(responseFormat);
253 mainYaml = fromCassandra.left().value();
256 exportComponent = toscaExportUtils.exportComponent(component);
257 if (exportComponent.isRight()) {
258 log.debug("exportComponent failed", exportComponent.right().value());
259 ActionStatus convertedFromToscaError = componentsUtils.convertFromToscaError(exportComponent.right().value());
260 ResponseFormat responseFormat = componentsUtils.getResponseFormat(convertedFromToscaError);
261 return Either.right(responseFormat);
263 ToscaRepresentation exportResult = exportComponent.left().value();
264 componentYaml = exportResult.getMainYaml();
265 mainYaml = componentYaml.getBytes();
266 dependencies = exportResult.getDependencies();
269 zip.putNextEntry(new ZipEntry(DEFINITIONS_PATH + fileName));
271 //US798487 - Abstraction of complex types
272 if (!ModelConverter.isAtomicComponent(component)){
273 log.debug("Component {} is complex - generating abstract type for it..", component.getName());
274 writeComponentInterface(component, zip, fileName, false);
277 if (dependencies == null) {
278 Either<ToscaTemplate, ToscaError> dependenciesRes = toscaExportUtils.getDependencies(component);
279 if (dependenciesRes.isRight()) {
280 log.debug("Failed to retrieve dependencies for component {}, error {}", component.getUniqueId(),
281 dependenciesRes.right().value());
282 ActionStatus convertFromToscaError = componentsUtils.convertFromToscaError(dependenciesRes.right().value());
283 ResponseFormat responseFormat = componentsUtils.getResponseFormat(convertFromToscaError);
284 return Either.right(responseFormat);
286 dependencies = dependenciesRes.left().value().getDependencies();
289 //UID <cassandraId,filename,component>
290 Map<String, ImmutableTriple<String,String, Component>> innerComponentsCache = new HashMap<>();
292 Either<ZipOutputStream, ResponseFormat> responseFormat = getZipOutputStreamResponseFormatEither(zip, dependencies, innerComponentsCache);
293 if (responseFormat != null) return responseFormat;
295 //retrieve SDC.zip from Cassandra
296 Either<byte[], ResponseFormat> latestSchemaFilesFromCassandra = getLatestSchemaFilesFromCassandra();
298 if(latestSchemaFilesFromCassandra.isRight()){
299 log.error("Error retrieving SDC Schema files from cassandra");
300 return Either.right(latestSchemaFilesFromCassandra.right().value());
303 final byte[] schemaFileZip = latestSchemaFilesFromCassandra.left().value();
305 final List<String> nodesFromPackage = findNonRootNodesFromPackage(dependencies);
307 //add files from retrieved SDC.zip to Definitions folder in CSAR
308 addSchemaFilesFromCassandra(zip, schemaFileZip, nodesFromPackage);
310 Either<CsarDefinition, ResponseFormat> collectedComponentCsarDefinition = collectComponentCsarDefinition(component);
312 if (collectedComponentCsarDefinition.isRight()) {
313 return Either.right(collectedComponentCsarDefinition.right().value());
316 if (generators != null) {
317 for (CsarEntryGenerator generator: generators) {
318 log.debug("Invoking CsarEntryGenerator: {}", generator.getClass().getName());
319 for (Entry<String, byte[]> pluginGeneratedFile : generator.generateCsarEntries(component).entrySet()) {
320 zip.putNextEntry(new ZipEntry(pluginGeneratedFile.getKey()));
321 zip.write(pluginGeneratedFile.getValue());
326 return writeAllFilesToCsar(component, collectedComponentCsarDefinition.left().value(), zip, isInCertificationRequest);
330 * Create a list of all derived nodes found on the package
332 * @param dependencies all node dependencies
333 * @return a list of nodes
335 private List<String> findNonRootNodesFromPackage(final List<Triple<String, String, Component>> dependencies) {
336 final List<String> nodes = new ArrayList<>();
337 if (CollectionUtils.isNotEmpty(dependencies)) {
338 final String NATIVE_ROOT = "tosca.nodes.Root";
339 dependencies.forEach(dependency -> {
340 if (dependency.getRight() instanceof Resource) {
341 final Resource resource = (Resource) dependency.getRight();
342 if (CollectionUtils.isNotEmpty(resource.getDerivedList())) {
343 resource.getDerivedList().stream()
344 .filter(node -> !nodes.contains(node) && !NATIVE_ROOT.equalsIgnoreCase(node))
345 .forEach(node -> nodes.add(node));
354 * Writes a new zip entry
356 * @param zipInputStream the zip entry to be read
357 * @return a map of the given zip entry
359 private Map<String, Object> readYamlZipEntry(final ZipInputStream zipInputStream) throws IOException {
360 final int initSize = 2048;
361 final StringBuilder zipEntry = new StringBuilder();
362 final byte[] buffer = new byte[initSize];
364 while ((read = zipInputStream.read(buffer, 0, initSize)) >= 0) {
365 zipEntry.append(new String(buffer, 0, read));
368 return (Map<String, Object>) new Yaml().load(zipEntry.toString());
372 * Filters and removes all duplicated nodes found
374 * @param nodesFromPackage a List of all derived nodes found on the given package
375 * @param nodesFromArtifactFile represents the nodes.yml file stored in Cassandra
376 * @return a nodes Map updated
378 private Map<String, Object> updateNodeYml(final List<String> nodesFromPackage,
379 final Map<String, Object> nodesFromArtifactFile) {
381 if (MapUtils.isNotEmpty(nodesFromArtifactFile)) {
382 final String nodeTypeBlock = ToscaTagNamesEnum.NODE_TYPES.getElementName();
383 final Map<String, Object> nodeTypes = (Map<String, Object>) nodesFromArtifactFile.get(nodeTypeBlock);
384 nodesFromPackage.stream()
385 .filter(nodeTypes::containsKey)
386 .forEach(nodeTypes::remove);
388 nodesFromArtifactFile.replace(nodeTypeBlock, nodeTypes);
391 return nodesFromArtifactFile;
395 * Updates the zip entry from the given parameters
397 * @param byteArrayOutputStream an output stream in which the data is written into a byte array.
398 * @param nodesYaml a Map of nodes to be written
400 private void updateZipEntry(final ByteArrayOutputStream byteArrayOutputStream,
401 final Map<String, Object> nodesYaml) throws IOException {
402 if (MapUtils.isNotEmpty(nodesYaml)) {
403 byteArrayOutputStream.write(new YamlUtil().objectToYaml(nodesYaml).getBytes());
407 private Either<ZipOutputStream, ResponseFormat> getZipOutputStreamResponseFormatEither(ZipOutputStream zip, List<Triple<String, String, Component>> dependencies, Map<String, ImmutableTriple<String, String, Component>> innerComponentsCache) throws IOException {
409 if (dependencies != null && !dependencies.isEmpty()) {
410 for (Triple<String, String, Component> d : dependencies) {
411 String cassandraId = d.getMiddle();
412 Component childComponent = d.getRight();
413 Either<byte[], ActionStatus> entryData = getEntryData(cassandraId, childComponent);
415 if (entryData.isRight()) {
416 ResponseFormat responseFormat = componentsUtils.getResponseFormat(entryData.right().value());
417 return Either.right(responseFormat);
420 //fill innerComponentsCache
421 fileName = d.getLeft();
422 addComponentToCache(innerComponentsCache, cassandraId, fileName, childComponent);
423 addInnerComponentsToCache(innerComponentsCache, childComponent);
426 //add inner components to CSAR
427 Either<ZipOutputStream, ResponseFormat> responseFormat = addInnerComponentsToCSAR(zip, innerComponentsCache);
428 if (responseFormat != null) return responseFormat;
433 private Either<ZipOutputStream, ResponseFormat> addInnerComponentsToCSAR(ZipOutputStream zip, Map<String, ImmutableTriple<String, String, Component>> innerComponentsCache) throws IOException {
434 for (Entry<String, ImmutableTriple<String, String, Component>> innerComponentTripleEntry : innerComponentsCache.entrySet()) {
436 ImmutableTriple<String, String, Component> innerComponentTriple = innerComponentTripleEntry.getValue();
438 Component innerComponent = innerComponentTriple.getRight();
439 String icFileName = innerComponentTriple.getMiddle();
441 // add component to zip
442 Either<byte[], ActionStatus> entryData = getEntryData(innerComponentTriple.getLeft(), innerComponent);
443 if (entryData.isRight()) {
444 ResponseFormat responseFormat = componentsUtils.getResponseFormat(entryData.right().value());
445 log.debug("Failed adding to zip component {}, error {}", innerComponentTriple.getLeft(),
446 entryData.right().value());
447 return Either.right(responseFormat);
449 byte[] content = entryData.left().value();
450 zip.putNextEntry(new ZipEntry(DEFINITIONS_PATH + icFileName));
453 // add component interface to zip
454 if (!ModelConverter.isAtomicComponent(innerComponent)) {
455 writeComponentInterface(innerComponent, zip, icFileName, true);
461 private void addSchemaFilesFromCassandra(final ZipOutputStream zip,
462 final byte[] schemaFileZip,
463 final List<String> nodesFromPackage) {
464 final int initSize = 2048;
465 log.debug("Starting copy from Schema file zip to CSAR zip");
466 try (final ZipInputStream zipStream = new ZipInputStream(new ByteArrayInputStream(schemaFileZip));
467 final ByteArrayOutputStream out = new ByteArrayOutputStream();
468 final BufferedOutputStream bos = new BufferedOutputStream(out, initSize)) {
471 while ((entry = zipStream.getNextEntry()) != null) {
472 ZipUtils.checkForZipSlipInRead(entry);
473 final String entryName = entry.getName();
474 int readSize = initSize;
475 final byte[] entryData = new byte[initSize];
476 if (entryName.equalsIgnoreCase("nodes.yml")) {
477 handleNode(zipStream, out, nodesFromPackage);
479 while ((readSize = zipStream.read(entryData, 0, readSize)) != -1) {
480 bos.write(entryData, 0, readSize);
485 zip.putNextEntry(new ZipEntry(DEFINITIONS_PATH + entryName));
486 zip.write(out.toByteArray());
490 } catch (final Exception e) {
491 log.error("Error while writing the SDC schema file to the CSAR", e);
492 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
494 log.debug("Finished copy from Schema file zip to CSAR zip");
498 * Handles the nodes.yml zip entry, updating the nodes.yml to avoid duplicated nodes on it.
500 * @param zipInputStream the zip entry to be read
501 * @param byteArrayOutputStream an output stream in which the data is written into a byte array.
502 * @param nodesFromPackage list of all nodes found on the onboarded package
504 private void handleNode(final ZipInputStream zipInputStream,
505 final ByteArrayOutputStream byteArrayOutputStream,
506 final List<String> nodesFromPackage) throws IOException {
508 final Map<String, Object> nodesFromArtifactFile = readYamlZipEntry(zipInputStream);
509 final Map<String, Object> nodesYaml = updateNodeYml(nodesFromPackage, nodesFromArtifactFile);
510 updateZipEntry(byteArrayOutputStream, nodesYaml);
513 private void addInnerComponentsToCache(Map<String, ImmutableTriple<String, String, Component>> componentCache,
514 Component childComponent) {
516 List<ComponentInstance> instances = childComponent.getComponentInstances();
518 if(instances != null) {
519 instances.forEach(ci -> {
520 ImmutableTriple<String, String, Component> componentRecord = componentCache.get(ci.getComponentUid());
521 if (componentRecord == null) {
522 // all resource must be only once!
523 Either<Resource, StorageOperationStatus> resource = toscaOperationFacade.getToscaElement(ci.getComponentUid());
524 Component componentRI = checkAndAddComponent(componentCache, ci, resource);
526 //if not atomic - insert inner components as well
527 if(!ModelConverter.isAtomicComponent(componentRI)) {
528 addInnerComponentsToCache(componentCache, componentRI);
535 private Component checkAndAddComponent(Map<String, ImmutableTriple<String, String, Component>> componentCache, ComponentInstance ci, Either<Resource, StorageOperationStatus> resource) {
536 if (resource.isRight()) {
537 log.debug("Failed to fetch resource with id {} for instance {}", ci.getComponentUid(), ci.getName());
539 Component componentRI = resource.left().value();
541 Map<String, ArtifactDefinition> childToscaArtifacts = componentRI.getToscaArtifacts();
542 ArtifactDefinition childArtifactDefinition = childToscaArtifacts.get(ToscaExportHandler.ASSET_TOSCA_TEMPLATE);
543 if (childArtifactDefinition != null) {
545 addComponentToCache(componentCache, childArtifactDefinition.getEsId(), childArtifactDefinition.getArtifactName(), componentRI);
550 private void addComponentToCache(Map<String, ImmutableTriple<String, String, Component>> componentCache,
551 String id, String fileName, Component component) {
553 ImmutableTriple<String, String, Component> cachedComponent = componentCache.get(component.getInvariantUUID());
554 if (cachedComponent == null || CommonBeUtils.compareAsdcComponentVersions(component.getVersion(), cachedComponent.getRight().getVersion())) {
555 componentCache.put(component.getInvariantUUID(),
556 new ImmutableTriple<>(id, fileName, component));
558 if(cachedComponent != null) {
559 //overwriting component with newer version
560 log.warn("Overwriting component invariantID {} of version {} with a newer version {}", id, cachedComponent.getRight().getVersion(), component.getVersion());
564 private Either<ZipOutputStream, ResponseFormat> writeComponentInterface(Component component, ZipOutputStream zip,
565 String fileName, boolean isAssociatedComponent) {
567 Either<ToscaRepresentation, ToscaError> componentInterface = toscaExportUtils
568 .exportComponentInterface(component, isAssociatedComponent);
569 ToscaRepresentation componentInterfaceYaml = componentInterface.left().value();
570 String mainYaml = componentInterfaceYaml.getMainYaml();
571 String interfaceFileName = DEFINITIONS_PATH + ToscaExportHandler.getInterfaceFilename(fileName);
573 zip.putNextEntry(new ZipEntry(interfaceFileName));
574 zip.write(mainYaml.getBytes());
576 } catch (Exception e) {
577 log.error("#writeComponentInterface - zip writing failed with error: ", e);
578 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
581 return Either.left(zip);
584 private Either<byte[], ActionStatus> getEntryData(String cassandraId, Component childComponent) {
586 if (cassandraId == null || cassandraId.isEmpty()) {
587 Either<ToscaRepresentation, ToscaError> exportRes = toscaExportUtils.exportComponent(childComponent);
588 if (exportRes.isRight()) {
589 log.debug("Failed to export tosca template for child component {} error {}",
590 childComponent.getUniqueId(), exportRes.right().value());
591 return Either.right(componentsUtils.convertFromToscaError(exportRes.right().value()));
593 content = exportRes.left().value().getMainYaml().getBytes();
595 Either<byte[], ActionStatus> fromCassandra = getFromCassandra(cassandraId);
596 if (fromCassandra.isRight()) {
597 return Either.right(fromCassandra.right().value());
599 content = fromCassandra.left().value();
602 return Either.left(content);
605 private Either<byte[], ResponseFormat> getLatestSchemaFilesFromCassandra() {
606 Either<List<SdcSchemaFilesData>, CassandraOperationStatus> specificSchemaFiles = sdcSchemaFilesCassandraDao.getSpecificSchemaFiles(getVersionFirstThreeOctets(), CONFORMANCE_LEVEL);
608 if(specificSchemaFiles.isRight()){
609 log.debug("Failed to get the schema files SDC-Version: {} Conformance-Level {}. Please fix DB table accordingly.", getVersionFirstThreeOctets(), CONFORMANCE_LEVEL);
610 StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(specificSchemaFiles.right().value());
611 ActionStatus convertedFromStorageResponse = componentsUtils.convertFromStorageResponse(storageStatus);
612 return Either.right(componentsUtils.getResponseFormat(convertedFromStorageResponse));
615 List<SdcSchemaFilesData> listOfSchemas = specificSchemaFiles.left().value();
617 if(listOfSchemas.isEmpty()){
618 log.debug("Failed to get the schema files SDC-Version: {} Conformance-Level {}", getVersionFirstThreeOctets(), CONFORMANCE_LEVEL);
619 return Either.right(componentsUtils.getResponseFormat(ActionStatus.TOSCA_SCHEMA_FILES_NOT_FOUND, getVersionFirstThreeOctets(), CONFORMANCE_LEVEL));
622 SdcSchemaFilesData schemaFile = listOfSchemas.iterator().next();
624 return Either.left(schemaFile.getPayloadAsArray());
627 private Either<byte[], ActionStatus> getFromCassandra(String cassandraId) {
628 Either<DAOArtifactData, CassandraOperationStatus> artifactResponse = artifactCassandraDao.getArtifact(cassandraId);
630 if (artifactResponse.isRight()) {
631 log.debug("Failed to fetch artifact from Cassandra by id {} error {} ", cassandraId, artifactResponse.right().value());
633 StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(artifactResponse.right().value());
634 ActionStatus convertedFromStorageResponse = componentsUtils.convertFromStorageResponse(storageStatus);
635 return Either.right(convertedFromStorageResponse);
637 DAOArtifactData artifactData = artifactResponse.left().value();
638 return Either.left(artifactData.getDataAsArray());
641 private String createCsarBlock0(String metaFileVersion, String toscaConformanceLevel) {
642 return String.format(BLOCK_0_TEMPLATE, metaFileVersion, toscaConformanceLevel);
645 private String createToscaBlock0(String metaFileVersion, String csarVersion, String createdBy, String entryDef) {
646 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";
647 return String.format(block0template, metaFileVersion, csarVersion, createdBy, entryDef);
651 * Extracts artifacts of VFCs from CSAR
654 * @return Map of <String, List<ArtifactDefinition>> the contains Lists of artifacts according vfcToscaNamespace
656 public static Map<String, List<ArtifactDefinition>> extractVfcsArtifactsFromCsar(Map<String, byte[]> csar) {
658 Map<String, List<ArtifactDefinition>> artifacts = new HashMap<>();
660 log.debug("************* Going to extract VFCs artifacts from Csar. ");
661 Map<String, Set<List<String>>> collectedWarningMessages = new HashMap<>();
662 csar.entrySet().stream()
663 // filter CSAR entry by node type artifact path
664 .filter(e -> Pattern.compile(VFC_NODE_TYPE_ARTIFACTS_PATH_PATTERN).matcher(e.getKey()).matches())
665 // extract ArtifactDefinition from CSAR entry for each entry with matching artifact path
666 .forEach(e -> addExtractedVfcArtifact(extractVfcArtifact(e, collectedWarningMessages), artifacts));
667 // add counter suffix to artifact labels
668 handleWarningMessages(collectedWarningMessages);
675 * Print warnings to log
677 * @param collectedWarningMessages
679 public static void handleWarningMessages(Map<String, Set<List<String>>> collectedWarningMessages) {
680 collectedWarningMessages.entrySet().stream()
682 .forEach(e -> e.getValue().stream()
683 // add each warning message to log
684 .forEach(args -> log.warn(e.getKey(), args.toArray())));
688 private static void addExtractedVfcArtifact(ImmutablePair<String, ArtifactDefinition> extractedVfcArtifact, Map<String, List<ArtifactDefinition>> artifacts) {
689 if (extractedVfcArtifact != null) {
690 List<ArtifactDefinition> currArtifactsList;
691 String vfcToscaNamespace = extractedVfcArtifact.getKey();
692 if (artifacts.containsKey(vfcToscaNamespace)) {
693 currArtifactsList = artifacts.get(vfcToscaNamespace);
695 currArtifactsList = new ArrayList<>();
696 artifacts.put(vfcToscaNamespace, currArtifactsList);
698 currArtifactsList.add(extractedVfcArtifact.getValue());
702 private static ImmutablePair<String, ArtifactDefinition> extractVfcArtifact(Entry<String, byte[]> entry, Map<String, Set<List<String>>> collectedWarningMessages) {
703 ArtifactDefinition artifact;
704 String[] parsedCsarArtifactPath = entry.getKey().split(PATH_DELIMITER);
705 Either<ArtifactGroupTypeEnum, Boolean> eitherArtifactGroupType = detectArtifactGroupType(parsedCsarArtifactPath[2].toUpperCase(), collectedWarningMessages);
706 if (eitherArtifactGroupType.isLeft()) {
707 artifact = buildArtifactDefinitionFromCsarArtifactPath(entry, collectedWarningMessages, parsedCsarArtifactPath, eitherArtifactGroupType.left().value());
711 return new ImmutablePair<>(parsedCsarArtifactPath[1], artifact);
714 private static Either<ArtifactGroupTypeEnum, Boolean> detectArtifactGroupType(String groupType, Map<String, Set<List<String>>> collectedWarningMessages) {
715 Either<ArtifactGroupTypeEnum, Boolean> result;
717 ArtifactGroupTypeEnum artifactGroupType = ArtifactGroupTypeEnum.findType(groupType.toUpperCase());
718 if (artifactGroupType == null || (artifactGroupType != ArtifactGroupTypeEnum.INFORMATIONAL && artifactGroupType != ArtifactGroupTypeEnum.DEPLOYMENT)) {
719 String warningMessage = "Warning - unrecognized artifact group type {} was received.";
720 List<String> messageArguments = new ArrayList<>();
721 messageArguments.add(groupType);
722 if (!collectedWarningMessages.containsKey(warningMessage)) {
723 Set<List<String>> messageArgumentLists = new HashSet<>();
724 messageArgumentLists.add(messageArguments);
725 collectedWarningMessages.put(warningMessage, messageArgumentLists);
727 collectedWarningMessages.get(warningMessage).add(messageArguments);
730 result = Either.right(false);
733 result = Either.left(artifactGroupType);
735 } catch (Exception e) {
736 log.debug("detectArtifactGroupType failed with exception", e);
737 result = Either.right(false);
742 private static ArtifactDefinition buildArtifactDefinitionFromCsarArtifactPath(Entry<String, byte[]> entry, Map<String, Set<List<String>>> collectedWarningMessages, String[] parsedCsarArtifactPath, ArtifactGroupTypeEnum artifactGroupType) {
743 ArtifactDefinition artifact;
744 artifact = new ArtifactDefinition();
745 artifact.setArtifactGroupType(artifactGroupType);
746 artifact.setArtifactType(detectArtifactTypeVFC(artifactGroupType, parsedCsarArtifactPath[3], parsedCsarArtifactPath[1], collectedWarningMessages));
747 artifact.setArtifactName(ValidationUtils.normalizeFileName(parsedCsarArtifactPath[parsedCsarArtifactPath.length - 1]));
748 artifact.setPayloadData(Base64.encodeBase64String(entry.getValue()));
749 artifact.setArtifactDisplayName(artifact.getArtifactName().lastIndexOf('.') > 0 ? artifact.getArtifactName().substring(0, artifact.getArtifactName().lastIndexOf('.')) : artifact.getArtifactName());
750 artifact.setArtifactLabel(ValidationUtils.normalizeArtifactLabel(artifact.getArtifactName()));
751 artifact.setDescription(ARTIFACT_CREATED_FROM_CSAR);
752 artifact.setIsFromCsar(true);
753 artifact.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(entry.getValue()));
757 public static final class NonMetaArtifactInfo {
758 private final String path;
759 private final String artifactName;
760 private final String displayName;
761 private final String artifactLabel;
762 private final ArtifactTypeEnum artifactType;
763 private final ArtifactGroupTypeEnum artifactGroupType;
764 private String payloadData;
765 private String artifactChecksum;
766 private String artifactUniqueId;
767 private final boolean isFromCsar;
769 public NonMetaArtifactInfo(String artifactName, String path, ArtifactTypeEnum artifactType, ArtifactGroupTypeEnum artifactGroupType, byte[] payloadData, String artifactUniqueId, boolean isFromCsar) {
772 this.isFromCsar = isFromCsar;
773 this.artifactName = ValidationUtils.normalizeFileName(artifactName);
774 this.artifactType = artifactType;
775 this.artifactGroupType = artifactGroupType;
776 final int pointIndex = artifactName.lastIndexOf('.');
777 if (pointIndex > 0) {
778 displayName = artifactName.substring(0, pointIndex);
780 displayName = artifactName;
782 this.artifactLabel = ValidationUtils.normalizeArtifactLabel(artifactName);
783 if (payloadData != null) {
784 this.payloadData = Base64.encodeBase64String(payloadData);
785 this.artifactChecksum = GeneralUtility.calculateMD5Base64EncodedByByteArray(payloadData);
787 this.artifactUniqueId = artifactUniqueId;
790 public String getPath() {
794 public String getArtifactName() {
798 public ArtifactTypeEnum getArtifactType() {
802 public String getDisplayName() {
806 public ArtifactGroupTypeEnum getArtifactGroupType() {
807 return artifactGroupType;
810 public String getArtifactLabel() {
811 return artifactLabel;
814 public boolean isFromCsar(){
818 public String getPayloadData() {
822 public String getArtifactChecksum() {
823 return artifactChecksum;
826 public String getArtifactUniqueId() {
827 return artifactUniqueId;
830 public void setArtifactUniqueId(String artifactUniqueId) {
831 this.artifactUniqueId = artifactUniqueId;
837 * This method checks the artifact GroupType & Artifact Type. <br>
838 * if there is any problem warning messages are added to collectedWarningMessages
840 * @param artifactPath
841 * @param collectedWarningMessages
844 public static Either<NonMetaArtifactInfo, Boolean> validateNonMetaArtifact(String artifactPath, byte[] payloadData, Map<String, Set<List<String>>> collectedWarningMessages) {
845 Either<NonMetaArtifactInfo, Boolean> ret;
847 String[] parsedArtifactPath = artifactPath.split(PATH_DELIMITER);
848 // Validate Artifact Group Type
849 Either<ArtifactGroupTypeEnum, Boolean> eitherGroupType = detectArtifactGroupType(parsedArtifactPath[1], collectedWarningMessages);
850 if (eitherGroupType.isLeft()) {
851 final ArtifactGroupTypeEnum groupTypeEnum = eitherGroupType.left().value();
853 // Validate Artifact Type
854 String artifactType = parsedArtifactPath[2];
855 artifactType = detectArtifactTypeVF(groupTypeEnum, artifactType, collectedWarningMessages);
857 String artifactFileNameType = parsedArtifactPath[3];
858 ret = Either.left(new NonMetaArtifactInfo(artifactFileNameType, artifactPath, ArtifactTypeEnum.findType(artifactType), groupTypeEnum, payloadData, null, true));
861 ret = Either.right(eitherGroupType.right().value());
863 } catch (Exception e) {
864 log.debug("detectArtifactGroupType failed with exception", e);
865 ret = Either.right(false);
871 private static String detectArtifactTypeVFC(ArtifactGroupTypeEnum artifactGroupType, String receivedTypeName, String parentVfName, Map<String, Set<List<String>>> collectedWarningMessages) {
872 String warningMessage = "Warning - artifact type {} that was provided for VFC {} is not recognized.";
873 return detectArtifactType(artifactGroupType, receivedTypeName, warningMessage, collectedWarningMessages, parentVfName);
876 private static String detectArtifactTypeVF(ArtifactGroupTypeEnum artifactGroupType, String receivedTypeName, Map<String, Set<List<String>>> collectedWarningMessages) {
877 String warningMessage = "Warning - artifact type {} that was provided for VF is not recognized.";
878 return detectArtifactType(artifactGroupType, receivedTypeName, warningMessage, collectedWarningMessages);
881 private static String detectArtifactType(ArtifactGroupTypeEnum artifactGroupType, String receivedTypeName, String warningMessage, Map<String, Set<List<String>>> collectedWarningMessages, String... arguments) {
883 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(receivedTypeName);
884 Map<String, ArtifactTypeConfig> resourceValidTypeArtifacts = null;
886 if(artifactGroupType != null){
887 switch (artifactGroupType) {
889 resourceValidTypeArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration()
890 .getResourceInformationalArtifacts();
893 resourceValidTypeArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration()
894 .getResourceDeploymentArtifacts();
901 Set<String> validArtifactTypes = null;
902 if(resourceValidTypeArtifacts != null){
903 validArtifactTypes = resourceValidTypeArtifacts.keySet();
906 if (validArtifactTypes == null || artifactType == null || !validArtifactTypes.contains(artifactType.getType())) {
907 List<String> messageArguments = new ArrayList<>();
908 messageArguments.add(receivedTypeName);
909 messageArguments.addAll(Arrays.asList(arguments));
910 if (!collectedWarningMessages.containsKey(warningMessage)) {
911 Set<List<String>> messageArgumentLists = new HashSet<>();
912 messageArgumentLists.add(messageArguments);
913 collectedWarningMessages.put(warningMessage, messageArgumentLists);
915 collectedWarningMessages.get(warningMessage).add(messageArguments);
919 return artifactType == null ? ArtifactTypeEnum.OTHER.getType() : artifactType.getType();
922 private Either<ZipOutputStream, ResponseFormat> writeAllFilesToCsar(Component mainComponent, CsarDefinition csarDefinition, ZipOutputStream zipstream, boolean isInCertificationRequest) throws IOException{
923 ComponentArtifacts componentArtifacts = csarDefinition.getComponentArtifacts();
925 Either<ZipOutputStream, ResponseFormat> writeComponentArtifactsToSpecifiedPath = writeComponentArtifactsToSpecifiedPath(mainComponent, componentArtifacts, zipstream, ARTIFACTS_PATH, isInCertificationRequest);
927 if(writeComponentArtifactsToSpecifiedPath.isRight()){
928 return Either.right(writeComponentArtifactsToSpecifiedPath.right().value());
931 ComponentTypeArtifacts mainTypeAndCIArtifacts = componentArtifacts.getMainTypeAndCIArtifacts();
932 writeComponentArtifactsToSpecifiedPath = writeArtifactsInfoToSpecifiedtPath(mainComponent, mainTypeAndCIArtifacts.getComponentArtifacts(), zipstream, ARTIFACTS_PATH, isInCertificationRequest);
934 if(writeComponentArtifactsToSpecifiedPath.isRight()){
935 return Either.right(writeComponentArtifactsToSpecifiedPath.right().value());
938 Map<String, ArtifactsInfo> componentInstancesArtifacts = mainTypeAndCIArtifacts.getComponentInstancesArtifacts();
939 Set<String> keySet = componentInstancesArtifacts.keySet();
941 String currentPath = ARTIFACTS_PATH + RESOURCES_PATH;
942 for (String keyAssetName : keySet) {
943 ArtifactsInfo artifactsInfo = componentInstancesArtifacts.get(keyAssetName);
944 String pathWithAssetName = currentPath + keyAssetName + PATH_DELIMITER;
945 writeComponentArtifactsToSpecifiedPath = writeArtifactsInfoToSpecifiedtPath(mainComponent, artifactsInfo, zipstream, pathWithAssetName, isInCertificationRequest);
947 if(writeComponentArtifactsToSpecifiedPath.isRight()){
948 return Either.right(writeComponentArtifactsToSpecifiedPath.right().value());
951 writeComponentArtifactsToSpecifiedPath = writeOperationsArtifactsToCsar(mainComponent, zipstream);
953 if (writeComponentArtifactsToSpecifiedPath.isRight()) {
954 return Either.right(writeComponentArtifactsToSpecifiedPath.right().value());
956 return Either.left(zipstream);
959 private Either<ZipOutputStream, ResponseFormat> writeOperationsArtifactsToCsar(Component component,
960 ZipOutputStream zipstream) {
961 if (checkComponentBeforeOperation(component)) return Either.left(zipstream);
962 final Map<String, InterfaceDefinition> interfaces = ((Resource) component).getInterfaces();
963 for (Map.Entry<String, InterfaceDefinition> interfaceEntry : interfaces.entrySet()) {
964 for (OperationDataDefinition operation : interfaceEntry.getValue().getOperations().values()) {
966 if (checkComponentBeforeWrite(component, interfaceEntry, operation)) continue;
967 final String artifactUUID = operation.getImplementation().getArtifactUUID();
968 final Either<byte[], ActionStatus> artifactFromCassandra = getFromCassandra(artifactUUID);
969 final String artifactName = operation.getImplementation().getArtifactName();
970 if (artifactFromCassandra.isRight()) {
971 log.error(ARTIFACT_NAME_UNIQUE_ID, artifactName, artifactUUID);
972 log.error("Failed to get {} payload from DB reason: {}", artifactName,
973 artifactFromCassandra.right().value());
974 return Either.right(componentsUtils.getResponseFormat(
975 ActionStatus.ARTIFACT_PAYLOAD_NOT_FOUND_DURING_CSAR_CREATION, "Resource",
976 component.getUniqueId(), artifactName, artifactUUID));
978 final byte[] payloadData = artifactFromCassandra.left().value();
979 zipstream.putNextEntry(new ZipEntry(OperationArtifactUtil.createOperationArtifactPath(
980 component, null, operation,true)));
981 zipstream.write(payloadData);
982 } catch (IOException e) {
983 log.error("Component Name {}, Interface Name {}, Operation Name {}", component.getNormalizedName(),
984 interfaceEntry.getKey(), operation.getName());
985 log.error("Error while writing the operation's artifacts to the CSAR " + "{}", e);
986 return Either.right(componentsUtils
987 .getResponseFormat(ActionStatus.ERROR_DURING_CSAR_CREATION, "Resource",
988 component.getUniqueId()));
992 return Either.left(zipstream);
995 private boolean checkComponentBeforeWrite(Component component, Entry<String, InterfaceDefinition> interfaceEntry, OperationDataDefinition operation) {
996 if (Objects.isNull(operation.getImplementation())) {
997 log.debug("Component Name {}, Interface Id {}, Operation Name {} - no Operation Implementation found",
998 component.getNormalizedName(), interfaceEntry.getValue().getUniqueId(),
999 operation.getName());
1002 if (Objects.isNull(operation.getImplementation().getArtifactName())) {
1003 log.debug("Component Name {}, Interface Id {}, Operation Name {} - no artifact found",
1004 component.getNormalizedName(), interfaceEntry.getValue().getUniqueId(),
1005 operation.getName());
1008 if (operation.getImplementation().getArtifactName().startsWith(Constants.ESCAPED_DOUBLE_QUOTE) && operation.getImplementation().getArtifactName().endsWith(Constants.ESCAPED_DOUBLE_QUOTE)) {
1009 log.debug("Component Name {}, Interface Id {}, Operation Name {} - artifact name is a literal value rather than an SDC artifact",
1010 component.getNormalizedName(), interfaceEntry.getValue().getUniqueId(),
1011 operation.getName());
1017 private boolean checkComponentBeforeOperation(Component component) {
1018 if (component instanceof Service) {
1021 if (Objects.isNull(((Resource) component).getInterfaces())) {
1022 log.debug("Component Name {}- no interfaces found", component.getNormalizedName());
1028 private Either<ZipOutputStream, ResponseFormat> writeComponentArtifactsToSpecifiedPath(Component mainComponent, ComponentArtifacts componentArtifacts, ZipOutputStream zipstream,
1029 String currentPath, boolean isInCertificationRequest) throws IOException {
1030 Map<String, ComponentTypeArtifacts> componentTypeArtifacts = componentArtifacts.getComponentTypeArtifacts();
1032 //<Inner Asset TOSCA name (e.g. VFC name)> folder name: <Inner Asset TOSCA name (e.g. VFC name)>_v<version>.
1033 //E.g. "org.openecomp.resource.vf.vipr_atm_v1.0"
1034 Set<String> componentTypeArtifactsKeys = componentTypeArtifacts.keySet();
1035 for (String keyAssetName : componentTypeArtifactsKeys) {
1036 ComponentTypeArtifacts componentInstanceArtifacts = componentTypeArtifacts.get(keyAssetName);
1037 ArtifactsInfo componentArtifacts2 = componentInstanceArtifacts.getComponentArtifacts();
1038 String pathWithAssetName = currentPath + keyAssetName + PATH_DELIMITER;
1039 Either<ZipOutputStream, ResponseFormat> writeArtifactsInfoToSpecifiedPath = writeArtifactsInfoToSpecifiedtPath(mainComponent, componentArtifacts2, zipstream, pathWithAssetName, isInCertificationRequest);
1041 if(writeArtifactsInfoToSpecifiedPath.isRight()){
1042 return writeArtifactsInfoToSpecifiedPath;
1046 return Either.left(zipstream);
1049 private Either<ZipOutputStream, ResponseFormat> writeArtifactsInfoToSpecifiedtPath(Component mainComponent, ArtifactsInfo currArtifactsInfo, ZipOutputStream zip, String path, boolean isInCertificationRequest) throws IOException {
1050 Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> artifactsInfo = currArtifactsInfo
1051 .getArtifactsInfo();
1052 Set<ArtifactGroupTypeEnum> groupTypeEnumKeySet = artifactsInfo.keySet();
1054 for (ArtifactGroupTypeEnum artifactGroupTypeEnum : groupTypeEnumKeySet) {
1055 String groupTypeFolder = path + WordUtils.capitalizeFully(artifactGroupTypeEnum.getType()) + PATH_DELIMITER;
1057 Map<ArtifactTypeEnum, List<ArtifactDefinition>> artifactTypesMap = artifactsInfo.get(artifactGroupTypeEnum);
1058 Set<ArtifactTypeEnum> artifactTypeEnumKeySet = artifactTypesMap.keySet();
1060 for (ArtifactTypeEnum artifactTypeEnum : artifactTypeEnumKeySet) {
1061 List<ArtifactDefinition> artifactDefinitionList = artifactTypesMap.get(artifactTypeEnum);
1062 String artifactTypeFolder = groupTypeFolder + artifactTypeEnum.toString() + PATH_DELIMITER;
1064 if(artifactTypeEnum == ArtifactTypeEnum.WORKFLOW && path.contains(ARTIFACTS_PATH + RESOURCES_PATH)){
1065 // Ignore this packaging as BPMN artifacts needs to be packaged in different manner
1068 if (artifactTypeEnum == ArtifactTypeEnum.WORKFLOW) {
1069 artifactTypeFolder += OperationArtifactUtil.BPMN_ARTIFACT_PATH + File.separator;
1072 Either<ZipOutputStream, ResponseFormat> writeArtifactDefinition = writeArtifactDefinition(mainComponent, zip, artifactDefinitionList, artifactTypeFolder, isInCertificationRequest);
1074 if(writeArtifactDefinition.isRight()){
1075 return writeArtifactDefinition;
1080 return Either.left(zip);
1083 private Either<ZipOutputStream, ResponseFormat> writeArtifactDefinition(Component mainComponent, ZipOutputStream zip, List<ArtifactDefinition> artifactDefinitionList,
1084 String artifactPathAndFolder, boolean isInCertificationRequest) throws IOException {
1086 ComponentTypeEnum componentType = mainComponent.getComponentType();
1087 String heatEnvType = ArtifactTypeEnum.HEAT_ENV.getType();
1089 for (ArtifactDefinition artifactDefinition : artifactDefinitionList) {
1090 if (!isInCertificationRequest && componentType == ComponentTypeEnum.SERVICE
1091 && artifactDefinition.getArtifactType().equals(heatEnvType) ||
1092 //this is placeholder
1093 (artifactDefinition.getEsId() == null && artifactDefinition.getMandatory())){
1097 byte[] payloadData = artifactDefinition.getPayloadData();
1098 String artifactFileName = artifactDefinition.getArtifactName();
1100 if (payloadData == null) {
1101 Either<byte[], ActionStatus> fromCassandra = getFromCassandra(artifactDefinition.getEsId());
1103 if (fromCassandra.isRight()) {
1104 log.debug(ARTIFACT_NAME_UNIQUE_ID, artifactDefinition.getArtifactName(), artifactDefinition.getUniqueId());
1105 log.debug("Failed to get {} payload from DB reason: {}", artifactFileName, fromCassandra.right().value());
1108 payloadData = fromCassandra.left().value();
1110 zip.putNextEntry(new ZipEntry(artifactPathAndFolder + artifactFileName));
1111 zip.write(payloadData);
1114 return Either.left(zip);
1117 /************************************ Artifacts Structure ******************************************************************/
1119 * The artifacts Definition saved by their structure
1121 private class ArtifactsInfo {
1122 //Key is the type of artifacts(Informational/Deployment)
1123 //Value is a map between an artifact type and a list of all artifacts of this type
1124 private Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> artifactsInfoField;
1126 public ArtifactsInfo() {
1127 this.artifactsInfoField = new EnumMap<>(ArtifactGroupTypeEnum.class);
1130 public Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> getArtifactsInfo() {
1131 return artifactsInfoField;
1134 public List<ArtifactDefinition> getFlatArtifactsListByType(ArtifactTypeEnum artifactType){
1135 List<ArtifactDefinition> artifacts = new ArrayList<>();
1136 for (List<ArtifactDefinition> artifactsByType:artifactsInfoField.get(artifactType).values()){
1137 artifacts.addAll(artifactsByType);
1142 public void addArtifactsToGroup(ArtifactGroupTypeEnum artifactGroup,Map<ArtifactTypeEnum, List<ArtifactDefinition>> artifactsDefinition){
1143 if (artifactsInfoField.get(artifactGroup) == null) {
1144 artifactsInfoField.put(artifactGroup, artifactsDefinition);
1146 Map<ArtifactTypeEnum, List<ArtifactDefinition>> artifactTypeEnumListMap =
1147 artifactsInfoField.get(artifactGroup);
1148 artifactTypeEnumListMap.putAll(artifactsDefinition);
1149 artifactsInfoField.put(artifactGroup, artifactTypeEnumListMap);
1154 public boolean isEmpty() {
1155 return artifactsInfoField.isEmpty();
1161 * The artifacts of the component and of all its composed instances
1164 private class ComponentTypeArtifacts {
1165 private ArtifactsInfo componentArtifacts; //component artifacts (describes the Informational Deployment folders)
1166 private Map<String, ArtifactsInfo> componentInstancesArtifacts; //artifacts of the composed instances mapped by the resourceInstance normalized name (describes the Resources folder)
1168 public ComponentTypeArtifacts() {
1169 componentArtifacts = new ArtifactsInfo();
1170 componentInstancesArtifacts = new HashMap<>();
1173 public ArtifactsInfo getComponentArtifacts() {
1174 return componentArtifacts;
1176 public void setComponentArtifacts(ArtifactsInfo artifactsInfo) {
1177 this.componentArtifacts = artifactsInfo;
1179 public Map<String, ArtifactsInfo> getComponentInstancesArtifacts() {
1180 return componentInstancesArtifacts;
1182 public void setComponentInstancesArtifacts(Map<String, ArtifactsInfo> componentInstancesArtifacts) {
1183 this.componentInstancesArtifacts = componentInstancesArtifacts;
1186 public void addComponentInstancesArtifacts(String normalizedName, ArtifactsInfo artifactsInfo) {
1187 componentInstancesArtifacts.put(normalizedName, artifactsInfo);
1192 private class ComponentArtifacts {
1193 //artifacts of the component and CI's artifacts contained in it's composition (represents Informational, Deployment & Resource folders of main component)
1194 private ComponentTypeArtifacts mainTypeAndCIArtifacts;
1195 //artifacts of all component types mapped by their tosca name
1196 private Map<String, ComponentTypeArtifacts> componentTypeArtifacts;
1198 public ComponentArtifacts(){
1199 mainTypeAndCIArtifacts = new ComponentTypeArtifacts();
1200 componentTypeArtifacts = new HashMap<>();
1203 public ComponentTypeArtifacts getMainTypeAndCIArtifacts() {
1204 return mainTypeAndCIArtifacts;
1207 public void setMainTypeAndCIArtifacts(ComponentTypeArtifacts componentInstanceArtifacts) {
1208 this.mainTypeAndCIArtifacts = componentInstanceArtifacts;
1211 public Map<String, ComponentTypeArtifacts> getComponentTypeArtifacts() {
1212 return componentTypeArtifacts;
1215 public void setComponentTypeArtifacts(Map<String, ComponentTypeArtifacts> componentTypeArtifacts) {
1216 this.componentTypeArtifacts = componentTypeArtifacts;
1220 private class CsarDefinition {
1221 private ComponentArtifacts componentArtifacts;
1223 // add list of tosca artifacts and meta describes CSAR zip root
1225 public CsarDefinition(ComponentArtifacts componentArtifacts) {
1226 this.componentArtifacts = componentArtifacts;
1229 public ComponentArtifacts getComponentArtifacts() {
1230 return componentArtifacts;
1234 /************************************ Artifacts Structure END******************************************************************/
1236 private Either<CsarDefinition,ResponseFormat> collectComponentCsarDefinition(Component component){
1237 ComponentArtifacts componentArtifacts = new ComponentArtifacts();
1238 Component updatedComponent = component;
1240 //get service to receive the AII artifacts uploaded to the service
1241 if (updatedComponent.getComponentType() == ComponentTypeEnum.SERVICE) {
1242 Either<Service, StorageOperationStatus> getServiceResponse = toscaOperationFacade.getToscaElement(updatedComponent.getUniqueId());
1244 if(getServiceResponse.isRight()){
1245 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getServiceResponse.right().value());
1246 return Either.right(componentsUtils.getResponseFormat(actionStatus));
1249 updatedComponent = getServiceResponse.left().value();
1252 //find the artifacts of the main component, it would have its composed instances artifacts in a separate folder
1253 ComponentTypeArtifacts componentInstanceArtifacts = new ComponentTypeArtifacts();
1254 ArtifactsInfo artifactsInfo = collectComponentArtifacts(updatedComponent);
1255 componentInstanceArtifacts.setComponentArtifacts(artifactsInfo);
1256 componentArtifacts.setMainTypeAndCIArtifacts(componentInstanceArtifacts);
1258 Map<String,ComponentTypeArtifacts> resourceTypeArtifacts = componentArtifacts.getComponentTypeArtifacts(); //artifacts mapped by the component type(tosca name+version)
1259 //get the component instances
1260 List<ComponentInstance> componentInstances = updatedComponent.getComponentInstances();
1261 if (componentInstances!=null){
1262 for (ComponentInstance componentInstance:componentInstances){
1263 //call recursive to find artifacts for all the path
1264 Either<Boolean, ResponseFormat> collectComponentInstanceArtifacts = collectComponentInstanceArtifacts(
1265 updatedComponent, componentInstance, resourceTypeArtifacts, componentInstanceArtifacts);
1266 if (collectComponentInstanceArtifacts.isRight()){
1267 return Either.right(collectComponentInstanceArtifacts.right().value());
1272 if(log.isDebugEnabled()){
1273 printResult(componentArtifacts,updatedComponent.getName());
1276 return Either.left(new CsarDefinition(componentArtifacts));
1279 private void printResult(ComponentArtifacts componentArtifacts, String name) {
1280 StringBuilder result = new StringBuilder();
1281 result.append("Artifacts of main component " + name + "\n");
1282 ComponentTypeArtifacts componentInstanceArtifacts = componentArtifacts.getMainTypeAndCIArtifacts();
1283 printArtifacts(componentInstanceArtifacts);
1284 result.append("Type Artifacts\n");
1285 for (Map.Entry<String, ComponentTypeArtifacts> typeArtifacts:componentArtifacts.getComponentTypeArtifacts().entrySet()){
1286 result.append("Folder " + typeArtifacts.getKey() + "\n");
1287 result.append(printArtifacts(typeArtifacts.getValue()));
1290 if(log.isDebugEnabled()){
1291 log.debug(result.toString());
1295 private String printArtifacts(ComponentTypeArtifacts componentInstanceArtifacts) {
1296 StringBuilder result = new StringBuilder();
1297 ArtifactsInfo artifactsInfo = componentInstanceArtifacts.getComponentArtifacts();
1298 Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> componetArtifacts = artifactsInfo.getArtifactsInfo();
1299 printArtifacts(componetArtifacts);
1300 result = result.append("Resources\n");
1301 for (Map.Entry<String, ArtifactsInfo> resourceInstance:componentInstanceArtifacts.getComponentInstancesArtifacts().entrySet()){
1302 result.append("Folder" + resourceInstance.getKey() + "\n");
1303 result.append(printArtifacts(resourceInstance.getValue().getArtifactsInfo()));
1306 return result.toString();
1309 private String printArtifacts(Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> componetArtifacts) {
1310 StringBuilder result = new StringBuilder();
1311 for (Map.Entry<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> artifactGroup:componetArtifacts.entrySet()){
1312 result.append(" " + artifactGroup.getKey().getType());
1313 for (Map.Entry<ArtifactTypeEnum, List<ArtifactDefinition>> groupArtifacts:artifactGroup.getValue().entrySet()){
1314 result.append(" " + groupArtifacts.getKey().getType());
1315 for (ArtifactDefinition artifact:groupArtifacts.getValue()){
1316 result.append(" " + artifact.getArtifactDisplayName());
1321 return result.toString();
1324 private ComponentTypeArtifacts collectComponentTypeArtifacts(Map<String, ComponentTypeArtifacts> resourcesArtifacts, ComponentInstance componentInstance,
1325 Component fetchedComponent) {
1326 String toscaComponentName = componentInstance.getToscaComponentName() + "_v" + componentInstance.getComponentVersion();
1328 ComponentTypeArtifacts componentArtifactsInfo = resourcesArtifacts.get(toscaComponentName);
1329 //if there are no artifacts for this component type we need to fetch and build them
1330 if (componentArtifactsInfo==null){
1331 ArtifactsInfo componentArtifacts = collectComponentArtifacts(fetchedComponent);
1332 componentArtifactsInfo = new ComponentTypeArtifacts();
1333 if (!componentArtifacts.isEmpty()){
1334 componentArtifactsInfo.setComponentArtifacts(componentArtifacts);
1335 resourcesArtifacts.put(toscaComponentName, componentArtifactsInfo);
1338 return componentArtifactsInfo;
1341 private Either<Boolean, ResponseFormat> collectComponentInstanceArtifacts(Component parentComponent,ComponentInstance componentInstance,
1342 Map<String, ComponentTypeArtifacts> resourcesTypeArtifacts,ComponentTypeArtifacts instanceArtifactsLocation) {
1343 //1. get the component instance component
1344 String componentUid;
1345 if (componentInstance.getOriginType() == OriginTypeEnum.ServiceProxy) {
1346 componentUid = componentInstance.getSourceModelUid();
1349 componentUid = componentInstance.getComponentUid();
1351 Either<Component, StorageOperationStatus> component = toscaOperationFacade.getToscaElement(componentUid);
1352 if (component.isRight()) {
1353 log.error("Failed to fetch resource with id {} for instance {}",componentUid, parentComponent.getUUID());
1354 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ASSET_NOT_FOUND_DURING_CSAR_CREATION,
1355 parentComponent.getComponentType().getValue(), parentComponent.getUUID(),
1356 componentInstance.getOriginType().getComponentType().getValue(), componentUid));
1358 Component fetchedComponent = component.left().value();
1360 //2. fill the artifacts for the current component parent type
1361 ComponentTypeArtifacts componentParentArtifacts = collectComponentTypeArtifacts(resourcesTypeArtifacts, componentInstance, fetchedComponent);
1363 //3. find the artifacts specific to the instance
1364 Map<ArtifactTypeEnum, List<ArtifactDefinition>> componentInstanceSpecificInformationalArtifacts =
1365 getComponentInstanceSpecificArtifacts(componentInstance.getArtifacts(),
1366 componentParentArtifacts.getComponentArtifacts().getArtifactsInfo(), ArtifactGroupTypeEnum.INFORMATIONAL);
1367 Map<ArtifactTypeEnum, List<ArtifactDefinition>> componentInstanceSpecificDeploymentArtifacts =
1368 getComponentInstanceSpecificArtifacts(componentInstance.getDeploymentArtifacts(),
1369 componentParentArtifacts.getComponentArtifacts().getArtifactsInfo(), ArtifactGroupTypeEnum.DEPLOYMENT);
1371 //4. add the instances artifacts to the component type
1372 ArtifactsInfo artifactsInfo = new ArtifactsInfo();
1373 if (!componentInstanceSpecificInformationalArtifacts.isEmpty()){
1374 artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.INFORMATIONAL, componentInstanceSpecificInformationalArtifacts);
1376 if (!componentInstanceSpecificDeploymentArtifacts.isEmpty()){
1377 artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.DEPLOYMENT, componentInstanceSpecificDeploymentArtifacts);
1379 if (!artifactsInfo.isEmpty()){
1380 instanceArtifactsLocation.addComponentInstancesArtifacts(componentInstance.getNormalizedName(), artifactsInfo);
1383 //5. do the same for all the component instances
1384 List<ComponentInstance> componentInstances = fetchedComponent.getComponentInstances();
1385 if (componentInstances!=null){
1386 for (ComponentInstance childComponentInstance:componentInstances){
1387 Either<Boolean, ResponseFormat> collectComponentInstanceArtifacts = collectComponentInstanceArtifacts(
1388 fetchedComponent, childComponentInstance, resourcesTypeArtifacts, componentParentArtifacts);
1389 if (collectComponentInstanceArtifacts.isRight()){
1390 return collectComponentInstanceArtifacts;
1395 return Either.left(true);
1398 public String getVersionFirstThreeOctets() {
1399 return versionFirstThreeOctets;
1402 public void setVersionFirstThreeOctets(String versionFirstThreeOctetes) {
1403 this.versionFirstThreeOctets = versionFirstThreeOctetes;
1405 private Map<ArtifactTypeEnum, List<ArtifactDefinition>> getComponentInstanceSpecificArtifacts(Map<String, ArtifactDefinition> componentArtifacts,
1406 Map<ArtifactGroupTypeEnum, Map<ArtifactTypeEnum, List<ArtifactDefinition>>> componentTypeArtifacts, ArtifactGroupTypeEnum artifactGroupTypeEnum) {
1407 Map<ArtifactTypeEnum, List<ArtifactDefinition>> parentArtifacts = componentTypeArtifacts.get(artifactGroupTypeEnum); //the artfiacts of the component itself and not the instance
1409 Map<ArtifactTypeEnum, List<ArtifactDefinition>> artifactsByTypeOfComponentInstance = new EnumMap<>(ArtifactTypeEnum.class);
1410 if (componentArtifacts!=null){
1411 for (ArtifactDefinition artifact:componentArtifacts.values()){
1412 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifact.getArtifactType());
1413 List<ArtifactDefinition> parentArtifactsByType = null;
1414 if (parentArtifacts!=null){
1415 parentArtifactsByType = parentArtifacts.get(artifactType);
1417 //the artifact is of instance
1418 if (parentArtifactsByType == null || !parentArtifactsByType.contains(artifact)){
1419 List<ArtifactDefinition> typeArtifacts = artifactsByTypeOfComponentInstance.get(artifactType);
1420 if (typeArtifacts == null){
1421 typeArtifacts = new ArrayList<>();
1422 artifactsByTypeOfComponentInstance.put(artifactType, typeArtifacts);
1424 typeArtifacts.add(artifact);
1429 return artifactsByTypeOfComponentInstance;
1432 private ArtifactsInfo collectComponentArtifacts(Component component) {
1433 Map<String, ArtifactDefinition> informationalArtifacts = component.getArtifacts();
1434 Map<ArtifactTypeEnum, List<ArtifactDefinition>> informationalArtifactsByType = collectGroupArtifacts(informationalArtifacts);
1435 Map<String, ArtifactDefinition> deploymentArtifacts = component.getDeploymentArtifacts();
1436 Map<ArtifactTypeEnum, List<ArtifactDefinition>> deploymentArtifactsByType = collectGroupArtifacts(deploymentArtifacts);
1437 Map<String, ArtifactDefinition> interfaceOperationArtifacts =
1438 OperationArtifactUtil.getDistinctInterfaceOperationArtifactsByName(component);
1439 Map<ArtifactTypeEnum, List<ArtifactDefinition>> interfaceOperationArtifactsByType = collectGroupArtifacts(
1440 interfaceOperationArtifacts);
1441 ArtifactsInfo artifactsInfo = new ArtifactsInfo();
1442 if (!informationalArtifactsByType.isEmpty()){
1443 artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.INFORMATIONAL, informationalArtifactsByType);
1445 if (!deploymentArtifactsByType.isEmpty() ){
1446 artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.DEPLOYMENT, deploymentArtifactsByType);
1448 //Add component interface operation artifacts
1449 if(MapUtils.isNotEmpty(interfaceOperationArtifacts)) {
1450 artifactsInfo.addArtifactsToGroup(ArtifactGroupTypeEnum.DEPLOYMENT, interfaceOperationArtifactsByType);
1453 return artifactsInfo;
1456 private Map<ArtifactTypeEnum, List<ArtifactDefinition>> collectGroupArtifacts(Map<String, ArtifactDefinition> componentArtifacts) {
1457 Map<ArtifactTypeEnum, List<ArtifactDefinition>> artifactsByType = new EnumMap<>(ArtifactTypeEnum.class);
1458 for (ArtifactDefinition artifact:componentArtifacts.values()){
1459 if (artifact.getArtifactUUID()!=null){
1460 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifact.getArtifactType());
1461 List<ArtifactDefinition> typeArtifacts = artifactsByType.get(artifactType);
1462 if (typeArtifacts==null){
1463 typeArtifacts = new ArrayList<>();
1464 artifactsByType.put(artifactType, typeArtifacts);
1466 typeArtifacts.add(artifact);
1469 return artifactsByType;