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=========================================================
19 * Modifications copyright (c) 2019 Nokia
20 * ================================================================================
23 package org.openecomp.sdc.be.components.impl;
25 import com.google.common.annotations.VisibleForTesting;
26 import com.google.gson.Gson;
27 import com.google.gson.GsonBuilder;
28 import fj.data.Either;
29 import org.apache.commons.codec.binary.Base64;
30 import org.apache.commons.collections.CollectionUtils;
31 import org.apache.commons.collections.MapUtils;
32 import org.apache.commons.lang.ArrayUtils;
33 import org.apache.commons.lang.StringUtils;
34 import org.apache.commons.lang3.tuple.ImmutablePair;
35 import org.openecomp.sdc.be.components.ArtifactsResolver;
36 import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum;
37 import org.openecomp.sdc.be.components.impl.artifact.ArtifactTypeToPayloadTypeSelector;
38 import org.openecomp.sdc.be.components.impl.artifact.PayloadTypeEnum;
39 import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
40 import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException;
41 import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
42 import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
43 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
44 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction.LifecycleChanceActionEnum;
45 import org.openecomp.sdc.be.components.utils.InterfaceOperationUtils;
46 import org.openecomp.sdc.be.config.BeEcompErrorManager;
47 import org.openecomp.sdc.be.config.Configuration.ArtifactTypeConfig;
48 import org.openecomp.sdc.be.config.ConfigurationManager;
49 import org.openecomp.sdc.be.dao.api.ActionStatus;
50 import org.openecomp.sdc.be.dao.cassandra.ArtifactCassandraDao;
51 import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus;
52 import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
53 import org.openecomp.sdc.be.datatypes.components.ComponentMetadataDataDefinition;
54 import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
55 import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
56 import org.openecomp.sdc.be.datatypes.elements.GroupInstanceDataDefinition;
57 import org.openecomp.sdc.be.datatypes.elements.HeatParameterDataDefinition;
58 import org.openecomp.sdc.be.datatypes.elements.OperationDataDefinition;
59 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
60 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
61 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
62 import org.openecomp.sdc.be.info.ArtifactTemplateInfo;
63 import org.openecomp.sdc.be.model.ArtifactDefinition;
64 import org.openecomp.sdc.be.model.ArtifactType;
65 import org.openecomp.sdc.be.model.Component;
66 import org.openecomp.sdc.be.model.ComponentInstance;
67 import org.openecomp.sdc.be.model.ComponentParametersView;
68 import org.openecomp.sdc.be.model.GroupDefinition;
69 import org.openecomp.sdc.be.model.GroupInstance;
70 import org.openecomp.sdc.be.model.HeatParameterDefinition;
71 import org.openecomp.sdc.be.model.InterfaceDefinition;
72 import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;
73 import org.openecomp.sdc.be.model.LifecycleStateEnum;
74 import org.openecomp.sdc.be.model.Operation;
75 import org.openecomp.sdc.be.model.Resource;
76 import org.openecomp.sdc.be.model.Service;
77 import org.openecomp.sdc.be.model.User;
78 import org.openecomp.sdc.be.model.heat.HeatParameterType;
79 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ArtifactsOperations;
80 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.InterfaceOperation;
81 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.NodeTemplateOperation;
82 import org.openecomp.sdc.be.model.operations.StorageException;
83 import org.openecomp.sdc.be.model.operations.api.IElementOperation;
84 import org.openecomp.sdc.be.model.operations.api.IGroupInstanceOperation;
85 import org.openecomp.sdc.be.model.operations.api.IGroupOperation;
86 import org.openecomp.sdc.be.model.operations.api.IGroupTypeOperation;
87 import org.openecomp.sdc.be.model.operations.api.IHeatParametersOperation;
88 import org.openecomp.sdc.be.model.operations.api.IInterfaceLifecycleOperation;
89 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
90 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
91 import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation;
92 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
93 import org.openecomp.sdc.be.model.operations.impl.UserAdminOperation;
94 import org.openecomp.sdc.be.resources.data.ComponentMetadataData;
95 import org.openecomp.sdc.be.resources.data.DAOArtifactData;
96 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
97 import org.openecomp.sdc.be.resources.data.auditing.model.ResourceCommonInfo;
98 import org.openecomp.sdc.be.resources.data.auditing.model.ResourceVersionInfo;
99 import org.openecomp.sdc.be.servlets.RepresentationUtils;
100 import org.openecomp.sdc.be.tosca.CsarUtils;
101 import org.openecomp.sdc.be.tosca.ToscaError;
102 import org.openecomp.sdc.be.tosca.ToscaExportHandler;
103 import org.openecomp.sdc.be.tosca.ToscaRepresentation;
104 import org.openecomp.sdc.be.user.Role;
105 import org.openecomp.sdc.be.user.UserBusinessLogic;
106 import org.openecomp.sdc.be.utils.TypeUtils;
107 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
108 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
109 import org.openecomp.sdc.common.api.Constants;
110 import org.openecomp.sdc.common.datastructure.Wrapper;
111 import org.openecomp.sdc.common.log.wrappers.Logger;
112 import org.openecomp.sdc.common.util.GeneralUtility;
113 import org.openecomp.sdc.common.util.ValidationUtils;
114 import org.openecomp.sdc.common.util.YamlToObjectConverter;
115 import org.openecomp.sdc.exception.ResponseFormat;
116 import org.springframework.beans.factory.annotation.Autowired;
117 import org.xml.sax.InputSource;
118 import org.xml.sax.SAXException;
119 import org.xml.sax.SAXNotRecognizedException;
120 import org.xml.sax.SAXNotSupportedException;
121 import org.xml.sax.XMLReader;
122 import org.yaml.snakeyaml.Yaml;
124 import javax.servlet.http.HttpServletRequest;
125 import javax.xml.XMLConstants;
126 import javax.xml.parsers.ParserConfigurationException;
127 import javax.xml.parsers.SAXParserFactory;
128 import java.io.ByteArrayInputStream;
129 import java.io.IOException;
130 import java.math.BigDecimal;
131 import java.util.ArrayList;
132 import java.util.Collections;
133 import java.util.Comparator;
134 import java.util.HashMap;
135 import java.util.Iterator;
136 import java.util.List;
137 import java.util.Map;
138 import java.util.Map.Entry;
139 import java.util.Objects;
140 import java.util.Optional;
141 import java.util.Set;
142 import java.util.function.Function;
143 import java.util.function.Predicate;
144 import java.util.function.Supplier;
145 import java.util.stream.Collectors;
147 import static org.openecomp.sdc.be.dao.api.ActionStatus.MISMATCH_BETWEEN_ARTIFACT_TYPE_AND_COMPONENT_TYPE;
149 @org.springframework.stereotype.Component("artifactBusinessLogic")
150 public class ArtifactsBusinessLogic extends BaseBusinessLogic {
151 private static final String RESOURCE_INSTANCE = "resource instance";
152 private static final String ARTIFACT_TYPE_OTHER = "OTHER";
153 private static final String ARTIFACT_DESCRIPTION = "artifact description";
154 private static final String ARTIFACT_LABEL = "artifact label";
155 private static final String ARTIFACT_URL = "artifact url";
156 private static final String ARTIFACT_NAME = "artifact name";
157 private static final String ARTIFACT_PAYLOAD = "artifact payload";
159 private static final String ARTIFACT_PLACEHOLDER_TYPE = "type";
160 private static final String ARTIFACT_PLACEHOLDER_DISPLAY_NAME = "displayName";
161 private static final Object ARTIFACT_PLACEHOLDER_DESCRIPTION = "description";
163 public static final String HEAT_ENV_NAME = "heatEnv";
164 public static final String HEAT_VF_ENV_NAME = "VfHeatEnv";
165 public static final String HEAT_ENV_SUFFIX = "env";
166 private static final String ARTIFACT_PLACEHOLDER_FILE_EXTENSION = "fileExtension";
168 private static final Logger log = Logger.getLogger(ArtifactsBusinessLogic.class.getName());
169 private static final String FAILED_UPDATE_GROUPS = "Failed to update groups of the component {}. ";
170 private static final String FAILED_UPDATE_ARTIFACT = "Failed to delete or update the artifact {}. Parent uniqueId is {}";
171 private static final String FAILED_SAVE_ARTIFACT = "Failed to save the artifact.";
172 public static final String ARTIFACT_ACTION_LOCK = "Artifact action - lock ";
173 private static final String UPDATE_ARTIFACT_LOCK = "Update Artifact - lock ";
174 private static final String FAILED_DOWNLOAD_ARTIFACT = "Download artifact {} failed";
175 public static final String FAILED_UPLOAD_ARTIFACT_TO_COMPONENT = "Failed to upload artifact to component with type {} and uuid {}. Status is {}. ";
176 private static final String FAILED_UPLOAD_ARTIFACT_TO_INSTANCE = "Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. ";
177 private static final String FAILED_FETCH_COMPONENT = "Could not fetch component with type {} and uuid {}. Status is {}. ";
178 private static final String NULL_PARAMETER = "One of the function parameteres is null";
179 public static final String COMPONENT_INSTANCE_NOT_FOUND = "Component instance {} was not found for component {}";
180 private static final String ROLLBACK = "all changes rollback";
181 private static final String COMMIT = "all changes committed";
182 private static final String ARTIFACT_SAVED = "Artifact saved into ES - {}";
183 private static final String UPDATE_ARTIFACT = "Update Artifact";
184 private static final String FOUND_DEPLOYMENT_ARTIFACT = "Found deployment artifact {}";
185 private Gson gson = new GsonBuilder().setPrettyPrinting().create();
187 @javax.annotation.Resource
188 private IInterfaceLifecycleOperation interfaceLifecycleOperation;
189 @javax.annotation.Resource
190 private UserAdminOperation userOperaton;
192 @javax.annotation.Resource
193 private IElementOperation elementOperation;
195 @javax.annotation.Resource
196 private IHeatParametersOperation heatParametersOperation;
198 private ArtifactCassandraDao artifactCassandraDao;
199 private ToscaExportHandler toscaExportUtils;
200 private CsarUtils csarUtils;
201 private LifecycleBusinessLogic lifecycleBusinessLogic;
202 private UserBusinessLogic userBusinessLogic;
203 private ArtifactsResolver artifactsResolver;
204 private NodeTemplateOperation nodeTemplateOperation;
207 public ArtifactsBusinessLogic(ArtifactCassandraDao artifactCassandraDao, ToscaExportHandler toscaExportUtils,
208 CsarUtils csarUtils, LifecycleBusinessLogic lifecycleBusinessLogic, UserBusinessLogic userBusinessLogic,
209 ArtifactsResolver artifactsResolver, IElementOperation elementDao, IGroupOperation groupOperation,
210 IGroupInstanceOperation groupInstanceOperation, IGroupTypeOperation groupTypeOperation, InterfaceOperation interfaceOperation,
211 InterfaceLifecycleOperation interfaceLifecycleTypeOperation, ArtifactsOperations artifactToscaOperation) {
212 super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation,
213 interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation);
214 this.artifactCassandraDao = artifactCassandraDao;
215 this.toscaExportUtils = toscaExportUtils;
216 this.csarUtils = csarUtils;
217 this.lifecycleBusinessLogic = lifecycleBusinessLogic;
218 this.userBusinessLogic = userBusinessLogic;
219 this.artifactsResolver = artifactsResolver;
222 public enum ArtifactOperationEnum {
223 CREATE, UPDATE, DELETE, DOWNLOAD, LINK;
225 public static boolean isCreateOrLink(ArtifactOperationEnum operation) {
226 return operation == CREATE || operation == LINK;
230 public class ArtifactOperationInfo {
232 private ArtifactOperationEnum artifactOperationEnum;
233 private boolean isExternalApi;
234 private boolean ignoreLifecycleState;
236 public ArtifactOperationInfo(boolean isExternalApi, boolean ignoreLifecycleState, ArtifactOperationEnum artifactOperationEnum) {
237 this.artifactOperationEnum = artifactOperationEnum;
238 this.isExternalApi = isExternalApi;
239 this.ignoreLifecycleState = ignoreLifecycleState;
242 public boolean isExternalApi() {
243 return isExternalApi;
246 public boolean ignoreLifecycleState() {
247 return ignoreLifecycleState;
250 public ArtifactOperationEnum getArtifactOperationEnum() {
251 return artifactOperationEnum;
257 public Either<ArtifactDefinition, Operation> handleArtifactRequest(String componentId, String userId, ComponentTypeEnum componentType,
258 ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo,
259 String origMd5, String originData, String interfaceName, String operationName,
260 String parentId, String containerComponentType, boolean shouldLock, boolean inTransaction) {
262 // step 1 - detect auditing type
263 AuditingActionEnum auditingAction = detectAuditingType(operation, origMd5);
264 // step 2 - check header
265 if (userId == null) {
266 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
267 log.debug("handleArtifactRequest - no HTTP_CSP_HEADER , component id {}", componentId);
268 handleAuditing(auditingAction, null, componentId, null, null, null, artifactId, responseFormat, componentType, null);
269 throw new ByActionStatusComponentException(ActionStatus.MISSING_INFORMATION);
271 // step 3 - check user existence
272 // step 4 - check user's role
273 User user = validateUserExists(userId, auditingAction, componentId, artifactId, componentType, inTransaction);
274 validateUserRole(user, auditingAction, componentId, artifactId, componentType, operation);
277 // 5. check service/resource existence
278 // 6. check service/resource check out
279 // 7. user is owner of checkout state
280 Component component = null;
281 String realComponentId = componentType == ComponentTypeEnum.RESOURCE_INSTANCE ? parentId : componentId;
282 component = validateComponentExists(realComponentId, auditingAction, user, artifactId, componentType, containerComponentType);
283 validateWorkOnComponent(component, userId, auditingAction, user, artifactId, operation);
284 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
285 validateResourceInstanceById(component, componentId);
289 return validateAndHandleArtifact(componentId, componentType, operation, artifactId, artifactInfo, origMd5,
290 originData, interfaceName, operationName, user, component, shouldLock, inTransaction, true);
293 public Either<ArtifactDefinition, Operation> handleArtifactRequest(String componentId, String userId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo,
294 String origMd5, String originData, String interfaceName, String operationName, String parentId, String containerComponentType) {
295 return handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, origMd5, originData, interfaceName, operationName, parentId, containerComponentType, true, false);
299 * This Method validates only the Artifact and does not validate user / role / component ect...<br>
300 * For regular usage use <br>
301 * {@link #handleArtifactRequest(String, String, ComponentTypeEnum, ArtifactOperationInfo, String, ArtifactDefinition, String, String, String, String, String, String)}
305 public Either<ArtifactDefinition, Operation> validateAndHandleArtifact(
306 String componentUniqueId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactUniqueId,
307 ArtifactDefinition artifactDefinition, String origMd5, String originData, String interfaceName,
308 String operationName, User user, Component component, boolean shouldLock, boolean inTransaction, boolean needUpdateGroup) {
309 AuditingActionEnum auditingAction = detectAuditingType(operation, origMd5);
310 artifactDefinition = validateArtifact(componentUniqueId, componentType, operation,
311 artifactUniqueId, artifactDefinition, auditingAction, user,
312 component, shouldLock, inTransaction);
315 Either<ArtifactDefinition, Operation> result = doAction(componentUniqueId, componentType, operation, artifactUniqueId, artifactDefinition,
316 origMd5, originData, interfaceName, operationName, auditingAction, user, component, shouldLock, inTransaction, needUpdateGroup);
317 //TODO: audit positive action
322 ArtifactDefinition validateArtifact(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, User user,
323 Component component, boolean shouldLock, boolean inTransaction) {
324 ArtifactDefinition artifactInfoToReturn = artifactInfo;
325 ArtifactOperationEnum operationEnum = operation.getArtifactOperationEnum();
326 if (operationEnum == ArtifactOperationEnum.UPDATE || operationEnum == ArtifactOperationEnum.DELETE || operationEnum == ArtifactOperationEnum.DOWNLOAD) {
327 ArtifactDefinition dbArtifact = getArtifactIfBelongsToComponent(componentId, componentType, artifactId, component);
328 if (operationEnum == ArtifactOperationEnum.DOWNLOAD) {
329 artifactInfoToReturn = dbArtifact;
330 handleHeatEnvDownload(componentId, componentType, user, component, dbArtifact, shouldLock, inTransaction);
333 return artifactInfoToReturn;
337 void handleHeatEnvDownload(String componentId, ComponentTypeEnum componentType, User user, Component component,
338 ArtifactDefinition artifactDefinition, boolean shouldLock, boolean inTransaction) {
340 if (artifactDefinition.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType())
341 && ComponentTypeEnum.SERVICE == component.getComponentType()) {
342 ComponentInstance componentInstance = component.getComponentInstances()
344 .filter(p -> p.getUniqueId().equals(componentId))
347 if (componentInstance == null) {
348 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentId,
349 "instance", "Service", component.getName());
351 Map<String, ArtifactDefinition> deploymentArtifacts = componentInstance.getDeploymentArtifacts();
353 ArtifactDefinition heatEnvWithHeatParams = deploymentArtifacts.values()
355 .filter(p -> p.getUniqueId()
356 .equals(artifactDefinition.getUniqueId()))
359 Either<ArtifactDefinition, ResponseFormat> eitherGenerated = generateHeatEnvArtifact(heatEnvWithHeatParams,
360 componentType, component, componentInstance.getName(), user, componentId, shouldLock, inTransaction);
361 if (eitherGenerated.isRight()) {
362 throw new ByResponseFormatComponentException((eitherGenerated.right().value()));
367 private boolean artifactGenerationRequired(Component component, ArtifactDefinition artifactInfo) {
368 boolean needGenerate;
369 needGenerate = artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA && (component.getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN || component
370 .getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
371 needGenerate = needGenerate || (ComponentTypeEnum.RESOURCE == component.getComponentType() && (artifactInfo.getArtifactType()
372 .equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV
373 .getType()) || isAbstractVfcEmptyCsar((Resource) component, artifactInfo)));
377 private boolean isAbstractVfcEmptyCsar(Resource resource, ArtifactDefinition artifactInfo) {
378 return resource.isAbstract() && artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA && artifactInfo
380 .equals(ArtifactTypeEnum.TOSCA_CSAR.getType()) && StringUtils.isEmpty(artifactInfo.getArtifactChecksum());
383 public Either<ArtifactDefinition, Operation> generateAndSaveToscaArtifact(
384 ArtifactDefinition artifactDefinition, Component component,
385 User user, boolean isInCertificationRequest, boolean shouldLock, boolean inTransaction,
386 boolean fetchTemplatesFromDB) {
387 generateToscaArtifact(component, artifactDefinition, isInCertificationRequest, fetchTemplatesFromDB);
388 byte[] decodedPayload = artifactDefinition.getPayloadData();
389 artifactDefinition.setEsId(artifactDefinition.getUniqueId());
390 artifactDefinition.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(decodedPayload));
391 return lockComponentAndUpdateArtifact(component.getUniqueId(), artifactDefinition, AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, artifactDefinition.getUniqueId(),
392 user, component.getComponentType(), component, decodedPayload, null, null, shouldLock, inTransaction);
395 private ArtifactDefinition generateToscaArtifact(Component parent, ArtifactDefinition artifactInfo, boolean isInCertificationRequest, boolean fetchTemplatesFromDB) {
396 log.debug("tosca artifact generation");
397 if (ArtifactTypeEnum.TOSCA_CSAR.getType().equals(artifactInfo.getArtifactType())) {
398 Either<byte[], ResponseFormat> generated = csarUtils.createCsar(parent, fetchTemplatesFromDB, isInCertificationRequest);
399 if (generated.isRight()) {
400 ResponseFormat error = generated.right().value();
401 log.debug("Failed to generate tosca csar for component {} error {}", parent.getUniqueId(), error);
402 throw new ByResponseFormatComponentException(error);
404 artifactInfo.setPayload(generated.left().value());
408 Either<ToscaRepresentation, ToscaError> exportComponent = toscaExportUtils.exportComponent(parent);
409 if (exportComponent.isRight()) {
410 ToscaError toscaError = exportComponent.right().value();
411 log.debug("Failed export tosca yaml for component {} error {}", parent.getUniqueId(), toscaError);
412 ActionStatus status = componentsUtils.convertFromToscaError(toscaError);
413 throw new ByActionStatusComponentException(status);
415 log.debug("Tosca yaml exported for component {} ", parent.getUniqueId());
416 artifactInfo.setPayloadData(exportComponent.left().value().getMainYaml());
421 private Either<ArtifactDefinition, Operation> doAction(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, String origMd5,
422 String originData, String interfaceName, String operationName, AuditingActionEnum auditingAction, User user, Component parent, boolean shouldLock, boolean inTransaction, boolean needUpdateGroup) {
423 if (interfaceName != null && operationName != null) {
424 interfaceName = interfaceName.toLowerCase();
425 operationName = operationName.toLowerCase();
428 lockComponent(componentType, artifactId, auditingAction, user, parent);
430 Either<ArtifactDefinition, Operation> result;
431 boolean operationSucceeded = false;
433 switch (operation.getArtifactOperationEnum()) {
435 if (artifactGenerationRequired(parent, artifactInfo)) {
436 result = Either.left(generateNotSavedArtifact(parent, artifactInfo));
438 result = Either.left(handleDownload(componentId, artifactId, componentType, parent));
442 result = Either.left(handleDeleteInternal(componentId, artifactId, componentType, parent));
445 result = handleUpdate(componentId, componentType, operation, artifactId, artifactInfo, null, origMd5, originData, interfaceName, operationName,
446 auditingAction, user, parent, needUpdateGroup);
449 result = handleCreate(componentId, artifactInfo, operation, auditingAction, user, componentType, parent, origMd5, originData, interfaceName,
453 result = Either.left(handleLink(componentId, artifactInfo, componentType, parent));
456 throw new UnsupportedOperationException("In ArtifactsBusinessLogic received illegal operation: " + operation.getArtifactOperationEnum());
458 operationSucceeded = true;
462 handleLockingAndCommit(parent, shouldLock, inTransaction, operationSucceeded);
466 private void lockComponent(ComponentTypeEnum componentType, String artifactId, AuditingActionEnum auditingAction, User user, Component parent) {
468 lockComponent(parent, ARTIFACT_ACTION_LOCK);
469 }catch (ComponentException e){
470 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, null, null, artifactId, e.getResponseFormat(),
471 componentType, null);
477 public Either<ArtifactDefinition, Operation> handleUpdate(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId,
478 ArtifactDefinition artifactInfo, byte[] decodedPayload, String origMd5, String originData, String interfaceName,
479 String operationName, AuditingActionEnum auditingAction, User user, Component parent,
480 boolean needUpdateGroup) {
481 Either<ArtifactDefinition, Operation> result;
482 ArtifactTypeEnum artifactType = validateAndReturnArtifactType(artifactInfo);
483 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE
484 && (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_VOL || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_ENV)) {
485 result = handleUpdateHeatEnvAndHeatMeta(componentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, originData, origMd5, operation);
486 if (needUpdateGroup) {
487 ActionStatus error = updateGroupInstance(artifactInfo, result.left().value(), parent, componentId);
488 if (error != ActionStatus.OK) {
489 throw new ByActionStatusComponentException(error);
493 else if (componentType == ComponentTypeEnum.RESOURCE && artifactType == ArtifactTypeEnum.HEAT_ENV) {
494 result = handleUpdateHeatWithHeatEnvParams(componentId, artifactInfo, auditingAction, componentType, parent, originData, origMd5, operation, needUpdateGroup);
497 if (decodedPayload == null) {
498 decodedPayload = validateInput(componentId, artifactInfo, operation, auditingAction, artifactId, user,
499 componentType, parent, origMd5, originData, interfaceName, operationName);
501 result = updateArtifactFlow(parent, componentId, artifactId, artifactInfo, decodedPayload, componentType, auditingAction, interfaceName, operationName);
502 if (needUpdateGroup && result.isLeft()) {
503 ArtifactDefinition updatedArtifact = result.left().value();
504 updateGroupForHeat(artifactInfo, updatedArtifact, parent);
510 private ArtifactTypeEnum validateAndReturnArtifactType(ArtifactDefinition artifactInfo) {
511 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
512 if (artifactType == null) {
513 throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType());
518 public ActionStatus updateGroupForHeatEnv(ArtifactDefinition artifactInfo, ArtifactDefinition artAfterUpdate, Component parent) {
519 return ActionStatus.OK;
523 public ActionStatus updateGroupForHeat(ArtifactDefinition artifactInfo, ArtifactDefinition artAfterUpdate, Component parent) {
524 List<GroupDefinition> groups = parent.getGroups();
525 if (groups != null && !groups.isEmpty()) {
526 List<GroupDataDefinition> groupToUpdate = groups.stream()
527 .filter(g -> g.getArtifacts() != null && g.getArtifacts()
528 .contains(artifactInfo
530 .collect(Collectors.toList());
531 if (groupToUpdate != null && !groupToUpdate.isEmpty()) {
532 groupToUpdate.forEach(g -> {
533 g.getArtifacts().remove(artifactInfo.getUniqueId());
534 g.getArtifactsUuid().remove(artifactInfo.getArtifactUUID());
535 g.getArtifacts().add(artAfterUpdate.getUniqueId());
536 g.getArtifactsUuid().add(artAfterUpdate.getArtifactUUID());
537 if(!artifactInfo.getArtifactUUID().equals(artAfterUpdate.getArtifactUUID())){
538 g.setGroupUUID(UniqueIdBuilder.generateUUID());
541 Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(parent, groupToUpdate);
542 if (status.isRight()) {
543 log.debug(FAILED_UPDATE_GROUPS, parent.getUniqueId());
544 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status.right().value()));
548 return ActionStatus.OK;
552 ActionStatus updateGroupForHeat(ArtifactDefinition artifactInfoHeat, ArtifactDefinition artHeatAfterUpdate, ArtifactDefinition artifactInfoHeatE, ArtifactDefinition artHEAfterUpdate, Component parent) {
553 List<GroupDefinition> groups = parent.getGroups();
554 if (groups != null && !groups.isEmpty()) {
555 List<GroupDataDefinition> groupToUpdate = groups.stream()
556 .filter(g -> g.getArtifacts() != null && g.getArtifacts()
557 .contains(artifactInfoHeat
559 .collect(Collectors.toList());
560 if (groupToUpdate != null && !groupToUpdate.isEmpty()) {
561 groupToUpdate.forEach(g -> {
562 g.getArtifacts().remove(artifactInfoHeat.getUniqueId());
563 g.getArtifactsUuid().remove(artifactInfoHeat.getArtifactUUID());
564 g.getArtifacts().remove(artifactInfoHeatE.getUniqueId());
565 g.getArtifacts().add(artHeatAfterUpdate.getUniqueId());
566 g.getArtifactsUuid().add(artHeatAfterUpdate.getArtifactUUID());
567 g.getArtifacts().add(artHEAfterUpdate.getUniqueId());
569 Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(parent, groupToUpdate);
570 if (status.isRight()) {
571 log.debug(FAILED_UPDATE_GROUPS, parent.getUniqueId());
572 return componentsUtils.convertFromStorageResponse(status.right().value());
576 return ActionStatus.OK;
579 private ActionStatus updateGroupInstance(ArtifactDefinition artifactInfo, ArtifactDefinition artAfterUpdate, Component parent, String parentId) {
580 List<GroupInstance> updatedGroupInstances = new ArrayList<>();
581 List<GroupInstance> groupInstances = null;
582 Optional<ComponentInstance> componentInstOp = parent.getComponentInstances()
584 .filter(ci -> ci.getUniqueId().equals(parentId))
586 if (componentInstOp.isPresent()) {
587 groupInstances = componentInstOp.get().getGroupInstances();
589 if (CollectionUtils.isNotEmpty(groupInstances)) {
590 boolean isUpdated = false;
591 for (GroupInstance groupInstance : groupInstances) {
593 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifacts()) && groupInstance.getGroupInstanceArtifacts()
594 .contains(artifactInfo
596 groupInstance.getGroupInstanceArtifacts().remove(artifactInfo.getUniqueId());
597 groupInstance.getGroupInstanceArtifacts().add(artAfterUpdate.getUniqueId());
600 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifactsUuid()) && groupInstance.getGroupInstanceArtifactsUuid()
601 .contains(artifactInfo
602 .getArtifactUUID())) {
603 groupInstance.getGroupInstanceArtifactsUuid().remove(artifactInfo.getArtifactUUID());
604 groupInstance.getGroupInstanceArtifacts().add(artAfterUpdate.getArtifactUUID());
608 updatedGroupInstances.add(groupInstance);
612 Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(parent, parentId, updatedGroupInstances);
613 if (status.isRight()) {
614 log.debug(FAILED_UPDATE_GROUPS, parent.getUniqueId());
615 return componentsUtils.convertFromStorageResponse(status.right().value());
617 return ActionStatus.OK;
620 ArtifactDefinition generateNotSavedArtifact(Component parent, ArtifactDefinition artifactInfo) {
621 if (artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA) {
622 return generateToscaArtifact(parent, artifactInfo, false, false);
625 String heatArtifactId = artifactInfo.getGeneratedFromId();
626 Either<ArtifactDefinition, StorageOperationStatus> heatRes = artifactToscaOperation.getArtifactById(parent.getUniqueId(), heatArtifactId);
627 if (heatRes.isRight()) {
628 log.debug("Failed to fetch heat artifact by generated id {} for heat env {}", heatArtifactId, artifactInfo.getUniqueId());
629 throw new StorageException(heatRes.right().value());
631 String generatedPayload = generateHeatEnvPayload(heatRes.left().value());
632 artifactInfo.setPayloadData(generatedPayload);
637 private Either<ArtifactDefinition, Operation> handleUpdateHeatWithHeatEnvParams(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction,
638 ComponentTypeEnum componentType, Component parent, String originData, String origMd5, ArtifactOperationInfo operation,
639 boolean needToUpdateGroup) {
640 Either<ArtifactDefinition, StorageOperationStatus> artifactHeatRes = artifactToscaOperation.getArtifactById(componentId, artifactInfo
641 .getGeneratedFromId());
642 ArtifactDefinition currHeatArtifact = artifactHeatRes.left().value();
643 if (origMd5 != null) {
644 validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
645 if (ArrayUtils.isNotEmpty(artifactInfo.getPayloadData())) {
646 handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
647 } else { // duplicate
648 throw new ByActionStatusComponentException(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
651 return updateHeatParams(componentId, artifactInfo, auditingAction, parent, componentType, currHeatArtifact, needToUpdateGroup);
654 private void handleLockingAndCommit(Component parent, boolean shouldLock, boolean inTransaction, boolean actionSucceeded) {
655 if (actionSucceeded) {
657 if (!inTransaction) {
658 janusGraphDao.commit();
662 if (!inTransaction) {
663 janusGraphDao.rollback();
667 graphLockOperation.unlockComponent(parent.getUniqueId(), parent.getComponentType().getNodeType());
671 public ImmutablePair<String, byte[]> handleDownloadToscaModelRequest(Component component, ArtifactDefinition csarArtifact) {
672 if (artifactGenerationRequired(component, csarArtifact)) {
673 Either<byte[], ResponseFormat> generated = csarUtils.createCsar(component, false, false);
675 if (generated.isRight()) {
676 log.debug("Failed to export tosca csar for component {} error {}", component.getUniqueId(), generated.right()
678 throw new ByResponseFormatComponentException(generated.right().value());
680 return new ImmutablePair<>(csarArtifact.getArtifactName(), generated.left().value());
682 return downloadArtifact(csarArtifact);
685 public ImmutablePair<String, byte[]> handleDownloadRequestById(String componentId, String artifactId, String userId, ComponentTypeEnum componentType, String parentId, String containerComponentType) {
686 // perform all validation in common flow
687 Either<ArtifactDefinition, Operation> result = handleArtifactRequest(componentId, userId, componentType, new ArtifactOperationInfo(false, false, ArtifactOperationEnum.DOWNLOAD), artifactId, null, null, null, null,
688 null, parentId, containerComponentType);
689 ArtifactDefinition artifactDefinition;
690 Either<ArtifactDefinition, Operation> insideValue = result;
691 if (insideValue.isLeft()) {
692 artifactDefinition = insideValue.left().value();
695 artifactDefinition = insideValue.right().value().getImplementationArtifact();
697 // for tosca artifacts and heat env on VF level generated on download without saving
698 if (artifactDefinition.getPayloadData() != null) {
699 return (new ImmutablePair<>(artifactDefinition.getArtifactName(), artifactDefinition
702 return downloadArtifact(artifactDefinition);
705 public Map<String, ArtifactDefinition> handleGetArtifactsByType(String containerComponentType, String parentId, ComponentTypeEnum componentType, String componentId, String artifactGroupType, String userId) {
707 // detect auditing type
708 Map<String, ArtifactDefinition> resMap = null;
709 // Either<Map<String, ArtifactDefinition>, ResponseFormat> resultOp = null;
714 if (userId == null) {
715 log.debug("handleGetArtifactsByType - no HTTP_CSP_HEADER , component id {}", componentId);
716 throw new ByActionStatusComponentException(ActionStatus.MISSING_INFORMATION);
719 // check user existence
723 validateUserExists(userId);
725 // 5. check service/resource existence
726 // 6. check service/resource check out
727 // 7. user is owner of checkout state
728 String realComponentId = componentType == ComponentTypeEnum.RESOURCE_INSTANCE ? parentId : componentId;
729 ComponentParametersView componentFilter = new ComponentParametersView();
730 componentFilter.disableAll();
731 componentFilter.setIgnoreArtifacts(false);
732 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
733 componentFilter.setIgnoreComponentInstances(false);
736 Component component = validateComponentExistsByFilter(realComponentId, ComponentTypeEnum
737 .findByParamName(containerComponentType), componentFilter);
738 lockComponent(component, ARTIFACT_ACTION_LOCK);
739 boolean failed = false;
741 ArtifactGroupTypeEnum groupType = ArtifactGroupTypeEnum.findType(artifactGroupType);
743 if (groupType == null) {
744 log.debug("handleGetArtifactsByType - not failed groupType {} , component id {}", artifactGroupType, componentId);
745 throw new ByActionStatusComponentException(ActionStatus.MISSING_INFORMATION);
747 if (groupType == ArtifactGroupTypeEnum.DEPLOYMENT) {
748 List<ArtifactDefinition> list = getDeploymentArtifacts(component, componentType.getNodeType(), componentId);
749 if (list != null && !list.isEmpty()) {
750 resMap = list.stream().collect(Collectors.toMap(ArtifactDataDefinition::getArtifactLabel, Function.identity()));
753 resMap = new HashMap<>();
758 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifactsMapStatus = getArtifacts(realComponentId, componentType
759 .getNodeType(), groupType, componentId);
760 if (artifactsMapStatus.isRight()) {
761 if (artifactsMapStatus.right().value() != StorageOperationStatus.NOT_FOUND) {
762 log.debug("handleGetArtifactsByType - not failed groupType {} , component id {}", artifactGroupType, componentId);
763 throw new ByActionStatusComponentException(ActionStatus.MISSING_INFORMATION);
766 resMap = new HashMap<>();
770 resMap = artifactsMapStatus.left().value();
774 }catch (ComponentException e){
781 janusGraphDao.rollback();
785 janusGraphDao.commit();
788 componentType = component.getComponentType();
789 NodeTypeEnum nodeType = componentType.getNodeType();
790 graphLockOperation.unlockComponent(component.getUniqueId(), nodeType);
795 private ArtifactDefinition getArtifactIfBelongsToComponent(String componentId, ComponentTypeEnum componentType, String artifactId, Component component) {
796 // check artifact existence
797 Either<ArtifactDefinition, StorageOperationStatus> artifactResult = artifactToscaOperation.getArtifactById(componentId, artifactId,
798 componentType, component.getUniqueId());
799 if (artifactResult.isRight()) {
800 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_ARTIFACT_NOT_FOUND, artifactId, componentId);
802 // verify artifact belongs to component
804 switch (componentType) {
807 found = checkArtifactInComponent(component, artifactId);
809 case RESOURCE_INSTANCE:
810 found = checkArtifactInResourceInstance(component, componentId, artifactId);
816 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_ARTIFACT_NOT_FOUND, artifactId, componentType.name().toLowerCase());
818 return artifactResult.left().value();
821 private Either<ArtifactDefinition, Operation> handleCreate(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, User user, ComponentTypeEnum componentType,
822 Component parent, String origMd5, String originData, String interfaceType, String operationName) {
823 byte[] decodedPayload = validateInput(componentId, artifactInfo, operation, auditingAction, null, user, componentType, parent, origMd5, originData, interfaceType, operationName);
824 return createArtifact(parent, componentId, artifactInfo, decodedPayload, componentType, auditingAction, interfaceType, operationName);
827 private ArtifactDefinition handleLink(String componentId, ArtifactDefinition artifactInfo, ComponentTypeEnum componentType,
829 ComponentInstance foundInstance = findComponentInstance(componentId, parent);
830 String instanceId = null;
831 if (foundInstance != null) {
832 instanceId = foundInstance.getUniqueId();
834 NodeTypeEnum nodeType = convertParentType(componentType);
835 Either<ArtifactDefinition, StorageOperationStatus> artifactDefinitionEither = artifactToscaOperation.addArtifactToComponent(artifactInfo, parent,
836 nodeType, true, instanceId);
837 if (artifactDefinitionEither.isRight()) {
838 throw new StorageException(artifactDefinitionEither.right().value(), artifactInfo.getArtifactDisplayName());
840 if (generateCustomizationUUIDOnInstance(parent.getUniqueId(), componentId, componentType) != StorageOperationStatus.OK) {
841 throw new StorageException(artifactDefinitionEither.right().value(), artifactInfo.getArtifactDisplayName());
843 return artifactDefinitionEither.left().value();
846 private Either<ArtifactDefinition, Operation> lockComponentAndUpdateArtifact(
847 String parentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId,
848 User user, ComponentTypeEnum componentType, Component parent, byte[] decodedPayload, String interfaceType,
849 String operationName, boolean shouldLock, boolean inTransaction) {
851 Either<ArtifactDefinition, Operation> resultOp = null;
852 boolean failed = false;
853 boolean writeAudit = true;
855 lockComponent(parent, shouldLock, ARTIFACT_ACTION_LOCK);
857 resultOp = updateArtifactFlow(parent, parentId, artifactId, artifactInfo, decodedPayload, componentType, auditingAction, interfaceType, operationName);
860 catch (ComponentException ce) {
862 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, ce.getResponseFormat(), componentType, null);
867 catch (StorageException se) {
874 unlockComponent(failed, parent, inTransaction);
879 private byte[] validateInput(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType,
880 Component parent, String origMd5, String originData, String interfaceType, String operationName) {
881 validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
882 return getValidPayload(componentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, interfaceType, operationName);
885 private byte[] getValidPayload(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction,
886 String artifactId, User user, ComponentTypeEnum componentType, Component parent, String interfaceType, String operationName) {
888 Either<ArtifactDefinition, ResponseFormat> validateResult = validateInput(componentId, artifactInfo, operation, artifactId, user, interfaceType, operationName, componentType, parent);
889 if (validateResult.isRight()) {
890 ResponseFormat responseFormat = validateResult.right().value();
891 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
892 throw new ByResponseFormatComponentException(responseFormat);
895 Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
896 if (payloadEither.isRight()) {
897 ResponseFormat responseFormat = payloadEither.right().value();
898 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
899 log.debug("Error during handle payload");
900 throw new ByResponseFormatComponentException(responseFormat);
902 // validate heat parameters. this part must be after the parameters are
903 // extracted in "handlePayload"
904 Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParameters = validateAndConvertHeatParameters(artifactInfo, artifactInfo
906 if (validateAndConvertHeatParameters.isRight()) {
907 ResponseFormat responseFormat = validateAndConvertHeatParameters.right().value();
908 handleAuditing(auditingAction, parent, componentId, user, artifactInfo, null, artifactId, responseFormat, componentType, null);
909 log.debug("Error during handle payload");
910 throw new ByResponseFormatComponentException(responseFormat);
912 return payloadEither.left().value();
915 public void handleAuditing(AuditingActionEnum auditingActionEnum, Component component, String componentId, User user,
916 ArtifactDefinition artifactDefinition, String prevArtifactUuid, String currentArtifactUuid,
917 ResponseFormat responseFormat, ComponentTypeEnum componentTypeEnum, String resourceInstanceName) {
919 if (componentsUtils.isExternalApiEvent(auditingActionEnum)) {
925 user.setUserId("UNKNOWN");
927 handleInternalAuditEvent(auditingActionEnum, component, componentId, user, artifactDefinition, prevArtifactUuid, currentArtifactUuid, responseFormat, componentTypeEnum, resourceInstanceName);
930 private void handleInternalAuditEvent(AuditingActionEnum auditingActionEnum, Component component, String componentId, User user, ArtifactDefinition artifactDefinition, String prevArtifactUuid, String currentArtifactUuid, ResponseFormat responseFormat, ComponentTypeEnum componentTypeEnum, String resourceInstanceName) {
931 switch (componentTypeEnum) {
933 Resource resource = (Resource) component;
934 if (resource == null) {
935 // In that case, component ID should be instead of name
936 resource = new Resource();
937 resource.setName(componentId);
939 componentsUtils.auditResource(responseFormat, user, resource, resource.getName(), auditingActionEnum,
940 ResourceVersionInfo.newBuilder()
941 .artifactUuid(prevArtifactUuid)
942 .build(), currentArtifactUuid, artifactDefinition);
946 Service service = (Service) component;
947 if (service == null) {
948 // In that case, component ID should be instead of name
949 service = new Service();
950 service.setName(componentId);
952 componentsUtils.auditComponent(responseFormat, user, service, auditingActionEnum, new ResourceCommonInfo(ComponentTypeEnum.SERVICE.getValue()),
953 ResourceVersionInfo.newBuilder()
954 .artifactUuid(prevArtifactUuid)
956 ResourceVersionInfo.newBuilder()
957 .artifactUuid(currentArtifactUuid)
959 null, artifactDefinition, null);
962 case RESOURCE_INSTANCE:
963 if (resourceInstanceName == null) {
964 resourceInstanceName = getResourceInstanceNameFromComponent(component, componentId);
966 componentsUtils.auditComponent(responseFormat, user, component, auditingActionEnum,
967 new ResourceCommonInfo(resourceInstanceName, ComponentTypeEnum.RESOURCE_INSTANCE.getValue()),
968 ResourceVersionInfo.newBuilder()
969 .artifactUuid(prevArtifactUuid)
971 ResourceVersionInfo.newBuilder()
972 .artifactUuid(currentArtifactUuid)
974 null, artifactDefinition, null);
981 private String getResourceInstanceNameFromComponent(Component component, String componentId) {
982 ComponentInstance resourceInstance = component.getComponentInstances()
984 .filter(p -> p.getUniqueId().equals(componentId))
987 String resourceInstanceName = null;
988 if (resourceInstance != null) {
989 resourceInstanceName = resourceInstance.getName();
991 return resourceInstanceName;
994 private void validateMd5(String origMd5, String originData, byte[] payload, ArtifactOperationInfo operation) {
995 if (origMd5 == null) {
996 if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()) && ArrayUtils.isNotEmpty(payload)) {
997 log.debug("Missing md5 header during artifact create");
998 throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_INVALID_MD5);
1001 if (ArrayUtils.isNotEmpty(payload)) {
1002 log.debug("Cannot have payload while md5 header is missing");
1003 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
1006 String encodeBase64Str = GeneralUtility.calculateMD5Base64EncodedByString(originData);
1007 if (!encodeBase64Str.equals(origMd5)) {
1008 log.debug("The calculated md5 is different then the received one");
1009 throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_INVALID_MD5);
1014 private Either<ArtifactDefinition, ResponseFormat> validateInput(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, String artifactId, User user, String interfaceName, String operationName,
1015 ComponentTypeEnum componentType, Component parentComponent) {
1017 ArtifactDefinition currentArtifactInfo = findArtifactOnParentComponent(parentComponent, componentType, componentId, operation, artifactId);
1018 ignoreUnupdateableFieldsInUpdate(operation, artifactInfo, currentArtifactInfo);
1019 validateInformationalArtifact(artifactInfo, parentComponent);
1020 Either<Boolean, ResponseFormat> validateAndSetArtifactname = validateAndSetArtifactName(
1022 if (validateAndSetArtifactname.isRight()) {
1023 return Either.right(validateAndSetArtifactname.right().value());
1025 if (!validateArtifactNameUniqueness(componentId, parentComponent, artifactInfo, componentType)) {
1026 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST));
1028 if (operationName != null && interfaceName != null) {
1029 operationName = operationName.toLowerCase();
1030 interfaceName = interfaceName.toLowerCase();
1032 Either<ActionStatus, ResponseFormat> logicalNameStatus = handleArtifactLabel(componentId, parentComponent, operation, artifactInfo, operationName, componentType);
1033 if (logicalNameStatus.isRight()) {
1034 return Either.right(logicalNameStatus.right().value());
1036 // This is a patch to block possibility of updating service api fields
1037 // through other artifacts flow
1039 ArtifactGroupTypeEnum artifactGroupType = operationName != null ? ArtifactGroupTypeEnum.LIFE_CYCLE : ArtifactGroupTypeEnum.INFORMATIONAL;
1040 if (!ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
1041 checkAndSetUnUpdatableFields(user, artifactInfo, currentArtifactInfo, artifactGroupType);
1044 checkCreateFields(user, artifactInfo, artifactGroupType);
1047 composeArtifactId(componentId, artifactId, artifactInfo, interfaceName, operationName);
1048 if (currentArtifactInfo != null) {
1049 artifactInfo.setMandatory(currentArtifactInfo.getMandatory());
1052 // artifactGroupType is not allowed to be updated
1053 if (!ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
1054 Either<ArtifactDefinition, ResponseFormat> validateGroupType = validateOrSetArtifactGroupType(artifactInfo, currentArtifactInfo);
1055 if (validateGroupType.isRight()) {
1056 return Either.right(validateGroupType.right().value());
1060 NodeTypeEnum parentType = convertParentType(componentType);
1063 boolean isCreate = ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum());
1065 if (isDeploymentArtifact(artifactInfo)) {
1066 validateDeploymentArtifact(parentComponent, componentId, isCreate, artifactInfo, currentArtifactInfo, parentType);
1069 artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
1072 Either<Boolean, ResponseFormat> descriptionResult = validateAndCleanDescription(artifactInfo);
1073 if (descriptionResult.isRight()) {
1074 return Either.right(descriptionResult.right().value());
1077 if (currentArtifactInfo != null && currentArtifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.SERVICE_API) {
1078 Either<ActionStatus, ResponseFormat> validateServiceApiType = validateArtifactType(user.getUserId(), artifactInfo, parentType);
1079 if (validateServiceApiType.isRight()) {
1080 return Either.right(validateServiceApiType.right().value());
1082 // Change of type is not allowed and should be ignored
1084 artifactInfo.setArtifactType(ARTIFACT_TYPE_OTHER);
1086 Either<Boolean, ResponseFormat> validateUrl = validateAndServiceApiUrl(artifactInfo);
1087 if (validateUrl.isRight()) {
1088 return Either.right(validateUrl.right().value());
1091 Either<Boolean, ResponseFormat> validateUpdate = validateFirstUpdateHasPayload(artifactInfo, currentArtifactInfo);
1092 if (validateUpdate.isRight()) {
1093 log.debug("serviceApi first update cnnot be without payload.");
1094 return Either.right(validateUpdate.right().value());
1098 Either<ActionStatus, ResponseFormat> validateArtifactType = validateArtifactType(user.getUserId(), artifactInfo, parentType);
1099 if (validateArtifactType.isRight()) {
1100 return Either.right(validateArtifactType.right().value());
1102 if (artifactInfo.getApiUrl() != null) {
1103 artifactInfo.setApiUrl(null);
1104 log.error("Artifact URL cannot be set through this API - ignoring");
1107 if (artifactInfo.getServiceApi() != null && artifactInfo.getServiceApi()) {
1108 artifactInfo.setServiceApi(false);
1109 log.error("Artifact service API flag cannot be changed - ignoring");
1113 return Either.left(artifactInfo);
1116 private void ignoreUnupdateableFieldsInUpdate(ArtifactOperationInfo operation, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifactInfo) {
1117 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.UPDATE) {
1118 artifactInfo.setArtifactType(currentArtifactInfo.getArtifactType());
1119 artifactInfo.setArtifactGroupType(currentArtifactInfo.getArtifactGroupType());
1120 artifactInfo.setArtifactLabel(currentArtifactInfo.getArtifactLabel());
1124 private ArtifactDefinition findArtifactOnParentComponent(Component parentComponent, ComponentTypeEnum componentType, String parentId, ArtifactOperationInfo operation, String artifactId) {
1126 ArtifactDefinition foundArtifact = null;
1127 if (StringUtils.isNotEmpty(artifactId)) {
1128 foundArtifact = findArtifact(parentComponent, componentType, parentId, artifactId);
1130 if (foundArtifact != null && ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
1131 log.debug("Artifact {} already exist", artifactId);
1132 throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_EXIST, foundArtifact.getArtifactLabel());
1134 if (foundArtifact == null && !ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
1135 log.debug("The artifact {} was not found on parent {}. ", artifactId, parentId);
1136 throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_NOT_FOUND, "");
1138 return foundArtifact;
1141 private ArtifactDefinition findArtifact(Component parentComponent, ComponentTypeEnum componentType, String parentId, String artifactId) {
1142 ArtifactDefinition foundArtifact;
1143 if (parentComponent.getUniqueId().equals(parentId)) {
1144 foundArtifact = artifactsResolver.findArtifactOnComponent(parentComponent, componentType, artifactId);
1147 ComponentInstance instance = findComponentInstance(parentId, parentComponent);
1148 foundArtifact = artifactsResolver.findArtifactOnComponentInstance(instance, artifactId);
1150 return foundArtifact;
1153 private void validateInformationalArtifact(ArtifactDefinition artifactInfo, Component parentComponent) {
1154 ComponentTypeEnum parentComponentType = parentComponent.getComponentType();
1155 ArtifactGroupTypeEnum groupType = artifactInfo.getArtifactGroupType();
1156 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
1157 if (artifactType == null) {
1158 throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType());
1160 else if (parentComponentType == ComponentTypeEnum.RESOURCE && groupType == ArtifactGroupTypeEnum.INFORMATIONAL) {
1161 String artifactTypeName = artifactType.getType();
1162 ResourceTypeEnum parentResourceType = ((Resource) parentComponent).getResourceType();
1163 Map<String, ArtifactTypeConfig> resourceInformationalArtifacts = ConfigurationManager.getConfigurationManager()
1165 .getResourceInformationalArtifacts();
1166 Set<String> validArtifactTypes = resourceInformationalArtifacts.keySet();
1167 if (!validArtifactTypes.contains(artifactTypeName)) {
1168 throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactTypeName);
1171 List<String> validResourceType = resourceInformationalArtifacts.get(artifactTypeName)
1172 .getValidForResourceTypes();
1173 if (!validResourceType.contains(parentResourceType.name())) {
1174 throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactTypeName);
1180 private NodeTypeEnum convertParentType(ComponentTypeEnum componentType) {
1181 if (componentType == ComponentTypeEnum.RESOURCE) {
1182 return NodeTypeEnum.Resource;
1184 else if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1185 return NodeTypeEnum.ResourceInstance;
1188 return NodeTypeEnum.Service;
1192 // This method is here for backward compatibility - when other parts of the code are cleaned can change to use the internal version
1193 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete(String parentId, String artifactId, User user, AuditingActionEnum auditingAction, ComponentTypeEnum componentType, Component parent,
1194 boolean shouldLock, boolean inTransaction) {
1195 ResponseFormat responseFormat;
1196 boolean operationSucceeded = false;
1198 lockComponent(componentType, artifactId, auditingAction, user, parent);
1201 ArtifactDefinition artifactDefinition = handleDeleteInternal(parentId, artifactId, componentType, parent);
1202 operationSucceeded = true;
1203 return Either.left(Either.left(artifactDefinition));
1205 catch (ComponentException ce) {
1206 responseFormat = componentsUtils.getResponseFormat(ce);
1207 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1208 return Either.right(responseFormat);
1210 catch (StorageException se) {
1211 responseFormat = componentsUtils.getResponseFormat(se);
1212 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1213 return Either.right(responseFormat);
1215 handleLockingAndCommit(parent, shouldLock, inTransaction, operationSucceeded);
1219 private ArtifactDefinition handleDeleteInternal(String parentId, String artifactId, ComponentTypeEnum componentType, Component parent) {
1220 NodeTypeEnum parentType = convertParentType(componentType);
1221 log.debug("Going to find the artifact {} on the component {}", artifactId, parent.getUniqueId());
1222 Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> getArtifactRes = findArtifact(artifactId, parent, parentId, componentType);
1223 if (getArtifactRes.isRight()) {
1224 log.debug("Failed to find the artifact {} belonging to {} on the component {}", artifactId, parentId, parent.getUniqueId());
1225 throw new ByActionStatusComponentException(getArtifactRes.right().value(), artifactId);
1227 ArtifactDefinition foundArtifact = getArtifactRes.left().value().getLeft();
1228 ComponentInstance foundInstance = getArtifactRes.left().value().getRight();
1229 String esId = foundArtifact.getEsId();
1230 boolean needToClone = false;
1231 if (StringUtils.isNotEmpty(esId)) {
1232 Either<Boolean, StorageOperationStatus> needCloneRes = null;
1233 needCloneRes = artifactToscaOperation.isCloneNeeded(parent.getUniqueId(), foundArtifact, parentType);
1234 if (needCloneRes.isRight()) {
1235 throw new StorageException(needCloneRes.right().value(), foundArtifact.getArtifactDisplayName());
1236 } else if (log.isDebugEnabled()) {
1237 needToClone = needCloneRes.left().value();
1238 log.debug("handleDelete: clone is needed for deleting {} held by {} in component {} ? {}",
1239 foundArtifact.getArtifactName(), parentType, parent.getUniqueId(), parent.getName(), needCloneRes.left().value());
1242 boolean isNeedToDeleteArtifactFromDB = true;
1243 boolean isDuplicated = false;
1244 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1245 isNeedToDeleteArtifactFromDB = isArtifactOnlyResourceInstanceArtifact(foundArtifact, parent, parentId);
1247 ArtifactDataDefinition updatedArtifact = deleteOrUpdateArtifactOnGraph(parent, parentId, artifactId, parentType, foundArtifact, needToClone);
1248 isDuplicated = updatedArtifact.getDuplicated();
1250 if (!needToClone && !isDuplicated && isNeedToDeleteArtifactFromDB) {
1251 log.debug("Going to delete the artifact {} from the database. ", artifactId);
1252 CassandraOperationStatus cassandraStatus = artifactCassandraDao.deleteArtifact(esId);
1253 if (cassandraStatus != CassandraOperationStatus.OK) {
1254 log.debug("Failed to delete the artifact {} from the database. ", artifactId);
1255 throw new StorageException(convertToStorageOperationStatus(cassandraStatus), foundArtifact.getArtifactDisplayName());
1258 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1259 List<GroupInstance> updatedGroupInstances = getUpdatedGroupInstances(artifactId, foundArtifact, foundInstance.getGroupInstances());
1260 if (CollectionUtils.isNotEmpty(updatedGroupInstances)) {
1261 Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(parent, parentId, updatedGroupInstances);
1262 if (status.isRight()) {
1263 log.debug(FAILED_UPDATE_GROUPS, parent.getUniqueId());
1264 throw new StorageException(status.right().value(), foundArtifact.getArtifactDisplayName());
1267 StorageOperationStatus status = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentType);
1268 if (status != StorageOperationStatus.OK) {
1269 log.debug("Failed to generate new customization UUID for the component instance {}. ", parentId);
1270 throw new StorageException(status, foundArtifact.getArtifactDisplayName());
1273 List<GroupDataDefinition> updatedGroups = getUpdatedGroups(artifactId, foundArtifact, parent.getGroups());
1274 if (CollectionUtils.isNotEmpty(updatedGroups)) {
1275 Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(parent, updatedGroups);
1276 if (status.isRight()) {
1277 log.debug(FAILED_UPDATE_GROUPS, parent.getUniqueId());
1278 throw new StorageException(status.right().value(), foundArtifact.getArtifactDisplayName());
1282 return foundArtifact;
1285 private boolean isArtifactOnlyResourceInstanceArtifact(ArtifactDefinition foundArtifact, Component parent, String instanceId) {
1286 Optional<ComponentInstance> componentInstanceOpt = parent.getComponentInstanceById(instanceId);
1287 if (!componentInstanceOpt.isPresent()) {
1288 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, instanceId, "", "", parent.getName());
1290 ComponentInstance foundInstance = componentInstanceOpt.get();
1291 String componentUid = foundInstance.getComponentUid();
1292 Either<Component, StorageOperationStatus> getContainerRes = toscaOperationFacade.getToscaElement(componentUid);
1293 if (getContainerRes.isRight()) {
1294 log.debug("Failed to fetch the container component {}. ", componentUid);
1295 throw new StorageException(getContainerRes.right().value());
1297 Component origComponent = getContainerRes.left().value();
1298 Map<String, ArtifactDefinition> deploymentArtifacts = origComponent.getDeploymentArtifacts();
1299 if (MapUtils.isNotEmpty(deploymentArtifacts)) {
1300 Optional<String> op = deploymentArtifacts.keySet()
1302 .filter(a -> a.equals(foundArtifact.getArtifactLabel()))
1304 if (op.isPresent()) {
1308 Map<String, ArtifactDefinition> artifacts = origComponent.getArtifacts();
1309 if (MapUtils.isNotEmpty(artifacts)) {
1310 Optional<String> op = artifacts.keySet()
1312 .filter(a -> a.equals(foundArtifact.getArtifactLabel()))
1314 if (op.isPresent()) {
1321 private List<GroupDataDefinition> getUpdatedGroups(String artifactId, ArtifactDefinition foundArtifact, List<GroupDefinition> groups) {
1322 List<GroupDataDefinition> updatedGroups = new ArrayList<>();
1323 boolean isUpdated = false;
1324 if (groups != null) {
1325 for (GroupDefinition group : groups) {
1327 if (CollectionUtils.isNotEmpty(group.getArtifacts()) && group.getArtifacts().contains(artifactId)) {
1328 group.getArtifacts().remove(artifactId);
1331 if (CollectionUtils.isNotEmpty(group.getArtifactsUuid()) && group.getArtifactsUuid()
1332 .contains(foundArtifact.getArtifactUUID())) {
1333 group.getArtifactsUuid().remove(foundArtifact.getArtifactUUID());
1337 updatedGroups.add(group);
1341 return updatedGroups;
1344 private List<GroupInstance> getUpdatedGroupInstances(String artifactId, ArtifactDefinition foundArtifact, List<GroupInstance> groupInstances) {
1345 List<GroupInstance> updatedGroupInstances = new ArrayList<>();
1346 if (CollectionUtils.isNotEmpty(groupInstances)) {
1347 boolean isUpdated = false;
1348 for (GroupInstance groupInstance : groupInstances) {
1350 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifacts()) && groupInstance.getGroupInstanceArtifacts().contains(artifactId)) {
1351 groupInstance.getGroupInstanceArtifacts().remove(artifactId);
1354 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifactsUuid()) && groupInstance.getGroupInstanceArtifactsUuid()
1355 .contains(foundArtifact.getArtifactUUID())) {
1356 groupInstance.getGroupInstanceArtifactsUuid().remove(foundArtifact.getArtifactUUID());
1360 updatedGroupInstances.add(groupInstance);
1364 return updatedGroupInstances;
1367 private ArtifactDataDefinition deleteOrUpdateArtifactOnGraph(Component component, String parentId, String artifactId, NodeTypeEnum parentType, ArtifactDefinition foundArtifact, Boolean cloneIsNeeded) {
1369 Either<ArtifactDataDefinition, StorageOperationStatus> result;
1370 boolean isMandatory = foundArtifact.getMandatory() || foundArtifact.getServiceApi();
1371 String componentId = component.getUniqueId();
1372 String instanceId = componentId.equals(parentId) ? null : parentId;
1374 log.debug("Going to update mandatory artifact {} from the component {}", artifactId, parentId);
1375 resetMandatoryArtifactFields(foundArtifact);
1376 result = artifactToscaOperation.updateArtifactOnGraph(component, foundArtifact, parentType, artifactId, instanceId, true, true);
1378 else if (cloneIsNeeded) {
1379 log.debug("Going to clone artifacts and to delete the artifact {} from the component {}", artifactId, parentId);
1380 result = artifactToscaOperation.deleteArtifactWithCloningOnGraph(componentId, foundArtifact, parentType, instanceId, false);
1383 log.debug("Going to delete the artifact {} from the component {}", artifactId, parentId);
1384 result = artifactToscaOperation.removeArtifactOnGraph(foundArtifact, componentId, instanceId, parentType, false);
1386 if (result.isRight()) {
1387 throw new StorageException(result.right().value(), foundArtifact.getArtifactDisplayName());
1389 return result.left().value();
1392 private Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> findArtifact(String artifactId, Component fetchedContainerComponent, String parentId, ComponentTypeEnum componentType) {
1394 Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> result = null;
1395 Map<String, ArtifactDefinition> artifacts = new HashMap<>();
1396 ComponentInstance foundInstance = null;
1397 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE && StringUtils.isNotEmpty(parentId)) {
1398 Optional<ComponentInstance> componentInstanceOpt = fetchedContainerComponent.getComponentInstances()
1400 .filter(i -> i.getUniqueId()
1403 if (!componentInstanceOpt.isPresent()) {
1404 result = Either.right(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER);
1407 foundInstance = componentInstanceOpt.get();
1408 fetchArtifactsFromInstance(artifactId, artifacts, foundInstance);
1412 fetchArtifactsFromComponent(artifactId, fetchedContainerComponent, artifacts);
1414 if (result == null) {
1415 if (artifacts.containsKey(artifactId)) {
1416 result = Either.left(new ImmutablePair<>(artifacts.get(artifactId), foundInstance));
1419 result = Either.right(ActionStatus.ARTIFACT_NOT_FOUND);
1425 private void fetchArtifactsFromComponent(String artifactId, Component component, Map<String, ArtifactDefinition> artifacts) {
1426 Map<String, ArtifactDefinition> currArtifacts;
1427 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getDeploymentArtifacts())) {
1428 currArtifacts = component.getDeploymentArtifacts()
1431 .collect(Collectors.toMap(ArtifactDataDefinition::getUniqueId, i -> i));
1432 if (MapUtils.isNotEmpty(currArtifacts)) {
1433 artifacts.putAll(currArtifacts);
1436 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getArtifacts())) {
1437 currArtifacts = component.getArtifacts()
1440 .collect(Collectors.toMap(ArtifactDataDefinition::getUniqueId, Function.identity()));
1441 if (MapUtils.isNotEmpty(currArtifacts)) {
1442 artifacts.putAll(currArtifacts);
1445 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getArtifacts())) {
1446 currArtifacts = component.getToscaArtifacts()
1449 .collect(Collectors.toMap(ArtifactDataDefinition::getUniqueId, Function.identity()));
1450 if (MapUtils.isNotEmpty(currArtifacts)) {
1451 artifacts.putAll(currArtifacts);
1456 private void fetchArtifactsFromInstance(String artifactId, Map<String, ArtifactDefinition> artifacts, ComponentInstance instance) {
1457 Map<String, ArtifactDefinition> currArtifacts;
1458 if (MapUtils.isNotEmpty(instance.getDeploymentArtifacts())) {
1459 currArtifacts = instance.getDeploymentArtifacts()
1462 .collect(Collectors.toMap(ArtifactDataDefinition::getUniqueId, Function.identity()));
1463 if (MapUtils.isNotEmpty(currArtifacts)) {
1464 artifacts.putAll(currArtifacts);
1467 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(instance.getArtifacts())) {
1468 currArtifacts = instance.getArtifacts()
1471 .collect(Collectors.toMap(ArtifactDataDefinition::getUniqueId, Function.identity()));
1472 if (MapUtils.isNotEmpty(currArtifacts)) {
1473 artifacts.putAll(currArtifacts);
1478 private StorageOperationStatus convertToStorageOperationStatus(CassandraOperationStatus cassandraStatus) {
1479 StorageOperationStatus result;
1480 switch (cassandraStatus) {
1482 result = StorageOperationStatus.OK;
1485 result = StorageOperationStatus.NOT_FOUND;
1487 case CLUSTER_NOT_CONNECTED:
1488 case KEYSPACE_NOT_CONNECTED:
1489 result = StorageOperationStatus.CONNECTION_FAILURE;
1492 result = StorageOperationStatus.GENERAL_ERROR;
1498 private void resetMandatoryArtifactFields(ArtifactDefinition fetchedArtifact) {
1499 if (fetchedArtifact != null) {
1500 log.debug("Going to reset mandatory artifact {} fields. ", fetchedArtifact.getUniqueId());
1501 fetchedArtifact.setEsId(null);
1502 fetchedArtifact.setArtifactName(null);
1503 fetchedArtifact.setDescription(null);
1504 fetchedArtifact.setApiUrl(null);
1505 fetchedArtifact.setArtifactChecksum(null);
1506 nodeTemplateOperation.setDefaultArtifactTimeout(fetchedArtifact.getArtifactGroupType(), fetchedArtifact);
1507 fetchedArtifact.setArtifactUUID(null);
1508 long time = System.currentTimeMillis();
1509 fetchedArtifact.setPayloadUpdateDate(time);
1510 fetchedArtifact.setHeatParameters(null);
1511 fetchedArtifact.setHeatParamsUpdateDate(null);
1515 private StorageOperationStatus generateCustomizationUUIDOnInstance(String componentId, String instanceId, ComponentTypeEnum componentType) {
1516 StorageOperationStatus error = StorageOperationStatus.OK;
1517 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1518 log.debug("Need to re-generate customization UUID for instance {}", instanceId);
1519 error = toscaOperationFacade.generateCustomizationUUIDOnInstance(componentId, instanceId);
1524 private ArtifactDefinition handleDownload(String componentId, String artifactId, ComponentTypeEnum componentType,
1526 Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(componentId, artifactId, componentType,
1527 parent.getUniqueId());
1528 if (artifactById.isRight()) {
1529 throw new StorageException(artifactById.right().value());
1531 ArtifactDefinition artifactDefinition = artifactById.left().value();
1532 if (artifactDefinition == null) {
1533 throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_NOT_FOUND, artifactId);
1535 return artifactDefinition;
1538 private Either<ActionStatus, ResponseFormat> handleArtifactLabel(String componentId, Component parentComponent, ArtifactOperationInfo operation, ArtifactDefinition artifactInfo, String operationName,
1539 ComponentTypeEnum componentType) {
1541 String artifactLabel = artifactInfo.getArtifactLabel();
1542 if (operationName == null && (artifactInfo.getArtifactLabel() == null || artifactInfo.getArtifactLabel()
1544 BeEcompErrorManager.getInstance()
1545 .logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel");
1546 log.debug("missing artifact logical name for component {}", componentId);
1547 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_LABEL));
1549 if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()) && !artifactInfo.getMandatory()) {
1551 if (operationName != null) {
1552 if (artifactInfo.getArtifactLabel() != null && !operationName.equals(artifactInfo.getArtifactLabel())) {
1553 log.debug("artifact label cannot be set {}", artifactLabel);
1554 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_LOGICAL_NAME_CANNOT_BE_CHANGED));
1557 artifactLabel = operationName;
1560 String displayName = artifactInfo.getArtifactDisplayName();
1561 if (displayName == null || displayName.isEmpty()) {
1562 displayName = artifactLabel;
1564 displayName = ValidationUtils.cleanArtifactDisplayName(displayName);
1565 artifactInfo.setArtifactDisplayName(displayName);
1567 if (!ValidationUtils.validateArtifactLabel(artifactLabel)) {
1568 log.debug("Invalid format form Artifact label : {}", artifactLabel);
1569 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1571 artifactLabel = ValidationUtils.normalizeArtifactLabel(artifactLabel);
1573 if (artifactLabel.isEmpty()) {
1574 log.debug("missing normalized artifact logical name for component {}", componentId);
1575 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_LABEL));
1578 if (!ValidationUtils.validateArtifactLabelLength(artifactLabel)) {
1579 log.debug("Invalid lenght form Artifact label : {}", artifactLabel);
1580 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_LABEL, String
1581 .valueOf(ValidationUtils.ARTIFACT_LABEL_LENGTH)));
1583 if (!validateLabelUniqueness(componentId, parentComponent, artifactLabel, componentType)) {
1584 log.debug("Non unique Artifact label : {}", artifactLabel);
1585 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactLabel));
1588 artifactInfo.setArtifactLabel(artifactLabel);
1590 return Either.left(ActionStatus.OK);
1593 private boolean validateLabelUniqueness(String componentId, Component parentComponent, String artifactLabel, ComponentTypeEnum componentType) {
1594 boolean isUnique = true;
1595 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifacts;
1596 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1597 artifacts = artifactToscaOperation.getAllInstanceArtifacts(parentComponent.getUniqueId(), componentId);
1600 artifacts = artifactToscaOperation.getArtifacts(componentId);
1603 if (artifacts.isLeft()) {
1604 for (String label : artifacts.left().value().keySet()) {
1605 if (label.equals(artifactLabel)) {
1611 if (componentType == ComponentTypeEnum.RESOURCE && isUnique) {
1612 isUnique = isUniqueLabelInResourceInterfaces(componentId, artifactLabel);
1617 boolean validateArtifactNameUniqueness(String componentId, Component parentComponent, ArtifactDefinition artifactInfo,
1618 ComponentTypeEnum componentType) {
1619 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifacts = getArtifacts(componentType,
1620 parentComponent, componentId, artifactInfo.getArtifactGroupType());
1621 String artifactName = artifactInfo.getArtifactName();
1622 if (artifacts.isLeft() && Objects.nonNull(artifacts.left().value())){
1623 if (artifacts.left().value().values().stream()
1624 .anyMatch(ad -> artifactName.equals(ad.getArtifactName())
1625 //check whether it is the same artifact we hold (by label)
1626 && !artifactInfo.getArtifactLabel().equals(ad.getArtifactLabel()))){
1630 if (ComponentTypeEnum.RESOURCE == componentType) {
1631 return isUniqueArtifactNameInResourceInterfaces(componentId, artifactName, artifactInfo.getArtifactLabel());
1636 private boolean isUniqueArtifactNameInResourceInterfaces(String componentId, String artifactName, String artifactLabel) {
1637 Either<Map<String, InterfaceDefinition>, StorageOperationStatus> allInterfacesOfResource = interfaceLifecycleOperation
1638 .getAllInterfacesOfResource(componentId, true, true);
1640 if (allInterfacesOfResource.isLeft()){
1641 return allInterfacesOfResource.left().value()
1643 .stream().map(InterfaceDefinition :: getOperationsMap)
1644 .flatMap(map -> map.values().stream())
1645 .map(OperationDataDefinition::getImplementation)
1646 .filter(Objects::nonNull)
1647 .noneMatch(add -> artifactName.equals(add.getArtifactName())
1648 && !artifactLabel.equals(add.getArtifactLabel()));
1653 private boolean isUniqueLabelInResourceInterfaces(String componentId, String artifactLabel) {
1654 Either<Map<String, InterfaceDefinition>, StorageOperationStatus> allInterfacesOfResource = interfaceLifecycleOperation
1655 .getAllInterfacesOfResource(componentId, true, true);
1657 if (allInterfacesOfResource.isLeft()){
1658 return allInterfacesOfResource.left().value()
1660 .stream().map(InterfaceDefinition :: getOperationsMap)
1661 .flatMap(map -> map.values().stream())
1662 .map(OperationDataDefinition::getImplementation)
1663 .filter(Objects::nonNull)
1664 .noneMatch(add -> artifactLabel.equals(add.getArtifactLabel()));
1669 private Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(ComponentTypeEnum componentType, Component parentComponent,
1670 String componentId, ArtifactGroupTypeEnum artifactGroupType) {
1671 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifactsResponse;
1672 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1673 artifactsResponse = artifactToscaOperation.getAllInstanceArtifacts(parentComponent.getUniqueId(), componentId);
1676 artifactsResponse = artifactToscaOperation.getArtifacts(componentId);
1678 if (artifactsResponse.isRight() && artifactsResponse.right().value() == StorageOperationStatus.NOT_FOUND) {
1679 log.debug("failed to retrieve artifacts for {} ", componentId);
1680 return Either.right(artifactsResponse.right().value());
1682 return Either.left(artifactsResponse.left().value().entrySet()
1684 .filter(x -> artifactGroupType == x.getValue().getArtifactGroupType())
1685 .collect(Collectors.toMap(Entry::getKey, Entry::getValue)));
1688 // ***************************************************************
1690 private Either<ArtifactDefinition, Operation> createArtifact(Component parent, String parentId, ArtifactDefinition artifactInfo, byte[] decodedPayload,
1691 ComponentTypeEnum componentTypeEnum, AuditingActionEnum auditingActionEnum, String interfaceType, String operationName) {
1693 DAOArtifactData artifactData = createEsArtifactData(artifactInfo, decodedPayload);
1694 if (artifactData == null) {
1695 BeEcompErrorManager.getInstance().logBeDaoSystemError("Upload Artifact");
1696 log.debug("Failed to create artifact object for ES.");
1697 throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
1699 ComponentInstance foundInstance = findComponentInstance(parentId, parent);
1700 String instanceId = null;
1701 if (foundInstance != null) {
1702 if (foundInstance.isArtifactExists(artifactInfo.getArtifactGroupType(), artifactInfo.getArtifactLabel())) {
1703 log.debug("Failed to create artifact, already exists");
1704 throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_EXIST, artifactInfo.getArtifactLabel());
1706 instanceId = foundInstance.getUniqueId();
1708 // set on graph object id of artifact in ES!
1709 artifactInfo.setEsId(artifactData.getId());
1711 Either<ArtifactDefinition, Operation> operationResult;
1712 if (interfaceType != null && operationName != null) {
1713 // lifecycle artifact
1714 Operation operation = convertToOperation(artifactInfo, operationName);
1715 Either<Operation, StorageOperationStatus> result = interfaceLifecycleOperation.updateInterfaceOperation(parentId, interfaceType, operationName, operation);
1716 if (result.isRight()) {
1717 throw new StorageException(result.right().value());
1719 operationResult = Either.right(result.left().value());
1722 // information/deployment/api artifacts
1723 NodeTypeEnum nodeType = convertParentType(componentTypeEnum);
1724 Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.addArtifactToComponent(
1725 artifactInfo, parent, nodeType, true, instanceId);
1726 if (result.isRight()) {
1727 throw new StorageException(result.right().value());
1729 ArtifactDefinition artifactDefinition = result.left().value();
1730 artifactData.setId(artifactDefinition.getEsId());
1731 operationResult = Either.left(artifactDefinition);
1733 if (generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentTypeEnum) != StorageOperationStatus.OK) {
1734 throw new StorageException(generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentTypeEnum));
1737 saveArtifactInCassandra(artifactData, parent, artifactInfo, "", "", auditingActionEnum, componentTypeEnum);
1738 return operationResult;
1741 private ComponentInstance findComponentInstance(String componentInstanceId, Component containerComponent) {
1742 ComponentInstance foundInstance = null;
1743 if (CollectionUtils.isNotEmpty(containerComponent.getComponentInstances())) {
1744 foundInstance = containerComponent.getComponentInstances()
1746 .filter(i -> i.getUniqueId().equals(componentInstanceId))
1750 return foundInstance;
1753 private void validateDeploymentArtifact(Component parentComponent, String parentId, boolean isCreate, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, NodeTypeEnum parentType) {
1755 ArtifactTypeEnum artifactType = getValidArtifactType(artifactInfo);
1756 Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts = fillDeploymentArtifactTypeConf(parentType);
1757 validateDeploymentArtifactTypeIsLegalForParent(artifactInfo, artifactType, resourceDeploymentArtifacts);
1759 validateArtifactTypeNotChanged(artifactInfo, currentArtifact);
1761 if (parentType == NodeTypeEnum.Resource) {
1762 Resource resource = (Resource) parentComponent;
1763 ResourceTypeEnum resourceType = resource.getResourceType();
1764 ArtifactTypeConfig config = resourceDeploymentArtifacts.get(artifactType.getType());
1765 if (config == null) {
1766 throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType());
1768 List<String> myList = config.getValidForResourceTypes();
1769 validateResourceType(resourceType, artifactInfo, myList);
1772 validateFileExtension(() -> getDeploymentArtifactTypeConfig(parentType, artifactType), artifactInfo, parentType, artifactType);
1774 if (NodeTypeEnum.ResourceInstance != parentType) {
1775 String artifactName = artifactInfo.getArtifactName();
1776 if (isCreate || !artifactName.equalsIgnoreCase(currentArtifact.getArtifactName())) {
1777 validateSingleDeploymentArtifactName(artifactName, parentComponent, parentType);
1781 switch (artifactType) {
1785 validateHeatTimeoutValue(isCreate, artifactInfo, currentArtifact);
1788 validateHeatEnvDeploymentArtifact(parentComponent, parentId, artifactInfo, parentType);
1789 artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
1791 case DCAE_INVENTORY_TOSCA:
1792 case DCAE_INVENTORY_JSON:
1793 case DCAE_INVENTORY_POLICY:
1794 // Validation is done in handle payload.
1795 case DCAE_INVENTORY_DOC:
1796 case DCAE_INVENTORY_BLUEPRINT:
1797 case DCAE_INVENTORY_EVENT:
1798 // No specific validation
1800 artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
1806 void validateDeploymentArtifactTypeIsLegalForParent(ArtifactDefinition artifactInfo, ArtifactTypeEnum artifactType, Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts) {
1807 if ((resourceDeploymentArtifacts == null) || !resourceDeploymentArtifacts.containsKey(artifactType.name())) {
1808 log.debug("Artifact Type: {} Not found !", artifactInfo.getArtifactType());
1809 throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType());
1813 private Map<String, ArtifactTypeConfig> fillDeploymentArtifactTypeConf(NodeTypeEnum parentType) {
1814 Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts;
1815 if (parentType == NodeTypeEnum.Resource) {
1816 resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager()
1818 .getResourceDeploymentArtifacts();
1820 else if (parentType == NodeTypeEnum.ResourceInstance) {
1821 resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager()
1823 .getResourceInstanceDeploymentArtifacts();
1826 resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager()
1828 .getServiceDeploymentArtifacts();
1830 return resourceDeploymentArtifacts;
1833 public ArtifactTypeEnum getValidArtifactType(ArtifactDefinition artifactInfo) {
1834 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
1835 if (artifactType == null) {
1836 log.debug("Artifact Type: {} Not found !", artifactInfo.getArtifactType());
1837 throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType());
1839 return artifactType;
1842 private ArtifactTypeConfig getDeploymentArtifactTypeConfig(NodeTypeEnum parentType, ArtifactTypeEnum artifactType) {
1843 ArtifactTypeConfig retConfig = null;
1844 String fileType = artifactType.getType();
1845 if (parentType == NodeTypeEnum.Resource) {
1846 retConfig = ConfigurationManager.getConfigurationManager()
1848 .getResourceDeploymentArtifacts()
1851 else if (parentType == NodeTypeEnum.Service) {
1852 retConfig = ConfigurationManager.getConfigurationManager()
1854 .getServiceDeploymentArtifacts()
1857 else if (parentType == NodeTypeEnum.ResourceInstance) {
1858 retConfig = ConfigurationManager.getConfigurationManager()
1860 .getResourceInstanceDeploymentArtifacts()
1866 private Either<Boolean, ResponseFormat> extractHeatParameters(ArtifactDefinition artifactInfo) {
1867 // extract heat parameters
1868 if (artifactInfo.getPayloadData() != null) {
1869 String heatDecodedPayload = new String(Base64.decodeBase64(artifactInfo.getPayloadData()));
1870 Either<List<HeatParameterDefinition>, ResultStatusEnum> heatParameters = ImportUtils.getHeatParamsWithoutImplicitTypes(heatDecodedPayload, artifactInfo
1871 .getArtifactType());
1872 if (heatParameters.isRight() && (heatParameters.right().value() != ResultStatusEnum.ELEMENT_NOT_FOUND)) {
1873 log.info("failed to parse heat parameters ");
1874 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactInfo
1875 .getArtifactType());
1876 return Either.right(responseFormat);
1878 else if (heatParameters.isLeft() && heatParameters.left().value() != null) {
1879 artifactInfo.setListHeatParameters(heatParameters.left().value());
1882 return Either.left(true);
1887 public void validateFileExtension(IDeploymentArtifactTypeConfigGetter deploymentConfigGetter, ArtifactDefinition artifactInfo, NodeTypeEnum parentType, ArtifactTypeEnum artifactType) {
1888 if (parentType != NodeTypeEnum.Resource && parentType != NodeTypeEnum.Service && parentType != NodeTypeEnum.ResourceInstance) {
1889 log.debug("parent type of artifact can be either resource or service");
1890 throw new ByActionStatusComponentException(MISMATCH_BETWEEN_ARTIFACT_TYPE_AND_COMPONENT_TYPE, artifactType.name(), "Service, Resource or ResourceInstance", parentType.getName());
1893 String fileType = artifactType.getType();
1894 ArtifactTypeConfig deploymentAcceptedTypes = deploymentConfigGetter.getDeploymentArtifactConfig();
1895 if (deploymentAcceptedTypes == null) {
1896 log.debug("invalid artifact type {}", fileType);
1897 throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, fileType);
1900 * No need to check specific types. In case there are no acceptedTypes in configuration, then any type is accepted.
1903 List<String> acceptedTypes = deploymentAcceptedTypes.getAcceptedTypes();
1904 String artifactName = artifactInfo.getArtifactName();
1905 String fileExtension = GeneralUtility.getFilenameExtension(artifactName);
1906 // Pavel - File extension validation is case-insensitive - Ella,
1908 if (CollectionUtils.isNotEmpty(acceptedTypes) && !acceptedTypes.contains(fileExtension.toLowerCase())) {
1909 log.debug("File extension \"{}\" is not allowed for {} which is of type:{}", fileExtension, artifactName, fileType);
1910 throw new ByActionStatusComponentException(ActionStatus.WRONG_ARTIFACT_FILE_EXTENSION, fileType);
1915 void validateHeatEnvDeploymentArtifact(Component parentComponent, String parentId, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) {
1917 Wrapper<ArtifactDefinition> heatMDWrapper = new Wrapper<>();
1918 Wrapper<byte[]> payloadWrapper = new Wrapper<>();
1920 validateYaml(artifactInfo);
1921 validateHeatExist(parentComponent.getUniqueId(), parentId, heatMDWrapper, artifactInfo,
1922 parentType, parentComponent.getComponentType());
1924 if (!heatMDWrapper.isEmpty()) {
1925 fillArtifactPayload(payloadWrapper, heatMDWrapper.getInnerElement());
1928 if (!heatMDWrapper.isEmpty()) {
1929 validateEnvVsHeat(artifactInfo, heatMDWrapper.getInnerElement(), payloadWrapper.getInnerElement());
1933 public void fillArtifactPayload(Wrapper<byte[]> payloadWrapper, ArtifactDefinition artifactDefinition) {
1934 if (ArrayUtils.isEmpty(artifactDefinition.getPayloadData())) {
1935 Either<DAOArtifactData, CassandraOperationStatus> eitherArtifactData = artifactCassandraDao.getArtifact(artifactDefinition.getEsId());
1936 if (eitherArtifactData.isLeft()) {
1937 byte[] data = eitherArtifactData.left().value().getDataAsArray();
1938 payloadWrapper.setInnerElement(Base64.encodeBase64(data));
1941 log.debug("Error getting payload for artifact:{}", artifactDefinition.getArtifactName());
1942 throw new StorageException(DaoStatusConverter.convertCassandraStatusToStorageStatus(eitherArtifactData.right().value()));
1946 payloadWrapper.setInnerElement(artifactDefinition.getPayloadData());
1950 private void validateEnvVsHeat(ArtifactDefinition envArtifact, ArtifactDefinition heatArtifact, byte[] heatPayloadData) {
1951 String envPayload = new String(Base64.decodeBase64(envArtifact.getPayloadData()));
1952 Map<String, Object> heatEnvToscaJson = (Map<String, Object>) new Yaml().load(envPayload);
1953 String heatDecodedPayload = new String(Base64.decodeBase64(heatPayloadData));
1954 Map<String, Object> heatToscaJson = (Map<String, Object>) new Yaml().load(heatDecodedPayload);
1956 Either<Map<String, Object>, ResultStatusEnum> eitherHeatEnvProperties = ImportUtils.findFirstToscaMapElement(heatEnvToscaJson, TypeUtils.ToscaTagNamesEnum.PARAMETERS);
1957 if (eitherHeatEnvProperties.isRight()) {
1958 log.debug("Invalid heat env format for file:{}", envArtifact.getArtifactName());
1959 throw new ByActionStatusComponentException(ActionStatus.CORRUPTED_FORMAT, "Heat Env");
1961 Either<Map<String, Object>, ResultStatusEnum> eitherHeatProperties = ImportUtils.findFirstToscaMapElement(heatToscaJson, TypeUtils.ToscaTagNamesEnum.PARAMETERS);
1962 if (eitherHeatProperties.isRight()) {
1963 log.debug("Invalid heat format for file:{}", heatArtifact.getArtifactName());
1964 throw new ByActionStatusComponentException(ActionStatus.CORRUPTED_FORMAT, "Heat");
1966 Set<String> heatPropertiesKeys = eitherHeatProperties.left().value().keySet();
1967 Set<String> heatEnvPropertiesKeys = eitherHeatEnvProperties.left().value().keySet();
1968 heatEnvPropertiesKeys.removeAll(heatPropertiesKeys);
1969 if (!heatEnvPropertiesKeys.isEmpty()) {
1970 log.debug("Validation of heat_env for artifact:{} vs heat artifact for artifact :{} failed", envArtifact.getArtifactName(), heatArtifact.getArtifactName());
1971 throw new ByActionStatusComponentException(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, envArtifact.getArtifactName(), heatArtifact.getArtifactName());
1975 private void validateYaml(ArtifactDefinition artifactInfo) {
1976 YamlToObjectConverter yamlConverter = new YamlToObjectConverter();
1977 boolean isYamlValid = yamlConverter.isValidYamlEncoded64(artifactInfo.getPayloadData());
1979 log.debug("Yaml is not valid for artifact : {}", artifactInfo.getArtifactName());
1980 throw new ByActionStatusComponentException(ActionStatus.INVALID_YAML, artifactInfo.getArtifactType());
1984 private boolean isValidXml(byte[] xmlToParse) {
1985 boolean isXmlValid = true;
1987 XMLReader reader = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
1988 setFeatures(reader);
1989 reader.parse(new InputSource(new ByteArrayInputStream(xmlToParse)));
1991 catch (ParserConfigurationException | IOException | SAXException e) {
1992 log.debug("Xml is invalid : {}", e.getMessage(), e);
1998 private void setFeatures(XMLReader reader) throws SAXNotSupportedException {
2000 reader.setFeature("http://apache.org/xml/features/validation/schema", false);
2001 reader.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
2003 catch (SAXNotRecognizedException e) {
2004 log.debug("Xml parser couldn't set feature: \"http://apache.org/xml/features/validation/schema\", false", e.getMessage(), e);
2008 private void validateSingleDeploymentArtifactName(String artifactName, Component parentComponent, NodeTypeEnum parentType) {
2009 boolean artifactNameFound = false;
2010 Iterator<ArtifactDefinition> parentDeploymentArtifactsItr = getDeploymentArtifacts(parentComponent, parentType, null)
2013 while (!artifactNameFound && parentDeploymentArtifactsItr.hasNext()) {
2014 artifactNameFound = artifactName.equalsIgnoreCase(parentDeploymentArtifactsItr.next().getArtifactName());
2016 if (artifactNameFound) {
2017 log.debug("Can't upload artifact: {}, because another artifact with this name already exist.", artifactName);
2018 throw new ByActionStatusComponentException(ActionStatus.DEPLOYMENT_ARTIFACT_NAME_ALREADY_EXISTS, parentType.name(),
2019 parentComponent.getName(), artifactName);
2023 private void validateHeatExist(String componentId, String parentRiId, Wrapper<ArtifactDefinition> heatArtifactMDWrapper, ArtifactDefinition heatEnvArtifact, NodeTypeEnum parentType,
2024 ComponentTypeEnum componentType) {
2025 Either<ArtifactDefinition, StorageOperationStatus> res = artifactToscaOperation.getHeatArtifactByHeatEnvId(parentRiId, heatEnvArtifact, parentType, componentId, componentType);
2026 if (res.isRight()) {
2027 throw new ByActionStatusComponentException(ActionStatus.MISSING_HEAT);
2029 heatArtifactMDWrapper.setInnerElement(res.left().value());
2034 void validateHeatTimeoutValue(boolean isCreate, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2035 log.trace("Started HEAT pre-payload validation for artifact {}", artifactInfo.getArtifactLabel());
2036 // timeout > 0 for HEAT artifacts
2037 Integer timeout = artifactInfo.getTimeout();
2038 if (timeout == null) {
2039 Integer defaultTimeout = isCreate ? NodeTemplateOperation.getDefaultHeatTimeout() : currentArtifact.getTimeout();
2040 artifactInfo.setTimeout(defaultTimeout);
2041 // HEAT artifact but timeout is invalid
2043 else if (timeout < 1) {
2044 throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_INVALID_TIMEOUT);
2046 // US649856 - Allow several HEAT files on Resource
2047 log.trace("Ended HEAT validation for artifact {}", artifactInfo.getArtifactLabel());
2051 void validateResourceType(ResourceTypeEnum resourceType, ArtifactDefinition artifactInfo, List<String> typeList) {
2052 if (typeList == null || !typeList.contains(resourceType.name())) {
2053 String listToString = (typeList != null) ? typeList.toString() : "";
2054 throw new ByActionStatusComponentException(MISMATCH_BETWEEN_ARTIFACT_TYPE_AND_COMPONENT_TYPE, artifactInfo.getArtifactName(),
2055 listToString, resourceType.getValue());
2060 Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParameters(ArtifactDefinition artifactInfo, String artifactType) {
2061 if (artifactInfo.getHeatParameters() != null) {
2062 for (HeatParameterDefinition heatParam : artifactInfo.getListHeatParameters()) {
2063 String parameterType = heatParam.getType();
2064 HeatParameterType heatParameterType = HeatParameterType.isValidType(parameterType);
2065 String artifactTypeStr = artifactType != null ? artifactType : ArtifactTypeEnum.HEAT.getType();
2066 if (heatParameterType == null) {
2067 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_HEAT_PARAMETER_TYPE, artifactTypeStr, heatParam
2069 return Either.right(responseFormat);
2072 StorageOperationStatus validateAndUpdateProperty = heatParametersOperation.validateAndUpdateProperty(heatParam);
2073 if (validateAndUpdateProperty != StorageOperationStatus.OK) {
2074 log.debug("Heat parameter {} is invalid. Status is {}", heatParam.getName(), validateAndUpdateProperty);
2075 ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE;
2076 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, artifactTypeStr, heatParam
2077 .getType(), heatParam.getName());
2078 return Either.right(responseFormat);
2082 return Either.left(artifactInfo);
2085 public List<ArtifactDefinition> getDeploymentArtifacts(Component parentComponent, NodeTypeEnum parentType, String ciId) {
2086 List<ArtifactDefinition> deploymentArtifacts = new ArrayList<>();
2087 if (parentComponent.getDeploymentArtifacts() != null) {
2088 if (NodeTypeEnum.ResourceInstance == parentType && ciId != null) {
2089 Either<ComponentInstance, ResponseFormat> getRI = getRIFromComponent(parentComponent, ciId, null, null, null);
2090 if (getRI.isRight()) {
2091 return deploymentArtifacts;
2093 ComponentInstance ri = getRI.left().value();
2094 if (ri.getDeploymentArtifacts() != null) {
2095 deploymentArtifacts.addAll(ri.getDeploymentArtifacts().values());
2098 else if (parentComponent.getDeploymentArtifacts() != null) {
2099 deploymentArtifacts.addAll(parentComponent.getDeploymentArtifacts().values());
2102 return deploymentArtifacts;
2105 private void checkCreateFields(User user, ArtifactDefinition artifactInfo, ArtifactGroupTypeEnum type) {
2106 // on create if null add informational to current
2107 if (artifactInfo.getArtifactGroupType() == null) {
2108 artifactInfo.setArtifactGroupType(type);
2110 if (artifactInfo.getUniqueId() != null) {
2111 log.error("artifact uniqid cannot be set ignoring");
2113 artifactInfo.setUniqueId(null);
2115 if (artifactInfo.getArtifactRef() != null) {
2116 log.error("artifact ref cannot be set ignoring");
2118 artifactInfo.setArtifactRef(null);
2120 if (artifactInfo.getArtifactRepository() != null) {
2121 log.error("artifact repository cannot be set ignoring");
2123 artifactInfo.setArtifactRepository(null);
2125 if (artifactInfo.getUserIdCreator() != null) {
2126 log.error("creator uuid cannot be set ignoring");
2128 artifactInfo.setArtifactCreator(user.getUserId());
2130 if (artifactInfo.getUserIdLastUpdater() != null) {
2131 log.error("userId of last updater cannot be set ignoring");
2133 artifactInfo.setUserIdLastUpdater(user.getUserId());
2135 if (artifactInfo.getCreatorFullName() != null) {
2136 log.error("creator Full name cannot be set ignoring");
2138 String fullName = user.getFirstName() + " " + user.getLastName();
2139 artifactInfo.setUpdaterFullName(fullName);
2141 if (artifactInfo.getUpdaterFullName() != null) {
2142 log.error("updater Full name cannot be set ignoring");
2144 artifactInfo.setUpdaterFullName(fullName);
2146 if (artifactInfo.getCreationDate() != null) {
2147 log.error("Creation Date cannot be set ignoring");
2149 long time = System.currentTimeMillis();
2150 artifactInfo.setCreationDate(time);
2152 if (artifactInfo.getLastUpdateDate() != null) {
2153 log.error("Last Update Date cannot be set ignoring");
2155 artifactInfo.setLastUpdateDate(time);
2157 if (artifactInfo.getEsId() != null) {
2158 log.error("es id cannot be set ignoring");
2160 artifactInfo.setEsId(null);
2165 private String composeArtifactId(String resourceId, String artifactId, ArtifactDefinition artifactInfo, String interfaceName, String operationName) {
2166 String id = artifactId;
2167 if (artifactId == null || artifactId.isEmpty()) {
2168 String uniqueId = null;
2169 if (interfaceName != null && operationName != null) {
2170 uniqueId = UniqueIdBuilder.buildArtifactByInterfaceUniqueId(resourceId, interfaceName, operationName, artifactInfo
2171 .getArtifactLabel());
2174 uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId, artifactInfo.getArtifactLabel());
2176 artifactInfo.setUniqueId(uniqueId);
2177 artifactInfo.setEsId(uniqueId);
2181 artifactInfo.setUniqueId(artifactId);
2182 artifactInfo.setEsId(artifactId);
2187 private Either<ActionStatus, ResponseFormat> validateArtifactType(String userId, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) {
2188 if (artifactInfo.getArtifactType() == null || artifactInfo.getArtifactType().isEmpty()) {
2189 BeEcompErrorManager.getInstance()
2190 .logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel");
2191 log.debug("Missing artifact type for artifact {}", artifactInfo.getArtifactName());
2192 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_TYPE));
2195 boolean artifactTypeExist = false;
2196 Either<List<ArtifactType>, ActionStatus> allArtifactTypes = null;
2197 ArtifactGroupTypeEnum artifactGroupType = artifactInfo.getArtifactGroupType();
2199 if ((artifactGroupType != null) && artifactGroupType == ArtifactGroupTypeEnum.DEPLOYMENT) {
2200 allArtifactTypes = getDeploymentArtifactTypes(parentType);
2204 allArtifactTypes = elementOperation.getAllArtifactTypes();
2206 if (allArtifactTypes.isRight()) {
2207 BeEcompErrorManager.getInstance()
2208 .logBeInvalidConfigurationError("Artifact Upload / Update", "artifactTypes", allArtifactTypes
2212 log.debug("Failed to retrieve list of suported artifact types. error: {}", allArtifactTypes.right()
2214 return Either.right(componentsUtils.getResponseFormatByUserId(allArtifactTypes.right().value(), userId));
2217 for (ArtifactType type : allArtifactTypes.left().value()) {
2218 if (type.getName().equalsIgnoreCase(artifactInfo.getArtifactType())) {
2219 artifactInfo.setArtifactType(artifactInfo.getArtifactType().toUpperCase());
2220 artifactTypeExist = true;
2225 if (!artifactTypeExist) {
2226 BeEcompErrorManager.getInstance()
2227 .logBeInvalidTypeError("Artifact Upload / Delete / Update - Not supported artifact type", artifactInfo
2228 .getArtifactType(), "Artifact " + artifactInfo.getArtifactName());
2229 log.debug("Not supported artifact type = {}", artifactInfo.getArtifactType());
2230 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
2231 .getArtifactType()));
2234 return Either.left(ActionStatus.OK);
2237 private Either<List<ArtifactType>, ActionStatus> getDeploymentArtifactTypes(NodeTypeEnum parentType) {
2239 Map<String, ArtifactTypeConfig> deploymentArtifacts ;
2240 List<ArtifactType> artifactTypes = new ArrayList<>();
2242 if (parentType == NodeTypeEnum.Service) {
2243 deploymentArtifacts = ConfigurationManager.getConfigurationManager()
2245 .getServiceDeploymentArtifacts();
2247 else if (parentType == NodeTypeEnum.ResourceInstance) {
2248 deploymentArtifacts = ConfigurationManager.getConfigurationManager()
2250 .getResourceInstanceDeploymentArtifacts();
2253 deploymentArtifacts = ConfigurationManager.getConfigurationManager()
2255 .getResourceDeploymentArtifacts();
2257 if (deploymentArtifacts != null) {
2258 for (String artifactType : deploymentArtifacts.keySet()) {
2259 ArtifactType artifactT = new ArtifactType();
2260 artifactT.setName(artifactType);
2261 artifactTypes.add(artifactT);
2263 return Either.left(artifactTypes);
2266 return Either.right(ActionStatus.GENERAL_ERROR);
2271 private Either<Boolean, ResponseFormat> validateFirstUpdateHasPayload(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2272 if (currentArtifact.getEsId() == null && (artifactInfo.getPayloadData() == null || artifactInfo.getPayloadData().length == 0)) {
2273 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD));
2275 return Either.left(true);
2280 Either<Boolean, ResponseFormat> validateAndSetArtifactName(ArtifactDefinition artifactInfo) {
2281 if (artifactInfo.getArtifactName() == null || artifactInfo.getArtifactName().isEmpty()) {
2282 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_NAME));
2284 String normalizeFileName = ValidationUtils.normalizeFileName(artifactInfo.getArtifactName());
2285 if (normalizeFileName == null || normalizeFileName.isEmpty()) {
2286 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_NAME));
2288 artifactInfo.setArtifactName(normalizeFileName);
2290 if (!ValidationUtils.validateArtifactNameLength(artifactInfo.getArtifactName())) {
2291 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_NAME, String.valueOf(ValidationUtils.ARTIFACT_NAME_LENGTH)));
2294 return Either.left(true);
2297 private void validateArtifactTypeNotChanged(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2298 if (StringUtils.isEmpty(artifactInfo.getArtifactType())) {
2299 log.info("artifact type is missing operation ignored");
2300 throw new ByActionStatusComponentException(ActionStatus.MISSING_ARTIFACT_TYPE);
2303 if (!currentArtifact.getArtifactType().equalsIgnoreCase(artifactInfo.getArtifactType())) {
2304 log.info("artifact type cannot be changed operation ignored");
2305 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
2309 private Either<ArtifactDefinition, ResponseFormat> validateOrSetArtifactGroupType(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2311 if (Objects.nonNull(artifactInfo) && Objects.nonNull(currentArtifact)) {
2312 if (artifactInfo.getArtifactGroupType() == null) {
2313 artifactInfo.setArtifactGroupType(currentArtifact.getArtifactGroupType());
2314 } else if (!currentArtifact.getArtifactGroupType()
2316 .equalsIgnoreCase(artifactInfo.getArtifactGroupType().getType())) {
2317 log.info("artifact group type cannot be changed. operation failed");
2318 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2321 return Either.left(artifactInfo);
2324 private void checkAndSetUnUpdatableFields(User user, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, ArtifactGroupTypeEnum type) {
2326 // on update if null add informational to current
2327 if (currentArtifact.getArtifactGroupType() == null && type != null) {
2328 currentArtifact.setArtifactGroupType(type);
2331 if (artifactInfo.getUniqueId() != null && !currentArtifact.getUniqueId().equals(artifactInfo.getUniqueId())) {
2332 log.error("artifact uniqid cannot be set ignoring");
2334 artifactInfo.setUniqueId(currentArtifact.getUniqueId());
2336 if (artifactInfo.getArtifactRef() != null && !currentArtifact.getArtifactRef()
2337 .equals(artifactInfo.getArtifactRef())) {
2338 log.error("artifact ref cannot be set ignoring");
2340 artifactInfo.setArtifactRef(currentArtifact.getArtifactRef());
2342 if (artifactInfo.getArtifactRepository() != null && !currentArtifact.getArtifactRepository()
2343 .equals(artifactInfo.getArtifactRepository())) {
2344 log.error("artifact repository cannot be set ignoring");
2346 artifactInfo.setArtifactRepository(currentArtifact.getArtifactRepository());
2348 if (artifactInfo.getUserIdCreator() != null && !currentArtifact.getUserIdCreator()
2349 .equals(artifactInfo.getUserIdCreator())) {
2350 log.error("creator uuid cannot be set ignoring");
2352 artifactInfo.setUserIdCreator(currentArtifact.getUserIdCreator());
2354 if (artifactInfo.getArtifactCreator() != null && !currentArtifact.getArtifactCreator()
2355 .equals(artifactInfo.getArtifactCreator())) {
2356 log.error("artifact creator cannot be set ignoring");
2358 artifactInfo.setArtifactCreator(currentArtifact.getArtifactCreator());
2360 if (artifactInfo.getUserIdLastUpdater() != null && !currentArtifact.getUserIdLastUpdater()
2361 .equals(artifactInfo.getUserIdLastUpdater())) {
2362 log.error("userId of last updater cannot be set ignoring");
2364 artifactInfo.setUserIdLastUpdater(user.getUserId());
2366 if (artifactInfo.getCreatorFullName() != null && !currentArtifact.getCreatorFullName()
2367 .equals(artifactInfo.getCreatorFullName())) {
2368 log.error("creator Full name cannot be set ignoring");
2370 artifactInfo.setCreatorFullName(currentArtifact.getCreatorFullName());
2372 if (artifactInfo.getUpdaterFullName() != null && !currentArtifact.getUpdaterFullName()
2373 .equals(artifactInfo.getUpdaterFullName())) {
2374 log.error("updater Full name cannot be set ignoring");
2376 String fullName = user.getFirstName() + " " + user.getLastName();
2377 artifactInfo.setUpdaterFullName(fullName);
2379 if (artifactInfo.getCreationDate() != null && !currentArtifact.getCreationDate()
2380 .equals(artifactInfo.getCreationDate())) {
2381 log.error("Creation Date cannot be set ignoring");
2383 artifactInfo.setCreationDate(currentArtifact.getCreationDate());
2385 if (artifactInfo.getLastUpdateDate() != null && !currentArtifact.getLastUpdateDate()
2386 .equals(artifactInfo.getLastUpdateDate())) {
2387 log.error("Last Update Date cannot be set ignoring");
2389 long time = System.currentTimeMillis();
2390 artifactInfo.setLastUpdateDate(time);
2392 if (artifactInfo.getEsId() != null && !currentArtifact.getEsId().equals(artifactInfo.getEsId())) {
2393 log.error("es id cannot be set ignoring");
2395 artifactInfo.setEsId(currentArtifact.getUniqueId());
2397 if (artifactInfo.getArtifactDisplayName() != null && !currentArtifact.getArtifactDisplayName()
2398 .equals(artifactInfo.getArtifactDisplayName())) {
2399 log.error(" Artifact Display Name cannot be set ignoring");
2401 artifactInfo.setArtifactDisplayName(currentArtifact.getArtifactDisplayName());
2403 if (artifactInfo.getServiceApi() != null && !currentArtifact.getServiceApi()
2404 .equals(artifactInfo.getServiceApi())) {
2405 log.debug("serviceApi cannot be set. ignoring.");
2407 artifactInfo.setServiceApi(currentArtifact.getServiceApi());
2409 if (artifactInfo.getArtifactGroupType() != null && currentArtifact.getArtifactGroupType() != artifactInfo.getArtifactGroupType()) {
2410 log.debug("artifact group cannot be set. ignoring.");
2412 artifactInfo.setArtifactGroupType(currentArtifact.getArtifactGroupType());
2414 artifactInfo.setArtifactVersion(currentArtifact.getArtifactVersion());
2416 if (artifactInfo.getArtifactUUID() != null && !artifactInfo.getArtifactUUID()
2417 .isEmpty() && !currentArtifact.getArtifactUUID()
2418 .equals(artifactInfo.getArtifactUUID())) {
2419 log.debug("artifact UUID cannot be set. ignoring.");
2421 artifactInfo.setArtifactUUID(currentArtifact.getArtifactUUID());
2423 if ((artifactInfo.getHeatParameters() != null) && (currentArtifact.getHeatParameters() != null) && !artifactInfo
2424 .getHeatParameters()
2425 .isEmpty() && !currentArtifact.getHeatParameters().isEmpty()) {
2426 checkAndSetUnupdatableHeatParams(artifactInfo.getListHeatParameters(), currentArtifact.getListHeatParameters());
2430 private void checkAndSetUnupdatableHeatParams(List<HeatParameterDefinition> heatParameters, List<HeatParameterDefinition> currentParameters) {
2432 Map<String, HeatParameterDefinition> currentParametersMap = getMapOfParameters(currentParameters);
2433 for (HeatParameterDefinition parameter : heatParameters) {
2434 HeatParameterDefinition currentParam = currentParametersMap.get(parameter.getUniqueId());
2436 if (currentParam != null) {
2438 if (parameter.getName() != null && !parameter.getName().equalsIgnoreCase(currentParam.getName())) {
2439 log.debug("heat parameter name cannot be updated ({}). ignoring.", parameter.getName());
2440 parameter.setName(currentParam.getName());
2442 if (parameter.getDefaultValue() != null && !parameter.getDefaultValue()
2443 .equalsIgnoreCase(currentParam.getDefaultValue())) {
2444 log.debug("heat parameter defaultValue cannot be updated ({}). ignoring.", parameter.getDefaultValue());
2445 parameter.setDefaultValue(currentParam.getDefaultValue());
2447 if (parameter.getType() != null && !parameter.getType().equalsIgnoreCase(currentParam.getType())) {
2448 log.debug("heat parameter type cannot be updated ({}). ignoring.", parameter.getType());
2449 parameter.setType(currentParam.getType());
2451 if (parameter.getDescription() != null && !parameter.getDescription()
2452 .equalsIgnoreCase(currentParam.getDescription())) {
2453 log.debug("heat parameter description cannot be updated ({}). ignoring.", parameter.getDescription());
2454 parameter.setDescription(currentParam.getDescription());
2457 // check and set current value
2458 if ((parameter.getCurrentValue() == null) && (currentParam.getDefaultValue() != null)) {
2459 log.debug("heat parameter current value is null. set it to default value {}). ignoring.", parameter.getDefaultValue());
2460 parameter.setCurrentValue(currentParam.getDefaultValue());
2466 private Map<String, HeatParameterDefinition> getMapOfParameters(List<HeatParameterDefinition> currentParameters) {
2468 Map<String, HeatParameterDefinition> currentParamsMap = new HashMap<>();
2469 for (HeatParameterDefinition param : currentParameters) {
2470 currentParamsMap.put(param.getUniqueId(), param);
2472 return currentParamsMap;
2475 private Either<Boolean, ResponseFormat> validateAndServiceApiUrl(ArtifactDefinition artifactInfo) {
2476 if (!ValidationUtils.validateStringNotEmpty(artifactInfo.getApiUrl())) {
2477 log.debug("Artifact url cannot be empty.");
2478 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_URL));
2480 artifactInfo.setApiUrl(artifactInfo.getApiUrl().toLowerCase());
2482 if (!ValidationUtils.validateUrl(artifactInfo.getApiUrl())) {
2483 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_SERVICE_API_URL));
2485 if (!ValidationUtils.validateUrlLength(artifactInfo.getApiUrl())) {
2486 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_URL, String.valueOf(ValidationUtils.API_URL_LENGTH)));
2489 return Either.left(true);
2492 private Either<Boolean, ResponseFormat> validateAndCleanDescription(ArtifactDefinition artifactInfo) {
2493 if (artifactInfo.getDescription() == null || artifactInfo.getDescription().isEmpty()) {
2494 log.debug("Artifact description cannot be empty.");
2495 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_DESCRIPTION));
2497 String description = artifactInfo.getDescription();
2498 description = ValidationUtils.removeNoneUtf8Chars(description);
2499 description = ValidationUtils.normaliseWhitespace(description);
2500 description = ValidationUtils.stripOctets(description);
2501 description = ValidationUtils.removeHtmlTagsOnly(description);
2502 if (!ValidationUtils.validateIsEnglish(description)) {
2503 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2505 if (!ValidationUtils.validateLength(description, ValidationUtils.ARTIFACT_DESCRIPTION_MAX_LENGTH)) {
2506 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_DESCRIPTION, String
2507 .valueOf(ValidationUtils.ARTIFACT_DESCRIPTION_MAX_LENGTH)));
2509 artifactInfo.setDescription(description);
2510 return Either.left(true);
2513 private Either<ArtifactDefinition, Operation> updateArtifactFlow(Component parent, String parentId, String artifactId, ArtifactDefinition artifactInfo, byte[] decodedPayload,
2514 ComponentTypeEnum componentType, AuditingActionEnum auditingAction, String interfaceType, String operationName) {
2515 DAOArtifactData artifactData = createEsArtifactData(artifactInfo, decodedPayload);
2516 if (artifactData == null) {
2517 BeEcompErrorManager.getInstance().logBeDaoSystemError(UPDATE_ARTIFACT);
2518 log.debug("Failed to create artifact object for ES.");
2519 throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
2521 String prevArtifactId;
2522 String currArtifactId = artifactId;
2523 ArtifactDefinition artifactDefinition = artifactInfo;
2524 log.debug("Entry on graph is updated. Update artifact in ES");
2525 // Changing previous and current artifactId for auditing
2526 prevArtifactId = currArtifactId;
2527 currArtifactId = artifactDefinition.getUniqueId();
2529 NodeTypeEnum parentType = convertParentType(componentType);
2531 if (decodedPayload == null) {
2532 if (!artifactDefinition.getMandatory() || artifactDefinition.getEsId() != null) {
2533 Either<DAOArtifactData, CassandraOperationStatus> artifactFromCassandra = artifactCassandraDao.getArtifact(artifactDefinition.getEsId());
2534 if (artifactFromCassandra.isRight()) {
2535 throw new StorageException(artifactFromCassandra.right().value());
2537 // clone data to new artifact
2538 artifactData.setData(artifactFromCassandra.left().value().getData());
2539 artifactData.setId(artifactFromCassandra.left().value().getId());
2541 } else if (artifactDefinition.getEsId() == null) {
2542 artifactDefinition.setEsId(artifactDefinition.getUniqueId());
2543 artifactData.setId(artifactDefinition.getUniqueId());
2546 Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.updateArtifactOnResource(artifactInfo,
2547 parent, artifactId, parentType, parentId, true);
2548 if (result.isRight()) {
2549 throw new StorageException(result.right().value());
2551 artifactDefinition = result.left().value();
2552 updateGeneratedIdInHeatEnv(parent, parentId, artifactId, artifactInfo, artifactDefinition, parentType);
2554 StorageOperationStatus storageOperationStatus = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentType);
2555 if (storageOperationStatus != StorageOperationStatus.OK) {
2556 throw new StorageException(storageOperationStatus);
2558 if (artifactData.getData() != null) {
2559 if (!artifactDefinition.getDuplicated() || artifactData.getId() == null) {
2560 artifactData.setId(artifactDefinition.getEsId());
2562 saveArtifactInCassandra(artifactData, parent, artifactInfo, currArtifactId, prevArtifactId, auditingAction, componentType);
2564 return Either.left(artifactDefinition);
2567 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateArtifactsFlowForInterfaceOperations(
2568 Component parent, String parentId, String artifactId, ArtifactDefinition artifactInfo, User user,
2569 byte[] decodedPayload, ComponentTypeEnum componentType, AuditingActionEnum auditingAction, String interfaceType,
2570 String operationUuid, DAOArtifactData artifactData, String prevArtifactId, String currArtifactId,
2571 ArtifactDefinition artifactDefinition) {
2572 StorageOperationStatus error;
2573 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp;
2574 if (decodedPayload == null) {
2575 if (!artifactDefinition.getMandatory() || artifactDefinition.getEsId() != null) {
2576 Either<DAOArtifactData, CassandraOperationStatus> artifactFromCassandra = artifactCassandraDao.getArtifact(artifactDefinition
2578 if (artifactFromCassandra.isRight()) {
2579 log.debug("Failed to get artifact data from ES for artifact id {}", artifactId);
2580 error = DaoStatusConverter.convertCassandraStatusToStorageStatus(artifactFromCassandra.right()
2582 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
2583 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
2584 resultOp = Either.right(responseFormat);
2587 // clone data to new artifact
2588 artifactData.setData(artifactFromCassandra.left().value().getData());
2589 artifactData.setId(artifactFromCassandra.left().value().getId());
2591 // todo if not exist(first time)
2595 if (artifactDefinition.getEsId() == null) {
2596 artifactDefinition.setEsId(artifactDefinition.getUniqueId());
2597 artifactData.setId(artifactDefinition.getUniqueId());
2600 NodeTypeEnum convertParentType = convertParentType(componentType);
2601 // Set additional fields for artifact
2602 artifactInfo.setArtifactLabel(artifactInfo.getArtifactName());
2603 artifactInfo.setArtifactDisplayName(artifactInfo.getArtifactName());
2605 Either<ArtifactDefinition, StorageOperationStatus> updateArtifactOnResourceEither =
2606 artifactToscaOperation.updateArtifactOnResource(artifactInfo, parent, artifactId, convertParentType, parentId, true);
2607 if(updateArtifactOnResourceEither.isRight()){
2608 log.debug("Failed to persist operation artifact {} in resource, error is {}",artifactInfo.getArtifactName(), updateArtifactOnResourceEither.right().value());
2609 ActionStatus convertedFromStorageResponse = componentsUtils.convertFromStorageResponse(updateArtifactOnResourceEither.right().value());
2610 return Either.right(componentsUtils.getResponseFormat(convertedFromStorageResponse));
2612 if (artifactData.getData() != null) {
2613 CassandraOperationStatus cassandraOperationStatus = artifactCassandraDao.saveArtifact(artifactData);
2614 if(cassandraOperationStatus != CassandraOperationStatus.OK){
2615 log.debug("Failed to persist operation artifact {}, error is {}",artifactInfo.getArtifactName(),cassandraOperationStatus);
2616 StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(cassandraOperationStatus);
2617 ActionStatus convertedFromStorageResponse = componentsUtils.convertFromStorageResponse(storageStatus);
2618 return Either.right(componentsUtils.getResponseFormat(convertedFromStorageResponse));
2622 Either<ArtifactDefinition, ResponseFormat> updateOprEither = updateOperationArtifact(parentId, interfaceType, operationUuid, updateArtifactOnResourceEither.left().value());
2623 if(updateOprEither.isRight()){
2624 return Either.right(updateOprEither.right().value());
2627 return Either.left(Either.left(updateOprEither.left().value()));
2630 private String updateGeneratedIdInHeatEnv(Component parent, String parentId, String artifactId, ArtifactDefinition artifactInfo, ArtifactDefinition artifactDefinition, NodeTypeEnum parentType) {
2631 if (NodeTypeEnum.Resource == parentType) {
2632 return updateGeneratedIdInHeatEnv(parent.getDeploymentArtifacts(), parent, parentId, artifactId, artifactInfo, artifactDefinition, parentType, false);
2634 return artifactDefinition.getUniqueId();
2637 private String updateGeneratedIdInHeatEnv(Map<String, ArtifactDefinition> deploymentArtifacts, Component parentComponent, String parentId, String artifactId, ArtifactDefinition artifactInfo, ArtifactDefinition artifactDefinition, NodeTypeEnum parentType, boolean isInstanceArtifact) {
2638 String artifactUniqueId;
2639 artifactUniqueId = artifactDefinition.getUniqueId();
2640 String artifactType = artifactInfo.getArtifactType();
2641 if ((ArtifactTypeEnum.HEAT.getType().equalsIgnoreCase(artifactType) ||
2642 ArtifactTypeEnum.HEAT_VOL.getType().equalsIgnoreCase(artifactType) ||
2643 ArtifactTypeEnum.HEAT_NET.getType().equalsIgnoreCase(artifactType))
2644 && !artifactUniqueId.equals(artifactId)) {
2645 // need to update the generated id in heat env
2646 Optional<Entry<String, ArtifactDefinition>> findFirst = deploymentArtifacts.entrySet()
2648 .filter(a -> artifactId.equals(a.getValue().getGeneratedFromId()))
2650 if (findFirst.isPresent()) {
2651 ArtifactDefinition artifactEnvInfo = findFirst.get().getValue();
2652 artifactEnvInfo.setIsFromCsar(artifactDefinition.getIsFromCsar());
2653 artifactEnvInfo.setArtifactChecksum(null);
2654 if (isInstanceArtifact) {
2655 artifactToscaOperation.updateHeatEnvArtifactOnInstance(parentComponent, artifactEnvInfo, artifactId, artifactUniqueId, parentType, parentId);
2657 artifactToscaOperation.updateHeatEnvArtifact(parentComponent, artifactEnvInfo, artifactId, artifactUniqueId, parentType, parentId);
2661 return artifactUniqueId;
2664 private String updateGeneratedIdInHeatEnvOnInstance(ComponentInstance parent, Component parentComponent, String artifactId, ArtifactDefinition artifactInfo, ArtifactDefinition artifactDefinition, NodeTypeEnum parentType) {
2665 return updateGeneratedIdInHeatEnv(parent.getDeploymentArtifacts(), parentComponent, parent.getUniqueId(),artifactId, artifactInfo, artifactDefinition, parentType, true);
2669 private Either<byte[], ResponseFormat> handlePayload(ArtifactDefinition artifactInfo, boolean isArtifactMetadataUpdate) {
2670 log.trace("Starting payload handling");
2671 byte[] payload = artifactInfo.getPayloadData();
2672 byte[] decodedPayload = null;
2674 if (payload != null && payload.length != 0) {
2675 // the generated artifacts were already decoded by the handler
2676 decodedPayload = artifactInfo.getGenerated() ? payload : Base64.decodeBase64(payload);
2677 if (decodedPayload.length == 0) {
2678 log.debug("Failed to decode the payload.");
2679 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
2680 return Either.right(responseFormat);
2683 String checkSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(decodedPayload);
2684 artifactInfo.setArtifactChecksum(checkSum);
2685 log.trace("Calculated checksum, base64 payload: {}, checksum: {}", payload, checkSum);
2687 // Specific payload validations of different types
2688 Either<Boolean, ResponseFormat> result = Either.left(true);
2689 if (isDeploymentArtifact(artifactInfo)) {
2690 log.trace("Starting deployment artifacts payload validation");
2691 String artifactType = artifactInfo.getArtifactType();
2692 String fileExtension = GeneralUtility.getFilenameExtension(artifactInfo.getArtifactName());
2693 PayloadTypeEnum payloadType = ArtifactTypeToPayloadTypeSelector.getPayloadType(artifactType, fileExtension);
2694 Either<Boolean, ActionStatus> isPayloadValid = payloadType.isValid(decodedPayload);
2695 if (isPayloadValid.isRight()) {
2696 ResponseFormat responseFormat = componentsUtils.getResponseFormat(isPayloadValid.right().value(), artifactType);
2697 return Either.right(responseFormat);
2700 if (payloadType.isHeatRelated()) {
2701 log.trace("Payload is heat related so going to extract heat parameters for artifact type {}", artifactType);
2702 result = extractHeatParameters(artifactInfo);
2705 if (result.isRight()) {
2706 return Either.right(result.right().value());
2709 } // null/empty payload is normal if called from metadata update ONLY.
2710 // The validation of whether this is metadata/payload update case is
2711 // currently done separately
2713 if (!isArtifactMetadataUpdate) {
2714 log.debug("In artifact: {} Payload is missing.",artifactInfo.getArtifactName());
2715 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
2716 return Either.right(responseFormat);
2719 log.trace("Ended payload handling");
2720 return Either.left(decodedPayload);
2724 public Either<Operation, ResponseFormat> deleteArtifactByInterface(String resourceId, String userUserId, String artifactId,
2725 boolean inTransaction) {
2726 User user = new User();
2727 user.setUserId(userUserId);
2728 Either<Resource, StorageOperationStatus> parent = toscaOperationFacade.getToscaElement(resourceId, JsonParseFlagEnum.ParseMetadata);
2729 if (parent.isRight()) {
2730 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(parent
2733 return Either.right(responseFormat);
2735 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = handleDelete(resourceId, artifactId, user, AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, parent
2738 false, inTransaction);
2739 if (handleDelete.isRight()) {
2740 return Either.right(handleDelete.right().value());
2742 Either<ArtifactDefinition, Operation> result = handleDelete.left().value();
2743 return Either.left(result.right().value());
2747 private Operation convertToOperation(ArtifactDefinition artifactInfo, String operationName) {
2748 Operation op = new Operation();
2749 long time = System.currentTimeMillis();
2750 op.setCreationDate(time);
2752 String artifactName = artifactInfo.getArtifactName();
2753 artifactInfo.setArtifactName(createInterfaceArtifactNameFromOperation(operationName, artifactName));
2755 op.setImplementation(artifactInfo);
2756 op.setLastUpdateDate(time);
2760 private String createInterfaceArtifactNameFromOperation(String operationName, String artifactName) {
2761 String newArtifactName = operationName + "_" + artifactName;
2762 log.trace("converting artifact name {} to {}", artifactName, newArtifactName);
2763 return newArtifactName;
2767 public byte[] downloadRsrcArtifactByNames(String serviceName, String serviceVersion, String resourceName, String resourceVersion, String artifactName) {
2769 // General validation
2770 if (serviceName == null || serviceVersion == null || resourceName == null || resourceVersion == null || artifactName == null) {
2771 log.debug(NULL_PARAMETER);
2772 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
2775 // Normalizing artifact name
2776 artifactName = ValidationUtils.normalizeFileName(artifactName);
2778 // Resource validation
2779 Resource resource = validateResourceNameAndVersion(resourceName, resourceVersion);
2780 String resourceId = resource.getUniqueId();
2782 // Service validation
2783 Service validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
2785 Map<String, ArtifactDefinition> artifacts = resource.getDeploymentArtifacts();
2786 if (artifacts == null || artifacts.isEmpty()) {
2787 log.debug("Deployment artifacts of resource {} are not found", resourceId);
2788 throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_NOT_FOUND, artifactName);
2791 ArtifactDefinition deploymentArtifact = null;
2793 for (ArtifactDefinition artifactDefinition : artifacts.values()) {
2794 if (artifactDefinition.getArtifactName() != null && artifactDefinition.getArtifactName()
2795 .equals(artifactName)) {
2796 log.debug(FOUND_DEPLOYMENT_ARTIFACT, artifactName);
2797 deploymentArtifact = artifactDefinition;
2802 if (deploymentArtifact == null) {
2803 log.debug("No deployment artifact {} was found for resource {}", artifactName, resourceId);
2804 throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_NOT_FOUND, artifactName);
2807 // Downloading the artifact
2808 ImmutablePair<String, byte[]> downloadArtifactEither = downloadArtifact(deploymentArtifact);
2809 log.trace("Download of resource artifact succeeded, uniqueId {}", deploymentArtifact.getUniqueId());
2810 return downloadArtifactEither.getRight();
2814 public byte[] downloadRsrcInstArtifactByNames(String serviceName, String serviceVersion, String resourceInstanceName, String artifactName) {
2816 // General validation
2817 if (serviceName == null || serviceVersion == null || resourceInstanceName == null || artifactName == null) {
2818 log.debug(NULL_PARAMETER);
2819 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
2822 // Normalizing artifact name
2823 artifactName = ValidationUtils.normalizeFileName(artifactName);
2825 // Service validation
2826 Service service = validateServiceNameAndVersion(serviceName, serviceVersion);
2828 // ResourceInstance validation
2829 ComponentInstance resourceInstance = validateResourceInstance(service, resourceInstanceName);
2831 Map<String, ArtifactDefinition> artifacts = resourceInstance.getDeploymentArtifacts();
2833 final String finalArtifactName = artifactName;
2834 Predicate<ArtifactDefinition> filterArtifactByName = p -> p.getArtifactName().equals(finalArtifactName);
2836 ArtifactDefinition deployableArtifact = artifacts==null ? null :
2837 artifacts.values().stream()
2838 .filter(filterArtifactByName)
2842 if (deployableArtifact == null) {
2843 log.debug("Deployment artifact with name {} not found", artifactName);
2844 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
2847 log.debug(FOUND_DEPLOYMENT_ARTIFACT, artifactName);
2848 ImmutablePair<String, byte[]> downloadArtifactEither = downloadArtifact(deployableArtifact);
2850 log.trace("Download of resource artifact succeeded, uniqueId {}", deployableArtifact.getUniqueId());
2851 return downloadArtifactEither.getRight();
2854 private ComponentInstance validateResourceInstance(Service service, String resourceInstanceName) {
2856 List<ComponentInstance> riList = service.getComponentInstances();
2857 for (ComponentInstance ri : riList) {
2858 if (ri.getNormalizedName().equals(resourceInstanceName)) {
2862 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND, resourceInstanceName);
2865 private ComponentInstance validateResourceInstanceById(Component component, String resourceInstanceId) {
2867 List<ComponentInstance> riList = component.getComponentInstances();
2868 for (ComponentInstance ri : riList) {
2869 if (ri.getUniqueId().equals(resourceInstanceId)) {
2873 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_NOT_FOUND, resourceInstanceId);
2876 private Service validateServiceNameAndVersion(String serviceName, String serviceVersion) {
2878 Either<List<Service>, StorageOperationStatus> serviceListBySystemName = toscaOperationFacade.getBySystemName(ComponentTypeEnum.SERVICE, serviceName);
2879 if (serviceListBySystemName.isRight()) {
2880 log.debug("Couldn't fetch any service with name {}", serviceName);
2881 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(serviceListBySystemName
2883 .value(), ComponentTypeEnum.SERVICE), serviceName);
2885 List<Service> serviceList = serviceListBySystemName.left().value();
2886 if (serviceList == null || serviceList.isEmpty()) {
2887 log.debug("Couldn't fetch any service with name {}", serviceName);
2888 throw new ByActionStatusComponentException(ActionStatus.SERVICE_NOT_FOUND, serviceName);
2891 Service foundService = null;
2892 for (Service service : serviceList) {
2893 if (service.getVersion().equals(serviceVersion)) {
2894 log.trace("Found service with version {}", serviceVersion);
2895 foundService = service;
2900 if (foundService == null) {
2901 log.debug("Couldn't find version {} for service {}", serviceVersion, serviceName);
2902 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_VERSION_NOT_FOUND, ComponentTypeEnum.SERVICE
2903 .getValue(), serviceVersion);
2905 return foundService;
2908 private Resource validateResourceNameAndVersion(String resourceName, String resourceVersion) {
2910 Either<Resource, StorageOperationStatus> resourceListBySystemName = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, resourceVersion, JsonParseFlagEnum.ParseMetadata);
2911 if (resourceListBySystemName.isRight()) {
2912 log.debug("Couldn't fetch any resource with name {} and version {}. ", resourceName, resourceVersion);
2913 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(resourceListBySystemName
2915 .value()), resourceName);
2917 return resourceListBySystemName.left().value();
2920 /*private Either<Resource, ResponseFormat> validateResourceNameAndVersion(String resourceName, String resourceVersion) {
2922 Either<Resource, StorageOperationStatus> resourceListBySystemName = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, resourceVersion, JsonParseFlagEnum.ParseMetadata);
2923 if (resourceListBySystemName.isRight()) {
2924 log.debug("Couldn't fetch any resource with name {} and version {}. ", resourceName, resourceVersion);
2925 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceListBySystemName
2927 .value()), resourceName));
2929 return Either.left(resourceListBySystemName.left().value());
2932 public byte[] downloadServiceArtifactByNames(String serviceName, String serviceVersion, String artifactName) {
2934 log.trace("Starting download of service interface artifact, serviceName {}, serviceVersion {}, artifact name {}", serviceName, serviceVersion, artifactName);
2935 if (serviceName == null || serviceVersion == null || artifactName == null) {
2936 log.debug(NULL_PARAMETER);
2937 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
2940 // Normalizing artifact name
2941 final String normalizedArtifactName = ValidationUtils.normalizeFileName(artifactName);
2943 // Service validation
2944 Service service = validateServiceNameAndVersion(serviceName, serviceVersion);
2945 // Looking for deployment or tosca artifacts
2946 String serviceId = service.getUniqueId();
2948 if (MapUtils.isEmpty(service.getDeploymentArtifacts()) && MapUtils.isEmpty(service.getToscaArtifacts())) {
2949 log.debug("Neither Deployment nor Tosca artifacts of service {} are found", serviceId);
2950 throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_NOT_FOUND, normalizedArtifactName);
2953 Optional<ArtifactDefinition> foundArtifactOptl = Optional.empty();
2955 if (!MapUtils.isEmpty(service.getDeploymentArtifacts())) {
2956 foundArtifactOptl = service.getDeploymentArtifacts().values().stream()
2957 // filters artifact by name
2958 .filter(a -> a.getArtifactName().equals(normalizedArtifactName)).findAny();
2960 if ((!foundArtifactOptl.isPresent()) && !MapUtils.isEmpty(service.getToscaArtifacts())) {
2961 foundArtifactOptl = service.getToscaArtifacts().values().stream()
2962 // filters TOSCA artifact by name
2963 .filter(a -> a.getArtifactName().equals(normalizedArtifactName)).findAny();
2965 if (!foundArtifactOptl.isPresent()) {
2966 log.debug("The artifact {} was not found for service {}", normalizedArtifactName, serviceId);
2967 throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_NOT_FOUND, normalizedArtifactName);
2969 log.debug(FOUND_DEPLOYMENT_ARTIFACT, normalizedArtifactName);
2970 // Downloading the artifact
2971 ImmutablePair<String, byte[]> downloadArtifactEither = downloadArtifact(foundArtifactOptl
2973 log.trace("Download of service artifact succeeded, uniqueId {}", foundArtifactOptl.get().getUniqueId());
2974 return downloadArtifactEither.getRight();
2977 public ImmutablePair<String, byte[]> downloadArtifact(String parentId, String artifactUniqueId) {
2978 log.trace("Starting download of artifact, uniqueId {}", artifactUniqueId);
2979 Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(parentId, artifactUniqueId);
2980 if (artifactById.isRight()) {
2981 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(artifactById.right().value());
2982 log.debug("Error when getting artifact info by id{}, error: {}", artifactUniqueId, actionStatus);
2983 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormatByArtifactId(actionStatus, ""));
2985 ArtifactDefinition artifactDefinition = artifactById.left().value();
2986 if (artifactDefinition == null) {
2987 log.debug("Empty artifact definition returned from DB by artifact id {}", artifactUniqueId);
2988 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ""));
2991 return downloadArtifact(artifactDefinition);
2994 private boolean checkArtifactInComponent(Component component, String artifactId) {
2995 boolean found = false;
2996 Map<String, ArtifactDefinition> artifactsS = component.getArtifacts();
2997 if (artifactsS != null) {
2998 for (Map.Entry<String, ArtifactDefinition> entry : artifactsS.entrySet()) {
2999 if (entry.getValue().getUniqueId().equals(artifactId)) {
3005 Map<String, ArtifactDefinition> deploymentArtifactsS = component.getDeploymentArtifacts();
3006 if (!found && deploymentArtifactsS != null) {
3007 for (Map.Entry<String, ArtifactDefinition> entry : deploymentArtifactsS.entrySet()) {
3008 if (entry.getValue().getUniqueId().equals(artifactId)) {
3014 Map<String, ArtifactDefinition> toscaArtifactsS = component.getToscaArtifacts();
3015 if (!found && toscaArtifactsS != null) {
3016 for (Map.Entry<String, ArtifactDefinition> entry : toscaArtifactsS.entrySet()) {
3017 if (entry.getValue().getUniqueId().equals(artifactId)) {
3024 Map<String, InterfaceDefinition> interfaces = component.getInterfaces();
3025 if (!found && interfaces != null) {
3026 for (Map.Entry<String, InterfaceDefinition> entry : interfaces.entrySet()) {
3027 Map<String, Operation> operations = entry.getValue().getOperationsMap();
3028 for (Map.Entry<String, Operation> entryOp : operations.entrySet()) {
3029 if (entryOp.getValue().getImplementation() != null && entryOp.getValue()
3030 .getImplementation()
3032 .equals(artifactId)) {
3039 switch (component.getComponentType()) {
3043 Map<String, ArtifactDefinition> apiArtifacts = ((Service) component).getServiceApiArtifacts();
3044 if (!found && apiArtifacts != null) {
3045 for (Map.Entry<String, ArtifactDefinition> entry : apiArtifacts.entrySet()) {
3046 if (entry.getValue().getUniqueId().equals(artifactId)) {
3060 private boolean checkArtifactInResourceInstance(Component component, String resourceInstanceId, String artifactId) {
3062 boolean found = false;
3063 List<ComponentInstance> resourceInstances = component.getComponentInstances();
3064 ComponentInstance resourceInstance = null;
3065 for (ComponentInstance ri : resourceInstances) {
3066 if (ri.getUniqueId().equals(resourceInstanceId)) {
3067 resourceInstance = ri;
3071 if (resourceInstance != null) {
3072 Map<String, ArtifactDefinition> artifacts = resourceInstance.getDeploymentArtifacts();
3073 if (artifacts != null) {
3074 for (Map.Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) {
3075 if (entry.getValue().getUniqueId().equals(artifactId)) {
3082 artifacts = resourceInstance.getArtifacts();
3083 if (artifacts != null) {
3084 for (Map.Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) {
3085 if (entry.getValue().getUniqueId().equals(artifactId)) {
3096 private Component validateComponentExists(String componentId, AuditingActionEnum auditingAction, User user, String artifactId, ComponentTypeEnum componentType,
3097 String containerComponentType) {
3099 ComponentTypeEnum componentForAudit = null == containerComponentType ? componentType : ComponentTypeEnum.findByParamName(containerComponentType);
3100 componentForAudit.getNodeType();
3102 Either<? extends Component, StorageOperationStatus> componentResult = toscaOperationFacade
3103 .getToscaFullElement(componentId);
3105 if (componentResult.isRight()) {
3106 ActionStatus status = componentForAudit == ComponentTypeEnum.RESOURCE ? ActionStatus.RESOURCE_NOT_FOUND : componentForAudit == ComponentTypeEnum.SERVICE ? ActionStatus.SERVICE_NOT_FOUND : ActionStatus.PRODUCT_NOT_FOUND;
3107 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, componentId);
3108 log.debug("Service not found, serviceId {}", componentId);
3109 handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentForAudit, null);
3110 throw new ByActionStatusComponentException(status, componentId);
3112 return componentResult.left().value();
3115 private Boolean validateWorkOnComponent(Component component, String userId, AuditingActionEnum auditingAction, User user, String artifactId, ArtifactOperationInfo operation) {
3116 if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.DOWNLOAD && !operation.ignoreLifecycleState()) {
3118 validateCanWorkOnComponent(component, userId);
3119 }catch (ComponentException e) {
3120 String uniqueId = component.getUniqueId();
3121 log.debug("Service status isn't CHECKOUT or user isn't owner, serviceId {}", uniqueId);
3122 handleAuditing(auditingAction, component, uniqueId, user, null, null, artifactId, e.getResponseFormat(),
3123 component.getComponentType(), null);
3130 private void validateUserRole(User user, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType, ArtifactOperationInfo operation) {
3132 if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.DOWNLOAD) {
3133 String role = user.getRole();
3134 if (!role.equals(Role.ADMIN.name()) && !role.equals(Role.DESIGNER.name())) {
3135 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
3136 log.debug("addArtifact - user isn't permitted to perform operation, userId {}, role {}", user.getUserId(), role);
3137 handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentType, null);
3138 throw new ByActionStatusComponentException(ActionStatus.RESTRICTED_OPERATION);
3143 private User validateUserExists(String userId, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType, boolean inTransaction) {
3146 user = validateUserExists(userId);
3147 } catch(ByResponseFormatComponentException e){
3148 ResponseFormat responseFormat = e.getResponseFormat();
3149 handleComponentException(auditingAction, componentId, artifactId, responseFormat, componentType, userId);
3151 } catch(ByActionStatusComponentException e){
3152 ResponseFormat responseFormat = componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
3153 handleComponentException(auditingAction, componentId, artifactId, responseFormat, componentType, userId);
3159 private void handleComponentException(AuditingActionEnum auditingAction, String componentId, String artifactId,
3160 ResponseFormat responseFormat, ComponentTypeEnum componentType, String userId){
3161 User user = new User();
3162 user.setUserId(userId);
3163 handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentType, null);
3166 protected AuditingActionEnum detectAuditingType(ArtifactOperationInfo operation, String origMd5) {
3167 AuditingActionEnum auditingAction = null;
3168 switch (operation.getArtifactOperationEnum()) {
3170 auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_UPLOAD_BY_API : AuditingActionEnum.ARTIFACT_UPLOAD;
3173 auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_UPLOAD_BY_API : origMd5 == null ? AuditingActionEnum.ARTIFACT_METADATA_UPDATE : AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE;
3176 auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_DELETE_BY_API : AuditingActionEnum.ARTIFACT_DELETE;
3179 auditingAction = operation.isExternalApi() ? AuditingActionEnum.DOWNLOAD_ARTIFACT : AuditingActionEnum.ARTIFACT_DOWNLOAD;
3184 return auditingAction;
3187 private ImmutablePair<String, byte[]> downloadArtifact(ArtifactDefinition artifactDefinition) {
3188 String esArtifactId = artifactDefinition.getEsId();
3189 Either<DAOArtifactData, CassandraOperationStatus> artifactfromES = artifactCassandraDao.getArtifact(esArtifactId);
3190 if (artifactfromES.isRight()) {
3191 CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value();
3192 StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
3193 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
3194 log.debug("Error when getting artifact from ES, error: {}", actionStatus);
3195 throw new ByActionStatusComponentException(actionStatus, artifactDefinition.getArtifactDisplayName());
3198 DAOArtifactData DAOArtifactData = artifactfromES.left().value();
3199 byte[] data = DAOArtifactData.getDataAsArray();
3201 log.debug("Artifact data from cassandra is null");
3202 throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_NOT_FOUND, artifactDefinition.getArtifactDisplayName());
3204 String artifactName = artifactDefinition.getArtifactName();
3205 log.trace("Download of artifact succeeded, uniqueId {}, artifact file name {}", artifactDefinition.getUniqueId(), artifactName);
3206 return new ImmutablePair<>(artifactName, data);
3209 public DAOArtifactData createEsArtifactData(ArtifactDataDefinition artifactInfo, byte[] artifactPayload) {
3210 return new DAOArtifactData(artifactInfo.getEsId(), artifactPayload);
3213 private void saveArtifactInCassandra(DAOArtifactData artifactData, Component parent, ArtifactDefinition artifactInfo,
3214 String currArtifactId, String prevArtifactId, AuditingActionEnum auditingAction, ComponentTypeEnum componentType) {
3215 CassandraOperationStatus resourceUploadStatus = artifactCassandraDao.saveArtifact(artifactData);
3217 if (resourceUploadStatus == CassandraOperationStatus.OK) {
3218 log.debug("Artifact {} was saved in component {}.", artifactData.getId(), parent.getUniqueId());
3219 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
3220 handleAuditing(auditingAction, parent, parent.getUniqueId(), null, artifactInfo, prevArtifactId,
3221 currArtifactId, responseFormat, componentType, null);
3224 BeEcompErrorManager.getInstance().logBeDaoSystemError(UPDATE_ARTIFACT);
3225 log.info(FAILED_SAVE_ARTIFACT);
3226 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
3227 handleAuditing(auditingAction, parent, parent.getUniqueId(), null, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
3228 throw new StorageException(resourceUploadStatus);
3232 private boolean isArtifactMetadataUpdate(AuditingActionEnum auditingActionEnum) {
3233 return auditingActionEnum == AuditingActionEnum.ARTIFACT_METADATA_UPDATE;
3236 private boolean isDeploymentArtifact(ArtifactDefinition artifactInfo) {
3237 return ArtifactGroupTypeEnum.DEPLOYMENT == artifactInfo.getArtifactGroupType();
3240 public ArtifactDefinition createArtifactPlaceHolderInfo(String resourceId, String logicalName, Map<String, Object> artifactInfoMap, String userUserId, ArtifactGroupTypeEnum groupType, boolean inTransaction) {
3241 User user = userBusinessLogic.getUser(userUserId, inTransaction);
3242 return createArtifactPlaceHolderInfo(resourceId, logicalName, artifactInfoMap, user, groupType);
3245 public ArtifactDefinition createArtifactPlaceHolderInfo(String resourceId, String logicalName, Map<String, Object> artifactInfoMap, User user, ArtifactGroupTypeEnum groupType) {
3246 ArtifactDefinition artifactInfo = new ArtifactDefinition();
3248 String artifactName = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_DISPLAY_NAME);
3249 String artifactType = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_TYPE);
3250 String artifactDescription = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_DESCRIPTION);
3252 artifactInfo.setArtifactDisplayName(artifactName);
3253 artifactInfo.setArtifactLabel(logicalName.toLowerCase());
3254 artifactInfo.setArtifactType(artifactType);
3255 artifactInfo.setDescription(artifactDescription);
3256 artifactInfo.setArtifactGroupType(groupType);
3257 nodeTemplateOperation.setDefaultArtifactTimeout(groupType, artifactInfo);
3259 setArtifactPlaceholderCommonFields(resourceId, user, artifactInfo);
3261 return artifactInfo;
3264 private void setArtifactPlaceholderCommonFields(String resourceId, User user, ArtifactDefinition artifactInfo) {
3265 String uniqueId = null;
3267 if (resourceId != null) {
3268 uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId.toLowerCase(), artifactInfo.getArtifactLabel()
3270 artifactInfo.setUniqueId(uniqueId);
3272 artifactInfo.setUserIdCreator(user.getUserId());
3273 String fullName = user.getFullName();
3274 artifactInfo.setUpdaterFullName(fullName);
3276 long time = System.currentTimeMillis();
3278 artifactInfo.setCreatorFullName(fullName);
3279 artifactInfo.setCreationDate(time);
3281 artifactInfo.setLastUpdateDate(time);
3282 artifactInfo.setUserIdLastUpdater(user.getUserId());
3284 artifactInfo.setMandatory(true);
3287 public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(String parentId, NodeTypeEnum parentType, ArtifactGroupTypeEnum groupType, String instanceId) {
3288 return artifactToscaOperation.getArtifacts(parentId, parentType, groupType, instanceId);
3291 public Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact(ArtifactDefinition artifactHeatEnv, ArtifactDefinition artifact, Component component, NodeTypeEnum parentType, String instanceId) {
3292 return artifactToscaOperation.addHeatEnvArtifact(artifactHeatEnv, artifact, component, parentType, true, instanceId);
3295 private Either<DAOArtifactData, ResponseFormat> createEsHeatEnvArtifactDataFromString(ArtifactDefinition artifactDefinition, String payloadStr) {
3297 byte[] payload = payloadStr.getBytes();
3299 DAOArtifactData artifactData = createEsArtifactData(artifactDefinition, payload);
3300 return Either.left(artifactData);
3304 * @param artifactDefinition
3307 public Either<ArtifactDefinition, ResponseFormat> generateHeatEnvArtifact(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, Component component, String resourceInstanceName, User modifier,
3308 String instanceId, boolean shouldLock, boolean inTransaction) {
3309 String payload = generateHeatEnvPayload(artifactDefinition);
3310 String prevUUID = artifactDefinition.getArtifactUUID();
3311 ArtifactDefinition clonedBeforeGenerate = new ArtifactDefinition(artifactDefinition);
3312 return generateAndSaveHeatEnvArtifact(artifactDefinition, payload, componentType, component, resourceInstanceName, modifier, instanceId, shouldLock, inTransaction)
3314 .bind(artifactDef -> updateArtifactOnGroupInstance(component, instanceId, prevUUID, clonedBeforeGenerate, artifactDef));
3317 public Either<ArtifactDefinition, ResponseFormat> forceGenerateHeatEnvArtifact(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, Component component, String resourceInstanceName, User modifier,
3318 boolean shouldLock, boolean inTransaction, String instanceId) {
3319 String payload = generateHeatEnvPayload(artifactDefinition);
3320 String prevUUID = artifactDefinition.getArtifactUUID();
3321 ArtifactDefinition clonedBeforeGenerate = new ArtifactDefinition(artifactDefinition);
3322 return forceGenerateAndSaveHeatEnvArtifact(artifactDefinition, payload, componentType, component, resourceInstanceName, modifier, instanceId, shouldLock, inTransaction)
3324 .bind(artifactDef -> updateArtifactOnGroupInstance(component, instanceId, prevUUID, clonedBeforeGenerate, artifactDef));
3328 Either<ArtifactDefinition, ResponseFormat> updateArtifactOnGroupInstance(Component component, String instanceId, String prevUUID, ArtifactDefinition clonedBeforeGenerate, ArtifactDefinition updatedArtDef) {
3329 if (prevUUID == null || !prevUUID.equals(updatedArtDef.getArtifactUUID())) {
3330 List<ComponentInstance> componentInstances = component.getComponentInstances();
3331 if (componentInstances != null) {
3332 Optional<ComponentInstance> findFirst = componentInstances.stream()
3333 .filter(ci -> ci.getUniqueId()
3334 .equals(instanceId))
3336 if (findFirst.isPresent()) {
3337 ComponentInstance relevantInst = findFirst.get();
3338 List<GroupInstance> updatedGroupInstances = getUpdatedGroupInstances(updatedArtDef.getUniqueId(), clonedBeforeGenerate, relevantInst
3339 .getGroupInstances());
3341 if (CollectionUtils.isNotEmpty(updatedGroupInstances)) {
3342 updatedGroupInstances.forEach(gi -> {
3343 gi.getGroupInstanceArtifacts().add(updatedArtDef.getUniqueId());
3344 gi.getGroupInstanceArtifactsUuid().add(updatedArtDef.getArtifactUUID());
3346 Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(component, instanceId, updatedGroupInstances);
3347 if (status.isRight()) {
3348 log.debug(FAILED_UPDATE_GROUPS, component.getUniqueId());
3349 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils
3350 .convertFromStorageResponse(status.right()
3351 .value()), clonedBeforeGenerate.getArtifactDisplayName());
3352 return Either.right(responseFormat);
3358 return Either.left(updatedArtDef);
3361 private String generateHeatEnvPayload(ArtifactDefinition artifactDefinition) {
3362 List<HeatParameterDefinition> heatParameters = artifactDefinition.getListHeatParameters();
3363 StringBuilder sb = new StringBuilder();
3364 sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactHeader());
3365 sb.append("parameters:\n");
3366 if (heatParameters != null) {
3367 heatParameters.sort(Comparator.comparing(HeatParameterDataDefinition::getName));
3369 List<HeatParameterDefinition> empltyHeatValues = new ArrayList<>();
3371 for (HeatParameterDefinition heatParameterDefinition : heatParameters) {
3373 String heatValue = heatParameterDefinition.getCurrentValue();
3374 if (!ValidationUtils.validateStringNotEmpty(heatValue)) {
3375 heatValue = heatParameterDefinition.getDefaultValue();
3376 if (!ValidationUtils.validateStringNotEmpty(heatValue)) {
3377 empltyHeatValues.add(heatParameterDefinition);
3381 HeatParameterType type = HeatParameterType.isValidType(heatParameterDefinition.getType());
3386 .append(heatParameterDefinition.getName())
3389 .append(Boolean.parseBoolean(heatValue))
3394 .append(heatParameterDefinition.getName())
3397 .append(new BigDecimal(heatValue).toPlainString())
3400 case COMMA_DELIMITED_LIST:
3403 .append(heatParameterDefinition.getName())
3410 String value = heatValue;
3411 boolean starts = value.startsWith("\"");
3412 boolean ends = value.endsWith("\"");
3413 if (!(starts && ends)) {
3414 starts = value.startsWith("'");
3415 ends = value.endsWith("'");
3416 if (!(starts && ends)) {
3417 value = "\"" + value + "\"";
3421 .append(heatParameterDefinition.getName())
3431 if (!empltyHeatValues.isEmpty()) {
3432 empltyHeatValues.sort(Comparator.comparing(HeatParameterDataDefinition::getName));
3433 empltyHeatValues.forEach(hv -> {
3434 sb.append(" ").append(hv.getName()).append(":");
3435 HeatParameterType type = HeatParameterType.isValidType(hv.getType());
3436 if (type != null && type == HeatParameterType.STRING && (hv.getCurrentValue() != null && "".equals(hv
3437 .getCurrentValue()) || hv.getDefaultValue() != null && "".equals(hv.getDefaultValue()))) {
3438 sb.append(" \"\"").append("\n");
3441 sb.append(" ").append("\n");
3446 sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactFooter());
3449 return sb.toString().replaceAll("\\\\n", "\n");
3453 * @param artifactDefinition
3457 public Either<ArtifactDefinition, ResponseFormat> generateAndSaveHeatEnvArtifact(ArtifactDefinition artifactDefinition, String payload, ComponentTypeEnum componentType, Component component, String resourceInstanceName,
3458 User modifier, String instanceId, boolean shouldLock, boolean inTransaction) {
3459 return generateArtifactPayload(artifactDefinition, componentType, component, resourceInstanceName, modifier, shouldLock, inTransaction, artifactDefinition::getHeatParamsUpdateDate,
3460 () -> createEsHeatEnvArtifactDataFromString(artifactDefinition, payload), instanceId);
3464 public Either<ArtifactDefinition, ResponseFormat> forceGenerateAndSaveHeatEnvArtifact(ArtifactDefinition artifactDefinition, String payload, ComponentTypeEnum componentType, Component component, String resourceInstanceName,
3465 User modifier, String instanceId, boolean shouldLock, boolean inTransaction) {
3466 return generateArtifactPayload(artifactDefinition, componentType, component, resourceInstanceName, modifier, shouldLock, inTransaction, System::currentTimeMillis,
3467 () -> createEsHeatEnvArtifactDataFromString(artifactDefinition, payload), instanceId);
3471 protected Either<ArtifactDefinition, ResponseFormat> generateArtifactPayload(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, Component component, String resourceInstanceName, User modifier,
3472 boolean shouldLock, boolean inTransaction, Supplier<Long> payloadUpdateDateGen, Supplier<Either<DAOArtifactData, ResponseFormat>> esDataCreator, String instanceId) {
3474 log.trace("Start generating payload for {} artifact {}", artifactDefinition.getArtifactType(), artifactDefinition
3476 if (artifactDefinition.getPayloadUpdateDate() == null || artifactDefinition.getPayloadUpdateDate() == 0 || artifactDefinition
3477 .getPayloadUpdateDate() <= payloadUpdateDateGen.get()) {
3479 log.trace("Generating payload for {} artifact {}", artifactDefinition.getArtifactType(), artifactDefinition.getEsId());
3480 Either<DAOArtifactData, ResponseFormat> artifactDataRes = esDataCreator.get();
3481 DAOArtifactData artifactData = null;
3483 if (artifactDataRes.isLeft()) {
3484 artifactData = artifactDataRes.left().value();
3487 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
3488 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
3489 .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
3490 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
3492 return Either.right(artifactDataRes.right().value());
3494 String newCheckSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(artifactData.getDataAsArray());
3496 String esArtifactId = artifactDefinition.getEsId();
3497 Either<DAOArtifactData, CassandraOperationStatus> artifactfromES;
3498 DAOArtifactData DAOArtifactData;
3499 if (esArtifactId != null && !esArtifactId.isEmpty() && artifactDefinition.getPayloadData() == null) {
3500 log.debug("Try to fetch artifact from cassandra with id : {}", esArtifactId);
3501 artifactfromES = artifactCassandraDao.getArtifact(esArtifactId);
3502 if (artifactfromES.isRight()) {
3503 CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value();
3504 StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
3505 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
3506 log.debug("Error when getting artifact from ES, error: {} esid : {}", actionStatus, esArtifactId);
3507 return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, artifactDefinition.getArtifactDisplayName()));
3509 DAOArtifactData = artifactfromES.left().value();
3510 oldCheckSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(DAOArtifactData.getDataAsArray());
3513 oldCheckSum = artifactDefinition.getArtifactChecksum();
3516 Either<ArtifactDefinition, StorageOperationStatus> updateArifactDefinitionStatus = null;
3520 lockComponent(component, "Update Artifact - lock resource: ");
3521 }catch (ComponentException e){
3522 handleAuditing(AuditingActionEnum.ARTIFACT_METADATA_UPDATE, component, component.getUniqueId(), modifier, null, null, artifactDefinition
3523 .getUniqueId(), e.getResponseFormat(), component.getComponentType(), null);
3528 if (oldCheckSum != null && oldCheckSum.equals(newCheckSum)) {
3530 artifactDefinition.setPayloadUpdateDate(payloadUpdateDateGen.get());
3531 updateArifactDefinitionStatus = artifactToscaOperation.updateArtifactOnResource(artifactDefinition, component
3532 ,artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId, true);
3533 log.trace("No real update done in payload for {} artifact, updating payloadUpdateDate {}", artifactDefinition
3534 .getArtifactType(), artifactDefinition.getEsId());
3535 if (updateArifactDefinitionStatus.isRight()) {
3536 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus
3538 .value()), artifactDefinition.getArtifactDisplayName());
3539 log.trace("Failed to update payloadUpdateDate {}", artifactDefinition.getEsId());
3540 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
3541 .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
3542 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
3544 return Either.right(responseFormat);
3548 artifactDefinition.getArtifactChecksum();
3549 artifactDefinition.setArtifactChecksum(newCheckSum);
3550 artifactDefinition.setEsId(artifactDefinition.getUniqueId());
3551 log.trace("No real update done in payload for {} artifact, updating payloadUpdateDate {}", artifactDefinition
3552 .getArtifactType(), artifactDefinition.getEsId());
3553 updateArifactDefinitionStatus = artifactToscaOperation.updateArtifactOnResource(artifactDefinition, component,
3554 artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId, true);
3556 log.trace("Update Payload {}", artifactDefinition.getEsId());
3558 if (updateArifactDefinitionStatus.isLeft()) {
3560 artifactDefinition = updateArifactDefinitionStatus.left().value();
3561 artifactData.setId(artifactDefinition.getUniqueId());
3562 CassandraOperationStatus saveArtifactStatus = artifactCassandraDao.saveArtifact(artifactData);
3564 if (saveArtifactStatus == CassandraOperationStatus.OK) {
3565 if (!inTransaction) {
3566 janusGraphDao.commit();
3568 log.debug("Artifact Saved In cassandra {}", artifactData.getId());
3569 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
3570 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
3571 .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
3572 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
3576 if (!inTransaction) {
3577 janusGraphDao.rollback();
3579 log.info("Failed to save artifact {}.", artifactData.getId());
3580 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
3581 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
3582 .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
3583 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
3585 return Either.right(responseFormat);
3589 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus
3591 .value()), artifactDefinition.getArtifactDisplayName());
3592 log.debug("Failed To update artifact {}", artifactData.getId());
3593 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
3594 .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
3595 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
3597 return Either.right(responseFormat);
3603 graphLockOperation.unlockComponent(component.getUniqueId(), component.getComponentType()
3609 return Either.left(artifactDefinition);
3613 public Map<String, Object> buildJsonForUpdateArtifact(ArtifactDefinition artifactDef, ArtifactGroupTypeEnum artifactGroupType, List<ArtifactTemplateInfo> updatedRequiredArtifacts) {
3614 return this.buildJsonForUpdateArtifact(artifactDef.getUniqueId(), artifactDef.getArtifactName(), artifactDef.getArtifactType(), artifactGroupType, artifactDef
3615 .getArtifactLabel(), artifactDef.getArtifactDisplayName(),
3616 artifactDef.getDescription(), artifactDef.getPayloadData(), updatedRequiredArtifacts, artifactDef.getListHeatParameters());
3620 public Map<String, Object> buildJsonForUpdateArtifact(String artifactId, String artifactName, String artifactType, ArtifactGroupTypeEnum artifactGroupType, String label, String displayName, String description, byte[] artifactContent,
3621 List<ArtifactTemplateInfo> updatedRequiredArtifacts, List<HeatParameterDefinition> heatParameters) {
3623 Map<String, Object> json = new HashMap<>();
3624 if (artifactId != null && !artifactId.isEmpty()) {
3625 json.put(Constants.ARTIFACT_ID, artifactId);
3628 json.put(Constants.ARTIFACT_NAME, artifactName);
3629 json.put(Constants.ARTIFACT_TYPE, artifactType);
3630 json.put(Constants.ARTIFACT_DESCRIPTION, description);
3632 if (artifactContent != null) {
3633 log.debug("payload is encoded. perform decode");
3634 String encodedPayload = Base64.encodeBase64String(artifactContent);
3635 json.put(Constants.ARTIFACT_PAYLOAD_DATA, encodedPayload);
3637 json.put(Constants.ARTIFACT_DISPLAY_NAME, displayName);
3638 json.put(Constants.ARTIFACT_LABEL, label);
3639 json.put(Constants.ARTIFACT_GROUP_TYPE, artifactGroupType.getType());
3640 json.put(Constants.REQUIRED_ARTIFACTS, (updatedRequiredArtifacts == null || updatedRequiredArtifacts.isEmpty()) ? new ArrayList<>()
3641 : updatedRequiredArtifacts.stream()
3642 .filter(e -> e.getType().equals(ArtifactTypeEnum.HEAT_ARTIFACT.getType()) || e
3644 .equals(ArtifactTypeEnum.HEAT_NESTED.getType()))
3645 .map(ArtifactTemplateInfo::getFileName)
3646 .collect(Collectors.toList()));
3647 json.put(Constants.ARTIFACT_HEAT_PARAMS, (heatParameters == null || heatParameters.isEmpty()) ? new ArrayList<>()
3652 public Either<ArtifactDefinition, Operation> updateResourceInstanceArtifactNoContent(String resourceId, Component containerComponent, User user, Map<String, Object> json, ArtifactOperationInfo operation, ArtifactDefinition artifactInfo) {
3654 String jsonStr = gson.toJson(json);
3655 ArtifactDefinition artifactDefinitionFromJson = artifactInfo == null ? RepresentationUtils.convertJsonToArtifactDefinition(jsonStr, ArtifactDefinition.class, false) : artifactInfo;
3656 String artifactUniqueId = artifactDefinitionFromJson == null ? null : artifactDefinitionFromJson.getUniqueId();
3657 Either<ArtifactDefinition, Operation> uploadArtifactToService = validateAndHandleArtifact(resourceId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactUniqueId,
3658 artifactDefinitionFromJson, null, jsonStr, null, null, user, containerComponent, false, false, true);
3660 return Either.left(uploadArtifactToService.left().value());
3663 private Either<ArtifactDefinition, Operation> handleUpdateHeatEnvAndHeatMeta(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType,
3664 Component parent, String originData, String origMd5, ArtifactOperationInfo operation) {
3665 if (origMd5 != null) {
3666 validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
3667 if (ArrayUtils.isNotEmpty(artifactInfo.getPayloadData())) {
3668 validateDeploymentArtifact(parent, componentId, false, artifactInfo, artifactInfo, NodeTypeEnum.ResourceInstance);
3669 handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
3670 } else { // duplicate
3671 throw new ByActionStatusComponentException(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
3674 return updateHeatEnvParamsAndMetadata(componentId, artifactId, artifactInfo, user, auditingAction, parent, componentType, origMd5);
3677 private Either<ArtifactDefinition, Operation> updateHeatEnvParamsAndMetadata(String componentId, String artifactId, ArtifactDefinition artifactInfo, User user, AuditingActionEnum auditingAction, Component parent,
3678 ComponentTypeEnum componentType, String origMd5) {
3679 Either<ComponentInstance, ResponseFormat> getRI = getRIFromComponent(parent, componentId, artifactId, auditingAction, user);
3680 if (getRI.isRight()) {
3681 throw new ByResponseFormatComponentException(getRI.right().value());
3683 ComponentInstance ri = getRI.left().value();
3684 Either<ArtifactDefinition, ResponseFormat> getArtifactRes = getArtifactFromRI(parent, ri, componentId, artifactId, auditingAction, user);
3685 if (getArtifactRes.isRight()) {
3686 throw new ByResponseFormatComponentException(getArtifactRes.right().value());
3688 ArtifactDefinition currArtifact = getArtifactRes.left().value();
3690 if (currArtifact.getArtifactType().equals(ArtifactTypeEnum.HEAT.getType()) ||
3691 currArtifact.getArtifactType().equals(ArtifactTypeEnum.HEAT_VOL.getType()) ||
3692 currArtifact.getArtifactType().equals(ArtifactTypeEnum.HEAT_NET.getType())) {
3693 throw new ByActionStatusComponentException(ActionStatus.RESTRICTED_OPERATION);
3695 List<HeatParameterDefinition> currentHeatEnvParams = currArtifact.getListHeatParameters();
3696 List<HeatParameterDefinition> updatedHeatEnvParams = artifactInfo.getListHeatParameters();
3699 if (origMd5 != null) {
3700 Either<List<HeatParameterDefinition>, ResponseFormat> uploadParamsValidationResult = validateUploadParamsFromEnvFile(auditingAction, parent, user, artifactInfo,
3701 artifactId, componentType, ri.getName(), currentHeatEnvParams, updatedHeatEnvParams, currArtifact.getArtifactName());
3702 if (uploadParamsValidationResult.isRight()) {
3703 throw new ByResponseFormatComponentException(uploadParamsValidationResult.right().value());
3705 artifactInfo.setListHeatParameters(updatedHeatEnvParams);
3708 Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers = validateAndConvertHeatParameters(artifactInfo, ArtifactTypeEnum.HEAT_ENV.getType());
3709 if (validateAndConvertHeatParamers.isRight()) {
3710 throw new ByResponseFormatComponentException(validateAndConvertHeatParamers.right().value());
3713 if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty()) {
3714 // fill reduced heat env parameters List for updating
3715 boolean updateRequired = replaceCurrHeatValueWithUpdatedValue(currentHeatEnvParams, updatedHeatEnvParams);
3716 if (updateRequired) {
3717 currArtifact.setHeatParamsUpdateDate(System.currentTimeMillis());
3718 currArtifact.setListHeatParameters(currentHeatEnvParams);
3719 Either<ArtifactDefinition, StorageOperationStatus> updateArtifactRes = artifactToscaOperation.updateArtifactOnResource(
3720 currArtifact, parent, currArtifact.getUniqueId(), componentType.getNodeType(), componentId, true);
3721 if (updateArtifactRes.isRight()) {
3722 log.debug("Failed to update artifact on graph - {}", artifactId);
3723 throw new StorageException(updateArtifactRes.right().value());
3725 StorageOperationStatus error = generateCustomizationUUIDOnGroupInstance(ri, updateArtifactRes.left().value().getUniqueId(), parent.getUniqueId());
3726 if (error != StorageOperationStatus.OK) {
3727 throw new StorageException(error);
3731 updateHeatMetaDataIfNeeded(componentId,user,auditingAction,componentType, parent,ri,artifactInfo);
3732 StorageOperationStatus error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), ri.getUniqueId(), componentType);
3733 if (error != StorageOperationStatus.OK) {
3734 throw new StorageException(error);
3737 return Either.left(currArtifact);
3741 updateHeatMetaDataIfNeeded(String componentId, User user, AuditingActionEnum auditingAction, ComponentTypeEnum componentType, Component parent, ComponentInstance resourceInstance, ArtifactDefinition updatedHeatEnvArtifact) {
3742 String heatArtifactId = updatedHeatEnvArtifact.getGeneratedFromId();
3743 Either<ArtifactDefinition, ResponseFormat> getArtifactRes = getArtifactFromRI(parent, resourceInstance, componentId, heatArtifactId, auditingAction, user);
3744 if (getArtifactRes.isRight()) {
3745 throw new ByResponseFormatComponentException(getArtifactRes.right().value());
3747 ArtifactDefinition heatArtifactToUpdate = getArtifactRes.left().value();
3748 if (isUpdateHeatMetaDataNeeded(updatedHeatEnvArtifact, heatArtifactToUpdate)) {
3749 validateHeatMetaData(updatedHeatEnvArtifact);
3750 updateHeatMetadataFromHeatEnv(updatedHeatEnvArtifact, heatArtifactToUpdate);
3751 Either<ArtifactDefinition, StorageOperationStatus> updateArtifactRes = artifactToscaOperation.updateArtifactOnResource(heatArtifactToUpdate, parent,
3752 heatArtifactToUpdate.getUniqueId(), componentType.getNodeType(), componentId, false);
3754 if (updateArtifactRes.isRight()) {
3755 log.debug("Failed to update artifact on graph - {}", heatArtifactId);
3756 throw new StorageException(updateArtifactRes.right().value());
3758 ArtifactDefinition artifactDefinition = updateArtifactRes.left().value();
3759 updateGeneratedIdInHeatEnvOnInstance(resourceInstance, parent, heatArtifactId, heatArtifactToUpdate, artifactDefinition, componentType.getNodeType());
3760 StorageOperationStatus error = generateCustomizationUUIDOnGroupInstance(resourceInstance, artifactDefinition.getUniqueId(), parent.getUniqueId());
3761 if (error != StorageOperationStatus.OK) {
3762 throw new StorageException(error);
3767 private void validateHeatMetaData(ArtifactDefinition updatedHeatEnv) {
3768 Integer maxMinutes = ConfigurationManager.getConfigurationManager().getConfiguration().getHeatArtifactDeploymentTimeout().getMaxMinutes();
3769 Integer minMinutes = ConfigurationManager.getConfigurationManager().getConfiguration().getHeatArtifactDeploymentTimeout().getMinMinutes();
3770 Integer updateTimeout = updatedHeatEnv.getTimeout();
3771 if (updateTimeout > maxMinutes || updateTimeout < minMinutes) {
3772 throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_INVALID_TIMEOUT);
3776 private boolean isUpdateHeatMetaDataNeeded(ArtifactDefinition updatedHeatEnv, ArtifactDefinition origHeat) {
3777 // currently only timeout metadata can be updated
3778 return !origHeat.getTimeout().equals(updatedHeatEnv.getTimeout());
3781 private void updateHeatMetadataFromHeatEnv(ArtifactDefinition updatedHeatEnv, ArtifactDefinition origHeat) {
3782 // currently only timeout metadata can be updated
3783 origHeat.setTimeout(updatedHeatEnv.getTimeout());
3786 private boolean replaceCurrHeatValueWithUpdatedValue(List<HeatParameterDefinition> currentHeatEnvParams, List<HeatParameterDefinition> updatedHeatEnvParams) {
3787 boolean isUpdate = false;
3788 List<String> currentParamsNames = currentHeatEnvParams.stream().map(x -> x.getName()).collect(Collectors.toList());
3789 for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) {
3790 String paramName = heatEnvParam.getName();
3791 validateParamName(paramName, currentParamsNames);
3792 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
3793 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
3794 String updatedParamValue = heatEnvParam.getCurrentValue();
3795 if (!Objects.equals(updatedParamValue, currHeatParam.getCurrentValue())) {
3796 currHeatParam.setCurrentValue(updatedParamValue);
3805 private void validateParamName(String paramName, List<String> heatParamsNames) {
3806 if (!heatParamsNames.contains(paramName)) {
3807 throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND, paramName);
3811 private Either<ArtifactDefinition, Operation> updateHeatParams(String componentId, ArtifactDefinition artifactEnvInfo, AuditingActionEnum auditingAction, Component parent,
3812 ComponentTypeEnum componentType, ArtifactDefinition currHeatArtifact, boolean needToUpdateGroup) {
3813 Either<ArtifactDefinition, Operation> insideEither = null;
3814 String currentHeatId = currHeatArtifact.getUniqueId();
3816 String esArtifactId = currHeatArtifact.getEsId();
3817 Either<DAOArtifactData, CassandraOperationStatus> artifactFromES = artifactCassandraDao.getArtifact(esArtifactId);
3818 if (artifactFromES.isRight()) {
3819 StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(artifactFromES.right().value());
3820 throw new StorageException(storageResponse, currHeatArtifact.getArtifactDisplayName());
3823 DAOArtifactData DAOArtifactData = artifactFromES.left().value();
3824 ArtifactDefinition updatedHeatArt = currHeatArtifact;
3825 List<HeatParameterDefinition> updatedHeatEnvParams = artifactEnvInfo.getListHeatParameters();
3826 List<HeatParameterDefinition> currentHeatEnvParams = currHeatArtifact.getListHeatParameters();
3827 List<HeatParameterDefinition> newHeatEnvParams = new ArrayList<>();
3829 if (CollectionUtils.isNotEmpty(updatedHeatEnvParams) && CollectionUtils.isNotEmpty(currentHeatEnvParams)) {
3830 //TODO: improve complexity - currently N^2
3832 for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) {
3833 paramName = heatEnvParam.getName();
3834 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
3835 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
3836 String updatedParamValue = heatEnvParam.getCurrentValue();
3837 if (updatedParamValue == null) {
3838 updatedParamValue = heatEnvParam.getDefaultValue();
3840 HeatParameterType paramType = HeatParameterType.isValidType(currHeatParam.getType());
3841 if (!paramType.getValidator().isValid(updatedParamValue, null)) {
3842 throw new ByActionStatusComponentException(ActionStatus.INVALID_HEAT_PARAMETER_VALUE,
3843 ArtifactTypeEnum.HEAT_ENV.getType(), paramType.getType(), paramName);
3845 currHeatParam.setCurrentValue(paramType.getConverter().convert(updatedParamValue, null, null));
3846 newHeatEnvParams.add(currHeatParam);
3851 if (!newHeatEnvParams.isEmpty()) {
3852 currHeatArtifact.setListHeatParameters(currentHeatEnvParams);
3853 Either<ArtifactDefinition, StorageOperationStatus> operationStatus = artifactToscaOperation.updateArtifactOnResource(
3854 currHeatArtifact, parent, currHeatArtifact.getUniqueId(), componentType.getNodeType(), componentId, true);
3856 if (operationStatus.isRight()) {
3857 log.debug("Failed to update artifact on graph - {}", currHeatArtifact.getUniqueId());
3858 throw new StorageException(operationStatus.right().value());
3860 updatedHeatArt = operationStatus.left().value();
3861 if (!updatedHeatArt.getDuplicated() || DAOArtifactData.getId() == null) {
3862 DAOArtifactData.setId(updatedHeatArt.getEsId());
3864 saveArtifactInCassandra(DAOArtifactData, parent, artifactEnvInfo, currentHeatId, updatedHeatArt
3865 .getUniqueId(), auditingAction, componentType);
3866 insideEither = Either.left(updatedHeatArt);
3869 Either<ArtifactDefinition, StorageOperationStatus> updateHeatEnvArtifact;
3870 if (!currentHeatId.equals(updatedHeatArt.getUniqueId())) {
3871 artifactEnvInfo.setArtifactChecksum(null);
3872 updateHeatEnvArtifact = artifactToscaOperation.updateHeatEnvArtifact(parent, artifactEnvInfo, currentHeatId, updatedHeatArt
3873 .getUniqueId(), componentType.getNodeType(), componentId);
3876 //TODO Andrey check if componentId = parent.getUniqeId
3877 updateHeatEnvArtifact = artifactToscaOperation.updateHeatEnvPlaceholder(artifactEnvInfo, parent, componentType
3881 if (needToUpdateGroup && updateHeatEnvArtifact.isLeft()) {
3882 ActionStatus result = updateGroupForHeat(currHeatArtifact, updatedHeatArt, artifactEnvInfo,
3883 updateHeatEnvArtifact.left().value(), parent);
3884 if (result != ActionStatus.OK) {
3885 throw new ByActionStatusComponentException(result);
3888 if (updatedHeatEnvParams.isEmpty()) {
3889 throw new ByActionStatusComponentException(ActionStatus.INVALID_YAML, currHeatArtifact.getArtifactName());
3891 return insideEither;
3895 private StorageOperationStatus generateCustomizationUUIDOnGroupInstance(ComponentInstance ri, String artifactId, String componentId) {
3896 StorageOperationStatus error = StorageOperationStatus.OK;
3897 log.debug("Need to re-generate customization UUID for group instance on component instance {}", ri.getUniqueId());
3898 List<GroupInstance> groupsInstances = ri.getGroupInstances();
3899 List<String> groupInstancesId = null;
3900 if (groupsInstances != null && !groupsInstances.isEmpty()) {
3901 groupInstancesId = groupsInstances.stream()
3902 .filter(p -> p.getGroupInstanceArtifacts() != null && p.getGroupInstanceArtifacts()
3903 .contains(artifactId))
3904 .map(GroupInstanceDataDefinition::getUniqueId)
3905 .collect(Collectors.toList());
3907 if (groupInstancesId != null && !groupInstancesId.isEmpty()) {
3908 toscaOperationFacade.generateCustomizationUUIDOnInstanceGroup(componentId, ri.getUniqueId(), groupInstancesId);
3914 public Either<List<HeatParameterDefinition>, ResponseFormat> validateUploadParamsFromEnvFile(AuditingActionEnum auditingAction, Component parent, User user, ArtifactDefinition artifactInfo, String artifactId, ComponentTypeEnum componentType,
3915 String riName, List<HeatParameterDefinition> currentHeatEnvParams, List<HeatParameterDefinition> updatedHeatEnvParams, String currArtifactName) {
3917 if (updatedHeatEnvParams == null || updatedHeatEnvParams.isEmpty()) {
3918 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactInfo
3919 .getArtifactName(), currArtifactName);
3920 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, riName);
3921 return Either.right(responseFormat);
3924 for (HeatParameterDefinition uploadedHeatParam : updatedHeatEnvParams) {
3925 String paramName = uploadedHeatParam.getName();
3926 boolean isExistsInHeat = false;
3927 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
3928 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
3930 isExistsInHeat = true;
3931 uploadedHeatParam.setType(currHeatParam.getType());
3932 uploadedHeatParam.setCurrentValue(uploadedHeatParam.getDefaultValue());
3933 uploadedHeatParam.setDefaultValue(currHeatParam.getDefaultValue());
3934 uploadedHeatParam.setUniqueId(currHeatParam.getUniqueId());
3938 if (!isExistsInHeat) {
3939 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, currArtifactName);
3940 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, riName);
3941 return Either.right(responseFormat);
3944 return Either.left(updatedHeatEnvParams);
3947 private Either<ComponentInstance, ResponseFormat> getRIFromComponent(Component component, String riID, String artifactId, AuditingActionEnum auditingAction, User user) {
3948 ResponseFormat responseFormat = null;
3949 List<ComponentInstance> ris = component.getComponentInstances();
3950 for (ComponentInstance ri : ris) {
3951 if (riID.equals(ri.getUniqueId())) {
3952 return Either.left(ri);
3955 responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, riID);
3956 log.debug("Resource Instance not found, resourceInstanceId {}", riID);
3957 handleAuditing(auditingAction, null, riID, user, null, null, artifactId, responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE, null);
3958 return Either.right(responseFormat);
3961 private Either<ArtifactDefinition, ResponseFormat> getArtifactFromRI(Component component, ComponentInstance ri, String riID, String artifactId, AuditingActionEnum auditingAction, User user) {
3962 ResponseFormat responseFormat = null;
3963 Map<String, ArtifactDefinition> rtifactsMap = ri.getDeploymentArtifacts();
3964 for (ArtifactDefinition artifact : rtifactsMap.values()) {
3965 if (artifactId.equals(artifact.getUniqueId())) {
3966 return Either.left(artifact);
3969 responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, riID, component.getUniqueId());
3970 handleAuditing(auditingAction, component, riID, user, null, null, artifactId, responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE, ri
3972 return Either.right(responseFormat);
3975 public ArtifactDefinition extractArtifactDefinition(Either<ArtifactDefinition, Operation> eitherArtifact) {
3976 ArtifactDefinition ret;
3977 if (eitherArtifact.isLeft()) {
3978 ret = eitherArtifact.left().value();
3981 ret = eitherArtifact.right().value().getImplementationArtifact();
3986 public byte[] downloadComponentArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String artifactUUID, ResourceCommonInfo resourceCommonInfo) {
3987 Component component = getComponentByUuid(componentType, componentUuid);
3988 resourceCommonInfo.setResourceName(component.getName());
3989 return downloadArtifact(component.getAllArtifacts(), artifactUUID, component.getName());
3993 * downloads an artifact of resource instance of component by UUIDs
3995 * @param componentType
3996 * @param componentUuid
3997 * @param resourceInstanceName
3998 * @param artifactUUID
4001 public byte[] downloadResourceInstanceArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid,
4002 String resourceInstanceName, String artifactUUID) {
4003 ComponentInstance resourceInstance = getRelatedComponentInstance(componentType, componentUuid, resourceInstanceName);
4004 return downloadArtifact(resourceInstance == null ? null : resourceInstance.getDeploymentArtifacts(),
4005 artifactUUID, resourceInstance.getName());
4009 * uploads an artifact to a component by UUID
4013 * @param componentType
4014 * @param componentUuid
4015 * @param resourceCommonInfo
4019 public ArtifactDefinition uploadArtifactToComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType,
4020 String componentUuid, ResourceCommonInfo resourceCommonInfo, ArtifactOperationInfo operation) {
4021 Either<ArtifactDefinition, Operation> actionResult;
4022 Component component;
4024 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class, false);
4025 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4026 String userId = request.getHeader(Constants.USER_ID_HEADER);
4028 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes =
4029 toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4030 if (getComponentRes.isRight()) {
4031 StorageOperationStatus status = getComponentRes.right().value();
4032 log.debug(FAILED_FETCH_COMPONENT, componentType, componentUuid, status);
4033 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status, componentType), componentUuid);
4036 ComponentMetadataDataDefinition componentMetadataDataDefinition = getComponentRes.left().value().getMetadataDataDefinition();
4037 componentId = componentMetadataDataDefinition.getUniqueId();
4038 String componentName = componentMetadataDataDefinition.getName();
4040 if (!componentMetadataDataDefinition
4042 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4043 component = checkoutParentComponent(componentType, componentId, userId);
4044 if (component != null) {
4045 componentId = component.getUniqueId();
4046 componentName = component.getName();
4049 resourceCommonInfo.setResourceName(componentName);
4051 actionResult = handleArtifactRequest(componentId, userId, componentType, operation, null, artifactInfo,
4052 origMd5, data, null, null, null, null);
4053 return actionResult.left().value();
4057 * upload an artifact to a resource instance by UUID
4061 * @param componentType
4062 * @param componentUuid
4063 * @param resourceInstanceName
4067 public ArtifactDefinition uploadArtifactToRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName,
4068 ArtifactOperationInfo operation) {
4069 Either<ArtifactDefinition, Operation> actionResult;
4070 Component component = null;
4071 String componentInstanceId;
4073 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4074 String userId = request.getHeader(Constants.USER_ID_HEADER);
4076 ImmutablePair<Component, ComponentInstance> componentRiPair = null;
4077 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4078 if (getComponentRes.isRight()) {
4079 StorageOperationStatus status = getComponentRes.right().value();
4080 log.debug(FAILED_FETCH_COMPONENT, componentType, componentUuid, status);
4081 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status, componentType), resourceInstanceName);
4083 if (!getComponentRes.left()
4085 .getMetadataDataDefinition()
4087 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4088 component = checkoutParentComponent(componentType, getComponentRes.left()
4090 .getMetadataDataDefinition()
4091 .getUniqueId(), userId);
4093 if (component == null) {
4094 componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName);
4097 componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName);
4099 componentInstanceId = componentRiPair.getRight().getUniqueId();
4100 componentId = componentRiPair.getLeft().getUniqueId();
4101 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class, false);
4103 actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE,
4104 operation, null, artifactInfo, origMd5, data, null, null,
4105 componentId, ComponentTypeEnum.findParamByType(componentType));
4107 return actionResult.left().value();
4111 * updates an artifact on a component by UUID
4115 * @param componentType
4116 * @param componentUuid
4117 * @param artifactUUID
4118 * @param resourceCommonInfo
4119 * @param operation TODO
4122 public ArtifactDefinition updateArtifactOnComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID,
4123 ResourceCommonInfo resourceCommonInfo, ArtifactOperationInfo operation) {
4124 Either<ArtifactDefinition, Operation> actionResult;
4125 Component component;
4128 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinitionForUpdate(data, ArtifactDefinition.class);
4129 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4130 String userId = request.getHeader(Constants.USER_ID_HEADER);
4132 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4133 if (getComponentRes.isRight()) {
4134 StorageOperationStatus status = getComponentRes.right().value();
4135 log.debug(FAILED_FETCH_COMPONENT, componentType, componentUuid, status);
4136 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status));
4138 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
4139 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
4141 if (!getComponentRes.left()
4143 .getMetadataDataDefinition()
4145 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4146 component = checkoutParentComponent(componentType, componentId, userId);
4147 if (component != null) {
4148 componentId = component.getUniqueId();
4149 componentName = component.getName();
4152 resourceCommonInfo.setResourceName(componentName);
4153 artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, componentId, componentType);
4154 actionResult = handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo,
4155 origMd5, data, null, null, null, null);
4156 if (actionResult.isRight()) {
4157 log.debug(FAILED_UPLOAD_ARTIFACT_TO_COMPONENT, componentType, componentUuid, actionResult
4162 return actionResult.left().value();
4166 * updates an artifact on a resource instance by UUID
4170 * @param componentType
4171 * @param componentUuid
4172 * @param resourceInstanceName
4173 * @param artifactUUID
4174 * @param operation TODO
4177 public ArtifactDefinition updateArtifactOnRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID,
4178 ArtifactOperationInfo operation) {
4180 Either<ArtifactDefinition, Operation> actionResult;
4181 Component component = null;
4182 String componentInstanceId;
4185 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4186 String userId = request.getHeader(Constants.USER_ID_HEADER);
4188 ImmutablePair<Component, ComponentInstance> componentRiPair = null;
4189 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4190 if (getComponentRes.isRight()) {
4191 StorageOperationStatus status = getComponentRes.right().value();
4192 log.debug(FAILED_FETCH_COMPONENT, componentType, componentUuid, status);
4193 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status));
4195 if (!getComponentRes.left()
4197 .getMetadataDataDefinition()
4199 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4200 component = checkoutParentComponent(componentType, getComponentRes.left()
4202 .getMetadataDataDefinition()
4203 .getUniqueId(), userId);
4205 if (component == null) {
4206 componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName);
4209 componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName);
4211 componentInstanceId = componentRiPair.getRight().getUniqueId();
4212 componentId = componentRiPair.getLeft().getUniqueId();
4213 artifactId = findArtifactId(componentRiPair.getRight(), artifactUUID);
4214 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class, false);
4216 actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, artifactInfo, origMd5, data, null, null, componentId, ComponentTypeEnum
4217 .findParamByType(componentType));
4218 return actionResult.left().value();
4221 private Either<ArtifactDefinition, ResponseFormat> updateOperationArtifact(String componentId, String interfaceType, String operationUuid, ArtifactDefinition artifactInfo){
4222 Either<Component, StorageOperationStatus> componentStorageOperationStatusEither = toscaOperationFacade.getToscaElement(componentId);
4223 if (componentStorageOperationStatusEither.isRight()) {
4224 StorageOperationStatus errorStatus = componentStorageOperationStatusEither.right().value();
4225 log.debug("Failed to fetch resource information by resource id, error {}", errorStatus);
4226 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(errorStatus)));
4228 Component storedComponent = componentStorageOperationStatusEither.left().value();
4230 Optional<InterfaceDefinition> optionalInterface = InterfaceOperationUtils.getInterfaceDefinitionFromComponentByInterfaceType(storedComponent, interfaceType);
4231 if(!optionalInterface.isPresent()) {
4232 log.debug("Failed to get resource interface for resource Id {}", componentId);
4233 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_NOT_FOUND_IN_COMPONENT, interfaceType));
4236 //fetch the operation from storage
4237 InterfaceDefinition gotInterface = optionalInterface.get();
4238 Map<String, Operation> operationsMap = gotInterface.getOperationsMap();
4239 Optional<Operation> optionalOperation = operationsMap.values()
4241 .filter(o -> o.getUniqueId().equals(operationUuid))
4243 if (!optionalOperation.isPresent()) {
4244 log.debug("Failed to get resource interface operation for resource Id {} and operationId {}", componentId, operationUuid);
4245 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_FOUND, componentId);
4246 return Either.right(responseFormat);
4249 Operation operation = optionalOperation.get();
4250 ArtifactDefinition implementationArtifact = operation.getImplementationArtifact();
4251 implementationArtifact.setArtifactUUID(artifactInfo.getArtifactUUID());
4252 implementationArtifact.setUniqueId(artifactInfo.getUniqueId());
4253 implementationArtifact.setArtifactName(artifactInfo.getArtifactName());
4254 implementationArtifact.setDescription(artifactInfo.getDescription());
4255 implementationArtifact.setArtifactType(artifactInfo.getArtifactType());
4256 implementationArtifact.setArtifactLabel(artifactInfo.getArtifactLabel());
4257 implementationArtifact.setArtifactDisplayName(artifactInfo.getArtifactDisplayName());
4258 implementationArtifact.setEsId(artifactInfo.getEsId());
4259 operation.setImplementation(implementationArtifact);
4260 gotInterface.setOperationsMap(operationsMap);
4261 Either<List<InterfaceDefinition>, StorageOperationStatus> interfaceDefinitionStorageOperationStatusEither =
4262 interfaceOperation.updateInterfaces(storedComponent.getUniqueId(), Collections.singletonList(gotInterface));
4263 if (interfaceDefinitionStorageOperationStatusEither.isRight()){
4264 StorageOperationStatus storageOperationStatus = interfaceDefinitionStorageOperationStatusEither.right().value();
4265 ActionStatus actionStatus =
4266 componentsUtils.convertFromStorageResponseForDataType(storageOperationStatus);
4267 return Either.right(componentsUtils.getResponseFormat(actionStatus));
4270 return Either.left(artifactInfo);
4275 * updates an artifact on a component by UUID
4279 * @param componentType
4280 * @param componentUuid
4281 * @param artifactUUID
4285 public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnInterfaceOperationByResourceUUID(
4286 String data, HttpServletRequest request, ComponentTypeEnum componentType,
4287 String componentUuid, String interfaceUUID, String operationUUID, String artifactUUID,
4288 ResourceCommonInfo resourceCommonInfo,ArtifactOperationInfo operation) {
4289 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4290 Either<ArtifactDefinition, ResponseFormat> updateArtifactResult;
4291 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4292 ArtifactDefinition updateArtifact = null;
4293 String componentId = null;
4294 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinitionForUpdate(data, ArtifactDefinition.class);
4295 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4296 String userId = request.getHeader(Constants.USER_ID_HEADER);
4297 ArtifactDefinition existingArtifactInfo = null;
4298 String interfaceName = null;
4300 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4301 if (getComponentRes.isRight()) {
4302 StorageOperationStatus status = getComponentRes.right().value();
4303 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4304 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4307 if (errorWrapper.isEmpty()) {
4308 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
4309 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
4310 if (!getComponentRes.left()
4312 .getMetadataDataDefinition()
4314 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4315 Component component = checkoutParentComponent(componentType, componentId, userId);
4316 if (component != null) {
4317 componentId = component.getUniqueId();
4318 componentName = component.getName();
4322 resourceCommonInfo.setResourceName(componentName);
4325 if(errorWrapper.isEmpty()){
4326 Either<String, ResponseFormat> interfaceNameEither = fetchInterfaceName(componentId, interfaceUUID);
4327 if (interfaceNameEither.isRight()) {
4328 errorWrapper.setInnerElement(interfaceNameEither.right().value());
4331 interfaceName = interfaceNameEither.left().value();
4334 if(errorWrapper.isEmpty()){
4335 Either<Component, StorageOperationStatus> toscaComponentEither = toscaOperationFacade.getToscaElement(componentId);
4336 if (toscaComponentEither.isRight()) {
4337 StorageOperationStatus status = toscaComponentEither.right().value();
4338 log.debug("Could not fetch component with type {} and id {}. Status is {}. ", componentType, componentId, status);
4339 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4342 if (errorWrapper.isEmpty()) {
4343 NodeTypeEnum parentType = convertParentType(componentType);
4344 List<ArtifactDefinition> existingDeploymentArtifacts = getDeploymentArtifacts(toscaComponentEither.left().value(), parentType,null);
4345 for (ArtifactDefinition artifactDefinition: existingDeploymentArtifacts){
4346 if(artifactInfo.getArtifactName().equalsIgnoreCase(artifactDefinition.getArtifactName())){
4347 existingArtifactInfo = artifactDefinition;
4351 if(existingArtifactInfo != null){
4352 return updateOperationArtifact(componentId, interfaceName, operationUUID, existingArtifactInfo);
4358 if (errorWrapper.isEmpty()) {
4360 actionResult = Either.left(handleArtifactRequest(componentId, userId, componentType, operation,
4361 artifactUUID, artifactInfo, origMd5, data, interfaceName,
4362 operationUUID, null, null));
4363 }catch (ComponentException e){
4364 errorWrapper.setInnerElement(e.getResponseFormat());
4368 if (errorWrapper.isEmpty()) {
4369 updateArtifact = actionResult.left().value().left().value();
4370 updateArtifactResult = Either.left(updateArtifact);
4374 updateArtifactResult = Either.right(errorWrapper.getInnerElement());
4376 return updateArtifactResult;
4379 private Either<String, ResponseFormat> fetchInterfaceName(String componentId, String interfaceUUID) {
4380 Either<Component, StorageOperationStatus> componentStorageOperationStatusEither = toscaOperationFacade.getToscaElement(componentId);
4381 if (componentStorageOperationStatusEither.isRight()) {
4382 StorageOperationStatus errorStatus = componentStorageOperationStatusEither.right().value();
4383 log.debug("Failed to fetch component information by component id, error {}", errorStatus);
4384 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(errorStatus)));
4386 Component storedComponent = componentStorageOperationStatusEither.left().value();
4388 Optional<InterfaceDefinition> optionalInterface = InterfaceOperationUtils
4389 .getInterfaceDefinitionFromComponentByInterfaceId(storedComponent, interfaceUUID);
4390 if(!optionalInterface.isPresent()) {
4391 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_NOT_FOUND_IN_COMPONENT, interfaceUUID));
4393 return Either.left(optionalInterface.get().getType());
4397 * deletes an artifact on a component by UUID
4400 * @param componentType
4401 * @param componentUuid
4402 * @param artifactUUID
4403 * @param resourceCommonInfo
4404 * @param operation TODO
4407 public ArtifactDefinition deleteArtifactOnComponentByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID, ResourceCommonInfo resourceCommonInfo,
4408 ArtifactOperationInfo operation) {
4410 Either<ArtifactDefinition, Operation> actionResult;
4411 Component component;
4412 String componentId ;
4414 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4415 String userId = request.getHeader(Constants.USER_ID_HEADER);
4417 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4418 if (getComponentRes.isRight()) {
4419 StorageOperationStatus status = getComponentRes.right().value();
4420 log.debug(FAILED_FETCH_COMPONENT, componentType, componentUuid, status);
4421 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status, componentType), componentUuid);
4423 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
4424 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
4425 if (!getComponentRes.left()
4427 .getMetadataDataDefinition()
4429 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4430 component = checkoutParentComponent(componentType, componentId, userId);
4431 if (component != null) {
4432 componentId = component.getUniqueId();
4433 componentName = component.getName();
4436 resourceCommonInfo.setResourceName(componentName);
4437 artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, componentId, componentType);
4438 actionResult = handleArtifactRequest(componentId, userId, componentType, operation, artifactId, null, origMd5, null, null, null, null, null);
4439 return actionResult.left().value();
4443 * deletes an artifact from a resource instance by UUID
4446 * @param componentType
4447 * @param componentUuid
4448 * @param resourceInstanceName
4449 * @param artifactUUID
4450 * @param operation TODO
4453 public ArtifactDefinition deleteArtifactOnRiByUUID(HttpServletRequest request, ComponentTypeEnum componentType,
4454 String componentUuid, String resourceInstanceName,
4455 String artifactUUID, ArtifactOperationInfo operation) {
4457 Either<ArtifactDefinition, Operation> actionResult;
4458 Component component = null;
4459 String componentInstanceId;
4462 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4463 String userId = request.getHeader(Constants.USER_ID_HEADER);
4464 ImmutablePair<Component, ComponentInstance> componentRiPair = null;
4465 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes =
4466 toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4467 if (getComponentRes.isRight()) {
4468 StorageOperationStatus status = getComponentRes.right().value();
4469 log.debug(FAILED_FETCH_COMPONENT, componentType, componentUuid, status);
4470 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status));
4472 if (!getComponentRes.left()
4474 .getMetadataDataDefinition()
4476 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4477 component = checkoutParentComponent(componentType, getComponentRes.left()
4479 .getMetadataDataDefinition()
4480 .getUniqueId(), userId);
4482 if (component == null) {
4483 componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName);
4486 componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName);
4488 componentInstanceId = componentRiPair.getRight().getUniqueId();
4489 componentId = componentRiPair.getLeft().getUniqueId();
4490 artifactId = findArtifactId(componentRiPair.getRight(), artifactUUID);
4492 actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, null, origMd5, null, null, null, componentId, ComponentTypeEnum
4493 .findParamByType(componentType));
4494 return actionResult.left().value();
4497 private String findArtifactId(ComponentInstance instance, String artifactUUID) {
4498 String artifactId = null;
4499 ArtifactDefinition foundArtifact = null;
4500 if (instance.getDeploymentArtifacts() != null) {
4501 foundArtifact = instance.getDeploymentArtifacts()
4504 .filter(e -> e.getArtifactUUID() != null && e.getArtifactUUID()
4505 .equals(artifactUUID))
4509 if (foundArtifact == null && instance.getArtifacts() != null) {
4510 foundArtifact = instance.getArtifacts()
4513 .filter(e -> e.getArtifactUUID() != null && e.getArtifactUUID()
4514 .equals(artifactUUID))
4518 if (foundArtifact == null) {
4519 log.debug("The artifact {} was not found on instance {}. ", artifactUUID, instance.getUniqueId());
4520 throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_NOT_FOUND, artifactUUID);
4523 artifactId = foundArtifact.getUniqueId();
4528 @SuppressWarnings("unchecked")
4529 public ArtifactDefinition createHeatEnvPlaceHolder(List<ArtifactDefinition> createdArtifacts, ArtifactDefinition heatArtifact,
4530 String envType, String parentId, NodeTypeEnum parentType,
4531 String parentName, User user, Component component,
4532 Map<String, String> existingEnvVersions) {
4533 Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager()
4535 .getDeploymentResourceInstanceArtifacts();
4536 if (deploymentResourceArtifacts == null) {
4537 log.debug("no deployment artifacts are configured for generated artifacts");
4538 throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
4540 Map<String, Object> placeHolderData = (Map<String, Object>) deploymentResourceArtifacts.get(envType);
4541 if (placeHolderData == null) {
4542 log.debug("no env type {} are configured for generated artifacts", envType);
4543 throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
4546 String envLabel = (heatArtifact.getArtifactLabel() + HEAT_ENV_SUFFIX).toLowerCase();
4547 ArtifactDefinition createArtifactPlaceHolder = createArtifactPlaceHolderInfo(parentId, envLabel, placeHolderData, user
4548 .getUserId(), ArtifactGroupTypeEnum.DEPLOYMENT, true);
4549 ArtifactDefinition artifactHeatEnv = createArtifactPlaceHolder;
4550 artifactHeatEnv.setGeneratedFromId(heatArtifact.getUniqueId());
4551 artifactHeatEnv.setHeatParamsUpdateDate(System.currentTimeMillis());
4552 artifactHeatEnv.setTimeout(0);
4553 artifactHeatEnv.setIsFromCsar(heatArtifact.getIsFromCsar());
4554 buildHeatEnvFileName(heatArtifact, artifactHeatEnv, placeHolderData);
4555 // rbetzer - keep env artifactVersion - changeComponentInstanceVersion flow
4556 handleEnvArtifactVersion(artifactHeatEnv, existingEnvVersions);
4557 ArtifactDefinition heatEnvPlaceholder;
4558 // Evg : for resource instance artifact will be added later as block with other env artifacts from BL
4559 if (parentType != NodeTypeEnum.ResourceInstance) {
4560 String checkSum = artifactToscaOperation.sortAndCalculateChecksumForHeatParameters(heatArtifact.getHeatParameters());
4561 artifactHeatEnv.setArtifactChecksum(checkSum);
4562 Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact = addHeatEnvArtifact(artifactHeatEnv, heatArtifact, component, parentType, parentId);
4563 if (addHeatEnvArtifact.isRight()) {
4564 log.debug("failed to create heat env artifact on resource instance");
4565 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(addHeatEnvArtifact
4567 .value(), false), "", null));
4569 heatEnvPlaceholder = createArtifactPlaceHolder;
4572 heatEnvPlaceholder = artifactHeatEnv;
4573 artifactToscaOperation.generateUUID(heatEnvPlaceholder, heatEnvPlaceholder.getArtifactVersion());
4574 setHeatCurrentValuesOnHeatEnvDefaultValues(heatArtifact, heatEnvPlaceholder);
4576 ComponentTypeEnum componentType = component.getComponentType();
4577 if (parentType == NodeTypeEnum.ResourceInstance) {
4578 componentType = ComponentTypeEnum.RESOURCE_INSTANCE;
4580 createdArtifacts.add(heatEnvPlaceholder);
4581 componentsUtils.auditComponent(componentsUtils.getResponseFormat(ActionStatus.OK), user, component, AuditingActionEnum.ARTIFACT_UPLOAD,
4582 new ResourceCommonInfo(parentName, componentType.getValue()),
4583 ResourceVersionInfo.newBuilder().build(),
4584 ResourceVersionInfo.newBuilder().artifactUuid(heatEnvPlaceholder.getUniqueId()).build(),
4585 null, heatEnvPlaceholder, null);
4586 return heatEnvPlaceholder;
4589 private void setHeatCurrentValuesOnHeatEnvDefaultValues(ArtifactDefinition artifact, ArtifactDefinition artifactDefinition) {
4590 if (artifact.getListHeatParameters() == null) {
4593 List<HeatParameterDefinition> heatEnvParameters = new ArrayList<>();
4594 for (HeatParameterDefinition parameter : artifact.getListHeatParameters()) {
4595 HeatParameterDefinition heatEnvParameter = new HeatParameterDefinition(parameter);
4596 heatEnvParameter.setDefaultValue(parameter.getCurrentValue());
4597 heatEnvParameter.setCurrentValue(null);
4598 heatEnvParameters.add(heatEnvParameter);
4600 artifactDefinition.setListHeatParameters(heatEnvParameters);
4603 private void buildHeatEnvFileName(ArtifactDefinition heatArtifact, ArtifactDefinition heatEnvArtifact, Map<String, Object> placeHolderData) {
4604 String heatExtension = GeneralUtility.getFilenameExtension(heatArtifact.getArtifactName());
4605 String envExtension = (String) placeHolderData.get(ARTIFACT_PLACEHOLDER_FILE_EXTENSION);
4606 String name = heatArtifact.getArtifactName();
4609 name = heatArtifact.getArtifactLabel();
4610 fileName = name + "." + envExtension;
4613 fileName = name.replaceAll("." + heatExtension, "." + envExtension);
4615 heatEnvArtifact.setArtifactName(fileName);
4618 private void handleEnvArtifactVersion(ArtifactDefinition heatEnvArtifact, Map<String, String> existingEnvVersions) {
4619 if (null != existingEnvVersions) {
4620 String prevVersion = existingEnvVersions.get(heatEnvArtifact.getArtifactName());
4621 if (null != prevVersion) {
4622 heatEnvArtifact.setArtifactVersion(prevVersion);
4627 public List<ArtifactDefinition> handleArtifactsForInnerVfcComponent(List<ArtifactDefinition> artifactsToHandle, Resource component, User user, List<ArtifactDefinition> vfcsNewCreatedArtifacts,
4628 ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) {
4629 ComponentTypeEnum componentType = component.getComponentType();
4630 List<ArtifactDefinition> uploadedArtifacts = new ArrayList<>();
4631 Either<ArtifactDefinition, Operation> result;
4633 for (ArtifactDefinition artifactDefinition : artifactsToHandle) {
4634 result = handleLoadedArtifact(component, user, operation, shouldLock, inTransaction, componentType, artifactDefinition);
4635 uploadedArtifacts.add(result.left().value());
4637 } catch (ComponentException e) {
4638 log.debug(FAILED_UPLOAD_ARTIFACT_TO_COMPONENT, componentType, component
4639 .getName(), e.getResponseFormat());
4640 if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
4641 vfcsNewCreatedArtifacts.addAll(uploadedArtifacts);
4645 return uploadedArtifacts;
4648 public Either<ArtifactDefinition, Operation> handleLoadedArtifact(Resource component, User user, ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction,
4649 ComponentTypeEnum componentType, ArtifactDefinition artifactDefinition) {
4650 AuditingActionEnum auditingAction = detectAuditingType(operation, "");
4651 String componentId = component.getUniqueId();
4652 String artifactId = artifactDefinition.getUniqueId();
4653 Either<ArtifactDefinition, Operation> result;
4654 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4655 //artifact validation
4656 artifactDefinition = validateArtifact(componentId, componentType, operation,
4657 artifactId, artifactDefinition, auditingAction, user,
4658 component, shouldLock, inTransaction);
4659 switch (operation.getArtifactOperationEnum()) {
4661 byte[] validPayload = getValidPayload(componentId, artifactDefinition, operation, auditingAction, artifactId, user, componentType, component, null, null);
4662 result = createArtifact(component, componentId, artifactDefinition, validPayload,
4663 componentType, auditingAction, null, null);
4666 validPayload = getValidPayload(componentId, artifactDefinition, operation, auditingAction, artifactId, user, componentType, component, null, null);
4667 result = handleUpdate(componentId, componentType, operation, artifactId, artifactDefinition, validPayload, null, null, null, null,
4668 auditingAction, user, component, true);
4671 result = Either.left(handleDeleteInternal(componentId, artifactId, componentType, component));
4674 if (artifactGenerationRequired(component, artifactDefinition)) {
4675 result = Either.left(generateNotSavedArtifact(component, artifactDefinition));
4677 result = Either.left(handleDownload(componentId, artifactId, componentType, component));
4681 result = Either.left(handleLink(componentId, artifactDefinition, componentType, component));
4684 throw new UnsupportedOperationException("In ArtifactsBusinessLogic received illegal operation: " + operation.getArtifactOperationEnum());
4689 public List<ArtifactDefinition> handleArtifactsRequestForInnerVfcComponent(List<ArtifactDefinition> artifactsToHandle, Resource component, User user, List<ArtifactDefinition> vfcsNewCreatedArtifacts,
4690 ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) {
4692 List<ArtifactDefinition> handleArtifactsResult;
4693 ComponentTypeEnum componentType = component.getComponentType();
4694 List<ArtifactDefinition> uploadedArtifacts = new ArrayList<>();
4695 Either<ArtifactDefinition, Operation> actionResult;
4699 for (ArtifactDefinition artifact : artifactsToHandle) {
4700 originData = buildJsonStringForCsarVfcArtifact(artifact);
4701 origMd5 = GeneralUtility.calculateMD5Base64EncodedByString(originData);
4702 actionResult = handleArtifactRequest(component.getUniqueId(), user.getUserId(), componentType, operation, artifact
4703 .getUniqueId(), artifact, origMd5, originData, null, null, null, null, shouldLock, inTransaction);
4704 uploadedArtifacts.add(actionResult.left().value());
4706 handleArtifactsResult = uploadedArtifacts;
4707 }catch (ComponentException e){
4708 if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
4709 vfcsNewCreatedArtifacts.addAll(uploadedArtifacts);
4713 return handleArtifactsResult;
4716 private ComponentInstance getRelatedComponentInstance(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName) {
4717 ComponentInstance componentInstance;
4718 String normalizedName = ValidationUtils.normalizeComponentInstanceName(resourceInstanceName);
4719 Component component = getComponentByUuid(componentType, componentUuid);
4720 componentInstance = (component == null) ? null : component.getComponentInstances()
4722 .filter(ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName())
4723 .equals(normalizedName))
4726 if (componentInstance == null) {
4727 log.debug(COMPONENT_INSTANCE_NOT_FOUND, resourceInstanceName, component.getName());
4728 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName,
4729 RESOURCE_INSTANCE, component.getComponentType().getValue(), component.getName());
4731 return componentInstance;
4734 private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(Component component, String resourceInstanceName) {
4736 ImmutablePair<Component, ComponentInstance> relatedComponentComponentInstancePair = null;
4737 String normalizedName = ValidationUtils.normalizeComponentInstanceName(resourceInstanceName);
4738 ComponentInstance componentInstance = component.getComponentInstances()
4740 .filter(ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName())
4741 .equals(normalizedName))
4744 if (componentInstance == null) {
4745 log.debug(COMPONENT_INSTANCE_NOT_FOUND, resourceInstanceName, component.getName());
4746 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName,
4747 RESOURCE_INSTANCE, component.getComponentType().getValue(), component.getName());
4750 relatedComponentComponentInstancePair = new ImmutablePair<>(component, componentInstance);
4752 return relatedComponentComponentInstancePair;
4755 private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(ComponentTypeEnum componentType,
4756 String componentUuid, String resourceInstanceName) {
4757 ComponentInstance componentInstance;
4758 ImmutablePair<Component, ComponentInstance> relatedComponentComponentInstancePair;
4759 Component component = getLatestComponentByUuid(componentType, componentUuid);
4760 componentInstance = component.getComponentInstances()
4762 .filter(ci -> ci.getNormalizedName().equals(resourceInstanceName))
4765 if (componentInstance == null) {
4766 log.debug(COMPONENT_INSTANCE_NOT_FOUND, resourceInstanceName, component.getName());
4767 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER,
4768 resourceInstanceName, RESOURCE_INSTANCE, component
4769 .getComponentType().getValue(), component.getName());
4772 relatedComponentComponentInstancePair = new ImmutablePair<>(component, componentInstance);
4774 return relatedComponentComponentInstancePair;
4777 private byte[] downloadArtifact(Map<String, ArtifactDefinition> artifacts, String artifactUUID, String componentName) {
4779 ImmutablePair<String, byte[]> downloadArtifact;
4780 List<ArtifactDefinition> artifactsList = null;
4781 ArtifactDefinition deploymentArtifact;
4782 if (artifacts != null && !artifacts.isEmpty()) {
4783 artifactsList = artifacts.values()
4785 .filter(art -> art.getArtifactUUID() != null && art.getArtifactUUID()
4786 .equals(artifactUUID))
4787 .collect(Collectors.toList());
4789 if (artifactsList == null || artifactsList.isEmpty()) {
4790 log.debug("Deployment artifact with uuid {} was not found for component {}", artifactUUID, componentName);
4791 throw new ByActionStatusComponentException(ActionStatus.ARTIFACT_NOT_FOUND, artifactUUID);
4793 deploymentArtifact = artifactsList.get(0);
4794 downloadArtifact = downloadArtifact(deploymentArtifact);
4795 log.trace("Succeeded to download artifact with uniqueId {}", deploymentArtifact.getUniqueId());
4796 return downloadArtifact.getRight();
4799 private Component getLatestComponentByUuid(ComponentTypeEnum componentType, String componentUuid) {
4800 Component component;
4801 Either<Component, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentByUuid(componentUuid);
4802 if (getComponentRes.isRight()) {
4803 StorageOperationStatus status = getComponentRes.right().value();
4804 log.debug(FAILED_FETCH_COMPONENT, componentType, componentUuid, status);
4805 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status));
4808 component = getComponentRes.left().value();
4813 private Component getComponentByUuid(ComponentTypeEnum componentType, String componentUuid) {
4814 Component component;
4815 Either<List<Component>, StorageOperationStatus> getComponentRes = toscaOperationFacade.getComponentListByUuid(componentUuid, null);
4816 if (getComponentRes.isRight()) {
4817 StorageOperationStatus status = getComponentRes.right().value();
4818 log.debug(FAILED_FETCH_COMPONENT, componentType, componentUuid, status);
4819 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(status));
4822 List<Component> value = getComponentRes.left().value();
4823 if (value.isEmpty()) {
4824 log.debug("Could not fetch component with type {} and uuid {}.", componentType, componentUuid);
4825 ActionStatus status = componentType == ComponentTypeEnum.RESOURCE ? ActionStatus.RESOURCE_NOT_FOUND : ActionStatus.SERVICE_NOT_FOUND;
4826 throw new ByActionStatusComponentException(status);
4829 component = value.get(0);
4835 private String getLatestParentArtifactDataIdByArtifactUUID(String artifactUUID, String parentId, ComponentTypeEnum componentType) {
4836 ActionStatus actionStatus = ActionStatus.ARTIFACT_NOT_FOUND;
4837 StorageOperationStatus storageStatus;
4838 ArtifactDefinition latestArtifact;
4839 List<ArtifactDefinition> artifacts;
4840 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifactsRes = artifactToscaOperation.getArtifacts(parentId);
4841 if (getArtifactsRes.isRight()) {
4842 storageStatus = getArtifactsRes.right().value();
4843 log.debug("Couldn't fetch artifacts data for parent component {} with uid {}, error: {}", componentType, parentId, storageStatus);
4844 if (storageStatus != StorageOperationStatus.NOT_FOUND) {
4845 actionStatus = componentsUtils.convertFromStorageResponse(storageStatus);
4847 throw new ByActionStatusComponentException(actionStatus, artifactUUID);
4849 artifacts = getArtifactsRes.left()
4853 .filter(a -> a.getArtifactUUID() != null && a.getArtifactUUID()
4854 .equals(artifactUUID))
4855 .collect(Collectors.toList());
4856 if (artifacts == null || artifacts.isEmpty()) {
4857 log.debug("Couldn't fetch artifact with UUID {} data for parent component {} with uid {}, error: {}", artifactUUID, componentType, parentId, actionStatus);
4858 throw new ByActionStatusComponentException(actionStatus, artifactUUID);
4860 latestArtifact = artifacts.stream().max((a1, a2) -> {
4861 int compareRes = Double.compare(Double.parseDouble(a1.getArtifactVersion()), Double.parseDouble(a2.getArtifactVersion()));
4862 if (compareRes == 0) {
4863 compareRes = Long.compare(a1.getLastUpdateDate() == null ? 0 : a1.getLastUpdateDate(), a2.getLastUpdateDate() == null ? 0 : a2
4864 .getLastUpdateDate());
4868 if (latestArtifact == null) {
4869 log.debug("Couldn't fetch latest artifact with UUID {} data for parent component {} with uid {}, error: {}", artifactUUID, componentType, parentId, actionStatus);
4870 throw new ByActionStatusComponentException(actionStatus, artifactUUID);
4872 return latestArtifact.getUniqueId();
4875 private Component checkoutParentComponent(ComponentTypeEnum componentType, String parentId, String userId) {
4877 Component component = null;
4878 User modifier = userBusinessLogic.getUser(userId, false);
4879 LifecycleChangeInfoWithAction changeInfo = new LifecycleChangeInfoWithAction("External API checkout", LifecycleChanceActionEnum.UPDATE_FROM_EXTERNAL_API);
4880 Either<? extends Component, ResponseFormat> checkoutRes = lifecycleBusinessLogic.changeComponentState(componentType, parentId, modifier, LifeCycleTransitionEnum.CHECKOUT, changeInfo, false, true);
4881 if (checkoutRes.isRight()) {
4882 log.debug("Could not change state of component {} with uid {} to checked out. Status is {}. ", componentType
4883 .getNodeType(), parentId, checkoutRes.right().value().getStatus());
4884 throw new ByResponseFormatComponentException(checkoutRes.right().value());
4886 return checkoutRes.left().value();
4889 private String buildJsonStringForCsarVfcArtifact(ArtifactDefinition artifact) {
4890 Map<String, Object> json = new HashMap<>();
4891 String artifactName = artifact.getArtifactName();
4892 json.put(Constants.ARTIFACT_NAME, artifactName);
4893 json.put(Constants.ARTIFACT_LABEL, artifact.getArtifactLabel());
4894 json.put(Constants.ARTIFACT_TYPE, artifact.getArtifactType());
4895 json.put(Constants.ARTIFACT_GROUP_TYPE, ArtifactGroupTypeEnum.DEPLOYMENT.getType());
4896 json.put(Constants.ARTIFACT_DESCRIPTION, artifact.getDescription());
4897 json.put(Constants.ARTIFACT_PAYLOAD_DATA, artifact.getPayloadData());
4898 json.put(Constants.ARTIFACT_DISPLAY_NAME, artifact.getArtifactDisplayName());
4899 return gson.toJson(json);
4903 void setNodeTemplateOperation(NodeTemplateOperation nodeTemplateOperation) {
4904 this.nodeTemplateOperation = nodeTemplateOperation;