2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.openecomp.sdc.be.components.impl;
23 import java.io.ByteArrayInputStream;
24 import java.io.IOException;
25 import java.math.BigDecimal;
26 import java.util.ArrayList;
27 import java.util.Comparator;
28 import java.util.EnumMap;
29 import java.util.HashMap;
30 import java.util.Iterator;
31 import java.util.List;
33 import java.util.Map.Entry;
34 import java.util.Optional;
36 import java.util.function.Predicate;
37 import java.util.function.Supplier;
38 import java.util.stream.Collectors;
40 import javax.servlet.http.HttpServletRequest;
42 import org.apache.commons.codec.binary.Base64;
43 import org.apache.commons.collections.CollectionUtils;
44 import org.apache.commons.collections.MapUtils;
45 import org.apache.commons.lang.StringUtils;
46 import org.apache.commons.lang3.tuple.ImmutablePair;
47 import org.openecomp.sdc.be.components.ArtifactsResolver;
48 import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum;
49 import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaTagNamesEnum;
50 import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
51 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
52 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction.LifecycleChanceActionEnum;
53 import org.openecomp.sdc.be.config.BeEcompErrorManager;
54 import org.openecomp.sdc.be.config.Configuration.ArtifactTypeConfig;
55 import org.openecomp.sdc.be.config.ConfigurationManager;
56 import org.openecomp.sdc.be.config.validation.DeploymentArtifactHeatConfiguration;
57 import org.openecomp.sdc.be.dao.api.ActionStatus;
58 import org.openecomp.sdc.be.dao.cassandra.ArtifactCassandraDao;
59 import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus;
60 import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
61 import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
62 import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
63 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
64 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
65 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
66 import org.openecomp.sdc.be.model.ArtifactDefinition;
67 import org.openecomp.sdc.be.model.ArtifactType;
68 import org.openecomp.sdc.be.model.Component;
69 import org.openecomp.sdc.be.model.ComponentInstance;
70 import org.openecomp.sdc.be.model.ComponentParametersView;
71 import org.openecomp.sdc.be.model.GroupDefinition;
72 import org.openecomp.sdc.be.model.GroupInstance;
73 import org.openecomp.sdc.be.model.HeatParameterDefinition;
74 import org.openecomp.sdc.be.model.InterfaceDefinition;
75 import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;
76 import org.openecomp.sdc.be.model.LifecycleStateEnum;
77 import org.openecomp.sdc.be.model.Operation;
78 import org.openecomp.sdc.be.model.Resource;
79 import org.openecomp.sdc.be.model.Service;
80 import org.openecomp.sdc.be.model.User;
81 import org.openecomp.sdc.be.model.heat.HeatParameterType;
82 import org.openecomp.sdc.be.model.jsontitan.operations.NodeTemplateOperation;
83 import org.openecomp.sdc.be.model.operations.api.IElementOperation;
84 import org.openecomp.sdc.be.model.operations.api.IHeatParametersOperation;
85 import org.openecomp.sdc.be.model.operations.api.IInterfaceLifecycleOperation;
86 import org.openecomp.sdc.be.model.operations.api.IUserAdminOperation;
87 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
88 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
89 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
90 import org.openecomp.sdc.be.resources.data.ComponentMetadataData;
91 import org.openecomp.sdc.be.resources.data.ESArtifactData;
92 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
93 import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants;
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.common.api.ArtifactGroupTypeEnum;
103 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
104 import org.openecomp.sdc.common.api.Constants;
105 import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
106 import org.openecomp.sdc.common.datastructure.Wrapper;
107 import org.openecomp.sdc.common.util.GeneralUtility;
108 import org.openecomp.sdc.common.util.ValidationUtils;
109 import org.openecomp.sdc.common.util.YamlToObjectConverter;
110 import org.openecomp.sdc.exception.ResponseFormat;
111 import org.slf4j.Logger;
112 import org.slf4j.LoggerFactory;
113 import org.springframework.beans.factory.annotation.Autowired;
114 import org.xml.sax.InputSource;
115 import org.xml.sax.SAXException;
116 import org.xml.sax.XMLReader;
117 import org.yaml.snakeyaml.Yaml;
119 import com.google.gson.Gson;
120 import com.google.gson.GsonBuilder;
121 import com.sun.org.apache.xerces.internal.parsers.SAXParser;
123 import fj.data.Either;
125 @org.springframework.stereotype.Component("artifactBusinessLogic")
126 public class ArtifactsBusinessLogic extends BaseBusinessLogic {
127 private static final String ARTIFACT_TYPE_OTHER = "OTHER";
128 private static final String ARTIFACT_DESCRIPTION = "artifact description";
129 private static final String ARTIFACT_LABEL = "artifact label";
130 private static final String ARTIFACT_URL = "artifact url";
131 private static final String ARTIFACT_NAME = "artifact name";
132 private static final String ARTIFACT_PAYLOAD = "artifact payload";
134 private static final String ARTIFACT_PLACEHOLDER_TYPE = "type";
135 private static final String ARTIFACT_PLACEHOLDER_DISPLAY_NAME = "displayName";
136 private static final Object ARTIFACT_PLACEHOLDER_DESCRIPTION = "description";
138 public static final String HEAT_ENV_NAME = "heatEnv";
139 public static final String HEAT_VF_ENV_NAME = "VfHeatEnv";
140 public static final String HEAT_ENV_SUFFIX = "env";
141 private static final String ARTIFACT_PLACEHOLDER_FILE_EXTENSION = "fileExtension";
143 // private static Integer defaultHeatTimeout;
144 // private static final Integer NON_HEAT_TIMEOUT = 0;
145 private static Logger log = LoggerFactory.getLogger(ArtifactsBusinessLogic.class.getName());
146 private Gson gson = new GsonBuilder().setPrettyPrinting().create();
148 @javax.annotation.Resource
149 private IInterfaceLifecycleOperation interfaceLifecycleOperation;
150 @javax.annotation.Resource
151 private IUserAdminOperation userOperaton;
153 @javax.annotation.Resource
154 private IElementOperation elementOperation;
156 @javax.annotation.Resource
157 private ResourceBusinessLogic resourceBusinessLogic;
159 @javax.annotation.Resource
160 private ServiceBusinessLogic serviceBusinessLogic;
162 @javax.annotation.Resource
163 private UserBusinessLogic userAdminManager;
165 @javax.annotation.Resource
166 private IHeatParametersOperation heatParametersOperation;
169 private ArtifactCassandraDao artifactCassandraDao;
172 private ToscaExportHandler toscaExportUtils;
175 private CsarUtils csarUtils;
178 private LifecycleBusinessLogic lifecycleBusinessLogic;
181 private IUserBusinessLogic userBusinessLogic;
183 NodeTemplateOperation nodeTemplateOperation;
186 private ArtifactsResolver artifactsResolver;
188 public ArtifactsBusinessLogic() {
189 // defaultHeatTimeout = ConfigurationManager.getConfigurationManager().getConfiguration().getDefaultHeatArtifactTimeoutMinutes();
190 // if ((defaultHeatTimeout == null) || (defaultHeatTimeout < 1)) {
191 // defaultHeatTimeout = 60;
195 public static enum ArtifactOperationEnum {
196 Create(), Update(), Delete(), Download();
199 public class ArtifactOperationInfo {
201 private ArtifactOperationEnum artifactOperationEnum;
202 private boolean isExternalApi;
203 private boolean ignoreLifecycleState;
205 public ArtifactOperationInfo(boolean isExternalApi, boolean ignoreLifecycleState, ArtifactOperationEnum artifactOperationEnum) {
206 this.artifactOperationEnum = artifactOperationEnum;
207 this.isExternalApi = isExternalApi;
208 this.ignoreLifecycleState = ignoreLifecycleState;
211 public boolean isExternalApi() {
212 return isExternalApi;
215 public boolean ignoreLifecycleState() {
216 return ignoreLifecycleState;
219 public ArtifactOperationEnum getArtifactOperationEnum() {
220 return artifactOperationEnum;
226 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleArtifactRequest(String componentId, String userId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo,
227 String origMd5, String originData, String interfaceName, String operationName, String parentId, String containerComponentType) {
228 return handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, origMd5, originData, interfaceName, operationName, parentId, containerComponentType, true, false);
231 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleArtifactRequest(String componentId, String userId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo,
232 String origMd5, String originData, String interfaceName, String operationName, String parentId, String containerComponentType, boolean shouldLock, boolean inTransaction) {
234 // step 1 - detect auditing type
235 AuditingActionEnum auditingAction = detectAuditingType(operation, origMd5);
236 // step 2 - check header
237 if (userId == null) {
238 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
239 log.debug("handleArtifactRequest - no HTTP_CSP_HEADER , component id {}", componentId);
240 handleAuditing(auditingAction, null, componentId, null, null, null, artifactId, responseFormat, componentType, null);
241 return Either.right(responseFormat);
243 // step 3 - check user existence
244 Either<User, ResponseFormat> userResult = validateUserExists(userId, auditingAction, componentId, artifactId, componentType, inTransaction);
245 if (userResult.isRight()) {
246 return Either.right(userResult.right().value());
249 // step 4 - check user's role
250 User user = userResult.left().value();
251 Either<Boolean, ResponseFormat> validateUserRole = validateUserRole(user, auditingAction, componentId, artifactId, componentType, operation);
252 if (validateUserRole.isRight()) {
253 return Either.right(validateUserRole.right().value());
257 // 5. check service/resource existence
258 // 6. check service/resource check out
259 // 7. user is owner of checkout state
260 org.openecomp.sdc.be.model.Component component = null;
261 // ComponentInstance resourceInstance = null;
262 String realComponentId = componentType == ComponentTypeEnum.RESOURCE_INSTANCE ? parentId : componentId;
263 Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(realComponentId, userId, auditingAction, user, artifactId, componentType, containerComponentType, inTransaction);
264 if (validateComponent.isRight()) {
265 return Either.right(validateComponent.right().value());
267 component = validateComponent.left().value();
268 Either<Boolean, ResponseFormat> validateWorkOnResource = validateWorkOnComponent(component, userId, auditingAction, user, artifactId, operation, componentType);
269 if (validateWorkOnResource.isRight()) {
270 return Either.right(validateWorkOnResource.right().value());
273 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result = validateAndHandleArtifact(componentId, componentType, operation, artifactId, artifactInfo, origMd5, originData, interfaceName, operationName, parentId, user, component,
274 shouldLock, inTransaction, true);
280 * This Method validates only the Artifact and does not validate user / role / component ect...<br>
281 * For regular usage use <br>
282 * {@link #handleArtifactRequest(String, String, ComponentTypeEnum, ArtifactOperationInfo, String, ArtifactDefinition, String, String, String, String, String, String)}
286 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> validateAndHandleArtifact(String componentUniqueId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactUniqueId,
287 ArtifactDefinition artifactDefinition, String origMd5, String originData, String interfaceName, String operationName, String parentId, User user, Component component, boolean shouldLock, boolean inTransaction, boolean needUpdateGroup) {
288 Component parent = component;
289 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
291 AuditingActionEnum auditingAction = detectAuditingType(operation, origMd5);
292 artifactDefinition = validateArtifact(componentUniqueId, componentType, operation, artifactUniqueId, artifactDefinition, parentId, auditingAction, user, component, parent, shouldLock, errorWrapper, inTransaction);
294 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result;
295 if (errorWrapper.isEmpty()) {
297 result = doAction(componentUniqueId, componentType, operation, artifactUniqueId, artifactDefinition, origMd5, originData, interfaceName, operationName, auditingAction, user, parent, shouldLock, inTransaction, needUpdateGroup);
299 result = Either.right(errorWrapper.getInnerElement());
304 private ArtifactDefinition validateArtifact(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, String parentId, AuditingActionEnum auditingAction, User user,
305 org.openecomp.sdc.be.model.Component component, org.openecomp.sdc.be.model.Component parent, boolean shouldLock, Wrapper<ResponseFormat> errorWrapper, boolean inTransaction) {
306 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Update || operation.getArtifactOperationEnum() == ArtifactOperationEnum.Delete || operation.getArtifactOperationEnum() == ArtifactOperationEnum.Download) {
307 Either<ArtifactDefinition, ResponseFormat> validateArtifact = validateArtifact(componentId, componentType, artifactId, component, auditingAction, parentId, inTransaction);
308 if (validateArtifact.isRight()) {
309 ResponseFormat responseFormat = validateArtifact.right().value();
310 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
311 errorWrapper.setInnerElement(validateArtifact.right().value());
313 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Download) {
314 artifactInfo = validateArtifact.left().value();
315 handleHeatEnvDownload(componentId, componentType, user, component, validateArtifact, shouldLock, errorWrapper);
322 private void handleHeatEnvDownload(String componentId, ComponentTypeEnum componentType, User user, org.openecomp.sdc.be.model.Component component, Either<ArtifactDefinition, ResponseFormat> validateArtifact, boolean shouldLock,
323 Wrapper<ResponseFormat> errorWrapper) {
324 ArtifactDefinition validatedArtifact = validateArtifact.left().value();
326 if (validatedArtifact.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType())) {
327 if (ComponentTypeEnum.SERVICE == component.getComponentType()) {
328 ComponentInstance componentInstance = component.getComponentInstances().stream().filter(p -> p.getUniqueId().equals(componentId)).findAny().get();
329 Map<String, ArtifactDefinition> deploymentArtifacts = componentInstance.getDeploymentArtifacts();
331 ArtifactDefinition heatEnvWithHeatParams = deploymentArtifacts.values().stream().filter(p -> p.getUniqueId().equals(validatedArtifact.getUniqueId())).findAny().get();
332 Either<ArtifactDefinition, ResponseFormat> eitherGenerated = generateHeatEnvArtifact(heatEnvWithHeatParams, componentType, component, componentInstance.getName(), user, shouldLock, componentId);
333 if (eitherGenerated.isRight()) {
334 errorWrapper.setInnerElement(eitherGenerated.right().value());
340 private boolean artifactGenerationRequired(org.openecomp.sdc.be.model.Component component, ArtifactDefinition artifactInfo) {
341 boolean needGenerate;
342 needGenerate = artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA && (component.getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN || component.getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
343 needGenerate = needGenerate || (ComponentTypeEnum.RESOURCE == component.getComponentType() && (artifactInfo.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType()) || isAbstractVfcEmptyCsar((Resource) component, artifactInfo)));
347 private boolean isAbstractVfcEmptyCsar(Resource resource, ArtifactDefinition artifactInfo) {
348 return resource.isAbstract() && artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA && artifactInfo.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType()) && StringUtils.isEmpty(artifactInfo.getArtifactChecksum());
351 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateAndSaveToscaArtifact(ArtifactDefinition artifactDefinition, org.openecomp.sdc.be.model.Component component, User user, boolean isInCertificationRequest,
352 boolean shouldLock, boolean inTransaction, boolean fetchTemplatesFromDB) {
354 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generated = generateToscaArtifact(component, artifactDefinition, isInCertificationRequest, fetchTemplatesFromDB);
355 if (generated.isRight()) {
358 byte[] decodedPayload = artifactDefinition.getPayloadData();
359 artifactDefinition.setEsId(artifactDefinition.getUniqueId());
360 artifactDefinition.setArtifactChecksum(GeneralUtility.calculateMD5ByByteArray(decodedPayload));
361 return lockComponentAndUpdateArtifact(component.getUniqueId(), artifactDefinition, AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, artifactDefinition.getUniqueId(), user, component.getComponentType(), component, decodedPayload, null, null,
362 shouldLock, inTransaction);
366 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateToscaArtifact(Component parent, ArtifactDefinition artifactInfo, boolean isInCertificationRequest, boolean fetchTemplatesFromDB) {
367 log.debug("tosca artifact generation");
368 if (artifactInfo.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType())) {
369 Either<byte[], ResponseFormat> generated = csarUtils.createCsar(parent, fetchTemplatesFromDB, isInCertificationRequest);
371 if (generated.isRight()) {
372 log.debug("Failed to export tosca csar for component {} error {}", parent.getUniqueId(), generated.right().value());
374 return Either.right(generated.right().value());
376 byte[] value = generated.left().value();
377 artifactInfo.setPayload(value);
380 Either<ToscaRepresentation, ToscaError> exportComponent = toscaExportUtils.exportComponent(parent);
381 if (exportComponent.isRight()) {
382 log.debug("Failed export tosca yaml for component {} error {}", parent.getUniqueId(), exportComponent.right().value());
383 ActionStatus status = componentsUtils.convertFromToscaError(exportComponent.right().value());
384 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status);
385 return Either.right(responseFormat);
387 log.debug("Tosca yaml exported for component {} ", parent.getUniqueId());
388 String payload = exportComponent.left().value().getMainYaml();
389 artifactInfo.setPayloadData(payload);
391 return Either.left(Either.left(artifactInfo));
394 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> doAction(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, String origMd5,
395 String originData, String interfaceName, String operationName, AuditingActionEnum auditingAction, User user, org.openecomp.sdc.be.model.Component parent, boolean shouldLock, boolean inTransaction, boolean needUpdateGroup) {
396 if (interfaceName != null && operationName != null) {
397 interfaceName = interfaceName.toLowerCase();
398 operationName = operationName.toLowerCase();
400 switch (operation.getArtifactOperationEnum()) {
402 if (artifactGenerationRequired(parent, artifactInfo)) {
403 return generateNotSavedArtifact(parent, artifactInfo, shouldLock, inTransaction);
405 return handleDownload(componentId, artifactId, user, auditingAction, componentType, parent, shouldLock, inTransaction);
407 return handleDelete(componentId, artifactId, user, auditingAction, componentType, parent, interfaceName, operationName, shouldLock, inTransaction);
409 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result = null;
410 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
411 if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)
412 && (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_VOL || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_ENV)) {
413 result = handleUpdateHeatEnv(componentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, originData, origMd5, operation, shouldLock, inTransaction);
414 if (needUpdateGroup && result.isLeft()) {
415 Either<ArtifactDefinition, Operation> updateResult = result.left().value();
416 ActionStatus error = updateGroupInstance(artifactInfo, updateResult.left().value(), parent, componentType, componentId);
417 if (error != ActionStatus.OK) {
418 result = Either.right(componentsUtils.getResponseFormat(error));
422 if (componentType.equals(ComponentTypeEnum.RESOURCE) && artifactType == ArtifactTypeEnum.HEAT_ENV) {
423 result = handleUpdateHeatWithHeatEnvParams(componentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, originData, origMd5, operation, shouldLock, inTransaction, needUpdateGroup);
426 if (result == null) {
427 result = handleUpdate(componentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceName, operationName, shouldLock, inTransaction);
428 if (needUpdateGroup && result.isLeft()) {
429 Either<ArtifactDefinition, Operation> updateResult = result.left().value();
431 ActionStatus error = updateGroupForHeat(artifactInfo, updateResult.left().value(), parent, componentType);
432 if (error != ActionStatus.OK) {
433 result = Either.right(componentsUtils.getResponseFormat(error));
439 return handleCreate(componentId, artifactInfo, operation, auditingAction, user, componentType, parent, origMd5, originData, interfaceName, operationName, shouldLock, inTransaction);
444 private ActionStatus updateGroupForHeat(ArtifactDefinition artifactInfo, ArtifactDefinition artAfterUpdate, Component parent, ComponentTypeEnum componentType) {
445 List<GroupDefinition> groups = parent.getGroups();
446 if (groups != null && !groups.isEmpty()) {
447 List<GroupDataDefinition> groupToUpdate = groups.stream().filter(g -> g.getArtifacts() != null && g.getArtifacts().contains(artifactInfo.getUniqueId())).collect(Collectors.toList());
448 if (groupToUpdate != null && !groupToUpdate.isEmpty()) {
449 groupToUpdate.forEach(g -> {
450 g.getArtifacts().remove(artifactInfo.getUniqueId());
451 g.getArtifactsUuid().remove(artifactInfo.getArtifactUUID());
452 g.getArtifacts().add(artAfterUpdate.getUniqueId());
453 g.getArtifactsUuid().add(artAfterUpdate.getArtifactUUID());
455 Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(parent, componentType, groupToUpdate);
456 if (status.isRight()) {
457 log.debug("Failed to update groups of the component {}. ", parent.getUniqueId());
458 return componentsUtils.convertFromStorageResponse(status.right().value());
462 return ActionStatus.OK;
465 private ActionStatus updateGroupForHeat(ArtifactDefinition artifactInfoHeat, ArtifactDefinition artHeatAfterUpdate, ArtifactDefinition artifactInfoHeatE, ArtifactDefinition artHEAfterUpdate, Component parent, ComponentTypeEnum componentType) {
466 List<GroupDefinition> groups = parent.getGroups();
467 if (groups != null && !groups.isEmpty()) {
468 List<GroupDataDefinition> groupToUpdate = groups.stream().filter(g -> g.getArtifacts() != null && g.getArtifacts().contains(artifactInfoHeat.getUniqueId())).collect(Collectors.toList());
469 if (groupToUpdate != null && !groupToUpdate.isEmpty()) {
470 groupToUpdate.forEach(g -> {
471 g.getArtifacts().remove(artifactInfoHeat.getUniqueId());
472 g.getArtifactsUuid().remove(artifactInfoHeat.getArtifactUUID());
473 g.getArtifacts().remove(artifactInfoHeatE.getUniqueId());
474 g.getArtifacts().add(artHeatAfterUpdate.getUniqueId());
475 g.getArtifactsUuid().add(artHeatAfterUpdate.getArtifactUUID());
476 g.getArtifacts().add(artHEAfterUpdate.getUniqueId());
478 Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(parent, componentType, groupToUpdate);
479 if (status.isRight()) {
480 log.debug("Failed to update groups of the component {}. ", parent.getUniqueId());
481 return componentsUtils.convertFromStorageResponse(status.right().value());
485 return ActionStatus.OK;
488 private ActionStatus updateGroupInstance(ArtifactDefinition artifactInfo, ArtifactDefinition artAfterUpdate, Component parent, ComponentTypeEnum componentType, String parentId) {
489 List<GroupInstance> updatedGroupInstances = new ArrayList<>();
490 List<GroupInstance> groupInstances = null;
491 Optional<ComponentInstance> componentInstOp = parent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(parentId)).findFirst();
492 if (componentInstOp.isPresent()) {
493 groupInstances = componentInstOp.get().getGroupInstances();
495 if (CollectionUtils.isNotEmpty(groupInstances)) {
496 boolean isUpdated = false;
497 for (GroupInstance groupInstance : groupInstances) {
499 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifacts()) && groupInstance.getGroupInstanceArtifacts().contains(artifactInfo.getUniqueId())) {
500 groupInstance.getGroupInstanceArtifacts().remove(artifactInfo.getUniqueId());
501 groupInstance.getGroupInstanceArtifacts().add(artAfterUpdate.getUniqueId());
504 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifactsUuid()) && groupInstance.getGroupInstanceArtifactsUuid().contains(artifactInfo.getArtifactUUID())) {
505 groupInstance.getGroupInstanceArtifactsUuid().remove(artifactInfo.getArtifactUUID());
506 groupInstance.getGroupInstanceArtifacts().add(artAfterUpdate.getArtifactUUID());
510 updatedGroupInstances.add(groupInstance);
514 Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(parent, componentType, parentId, updatedGroupInstances);
515 if (status.isRight()) {
516 log.debug("Failed to update groups of the component {}. ", parent.getUniqueId());
517 return componentsUtils.convertFromStorageResponse(status.right().value());
519 return ActionStatus.OK;
522 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateNotSavedArtifact(org.openecomp.sdc.be.model.Component parent, ArtifactDefinition artifactInfo, boolean shouldLock, boolean inTransaction) {
523 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result;
524 if (artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA) {
525 result = generateToscaArtifact(parent, artifactInfo, false, false);
527 String heatArtifactId = artifactInfo.getGeneratedFromId();
528 Either<ArtifactDefinition, StorageOperationStatus> heatRes = artifactToscaOperation.getArtifactById(parent.getUniqueId(), heatArtifactId);
529 if (heatRes.isRight()) {
530 log.debug("Failed to fetch heat artifact by generated id {} for heat env {}", heatArtifactId, artifactInfo.getUniqueId());
531 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(heatRes.right().value()), "");
532 return Either.right(responseFormat);
534 String generatedPayload = generateHeatEnvPayload(heatRes.left().value());
535 artifactInfo.setPayloadData(generatedPayload);
536 result = Either.left(Either.left(artifactInfo));
541 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdateHeatWithHeatEnvParams(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user,
542 ComponentTypeEnum componentType, Component parent, String originData, String origMd5, ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction, boolean needToUpdateGroup) {
543 convertParentType(componentType);
544 String parentId = parent.getUniqueId();
545 Either<ArtifactDefinition, StorageOperationStatus> artifactHeatRes = artifactToscaOperation.getArtifactById(componentId, artifactInfo.getGeneratedFromId());
546 ArtifactDefinition currHeatArtifact = artifactHeatRes.left().value();
548 if (origMd5 != null) {
549 Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
550 if (validateMd5.isRight()) {
551 ResponseFormat responseFormat = validateMd5.right().value();
552 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
553 return Either.right(responseFormat);
556 if (artifactInfo.getPayloadData() != null && artifactInfo.getPayloadData().length != 0) {
558 Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
559 if (payloadEither.isRight()) {
560 ResponseFormat responseFormat = payloadEither.right().value();
561 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
562 return Either.right(responseFormat);
564 } else { // duplicate
565 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
566 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
567 return Either.right(responseFormat);
573 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Update Artifact - lock ");
574 if (lockComponent.isRight()) {
575 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right().value(), componentType, null);
576 return Either.right(lockComponent.right().value());
579 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
581 resultOp = updateHeatParams(componentId, artifactId, artifactInfo, user, auditingAction, parent, componentType, currHeatArtifact, origMd5, needToUpdateGroup);
586 if (resultOp == null || resultOp.isRight()) {
587 log.debug("all changes rollback");
588 if (false == inTransaction)
591 log.debug("all changes committed");
592 if (false == inTransaction)
596 componentType = parent.getComponentType();
597 NodeTypeEnum nodeType = componentType.getNodeType();
598 graphLockOperation.unlockComponent(parent.getUniqueId(), nodeType);
599 // graphLockOperation.unlockComponent(parentId, parentType);
608 * @param componentType
613 public Either<ImmutablePair<String, byte[]>, ResponseFormat> handleDownloadToscaModelRequest(Component component, ArtifactDefinition csarArtifact) {
614 if (artifactGenerationRequired(component, csarArtifact)) {
615 Either<byte[], ResponseFormat> generated = csarUtils.createCsar(component, false, false);
617 if (generated.isRight()) {
618 log.debug("Failed to export tosca csar for component {} error {}", component.getUniqueId(), generated.right().value());
620 return Either.right(generated.right().value());
622 return Either.left(new ImmutablePair<String, byte[]>(csarArtifact.getArtifactName(), generated.left().value()));
624 return downloadArtifact(csarArtifact);
627 public Either<ImmutablePair<String, byte[]>, ResponseFormat> handleDownloadRequestById(String componentId, String artifactId, String userId, ComponentTypeEnum componentType, String parentId, String containerComponentType) {
628 // perform all validation in common flow
629 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result = handleArtifactRequest(componentId, userId, componentType, new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Download), artifactId, null, null, null, null,
630 null, parentId, containerComponentType);
631 if (result.isRight()) {
632 return Either.right(result.right().value());
634 ArtifactDefinition artifactDefinition;
635 Either<ArtifactDefinition, Operation> insideValue = result.left().value();
636 if (insideValue.isLeft()) {
637 artifactDefinition = insideValue.left().value();
639 artifactDefinition = insideValue.right().value().getImplementationArtifact();
641 // for tosca artifacts and heat env on VF level generated on download without saving
642 if (artifactDefinition.getPayloadData() != null) {
643 return Either.left(new ImmutablePair<String, byte[]>(artifactDefinition.getArtifactName(), artifactDefinition.getPayloadData()));
645 return downloadArtifact(artifactDefinition);
648 public Either<Map<String, ArtifactDefinition>, ResponseFormat> handleGetArtifactsByType(String containerComponentType, String parentId, ComponentTypeEnum componentType, String componentId, String artifactGroupType, String userId) {
650 // detect auditing type
651 Map<String, ArtifactDefinition> resMap = null;
652 Either<Map<String, ArtifactDefinition>, ResponseFormat> resultOp = null;
657 if (userId == null) {
658 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
659 log.debug("handleGetArtifactsByType - no HTTP_CSP_HEADER , component id {}", componentId);
661 resultOp = Either.right(responseFormat);
665 // check user existence
669 Either<User, ResponseFormat> userResult = validateUserExists(userId, "get artifacts", false);
670 if (userResult.isRight()) {
672 resultOp = Either.right(userResult.right().value());
676 userResult.left().value();
679 // 5. check service/resource existence
680 // 6. check service/resource check out
681 // 7. user is owner of checkout state
682 org.openecomp.sdc.be.model.Component component = null;
683 // ComponentInstance resourceInstance = null;
684 String realComponentId = componentType == ComponentTypeEnum.RESOURCE_INSTANCE ? parentId : componentId;
685 ComponentParametersView componentFilter = new ComponentParametersView();
686 componentFilter.disableAll();
687 componentFilter.setIgnoreArtifacts(false);
688 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE)
689 componentFilter.setIgnoreComponentInstances(false);
691 Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExistsByFilter(realComponentId, ComponentTypeEnum.findByParamName(containerComponentType), componentFilter, false);
693 if (validateComponent.isRight()) {
694 resultOp = Either.right(validateComponent.right().value());
697 component = validateComponent.left().value();
698 Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, "Update Artifact - lock ");
699 if (lockComponent.isRight()) {
701 resultOp = Either.right(lockComponent.right().value());
706 ArtifactGroupTypeEnum groupType = ArtifactGroupTypeEnum.findType(artifactGroupType);
708 if (groupType == null) {
709 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
710 log.debug("handleGetArtifactsByType - not falid groupType {} , component id {}", artifactGroupType, componentId);
712 resultOp = Either.right(responseFormat);
716 if (groupType == ArtifactGroupTypeEnum.DEPLOYMENT) {
717 List<ArtifactDefinition> list = getDeploymentArtifacts(component, componentType.getNodeType(), componentId);
718 if (list != null && !list.isEmpty()) {
719 resMap = list.stream().collect(Collectors.toMap(a -> a.getArtifactLabel(), a -> a));
721 resMap = new HashMap<>();
723 resultOp = Either.left(resMap);
727 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifactsMapStatus = getArtifacts(realComponentId, componentType.getNodeType(), false, groupType, componentId);
728 if (artifactsMapStatus.isRight()) {
729 if (artifactsMapStatus.right().value() != StorageOperationStatus.NOT_FOUND) {
730 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
731 log.debug("handleGetArtifactsByType - not falid groupType {} , component id {}", artifactGroupType, componentId);
732 resultOp = Either.right(responseFormat);
734 resMap = new HashMap<>();
735 resultOp = Either.left(resMap);
738 resMap = artifactsMapStatus.left().value();
739 resultOp = Either.left(resMap);
745 if (resultOp == null || resultOp.isRight()) {
746 log.debug("all changes rollback");
749 log.debug("all changes committed");
754 componentType = component.getComponentType();
755 NodeTypeEnum nodeType = componentType.getNodeType();
756 graphLockOperation.unlockComponent(component.getUniqueId(), nodeType);
757 // graphLockOperation.unlockComponent(parentId, parentType);
762 private Either<ArtifactDefinition, ResponseFormat> validateArtifact(String componentId, ComponentTypeEnum componentType, String artifactId, org.openecomp.sdc.be.model.Component component, AuditingActionEnum auditingAction, String parentId,
763 boolean inTransaction) {
765 // check artifact existence
766 Either<ArtifactDefinition, StorageOperationStatus> artifactResult = artifactToscaOperation.getArtifactById(componentId, artifactId, componentType, component.getUniqueId());
767 if (artifactResult.isRight()) {
768 if (artifactResult.right().value().equals(StorageOperationStatus.ARTIFACT_NOT_FOUND)) {
769 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, "");
770 log.debug("addArtifact - artifact {} not found", artifactId);
771 return Either.right(responseFormat);
774 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(artifactResult.right().value()));
775 log.debug("addArtifact - failed to fetch artifact {}, error {}", artifactId, artifactResult.right().value());
776 return Either.right(responseFormat);
780 // check artifact belong to component
781 boolean found = false;
782 switch (componentType) {
785 found = checkArtifactInComponent(component, artifactId);
787 case RESOURCE_INSTANCE:
788 found = checkArtifactInResourceInstance(component, componentId, artifactId);
794 // String component =
795 // componentType.equals(ComponentTypeEnum.RESOURCE) ? "resource" :
797 String componentName = componentType.name().toLowerCase();
798 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ARTIFACT_NOT_FOUND, componentName);
799 log.debug("addArtifact - Component artifact not found component Id {}, artifact id {}", componentId, artifactId);
800 return Either.right(responseFormat);
802 return Either.left(artifactResult.left().value());
805 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleCreate(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, User user, ComponentTypeEnum componentType,
806 org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
808 String artifactId = null;
811 Either<byte[], ResponseFormat> payloadEither = validateInput(componentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceType, operationName, inTransaction);
812 if (payloadEither.isRight()) {
813 return Either.right(payloadEither.right().value());
815 byte[] decodedPayload = payloadEither.left().value();
816 convertParentType(componentType);
819 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Upload Artifact - lock ");
820 if (lockComponent.isRight()) {
821 handleAuditing(auditingAction, parent, componentId, user, null, null, null, lockComponent.right().value(), componentType, null);
822 return Either.right(lockComponent.right().value());
825 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
828 resultOp = createArtifact(parent, componentId, artifactInfo, decodedPayload, user, componentType, auditingAction, interfaceType, operationName);
832 unlockComponent(resultOp, parent, inTransaction);
839 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> lockComponentAndUpdateArtifact(String parentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user,
840 ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent, byte[] decodedPayload, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
842 convertParentType(componentType);
846 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Update Artifact - lock ");
848 if (lockComponent.isRight()) {
849 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right().value(), componentType, null);
850 return Either.right(lockComponent.right().value());
854 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
856 resultOp = updateArtifactFlow(parent, parentId, artifactId, artifactInfo, user, decodedPayload, componentType, auditingAction, interfaceType, operationName);
861 unlockComponent(resultOp, parent, inTransaction);
866 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdate(String parentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, String artifactId, User user,
867 ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
869 Either<byte[], ResponseFormat> payloadEither = validateInput(parentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceType, operationName, inTransaction);
871 if (payloadEither.isRight()) {
872 return Either.right(payloadEither.right().value());
874 byte[] decodedPayload = payloadEither.left().value();
876 return lockComponentAndUpdateArtifact(parentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, decodedPayload, interfaceType, operationName, shouldLock, inTransaction);
879 private Either<byte[], ResponseFormat> validateInput(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType,
880 org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean inTransaction) {
882 Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
883 if (validateMd5.isRight()) {
884 ResponseFormat responseFormat = validateMd5.right().value();
885 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
886 return Either.right(responseFormat);
890 Either<ArtifactDefinition, ResponseFormat> validateResult = validateInput(componentId, artifactInfo, operation, artifactId, user, interfaceType, operationName, componentType, parent, inTransaction);
891 if (validateResult.isRight()) {
892 ResponseFormat responseFormat = validateResult.right().value();
893 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
894 return Either.right(validateResult.right().value());
897 Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
898 if (payloadEither.isRight()) {
899 ResponseFormat responseFormat = payloadEither.right().value();
900 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
901 log.debug("Error during handle payload");
902 return Either.right(responseFormat);
905 // validate heat parameters. this part must be after the parameters are
906 // extracted in "handlePayload"
907 Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers = validateAndConvertHeatParamers(artifactInfo, artifactInfo.getArtifactType());
908 if (validateAndConvertHeatParamers.isRight()) {
909 ResponseFormat responseFormat = validateAndConvertHeatParamers.right().value();
910 handleAuditing(auditingAction, parent, componentId, user, artifactInfo, null, artifactId, responseFormat, componentType, null);
911 log.debug("Error during handle payload");
912 return Either.right(responseFormat);
914 return payloadEither;
917 public void handleAuditing(AuditingActionEnum auditingActionEnum, Component component, String componentId, User user, ArtifactDefinition artifactDefinition, String prevArtifactUuid, String currentArtifactUuid, ResponseFormat responseFormat,
918 ComponentTypeEnum componentTypeEnum, String resourceInstanceName) {
920 if (auditingActionEnum.getAuditingEsType().equals(AuditingTypesConstants.EXTERNAL_API_EVENT_TYPE)) {
924 EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = createArtifactAuditingFields(artifactDefinition, prevArtifactUuid, currentArtifactUuid);
928 user.setUserId("UNKNOWN");
930 switch (componentTypeEnum) {
933 Resource resource = (Resource) component;
934 if (resource == null) {
935 // In that case, component ID should be instead of name
936 resource = new Resource();
937 resource.setName(componentId);
939 componentsUtils.auditResource(responseFormat, user, resource, null, null, auditingActionEnum, auditingFields);
943 Service service = (Service) component;
944 if (service == null) {
945 // In that case, component ID should be instead of name
946 service = new Service();
947 service.setName(componentId);
949 componentsUtils.auditComponent(responseFormat, user, service, null, null, auditingActionEnum, ComponentTypeEnum.SERVICE, auditingFields);
952 case RESOURCE_INSTANCE:
953 if (resourceInstanceName == null) {
954 resourceInstanceName = getResourceInstanceNameFromComponent(component, componentId);
956 auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceInstanceName);
957 componentsUtils.auditComponent(responseFormat, user, component, null, null, auditingActionEnum, ComponentTypeEnum.RESOURCE_INSTANCE, auditingFields);
965 private String getResourceInstanceNameFromComponent(Component component, String componentId) {
966 ComponentInstance resourceInstance = component.getComponentInstances().stream().filter(p -> p.getUniqueId().equals(componentId)).findFirst().orElse(null);
967 String resourceInstanceName = null;
968 if (resourceInstance != null) {
969 resourceInstanceName = resourceInstance.getName();
971 return resourceInstanceName;
974 public EnumMap<AuditingFieldsKeysEnum, Object> createArtifactAuditingFields(ArtifactDefinition artifactDefinition, String prevArtifactUuid, String currentArtifactUuid) {
975 EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
976 // Putting together artifact info
977 String artifactData = buildAuditingArtifactData(artifactDefinition);
978 auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, artifactData);
979 auditingFields.put(AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID, prevArtifactUuid);
980 auditingFields.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, currentArtifactUuid);
981 return auditingFields;
986 private String buildAuditingArtifactData(ArtifactDefinition artifactDefinition) {
987 StringBuilder sb = new StringBuilder();
988 if (artifactDefinition != null) {
989 sb.append(artifactDefinition.getArtifactGroupType().getType()).append(",").append("'").append(artifactDefinition.getArtifactLabel()).append("'").append(",").append(artifactDefinition.getArtifactType()).append(",")
990 .append(artifactDefinition.getArtifactName()).append(",").append(artifactDefinition.getTimeout()).append(",").append(artifactDefinition.getEsId());
993 if (artifactDefinition.getArtifactVersion() != null) {
995 sb.append(artifactDefinition.getArtifactVersion());
1000 if (artifactDefinition.getArtifactUUID() != null) {
1001 sb.append(artifactDefinition.getArtifactUUID());
1006 return sb.toString();
1009 private Either<Boolean, ResponseFormat> validateMd5(String origMd5, String originData, byte[] payload, ArtifactOperationInfo operation) {
1011 if (origMd5 != null) {
1012 String encodeBase64Str = GeneralUtility.calculateMD5ByString(originData);
1014 if (false == encodeBase64Str.equals(origMd5)) {
1015 log.debug("The calculated md5 is different then the received one");
1016 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_MD5));
1019 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create) {
1020 log.debug("Missing md5 header during artifact create");
1021 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_MD5));
1024 if (payload != null && payload.length != 0) {
1025 log.debug("Cannot have payload while md5 header is missing");
1026 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1029 return Either.left(true);
1032 private Either<ArtifactDefinition, ResponseFormat> validateInput(String componentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, String artifactId, User user, String interfaceName, String operationName,
1033 ComponentTypeEnum componentType, Component parentComponent, boolean inTransaction) {
1035 Either<ArtifactDefinition, ResponseFormat> artifactById = findArtifactOnParentComponent(parentComponent, componentType, componentId, operation, artifactId);
1036 if (artifactById.isRight()) {
1037 return Either.right(artifactById.right().value());
1039 ArtifactDefinition currentArtifactInfo = artifactById.left().value();
1041 ignoreUnupdateableFieldsInUpdate(operation, artifactInfo, currentArtifactInfo);
1042 Either<Boolean, ResponseFormat> validateInformationalArtifactRes = validateInformationalArtifact(artifactInfo, parentComponent);
1043 if (validateInformationalArtifactRes.isRight()) {
1044 return Either.right(validateInformationalArtifactRes.right().value());
1046 Either<Boolean, ResponseFormat> validateAndSetArtifactname = validateAndSetArtifactname(artifactInfo);
1047 if (validateAndSetArtifactname.isRight()) {
1048 return Either.right(validateAndSetArtifactname.right().value());
1050 if (operationName != null && interfaceName != null) {
1051 operationName = operationName.toLowerCase();
1052 interfaceName = interfaceName.toLowerCase();
1054 Either<ActionStatus, ResponseFormat> logicalNameStatus = handleArtifactLabel(componentId, parentComponent, operation, artifactId, artifactInfo, interfaceName, operationName, currentArtifactInfo, componentType);
1055 if (logicalNameStatus.isRight()) {
1056 return Either.right(logicalNameStatus.right().value());
1058 // This is a patch to block possibility of updating service api fields
1059 // through other artifacts flow
1061 if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.Create) {
1062 checkAndSetUnUpdatableFields(user, artifactInfo, currentArtifactInfo, (operationName != null ? ArtifactGroupTypeEnum.LIFE_CYCLE : ArtifactGroupTypeEnum.INFORMATIONAL));
1064 checkCreateFields(user, artifactInfo, (operationName != null ? ArtifactGroupTypeEnum.LIFE_CYCLE : ArtifactGroupTypeEnum.INFORMATIONAL));
1067 composeArtifactId(componentId, artifactId, artifactInfo, interfaceName, operationName);
1068 if (currentArtifactInfo != null) {
1069 artifactInfo.setMandatory(currentArtifactInfo.getMandatory());
1072 // artifactGroupType is not allowed to be updated
1073 if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.Create) {
1074 Either<ArtifactDefinition, ResponseFormat> validateGroupType = validateOrSetArtifactGroupType(artifactInfo, currentArtifactInfo);
1075 if (validateGroupType.isRight()) {
1076 return Either.right(validateGroupType.right().value());
1080 NodeTypeEnum parentType = convertParentType(componentType);
1083 boolean isCreate = operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create;
1085 if (isDeploymentArtifact(artifactInfo)) {
1086 Either<Boolean, ResponseFormat> deploymentValidationResult = validateDeploymentArtifact(parentComponent, componentId, user.getUserId(), isCreate, artifactInfo, currentArtifactInfo, parentType);
1087 if (deploymentValidationResult.isRight()) {
1088 return Either.right(deploymentValidationResult.right().value());
1091 artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
1094 * if (informationDeployedArtifactsBusinessLogic. isInformationDeployedArtifact(artifactInfo)) { Either<Boolean, ResponseFormat> validationResult = informationDeployedArtifactsBusinessLogic.validateArtifact( isCreate, artifactInfo,
1095 * parentComponent, parentType); if (validationResult.isRight()) { return Either.right(validationResult.right().value()); } }
1099 Either<Boolean, ResponseFormat> descriptionResult = validateAndCleanDescription(artifactInfo);
1100 if (descriptionResult.isRight()) {
1101 return Either.right(descriptionResult.right().value());
1104 if (currentArtifactInfo != null && currentArtifactInfo.getArtifactGroupType().equals(ArtifactGroupTypeEnum.SERVICE_API)) {
1105 Either<ActionStatus, ResponseFormat> validateServiceApiType = validateArtifactType(user.getUserId(), artifactInfo, parentType);
1106 if (validateServiceApiType.isRight()) {
1107 return Either.right(validateServiceApiType.right().value());
1109 // Change of type is not allowed and should be ignored
1111 artifactInfo.setArtifactType(ARTIFACT_TYPE_OTHER);
1113 Either<Boolean, ResponseFormat> validateUrl = validateAndServiceApiUrl(artifactInfo);
1114 if (validateUrl.isRight()) {
1115 return Either.right(validateUrl.right().value());
1118 Either<Boolean, ResponseFormat> validateUpdate = validateFirstUpdateHasPayload(artifactInfo, currentArtifactInfo);
1119 if (validateUpdate.isRight()) {
1120 log.debug("serviceApi first update cnnot be without payload.");
1121 return Either.right(validateUpdate.right().value());
1124 Either<ActionStatus, ResponseFormat> validateArtifactType = validateArtifactType(user.getUserId(), artifactInfo, parentType);
1125 if (validateArtifactType.isRight()) {
1126 return Either.right(validateArtifactType.right().value());
1128 if (artifactInfo.getApiUrl() != null) {
1129 artifactInfo.setApiUrl(null);
1130 log.error("Artifact URL cannot be set through this API - ignoring");
1133 if (artifactInfo.getServiceApi() != null) {
1134 if (artifactInfo.getServiceApi()) {
1135 artifactInfo.setServiceApi(false);
1136 log.error("Artifact service API flag cannot be changed - ignoring");
1141 return Either.left(artifactInfo);
1144 private void ignoreUnupdateableFieldsInUpdate(ArtifactOperationInfo operation, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifactInfo) {
1145 if(operation.getArtifactOperationEnum().equals(ArtifactOperationEnum.Update)){
1146 artifactInfo.setArtifactType(currentArtifactInfo.getArtifactType());
1147 artifactInfo.setArtifactGroupType(currentArtifactInfo.getArtifactGroupType());
1148 artifactInfo.setArtifactLabel(currentArtifactInfo.getArtifactLabel());
1152 private Either<ArtifactDefinition, ResponseFormat> findArtifactOnParentComponent(Component parentComponent, ComponentTypeEnum componentType, String parentId, ArtifactOperationInfo operation, String artifactId) {
1154 Either<ArtifactDefinition, ResponseFormat> result = null;
1155 ArtifactDefinition foundArtifact = null;
1156 if (StringUtils.isNotEmpty(artifactId)) {
1157 foundArtifact = findArtifact(parentComponent, componentType, parentId, artifactId);
1159 if (foundArtifact != null && operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create) {
1160 log.debug("Artifact {} already exist", artifactId);
1161 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, foundArtifact.getArtifactLabel()));
1163 if (foundArtifact == null && operation.getArtifactOperationEnum() != ArtifactOperationEnum.Create) {
1164 log.debug("The artifact {} was not found on parent {}. ", artifactId, parentId);
1165 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ""));
1167 if (result == null) {
1168 result = Either.left(foundArtifact);
1173 private ArtifactDefinition findArtifact(Component parentComponent, ComponentTypeEnum componentType, String parentId, String artifactId) {
1174 ArtifactDefinition foundArtifact;
1175 if (parentComponent.getUniqueId().equals(parentId)) {
1176 foundArtifact = artifactsResolver.findArtifactOnComponent(parentComponent, componentType, artifactId);
1178 ComponentInstance instance = findComponentInstance(parentId, parentComponent);
1179 foundArtifact = artifactsResolver.findArtifactOnComponentInstance(instance, artifactId);
1181 return foundArtifact;
1184 private Either<Boolean, ResponseFormat> validateInformationalArtifact(ArtifactDefinition artifactInfo, Component parentComponent) {
1185 ComponentTypeEnum parentComponentType = parentComponent.getComponentType();
1186 ArtifactGroupTypeEnum groupType = artifactInfo.getArtifactGroupType();
1187 Either<Boolean, ResponseFormat> validationResult = Either.left(true);
1188 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
1189 if (artifactType == null) {
1190 validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType()));
1191 } else if (parentComponentType == ComponentTypeEnum.RESOURCE && groupType == ArtifactGroupTypeEnum.INFORMATIONAL) {
1192 String artifactTypeName = artifactType.getType();
1193 ResourceTypeEnum parentResourceType = ((Resource) parentComponent).getResourceType();
1194 Map<String, ArtifactTypeConfig> resourceInformationalArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceInformationalArtifacts();
1195 Set<String> validArtifactTypes = resourceInformationalArtifacts.keySet();
1196 if (!validArtifactTypes.contains(artifactTypeName)) {
1197 validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactTypeName));
1199 List<String> validResourceType = resourceInformationalArtifacts.get(artifactTypeName).getValidForResourceTypes();
1200 if (!validResourceType.contains(parentResourceType.name())) {
1201 validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactTypeName));
1205 return validationResult;
1208 private NodeTypeEnum convertParentType(ComponentTypeEnum componentType) {
1209 if (componentType.equals(ComponentTypeEnum.RESOURCE)) {
1210 return NodeTypeEnum.Resource;
1211 } else if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) {
1212 return NodeTypeEnum.ResourceInstance;
1214 return NodeTypeEnum.Service;
1218 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete(String parentId, String artifactId, User user, AuditingActionEnum auditingAction, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent,
1219 String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
1221 NodeTypeEnum parentType = convertParentType(componentType);
1222 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
1223 Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> getArtifactRes = null;
1224 ArtifactDefinition foundArtifact = null;
1225 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
1226 Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getContainerRes = null;
1227 org.openecomp.sdc.be.model.Component fetchedContainerComponent = null;
1228 boolean isDuplicated = false;
1230 Either<Boolean, StorageOperationStatus> needCloneRes = null;
1233 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Delete Artifact - lock resource: ");
1234 if (lockComponent.isRight()) {
1235 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right().value(), componentType, null);
1236 resultOp = Either.right(lockComponent.right().value());
1239 if (resultOp == null) {
1240 log.debug("Going to fetch the container component {}. ", parent.getUniqueId());
1241 getContainerRes = toscaOperationFacade.getToscaElement(parent.getUniqueId());
1242 if (getContainerRes.isRight()) {
1243 log.debug("Failed to fetch the container component {}. ", parentId);
1244 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(getContainerRes.right().value()), artifactId);
1245 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1246 resultOp = Either.right(responseFormat);
1249 if (resultOp == null) {
1250 fetchedContainerComponent = getContainerRes.left().value();
1251 log.debug("Going to find the artifact {} on the component {}", artifactId, fetchedContainerComponent.getUniqueId());
1252 getArtifactRes = findArtifact(artifactId, fetchedContainerComponent, parentId, componentType);
1253 if (getArtifactRes.isRight()) {
1254 log.debug("Failed to find the artifact {} belonging to {} on the component {}", artifactId, parentId, fetchedContainerComponent.getUniqueId());
1255 responseFormat = componentsUtils.getResponseFormatByArtifactId(getArtifactRes.right().value(), artifactId);
1256 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1257 resultOp = Either.right(responseFormat);
1259 foundArtifact = getArtifactRes.left().value().getLeft();
1260 esId = foundArtifact.getEsId();
1263 if (resultOp == null && StringUtils.isNotEmpty(esId)) {
1264 needCloneRes = artifactToscaOperation.isCloneNeeded(parent.getUniqueId(), foundArtifact, convertParentType(parent.getComponentType()));
1265 if (needCloneRes.isRight()) {
1266 log.debug("Failed to delete or update the artifact {}. Parent uniqueId is {}", artifactId, parentId);
1267 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(needCloneRes.right().value()), foundArtifact.getArtifactDisplayName());
1268 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1269 resultOp = Either.right(responseFormat);
1272 if (resultOp == null) {
1273 Either<ArtifactDataDefinition, StorageOperationStatus> updatedArtifactRes = deleteOrUpdateArtifactOnGraph(parent, parentId, artifactId, parentType, foundArtifact, needCloneRes.left().value());
1274 if (updatedArtifactRes.isRight()) {
1275 log.debug("Failed to delete or update the artifact {}. Parent uniqueId is {}", artifactId, parentId);
1276 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updatedArtifactRes.right().value()), foundArtifact.getArtifactDisplayName());
1277 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1278 resultOp = Either.right(responseFormat);
1280 isDuplicated = updatedArtifactRes.left().value().getDuplicated();
1284 if (resultOp == null && (!needCloneRes.left().value() && !isDuplicated)) {
1285 log.debug("Going to delete the artifact {} from the database. ", artifactId);
1286 CassandraOperationStatus cassandraStatus = artifactCassandraDao.deleteArtifact(esId);
1287 if (cassandraStatus != CassandraOperationStatus.OK) {
1288 log.debug("Failed to delete the artifact {} from the database. ", artifactId);
1289 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(convertToStorageOperationStatus(cassandraStatus)), foundArtifact.getArtifactDisplayName());
1290 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1291 resultOp = Either.right(responseFormat);
1294 if (resultOp == null && componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1296 List<GroupInstance> updatedGroupInstances = getUpdatedGroupInstances(artifactId, foundArtifact, getArtifactRes.left().value().getRight().getGroupInstances());
1297 if (CollectionUtils.isNotEmpty(updatedGroupInstances)) {
1298 Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(fetchedContainerComponent, componentType, parentId, updatedGroupInstances);
1299 if (status.isRight()) {
1300 log.debug("Failed to update groups of the component {}. ", fetchedContainerComponent.getUniqueId());
1301 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status.right().value()), foundArtifact.getArtifactDisplayName());
1302 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1303 resultOp = Either.right(responseFormat);
1307 if (resultOp == null && componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1308 StorageOperationStatus status = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentType);
1309 if (status != StorageOperationStatus.OK) {
1310 log.debug("Failed to generate new customization UUID for the component instance {}. ", parentId);
1311 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status), foundArtifact.getArtifactDisplayName());
1312 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1313 resultOp = Either.right(responseFormat);
1316 if (resultOp == null && componentType != ComponentTypeEnum.RESOURCE_INSTANCE) {
1317 List<GroupDataDefinition> updatedGroups = getUpdatedGroups(artifactId, foundArtifact, fetchedContainerComponent.getGroups());
1318 if (CollectionUtils.isNotEmpty(updatedGroups)) {
1319 Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(fetchedContainerComponent, componentType, updatedGroups);
1320 if (status.isRight()) {
1321 log.debug("Failed to update groups of the component {}. ", fetchedContainerComponent.getUniqueId());
1322 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status.right().value()), foundArtifact.getArtifactDisplayName());
1323 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1324 resultOp = Either.right(responseFormat);
1328 if (resultOp == null) {
1329 resultOp = Either.left(Either.left(foundArtifact));
1330 handleAuditing(auditingAction, parent, parentId, user, foundArtifact, null, artifactId, responseFormat, componentType, null);
1335 unlockComponent(resultOp, parent, inTransaction);
1340 private List<GroupDataDefinition> getUpdatedGroups(String artifactId, ArtifactDefinition foundArtifact, List<GroupDefinition> groups) {
1341 List<GroupDataDefinition> updatedGroups = new ArrayList<>();
1342 boolean isUpdated = false;
1343 if (groups != null) {
1344 for (GroupDefinition group : groups) {
1346 if (CollectionUtils.isNotEmpty(group.getArtifacts()) && group.getArtifacts().contains(artifactId)) {
1347 group.getArtifacts().remove(artifactId);
1350 if (CollectionUtils.isNotEmpty(group.getArtifactsUuid()) && group.getArtifactsUuid().contains(foundArtifact.getArtifactUUID())) {
1351 group.getArtifactsUuid().remove(foundArtifact.getArtifactUUID());
1355 updatedGroups.add(group);
1359 return updatedGroups;
1362 private List<GroupInstance> getUpdatedGroupInstances(String artifactId, ArtifactDefinition foundArtifact, List<GroupInstance> groupInstances) {
1363 List<GroupInstance> updatedGroupInstances = new ArrayList<>();
1364 if (CollectionUtils.isNotEmpty(groupInstances)) {
1365 boolean isUpdated = false;
1366 for (GroupInstance groupInstance : groupInstances) {
1368 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifacts()) && groupInstance.getGroupInstanceArtifacts().contains(artifactId)) {
1369 groupInstance.getGroupInstanceArtifacts().remove(artifactId);
1372 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifactsUuid()) && groupInstance.getGroupInstanceArtifactsUuid().contains(foundArtifact.getArtifactUUID())) {
1373 groupInstance.getGroupInstanceArtifactsUuid().remove(foundArtifact.getArtifactUUID());
1377 updatedGroupInstances.add(groupInstance);
1381 return updatedGroupInstances;
1384 private Either<ArtifactDataDefinition, StorageOperationStatus> deleteOrUpdateArtifactOnGraph(Component component, String parentId, String artifactId, NodeTypeEnum parentType, ArtifactDefinition foundArtifact, Boolean cloneIsNeeded) {
1386 Either<ArtifactDataDefinition, StorageOperationStatus> result;
1387 boolean isMandatory = foundArtifact.getMandatory() || foundArtifact.getServiceApi();
1388 String componentId = component.getUniqueId();
1389 String instanceId = componentId.equals(parentId) ? null : parentId;
1391 log.debug("Going to update mandatory artifact {} from the component {}", artifactId, parentId);
1392 resetMandatoryArtifactFields(foundArtifact);
1393 result = artifactToscaOperation.updateArtifactOnGraph(componentId, foundArtifact, parentType, artifactId, instanceId, true);
1394 } else if (cloneIsNeeded) {
1395 log.debug("Going to clone artifacts and to delete the artifact {} from the component {}", artifactId, parentId);
1396 result = artifactToscaOperation.deleteArtifactWithClonnigOnGraph(componentId, foundArtifact, parentType, instanceId, false);
1398 log.debug("Going to delete the artifact {} from the component {}", artifactId, parentId);
1399 result = artifactToscaOperation.removeArtifactOnGraph(foundArtifact, componentId, instanceId, parentType, false);
1404 private Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> findArtifact(String artifactId, Component fetchedContainerComponent, String parentId, ComponentTypeEnum componentType) {
1406 Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> result = null;
1407 Map<String, ArtifactDefinition> artifacts = new HashMap<>();
1408 ComponentInstance foundInstance = null;
1409 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE && StringUtils.isNotEmpty(parentId)) {
1410 Optional<ComponentInstance> componentInstanceOpt = fetchedContainerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(parentId)).findFirst();
1411 if (!componentInstanceOpt.isPresent()) {
1412 result = Either.right(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER);
1414 foundInstance = componentInstanceOpt.get();
1415 fetchArtifactsFromInstance(artifactId, artifacts, foundInstance);
1418 fetchArtifactsFromComponent(artifactId, fetchedContainerComponent, artifacts);
1420 if (result == null) {
1421 if (artifacts.containsKey(artifactId)) {
1422 result = Either.left(new ImmutablePair<>(artifacts.get(artifactId), foundInstance));
1424 result = Either.right(ActionStatus.ARTIFACT_NOT_FOUND);
1430 private void fetchArtifactsFromComponent(String artifactId, Component component, Map<String, ArtifactDefinition> artifacts) {
1431 Map<String, ArtifactDefinition> currArtifacts;
1432 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getDeploymentArtifacts())) {
1433 currArtifacts = component.getDeploymentArtifacts().values().stream().collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1434 if (MapUtils.isNotEmpty(currArtifacts)) {
1435 artifacts.putAll(currArtifacts);
1438 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getArtifacts())) {
1439 currArtifacts = component.getArtifacts().values().stream().collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1440 if (MapUtils.isNotEmpty(currArtifacts)) {
1441 artifacts.putAll(currArtifacts);
1444 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getArtifacts())) {
1445 currArtifacts = component.getToscaArtifacts().values().stream().collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1446 if (MapUtils.isNotEmpty(currArtifacts)) {
1447 artifacts.putAll(currArtifacts);
1452 private void fetchArtifactsFromInstance(String artifactId, Map<String, ArtifactDefinition> artifacts, ComponentInstance instance) {
1453 Map<String, ArtifactDefinition> currArtifacts;
1454 if (MapUtils.isNotEmpty(instance.getDeploymentArtifacts())) {
1455 currArtifacts = instance.getDeploymentArtifacts().values().stream().collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1456 if (MapUtils.isNotEmpty(currArtifacts)) {
1457 artifacts.putAll(currArtifacts);
1460 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(instance.getArtifacts())) {
1461 currArtifacts = instance.getArtifacts().values().stream().collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1462 if (MapUtils.isNotEmpty(currArtifacts)) {
1463 artifacts.putAll(currArtifacts);
1468 private StorageOperationStatus convertToStorageOperationStatus(CassandraOperationStatus cassandraStatus) {
1469 StorageOperationStatus result;
1470 switch (cassandraStatus) {
1472 result = StorageOperationStatus.OK;
1475 result = StorageOperationStatus.NOT_FOUND;
1477 case CLUSTER_NOT_CONNECTED:
1478 case KEYSPACE_NOT_CONNECTED:
1479 result = StorageOperationStatus.CONNECTION_FAILURE;
1482 result = StorageOperationStatus.GENERAL_ERROR;
1488 private void resetMandatoryArtifactFields(ArtifactDefinition fetchedArtifact) {
1489 if (fetchedArtifact != null) {
1490 log.debug("Going to reset mandatory artifact {} fields. ", fetchedArtifact.getUniqueId());
1491 fetchedArtifact.setEsId(null);
1492 fetchedArtifact.setArtifactName(null);
1493 fetchedArtifact.setDescription(null);
1494 fetchedArtifact.setApiUrl(null);
1495 fetchedArtifact.setArtifactChecksum(null);
1496 nodeTemplateOperation.setDefaultArtifactTimeout(fetchedArtifact.getArtifactGroupType(), fetchedArtifact);
1497 fetchedArtifact.setArtifactUUID(null);
1498 long time = System.currentTimeMillis();
1499 fetchedArtifact.setPayloadUpdateDate(time);
1500 fetchedArtifact.setHeatParameters(null);
1501 fetchedArtifact.setHeatParamsUpdateDate(null);
1505 private StorageOperationStatus generateCustomizationUUIDOnInstance(String componentId, String instanceId, ComponentTypeEnum componentType) {
1506 StorageOperationStatus error = StorageOperationStatus.OK;
1507 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1508 log.debug("Need to re-generate customization UUID for instance {}", instanceId);
1509 error = toscaOperationFacade.generateCustomizationUUIDOnInstance(componentId, instanceId);
1514 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDownload(String componentId, String artifactId, User user, AuditingActionEnum auditingAction, ComponentTypeEnum componentType,
1515 org.openecomp.sdc.be.model.Component parent, boolean shouldLock, boolean inTransaction) {
1516 Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(componentId, artifactId, componentType, parent.getUniqueId());
1517 if (artifactById.isRight()) {
1518 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(artifactById.right().value());
1519 log.debug("Error when getting artifact info by id{}, error: {}", artifactId, actionStatus.name());
1520 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(actionStatus, "");
1521 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
1522 return Either.right(responseFormat);
1524 ArtifactDefinition artifactDefinition = artifactById.left().value();
1525 if (artifactDefinition == null) {
1526 log.debug("Empty artifact definition returned from DB by artifact id {}", artifactId);
1527 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, "");
1528 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
1529 return Either.right(responseFormat);
1531 Either<ArtifactDefinition, Operation> insideEither = Either.left(artifactDefinition);
1532 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
1533 handleAuditing(auditingAction, parent, componentId, user, artifactDefinition, null, artifactId, responseFormat, componentType, null);
1534 return Either.left(insideEither);
1537 private Either<ArtifactDefinition, ResponseFormat> fetchCurrentArtifact(String parentId, ArtifactOperationInfo operation, String artifactId) {
1538 Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(parentId, artifactId);
1539 if (!(operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create) && artifactById.isRight()) {
1540 // in case of update artifact must be
1541 BeEcompErrorManager.getInstance().logBeArtifactMissingError("Artifact Update / Upload", artifactId);
1542 log.debug("Failed to fetch artifact {}. error: {}", artifactId, artifactById.right().value());
1543 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(artifactById.right().value()), artifactId));
1545 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create && artifactById.isLeft()) {
1546 log.debug("Artifact {} already exist", artifactId);
1547 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactById.left().value().getArtifactLabel()));
1549 ArtifactDefinition currentArtifactInfo = null;
1550 if (artifactById.isLeft()) {
1551 // get previous value
1552 currentArtifactInfo = artifactById.left().value();
1554 return Either.left(currentArtifactInfo);
1557 private Either<ActionStatus, ResponseFormat> handleArtifactLabel(String componentId, Component parentComponent, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, String interfaceName, String operationName,
1558 ArtifactDefinition currentArtifactInfo, ComponentTypeEnum componentType) {
1560 String artifactLabel = artifactInfo.getArtifactLabel();
1561 if (operationName == null && (artifactInfo.getArtifactLabel() == null || artifactInfo.getArtifactLabel().isEmpty())) {
1562 BeEcompErrorManager.getInstance().logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel");
1563 log.debug("missing artifact logical name for component {}", componentId);
1564 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_LABEL));
1566 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create && !artifactInfo.getMandatory()) {
1568 if (operationName != null) {
1569 if (artifactInfo.getArtifactLabel() != null && !operationName.equals(artifactInfo.getArtifactLabel())) {
1570 log.debug("artifact label cannot be set {}", artifactLabel);
1571 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_LOGICAL_NAME_CANNOT_BE_CHANGED));
1573 artifactLabel = operationName;
1576 String displayName = artifactInfo.getArtifactDisplayName();
1577 if (displayName == null || displayName.isEmpty())
1578 displayName = artifactLabel;
1579 displayName = ValidationUtils.cleanArtifactDisplayName(displayName);
1580 // if (!ValidationUtils.validateArtifactDisplayName(displayName)) {
1581 // log.debug("Invalid format form Artifact displayName : {}", displayName);
1582 // return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1584 artifactInfo.setArtifactDisplayName(displayName);
1586 if (!ValidationUtils.validateArtifactLabel(artifactLabel)) {
1587 log.debug("Invalid format form Artifact label : {}", artifactLabel);
1588 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1590 artifactLabel = ValidationUtils.normalizeArtifactLabel(artifactLabel);
1592 if (artifactLabel.isEmpty()) {
1593 log.debug("missing normalized artifact logical name for component {}", componentId);
1594 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_LABEL));
1597 if (!ValidationUtils.validateArtifactLabelLength(artifactLabel)) {
1598 log.debug("Invalid lenght form Artifact label : {}", artifactLabel);
1599 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_LABEL, String.valueOf(ValidationUtils.ARTIFACT_LABEL_LENGTH)));
1601 if (!validateLabelUniqueness(componentId, parentComponent, artifactLabel, componentType)) {
1602 log.debug("Non unique Artifact label : {}", artifactLabel);
1603 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactLabel));
1606 artifactInfo.setArtifactLabel(artifactLabel);
1608 return Either.left(ActionStatus.OK);
1611 private boolean validateLabelUniqueness(String componentId, Component parentComponent, String artifactLabel, ComponentTypeEnum componentType) {
1612 boolean isUnique = true;
1613 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifacts;
1614 if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) {
1615 artifacts = artifactToscaOperation.getAllInstanceArtifacts(parentComponent.getUniqueId(), componentId);
1617 artifacts = artifactToscaOperation.getArtifacts(componentId);
1620 if (artifacts.isLeft()) {
1621 for (String label : artifacts.left().value().keySet()) {
1622 if (label.equals(artifactLabel)) {
1628 if (componentType.equals(ComponentTypeEnum.RESOURCE)) {
1629 Either<Map<String, InterfaceDefinition>, StorageOperationStatus> allInterfacesOfResource = interfaceLifecycleOperation.getAllInterfacesOfResource(componentId, true, true);
1630 if (allInterfacesOfResource.isLeft()) {
1631 for (InterfaceDefinition interace : allInterfacesOfResource.left().value().values()) {
1632 for (Operation operation : interace.getOperationsMap().values()) {
1633 if (operation.getImplementation() != null && operation.getImplementation().getArtifactLabel().equals(artifactLabel)) {
1644 // ***************************************************************
1646 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> createArtifact(org.openecomp.sdc.be.model.Component parent, String parentId, ArtifactDefinition artifactInfo, byte[] decodedPayload, User user,
1647 ComponentTypeEnum componentTypeEnum, AuditingActionEnum auditingActionEnum, String interfaceType, String operationName) {
1649 ESArtifactData artifactData = createEsArtifactData(artifactInfo, decodedPayload);
1650 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
1651 Either<ArtifactDefinition, Operation> insideEither = null;
1652 ComponentInstance foundInstance = findComponentInstance(parentId, parent);
1653 String instanceId = null;
1654 String instanceName = null;
1655 if (foundInstance != null) {
1656 instanceId = foundInstance.getUniqueId();
1657 instanceName = foundInstance.getName();
1659 if (artifactData == null) {
1660 BeEcompErrorManager.getInstance().logBeDaoSystemError("Upload Artifact");
1661 log.debug("Failed to create artifact object for ES.");
1662 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
1663 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, null);
1664 resultOp = Either.right(responseFormat);
1668 // set on graph object id of artifact in ES!
1669 artifactInfo.setEsId(artifactData.getId());
1671 boolean isLeft = false;
1672 String artifactUniqueId = null;
1673 StorageOperationStatus error = null;
1674 if (interfaceType != null && operationName != null) {
1675 // lifecycle artifact
1676 Operation operation = convertToOperation(artifactInfo, operationName);
1678 Either<Operation, StorageOperationStatus> result = interfaceLifecycleOperation.updateInterfaceOperation(parentId, interfaceType, operationName, operation);
1680 isLeft = result.isLeft();
1682 artifactUniqueId = result.left().value().getImplementation().getUniqueId();
1683 result.left().value().getImplementation();
1685 insideEither = Either.right(result.left().value());
1686 resultOp = Either.left(insideEither);
1688 error = result.right().value();
1691 // information/deployment/api aritfacts
1692 log.trace("Try to create entry on graph");
1693 NodeTypeEnum nodeType = convertParentType(componentTypeEnum);
1694 Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.addArifactToComponent(artifactInfo, parent.getUniqueId(), nodeType, true, instanceId);
1696 isLeft = result.isLeft();
1698 artifactUniqueId = result.left().value().getUniqueId();
1699 result.left().value();
1701 insideEither = Either.left(result.left().value());
1702 resultOp = Either.left(insideEither);
1704 error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentTypeEnum);
1705 if (error != StorageOperationStatus.OK) {
1710 error = result.right().value();
1714 boolean res = saveArtifacts(artifactData, parentId, false);
1715 // String uniqueId = artifactDefinition.getUniqueId();
1718 log.debug("Artifact saved into ES - {}", artifactUniqueId);
1720 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
1721 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, artifactUniqueId, artifactUniqueId, responseFormat, componentTypeEnum, instanceName);
1724 BeEcompErrorManager.getInstance().logBeDaoSystemError("Upload Artifact");
1725 log.debug("Failed to save the artifact.");
1726 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
1727 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, artifactUniqueId, responseFormat, componentTypeEnum, instanceName);
1729 resultOp = Either.right(responseFormat);
1733 log.debug("Failed to create entry on graph for artifact {}", artifactInfo.getArtifactName());
1734 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(error), artifactInfo.getArtifactDisplayName());
1735 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, instanceName);
1736 resultOp = Either.right(responseFormat);
1742 private ComponentInstance findComponentInstance(String componentInstanceId, Component containerComponent) {
1743 ComponentInstance foundInstance = null;
1744 if (CollectionUtils.isNotEmpty(containerComponent.getComponentInstances())) {
1745 foundInstance = containerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(componentInstanceId)).findFirst().orElse(null);
1747 return foundInstance;
1750 private Either<Boolean, ResponseFormat> validateDeploymentArtifact(Component parentComponent, String parentId, String userId, boolean isCreate, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, NodeTypeEnum parentType) {
1752 Either<Boolean, ResponseFormat> result = Either.left(true);
1753 Wrapper<ResponseFormat> responseWrapper = new Wrapper<ResponseFormat>();
1755 validateArtifactTypeExists(responseWrapper, artifactInfo);
1757 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
1759 Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts = fillDeploymentArtifactTypeConf(parentType);
1761 if (responseWrapper.isEmpty()) {
1762 validateDeploymentArtifactConf(artifactInfo, responseWrapper, artifactType, resourceDeploymentArtifacts);
1765 if (responseWrapper.isEmpty()) {
1766 // Common code for all types
1767 // not allowed to change artifactType
1769 Either<Boolean, ResponseFormat> validateServiceApiType = validateArtifactTypeNotChanged(artifactInfo, currentArtifact);
1770 if (validateServiceApiType.isRight()) {
1771 responseWrapper.setInnerElement(validateServiceApiType.right().value());
1775 if (responseWrapper.isEmpty()) {
1776 if (parentType.equals(NodeTypeEnum.Resource)) {
1777 // if (parentComponent instanceof Resource) {
1778 Resource resource = (Resource) parentComponent;
1779 ResourceTypeEnum resourceType = resource.getResourceType();
1780 ArtifactTypeConfig config = resourceDeploymentArtifacts.get(artifactType.getType());
1781 if (config == null) {
1782 responseWrapper.setInnerElement(ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType()));
1784 List<String> myList = config.getValidForResourceTypes();
1785 Either<Boolean, ResponseFormat> either = validateResourceType(resourceType, artifactInfo, myList);
1786 if (either.isRight()) {
1787 responseWrapper.setInnerElement(either.right().value());
1792 if (responseWrapper.isEmpty()) {
1793 validateFileExtension(responseWrapper, () -> getDeploymentArtifactTypeConfig(parentType, artifactType), artifactInfo, parentType, artifactType);
1796 if (responseWrapper.isEmpty() && !NodeTypeEnum.ResourceInstance.equals(parentType)) {
1797 String artifactName = artifactInfo.getArtifactName();
1798 if (isCreate || !artifactName.equalsIgnoreCase(currentArtifact.getArtifactName())) {
1799 validateSingleDeploymentArtifactName(responseWrapper, artifactName, parentComponent, parentType);
1803 if (responseWrapper.isEmpty()) {
1804 switch (artifactType) {
1808 result = validateHeatDeploymentArtifact(parentComponent, userId, isCreate, artifactInfo, currentArtifact, parentType);
1812 result = validateHeatEnvDeploymentArtifact(parentComponent, parentId, userId, isCreate, artifactInfo, parentType);
1813 artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
1816 case DCAE_INVENTORY_TOSCA:
1817 case DCAE_INVENTORY_JSON:
1818 case DCAE_INVENTORY_POLICY:
1819 // Validation is done in handle payload.
1820 case DCAE_INVENTORY_DOC:
1821 case DCAE_INVENTORY_BLUEPRINT:
1822 case DCAE_INVENTORY_EVENT:
1823 // No specific validation
1825 artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
1831 if (!responseWrapper.isEmpty()) {
1832 result = Either.right(responseWrapper.getInnerElement());
1837 private void validateDeploymentArtifactConf(ArtifactDefinition artifactInfo, Wrapper<ResponseFormat> responseWrapper, ArtifactTypeEnum artifactType, Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts) {
1838 if ((resourceDeploymentArtifacts == null) || !resourceDeploymentArtifacts.containsKey(artifactType.name())) {
1839 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType());
1840 responseWrapper.setInnerElement(responseFormat);
1841 log.debug("Artifact Type: {} Not found !", artifactInfo.getArtifactType());
1845 private Map<String, ArtifactTypeConfig> fillDeploymentArtifactTypeConf(NodeTypeEnum parentType) {
1846 Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts = null;
1847 if (parentType.equals(NodeTypeEnum.Resource)) {
1848 resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceDeploymentArtifacts();
1849 } else if (parentType.equals(NodeTypeEnum.ResourceInstance)) {
1850 resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceInstanceDeploymentArtifacts();
1852 resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getServiceDeploymentArtifacts();
1854 return resourceDeploymentArtifacts;
1857 public void validateArtifactTypeExists(Wrapper<ResponseFormat> responseWrapper, ArtifactDefinition artifactInfo) {
1858 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
1859 if (artifactType == null) {
1860 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType());
1861 responseWrapper.setInnerElement(responseFormat);
1862 log.debug("Artifact Type: {} Not found !", artifactInfo.getArtifactType());
1866 private ArtifactTypeConfig getDeploymentArtifactTypeConfig(NodeTypeEnum parentType, ArtifactTypeEnum artifactType) {
1867 ArtifactTypeConfig retConfig = null;
1868 String fileType = artifactType.getType();
1869 if (parentType.equals(NodeTypeEnum.Resource)) {
1870 retConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceDeploymentArtifacts().get(fileType);
1871 } else if (parentType.equals(NodeTypeEnum.Service)) {
1872 retConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getServiceDeploymentArtifacts().get(fileType);
1873 } else if (parentType.equals(NodeTypeEnum.ResourceInstance)) {
1874 retConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceInstanceDeploymentArtifacts().get(fileType);
1879 private Either<Boolean, ResponseFormat> extractHeatParameters(ArtifactDefinition artifactInfo) {
1880 // extract heat parameters
1881 if (artifactInfo.getPayloadData() != null) {
1882 String heatDecodedPayload = new String(Base64.decodeBase64(artifactInfo.getPayloadData()));
1883 Either<List<HeatParameterDefinition>, ResultStatusEnum> heatParameters = ImportUtils.getHeatParamsWithoutImplicitTypes(heatDecodedPayload, artifactInfo.getArtifactType());
1884 if (heatParameters.isRight() && (!heatParameters.right().value().equals(ResultStatusEnum.ELEMENT_NOT_FOUND))) {
1885 log.info("failed to parse heat parameters ");
1886 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactInfo.getArtifactType());
1887 return Either.right(responseFormat);
1888 } else if (heatParameters.isLeft() && heatParameters.left().value() != null) {
1889 artifactInfo.setListHeatParameters(heatParameters.left().value());
1892 return Either.left(true);
1897 public void validateFileExtension(Wrapper<ResponseFormat> responseWrapper, IDeploymentArtifactTypeConfigGetter deploymentConfigGetter, ArtifactDefinition artifactInfo, NodeTypeEnum parentType, ArtifactTypeEnum artifactType) {
1898 String fileType = artifactType.getType();
1899 List<String> acceptedTypes = null;
1900 ArtifactTypeConfig deploymentAcceptedTypes = deploymentConfigGetter.getDeploymentArtifactConfig();
1901 if (!parentType.equals(NodeTypeEnum.Resource) && !parentType.equals(NodeTypeEnum.Service) && !parentType.equals(NodeTypeEnum.ResourceInstance)) {
1902 log.debug("parent type of artifact can be either resource or service");
1903 responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
1907 if (deploymentAcceptedTypes == null) {
1908 log.debug("parent type of artifact can be either resource or service");
1909 responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType()));
1912 acceptedTypes = deploymentAcceptedTypes.getAcceptedTypes();
1915 * No need to check specific types. In case there are no acceptedTypes in configuration, then any type is accepted.
1917 * if ((!artifactType.equals(ArtifactTypeEnum.OTHER) && !artifactType.equals(ArtifactTypeEnum.HEAT_ARTIFACT )) && (acceptedTypes == null || acceptedTypes.isEmpty()) ) { log.debug( "No accepted types found for type {}, parent type {}",
1918 * fileType, parentType.getName()); String methodName = new Object() { }.getClass().getEnclosingMethod().getName(); String configEntryMissing = (parentType.equals(NodeTypeEnum.Resource)) ? "resourceDeploymentArtifacts:" + fileType :
1919 * "serviceDeploymentArtifacts:" + fileType; BeEcompErrorManager.getInstance().processEcompError(EcompErrorName. BeMissingConfigurationError, methodName, configEntryMissing); BeEcompErrorManager.getInstance().logBeMissingConfigurationError(
1920 * methodName, configEntryMissing); responseWrapper.setInnerElement(componentsUtils.getResponseFormat( ActionStatus.GENERAL_ERROR)); return; }
1923 String artifactName = artifactInfo.getArtifactName();
1924 String fileExtension = GeneralUtility.getFilenameExtension(artifactName);
1925 // Pavel - File extension validation is case-insensitive - Ella,
1927 if (acceptedTypes != null && !acceptedTypes.isEmpty() && !acceptedTypes.contains(fileExtension.toLowerCase())) {
1928 log.debug("File extension \"{}\" is not allowed for {} which is of type:{}", fileExtension, artifactName, fileType);
1929 responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.WRONG_ARTIFACT_FILE_EXTENSION, fileType));
1934 private Either<Boolean, ResponseFormat> validateHeatEnvDeploymentArtifact(Component parentComponent, String parentId, String userId, boolean isCreate, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) {
1936 Wrapper<ResponseFormat> errorWrapper = new Wrapper<ResponseFormat>();
1937 Wrapper<ArtifactDefinition> heatMDWrapper = new Wrapper<ArtifactDefinition>();
1938 Wrapper<byte[]> payloadWrapper = new Wrapper<>();
1940 if (errorWrapper.isEmpty()) {
1941 validateValidYaml(errorWrapper, artifactInfo);
1944 if (errorWrapper.isEmpty()) {
1945 // Validate Heat Exist
1946 validateHeatExist(parentComponent.getUniqueId(), parentId, errorWrapper, heatMDWrapper, artifactInfo, parentType, parentComponent.getComponentType());
1949 // if (errorWrapper.isEmpty() && isCreate) {
1950 // // Validate Only Single HeatEnv Artifact
1951 // validateSingleArtifactType(errorWrapper, ArtifactTypeEnum.HEAT_ENV, parentComponent, parentType, parentId);
1954 if (errorWrapper.isEmpty() && !heatMDWrapper.isEmpty()) {
1955 fillArtifactPayloadValidation(errorWrapper, payloadWrapper, heatMDWrapper.getInnerElement());
1958 if (errorWrapper.isEmpty() && !heatMDWrapper.isEmpty()) {
1959 validateEnvVsHeat(errorWrapper, artifactInfo, heatMDWrapper.getInnerElement(), payloadWrapper.getInnerElement());
1963 Either<Boolean, ResponseFormat> eitherResponse;
1964 if (errorWrapper.isEmpty()) {
1965 eitherResponse = Either.left(true);
1967 eitherResponse = Either.right(errorWrapper.getInnerElement());
1969 return eitherResponse;
1972 public void fillArtifactPayloadValidation(Wrapper<ResponseFormat> errorWrapper, Wrapper<byte[]> payloadWrapper, ArtifactDefinition artifactDefinition) {
1973 if (artifactDefinition.getPayloadData() == null || artifactDefinition.getPayloadData().length == 0) {
1974 Either<Boolean, ResponseFormat> fillArtifactPayload = fillArtifactPayload(payloadWrapper, artifactDefinition);
1975 if (fillArtifactPayload.isRight()) {
1976 errorWrapper.setInnerElement(fillArtifactPayload.right().value());
1977 log.debug("Error getting payload for artifact:{}", artifactDefinition.getArtifactName());
1980 payloadWrapper.setInnerElement(artifactDefinition.getPayloadData());
1984 public Either<Boolean, ResponseFormat> fillArtifactPayload(Wrapper<byte[]> payloadWrapper, ArtifactDefinition artifactMD) {
1985 Either<Boolean, ResponseFormat> result = Either.left(true);
1986 Either<ESArtifactData, CassandraOperationStatus> eitherArtifactData = artifactCassandraDao.getArtifact(artifactMD.getEsId());
1987 if (eitherArtifactData.isLeft()) {
1988 byte[] data = eitherArtifactData.left().value().getDataAsArray();
1989 data = Base64.encodeBase64(data);
1990 payloadWrapper.setInnerElement(data);
1992 StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(eitherArtifactData.right().value());
1993 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus));
1994 result = Either.right(responseFormat);
2000 @SuppressWarnings("unchecked")
2001 private void validateEnvVsHeat(Wrapper<ResponseFormat> errorWrapper, ArtifactDefinition envArtifact, ArtifactDefinition heatArtifact, byte[] heatPayloadData) {
2002 String envPayload = new String(Base64.decodeBase64(envArtifact.getPayloadData()));
2003 Map<String, Object> heatEnvToscaJson = (Map<String, Object>) new Yaml().load(envPayload);
2004 String heatDecodedPayload = new String(Base64.decodeBase64(heatPayloadData));
2005 Map<String, Object> heatToscaJson = (Map<String, Object>) new Yaml().load(heatDecodedPayload);
2007 Either<Map<String, Object>, ResultStatusEnum> eitherHeatEnvProperties = ImportUtils.findFirstToscaMapElement(heatEnvToscaJson, ToscaTagNamesEnum.PARAMETERS);
2008 Either<Map<String, Object>, ResultStatusEnum> eitherHeatProperties = ImportUtils.findFirstToscaMapElement(heatToscaJson, ToscaTagNamesEnum.PARAMETERS);
2009 if (eitherHeatEnvProperties.isRight()) {
2010 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.CORRUPTED_FORMAT, "Heat Env");
2011 errorWrapper.setInnerElement(responseFormat);
2012 log.debug("Invalid heat env format for file:{}", envArtifact.getArtifactName());
2013 } else if (eitherHeatProperties.isRight()) {
2014 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, envArtifact.getArtifactName(), heatArtifact.getArtifactName());
2015 errorWrapper.setInnerElement(responseFormat);
2016 log.debug("Validation of heat_env for artifact:{} vs heat artifact for artifact :{} failed", envArtifact.getArtifactName(), heatArtifact.getArtifactName());
2018 Set<String> heatPropertiesKeys = eitherHeatProperties.left().value().keySet();
2019 Set<String> heatEnvPropertiesKeys = eitherHeatEnvProperties.left().value().keySet();
2020 heatEnvPropertiesKeys.removeAll(heatPropertiesKeys);
2021 if (heatEnvPropertiesKeys.size() > 0) {
2022 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, envArtifact.getArtifactName(), heatArtifact.getArtifactName());
2023 errorWrapper.setInnerElement(responseFormat);
2028 private void validateValidYaml(Wrapper<ResponseFormat> errorWrapper, ArtifactDefinition artifactInfo) {
2029 YamlToObjectConverter yamlConvertor = new YamlToObjectConverter();
2030 boolean isYamlValid = yamlConvertor.isValidYamlEncoded64(artifactInfo.getPayloadData());
2032 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.INVALID_YAML, artifactInfo.getArtifactType());
2033 errorWrapper.setInnerElement(responseFormat);
2034 log.debug("Yaml is not valid for artifact : {}", artifactInfo.getArtifactName());
2038 @SuppressWarnings("restriction")
2039 public boolean isValidXml(byte[] xmlToParse) {
2040 XMLReader parser = new SAXParser();
2041 boolean isXmlValid = true;
2043 parser.parse(new InputSource(new ByteArrayInputStream(xmlToParse)));
2044 } catch (IOException | SAXException e) {
2045 log.debug("Xml is invalid : {}", e.getMessage(), e);
2051 public boolean isValidJson(byte[] jsonToParse) {
2052 String parsed = new String(jsonToParse);
2054 gson.fromJson(parsed, Object.class);
2055 } catch (Exception e) {
2056 log.debug("Json is invalid : {}", e.getMessage(), e);
2062 public void validateSingleArtifactType(Wrapper<ResponseFormat> errorWrapper, ArtifactTypeEnum allowedArtifactType, Component parentComponent, NodeTypeEnum parentType, String parentRiId) {
2063 boolean typeArtifactFound = false;
2064 // Iterator<ArtifactDefinition> parentDeploymentArtifactsItr =
2065 // (parentType == NodeTypeEnum.Resource) ?
2066 // informationDeployedArtifactsBusinessLogic.getAllDeployableArtifacts((Resource)
2067 // parentComponent).iterator()
2068 // : getDeploymentArtifacts(parentComponent, parentType).iterator();
2070 Iterator<ArtifactDefinition> parentDeploymentArtifactsItr = getDeploymentArtifacts(parentComponent, parentType, parentRiId).iterator();
2072 while (!typeArtifactFound && parentDeploymentArtifactsItr.hasNext()) {
2073 ArtifactTypeEnum foundArtifactType = ArtifactTypeEnum.findType(parentDeploymentArtifactsItr.next().getArtifactType());
2074 typeArtifactFound = (foundArtifactType == allowedArtifactType);
2076 if (typeArtifactFound) {
2077 String parentName = parentComponent.getName();
2078 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.DEPLOYMENT_ARTIFACT_OF_TYPE_ALREADY_EXISTS, parentType.name(), parentName, allowedArtifactType.getType(), allowedArtifactType.getType());
2080 errorWrapper.setInnerElement(responseFormat);
2081 log.debug("Can't upload artifact of type: {}, because another artifact of this type already exist.", allowedArtifactType.getType());
2086 public void validateSingleDeploymentArtifactName(Wrapper<ResponseFormat> errorWrapper, String artifactName, Component parentComponent, NodeTypeEnum parentType) {
2087 boolean artifactNameFound = false;
2088 // Iterator<ArtifactDefinition> parentDeploymentArtifactsItr =
2089 // (parentType == NodeTypeEnum.Resource) ?
2090 // informationDeployedArtifactsBusinessLogic.getAllDeployableArtifacts((Resource)
2091 // parentComponent).iterator()
2092 // : getDeploymentArtifacts(parentComponent, parentType).iterator();
2094 Iterator<ArtifactDefinition> parentDeploymentArtifactsItr = getDeploymentArtifacts(parentComponent, parentType, null).iterator();
2096 while (!artifactNameFound && parentDeploymentArtifactsItr.hasNext()) {
2097 artifactNameFound = (artifactName.equalsIgnoreCase(parentDeploymentArtifactsItr.next().getArtifactName()));
2099 if (artifactNameFound) {
2100 String parentName = parentComponent.getName();
2101 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.DEPLOYMENT_ARTIFACT_NAME_ALREADY_EXISTS, parentType.name(), parentName, artifactName);
2103 errorWrapper.setInnerElement(responseFormat);
2104 log.debug("Can't upload artifact: {}, because another artifact with this name already exist.", artifactName);
2109 private void validateHeatExist(String componentId, String parentRiId, Wrapper<ResponseFormat> errorWrapper, Wrapper<ArtifactDefinition> heatArtifactMDWrapper, ArtifactDefinition heatEnvArtifact, NodeTypeEnum parentType,
2110 ComponentTypeEnum componentType) {
2111 Either<ArtifactDefinition, StorageOperationStatus> res = artifactToscaOperation.getHeatArtifactByHeatEnvId(parentRiId, heatEnvArtifact, parentType, componentId, componentType);
2112 if (res.isRight()) {
2113 ResponseFormat responseFormat;
2114 if (res.right().value() == StorageOperationStatus.NOT_FOUND) {
2115 responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT);
2117 responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT);
2119 errorWrapper.setInnerElement(responseFormat);
2123 ArtifactDefinition heatArtifact = res.left().value();
2124 heatArtifactMDWrapper.setInnerElement(heatArtifact);
2125 // Iterator<ArtifactDefinition> parentArtifactsItr = parentDeploymentArtifacts.iterator();
2126 // while (!heatFound && parentArtifactsItr.hasNext()) {
2127 // ArtifactDefinition currArtifact = parentArtifactsItr.next();
2128 // if (heatArtifact.getUniqueId().equals(currArtifact.getUniqueId())) {
2129 // heatFound = true;
2130 // heatArtifactMDWrapper.setInnerElement(currArtifact);
2131 // log.trace("In validateHeatExist found artifact {}", currArtifact);
2133 // * ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(currArtifact.getArtifactType()); if(artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_VOL || artifactType == ArtifactTypeEnum.HEAT_NET){
2134 // * heatFound = true; } if (heatFound) { heatArtifactMDWrapper.setInnerElement(currArtifact); }
2138 // if (!heatFound) {
2139 // ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT);
2140 // errorWrapper.setInnerElement(responseFormat);
2141 // log.debug("Can't create heat env artifact because No heat Artifact exist.");
2146 private Either<Boolean, ResponseFormat> validateHeatDeploymentArtifact(Component parentComponent, String userId, boolean isCreate, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, NodeTypeEnum parentType) {
2147 log.trace("Started HEAT pre-payload validation for artifact {}", artifactInfo.getArtifactLabel());
2148 // timeout > 0 for HEAT artifacts
2149 Integer timeout = artifactInfo.getTimeout();
2150 Integer defaultTimeout = (isCreate) ? NodeTemplateOperation.getDefaultHeatTimeout() : currentArtifact.getTimeout();
2151 if (timeout == null) {
2152 artifactInfo.setTimeout(defaultTimeout);
2153 // HEAT artifact but timeout is invalid
2154 } else if (timeout < 1) {
2155 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_TIMEOUT));
2158 // US649856 - Allow several HEAT files on Resource
2160 * if (isCreate) { Wrapper<ResponseFormat> errorWrapper = new Wrapper<>(); validateSingleArtifactType(errorWrapper, ArtifactTypeEnum.findType(artifactInfo.getArtifactType()), parentComponent, parentType); if (!errorWrapper.isEmpty()) { return
2161 * Either.right(errorWrapper.getInnerElement()); } }
2164 log.trace("Ended HEAT validation for artifact {}", artifactInfo.getArtifactLabel());
2165 return Either.left(true);
2168 private Either<Boolean, ResponseFormat> validateResourceType(ResourceTypeEnum resourceType, ArtifactDefinition artifactInfo, List<String> typeList) {
2169 String listToString = (typeList != null) ? typeList.toString() : "";
2170 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISMATCH_BETWEEN_ARTIFACT_TYPE_AND_COMPONENT_TYPE, artifactInfo.getArtifactName(), listToString, resourceType.getValue());
2171 Either<Boolean, ResponseFormat> either = Either.right(responseFormat);
2172 String resourceTypeName = resourceType.name();
2173 if (typeList != null && typeList.contains(resourceTypeName)) {
2174 either = Either.left(true);
2179 private Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers(ArtifactDefinition artifactInfo, String artifactType) {
2180 if (artifactInfo.getHeatParameters() != null) {
2181 for (HeatParameterDefinition heatParam : artifactInfo.getListHeatParameters()) {
2182 String parameterType = heatParam.getType();
2183 HeatParameterType heatParameterType = HeatParameterType.isValidType(parameterType);
2184 String artifactTypeStr = artifactType != null ? artifactType : ArtifactTypeEnum.HEAT.getType();
2185 if (heatParameterType == null) {
2186 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_HEAT_PARAMETER_TYPE, artifactTypeStr, heatParam.getType());
2187 return Either.right(responseFormat);
2190 StorageOperationStatus validateAndUpdateProperty = heatParametersOperation.validateAndUpdateProperty(heatParam);
2191 if (validateAndUpdateProperty != StorageOperationStatus.OK) {
2192 log.debug("Heat parameter {} is invalid. Status is {}", heatParam.getName(), validateAndUpdateProperty);
2193 ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE;
2194 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, artifactTypeStr, heatParam.getType(), heatParam.getName());
2195 return Either.right(responseFormat);
2199 return Either.left(artifactInfo);
2202 public List<ArtifactDefinition> getDeploymentArtifacts(Component parentComponent, NodeTypeEnum parentType, String ciId) {
2203 List<ArtifactDefinition> deploymentArtifacts = new ArrayList<>();
2204 if (parentComponent.getDeploymentArtifacts() != null) {
2205 if (NodeTypeEnum.ResourceInstance == parentType && ciId != null) {
2206 Either<ComponentInstance, ResponseFormat> getRI = getRIFromComponent(parentComponent, ciId, null, null, null);
2207 if (getRI.isRight()) {
2208 return deploymentArtifacts;
2210 ComponentInstance ri = getRI.left().value();
2211 if (ri.getDeploymentArtifacts() != null) {
2212 deploymentArtifacts.addAll(ri.getDeploymentArtifacts().values());
2214 } else if (parentComponent.getDeploymentArtifacts() != null) {
2215 deploymentArtifacts.addAll(parentComponent.getDeploymentArtifacts().values());
2218 return deploymentArtifacts;
2221 private void checkCreateFields(User user, ArtifactDefinition artifactInfo, ArtifactGroupTypeEnum type) {
2222 // on create if null add informational to current
2223 if (artifactInfo.getArtifactGroupType() == null) {
2224 artifactInfo.setArtifactGroupType(type);
2226 if (artifactInfo.getUniqueId() != null) {
2227 log.error("artifact uniqid cannot be set ignoring");
2229 artifactInfo.setUniqueId(null);
2231 if (artifactInfo.getArtifactRef() != null) {
2232 log.error("artifact ref cannot be set ignoring");
2234 artifactInfo.setArtifactRef(null);
2236 if (artifactInfo.getArtifactRepository() != null) {
2237 log.error("artifact repository cannot be set ignoring");
2239 artifactInfo.setArtifactRepository(null);
2241 if (artifactInfo.getUserIdCreator() != null) {
2242 log.error("creator uuid cannot be set ignoring");
2244 artifactInfo.setArtifactCreator(user.getUserId());
2246 if (artifactInfo.getUserIdLastUpdater() != null) {
2247 log.error("userId of last updater cannot be set ignoring");
2249 artifactInfo.setUserIdLastUpdater(user.getUserId());
2251 if (artifactInfo.getCreatorFullName() != null) {
2252 log.error("creator Full name cannot be set ignoring");
2254 String fullName = user.getFirstName() + " " + user.getLastName();
2255 artifactInfo.setUpdaterFullName(fullName);
2257 if (artifactInfo.getUpdaterFullName() != null) {
2258 log.error("updater Full name cannot be set ignoring");
2260 artifactInfo.setUpdaterFullName(fullName);
2262 if (artifactInfo.getCreationDate() != null) {
2263 log.error("Creation Date cannot be set ignoring");
2265 long time = System.currentTimeMillis();
2266 artifactInfo.setCreationDate(time);
2268 if (artifactInfo.getLastUpdateDate() != null) {
2269 log.error("Last Update Date cannot be set ignoring");
2271 artifactInfo.setLastUpdateDate(time);
2273 if (artifactInfo.getEsId() != null) {
2274 log.error("es id cannot be set ignoring");
2276 artifactInfo.setEsId(null);
2281 * private Either<ArtifactDefinition, ResponseFormat> fetchCurrentArtifact(boolean isCreate, String artifactId) { Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(artifactId); if (isCreate
2282 * == false && artifactById.isRight()) { // in case of update artifact must be BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeArtifactMissingError, "Artifact Update / Upload", artifactId);
2283 * BeEcompErrorManager.getInstance().logBeArtifactMissingError("Artifact Update / Upload", artifactId); log.debug("Failed to fetch artifact {}. error: {}", artifactId, artifactById.right().value()); return
2284 * Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(artifactById.right().value()), artifactId)); } if (isCreate && artifactById.isLeft()) { log.debug("Artifact {} already exist", artifactId); return
2285 * Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactById.left().value().getArtifactLabel())); } ArtifactDefinition currentArtifactInfo = null; if (artifactById.isLeft()) { // get previous value
2286 * currentArtifactInfo = artifactById.left().value(); } return Either.left(currentArtifactInfo); }
2289 private String composeArtifactId(String resourceId, String artifactId, ArtifactDefinition artifactInfo, String interfaceName, String operationName) {
2290 String id = artifactId;
2291 if (artifactId == null || artifactId.isEmpty()) {
2292 String uniqueId = null;
2293 if (interfaceName != null && operationName != null) {
2294 uniqueId = UniqueIdBuilder.buildArtifactByInterfaceUniqueId(resourceId, interfaceName, operationName, artifactInfo.getArtifactLabel());
2296 uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId, artifactInfo.getArtifactLabel());
2298 artifactInfo.setUniqueId(uniqueId);
2299 artifactInfo.setEsId(uniqueId);
2302 artifactInfo.setUniqueId(artifactId);
2303 artifactInfo.setEsId(artifactId);
2308 private Either<ActionStatus, ResponseFormat> validateArtifactType(String userId, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) {
2309 if (artifactInfo.getArtifactType() == null || artifactInfo.getArtifactType().isEmpty()) {
2310 BeEcompErrorManager.getInstance().logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel");
2311 log.debug("Missing artifact type for artifact {}", artifactInfo.getArtifactName());
2312 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_TYPE));
2315 boolean artifactTypeExist = false;
2316 Either<List<ArtifactType>, ActionStatus> allArtifactTypes = null;
2317 ArtifactGroupTypeEnum artifactGroupType = artifactInfo.getArtifactGroupType();
2319 if ((artifactGroupType != null) && artifactGroupType.equals(ArtifactGroupTypeEnum.DEPLOYMENT)) {
2320 allArtifactTypes = getDeploymentArtifactTypes(userId, artifactInfo, parentType);
2323 allArtifactTypes = elementOperation.getAllArtifactTypes();
2325 if (allArtifactTypes.isRight()) {
2326 BeEcompErrorManager.getInstance().logBeInvalidConfigurationError("Artifact Upload / Update", "artifactTypes", allArtifactTypes.right().value().name());
2327 log.debug("Failed to retrieve list of suported artifact types. error: {}", allArtifactTypes.right().value());
2328 return Either.right(componentsUtils.getResponseFormatByUserId(allArtifactTypes.right().value(), userId));
2331 for (ArtifactType type : allArtifactTypes.left().value()) {
2332 if (type.getName().equalsIgnoreCase(artifactInfo.getArtifactType())) {
2333 artifactInfo.setArtifactType(artifactInfo.getArtifactType().toUpperCase());
2334 artifactTypeExist = true;
2339 if (!artifactTypeExist) {
2340 BeEcompErrorManager.getInstance().logBeInvalidTypeError("Artifact Upload / Delete / Update - Not supported artifact type", artifactInfo.getArtifactType(), "Artifact " + artifactInfo.getArtifactName());
2341 log.debug("Not supported artifact type = {}", artifactInfo.getArtifactType());
2342 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType()));
2345 return Either.left(ActionStatus.OK);
2348 private Either<List<ArtifactType>, ActionStatus> getDeploymentArtifactTypes(String userId, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) {
2350 Map<String, ArtifactTypeConfig> deploymentArtifacts = null;
2351 List<ArtifactType> artifactTypes = new ArrayList<ArtifactType>();
2353 if (parentType.equals(NodeTypeEnum.Service)) {
2354 deploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getServiceDeploymentArtifacts();
2355 } else if (parentType.equals(NodeTypeEnum.ResourceInstance)) {
2356 deploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceInstanceDeploymentArtifacts();
2358 deploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceDeploymentArtifacts();
2360 if (deploymentArtifacts != null) {
2361 for (String artifactType : deploymentArtifacts.keySet()) {
2362 ArtifactType artifactT = new ArtifactType();
2363 artifactT.setName(artifactType);
2364 artifactTypes.add(artifactT);
2366 return Either.left(artifactTypes);
2368 return Either.right(ActionStatus.GENERAL_ERROR);
2373 private Either<Boolean, ResponseFormat> validateFirstUpdateHasPayload(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2374 if (currentArtifact.getEsId() == null && (artifactInfo.getPayloadData() == null || artifactInfo.getPayloadData().length == 0)) {
2375 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD));
2377 return Either.left(true);
2381 private Either<Boolean, ResponseFormat> validateAndSetArtifactname(ArtifactDefinition artifactInfo) {
2382 if (artifactInfo.getArtifactName() == null || artifactInfo.getArtifactName().isEmpty()) {
2383 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_NAME));
2386 String normalizeFileName = ValidationUtils.normalizeFileName(artifactInfo.getArtifactName());
2387 if (normalizeFileName == null || normalizeFileName.isEmpty()) {
2388 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_NAME));
2390 artifactInfo.setArtifactName(normalizeFileName);
2392 if (!ValidationUtils.validateArtifactNameLength(artifactInfo.getArtifactName())) {
2393 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_NAME, String.valueOf(ValidationUtils.ARTIFACT_NAME_LENGTH)));
2396 return Either.left(true);
2399 private Either<Boolean, ResponseFormat> validateArtifactTypeNotChanged(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2400 if (artifactInfo.getArtifactType() == null || artifactInfo.getArtifactType().isEmpty()) {
2401 log.info("artifact type is missing operation ignored");
2402 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_TYPE));
2405 if (!currentArtifact.getArtifactType().equalsIgnoreCase(artifactInfo.getArtifactType())) {
2406 log.info("artifact type cannot be changed operation ignored");
2407 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2409 return Either.left(true);
2412 private Either<ArtifactDefinition, ResponseFormat> validateOrSetArtifactGroupType(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2413 if (artifactInfo.getArtifactGroupType() == null) {
2414 artifactInfo.setArtifactGroupType(currentArtifact.getArtifactGroupType());
2417 else if (!currentArtifact.getArtifactGroupType().getType().equalsIgnoreCase(artifactInfo.getArtifactGroupType().getType())) {
2418 log.info("artifact group type cannot be changed. operation failed");
2419 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2421 return Either.left(artifactInfo);
2424 private void checkAndSetUnUpdatableFields(User user, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, ArtifactGroupTypeEnum type) {
2426 // on update if null add informational to current
2427 if (currentArtifact.getArtifactGroupType() == null && type != null) {
2428 currentArtifact.setArtifactGroupType(type);
2431 if (artifactInfo.getUniqueId() != null && !currentArtifact.getUniqueId().equals(artifactInfo.getUniqueId())) {
2432 log.error("artifact uniqid cannot be set ignoring");
2434 artifactInfo.setUniqueId(currentArtifact.getUniqueId());
2436 if (artifactInfo.getArtifactRef() != null && !currentArtifact.getArtifactRef().equals(artifactInfo.getArtifactRef())) {
2437 log.error("artifact ref cannot be set ignoring");
2439 artifactInfo.setArtifactRef(currentArtifact.getArtifactRef());
2441 if (artifactInfo.getArtifactRepository() != null && !currentArtifact.getArtifactRepository().equals(artifactInfo.getArtifactRepository())) {
2442 log.error("artifact repository cannot be set ignoring");
2444 artifactInfo.setArtifactRepository(currentArtifact.getArtifactRepository());
2446 if (artifactInfo.getUserIdCreator() != null && !currentArtifact.getUserIdCreator().equals(artifactInfo.getUserIdCreator())) {
2447 log.error("creator uuid cannot be set ignoring");
2449 artifactInfo.setUserIdCreator(currentArtifact.getUserIdCreator());
2451 if (artifactInfo.getArtifactCreator() != null && !currentArtifact.getArtifactCreator().equals(artifactInfo.getArtifactCreator())) {
2452 log.error("artifact creator cannot be set ignoring");
2454 artifactInfo.setArtifactCreator(currentArtifact.getArtifactCreator());
2456 if (artifactInfo.getUserIdLastUpdater() != null && !currentArtifact.getUserIdLastUpdater().equals(artifactInfo.getUserIdLastUpdater())) {
2457 log.error("userId of last updater cannot be set ignoring");
2459 artifactInfo.setUserIdLastUpdater(user.getUserId());
2461 if (artifactInfo.getCreatorFullName() != null && !currentArtifact.getCreatorFullName().equals(artifactInfo.getCreatorFullName())) {
2462 log.error("creator Full name cannot be set ignoring");
2464 artifactInfo.setCreatorFullName(currentArtifact.getCreatorFullName());
2466 if (artifactInfo.getUpdaterFullName() != null && !currentArtifact.getUpdaterFullName().equals(artifactInfo.getUpdaterFullName())) {
2467 log.error("updater Full name cannot be set ignoring");
2469 String fullName = user.getFirstName() + " " + user.getLastName();
2470 artifactInfo.setUpdaterFullName(fullName);
2472 if (artifactInfo.getCreationDate() != null && !currentArtifact.getCreationDate().equals(artifactInfo.getCreationDate())) {
2473 log.error("Creation Date cannot be set ignoring");
2475 artifactInfo.setCreationDate(currentArtifact.getCreationDate());
2477 if (artifactInfo.getLastUpdateDate() != null && !currentArtifact.getLastUpdateDate().equals(artifactInfo.getLastUpdateDate())) {
2478 log.error("Last Update Date cannot be set ignoring");
2480 long time = System.currentTimeMillis();
2481 artifactInfo.setLastUpdateDate(time);
2483 if (artifactInfo.getEsId() != null && !currentArtifact.getEsId().equals(artifactInfo.getEsId())) {
2484 log.error("es id cannot be set ignoring");
2486 artifactInfo.setEsId(currentArtifact.getUniqueId());
2488 if (artifactInfo.getArtifactDisplayName() != null && !currentArtifact.getArtifactDisplayName().equals(artifactInfo.getArtifactDisplayName())) {
2489 log.error(" Artifact Display Name cannot be set ignoring");
2491 artifactInfo.setArtifactDisplayName(currentArtifact.getArtifactDisplayName());
2493 if (artifactInfo.getServiceApi() != null && !currentArtifact.getServiceApi().equals(artifactInfo.getServiceApi())) {
2494 log.debug("serviceApi cannot be set. ignoring.");
2496 artifactInfo.setServiceApi(currentArtifact.getServiceApi());
2498 if (artifactInfo.getArtifactGroupType() != null && !currentArtifact.getArtifactGroupType().equals(artifactInfo.getArtifactGroupType())) {
2499 log.debug("artifact group cannot be set. ignoring.");
2501 artifactInfo.setArtifactGroupType(currentArtifact.getArtifactGroupType());
2503 artifactInfo.setArtifactVersion(currentArtifact.getArtifactVersion());
2505 if (artifactInfo.getArtifactUUID() != null && !artifactInfo.getArtifactUUID().isEmpty() && !currentArtifact.getArtifactUUID().equals(artifactInfo.getArtifactUUID())) {
2506 log.debug("artifact UUID cannot be set. ignoring.");
2508 artifactInfo.setArtifactUUID(currentArtifact.getArtifactUUID());
2510 if ((artifactInfo.getHeatParameters() != null) && (currentArtifact.getHeatParameters() != null) && !artifactInfo.getHeatParameters().isEmpty() && !currentArtifact.getHeatParameters().isEmpty()) {
2511 checkAndSetUnupdatableHeatParams(artifactInfo.getListHeatParameters(), currentArtifact.getListHeatParameters());
2515 private void checkAndSetUnupdatableHeatParams(List<HeatParameterDefinition> heatParameters, List<HeatParameterDefinition> currentParameters) {
2517 Map<String, HeatParameterDefinition> currentParametersMap = getMapOfParameters(currentParameters);
2518 for (HeatParameterDefinition parameter : heatParameters) {
2519 HeatParameterDefinition currentParam = currentParametersMap.get(parameter.getUniqueId());
2521 if (currentParam != null) {
2523 if (parameter.getName() != null && !parameter.getName().equalsIgnoreCase(currentParam.getName())) {
2524 log.debug("heat parameter name cannot be updated ({}). ignoring.", parameter.getName());
2525 parameter.setName(currentParam.getName());
2527 if (parameter.getDefaultValue() != null && !parameter.getDefaultValue().equalsIgnoreCase(currentParam.getDefaultValue())) {
2528 log.debug("heat parameter defaultValue cannot be updated ({}). ignoring.", parameter.getDefaultValue());
2529 parameter.setDefaultValue(currentParam.getDefaultValue());
2531 if (parameter.getType() != null && !parameter.getType().equalsIgnoreCase(currentParam.getType())) {
2532 log.debug("heat parameter type cannot be updated ({}). ignoring.", parameter.getType());
2533 parameter.setType(currentParam.getType());
2535 if (parameter.getDescription() != null && !parameter.getDescription().equalsIgnoreCase(currentParam.getDescription())) {
2536 log.debug("heat parameter description cannot be updated ({}). ignoring.", parameter.getDescription());
2537 parameter.setDescription(currentParam.getDescription());
2540 // check and set current value
2541 if ((parameter.getCurrentValue() == null) && (currentParam.getDefaultValue() != null)) {
2542 log.debug("heat parameter current value is null. set it to default value {}). ignoring.", parameter.getDefaultValue());
2543 parameter.setCurrentValue(currentParam.getDefaultValue());
2549 private Map<String, HeatParameterDefinition> getMapOfParameters(List<HeatParameterDefinition> currentParameters) {
2551 Map<String, HeatParameterDefinition> currentParamsMap = new HashMap<String, HeatParameterDefinition>();
2552 for (HeatParameterDefinition param : currentParameters) {
2553 currentParamsMap.put(param.getUniqueId(), param);
2555 return currentParamsMap;
2558 private Either<Boolean, ResponseFormat> validateAndServiceApiUrl(ArtifactDefinition artifactInfo) {
2559 if (!ValidationUtils.validateStringNotEmpty(artifactInfo.getApiUrl())) {
2560 log.debug("Artifact url cannot be empty.");
2561 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_URL));
2563 artifactInfo.setApiUrl(artifactInfo.getApiUrl().toLowerCase());
2565 if (!ValidationUtils.validateUrl(artifactInfo.getApiUrl())) {
2566 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_SERVICE_API_URL));
2568 if (!ValidationUtils.validateUrlLength(artifactInfo.getApiUrl())) {
2569 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_URL, String.valueOf(ValidationUtils.API_URL_LENGTH)));
2572 return Either.left(true);
2575 private Either<Boolean, ResponseFormat> validateAndCleanDescription(ArtifactDefinition artifactInfo) {
2576 if (artifactInfo.getDescription() == null || artifactInfo.getDescription().isEmpty()) {
2577 log.debug("Artifact description cannot be empty.");
2578 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_DESCRIPTION));
2580 String description = artifactInfo.getDescription();
2581 description = ValidationUtils.removeNoneUtf8Chars(description);
2582 description = ValidationUtils.normaliseWhitespace(description);
2583 description = ValidationUtils.stripOctets(description);
2584 description = ValidationUtils.removeHtmlTagsOnly(description);
2585 if (!ValidationUtils.validateIsEnglish(description)) {
2586 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2588 if (!ValidationUtils.validateLength(description, ValidationUtils.ARTIFACT_DESCRIPTION_MAX_LENGTH)) {
2589 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_DESCRIPTION, String.valueOf(ValidationUtils.ARTIFACT_DESCRIPTION_MAX_LENGTH)));
2591 artifactInfo.setDescription(description);
2592 return Either.left(true);
2595 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateArtifactFlow(org.openecomp.sdc.be.model.Component parent, String parentId, String artifactId, ArtifactDefinition artifactInfo, User user, byte[] decodedPayload,
2596 ComponentTypeEnum componentType, AuditingActionEnum auditingAction, String interfaceType, String operationName) {
2597 ESArtifactData artifactData = createEsArtifactData(artifactInfo, decodedPayload);
2598 String prevArtifactId = null;
2599 String currArtifactId = artifactId;
2601 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
2602 Either<ArtifactDefinition, Operation> insideEither = null;
2604 if (artifactData == null) {
2605 BeEcompErrorManager.getInstance().logBeDaoSystemError("Update Artifact");
2606 log.debug("Failed to create artifact object for ES.");
2607 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
2608 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
2609 resultOp = Either.right(responseFormat);
2612 log.trace("Try to update entry on graph");
2613 String artifactUniqueId = null;
2614 ArtifactDefinition artifactDefinition = artifactInfo;
2615 StorageOperationStatus error = null;
2617 boolean isLeft = false;
2618 if (interfaceType != null && operationName != null) {
2619 // lifecycle artifact
2621 * Operation operation = convertToOperation(artifactInfo, operationName);
2623 * Either<Operation, StorageOperationStatus> result = interfaceLifecycleOperation.updateInterfaceOperation(parentId, interfaceType, operationName, operation);
2625 * isLeft = result.isLeft(); if (isLeft) { artifactUniqueId = result.left().value().getUniqueId(); artifactDefinition = result.left().value().getImplementation();
2627 * insideEither = Either.right(result.left().value()); resultOp = Either.left(insideEither); } else { error = result.right().value(); }
2630 log.debug("Enty on graph is updated. Update artifact in ES");
2632 // Changing previous and current artifactId for auditing
2633 prevArtifactId = currArtifactId;
2634 currArtifactId = artifactDefinition.getUniqueId();
2636 NodeTypeEnum convertParentType = convertParentType(componentType);
2638 if (decodedPayload == null) {
2639 if (!artifactDefinition.getMandatory() || artifactDefinition.getEsId() != null) {
2640 Either<ESArtifactData, CassandraOperationStatus> artifactFromCassandra = artifactCassandraDao.getArtifact(artifactDefinition.getEsId());
2641 // Either<ESArtifactData, ResourceUploadStatus>
2642 // artifactfromES = daoUploader.getArtifact(artifactId);
2643 if (artifactFromCassandra.isRight()) {
2644 log.debug("Failed to get artifact data from ES for artifact id {}", artifactId);
2645 error = DaoStatusConverter.convertCassandraStatusToStorageStatus(artifactFromCassandra.right().value());
2646 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
2647 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
2648 resultOp = Either.right(responseFormat);
2651 // clone data to new artifact
2652 artifactData.setData(artifactFromCassandra.left().value().getData());
2653 artifactData.setId(artifactFromCassandra.left().value().getId());
2656 if (artifactDefinition.getEsId() == null) {
2657 artifactDefinition.setEsId(artifactDefinition.getUniqueId());
2658 artifactData.setId(artifactDefinition.getUniqueId());
2662 Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.updateArifactOnResource(artifactInfo, parent.getUniqueId(), artifactId, convertParentType, parentId);
2663 isLeft = result.isLeft();
2665 artifactUniqueId = result.left().value().getUniqueId();
2666 artifactDefinition = result.left().value();
2667 String artifactType = artifactInfo.getArtifactType();
2668 if (NodeTypeEnum.Resource == convertParentType
2669 && (ArtifactTypeEnum.HEAT.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.HEAT_VOL.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.HEAT_NET.getType().equalsIgnoreCase(artifactType))) {
2671 if (!artifactUniqueId.equals(artifactId)) {
2672 // need to update the generated id in heat env
2673 Map<String, ArtifactDefinition> deploymentArtifacts = parent.getDeploymentArtifacts();
2674 Optional<Entry<String, ArtifactDefinition>> findFirst = deploymentArtifacts.entrySet().stream().filter(a -> a.getValue().getGeneratedFromId()!=null && a.getValue().getGeneratedFromId().equals(artifactId)).findFirst();
2675 if (findFirst.isPresent()) {
2676 ArtifactDefinition artifactEnvInfo = findFirst.get().getValue();
2677 artifactEnvInfo.setArtifactChecksum(null);
2678 artifactToscaOperation.updateHeatEnvArtifact(parent.getUniqueId(), artifactEnvInfo, artifactId, artifactUniqueId, convertParentType, parentId);
2683 * if (!artifactUniqueId.equals(artifactId)) { artifactToscaOperation.updateHeatEnvArtifact(parentId, null, artifactId, artifactUniqueId, convertParentType);
2685 * } else { if (!artifactInfo.getArtifactChecksum().equals(artifactDefinition.getArtifactChecksum())) { Either<ArtifactDefinition, StorageOperationStatus> heatEnvEither =
2686 * artifactToscaOperation.getHeatEnvByGeneratedFromId(artifactUniqueId); if (heatEnvEither.isLeft()) { artifactToscaOperation.updateHeatEnvPlaceholder(heatEnvEither.left().value(), parentId);
2691 error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentType);
2693 insideEither = Either.left(result.left().value());
2694 resultOp = Either.left(insideEither);
2695 if (error != StorageOperationStatus.OK) {
2700 error = result.right().value();
2704 // create new entry in ES
2706 if (artifactData.getData() != null) {
2707 if (!artifactDefinition.getDuplicated() || artifactData.getId() == null)
2708 artifactData.setId(artifactDefinition.getEsId());
2709 res = saveArtifacts(artifactData, parentId, false);
2715 log.debug("Artifact saved into ES - {}", artifactUniqueId);
2716 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
2717 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
2718 // resultOp = Either.left(result.left().value());
2721 BeEcompErrorManager.getInstance().logBeDaoSystemError("Update Artifact");
2722 log.debug("Failed to save the artifact.");
2723 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
2724 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
2725 resultOp = Either.right(responseFormat);
2733 private Either<byte[], ResponseFormat> handlePayload(ArtifactDefinition artifactInfo, boolean isArtifactMetadataUpdate) {
2734 log.trace("Starting payload handling");
2735 byte[] payload = artifactInfo.getPayloadData();
2736 byte[] decodedPayload = null;
2738 if (payload != null && payload.length != 0) {
2739 // the generated artifacts were already decoded by the handler
2740 decodedPayload = artifactInfo.getGenerated() ? payload : Base64.decodeBase64(payload);
2741 if (decodedPayload.length == 0) {
2742 log.debug("Failed to decode the payload.");
2743 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
2744 return Either.right(responseFormat);
2747 String checkSum = GeneralUtility.calculateMD5ByByteArray(decodedPayload);
2748 artifactInfo.setArtifactChecksum(checkSum);
2749 log.trace("Calculated checksum, base64 payload: {}, checksum: {}", payload, checkSum);
2751 // Specific payload validations of different types
2752 Either<Boolean, ResponseFormat> isValidPayload = Either.left(true);
2753 if (isDeploymentArtifact(artifactInfo)) {
2754 log.trace("Starting deployment artifacts payload validation");
2755 String artifactType = artifactInfo.getArtifactType();
2756 if (ArtifactTypeEnum.HEAT.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.HEAT_VOL.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.HEAT_NET.getType().equalsIgnoreCase(artifactType)
2757 || ArtifactTypeEnum.HEAT_ENV.getType().equalsIgnoreCase(artifactType)) {
2758 isValidPayload = validateDeploymentHeatPayload(decodedPayload, artifactType);
2759 if (isValidPayload.isLeft()) {
2760 isValidPayload = extractHeatParameters(artifactInfo);
2762 } else if (ArtifactTypeEnum.YANG_XML.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.VNF_CATALOG.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.VF_LICENSE.getType().equalsIgnoreCase(artifactType)
2763 || ArtifactTypeEnum.VENDOR_LICENSE.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.MODEL_INVENTORY_PROFILE.getType().equalsIgnoreCase(artifactType)
2764 || ArtifactTypeEnum.MODEL_QUERY_SPEC.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.UCPE_LAYER_2_CONFIGURATION.getType().equalsIgnoreCase(artifactType)) {
2765 isValidPayload = validateXmlPayload(decodedPayload, artifactType);
2767 // if(ArtifactTypeEnum.APPC_CONFIG.getType().equalsIgnoreCase(artifactType)
2769 } else if (ArtifactTypeEnum.DCAE_INVENTORY_JSON.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType().equalsIgnoreCase(artifactType)
2770 || ArtifactTypeEnum.VES_EVENTS.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.LIFECYCLE_OPERATIONS.getType().equalsIgnoreCase(artifactType)) {
2771 String artifactFileName = artifactInfo.getArtifactName();
2772 String fileExtension = GeneralUtility.getFilenameExtension(artifactFileName).toLowerCase();
2773 switch (fileExtension) {
2775 isValidPayload = validateXmlPayload(decodedPayload, artifactType);
2778 isValidPayload = validateJsonPayload(decodedPayload, artifactType);
2782 isValidPayload = validateYmlPayload(decodedPayload, artifactType);
2787 if (isValidPayload.isRight()) {
2788 ResponseFormat responseFormat = isValidPayload.right().value();
2789 return Either.right(responseFormat);
2792 } // null/empty payload is normal if called from metadata update ONLY.
2793 // The validation of whether this is metadata/payload update case is
2794 // currently done separately
2796 if (!isArtifactMetadataUpdate) {
2797 log.debug("Payload is missing.");
2798 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
2799 return Either.right(responseFormat);
2802 log.trace("Ended payload handling");
2803 return Either.left(decodedPayload);
2806 private Either<Boolean, ResponseFormat> validateDeploymentHeatPayload(byte[] decodedPayload, String artifactType) {
2807 // Basic YAML validation
2808 YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter();
2809 if (!yamlToObjectConverter.isValidYaml(decodedPayload)) {
2810 log.debug("Invalid YAML format");
2811 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, artifactType);
2812 return Either.right(responseFormat);
2814 if (!ArtifactTypeEnum.HEAT_ENV.getType().equalsIgnoreCase(artifactType)) {
2815 // HEAT specific YAML validation
2816 DeploymentArtifactHeatConfiguration heatConfiguration = yamlToObjectConverter.convert(decodedPayload, DeploymentArtifactHeatConfiguration.class);
2817 if (heatConfiguration == null || heatConfiguration.getHeat_template_version() == null) {
2818 log.debug("HEAT doesn't contain required \"heat_template_version\" section.");
2819 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactType);
2820 return Either.right(responseFormat);
2824 return Either.left(true);
2827 private Either<Boolean, ResponseFormat> validateYmlPayload(byte[] decodedPayload, String artifactType) {
2828 Either<Boolean, ResponseFormat> res = Either.left(true);
2829 YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter();
2830 if (!yamlToObjectConverter.isValidYaml(decodedPayload)) {
2831 log.debug("Invalid YAML format");
2832 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, artifactType);
2833 res = Either.right(responseFormat);
2839 private Either<Boolean, ResponseFormat> validateXmlPayload(byte[] payload, String artifactType) {
2840 boolean isXmlValid = isValidXml(payload);
2842 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.INVALID_XML, artifactType);
2843 log.debug("Invalid XML content");
2844 return Either.right(responseFormat);
2846 return Either.left(true);
2849 private Either<Boolean, ResponseFormat> validateJsonPayload(byte[] payload, String type) {
2850 boolean isJsonValid = isValidJson(payload);
2852 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.INVALID_JSON, type);
2853 log.debug("Invalid JSON content");
2854 return Either.right(responseFormat);
2856 return Either.left(true);
2859 public void handleTransaction(Either<Operation, ResponseFormat> opState) {
2860 if (opState == null || opState.isRight()) {
2861 titanDao.rollback();
2867 public Either<Operation, ResponseFormat> deleteArtifactByInterface(String resourceId, String interfaceType, String operationName, String userUserId, String artifactId, ImmutablePair<User, Resource> userResourceAuditPair, boolean shouldLock,
2868 boolean inTransaction) {
2869 User user = new User();
2870 user.setUserId(userUserId);
2871 Either<Resource, StorageOperationStatus> parent = toscaOperationFacade.getToscaElement(resourceId, JsonParseFlagEnum.ParseMetadata);
2872 if (parent.isRight()) {
2873 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(parent.right().value()));
2874 return Either.right(responseFormat);
2876 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = handleDelete(resourceId, artifactId, user, AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, parent.left().value(), interfaceType, operationName,
2877 false, inTransaction);
2878 if (handleDelete.isRight()) {
2879 return Either.right(handleDelete.right().value());
2881 Either<ArtifactDefinition, Operation> result = handleDelete.left().value();
2882 return Either.left(result.right().value());
2886 public StorageOperationStatus deleteAllComponentArtifactsIfNotOnGraph(List<ArtifactDefinition> artifacts) {
2888 if (artifacts != null && !artifacts.isEmpty()) {
2889 for (ArtifactDefinition artifactDefinition : artifacts) {
2890 String esId = artifactDefinition.getEsId();
2891 if (esId != null && !esId.isEmpty()) {
2892 StorageOperationStatus deleteIfNotOnGraph = deleteIfNotOnGraph(artifactDefinition.getUniqueId(), esId, false);
2893 if (!deleteIfNotOnGraph.equals(StorageOperationStatus.OK)) {
2894 return deleteIfNotOnGraph;
2899 return StorageOperationStatus.OK;
2902 private Operation convertToOperation(ArtifactDefinition artifactInfo, String operationName) {
2903 Operation op = new Operation();
2904 long time = System.currentTimeMillis();
2905 op.setCreationDate(time);
2907 String artifactName = artifactInfo.getArtifactName();
2908 artifactInfo.setArtifactName(createInterfaceArtifactNameFromOperation(operationName, artifactName));
2910 op.setImplementation(artifactInfo);
2911 op.setLastUpdateDate(time);
2915 private String createInterfaceArtifactNameFromOperation(String operationName, String artifactName) {
2916 String newArtifactName = operationName + "_" + artifactName;
2917 log.trace("converting artifact name {} to {}", artifactName, newArtifactName);
2918 return newArtifactName;
2921 public StorageOperationStatus deleteIfNotOnGraph(String artifactId, String artifactEsId, boolean deleteOnlyPayload) {
2922 log.debug("deleteIfNotOnGraph: delete only payload = {}", deleteOnlyPayload);
2923 // Either<ArtifactData, TitanOperationStatus> checkArtifactNode = titanDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ArtifactRef), artifactId, ArtifactData.class);
2924 // if ((artifactEsId != null && !artifactEsId.isEmpty())) {
2925 // boolean isNotExistOnGraph = checkArtifactNode.isRight() && checkArtifactNode.right().value().equals(TitanOperationStatus.NOT_FOUND);
2927 // if ((isNotExistOnGraph) || (checkArtifactNode.left().value().getArtifactDataDefinition().getMandatory() && deleteOnlyPayload)
2928 // || (ArtifactGroupTypeEnum.SERVICE_API.equals(checkArtifactNode.left().value().getArtifactDataDefinition().getArtifactGroupType()) && deleteOnlyPayload)) {
2929 // // last one. need to delete in ES
2930 // log.debug("Entry on graph is deleted. Delete artifact in ES for id = {}", artifactEsId);
2931 // artifactCassandraDao.deleteArtifact(artifactEsId);
2932 // return StorageOperationStatus.OK;
2934 // // componentsUtils.getResponseFormatByResourceId(ActionStatus.OK,
2938 // log.debug("Entry on graph is deleted. Exist more connections on this artifact. Don't delete artifact in ES for id = {}", artifactEsId);
2939 // return StorageOperationStatus.OK;
2943 return StorageOperationStatus.OK;
2947 public Either<byte[], ResponseFormat> downloadRsrcArtifactByNames(String serviceName, String serviceVersion, String resourceName, String resourceVersion, String artifactName) {
2949 // General validation
2950 if (serviceName == null || serviceVersion == null || resourceName == null || resourceVersion == null || artifactName == null) {
2951 log.debug("One of the function parameteres is null");
2952 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2955 // Normalizing artifact name
2956 artifactName = ValidationUtils.normalizeFileName(artifactName);
2958 // Resource validation
2959 Either<Resource, ResponseFormat> validateResourceNameAndVersion = validateResourceNameAndVersion(resourceName, resourceVersion);
2960 if (validateResourceNameAndVersion.isRight()) {
2961 return Either.right(validateResourceNameAndVersion.right().value());
2964 Resource resource = validateResourceNameAndVersion.left().value();
2965 String resourceId = resource.getUniqueId();
2967 // Service validation
2968 Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
2969 if (validateServiceNameAndVersion.isRight()) {
2970 return Either.right(validateServiceNameAndVersion.right().value());
2973 Map<String, ArtifactDefinition> artifacts = resource.getDeploymentArtifacts();
2974 if (artifacts == null || artifacts.isEmpty()) {
2975 log.debug("Deployment artifacts of resource {} are not found", resourceId);
2976 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
2979 ArtifactDefinition deploymentArtifact = null;
2981 for (ArtifactDefinition artifactDefinition : artifacts.values()) {
2982 if (artifactDefinition.getArtifactName() != null && artifactDefinition.getArtifactName().equals(artifactName)) {
2983 log.debug("Found deployment artifact {}", artifactName);
2984 deploymentArtifact = artifactDefinition;
2989 if (deploymentArtifact == null) {
2990 log.debug("No deployment artifact {} was found for resource {}", artifactName, resourceId);
2991 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
2994 // Downloading the artifact
2995 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(deploymentArtifact);
2996 if (downloadArtifactEither.isRight()) {
2997 log.debug("Download artifact {} failed", artifactName);
2998 return Either.right(downloadArtifactEither.right().value());
3000 log.trace("Download of resource artifact succeeded, uniqueId {}", deploymentArtifact.getUniqueId());
3001 return Either.left(downloadArtifactEither.left().value().getRight());
3005 public Either<byte[], ResponseFormat> downloadRsrcInstArtifactByNames(String serviceName, String serviceVersion, String resourceInstanceName, String artifactName) {
3007 // General validation
3008 if (serviceName == null || serviceVersion == null || resourceInstanceName == null || artifactName == null) {
3009 log.debug("One of the function parameteres is null");
3010 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
3013 // Normalizing artifact name
3014 artifactName = ValidationUtils.normalizeFileName(artifactName);
3016 // Resource validation
3018 * Either<Resource, ResponseFormat> validateResourceNameAndVersion = validateResourceNameAndVersion(resourceName, resourceVersion); if (validateResourceNameAndVersion.isRight()) { return
3019 * Either.right(validateResourceNameAndVersion.right().value()); }
3021 * Resource resource = validateResourceNameAndVersion.left().value(); String resourceId = resource.getUniqueId();
3024 // Service validation
3025 Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
3026 if (validateServiceNameAndVersion.isRight()) {
3027 return Either.right(validateServiceNameAndVersion.right().value());
3030 Service service = validateServiceNameAndVersion.left().value();
3032 // ResourceInstance validation
3033 Either<ComponentInstance, ResponseFormat> validateResourceInstance = validateResourceInstance(service, resourceInstanceName);
3034 if (validateResourceInstance.isRight()) {
3035 return Either.right(validateResourceInstance.right().value());
3038 ComponentInstance resourceInstance = validateResourceInstance.left().value();
3040 Map<String, ArtifactDefinition> artifacts = resourceInstance.getDeploymentArtifacts();
3042 final String finalArtifactName = artifactName;
3043 Predicate<ArtifactDefinition> filterArtifactByName = p -> p.getArtifactName().equals(finalArtifactName);
3045 boolean hasDeploymentArtifacts = artifacts != null && artifacts.values().stream().anyMatch(filterArtifactByName);
3046 ArtifactDefinition deployableArtifact;
3048 if (!hasDeploymentArtifacts) {
3049 log.debug("Deployment artifact with name {} not found", artifactName);
3050 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
3053 log.debug("Found deployment artifact {}", artifactName);
3054 deployableArtifact = artifacts.values().stream().filter(filterArtifactByName).findFirst().get();
3055 // Downloading the artifact
3056 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(deployableArtifact);
3058 if (downloadArtifactEither.isRight()) {
3059 log.debug("Download artifact {} failed", artifactName);
3060 return Either.right(downloadArtifactEither.right().value());
3062 log.trace("Download of resource artifact succeeded, uniqueId {}", deployableArtifact.getUniqueId());
3063 return Either.left(downloadArtifactEither.left().value().getRight());
3066 private Either<ComponentInstance, ResponseFormat> validateResourceInstance(Service service, String resourceInstanceName) {
3068 List<ComponentInstance> riList = service.getComponentInstances();
3069 for (ComponentInstance ri : riList) {
3070 if (ri.getNormalizedName().equals(resourceInstanceName))
3071 return Either.left(ri);
3074 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND, resourceInstanceName));
3077 private Either<Service, ResponseFormat> validateServiceNameAndVersion(String serviceName, String serviceVersion) {
3079 Either<List<Service>, StorageOperationStatus> serviceListBySystemName = toscaOperationFacade.getBySystemName(ComponentTypeEnum.SERVICE, serviceName);
3080 if (serviceListBySystemName.isRight()) {
3081 log.debug("Couldn't fetch any service with name {}", serviceName);
3082 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceListBySystemName.right().value(), ComponentTypeEnum.SERVICE), serviceName));
3084 List<Service> serviceList = serviceListBySystemName.left().value();
3085 if (serviceList == null || serviceList.isEmpty()) {
3086 log.debug("Couldn't fetch any service with name {}", serviceName);
3087 return Either.right(componentsUtils.getResponseFormat(ActionStatus.SERVICE_NOT_FOUND, serviceName));
3090 Service foundService = null;
3091 for (Service service : serviceList) {
3092 if (service.getVersion().equals(serviceVersion)) {
3093 log.trace("Found service with version {}", serviceVersion);
3094 foundService = service;
3099 if (foundService == null) {
3100 log.debug("Couldn't find version {} for service {}", serviceVersion, serviceName);
3101 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_VERSION_NOT_FOUND, ComponentTypeEnum.SERVICE.getValue(), serviceVersion));
3103 return Either.left(foundService);
3106 private Either<Resource, ResponseFormat> validateResourceNameAndVersion(String resourceName, String resourceVersion) {
3108 Either<Resource, StorageOperationStatus> resourceListBySystemName = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, resourceVersion, JsonParseFlagEnum.ParseMetadata);
3109 if (resourceListBySystemName.isRight()) {
3110 log.debug("Couldn't fetch any resource with name {} and version {}. ", resourceName, resourceVersion);
3111 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceListBySystemName.right().value()), resourceName));
3113 return Either.left(resourceListBySystemName.left().value());
3116 public Either<byte[], ResponseFormat> downloadServiceArtifactByNames(String serviceName, String serviceVersion, String artifactName) {
3118 log.trace("Starting download of service interface artifact, serviceName {}, serviceVersion {}, artifact name {}", serviceName, serviceVersion, artifactName);
3119 if (serviceName == null || serviceVersion == null || artifactName == null) {
3120 log.debug("One of the function parameteres is null");
3121 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
3124 // Normalizing artifact name
3125 final String normalizedArtifactName = ValidationUtils.normalizeFileName(artifactName);
3127 // Service validation
3128 Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
3129 if (validateServiceNameAndVersion.isRight()) {
3130 return Either.right(validateServiceNameAndVersion.right().value());
3133 String serviceId = validateServiceNameAndVersion.left().value().getUniqueId();
3135 // Looking for deployment or tosca artifacts
3136 Service service = validateServiceNameAndVersion.left().value();
3138 if (MapUtils.isEmpty(service.getDeploymentArtifacts()) && MapUtils.isEmpty(service.getToscaArtifacts())) {
3139 log.debug("Neither Deployment nor Tosca artifacts of service {} are found", serviceId);
3140 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, normalizedArtifactName));
3143 Optional<ArtifactDefinition> foundArtifactOptl = null;
3145 if (!MapUtils.isEmpty(service.getDeploymentArtifacts())) {
3146 foundArtifactOptl = service.getDeploymentArtifacts().values().stream()
3147 // filters artifact by name
3148 .filter(a -> a.getArtifactName().equals(normalizedArtifactName)).findAny();
3150 if ((foundArtifactOptl == null || !foundArtifactOptl.isPresent()) && !MapUtils.isEmpty(service.getToscaArtifacts())) {
3151 foundArtifactOptl = service.getToscaArtifacts().values().stream()
3152 // filters TOSCA artifact by name
3153 .filter(a -> a.getArtifactName().equals(normalizedArtifactName)).findAny();
3155 if (!foundArtifactOptl.isPresent()) {
3156 log.debug("The artifact {} was not found for service {}", normalizedArtifactName, serviceId);
3157 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, normalizedArtifactName));
3159 log.debug("Found deployment artifact {}", normalizedArtifactName);
3160 // Downloading the artifact
3161 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(foundArtifactOptl.get());
3162 if (downloadArtifactEither.isRight()) {
3163 log.debug("Download artifact {} failed", normalizedArtifactName);
3164 return Either.right(downloadArtifactEither.right().value());
3166 log.trace("Download of service artifact succeeded, uniqueId {}", foundArtifactOptl.get().getUniqueId());
3167 return Either.left(downloadArtifactEither.left().value().getRight());
3170 public Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifact(String parentId, String artifactUniqueId) {
3171 log.trace("Starting download of artifact, uniqueId {}", artifactUniqueId);
3172 Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(parentId, artifactUniqueId);
3173 if (artifactById.isRight()) {
3174 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(artifactById.right().value());
3175 log.debug("Error when getting artifact info by id{}, error: {}", artifactUniqueId, actionStatus.name());
3176 return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, ""));
3178 ArtifactDefinition artifactDefinition = artifactById.left().value();
3179 if (artifactDefinition == null) {
3180 log.debug("Empty artifact definition returned from DB by artifact id {}", artifactUniqueId);
3181 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ""));
3184 return downloadArtifact(artifactDefinition);
3187 private boolean checkArtifactInComponent(org.openecomp.sdc.be.model.Component component, String artifactId) {
3188 boolean found = false;
3189 Map<String, ArtifactDefinition> artifactsS = component.getArtifacts();
3190 if (artifactsS != null) {
3191 for (Map.Entry<String, ArtifactDefinition> entry : artifactsS.entrySet()) {
3192 if (entry.getValue().getUniqueId().equals(artifactId)) {
3198 Map<String, ArtifactDefinition> deploymentArtifactsS = component.getDeploymentArtifacts();
3199 if (!found && deploymentArtifactsS != null) {
3200 for (Map.Entry<String, ArtifactDefinition> entry : deploymentArtifactsS.entrySet()) {
3201 if (entry.getValue().getUniqueId().equals(artifactId)) {
3207 Map<String, ArtifactDefinition> toscaArtifactsS = component.getToscaArtifacts();
3208 if (!found && toscaArtifactsS != null) {
3209 for (Map.Entry<String, ArtifactDefinition> entry : toscaArtifactsS.entrySet()) {
3210 if (entry.getValue().getUniqueId().equals(artifactId)) {
3216 switch (component.getComponentType()) {
3218 Map<String, InterfaceDefinition> interfaces = ((Resource) component).getInterfaces();
3219 if (!found && interfaces != null) {
3220 for (Map.Entry<String, InterfaceDefinition> entry : interfaces.entrySet()) {
3221 Map<String, Operation> operations = entry.getValue().getOperationsMap();
3222 for (Map.Entry<String, Operation> entryOp : operations.entrySet()) {
3223 if (entryOp.getValue().getImplementation() != null && entryOp.getValue().getImplementation().getUniqueId().equals(artifactId)) {
3232 Map<String, ArtifactDefinition> apiArtifacts = ((Service) component).getServiceApiArtifacts();
3233 if (!found && apiArtifacts != null) {
3234 for (Map.Entry<String, ArtifactDefinition> entry : apiArtifacts.entrySet()) {
3235 if (entry.getValue().getUniqueId().equals(artifactId)) {
3249 private boolean checkArtifactInResourceInstance(Component component, String resourceInstanceId, String artifactId) {
3251 boolean found = false;
3252 List<ComponentInstance> resourceInstances = component.getComponentInstances();
3253 ComponentInstance resourceInstance = null;
3254 for (ComponentInstance ri : resourceInstances) {
3255 if (ri.getUniqueId().equals(resourceInstanceId)) {
3256 resourceInstance = ri;
3260 if (resourceInstance != null) {
3261 Map<String, ArtifactDefinition> artifacts = resourceInstance.getDeploymentArtifacts();
3262 if (artifacts != null) {
3263 for (Map.Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) {
3264 if (entry.getValue().getUniqueId().equals(artifactId)) {
3271 artifacts = resourceInstance.getArtifacts();
3272 if (artifacts != null) {
3273 for (Map.Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) {
3274 if (entry.getValue().getUniqueId().equals(artifactId)) {
3285 private Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists(String componentId, String userId, AuditingActionEnum auditingAction, User user, String artifactId, ComponentTypeEnum componentType,
3286 String containerComponentType, boolean inTransaction) {
3288 ComponentTypeEnum componentForAudit = null == containerComponentType ? componentType : ComponentTypeEnum.findByParamName(containerComponentType);
3289 componentForAudit.getNodeType();
3291 Either<? extends org.openecomp.sdc.be.model.Component, StorageOperationStatus> componentResult = toscaOperationFacade.getToscaFullElement(componentId);
3293 if (componentResult.isRight()) {
3294 ActionStatus status = componentForAudit == ComponentTypeEnum.RESOURCE ? ActionStatus.RESOURCE_NOT_FOUND : componentType == ComponentTypeEnum.SERVICE ? ActionStatus.SERVICE_NOT_FOUND : ActionStatus.PRODUCT_NOT_FOUND;
3295 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, componentId);
3296 log.debug("Service not found, serviceId {}", componentId);
3297 handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentForAudit, null);
3298 return Either.right(responseFormat);
3300 return Either.left(componentResult.left().value());
3303 private Either<Boolean, ResponseFormat> validateWorkOnComponent(org.openecomp.sdc.be.model.Component component, String userId, AuditingActionEnum auditingAction, User user, String artifactId, ArtifactOperationInfo operation,
3304 ComponentTypeEnum componentType) {
3305 if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.Download && !operation.ignoreLifecycleState()) {
3306 Either<Boolean, ResponseFormat> canWork = validateCanWorkOnComponent(component, userId);
3307 if (canWork.isRight()) {
3308 String uniqueId = component.getUniqueId();
3309 log.debug("Service status isn't CHECKOUT or user isn't owner, serviceId {}", uniqueId);
3310 handleAuditing(auditingAction, component, uniqueId, user, null, null, artifactId, canWork.right().value(), component.getComponentType(), null);
3311 return Either.right(canWork.right().value());
3314 return Either.left(true);
3317 private Either<Boolean, ResponseFormat> validateUserRole(User user, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType, ArtifactOperationInfo operation) {
3319 if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.Download) {
3320 String role = user.getRole();
3321 if (!role.equals(Role.ADMIN.name()) && !role.equals(Role.DESIGNER.name())) {
3322 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
3323 log.debug("addArtifact - user isn't permitted to perform operation, userId {}, role {}", user.getUserId(), role);
3324 handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentType, null);
3325 return Either.right(responseFormat);
3328 return Either.left(true);
3331 private Either<User, ResponseFormat> validateUserExists(String userId, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType, boolean inTransaction) {
3332 Either<User, ResponseFormat> validateUserExists = validateUserExists(userId, auditingAction.getName(), inTransaction);
3334 if (validateUserExists.isRight()) {
3335 User user = new User();
3336 user.setUserId(userId);
3337 handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, validateUserExists.right().value(), componentType, null);
3338 return Either.right(validateUserExists.right().value());
3340 return Either.left(validateUserExists.left().value());
3343 protected AuditingActionEnum detectAuditingType(ArtifactOperationInfo operation, String origMd5) {
3344 AuditingActionEnum auditingAction = null;
3345 switch (operation.getArtifactOperationEnum()) {
3347 auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_UPLOAD_BY_API : AuditingActionEnum.ARTIFACT_UPLOAD;
3350 auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_UPLOAD_BY_API : origMd5 == null ? AuditingActionEnum.ARTIFACT_METADATA_UPDATE : AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE;
3353 auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_DELETE_BY_API : AuditingActionEnum.ARTIFACT_DELETE;
3356 auditingAction = operation.isExternalApi() ? AuditingActionEnum.DOWNLOAD_ARTIFACT : AuditingActionEnum.ARTIFACT_DOWNLOAD;
3361 return auditingAction;
3364 private Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifact(ArtifactDefinition artifactDefinition) {
3365 String esArtifactId = artifactDefinition.getEsId();
3366 Either<ESArtifactData, CassandraOperationStatus> artifactfromES = artifactCassandraDao.getArtifact(esArtifactId);
3367 if (artifactfromES.isRight()) {
3368 CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value();
3369 StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
3370 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
3371 log.debug("Error when getting artifact from ES, error: {}", actionStatus.name());
3372 return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, artifactDefinition.getArtifactDisplayName()));
3375 ESArtifactData esArtifactData = artifactfromES.left().value();
3376 byte[] data = esArtifactData.getDataAsArray();
3378 log.debug("Artifact data from ES is null");
3379 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactDefinition.getArtifactDisplayName()));
3381 String artifactName = artifactDefinition.getArtifactName();
3382 log.trace("Download of artifact succeeded, uniqueId {}, artifact file name {}", artifactDefinition.getUniqueId(), artifactName);
3383 return Either.left(new ImmutablePair<String, byte[]>(artifactName, data));
3386 public ESArtifactData createEsArtifactData(ArtifactDataDefinition artifactInfo, byte[] artifactPayload) {
3387 ESArtifactData artifactData = new ESArtifactData(artifactInfo.getEsId(), artifactPayload);
3388 return artifactData;
3391 private boolean saveArtifacts(ESArtifactData artifactData, String resourceId, boolean reload) {
3393 CassandraOperationStatus resourceUploadStatus = artifactCassandraDao.saveArtifact(artifactData);
3395 if (resourceUploadStatus.equals(CassandraOperationStatus.OK)) {
3396 log.debug("Artifact {} was saved in component .", artifactData.getId(), resourceId);
3398 log.info("Failed to save artifact {}.", artifactData.getId());
3404 private boolean isArtifactMetadataUpdate(AuditingActionEnum auditingActionEnum) {
3405 return (auditingActionEnum.equals(AuditingActionEnum.ARTIFACT_METADATA_UPDATE));
3408 private boolean isDeploymentArtifact(ArtifactDefinition artifactInfo) {
3409 return (ArtifactGroupTypeEnum.DEPLOYMENT.equals(artifactInfo.getArtifactGroupType()));
3412 public Either<ArtifactDefinition, ResponseFormat> createArtifactPlaceHolderInfo(String resourceId, String logicalName, Map<String, Object> artifactInfoMap, String userUserId, ArtifactGroupTypeEnum groupType, boolean inTransaction) {
3413 Either<User, ActionStatus> user = userAdminManager.getUser(userUserId, inTransaction);
3414 if (user.isRight()) {
3415 ResponseFormat responseFormat;
3416 if (user.right().value().equals(ActionStatus.USER_NOT_FOUND)) {
3417 log.debug("create artifact placeholder - not authorized user, userId {}", userUserId);
3418 responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
3420 log.debug("create artifact placeholder - failed to authorize user, userId {}", userUserId);
3421 responseFormat = componentsUtils.getResponseFormat(user.right().value());
3423 return Either.right(responseFormat);
3426 ArtifactDefinition artifactDefinition = createArtifactPlaceHolderInfo(resourceId, logicalName, artifactInfoMap, user.left().value(), groupType);
3427 return Either.left(artifactDefinition);
3430 public ArtifactDefinition createArtifactPlaceHolderInfo(String resourceId, String logicalName, Map<String, Object> artifactInfoMap, User user, ArtifactGroupTypeEnum groupType) {
3431 ArtifactDefinition artifactInfo = new ArtifactDefinition();
3433 String artifactName = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_DISPLAY_NAME);
3434 String artifactType = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_TYPE);
3435 String artifactDescription = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_DESCRIPTION);
3437 artifactInfo.setArtifactDisplayName(artifactName);
3438 artifactInfo.setArtifactLabel(logicalName.toLowerCase());
3439 artifactInfo.setArtifactType(artifactType);
3440 artifactInfo.setDescription(artifactDescription);
3441 artifactInfo.setArtifactGroupType(groupType);
3442 nodeTemplateOperation.setDefaultArtifactTimeout(groupType, artifactInfo);
3444 setArtifactPlaceholderCommonFields(resourceId, user, artifactInfo);
3446 return artifactInfo;
3449 private void setArtifactPlaceholderCommonFields(String resourceId, User user, ArtifactDefinition artifactInfo) {
3450 String uniqueId = null;
3452 if (resourceId != null) {
3453 uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId.toLowerCase(), artifactInfo.getArtifactLabel().toLowerCase());
3454 artifactInfo.setUniqueId(uniqueId);
3456 artifactInfo.setUserIdCreator(user.getUserId());
3457 String fullName = user.getFullName();
3458 artifactInfo.setUpdaterFullName(fullName);
3460 long time = System.currentTimeMillis();
3462 artifactInfo.setCreatorFullName(fullName);
3463 artifactInfo.setCreationDate(time);
3465 artifactInfo.setLastUpdateDate(time);
3466 artifactInfo.setUserIdLastUpdater(user.getUserId());
3468 artifactInfo.setMandatory(true);
3471 public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(String parentId, NodeTypeEnum parentType, boolean inTransaction, ArtifactGroupTypeEnum groupType, String instanceId) {
3472 return artifactToscaOperation.getArtifacts(parentId, parentType, groupType, instanceId);
3475 public Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact(ArtifactDefinition artifactHeatEnv, ArtifactDefinition artifact, String componentId, NodeTypeEnum parentType, String instanceId) {
3476 return artifactToscaOperation.addHeatEnvArtifact(artifactHeatEnv, artifact, componentId, parentType, true, instanceId);
3479 private Either<ESArtifactData, ResponseFormat> createEsHeatEnvArtifactDataFromString(ArtifactDefinition artifactDefinition, String payloadStr) {
3481 byte[] payload = payloadStr.getBytes();
3483 ESArtifactData artifactData = createEsArtifactData(artifactDefinition, payload);
3484 return Either.left(artifactData);
3489 * @param artifactDefinition
3492 public Either<ArtifactDefinition, ResponseFormat> generateHeatEnvArtifact(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier,
3493 boolean shouldLock, String instanceId) {
3494 String payload = generateHeatEnvPayload(artifactDefinition);
3495 String prevUUID = artifactDefinition.getArtifactUUID();
3496 ArtifactDefinition clonedBeforeGenerate = new ArtifactDefinition(artifactDefinition);
3497 Either<ArtifactDefinition, ResponseFormat> generateResult = generateAndSaveHeatEnvArtifact(artifactDefinition, payload, componentType, component, resourceInstanceName, modifier, shouldLock, instanceId);
3498 if (generateResult.isLeft()) {
3499 ArtifactDefinition updatedArtDef = generateResult.left().value();
3500 if (!prevUUID.equals(updatedArtDef.getArtifactUUID())) {
3501 List<ComponentInstance> componentInstances = component.getComponentInstances();
3502 if (componentInstances != null) {
3503 Optional<ComponentInstance> findFirst = componentInstances.stream().filter(ci -> ci.getUniqueId().equals(instanceId)).findFirst();
3504 if (findFirst.isPresent()) {
3505 ComponentInstance relevantInst = findFirst.get();
3506 List<GroupInstance> updatedGroupInstances = getUpdatedGroupInstances(updatedArtDef.getUniqueId(), clonedBeforeGenerate, relevantInst.getGroupInstances());
3508 if (CollectionUtils.isNotEmpty(updatedGroupInstances)) {
3509 updatedGroupInstances.forEach(gi -> {
3510 gi.getGroupInstanceArtifacts().add(updatedArtDef.getUniqueId());
3511 gi.getGroupInstanceArtifactsUuid().add(updatedArtDef.getArtifactUUID());
3513 Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(component, componentType, instanceId, updatedGroupInstances);
3514 if (status.isRight()) {
3515 log.debug("Failed to update groups of the component {}. ", component.getUniqueId());
3516 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status.right().value()), clonedBeforeGenerate.getArtifactDisplayName());
3517 return Either.right(responseFormat);
3525 return generateResult;
3528 private String generateHeatEnvPayload(ArtifactDefinition artifactDefinition) {
3529 List<HeatParameterDefinition> heatParameters = artifactDefinition.getListHeatParameters();
3530 StringBuilder sb = new StringBuilder();
3531 sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactHeader());
3532 sb.append("parameters:\n");
3533 if (heatParameters != null) {
3534 heatParameters.sort(Comparator.comparing(e -> e.getName()));
3536 List<HeatParameterDefinition> empltyHeatValues = new ArrayList<>();
3538 for (HeatParameterDefinition heatParameterDefinition : heatParameters) {
3540 String heatValue = heatParameterDefinition.getCurrentValue();
3541 if (!ValidationUtils.validateStringNotEmpty(heatValue)) {
3542 heatValue = heatParameterDefinition.getDefaultValue();
3543 if (!ValidationUtils.validateStringNotEmpty(heatValue)) {
3544 empltyHeatValues.add(heatParameterDefinition);
3548 HeatParameterType type = HeatParameterType.isValidType(heatParameterDefinition.getType());
3552 sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(Boolean.parseBoolean(heatValue)).append("\n");
3555 sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(new BigDecimal(heatValue).toPlainString()).append("\n");
3557 case COMMA_DELIMITED_LIST:
3559 sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(heatValue).append("\n");
3562 String value = heatValue;
3563 boolean starts = value.startsWith("\"");
3564 boolean ends = value.endsWith("\"");
3565 if (!(starts && ends)) {
3566 starts = value.startsWith("'");
3567 ends = value.endsWith("'");
3568 if (!(starts && ends)) {
3569 value = "\"" + value + "\"";
3572 sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(value);
3579 if (!empltyHeatValues.isEmpty()) {
3580 empltyHeatValues.sort(Comparator.comparing(e -> e.getName()));
3581 empltyHeatValues.forEach(hv -> {
3582 sb.append(" ").append(hv.getName()).append(":");
3583 HeatParameterType type = HeatParameterType.isValidType(hv.getType());
3584 if (type != null && type == HeatParameterType.STRING && (hv.getCurrentValue() != null && "".equals(hv.getCurrentValue()) || hv.getDefaultValue() != null && "".equals(hv.getDefaultValue()))) {
3585 sb.append(" \"\"").append("\n");
3587 sb.append(" ").append("\n");
3592 sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactFooter());
3595 String result = sb.toString().replaceAll("\\\\n", "\n");
3602 * @param artifactDefinition
3606 public Either<ArtifactDefinition, ResponseFormat> generateAndSaveHeatEnvArtifact(ArtifactDefinition artifactDefinition, String payload, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName,
3607 User modifier, boolean shouldLock, String instanceId) {
3608 return generateArtifactPayload(artifactDefinition, componentType, component, resourceInstanceName, modifier, shouldLock, () -> artifactDefinition.getHeatParamsUpdateDate(),
3609 () -> createEsHeatEnvArtifactDataFromString(artifactDefinition, payload), instanceId);
3613 protected Either<ArtifactDefinition, ResponseFormat> generateArtifactPayload(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier,
3614 boolean shouldLock, Supplier<Long> payloadUpdateDateGen, Supplier<Either<ESArtifactData, ResponseFormat>> esDataCreator, String instanceId) {
3616 log.trace("Start generating payload for {} artifact {}", artifactDefinition.getArtifactType(), artifactDefinition.getEsId());
3617 if (artifactDefinition.getPayloadUpdateDate() == null || artifactDefinition.getPayloadUpdateDate() == 0 || artifactDefinition.getPayloadUpdateDate() <= payloadUpdateDateGen.get()) {
3619 log.trace("Generating payload for {} artifact {}", artifactDefinition.getArtifactType(), artifactDefinition.getEsId());
3620 Either<ESArtifactData, ResponseFormat> artifactDataRes = esDataCreator.get();
3621 ESArtifactData artifactData = null;
3623 if (artifactDataRes.isLeft()) {
3624 artifactData = artifactDataRes.left().value();
3626 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
3627 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
3628 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
3630 return Either.right(artifactDataRes.right().value());
3632 String newCheckSum = GeneralUtility.calculateMD5ByByteArray(artifactData.getDataAsArray());
3634 String esArtifactId = artifactDefinition.getEsId();
3635 Either<ESArtifactData, CassandraOperationStatus> artifactfromES;
3636 ESArtifactData esArtifactData;
3637 if (esArtifactId != null && !esArtifactId.isEmpty() && artifactDefinition.getPayloadData() == null) {
3638 artifactfromES = artifactCassandraDao.getArtifact(esArtifactId);
3639 if (artifactfromES.isRight()) {
3640 CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value();
3641 StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
3642 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
3643 log.debug("Error when getting artifact from ES, error: {}", actionStatus.name());
3644 return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, artifactDefinition.getArtifactDisplayName()));
3646 esArtifactData = artifactfromES.left().value();
3647 oldCheckSum = GeneralUtility.calculateMD5ByByteArray(esArtifactData.getDataAsArray());
3649 oldCheckSum = artifactDefinition.getArtifactChecksum();
3652 Either<ArtifactDefinition, StorageOperationStatus> updateArifactDefinitionStatus = null;
3655 Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, "Update Artifact - lock resource: ");
3656 if (lockComponent.isRight()) {
3657 handleAuditing(AuditingActionEnum.ARTIFACT_METADATA_UPDATE, component, component.getUniqueId(), modifier, null, null, artifactDefinition.getUniqueId(), lockComponent.right().value(), component.getComponentType(), null);
3658 return Either.right(lockComponent.right().value());
3662 if (oldCheckSum != null && oldCheckSum.equals(newCheckSum)) {
3664 artifactDefinition.setPayloadUpdateDate(payloadUpdateDateGen.get());
3665 updateArifactDefinitionStatus = artifactToscaOperation.updateArifactOnResource(artifactDefinition, component.getUniqueId(), artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId);
3666 log.trace("No real update done in payload for {} artifact, updating payloadUpdateDate {}", artifactDefinition.getArtifactType(), artifactDefinition.getEsId());
3667 if (updateArifactDefinitionStatus.isRight()) {
3668 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus.right().value()), artifactDefinition.getArtifactDisplayName());
3669 log.trace("Failed to update payloadUpdateDate {}", artifactDefinition.getEsId());
3670 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
3671 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
3673 return Either.right(responseFormat);
3677 oldCheckSum = artifactDefinition.getArtifactChecksum();
3678 artifactDefinition.setArtifactChecksum(newCheckSum);
3679 // artifactToscaOperation.updateUUID(artifactDefinition, oldCheckSum, artifactDefinition.getArtifactVersion());
3680 artifactDefinition.setEsId(artifactDefinition.getUniqueId());
3681 log.trace("No real update done in payload for {} artifact, updating payloadUpdateDate {}", artifactDefinition.getArtifactType(), artifactDefinition.getEsId());
3682 updateArifactDefinitionStatus = artifactToscaOperation.updateArifactOnResource(artifactDefinition, component.getUniqueId(), artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId);
3684 log.trace("Update Payload ", artifactDefinition.getEsId());
3686 if (updateArifactDefinitionStatus != null && updateArifactDefinitionStatus.isLeft()) {
3688 artifactDefinition = updateArifactDefinitionStatus.left().value();
3689 artifactData.setId(artifactDefinition.getUniqueId());
3690 CassandraOperationStatus saveArtifactStatus = artifactCassandraDao.saveArtifact(artifactData);
3692 if (saveArtifactStatus.equals(CassandraOperationStatus.OK)) {
3694 log.debug("Artifact Saved In ES {}", artifactData.getId());
3695 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
3696 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
3697 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
3700 titanDao.rollback();
3701 log.info("Failed to save artifact {}.", artifactData.getId());
3702 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
3703 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
3704 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
3706 return Either.right(responseFormat);
3709 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus.right().value()), artifactDefinition.getArtifactDisplayName());
3710 log.debug("Failed To update artifact {}", artifactData.getId());
3711 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
3712 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
3714 return Either.right(responseFormat);
3719 graphLockOperation.unlockComponent(component.getUniqueId(), component.getComponentType().getNodeType());
3724 return Either.left(artifactDefinition);
3727 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdateHeatEnv(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType,
3728 org.openecomp.sdc.be.model.Component parent, String originData, String origMd5, ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) {
3729 convertParentType(componentType);
3730 String parentId = parent.getUniqueId();
3731 // Either<ArtifactDefinition, StorageOperationStatus> artifactRes = this.artifactToscaOperation.getArtifactById(componentId, artifactId);
3732 ArtifactDefinition currArtifact = artifactInfo;
3734 if (origMd5 != null) {
3735 Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
3736 if (validateMd5.isRight()) {
3737 ResponseFormat responseFormat = validateMd5.right().value();
3738 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
3739 return Either.right(responseFormat);
3742 if (artifactInfo.getPayloadData() != null && artifactInfo.getPayloadData().length != 0) {
3743 Either<Boolean, ResponseFormat> deploymentValidationResult = validateDeploymentArtifact(parent, componentId, user.getUserId(), false, artifactInfo, currArtifact, NodeTypeEnum.ResourceInstance);
3744 if (deploymentValidationResult.isRight()) {
3745 ResponseFormat responseFormat = deploymentValidationResult.right().value();
3746 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
3747 return Either.right(responseFormat);
3750 Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
3751 if (payloadEither.isRight()) {
3752 ResponseFormat responseFormat = payloadEither.right().value();
3753 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
3754 return Either.right(responseFormat);
3756 } else { // duplicate
3757 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
3758 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
3759 return Either.right(responseFormat);
3765 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Update Artifact - lock ");
3766 if (lockComponent.isRight()) {
3767 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right().value(), componentType, null);
3768 return Either.right(lockComponent.right().value());
3771 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
3773 resultOp = updateHeatEnvParams(componentId, artifactId, artifactInfo, user, auditingAction, parent, componentType, currArtifact, origMd5, inTransaction);
3778 if (resultOp == null || resultOp.isRight()) {
3779 log.debug("all changes rollback");
3780 if (false == inTransaction)
3781 titanDao.rollback();
3783 log.debug("all changes committed");
3784 if (false == inTransaction)
3788 componentType = parent.getComponentType();
3789 NodeTypeEnum nodeType = componentType.getNodeType();
3790 graphLockOperation.unlockComponent(parent.getUniqueId(), nodeType);
3791 // graphLockOperation.unlockComponent(parentId, parentType);
3795 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateHeatEnvParams(String componentId, String artifactId, ArtifactDefinition artifactInfo, User user, AuditingActionEnum auditingAction, Component parent,
3796 ComponentTypeEnum componentType, ArtifactDefinition currArtifact1, String origMd5, boolean inTransaction) {
3798 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
3799 Either<ArtifactDefinition, Operation> insideEither = null;
3801 * currently getArtifactById does not retrieve heatParameters Either<ArtifactDefinition, StorageOperationStatus> artifactRes = artifactOperation.getArtifactById(artifactId, false); ArtifactDefinition currArtifact = artifactRes.left().value();
3803 Either<ComponentInstance, ResponseFormat> getRI = getRIFromComponent(parent, componentId, artifactId, auditingAction, user);
3804 if (getRI.isRight()) {
3805 return Either.right(getRI.right().value());
3807 ComponentInstance ri = getRI.left().value();
3808 Either<ArtifactDefinition, ResponseFormat> getArtifactRes = getArtifactFromRI(parent, ri, componentId, artifactId, auditingAction, user);
3809 if (getArtifactRes.isRight()) {
3810 return Either.right(getArtifactRes.right().value());
3812 ArtifactDefinition currArtifact = getArtifactRes.left().value();
3814 if (currArtifact.getArtifactType().equals(ArtifactTypeEnum.HEAT.getType()) || currArtifact.getArtifactType().equals(ArtifactTypeEnum.HEAT_VOL.getType()) || currArtifact.getArtifactType().equals(ArtifactTypeEnum.HEAT_NET.getType())) {
3815 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
3816 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
3817 return Either.right(responseFormat);
3819 List<HeatParameterDefinition> currentHeatEnvParams = currArtifact.getListHeatParameters();
3820 List<HeatParameterDefinition> updatedHeatEnvParams = artifactInfo.getListHeatParameters();
3821 new ArrayList<HeatParameterDefinition>();
3824 if (origMd5 != null) {
3825 Either<List<HeatParameterDefinition>, ResponseFormat> uploadParamsValidationResult = validateUploadParamsFromEnvFile(auditingAction, parent, user, artifactInfo, artifactId, componentType, ri.getName(), currentHeatEnvParams,
3826 updatedHeatEnvParams, currArtifact.getArtifactName());
3827 if (uploadParamsValidationResult.isRight()) {
3828 ResponseFormat responseFormat = uploadParamsValidationResult.right().value();
3829 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
3830 return Either.right(responseFormat);
3832 artifactInfo.setListHeatParameters(updatedHeatEnvParams);
3835 Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers = validateAndConvertHeatParamers(artifactInfo, ArtifactTypeEnum.HEAT_ENV.getType());
3836 if (validateAndConvertHeatParamers.isRight()) {
3837 ResponseFormat responseFormat = validateAndConvertHeatParamers.right().value();
3838 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
3839 return Either.right(responseFormat);
3842 if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty()) {
3844 // fill reduced heat env parameters List for updating
3845 for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) {
3846 paramName = heatEnvParam.getName();
3847 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
3848 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
3849 String updatedParamValue = heatEnvParam.getCurrentValue();
3850 if (updatedParamValue != null && updatedParamValue.equals("")) { // reset
3851 currHeatParam.setCurrentValue(heatEnvParam.getDefaultValue());
3852 } else if (updatedParamValue != null) {
3853 currHeatParam.setCurrentValue(updatedParamValue);
3858 currArtifact.setHeatParamsUpdateDate(System.currentTimeMillis());
3859 currArtifact.setListHeatParameters(currentHeatEnvParams);
3861 Either<ArtifactDefinition, StorageOperationStatus> updateArifactRes = artifactToscaOperation.updateArifactOnResource(currArtifact, parent.getUniqueId(), currArtifact.getUniqueId(), componentType.getNodeType(), componentId);
3862 if (updateArifactRes.isRight()) {
3863 log.debug("Failed to update artifact on graph - {}", artifactId);
3864 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateArifactRes.right().value()));
3865 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
3866 return Either.right(responseFormat);
3868 StorageOperationStatus error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), ri.getUniqueId(), componentType);
3869 if (error != StorageOperationStatus.OK) {
3870 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
3871 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
3872 return Either.right(responseFormat);
3875 error = generateCustomizationUUIDOnGroupInstance(ri, updateArifactRes.left().value().getUniqueId(), parent.getUniqueId());
3876 if (error != StorageOperationStatus.OK) {
3877 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
3878 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
3879 return Either.right(responseFormat);
3885 insideEither = Either.left(currArtifact);
3886 resultOp = Either.left(insideEither);
3887 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
3888 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currArtifact, null, artifactId, responseFormat, componentType, ri.getName());
3892 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateHeatParams(String componentId, String artifactId, ArtifactDefinition artifactEnvInfo, User user, AuditingActionEnum auditingAction, Component parent,
3893 ComponentTypeEnum componentType, ArtifactDefinition currHeatArtifact, String origMd5, boolean needToUpdateGroup) {
3895 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
3896 Either<ArtifactDefinition, Operation> insideEither = null;
3898 * currently getArtifactById does not retrieve heatParameters Either<ArtifactDefinition, StorageOperationStatus> artifactRes = artifactOperation.getArtifactById(artifactId, false); ArtifactDefinition currArtifact = artifactRes.left().value();
3900 String currentHeatId = currHeatArtifact.getUniqueId();
3902 String esArtifactId = currHeatArtifact.getEsId();
3903 Either<ESArtifactData, CassandraOperationStatus> artifactfromES = artifactCassandraDao.getArtifact(esArtifactId);
3904 if (artifactfromES.isRight()) {
3905 CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value();
3906 StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
3907 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
3908 log.debug("Error when getting artifact from ES, error: {}", actionStatus.name());
3909 return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, currHeatArtifact.getArtifactDisplayName()));
3912 ESArtifactData esArtifactData = artifactfromES.left().value();
3913 byte[] data = esArtifactData.getDataAsArray();
3916 ArtifactDefinition updatedHeatArt = currHeatArtifact;
3918 List<HeatParameterDefinition> updatedHeatEnvParams = artifactEnvInfo.getListHeatParameters();
3919 List<HeatParameterDefinition> currentHeatEnvParams = currHeatArtifact.getListHeatParameters();
3920 List<HeatParameterDefinition> newHeatEnvParams = new ArrayList<HeatParameterDefinition>();
3922 if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty() && currentHeatEnvParams != null && !currentHeatEnvParams.isEmpty()) {
3925 for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) {
3927 paramName = heatEnvParam.getName();
3928 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
3929 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
3931 String updatedParamValue = heatEnvParam.getCurrentValue();
3932 if (updatedParamValue == null)
3933 updatedParamValue = heatEnvParam.getDefaultValue();
3934 HeatParameterType paramType = HeatParameterType.isValidType(currHeatParam.getType());
3935 if (!paramType.getValidator().isValid(updatedParamValue, null)) {
3936 ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE;
3937 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, ArtifactTypeEnum.HEAT_ENV.getType(), paramType.getType(), paramName);
3938 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactEnvInfo, null, artifactId, responseFormat, componentType, "");
3939 return Either.right(responseFormat);
3942 currHeatParam.setCurrentValue(paramType.getConverter().convert(updatedParamValue, null, null));
3943 newHeatEnvParams.add(currHeatParam);
3948 if (!newHeatEnvParams.isEmpty()) {
3949 currHeatArtifact.setListHeatParameters(currentHeatEnvParams);
3950 Either<ArtifactDefinition, StorageOperationStatus> operationStatus = artifactToscaOperation.updateArifactOnResource(currHeatArtifact, parent.getUniqueId(), currHeatArtifact.getUniqueId(), componentType.getNodeType(), componentId);
3952 if (operationStatus.isRight()) {
3953 log.debug("Failed to update artifact on graph - {}", currHeatArtifact.getUniqueId());
3955 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(operationStatus.right().value()));
3956 return Either.right(responseFormat);
3959 updatedHeatArt = operationStatus.left().value();
3961 if (!updatedHeatArt.getDuplicated() || esArtifactData.getId() == null)
3962 esArtifactData.setId(updatedHeatArt.getEsId());
3963 res = saveArtifacts(esArtifactData, parent.getUniqueId(), false);
3966 log.debug("Artifact saved into ES - {}", updatedHeatArt.getUniqueId());
3967 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
3968 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, updatedHeatArt, currentHeatId, updatedHeatArt.getUniqueId(), responseFormat, componentType, null);
3969 // resultOp = Either.left(result.left().value());
3972 BeEcompErrorManager.getInstance().logBeDaoSystemError("Update Artifact");
3973 log.debug("Failed to save the artifact.");
3974 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
3975 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, updatedHeatArt, currentHeatId, updatedHeatArt.getUniqueId(), responseFormat, componentType, null);
3976 resultOp = Either.right(responseFormat);
3980 insideEither = Either.left(updatedHeatArt);
3983 Either<ArtifactDefinition, StorageOperationStatus> updateHeatEnvArtifact;
3984 if (!currentHeatId.equals(updatedHeatArt.getUniqueId())) {
3985 artifactEnvInfo.setArtifactChecksum(null);
3986 updateHeatEnvArtifact = artifactToscaOperation.updateHeatEnvArtifact(parent.getUniqueId(), artifactEnvInfo, currentHeatId, updatedHeatArt.getUniqueId(), componentType.getNodeType(), componentId);
3988 updateHeatEnvArtifact = artifactToscaOperation.updateHeatEnvPlaceholder(artifactEnvInfo, componentId, componentType.getNodeType());
3991 if (needToUpdateGroup && updateHeatEnvArtifact.isLeft()) {
3992 ActionStatus result = updateGroupForHeat(currHeatArtifact, updatedHeatArt, artifactEnvInfo, updateHeatEnvArtifact.left().value(), parent, componentType);
3993 if (result != ActionStatus.OK) {
3994 ResponseFormat responseFormat = componentsUtils.getResponseFormat(result);
3995 return Either.right(responseFormat);
3999 if (updatedHeatEnvParams.isEmpty()) {
4000 return getResponseAndAuditInvalidEmptyHeatEnvFile(auditingAction, parent, parent.getUniqueId(), user, currHeatArtifact, artifactId, componentType);
4002 resultOp = Either.left(insideEither);
4003 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
4004 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currHeatArtifact, null, artifactId, responseFormat, componentType, "");
4009 private Either<Either<ArtifactDefinition,Operation>,ResponseFormat> getResponseAndAuditInvalidEmptyHeatEnvFile(AuditingActionEnum auditingAction, Component parent, String uniqueId, User user, ArtifactDefinition currHeatArtifact, String artifactId, ComponentTypeEnum componentType) {
4010 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML);
4011 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currHeatArtifact, null, artifactId, responseFormat, componentType, "");
4012 return Either.right(responseFormat);
4016 private StorageOperationStatus generateCustomizationUUIDOnGroupInstance(ComponentInstance ri, String artifactId, String componentId) {
4017 StorageOperationStatus error = StorageOperationStatus.OK;
4018 log.debug("Need to re-generate customization UUID for group instance on component instance {}", ri.getUniqueId());
4019 List<GroupInstance> groupsInstances = ri.getGroupInstances();
4020 // List<GroupInstance> associatedGroups = null;
4021 List<String> groupInstancesId = null;
4022 if (groupsInstances != null && !groupsInstances.isEmpty()) {
4023 groupInstancesId = groupsInstances.stream().filter(p -> p.getGroupInstanceArtifacts() != null && p.getGroupInstanceArtifacts().contains(artifactId)).map(p -> p.getUniqueId()).collect(Collectors.toList());
4025 if (groupInstancesId != null && !groupInstancesId.isEmpty()) {
4026 // associatedGroups.stream().forEach(c -> this.groupInstanceOperation.updateCustomizationUUID(c.getUniqueId()));
4027 toscaOperationFacade.generateCustomizationUUIDOnInstanceGroup(componentId, ri.getUniqueId(), groupInstancesId);
4033 public Either<List<HeatParameterDefinition>, ResponseFormat> validateUploadParamsFromEnvFile(AuditingActionEnum auditingAction, Component parent, User user, ArtifactDefinition artifactInfo, String artifactId, ComponentTypeEnum componentType,
4034 String riName, List<HeatParameterDefinition> currentHeatEnvParams, List<HeatParameterDefinition> updatedHeatEnvParams, String currArtifactName) {
4036 if (updatedHeatEnvParams == null || updatedHeatEnvParams.isEmpty()) {
4037 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactInfo.getArtifactName(), currArtifactName);
4038 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, riName);
4039 return Either.right(responseFormat);
4042 for (HeatParameterDefinition uploadedHeatParam : updatedHeatEnvParams) {
4043 String paramName = uploadedHeatParam.getName();
4044 boolean isExistsInHeat = false;
4045 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
4046 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
4048 isExistsInHeat = true;
4049 uploadedHeatParam.setType(currHeatParam.getType());
4050 uploadedHeatParam.setCurrentValue(uploadedHeatParam.getDefaultValue());
4051 uploadedHeatParam.setDefaultValue(currHeatParam.getDefaultValue());
4052 uploadedHeatParam.setUniqueId(currHeatParam.getUniqueId());
4056 if (!isExistsInHeat) {
4057 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, currArtifactName);
4058 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, riName);
4059 return Either.right(responseFormat);
4062 return Either.left(updatedHeatEnvParams);
4065 private Either<ComponentInstance, ResponseFormat> getRIFromComponent(Component component, String riID, String artifactId, AuditingActionEnum auditingAction, User user) {
4066 ResponseFormat responseFormat = null;
4067 List<ComponentInstance> ris = component.getComponentInstances();
4068 for (ComponentInstance ri : ris) {
4069 if (riID.equals(ri.getUniqueId())) {
4070 return Either.left(ri);
4073 responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, riID);
4074 log.debug("Resource Instance not found, resourceInstanceId {}", riID);
4075 handleAuditing(auditingAction, null, riID, user, null, null, artifactId, responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE, null);
4076 return Either.right(responseFormat);
4079 private Either<ArtifactDefinition, ResponseFormat> getArtifactFromRI(Component component, ComponentInstance ri, String riID, String artifactId, AuditingActionEnum auditingAction, User user) {
4080 ResponseFormat responseFormat = null;
4081 Map<String, ArtifactDefinition> rtifactsMap = ri.getDeploymentArtifacts();
4082 for (ArtifactDefinition artifact : rtifactsMap.values()) {
4083 if (artifactId.equals(artifact.getUniqueId())) {
4084 return Either.left(artifact);
4087 responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, riID, component.getUniqueId());
4088 handleAuditing(auditingAction, component, riID, user, null, null, artifactId, responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE, ri.getName());
4089 return Either.right(responseFormat);
4092 public ArtifactDefinition extractArtifactDefinition(Either<ArtifactDefinition, Operation> eitherArtifact) {
4093 ArtifactDefinition ret;
4094 if (eitherArtifact.isLeft()) {
4095 ret = eitherArtifact.left().value();
4097 ret = eitherArtifact.right().value().getImplementationArtifact();
4103 * downloads artifact of component by UUIDs
4105 * @param componentType
4106 * @param componentUuid
4107 * @param artifactUUID
4108 * @param auditAdditionalParam
4111 public Either<byte[], ResponseFormat> downloadComponentArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String artifactUUID, Map<AuditingFieldsKeysEnum, Object> auditAdditionalParam) {
4112 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4113 Either<byte[], ResponseFormat> result;
4114 byte[] downloadedArtifact = null;
4115 Component component = getComponentByUuid(componentType, componentUuid, errorWrapper);
4116 if (errorWrapper.isEmpty()) {
4117 auditAdditionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, component.getName());
4118 downloadedArtifact = downloadArtifact(component.getAllArtifacts(), artifactUUID, errorWrapper, component.getName());
4120 if (errorWrapper.isEmpty()) {
4121 result = Either.left(downloadedArtifact);
4123 result = Either.right(errorWrapper.getInnerElement());
4129 * downloads an artifact of resource instance of component by UUIDs
4131 * @param componentType
4132 * @param componentUuid
4133 * @param resourceName
4134 * @param artifactUUID
4135 * @param auditAdditionalParam
4138 public Either<byte[], ResponseFormat> downloadResourceInstanceArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID, Map<AuditingFieldsKeysEnum, Object> auditAdditionalParam) {
4139 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4140 Either<byte[], ResponseFormat> result;
4141 byte[] downloadedArtifact = null;
4142 ComponentInstance resourceInstance = getRelatedComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
4143 if (errorWrapper.isEmpty()) {
4144 downloadedArtifact = downloadArtifact(resourceInstance.getDeploymentArtifacts(), artifactUUID, errorWrapper, resourceInstance.getName());
4146 if (errorWrapper.isEmpty()) {
4147 result = Either.left(downloadedArtifact);
4149 result = Either.right(errorWrapper.getInnerElement());
4155 * uploads an artifact to a component by UUID
4159 * @param componentType
4160 * @param componentUuid
4161 * @param additionalParams
4165 public Either<ArtifactDefinition, ResponseFormat> uploadArtifactToComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, Map<AuditingFieldsKeysEnum, Object> additionalParams,
4166 ArtifactOperationInfo operation) {
4167 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4168 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4169 Either<ArtifactDefinition, ResponseFormat> uploadArtifactResult;
4170 ArtifactDefinition uploadArtifact = null;
4171 Component component = null;
4172 String componentId = null;
4173 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
4174 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4175 String userId = request.getHeader(Constants.USER_ID_HEADER);
4177 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4178 if (getComponentRes.isRight()) {
4179 StorageOperationStatus status = getComponentRes.right().value();
4180 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4181 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), componentUuid));
4183 if (errorWrapper.isEmpty()) {
4184 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
4185 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
4187 if (!getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4188 component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
4189 if (component != null) {
4190 componentId = component.getUniqueId();
4191 componentName = component.getName();
4194 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentName);
4196 if (errorWrapper.isEmpty()) {
4197 actionResult = handleArtifactRequest(componentId, userId, componentType, operation, null, artifactInfo, origMd5, data, null, null, null, null);
4198 if (actionResult.isRight()) {
4199 log.debug("Failed to upload artifact to component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, actionResult.right().value());
4200 errorWrapper.setInnerElement(actionResult.right().value());
4203 if (errorWrapper.isEmpty()) {
4204 uploadArtifact = actionResult.left().value().left().value();
4205 uploadArtifactResult = Either.left(uploadArtifact);
4207 uploadArtifactResult = Either.right(errorWrapper.getInnerElement());
4209 updateAuditParametersWithArtifactDefinition(additionalParams, uploadArtifact);
4210 return uploadArtifactResult;
4214 * upload an artifact to a resource instance by UUID
4218 * @param componentType
4219 * @param componentUuid
4220 * @param resourceInstanceName
4221 * @param additionalParams
4225 public Either<ArtifactDefinition, ResponseFormat> uploadArtifactToRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName,
4226 Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
4227 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4228 Either<ArtifactDefinition, ResponseFormat> uploadArtifactResult;
4229 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4230 ArtifactDefinition uploadArtifact = null;
4231 Component component = null;
4232 String componentInstanceId;
4234 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4235 String userId = request.getHeader(Constants.USER_ID_HEADER);
4237 ImmutablePair<Component, ComponentInstance> componentRiPair = null;
4238 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4239 if (getComponentRes.isRight()) {
4240 StorageOperationStatus status = getComponentRes.right().value();
4241 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4242 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), resourceInstanceName));
4244 if (errorWrapper.isEmpty() && !getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4245 component = checkoutParentComponent(componentType, getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(), userId, errorWrapper);
4247 if (errorWrapper.isEmpty()) {
4248 if (component == null) {
4249 componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
4251 componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
4254 if (errorWrapper.isEmpty()) {
4255 componentInstanceId = componentRiPair.getRight().getUniqueId();
4256 componentId = componentRiPair.getLeft().getUniqueId();
4257 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
4259 actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, null, artifactInfo, origMd5, data, null, null, componentId, ComponentTypeEnum.findParamByType(componentType));
4260 if (actionResult.isRight()) {
4261 log.debug("Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. ", resourceInstanceName, componentType, componentUuid, actionResult.right().value());
4262 errorWrapper.setInnerElement(actionResult.right().value());
4265 if (errorWrapper.isEmpty()) {
4266 uploadArtifact = actionResult.left().value().left().value();
4267 uploadArtifactResult = Either.left(uploadArtifact);
4269 uploadArtifactResult = Either.right(errorWrapper.getInnerElement());
4271 updateAuditParametersWithArtifactDefinition(additionalParams, uploadArtifact);
4272 return uploadArtifactResult;
4276 * updates an artifact on a component by UUID
4280 * @param componentType
4281 * @param componentUuid
4282 * @param artifactUUID
4283 * @param additionalParams
4288 public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID,
4289 Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
4290 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4291 Either<ArtifactDefinition, ResponseFormat> updateArtifactResult;
4292 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4293 ArtifactDefinition updateArtifact = null;
4294 Component component = null;
4295 String componentId = null;
4296 String artifactId = null;
4297 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinitionForUpdate(data, ArtifactDefinition.class);
4298 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4299 String userId = request.getHeader(Constants.USER_ID_HEADER);
4301 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4302 if (getComponentRes.isRight()) {
4303 StorageOperationStatus status = getComponentRes.right().value();
4304 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4305 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4307 if (errorWrapper.isEmpty()) {
4308 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
4309 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
4311 if (!getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4312 component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
4313 if (component != null) {
4314 componentId = component.getUniqueId();
4315 componentName = component.getName();
4318 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentName);
4320 if (errorWrapper.isEmpty()) {
4321 artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentId, componentType);
4323 if (errorWrapper.isEmpty()) {
4324 actionResult = handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, origMd5, data, null, null, null, null);
4325 if (actionResult.isRight()) {
4326 log.debug("Failed to upload artifact to component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, actionResult.right().value());
4327 errorWrapper.setInnerElement(actionResult.right().value());
4330 if (errorWrapper.isEmpty()) {
4331 updateArtifact = actionResult.left().value().left().value();
4332 updateArtifactResult = Either.left(updateArtifact);
4335 updateArtifactResult = Either.right(errorWrapper.getInnerElement());
4337 updateAuditParametersWithArtifactDefinition(additionalParams, updateArtifact);
4338 return updateArtifactResult;
4342 * updates an artifact on a resource instance by UUID
4346 * @param componentType
4347 * @param componentUuid
4348 * @param resourceInstanceName
4349 * @param artifactUUID
4350 * @param additionalParams
4355 public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID,
4356 Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
4358 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4359 Either<ArtifactDefinition, ResponseFormat> updateArtifactResult;
4360 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4361 ArtifactDefinition updateArtifact = null;
4362 Component component = null;
4363 String componentInstanceId = null;
4364 String componentId = null;
4365 String artifactId = null;
4366 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4367 String userId = request.getHeader(Constants.USER_ID_HEADER);
4369 ImmutablePair<Component, ComponentInstance> componentRiPair = null;
4370 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4371 if (getComponentRes.isRight()) {
4372 StorageOperationStatus status = getComponentRes.right().value();
4373 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4374 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4376 if (errorWrapper.isEmpty() && !getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4377 component = checkoutParentComponent(componentType, getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(), userId, errorWrapper);
4379 if (errorWrapper.isEmpty()) {
4380 if (component == null) {
4381 componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
4383 componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
4386 if (errorWrapper.isEmpty()) {
4387 componentInstanceId = componentRiPair.getRight().getUniqueId();
4388 componentId = componentRiPair.getLeft().getUniqueId();
4389 artifactId = findArtifactId(componentRiPair.getRight(), artifactUUID, errorWrapper);
4391 if (errorWrapper.isEmpty()) {
4392 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
4394 actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, artifactInfo, origMd5, data, null, null, componentId, ComponentTypeEnum.findParamByType(componentType));
4395 if (actionResult.isRight()) {
4396 log.debug("Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. ", resourceInstanceName, componentType, componentUuid, actionResult.right().value());
4397 errorWrapper.setInnerElement(actionResult.right().value());
4400 if (errorWrapper.isEmpty()) {
4401 updateArtifact = actionResult.left().value().left().value();
4402 updateArtifactResult = Either.left(updateArtifact);
4404 updateArtifactResult = Either.right(errorWrapper.getInnerElement());
4406 updateAuditParametersWithArtifactDefinition(additionalParams, updateArtifact);
4407 return updateArtifactResult;
4411 * deletes an artifact on a component by UUID
4414 * @param componentType
4415 * @param componentUuid
4416 * @param artifactUUID
4417 * @param additionalParams
4422 public Either<ArtifactDefinition, ResponseFormat> deleteArtifactOnComponentByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID, Map<AuditingFieldsKeysEnum, Object> additionalParams,
4423 ArtifactOperationInfo operation) {
4425 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4426 Either<ArtifactDefinition, ResponseFormat> deleteArtifactResult;
4427 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4428 ArtifactDefinition deleteArtifact = null;
4429 Component component = null;
4430 String componentId = null;
4431 String artifactId = null;
4432 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4433 String userId = request.getHeader(Constants.USER_ID_HEADER);
4435 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4436 if (getComponentRes.isRight()) {
4437 StorageOperationStatus status = getComponentRes.right().value();
4438 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4439 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), componentUuid));
4441 if (errorWrapper.isEmpty()) {
4442 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
4443 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
4444 if (!getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4445 component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
4446 if (component != null) {
4447 componentId = component.getUniqueId();
4448 componentName = component.getName();
4451 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentName);
4453 if (errorWrapper.isEmpty()) {
4454 artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentId, componentType);
4456 if (errorWrapper.isEmpty()) {
4457 actionResult = handleArtifactRequest(componentId, userId, componentType, operation, artifactId, null, origMd5, null, null, null, null, null);
4458 if (actionResult.isRight()) {
4459 log.debug("Failed to upload artifact to component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, actionResult.right().value());
4460 errorWrapper.setInnerElement(actionResult.right().value());
4463 if (errorWrapper.isEmpty()) {
4464 deleteArtifact = actionResult.left().value().left().value();
4465 deleteArtifactResult = Either.left(deleteArtifact);
4467 deleteArtifactResult = Either.right(errorWrapper.getInnerElement());
4469 updateAuditParametersWithArtifactDefinition(additionalParams, deleteArtifact);
4470 return deleteArtifactResult;
4474 * deletes an artifact from a resource instance by UUID
4477 * @param componentType
4478 * @param componentUuid
4479 * @param resourceInstanceName
4480 * @param artifactUUID
4481 * @param additionalParams
4486 public Either<ArtifactDefinition, ResponseFormat> deleteArtifactOnRiByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID,
4487 Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
4489 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4490 Either<ArtifactDefinition, ResponseFormat> deleteArtifactResult;
4491 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4492 ArtifactDefinition deleteArtifact = null;
4493 Component component = null;
4494 String componentInstanceId = null;
4495 String componentId = null;
4496 String artifactId = null;
4497 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4498 String userId = request.getHeader(Constants.USER_ID_HEADER);
4499 ImmutablePair<Component, ComponentInstance> componentRiPair = null;
4500 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4501 if (getComponentRes.isRight()) {
4502 StorageOperationStatus status = getComponentRes.right().value();
4503 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4504 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4506 if (errorWrapper.isEmpty() && !getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4507 component = checkoutParentComponent(componentType, getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(), userId, errorWrapper);
4509 if (errorWrapper.isEmpty()) {
4510 if (component == null) {
4511 componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
4513 componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
4516 if (errorWrapper.isEmpty()) {
4517 componentInstanceId = componentRiPair.getRight().getUniqueId();
4518 componentId = componentRiPair.getLeft().getUniqueId();
4519 artifactId = findArtifactId(componentRiPair.getRight(), artifactUUID, errorWrapper);
4521 if (errorWrapper.isEmpty()) {
4523 actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, null, origMd5, null, null, null, componentId, ComponentTypeEnum.findParamByType(componentType));
4525 if (actionResult.isRight()) {
4526 log.debug("Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. ", resourceInstanceName, componentType, componentUuid, actionResult.right().value());
4527 errorWrapper.setInnerElement(actionResult.right().value());
4530 if (errorWrapper.isEmpty()) {
4531 deleteArtifact = actionResult.left().value().left().value();
4532 deleteArtifactResult = Either.left(deleteArtifact);
4534 deleteArtifactResult = Either.right(errorWrapper.getInnerElement());
4536 updateAuditParametersWithArtifactDefinition(additionalParams, deleteArtifact);
4537 return deleteArtifactResult;
4540 private String findArtifactId(ComponentInstance instance, String artifactUUID, Wrapper<ResponseFormat> errorWrapper) {
4541 String artifactId = null;
4542 ArtifactDefinition foundArtifact = null;
4543 if (instance.getDeploymentArtifacts() != null) {
4544 foundArtifact = instance.getDeploymentArtifacts().values().stream().filter(e -> e.getArtifactUUID() != null && e.getArtifactUUID().equals(artifactUUID)).findFirst().orElse(null);
4546 if (foundArtifact == null && instance.getArtifacts() != null) {
4547 foundArtifact = instance.getArtifacts().values().stream().filter(e -> e.getArtifactUUID() != null && e.getArtifactUUID().equals(artifactUUID)).findFirst().orElse(null);
4549 if (foundArtifact == null) {
4550 log.debug("The artifact {} was not found on instance {}. ", artifactUUID, instance.getUniqueId());
4551 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactUUID));
4553 artifactId = foundArtifact.getUniqueId();
4558 public Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder(ArtifactDefinition artifact, String envType, String parentId, NodeTypeEnum parentType, String parentName, User user, Component component,
4559 Map<String, String> existingEnvVersions) {
4560 return createHeatEnvPlaceHolder(artifact, envType, parentId, parentType, parentName, user, component, existingEnvVersions, true);
4564 @SuppressWarnings("unchecked")
4565 public Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder(ArtifactDefinition artifact, String envType, String parentId, NodeTypeEnum parentType, String parentName, User user, Component component,
4566 Map<String, String> existingEnvVersions, boolean overrideId) {
4567 Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getDeploymentResourceInstanceArtifacts();
4568 if (deploymentResourceArtifacts == null) {
4569 log.debug("no deployment artifacts are configured for generated artifacts");
4570 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
4572 Map<String, Object> placeHolderData = (Map<String, Object>) deploymentResourceArtifacts.get(envType);
4573 if (placeHolderData == null) {
4574 log.debug("no env type {} are configured for generated artifacts", envType);
4575 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
4578 String envLabel = (artifact.getArtifactLabel() + HEAT_ENV_SUFFIX).toLowerCase();
4579 String parentIdParam = parentId;
4581 parentIdParam = null;
4583 Either<ArtifactDefinition, ResponseFormat> createArtifactPlaceHolder = createArtifactPlaceHolderInfo(parentIdParam, envLabel, placeHolderData, user.getUserId(), ArtifactGroupTypeEnum.DEPLOYMENT, true);
4584 if (createArtifactPlaceHolder.isRight()) {
4585 return Either.right(createArtifactPlaceHolder.right().value());
4587 ArtifactDefinition artifactHeatEnv = createArtifactPlaceHolder.left().value();
4589 // fix for migration only!!!! create heat env placeholder according to heat id.
4590 artifactHeatEnv.setUniqueId(artifact.getUniqueId() + HEAT_ENV_SUFFIX);
4593 artifactHeatEnv.setGeneratedFromId(artifact.getUniqueId());
4594 artifactHeatEnv.setHeatParamsUpdateDate(System.currentTimeMillis());
4595 artifactHeatEnv.setTimeout(0);
4596 buildHeatEnvFileName(artifact, artifactHeatEnv, placeHolderData);
4597 // rbetzer - keep env artifactVersion - changeComponentInstanceVersion flow
4598 handleEnvArtifactVersion(artifactHeatEnv, existingEnvVersions);
4599 // clone heat parameters in case of heat env only not VF heat env
4600 if (envType.equals(HEAT_ENV_NAME)) {
4601 artifactHeatEnv.setHeatParameters(artifact.getHeatParameters());
4603 ArtifactDefinition artifactDefinition;
4604 // Evg : for resource instance artifact will be added later as block with other env artifacts from BL
4605 if (parentType != NodeTypeEnum.ResourceInstance) {
4606 Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact = addHeatEnvArtifact(artifactHeatEnv, artifact, component.getUniqueId(), parentType, parentId);
4607 if (addHeatEnvArtifact.isRight()) {
4608 log.debug("failed to create heat env artifact on resource instance");
4609 return Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(addHeatEnvArtifact.right().value(), false), "", null));
4611 artifactDefinition = createArtifactPlaceHolder.left().value();
4613 artifactDefinition = artifactHeatEnv;
4614 artifactToscaOperation.generateUUID(artifactDefinition, artifactDefinition.getArtifactVersion());
4617 if (artifact.getHeatParameters() != null) {
4618 List<HeatParameterDefinition> heatEnvParameters = new ArrayList<HeatParameterDefinition>();
4619 for (HeatParameterDefinition parameter : artifact.getListHeatParameters()) {
4620 HeatParameterDefinition heatEnvParameter = new HeatParameterDefinition(parameter);
4621 heatEnvParameter.setDefaultValue(parameter.getCurrentValue());
4622 heatEnvParameters.add(heatEnvParameter);
4624 artifactDefinition.setListHeatParameters(heatEnvParameters);
4628 EnumMap<AuditingFieldsKeysEnum, Object> artifactAuditingFields = createArtifactAuditingFields(artifactDefinition, "", artifactDefinition.getUniqueId());
4629 artifactAuditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, parentName);
4630 ComponentTypeEnum componentType = component.getComponentType();
4631 if (parentType == NodeTypeEnum.ResourceInstance) {
4632 componentType = ComponentTypeEnum.RESOURCE_INSTANCE;
4634 componentsUtils.auditComponent(componentsUtils.getResponseFormat(ActionStatus.OK), user, component, "", "", AuditingActionEnum.ARTIFACT_UPLOAD, componentType, artifactAuditingFields);
4635 return Either.left(artifactDefinition);
4638 private void buildHeatEnvFileName(ArtifactDefinition heatArtifact, ArtifactDefinition heatEnvArtifact, Map<String, Object> placeHolderData) {
4639 String heatExtension = GeneralUtility.getFilenameExtension(heatArtifact.getArtifactName());
4640 String envExtension = (String) placeHolderData.get(ARTIFACT_PLACEHOLDER_FILE_EXTENSION);
4641 String name = heatArtifact.getArtifactName();
4644 name = heatArtifact.getArtifactLabel();
4645 fileName = name + "." + envExtension;
4647 fileName = name.replaceAll("." + heatExtension, "." + envExtension);
4649 heatEnvArtifact.setArtifactName(fileName);
4652 private void handleEnvArtifactVersion(ArtifactDefinition heatEnvArtifact, Map<String, String> existingEnvVersions) {
4653 if (null != existingEnvVersions) {
4654 String prevVersion = existingEnvVersions.get(heatEnvArtifact.getArtifactName());
4655 if (null != prevVersion) {
4656 heatEnvArtifact.setArtifactVersion(prevVersion);
4662 * Handles Artifacts Request For Inner Component
4664 * @param artifactsToHandle
4667 * @param vfcsNewCreatedArtifacts
4670 * @param inTransaction
4673 public Either<List<ArtifactDefinition>, ResponseFormat> handleArtifactsRequestForInnerVfcComponent(List<ArtifactDefinition> artifactsToHandle, Resource component, User user, List<ArtifactDefinition> vfcsNewCreatedArtifacts,
4674 ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) {
4676 Either<List<ArtifactDefinition>, ResponseFormat> handleArtifactsResult = null;
4677 ComponentTypeEnum componentType = component.getComponentType();
4678 List<ArtifactDefinition> uploadedArtifacts = new ArrayList<>();
4679 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4680 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult;
4684 for (ArtifactDefinition artifact : artifactsToHandle) {
4685 originData = buildJsonStringForCsarVfcArtifact(artifact);
4686 origMd5 = GeneralUtility.calculateMD5ByString(originData);
4687 actionResult = handleArtifactRequest(component.getUniqueId(), user.getUserId(), componentType, operation, artifact.getUniqueId(), artifact, origMd5, originData, null, null, null, null, shouldLock, inTransaction);
4688 if (actionResult.isRight()) {
4689 log.debug("Failed to upload artifact to component with type {} and name {}. Status is {}. ", componentType, component.getName(), actionResult.right().value());
4690 errorWrapper.setInnerElement(actionResult.right().value());
4691 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create) {
4692 vfcsNewCreatedArtifacts.addAll(uploadedArtifacts);
4696 uploadedArtifacts.add(actionResult.left().value().left().value());
4698 if (errorWrapper.isEmpty()) {
4699 handleArtifactsResult = Either.left(uploadedArtifacts);
4701 handleArtifactsResult = Either.right(errorWrapper.getInnerElement());
4703 } catch (Exception e) {
4704 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
4705 handleArtifactsResult = Either.right(responseFormat);
4706 log.debug("Exception occured when handleArtifactsRequestForInnerVfcComponent, error is:{}", e.getMessage(), e);
4708 return handleArtifactsResult;
4711 private ComponentInstance getRelatedComponentInstance(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
4712 ComponentInstance componentInstance = null;
4713 String normalizedName = ValidationUtils.normalizeComponentInstanceName(resourceInstanceName);
4714 Component component = getComponentByUuid(componentType, componentUuid, errorWrapper);
4715 if (errorWrapper.isEmpty()) {
4716 componentInstance = component.getComponentInstances().stream().filter(ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName()).equals(normalizedName)).findFirst().orElse(null);
4717 if (componentInstance == null) {
4718 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, "resource instance", component.getComponentType().getValue(), component.getName()));
4719 log.debug("Component instance {} was not found for component {}", resourceInstanceName, component.getName());
4722 return componentInstance;
4725 private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(Component component, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
4727 ImmutablePair<Component, ComponentInstance> relatedComponentComponentInstancePair = null;
4728 String normalizedName = ValidationUtils.normalizeComponentInstanceName(resourceInstanceName);
4729 ComponentInstance componentInstance = component.getComponentInstances().stream().filter(ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName()).equals(normalizedName)).findFirst().orElse(null);
4730 if (componentInstance == null) {
4731 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, "resource instance", component.getComponentType().getValue(), component.getName()));
4732 log.debug("Component instance {} was not found for component {}", resourceInstanceName, component.getName());
4734 relatedComponentComponentInstancePair = new ImmutablePair<>(component, componentInstance);
4736 return relatedComponentComponentInstancePair;
4739 private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
4740 ComponentInstance componentInstance;
4741 ImmutablePair<Component, ComponentInstance> relatedComponentComponentInstancePair = null;
4742 Component component = getLatestComponentByUuid(componentType, componentUuid, errorWrapper);
4743 if (errorWrapper.isEmpty()) {
4744 componentInstance = component.getComponentInstances().stream().filter(ci -> ci.getNormalizedName().equals(resourceInstanceName)).findFirst().orElse(null);
4745 if (componentInstance == null) {
4746 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, "resource instance", component.getComponentType().getValue(), component.getName()));
4747 log.debug("Component instance {} was not found for component {}", resourceInstanceName, component.getName());
4749 relatedComponentComponentInstancePair = new ImmutablePair<>(component, componentInstance);
4752 return relatedComponentComponentInstancePair;
4755 private byte[] downloadArtifact(Map<String, ArtifactDefinition> artifacts, String artifactUUID, Wrapper<ResponseFormat> errorWrapper, String componentName) {
4757 byte[] downloadedArtifact = null;
4758 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = null;
4759 List<ArtifactDefinition> artifactsList = null;
4760 ArtifactDefinition deploymentArtifact = null;
4761 if (artifacts != null && !artifacts.isEmpty()) {
4762 artifactsList = artifacts.values().stream().filter(art -> art.getArtifactUUID() != null && art.getArtifactUUID().equals(artifactUUID)).collect(Collectors.toList());
4764 if (artifactsList == null || artifactsList.isEmpty()) {
4765 log.debug("Deployment artifact with uuid {} was not found for component {}", artifactUUID, componentName);
4766 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactUUID));
4768 if (errorWrapper.isEmpty()) {
4769 deploymentArtifact = artifactsList.get(0);
4770 downloadArtifactEither = downloadArtifact(deploymentArtifact);
4771 if (downloadArtifactEither.isRight()) {
4772 log.debug("Failed to download artifact {}. ", deploymentArtifact.getArtifactName());
4773 errorWrapper.setInnerElement(downloadArtifactEither.right().value());
4776 if (errorWrapper.isEmpty()) {
4777 log.trace("Succeeded to download artifact with uniqueId {}", deploymentArtifact.getUniqueId());
4778 downloadedArtifact = downloadArtifactEither.left().value().getRight();
4780 return downloadedArtifact;
4783 private Component getLatestComponentByUuid(ComponentTypeEnum componentType, String componentUuid, Wrapper<ResponseFormat> errorWrapper) {
4784 Component component = null;
4785 Either<Component, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentByUuid(componentUuid);
4786 if (getComponentRes.isRight()) {
4787 StorageOperationStatus status = getComponentRes.right().value();
4788 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4789 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4791 component = getComponentRes.left().value();
4796 private Component getComponentByUuid(ComponentTypeEnum componentType, String componentUuid, Wrapper<ResponseFormat> errorWrapper) {
4797 Component component = null;
4798 Either<List<Component>, StorageOperationStatus> getComponentRes = toscaOperationFacade.getComponentListByUuid(componentUuid, null);
4799 if (getComponentRes.isRight()) {
4800 StorageOperationStatus status = getComponentRes.right().value();
4801 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4802 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4804 List<Component> value = getComponentRes.left().value();
4805 if (value.isEmpty()){
4806 log.debug("Could not fetch component with type {} and uuid {}.", componentType, componentUuid);
4807 ActionStatus status = componentType == ComponentTypeEnum.RESOURCE ? ActionStatus.RESOURCE_NOT_FOUND : ActionStatus.SERVICE_NOT_FOUND;
4808 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(status));
4810 component = value.get(0);
4816 private String getLatestParentArtifactDataIdByArtifactUUID(String artifactUUID, Wrapper<ResponseFormat> errorWrapper, String parentId, ComponentTypeEnum componentType) {
4817 String artifactId = null;
4818 ActionStatus actionStatus = ActionStatus.ARTIFACT_NOT_FOUND;
4819 StorageOperationStatus storageStatus;
4820 ArtifactDefinition latestArtifact = null;
4821 List<ArtifactDefinition> artifacts = null;
4822 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifactsRes = artifactToscaOperation.getArtifacts(parentId);
4823 if (getArtifactsRes.isRight()) {
4824 storageStatus = getArtifactsRes.right().value();
4825 log.debug("Couldn't fetch artifacts data for parent component {} with uid {}, error: {}", componentType.name(), parentId, storageStatus);
4826 if (!storageStatus.equals(StorageOperationStatus.NOT_FOUND)) {
4827 actionStatus = componentsUtils.convertFromStorageResponse(storageStatus);
4829 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
4831 if (errorWrapper.isEmpty()) {
4832 artifacts = getArtifactsRes.left().value().values().stream().filter(a -> a.getArtifactUUID() != null && a.getArtifactUUID().equals(artifactUUID)).collect(Collectors.toList());
4833 if (artifacts == null || artifacts.isEmpty()) {
4834 log.debug("Couldn't fetch artifact with UUID {} data for parent component {} with uid {}, error: {}", artifactUUID, componentType.name(), parentId, actionStatus);
4835 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
4838 if (errorWrapper.isEmpty()) {
4839 latestArtifact = artifacts.stream().max((a1, a2) -> {
4840 int compareRes = Double.compare(Double.parseDouble(a1.getArtifactVersion()), Double.parseDouble(a2.getArtifactVersion()));
4841 if (compareRes == 0) {
4842 compareRes = Long.compare(a1.getLastUpdateDate() == null ? 0 : a1.getLastUpdateDate(), a2.getLastUpdateDate() == null ? 0 : a2.getLastUpdateDate());
4846 if (latestArtifact == null) {
4847 log.debug("Couldn't fetch latest artifact with UUID {} data for parent component {} with uid {}, error: {}", artifactUUID, componentType.name(), parentId, actionStatus);
4848 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
4851 if (errorWrapper.isEmpty()) {
4852 artifactId = latestArtifact.getUniqueId();
4857 private Component checkoutParentComponent(ComponentTypeEnum componentType, String parentId, String userId, Wrapper<ResponseFormat> errorWrapper) {
4859 Component component = null;
4860 Either<User, ActionStatus> getUserRes = userBusinessLogic.getUser(userId, false);
4861 if (getUserRes.isRight()) {
4862 log.debug("Could not fetch User of component {} with uid {} to checked out. Status is {}. ", componentType.getNodeType(), parentId, getUserRes.right().value());
4863 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(getUserRes.right().value()));
4865 if (errorWrapper.isEmpty()) {
4866 User modifier = getUserRes.left().value();
4867 LifecycleChangeInfoWithAction changeInfo = new LifecycleChangeInfoWithAction("External API checkout", LifecycleChanceActionEnum.UPDATE_FROM_EXTERNAL_API);
4868 Either<? extends Component, ResponseFormat> checkoutRes = lifecycleBusinessLogic.changeComponentState(componentType, parentId, modifier, LifeCycleTransitionEnum.CHECKOUT, changeInfo, false, true);
4869 if (checkoutRes.isRight()) {
4870 log.debug("Could not change state of component {} with uid {} to checked out. Status is {}. ", componentType.getNodeType(), parentId, checkoutRes.right().value().getStatus());
4871 errorWrapper.setInnerElement(checkoutRes.right().value());
4873 component = checkoutRes.left().value();
4879 private void updateAuditParametersWithArtifactDefinition(Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactDefinition artifact) {
4880 if (artifact == null) {
4881 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, "");
4882 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, "");
4883 if (!additionalParams.containsKey(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID)) {
4884 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, "");
4887 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifact.getArtifactUUID());
4888 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, buildAuditingArtifactData(artifact));
4889 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, artifact.getUpdaterFullName());
4893 private String buildJsonStringForCsarVfcArtifact(ArtifactDefinition artifact) {
4894 Map<String, Object> json = new HashMap<>();
4895 String artifactName = artifact.getArtifactName();
4896 json.put(Constants.ARTIFACT_NAME, artifactName);
4897 json.put(Constants.ARTIFACT_LABEL, artifact.getArtifactLabel());
4898 json.put(Constants.ARTIFACT_TYPE, artifact.getArtifactType());
4899 json.put(Constants.ARTIFACT_GROUP_TYPE, ArtifactGroupTypeEnum.DEPLOYMENT.getType());
4900 json.put(Constants.ARTIFACT_DESCRIPTION, artifact.getDescription());
4901 json.put(Constants.ARTIFACT_PAYLOAD_DATA, artifact.getPayloadData());
4902 json.put(Constants.ARTIFACT_DISPLAY_NAME, artifact.getArtifactDisplayName());
4903 return gson.toJson(json);