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.gson.Gson;
26 import com.google.gson.GsonBuilder;
27 import fj.data.Either;
28 import org.apache.commons.codec.binary.Base64;
29 import org.apache.commons.collections.CollectionUtils;
30 import org.apache.commons.collections.MapUtils;
31 import org.apache.commons.lang.StringUtils;
32 import org.apache.commons.lang3.tuple.ImmutablePair;
33 import org.elasticsearch.common.Strings;
34 import org.openecomp.sdc.be.components.ArtifactsResolver;
35 import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum;
36 import org.openecomp.sdc.be.components.impl.artifact.ArtifactTypeToPayloadTypeSelector;
37 import org.openecomp.sdc.be.components.impl.artifact.PayloadTypeEnum;
38 import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
39 import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException;
40 import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
41 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
42 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction.LifecycleChanceActionEnum;
43 import org.openecomp.sdc.be.components.utils.InterfaceOperationUtils;
44 import org.openecomp.sdc.be.config.BeEcompErrorManager;
45 import org.openecomp.sdc.be.config.Configuration.ArtifactTypeConfig;
46 import org.openecomp.sdc.be.config.ConfigurationManager;
47 import org.openecomp.sdc.be.dao.api.ActionStatus;
48 import org.openecomp.sdc.be.dao.cassandra.ArtifactCassandraDao;
49 import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus;
50 import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
51 import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
52 import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
53 import org.openecomp.sdc.be.datatypes.elements.GroupInstanceDataDefinition;
54 import org.openecomp.sdc.be.datatypes.elements.OperationDataDefinition;
55 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
56 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
57 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
58 import org.openecomp.sdc.be.info.ArtifactTemplateInfo;
59 import org.openecomp.sdc.be.model.ArtifactDefinition;
60 import org.openecomp.sdc.be.model.ArtifactType;
61 import org.openecomp.sdc.be.model.Component;
62 import org.openecomp.sdc.be.model.ComponentInstance;
63 import org.openecomp.sdc.be.model.ComponentParametersView;
64 import org.openecomp.sdc.be.model.GroupDefinition;
65 import org.openecomp.sdc.be.model.GroupInstance;
66 import org.openecomp.sdc.be.model.HeatParameterDefinition;
67 import org.openecomp.sdc.be.model.InterfaceDefinition;
68 import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;
69 import org.openecomp.sdc.be.model.LifecycleStateEnum;
70 import org.openecomp.sdc.be.model.Operation;
71 import org.openecomp.sdc.be.model.Resource;
72 import org.openecomp.sdc.be.model.Service;
73 import org.openecomp.sdc.be.model.User;
74 import org.openecomp.sdc.be.model.heat.HeatParameterType;
75 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ArtifactsOperations;
76 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.InterfaceOperation;
77 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.NodeTemplateOperation;
78 import org.openecomp.sdc.be.model.operations.api.IElementOperation;
79 import org.openecomp.sdc.be.model.operations.api.IGroupInstanceOperation;
80 import org.openecomp.sdc.be.model.operations.api.IGroupOperation;
81 import org.openecomp.sdc.be.model.operations.api.IGroupTypeOperation;
82 import org.openecomp.sdc.be.model.operations.api.IHeatParametersOperation;
83 import org.openecomp.sdc.be.model.operations.api.IInterfaceLifecycleOperation;
84 import org.openecomp.sdc.be.model.operations.api.IUserAdminOperation;
85 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
86 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
87 import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation;
88 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
89 import org.openecomp.sdc.be.resources.data.ComponentMetadataData;
90 import org.openecomp.sdc.be.resources.data.ESArtifactData;
91 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
92 import org.openecomp.sdc.be.resources.data.auditing.model.ResourceCommonInfo;
93 import org.openecomp.sdc.be.resources.data.auditing.model.ResourceVersionInfo;
94 import org.openecomp.sdc.be.servlets.RepresentationUtils;
95 import org.openecomp.sdc.be.tosca.CsarUtils;
96 import org.openecomp.sdc.be.tosca.ToscaError;
97 import org.openecomp.sdc.be.tosca.ToscaExportHandler;
98 import org.openecomp.sdc.be.tosca.ToscaRepresentation;
99 import org.openecomp.sdc.be.user.IUserBusinessLogic;
100 import org.openecomp.sdc.be.user.Role;
101 import org.openecomp.sdc.be.user.UserBusinessLogic;
102 import org.openecomp.sdc.be.utils.TypeUtils;
103 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
104 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
105 import org.openecomp.sdc.common.api.Constants;
106 import org.openecomp.sdc.common.datastructure.Wrapper;
107 import org.openecomp.sdc.common.log.wrappers.Logger;
108 import org.openecomp.sdc.common.util.GeneralUtility;
109 import org.openecomp.sdc.common.util.ValidationUtils;
110 import org.openecomp.sdc.common.util.YamlToObjectConverter;
111 import org.openecomp.sdc.exception.ResponseFormat;
112 import org.springframework.beans.factory.annotation.Autowired;
113 import org.xml.sax.InputSource;
114 import org.xml.sax.SAXException;
115 import org.xml.sax.SAXNotRecognizedException;
116 import org.xml.sax.SAXNotSupportedException;
117 import org.xml.sax.XMLReader;
118 import org.yaml.snakeyaml.Yaml;
120 import javax.servlet.http.HttpServletRequest;
121 import javax.xml.XMLConstants;
122 import javax.xml.parsers.ParserConfigurationException;
123 import javax.xml.parsers.SAXParserFactory;
124 import java.io.ByteArrayInputStream;
125 import java.io.IOException;
126 import java.math.BigDecimal;
127 import java.util.ArrayList;
128 import java.util.Collections;
129 import java.util.Comparator;
130 import java.util.HashMap;
131 import java.util.Iterator;
132 import java.util.List;
133 import java.util.Map;
134 import java.util.Map.Entry;
135 import java.util.Objects;
136 import java.util.Optional;
137 import java.util.Set;
138 import java.util.function.Predicate;
139 import java.util.function.Supplier;
140 import java.util.stream.Collectors;
142 @org.springframework.stereotype.Component("artifactBusinessLogic")
143 public class ArtifactsBusinessLogic extends BaseBusinessLogic {
144 private static final String RESOURCE_INSTANCE = "resource instance";
145 private static final String ARTIFACT_TYPE_OTHER = "OTHER";
146 private static final String ARTIFACT_DESCRIPTION = "artifact description";
147 private static final String ARTIFACT_LABEL = "artifact label";
148 private static final String ARTIFACT_URL = "artifact url";
149 private static final String ARTIFACT_NAME = "artifact name";
150 private static final String ARTIFACT_PAYLOAD = "artifact payload";
152 private static final String ARTIFACT_PLACEHOLDER_TYPE = "type";
153 private static final String ARTIFACT_PLACEHOLDER_DISPLAY_NAME = "displayName";
154 private static final Object ARTIFACT_PLACEHOLDER_DESCRIPTION = "description";
156 public static final String HEAT_ENV_NAME = "heatEnv";
157 public static final String HEAT_VF_ENV_NAME = "VfHeatEnv";
158 public static final String HEAT_ENV_SUFFIX = "env";
159 private static final String ARTIFACT_PLACEHOLDER_FILE_EXTENSION = "fileExtension";
161 private static final Logger log = Logger.getLogger(ArtifactsBusinessLogic.class);
162 private static final String FAILED_UPDATE_GROUPS = "Failed to update groups of the component {}. ";
163 private static final String FAILED_UPDATE_ARTIFACT = "Failed to delete or update the artifact {}. Parent uniqueId is {}";
164 private static final String FAILED_SAVE_ARTIFACT = "Failed to save the artifact.";
165 private static final String UPDATE_ARTIFACT_LOCK = "Update Artifact - lock ";
166 private static final String FAILED_DOWNLOAD_ARTIFACT = "Download artifact {} failed";
167 private static final String FAILED_UPLOAD_ARTIFACT_TO_COMPONENT = "Failed to upload artifact to component with type {} and uuid {}. Status is {}. ";
168 private static final String FAILED_UPLOAD_ARTIFACT_TO_INSTANCE = "Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. ";
169 private static final String FAILED_FETCH_COMPONENT = "Could not fetch component with type {} and uuid {}. Status is {}. ";
170 private static final String NULL_PARAMETER = "One of the function parameteres is null";
171 public static final String COMPONENT_INSTANCE_NOT_FOUND = "Component instance {} was not found for component {}";
172 private static final String ROLLBACK = "all changes rollback";
173 private static final String COMMIT = "all changes committed";
174 private static final String ARTIFACT_SAVED = "Artifact saved into ES - {}";
175 private static final String UPDATE_ARTIFACT = "Update Artifact";
176 private static final String FOUND_DEPLOYMENT_ARTIFACT = "Found deployment artifact {}";
177 private Gson gson = new GsonBuilder().setPrettyPrinting().create();
179 @javax.annotation.Resource
180 private IInterfaceLifecycleOperation interfaceLifecycleOperation;
181 @javax.annotation.Resource
182 private IUserAdminOperation userOperaton;
184 @javax.annotation.Resource
185 private IElementOperation elementOperation;
187 @javax.annotation.Resource
188 private UserBusinessLogic userAdminManager;
190 @javax.annotation.Resource
191 private IHeatParametersOperation heatParametersOperation;
193 private final ArtifactCassandraDao artifactCassandraDao;
194 private final ToscaExportHandler toscaExportUtils;
195 private final CsarUtils csarUtils;
196 private final LifecycleBusinessLogic lifecycleBusinessLogic;
197 private final IUserBusinessLogic userBusinessLogic;
198 private final ArtifactsResolver artifactsResolver;
199 private NodeTemplateOperation nodeTemplateOperation;
202 public ArtifactsBusinessLogic(ArtifactCassandraDao artifactCassandraDao, ToscaExportHandler toscaExportUtils,
203 CsarUtils csarUtils, LifecycleBusinessLogic lifecycleBusinessLogic, IUserBusinessLogic userBusinessLogic,
204 ArtifactsResolver artifactsResolver, IElementOperation elementDao, IGroupOperation groupOperation,
205 IGroupInstanceOperation groupInstanceOperation, IGroupTypeOperation groupTypeOperation, InterfaceOperation interfaceOperation,
206 InterfaceLifecycleOperation interfaceLifecycleTypeOperation, ArtifactsOperations artifactToscaOperation) {
207 super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation,
208 interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation);
209 this.artifactCassandraDao = artifactCassandraDao;
210 this.toscaExportUtils = toscaExportUtils;
211 this.csarUtils = csarUtils;
212 this.lifecycleBusinessLogic = lifecycleBusinessLogic;
213 this.userBusinessLogic = userBusinessLogic;
214 this.artifactsResolver = artifactsResolver;
217 public enum ArtifactOperationEnum {
218 CREATE, UPDATE, DELETE, DOWNLOAD, LINK;
220 public static boolean isCreateOrLink(ArtifactOperationEnum operation) {
221 return operation == CREATE || operation == LINK;
225 public class ArtifactOperationInfo {
227 private ArtifactOperationEnum artifactOperationEnum;
228 private boolean isExternalApi;
229 private boolean ignoreLifecycleState;
231 public ArtifactOperationInfo(boolean isExternalApi, boolean ignoreLifecycleState, ArtifactOperationEnum artifactOperationEnum) {
232 this.artifactOperationEnum = artifactOperationEnum;
233 this.isExternalApi = isExternalApi;
234 this.ignoreLifecycleState = ignoreLifecycleState;
237 public boolean isExternalApi() {
238 return isExternalApi;
241 public boolean ignoreLifecycleState() {
242 return ignoreLifecycleState;
245 public ArtifactOperationEnum getArtifactOperationEnum() {
246 return artifactOperationEnum;
252 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleArtifactRequest(String componentId, String userId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo,
253 String origMd5, String originData, String interfaceUuid, String operationUuid, String parentId, String containerComponentType) {
254 return handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, origMd5, originData, interfaceUuid, operationUuid, parentId, containerComponentType, true, false);
257 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleArtifactRequest(String componentId, String userId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo,
258 String origMd5, String originData, String interfaceUuid, String operationUuid, String parentId, String containerComponentType, boolean shouldLock, boolean inTransaction) {
260 // step 1 - detect auditing type
261 AuditingActionEnum auditingAction = detectAuditingType(operation, origMd5);
262 // step 2 - check header
263 if (userId == null) {
264 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
265 log.debug("handleArtifactRequest - no HTTP_CSP_HEADER , component id {}", componentId);
266 handleAuditing(auditingAction, null, componentId, null, null, null, artifactId, responseFormat, componentType, null);
267 return Either.right(responseFormat);
269 // step 3 - check user existence
270 Either<User, ResponseFormat> userResult = validateUserExists(userId, auditingAction, componentId, artifactId, componentType, inTransaction);
271 if (userResult.isRight()) {
272 return Either.right(userResult.right().value());
275 // step 4 - check user's role
276 User user = userResult.left().value();
277 Either<Boolean, ResponseFormat> validateUserRole = validateUserRole(user, auditingAction, componentId, artifactId, componentType, operation);
278 if (validateUserRole.isRight()) {
279 return Either.right(validateUserRole.right().value());
283 // 5. check service/resource existence
284 // 6. check service/resource check out
285 // 7. user is owner of checkout state
286 org.openecomp.sdc.be.model.Component component = null;
287 String realComponentId = componentType == ComponentTypeEnum.RESOURCE_INSTANCE ? parentId : componentId;
288 Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(realComponentId, auditingAction, user, artifactId, componentType, containerComponentType);
289 if (validateComponent.isRight()) {
290 return Either.right(validateComponent.right().value());
292 component = validateComponent.left().value();
293 Either<Boolean, ResponseFormat> validateWorkOnResource = validateWorkOnComponent(component, userId, auditingAction, user, artifactId, operation);
294 if (validateWorkOnResource.isRight()) {
295 return Either.right(validateWorkOnResource.right().value());
299 return validateAndHandleArtifact(componentId, componentType, operation, artifactId, artifactInfo, origMd5, originData, interfaceUuid, operationUuid, user, component,
300 shouldLock, inTransaction, true);
304 * This Method validates only the Artifact and does not validate user / role / component ect...<br>
305 * For regular usage use <br>
306 * {@link #handleArtifactRequest(String, String, ComponentTypeEnum, ArtifactOperationInfo, String, ArtifactDefinition, String, String, String, String, String, String)}
310 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> validateAndHandleArtifact(String componentUniqueId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactUniqueId,
311 ArtifactDefinition artifactDefinition, String origMd5, String originData, String interfaceUuid, String operationName, User user, Component component, boolean shouldLock, boolean inTransaction, boolean needUpdateGroup) {
312 Component parent = component;
313 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
315 AuditingActionEnum auditingAction = detectAuditingType(operation, origMd5);
316 artifactDefinition = validateArtifact(componentUniqueId, componentType, operation, artifactUniqueId, artifactDefinition, auditingAction, user, component, parent, errorWrapper, shouldLock, inTransaction);
318 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result;
319 if (errorWrapper.isEmpty()) {
321 result = doAction(componentUniqueId, componentType, operation, artifactUniqueId, artifactDefinition, origMd5, originData, interfaceUuid, operationName, auditingAction, user, parent, shouldLock, inTransaction, needUpdateGroup);
324 result = Either.right(errorWrapper.getInnerElement());
329 private ArtifactDefinition validateArtifact(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, User user,
330 Component component, Component parent, Wrapper<ResponseFormat> errorWrapper, boolean shouldLock, boolean inTransaction) {
331 ArtifactDefinition validatedArtifactInfo = artifactInfo;
332 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.UPDATE || operation.getArtifactOperationEnum() == ArtifactOperationEnum.DELETE || operation
333 .getArtifactOperationEnum() == ArtifactOperationEnum.DOWNLOAD) {
334 Either<ArtifactDefinition, ResponseFormat> validateArtifact = validateArtifact(componentId, componentType, artifactId, component);
335 if (validateArtifact.isRight()) {
336 ResponseFormat responseFormat = validateArtifact.right().value();
337 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
338 errorWrapper.setInnerElement(validateArtifact.right().value());
340 else if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.DOWNLOAD) {
341 validatedArtifactInfo = validateArtifact.left().value();
342 handleHeatEnvDownload(componentId, componentType, user, component, validateArtifact, errorWrapper, shouldLock, inTransaction);
345 return validatedArtifactInfo;
348 private void handleHeatEnvDownload(String componentId, ComponentTypeEnum componentType, User user, org.openecomp.sdc.be.model.Component component, Either<ArtifactDefinition,
349 ResponseFormat> validateArtifact, Wrapper<ResponseFormat> errorWrapper, boolean shouldLock, boolean inTransaction) {
350 ArtifactDefinition validatedArtifact = validateArtifact.left().value();
352 if (validatedArtifact.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType())
353 && ComponentTypeEnum.SERVICE == component.getComponentType()) {
354 ComponentInstance componentInstance = component.getComponentInstances()
356 .filter(p -> p.getUniqueId().equals(componentId))
359 Map<String, ArtifactDefinition> deploymentArtifacts = componentInstance.getDeploymentArtifacts();
361 ArtifactDefinition heatEnvWithHeatParams = deploymentArtifacts.values()
363 .filter(p -> p.getUniqueId()
364 .equals(validatedArtifact.getUniqueId()))
367 Either<ArtifactDefinition, ResponseFormat> eitherGenerated = generateHeatEnvArtifact(heatEnvWithHeatParams, componentType, component, componentInstance
368 .getName(), user, componentId, shouldLock, inTransaction);
369 if (eitherGenerated.isRight()) {
370 errorWrapper.setInnerElement(eitherGenerated.right().value());
375 private boolean artifactGenerationRequired(org.openecomp.sdc.be.model.Component component, ArtifactDefinition artifactInfo) {
376 boolean needGenerate;
377 needGenerate = artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA && (component.getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN || component
378 .getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
379 needGenerate = needGenerate || (ComponentTypeEnum.RESOURCE == component.getComponentType() && (artifactInfo.getArtifactType()
380 .equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV
381 .getType()) || isAbstractVfcEmptyCsar((Resource) component, artifactInfo)));
385 private boolean isAbstractVfcEmptyCsar(Resource resource, ArtifactDefinition artifactInfo) {
386 return resource.isAbstract() && artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA && artifactInfo
388 .equals(ArtifactTypeEnum.TOSCA_CSAR.getType()) && StringUtils.isEmpty(artifactInfo.getArtifactChecksum());
391 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateAndSaveToscaArtifact(ArtifactDefinition artifactDefinition, org.openecomp.sdc.be.model.Component component, User user, boolean isInCertificationRequest,
392 boolean shouldLock, boolean inTransaction, boolean fetchTemplatesFromDB) {
394 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generated = generateToscaArtifact(component, artifactDefinition, isInCertificationRequest, fetchTemplatesFromDB);
395 if (generated.isRight()) {
398 byte[] decodedPayload = artifactDefinition.getPayloadData();
399 artifactDefinition.setEsId(artifactDefinition.getUniqueId());
400 artifactDefinition.setArtifactChecksum(GeneralUtility.calculateMD5Base64EncodedByByteArray(decodedPayload));
401 return lockComponentAndUpdateArtifact(component.getUniqueId(), artifactDefinition, AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, artifactDefinition
402 .getUniqueId(), user, component.getComponentType(), component, decodedPayload, null, null,
403 shouldLock, inTransaction);
407 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateToscaArtifact(Component parent, ArtifactDefinition artifactInfo, boolean isInCertificationRequest, boolean fetchTemplatesFromDB) {
408 log.debug("tosca artifact generation");
409 if (artifactInfo.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType())) {
410 Either<byte[], ResponseFormat> generated = csarUtils.createCsar(parent, fetchTemplatesFromDB, isInCertificationRequest);
412 if (generated.isRight()) {
413 log.debug("Failed to export tosca csar for component {} error {}", parent.getUniqueId(), generated.right()
416 return Either.right(generated.right().value());
418 byte[] value = generated.left().value();
419 artifactInfo.setPayload(value);
423 Either<ToscaRepresentation, ToscaError> exportComponent = toscaExportUtils.exportComponent(parent);
424 if (exportComponent.isRight()) {
425 log.debug("Failed export tosca yaml for component {} error {}", parent.getUniqueId(), exportComponent.right()
427 ActionStatus status = componentsUtils.convertFromToscaError(exportComponent.right().value());
428 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status);
429 return Either.right(responseFormat);
431 log.debug("Tosca yaml exported for component {} ", parent.getUniqueId());
432 String payload = exportComponent.left().value().getMainYaml();
433 artifactInfo.setPayloadData(payload);
435 return Either.left(Either.left(artifactInfo));
438 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> doAction(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, String origMd5,
439 String originData, String interfaceName, String operationName, AuditingActionEnum auditingAction, User user, org.openecomp.sdc.be.model.Component parent, boolean shouldLock, boolean inTransaction, boolean needUpdateGroup) {
440 switch (operation.getArtifactOperationEnum()) {
442 if (artifactGenerationRequired(parent, artifactInfo)) {
443 return generateNotSavedArtifact(parent, artifactInfo);
445 return handleDownload(componentId, artifactId, user, auditingAction, componentType, parent);
447 return handleDelete(componentId, artifactId, user, auditingAction, componentType, parent, shouldLock, inTransaction);
449 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result = null;
450 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
451 if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)
452 && (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_VOL || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_ENV)) {
453 result = handleUpdateHeatEnv(componentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, originData, origMd5, operation, shouldLock, inTransaction);
454 if (needUpdateGroup && result.isLeft()) {
455 Either<ArtifactDefinition, Operation> updateResult = result.left().value();
456 ActionStatus error = updateGroupInstance(artifactInfo, updateResult.left()
457 .value(), parent, componentType, componentId);
458 if (error != ActionStatus.OK) {
459 result = Either.right(componentsUtils.getResponseFormat(error));
464 if (componentType.equals(ComponentTypeEnum.RESOURCE) && artifactType == ArtifactTypeEnum.HEAT_ENV) {
465 result = handleUpdateHeatWithHeatEnvParams(componentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, originData, origMd5, operation, shouldLock, inTransaction, needUpdateGroup);
468 if (result == null) {
469 result = handleUpdate(componentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceName, operationName, shouldLock, inTransaction);
470 if (needUpdateGroup && result.isLeft()) {
471 Either<ArtifactDefinition, Operation> updateResult = result.left().value();
473 ActionStatus error = updateGroupForHeat(artifactInfo, updateResult.left()
474 .value(), parent, componentType);
475 if (error != ActionStatus.OK) {
476 result = Either.right(componentsUtils.getResponseFormat(error));
482 return handleCreate(componentId, artifactInfo, operation, auditingAction, user, componentType, parent, origMd5, originData, interfaceName, operationName, shouldLock, inTransaction);
484 return handleLink(componentId, artifactInfo, auditingAction, user, componentType, parent, shouldLock, inTransaction);
489 private ActionStatus updateGroupForHeat(ArtifactDefinition artifactInfo, ArtifactDefinition artAfterUpdate, Component parent, ComponentTypeEnum componentType) {
490 List<GroupDefinition> groups = parent.getGroups();
491 if (groups != null && !groups.isEmpty()) {
492 List<GroupDataDefinition> groupToUpdate = groups.stream()
493 .filter(g -> g.getArtifacts() != null && g.getArtifacts()
494 .contains(artifactInfo
496 .collect(Collectors.toList());
497 if (groupToUpdate != null && !groupToUpdate.isEmpty()) {
498 groupToUpdate.forEach(g -> {
499 g.getArtifacts().remove(artifactInfo.getUniqueId());
500 g.getArtifactsUuid().remove(artifactInfo.getArtifactUUID());
501 g.getArtifacts().add(artAfterUpdate.getUniqueId());
502 g.getArtifactsUuid().add(artAfterUpdate.getArtifactUUID());
504 Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(parent, groupToUpdate);
505 if (status.isRight()) {
506 log.debug(FAILED_UPDATE_GROUPS, parent.getUniqueId());
507 return componentsUtils.convertFromStorageResponse(status.right().value());
511 return ActionStatus.OK;
514 private ActionStatus updateGroupForHeat(ArtifactDefinition artifactInfoHeat, ArtifactDefinition artHeatAfterUpdate, ArtifactDefinition artifactInfoHeatE, ArtifactDefinition artHEAfterUpdate, Component parent, ComponentTypeEnum componentType) {
515 List<GroupDefinition> groups = parent.getGroups();
516 if (groups != null && !groups.isEmpty()) {
517 List<GroupDataDefinition> groupToUpdate = groups.stream()
518 .filter(g -> g.getArtifacts() != null && g.getArtifacts()
519 .contains(artifactInfoHeat
521 .collect(Collectors.toList());
522 if (groupToUpdate != null && !groupToUpdate.isEmpty()) {
523 groupToUpdate.forEach(g -> {
524 g.getArtifacts().remove(artifactInfoHeat.getUniqueId());
525 g.getArtifactsUuid().remove(artifactInfoHeat.getArtifactUUID());
526 g.getArtifacts().remove(artifactInfoHeatE.getUniqueId());
527 g.getArtifacts().add(artHeatAfterUpdate.getUniqueId());
528 g.getArtifactsUuid().add(artHeatAfterUpdate.getArtifactUUID());
529 g.getArtifacts().add(artHEAfterUpdate.getUniqueId());
531 Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(parent, groupToUpdate);
532 if (status.isRight()) {
533 log.debug(FAILED_UPDATE_GROUPS, parent.getUniqueId());
534 return componentsUtils.convertFromStorageResponse(status.right().value());
538 return ActionStatus.OK;
541 private ActionStatus updateGroupInstance(ArtifactDefinition artifactInfo, ArtifactDefinition artAfterUpdate, Component parent, ComponentTypeEnum componentType, String parentId) {
542 List<GroupInstance> updatedGroupInstances = new ArrayList<>();
543 List<GroupInstance> groupInstances = null;
544 Optional<ComponentInstance> componentInstOp = parent.getComponentInstances()
546 .filter(ci -> ci.getUniqueId().equals(parentId))
548 if (componentInstOp.isPresent()) {
549 groupInstances = componentInstOp.get().getGroupInstances();
551 if (CollectionUtils.isNotEmpty(groupInstances)) {
552 boolean isUpdated = false;
553 for (GroupInstance groupInstance : groupInstances) {
555 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifacts()) && groupInstance.getGroupInstanceArtifacts()
556 .contains(artifactInfo
558 groupInstance.getGroupInstanceArtifacts().remove(artifactInfo.getUniqueId());
559 groupInstance.getGroupInstanceArtifacts().add(artAfterUpdate.getUniqueId());
562 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifactsUuid()) && groupInstance.getGroupInstanceArtifactsUuid()
563 .contains(artifactInfo
564 .getArtifactUUID())) {
565 groupInstance.getGroupInstanceArtifactsUuid().remove(artifactInfo.getArtifactUUID());
566 groupInstance.getGroupInstanceArtifacts().add(artAfterUpdate.getArtifactUUID());
570 updatedGroupInstances.add(groupInstance);
574 Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(parent, parentId, updatedGroupInstances);
575 if (status.isRight()) {
576 log.debug(FAILED_UPDATE_GROUPS, parent.getUniqueId());
577 return componentsUtils.convertFromStorageResponse(status.right().value());
579 return ActionStatus.OK;
582 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateNotSavedArtifact(Component parent, ArtifactDefinition artifactInfo) {
583 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result;
584 if (artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA) {
585 result = generateToscaArtifact(parent, artifactInfo, false, false);
588 String heatArtifactId = artifactInfo.getGeneratedFromId();
589 Either<ArtifactDefinition, StorageOperationStatus> heatRes = artifactToscaOperation.getArtifactById(parent.getUniqueId(), heatArtifactId);
590 if (heatRes.isRight()) {
591 log.debug("Failed to fetch heat artifact by generated id {} for heat env {}", heatArtifactId, artifactInfo
593 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(heatRes
596 return Either.right(responseFormat);
598 String generatedPayload = generateHeatEnvPayload(heatRes.left().value());
599 artifactInfo.setPayloadData(generatedPayload);
600 result = Either.left(Either.left(artifactInfo));
605 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdateHeatWithHeatEnvParams(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user,
606 ComponentTypeEnum componentType, Component parent, String originData, String origMd5, ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction, boolean needToUpdateGroup) {
607 convertParentType(componentType);
608 String parentId = parent.getUniqueId();
609 Either<ArtifactDefinition, StorageOperationStatus> artifactHeatRes = artifactToscaOperation.getArtifactById(componentId, artifactInfo
610 .getGeneratedFromId());
611 ArtifactDefinition currHeatArtifact = artifactHeatRes.left().value();
613 if (origMd5 != null) {
614 Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
615 if (validateMd5.isRight()) {
616 ResponseFormat responseFormat = validateMd5.right().value();
617 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
618 return Either.right(responseFormat);
621 if (artifactInfo.getPayloadData() != null && artifactInfo.getPayloadData().length != 0) {
623 Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
624 if (payloadEither.isRight()) {
625 ResponseFormat responseFormat = payloadEither.right().value();
626 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
627 return Either.right(responseFormat);
631 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
632 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
633 return Either.right(responseFormat);
639 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, UPDATE_ARTIFACT_LOCK);
640 if (lockComponent.isRight()) {
641 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right()
642 .value(), componentType, null);
643 return Either.right(lockComponent.right().value());
646 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
648 resultOp = updateHeatParams(componentId, artifactId, artifactInfo, user, auditingAction, parent, componentType, currHeatArtifact, needToUpdateGroup);
654 if (resultOp == null || resultOp.isRight()) {
656 if (!inTransaction) {
657 janusGraphDao.rollback();
662 if (!inTransaction) {
663 janusGraphDao.commit();
667 graphLockOperation.unlockComponent(parent.getUniqueId(), parent.getComponentType().getNodeType());
672 public Either<ImmutablePair<String, byte[]>, ResponseFormat> handleDownloadToscaModelRequest(Component component, ArtifactDefinition csarArtifact) {
673 if (artifactGenerationRequired(component, csarArtifact)) {
674 Either<byte[], ResponseFormat> generated = csarUtils.createCsar(component, false, false);
676 if (generated.isRight()) {
677 log.debug("Failed to export tosca csar for component {} error {}", component.getUniqueId(), generated.right()
680 return Either.right(generated.right().value());
682 return Either.left(new ImmutablePair<String, byte[]>(csarArtifact.getArtifactName(), generated.left()
685 return downloadArtifact(csarArtifact);
688 public Either<ImmutablePair<String, byte[]>, ResponseFormat> handleDownloadRequestById(String componentId, String artifactId, String userId, ComponentTypeEnum componentType, String parentId, String containerComponentType) {
689 // perform all validation in common flow
690 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result = handleArtifactRequest(componentId, userId, componentType, new ArtifactOperationInfo(false, false, ArtifactOperationEnum.DOWNLOAD), artifactId, null, null, null, null,
691 null, parentId, containerComponentType);
692 if (result.isRight()) {
693 return Either.right(result.right().value());
695 ArtifactDefinition artifactDefinition;
696 Either<ArtifactDefinition, Operation> insideValue = result.left().value();
697 if (insideValue.isLeft()) {
698 artifactDefinition = insideValue.left().value();
701 artifactDefinition = insideValue.right().value().getImplementationArtifact();
703 // for tosca artifacts and heat env on VF level generated on download without saving
704 if (artifactDefinition.getPayloadData() != null) {
705 return Either.left(new ImmutablePair<String, byte[]>(artifactDefinition.getArtifactName(), artifactDefinition
708 return downloadArtifact(artifactDefinition);
711 public Either<Map<String, ArtifactDefinition>, ResponseFormat> handleGetArtifactsByType(String containerComponentType, String parentId, ComponentTypeEnum componentType, String componentId, String artifactGroupType, String userId) {
713 // detect auditing type
714 Map<String, ArtifactDefinition> resMap = null;
715 Either<Map<String, ArtifactDefinition>, ResponseFormat> resultOp = null;
720 if (userId == null) {
721 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
722 log.debug("handleGetArtifactsByType - no HTTP_CSP_HEADER , component id {}", componentId);
724 resultOp = Either.right(responseFormat);
728 // check user existence
732 validateUserExists(userId, "get artifacts", false);
734 // 5. check service/resource existence
735 // 6. check service/resource check out
736 // 7. user is owner of checkout state
737 org.openecomp.sdc.be.model.Component component = null;
738 String realComponentId = componentType == ComponentTypeEnum.RESOURCE_INSTANCE ? parentId : componentId;
739 ComponentParametersView componentFilter = new ComponentParametersView();
740 componentFilter.disableAll();
741 componentFilter.setIgnoreArtifacts(false);
742 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
743 componentFilter.setIgnoreComponentInstances(false);
746 Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExistsByFilter(realComponentId, ComponentTypeEnum
747 .findByParamName(containerComponentType), componentFilter);
749 if (validateComponent.isRight()) {
750 resultOp = Either.right(validateComponent.right().value());
753 component = validateComponent.left().value();
754 Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, UPDATE_ARTIFACT_LOCK);
755 if (lockComponent.isRight()) {
757 resultOp = Either.right(lockComponent.right().value());
762 ArtifactGroupTypeEnum groupType = ArtifactGroupTypeEnum.findType(artifactGroupType);
764 if (groupType == null) {
765 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
766 log.debug("handleGetArtifactsByType - not falid groupType {} , component id {}", artifactGroupType, componentId);
768 resultOp = Either.right(responseFormat);
772 if (groupType == ArtifactGroupTypeEnum.DEPLOYMENT) {
773 List<ArtifactDefinition> list = getDeploymentArtifacts(component, componentType.getNodeType(), componentId);
774 if (list != null && !list.isEmpty()) {
775 resMap = list.stream().collect(Collectors.toMap(a -> a.getArtifactLabel(), a -> a));
778 resMap = new HashMap<>();
780 resultOp = Either.left(resMap);
785 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifactsMapStatus = getArtifacts(realComponentId, componentType
786 .getNodeType(), groupType, componentId);
787 if (artifactsMapStatus.isRight()) {
788 if (artifactsMapStatus.right().value() != StorageOperationStatus.NOT_FOUND) {
789 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
790 log.debug("handleGetArtifactsByType - not falid groupType {} , component id {}", artifactGroupType, componentId);
791 resultOp = Either.right(responseFormat);
794 resMap = new HashMap<>();
795 resultOp = Either.left(resMap);
799 resMap = artifactsMapStatus.left().value();
800 resultOp = Either.left(resMap);
807 if (resultOp == null || resultOp.isRight()) {
809 janusGraphDao.rollback();
813 janusGraphDao.commit();
816 componentType = component.getComponentType();
817 NodeTypeEnum nodeType = componentType.getNodeType();
818 graphLockOperation.unlockComponent(component.getUniqueId(), nodeType);
823 private Either<ArtifactDefinition, ResponseFormat> validateArtifact(String componentId, ComponentTypeEnum componentType, String artifactId, Component component) {
825 // check artifact existence
826 Either<ArtifactDefinition, StorageOperationStatus> artifactResult = artifactToscaOperation.getArtifactById(componentId, artifactId, componentType, component
828 if (artifactResult.isRight()) {
829 if (artifactResult.right().value().equals(StorageOperationStatus.ARTIFACT_NOT_FOUND)) {
830 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, "");
831 log.debug("addArtifact - artifact {} not found", artifactId);
832 return Either.right(responseFormat);
836 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(artifactResult
839 log.debug("addArtifact - failed to fetch artifact {}, error {}", artifactId, artifactResult.right()
841 return Either.right(responseFormat);
845 // check artifact belong to component
846 boolean found = false;
847 switch (componentType) {
850 found = checkArtifactInComponent(component, artifactId);
852 case RESOURCE_INSTANCE:
853 found = checkArtifactInResourceInstance(component, componentId, artifactId);
859 String componentName = componentType.name().toLowerCase();
860 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ARTIFACT_NOT_FOUND, componentName);
861 log.debug("addArtifact - Component artifact not found component Id {}, artifact id {}", componentId, artifactId);
862 return Either.right(responseFormat);
864 return Either.left(artifactResult.left().value());
867 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleCreate(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, User user, ComponentTypeEnum componentType,
868 org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
870 String artifactId = null;
873 Either<byte[], ResponseFormat> payloadEither = validateInput(componentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceType, operationName);
874 if (payloadEither.isRight()) {
875 return Either.right(payloadEither.right().value());
877 byte[] decodedPayload = payloadEither.left().value();
878 convertParentType(componentType);
881 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Upload Artifact - lock ");
882 if (lockComponent.isRight()) {
883 handleAuditing(auditingAction, parent, componentId, user, null, null, null, lockComponent.right()
884 .value(), componentType, null);
885 return Either.right(lockComponent.right().value());
888 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
891 resultOp = createArtifact(parent, componentId, artifactInfo, decodedPayload, user, componentType, auditingAction, interfaceType, operationName);
896 unlockComponent(resultOp, parent, inTransaction);
903 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleLink(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, User user, ComponentTypeEnum componentType,
904 Component parent, boolean shouldLock, boolean inTransaction) {
907 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Upload Artifact - lock ");
908 if (lockComponent.isRight()) {
909 handleAuditing(auditingAction, parent, componentId, user, null, null, null, lockComponent.right()
910 .value(), componentType, null);
911 return Either.right(lockComponent.right().value());
914 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
917 resultOp = createAndLinkArtifact(parent, componentId, artifactInfo, user, componentType, auditingAction);
922 unlockComponent(resultOp, parent, inTransaction);
929 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> lockComponentAndUpdateArtifact(String parentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user,
930 ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent, byte[] decodedPayload, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
932 convertParentType(componentType);
936 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, UPDATE_ARTIFACT_LOCK);
938 if (lockComponent.isRight()) {
939 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right()
940 .value(), componentType, null);
941 return Either.right(lockComponent.right().value());
945 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
947 resultOp = updateArtifactFlow(parent, parentId, artifactId, artifactInfo, user, decodedPayload, componentType, auditingAction, interfaceType, operationName);
953 unlockComponent(resultOp, parent, inTransaction);
958 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdate(String parentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, String artifactId, User user,
959 ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
961 Either<byte[], ResponseFormat> payloadEither = validateInput(parentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceType, operationName);
963 if (payloadEither.isRight()) {
964 return Either.right(payloadEither.right().value());
966 byte[] decodedPayload = payloadEither.left().value();
968 return lockComponentAndUpdateArtifact(parentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, decodedPayload, interfaceType, operationName, shouldLock, inTransaction);
971 private Either<byte[], ResponseFormat> validateInput(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType,
972 Component parent, String origMd5, String originData, String interfaceType, String operationName) {
974 Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
975 if (validateMd5.isRight()) {
976 ResponseFormat responseFormat = validateMd5.right().value();
977 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
978 return Either.right(responseFormat);
982 Either<ArtifactDefinition, ResponseFormat> validateResult = validateInput(componentId, artifactInfo, operation, artifactId, user, interfaceType, operationName, componentType, parent);
983 if (validateResult.isRight()) {
984 ResponseFormat responseFormat = validateResult.right().value();
985 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
986 return Either.right(validateResult.right().value());
989 Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
990 if (payloadEither.isRight()) {
991 ResponseFormat responseFormat = payloadEither.right().value();
992 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
993 log.debug("Error during handle payload");
994 return Either.right(responseFormat);
997 // validate heat parameters. this part must be after the parameters are
998 // extracted in "handlePayload"
999 Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers = validateAndConvertHeatParamers(artifactInfo, artifactInfo
1000 .getArtifactType());
1001 if (validateAndConvertHeatParamers.isRight()) {
1002 ResponseFormat responseFormat = validateAndConvertHeatParamers.right().value();
1003 handleAuditing(auditingAction, parent, componentId, user, artifactInfo, null, artifactId, responseFormat, componentType, null);
1004 log.debug("Error during handle payload");
1005 return Either.right(responseFormat);
1007 return payloadEither;
1010 public void handleAuditing(AuditingActionEnum auditingActionEnum, Component component, String componentId, User user, ArtifactDefinition artifactDefinition, String prevArtifactUuid, String currentArtifactUuid, ResponseFormat responseFormat,
1011 ComponentTypeEnum componentTypeEnum, String resourceInstanceName) {
1013 if (componentsUtils.isExternalApiEvent(auditingActionEnum)) {
1019 user.setUserId("UNKNOWN");
1021 handleInternalAuditEvent(auditingActionEnum, component, componentId, user, artifactDefinition, prevArtifactUuid, currentArtifactUuid, responseFormat, componentTypeEnum, resourceInstanceName);
1024 private void handleInternalAuditEvent(AuditingActionEnum auditingActionEnum, Component component, String componentId, User user, ArtifactDefinition artifactDefinition, String prevArtifactUuid, String currentArtifactUuid, ResponseFormat responseFormat, ComponentTypeEnum componentTypeEnum, String resourceInstanceName) {
1025 switch (componentTypeEnum) {
1027 Resource resource = (Resource) component;
1028 if (resource == null) {
1029 // In that case, component ID should be instead of name
1030 resource = new Resource();
1031 resource.setName(componentId);
1033 componentsUtils.auditResource(responseFormat, user, resource, resource.getName(), auditingActionEnum,
1034 ResourceVersionInfo.newBuilder()
1035 .artifactUuid(prevArtifactUuid)
1036 .build(), currentArtifactUuid, artifactDefinition);
1040 Service service = (Service) component;
1041 if (service == null) {
1042 // In that case, component ID should be instead of name
1043 service = new Service();
1044 service.setName(componentId);
1046 componentsUtils.auditComponent(responseFormat, user, service, auditingActionEnum, new ResourceCommonInfo(ComponentTypeEnum.SERVICE.getValue()),
1047 ResourceVersionInfo.newBuilder()
1048 .artifactUuid(prevArtifactUuid)
1050 ResourceVersionInfo.newBuilder()
1051 .artifactUuid(currentArtifactUuid)
1053 null, artifactDefinition, null);
1056 case RESOURCE_INSTANCE:
1057 if (resourceInstanceName == null) {
1058 resourceInstanceName = getResourceInstanceNameFromComponent(component, componentId);
1060 componentsUtils.auditComponent(responseFormat, user, component, auditingActionEnum,
1061 new ResourceCommonInfo(resourceInstanceName, ComponentTypeEnum.RESOURCE_INSTANCE.getValue()),
1062 ResourceVersionInfo.newBuilder()
1063 .artifactUuid(prevArtifactUuid)
1065 ResourceVersionInfo.newBuilder()
1066 .artifactUuid(currentArtifactUuid)
1068 null, artifactDefinition, null);
1075 private String getResourceInstanceNameFromComponent(Component component, String componentId) {
1076 ComponentInstance resourceInstance = component.getComponentInstances()
1078 .filter(p -> p.getUniqueId().equals(componentId))
1081 String resourceInstanceName = null;
1082 if (resourceInstance != null) {
1083 resourceInstanceName = resourceInstance.getName();
1085 return resourceInstanceName;
1088 private String buildAuditingArtifactData(ArtifactDefinition artifactDefinition) {
1089 StringBuilder sb = new StringBuilder();
1090 if (artifactDefinition != null) {
1091 sb.append(artifactDefinition.getArtifactGroupType().getType())
1094 .append(artifactDefinition.getArtifactLabel())
1097 .append(artifactDefinition.getArtifactType())
1099 .append(artifactDefinition.getArtifactName())
1101 .append(artifactDefinition.getTimeout())
1103 .append(artifactDefinition.getEsId());
1106 if (artifactDefinition.getArtifactVersion() != null) {
1108 sb.append(artifactDefinition.getArtifactVersion());
1114 if (artifactDefinition.getArtifactUUID() != null) {
1115 sb.append(artifactDefinition.getArtifactUUID());
1121 return sb.toString();
1124 private Either<Boolean, ResponseFormat> validateMd5(String origMd5, String originData, byte[] payload, ArtifactOperationInfo operation) {
1126 if (origMd5 != null) {
1127 String encodeBase64Str = GeneralUtility.calculateMD5Base64EncodedByString(originData);
1128 if (!encodeBase64Str.equals(origMd5)) {
1129 log.debug("The calculated md5 is different then the received one");
1130 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_MD5));
1134 if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()) && payload != null && payload.length != 0) {
1135 log.debug("Missing md5 header during artifact create");
1136 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_MD5));
1139 if (payload != null && payload.length != 0) {
1140 log.debug("Cannot have payload while md5 header is missing");
1141 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1144 return Either.left(true);
1147 private Either<ArtifactDefinition, ResponseFormat> validateInput(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, String artifactId, User user, String interfaceName, String operationName,
1148 ComponentTypeEnum componentType, Component parentComponent) {
1150 Either<ArtifactDefinition, ResponseFormat> artifactById = findArtifactOnParentComponent(parentComponent, componentType, componentId, operation, artifactId);
1151 if (artifactById.isRight()) {
1152 return Either.right(artifactById.right().value());
1154 ArtifactDefinition currentArtifactInfo = artifactById.left().value();
1156 ignoreUnupdateableFieldsInUpdate(operation, artifactInfo, currentArtifactInfo);
1157 Either<Boolean, ResponseFormat> validateInformationalArtifactRes = validateInformationalArtifact(artifactInfo, parentComponent);
1158 if (validateInformationalArtifactRes.isRight()) {
1159 return Either.right(validateInformationalArtifactRes.right().value());
1161 Either<Boolean, ResponseFormat> validateAndSetArtifactname = validateAndSetArtifactname(artifactInfo);
1162 if (validateAndSetArtifactname.isRight()) {
1163 return Either.right(validateAndSetArtifactname.right().value());
1165 if (operationName != null && interfaceName != null) {
1166 operationName = operationName.toLowerCase();
1167 interfaceName = interfaceName.toLowerCase();
1169 Either<ActionStatus, ResponseFormat> logicalNameStatus = handleArtifactLabel(componentId, parentComponent, operation, artifactInfo, operationName, componentType);
1170 if (logicalNameStatus.isRight()) {
1171 return Either.right(logicalNameStatus.right().value());
1173 // This is a patch to block possibility of updating service api fields
1174 // through other artifacts flow
1176 ArtifactGroupTypeEnum artifactGroupType = operationName != null ? ArtifactGroupTypeEnum.LIFE_CYCLE : ArtifactGroupTypeEnum.INFORMATIONAL;
1177 if (!ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
1178 checkAndSetUnUpdatableFields(user, artifactInfo, currentArtifactInfo, artifactGroupType);
1181 checkCreateFields(user, artifactInfo, artifactGroupType);
1184 composeArtifactId(componentId, artifactId, artifactInfo, interfaceName, operationName);
1185 if (currentArtifactInfo != null) {
1186 artifactInfo.setMandatory(currentArtifactInfo.getMandatory());
1189 // artifactGroupType is not allowed to be updated
1190 if (!ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
1191 Either<ArtifactDefinition, ResponseFormat> validateGroupType = validateOrSetArtifactGroupType(artifactInfo, currentArtifactInfo);
1192 if (validateGroupType.isRight()) {
1193 return Either.right(validateGroupType.right().value());
1196 NodeTypeEnum parentType = convertParentType(componentType);
1198 boolean isCreate = ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum());
1200 if (isDeploymentArtifact(artifactInfo)) {
1201 Either<Boolean, ResponseFormat> deploymentValidationResult = validateDeploymentArtifact(parentComponent, componentId, isCreate, artifactInfo, currentArtifactInfo, parentType);
1202 if (deploymentValidationResult.isRight()) {
1203 return Either.right(deploymentValidationResult.right().value());
1207 artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
1210 Either<Boolean, ResponseFormat> descriptionResult = validateAndCleanDescription(artifactInfo);
1211 if (descriptionResult.isRight()) {
1212 return Either.right(descriptionResult.right().value());
1215 if (currentArtifactInfo != null && currentArtifactInfo.getArtifactGroupType()
1216 .equals(ArtifactGroupTypeEnum.SERVICE_API)) {
1217 Either<ActionStatus, ResponseFormat> validateServiceApiType = validateArtifactType(user.getUserId(), artifactInfo, parentType);
1218 if (validateServiceApiType.isRight()) {
1219 return Either.right(validateServiceApiType.right().value());
1221 // Change of type is not allowed and should be ignored
1223 artifactInfo.setArtifactType(ARTIFACT_TYPE_OTHER);
1225 Either<Boolean, ResponseFormat> validateUrl = validateAndServiceApiUrl(artifactInfo);
1226 if (validateUrl.isRight()) {
1227 return Either.right(validateUrl.right().value());
1230 Either<Boolean, ResponseFormat> validateUpdate = validateFirstUpdateHasPayload(artifactInfo, currentArtifactInfo);
1231 if (validateUpdate.isRight()) {
1232 log.debug("serviceApi first update cnnot be without payload.");
1233 return Either.right(validateUpdate.right().value());
1237 Either<ActionStatus, ResponseFormat> validateArtifactType = validateArtifactType(user.getUserId(), artifactInfo, parentType);
1238 if (validateArtifactType.isRight()) {
1239 return Either.right(validateArtifactType.right().value());
1241 if (artifactInfo.getApiUrl() != null) {
1242 artifactInfo.setApiUrl(null);
1243 log.error("Artifact URL cannot be set through this API - ignoring");
1246 if (artifactInfo.getServiceApi() != null && artifactInfo.getServiceApi()) {
1247 artifactInfo.setServiceApi(false);
1248 log.error("Artifact service API flag cannot be changed - ignoring");
1252 return Either.left(artifactInfo);
1255 private void ignoreUnupdateableFieldsInUpdate(ArtifactOperationInfo operation, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifactInfo) {
1256 if (operation.getArtifactOperationEnum().equals(ArtifactOperationEnum.UPDATE)) {
1257 artifactInfo.setArtifactType(currentArtifactInfo.getArtifactType());
1258 artifactInfo.setArtifactGroupType(currentArtifactInfo.getArtifactGroupType());
1259 artifactInfo.setArtifactLabel(currentArtifactInfo.getArtifactLabel());
1263 private Either<ArtifactDefinition, ResponseFormat> findArtifactOnParentComponent(Component parentComponent, ComponentTypeEnum componentType, String parentId, ArtifactOperationInfo operation, String artifactId) {
1265 Either<ArtifactDefinition, ResponseFormat> result = null;
1266 ArtifactDefinition foundArtifact = null;
1267 if (StringUtils.isNotEmpty(artifactId)) {
1268 foundArtifact = findArtifact(parentComponent, componentType, parentId, artifactId);
1270 if (foundArtifact != null && ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
1271 log.debug("Artifact {} already exist", artifactId);
1272 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, foundArtifact.getArtifactLabel()));
1274 if (foundArtifact == null && !ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
1275 log.debug("The artifact {} was not found on parent {}. ", artifactId, parentId);
1276 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ""));
1278 if (result == null) {
1279 result = Either.left(foundArtifact);
1284 private ArtifactDefinition findArtifact(Component parentComponent, ComponentTypeEnum componentType, String parentId, String artifactId) {
1285 ArtifactDefinition foundArtifact;
1286 if (parentComponent.getUniqueId().equals(parentId)) {
1287 foundArtifact = artifactsResolver.findArtifactOnComponent(parentComponent, componentType, artifactId);
1290 ComponentInstance instance = findComponentInstance(parentId, parentComponent);
1291 foundArtifact = artifactsResolver.findArtifactOnComponentInstance(instance, artifactId);
1293 return foundArtifact;
1296 private Either<Boolean, ResponseFormat> validateInformationalArtifact(ArtifactDefinition artifactInfo, Component parentComponent) {
1297 ComponentTypeEnum parentComponentType = parentComponent.getComponentType();
1298 ArtifactGroupTypeEnum groupType = artifactInfo.getArtifactGroupType();
1299 Either<Boolean, ResponseFormat> validationResult = Either.left(true);
1300 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
1301 if (artifactType == null) {
1302 validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
1303 .getArtifactType()));
1305 else if (parentComponentType == ComponentTypeEnum.RESOURCE && groupType == ArtifactGroupTypeEnum.INFORMATIONAL) {
1306 String artifactTypeName = artifactType.getType();
1307 ResourceTypeEnum parentResourceType = ((Resource) parentComponent).getResourceType();
1308 Map<String, ArtifactTypeConfig> resourceInformationalArtifacts = ConfigurationManager.getConfigurationManager()
1310 .getResourceInformationalArtifacts();
1311 Set<String> validArtifactTypes = resourceInformationalArtifacts.keySet();
1312 if (!validArtifactTypes.contains(artifactTypeName)) {
1313 validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactTypeName));
1316 List<String> validResourceType = resourceInformationalArtifacts.get(artifactTypeName)
1317 .getValidForResourceTypes();
1318 if (!validResourceType.contains(parentResourceType.name())) {
1319 validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactTypeName));
1323 return validationResult;
1326 private NodeTypeEnum convertParentType(ComponentTypeEnum componentType) {
1327 if (componentType.equals(ComponentTypeEnum.RESOURCE)) {
1328 return NodeTypeEnum.Resource;
1330 else if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) {
1331 return NodeTypeEnum.ResourceInstance;
1334 return NodeTypeEnum.Service;
1338 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete(String parentId, String artifactId, User user, AuditingActionEnum auditingAction, ComponentTypeEnum componentType, Component parent,
1339 boolean shouldLock, boolean inTransaction) {
1341 NodeTypeEnum parentType = convertParentType(componentType);
1342 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
1343 Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> getArtifactRes = null;
1344 ArtifactDefinition foundArtifact = null;
1345 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
1346 Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getContainerRes = null;
1347 org.openecomp.sdc.be.model.Component fetchedContainerComponent = null;
1348 boolean isDuplicated = false;
1350 Either<Boolean, StorageOperationStatus> needCloneRes = null;
1353 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Delete Artifact - lock resource: ");
1354 if (lockComponent.isRight()) {
1355 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right()
1356 .value(), componentType, null);
1357 resultOp = Either.right(lockComponent.right().value());
1360 if (resultOp == null) {
1361 log.debug("Going to fetch the container component {}. ", parent.getUniqueId());
1362 getContainerRes = toscaOperationFacade.getToscaElement(parent.getUniqueId());
1363 if (getContainerRes.isRight()) {
1364 log.debug("Failed to fetch the container component {}. ", parentId);
1365 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(getContainerRes
1367 .value()), artifactId);
1368 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1369 resultOp = Either.right(responseFormat);
1372 if (resultOp == null) {
1373 fetchedContainerComponent = getContainerRes.left().value();
1374 log.debug("Going to find the artifact {} on the component {}", artifactId, fetchedContainerComponent.getUniqueId());
1375 getArtifactRes = findArtifact(artifactId, fetchedContainerComponent, parentId, componentType);
1376 if (getArtifactRes.isRight()) {
1377 log.debug("Failed to find the artifact {} belonging to {} on the component {}", artifactId, parentId, fetchedContainerComponent
1379 responseFormat = componentsUtils.getResponseFormatByArtifactId(getArtifactRes.right()
1380 .value(), artifactId);
1381 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1382 resultOp = Either.right(responseFormat);
1385 foundArtifact = getArtifactRes.left().value().getLeft();
1386 esId = foundArtifact.getEsId();
1389 if (resultOp == null && StringUtils.isNotEmpty(esId)) {
1390 needCloneRes = artifactToscaOperation.isCloneNeeded(parent.getUniqueId(), foundArtifact, convertParentType(parent
1391 .getComponentType()));
1392 if (needCloneRes.isRight()) {
1393 log.debug(FAILED_UPDATE_ARTIFACT, artifactId, parentId);
1394 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(needCloneRes
1396 .value()), foundArtifact.getArtifactDisplayName());
1397 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1398 resultOp = Either.right(responseFormat);
1401 boolean isNeedToDeleteArtifactFromDB = true;
1402 if (resultOp == null) {
1404 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1405 String instanceId = parentId;
1406 Either<Boolean, ActionStatus> isOnlyResourceInstanceArtifact = isArtifactOnlyResourceInstanceArtifact(foundArtifact, fetchedContainerComponent, instanceId);
1408 if (isOnlyResourceInstanceArtifact.isRight()) {
1409 log.debug(FAILED_UPDATE_ARTIFACT, artifactId, parentId);
1410 responseFormat = componentsUtils.getResponseFormatByArtifactId(isOnlyResourceInstanceArtifact.right()
1411 .value(), foundArtifact
1412 .getArtifactDisplayName());
1413 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1414 return Either.right(responseFormat);
1416 isNeedToDeleteArtifactFromDB = isOnlyResourceInstanceArtifact.left().value();
1419 Either<ArtifactDataDefinition, StorageOperationStatus> updatedArtifactRes = deleteOrUpdateArtifactOnGraph(parent, parentId, artifactId, parentType, foundArtifact, needCloneRes
1422 if (updatedArtifactRes.isRight()) {
1423 log.debug(FAILED_UPDATE_ARTIFACT, artifactId, parentId);
1424 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updatedArtifactRes
1426 .value()), foundArtifact.getArtifactDisplayName());
1427 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1428 resultOp = Either.right(responseFormat);
1431 isDuplicated = updatedArtifactRes.left().value().getDuplicated();
1435 if (resultOp == null && (!needCloneRes.left().value() && !isDuplicated) && isNeedToDeleteArtifactFromDB) {
1436 log.debug("Going to delete the artifact {} from the database. ", artifactId);
1437 CassandraOperationStatus cassandraStatus = artifactCassandraDao.deleteArtifact(esId);
1438 if (cassandraStatus != CassandraOperationStatus.OK) {
1439 log.debug("Failed to delete the artifact {} from the database. ", artifactId);
1440 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(componentsUtils.convertToStorageOperationStatus(cassandraStatus)), foundArtifact
1441 .getArtifactDisplayName());
1442 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1443 resultOp = Either.right(responseFormat);
1446 if (resultOp == null && componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1448 List<GroupInstance> updatedGroupInstances = getUpdatedGroupInstances(artifactId, foundArtifact, getArtifactRes
1452 .getGroupInstances());
1453 if (CollectionUtils.isNotEmpty(updatedGroupInstances)) {
1454 Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(fetchedContainerComponent, parentId, updatedGroupInstances);
1455 if (status.isRight()) {
1456 log.debug(FAILED_UPDATE_GROUPS, fetchedContainerComponent.getUniqueId());
1457 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status
1459 .value()), foundArtifact.getArtifactDisplayName());
1460 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1461 resultOp = Either.right(responseFormat);
1465 if (resultOp == null && componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1466 StorageOperationStatus status = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentType);
1467 if (status != StorageOperationStatus.OK) {
1468 log.debug("Failed to generate new customization UUID for the component instance {}. ", parentId);
1469 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status), foundArtifact
1470 .getArtifactDisplayName());
1471 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1472 resultOp = Either.right(responseFormat);
1475 if (resultOp == null && componentType != ComponentTypeEnum.RESOURCE_INSTANCE) {
1476 List<GroupDataDefinition> updatedGroups = getUpdatedGroups(artifactId, foundArtifact, fetchedContainerComponent
1478 if (CollectionUtils.isNotEmpty(updatedGroups)) {
1479 Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(fetchedContainerComponent, updatedGroups);
1480 if (status.isRight()) {
1481 log.debug(FAILED_UPDATE_GROUPS, fetchedContainerComponent.getUniqueId());
1482 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status
1484 .value()), foundArtifact.getArtifactDisplayName());
1485 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1486 resultOp = Either.right(responseFormat);
1490 if (resultOp == null) {
1491 resultOp = Either.left(Either.left(foundArtifact));
1492 handleAuditing(auditingAction, parent, parentId, user, foundArtifact, null, artifactId, responseFormat, componentType, null);
1498 unlockComponent(resultOp, parent, inTransaction);
1503 private Either<Boolean, ActionStatus> isArtifactOnlyResourceInstanceArtifact(ArtifactDefinition foundArtifact, Component parent, String instanceId) {
1504 Either<Boolean, ActionStatus> result = Either.left(true);
1505 ComponentInstance foundInstance = null;
1506 Optional<ComponentInstance> componentInstanceOpt = parent.getComponentInstances()
1508 .filter(i -> i.getUniqueId().equals(instanceId))
1510 if (!componentInstanceOpt.isPresent()) {
1511 result = Either.right(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER);
1514 foundInstance = componentInstanceOpt.get();
1515 String componentUid = foundInstance.getComponentUid();
1516 Either<Component, StorageOperationStatus> getContainerRes = toscaOperationFacade.getToscaElement(componentUid);
1517 if (getContainerRes.isRight()) {
1518 log.debug("Failed to fetch the container component {}. ", componentUid);
1519 return Either.right(componentsUtils.convertFromStorageResponse(getContainerRes.right().value()));
1521 Component origComponent = getContainerRes.left().value();
1522 Map<String, ArtifactDefinition> deploymentArtifacts = origComponent.getDeploymentArtifacts();
1523 if (deploymentArtifacts != null && !deploymentArtifacts.isEmpty()) {
1524 Optional<String> op = deploymentArtifacts.keySet()
1526 .filter(a -> a.equals(foundArtifact.getArtifactLabel()))
1528 if (op.isPresent()) {
1529 return Either.left(false);
1532 Map<String, ArtifactDefinition> artifacts = origComponent.getArtifacts();
1533 if (artifacts != null && !artifacts.isEmpty()) {
1534 Optional<String> op = artifacts.keySet()
1536 .filter(a -> a.equals(foundArtifact.getArtifactLabel()))
1538 if (op.isPresent()) {
1539 return Either.left(false);
1547 private List<GroupDataDefinition> getUpdatedGroups(String artifactId, ArtifactDefinition foundArtifact, List<GroupDefinition> groups) {
1548 List<GroupDataDefinition> updatedGroups = new ArrayList<>();
1549 boolean isUpdated = false;
1550 if (groups != null) {
1551 for (GroupDefinition group : groups) {
1553 if (CollectionUtils.isNotEmpty(group.getArtifacts()) && group.getArtifacts().contains(artifactId)) {
1554 group.getArtifacts().remove(artifactId);
1557 if (CollectionUtils.isNotEmpty(group.getArtifactsUuid()) && group.getArtifactsUuid()
1558 .contains(foundArtifact.getArtifactUUID())) {
1559 group.getArtifactsUuid().remove(foundArtifact.getArtifactUUID());
1563 updatedGroups.add(group);
1567 return updatedGroups;
1570 private List<GroupInstance> getUpdatedGroupInstances(String artifactId, ArtifactDefinition foundArtifact, List<GroupInstance> groupInstances) {
1571 List<GroupInstance> updatedGroupInstances = new ArrayList<>();
1572 if (CollectionUtils.isNotEmpty(groupInstances)) {
1573 boolean isUpdated = false;
1574 for (GroupInstance groupInstance : groupInstances) {
1576 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifacts()) && groupInstance.getGroupInstanceArtifacts()
1577 .contains(artifactId)) {
1578 groupInstance.getGroupInstanceArtifacts().remove(artifactId);
1581 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifactsUuid()) && groupInstance.getGroupInstanceArtifactsUuid()
1582 .contains(foundArtifact
1583 .getArtifactUUID())) {
1584 groupInstance.getGroupInstanceArtifactsUuid().remove(foundArtifact.getArtifactUUID());
1588 updatedGroupInstances.add(groupInstance);
1592 return updatedGroupInstances;
1595 private Either<ArtifactDataDefinition, StorageOperationStatus> deleteOrUpdateArtifactOnGraph(Component component, String parentId, String artifactId, NodeTypeEnum parentType, ArtifactDefinition foundArtifact, Boolean cloneIsNeeded) {
1597 Either<ArtifactDataDefinition, StorageOperationStatus> result;
1598 boolean isMandatory = foundArtifact.getMandatory() || foundArtifact.getServiceApi();
1599 String componentId = component.getUniqueId();
1600 String instanceId = componentId.equals(parentId) ? null : parentId;
1602 log.debug("Going to update mandatory artifact {} from the component {}", artifactId, parentId);
1603 resetMandatoryArtifactFields(foundArtifact);
1604 result = artifactToscaOperation.updateArtifactOnGraph(componentId, foundArtifact, parentType, artifactId, instanceId, true, true);
1606 else if (cloneIsNeeded) {
1607 log.debug("Going to clone artifacts and to delete the artifact {} from the component {}", artifactId, parentId);
1608 result = artifactToscaOperation.deleteArtifactWithCloningOnGraph(componentId, foundArtifact, parentType, instanceId, false);
1611 log.debug("Going to delete the artifact {} from the component {}", artifactId, parentId);
1612 result = artifactToscaOperation.removeArtifactOnGraph(foundArtifact, componentId, instanceId, parentType, false);
1617 private Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> findArtifact(String artifactId, Component fetchedContainerComponent, String parentId, ComponentTypeEnum componentType) {
1619 Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> result = null;
1620 Map<String, ArtifactDefinition> artifacts = new HashMap<>();
1621 ComponentInstance foundInstance = null;
1622 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE && StringUtils.isNotEmpty(parentId)) {
1623 Optional<ComponentInstance> componentInstanceOpt = fetchedContainerComponent.getComponentInstances()
1625 .filter(i -> i.getUniqueId()
1628 if (!componentInstanceOpt.isPresent()) {
1629 result = Either.right(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER);
1632 foundInstance = componentInstanceOpt.get();
1633 fetchArtifactsFromInstance(artifactId, artifacts, foundInstance);
1637 fetchArtifactsFromComponent(artifactId, fetchedContainerComponent, artifacts);
1639 if (result == null) {
1640 if (artifacts.containsKey(artifactId)) {
1641 result = Either.left(new ImmutablePair<>(artifacts.get(artifactId), foundInstance));
1644 result = Either.right(ActionStatus.ARTIFACT_NOT_FOUND);
1650 private void fetchArtifactsFromComponent(String artifactId, Component component, Map<String, ArtifactDefinition> artifacts) {
1651 Map<String, ArtifactDefinition> currArtifacts;
1652 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getDeploymentArtifacts())) {
1653 currArtifacts = component.getDeploymentArtifacts()
1656 .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1657 if (MapUtils.isNotEmpty(currArtifacts)) {
1658 artifacts.putAll(currArtifacts);
1661 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getArtifacts())) {
1662 currArtifacts = component.getArtifacts()
1665 .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1666 if (MapUtils.isNotEmpty(currArtifacts)) {
1667 artifacts.putAll(currArtifacts);
1670 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getArtifacts())) {
1671 currArtifacts = component.getToscaArtifacts()
1674 .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1675 if (MapUtils.isNotEmpty(currArtifacts)) {
1676 artifacts.putAll(currArtifacts);
1681 private void fetchArtifactsFromInstance(String artifactId, Map<String, ArtifactDefinition> artifacts, ComponentInstance instance) {
1682 Map<String, ArtifactDefinition> currArtifacts;
1683 if (MapUtils.isNotEmpty(instance.getDeploymentArtifacts())) {
1684 currArtifacts = instance.getDeploymentArtifacts()
1687 .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1688 if (MapUtils.isNotEmpty(currArtifacts)) {
1689 artifacts.putAll(currArtifacts);
1692 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(instance.getArtifacts())) {
1693 currArtifacts = instance.getArtifacts()
1696 .collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1697 if (MapUtils.isNotEmpty(currArtifacts)) {
1698 artifacts.putAll(currArtifacts);
1703 private void resetMandatoryArtifactFields(ArtifactDefinition fetchedArtifact) {
1704 if (fetchedArtifact != null) {
1705 log.debug("Going to reset mandatory artifact {} fields. ", fetchedArtifact.getUniqueId());
1706 fetchedArtifact.setEsId(null);
1707 fetchedArtifact.setArtifactName(null);
1708 fetchedArtifact.setDescription(null);
1709 fetchedArtifact.setApiUrl(null);
1710 fetchedArtifact.setArtifactChecksum(null);
1711 nodeTemplateOperation.setDefaultArtifactTimeout(fetchedArtifact.getArtifactGroupType(), fetchedArtifact);
1712 fetchedArtifact.setArtifactUUID(null);
1713 long time = System.currentTimeMillis();
1714 fetchedArtifact.setPayloadUpdateDate(time);
1715 fetchedArtifact.setHeatParameters(null);
1716 fetchedArtifact.setHeatParamsUpdateDate(null);
1720 private StorageOperationStatus generateCustomizationUUIDOnInstance(String componentId, String instanceId, ComponentTypeEnum componentType) {
1721 StorageOperationStatus error = StorageOperationStatus.OK;
1722 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1723 log.debug("Need to re-generate customization UUID for instance {}", instanceId);
1724 error = toscaOperationFacade.generateCustomizationUUIDOnInstance(componentId, instanceId);
1729 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDownload(String componentId, String artifactId, User user, AuditingActionEnum auditingAction, ComponentTypeEnum componentType,
1731 Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(componentId, artifactId, componentType, parent
1733 if (artifactById.isRight()) {
1734 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(artifactById.right().value());
1735 log.debug("Error when getting artifact info by id{}, error: {}", artifactId, actionStatus);
1736 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(actionStatus, "");
1737 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
1738 return Either.right(responseFormat);
1740 ArtifactDefinition artifactDefinition = artifactById.left().value();
1741 if (artifactDefinition == null) {
1742 log.debug("Empty artifact definition returned from DB by artifact id {}", artifactId);
1743 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, "");
1744 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
1745 return Either.right(responseFormat);
1748 Either<ArtifactDefinition, Operation> insideEither = Either.left(artifactDefinition);
1749 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
1750 handleAuditing(auditingAction, parent, componentId, user, artifactDefinition, null, artifactId, responseFormat, componentType, null);
1751 return Either.left(insideEither);
1754 private Either<ActionStatus, ResponseFormat> handleArtifactLabel(String componentId, Component parentComponent, ArtifactOperationInfo operation, ArtifactDefinition artifactInfo, String operationName,
1755 ComponentTypeEnum componentType) {
1757 String artifactLabel = artifactInfo.getArtifactLabel();
1758 if (operationName == null && (artifactInfo.getArtifactLabel() == null || artifactInfo.getArtifactLabel()
1760 BeEcompErrorManager.getInstance()
1761 .logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel");
1762 log.debug("missing artifact logical name for component {}", componentId);
1763 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_LABEL));
1765 if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum()) && !artifactInfo.getMandatory()) {
1767 if (operationName != null) {
1768 if (artifactInfo.getArtifactLabel() != null && !operationName.equals(artifactInfo.getArtifactLabel())) {
1769 log.debug("artifact label cannot be set {}", artifactLabel);
1770 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_LOGICAL_NAME_CANNOT_BE_CHANGED));
1773 artifactLabel = operationName;
1776 String displayName = artifactInfo.getArtifactDisplayName();
1777 if (displayName == null || displayName.isEmpty()) {
1778 displayName = artifactLabel;
1780 displayName = ValidationUtils.cleanArtifactDisplayName(displayName);
1781 artifactInfo.setArtifactDisplayName(displayName);
1783 if (!ValidationUtils.validateArtifactLabel(artifactLabel)) {
1784 log.debug("Invalid format form Artifact label : {}", artifactLabel);
1785 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1787 artifactLabel = ValidationUtils.normalizeArtifactLabel(artifactLabel);
1789 if (artifactLabel.isEmpty()) {
1790 log.debug("missing normalized artifact logical name for component {}", componentId);
1791 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_LABEL));
1794 if (!ValidationUtils.validateArtifactLabelLength(artifactLabel)) {
1795 log.debug("Invalid lenght form Artifact label : {}", artifactLabel);
1796 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_LABEL, String
1797 .valueOf(ValidationUtils.ARTIFACT_LABEL_LENGTH)));
1799 if (!validateLabelUniqueness(componentId, parentComponent, artifactLabel, componentType)) {
1800 log.debug("Non unique Artifact label : {}", artifactLabel);
1801 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactLabel));
1804 artifactInfo.setArtifactLabel(artifactLabel);
1806 return Either.left(ActionStatus.OK);
1809 private boolean validateLabelUniqueness(String componentId, Component parentComponent, String artifactLabel, ComponentTypeEnum componentType) {
1810 boolean isUnique = true;
1811 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifacts;
1812 if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) {
1813 artifacts = artifactToscaOperation.getAllInstanceArtifacts(parentComponent.getUniqueId(), componentId);
1816 artifacts = artifactToscaOperation.getArtifacts(componentId);
1819 if (artifacts.isLeft()) {
1820 for (String label : artifacts.left().value().keySet()) {
1821 if (label.equals(artifactLabel)) {
1827 if (componentType.equals(ComponentTypeEnum.RESOURCE)) {
1828 Either<Map<String, InterfaceDefinition>, StorageOperationStatus> allInterfacesOfResource = interfaceLifecycleOperation
1829 .getAllInterfacesOfResource(componentId, true, true);
1830 if (allInterfacesOfResource.isLeft()) {
1831 for (InterfaceDefinition interace : allInterfacesOfResource.left().value().values()) {
1832 for (Operation operation : interace.getOperationsMap().values()) {
1833 if (operation.getImplementation() != null && operation.getImplementation()
1835 .equals(artifactLabel)) {
1846 boolean validateArtifactNameUniqueness(String componentId, Component parentComponent, ArtifactDefinition artifactInfo,
1847 ComponentTypeEnum componentType) {
1848 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifacts = getArtifacts(componentType,
1849 parentComponent, componentId, artifactInfo.getArtifactGroupType());
1850 String artifactName = artifactInfo.getArtifactName();
1851 if (artifacts.isLeft() && Objects.nonNull(artifacts.left().value())){
1852 if (artifacts.left().value().values().stream()
1853 .anyMatch(ad -> artifactName.equals(ad.getArtifactName())
1854 //check whether it is the same artifact we hold (by label)
1855 && !artifactInfo.getArtifactLabel().equals(ad.getArtifactLabel()))){
1859 if (ComponentTypeEnum.RESOURCE.equals(componentType)) {
1860 return isUniqueArtifactNameInResourceInterfaces(componentId, artifactName, artifactInfo.getArtifactLabel());
1865 private boolean isUniqueArtifactNameInResourceInterfaces(String componentId, String artifactName, String artifactLabel) {
1866 Either<Map<String, InterfaceDefinition>, StorageOperationStatus> allInterfacesOfResource = interfaceLifecycleOperation
1867 .getAllInterfacesOfResource(componentId, true, true);
1869 if (allInterfacesOfResource.isLeft() && Objects.nonNull(allInterfacesOfResource)){
1870 return !allInterfacesOfResource.left().value()
1872 .stream().map(InterfaceDefinition :: getOperationsMap)
1873 .flatMap(map -> map.values().stream())
1874 .map(OperationDataDefinition::getImplementation)
1875 .filter(Objects::nonNull)
1876 .anyMatch(add -> artifactName.equals(add.getArtifactName())
1877 && !artifactLabel.equals(add.getArtifactLabel()));
1882 private boolean isUniqueLabelInResourceInterfaces(String componentId, String artifactLabel) {
1883 Either<Map<String, InterfaceDefinition>, StorageOperationStatus> allInterfacesOfResource = interfaceLifecycleOperation
1884 .getAllInterfacesOfResource(componentId, true, true);
1886 if (allInterfacesOfResource.isLeft()){
1887 return !allInterfacesOfResource.left().value()
1889 .stream().map(InterfaceDefinition :: getOperationsMap)
1890 .flatMap(map -> map.values().stream())
1891 .map(OperationDataDefinition::getImplementation)
1892 .filter(Objects::nonNull)
1893 .anyMatch(add -> artifactLabel.equals(add.getArtifactLabel()));
1898 private Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(ComponentTypeEnum componentType, Component parentComponent,
1899 String componentId, ArtifactGroupTypeEnum artifactGroupType) {
1900 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifactsResponse;
1901 if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) {
1902 artifactsResponse = artifactToscaOperation.getAllInstanceArtifacts(parentComponent.getUniqueId(), componentId);
1905 artifactsResponse = artifactToscaOperation.getArtifacts(componentId);
1907 if (artifactsResponse.isRight() && artifactsResponse.right().value().equals(StorageOperationStatus.NOT_FOUND)) {
1908 log.debug("failed to retrieve artifacts for {} ", componentId);
1909 return Either.right(artifactsResponse.right().value());
1911 return Either.left(artifactsResponse.left().value().entrySet()
1913 .filter(x -> artifactGroupType.equals(x.getValue().getArtifactGroupType()))
1914 .collect(Collectors.toMap(Entry::getKey, Entry::getValue)));
1917 private List<String> getListOfArtifactName(Map<String, ArtifactDefinition> artifacts) {
1918 return artifacts.entrySet()
1920 .map(x -> x.getValue().getArtifactName())
1921 .collect(Collectors.toList());
1924 // ***************************************************************
1926 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> createAndLinkArtifact(org.openecomp.sdc.be.model.Component parent, String parentId, ArtifactDefinition artifactInfo, User user,
1927 ComponentTypeEnum componentTypeEnum, AuditingActionEnum auditingActionEnum) {
1928 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
1929 Either<ArtifactDefinition, Operation> insideEither = null;
1930 ComponentInstance foundInstance = findComponentInstance(parentId, parent);
1931 String instanceId = null;
1932 String instanceName = null;
1933 if (foundInstance != null) {
1934 instanceId = foundInstance.getUniqueId();
1935 instanceName = foundInstance.getName();
1937 boolean isLeft = false;
1938 String artifactUniqueId = null;
1939 StorageOperationStatus error = null;
1940 // information/deployment/api aritfacts
1941 log.trace("Try to create entry on graph");
1942 NodeTypeEnum nodeType = convertParentType(componentTypeEnum);
1943 Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.addArifactToComponent(artifactInfo, parent
1944 .getUniqueId(), nodeType, true, instanceId);
1946 isLeft = result.isLeft();
1948 artifactUniqueId = result.left().value().getUniqueId();
1949 result.left().value();
1951 insideEither = Either.left(result.left().value());
1952 resultOp = Either.left(insideEither);
1954 error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentTypeEnum);
1955 if (error != StorageOperationStatus.OK) {
1961 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
1962 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, artifactUniqueId, artifactUniqueId, responseFormat, componentTypeEnum, instanceName);
1966 log.debug("Failed to create entry on graph for artifact {}", artifactInfo.getArtifactName());
1967 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(error), artifactInfo
1968 .getArtifactDisplayName());
1969 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, instanceName);
1970 resultOp = Either.right(responseFormat);
1976 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> createArtifact(org.openecomp.sdc.be.model.Component parent, String parentId, ArtifactDefinition artifactInfo, byte[] decodedPayload, User user,
1977 ComponentTypeEnum componentTypeEnum, AuditingActionEnum auditingActionEnum, String interfaceType, String operationName) {
1979 ESArtifactData artifactData = createEsArtifactData(artifactInfo, decodedPayload);
1980 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
1981 Either<ArtifactDefinition, Operation> insideEither = null;
1982 ComponentInstance foundInstance = findComponentInstance(parentId, parent);
1983 String instanceId = null;
1984 String instanceName = null;
1985 if (foundInstance != null) {
1986 if (foundInstance.isArtifactExists(artifactInfo.getArtifactGroupType(), artifactInfo.getArtifactLabel())) {
1987 log.debug("Failed to create artifact, already exists");
1988 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactInfo
1989 .getArtifactLabel());
1990 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, artifactInfo.getUniqueId(), responseFormat, componentTypeEnum, foundInstance
1992 resultOp = Either.right(responseFormat);
1996 instanceId = foundInstance.getUniqueId();
1997 instanceName = foundInstance.getName();
1999 if (artifactData == null) {
2000 BeEcompErrorManager.getInstance().logBeDaoSystemError("Upload Artifact");
2001 log.debug("Failed to create artifact object for ES.");
2002 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
2003 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, null);
2004 resultOp = Either.right(responseFormat);
2008 // set on graph object id of artifact in ES!
2009 artifactInfo.setEsId(artifactData.getId());
2011 boolean isLeft = false;
2012 String artifactUniqueId = null;
2013 StorageOperationStatus error = null;
2014 if (interfaceType != null && operationName != null) {
2015 // lifecycle artifact
2016 Operation operation = convertToOperation(artifactInfo, operationName);
2018 Either<Operation, StorageOperationStatus> result = interfaceLifecycleOperation.updateInterfaceOperation(parentId, interfaceType, operationName, operation);
2020 isLeft = result.isLeft();
2022 artifactUniqueId = result.left().value().getImplementation().getUniqueId();
2023 result.left().value().getImplementation();
2025 insideEither = Either.right(result.left().value());
2026 resultOp = Either.left(insideEither);
2029 error = result.right().value();
2033 // information/deployment/api aritfacts
2034 log.trace("Try to create entry on graph");
2035 NodeTypeEnum nodeType = convertParentType(componentTypeEnum);
2036 Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.addArifactToComponent(artifactInfo, parent
2037 .getUniqueId(), nodeType, true, instanceId);
2039 isLeft = result.isLeft();
2041 artifactUniqueId = result.left().value().getUniqueId();
2042 artifactData.setId(result.left().value().getEsId());
2043 insideEither = Either.left(result.left().value());
2044 resultOp = Either.left(insideEither);
2046 error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentTypeEnum);
2047 if (error != StorageOperationStatus.OK) {
2053 error = result.right().value();
2057 boolean res = saveArtifacts(artifactData, parentId);
2060 log.debug(ARTIFACT_SAVED, artifactUniqueId);
2062 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
2063 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, artifactUniqueId, artifactUniqueId, responseFormat, componentTypeEnum, instanceName);
2067 BeEcompErrorManager.getInstance().logBeDaoSystemError("Upload Artifact");
2068 log.debug(FAILED_SAVE_ARTIFACT);
2069 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
2070 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, artifactUniqueId, responseFormat, componentTypeEnum, instanceName);
2072 resultOp = Either.right(responseFormat);
2077 log.debug("Failed to create entry on graph for artifact {}", artifactInfo.getArtifactName());
2078 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(error), artifactInfo
2079 .getArtifactDisplayName());
2080 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, instanceName);
2081 resultOp = Either.right(responseFormat);
2087 private ComponentInstance findComponentInstance(String componentInstanceId, Component containerComponent) {
2088 ComponentInstance foundInstance = null;
2089 if (CollectionUtils.isNotEmpty(containerComponent.getComponentInstances())) {
2090 foundInstance = containerComponent.getComponentInstances()
2092 .filter(i -> i.getUniqueId().equals(componentInstanceId))
2096 return foundInstance;
2099 private Either<Boolean, ResponseFormat> validateDeploymentArtifact(Component parentComponent, String parentId, boolean isCreate, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, NodeTypeEnum parentType) {
2101 Either<Boolean, ResponseFormat> result = Either.left(true);
2102 Wrapper<ResponseFormat> responseWrapper = new Wrapper<>();
2104 validateArtifactTypeExists(responseWrapper, artifactInfo);
2106 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
2108 Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts = fillDeploymentArtifactTypeConf(parentType);
2110 if (responseWrapper.isEmpty()) {
2111 validateDeploymentArtifactConf(artifactInfo, responseWrapper, artifactType, resourceDeploymentArtifacts);
2114 // Common code for all types
2115 // not allowed to change artifactType
2116 if (responseWrapper.isEmpty() && !isCreate) {
2117 Either<Boolean, ResponseFormat> validateServiceApiType = validateArtifactTypeNotChanged(artifactInfo, currentArtifact);
2118 if (validateServiceApiType.isRight()) {
2119 responseWrapper.setInnerElement(validateServiceApiType.right().value());
2122 if (responseWrapper.isEmpty()) {
2123 if (parentType.equals(NodeTypeEnum.Resource)) {
2124 Resource resource = (Resource) parentComponent;
2125 ResourceTypeEnum resourceType = resource.getResourceType();
2126 ArtifactTypeConfig config = resourceDeploymentArtifacts.get(artifactType.getType());
2127 if (config == null) {
2128 responseWrapper.setInnerElement(ResponseFormatManager.getInstance()
2129 .getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
2130 .getArtifactType()));
2133 List<String> myList = config.getValidForResourceTypes();
2134 Either<Boolean, ResponseFormat> either = validateResourceType(resourceType, artifactInfo, myList);
2135 if (either.isRight()) {
2136 responseWrapper.setInnerElement(either.right().value());
2141 validateFileExtension(responseWrapper, () -> getDeploymentArtifactTypeConfig(parentType, artifactType), artifactInfo, parentType, artifactType);
2144 if (responseWrapper.isEmpty() && !NodeTypeEnum.ResourceInstance.equals(parentType)) {
2145 String artifactName = artifactInfo.getArtifactName();
2146 if (isCreate || !artifactName.equalsIgnoreCase(currentArtifact.getArtifactName())) {
2147 validateSingleDeploymentArtifactName(responseWrapper, artifactName, parentComponent, parentType);
2151 if (responseWrapper.isEmpty()) {
2152 switch (artifactType) {
2156 result = validateHeatDeploymentArtifact(isCreate, artifactInfo, currentArtifact);
2159 result = validateHeatEnvDeploymentArtifact(parentComponent, parentId, artifactInfo, parentType);
2160 artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
2162 case DCAE_INVENTORY_TOSCA:
2163 case DCAE_INVENTORY_JSON:
2164 case DCAE_INVENTORY_POLICY:
2165 // Validation is done in handle payload.
2166 case DCAE_INVENTORY_DOC:
2167 case DCAE_INVENTORY_BLUEPRINT:
2168 case DCAE_INVENTORY_EVENT:
2169 // No specific validation
2171 artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
2177 if (!responseWrapper.isEmpty()) {
2178 result = Either.right(responseWrapper.getInnerElement());
2183 private void validateDeploymentArtifactConf(ArtifactDefinition artifactInfo, Wrapper<ResponseFormat> responseWrapper, ArtifactTypeEnum artifactType, Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts) {
2184 if ((resourceDeploymentArtifacts == null) || !resourceDeploymentArtifacts.containsKey(artifactType.name())) {
2185 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2186 .getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
2187 .getArtifactType());
2188 responseWrapper.setInnerElement(responseFormat);
2189 log.debug("Artifact Type: {} Not found !", artifactInfo.getArtifactType());
2193 private Map<String, ArtifactTypeConfig> fillDeploymentArtifactTypeConf(NodeTypeEnum parentType) {
2194 Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts = null;
2195 if (parentType.equals(NodeTypeEnum.Resource)) {
2196 resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager()
2198 .getResourceDeploymentArtifacts();
2200 else if (parentType.equals(NodeTypeEnum.ResourceInstance)) {
2201 resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager()
2203 .getResourceInstanceDeploymentArtifacts();
2206 resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager()
2208 .getServiceDeploymentArtifacts();
2210 return resourceDeploymentArtifacts;
2213 public void validateArtifactTypeExists(Wrapper<ResponseFormat> responseWrapper, ArtifactDefinition artifactInfo) {
2214 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
2215 if (artifactType == null) {
2216 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2217 .getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
2218 .getArtifactType());
2219 responseWrapper.setInnerElement(responseFormat);
2220 log.debug("Artifact Type: {} Not found !", artifactInfo.getArtifactType());
2224 private ArtifactTypeConfig getDeploymentArtifactTypeConfig(NodeTypeEnum parentType, ArtifactTypeEnum artifactType) {
2225 ArtifactTypeConfig retConfig = null;
2226 String fileType = artifactType.getType();
2227 if (parentType.equals(NodeTypeEnum.Resource)) {
2228 retConfig = ConfigurationManager.getConfigurationManager()
2230 .getResourceDeploymentArtifacts()
2233 else if (parentType.equals(NodeTypeEnum.Service)) {
2234 retConfig = ConfigurationManager.getConfigurationManager()
2236 .getServiceDeploymentArtifacts()
2239 else if (parentType.equals(NodeTypeEnum.ResourceInstance)) {
2240 retConfig = ConfigurationManager.getConfigurationManager()
2242 .getResourceInstanceDeploymentArtifacts()
2248 private Either<Boolean, ResponseFormat> extractHeatParameters(ArtifactDefinition artifactInfo) {
2249 // extract heat parameters
2250 if (artifactInfo.getPayloadData() != null) {
2251 String heatDecodedPayload = new String(Base64.decodeBase64(artifactInfo.getPayloadData()));
2252 Either<List<HeatParameterDefinition>, ResultStatusEnum> heatParameters = ImportUtils.getHeatParamsWithoutImplicitTypes(heatDecodedPayload, artifactInfo
2253 .getArtifactType());
2254 if (heatParameters.isRight() && (!heatParameters.right()
2256 .equals(ResultStatusEnum.ELEMENT_NOT_FOUND))) {
2257 log.info("failed to parse heat parameters ");
2258 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactInfo
2259 .getArtifactType());
2260 return Either.right(responseFormat);
2262 else if (heatParameters.isLeft() && heatParameters.left().value() != null) {
2263 artifactInfo.setListHeatParameters(heatParameters.left().value());
2266 return Either.left(true);
2271 public void validateFileExtension(Wrapper<ResponseFormat> responseWrapper, IDeploymentArtifactTypeConfigGetter deploymentConfigGetter, ArtifactDefinition artifactInfo, NodeTypeEnum parentType, ArtifactTypeEnum artifactType) {
2272 String fileType = artifactType.getType();
2273 List<String> acceptedTypes = null;
2274 ArtifactTypeConfig deploymentAcceptedTypes = deploymentConfigGetter.getDeploymentArtifactConfig();
2275 if (!parentType.equals(NodeTypeEnum.Resource) && !parentType.equals(NodeTypeEnum.Service) && !parentType.equals(NodeTypeEnum.ResourceInstance)) {
2276 log.debug("parent type of artifact can be either resource or service");
2277 responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
2281 if (deploymentAcceptedTypes == null) {
2282 log.debug("parent type of artifact can be either resource or service");
2283 responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
2284 .getArtifactType()));
2288 acceptedTypes = deploymentAcceptedTypes.getAcceptedTypes();
2291 * No need to check specific types. In case there are no acceptedTypes in configuration, then any type is accepted.
2294 String artifactName = artifactInfo.getArtifactName();
2295 String fileExtension = GeneralUtility.getFilenameExtension(artifactName);
2296 // Pavel - File extension validation is case-insensitive - Ella,
2298 if (acceptedTypes != null && !acceptedTypes.isEmpty() && !acceptedTypes.contains(fileExtension.toLowerCase())) {
2299 log.debug("File extension \"{}\" is not allowed for {} which is of type:{}", fileExtension, artifactName, fileType);
2300 responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.WRONG_ARTIFACT_FILE_EXTENSION, fileType));
2305 private Either<Boolean, ResponseFormat> validateHeatEnvDeploymentArtifact(Component parentComponent, String parentId, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) {
2307 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
2308 Wrapper<ArtifactDefinition> heatMDWrapper = new Wrapper<>();
2309 Wrapper<byte[]> payloadWrapper = new Wrapper<>();
2311 if (errorWrapper.isEmpty()) {
2312 validateValidYaml(errorWrapper, artifactInfo);
2315 if (errorWrapper.isEmpty()) {
2316 // Validate Heat Exist
2317 validateHeatExist(parentComponent.getUniqueId(), parentId, errorWrapper, heatMDWrapper, artifactInfo, parentType, parentComponent
2318 .getComponentType());
2321 if (errorWrapper.isEmpty() && !heatMDWrapper.isEmpty()) {
2322 fillArtifactPayloadValidation(errorWrapper, payloadWrapper, heatMDWrapper.getInnerElement());
2325 if (errorWrapper.isEmpty() && !heatMDWrapper.isEmpty()) {
2326 validateEnvVsHeat(errorWrapper, artifactInfo, heatMDWrapper.getInnerElement(), payloadWrapper.getInnerElement());
2330 Either<Boolean, ResponseFormat> eitherResponse;
2331 if (errorWrapper.isEmpty()) {
2332 eitherResponse = Either.left(true);
2335 eitherResponse = Either.right(errorWrapper.getInnerElement());
2337 return eitherResponse;
2340 public void fillArtifactPayloadValidation(Wrapper<ResponseFormat> errorWrapper, Wrapper<byte[]> payloadWrapper, ArtifactDefinition artifactDefinition) {
2341 if (artifactDefinition.getPayloadData() == null || artifactDefinition.getPayloadData().length == 0) {
2342 Either<Boolean, ResponseFormat> fillArtifactPayload = fillArtifactPayload(payloadWrapper, artifactDefinition);
2343 if (fillArtifactPayload.isRight()) {
2344 errorWrapper.setInnerElement(fillArtifactPayload.right().value());
2345 log.debug("Error getting payload for artifact:{}", artifactDefinition.getArtifactName());
2349 payloadWrapper.setInnerElement(artifactDefinition.getPayloadData());
2353 public Either<Boolean, ResponseFormat> fillArtifactPayload(Wrapper<byte[]> payloadWrapper, ArtifactDefinition artifactMD) {
2354 Either<Boolean, ResponseFormat> result = Either.left(true);
2355 Either<ESArtifactData, CassandraOperationStatus> eitherArtifactData = artifactCassandraDao.getArtifact(artifactMD
2357 if (eitherArtifactData.isLeft()) {
2358 byte[] data = eitherArtifactData.left().value().getDataAsArray();
2359 data = Base64.encodeBase64(data);
2360 payloadWrapper.setInnerElement(data);
2363 StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(eitherArtifactData
2366 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus));
2367 result = Either.right(responseFormat);
2373 @SuppressWarnings("unchecked")
2374 private void validateEnvVsHeat(Wrapper<ResponseFormat> errorWrapper, ArtifactDefinition envArtifact, ArtifactDefinition heatArtifact, byte[] heatPayloadData) {
2375 String envPayload = new String(Base64.decodeBase64(envArtifact.getPayloadData()));
2376 Map<String, Object> heatEnvToscaJson = (Map<String, Object>) new Yaml().load(envPayload);
2377 String heatDecodedPayload = new String(Base64.decodeBase64(heatPayloadData));
2378 Map<String, Object> heatToscaJson = (Map<String, Object>) new Yaml().load(heatDecodedPayload);
2380 Either<Map<String, Object>, ResultStatusEnum> eitherHeatEnvProperties = ImportUtils.findFirstToscaMapElement(heatEnvToscaJson, TypeUtils.ToscaTagNamesEnum.PARAMETERS);
2381 Either<Map<String, Object>, ResultStatusEnum> eitherHeatProperties = ImportUtils.findFirstToscaMapElement(heatToscaJson, TypeUtils.ToscaTagNamesEnum.PARAMETERS);
2382 if (eitherHeatEnvProperties.isRight()) {
2383 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2384 .getResponseFormat(ActionStatus.CORRUPTED_FORMAT, "Heat Env");
2385 errorWrapper.setInnerElement(responseFormat);
2386 log.debug("Invalid heat env format for file:{}", envArtifact.getArtifactName());
2388 else if (eitherHeatProperties.isRight()) {
2389 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2390 .getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, envArtifact
2391 .getArtifactName(), heatArtifact.getArtifactName());
2392 errorWrapper.setInnerElement(responseFormat);
2393 log.debug("Validation of heat_env for artifact:{} vs heat artifact for artifact :{} failed", envArtifact.getArtifactName(), heatArtifact
2394 .getArtifactName());
2397 Set<String> heatPropertiesKeys = eitherHeatProperties.left().value().keySet();
2398 Set<String> heatEnvPropertiesKeys = eitherHeatEnvProperties.left().value().keySet();
2399 heatEnvPropertiesKeys.removeAll(heatPropertiesKeys);
2400 if (!heatEnvPropertiesKeys.isEmpty()) {
2401 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2402 .getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, envArtifact
2403 .getArtifactName(), heatArtifact.getArtifactName());
2404 errorWrapper.setInnerElement(responseFormat);
2409 private void validateValidYaml(Wrapper<ResponseFormat> errorWrapper, ArtifactDefinition artifactInfo) {
2410 YamlToObjectConverter yamlConvertor = new YamlToObjectConverter();
2411 boolean isYamlValid = yamlConvertor.isValidYamlEncoded64(artifactInfo.getPayloadData());
2413 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2414 .getResponseFormat(ActionStatus.INVALID_YAML, artifactInfo
2415 .getArtifactType());
2416 errorWrapper.setInnerElement(responseFormat);
2417 log.debug("Yaml is not valid for artifact : {}", artifactInfo.getArtifactName());
2421 private boolean isValidXml(byte[] xmlToParse) {
2422 boolean isXmlValid = true;
2424 XMLReader reader = SAXParserFactory.newInstance().newSAXParser().getXMLReader();
2425 setFeatures(reader);
2426 reader.parse(new InputSource(new ByteArrayInputStream(xmlToParse)));
2428 catch (ParserConfigurationException | IOException | SAXException e) {
2429 log.debug("Xml is invalid : {}", e.getMessage(), e);
2435 private void setFeatures(XMLReader reader) throws SAXNotSupportedException {
2437 reader.setFeature("http://apache.org/xml/features/validation/schema", false);
2438 reader.setFeature(XMLConstants.FEATURE_SECURE_PROCESSING, true);
2440 catch (SAXNotRecognizedException e) {
2441 log.debug("Xml parser couldn't set feature: \"http://apache.org/xml/features/validation/schema\", false", e.getMessage(), e);
2445 private void validateSingleDeploymentArtifactName(Wrapper<ResponseFormat> errorWrapper, String artifactName, Component parentComponent, NodeTypeEnum parentType) {
2446 boolean artifactNameFound = false;
2447 Iterator<ArtifactDefinition> parentDeploymentArtifactsItr = getDeploymentArtifacts(parentComponent, parentType, null)
2450 while (!artifactNameFound && parentDeploymentArtifactsItr.hasNext()) {
2451 artifactNameFound = artifactName.equalsIgnoreCase(parentDeploymentArtifactsItr.next().getArtifactName());
2453 if (artifactNameFound) {
2454 String parentName = parentComponent.getName();
2455 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2456 .getResponseFormat(ActionStatus.DEPLOYMENT_ARTIFACT_NAME_ALREADY_EXISTS, parentType
2457 .name(), parentName, artifactName);
2459 errorWrapper.setInnerElement(responseFormat);
2460 log.debug("Can't upload artifact: {}, because another artifact with this name already exist.", artifactName);
2465 private void validateHeatExist(String componentId, String parentRiId, Wrapper<ResponseFormat> errorWrapper, Wrapper<ArtifactDefinition> heatArtifactMDWrapper, ArtifactDefinition heatEnvArtifact, NodeTypeEnum parentType,
2466 ComponentTypeEnum componentType) {
2467 Either<ArtifactDefinition, StorageOperationStatus> res = artifactToscaOperation.getHeatArtifactByHeatEnvId(parentRiId, heatEnvArtifact, parentType, componentId, componentType);
2468 if (res.isRight()) {
2469 ResponseFormat responseFormat;
2470 if (res.right().value() == StorageOperationStatus.NOT_FOUND) {
2471 responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT);
2474 responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT);
2476 errorWrapper.setInnerElement(responseFormat);
2479 ArtifactDefinition heatArtifact = res.left().value();
2480 heatArtifactMDWrapper.setInnerElement(heatArtifact);
2483 private Either<Boolean, ResponseFormat> validateHeatDeploymentArtifact(boolean isCreate, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2484 log.trace("Started HEAT pre-payload validation for artifact {}", artifactInfo.getArtifactLabel());
2485 // timeout > 0 for HEAT artifacts
2486 Integer timeout = artifactInfo.getTimeout();
2487 if (timeout == null) {
2488 Integer defaultTimeout = isCreate ? NodeTemplateOperation.getDefaultHeatTimeout() : currentArtifact.getTimeout();
2489 artifactInfo.setTimeout(defaultTimeout);
2490 // HEAT artifact but timeout is invalid
2492 else if (timeout < 1) {
2493 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_TIMEOUT));
2496 // US649856 - Allow several HEAT files on Resource
2497 log.trace("Ended HEAT validation for artifact {}", artifactInfo.getArtifactLabel());
2498 return Either.left(true);
2501 private Either<Boolean, ResponseFormat> validateResourceType(ResourceTypeEnum resourceType, ArtifactDefinition artifactInfo, List<String> typeList) {
2502 String listToString = (typeList != null) ? typeList.toString() : "";
2503 ResponseFormat responseFormat = ResponseFormatManager.getInstance()
2504 .getResponseFormat(ActionStatus.MISMATCH_BETWEEN_ARTIFACT_TYPE_AND_COMPONENT_TYPE, artifactInfo
2505 .getArtifactName(), listToString, resourceType.getValue());
2506 Either<Boolean, ResponseFormat> either = Either.right(responseFormat);
2507 String resourceTypeName = resourceType.name();
2508 if (typeList != null && typeList.contains(resourceTypeName)) {
2509 either = Either.left(true);
2514 private Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers(ArtifactDefinition artifactInfo, String artifactType) {
2515 if (artifactInfo.getHeatParameters() != null) {
2516 for (HeatParameterDefinition heatParam : artifactInfo.getListHeatParameters()) {
2517 String parameterType = heatParam.getType();
2518 HeatParameterType heatParameterType = HeatParameterType.isValidType(parameterType);
2519 String artifactTypeStr = artifactType != null ? artifactType : ArtifactTypeEnum.HEAT.getType();
2520 if (heatParameterType == null) {
2521 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_HEAT_PARAMETER_TYPE, artifactTypeStr, heatParam
2523 return Either.right(responseFormat);
2526 StorageOperationStatus validateAndUpdateProperty = heatParametersOperation.validateAndUpdateProperty(heatParam);
2527 if (validateAndUpdateProperty != StorageOperationStatus.OK) {
2528 log.debug("Heat parameter {} is invalid. Status is {}", heatParam.getName(), validateAndUpdateProperty);
2529 ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE;
2530 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, artifactTypeStr, heatParam
2531 .getType(), heatParam.getName());
2532 return Either.right(responseFormat);
2536 return Either.left(artifactInfo);
2539 public List<ArtifactDefinition> getDeploymentArtifacts(Component parentComponent, NodeTypeEnum parentType, String ciId) {
2540 List<ArtifactDefinition> deploymentArtifacts = new ArrayList<>();
2541 if (parentComponent.getDeploymentArtifacts() != null) {
2542 if (NodeTypeEnum.ResourceInstance == parentType && ciId != null) {
2543 Either<ComponentInstance, ResponseFormat> getRI = getRIFromComponent(parentComponent, ciId, null, null, null);
2544 if (getRI.isRight()) {
2545 return deploymentArtifacts;
2547 ComponentInstance ri = getRI.left().value();
2548 if (ri.getDeploymentArtifacts() != null) {
2549 deploymentArtifacts.addAll(ri.getDeploymentArtifacts().values());
2552 else if (parentComponent.getDeploymentArtifacts() != null) {
2553 deploymentArtifacts.addAll(parentComponent.getDeploymentArtifacts().values());
2556 return deploymentArtifacts;
2559 private void checkCreateFields(User user, ArtifactDefinition artifactInfo, ArtifactGroupTypeEnum type) {
2560 // on create if null add informational to current
2561 if (artifactInfo.getArtifactGroupType() == null) {
2562 artifactInfo.setArtifactGroupType(type);
2564 if (artifactInfo.getUniqueId() != null) {
2565 log.error("artifact uniqid cannot be set ignoring");
2567 artifactInfo.setUniqueId(null);
2569 if (artifactInfo.getArtifactRef() != null) {
2570 log.error("artifact ref cannot be set ignoring");
2572 artifactInfo.setArtifactRef(null);
2574 if (artifactInfo.getArtifactRepository() != null) {
2575 log.error("artifact repository cannot be set ignoring");
2577 artifactInfo.setArtifactRepository(null);
2579 if (artifactInfo.getUserIdCreator() != null) {
2580 log.error("creator uuid cannot be set ignoring");
2582 artifactInfo.setArtifactCreator(user.getUserId());
2584 if (artifactInfo.getUserIdLastUpdater() != null) {
2585 log.error("userId of last updater cannot be set ignoring");
2587 artifactInfo.setUserIdLastUpdater(user.getUserId());
2589 if (artifactInfo.getCreatorFullName() != null) {
2590 log.error("creator Full name cannot be set ignoring");
2592 String fullName = user.getFirstName() + " " + user.getLastName();
2593 artifactInfo.setUpdaterFullName(fullName);
2595 if (artifactInfo.getUpdaterFullName() != null) {
2596 log.error("updater Full name cannot be set ignoring");
2598 artifactInfo.setUpdaterFullName(fullName);
2600 if (artifactInfo.getCreationDate() != null) {
2601 log.error("Creation Date cannot be set ignoring");
2603 long time = System.currentTimeMillis();
2604 artifactInfo.setCreationDate(time);
2606 if (artifactInfo.getLastUpdateDate() != null) {
2607 log.error("Last Update Date cannot be set ignoring");
2609 artifactInfo.setLastUpdateDate(time);
2611 if (artifactInfo.getEsId() != null) {
2612 log.error("es id cannot be set ignoring");
2614 artifactInfo.setEsId(null);
2619 private String composeArtifactId(String resourceId, String artifactId, ArtifactDefinition artifactInfo, String interfaceName, String operationName) {
2620 String id = artifactId;
2621 if (artifactId == null || artifactId.isEmpty()) {
2622 String uniqueId = null;
2623 if (interfaceName != null && operationName != null) {
2624 uniqueId = UniqueIdBuilder.buildArtifactByInterfaceUniqueId(resourceId, interfaceName, operationName, artifactInfo
2625 .getArtifactLabel());
2628 uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId, artifactInfo.getArtifactLabel());
2630 artifactInfo.setUniqueId(uniqueId);
2631 artifactInfo.setEsId(uniqueId);
2635 artifactInfo.setUniqueId(artifactId);
2636 artifactInfo.setEsId(artifactId);
2641 private Either<ActionStatus, ResponseFormat> validateArtifactType(String userId, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) {
2642 if (Strings.isNullOrEmpty(artifactInfo.getArtifactType())) {
2643 BeEcompErrorManager.getInstance()
2644 .logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel");
2645 log.debug("Missing artifact type for artifact {}", artifactInfo.getArtifactName());
2646 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_TYPE));
2649 boolean artifactTypeExist = false;
2650 Either<List<ArtifactType>, ActionStatus> allArtifactTypes = null;
2651 ArtifactGroupTypeEnum artifactGroupType = artifactInfo.getArtifactGroupType();
2653 if ((artifactGroupType != null) && artifactGroupType.equals(ArtifactGroupTypeEnum.DEPLOYMENT)) {
2654 allArtifactTypes = getDeploymentArtifactTypes(parentType);
2658 allArtifactTypes = elementOperation.getAllArtifactTypes();
2660 if (allArtifactTypes.isRight()) {
2661 BeEcompErrorManager.getInstance()
2662 .logBeInvalidConfigurationError("Artifact Upload / Update", "artifactTypes", allArtifactTypes
2666 log.debug("Failed to retrieve list of suported artifact types. error: {}", allArtifactTypes.right()
2668 return Either.right(componentsUtils.getResponseFormatByUserId(allArtifactTypes.right().value(), userId));
2671 for (ArtifactType type : allArtifactTypes.left().value()) {
2672 if (type.getName().equalsIgnoreCase(artifactInfo.getArtifactType())) {
2673 artifactInfo.setArtifactType(artifactInfo.getArtifactType().toUpperCase());
2674 artifactTypeExist = true;
2679 if (!artifactTypeExist) {
2680 BeEcompErrorManager.getInstance()
2681 .logBeInvalidTypeError("Artifact Upload / Delete / Update - Not supported artifact type", artifactInfo
2682 .getArtifactType(), "Artifact " + artifactInfo.getArtifactName());
2683 log.debug("Not supported artifact type = {}", artifactInfo.getArtifactType());
2684 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo
2685 .getArtifactType()));
2688 return Either.left(ActionStatus.OK);
2691 private Either<List<ArtifactType>, ActionStatus> getDeploymentArtifactTypes(NodeTypeEnum parentType) {
2693 Map<String, ArtifactTypeConfig> deploymentArtifacts ;
2694 List<ArtifactType> artifactTypes = new ArrayList<>();
2696 if (parentType.equals(NodeTypeEnum.Service)) {
2697 deploymentArtifacts = ConfigurationManager.getConfigurationManager()
2699 .getServiceDeploymentArtifacts();
2701 else if (parentType.equals(NodeTypeEnum.ResourceInstance)) {
2702 deploymentArtifacts = ConfigurationManager.getConfigurationManager()
2704 .getResourceInstanceDeploymentArtifacts();
2707 deploymentArtifacts = ConfigurationManager.getConfigurationManager()
2709 .getResourceDeploymentArtifacts();
2711 if (deploymentArtifacts != null) {
2712 for (String artifactType : deploymentArtifacts.keySet()) {
2713 ArtifactType artifactT = new ArtifactType();
2714 artifactT.setName(artifactType);
2715 artifactTypes.add(artifactT);
2717 return Either.left(artifactTypes);
2720 return Either.right(ActionStatus.GENERAL_ERROR);
2725 private Either<Boolean, ResponseFormat> validateFirstUpdateHasPayload(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2726 if (currentArtifact.getEsId() == null && (artifactInfo.getPayloadData() == null || artifactInfo.getPayloadData().length == 0)) {
2727 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD));
2729 return Either.left(true);
2733 private Either<Boolean, ResponseFormat> validateAndSetArtifactname(ArtifactDefinition artifactInfo) {
2734 if (artifactInfo.getArtifactName() == null || artifactInfo.getArtifactName().isEmpty()) {
2735 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_NAME));
2738 String normalizeFileName = ValidationUtils.normalizeFileName(artifactInfo.getArtifactName());
2739 if (normalizeFileName == null || normalizeFileName.isEmpty()) {
2740 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_NAME));
2742 artifactInfo.setArtifactName(normalizeFileName);
2744 if (!ValidationUtils.validateArtifactNameLength(artifactInfo.getArtifactName())) {
2745 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_NAME, String.valueOf(ValidationUtils.ARTIFACT_NAME_LENGTH)));
2748 return Either.left(true);
2751 private Either<Boolean, ResponseFormat> validateArtifactTypeNotChanged(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2752 if (artifactInfo.getArtifactType() == null || artifactInfo.getArtifactType().isEmpty()) {
2753 log.info("artifact type is missing operation ignored");
2754 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_TYPE));
2757 if (!currentArtifact.getArtifactType().equalsIgnoreCase(artifactInfo.getArtifactType())) {
2758 log.info("artifact type cannot be changed operation ignored");
2759 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2761 return Either.left(true);
2764 private Either<ArtifactDefinition, ResponseFormat> validateOrSetArtifactGroupType(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2765 if (artifactInfo.getArtifactGroupType() == null) {
2766 artifactInfo.setArtifactGroupType(currentArtifact.getArtifactGroupType());
2769 else if (!currentArtifact.getArtifactGroupType()
2771 .equalsIgnoreCase(artifactInfo.getArtifactGroupType().getType())) {
2772 log.info("artifact group type cannot be changed. operation failed");
2773 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2775 return Either.left(artifactInfo);
2778 private void checkAndSetUnUpdatableFields(User user, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, ArtifactGroupTypeEnum type) {
2780 // on update if null add informational to current
2781 if (currentArtifact.getArtifactGroupType() == null && type != null) {
2782 currentArtifact.setArtifactGroupType(type);
2785 if (artifactInfo.getUniqueId() != null && !currentArtifact.getUniqueId().equals(artifactInfo.getUniqueId())) {
2786 log.error("artifact uniqid cannot be set ignoring");
2788 artifactInfo.setUniqueId(currentArtifact.getUniqueId());
2790 if (artifactInfo.getArtifactRef() != null && !currentArtifact.getArtifactRef()
2791 .equals(artifactInfo.getArtifactRef())) {
2792 log.error("artifact ref cannot be set ignoring");
2794 artifactInfo.setArtifactRef(currentArtifact.getArtifactRef());
2796 if (artifactInfo.getArtifactRepository() != null && !currentArtifact.getArtifactRepository()
2797 .equals(artifactInfo.getArtifactRepository())) {
2798 log.error("artifact repository cannot be set ignoring");
2800 artifactInfo.setArtifactRepository(currentArtifact.getArtifactRepository());
2802 if (artifactInfo.getUserIdCreator() != null && !currentArtifact.getUserIdCreator()
2803 .equals(artifactInfo.getUserIdCreator())) {
2804 log.error("creator uuid cannot be set ignoring");
2806 artifactInfo.setUserIdCreator(currentArtifact.getUserIdCreator());
2808 if (artifactInfo.getArtifactCreator() != null && !currentArtifact.getArtifactCreator()
2809 .equals(artifactInfo.getArtifactCreator())) {
2810 log.error("artifact creator cannot be set ignoring");
2812 artifactInfo.setArtifactCreator(currentArtifact.getArtifactCreator());
2814 if (artifactInfo.getUserIdLastUpdater() != null && !currentArtifact.getUserIdLastUpdater()
2815 .equals(artifactInfo.getUserIdLastUpdater())) {
2816 log.error("userId of last updater cannot be set ignoring");
2818 artifactInfo.setUserIdLastUpdater(user.getUserId());
2820 if (artifactInfo.getCreatorFullName() != null && !currentArtifact.getCreatorFullName()
2821 .equals(artifactInfo.getCreatorFullName())) {
2822 log.error("creator Full name cannot be set ignoring");
2824 artifactInfo.setCreatorFullName(currentArtifact.getCreatorFullName());
2826 if (artifactInfo.getUpdaterFullName() != null && !currentArtifact.getUpdaterFullName()
2827 .equals(artifactInfo.getUpdaterFullName())) {
2828 log.error("updater Full name cannot be set ignoring");
2830 String fullName = user.getFirstName() + " " + user.getLastName();
2831 artifactInfo.setUpdaterFullName(fullName);
2833 if (artifactInfo.getCreationDate() != null && !currentArtifact.getCreationDate()
2834 .equals(artifactInfo.getCreationDate())) {
2835 log.error("Creation Date cannot be set ignoring");
2837 artifactInfo.setCreationDate(currentArtifact.getCreationDate());
2839 if (artifactInfo.getLastUpdateDate() != null && !currentArtifact.getLastUpdateDate()
2840 .equals(artifactInfo.getLastUpdateDate())) {
2841 log.error("Last Update Date cannot be set ignoring");
2843 long time = System.currentTimeMillis();
2844 artifactInfo.setLastUpdateDate(time);
2846 if (artifactInfo.getEsId() != null && !currentArtifact.getEsId().equals(artifactInfo.getEsId())) {
2847 log.error("es id cannot be set ignoring");
2849 artifactInfo.setEsId(currentArtifact.getUniqueId());
2851 if (artifactInfo.getArtifactDisplayName() != null && !currentArtifact.getArtifactDisplayName()
2852 .equals(artifactInfo.getArtifactDisplayName())) {
2853 log.error(" Artifact Display Name cannot be set ignoring");
2855 artifactInfo.setArtifactDisplayName(currentArtifact.getArtifactDisplayName());
2857 if (artifactInfo.getServiceApi() != null && !currentArtifact.getServiceApi()
2858 .equals(artifactInfo.getServiceApi())) {
2859 log.debug("serviceApi cannot be set. ignoring.");
2861 artifactInfo.setServiceApi(currentArtifact.getServiceApi());
2863 if (artifactInfo.getArtifactGroupType() != null && !currentArtifact.getArtifactGroupType()
2864 .equals(artifactInfo.getArtifactGroupType())) {
2865 log.debug("artifact group cannot be set. ignoring.");
2867 artifactInfo.setArtifactGroupType(currentArtifact.getArtifactGroupType());
2869 artifactInfo.setArtifactVersion(currentArtifact.getArtifactVersion());
2871 if (artifactInfo.getArtifactUUID() != null && !artifactInfo.getArtifactUUID()
2872 .isEmpty() && !currentArtifact.getArtifactUUID()
2873 .equals(artifactInfo.getArtifactUUID())) {
2874 log.debug("artifact UUID cannot be set. ignoring.");
2876 artifactInfo.setArtifactUUID(currentArtifact.getArtifactUUID());
2878 if ((artifactInfo.getHeatParameters() != null) && (currentArtifact.getHeatParameters() != null) && !artifactInfo
2879 .getHeatParameters()
2880 .isEmpty() && !currentArtifact.getHeatParameters().isEmpty()) {
2881 checkAndSetUnupdatableHeatParams(artifactInfo.getListHeatParameters(), currentArtifact.getListHeatParameters());
2885 private void checkAndSetUnupdatableHeatParams(List<HeatParameterDefinition> heatParameters, List<HeatParameterDefinition> currentParameters) {
2887 Map<String, HeatParameterDefinition> currentParametersMap = getMapOfParameters(currentParameters);
2888 for (HeatParameterDefinition parameter : heatParameters) {
2889 HeatParameterDefinition currentParam = currentParametersMap.get(parameter.getUniqueId());
2891 if (currentParam != null) {
2893 if (parameter.getName() != null && !parameter.getName().equalsIgnoreCase(currentParam.getName())) {
2894 log.debug("heat parameter name cannot be updated ({}). ignoring.", parameter.getName());
2895 parameter.setName(currentParam.getName());
2897 if (parameter.getDefaultValue() != null && !parameter.getDefaultValue()
2898 .equalsIgnoreCase(currentParam.getDefaultValue())) {
2899 log.debug("heat parameter defaultValue cannot be updated ({}). ignoring.", parameter.getDefaultValue());
2900 parameter.setDefaultValue(currentParam.getDefaultValue());
2902 if (parameter.getType() != null && !parameter.getType().equalsIgnoreCase(currentParam.getType())) {
2903 log.debug("heat parameter type cannot be updated ({}). ignoring.", parameter.getType());
2904 parameter.setType(currentParam.getType());
2906 if (parameter.getDescription() != null && !parameter.getDescription()
2907 .equalsIgnoreCase(currentParam.getDescription())) {
2908 log.debug("heat parameter description cannot be updated ({}). ignoring.", parameter.getDescription());
2909 parameter.setDescription(currentParam.getDescription());
2912 // check and set current value
2913 if ((parameter.getCurrentValue() == null) && (currentParam.getDefaultValue() != null)) {
2914 log.debug("heat parameter current value is null. set it to default value {}). ignoring.", parameter.getDefaultValue());
2915 parameter.setCurrentValue(currentParam.getDefaultValue());
2921 private Map<String, HeatParameterDefinition> getMapOfParameters(List<HeatParameterDefinition> currentParameters) {
2923 Map<String, HeatParameterDefinition> currentParamsMap = new HashMap<String, HeatParameterDefinition>();
2924 for (HeatParameterDefinition param : currentParameters) {
2925 currentParamsMap.put(param.getUniqueId(), param);
2927 return currentParamsMap;
2930 private Either<Boolean, ResponseFormat> validateAndServiceApiUrl(ArtifactDefinition artifactInfo) {
2931 if (!ValidationUtils.validateStringNotEmpty(artifactInfo.getApiUrl())) {
2932 log.debug("Artifact url cannot be empty.");
2933 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_URL));
2935 artifactInfo.setApiUrl(artifactInfo.getApiUrl().toLowerCase());
2937 if (!ValidationUtils.validateUrl(artifactInfo.getApiUrl())) {
2938 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_SERVICE_API_URL));
2940 if (!ValidationUtils.validateUrlLength(artifactInfo.getApiUrl())) {
2941 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_URL, String.valueOf(ValidationUtils.API_URL_LENGTH)));
2944 return Either.left(true);
2947 private Either<Boolean, ResponseFormat> validateAndCleanDescription(ArtifactDefinition artifactInfo) {
2948 if (artifactInfo.getDescription() == null || artifactInfo.getDescription().isEmpty()) {
2949 log.debug("Artifact description cannot be empty.");
2950 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_DESCRIPTION));
2952 String description = artifactInfo.getDescription();
2953 description = ValidationUtils.removeNoneUtf8Chars(description);
2954 description = ValidationUtils.normaliseWhitespace(description);
2955 description = ValidationUtils.stripOctets(description);
2956 description = ValidationUtils.removeHtmlTagsOnly(description);
2957 if (!ValidationUtils.validateIsEnglish(description)) {
2958 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2960 if (!ValidationUtils.validateLength(description, ValidationUtils.ARTIFACT_DESCRIPTION_MAX_LENGTH)) {
2961 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_DESCRIPTION, String
2962 .valueOf(ValidationUtils.ARTIFACT_DESCRIPTION_MAX_LENGTH)));
2964 artifactInfo.setDescription(description);
2965 return Either.left(true);
2968 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateArtifactFlow(org.openecomp.sdc.be.model.Component parent, String parentId, String artifactId, ArtifactDefinition artifactInfo, User user, byte[] decodedPayload,
2969 ComponentTypeEnum componentType, AuditingActionEnum auditingAction, String interfaceType, String operationUuid) {
2970 ESArtifactData artifactData = createEsArtifactData(artifactInfo, decodedPayload);
2971 String prevArtifactId = null;
2972 String currArtifactId = artifactId;
2974 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
2975 Either<ArtifactDefinition, Operation> insideEither = null;
2977 log.trace("Try to update entry on graph");
2978 String artifactUniqueId = null;
2979 ArtifactDefinition artifactDefinition = artifactInfo;
2980 StorageOperationStatus error;
2983 if (interfaceType == null || operationUuid == null) {
2984 log.debug("Entity on graph is updated. Update artifact in ES");
2986 // Changing previous and current artifactId for auditing
2987 prevArtifactId = currArtifactId;
2988 currArtifactId = artifactDefinition.getUniqueId();
2991 if (decodedPayload == null) {
2992 if (!artifactDefinition.getMandatory() || artifactDefinition.getEsId() != null) {
2993 Either<ESArtifactData, CassandraOperationStatus> artifactFromCassandra = artifactCassandraDao.getArtifact(artifactDefinition
2995 if (artifactFromCassandra.isRight()) {
2996 log.debug("Failed to get artifact data from ES for artifact id {}", artifactId);
2997 error = DaoStatusConverter.convertCassandraStatusToStorageStatus(artifactFromCassandra.right()
2999 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
3000 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
3001 resultOp = Either.right(responseFormat);
3004 // clone data to new artifact
3005 artifactData.setData(artifactFromCassandra.left().value().getData());
3006 artifactData.setId(artifactFromCassandra.left().value().getId());
3009 if (artifactDefinition.getEsId() == null) {
3010 artifactDefinition.setEsId(artifactDefinition.getUniqueId());
3011 artifactData.setId(artifactDefinition.getUniqueId());
3015 NodeTypeEnum convertParentType = convertParentType(componentType);
3016 Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.updateArtifactOnResource(artifactInfo, parent
3017 .getUniqueId(), artifactId, convertParentType, parentId);
3018 isLeft = result.isLeft();
3020 artifactUniqueId = result.left().value().getUniqueId();
3021 artifactDefinition = result.left().value();
3022 String artifactType = artifactInfo.getArtifactType();
3023 if (NodeTypeEnum.Resource == convertParentType
3024 && (ArtifactTypeEnum.HEAT.getType().equalsIgnoreCase(artifactType)
3025 || ArtifactTypeEnum.HEAT_VOL.getType().equalsIgnoreCase(artifactType)
3026 || ArtifactTypeEnum.HEAT_NET.getType().equalsIgnoreCase(artifactType))
3027 && !artifactUniqueId.equals(artifactId)) {
3028 // need to update the generated id in heat env
3029 Map<String, ArtifactDefinition> deploymentArtifacts = parent.getDeploymentArtifacts();
3030 Optional<Entry<String, ArtifactDefinition>> findFirst = deploymentArtifacts.entrySet()
3032 .filter(a -> a.getValue()
3033 .getGeneratedFromId() != null && a
3035 .getGeneratedFromId()
3036 .equals(artifactId))
3038 if (findFirst.isPresent()) {
3039 ArtifactDefinition artifactEnvInfo = findFirst.get().getValue();
3040 artifactEnvInfo.setArtifactChecksum(null);
3041 artifactToscaOperation.updateHeatEnvArtifact(parent.getUniqueId(), artifactEnvInfo, artifactId, artifactUniqueId, convertParentType, parentId);
3044 error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentType);
3046 insideEither = Either.left(result.left().value());
3047 resultOp = Either.left(insideEither);
3048 if (error != StorageOperationStatus.OK) {
3053 error = result.right().value();
3057 // create new entry in ES
3059 if (artifactData.getData() != null) {
3060 if (!artifactDefinition.getDuplicated() || artifactData.getId() == null) {
3061 artifactData.setId(artifactDefinition.getEsId());
3063 res = saveArtifacts(artifactData, parentId);
3069 log.debug(ARTIFACT_SAVED, artifactUniqueId);
3070 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
3071 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
3073 BeEcompErrorManager.getInstance().logBeDaoSystemError(UPDATE_ARTIFACT);
3074 log.debug(FAILED_SAVE_ARTIFACT);
3075 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
3076 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
3077 resultOp = Either.right(responseFormat);
3080 return updateArtifactsFlowForInterfaceOperations(parent, parentId, artifactId, artifactInfo, user,
3081 decodedPayload, componentType, auditingAction, interfaceType, operationUuid, artifactData, prevArtifactId,
3082 currArtifactId, artifactDefinition);
3088 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateArtifactsFlowForInterfaceOperations(
3089 Component parent, String parentId, String artifactId, ArtifactDefinition artifactInfo, User user,
3090 byte[] decodedPayload, ComponentTypeEnum componentType, AuditingActionEnum auditingAction, String interfaceType,
3091 String operationUuid, ESArtifactData artifactData, String prevArtifactId, String currArtifactId,
3092 ArtifactDefinition artifactDefinition) {
3093 StorageOperationStatus error;
3094 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp;
3095 if (decodedPayload == null) {
3096 if (!artifactDefinition.getMandatory() || artifactDefinition.getEsId() != null) {
3097 Either<ESArtifactData, CassandraOperationStatus> artifactFromCassandra = artifactCassandraDao.getArtifact(artifactDefinition
3099 if (artifactFromCassandra.isRight()) {
3100 log.debug("Failed to get artifact data from ES for artifact id {}", artifactId);
3101 error = DaoStatusConverter.convertCassandraStatusToStorageStatus(artifactFromCassandra.right()
3103 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
3104 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
3105 resultOp = Either.right(responseFormat);
3108 // clone data to new artifact
3109 artifactData.setData(artifactFromCassandra.left().value().getData());
3110 artifactData.setId(artifactFromCassandra.left().value().getId());
3112 // todo if not exist(first time)
3116 if (artifactDefinition.getEsId() == null) {
3117 artifactDefinition.setEsId(artifactDefinition.getUniqueId());
3118 artifactData.setId(artifactDefinition.getUniqueId());
3121 NodeTypeEnum convertParentType = convertParentType(componentType);
3122 // Set additional fields for artifact
3123 artifactInfo.setArtifactLabel(artifactInfo.getArtifactName());
3124 artifactInfo.setArtifactDisplayName(artifactInfo.getArtifactName());
3126 Either<ArtifactDefinition, StorageOperationStatus> updateArtifactOnResourceEither =
3127 artifactToscaOperation.updateArtifactOnResource(artifactInfo, parent.getUniqueId(), artifactId, convertParentType, parentId);
3128 if(updateArtifactOnResourceEither.isRight()){
3129 log.debug("Failed to persist operation artifact {} in resource, error is {}",artifactInfo.getArtifactName(), updateArtifactOnResourceEither.right().value());
3130 ActionStatus convertedFromStorageResponse = componentsUtils.convertFromStorageResponse(updateArtifactOnResourceEither.right().value());
3131 return Either.right(componentsUtils.getResponseFormat(convertedFromStorageResponse));
3133 if (artifactData.getData() != null) {
3134 CassandraOperationStatus cassandraOperationStatus = artifactCassandraDao.saveArtifact(artifactData);
3135 if(cassandraOperationStatus != CassandraOperationStatus.OK){
3136 log.debug("Failed to persist operation artifact {}, error is {}",artifactInfo.getArtifactName(),cassandraOperationStatus);
3137 StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(cassandraOperationStatus);
3138 ActionStatus convertedFromStorageResponse = componentsUtils.convertFromStorageResponse(storageStatus);
3139 return Either.right(componentsUtils.getResponseFormat(convertedFromStorageResponse));
3143 Either<ArtifactDefinition, ResponseFormat> updateOprEither = updateOperationArtifact(parentId, interfaceType, operationUuid, updateArtifactOnResourceEither.left().value());
3144 if(updateOprEither.isRight()){
3145 return Either.right(updateOprEither.right().value());
3148 return Either.left(Either.left(updateOprEither.left().value()));
3151 private Either<byte[], ResponseFormat> handlePayload(ArtifactDefinition artifactInfo, boolean isArtifactMetadataUpdate) {
3152 log.trace("Starting payload handling");
3153 byte[] payload = artifactInfo.getPayloadData();
3154 byte[] decodedPayload = null;
3156 if (payload != null && payload.length != 0) {
3157 // the generated artifacts were already decoded by the handler
3158 decodedPayload = artifactInfo.getGenerated() ? payload : Base64.decodeBase64(payload);
3159 if (decodedPayload.length == 0) {
3160 log.debug("Failed to decode the payload.");
3161 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
3162 return Either.right(responseFormat);
3165 String checkSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(decodedPayload);
3166 artifactInfo.setArtifactChecksum(checkSum);
3167 log.trace("Calculated checksum, base64 payload: {}, checksum: {}", payload, checkSum);
3169 // Specific payload validations of different types
3170 Either<Boolean, ResponseFormat> result = Either.left(true);
3171 if (isDeploymentArtifact(artifactInfo)) {
3172 log.trace("Starting deployment artifacts payload validation");
3173 String artifactType = artifactInfo.getArtifactType();
3174 String fileExtension = GeneralUtility.getFilenameExtension(artifactInfo.getArtifactName());
3175 PayloadTypeEnum payloadType = ArtifactTypeToPayloadTypeSelector.getPayloadType(artifactType, fileExtension);
3176 Either<Boolean, ActionStatus> isPayloadValid = payloadType.isValid(decodedPayload);
3177 if (isPayloadValid.isRight()) {
3178 ResponseFormat responseFormat = componentsUtils.getResponseFormat(isPayloadValid.right().value(), artifactType);
3179 return Either.right(responseFormat);
3182 if (payloadType.isHeatRelated()) {
3183 log.trace("Payload is heat related so going to extract heat parameters for artifact type {}", artifactType);
3184 result = extractHeatParameters(artifactInfo);
3187 if (result.isRight()) {
3188 return Either.right(result.right().value());
3191 } // null/empty payload is normal if called from metadata update ONLY.
3192 // The validation of whether this is metadata/payload update case is
3193 // currently done separately
3195 if (!isArtifactMetadataUpdate) {
3196 log.debug("In artifact: {} Payload is missing.",artifactInfo.getArtifactName());
3197 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
3198 return Either.right(responseFormat);
3201 log.trace("Ended payload handling");
3202 return Either.left(decodedPayload);
3205 public Either<Operation, ResponseFormat> deleteArtifactByInterface(String resourceId, String userUserId, String artifactId,
3206 boolean inTransaction) {
3207 User user = new User();
3208 user.setUserId(userUserId);
3209 Either<Resource, StorageOperationStatus> parent = toscaOperationFacade.getToscaElement(resourceId, JsonParseFlagEnum.ParseMetadata);
3210 if (parent.isRight()) {
3211 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(parent
3214 return Either.right(responseFormat);
3216 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = handleDelete(resourceId, artifactId, user, AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, parent
3219 false, inTransaction);
3220 if (handleDelete.isRight()) {
3221 return Either.right(handleDelete.right().value());
3223 Either<ArtifactDefinition, Operation> result = handleDelete.left().value();
3224 return Either.left(result.right().value());
3228 private Operation convertToOperation(ArtifactDefinition artifactInfo, String operationName) {
3229 Operation op = new Operation();
3230 long time = System.currentTimeMillis();
3231 op.setCreationDate(time);
3233 String artifactName = artifactInfo.getArtifactName();
3234 artifactInfo.setArtifactName(createInterfaceArtifactNameFromOperation(operationName, artifactName));
3236 op.setImplementation(artifactInfo);
3237 op.setLastUpdateDate(time);
3241 private String createInterfaceArtifactNameFromOperation(String operationName, String artifactName) {
3242 String newArtifactName = operationName + "_" + artifactName;
3243 log.trace("converting artifact name {} to {}", artifactName, newArtifactName);
3244 return newArtifactName;
3248 public Either<byte[], ResponseFormat> downloadRsrcArtifactByNames(String serviceName, String serviceVersion, String resourceName, String resourceVersion, String artifactName) {
3250 // General validation
3251 if (serviceName == null || serviceVersion == null || resourceName == null || resourceVersion == null || artifactName == null) {
3252 log.debug(NULL_PARAMETER);
3253 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
3256 // Normalizing artifact name
3257 artifactName = ValidationUtils.normalizeFileName(artifactName);
3259 // Resource validation
3260 Either<Resource, ResponseFormat> validateResourceNameAndVersion = validateResourceNameAndVersion(resourceName, resourceVersion);
3261 if (validateResourceNameAndVersion.isRight()) {
3262 return Either.right(validateResourceNameAndVersion.right().value());
3265 Resource resource = validateResourceNameAndVersion.left().value();
3266 String resourceId = resource.getUniqueId();
3268 // Service validation
3269 Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
3270 if (validateServiceNameAndVersion.isRight()) {
3271 return Either.right(validateServiceNameAndVersion.right().value());
3274 Map<String, ArtifactDefinition> artifacts = resource.getDeploymentArtifacts();
3275 if (artifacts == null || artifacts.isEmpty()) {
3276 log.debug("Deployment artifacts of resource {} are not found", resourceId);
3277 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
3280 ArtifactDefinition deploymentArtifact = null;
3282 for (ArtifactDefinition artifactDefinition : artifacts.values()) {
3283 if (artifactDefinition.getArtifactName() != null && artifactDefinition.getArtifactName()
3284 .equals(artifactName)) {
3285 log.debug(FOUND_DEPLOYMENT_ARTIFACT, artifactName);
3286 deploymentArtifact = artifactDefinition;
3291 if (deploymentArtifact == null) {
3292 log.debug("No deployment artifact {} was found for resource {}", artifactName, resourceId);
3293 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
3296 // Downloading the artifact
3297 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(deploymentArtifact);
3298 if (downloadArtifactEither.isRight()) {
3299 log.debug(FAILED_DOWNLOAD_ARTIFACT, artifactName);
3300 return Either.right(downloadArtifactEither.right().value());
3302 log.trace("Download of resource artifact succeeded, uniqueId {}", deploymentArtifact.getUniqueId());
3303 return Either.left(downloadArtifactEither.left().value().getRight());
3307 public Either<byte[], ResponseFormat> downloadRsrcInstArtifactByNames(String serviceName, String serviceVersion, String resourceInstanceName, String artifactName) {
3309 // General validation
3310 if (serviceName == null || serviceVersion == null || resourceInstanceName == null || artifactName == null) {
3311 log.debug(NULL_PARAMETER);
3312 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
3315 // Normalizing artifact name
3316 artifactName = ValidationUtils.normalizeFileName(artifactName);
3318 // Service validation
3319 Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
3320 if (validateServiceNameAndVersion.isRight()) {
3321 return Either.right(validateServiceNameAndVersion.right().value());
3324 Service service = validateServiceNameAndVersion.left().value();
3326 // ResourceInstance validation
3327 Either<ComponentInstance, ResponseFormat> validateResourceInstance = validateResourceInstance(service, resourceInstanceName);
3328 if (validateResourceInstance.isRight()) {
3329 return Either.right(validateResourceInstance.right().value());
3332 ComponentInstance resourceInstance = validateResourceInstance.left().value();
3334 Map<String, ArtifactDefinition> artifacts = resourceInstance.getDeploymentArtifacts();
3336 final String finalArtifactName = artifactName;
3337 Predicate<ArtifactDefinition> filterArtifactByName = p -> p.getArtifactName().equals(finalArtifactName);
3339 boolean hasDeploymentArtifacts = artifacts != null && artifacts.values()
3341 .anyMatch(filterArtifactByName);
3342 ArtifactDefinition deployableArtifact;
3344 if (!hasDeploymentArtifacts) {
3345 log.debug("Deployment artifact with name {} not found", artifactName);
3346 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
3349 log.debug(FOUND_DEPLOYMENT_ARTIFACT, artifactName);
3350 deployableArtifact = artifacts.values().stream().filter(filterArtifactByName).findFirst().get();
3351 // Downloading the artifact
3352 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(deployableArtifact);
3354 if (downloadArtifactEither.isRight()) {
3355 log.debug(FAILED_DOWNLOAD_ARTIFACT, artifactName);
3356 return Either.right(downloadArtifactEither.right().value());
3358 log.trace("Download of resource artifact succeeded, uniqueId {}", deployableArtifact.getUniqueId());
3359 return Either.left(downloadArtifactEither.left().value().getRight());
3362 private Either<ComponentInstance, ResponseFormat> validateResourceInstance(Service service, String resourceInstanceName) {
3364 List<ComponentInstance> riList = service.getComponentInstances();
3365 for (ComponentInstance ri : riList) {
3366 if (ri.getNormalizedName().equals(resourceInstanceName)) {
3367 return Either.left(ri);
3371 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND, resourceInstanceName));
3374 private Either<Service, ResponseFormat> validateServiceNameAndVersion(String serviceName, String serviceVersion) {
3376 Either<List<Service>, StorageOperationStatus> serviceListBySystemName = toscaOperationFacade.getBySystemName(ComponentTypeEnum.SERVICE, serviceName);
3377 if (serviceListBySystemName.isRight()) {
3378 log.debug("Couldn't fetch any service with name {}", serviceName);
3379 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceListBySystemName
3381 .value(), ComponentTypeEnum.SERVICE), serviceName));
3383 List<Service> serviceList = serviceListBySystemName.left().value();
3384 if (serviceList == null || serviceList.isEmpty()) {
3385 log.debug("Couldn't fetch any service with name {}", serviceName);
3386 return Either.right(componentsUtils.getResponseFormat(ActionStatus.SERVICE_NOT_FOUND, serviceName));
3389 Service foundService = null;
3390 for (Service service : serviceList) {
3391 if (service.getVersion().equals(serviceVersion)) {
3392 log.trace("Found service with version {}", serviceVersion);
3393 foundService = service;
3398 if (foundService == null) {
3399 log.debug("Couldn't find version {} for service {}", serviceVersion, serviceName);
3400 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_VERSION_NOT_FOUND, ComponentTypeEnum.SERVICE
3401 .getValue(), serviceVersion));
3403 return Either.left(foundService);
3406 private Either<Resource, ResponseFormat> validateResourceNameAndVersion(String resourceName, String resourceVersion) {
3408 Either<Resource, StorageOperationStatus> resourceListBySystemName = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, resourceVersion, JsonParseFlagEnum.ParseMetadata);
3409 if (resourceListBySystemName.isRight()) {
3410 log.debug("Couldn't fetch any resource with name {} and version {}. ", resourceName, resourceVersion);
3411 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceListBySystemName
3413 .value()), resourceName));
3415 return Either.left(resourceListBySystemName.left().value());
3418 public Either<byte[], ResponseFormat> downloadServiceArtifactByNames(String serviceName, String serviceVersion, String artifactName) {
3420 log.trace("Starting download of service interface artifact, serviceName {}, serviceVersion {}, artifact name {}", serviceName, serviceVersion, artifactName);
3421 if (serviceName == null || serviceVersion == null || artifactName == null) {
3422 log.debug(NULL_PARAMETER);
3423 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
3426 // Normalizing artifact name
3427 final String normalizedArtifactName = ValidationUtils.normalizeFileName(artifactName);
3429 // Service validation
3430 Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
3431 if (validateServiceNameAndVersion.isRight()) {
3432 return Either.right(validateServiceNameAndVersion.right().value());
3435 String serviceId = validateServiceNameAndVersion.left().value().getUniqueId();
3437 // Looking for deployment or tosca artifacts
3438 Service service = validateServiceNameAndVersion.left().value();
3440 if (MapUtils.isEmpty(service.getDeploymentArtifacts()) && MapUtils.isEmpty(service.getToscaArtifacts())) {
3441 log.debug("Neither Deployment nor Tosca artifacts of service {} are found", serviceId);
3442 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, normalizedArtifactName));
3445 Optional<ArtifactDefinition> foundArtifactOptl = null;
3447 if (!MapUtils.isEmpty(service.getDeploymentArtifacts())) {
3448 foundArtifactOptl = service.getDeploymentArtifacts().values().stream()
3449 // filters artifact by name
3450 .filter(a -> a.getArtifactName().equals(normalizedArtifactName)).findAny();
3452 if ((foundArtifactOptl == null || !foundArtifactOptl.isPresent()) && !MapUtils.isEmpty(service.getToscaArtifacts())) {
3453 foundArtifactOptl = service.getToscaArtifacts().values().stream()
3454 // filters TOSCA artifact by name
3455 .filter(a -> a.getArtifactName().equals(normalizedArtifactName)).findAny();
3457 if (!foundArtifactOptl.isPresent()) {
3458 log.debug("The artifact {} was not found for service {}", normalizedArtifactName, serviceId);
3459 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, normalizedArtifactName));
3461 log.debug(FOUND_DEPLOYMENT_ARTIFACT, normalizedArtifactName);
3462 // Downloading the artifact
3463 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(foundArtifactOptl
3465 if (downloadArtifactEither.isRight()) {
3466 log.debug(FAILED_DOWNLOAD_ARTIFACT, normalizedArtifactName);
3467 return Either.right(downloadArtifactEither.right().value());
3469 log.trace("Download of service artifact succeeded, uniqueId {}", foundArtifactOptl.get().getUniqueId());
3470 return Either.left(downloadArtifactEither.left().value().getRight());
3473 public Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifact(String parentId, String artifactUniqueId) {
3474 log.trace("Starting download of artifact, uniqueId {}", artifactUniqueId);
3475 Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(parentId, artifactUniqueId);
3476 if (artifactById.isRight()) {
3477 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(artifactById.right().value());
3478 log.debug("Error when getting artifact info by id{}, error: {}", artifactUniqueId, actionStatus);
3479 return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, ""));
3481 ArtifactDefinition artifactDefinition = artifactById.left().value();
3482 if (artifactDefinition == null) {
3483 log.debug("Empty artifact definition returned from DB by artifact id {}", artifactUniqueId);
3484 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ""));
3487 return downloadArtifact(artifactDefinition);
3490 private boolean checkArtifactInComponent(org.openecomp.sdc.be.model.Component component, String artifactId) {
3491 boolean found = false;
3492 Map<String, ArtifactDefinition> artifactsS = component.getArtifacts();
3493 if (artifactsS != null) {
3494 for (Map.Entry<String, ArtifactDefinition> entry : artifactsS.entrySet()) {
3495 if (entry.getValue().getUniqueId().equals(artifactId)) {
3501 Map<String, ArtifactDefinition> deploymentArtifactsS = component.getDeploymentArtifacts();
3502 if (!found && deploymentArtifactsS != null) {
3503 for (Map.Entry<String, ArtifactDefinition> entry : deploymentArtifactsS.entrySet()) {
3504 if (entry.getValue().getUniqueId().equals(artifactId)) {
3510 Map<String, ArtifactDefinition> toscaArtifactsS = component.getToscaArtifacts();
3511 if (!found && toscaArtifactsS != null) {
3512 for (Map.Entry<String, ArtifactDefinition> entry : toscaArtifactsS.entrySet()) {
3513 if (entry.getValue().getUniqueId().equals(artifactId)) {
3520 Map<String, InterfaceDefinition> interfaces = component.getInterfaces();
3521 if (!found && interfaces != null) {
3522 for (Map.Entry<String, InterfaceDefinition> entry : interfaces.entrySet()) {
3523 Map<String, Operation> operations = entry.getValue().getOperationsMap();
3524 for (Map.Entry<String, Operation> entryOp : operations.entrySet()) {
3525 if (entryOp.getValue().getImplementation() != null && entryOp.getValue()
3526 .getImplementation()
3528 .equals(artifactId)) {
3536 switch (component.getComponentType()) {
3540 Map<String, ArtifactDefinition> apiArtifacts = ((Service) component).getServiceApiArtifacts();
3541 if (!found && apiArtifacts != null) {
3542 for (Map.Entry<String, ArtifactDefinition> entry : apiArtifacts.entrySet()) {
3543 if (entry.getValue().getUniqueId().equals(artifactId)) {
3557 private boolean checkArtifactInResourceInstance(Component component, String resourceInstanceId, String artifactId) {
3559 boolean found = false;
3560 List<ComponentInstance> resourceInstances = component.getComponentInstances();
3561 ComponentInstance resourceInstance = null;
3562 for (ComponentInstance ri : resourceInstances) {
3563 if (ri.getUniqueId().equals(resourceInstanceId)) {
3564 resourceInstance = ri;
3568 if (resourceInstance != null) {
3569 Map<String, ArtifactDefinition> artifacts = resourceInstance.getDeploymentArtifacts();
3570 if (artifacts != null) {
3571 for (Map.Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) {
3572 if (entry.getValue().getUniqueId().equals(artifactId)) {
3579 artifacts = resourceInstance.getArtifacts();
3580 if (artifacts != null) {
3581 for (Map.Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) {
3582 if (entry.getValue().getUniqueId().equals(artifactId)) {
3593 private Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists(String componentId, AuditingActionEnum auditingAction, User user, String artifactId, ComponentTypeEnum componentType,
3594 String containerComponentType) {
3596 ComponentTypeEnum componentForAudit = null == containerComponentType ? componentType : ComponentTypeEnum.findByParamName(containerComponentType);
3597 componentForAudit.getNodeType();
3599 Either<? extends org.openecomp.sdc.be.model.Component, StorageOperationStatus> componentResult = toscaOperationFacade
3600 .getToscaFullElement(componentId);
3602 if (componentResult.isRight()) {
3603 ActionStatus status = componentForAudit == ComponentTypeEnum.RESOURCE ? ActionStatus.RESOURCE_NOT_FOUND : componentType == ComponentTypeEnum.SERVICE ? ActionStatus.SERVICE_NOT_FOUND : ActionStatus.PRODUCT_NOT_FOUND;
3604 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, componentId);
3605 log.debug("Service not found, serviceId {}", componentId);
3606 handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentForAudit, null);
3607 return Either.right(responseFormat);
3609 return Either.left(componentResult.left().value());
3612 private Either<Boolean, ResponseFormat> validateWorkOnComponent(Component component, String userId, AuditingActionEnum auditingAction, User user, String artifactId, ArtifactOperationInfo operation) {
3613 if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.DOWNLOAD && !operation.ignoreLifecycleState()) {
3614 Either<Boolean, ResponseFormat> canWork = validateCanWorkOnComponent(component, userId);
3615 if (canWork.isRight()) {
3616 String uniqueId = component.getUniqueId();
3617 log.debug("Service status isn't CHECKOUT or user isn't owner, serviceId {}", uniqueId);
3618 handleAuditing(auditingAction, component, uniqueId, user, null, null, artifactId, canWork.right()
3620 .getComponentType(), null);
3621 return Either.right(canWork.right().value());
3624 return Either.left(true);
3627 private Either<Boolean, ResponseFormat> validateUserRole(User user, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType, ArtifactOperationInfo operation) {
3629 if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.DOWNLOAD) {
3630 String role = user.getRole();
3631 if (!role.equals(Role.ADMIN.name()) && !role.equals(Role.DESIGNER.name())) {
3632 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
3633 log.debug("addArtifact - user isn't permitted to perform operation, userId {}, role {}", user.getUserId(), role);
3634 handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentType, null);
3635 return Either.right(responseFormat);
3638 return Either.left(true);
3641 private Either<User, ResponseFormat> validateUserExists(String userId, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType, boolean inTransaction) {
3644 user = validateUserExists(userId, auditingAction.getName(), inTransaction);
3645 } catch(ByResponseFormatComponentException e){
3646 ResponseFormat responseFormat = e.getResponseFormat();
3647 handleComponentException(auditingAction, componentId, artifactId, responseFormat, componentType, userId);
3649 } catch(ByActionStatusComponentException e){
3650 ResponseFormat responseFormat = componentsUtils.getResponseFormat(e.getActionStatus(), e.getParams());
3651 handleComponentException(auditingAction, componentId, artifactId, responseFormat, componentType, userId);
3654 return Either.left(user);
3657 private void handleComponentException(AuditingActionEnum auditingAction, String componentId, String artifactId,
3658 ResponseFormat responseFormat, ComponentTypeEnum componentType, String userId){
3659 User user = new User();
3660 user.setUserId(userId);
3661 handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentType, null);
3664 protected AuditingActionEnum detectAuditingType(ArtifactOperationInfo operation, String origMd5) {
3665 AuditingActionEnum auditingAction = null;
3666 switch (operation.getArtifactOperationEnum()) {
3668 auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_UPLOAD_BY_API : AuditingActionEnum.ARTIFACT_UPLOAD;
3671 auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_UPLOAD_BY_API : origMd5 == null ? AuditingActionEnum.ARTIFACT_METADATA_UPDATE : AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE;
3674 auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_DELETE_BY_API : AuditingActionEnum.ARTIFACT_DELETE;
3677 auditingAction = operation.isExternalApi() ? AuditingActionEnum.DOWNLOAD_ARTIFACT : AuditingActionEnum.ARTIFACT_DOWNLOAD;
3682 return auditingAction;
3685 private Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifact(ArtifactDefinition artifactDefinition) {
3686 String esArtifactId = artifactDefinition.getEsId();
3687 Either<ESArtifactData, CassandraOperationStatus> artifactfromES = artifactCassandraDao.getArtifact(esArtifactId);
3688 if (artifactfromES.isRight()) {
3689 CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value();
3690 StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
3691 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
3692 log.debug("Error when getting artifact from ES, error: {}", actionStatus);
3693 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(actionStatus, artifactDefinition
3694 .getArtifactDisplayName());
3696 return Either.right(responseFormat);
3699 ESArtifactData esArtifactData = artifactfromES.left().value();
3700 byte[] data = esArtifactData.getDataAsArray();
3702 log.debug("Artifact data from ES is null");
3703 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactDefinition.getArtifactDisplayName()));
3705 String artifactName = artifactDefinition.getArtifactName();
3706 log.trace("Download of artifact succeeded, uniqueId {}, artifact file name {}", artifactDefinition.getUniqueId(), artifactName);
3707 return Either.left(new ImmutablePair<String, byte[]>(artifactName, data));
3710 public ESArtifactData createEsArtifactData(ArtifactDataDefinition artifactInfo, byte[] artifactPayload) {
3711 return new ESArtifactData(artifactInfo.getEsId(), artifactPayload);
3714 private boolean saveArtifacts(ESArtifactData artifactData, String resourceId) {
3715 CassandraOperationStatus resourceUploadStatus = artifactCassandraDao.saveArtifact(artifactData);
3717 if (resourceUploadStatus.equals(CassandraOperationStatus.OK)) {
3718 log.debug("Artifact {} was saved in component .", artifactData.getId(), resourceId);
3721 log.info("Failed to save artifact {}.", artifactData.getId());
3727 private boolean isArtifactMetadataUpdate(AuditingActionEnum auditingActionEnum) {
3728 return auditingActionEnum.equals(AuditingActionEnum.ARTIFACT_METADATA_UPDATE);
3731 private boolean isDeploymentArtifact(ArtifactDefinition artifactInfo) {
3732 return ArtifactGroupTypeEnum.DEPLOYMENT.equals(artifactInfo.getArtifactGroupType());
3735 public Either<ArtifactDefinition, ResponseFormat> createArtifactPlaceHolderInfo(String resourceId, String logicalName, Map<String, Object> artifactInfoMap, String userUserId, ArtifactGroupTypeEnum groupType, boolean inTransaction) {
3736 Either<User, ActionStatus> user = userAdminManager.getUser(userUserId, inTransaction);
3737 if (user.isRight()) {
3738 ResponseFormat responseFormat;
3739 if (user.right().value().equals(ActionStatus.USER_NOT_FOUND)) {
3740 log.debug("create artifact placeholder - not authorized user, userId {}", userUserId);
3741 responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
3744 log.debug("create artifact placeholder - failed to authorize user, userId {}", userUserId);
3745 responseFormat = componentsUtils.getResponseFormat(user.right().value());
3747 return Either.right(responseFormat);
3750 ArtifactDefinition artifactDefinition = createArtifactPlaceHolderInfo(resourceId, logicalName, artifactInfoMap, user
3752 .value(), groupType);
3753 return Either.left(artifactDefinition);
3756 public ArtifactDefinition createArtifactPlaceHolderInfo(String resourceId, String logicalName, Map<String, Object> artifactInfoMap, User user, ArtifactGroupTypeEnum groupType) {
3757 ArtifactDefinition artifactInfo = new ArtifactDefinition();
3759 String artifactName = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_DISPLAY_NAME);
3760 String artifactType = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_TYPE);
3761 String artifactDescription = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_DESCRIPTION);
3763 artifactInfo.setArtifactDisplayName(artifactName);
3764 artifactInfo.setArtifactLabel(logicalName.toLowerCase());
3765 artifactInfo.setArtifactType(artifactType);
3766 artifactInfo.setDescription(artifactDescription);
3767 artifactInfo.setArtifactGroupType(groupType);
3768 nodeTemplateOperation.setDefaultArtifactTimeout(groupType, artifactInfo);
3770 setArtifactPlaceholderCommonFields(resourceId, user, artifactInfo);
3772 return artifactInfo;
3775 private void setArtifactPlaceholderCommonFields(String resourceId, User user, ArtifactDefinition artifactInfo) {
3776 String uniqueId = null;
3778 if (resourceId != null) {
3779 uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId.toLowerCase(), artifactInfo.getArtifactLabel()
3781 artifactInfo.setUniqueId(uniqueId);
3783 artifactInfo.setUserIdCreator(user.getUserId());
3784 String fullName = user.getFullName();
3785 artifactInfo.setUpdaterFullName(fullName);
3787 long time = System.currentTimeMillis();
3789 artifactInfo.setCreatorFullName(fullName);
3790 artifactInfo.setCreationDate(time);
3792 artifactInfo.setLastUpdateDate(time);
3793 artifactInfo.setUserIdLastUpdater(user.getUserId());
3795 artifactInfo.setMandatory(true);
3798 public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(String parentId, NodeTypeEnum parentType, ArtifactGroupTypeEnum groupType, String instanceId) {
3799 return artifactToscaOperation.getArtifacts(parentId, parentType, groupType, instanceId);
3802 public Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact(ArtifactDefinition artifactHeatEnv, ArtifactDefinition artifact, String componentId, NodeTypeEnum parentType, String instanceId) {
3803 return artifactToscaOperation.addHeatEnvArtifact(artifactHeatEnv, artifact, componentId, parentType, true, instanceId);
3806 private Either<ESArtifactData, ResponseFormat> createEsHeatEnvArtifactDataFromString(ArtifactDefinition artifactDefinition, String payloadStr) {
3808 byte[] payload = payloadStr.getBytes();
3810 ESArtifactData artifactData = createEsArtifactData(artifactDefinition, payload);
3811 return Either.left(artifactData);
3815 * @param artifactDefinition
3818 public Either<ArtifactDefinition, ResponseFormat> generateHeatEnvArtifact(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier,
3819 String instanceId, boolean shouldLock, boolean inTransaction) {
3820 String payload = generateHeatEnvPayload(artifactDefinition);
3821 String prevUUID = artifactDefinition.getArtifactUUID();
3822 ArtifactDefinition clonedBeforeGenerate = new ArtifactDefinition(artifactDefinition);
3823 return generateAndSaveHeatEnvArtifact(artifactDefinition, payload, componentType, component, resourceInstanceName, modifier, instanceId, shouldLock, inTransaction)
3825 .bind(artifactDef -> updateArtifactOnGroupInstance(componentType, component, instanceId, prevUUID, clonedBeforeGenerate, artifactDef));
3828 public Either<ArtifactDefinition, ResponseFormat> forceGenerateHeatEnvArtifact(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier,
3829 boolean shouldLock, boolean inTransaction, String instanceId) {
3830 String payload = generateHeatEnvPayload(artifactDefinition);
3831 String prevUUID = artifactDefinition.getArtifactUUID();
3832 ArtifactDefinition clonedBeforeGenerate = new ArtifactDefinition(artifactDefinition);
3833 return forceGenerateAndSaveHeatEnvArtifact(artifactDefinition, payload, componentType, component, resourceInstanceName, modifier, instanceId, shouldLock, inTransaction)
3835 .bind(artifactDef -> updateArtifactOnGroupInstance(componentType, component, instanceId, prevUUID, clonedBeforeGenerate, artifactDef));
3838 private Either<ArtifactDefinition, ResponseFormat> updateArtifactOnGroupInstance(ComponentTypeEnum componentType, Component component, String instanceId, String prevUUID, ArtifactDefinition clonedBeforeGenerate, ArtifactDefinition updatedArtDef) {
3839 if (prevUUID == null || !prevUUID.equals(updatedArtDef.getArtifactUUID())) {
3840 List<ComponentInstance> componentInstances = component.getComponentInstances();
3841 if (componentInstances != null) {
3842 Optional<ComponentInstance> findFirst = componentInstances.stream()
3843 .filter(ci -> ci.getUniqueId()
3844 .equals(instanceId))
3846 if (findFirst.isPresent()) {
3847 ComponentInstance relevantInst = findFirst.get();
3848 List<GroupInstance> updatedGroupInstances = getUpdatedGroupInstances(updatedArtDef.getUniqueId(), clonedBeforeGenerate, relevantInst
3849 .getGroupInstances());
3851 if (CollectionUtils.isNotEmpty(updatedGroupInstances)) {
3852 updatedGroupInstances.forEach(gi -> {
3853 gi.getGroupInstanceArtifacts().add(updatedArtDef.getUniqueId());
3854 gi.getGroupInstanceArtifactsUuid().add(updatedArtDef.getArtifactUUID());
3856 Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(component, instanceId, updatedGroupInstances);
3857 if (status.isRight()) {
3858 log.debug(FAILED_UPDATE_GROUPS, component.getUniqueId());
3859 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils
3860 .convertFromStorageResponse(status.right()
3861 .value()), clonedBeforeGenerate.getArtifactDisplayName());
3862 return Either.right(responseFormat);
3868 return Either.left(updatedArtDef);
3871 private String generateHeatEnvPayload(ArtifactDefinition artifactDefinition) {
3872 List<HeatParameterDefinition> heatParameters = artifactDefinition.getListHeatParameters();
3873 StringBuilder sb = new StringBuilder();
3874 sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactHeader());
3875 sb.append("parameters:\n");
3876 if (heatParameters != null) {
3877 heatParameters.sort(Comparator.comparing(e -> e.getName()));
3879 List<HeatParameterDefinition> empltyHeatValues = new ArrayList<>();
3881 for (HeatParameterDefinition heatParameterDefinition : heatParameters) {
3883 String heatValue = heatParameterDefinition.getCurrentValue();
3884 if (!ValidationUtils.validateStringNotEmpty(heatValue)) {
3885 heatValue = heatParameterDefinition.getDefaultValue();
3886 if (!ValidationUtils.validateStringNotEmpty(heatValue)) {
3887 empltyHeatValues.add(heatParameterDefinition);
3891 HeatParameterType type = HeatParameterType.isValidType(heatParameterDefinition.getType());
3896 .append(heatParameterDefinition.getName())
3899 .append(Boolean.parseBoolean(heatValue))
3904 .append(heatParameterDefinition.getName())
3907 .append(new BigDecimal(heatValue).toPlainString())
3910 case COMMA_DELIMITED_LIST:
3913 .append(heatParameterDefinition.getName())
3920 String value = heatValue;
3921 boolean starts = value.startsWith("\"");
3922 boolean ends = value.endsWith("\"");
3923 if (!(starts && ends)) {
3924 starts = value.startsWith("'");
3925 ends = value.endsWith("'");
3926 if (!(starts && ends)) {
3927 value = "\"" + value + "\"";
3931 .append(heatParameterDefinition.getName())
3941 if (!empltyHeatValues.isEmpty()) {
3942 empltyHeatValues.sort(Comparator.comparing(e -> e.getName()));
3943 empltyHeatValues.forEach(hv -> {
3944 sb.append(" ").append(hv.getName()).append(":");
3945 HeatParameterType type = HeatParameterType.isValidType(hv.getType());
3946 if (type != null && type == HeatParameterType.STRING && (hv.getCurrentValue() != null && "".equals(hv
3947 .getCurrentValue()) || hv.getDefaultValue() != null && "".equals(hv.getDefaultValue()))) {
3948 sb.append(" \"\"").append("\n");
3951 sb.append(" ").append("\n");
3956 sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactFooter());
3959 return sb.toString().replaceAll("\\\\n", "\n");
3963 * @param artifactDefinition
3967 public Either<ArtifactDefinition, ResponseFormat> generateAndSaveHeatEnvArtifact(ArtifactDefinition artifactDefinition, String payload, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName,
3968 User modifier, String instanceId, boolean shouldLock, boolean inTransaction) {
3969 return generateArtifactPayload(artifactDefinition, componentType, component, resourceInstanceName, modifier, shouldLock, inTransaction, () -> artifactDefinition
3970 .getHeatParamsUpdateDate(),
3971 () -> createEsHeatEnvArtifactDataFromString(artifactDefinition, payload), instanceId);
3975 public Either<ArtifactDefinition, ResponseFormat> forceGenerateAndSaveHeatEnvArtifact(ArtifactDefinition artifactDefinition, String payload, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName,
3976 User modifier, String instanceId, boolean shouldLock, boolean inTransaction) {
3977 return generateArtifactPayload(artifactDefinition, componentType, component, resourceInstanceName, modifier, shouldLock, inTransaction, System::currentTimeMillis,
3978 () -> createEsHeatEnvArtifactDataFromString(artifactDefinition, payload), instanceId);
3982 protected Either<ArtifactDefinition, ResponseFormat> generateArtifactPayload(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier,
3983 boolean shouldLock, boolean inTransaction, Supplier<Long> payloadUpdateDateGen, Supplier<Either<ESArtifactData, ResponseFormat>> esDataCreator, String instanceId) {
3985 log.trace("Start generating payload for {} artifact {}", artifactDefinition.getArtifactType(), artifactDefinition
3987 if (artifactDefinition.getPayloadUpdateDate() == null || artifactDefinition.getPayloadUpdateDate() == 0 || artifactDefinition
3988 .getPayloadUpdateDate() <= payloadUpdateDateGen.get()) {
3990 log.trace("Generating payload for {} artifact {}", artifactDefinition.getArtifactType(), artifactDefinition.getEsId());
3991 Either<ESArtifactData, ResponseFormat> artifactDataRes = esDataCreator.get();
3992 ESArtifactData artifactData = null;
3994 if (artifactDataRes.isLeft()) {
3995 artifactData = artifactDataRes.left().value();
3998 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
3999 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
4000 .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
4001 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
4003 return Either.right(artifactDataRes.right().value());
4005 String newCheckSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(artifactData.getDataAsArray());
4007 String esArtifactId = artifactDefinition.getEsId();
4008 Either<ESArtifactData, CassandraOperationStatus> artifactfromES;
4009 ESArtifactData esArtifactData;
4010 if (esArtifactId != null && !esArtifactId.isEmpty() && artifactDefinition.getPayloadData() == null) {
4011 log.debug("Try to fetch artifact from cassandra with id : {}", esArtifactId);
4012 artifactfromES = artifactCassandraDao.getArtifact(esArtifactId);
4013 if (artifactfromES.isRight()) {
4014 CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value();
4015 StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
4016 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
4017 log.debug("Error when getting artifact from ES, error: {} esid : {}", actionStatus, esArtifactId);
4018 return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, artifactDefinition.getArtifactDisplayName()));
4020 esArtifactData = artifactfromES.left().value();
4021 oldCheckSum = GeneralUtility.calculateMD5Base64EncodedByByteArray(esArtifactData.getDataAsArray());
4024 oldCheckSum = artifactDefinition.getArtifactChecksum();
4027 Either<ArtifactDefinition, StorageOperationStatus> updateArifactDefinitionStatus = null;
4030 Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, "Update Artifact - lock resource: ");
4031 if (lockComponent.isRight()) {
4032 handleAuditing(AuditingActionEnum.ARTIFACT_METADATA_UPDATE, component, component.getUniqueId(), modifier, null, null, artifactDefinition
4033 .getUniqueId(), lockComponent.right().value(), component.getComponentType(), null);
4034 return Either.right(lockComponent.right().value());
4038 if (oldCheckSum != null && oldCheckSum.equals(newCheckSum)) {
4040 artifactDefinition.setPayloadUpdateDate(payloadUpdateDateGen.get());
4041 updateArifactDefinitionStatus = artifactToscaOperation.updateArtifactOnResource(artifactDefinition, component
4042 .getUniqueId(), artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId);
4043 log.trace("No real update done in payload for {} artifact, updating payloadUpdateDate {}", artifactDefinition
4044 .getArtifactType(), artifactDefinition.getEsId());
4045 if (updateArifactDefinitionStatus.isRight()) {
4046 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus
4048 .value()), artifactDefinition.getArtifactDisplayName());
4049 log.trace("Failed to update payloadUpdateDate {}", artifactDefinition.getEsId());
4050 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
4051 .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
4052 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
4054 return Either.right(responseFormat);
4059 oldCheckSum = artifactDefinition.getArtifactChecksum();
4060 artifactDefinition.setArtifactChecksum(newCheckSum);
4061 artifactDefinition.setEsId(artifactDefinition.getUniqueId());
4062 log.trace("No real update done in payload for {} artifact, updating payloadUpdateDate {}", artifactDefinition
4063 .getArtifactType(), artifactDefinition.getEsId());
4064 updateArifactDefinitionStatus = artifactToscaOperation.updateArtifactOnResource(artifactDefinition, component
4065 .getUniqueId(), artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId);
4067 log.trace("Update Payload ", artifactDefinition.getEsId());
4069 if (updateArifactDefinitionStatus != null && updateArifactDefinitionStatus.isLeft()) {
4071 artifactDefinition = updateArifactDefinitionStatus.left().value();
4072 artifactData.setId(artifactDefinition.getUniqueId());
4073 CassandraOperationStatus saveArtifactStatus = artifactCassandraDao.saveArtifact(artifactData);
4075 if (saveArtifactStatus.equals(CassandraOperationStatus.OK)) {
4076 if (!inTransaction) {
4077 janusGraphDao.commit();
4079 log.debug("Artifact Saved In ES {}", artifactData.getId());
4080 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
4081 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
4082 .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
4083 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
4087 if (!inTransaction) {
4088 janusGraphDao.rollback();
4090 log.info("Failed to save artifact {}.", artifactData.getId());
4091 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
4092 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
4093 .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
4094 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
4096 return Either.right(responseFormat);
4100 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus
4102 .value()), artifactDefinition.getArtifactDisplayName());
4103 log.debug("Failed To update artifact {}", artifactData.getId());
4104 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition
4105 .getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
4106 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
4108 return Either.right(responseFormat);
4114 graphLockOperation.unlockComponent(component.getUniqueId(), component.getComponentType()
4120 return Either.left(artifactDefinition);
4124 public Map<String, Object> buildJsonForUpdateArtifact(ArtifactDefinition artifactDef, ArtifactGroupTypeEnum artifactGroupType, List<ArtifactTemplateInfo> updatedRequiredArtifacts) {
4125 return this.buildJsonForUpdateArtifact(artifactDef.getUniqueId(), artifactDef.getArtifactName(), artifactDef.getArtifactType(), artifactGroupType, artifactDef
4126 .getArtifactLabel(), artifactDef.getArtifactDisplayName(),
4127 artifactDef.getDescription(), artifactDef.getPayloadData(), updatedRequiredArtifacts, artifactDef.getListHeatParameters());
4131 public Map<String, Object> buildJsonForUpdateArtifact(String artifactId, String artifactName, String artifactType, ArtifactGroupTypeEnum artifactGroupType, String label, String displayName, String description, byte[] artifactContent,
4132 List<ArtifactTemplateInfo> updatedRequiredArtifacts, List<HeatParameterDefinition> heatParameters) {
4134 Map<String, Object> json = new HashMap<>();
4135 if (artifactId != null && !artifactId.isEmpty()) {
4136 json.put(Constants.ARTIFACT_ID, artifactId);
4139 json.put(Constants.ARTIFACT_NAME, artifactName);
4140 json.put(Constants.ARTIFACT_TYPE, artifactType);
4141 json.put(Constants.ARTIFACT_DESCRIPTION, description);
4143 if (artifactContent != null) {
4144 log.debug("payload is encoded. perform decode");
4145 String encodedPayload = Base64.encodeBase64String(artifactContent);
4146 json.put(Constants.ARTIFACT_PAYLOAD_DATA, encodedPayload);
4148 json.put(Constants.ARTIFACT_DISPLAY_NAME, displayName);
4149 json.put(Constants.ARTIFACT_LABEL, label);
4150 json.put(Constants.ARTIFACT_GROUP_TYPE, artifactGroupType.getType());
4151 json.put(Constants.REQUIRED_ARTIFACTS, (updatedRequiredArtifacts == null || updatedRequiredArtifacts.isEmpty()) ? new ArrayList<>()
4152 : updatedRequiredArtifacts.stream()
4153 .filter(e -> e.getType().equals(ArtifactTypeEnum.HEAT_ARTIFACT.getType()) || e
4155 .equals(ArtifactTypeEnum.HEAT_NESTED.getType()))
4156 .map(e -> e.getFileName())
4157 .collect(Collectors.toList()));
4158 json.put(Constants.ARTIFACT_HEAT_PARAMS, (heatParameters == null || heatParameters.isEmpty()) ? new ArrayList<>()
4163 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateResourceInstanceArtifactNoContent(String resourceId, Component containerComponent, User user, Map<String, Object> json, ArtifactOperationInfo operation, ArtifactDefinition artifactInfo) {
4165 String jsonStr = gson.toJson(json);
4166 ArtifactDefinition artifactDefinitionFromJson = artifactInfo == null ? RepresentationUtils.convertJsonToArtifactDefinition(jsonStr, ArtifactDefinition.class) : artifactInfo;
4167 String artifactUniqueId = artifactDefinitionFromJson == null ? null : artifactDefinitionFromJson.getUniqueId();
4168 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> uploadArtifactToService = validateAndHandleArtifact(resourceId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactUniqueId,
4169 artifactDefinitionFromJson, null, jsonStr, null, null, user, containerComponent, false, false, true);
4170 if (uploadArtifactToService.isRight()) {
4171 return Either.right(uploadArtifactToService.right().value());
4174 return Either.left(uploadArtifactToService.left().value());
4177 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdateHeatEnv(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType,
4178 org.openecomp.sdc.be.model.Component parent, String originData, String origMd5, ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) {
4179 convertParentType(componentType);
4180 String parentId = parent.getUniqueId();
4181 ArtifactDefinition currArtifact = artifactInfo;
4183 if (origMd5 != null) {
4184 Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
4185 if (validateMd5.isRight()) {
4186 ResponseFormat responseFormat = validateMd5.right().value();
4187 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
4188 return Either.right(responseFormat);
4191 if (artifactInfo.getPayloadData() != null && artifactInfo.getPayloadData().length != 0) {
4192 Either<Boolean, ResponseFormat> deploymentValidationResult = validateDeploymentArtifact(parent, componentId, false, artifactInfo, currArtifact, NodeTypeEnum.ResourceInstance);
4193 if (deploymentValidationResult.isRight()) {
4194 ResponseFormat responseFormat = deploymentValidationResult.right().value();
4195 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
4196 return Either.right(responseFormat);
4199 Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
4200 if (payloadEither.isRight()) {
4201 ResponseFormat responseFormat = payloadEither.right().value();
4202 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
4203 return Either.right(responseFormat);
4207 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
4208 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
4209 return Either.right(responseFormat);
4215 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, UPDATE_ARTIFACT_LOCK);
4216 if (lockComponent.isRight()) {
4217 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right()
4218 .value(), componentType, null);
4219 return Either.right(lockComponent.right().value());
4222 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
4224 resultOp = updateHeatEnvParams(componentId, artifactId, artifactInfo, user, auditingAction, parent, componentType, origMd5);
4230 if (resultOp == null || resultOp.isRight()) {
4231 log.debug(ROLLBACK);
4232 if (!inTransaction) {
4233 janusGraphDao.rollback();
4238 if (!inTransaction) {
4239 janusGraphDao.commit();
4243 componentType = parent.getComponentType();
4245 NodeTypeEnum nodeType = componentType.getNodeType();
4246 graphLockOperation.unlockComponent(parent.getUniqueId(), nodeType);
4250 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateHeatEnvParams(String componentId, String artifactId, ArtifactDefinition artifactInfo, User user, AuditingActionEnum auditingAction, Component parent,
4251 ComponentTypeEnum componentType, String origMd5) {
4253 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
4254 Either<ArtifactDefinition, Operation> insideEither = null;
4255 Either<ComponentInstance, ResponseFormat> getRI = getRIFromComponent(parent, componentId, artifactId, auditingAction, user);
4256 if (getRI.isRight()) {
4257 return Either.right(getRI.right().value());
4259 ComponentInstance ri = getRI.left().value();
4260 Either<ArtifactDefinition, ResponseFormat> getArtifactRes = getArtifactFromRI(parent, ri, componentId, artifactId, auditingAction, user);
4261 if (getArtifactRes.isRight()) {
4262 return Either.right(getArtifactRes.right().value());
4264 ArtifactDefinition currArtifact = getArtifactRes.left().value();
4266 if (currArtifact.getArtifactType().equals(ArtifactTypeEnum.HEAT.getType()) || currArtifact.getArtifactType()
4267 .equals(ArtifactTypeEnum.HEAT_VOL
4268 .getType()) || currArtifact
4270 .equals(ArtifactTypeEnum.HEAT_NET.getType())) {
4271 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
4272 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
4274 return Either.right(responseFormat);
4276 List<HeatParameterDefinition> currentHeatEnvParams = currArtifact.getListHeatParameters();
4277 List<HeatParameterDefinition> updatedHeatEnvParams = artifactInfo.getListHeatParameters();
4278 new ArrayList<HeatParameterDefinition>();
4281 if (origMd5 != null) {
4282 Either<List<HeatParameterDefinition>, ResponseFormat> uploadParamsValidationResult = validateUploadParamsFromEnvFile(auditingAction, parent, user, artifactInfo, artifactId, componentType, ri
4283 .getName(), currentHeatEnvParams,
4284 updatedHeatEnvParams, currArtifact.getArtifactName());
4285 if (uploadParamsValidationResult.isRight()) {
4286 ResponseFormat responseFormat = uploadParamsValidationResult.right().value();
4287 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
4289 return Either.right(responseFormat);
4291 artifactInfo.setListHeatParameters(updatedHeatEnvParams);
4294 Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers = validateAndConvertHeatParamers(artifactInfo, ArtifactTypeEnum.HEAT_ENV
4296 if (validateAndConvertHeatParamers.isRight()) {
4297 ResponseFormat responseFormat = validateAndConvertHeatParamers.right().value();
4298 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
4300 return Either.right(responseFormat);
4303 if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty()) {
4304 // fill reduced heat env parameters List for updating
4305 replaceCurrHeatValueWithUpdatedValue(currentHeatEnvParams, updatedHeatEnvParams);
4306 currArtifact.setHeatParamsUpdateDate(System.currentTimeMillis());
4307 currArtifact.setListHeatParameters(currentHeatEnvParams);
4309 Either<ArtifactDefinition, StorageOperationStatus> updateArifactRes = artifactToscaOperation.updateArtifactOnResource(currArtifact, parent
4310 .getUniqueId(), currArtifact.getUniqueId(), componentType.getNodeType(), componentId);
4311 if (updateArifactRes.isRight()) {
4312 log.debug("Failed to update artifact on graph - {}", artifactId);
4313 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateArifactRes
4316 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
4318 return Either.right(responseFormat);
4320 StorageOperationStatus error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), ri.getUniqueId(), componentType);
4321 if (error != StorageOperationStatus.OK) {
4322 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
4323 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
4325 return Either.right(responseFormat);
4328 error = generateCustomizationUUIDOnGroupInstance(ri, updateArifactRes.left()
4330 .getUniqueId(), parent.getUniqueId());
4331 if (error != StorageOperationStatus.OK) {
4332 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
4333 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri
4335 return Either.right(responseFormat);
4339 insideEither = Either.left(currArtifact);
4340 resultOp = Either.left(insideEither);
4341 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
4342 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currArtifact, null, artifactId, responseFormat, componentType, ri
4347 private void replaceCurrHeatValueWithUpdatedValue(List<HeatParameterDefinition> currentHeatEnvParams, List<HeatParameterDefinition> updatedHeatEnvParams) {
4348 for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) {
4349 String paramName = heatEnvParam.getName();
4350 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
4351 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
4352 String updatedParamValue = heatEnvParam.getCurrentValue();
4353 currHeatParam.setCurrentValue(updatedParamValue);
4359 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateHeatParams(String componentId, String artifactId, ArtifactDefinition artifactEnvInfo, User user, AuditingActionEnum auditingAction, Component parent,
4360 ComponentTypeEnum componentType, ArtifactDefinition currHeatArtifact, boolean needToUpdateGroup) {
4362 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp;
4363 Either<ArtifactDefinition, Operation> insideEither = null;
4364 String currentHeatId = currHeatArtifact.getUniqueId();
4366 String esArtifactId = currHeatArtifact.getEsId();
4367 Either<ESArtifactData, CassandraOperationStatus> artifactFromES = artifactCassandraDao.getArtifact(esArtifactId);
4368 if (artifactFromES.isRight()) {
4369 CassandraOperationStatus resourceUploadStatus = artifactFromES.right().value();
4370 StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
4371 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
4372 log.debug("Error when getting artifact from ES, error: {}", actionStatus);
4373 return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, currHeatArtifact.getArtifactDisplayName()));
4376 ESArtifactData esArtifactData = artifactFromES.left().value();
4378 ArtifactDefinition updatedHeatArt = currHeatArtifact;
4380 List<HeatParameterDefinition> updatedHeatEnvParams = artifactEnvInfo.getListHeatParameters();
4381 List<HeatParameterDefinition> currentHeatEnvParams = currHeatArtifact.getListHeatParameters();
4382 List<HeatParameterDefinition> newHeatEnvParams = new ArrayList<HeatParameterDefinition>();
4384 if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty() && currentHeatEnvParams != null && !currentHeatEnvParams
4388 for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) {
4390 paramName = heatEnvParam.getName();
4391 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
4392 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
4394 String updatedParamValue = heatEnvParam.getCurrentValue();
4395 if (updatedParamValue == null) {
4396 updatedParamValue = heatEnvParam.getDefaultValue();
4398 HeatParameterType paramType = HeatParameterType.isValidType(currHeatParam.getType());
4399 if (!paramType.getValidator().isValid(updatedParamValue, null)) {
4400 ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE;
4401 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, ArtifactTypeEnum.HEAT_ENV
4402 .getType(), paramType.getType(), paramName);
4403 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactEnvInfo, null, artifactId, responseFormat, componentType, "");
4404 return Either.right(responseFormat);
4407 currHeatParam.setCurrentValue(paramType.getConverter().convert(updatedParamValue, null, null));
4408 newHeatEnvParams.add(currHeatParam);
4413 if (!newHeatEnvParams.isEmpty()) {
4414 currHeatArtifact.setListHeatParameters(currentHeatEnvParams);
4415 Either<ArtifactDefinition, StorageOperationStatus> operationStatus = artifactToscaOperation.updateArtifactOnResource(currHeatArtifact, parent
4416 .getUniqueId(), currHeatArtifact.getUniqueId(), componentType.getNodeType(), componentId);
4418 if (operationStatus.isRight()) {
4419 log.debug("Failed to update artifact on graph - {}", currHeatArtifact.getUniqueId());
4421 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(operationStatus
4424 return Either.right(responseFormat);
4427 updatedHeatArt = operationStatus.left().value();
4429 if (!updatedHeatArt.getDuplicated() || esArtifactData.getId() == null) {
4430 esArtifactData.setId(updatedHeatArt.getEsId());
4432 res = saveArtifacts(esArtifactData, parent.getUniqueId());
4435 log.debug(ARTIFACT_SAVED, updatedHeatArt.getUniqueId());
4436 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
4437 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, updatedHeatArt, currentHeatId, updatedHeatArt
4438 .getUniqueId(), responseFormat, componentType, null);
4441 BeEcompErrorManager.getInstance().logBeDaoSystemError(UPDATE_ARTIFACT);
4442 log.debug(FAILED_SAVE_ARTIFACT);
4443 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
4444 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, updatedHeatArt, currentHeatId, updatedHeatArt
4445 .getUniqueId(), responseFormat, componentType, null);
4446 resultOp = Either.right(responseFormat);
4449 insideEither = Either.left(updatedHeatArt);
4452 Either<ArtifactDefinition, StorageOperationStatus> updateHeatEnvArtifact;
4453 if (!currentHeatId.equals(updatedHeatArt.getUniqueId())) {
4454 artifactEnvInfo.setArtifactChecksum(null);
4455 updateHeatEnvArtifact = artifactToscaOperation.updateHeatEnvArtifact(parent.getUniqueId(), artifactEnvInfo, currentHeatId, updatedHeatArt
4456 .getUniqueId(), componentType.getNodeType(), componentId);
4459 updateHeatEnvArtifact = artifactToscaOperation.updateHeatEnvPlaceholder(artifactEnvInfo, componentId, componentType
4463 if (needToUpdateGroup && updateHeatEnvArtifact.isLeft()) {
4464 ActionStatus result = updateGroupForHeat(currHeatArtifact, updatedHeatArt, artifactEnvInfo, updateHeatEnvArtifact
4466 .value(), parent, componentType);
4467 if (result != ActionStatus.OK) {
4468 ResponseFormat responseFormat = componentsUtils.getResponseFormat(result);
4469 return Either.right(responseFormat);
4473 if (updatedHeatEnvParams.isEmpty()) {
4474 return getResponseAndAuditInvalidEmptyHeatEnvFile(auditingAction, parent, user, currHeatArtifact, artifactId, componentType);
4476 resultOp = Either.left(insideEither);
4477 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
4478 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currHeatArtifact, null, artifactId, responseFormat, componentType, "");
4483 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> getResponseAndAuditInvalidEmptyHeatEnvFile(AuditingActionEnum auditingAction, Component parent, User user, ArtifactDefinition currHeatArtifact, String artifactId, ComponentTypeEnum componentType) {
4484 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, currHeatArtifact.getArtifactName());
4485 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currHeatArtifact, null, artifactId, responseFormat, componentType, "");
4486 return Either.right(responseFormat);
4490 private StorageOperationStatus generateCustomizationUUIDOnGroupInstance(ComponentInstance ri, String artifactId, String componentId) {
4491 StorageOperationStatus error = StorageOperationStatus.OK;
4492 log.debug("Need to re-generate customization UUID for group instance on component instance {}", ri.getUniqueId());
4493 List<GroupInstance> groupsInstances = ri.getGroupInstances();
4494 List<String> groupInstancesId = null;
4495 if (groupsInstances != null && !groupsInstances.isEmpty()) {
4496 groupInstancesId = groupsInstances.stream()
4497 .filter(p -> p.getGroupInstanceArtifacts() != null && p.getGroupInstanceArtifacts()
4498 .contains(artifactId))
4499 .map(GroupInstanceDataDefinition::getUniqueId)
4500 .collect(Collectors.toList());
4502 if (groupInstancesId != null && !groupInstancesId.isEmpty()) {
4503 toscaOperationFacade.generateCustomizationUUIDOnInstanceGroup(componentId, ri.getUniqueId(), groupInstancesId);
4509 public Either<List<HeatParameterDefinition>, ResponseFormat> validateUploadParamsFromEnvFile(AuditingActionEnum auditingAction, Component parent, User user, ArtifactDefinition artifactInfo, String artifactId, ComponentTypeEnum componentType,
4510 String riName, List<HeatParameterDefinition> currentHeatEnvParams, List<HeatParameterDefinition> updatedHeatEnvParams, String currArtifactName) {
4512 if (updatedHeatEnvParams == null || updatedHeatEnvParams.isEmpty()) {
4513 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactInfo
4514 .getArtifactName(), currArtifactName);
4515 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, riName);
4516 return Either.right(responseFormat);
4519 for (HeatParameterDefinition uploadedHeatParam : updatedHeatEnvParams) {
4520 String paramName = uploadedHeatParam.getName();
4521 boolean isExistsInHeat = false;
4522 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
4523 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
4525 isExistsInHeat = true;
4526 uploadedHeatParam.setType(currHeatParam.getType());
4527 uploadedHeatParam.setCurrentValue(uploadedHeatParam.getDefaultValue());
4528 uploadedHeatParam.setDefaultValue(currHeatParam.getDefaultValue());
4529 uploadedHeatParam.setUniqueId(currHeatParam.getUniqueId());
4533 if (!isExistsInHeat) {
4534 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, currArtifactName);
4535 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, riName);
4536 return Either.right(responseFormat);
4539 return Either.left(updatedHeatEnvParams);
4542 private Either<ComponentInstance, ResponseFormat> getRIFromComponent(Component component, String riID, String artifactId, AuditingActionEnum auditingAction, User user) {
4543 ResponseFormat responseFormat = null;
4544 List<ComponentInstance> ris = component.getComponentInstances();
4545 for (ComponentInstance ri : ris) {
4546 if (riID.equals(ri.getUniqueId())) {
4547 return Either.left(ri);
4550 responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, riID);
4551 log.debug("Resource Instance not found, resourceInstanceId {}", riID);
4552 handleAuditing(auditingAction, null, riID, user, null, null, artifactId, responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE, null);
4553 return Either.right(responseFormat);
4556 private Either<ArtifactDefinition, ResponseFormat> getArtifactFromRI(Component component, ComponentInstance ri, String riID, String artifactId, AuditingActionEnum auditingAction, User user) {
4557 ResponseFormat responseFormat = null;
4558 Map<String, ArtifactDefinition> rtifactsMap = ri.getDeploymentArtifacts();
4559 for (ArtifactDefinition artifact : rtifactsMap.values()) {
4560 if (artifactId.equals(artifact.getUniqueId())) {
4561 return Either.left(artifact);
4564 responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, riID, component.getUniqueId());
4565 handleAuditing(auditingAction, component, riID, user, null, null, artifactId, responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE, ri
4567 return Either.right(responseFormat);
4570 public ArtifactDefinition extractArtifactDefinition(Either<ArtifactDefinition, Operation> eitherArtifact) {
4571 ArtifactDefinition ret;
4572 if (eitherArtifact.isLeft()) {
4573 ret = eitherArtifact.left().value();
4576 ret = eitherArtifact.right().value().getImplementationArtifact();
4582 * downloads artifact of component by UUIDs
4584 * @param componentType
4585 * @param componentUuid
4586 * @param artifactUUID
4587 * @param resourceCommonInfo
4590 public Either<byte[], ResponseFormat> downloadComponentArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String artifactUUID, ResourceCommonInfo resourceCommonInfo) {
4591 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4592 Either<byte[], ResponseFormat> result;
4593 byte[] downloadedArtifact = null;
4594 Component component = getComponentByUuid(componentType, componentUuid, errorWrapper);
4595 if (errorWrapper.isEmpty() && component != null) {
4596 resourceCommonInfo.setResourceName(component.getName());
4597 downloadedArtifact = downloadArtifact(component.getAllArtifacts(), artifactUUID, errorWrapper, component.getName());
4599 if (errorWrapper.isEmpty()) {
4600 result = Either.left(downloadedArtifact);
4603 result = Either.right(errorWrapper.getInnerElement());
4609 * downloads an artifact of resource instance of component by UUIDs
4611 * @param componentType
4612 * @param componentUuid
4613 * @param resourceInstanceName
4614 * @param artifactUUID
4617 public Either<byte[], ResponseFormat> downloadResourceInstanceArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID) {
4618 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4619 Either<byte[], ResponseFormat> result;
4620 byte[] downloadedArtifact = null;
4621 ComponentInstance resourceInstance = getRelatedComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
4622 if (errorWrapper.isEmpty()) {
4623 downloadedArtifact = downloadArtifact(resourceInstance.getDeploymentArtifacts(), artifactUUID, errorWrapper, resourceInstance
4626 if (errorWrapper.isEmpty()) {
4627 result = Either.left(downloadedArtifact);
4630 result = Either.right(errorWrapper.getInnerElement());
4636 * uploads an artifact to a component by UUID
4640 * @param componentType
4641 * @param componentUuid
4642 * @param resourceCommonInfo
4646 public Either<ArtifactDefinition, ResponseFormat> uploadArtifactToComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, ResourceCommonInfo resourceCommonInfo,ArtifactOperationInfo operation) {
4647 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4648 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4649 Component component = null;
4650 String componentId = null;
4651 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
4652 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4653 String userId = request.getHeader(Constants.USER_ID_HEADER);
4655 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4656 if (getComponentRes.isRight()) {
4657 StorageOperationStatus status = getComponentRes.right().value();
4658 log.debug(FAILED_FETCH_COMPONENT, componentType, componentUuid, status);
4659 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), componentUuid));
4661 if (errorWrapper.isEmpty()) {
4662 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
4663 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
4665 if (!getComponentRes.left()
4667 .getMetadataDataDefinition()
4669 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4670 component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
4671 if (component != null) {
4672 componentId = component.getUniqueId();
4673 componentName = component.getName();
4676 resourceCommonInfo.setResourceName(componentName);
4678 if (errorWrapper.isEmpty()) {
4679 actionResult = handleArtifactRequest(componentId, userId, componentType, operation, null, artifactInfo, origMd5, data, null, null, null, null);
4680 if (actionResult.isRight()) {
4681 log.debug(FAILED_UPLOAD_ARTIFACT_TO_COMPONENT, componentType, componentUuid, actionResult
4684 return Either.right(actionResult.right().value());
4686 return Either.left(actionResult.left().value().left().value());
4688 return Either.right(errorWrapper.getInnerElement());
4691 * upload an artifact to a resource instance by UUID
4695 * @param componentType
4696 * @param componentUuid
4697 * @param resourceInstanceName
4701 public Either<ArtifactDefinition, ResponseFormat> uploadArtifactToRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName,
4702 ArtifactOperationInfo operation) {
4703 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4704 Either<ArtifactDefinition, ResponseFormat> uploadArtifactResult;
4705 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4706 ArtifactDefinition uploadArtifact = null;
4707 Component component = null;
4708 String componentInstanceId;
4710 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4711 String userId = request.getHeader(Constants.USER_ID_HEADER);
4713 ImmutablePair<Component, ComponentInstance> componentRiPair = null;
4714 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4715 if (getComponentRes.isRight()) {
4716 StorageOperationStatus status = getComponentRes.right().value();
4717 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4718 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), resourceInstanceName));
4720 if (errorWrapper.isEmpty() && !getComponentRes.left()
4722 .getMetadataDataDefinition()
4724 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4725 component = checkoutParentComponent(componentType, getComponentRes.left()
4727 .getMetadataDataDefinition()
4728 .getUniqueId(), userId, errorWrapper);
4730 if (errorWrapper.isEmpty()) {
4731 if (component == null) {
4732 componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
4735 componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
4738 if (errorWrapper.isEmpty()) {
4739 componentInstanceId = componentRiPair.getRight().getUniqueId();
4740 componentId = componentRiPair.getLeft().getUniqueId();
4741 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
4743 actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, null, artifactInfo, origMd5, data, null, null, componentId, ComponentTypeEnum
4744 .findParamByType(componentType));
4745 if (actionResult.isRight()) {
4746 log.debug(FAILED_UPLOAD_ARTIFACT_TO_INSTANCE, resourceInstanceName, componentType, componentUuid, actionResult
4749 errorWrapper.setInnerElement(actionResult.right().value());
4752 if (errorWrapper.isEmpty()) {
4753 uploadArtifact = actionResult.left().value().left().value();
4754 uploadArtifactResult = Either.left(uploadArtifact);
4757 uploadArtifactResult = Either.right(errorWrapper.getInnerElement());
4759 return uploadArtifactResult;
4763 * updates an artifact on a component by UUID
4767 * @param componentType
4768 * @param componentUuid
4769 * @param artifactUUID
4773 public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID,
4774 ResourceCommonInfo resourceCommonInfo, ArtifactOperationInfo operation) {
4775 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4776 Either<ArtifactDefinition, ResponseFormat> updateArtifactResult;
4777 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4778 ArtifactDefinition updateArtifact = null;
4779 Component component = null;
4780 String componentId = null;
4781 String artifactId = null;
4782 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinitionForUpdate(data, ArtifactDefinition.class);
4783 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4784 String userId = request.getHeader(Constants.USER_ID_HEADER);
4786 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4787 if (getComponentRes.isRight()) {
4788 StorageOperationStatus status = getComponentRes.right().value();
4789 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4790 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4792 if (errorWrapper.isEmpty()) {
4793 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
4794 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
4796 if (!getComponentRes.left()
4798 .getMetadataDataDefinition()
4800 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4801 component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
4802 if (component != null) {
4803 componentId = component.getUniqueId();
4804 componentName = component.getName();
4807 resourceCommonInfo.setResourceName(componentName);
4809 if (errorWrapper.isEmpty()) {
4810 artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentId, componentType);
4812 if (errorWrapper.isEmpty()) {
4813 actionResult = handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, origMd5, data, null, null, null, null);
4814 if (actionResult.isRight()) {
4815 log.debug(FAILED_UPLOAD_ARTIFACT_TO_COMPONENT, componentType, componentUuid, actionResult
4818 errorWrapper.setInnerElement(actionResult.right().value());
4821 if (errorWrapper.isEmpty()) {
4822 updateArtifact = actionResult.left().value().left().value();
4823 updateArtifactResult = Either.left(updateArtifact);
4827 updateArtifactResult = Either.right(errorWrapper.getInnerElement());
4829 return updateArtifactResult;
4833 * updates an artifact on a resource instance by UUID
4837 * @param componentType
4838 * @param componentUuid
4839 * @param resourceInstanceName
4840 * @param artifactUUID
4841 * @param operation TODO
4844 public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID,
4845 ArtifactOperationInfo operation) {
4847 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4848 Either<ArtifactDefinition, ResponseFormat> updateArtifactResult;
4849 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4850 ArtifactDefinition updateArtifact = null;
4851 Component component = null;
4852 String componentInstanceId = null;
4853 String componentId = null;
4854 String artifactId = null;
4855 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4856 String userId = request.getHeader(Constants.USER_ID_HEADER);
4858 ImmutablePair<Component, ComponentInstance> componentRiPair = null;
4859 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4860 if (getComponentRes.isRight()) {
4861 StorageOperationStatus status = getComponentRes.right().value();
4862 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4863 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4865 if (errorWrapper.isEmpty() && !getComponentRes.left()
4867 .getMetadataDataDefinition()
4869 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4870 component = checkoutParentComponent(componentType, getComponentRes.left()
4872 .getMetadataDataDefinition()
4873 .getUniqueId(), userId, errorWrapper);
4875 if (errorWrapper.isEmpty()) {
4876 if (component == null) {
4877 componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
4880 componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
4883 if (errorWrapper.isEmpty()) {
4884 componentInstanceId = componentRiPair.getRight().getUniqueId();
4885 componentId = componentRiPair.getLeft().getUniqueId();
4886 artifactId = findArtifactId(componentRiPair.getRight(), artifactUUID, errorWrapper);
4888 if (errorWrapper.isEmpty()) {
4889 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
4891 actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, artifactInfo, origMd5, data, null, null, componentId, ComponentTypeEnum
4892 .findParamByType(componentType));
4893 if (actionResult.isRight()) {
4894 log.debug(FAILED_UPLOAD_ARTIFACT_TO_INSTANCE, resourceInstanceName, componentType, componentUuid, actionResult
4897 errorWrapper.setInnerElement(actionResult.right().value());
4900 if (errorWrapper.isEmpty()) {
4901 updateArtifact = actionResult.left().value().left().value();
4902 updateArtifactResult = Either.left(updateArtifact);
4905 updateArtifactResult = Either.right(errorWrapper.getInnerElement());
4907 return updateArtifactResult;
4910 private Either<ArtifactDefinition, ResponseFormat> updateOperationArtifact(String componentId, String interfaceType, String operationUuid, ArtifactDefinition artifactInfo){
4911 Either<Component, StorageOperationStatus> componentStorageOperationStatusEither = toscaOperationFacade.getToscaElement(componentId);
4912 if (componentStorageOperationStatusEither.isRight()) {
4913 StorageOperationStatus errorStatus = componentStorageOperationStatusEither.right().value();
4914 log.debug("Failed to fetch resource information by resource id, error {}", errorStatus);
4915 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(errorStatus)));
4917 Component storedComponent = componentStorageOperationStatusEither.left().value();
4919 Optional<InterfaceDefinition> optionalInterface = InterfaceOperationUtils.getInterfaceDefinitionFromComponentByInterfaceType(storedComponent, interfaceType);
4920 if(!optionalInterface.isPresent()) {
4921 log.debug("Failed to get resource interface for resource Id {}", componentId);
4922 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_NOT_FOUND_IN_COMPONENT, interfaceType));
4925 //fetch the operation from storage
4926 InterfaceDefinition gotInterface = optionalInterface.get();
4927 Map<String, Operation> operationsMap = gotInterface.getOperationsMap();
4928 Optional<Operation> optionalOperation = operationsMap.values()
4930 .filter(o -> o.getUniqueId().equals(operationUuid))
4932 if (!optionalOperation.isPresent()) {
4933 log.debug("Failed to get resource interface operation for resource Id {} and operationId {}", componentId, operationUuid);
4934 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INTERFACE_OPERATION_NOT_FOUND, componentId);
4935 return Either.right(responseFormat);
4938 Operation operation = optionalOperation.get();
4939 ArtifactDefinition implementationArtifact = operation.getImplementationArtifact();
4940 implementationArtifact.setArtifactUUID(artifactInfo.getArtifactUUID());
4941 implementationArtifact.setUniqueId(artifactInfo.getUniqueId());
4942 implementationArtifact.setArtifactName(artifactInfo.getArtifactName());
4943 implementationArtifact.setDescription(artifactInfo.getDescription());
4944 implementationArtifact.setArtifactType(artifactInfo.getArtifactType());
4945 implementationArtifact.setArtifactLabel(artifactInfo.getArtifactLabel());
4946 implementationArtifact.setArtifactDisplayName(artifactInfo.getArtifactDisplayName());
4947 implementationArtifact.setEsId(artifactInfo.getEsId());
4948 operation.setImplementation(implementationArtifact);
4949 gotInterface.setOperationsMap(operationsMap);
4950 Either<List<InterfaceDefinition>, StorageOperationStatus> interfaceDefinitionStorageOperationStatusEither =
4951 interfaceOperation.updateInterfaces(storedComponent.getUniqueId(), Collections.singletonList(gotInterface));
4952 if (interfaceDefinitionStorageOperationStatusEither.isRight()){
4953 StorageOperationStatus storageOperationStatus = interfaceDefinitionStorageOperationStatusEither.right().value();
4954 ActionStatus actionStatus =
4955 componentsUtils.convertFromStorageResponseForDataType(storageOperationStatus);
4956 return Either.right(componentsUtils.getResponseFormat(actionStatus));
4959 return Either.left(artifactInfo);
4963 * updates an artifact on a component by UUID
4967 * @param componentType
4968 * @param componentUuid
4969 * @param artifactUUID
4973 public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnInterfaceOperationByResourceUUID(
4974 String data, HttpServletRequest request, ComponentTypeEnum componentType,
4975 String componentUuid, String interfaceUUID, String operationUUID, String artifactUUID,
4976 ResourceCommonInfo resourceCommonInfo,ArtifactOperationInfo operation) {
4977 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4978 Either<ArtifactDefinition, ResponseFormat> updateArtifactResult;
4979 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4980 ArtifactDefinition updateArtifact = null;
4981 String componentId = null;
4982 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinitionForUpdate(data, ArtifactDefinition.class);
4983 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4984 String userId = request.getHeader(Constants.USER_ID_HEADER);
4985 ArtifactDefinition existingArtifactInfo = null;
4986 String interfaceName = null;
4988 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4989 if (getComponentRes.isRight()) {
4990 StorageOperationStatus status = getComponentRes.right().value();
4991 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4992 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4995 if (errorWrapper.isEmpty()) {
4996 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
4997 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
4998 if (!getComponentRes.left()
5000 .getMetadataDataDefinition()
5002 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
5003 Component component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
5004 if (component != null) {
5005 componentId = component.getUniqueId();
5006 componentName = component.getName();
5010 resourceCommonInfo.setResourceName(componentName);
5013 if(errorWrapper.isEmpty()){
5014 Either<String, ResponseFormat> interfaceNameEither = fetchInterfaceName(componentId, interfaceUUID);
5015 if (interfaceNameEither.isRight()) {
5016 errorWrapper.setInnerElement(interfaceNameEither.right().value());
5019 interfaceName = interfaceNameEither.left().value();
5022 if(errorWrapper.isEmpty()){
5023 Either<Component, StorageOperationStatus> toscaComponentEither = toscaOperationFacade.getToscaElement(componentId);
5024 if (toscaComponentEither.isRight()) {
5025 StorageOperationStatus status = toscaComponentEither.right().value();
5026 log.debug("Could not fetch component with type {} and id {}. Status is {}. ", componentType, componentId, status);
5027 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
5030 if (errorWrapper.isEmpty()) {
5031 NodeTypeEnum parentType = convertParentType(componentType);
5032 List<ArtifactDefinition> existingDeploymentArtifacts = getDeploymentArtifacts(toscaComponentEither.left().value(), parentType,null);
5033 for (ArtifactDefinition artifactDefinition: existingDeploymentArtifacts){
5034 if(artifactInfo.getArtifactName().equalsIgnoreCase(artifactDefinition.getArtifactName())){
5035 existingArtifactInfo = artifactDefinition;
5039 if(existingArtifactInfo != null){
5040 return updateOperationArtifact(componentId, interfaceName, operationUUID, existingArtifactInfo);
5046 if (errorWrapper.isEmpty()) {
5047 actionResult = handleArtifactRequest(componentId, userId, componentType, operation,
5048 artifactUUID, artifactInfo, origMd5, data, interfaceName,
5049 operationUUID, null, null);
5050 if (actionResult.isRight()) {
5051 log.debug(FAILED_UPLOAD_ARTIFACT_TO_COMPONENT, componentType, componentUuid, actionResult
5054 errorWrapper.setInnerElement(actionResult.right().value());
5058 if (errorWrapper.isEmpty()) {
5059 updateArtifact = actionResult.left().value().left().value();
5060 updateArtifactResult = Either.left(updateArtifact);
5064 updateArtifactResult = Either.right(errorWrapper.getInnerElement());
5066 return updateArtifactResult;
5069 private Either<String, ResponseFormat> fetchInterfaceName(String componentId, String interfaceUUID) {
5070 Either<Component, StorageOperationStatus> componentStorageOperationStatusEither = toscaOperationFacade.getToscaElement(componentId);
5071 if (componentStorageOperationStatusEither.isRight()) {
5072 StorageOperationStatus errorStatus = componentStorageOperationStatusEither.right().value();
5073 log.debug("Failed to fetch component information by component id, error {}", errorStatus);
5074 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(errorStatus)));
5076 Component storedComponent = componentStorageOperationStatusEither.left().value();
5078 Optional<InterfaceDefinition> optionalInterface = InterfaceOperationUtils
5079 .getInterfaceDefinitionFromComponentByInterfaceId(storedComponent, interfaceUUID);
5080 if(!optionalInterface.isPresent()) {
5081 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INTERFACE_NOT_FOUND_IN_COMPONENT, interfaceUUID));
5083 return Either.left(optionalInterface.get().getType());
5088 * deletes an artifact on a component by UUID
5091 * @param componentType
5092 * @param componentUuid
5093 * @param artifactUUID
5094 * @param resourceCommonInfo
5095 * @param operation TODO
5098 public Either<ArtifactDefinition, ResponseFormat> deleteArtifactOnComponentByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID, ResourceCommonInfo resourceCommonInfo,
5099 ArtifactOperationInfo operation) {
5101 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
5102 Either<ArtifactDefinition, ResponseFormat> deleteArtifactResult;
5103 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
5104 ArtifactDefinition deleteArtifact = null;
5105 Component component = null;
5106 String componentId = null;
5107 String artifactId = null;
5108 String origMd5 = request.getHeader(Constants.MD5_HEADER);
5109 String userId = request.getHeader(Constants.USER_ID_HEADER);
5111 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
5112 if (getComponentRes.isRight()) {
5113 StorageOperationStatus status = getComponentRes.right().value();
5114 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
5115 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), componentUuid));
5117 if (errorWrapper.isEmpty()) {
5118 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
5119 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
5120 if (!getComponentRes.left()
5122 .getMetadataDataDefinition()
5124 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
5125 component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
5126 if (component != null) {
5127 componentId = component.getUniqueId();
5128 componentName = component.getName();
5131 resourceCommonInfo.setResourceName(componentName);
5133 if (errorWrapper.isEmpty()) {
5134 artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentId, componentType);
5136 if (errorWrapper.isEmpty()) {
5137 actionResult = handleArtifactRequest(componentId, userId, componentType, operation, artifactId, null, origMd5, null, null, null, null, null);
5138 if (actionResult.isRight()) {
5139 log.debug(FAILED_UPLOAD_ARTIFACT_TO_COMPONENT, componentType, componentUuid, actionResult
5142 errorWrapper.setInnerElement(actionResult.right().value());
5145 if (errorWrapper.isEmpty()) {
5146 deleteArtifact = actionResult.left().value().left().value();
5147 deleteArtifactResult = Either.left(deleteArtifact);
5150 deleteArtifactResult = Either.right(errorWrapper.getInnerElement());
5152 return deleteArtifactResult;
5156 * deletes an artifact from a resource instance by UUID
5159 * @param componentType
5160 * @param componentUuid
5161 * @param resourceInstanceName
5162 * @param artifactUUID
5163 * @param operation TODO
5166 public Either<ArtifactDefinition, ResponseFormat> deleteArtifactOnRiByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID,
5167 ArtifactOperationInfo operation) {
5169 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
5170 Either<ArtifactDefinition, ResponseFormat> deleteArtifactResult;
5171 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
5172 ArtifactDefinition deleteArtifact = null;
5173 Component component = null;
5174 String componentInstanceId = null;
5175 String componentId = null;
5176 String artifactId = null;
5177 String origMd5 = request.getHeader(Constants.MD5_HEADER);
5178 String userId = request.getHeader(Constants.USER_ID_HEADER);
5179 ImmutablePair<Component, ComponentInstance> componentRiPair = null;
5180 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
5181 if (getComponentRes.isRight()) {
5182 StorageOperationStatus status = getComponentRes.right().value();
5183 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
5184 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
5186 if (errorWrapper.isEmpty() && !getComponentRes.left()
5188 .getMetadataDataDefinition()
5190 .equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
5191 component = checkoutParentComponent(componentType, getComponentRes.left()
5193 .getMetadataDataDefinition()
5194 .getUniqueId(), userId, errorWrapper);
5196 if (errorWrapper.isEmpty()) {
5197 if (component == null) {
5198 componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
5201 componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
5204 if (errorWrapper.isEmpty()) {
5205 componentInstanceId = componentRiPair.getRight().getUniqueId();
5206 componentId = componentRiPair.getLeft().getUniqueId();
5207 artifactId = findArtifactId(componentRiPair.getRight(), artifactUUID, errorWrapper);
5209 if (errorWrapper.isEmpty()) {
5211 actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, null, origMd5, null, null, null, componentId, ComponentTypeEnum
5212 .findParamByType(componentType));
5214 if (actionResult.isRight()) {
5215 log.debug(FAILED_UPLOAD_ARTIFACT_TO_INSTANCE, resourceInstanceName, componentType, componentUuid, actionResult
5218 errorWrapper.setInnerElement(actionResult.right().value());
5221 if (errorWrapper.isEmpty()) {
5222 deleteArtifact = actionResult.left().value().left().value();
5223 deleteArtifactResult = Either.left(deleteArtifact);
5226 deleteArtifactResult = Either.right(errorWrapper.getInnerElement());
5228 return deleteArtifactResult;
5231 private String findArtifactId(ComponentInstance instance, String artifactUUID, Wrapper<ResponseFormat> errorWrapper) {
5232 String artifactId = null;
5233 ArtifactDefinition foundArtifact = null;
5234 if (instance.getDeploymentArtifacts() != null) {
5235 foundArtifact = instance.getDeploymentArtifacts()
5238 .filter(e -> e.getArtifactUUID() != null && e.getArtifactUUID()
5239 .equals(artifactUUID))
5243 if (foundArtifact == null && instance.getArtifacts() != null) {
5244 foundArtifact = instance.getArtifacts()
5247 .filter(e -> e.getArtifactUUID() != null && e.getArtifactUUID()
5248 .equals(artifactUUID))
5252 if (foundArtifact == null) {
5253 log.debug("The artifact {} was not found on instance {}. ", artifactUUID, instance.getUniqueId());
5254 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactUUID));
5257 artifactId = foundArtifact.getUniqueId();
5262 @SuppressWarnings("unchecked")
5263 public Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder(ArtifactDefinition heatArtifact, String envType, String parentId, NodeTypeEnum parentType, String parentName, User user, Component component,
5264 Map<String, String> existingEnvVersions) {
5265 Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager()
5267 .getDeploymentResourceInstanceArtifacts();
5268 if (deploymentResourceArtifacts == null) {
5269 log.debug("no deployment artifacts are configured for generated artifacts");
5270 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
5272 Map<String, Object> placeHolderData = (Map<String, Object>) deploymentResourceArtifacts.get(envType);
5273 if (placeHolderData == null) {
5274 log.debug("no env type {} are configured for generated artifacts", envType);
5275 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
5278 String envLabel = (heatArtifact.getArtifactLabel() + HEAT_ENV_SUFFIX).toLowerCase();
5279 Either<ArtifactDefinition, ResponseFormat> createArtifactPlaceHolder = createArtifactPlaceHolderInfo(parentId, envLabel, placeHolderData, user
5280 .getUserId(), ArtifactGroupTypeEnum.DEPLOYMENT, true);
5281 if (createArtifactPlaceHolder.isRight()) {
5282 return Either.right(createArtifactPlaceHolder.right().value());
5284 ArtifactDefinition artifactHeatEnv = createArtifactPlaceHolder.left().value();
5285 artifactHeatEnv.setGeneratedFromId(heatArtifact.getUniqueId());
5286 artifactHeatEnv.setHeatParamsUpdateDate(System.currentTimeMillis());
5287 artifactHeatEnv.setTimeout(0);
5288 buildHeatEnvFileName(heatArtifact, artifactHeatEnv, placeHolderData);
5289 // rbetzer - keep env artifactVersion - changeComponentInstanceVersion flow
5290 handleEnvArtifactVersion(artifactHeatEnv, existingEnvVersions);
5291 ArtifactDefinition heatEnvPlaceholder;
5292 // Evg : for resource instance artifact will be added later as block with other env artifacts from BL
5293 if (parentType != NodeTypeEnum.ResourceInstance) {
5294 Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact = addHeatEnvArtifact(artifactHeatEnv, heatArtifact, component
5295 .getUniqueId(), parentType, parentId);
5296 if (addHeatEnvArtifact.isRight()) {
5297 log.debug("failed to create heat env artifact on resource instance");
5298 return Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(addHeatEnvArtifact
5300 .value(), false), "", null));
5302 heatEnvPlaceholder = createArtifactPlaceHolder.left().value();
5305 heatEnvPlaceholder = artifactHeatEnv;
5306 artifactToscaOperation.generateUUID(heatEnvPlaceholder, heatEnvPlaceholder.getArtifactVersion());
5307 setHeatCurrentValuesOnHeatEnvDefaultValues(heatArtifact, heatEnvPlaceholder);
5310 ComponentTypeEnum componentType = component.getComponentType();
5311 if (parentType == NodeTypeEnum.ResourceInstance) {
5312 componentType = ComponentTypeEnum.RESOURCE_INSTANCE;
5314 componentsUtils.auditComponent(componentsUtils.getResponseFormat(ActionStatus.OK), user, component, AuditingActionEnum.ARTIFACT_UPLOAD,
5315 new ResourceCommonInfo(parentName, componentType.getValue()),
5316 ResourceVersionInfo.newBuilder().build(),
5317 ResourceVersionInfo.newBuilder().artifactUuid(heatEnvPlaceholder.getUniqueId()).build(),
5318 null, heatEnvPlaceholder, null);
5319 return Either.left(heatEnvPlaceholder);
5322 private void setHeatCurrentValuesOnHeatEnvDefaultValues(ArtifactDefinition artifact, ArtifactDefinition artifactDefinition) {
5323 if (artifact.getListHeatParameters() == null) {
5326 List<HeatParameterDefinition> heatEnvParameters = new ArrayList<>();
5327 for (HeatParameterDefinition parameter : artifact.getListHeatParameters()) {
5328 HeatParameterDefinition heatEnvParameter = new HeatParameterDefinition(parameter);
5329 heatEnvParameter.setDefaultValue(parameter.getCurrentValue());
5330 heatEnvParameter.setCurrentValue(null);
5331 heatEnvParameters.add(heatEnvParameter);
5333 artifactDefinition.setListHeatParameters(heatEnvParameters);
5336 private void buildHeatEnvFileName(ArtifactDefinition heatArtifact, ArtifactDefinition heatEnvArtifact, Map<String, Object> placeHolderData) {
5337 String heatExtension = GeneralUtility.getFilenameExtension(heatArtifact.getArtifactName());
5338 String envExtension = (String) placeHolderData.get(ARTIFACT_PLACEHOLDER_FILE_EXTENSION);
5339 String name = heatArtifact.getArtifactName();
5342 name = heatArtifact.getArtifactLabel();
5343 fileName = name + "." + envExtension;
5346 fileName = name.replaceAll("." + heatExtension, "." + envExtension);
5348 heatEnvArtifact.setArtifactName(fileName);
5351 private void handleEnvArtifactVersion(ArtifactDefinition heatEnvArtifact, Map<String, String> existingEnvVersions) {
5352 if (null != existingEnvVersions) {
5353 String prevVersion = existingEnvVersions.get(heatEnvArtifact.getArtifactName());
5354 if (null != prevVersion) {
5355 heatEnvArtifact.setArtifactVersion(prevVersion);
5361 * Handles Artifacts Request For Inner Component
5363 * @param artifactsToHandle
5366 * @param vfcsNewCreatedArtifacts
5369 * @param inTransaction
5372 public Either<List<ArtifactDefinition>, ResponseFormat> handleArtifactsRequestForInnerVfcComponent(List<ArtifactDefinition> artifactsToHandle, Resource component, User user, List<ArtifactDefinition> vfcsNewCreatedArtifacts,
5373 ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) {
5375 Either<List<ArtifactDefinition>, ResponseFormat> handleArtifactsResult = null;
5376 ComponentTypeEnum componentType = component.getComponentType();
5377 List<ArtifactDefinition> uploadedArtifacts = new ArrayList<>();
5378 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
5379 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult;
5383 for (ArtifactDefinition artifact : artifactsToHandle) {
5384 originData = buildJsonStringForCsarVfcArtifact(artifact);
5385 origMd5 = GeneralUtility.calculateMD5Base64EncodedByString(originData);
5386 actionResult = handleArtifactRequest(component.getUniqueId(), user.getUserId(), componentType, operation, artifact
5387 .getUniqueId(), artifact, origMd5, originData, null, null, null, null, shouldLock, inTransaction);
5388 if (actionResult.isRight()) {
5389 log.debug("Failed to upload artifact to component with type {} and name {}. Status is {}. ", componentType, component
5390 .getName(), actionResult.right().value());
5391 errorWrapper.setInnerElement(actionResult.right().value());
5392 if (ArtifactOperationEnum.isCreateOrLink(operation.getArtifactOperationEnum())) {
5393 vfcsNewCreatedArtifacts.addAll(uploadedArtifacts);
5397 uploadedArtifacts.add(actionResult.left().value().left().value());
5399 if (errorWrapper.isEmpty()) {
5400 handleArtifactsResult = Either.left(uploadedArtifacts);
5403 handleArtifactsResult = Either.right(errorWrapper.getInnerElement());
5406 catch (Exception e) {
5407 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
5408 handleArtifactsResult = Either.right(responseFormat);
5409 log.debug("Exception occured when handleArtifactsRequestForInnerVfcComponent, error is:{}", e.getMessage(), e);
5411 return handleArtifactsResult;
5414 private ComponentInstance getRelatedComponentInstance(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
5415 ComponentInstance componentInstance = null;
5416 String normalizedName = ValidationUtils.normalizeComponentInstanceName(resourceInstanceName);
5417 Component component = getComponentByUuid(componentType, componentUuid, errorWrapper);
5418 if (errorWrapper.isEmpty()) {
5419 componentInstance = component.getComponentInstances()
5421 .filter(ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName())
5422 .equals(normalizedName))
5425 if (componentInstance == null) {
5426 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, RESOURCE_INSTANCE, component
5428 .getValue(), component.getName()));
5429 log.debug(COMPONENT_INSTANCE_NOT_FOUND, resourceInstanceName, component.getName());
5432 return componentInstance;
5435 private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(Component component, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
5437 ImmutablePair<Component, ComponentInstance> relatedComponentComponentInstancePair = null;
5438 String normalizedName = ValidationUtils.normalizeComponentInstanceName(resourceInstanceName);
5439 ComponentInstance componentInstance = component.getComponentInstances()
5441 .filter(ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName())
5442 .equals(normalizedName))
5445 if (componentInstance == null) {
5446 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, RESOURCE_INSTANCE, component
5448 .getValue(), component.getName()));
5449 log.debug(COMPONENT_INSTANCE_NOT_FOUND, resourceInstanceName, component.getName());
5452 relatedComponentComponentInstancePair = new ImmutablePair<>(component, componentInstance);
5454 return relatedComponentComponentInstancePair;
5457 private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
5458 ComponentInstance componentInstance;
5459 ImmutablePair<Component, ComponentInstance> relatedComponentComponentInstancePair = null;
5460 Component component = getLatestComponentByUuid(componentType, componentUuid, errorWrapper);
5461 if (errorWrapper.isEmpty()) {
5462 componentInstance = component.getComponentInstances()
5464 .filter(ci -> ci.getNormalizedName().equals(resourceInstanceName))
5467 if (componentInstance == null) {
5468 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, RESOURCE_INSTANCE, component
5470 .getValue(), component.getName()));
5471 log.debug(COMPONENT_INSTANCE_NOT_FOUND, resourceInstanceName, component.getName());
5474 relatedComponentComponentInstancePair = new ImmutablePair<>(component, componentInstance);
5477 return relatedComponentComponentInstancePair;
5480 private byte[] downloadArtifact(Map<String, ArtifactDefinition> artifacts, String artifactUUID, Wrapper<ResponseFormat> errorWrapper, String componentName) {
5482 byte[] downloadedArtifact = null;
5483 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = null;
5484 List<ArtifactDefinition> artifactsList = null;
5485 ArtifactDefinition deploymentArtifact = null;
5486 if (artifacts != null && !artifacts.isEmpty()) {
5487 artifactsList = artifacts.values()
5489 .filter(art -> art.getArtifactUUID() != null && art.getArtifactUUID()
5490 .equals(artifactUUID))
5491 .collect(Collectors.toList());
5493 if (artifactsList == null || artifactsList.isEmpty()) {
5494 log.debug("Deployment artifact with uuid {} was not found for component {}", artifactUUID, componentName);
5495 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactUUID));
5497 if (errorWrapper.isEmpty()) {
5498 deploymentArtifact = artifactsList.get(0);
5499 downloadArtifactEither = downloadArtifact(deploymentArtifact);
5500 if (downloadArtifactEither.isRight()) {
5501 log.debug("Failed to download artifact {}. ", deploymentArtifact.getArtifactName());
5502 errorWrapper.setInnerElement(downloadArtifactEither.right().value());
5505 if (errorWrapper.isEmpty()) {
5506 log.trace("Succeeded to download artifact with uniqueId {}", deploymentArtifact.getUniqueId());
5507 downloadedArtifact = downloadArtifactEither.left().value().getRight();
5509 return downloadedArtifact;
5512 private Component getLatestComponentByUuid(ComponentTypeEnum componentType, String componentUuid, Wrapper<ResponseFormat> errorWrapper) {
5513 Component component = null;
5514 Either<Component, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentByUuid(componentUuid);
5515 if (getComponentRes.isRight()) {
5516 StorageOperationStatus status = getComponentRes.right().value();
5517 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
5518 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
5521 component = getComponentRes.left().value();
5526 private Component getComponentByUuid(ComponentTypeEnum componentType, String componentUuid, Wrapper<ResponseFormat> errorWrapper) {
5527 Component component = null;
5528 Either<List<Component>, StorageOperationStatus> getComponentRes = toscaOperationFacade.getComponentListByUuid(componentUuid, null);
5529 if (getComponentRes.isRight()) {
5530 StorageOperationStatus status = getComponentRes.right().value();
5531 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
5532 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
5535 List<Component> value = getComponentRes.left().value();
5536 if (value.isEmpty()) {
5537 log.debug("Could not fetch component with type {} and uuid {}.", componentType, componentUuid);
5538 ActionStatus status = componentType == ComponentTypeEnum.RESOURCE ? ActionStatus.RESOURCE_NOT_FOUND : ActionStatus.SERVICE_NOT_FOUND;
5539 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(status));
5542 component = value.get(0);
5548 private String getLatestParentArtifactDataIdByArtifactUUID(String artifactUUID, Wrapper<ResponseFormat> errorWrapper, String parentId, ComponentTypeEnum componentType) {
5549 String artifactId = null;
5550 ActionStatus actionStatus = ActionStatus.ARTIFACT_NOT_FOUND;
5551 StorageOperationStatus storageStatus;
5552 ArtifactDefinition latestArtifact = null;
5553 List<ArtifactDefinition> artifacts = null;
5554 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifactsRes = artifactToscaOperation.getArtifacts(parentId);
5555 if (getArtifactsRes.isRight()) {
5556 storageStatus = getArtifactsRes.right().value();
5557 log.debug("Couldn't fetch artifacts data for parent component {} with uid {}, error: {}", componentType, parentId, storageStatus);
5558 if (!storageStatus.equals(StorageOperationStatus.NOT_FOUND)) {
5559 actionStatus = componentsUtils.convertFromStorageResponse(storageStatus);
5561 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
5563 if (errorWrapper.isEmpty()) {
5564 artifacts = getArtifactsRes.left()
5568 .filter(a -> a.getArtifactUUID() != null && a.getArtifactUUID()
5569 .equals(artifactUUID))
5570 .collect(Collectors.toList());
5571 if (artifacts == null || artifacts.isEmpty()) {
5572 log.debug("Couldn't fetch artifact with UUID {} data for parent component {} with uid {}, error: {}", artifactUUID, componentType, parentId, actionStatus);
5573 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
5576 if (errorWrapper.isEmpty()) {
5577 latestArtifact = artifacts.stream().max((a1, a2) -> {
5578 int compareRes = Double.compare(Double.parseDouble(a1.getArtifactVersion()), Double.parseDouble(a2.getArtifactVersion()));
5579 if (compareRes == 0) {
5580 compareRes = Long.compare(a1.getLastUpdateDate() == null ? 0 : a1.getLastUpdateDate(), a2.getLastUpdateDate() == null ? 0 : a2
5581 .getLastUpdateDate());
5585 if (latestArtifact == null) {
5586 log.debug("Couldn't fetch latest artifact with UUID {} data for parent component {} with uid {}, error: {}", artifactUUID, componentType, parentId, actionStatus);
5587 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
5590 if (errorWrapper.isEmpty()) {
5591 artifactId = latestArtifact.getUniqueId();
5596 private Component checkoutParentComponent(ComponentTypeEnum componentType, String parentId, String userId, Wrapper<ResponseFormat> errorWrapper) {
5598 Component component = null;
5599 Either<User, ActionStatus> getUserRes = userBusinessLogic.getUser(userId, false);
5600 if (getUserRes.isRight()) {
5601 log.debug("Could not fetch User of component {} with uid {} to checked out. Status is {}. ", componentType.getNodeType(), parentId, getUserRes
5604 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(getUserRes.right().value()));
5606 if (errorWrapper.isEmpty()) {
5607 User modifier = getUserRes.left().value();
5608 LifecycleChangeInfoWithAction changeInfo = new LifecycleChangeInfoWithAction("External API checkout", LifecycleChanceActionEnum.UPDATE_FROM_EXTERNAL_API);
5609 Either<? extends Component, ResponseFormat> checkoutRes = lifecycleBusinessLogic.changeComponentState(componentType, parentId, modifier, LifeCycleTransitionEnum.CHECKOUT, changeInfo, false, true);
5610 if (checkoutRes.isRight()) {
5611 log.debug("Could not change state of component {} with uid {} to checked out. Status is {}. ", componentType
5612 .getNodeType(), parentId, checkoutRes.right().value().getStatus());
5613 errorWrapper.setInnerElement(checkoutRes.right().value());
5616 component = checkoutRes.left().value();
5622 private String buildJsonStringForCsarVfcArtifact(ArtifactDefinition artifact) {
5623 Map<String, Object> json = new HashMap<>();
5624 String artifactName = artifact.getArtifactName();
5625 json.put(Constants.ARTIFACT_NAME, artifactName);
5626 json.put(Constants.ARTIFACT_LABEL, artifact.getArtifactLabel());
5627 json.put(Constants.ARTIFACT_TYPE, artifact.getArtifactType());
5628 json.put(Constants.ARTIFACT_GROUP_TYPE, ArtifactGroupTypeEnum.DEPLOYMENT.getType());
5629 json.put(Constants.ARTIFACT_DESCRIPTION, artifact.getDescription());
5630 json.put(Constants.ARTIFACT_PAYLOAD_DATA, artifact.getPayloadData());
5631 json.put(Constants.ARTIFACT_DISPLAY_NAME, artifact.getArtifactDisplayName());
5632 return gson.toJson(json);
5636 void setNodeTemplateOperation(NodeTemplateOperation nodeTemplateOperation) {
5637 this.nodeTemplateOperation = nodeTemplateOperation;