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()));
347 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateAndSaveToscaArtifact(ArtifactDefinition artifactDefinition, org.openecomp.sdc.be.model.Component component, User user, boolean isInCertificationRequest,
348 boolean shouldLock, boolean inTransaction, boolean fetchTemplatesFromDB) {
350 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generated = generateToscaArtifact(component, artifactDefinition, isInCertificationRequest, fetchTemplatesFromDB);
351 if (generated.isRight()) {
354 byte[] decodedPayload = artifactDefinition.getPayloadData();
355 artifactDefinition.setEsId(artifactDefinition.getUniqueId());
356 artifactDefinition.setArtifactChecksum(GeneralUtility.calculateMD5ByByteArray(decodedPayload));
357 return lockComponentAndUpdateArtifact(component.getUniqueId(), artifactDefinition, AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, artifactDefinition.getUniqueId(), user, component.getComponentType(), component, decodedPayload, null, null,
358 shouldLock, inTransaction);
362 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateToscaArtifact(Component parent, ArtifactDefinition artifactInfo, boolean isInCertificationRequest, boolean fetchTemplatesFromDB) {
363 log.debug("tosca artifact generation");
364 if (artifactInfo.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType())) {
365 Either<byte[], ResponseFormat> generated = csarUtils.createCsar(parent, fetchTemplatesFromDB, isInCertificationRequest);
367 if (generated.isRight()) {
368 log.debug("Failed to export tosca csar for component {} error {}", parent.getUniqueId(), generated.right().value());
370 return Either.right(generated.right().value());
372 byte[] value = generated.left().value();
373 artifactInfo.setPayload(value);
376 Either<ToscaRepresentation, ToscaError> exportComponent = toscaExportUtils.exportComponent(parent);
377 if (exportComponent.isRight()) {
378 log.debug("Failed export tosca yaml for component {} error {}", parent.getUniqueId(), exportComponent.right().value());
379 ActionStatus status = componentsUtils.convertFromToscaError(exportComponent.right().value());
380 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status);
381 return Either.right(responseFormat);
383 log.debug("Tosca yaml exported for component {} ", parent.getUniqueId());
384 String payload = exportComponent.left().value().getMainYaml();
385 artifactInfo.setPayloadData(payload);
387 return Either.left(Either.left(artifactInfo));
390 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> doAction(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, String origMd5,
391 String originData, String interfaceName, String operationName, AuditingActionEnum auditingAction, User user, org.openecomp.sdc.be.model.Component parent, boolean shouldLock, boolean inTransaction, boolean needUpdateGroup) {
392 if (interfaceName != null && operationName != null) {
393 interfaceName = interfaceName.toLowerCase();
394 operationName = operationName.toLowerCase();
396 switch (operation.getArtifactOperationEnum()) {
398 if (artifactGenerationRequired(parent, artifactInfo)) {
399 return generateNotSavedArtifact(parent, artifactInfo, shouldLock, inTransaction);
401 return handleDownload(componentId, artifactId, user, auditingAction, componentType, parent, shouldLock, inTransaction);
403 return handleDelete(componentId, artifactId, user, auditingAction, componentType, parent, interfaceName, operationName, shouldLock, inTransaction);
405 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result = null;
406 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
407 if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)
408 && (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_VOL || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_ENV)) {
409 result = handleUpdateHeatEnv(componentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, originData, origMd5, operation, shouldLock, inTransaction);
410 if (needUpdateGroup && result.isLeft()) {
411 Either<ArtifactDefinition, Operation> updateResult = result.left().value();
412 ActionStatus error = updateGroupInstance(artifactInfo, updateResult.left().value(), parent, componentType, componentId);
413 if (error != ActionStatus.OK) {
414 result = Either.right(componentsUtils.getResponseFormat(error));
418 if (componentType.equals(ComponentTypeEnum.RESOURCE) && artifactType == ArtifactTypeEnum.HEAT_ENV) {
419 result = handleUpdateHeatWithHeatEnvParams(componentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, originData, origMd5, operation, shouldLock, inTransaction, needUpdateGroup);
422 if (result == null) {
423 result = handleUpdate(componentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceName, operationName, shouldLock, inTransaction);
424 if (needUpdateGroup && result.isLeft()) {
425 Either<ArtifactDefinition, Operation> updateResult = result.left().value();
427 ActionStatus error = updateGroupForHeat(artifactInfo, updateResult.left().value(), parent, componentType);
428 if (error != ActionStatus.OK) {
429 result = Either.right(componentsUtils.getResponseFormat(error));
435 return handleCreate(componentId, artifactInfo, operation, auditingAction, user, componentType, parent, origMd5, originData, interfaceName, operationName, shouldLock, inTransaction);
440 private ActionStatus updateGroupForHeat(ArtifactDefinition artifactInfo, ArtifactDefinition artAfterUpdate, Component parent, ComponentTypeEnum componentType) {
441 List<GroupDefinition> groups = parent.getGroups();
442 if (groups != null && !groups.isEmpty()) {
443 List<GroupDataDefinition> groupToUpdate = groups.stream().filter(g -> g.getArtifacts() != null && g.getArtifacts().contains(artifactInfo.getUniqueId())).collect(Collectors.toList());
444 if (groupToUpdate != null && !groupToUpdate.isEmpty()) {
445 groupToUpdate.forEach(g -> {
446 g.getArtifacts().remove(artifactInfo.getUniqueId());
447 g.getArtifactsUuid().remove(artifactInfo.getArtifactUUID());
448 g.getArtifacts().add(artAfterUpdate.getUniqueId());
449 g.getArtifactsUuid().add(artAfterUpdate.getArtifactUUID());
451 Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(parent, componentType, groupToUpdate);
452 if (status.isRight()) {
453 log.debug("Failed to update groups of the component {}. ", parent.getUniqueId());
454 return componentsUtils.convertFromStorageResponse(status.right().value());
458 return ActionStatus.OK;
461 private ActionStatus updateGroupForHeat(ArtifactDefinition artifactInfoHeat, ArtifactDefinition artHeatAfterUpdate, ArtifactDefinition artifactInfoHeatE, ArtifactDefinition artHEAfterUpdate, Component parent, ComponentTypeEnum componentType) {
462 List<GroupDefinition> groups = parent.getGroups();
463 if (groups != null && !groups.isEmpty()) {
464 List<GroupDataDefinition> groupToUpdate = groups.stream().filter(g -> g.getArtifacts() != null && g.getArtifacts().contains(artifactInfoHeat.getUniqueId())).collect(Collectors.toList());
465 if (groupToUpdate != null && !groupToUpdate.isEmpty()) {
466 groupToUpdate.forEach(g -> {
467 g.getArtifacts().remove(artifactInfoHeat.getUniqueId());
468 g.getArtifactsUuid().remove(artifactInfoHeat.getArtifactUUID());
469 g.getArtifacts().remove(artifactInfoHeatE.getUniqueId());
470 g.getArtifacts().add(artHeatAfterUpdate.getUniqueId());
471 g.getArtifactsUuid().add(artHeatAfterUpdate.getArtifactUUID());
472 g.getArtifacts().add(artHEAfterUpdate.getUniqueId());
474 Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(parent, componentType, groupToUpdate);
475 if (status.isRight()) {
476 log.debug("Failed to update groups of the component {}. ", parent.getUniqueId());
477 return componentsUtils.convertFromStorageResponse(status.right().value());
481 return ActionStatus.OK;
484 private ActionStatus updateGroupInstance(ArtifactDefinition artifactInfo, ArtifactDefinition artAfterUpdate, Component parent, ComponentTypeEnum componentType, String parentId) {
485 List<GroupInstance> updatedGroupInstances = new ArrayList<>();
486 List<GroupInstance> groupInstances = null;
487 Optional<ComponentInstance> componentInstOp = parent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(parentId)).findFirst();
488 if (componentInstOp.isPresent()) {
489 groupInstances = componentInstOp.get().getGroupInstances();
491 if (CollectionUtils.isNotEmpty(groupInstances)) {
492 boolean isUpdated = false;
493 for (GroupInstance groupInstance : groupInstances) {
495 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifacts()) && groupInstance.getGroupInstanceArtifacts().contains(artifactInfo.getUniqueId())) {
496 groupInstance.getGroupInstanceArtifacts().remove(artifactInfo.getUniqueId());
497 groupInstance.getGroupInstanceArtifacts().add(artAfterUpdate.getUniqueId());
500 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifactsUuid()) && groupInstance.getGroupInstanceArtifactsUuid().contains(artifactInfo.getArtifactUUID())) {
501 groupInstance.getGroupInstanceArtifactsUuid().remove(artifactInfo.getArtifactUUID());
502 groupInstance.getGroupInstanceArtifacts().add(artAfterUpdate.getArtifactUUID());
506 updatedGroupInstances.add(groupInstance);
510 Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(parent, componentType, parentId, updatedGroupInstances);
511 if (status.isRight()) {
512 log.debug("Failed to update groups of the component {}. ", parent.getUniqueId());
513 return componentsUtils.convertFromStorageResponse(status.right().value());
515 return ActionStatus.OK;
518 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateNotSavedArtifact(org.openecomp.sdc.be.model.Component parent, ArtifactDefinition artifactInfo, boolean shouldLock, boolean inTransaction) {
519 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result;
520 if (artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA) {
521 result = generateToscaArtifact(parent, artifactInfo, false, false);
523 String heatArtifactId = artifactInfo.getGeneratedFromId();
524 Either<ArtifactDefinition, StorageOperationStatus> heatRes = artifactToscaOperation.getArtifactById(parent.getUniqueId(), heatArtifactId);
525 if (heatRes.isRight()) {
526 log.debug("Failed to fetch heat artifact by generated id {} for heat env {}", heatArtifactId, artifactInfo.getUniqueId());
527 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(heatRes.right().value()), "");
528 return Either.right(responseFormat);
530 String generatedPayload = generateHeatEnvPayload(heatRes.left().value());
531 artifactInfo.setPayloadData(generatedPayload);
532 result = Either.left(Either.left(artifactInfo));
537 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdateHeatWithHeatEnvParams(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user,
538 ComponentTypeEnum componentType, Component parent, String originData, String origMd5, ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction, boolean needToUpdateGroup) {
539 convertParentType(componentType);
540 String parentId = parent.getUniqueId();
541 Either<ArtifactDefinition, StorageOperationStatus> artifactHeatRes = artifactToscaOperation.getArtifactById(componentId, artifactInfo.getGeneratedFromId());
542 ArtifactDefinition currHeatArtifact = artifactHeatRes.left().value();
544 if (origMd5 != null) {
545 Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
546 if (validateMd5.isRight()) {
547 ResponseFormat responseFormat = validateMd5.right().value();
548 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
549 return Either.right(responseFormat);
552 if (artifactInfo.getPayloadData() != null && artifactInfo.getPayloadData().length != 0) {
554 Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
555 if (payloadEither.isRight()) {
556 ResponseFormat responseFormat = payloadEither.right().value();
557 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
558 return Either.right(responseFormat);
560 } else { // duplicate
561 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
562 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
563 return Either.right(responseFormat);
569 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Update Artifact - lock ");
570 if (lockComponent.isRight()) {
571 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right().value(), componentType, null);
572 return Either.right(lockComponent.right().value());
575 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
577 resultOp = updateHeatParams(componentId, artifactId, artifactInfo, user, auditingAction, parent, componentType, currHeatArtifact, origMd5, needToUpdateGroup);
582 if (resultOp == null || resultOp.isRight()) {
583 log.debug("all changes rollback");
584 if (false == inTransaction)
587 log.debug("all changes committed");
588 if (false == inTransaction)
592 componentType = parent.getComponentType();
593 NodeTypeEnum nodeType = componentType.getNodeType();
594 graphLockOperation.unlockComponent(parent.getUniqueId(), nodeType);
595 // graphLockOperation.unlockComponent(parentId, parentType);
604 * @param componentType
609 public Either<ImmutablePair<String, byte[]>, ResponseFormat> handleDownloadToscaModelRequest(Component component, ArtifactDefinition csarArtifact) {
610 if (artifactGenerationRequired(component, csarArtifact)) {
611 Either<byte[], ResponseFormat> generated = csarUtils.createCsar(component, false, false);
613 if (generated.isRight()) {
614 log.debug("Failed to export tosca csar for component {} error {}", component.getUniqueId(), generated.right().value());
616 return Either.right(generated.right().value());
618 return Either.left(new ImmutablePair<String, byte[]>(csarArtifact.getArtifactName(), generated.left().value()));
620 return downloadArtifact(csarArtifact);
623 public Either<ImmutablePair<String, byte[]>, ResponseFormat> handleDownloadRequestById(String componentId, String artifactId, String userId, ComponentTypeEnum componentType, String parentId, String containerComponentType) {
624 // perform all validation in common flow
625 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result = handleArtifactRequest(componentId, userId, componentType, new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Download), artifactId, null, null, null, null,
626 null, parentId, containerComponentType);
627 if (result.isRight()) {
628 return Either.right(result.right().value());
630 ArtifactDefinition artifactDefinition;
631 Either<ArtifactDefinition, Operation> insideValue = result.left().value();
632 if (insideValue.isLeft()) {
633 artifactDefinition = insideValue.left().value();
635 artifactDefinition = insideValue.right().value().getImplementationArtifact();
637 // for tosca artifacts and heat env on VF level generated on download without saving
638 if (artifactDefinition.getPayloadData() != null) {
639 return Either.left(new ImmutablePair<String, byte[]>(artifactDefinition.getArtifactName(), artifactDefinition.getPayloadData()));
641 return downloadArtifact(artifactDefinition);
644 public Either<Map<String, ArtifactDefinition>, ResponseFormat> handleGetArtifactsByType(String containerComponentType, String parentId, ComponentTypeEnum componentType, String componentId, String artifactGroupType, String userId) {
646 // detect auditing type
647 Map<String, ArtifactDefinition> resMap = null;
648 Either<Map<String, ArtifactDefinition>, ResponseFormat> resultOp = null;
653 if (userId == null) {
654 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
655 log.debug("handleGetArtifactsByType - no HTTP_CSP_HEADER , component id {}", componentId);
657 resultOp = Either.right(responseFormat);
661 // check user existence
665 Either<User, ResponseFormat> userResult = validateUserExists(userId, "get artifacts", false);
666 if (userResult.isRight()) {
668 resultOp = Either.right(userResult.right().value());
672 userResult.left().value();
675 // 5. check service/resource existence
676 // 6. check service/resource check out
677 // 7. user is owner of checkout state
678 org.openecomp.sdc.be.model.Component component = null;
679 // ComponentInstance resourceInstance = null;
680 String realComponentId = componentType == ComponentTypeEnum.RESOURCE_INSTANCE ? parentId : componentId;
681 ComponentParametersView componentFilter = new ComponentParametersView();
682 componentFilter.disableAll();
683 componentFilter.setIgnoreArtifacts(false);
684 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE)
685 componentFilter.setIgnoreComponentInstances(false);
687 Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExistsByFilter(realComponentId, ComponentTypeEnum.findByParamName(containerComponentType), componentFilter, false);
689 if (validateComponent.isRight()) {
690 resultOp = Either.right(validateComponent.right().value());
693 component = validateComponent.left().value();
694 Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, "Update Artifact - lock ");
695 if (lockComponent.isRight()) {
697 resultOp = Either.right(lockComponent.right().value());
702 ArtifactGroupTypeEnum groupType = ArtifactGroupTypeEnum.findType(artifactGroupType);
704 if (groupType == null) {
705 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
706 log.debug("handleGetArtifactsByType - not falid groupType {} , component id {}", artifactGroupType, componentId);
708 resultOp = Either.right(responseFormat);
712 if (groupType == ArtifactGroupTypeEnum.DEPLOYMENT) {
713 List<ArtifactDefinition> list = getDeploymentArtifacts(component, componentType.getNodeType(), componentId);
714 if (list != null && !list.isEmpty()) {
715 resMap = list.stream().collect(Collectors.toMap(a -> a.getArtifactLabel(), a -> a));
717 resMap = new HashMap<>();
719 resultOp = Either.left(resMap);
723 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifactsMapStatus = getArtifacts(realComponentId, componentType.getNodeType(), false, groupType, componentId);
724 if (artifactsMapStatus.isRight()) {
725 if (artifactsMapStatus.right().value() != StorageOperationStatus.NOT_FOUND) {
726 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
727 log.debug("handleGetArtifactsByType - not falid groupType {} , component id {}", artifactGroupType, componentId);
728 resultOp = Either.right(responseFormat);
730 resMap = new HashMap<>();
731 resultOp = Either.left(resMap);
734 resMap = artifactsMapStatus.left().value();
735 resultOp = Either.left(resMap);
741 if (resultOp == null || resultOp.isRight()) {
742 log.debug("all changes rollback");
745 log.debug("all changes committed");
750 componentType = component.getComponentType();
751 NodeTypeEnum nodeType = componentType.getNodeType();
752 graphLockOperation.unlockComponent(component.getUniqueId(), nodeType);
753 // graphLockOperation.unlockComponent(parentId, parentType);
758 private Either<ArtifactDefinition, ResponseFormat> validateArtifact(String componentId, ComponentTypeEnum componentType, String artifactId, org.openecomp.sdc.be.model.Component component, AuditingActionEnum auditingAction, String parentId,
759 boolean inTransaction) {
761 // check artifact existence
762 Either<ArtifactDefinition, StorageOperationStatus> artifactResult = artifactToscaOperation.getArtifactById(componentId, artifactId, componentType, component.getUniqueId());
763 if (artifactResult.isRight()) {
764 if (artifactResult.right().value().equals(StorageOperationStatus.ARTIFACT_NOT_FOUND)) {
765 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, "");
766 log.debug("addArtifact - artifact {} not found", artifactId);
767 return Either.right(responseFormat);
770 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(artifactResult.right().value()));
771 log.debug("addArtifact - failed to fetch artifact {}, error {}", artifactId, artifactResult.right().value());
772 return Either.right(responseFormat);
776 // check artifact belong to component
777 boolean found = false;
778 switch (componentType) {
781 found = checkArtifactInComponent(component, artifactId);
783 case RESOURCE_INSTANCE:
784 found = checkArtifactInResourceInstance(component, componentId, artifactId);
790 // String component =
791 // componentType.equals(ComponentTypeEnum.RESOURCE) ? "resource" :
793 String componentName = componentType.name().toLowerCase();
794 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ARTIFACT_NOT_FOUND, componentName);
795 log.debug("addArtifact - Component artifact not found component Id {}, artifact id {}", componentId, artifactId);
796 return Either.right(responseFormat);
798 return Either.left(artifactResult.left().value());
801 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleCreate(String parentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, User user, ComponentTypeEnum componentType,
802 org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
804 String artifactId = null;
807 Either<byte[], ResponseFormat> payloadEither = validateInput(parentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceType, operationName, inTransaction);
808 if (payloadEither.isRight()) {
809 return Either.right(payloadEither.right().value());
811 byte[] decodedPayload = payloadEither.left().value();
812 convertParentType(componentType);
815 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Upload Artifact - lock ");
816 if (lockComponent.isRight()) {
817 handleAuditing(auditingAction, parent, parentId, user, null, null, null, lockComponent.right().value(), componentType, null);
818 return Either.right(lockComponent.right().value());
821 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
824 resultOp = createArtifact(parent, parentId, artifactInfo, decodedPayload, user, componentType, auditingAction, interfaceType, operationName);
828 unlockComponent(resultOp, parent, inTransaction);
835 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> lockComponentAndUpdateArtifact(String parentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user,
836 ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent, byte[] decodedPayload, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
838 convertParentType(componentType);
842 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Update Artifact - lock ");
844 if (lockComponent.isRight()) {
845 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right().value(), componentType, null);
846 return Either.right(lockComponent.right().value());
850 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
852 resultOp = updateArtifactFlow(parent, parentId, artifactId, artifactInfo, user, decodedPayload, componentType, auditingAction, interfaceType, operationName);
857 unlockComponent(resultOp, parent, inTransaction);
862 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdate(String parentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, String artifactId, User user,
863 ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
865 Either<byte[], ResponseFormat> payloadEither = validateInput(parentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceType, operationName, inTransaction);
867 if (payloadEither.isRight()) {
868 return Either.right(payloadEither.right().value());
870 byte[] decodedPayload = payloadEither.left().value();
872 return lockComponentAndUpdateArtifact(parentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, decodedPayload, interfaceType, operationName, shouldLock, inTransaction);
875 private Either<byte[], ResponseFormat> validateInput(String parentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType,
876 org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean inTransaction) {
878 Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
879 if (validateMd5.isRight()) {
880 ResponseFormat responseFormat = validateMd5.right().value();
881 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
882 return Either.right(responseFormat);
886 Either<ArtifactDefinition, ResponseFormat> validateResult = validateInput(parentId, artifactInfo, operation, artifactId, user, interfaceType, operationName, componentType, parent, inTransaction);
887 if (validateResult.isRight()) {
888 ResponseFormat responseFormat = validateResult.right().value();
889 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
890 return Either.right(validateResult.right().value());
893 Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
894 if (payloadEither.isRight()) {
895 ResponseFormat responseFormat = payloadEither.right().value();
896 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
897 log.debug("Error during handle payload");
898 return Either.right(responseFormat);
901 // validate heat parameters. this part must be after the parameters are
902 // extracted in "handlePayload"
903 Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers = validateAndConvertHeatParamers(artifactInfo, artifactInfo.getArtifactType());
904 if (validateAndConvertHeatParamers.isRight()) {
905 ResponseFormat responseFormat = validateAndConvertHeatParamers.right().value();
906 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, null, artifactId, responseFormat, componentType, null);
907 log.debug("Error during handle payload");
908 return Either.right(responseFormat);
910 return payloadEither;
913 public void handleAuditing(AuditingActionEnum auditingActionEnum, Component component, String componentId, User user, ArtifactDefinition artifactDefinition, String prevArtifactUuid, String currentArtifactUuid, ResponseFormat responseFormat,
914 ComponentTypeEnum componentTypeEnum, String resourceInstanceName) {
916 if (auditingActionEnum.getAuditingEsType().equals(AuditingTypesConstants.EXTERNAL_API_EVENT_TYPE)) {
920 EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = createArtifactAuditingFields(artifactDefinition, prevArtifactUuid, currentArtifactUuid);
924 user.setUserId("UNKNOWN");
926 switch (componentTypeEnum) {
929 Resource resource = (Resource) component;
930 if (resource == null) {
931 // In that case, component ID should be instead of name
932 resource = new Resource();
933 resource.setName(componentId);
935 componentsUtils.auditResource(responseFormat, user, resource, null, null, auditingActionEnum, auditingFields);
939 Service service = (Service) component;
940 if (service == null) {
941 // In that case, component ID should be instead of name
942 service = new Service();
943 service.setName(componentId);
945 componentsUtils.auditComponent(responseFormat, user, service, null, null, auditingActionEnum, ComponentTypeEnum.SERVICE, auditingFields);
948 case RESOURCE_INSTANCE:
949 if (resourceInstanceName == null) {
950 resourceInstanceName = getResourceInstanceNameFromComponent(component, componentId);
952 auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceInstanceName);
953 componentsUtils.auditComponent(responseFormat, user, component, null, null, auditingActionEnum, ComponentTypeEnum.RESOURCE_INSTANCE, auditingFields);
961 private String getResourceInstanceNameFromComponent(Component component, String componentId) {
962 ComponentInstance resourceInstance = component.getComponentInstances().stream().filter(p -> p.getUniqueId().equals(componentId)).findFirst().orElse(null);
963 String resourceInstanceName = null;
964 if (resourceInstance != null) {
965 resourceInstanceName = resourceInstance.getName();
967 return resourceInstanceName;
970 public EnumMap<AuditingFieldsKeysEnum, Object> createArtifactAuditingFields(ArtifactDefinition artifactDefinition, String prevArtifactUuid, String currentArtifactUuid) {
971 EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
972 // Putting together artifact info
973 String artifactData = buildAuditingArtifactData(artifactDefinition);
974 auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, artifactData);
975 auditingFields.put(AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID, prevArtifactUuid);
976 auditingFields.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, currentArtifactUuid);
977 return auditingFields;
982 private String buildAuditingArtifactData(ArtifactDefinition artifactDefinition) {
983 StringBuilder sb = new StringBuilder();
984 if (artifactDefinition != null) {
985 sb.append(artifactDefinition.getArtifactGroupType().getType()).append(",").append("'").append(artifactDefinition.getArtifactLabel()).append("'").append(",").append(artifactDefinition.getArtifactType()).append(",")
986 .append(artifactDefinition.getArtifactName()).append(",").append(artifactDefinition.getTimeout()).append(",").append(artifactDefinition.getEsId());
989 if (artifactDefinition.getArtifactVersion() != null) {
991 sb.append(artifactDefinition.getArtifactVersion());
996 if (artifactDefinition.getArtifactUUID() != null) {
997 sb.append(artifactDefinition.getArtifactUUID());
1002 return sb.toString();
1005 private Either<Boolean, ResponseFormat> validateMd5(String origMd5, String originData, byte[] payload, ArtifactOperationInfo operation) {
1007 if (origMd5 != null) {
1008 String encodeBase64Str = GeneralUtility.calculateMD5ByString(originData);
1010 if (false == encodeBase64Str.equals(origMd5)) {
1011 log.debug("The calculated md5 is different then the received one");
1012 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_MD5));
1015 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create) {
1016 log.debug("Missing md5 header during artifact create");
1017 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_MD5));
1020 if (payload != null && payload.length != 0) {
1021 log.debug("Cannot have payload while md5 header is missing");
1022 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1025 return Either.left(true);
1028 private Either<ArtifactDefinition, ResponseFormat> validateInput(String parentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, String artifactId, User user, String interfaceName, String operationName,
1029 ComponentTypeEnum componentType, Component parentComponent, boolean inTransaction) {
1031 Either<Boolean, ResponseFormat> validateInformationalArtifactRes = validateInformationalArtifact(artifactInfo, parentComponent);
1032 if (validateInformationalArtifactRes.isRight()) {
1033 return Either.right(validateInformationalArtifactRes.right().value());
1035 Either<Boolean, ResponseFormat> validateAndSetArtifactname = validateAndSetArtifactname(artifactInfo);
1036 if (validateAndSetArtifactname.isRight()) {
1037 return Either.right(validateAndSetArtifactname.right().value());
1039 Either<ArtifactDefinition, ResponseFormat> artifactById = findArtifactOnParentComponent(parentComponent, componentType, parentId, operation, artifactId);
1040 if (artifactById.isRight()) {
1041 return Either.right(artifactById.right().value());
1043 ArtifactDefinition currentArtifactInfo = artifactById.left().value();
1044 if (operationName != null && interfaceName != null) {
1045 operationName = operationName.toLowerCase();
1046 interfaceName = interfaceName.toLowerCase();
1048 Either<ActionStatus, ResponseFormat> logicalNameStatus = handleArtifactLabel(parentId, operation, artifactId, artifactInfo, interfaceName, operationName, currentArtifactInfo, componentType, inTransaction);
1049 if (logicalNameStatus.isRight()) {
1050 return Either.right(logicalNameStatus.right().value());
1052 // This is a patch to block possibility of updating service api fields
1053 // through other artifacts flow
1055 if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.Create) {
1056 checkAndSetUnUpdatableFields(user, artifactInfo, currentArtifactInfo, (operationName != null ? ArtifactGroupTypeEnum.LIFE_CYCLE : ArtifactGroupTypeEnum.INFORMATIONAL));
1058 checkCreateFields(user, artifactInfo, (operationName != null ? ArtifactGroupTypeEnum.LIFE_CYCLE : ArtifactGroupTypeEnum.INFORMATIONAL));
1061 composeArtifactId(parentId, artifactId, artifactInfo, interfaceName, operationName);
1062 if (currentArtifactInfo != null) {
1063 artifactInfo.setMandatory(currentArtifactInfo.getMandatory());
1066 // artifactGroupType is not allowed to be updated
1067 if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.Create) {
1068 Either<ArtifactDefinition, ResponseFormat> validateGroupType = validateOrSetArtifactGroupType(artifactInfo, currentArtifactInfo);
1069 if (validateGroupType.isRight()) {
1070 return Either.right(validateGroupType.right().value());
1074 NodeTypeEnum parentType = convertParentType(componentType);
1077 boolean isCreate = operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create;
1079 if (isDeploymentArtifact(artifactInfo)) {
1080 Either<Boolean, ResponseFormat> deploymentValidationResult = validateDeploymentArtifact(parentComponent, parentId, user.getUserId(), isCreate, artifactInfo, currentArtifactInfo, parentType);
1081 if (deploymentValidationResult.isRight()) {
1082 return Either.right(deploymentValidationResult.right().value());
1085 artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
1088 * if (informationDeployedArtifactsBusinessLogic. isInformationDeployedArtifact(artifactInfo)) { Either<Boolean, ResponseFormat> validationResult = informationDeployedArtifactsBusinessLogic.validateArtifact( isCreate, artifactInfo,
1089 * parentComponent, parentType); if (validationResult.isRight()) { return Either.right(validationResult.right().value()); } }
1093 Either<Boolean, ResponseFormat> descriptionResult = validateAndCleanDescription(artifactInfo);
1094 if (descriptionResult.isRight()) {
1095 return Either.right(descriptionResult.right().value());
1098 if (currentArtifactInfo != null && currentArtifactInfo.getArtifactGroupType().equals(ArtifactGroupTypeEnum.SERVICE_API)) {
1099 Either<ActionStatus, ResponseFormat> validateServiceApiType = validateArtifactType(user.getUserId(), artifactInfo, parentType);
1100 if (validateServiceApiType.isRight()) {
1101 return Either.right(validateServiceApiType.right().value());
1103 // Change of type is not allowed and should be ignored
1105 artifactInfo.setArtifactType(ARTIFACT_TYPE_OTHER);
1107 Either<Boolean, ResponseFormat> validateUrl = validateAndServiceApiUrl(artifactInfo);
1108 if (validateUrl.isRight()) {
1109 return Either.right(validateUrl.right().value());
1112 Either<Boolean, ResponseFormat> validateUpdate = validateFirstUpdateHasPayload(artifactInfo, currentArtifactInfo);
1113 if (validateUpdate.isRight()) {
1114 log.debug("serviceApi first update cnnot be without payload.");
1115 return Either.right(validateUpdate.right().value());
1118 Either<ActionStatus, ResponseFormat> validateArtifactType = validateArtifactType(user.getUserId(), artifactInfo, parentType);
1119 if (validateArtifactType.isRight()) {
1120 return Either.right(validateArtifactType.right().value());
1122 if (artifactInfo.getApiUrl() != null) {
1123 artifactInfo.setApiUrl(null);
1124 log.error("Artifact URL cannot be set through this API - ignoring");
1127 if (artifactInfo.getServiceApi() != null) {
1128 if (artifactInfo.getServiceApi()) {
1129 artifactInfo.setServiceApi(false);
1130 log.error("Artifact service API flag cannot be changed - ignoring");
1135 return Either.left(artifactInfo);
1138 private Either<ArtifactDefinition, ResponseFormat> findArtifactOnParentComponent(Component parentComponent, ComponentTypeEnum componentType, String parentId, ArtifactOperationInfo operation, String artifactId) {
1140 Either<ArtifactDefinition, ResponseFormat> result = null;
1141 ArtifactDefinition foundArtifact = null;
1142 if (StringUtils.isNotEmpty(artifactId)) {
1143 foundArtifact = findArtifact(parentComponent, componentType, parentId, artifactId);
1145 if (foundArtifact != null && operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create) {
1146 log.debug("Artifact {} already exist", artifactId);
1147 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, foundArtifact.getArtifactLabel()));
1149 if (foundArtifact == null && operation.getArtifactOperationEnum() != ArtifactOperationEnum.Create) {
1150 log.debug("The artifact {} was not found on parent {}. ", artifactId, parentId);
1151 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ""));
1153 if (result == null) {
1154 result = Either.left(foundArtifact);
1159 private ArtifactDefinition findArtifact(Component parentComponent, ComponentTypeEnum componentType, String parentId, String artifactId) {
1160 ArtifactDefinition foundArtifact;
1161 if (parentComponent.getUniqueId().equals(parentId)) {
1162 foundArtifact = artifactsResolver.findArtifactOnComponent(parentComponent, componentType, artifactId);
1164 ComponentInstance instance = findComponentInstance(parentId, parentComponent);
1165 foundArtifact = artifactsResolver.findArtifactOnComponentInstance(instance, artifactId);
1167 return foundArtifact;
1170 private Either<Boolean, ResponseFormat> validateInformationalArtifact(ArtifactDefinition artifactInfo, Component parentComponent) {
1171 ComponentTypeEnum parentComponentType = parentComponent.getComponentType();
1172 ArtifactGroupTypeEnum groupType = artifactInfo.getArtifactGroupType();
1173 Either<Boolean, ResponseFormat> validationResult = Either.left(true);
1174 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
1175 if (artifactType == null) {
1176 validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType()));
1177 } else if (parentComponentType == ComponentTypeEnum.RESOURCE && groupType == ArtifactGroupTypeEnum.INFORMATIONAL) {
1178 String artifactTypeName = artifactType.getType();
1179 ResourceTypeEnum parentResourceType = ((Resource) parentComponent).getResourceType();
1180 Map<String, ArtifactTypeConfig> resourceInformationalArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceInformationalArtifacts();
1181 Set<String> validArtifactTypes = resourceInformationalArtifacts.keySet();
1182 if (!validArtifactTypes.contains(artifactTypeName)) {
1183 validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactTypeName));
1185 List<String> validResourceType = resourceInformationalArtifacts.get(artifactTypeName).getValidForResourceTypes();
1186 if (!validResourceType.contains(parentResourceType.name())) {
1187 validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactTypeName));
1191 return validationResult;
1194 private NodeTypeEnum convertParentType(ComponentTypeEnum componentType) {
1195 if (componentType.equals(ComponentTypeEnum.RESOURCE)) {
1196 return NodeTypeEnum.Resource;
1197 } else if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) {
1198 return NodeTypeEnum.ResourceInstance;
1200 return NodeTypeEnum.Service;
1204 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete(String parentId, String artifactId, User user, AuditingActionEnum auditingAction, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent,
1205 String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
1207 NodeTypeEnum parentType = convertParentType(componentType);
1208 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
1209 Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> getArtifactRes = null;
1210 ArtifactDefinition foundArtifact = null;
1211 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
1212 Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getContainerRes = null;
1213 org.openecomp.sdc.be.model.Component fetchedContainerComponent = null;
1214 boolean isDuplicated = false;
1216 Either<Boolean, StorageOperationStatus> needCloneRes = null;
1219 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Delete Artifact - lock resource: ");
1220 if (lockComponent.isRight()) {
1221 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right().value(), componentType, null);
1222 resultOp = Either.right(lockComponent.right().value());
1225 if (resultOp == null) {
1226 log.debug("Going to fetch the container component {}. ", parent.getUniqueId());
1227 getContainerRes = toscaOperationFacade.getToscaElement(parent.getUniqueId());
1228 if (getContainerRes.isRight()) {
1229 log.debug("Failed to fetch the container component {}. ", parentId);
1230 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(getContainerRes.right().value()), artifactId);
1231 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1232 resultOp = Either.right(responseFormat);
1235 if (resultOp == null) {
1236 fetchedContainerComponent = getContainerRes.left().value();
1237 log.debug("Going to find the artifact {} on the component {}", artifactId, fetchedContainerComponent.getUniqueId());
1238 getArtifactRes = findArtifact(artifactId, fetchedContainerComponent, parentId, componentType);
1239 if (getArtifactRes.isRight()) {
1240 log.debug("Failed to find the artifact {} belonging to {} on the component {}", artifactId, parentId, fetchedContainerComponent.getUniqueId());
1241 responseFormat = componentsUtils.getResponseFormatByArtifactId(getArtifactRes.right().value(), artifactId);
1242 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1243 resultOp = Either.right(responseFormat);
1245 foundArtifact = getArtifactRes.left().value().getLeft();
1246 esId = foundArtifact.getEsId();
1249 if (resultOp == null && StringUtils.isNotEmpty(esId)) {
1250 needCloneRes = artifactToscaOperation.isCloneNeeded(parent.getUniqueId(), foundArtifact, convertParentType(parent.getComponentType()));
1251 if (needCloneRes.isRight()) {
1252 log.debug("Failed to delete or update the artifact {}. Parent uniqueId is {}", artifactId, parentId);
1253 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(needCloneRes.right().value()), foundArtifact.getArtifactDisplayName());
1254 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1255 resultOp = Either.right(responseFormat);
1258 if (resultOp == null) {
1259 Either<ArtifactDataDefinition, StorageOperationStatus> updatedArtifactRes = deleteOrUpdateArtifactOnGraph(parent, parentId, artifactId, parentType, foundArtifact, needCloneRes.left().value());
1260 if (updatedArtifactRes.isRight()) {
1261 log.debug("Failed to delete or update the artifact {}. Parent uniqueId is {}", artifactId, parentId);
1262 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updatedArtifactRes.right().value()), foundArtifact.getArtifactDisplayName());
1263 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1264 resultOp = Either.right(responseFormat);
1266 isDuplicated = updatedArtifactRes.left().value().getDuplicated();
1270 if (resultOp == null && (!needCloneRes.left().value() && !isDuplicated)) {
1271 log.debug("Going to delete the artifact {} from the database. ", artifactId);
1272 CassandraOperationStatus cassandraStatus = artifactCassandraDao.deleteArtifact(esId);
1273 if (cassandraStatus != CassandraOperationStatus.OK) {
1274 log.debug("Failed to delete the artifact {} from the database. ", artifactId);
1275 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(convertToStorageOperationStatus(cassandraStatus)), foundArtifact.getArtifactDisplayName());
1276 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1277 resultOp = Either.right(responseFormat);
1280 if (resultOp == null && componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1282 List<GroupInstance> updatedGroupInstances = getUpdatedGroupInstances(artifactId, foundArtifact, getArtifactRes.left().value().getRight().getGroupInstances());
1283 if (CollectionUtils.isNotEmpty(updatedGroupInstances)) {
1284 Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(fetchedContainerComponent, componentType, parentId, updatedGroupInstances);
1285 if (status.isRight()) {
1286 log.debug("Failed to update groups of the component {}. ", fetchedContainerComponent.getUniqueId());
1287 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status.right().value()), foundArtifact.getArtifactDisplayName());
1288 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1289 resultOp = Either.right(responseFormat);
1293 if (resultOp == null && componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1294 StorageOperationStatus status = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentType);
1295 if (status != StorageOperationStatus.OK) {
1296 log.debug("Failed to generate new customization UUID for the component instance {}. ", parentId);
1297 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status), foundArtifact.getArtifactDisplayName());
1298 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1299 resultOp = Either.right(responseFormat);
1302 if (resultOp == null && componentType != ComponentTypeEnum.RESOURCE_INSTANCE) {
1303 List<GroupDataDefinition> updatedGroups = getUpdatedGroups(artifactId, foundArtifact, fetchedContainerComponent.getGroups());
1304 if (CollectionUtils.isNotEmpty(updatedGroups)) {
1305 Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(fetchedContainerComponent, componentType, updatedGroups);
1306 if (status.isRight()) {
1307 log.debug("Failed to update groups of the component {}. ", fetchedContainerComponent.getUniqueId());
1308 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status.right().value()), foundArtifact.getArtifactDisplayName());
1309 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1310 resultOp = Either.right(responseFormat);
1314 if (resultOp == null) {
1315 resultOp = Either.left(Either.left(foundArtifact));
1316 handleAuditing(auditingAction, parent, parentId, user, foundArtifact, null, artifactId, responseFormat, componentType, null);
1321 unlockComponent(resultOp, parent, inTransaction);
1326 private List<GroupDataDefinition> getUpdatedGroups(String artifactId, ArtifactDefinition foundArtifact, List<GroupDefinition> groups) {
1327 List<GroupDataDefinition> updatedGroups = new ArrayList<>();
1328 boolean isUpdated = false;
1329 if (groups != null) {
1330 for (GroupDefinition group : groups) {
1332 if (CollectionUtils.isNotEmpty(group.getArtifacts()) && group.getArtifacts().contains(artifactId)) {
1333 group.getArtifacts().remove(artifactId);
1336 if (CollectionUtils.isNotEmpty(group.getArtifactsUuid()) && group.getArtifactsUuid().contains(foundArtifact.getArtifactUUID())) {
1337 group.getArtifactsUuid().remove(foundArtifact.getArtifactUUID());
1341 updatedGroups.add(group);
1345 return updatedGroups;
1348 private List<GroupInstance> getUpdatedGroupInstances(String artifactId, ArtifactDefinition foundArtifact, List<GroupInstance> groupInstances) {
1349 List<GroupInstance> updatedGroupInstances = new ArrayList<>();
1350 if (CollectionUtils.isNotEmpty(groupInstances)) {
1351 boolean isUpdated = false;
1352 for (GroupInstance groupInstance : groupInstances) {
1354 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifacts()) && groupInstance.getGroupInstanceArtifacts().contains(artifactId)) {
1355 groupInstance.getGroupInstanceArtifacts().remove(artifactId);
1358 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifactsUuid()) && groupInstance.getGroupInstanceArtifactsUuid().contains(foundArtifact.getArtifactUUID())) {
1359 groupInstance.getGroupInstanceArtifactsUuid().remove(foundArtifact.getArtifactUUID());
1363 updatedGroupInstances.add(groupInstance);
1367 return updatedGroupInstances;
1370 private Either<ArtifactDataDefinition, StorageOperationStatus> deleteOrUpdateArtifactOnGraph(Component component, String parentId, String artifactId, NodeTypeEnum parentType, ArtifactDefinition foundArtifact, Boolean cloneIsNeeded) {
1372 Either<ArtifactDataDefinition, StorageOperationStatus> result;
1373 boolean isMandatory = foundArtifact.getMandatory() || foundArtifact.getServiceApi();
1374 String componentId = component.getUniqueId();
1375 String instanceId = componentId.equals(parentId) ? null : parentId;
1377 log.debug("Going to update mandatory artifact {} from the component {}", artifactId, parentId);
1378 resetMandatoryArtifactFields(foundArtifact);
1379 result = artifactToscaOperation.updateArtifactOnGraph(componentId, foundArtifact, parentType, artifactId, instanceId, true);
1380 } else if (cloneIsNeeded) {
1381 log.debug("Going to clone artifacts and to delete the artifact {} from the component {}", artifactId, parentId);
1382 result = artifactToscaOperation.deleteArtifactWithClonnigOnGraph(componentId, foundArtifact, parentType, instanceId, false);
1384 log.debug("Going to delete the artifact {} from the component {}", artifactId, parentId);
1385 result = artifactToscaOperation.removeArtifactOnGraph(foundArtifact, componentId, instanceId, parentType, false);
1390 private Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> findArtifact(String artifactId, Component fetchedContainerComponent, String parentId, ComponentTypeEnum componentType) {
1392 Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> result = null;
1393 Map<String, ArtifactDefinition> artifacts = new HashMap<>();
1394 ComponentInstance foundInstance = null;
1395 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE && StringUtils.isNotEmpty(parentId)) {
1396 Optional<ComponentInstance> componentInstanceOpt = fetchedContainerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(parentId)).findFirst();
1397 if (!componentInstanceOpt.isPresent()) {
1398 result = Either.right(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER);
1400 foundInstance = componentInstanceOpt.get();
1401 fetchArtifactsFromInstance(artifactId, artifacts, foundInstance);
1404 fetchArtifactsFromComponent(artifactId, fetchedContainerComponent, artifacts);
1406 if (result == null) {
1407 if (artifacts.containsKey(artifactId)) {
1408 result = Either.left(new ImmutablePair<>(artifacts.get(artifactId), foundInstance));
1410 result = Either.right(ActionStatus.ARTIFACT_NOT_FOUND);
1416 private void fetchArtifactsFromComponent(String artifactId, Component component, Map<String, ArtifactDefinition> artifacts) {
1417 Map<String, ArtifactDefinition> currArtifacts;
1418 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getDeploymentArtifacts())) {
1419 currArtifacts = component.getDeploymentArtifacts().values().stream().collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1420 if (MapUtils.isNotEmpty(currArtifacts)) {
1421 artifacts.putAll(currArtifacts);
1424 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getArtifacts())) {
1425 currArtifacts = component.getArtifacts().values().stream().collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1426 if (MapUtils.isNotEmpty(currArtifacts)) {
1427 artifacts.putAll(currArtifacts);
1430 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getArtifacts())) {
1431 currArtifacts = component.getToscaArtifacts().values().stream().collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1432 if (MapUtils.isNotEmpty(currArtifacts)) {
1433 artifacts.putAll(currArtifacts);
1438 private void fetchArtifactsFromInstance(String artifactId, Map<String, ArtifactDefinition> artifacts, ComponentInstance instance) {
1439 Map<String, ArtifactDefinition> currArtifacts;
1440 if (MapUtils.isNotEmpty(instance.getDeploymentArtifacts())) {
1441 currArtifacts = instance.getDeploymentArtifacts().values().stream().collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1442 if (MapUtils.isNotEmpty(currArtifacts)) {
1443 artifacts.putAll(currArtifacts);
1446 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(instance.getArtifacts())) {
1447 currArtifacts = instance.getArtifacts().values().stream().collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1448 if (MapUtils.isNotEmpty(currArtifacts)) {
1449 artifacts.putAll(currArtifacts);
1454 private StorageOperationStatus convertToStorageOperationStatus(CassandraOperationStatus cassandraStatus) {
1455 StorageOperationStatus result;
1456 switch (cassandraStatus) {
1458 result = StorageOperationStatus.OK;
1461 result = StorageOperationStatus.NOT_FOUND;
1463 case CLUSTER_NOT_CONNECTED:
1464 case KEYSPACE_NOT_CONNECTED:
1465 result = StorageOperationStatus.CONNECTION_FAILURE;
1468 result = StorageOperationStatus.GENERAL_ERROR;
1474 private void resetMandatoryArtifactFields(ArtifactDefinition fetchedArtifact) {
1475 if (fetchedArtifact != null) {
1476 log.debug("Going to reset mandatory artifact {} fields. ", fetchedArtifact.getUniqueId());
1477 fetchedArtifact.setEsId("");
1478 fetchedArtifact.setArtifactName("");
1479 fetchedArtifact.setDescription("");
1480 fetchedArtifact.setApiUrl("");
1481 fetchedArtifact.setArtifactChecksum("");
1482 nodeTemplateOperation.setDefaultArtifactTimeout(fetchedArtifact.getArtifactGroupType(), fetchedArtifact);
1483 fetchedArtifact.setArtifactUUID("");
1484 long time = System.currentTimeMillis();
1485 fetchedArtifact.setPayloadUpdateDate(time);
1486 fetchedArtifact.setHeatParameters(null);
1487 fetchedArtifact.setHeatParamsUpdateDate(null);
1491 private StorageOperationStatus generateCustomizationUUIDOnInstance(String componentId, String instanceId, ComponentTypeEnum componentType) {
1492 StorageOperationStatus error = StorageOperationStatus.OK;
1493 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1494 log.debug("Need to re-generate customization UUID for instance {}", instanceId);
1495 error = toscaOperationFacade.generateCustomizationUUIDOnInstance(componentId, instanceId);
1500 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDownload(String componentId, String artifactId, User user, AuditingActionEnum auditingAction, ComponentTypeEnum componentType,
1501 org.openecomp.sdc.be.model.Component parent, boolean shouldLock, boolean inTransaction) {
1502 Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(componentId, artifactId, componentType, parent.getUniqueId());
1503 if (artifactById.isRight()) {
1504 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(artifactById.right().value());
1505 log.debug("Error when getting artifact info by id{}, error: {}", artifactId, actionStatus.name());
1506 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(actionStatus, "");
1507 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
1508 return Either.right(responseFormat);
1510 ArtifactDefinition artifactDefinition = artifactById.left().value();
1511 if (artifactDefinition == null) {
1512 log.debug("Empty artifact definition returned from DB by artifact id {}", artifactId);
1513 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, "");
1514 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
1515 return Either.right(responseFormat);
1517 Either<ArtifactDefinition, Operation> insideEither = Either.left(artifactDefinition);
1518 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
1519 handleAuditing(auditingAction, parent, componentId, user, artifactDefinition, null, artifactId, responseFormat, componentType, null);
1520 return Either.left(insideEither);
1523 private Either<ArtifactDefinition, ResponseFormat> fetchCurrentArtifact(String parentId, ArtifactOperationInfo operation, String artifactId) {
1524 Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(parentId, artifactId);
1525 if (!(operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create) && artifactById.isRight()) {
1526 // in case of update artifact must be
1527 BeEcompErrorManager.getInstance().logBeArtifactMissingError("Artifact Update / Upload", artifactId);
1528 log.debug("Failed to fetch artifact {}. error: {}", artifactId, artifactById.right().value());
1529 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(artifactById.right().value()), artifactId));
1531 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create && artifactById.isLeft()) {
1532 log.debug("Artifact {} already exist", artifactId);
1533 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactById.left().value().getArtifactLabel()));
1535 ArtifactDefinition currentArtifactInfo = null;
1536 if (artifactById.isLeft()) {
1537 // get previous value
1538 currentArtifactInfo = artifactById.left().value();
1540 return Either.left(currentArtifactInfo);
1543 private Either<ActionStatus, ResponseFormat> handleArtifactLabel(String componentId, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, String interfaceName, String operationName,
1544 ArtifactDefinition currentArtifactInfo, ComponentTypeEnum componentType, boolean inTransaction) {
1545 String artifactLabel = artifactInfo.getArtifactLabel();
1547 if (operationName == null && (artifactInfo.getArtifactLabel() == null || artifactInfo.getArtifactLabel().isEmpty())) {
1548 BeEcompErrorManager.getInstance().logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel");
1549 log.debug("missing artifact logical name for component {}", componentId);
1550 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_LABEL));
1552 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create && !artifactInfo.getMandatory()) {
1554 if (operationName != null) {
1555 if (artifactInfo.getArtifactLabel() != null && !operationName.equals(artifactInfo.getArtifactLabel())) {
1556 log.debug("artifact label cannot be set {}", artifactLabel);
1557 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_LOGICAL_NAME_CANNOT_BE_CHANGED));
1559 artifactLabel = operationName;
1562 String displayName = artifactInfo.getArtifactDisplayName();
1563 if (displayName == null || displayName.isEmpty())
1564 displayName = artifactLabel;
1565 displayName = ValidationUtils.cleanArtifactDisplayName(displayName);
1566 // if (!ValidationUtils.validateArtifactDisplayName(displayName)) {
1567 // log.debug("Invalid format form Artifact displayName : {}", displayName);
1568 // return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1570 artifactInfo.setArtifactDisplayName(displayName);
1572 if (!ValidationUtils.validateArtifactLabel(artifactLabel)) {
1573 log.debug("Invalid format form Artifact label : {}", artifactLabel);
1574 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1576 artifactLabel = ValidationUtils.normalizeArtifactLabel(artifactLabel);
1578 if (artifactLabel.isEmpty()) {
1579 log.debug("missing normalized artifact logical name for component {}", componentId);
1580 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_LABEL));
1583 if (!ValidationUtils.validateArtifactLabelLength(artifactLabel)) {
1584 log.debug("Invalid lenght form Artifact label : {}", artifactLabel);
1585 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_LABEL, String.valueOf(ValidationUtils.ARTIFACT_LABEL_LENGTH)));
1587 if (!validateLabelUniqueness(componentId, artifactLabel, componentType)) {
1588 log.debug("Non unique Artifact label : {}", artifactLabel);
1589 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactLabel));
1592 artifactInfo.setArtifactLabel(artifactLabel);
1594 if (currentArtifactInfo != null && !currentArtifactInfo.getArtifactLabel().equals(artifactInfo.getArtifactLabel())) {
1595 log.info("Logical artifact's name cannot be changed {}", artifactId);
1596 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_LOGICAL_NAME_CANNOT_BE_CHANGED));
1598 return Either.left(ActionStatus.OK);
1601 private boolean validateLabelUniqueness(String parentId, String artifactLabel, ComponentTypeEnum componentType) {
1602 boolean isUnique = true;
1603 if (componentType.equals(ComponentTypeEnum.RESOURCE)) {
1606 // Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifacts = artifactOperation.getArtifacts(parentId, parentType, inTransaction);
1607 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifacts = artifactToscaOperation.getArtifacts(parentId);
1608 if (artifacts.isLeft()) {
1609 for (String label : artifacts.left().value().keySet()) {
1610 if (label.equals(artifactLabel)) {
1616 if (componentType.equals(ComponentTypeEnum.RESOURCE)) {
1617 Either<Map<String, InterfaceDefinition>, StorageOperationStatus> allInterfacesOfResource = interfaceLifecycleOperation.getAllInterfacesOfResource(parentId, true, true);
1618 if (allInterfacesOfResource.isLeft()) {
1619 for (InterfaceDefinition interace : allInterfacesOfResource.left().value().values()) {
1620 for (Operation operation : interace.getOperationsMap().values()) {
1621 if (operation.getImplementation() != null && operation.getImplementation().getArtifactLabel().equals(artifactLabel)) {
1632 // ***************************************************************
1634 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> createArtifact(org.openecomp.sdc.be.model.Component parent, String parentId, ArtifactDefinition artifactInfo, byte[] decodedPayload, User user,
1635 ComponentTypeEnum componentTypeEnum, AuditingActionEnum auditingActionEnum, String interfaceType, String operationName) {
1637 ESArtifactData artifactData = createEsArtifactData(artifactInfo, decodedPayload);
1638 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
1639 Either<ArtifactDefinition, Operation> insideEither = null;
1640 ComponentInstance foundInstance = findComponentInstance(parentId, parent);
1641 String instanceId = null;
1642 String instanceName = null;
1643 if (foundInstance != null) {
1644 instanceId = foundInstance.getUniqueId();
1645 instanceName = foundInstance.getName();
1647 if (artifactData == null) {
1648 BeEcompErrorManager.getInstance().logBeDaoSystemError("Upload Artifact");
1649 log.debug("Failed to create artifact object for ES.");
1650 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
1651 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, null);
1652 resultOp = Either.right(responseFormat);
1656 // set on graph object id of artifact in ES!
1657 artifactInfo.setEsId(artifactData.getId());
1659 boolean isLeft = false;
1660 String artifactUniqueId = null;
1661 StorageOperationStatus error = null;
1662 if (interfaceType != null && operationName != null) {
1663 // lifecycle artifact
1664 Operation operation = convertToOperation(artifactInfo, operationName);
1666 Either<Operation, StorageOperationStatus> result = interfaceLifecycleOperation.updateInterfaceOperation(parentId, interfaceType, operationName, operation);
1668 isLeft = result.isLeft();
1670 artifactUniqueId = result.left().value().getImplementation().getUniqueId();
1671 result.left().value().getImplementation();
1673 insideEither = Either.right(result.left().value());
1674 resultOp = Either.left(insideEither);
1676 error = result.right().value();
1679 // information/deployment/api aritfacts
1680 log.trace("Try to create entry on graph");
1681 NodeTypeEnum nodeType = convertParentType(componentTypeEnum);
1682 Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.addArifactToComponent(artifactInfo, parent.getUniqueId(), nodeType, true, instanceId);
1684 isLeft = result.isLeft();
1686 artifactUniqueId = result.left().value().getUniqueId();
1687 result.left().value();
1689 insideEither = Either.left(result.left().value());
1690 resultOp = Either.left(insideEither);
1692 error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentTypeEnum);
1693 if (error != StorageOperationStatus.OK) {
1698 error = result.right().value();
1702 boolean res = saveArtifacts(artifactData, parentId, false);
1703 // String uniqueId = artifactDefinition.getUniqueId();
1706 log.debug("Artifact saved into ES - {}", artifactUniqueId);
1708 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
1709 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, artifactUniqueId, artifactUniqueId, responseFormat, componentTypeEnum, instanceName);
1712 BeEcompErrorManager.getInstance().logBeDaoSystemError("Upload Artifact");
1713 log.debug("Failed to save the artifact.");
1714 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
1715 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, artifactUniqueId, responseFormat, componentTypeEnum, instanceName);
1717 resultOp = Either.right(responseFormat);
1721 log.debug("Failed to create entry on graph for artifact {}", artifactInfo.getArtifactName());
1722 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(error), artifactInfo.getArtifactDisplayName());
1723 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, instanceName);
1724 resultOp = Either.right(responseFormat);
1730 private ComponentInstance findComponentInstance(String componentInstanceId, Component containerComponent) {
1731 ComponentInstance foundInstance = null;
1732 if (CollectionUtils.isNotEmpty(containerComponent.getComponentInstances())) {
1733 foundInstance = containerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(componentInstanceId)).findFirst().orElse(null);
1735 return foundInstance;
1738 private Either<Boolean, ResponseFormat> validateDeploymentArtifact(Component parentComponent, String parentId, String userId, boolean isCreate, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, NodeTypeEnum parentType) {
1740 Either<Boolean, ResponseFormat> result = Either.left(true);
1741 Wrapper<ResponseFormat> responseWrapper = new Wrapper<ResponseFormat>();
1743 validateArtifactTypeExists(responseWrapper, artifactInfo);
1745 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
1747 Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts = fillDeploymentArtifactTypeConf(parentType);
1749 if (responseWrapper.isEmpty()) {
1750 validateDeploymentArtifactConf(artifactInfo, responseWrapper, artifactType, resourceDeploymentArtifacts);
1753 if (responseWrapper.isEmpty()) {
1754 // Common code for all types
1755 // not allowed to change artifactType
1757 Either<Boolean, ResponseFormat> validateServiceApiType = validateArtifactTypeNotChanged(artifactInfo, currentArtifact);
1758 if (validateServiceApiType.isRight()) {
1759 responseWrapper.setInnerElement(validateServiceApiType.right().value());
1763 if (responseWrapper.isEmpty()) {
1764 if (parentType.equals(NodeTypeEnum.Resource)) {
1765 // if (parentComponent instanceof Resource) {
1766 Resource resource = (Resource) parentComponent;
1767 ResourceTypeEnum resourceType = resource.getResourceType();
1768 ArtifactTypeConfig config = resourceDeploymentArtifacts.get(artifactType.getType());
1769 if (config == null) {
1770 responseWrapper.setInnerElement(ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType()));
1772 List<String> myList = config.getValidForResourceTypes();
1773 Either<Boolean, ResponseFormat> either = validateResourceType(resourceType, artifactInfo, myList);
1774 if (either.isRight()) {
1775 responseWrapper.setInnerElement(either.right().value());
1780 if (responseWrapper.isEmpty()) {
1781 validateFileExtension(responseWrapper, () -> getDeploymentArtifactTypeConfig(parentType, artifactType), artifactInfo, parentType, artifactType);
1784 if (responseWrapper.isEmpty() && !NodeTypeEnum.ResourceInstance.equals(parentType)) {
1785 String artifactName = artifactInfo.getArtifactName();
1786 if (isCreate || !artifactName.equalsIgnoreCase(currentArtifact.getArtifactName())) {
1787 validateSingleDeploymentArtifactName(responseWrapper, artifactName, parentComponent, parentType);
1791 if (responseWrapper.isEmpty()) {
1792 switch (artifactType) {
1796 result = validateHeatDeploymentArtifact(parentComponent, userId, isCreate, artifactInfo, currentArtifact, parentType);
1800 result = validateHeatEnvDeploymentArtifact(parentComponent, parentId, userId, isCreate, artifactInfo, parentType);
1801 artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
1804 case DCAE_INVENTORY_TOSCA:
1805 case DCAE_INVENTORY_JSON:
1806 case DCAE_INVENTORY_POLICY:
1807 // Validation is done in handle payload.
1808 case DCAE_INVENTORY_DOC:
1809 case DCAE_INVENTORY_BLUEPRINT:
1810 case DCAE_INVENTORY_EVENT:
1811 // No specific validation
1813 artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
1819 if (!responseWrapper.isEmpty()) {
1820 result = Either.right(responseWrapper.getInnerElement());
1825 private void validateDeploymentArtifactConf(ArtifactDefinition artifactInfo, Wrapper<ResponseFormat> responseWrapper, ArtifactTypeEnum artifactType, Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts) {
1826 if ((resourceDeploymentArtifacts == null) || !resourceDeploymentArtifacts.containsKey(artifactType.name())) {
1827 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType());
1828 responseWrapper.setInnerElement(responseFormat);
1829 log.debug("Artifact Type: {} Not found !", artifactInfo.getArtifactType());
1833 private Map<String, ArtifactTypeConfig> fillDeploymentArtifactTypeConf(NodeTypeEnum parentType) {
1834 Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts = null;
1835 if (parentType.equals(NodeTypeEnum.Resource)) {
1836 resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceDeploymentArtifacts();
1837 } else if (parentType.equals(NodeTypeEnum.ResourceInstance)) {
1838 resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceInstanceDeploymentArtifacts();
1840 resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getServiceDeploymentArtifacts();
1842 return resourceDeploymentArtifacts;
1845 public void validateArtifactTypeExists(Wrapper<ResponseFormat> responseWrapper, ArtifactDefinition artifactInfo) {
1846 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
1847 if (artifactType == null) {
1848 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType());
1849 responseWrapper.setInnerElement(responseFormat);
1850 log.debug("Artifact Type: {} Not found !", artifactInfo.getArtifactType());
1854 private ArtifactTypeConfig getDeploymentArtifactTypeConfig(NodeTypeEnum parentType, ArtifactTypeEnum artifactType) {
1855 ArtifactTypeConfig retConfig = null;
1856 String fileType = artifactType.getType();
1857 if (parentType.equals(NodeTypeEnum.Resource)) {
1858 retConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceDeploymentArtifacts().get(fileType);
1859 } else if (parentType.equals(NodeTypeEnum.Service)) {
1860 retConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getServiceDeploymentArtifacts().get(fileType);
1861 } else if (parentType.equals(NodeTypeEnum.ResourceInstance)) {
1862 retConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceInstanceDeploymentArtifacts().get(fileType);
1867 private Either<Boolean, ResponseFormat> extractHeatParameters(ArtifactDefinition artifactInfo) {
1868 // extract heat parameters
1869 if (artifactInfo.getPayloadData() != null) {
1870 String heatDecodedPayload = new String(Base64.decodeBase64(artifactInfo.getPayloadData()));
1871 Either<List<HeatParameterDefinition>, ResultStatusEnum> heatParameters = ImportUtils.getHeatParamsWithoutImplicitTypes(heatDecodedPayload, artifactInfo.getArtifactType());
1872 if (heatParameters.isRight() && (!heatParameters.right().value().equals(ResultStatusEnum.ELEMENT_NOT_FOUND))) {
1873 log.info("failed to parse heat parameters ");
1874 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactInfo.getArtifactType());
1875 return Either.right(responseFormat);
1876 } else if (heatParameters.isLeft() && heatParameters.left().value() != null) {
1877 artifactInfo.setListHeatParameters(heatParameters.left().value());
1880 return Either.left(true);
1885 public void validateFileExtension(Wrapper<ResponseFormat> responseWrapper, IDeploymentArtifactTypeConfigGetter deploymentConfigGetter, ArtifactDefinition artifactInfo, NodeTypeEnum parentType, ArtifactTypeEnum artifactType) {
1886 String fileType = artifactType.getType();
1887 List<String> acceptedTypes = null;
1888 ArtifactTypeConfig deploymentAcceptedTypes = deploymentConfigGetter.getDeploymentArtifactConfig();
1889 if (!parentType.equals(NodeTypeEnum.Resource) && !parentType.equals(NodeTypeEnum.Service) && !parentType.equals(NodeTypeEnum.ResourceInstance)) {
1890 log.debug("parent type of artifact can be either resource or service");
1891 responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
1895 if (deploymentAcceptedTypes == null) {
1896 log.debug("parent type of artifact can be either resource or service");
1897 responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType()));
1900 acceptedTypes = deploymentAcceptedTypes.getAcceptedTypes();
1903 * No need to check specific types. In case there are no acceptedTypes in configuration, then any type is accepted.
1905 * if ((!artifactType.equals(ArtifactTypeEnum.OTHER) && !artifactType.equals(ArtifactTypeEnum.HEAT_ARTIFACT )) && (acceptedTypes == null || acceptedTypes.isEmpty()) ) { log.debug( "No accepted types found for type {}, parent type {}",
1906 * fileType, parentType.getName()); String methodName = new Object() { }.getClass().getEnclosingMethod().getName(); String configEntryMissing = (parentType.equals(NodeTypeEnum.Resource)) ? "resourceDeploymentArtifacts:" + fileType :
1907 * "serviceDeploymentArtifacts:" + fileType; BeEcompErrorManager.getInstance().processEcompError(EcompErrorName. BeMissingConfigurationError, methodName, configEntryMissing); BeEcompErrorManager.getInstance().logBeMissingConfigurationError(
1908 * methodName, configEntryMissing); responseWrapper.setInnerElement(componentsUtils.getResponseFormat( ActionStatus.GENERAL_ERROR)); return; }
1911 String artifactName = artifactInfo.getArtifactName();
1912 String fileExtension = GeneralUtility.getFilenameExtension(artifactName);
1913 // Pavel - File extension validation is case-insensitive - Ella,
1915 if (acceptedTypes != null && !acceptedTypes.isEmpty() && !acceptedTypes.contains(fileExtension.toLowerCase())) {
1916 log.debug("File extension \"{}\" is not allowed for {} which is of type:{}", fileExtension, artifactName, fileType);
1917 responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.WRONG_ARTIFACT_FILE_EXTENSION, fileType));
1922 private Either<Boolean, ResponseFormat> validateHeatEnvDeploymentArtifact(Component parentComponent, String parentId, String userId, boolean isCreate, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) {
1924 Wrapper<ResponseFormat> errorWrapper = new Wrapper<ResponseFormat>();
1925 Wrapper<ArtifactDefinition> heatMDWrapper = new Wrapper<ArtifactDefinition>();
1926 Wrapper<byte[]> payloadWrapper = new Wrapper<>();
1928 if (errorWrapper.isEmpty()) {
1929 validateValidYaml(errorWrapper, artifactInfo);
1932 if (errorWrapper.isEmpty()) {
1933 // Validate Heat Exist
1934 validateHeatExist(parentComponent.getUniqueId(), parentId, errorWrapper, heatMDWrapper, artifactInfo, parentType, parentComponent.getComponentType());
1937 // if (errorWrapper.isEmpty() && isCreate) {
1938 // // Validate Only Single HeatEnv Artifact
1939 // validateSingleArtifactType(errorWrapper, ArtifactTypeEnum.HEAT_ENV, parentComponent, parentType, parentId);
1942 if (errorWrapper.isEmpty() && !heatMDWrapper.isEmpty()) {
1943 fillArtifactPayloadValidation(errorWrapper, payloadWrapper, heatMDWrapper.getInnerElement());
1946 if (errorWrapper.isEmpty() && !heatMDWrapper.isEmpty()) {
1947 validateEnvVsHeat(errorWrapper, artifactInfo, heatMDWrapper.getInnerElement(), payloadWrapper.getInnerElement());
1951 Either<Boolean, ResponseFormat> eitherResponse;
1952 if (errorWrapper.isEmpty()) {
1953 eitherResponse = Either.left(true);
1955 eitherResponse = Either.right(errorWrapper.getInnerElement());
1957 return eitherResponse;
1960 public void fillArtifactPayloadValidation(Wrapper<ResponseFormat> errorWrapper, Wrapper<byte[]> payloadWrapper, ArtifactDefinition artifactDefinition) {
1961 if (artifactDefinition.getPayloadData() == null || artifactDefinition.getPayloadData().length == 0) {
1962 Either<Boolean, ResponseFormat> fillArtifactPayload = fillArtifactPayload(payloadWrapper, artifactDefinition);
1963 if (fillArtifactPayload.isRight()) {
1964 errorWrapper.setInnerElement(fillArtifactPayload.right().value());
1965 log.debug("Error getting payload for artifact:{}", artifactDefinition.getArtifactName());
1968 payloadWrapper.setInnerElement(artifactDefinition.getPayloadData());
1972 public Either<Boolean, ResponseFormat> fillArtifactPayload(Wrapper<byte[]> payloadWrapper, ArtifactDefinition artifactMD) {
1973 Either<Boolean, ResponseFormat> result = Either.left(true);
1974 Either<ESArtifactData, CassandraOperationStatus> eitherArtifactData = artifactCassandraDao.getArtifact(artifactMD.getEsId());
1975 if (eitherArtifactData.isLeft()) {
1976 byte[] data = eitherArtifactData.left().value().getDataAsArray();
1977 data = Base64.encodeBase64(data);
1978 payloadWrapper.setInnerElement(data);
1980 StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(eitherArtifactData.right().value());
1981 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus));
1982 result = Either.right(responseFormat);
1988 @SuppressWarnings("unchecked")
1989 private void validateEnvVsHeat(Wrapper<ResponseFormat> errorWrapper, ArtifactDefinition envArtifact, ArtifactDefinition heatArtifact, byte[] heatPayloadData) {
1990 String envPayload = new String(Base64.decodeBase64(envArtifact.getPayloadData()));
1991 Map<String, Object> heatEnvToscaJson = (Map<String, Object>) new Yaml().load(envPayload);
1992 String heatDecodedPayload = new String(Base64.decodeBase64(heatPayloadData));
1993 Map<String, Object> heatToscaJson = (Map<String, Object>) new Yaml().load(heatDecodedPayload);
1995 Either<Map<String, Object>, ResultStatusEnum> eitherHeatEnvProperties = ImportUtils.findFirstToscaMapElement(heatEnvToscaJson, ToscaTagNamesEnum.PARAMETERS);
1996 Either<Map<String, Object>, ResultStatusEnum> eitherHeatProperties = ImportUtils.findFirstToscaMapElement(heatToscaJson, ToscaTagNamesEnum.PARAMETERS);
1997 if (eitherHeatEnvProperties.isRight()) {
1998 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.CORRUPTED_FORMAT, "Heat Env");
1999 errorWrapper.setInnerElement(responseFormat);
2000 log.debug("Invalid heat env format for file:{}", envArtifact.getArtifactName());
2001 } else if (eitherHeatProperties.isRight()) {
2002 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, envArtifact.getArtifactName(), heatArtifact.getArtifactName());
2003 errorWrapper.setInnerElement(responseFormat);
2004 log.debug("Validation of heat_env for artifact:{} vs heat artifact for artifact :{} failed", envArtifact.getArtifactName(), heatArtifact.getArtifactName());
2006 Set<String> heatPropertiesKeys = eitherHeatProperties.left().value().keySet();
2007 Set<String> heatEnvPropertiesKeys = eitherHeatEnvProperties.left().value().keySet();
2008 heatEnvPropertiesKeys.removeAll(heatPropertiesKeys);
2009 if (heatEnvPropertiesKeys.size() > 0) {
2010 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, envArtifact.getArtifactName(), heatArtifact.getArtifactName());
2011 errorWrapper.setInnerElement(responseFormat);
2016 private void validateValidYaml(Wrapper<ResponseFormat> errorWrapper, ArtifactDefinition artifactInfo) {
2017 YamlToObjectConverter yamlConvertor = new YamlToObjectConverter();
2018 boolean isYamlValid = yamlConvertor.isValidYamlEncoded64(artifactInfo.getPayloadData());
2020 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.INVALID_YAML, artifactInfo.getArtifactType());
2021 errorWrapper.setInnerElement(responseFormat);
2022 log.debug("Yaml is not valid for artifact : {}", artifactInfo.getArtifactName());
2026 @SuppressWarnings("restriction")
2027 public boolean isValidXml(byte[] xmlToParse) {
2028 XMLReader parser = new SAXParser();
2029 boolean isXmlValid = true;
2031 parser.parse(new InputSource(new ByteArrayInputStream(xmlToParse)));
2032 } catch (IOException | SAXException e) {
2033 log.debug("Xml is invalid : {}", e.getMessage(), e);
2039 public boolean isValidJson(byte[] jsonToParse) {
2040 String parsed = new String(jsonToParse);
2042 gson.fromJson(parsed, Object.class);
2043 } catch (Exception e) {
2044 log.debug("Json is invalid : {}", e.getMessage(), e);
2050 public void validateSingleArtifactType(Wrapper<ResponseFormat> errorWrapper, ArtifactTypeEnum allowedArtifactType, Component parentComponent, NodeTypeEnum parentType, String parentRiId) {
2051 boolean typeArtifactFound = false;
2052 // Iterator<ArtifactDefinition> parentDeploymentArtifactsItr =
2053 // (parentType == NodeTypeEnum.Resource) ?
2054 // informationDeployedArtifactsBusinessLogic.getAllDeployableArtifacts((Resource)
2055 // parentComponent).iterator()
2056 // : getDeploymentArtifacts(parentComponent, parentType).iterator();
2058 Iterator<ArtifactDefinition> parentDeploymentArtifactsItr = getDeploymentArtifacts(parentComponent, parentType, parentRiId).iterator();
2060 while (!typeArtifactFound && parentDeploymentArtifactsItr.hasNext()) {
2061 ArtifactTypeEnum foundArtifactType = ArtifactTypeEnum.findType(parentDeploymentArtifactsItr.next().getArtifactType());
2062 typeArtifactFound = (foundArtifactType == allowedArtifactType);
2064 if (typeArtifactFound) {
2065 String parentName = parentComponent.getName();
2066 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.DEPLOYMENT_ARTIFACT_OF_TYPE_ALREADY_EXISTS, parentType.name(), parentName, allowedArtifactType.getType(), allowedArtifactType.getType());
2068 errorWrapper.setInnerElement(responseFormat);
2069 log.debug("Can't upload artifact of type: {}, because another artifact of this type already exist.", allowedArtifactType.getType());
2074 public void validateSingleDeploymentArtifactName(Wrapper<ResponseFormat> errorWrapper, String artifactName, Component parentComponent, NodeTypeEnum parentType) {
2075 boolean artifactNameFound = false;
2076 // Iterator<ArtifactDefinition> parentDeploymentArtifactsItr =
2077 // (parentType == NodeTypeEnum.Resource) ?
2078 // informationDeployedArtifactsBusinessLogic.getAllDeployableArtifacts((Resource)
2079 // parentComponent).iterator()
2080 // : getDeploymentArtifacts(parentComponent, parentType).iterator();
2082 Iterator<ArtifactDefinition> parentDeploymentArtifactsItr = getDeploymentArtifacts(parentComponent, parentType, null).iterator();
2084 while (!artifactNameFound && parentDeploymentArtifactsItr.hasNext()) {
2085 artifactNameFound = (artifactName.equalsIgnoreCase(parentDeploymentArtifactsItr.next().getArtifactName()));
2087 if (artifactNameFound) {
2088 String parentName = parentComponent.getName();
2089 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.DEPLOYMENT_ARTIFACT_NAME_ALREADY_EXISTS, parentType.name(), parentName, artifactName);
2091 errorWrapper.setInnerElement(responseFormat);
2092 log.debug("Can't upload artifact: {}, because another artifact with this name already exist.", artifactName);
2097 private void validateHeatExist(String componentId, String parentRiId, Wrapper<ResponseFormat> errorWrapper, Wrapper<ArtifactDefinition> heatArtifactMDWrapper, ArtifactDefinition heatEnvArtifact, NodeTypeEnum parentType,
2098 ComponentTypeEnum componentType) {
2099 Either<ArtifactDefinition, StorageOperationStatus> res = artifactToscaOperation.getHeatArtifactByHeatEnvId(parentRiId, heatEnvArtifact, parentType, componentId, componentType);
2100 if (res.isRight()) {
2101 ResponseFormat responseFormat;
2102 if (res.right().value() == StorageOperationStatus.NOT_FOUND) {
2103 responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT);
2105 responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT);
2107 errorWrapper.setInnerElement(responseFormat);
2111 ArtifactDefinition heatArtifact = res.left().value();
2112 heatArtifactMDWrapper.setInnerElement(heatArtifact);
2113 // Iterator<ArtifactDefinition> parentArtifactsItr = parentDeploymentArtifacts.iterator();
2114 // while (!heatFound && parentArtifactsItr.hasNext()) {
2115 // ArtifactDefinition currArtifact = parentArtifactsItr.next();
2116 // if (heatArtifact.getUniqueId().equals(currArtifact.getUniqueId())) {
2117 // heatFound = true;
2118 // heatArtifactMDWrapper.setInnerElement(currArtifact);
2119 // log.trace("In validateHeatExist found artifact {}", currArtifact);
2121 // * ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(currArtifact.getArtifactType()); if(artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_VOL || artifactType == ArtifactTypeEnum.HEAT_NET){
2122 // * heatFound = true; } if (heatFound) { heatArtifactMDWrapper.setInnerElement(currArtifact); }
2126 // if (!heatFound) {
2127 // ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT);
2128 // errorWrapper.setInnerElement(responseFormat);
2129 // log.debug("Can't create heat env artifact because No heat Artifact exist.");
2134 private Either<Boolean, ResponseFormat> validateHeatDeploymentArtifact(Component parentComponent, String userId, boolean isCreate, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, NodeTypeEnum parentType) {
2135 log.trace("Started HEAT pre-payload validation for artifact {}", artifactInfo.getArtifactLabel());
2136 // timeout > 0 for HEAT artifacts
2137 Integer timeout = artifactInfo.getTimeout();
2138 Integer defaultTimeout = (isCreate) ? NodeTemplateOperation.getDefaultHeatTimeout() : currentArtifact.getTimeout();
2139 if (timeout == null) {
2140 artifactInfo.setTimeout(defaultTimeout);
2141 // HEAT artifact but timeout is invalid
2142 } else if (timeout < 1) {
2143 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_TIMEOUT));
2146 // US649856 - Allow several HEAT files on Resource
2148 * if (isCreate) { Wrapper<ResponseFormat> errorWrapper = new Wrapper<>(); validateSingleArtifactType(errorWrapper, ArtifactTypeEnum.findType(artifactInfo.getArtifactType()), parentComponent, parentType); if (!errorWrapper.isEmpty()) { return
2149 * Either.right(errorWrapper.getInnerElement()); } }
2152 log.trace("Ended HEAT validation for artifact {}", artifactInfo.getArtifactLabel());
2153 return Either.left(true);
2156 private Either<Boolean, ResponseFormat> validateResourceType(ResourceTypeEnum resourceType, ArtifactDefinition artifactInfo, List<String> typeList) {
2157 String listToString = (typeList != null) ? typeList.toString() : "";
2158 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISMATCH_BETWEEN_ARTIFACT_TYPE_AND_COMPONENT_TYPE, artifactInfo.getArtifactName(), listToString, resourceType.getValue());
2159 Either<Boolean, ResponseFormat> either = Either.right(responseFormat);
2160 String resourceTypeName = resourceType.name();
2161 if (typeList != null && typeList.contains(resourceTypeName)) {
2162 either = Either.left(true);
2167 private Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers(ArtifactDefinition artifactInfo, String artifactType) {
2168 if (artifactInfo.getHeatParameters() != null) {
2169 for (HeatParameterDefinition heatParam : artifactInfo.getListHeatParameters()) {
2170 String parameterType = heatParam.getType();
2171 HeatParameterType heatParameterType = HeatParameterType.isValidType(parameterType);
2172 String artifactTypeStr = artifactType != null ? artifactType : ArtifactTypeEnum.HEAT.getType();
2173 if (heatParameterType == null) {
2174 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_HEAT_PARAMETER_TYPE, artifactTypeStr, heatParam.getType());
2175 return Either.right(responseFormat);
2178 StorageOperationStatus validateAndUpdateProperty = heatParametersOperation.validateAndUpdateProperty(heatParam);
2179 if (validateAndUpdateProperty != StorageOperationStatus.OK) {
2180 log.debug("Heat parameter {} is invalid. Status is {}", heatParam.getName(), validateAndUpdateProperty);
2181 ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE;
2182 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, artifactTypeStr, heatParam.getType(), heatParam.getName());
2183 return Either.right(responseFormat);
2187 return Either.left(artifactInfo);
2190 public List<ArtifactDefinition> getDeploymentArtifacts(Component parentComponent, NodeTypeEnum parentType, String ciId) {
2191 List<ArtifactDefinition> deploymentArtifacts = new ArrayList<>();
2192 if (parentComponent.getDeploymentArtifacts() != null) {
2193 if (NodeTypeEnum.ResourceInstance == parentType && ciId != null) {
2194 Either<ComponentInstance, ResponseFormat> getRI = getRIFromComponent(parentComponent, ciId, null, null, null);
2195 if (getRI.isRight()) {
2196 return deploymentArtifacts;
2198 ComponentInstance ri = getRI.left().value();
2199 if (ri.getDeploymentArtifacts() != null) {
2200 deploymentArtifacts.addAll(ri.getDeploymentArtifacts().values());
2202 } else if (parentComponent.getDeploymentArtifacts() != null) {
2203 deploymentArtifacts.addAll(parentComponent.getDeploymentArtifacts().values());
2206 return deploymentArtifacts;
2209 private void checkCreateFields(User user, ArtifactDefinition artifactInfo, ArtifactGroupTypeEnum type) {
2210 // on create if null add informational to current
2211 if (artifactInfo.getArtifactGroupType() == null) {
2212 artifactInfo.setArtifactGroupType(type);
2214 if (artifactInfo.getUniqueId() != null) {
2215 log.error("artifact uniqid cannot be set ignoring");
2217 artifactInfo.setUniqueId(null);
2219 if (artifactInfo.getArtifactRef() != null) {
2220 log.error("artifact ref cannot be set ignoring");
2222 artifactInfo.setArtifactRef(null);
2224 if (artifactInfo.getArtifactRepository() != null) {
2225 log.error("artifact repository cannot be set ignoring");
2227 artifactInfo.setArtifactRepository(null);
2229 if (artifactInfo.getUserIdCreator() != null) {
2230 log.error("creator uuid cannot be set ignoring");
2232 artifactInfo.setArtifactCreator(user.getUserId());
2234 if (artifactInfo.getUserIdLastUpdater() != null) {
2235 log.error("userId of last updater cannot be set ignoring");
2237 artifactInfo.setUserIdLastUpdater(user.getUserId());
2239 if (artifactInfo.getCreatorFullName() != null) {
2240 log.error("creator Full name cannot be set ignoring");
2242 String fullName = user.getFirstName() + " " + user.getLastName();
2243 artifactInfo.setUpdaterFullName(fullName);
2245 if (artifactInfo.getUpdaterFullName() != null) {
2246 log.error("updater Full name cannot be set ignoring");
2248 artifactInfo.setUpdaterFullName(fullName);
2250 if (artifactInfo.getCreationDate() != null) {
2251 log.error("Creation Date cannot be set ignoring");
2253 long time = System.currentTimeMillis();
2254 artifactInfo.setCreationDate(time);
2256 if (artifactInfo.getLastUpdateDate() != null) {
2257 log.error("Last Update Date cannot be set ignoring");
2259 artifactInfo.setLastUpdateDate(time);
2261 if (artifactInfo.getEsId() != null) {
2262 log.error("es id cannot be set ignoring");
2264 artifactInfo.setEsId(null);
2269 * private Either<ArtifactDefinition, ResponseFormat> fetchCurrentArtifact(boolean isCreate, String artifactId) { Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(artifactId); if (isCreate
2270 * == false && artifactById.isRight()) { // in case of update artifact must be BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeArtifactMissingError, "Artifact Update / Upload", artifactId);
2271 * BeEcompErrorManager.getInstance().logBeArtifactMissingError("Artifact Update / Upload", artifactId); log.debug("Failed to fetch artifact {}. error: {}", artifactId, artifactById.right().value()); return
2272 * Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(artifactById.right().value()), artifactId)); } if (isCreate && artifactById.isLeft()) { log.debug("Artifact {} already exist", artifactId); return
2273 * Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactById.left().value().getArtifactLabel())); } ArtifactDefinition currentArtifactInfo = null; if (artifactById.isLeft()) { // get previous value
2274 * currentArtifactInfo = artifactById.left().value(); } return Either.left(currentArtifactInfo); }
2277 private String composeArtifactId(String resourceId, String artifactId, ArtifactDefinition artifactInfo, String interfaceName, String operationName) {
2278 String id = artifactId;
2279 if (artifactId == null || artifactId.isEmpty()) {
2280 String uniqueId = null;
2281 if (interfaceName != null && operationName != null) {
2282 uniqueId = UniqueIdBuilder.buildArtifactByInterfaceUniqueId(resourceId, interfaceName, operationName, artifactInfo.getArtifactLabel());
2284 uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId, artifactInfo.getArtifactLabel());
2286 artifactInfo.setUniqueId(uniqueId);
2287 artifactInfo.setEsId(uniqueId);
2290 artifactInfo.setUniqueId(artifactId);
2291 artifactInfo.setEsId(artifactId);
2296 private Either<ActionStatus, ResponseFormat> validateArtifactType(String userId, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) {
2297 if (artifactInfo.getArtifactType() == null || artifactInfo.getArtifactType().isEmpty()) {
2298 BeEcompErrorManager.getInstance().logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel");
2299 log.debug("Missing artifact type for artifact {}", artifactInfo.getArtifactName());
2300 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_TYPE));
2303 boolean artifactTypeExist = false;
2304 Either<List<ArtifactType>, ActionStatus> allArtifactTypes = null;
2305 ArtifactGroupTypeEnum artifactGroupType = artifactInfo.getArtifactGroupType();
2307 if ((artifactGroupType != null) && artifactGroupType.equals(ArtifactGroupTypeEnum.DEPLOYMENT)) {
2308 allArtifactTypes = getDeploymentArtifactTypes(userId, artifactInfo, parentType);
2311 allArtifactTypes = elementOperation.getAllArtifactTypes();
2313 if (allArtifactTypes.isRight()) {
2314 BeEcompErrorManager.getInstance().logBeInvalidConfigurationError("Artifact Upload / Update", "artifactTypes", allArtifactTypes.right().value().name());
2315 log.debug("Failed to retrieve list of suported artifact types. error: {}", allArtifactTypes.right().value());
2316 return Either.right(componentsUtils.getResponseFormatByUserId(allArtifactTypes.right().value(), userId));
2319 for (ArtifactType type : allArtifactTypes.left().value()) {
2320 if (type.getName().equalsIgnoreCase(artifactInfo.getArtifactType())) {
2321 artifactInfo.setArtifactType(artifactInfo.getArtifactType().toUpperCase());
2322 artifactTypeExist = true;
2327 if (!artifactTypeExist) {
2328 BeEcompErrorManager.getInstance().logBeInvalidTypeError("Artifact Upload / Delete / Update - Not supported artifact type", artifactInfo.getArtifactType(), "Artifact " + artifactInfo.getArtifactName());
2329 log.debug("Not supported artifact type = {}", artifactInfo.getArtifactType());
2330 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType()));
2333 return Either.left(ActionStatus.OK);
2336 private Either<List<ArtifactType>, ActionStatus> getDeploymentArtifactTypes(String userId, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) {
2338 Map<String, ArtifactTypeConfig> deploymentArtifacts = null;
2339 List<ArtifactType> artifactTypes = new ArrayList<ArtifactType>();
2341 if (parentType.equals(NodeTypeEnum.Service)) {
2342 deploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getServiceDeploymentArtifacts();
2343 } else if (parentType.equals(NodeTypeEnum.ResourceInstance)) {
2344 deploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceInstanceDeploymentArtifacts();
2346 deploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceDeploymentArtifacts();
2348 if (deploymentArtifacts != null) {
2349 for (String artifactType : deploymentArtifacts.keySet()) {
2350 ArtifactType artifactT = new ArtifactType();
2351 artifactT.setName(artifactType);
2352 artifactTypes.add(artifactT);
2354 return Either.left(artifactTypes);
2356 return Either.right(ActionStatus.GENERAL_ERROR);
2361 private Either<Boolean, ResponseFormat> validateFirstUpdateHasPayload(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2362 if (currentArtifact.getEsId() == null && (artifactInfo.getPayloadData() == null || artifactInfo.getPayloadData().length == 0)) {
2363 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD));
2365 return Either.left(true);
2369 private Either<Boolean, ResponseFormat> validateAndSetArtifactname(ArtifactDefinition artifactInfo) {
2370 if (artifactInfo.getArtifactName() == null || artifactInfo.getArtifactName().isEmpty()) {
2371 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_NAME));
2374 String normalizeFileName = ValidationUtils.normalizeFileName(artifactInfo.getArtifactName());
2375 if (normalizeFileName == null || normalizeFileName.isEmpty()) {
2376 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_NAME));
2378 artifactInfo.setArtifactName(normalizeFileName);
2380 if (!ValidationUtils.validateArtifactNameLength(artifactInfo.getArtifactName())) {
2381 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_NAME, String.valueOf(ValidationUtils.ARTIFACT_NAME_LENGTH)));
2384 return Either.left(true);
2387 private Either<Boolean, ResponseFormat> validateArtifactTypeNotChanged(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2388 if (artifactInfo.getArtifactType() == null || artifactInfo.getArtifactType().isEmpty()) {
2389 log.info("artifact type is missing operation ignored");
2390 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_TYPE));
2393 if (!currentArtifact.getArtifactType().equalsIgnoreCase(artifactInfo.getArtifactType())) {
2394 log.info("artifact type cannot be changed operation ignored");
2395 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2397 return Either.left(true);
2400 private Either<ArtifactDefinition, ResponseFormat> validateOrSetArtifactGroupType(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2401 if (artifactInfo.getArtifactGroupType() == null) {
2402 artifactInfo.setArtifactGroupType(currentArtifact.getArtifactGroupType());
2405 else if (!currentArtifact.getArtifactGroupType().getType().equalsIgnoreCase(artifactInfo.getArtifactGroupType().getType())) {
2406 log.info("artifact group type cannot be changed. operation failed");
2407 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2409 return Either.left(artifactInfo);
2412 private void checkAndSetUnUpdatableFields(User user, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, ArtifactGroupTypeEnum type) {
2414 // on update if null add informational to current
2415 if (currentArtifact.getArtifactGroupType() == null && type != null) {
2416 currentArtifact.setArtifactGroupType(type);
2419 if (artifactInfo.getUniqueId() != null && !currentArtifact.getUniqueId().equals(artifactInfo.getUniqueId())) {
2420 log.error("artifact uniqid cannot be set ignoring");
2422 artifactInfo.setUniqueId(currentArtifact.getUniqueId());
2424 if (artifactInfo.getArtifactRef() != null && !currentArtifact.getArtifactRef().equals(artifactInfo.getArtifactRef())) {
2425 log.error("artifact ref cannot be set ignoring");
2427 artifactInfo.setArtifactRef(currentArtifact.getArtifactRef());
2429 if (artifactInfo.getArtifactRepository() != null && !currentArtifact.getArtifactRepository().equals(artifactInfo.getArtifactRepository())) {
2430 log.error("artifact repository cannot be set ignoring");
2432 artifactInfo.setArtifactRepository(currentArtifact.getArtifactRepository());
2434 if (artifactInfo.getUserIdCreator() != null && !currentArtifact.getUserIdCreator().equals(artifactInfo.getUserIdCreator())) {
2435 log.error("creator uuid cannot be set ignoring");
2437 artifactInfo.setUserIdCreator(currentArtifact.getUserIdCreator());
2439 if (artifactInfo.getArtifactCreator() != null && !currentArtifact.getArtifactCreator().equals(artifactInfo.getArtifactCreator())) {
2440 log.error("artifact creator cannot be set ignoring");
2442 artifactInfo.setArtifactCreator(currentArtifact.getArtifactCreator());
2444 if (artifactInfo.getUserIdLastUpdater() != null && !currentArtifact.getUserIdLastUpdater().equals(artifactInfo.getUserIdLastUpdater())) {
2445 log.error("userId of last updater cannot be set ignoring");
2447 artifactInfo.setUserIdLastUpdater(user.getUserId());
2449 if (artifactInfo.getCreatorFullName() != null && !currentArtifact.getCreatorFullName().equals(artifactInfo.getCreatorFullName())) {
2450 log.error("creator Full name cannot be set ignoring");
2452 artifactInfo.setCreatorFullName(currentArtifact.getCreatorFullName());
2454 if (artifactInfo.getUpdaterFullName() != null && !currentArtifact.getUpdaterFullName().equals(artifactInfo.getUpdaterFullName())) {
2455 log.error("updater Full name cannot be set ignoring");
2457 String fullName = user.getFirstName() + " " + user.getLastName();
2458 artifactInfo.setUpdaterFullName(fullName);
2460 if (artifactInfo.getCreationDate() != null && !currentArtifact.getCreationDate().equals(artifactInfo.getCreationDate())) {
2461 log.error("Creation Date cannot be set ignoring");
2463 artifactInfo.setCreationDate(currentArtifact.getCreationDate());
2465 if (artifactInfo.getLastUpdateDate() != null && !currentArtifact.getLastUpdateDate().equals(artifactInfo.getLastUpdateDate())) {
2466 log.error("Last Update Date cannot be set ignoring");
2468 long time = System.currentTimeMillis();
2469 artifactInfo.setLastUpdateDate(time);
2471 if (artifactInfo.getEsId() != null && !currentArtifact.getEsId().equals(artifactInfo.getEsId())) {
2472 log.error("es id cannot be set ignoring");
2474 artifactInfo.setEsId(currentArtifact.getUniqueId());
2476 if (artifactInfo.getArtifactDisplayName() != null && !currentArtifact.getArtifactDisplayName().equals(artifactInfo.getArtifactDisplayName())) {
2477 log.error(" Artifact Display Name cannot be set ignoring");
2479 artifactInfo.setArtifactDisplayName(currentArtifact.getArtifactDisplayName());
2481 if (artifactInfo.getServiceApi() != null && !currentArtifact.getServiceApi().equals(artifactInfo.getServiceApi())) {
2482 log.debug("serviceApi cannot be set. ignoring.");
2484 artifactInfo.setServiceApi(currentArtifact.getServiceApi());
2486 if (artifactInfo.getArtifactGroupType() != null && !currentArtifact.getArtifactGroupType().equals(artifactInfo.getArtifactGroupType())) {
2487 log.debug("artifact group cannot be set. ignoring.");
2489 artifactInfo.setArtifactGroupType(currentArtifact.getArtifactGroupType());
2491 artifactInfo.setArtifactVersion(currentArtifact.getArtifactVersion());
2493 if (artifactInfo.getArtifactUUID() != null && !artifactInfo.getArtifactUUID().isEmpty() && !currentArtifact.getArtifactUUID().equals(artifactInfo.getArtifactUUID())) {
2494 log.debug("artifact UUID cannot be set. ignoring.");
2496 artifactInfo.setArtifactUUID(currentArtifact.getArtifactUUID());
2498 if ((artifactInfo.getHeatParameters() != null) && (currentArtifact.getHeatParameters() != null) && !artifactInfo.getHeatParameters().isEmpty() && !currentArtifact.getHeatParameters().isEmpty()) {
2499 checkAndSetUnupdatableHeatParams(artifactInfo.getListHeatParameters(), currentArtifact.getListHeatParameters());
2503 private void checkAndSetUnupdatableHeatParams(List<HeatParameterDefinition> heatParameters, List<HeatParameterDefinition> currentParameters) {
2505 Map<String, HeatParameterDefinition> currentParametersMap = getMapOfParameters(currentParameters);
2506 for (HeatParameterDefinition parameter : heatParameters) {
2507 HeatParameterDefinition currentParam = currentParametersMap.get(parameter.getUniqueId());
2509 if (currentParam != null) {
2511 if (parameter.getName() != null && !parameter.getName().equalsIgnoreCase(currentParam.getName())) {
2512 log.debug("heat parameter name cannot be updated ({}). ignoring.", parameter.getName());
2513 parameter.setName(currentParam.getName());
2515 if (parameter.getDefaultValue() != null && !parameter.getDefaultValue().equalsIgnoreCase(currentParam.getDefaultValue())) {
2516 log.debug("heat parameter defaultValue cannot be updated ({}). ignoring.", parameter.getDefaultValue());
2517 parameter.setDefaultValue(currentParam.getDefaultValue());
2519 if (parameter.getType() != null && !parameter.getType().equalsIgnoreCase(currentParam.getType())) {
2520 log.debug("heat parameter type cannot be updated ({}). ignoring.", parameter.getType());
2521 parameter.setType(currentParam.getType());
2523 if (parameter.getDescription() != null && !parameter.getDescription().equalsIgnoreCase(currentParam.getDescription())) {
2524 log.debug("heat parameter description cannot be updated ({}). ignoring.", parameter.getDescription());
2525 parameter.setDescription(currentParam.getDescription());
2528 // check and set current value
2529 if ((parameter.getCurrentValue() == null) && (currentParam.getDefaultValue() != null)) {
2530 log.debug("heat parameter current value is null. set it to default value {}). ignoring.", parameter.getDefaultValue());
2531 parameter.setCurrentValue(currentParam.getDefaultValue());
2537 private Map<String, HeatParameterDefinition> getMapOfParameters(List<HeatParameterDefinition> currentParameters) {
2539 Map<String, HeatParameterDefinition> currentParamsMap = new HashMap<String, HeatParameterDefinition>();
2540 for (HeatParameterDefinition param : currentParameters) {
2541 currentParamsMap.put(param.getUniqueId(), param);
2543 return currentParamsMap;
2546 private Either<Boolean, ResponseFormat> validateAndServiceApiUrl(ArtifactDefinition artifactInfo) {
2547 if (!ValidationUtils.validateStringNotEmpty(artifactInfo.getApiUrl())) {
2548 log.debug("Artifact url cannot be empty.");
2549 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_URL));
2551 artifactInfo.setApiUrl(artifactInfo.getApiUrl().toLowerCase());
2553 if (!ValidationUtils.validateUrl(artifactInfo.getApiUrl())) {
2554 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_SERVICE_API_URL));
2556 if (!ValidationUtils.validateUrlLength(artifactInfo.getApiUrl())) {
2557 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_URL, String.valueOf(ValidationUtils.API_URL_LENGTH)));
2560 return Either.left(true);
2563 private Either<Boolean, ResponseFormat> validateAndCleanDescription(ArtifactDefinition artifactInfo) {
2564 if (artifactInfo.getDescription() == null || artifactInfo.getDescription().isEmpty()) {
2565 log.debug("Artifact description cannot be empty.");
2566 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_DESCRIPTION));
2568 String description = artifactInfo.getDescription();
2569 description = ValidationUtils.removeNoneUtf8Chars(description);
2570 description = ValidationUtils.normaliseWhitespace(description);
2571 description = ValidationUtils.stripOctets(description);
2572 description = ValidationUtils.removeHtmlTagsOnly(description);
2573 if (!ValidationUtils.validateIsEnglish(description)) {
2574 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2576 if (!ValidationUtils.validateLength(description, ValidationUtils.ARTIFACT_DESCRIPTION_MAX_LENGTH)) {
2577 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_DESCRIPTION, String.valueOf(ValidationUtils.ARTIFACT_DESCRIPTION_MAX_LENGTH)));
2579 artifactInfo.setDescription(description);
2580 return Either.left(true);
2583 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateArtifactFlow(org.openecomp.sdc.be.model.Component parent, String parentId, String artifactId, ArtifactDefinition artifactInfo, User user, byte[] decodedPayload,
2584 ComponentTypeEnum componentType, AuditingActionEnum auditingAction, String interfaceType, String operationName) {
2585 ESArtifactData artifactData = createEsArtifactData(artifactInfo, decodedPayload);
2586 String prevArtifactId = null;
2587 String currArtifactId = artifactId;
2589 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
2590 Either<ArtifactDefinition, Operation> insideEither = null;
2592 if (artifactData == null) {
2593 BeEcompErrorManager.getInstance().logBeDaoSystemError("Update Artifact");
2594 log.debug("Failed to create artifact object for ES.");
2595 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
2596 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
2597 resultOp = Either.right(responseFormat);
2600 log.trace("Try to update entry on graph");
2601 String artifactUniqueId = null;
2602 ArtifactDefinition artifactDefinition = artifactInfo;
2603 StorageOperationStatus error = null;
2605 boolean isLeft = false;
2606 if (interfaceType != null && operationName != null) {
2607 // lifecycle artifact
2609 * Operation operation = convertToOperation(artifactInfo, operationName);
2611 * Either<Operation, StorageOperationStatus> result = interfaceLifecycleOperation.updateInterfaceOperation(parentId, interfaceType, operationName, operation);
2613 * isLeft = result.isLeft(); if (isLeft) { artifactUniqueId = result.left().value().getUniqueId(); artifactDefinition = result.left().value().getImplementation();
2615 * insideEither = Either.right(result.left().value()); resultOp = Either.left(insideEither); } else { error = result.right().value(); }
2618 log.debug("Enty on graph is updated. Update artifact in ES");
2620 // Changing previous and current artifactId for auditing
2621 prevArtifactId = currArtifactId;
2622 currArtifactId = artifactDefinition.getUniqueId();
2624 NodeTypeEnum convertParentType = convertParentType(componentType);
2626 if (decodedPayload == null) {
2627 if (!artifactDefinition.getMandatory() || artifactDefinition.getEsId() != null) {
2628 Either<ESArtifactData, CassandraOperationStatus> artifactFromCassandra = artifactCassandraDao.getArtifact(artifactDefinition.getEsId());
2629 // Either<ESArtifactData, ResourceUploadStatus>
2630 // artifactfromES = daoUploader.getArtifact(artifactId);
2631 if (artifactFromCassandra.isRight()) {
2632 log.debug("Failed to get artifact data from ES for artifact id {}", artifactId);
2633 error = DaoStatusConverter.convertCassandraStatusToStorageStatus(artifactFromCassandra.right().value());
2634 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
2635 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
2636 resultOp = Either.right(responseFormat);
2639 // clone data to new artifact
2640 artifactData.setData(artifactFromCassandra.left().value().getData());
2641 artifactData.setId(artifactFromCassandra.left().value().getId());
2644 if (artifactDefinition.getEsId() == null) {
2645 artifactDefinition.setEsId(artifactDefinition.getUniqueId());
2646 artifactData.setId(artifactDefinition.getUniqueId());
2650 Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.updateArifactOnResource(artifactInfo, parent.getUniqueId(), artifactId, convertParentType, parentId);
2651 isLeft = result.isLeft();
2653 artifactUniqueId = result.left().value().getUniqueId();
2654 artifactDefinition = result.left().value();
2655 String artifactType = artifactInfo.getArtifactType();
2656 if (NodeTypeEnum.Resource == convertParentType
2657 && (ArtifactTypeEnum.HEAT.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.HEAT_VOL.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.HEAT_NET.getType().equalsIgnoreCase(artifactType))) {
2659 if (!artifactUniqueId.equals(artifactId)) {
2660 // need to update the generated id in heat env
2661 Map<String, ArtifactDefinition> deploymentArtifacts = parent.getDeploymentArtifacts();
2662 Optional<Entry<String, ArtifactDefinition>> findFirst = deploymentArtifacts.entrySet().stream().filter(a -> a.getValue().getGeneratedFromId()!=null && a.getValue().getGeneratedFromId().equals(artifactId)).findFirst();
2663 if (findFirst.isPresent()) {
2664 ArtifactDefinition artifactEnvInfo = findFirst.get().getValue();
2665 artifactEnvInfo.setArtifactChecksum(null);
2666 artifactToscaOperation.updateHeatEnvArtifact(parent.getUniqueId(), artifactEnvInfo, artifactId, artifactUniqueId, convertParentType, parentId);
2671 * if (!artifactUniqueId.equals(artifactId)) { artifactToscaOperation.updateHeatEnvArtifact(parentId, null, artifactId, artifactUniqueId, convertParentType);
2673 * } else { if (!artifactInfo.getArtifactChecksum().equals(artifactDefinition.getArtifactChecksum())) { Either<ArtifactDefinition, StorageOperationStatus> heatEnvEither =
2674 * artifactToscaOperation.getHeatEnvByGeneratedFromId(artifactUniqueId); if (heatEnvEither.isLeft()) { artifactToscaOperation.updateHeatEnvPlaceholder(heatEnvEither.left().value(), parentId);
2679 error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentType);
2681 insideEither = Either.left(result.left().value());
2682 resultOp = Either.left(insideEither);
2683 if (error != StorageOperationStatus.OK) {
2688 error = result.right().value();
2692 // create new entry in ES
2694 if (artifactData.getData() != null) {
2695 if (!artifactDefinition.getDuplicated() || artifactData.getId() == null)
2696 artifactData.setId(artifactDefinition.getEsId());
2697 res = saveArtifacts(artifactData, parentId, false);
2703 log.debug("Artifact saved into ES - {}", artifactUniqueId);
2704 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
2705 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
2706 // resultOp = Either.left(result.left().value());
2709 BeEcompErrorManager.getInstance().logBeDaoSystemError("Update Artifact");
2710 log.debug("Failed to save the artifact.");
2711 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
2712 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
2713 resultOp = Either.right(responseFormat);
2721 private Either<byte[], ResponseFormat> handlePayload(ArtifactDefinition artifactInfo, boolean isArtifactMetadataUpdate) {
2722 log.trace("Starting payload handling");
2723 byte[] payload = artifactInfo.getPayloadData();
2724 byte[] decodedPayload = null;
2726 if (payload != null && payload.length != 0) {
2727 // the generated artifacts were already decoded by the handler
2728 decodedPayload = artifactInfo.getGenerated() ? payload : Base64.decodeBase64(payload);
2729 if (decodedPayload.length == 0) {
2730 log.debug("Failed to decode the payload.");
2731 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
2732 return Either.right(responseFormat);
2735 String checkSum = GeneralUtility.calculateMD5ByByteArray(decodedPayload);
2736 artifactInfo.setArtifactChecksum(checkSum);
2737 log.trace("Calculated checksum, base64 payload: {}, checksum: {}", payload, checkSum);
2739 // Specific payload validations of different types
2740 Either<Boolean, ResponseFormat> isValidPayload = Either.left(true);
2741 if (isDeploymentArtifact(artifactInfo)) {
2742 log.trace("Starting deployment artifacts payload validation");
2743 String artifactType = artifactInfo.getArtifactType();
2744 if (ArtifactTypeEnum.HEAT.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.HEAT_VOL.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.HEAT_NET.getType().equalsIgnoreCase(artifactType)
2745 || ArtifactTypeEnum.HEAT_ENV.getType().equalsIgnoreCase(artifactType)) {
2746 isValidPayload = validateDeploymentHeatPayload(decodedPayload, artifactType);
2747 if (isValidPayload.isLeft()) {
2748 isValidPayload = extractHeatParameters(artifactInfo);
2750 } else if (ArtifactTypeEnum.YANG_XML.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.VNF_CATALOG.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.VF_LICENSE.getType().equalsIgnoreCase(artifactType)
2751 || ArtifactTypeEnum.VENDOR_LICENSE.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.MODEL_INVENTORY_PROFILE.getType().equalsIgnoreCase(artifactType)
2752 || ArtifactTypeEnum.MODEL_QUERY_SPEC.getType().equalsIgnoreCase(artifactType)) {
2753 isValidPayload = validateYangPayload(decodedPayload, artifactType);
2755 // if(ArtifactTypeEnum.APPC_CONFIG.getType().equalsIgnoreCase(artifactType)
2757 } else if (ArtifactTypeEnum.DCAE_INVENTORY_JSON.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType().equalsIgnoreCase(artifactType)
2758 || ArtifactTypeEnum.VES_EVENTS.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.LIFECYCLE_OPERATIONS.getType().equalsIgnoreCase(artifactType)) {
2759 String artifactFileName = artifactInfo.getArtifactName();
2760 String fileExtension = GeneralUtility.getFilenameExtension(artifactFileName).toLowerCase();
2761 switch (fileExtension) {
2763 isValidPayload = validateYangPayload(decodedPayload, artifactType);
2766 isValidPayload = validateJsonPayload(decodedPayload, artifactType);
2770 isValidPayload = validateYmlPayload(decodedPayload, artifactType);
2775 if (isValidPayload.isRight()) {
2776 ResponseFormat responseFormat = isValidPayload.right().value();
2777 return Either.right(responseFormat);
2780 } // null/empty payload is normal if called from metadata update ONLY.
2781 // The validation of whether this is metadata/payload update case is
2782 // currently done separately
2784 if (!isArtifactMetadataUpdate) {
2785 log.debug("Payload is missing.");
2786 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
2787 return Either.right(responseFormat);
2790 log.trace("Ended payload handling");
2791 return Either.left(decodedPayload);
2794 private Either<Boolean, ResponseFormat> validateDeploymentHeatPayload(byte[] decodedPayload, String artifactType) {
2795 // Basic YAML validation
2796 YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter();
2797 if (!yamlToObjectConverter.isValidYaml(decodedPayload)) {
2798 log.debug("Invalid YAML format");
2799 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, artifactType);
2800 return Either.right(responseFormat);
2802 if (!ArtifactTypeEnum.HEAT_ENV.getType().equalsIgnoreCase(artifactType)) {
2803 // HEAT specific YAML validation
2804 DeploymentArtifactHeatConfiguration heatConfiguration = yamlToObjectConverter.convert(decodedPayload, DeploymentArtifactHeatConfiguration.class);
2805 if (heatConfiguration == null || heatConfiguration.getHeat_template_version() == null) {
2806 log.debug("HEAT doesn't contain required \"heat_template_version\" section.");
2807 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactType);
2808 return Either.right(responseFormat);
2812 return Either.left(true);
2815 private Either<Boolean, ResponseFormat> validateYmlPayload(byte[] decodedPayload, String artifactType) {
2816 Either<Boolean, ResponseFormat> res = Either.left(true);
2817 YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter();
2818 if (!yamlToObjectConverter.isValidYaml(decodedPayload)) {
2819 log.debug("Invalid YAML format");
2820 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, artifactType);
2821 res = Either.right(responseFormat);
2827 private Either<Boolean, ResponseFormat> validateYangPayload(byte[] payload, String artifactType) {
2828 boolean isXmlValid = isValidXml(payload);
2830 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.INVALID_XML, artifactType);
2831 log.debug("Invalid XML content");
2832 return Either.right(responseFormat);
2834 return Either.left(true);
2837 private Either<Boolean, ResponseFormat> validateJsonPayload(byte[] payload, String type) {
2838 boolean isJsonValid = isValidJson(payload);
2840 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.INVALID_JSON, type);
2841 log.debug("Invalid JSON content");
2842 return Either.right(responseFormat);
2844 return Either.left(true);
2847 public void handleTransaction(Either<Operation, ResponseFormat> opState) {
2848 if (opState == null || opState.isRight()) {
2849 titanDao.rollback();
2855 public Either<Operation, ResponseFormat> deleteArtifactByInterface(String resourceId, String interfaceType, String operationName, String userUserId, String artifactId, ImmutablePair<User, Resource> userResourceAuditPair, boolean shouldLock,
2856 boolean inTransaction) {
2857 User user = new User();
2858 user.setUserId(userUserId);
2859 Either<Resource, StorageOperationStatus> parent = toscaOperationFacade.getToscaElement(resourceId, JsonParseFlagEnum.ParseMetadata);
2860 if (parent.isRight()) {
2861 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(parent.right().value()));
2862 return Either.right(responseFormat);
2864 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = handleDelete(resourceId, artifactId, user, AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, parent.left().value(), interfaceType, operationName,
2865 false, inTransaction);
2866 if (handleDelete.isRight()) {
2867 return Either.right(handleDelete.right().value());
2869 Either<ArtifactDefinition, Operation> result = handleDelete.left().value();
2870 return Either.left(result.right().value());
2874 public StorageOperationStatus deleteAllComponentArtifactsIfNotOnGraph(List<ArtifactDefinition> artifacts) {
2876 if (artifacts != null && !artifacts.isEmpty()) {
2877 for (ArtifactDefinition artifactDefinition : artifacts) {
2878 String esId = artifactDefinition.getEsId();
2879 if (esId != null && !esId.isEmpty()) {
2880 StorageOperationStatus deleteIfNotOnGraph = deleteIfNotOnGraph(artifactDefinition.getUniqueId(), esId, false);
2881 if (!deleteIfNotOnGraph.equals(StorageOperationStatus.OK)) {
2882 return deleteIfNotOnGraph;
2887 return StorageOperationStatus.OK;
2890 private Operation convertToOperation(ArtifactDefinition artifactInfo, String operationName) {
2891 Operation op = new Operation();
2892 long time = System.currentTimeMillis();
2893 op.setCreationDate(time);
2895 String artifactName = artifactInfo.getArtifactName();
2896 artifactInfo.setArtifactName(createInterfaceArtifactNameFromOperation(operationName, artifactName));
2898 op.setImplementation(artifactInfo);
2899 op.setLastUpdateDate(time);
2903 private String createInterfaceArtifactNameFromOperation(String operationName, String artifactName) {
2904 String newArtifactName = operationName + "_" + artifactName;
2905 log.trace("converting artifact name {} to {}", artifactName, newArtifactName);
2906 return newArtifactName;
2909 public StorageOperationStatus deleteIfNotOnGraph(String artifactId, String artifactEsId, boolean deleteOnlyPayload) {
2910 log.debug("deleteIfNotOnGraph: delete only payload = {}", deleteOnlyPayload);
2911 // Either<ArtifactData, TitanOperationStatus> checkArtifactNode = titanDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ArtifactRef), artifactId, ArtifactData.class);
2912 // if ((artifactEsId != null && !artifactEsId.isEmpty())) {
2913 // boolean isNotExistOnGraph = checkArtifactNode.isRight() && checkArtifactNode.right().value().equals(TitanOperationStatus.NOT_FOUND);
2915 // if ((isNotExistOnGraph) || (checkArtifactNode.left().value().getArtifactDataDefinition().getMandatory() && deleteOnlyPayload)
2916 // || (ArtifactGroupTypeEnum.SERVICE_API.equals(checkArtifactNode.left().value().getArtifactDataDefinition().getArtifactGroupType()) && deleteOnlyPayload)) {
2917 // // last one. need to delete in ES
2918 // log.debug("Entry on graph is deleted. Delete artifact in ES for id = {}", artifactEsId);
2919 // artifactCassandraDao.deleteArtifact(artifactEsId);
2920 // return StorageOperationStatus.OK;
2922 // // componentsUtils.getResponseFormatByResourceId(ActionStatus.OK,
2926 // log.debug("Entry on graph is deleted. Exist more connections on this artifact. Don't delete artifact in ES for id = {}", artifactEsId);
2927 // return StorageOperationStatus.OK;
2931 return StorageOperationStatus.OK;
2935 public Either<byte[], ResponseFormat> downloadRsrcArtifactByNames(String serviceName, String serviceVersion, String resourceName, String resourceVersion, String artifactName) {
2937 // General validation
2938 if (serviceName == null || serviceVersion == null || resourceName == null || resourceVersion == null || artifactName == null) {
2939 log.debug("One of the function parameteres is null");
2940 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2943 // Normalizing artifact name
2944 artifactName = ValidationUtils.normalizeFileName(artifactName);
2946 // Resource validation
2947 Either<Resource, ResponseFormat> validateResourceNameAndVersion = validateResourceNameAndVersion(resourceName, resourceVersion);
2948 if (validateResourceNameAndVersion.isRight()) {
2949 return Either.right(validateResourceNameAndVersion.right().value());
2952 Resource resource = validateResourceNameAndVersion.left().value();
2953 String resourceId = resource.getUniqueId();
2955 // Service validation
2956 Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
2957 if (validateServiceNameAndVersion.isRight()) {
2958 return Either.right(validateServiceNameAndVersion.right().value());
2961 Map<String, ArtifactDefinition> artifacts = resource.getDeploymentArtifacts();
2962 if (artifacts == null || artifacts.isEmpty()) {
2963 log.debug("Deployment artifacts of resource {} are not found", resourceId);
2964 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
2967 ArtifactDefinition deploymentArtifact = null;
2969 for (ArtifactDefinition artifactDefinition : artifacts.values()) {
2970 if (artifactDefinition.getArtifactName() != null && artifactDefinition.getArtifactName().equals(artifactName)) {
2971 log.debug("Found deployment artifact {}", artifactName);
2972 deploymentArtifact = artifactDefinition;
2977 if (deploymentArtifact == null) {
2978 log.debug("No deployment artifact {} was found for resource {}", artifactName, resourceId);
2979 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
2982 // Downloading the artifact
2983 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(deploymentArtifact);
2984 if (downloadArtifactEither.isRight()) {
2985 log.debug("Download artifact {} failed", artifactName);
2986 return Either.right(downloadArtifactEither.right().value());
2988 log.trace("Download of resource artifact succeeded, uniqueId {}", deploymentArtifact.getUniqueId());
2989 return Either.left(downloadArtifactEither.left().value().getRight());
2993 public Either<byte[], ResponseFormat> downloadRsrcInstArtifactByNames(String serviceName, String serviceVersion, String resourceInstanceName, String artifactName) {
2995 // General validation
2996 if (serviceName == null || serviceVersion == null || resourceInstanceName == null || artifactName == null) {
2997 log.debug("One of the function parameteres is null");
2998 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
3001 // Normalizing artifact name
3002 artifactName = ValidationUtils.normalizeFileName(artifactName);
3004 // Resource validation
3006 * Either<Resource, ResponseFormat> validateResourceNameAndVersion = validateResourceNameAndVersion(resourceName, resourceVersion); if (validateResourceNameAndVersion.isRight()) { return
3007 * Either.right(validateResourceNameAndVersion.right().value()); }
3009 * Resource resource = validateResourceNameAndVersion.left().value(); String resourceId = resource.getUniqueId();
3012 // Service validation
3013 Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
3014 if (validateServiceNameAndVersion.isRight()) {
3015 return Either.right(validateServiceNameAndVersion.right().value());
3018 Service service = validateServiceNameAndVersion.left().value();
3020 // ResourceInstance validation
3021 Either<ComponentInstance, ResponseFormat> validateResourceInstance = validateResourceInstance(service, resourceInstanceName);
3022 if (validateResourceInstance.isRight()) {
3023 return Either.right(validateResourceInstance.right().value());
3026 ComponentInstance resourceInstance = validateResourceInstance.left().value();
3028 Map<String, ArtifactDefinition> artifacts = resourceInstance.getDeploymentArtifacts();
3030 final String finalArtifactName = artifactName;
3031 Predicate<ArtifactDefinition> filterArtifactByName = p -> p.getArtifactName().equals(finalArtifactName);
3033 boolean hasDeploymentArtifacts = artifacts != null && artifacts.values().stream().anyMatch(filterArtifactByName);
3034 ArtifactDefinition deployableArtifact;
3036 if (!hasDeploymentArtifacts) {
3037 log.debug("Deployment artifact with name {} not found", artifactName);
3038 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
3041 log.debug("Found deployment artifact {}", artifactName);
3042 deployableArtifact = artifacts.values().stream().filter(filterArtifactByName).findFirst().get();
3043 // Downloading the artifact
3044 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(deployableArtifact);
3046 if (downloadArtifactEither.isRight()) {
3047 log.debug("Download artifact {} failed", artifactName);
3048 return Either.right(downloadArtifactEither.right().value());
3050 log.trace("Download of resource artifact succeeded, uniqueId {}", deployableArtifact.getUniqueId());
3051 return Either.left(downloadArtifactEither.left().value().getRight());
3054 private Either<ComponentInstance, ResponseFormat> validateResourceInstance(Service service, String resourceInstanceName) {
3056 List<ComponentInstance> riList = service.getComponentInstances();
3057 for (ComponentInstance ri : riList) {
3058 if (ri.getNormalizedName().equals(resourceInstanceName))
3059 return Either.left(ri);
3062 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND, resourceInstanceName));
3065 private Either<Service, ResponseFormat> validateServiceNameAndVersion(String serviceName, String serviceVersion) {
3067 Either<List<Service>, StorageOperationStatus> serviceListBySystemName = toscaOperationFacade.getBySystemName(ComponentTypeEnum.SERVICE, serviceName);
3068 if (serviceListBySystemName.isRight()) {
3069 log.debug("Couldn't fetch any service with name {}", serviceName);
3070 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceListBySystemName.right().value(), ComponentTypeEnum.SERVICE), serviceName));
3072 List<Service> serviceList = serviceListBySystemName.left().value();
3073 if (serviceList == null || serviceList.isEmpty()) {
3074 log.debug("Couldn't fetch any service with name {}", serviceName);
3075 return Either.right(componentsUtils.getResponseFormat(ActionStatus.SERVICE_NOT_FOUND, serviceName));
3078 Service foundService = null;
3079 for (Service service : serviceList) {
3080 if (service.getVersion().equals(serviceVersion)) {
3081 log.trace("Found service with version {}", serviceVersion);
3082 foundService = service;
3087 if (foundService == null) {
3088 log.debug("Couldn't find version {} for service {}", serviceVersion, serviceName);
3089 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_VERSION_NOT_FOUND, ComponentTypeEnum.SERVICE.getValue(), serviceVersion));
3091 return Either.left(foundService);
3094 private Either<Resource, ResponseFormat> validateResourceNameAndVersion(String resourceName, String resourceVersion) {
3096 Either<Resource, StorageOperationStatus> resourceListBySystemName = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, resourceVersion, JsonParseFlagEnum.ParseMetadata);
3097 if (resourceListBySystemName.isRight()) {
3098 log.debug("Couldn't fetch any resource with name {} and version {}. ", resourceName, resourceVersion);
3099 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceListBySystemName.right().value()), resourceName));
3101 return Either.left(resourceListBySystemName.left().value());
3104 public Either<byte[], ResponseFormat> downloadServiceArtifactByNames(String serviceName, String serviceVersion, String artifactName) {
3106 log.trace("Starting download of service interface artifact, serviceName {}, serviceVersion {}, artifact name {}", serviceName, serviceVersion, artifactName);
3107 if (serviceName == null || serviceVersion == null || artifactName == null) {
3108 log.debug("One of the function parameteres is null");
3109 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
3112 // Normalizing artifact name
3113 final String normalizedArtifactName = ValidationUtils.normalizeFileName(artifactName);
3115 // Service validation
3116 Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
3117 if (validateServiceNameAndVersion.isRight()) {
3118 return Either.right(validateServiceNameAndVersion.right().value());
3121 String serviceId = validateServiceNameAndVersion.left().value().getUniqueId();
3123 // Looking for deployment or tosca artifacts
3124 Service service = validateServiceNameAndVersion.left().value();
3126 if (MapUtils.isEmpty(service.getDeploymentArtifacts()) && MapUtils.isEmpty(service.getToscaArtifacts())) {
3127 log.debug("Neither Deployment nor Tosca artifacts of service {} are found", serviceId);
3128 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, normalizedArtifactName));
3131 Optional<ArtifactDefinition> foundArtifactOptl = null;
3133 if (!MapUtils.isEmpty(service.getDeploymentArtifacts())) {
3134 foundArtifactOptl = service.getDeploymentArtifacts().values().stream()
3135 // filters artifact by name
3136 .filter(a -> a.getArtifactName().equals(normalizedArtifactName)).findAny();
3138 if ((foundArtifactOptl == null || !foundArtifactOptl.isPresent()) && !MapUtils.isEmpty(service.getToscaArtifacts())) {
3139 foundArtifactOptl = service.getToscaArtifacts().values().stream()
3140 // filters TOSCA artifact by name
3141 .filter(a -> a.getArtifactName().equals(normalizedArtifactName)).findAny();
3143 if (!foundArtifactOptl.isPresent()) {
3144 log.debug("The artifact {} was not found for service {}", normalizedArtifactName, serviceId);
3145 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, normalizedArtifactName));
3147 log.debug("Found deployment artifact {}", normalizedArtifactName);
3148 // Downloading the artifact
3149 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(foundArtifactOptl.get());
3150 if (downloadArtifactEither.isRight()) {
3151 log.debug("Download artifact {} failed", normalizedArtifactName);
3152 return Either.right(downloadArtifactEither.right().value());
3154 log.trace("Download of service artifact succeeded, uniqueId {}", foundArtifactOptl.get().getUniqueId());
3155 return Either.left(downloadArtifactEither.left().value().getRight());
3158 public Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifact(String parentId, String artifactUniqueId) {
3159 log.trace("Starting download of artifact, uniqueId {}", artifactUniqueId);
3160 Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(parentId, artifactUniqueId);
3161 if (artifactById.isRight()) {
3162 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(artifactById.right().value());
3163 log.debug("Error when getting artifact info by id{}, error: {}", artifactUniqueId, actionStatus.name());
3164 return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, ""));
3166 ArtifactDefinition artifactDefinition = artifactById.left().value();
3167 if (artifactDefinition == null) {
3168 log.debug("Empty artifact definition returned from DB by artifact id {}", artifactUniqueId);
3169 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ""));
3172 return downloadArtifact(artifactDefinition);
3175 private boolean checkArtifactInComponent(org.openecomp.sdc.be.model.Component component, String artifactId) {
3176 boolean found = false;
3177 Map<String, ArtifactDefinition> artifactsS = component.getArtifacts();
3178 if (artifactsS != null) {
3179 for (Map.Entry<String, ArtifactDefinition> entry : artifactsS.entrySet()) {
3180 if (entry.getValue().getUniqueId().equals(artifactId)) {
3186 Map<String, ArtifactDefinition> deploymentArtifactsS = component.getDeploymentArtifacts();
3187 if (!found && deploymentArtifactsS != null) {
3188 for (Map.Entry<String, ArtifactDefinition> entry : deploymentArtifactsS.entrySet()) {
3189 if (entry.getValue().getUniqueId().equals(artifactId)) {
3195 Map<String, ArtifactDefinition> toscaArtifactsS = component.getToscaArtifacts();
3196 if (!found && toscaArtifactsS != null) {
3197 for (Map.Entry<String, ArtifactDefinition> entry : toscaArtifactsS.entrySet()) {
3198 if (entry.getValue().getUniqueId().equals(artifactId)) {
3204 switch (component.getComponentType()) {
3206 Map<String, InterfaceDefinition> interfaces = ((Resource) component).getInterfaces();
3207 if (!found && interfaces != null) {
3208 for (Map.Entry<String, InterfaceDefinition> entry : interfaces.entrySet()) {
3209 Map<String, Operation> operations = entry.getValue().getOperationsMap();
3210 for (Map.Entry<String, Operation> entryOp : operations.entrySet()) {
3211 if (entryOp.getValue().getImplementation() != null && entryOp.getValue().getImplementation().getUniqueId().equals(artifactId)) {
3220 Map<String, ArtifactDefinition> apiArtifacts = ((Service) component).getServiceApiArtifacts();
3221 if (!found && apiArtifacts != null) {
3222 for (Map.Entry<String, ArtifactDefinition> entry : apiArtifacts.entrySet()) {
3223 if (entry.getValue().getUniqueId().equals(artifactId)) {
3237 private boolean checkArtifactInResourceInstance(Component component, String resourceInstanceId, String artifactId) {
3239 boolean found = false;
3240 List<ComponentInstance> resourceInstances = component.getComponentInstances();
3241 ComponentInstance resourceInstance = null;
3242 for (ComponentInstance ri : resourceInstances) {
3243 if (ri.getUniqueId().equals(resourceInstanceId)) {
3244 resourceInstance = ri;
3248 if (resourceInstance != null) {
3249 Map<String, ArtifactDefinition> artifacts = resourceInstance.getDeploymentArtifacts();
3250 if (artifacts != null) {
3251 for (Map.Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) {
3252 if (entry.getValue().getUniqueId().equals(artifactId)) {
3259 artifacts = resourceInstance.getArtifacts();
3260 if (artifacts != null) {
3261 for (Map.Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) {
3262 if (entry.getValue().getUniqueId().equals(artifactId)) {
3273 private Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists(String componentId, String userId, AuditingActionEnum auditingAction, User user, String artifactId, ComponentTypeEnum componentType,
3274 String containerComponentType, boolean inTransaction) {
3276 ComponentTypeEnum componentForAudit = null == containerComponentType ? componentType : ComponentTypeEnum.findByParamName(containerComponentType);
3277 componentForAudit.getNodeType();
3279 Either<? extends org.openecomp.sdc.be.model.Component, StorageOperationStatus> componentResult = toscaOperationFacade.getToscaFullElement(componentId);
3281 if (componentResult.isRight()) {
3282 ActionStatus status = componentForAudit == ComponentTypeEnum.RESOURCE ? ActionStatus.RESOURCE_NOT_FOUND : componentType == ComponentTypeEnum.SERVICE ? ActionStatus.SERVICE_NOT_FOUND : ActionStatus.PRODUCT_NOT_FOUND;
3283 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, componentId);
3284 log.debug("Service not found, serviceId {}", componentId);
3285 handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentForAudit, null);
3286 return Either.right(responseFormat);
3288 return Either.left(componentResult.left().value());
3291 private Either<Boolean, ResponseFormat> validateWorkOnComponent(org.openecomp.sdc.be.model.Component component, String userId, AuditingActionEnum auditingAction, User user, String artifactId, ArtifactOperationInfo operation,
3292 ComponentTypeEnum componentType) {
3293 if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.Download && !operation.ignoreLifecycleState()) {
3294 Either<Boolean, ResponseFormat> canWork = validateCanWorkOnComponent(component, userId);
3295 if (canWork.isRight()) {
3296 String uniqueId = component.getUniqueId();
3297 log.debug("Service status isn't CHECKOUT or user isn't owner, serviceId {}", uniqueId);
3298 handleAuditing(auditingAction, component, uniqueId, user, null, null, artifactId, canWork.right().value(), component.getComponentType(), null);
3299 return Either.right(canWork.right().value());
3302 return Either.left(true);
3305 private Either<Boolean, ResponseFormat> validateUserRole(User user, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType, ArtifactOperationInfo operation) {
3307 if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.Download) {
3308 String role = user.getRole();
3309 if (!role.equals(Role.ADMIN.name()) && !role.equals(Role.DESIGNER.name())) {
3310 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
3311 log.debug("addArtifact - user isn't permitted to perform operation, userId {}, role {}", user.getUserId(), role);
3312 handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentType, null);
3313 return Either.right(responseFormat);
3316 return Either.left(true);
3319 private Either<User, ResponseFormat> validateUserExists(String userId, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType, boolean inTransaction) {
3320 Either<User, ResponseFormat> validateUserExists = validateUserExists(userId, auditingAction.getName(), inTransaction);
3322 if (validateUserExists.isRight()) {
3323 User user = new User();
3324 user.setUserId(userId);
3325 handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, validateUserExists.right().value(), componentType, null);
3326 return Either.right(validateUserExists.right().value());
3328 return Either.left(validateUserExists.left().value());
3331 protected AuditingActionEnum detectAuditingType(ArtifactOperationInfo operation, String origMd5) {
3332 AuditingActionEnum auditingAction = null;
3333 switch (operation.getArtifactOperationEnum()) {
3335 auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_UPLOAD_BY_API : AuditingActionEnum.ARTIFACT_UPLOAD;
3338 auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_UPLOAD_BY_API : origMd5 == null ? AuditingActionEnum.ARTIFACT_METADATA_UPDATE : AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE;
3341 auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_DELETE_BY_API : AuditingActionEnum.ARTIFACT_DELETE;
3344 auditingAction = operation.isExternalApi() ? AuditingActionEnum.DOWNLOAD_ARTIFACT : AuditingActionEnum.ARTIFACT_DOWNLOAD;
3349 return auditingAction;
3352 private Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifact(ArtifactDefinition artifactDefinition) {
3353 String esArtifactId = artifactDefinition.getEsId();
3354 Either<ESArtifactData, CassandraOperationStatus> artifactfromES = artifactCassandraDao.getArtifact(esArtifactId);
3355 if (artifactfromES.isRight()) {
3356 CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value();
3357 StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
3358 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
3359 log.debug("Error when getting artifact from ES, error: {}", actionStatus.name());
3360 return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, artifactDefinition.getArtifactDisplayName()));
3363 ESArtifactData esArtifactData = artifactfromES.left().value();
3364 byte[] data = esArtifactData.getDataAsArray();
3366 log.debug("Artifact data from ES is null");
3367 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactDefinition.getArtifactDisplayName()));
3369 String artifactName = artifactDefinition.getArtifactName();
3370 log.trace("Download of artifact succeeded, uniqueId {}, artifact file name {}", artifactDefinition.getUniqueId(), artifactName);
3371 return Either.left(new ImmutablePair<String, byte[]>(artifactName, data));
3374 public ESArtifactData createEsArtifactData(ArtifactDataDefinition artifactInfo, byte[] artifactPayload) {
3375 ESArtifactData artifactData = new ESArtifactData(artifactInfo.getEsId(), artifactPayload);
3376 return artifactData;
3379 private boolean saveArtifacts(ESArtifactData artifactData, String resourceId, boolean reload) {
3381 CassandraOperationStatus resourceUploadStatus = artifactCassandraDao.saveArtifact(artifactData);
3383 if (resourceUploadStatus.equals(CassandraOperationStatus.OK)) {
3384 log.debug("Artifact {} was saved in component .", artifactData.getId(), resourceId);
3386 log.info("Failed to save artifact {}.", artifactData.getId());
3392 private boolean isArtifactMetadataUpdate(AuditingActionEnum auditingActionEnum) {
3393 return (auditingActionEnum.equals(AuditingActionEnum.ARTIFACT_METADATA_UPDATE));
3396 private boolean isDeploymentArtifact(ArtifactDefinition artifactInfo) {
3397 return (ArtifactGroupTypeEnum.DEPLOYMENT.equals(artifactInfo.getArtifactGroupType()));
3400 public Either<ArtifactDefinition, ResponseFormat> createArtifactPlaceHolderInfo(String resourceId, String logicalName, Map<String, Object> artifactInfoMap, String userUserId, ArtifactGroupTypeEnum groupType, boolean inTransaction) {
3401 Either<User, ActionStatus> user = userAdminManager.getUser(userUserId, inTransaction);
3402 if (user.isRight()) {
3403 ResponseFormat responseFormat;
3404 if (user.right().value().equals(ActionStatus.USER_NOT_FOUND)) {
3405 log.debug("create artifact placeholder - not authorized user, userId {}", userUserId);
3406 responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
3408 log.debug("create artifact placeholder - failed to authorize user, userId {}", userUserId);
3409 responseFormat = componentsUtils.getResponseFormat(user.right().value());
3411 return Either.right(responseFormat);
3414 ArtifactDefinition artifactDefinition = createArtifactPlaceHolderInfo(resourceId, logicalName, artifactInfoMap, user.left().value(), groupType);
3415 return Either.left(artifactDefinition);
3418 public ArtifactDefinition createArtifactPlaceHolderInfo(String resourceId, String logicalName, Map<String, Object> artifactInfoMap, User user, ArtifactGroupTypeEnum groupType) {
3419 ArtifactDefinition artifactInfo = new ArtifactDefinition();
3421 String artifactName = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_DISPLAY_NAME);
3422 String artifactType = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_TYPE);
3423 String artifactDescription = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_DESCRIPTION);
3425 artifactInfo.setArtifactDisplayName(artifactName);
3426 artifactInfo.setArtifactLabel(logicalName.toLowerCase());
3427 artifactInfo.setArtifactType(artifactType);
3428 artifactInfo.setDescription(artifactDescription);
3429 artifactInfo.setArtifactGroupType(groupType);
3430 nodeTemplateOperation.setDefaultArtifactTimeout(groupType, artifactInfo);
3432 setArtifactPlaceholderCommonFields(resourceId, user, artifactInfo);
3434 return artifactInfo;
3437 private void setArtifactPlaceholderCommonFields(String resourceId, User user, ArtifactDefinition artifactInfo) {
3438 String uniqueId = null;
3440 if (resourceId != null) {
3441 uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId.toLowerCase(), artifactInfo.getArtifactLabel().toLowerCase());
3442 artifactInfo.setUniqueId(uniqueId);
3444 artifactInfo.setUserIdCreator(user.getUserId());
3445 String fullName = user.getFullName();
3446 artifactInfo.setUpdaterFullName(fullName);
3448 long time = System.currentTimeMillis();
3450 artifactInfo.setCreatorFullName(fullName);
3451 artifactInfo.setCreationDate(time);
3453 artifactInfo.setLastUpdateDate(time);
3454 artifactInfo.setUserIdLastUpdater(user.getUserId());
3456 artifactInfo.setMandatory(true);
3459 public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(String parentId, NodeTypeEnum parentType, boolean inTransaction, ArtifactGroupTypeEnum groupType, String instanceId) {
3460 return artifactToscaOperation.getArtifacts(parentId, parentType, groupType, instanceId);
3463 public Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact(ArtifactDefinition artifactHeatEnv, ArtifactDefinition artifact, String componentId, NodeTypeEnum parentType, String instanceId) {
3464 return artifactToscaOperation.addHeatEnvArtifact(artifactHeatEnv, artifact, componentId, parentType, true, instanceId);
3467 private Either<ESArtifactData, ResponseFormat> createEsHeatEnvArtifactDataFromString(ArtifactDefinition artifactDefinition, String payloadStr) {
3469 byte[] payload = payloadStr.getBytes();
3471 ESArtifactData artifactData = createEsArtifactData(artifactDefinition, payload);
3472 return Either.left(artifactData);
3477 * @param artifactDefinition
3480 public Either<ArtifactDefinition, ResponseFormat> generateHeatEnvArtifact(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier,
3481 boolean shouldLock, String instanceId) {
3482 String payload = generateHeatEnvPayload(artifactDefinition);
3483 String prevUUID = artifactDefinition.getArtifactUUID();
3484 ArtifactDefinition clonedBeforeGenerate = new ArtifactDefinition(artifactDefinition);
3485 Either<ArtifactDefinition, ResponseFormat> generateResult = generateAndSaveHeatEnvArtifact(artifactDefinition, payload, componentType, component, resourceInstanceName, modifier, shouldLock, instanceId);
3486 if (generateResult.isLeft()) {
3487 ArtifactDefinition updatedArtDef = generateResult.left().value();
3488 if (!prevUUID.equals(updatedArtDef.getArtifactUUID())) {
3489 List<ComponentInstance> componentInstances = component.getComponentInstances();
3490 if (componentInstances != null) {
3491 Optional<ComponentInstance> findFirst = componentInstances.stream().filter(ci -> ci.getUniqueId().equals(instanceId)).findFirst();
3492 if (findFirst.isPresent()) {
3493 ComponentInstance relevantInst = findFirst.get();
3494 List<GroupInstance> updatedGroupInstances = getUpdatedGroupInstances(updatedArtDef.getUniqueId(), clonedBeforeGenerate, relevantInst.getGroupInstances());
3496 if (CollectionUtils.isNotEmpty(updatedGroupInstances)) {
3497 updatedGroupInstances.forEach(gi -> {
3498 gi.getGroupInstanceArtifacts().add(updatedArtDef.getUniqueId());
3499 gi.getGroupInstanceArtifactsUuid().add(updatedArtDef.getArtifactUUID());
3501 Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(component, componentType, instanceId, updatedGroupInstances);
3502 if (status.isRight()) {
3503 log.debug("Failed to update groups of the component {}. ", component.getUniqueId());
3504 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status.right().value()), clonedBeforeGenerate.getArtifactDisplayName());
3505 return Either.right(responseFormat);
3513 return generateResult;
3516 private String generateHeatEnvPayload(ArtifactDefinition artifactDefinition) {
3517 List<HeatParameterDefinition> heatParameters = artifactDefinition.getListHeatParameters();
3518 heatParameters.sort(Comparator.comparing(e -> e.getName()));
3519 StringBuilder sb = new StringBuilder();
3520 sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactHeader());
3521 sb.append("parameters:\n");
3522 if (heatParameters != null) {
3523 List<HeatParameterDefinition> empltyHeatValues = new ArrayList<>();
3525 for (HeatParameterDefinition heatParameterDefinition : heatParameters) {
3527 String heatValue = heatParameterDefinition.getCurrentValue();
3528 if (!ValidationUtils.validateStringNotEmpty(heatValue)) {
3529 heatValue = heatParameterDefinition.getDefaultValue();
3530 if (!ValidationUtils.validateStringNotEmpty(heatValue)) {
3531 empltyHeatValues.add(heatParameterDefinition);
3535 HeatParameterType type = HeatParameterType.isValidType(heatParameterDefinition.getType());
3539 sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(Boolean.parseBoolean(heatValue)).append("\n");
3542 sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(new BigDecimal(heatValue).toPlainString()).append("\n");
3544 case COMMA_DELIMITED_LIST:
3546 sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(heatValue).append("\n");
3549 String value = heatValue;
3550 boolean starts = value.startsWith("\"");
3551 boolean ends = value.endsWith("\"");
3552 if (!(starts && ends)) {
3553 starts = value.startsWith("'");
3554 ends = value.endsWith("'");
3555 if (!(starts && ends)) {
3556 value = "\"" + value + "\"";
3559 sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(value);
3566 if (!empltyHeatValues.isEmpty()) {
3567 empltyHeatValues.sort(Comparator.comparing(e -> e.getName()));
3568 empltyHeatValues.forEach(hv -> {
3569 sb.append(" ").append(hv.getName()).append(":");
3570 HeatParameterType type = HeatParameterType.isValidType(hv.getType());
3571 if (type != null && type == HeatParameterType.STRING && (hv.getCurrentValue() != null && "".equals(hv.getCurrentValue()) || hv.getDefaultValue() != null && "".equals(hv.getDefaultValue()))) {
3572 sb.append(" \"\"").append("\n");
3574 sb.append(" ").append("\n");
3579 sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactFooter());
3582 String result = sb.toString().replaceAll("\\\\n", "\n");
3589 * @param artifactDefinition
3593 public Either<ArtifactDefinition, ResponseFormat> generateAndSaveHeatEnvArtifact(ArtifactDefinition artifactDefinition, String payload, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName,
3594 User modifier, boolean shouldLock, String instanceId) {
3595 return generateArtifactPayload(artifactDefinition, componentType, component, resourceInstanceName, modifier, shouldLock, () -> artifactDefinition.getHeatParamsUpdateDate(),
3596 () -> createEsHeatEnvArtifactDataFromString(artifactDefinition, payload), instanceId);
3600 protected Either<ArtifactDefinition, ResponseFormat> generateArtifactPayload(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier,
3601 boolean shouldLock, Supplier<Long> payloadUpdateDateGen, Supplier<Either<ESArtifactData, ResponseFormat>> esDataCreator, String instanceId) {
3603 if (artifactDefinition.getPayloadUpdateDate() == null || artifactDefinition.getPayloadUpdateDate() == 0 || artifactDefinition.getPayloadUpdateDate() < payloadUpdateDateGen.get()) {
3605 log.trace("Generaing payload for {} artifact {}", artifactDefinition.getArtifactType(), artifactDefinition.getEsId());
3606 Either<ESArtifactData, ResponseFormat> artifactDataRes = esDataCreator.get();
3607 ESArtifactData artifactData = null;
3609 if (artifactDataRes.isLeft()) {
3610 artifactData = artifactDataRes.left().value();
3612 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
3613 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
3614 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
3616 return Either.right(artifactDataRes.right().value());
3618 String newCheckSum = GeneralUtility.calculateMD5ByByteArray(artifactData.getDataAsArray());
3620 String esArtifactId = artifactDefinition.getEsId();
3621 Either<ESArtifactData, CassandraOperationStatus> artifactfromES;
3622 ESArtifactData esArtifactData;
3623 if (esArtifactId != null && !esArtifactId.isEmpty() && artifactDefinition.getPayloadData() == null) {
3624 artifactfromES = artifactCassandraDao.getArtifact(esArtifactId);
3625 if (artifactfromES.isRight()) {
3626 CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value();
3627 StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
3628 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
3629 log.debug("Error when getting artifact from ES, error: {}", actionStatus.name());
3630 return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, artifactDefinition.getArtifactDisplayName()));
3632 esArtifactData = artifactfromES.left().value();
3633 oldCheckSum = GeneralUtility.calculateMD5ByByteArray(esArtifactData.getDataAsArray());
3635 oldCheckSum = artifactDefinition.getArtifactChecksum();
3638 Either<ArtifactDefinition, StorageOperationStatus> updateArifactDefinitionStatus = null;
3641 Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, "Update Artifact - lock resource: ");
3642 if (lockComponent.isRight()) {
3643 handleAuditing(AuditingActionEnum.ARTIFACT_METADATA_UPDATE, component, component.getUniqueId(), modifier, null, null, artifactDefinition.getUniqueId(), lockComponent.right().value(), component.getComponentType(), null);
3644 return Either.right(lockComponent.right().value());
3648 if (oldCheckSum != null && oldCheckSum.equals(newCheckSum)) {
3650 artifactDefinition.setPayloadUpdateDate(payloadUpdateDateGen.get());
3651 updateArifactDefinitionStatus = artifactToscaOperation.updateArifactOnResource(artifactDefinition, component.getUniqueId(), artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId);
3652 log.trace("No real update done in payload for {} artifact, updating payloadUpdateDate {}", artifactDefinition.getArtifactType(), artifactDefinition.getEsId());
3653 if (updateArifactDefinitionStatus.isRight()) {
3654 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus.right().value()), artifactDefinition.getArtifactDisplayName());
3655 log.trace("Failed to update payloadUpdateDate {}", artifactDefinition.getEsId());
3656 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
3657 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
3659 return Either.right(responseFormat);
3663 oldCheckSum = artifactDefinition.getArtifactChecksum();
3664 artifactDefinition.setArtifactChecksum(newCheckSum);
3665 // artifactToscaOperation.updateUUID(artifactDefinition, oldCheckSum, artifactDefinition.getArtifactVersion());
3666 artifactDefinition.setEsId(artifactDefinition.getUniqueId());
3667 updateArifactDefinitionStatus = artifactToscaOperation.updateArifactOnResource(artifactDefinition, component.getUniqueId(), artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId);
3669 log.trace("Update Payload ", artifactDefinition.getEsId());
3671 if (updateArifactDefinitionStatus != null && updateArifactDefinitionStatus.isLeft()) {
3673 artifactDefinition = updateArifactDefinitionStatus.left().value();
3674 artifactData.setId(artifactDefinition.getUniqueId());
3675 CassandraOperationStatus saveArtifactStatus = artifactCassandraDao.saveArtifact(artifactData);
3677 if (saveArtifactStatus.equals(CassandraOperationStatus.OK)) {
3679 log.debug("Artifact Saved In ES {}", artifactData.getId());
3680 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
3681 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
3682 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
3685 titanDao.rollback();
3686 log.info("Failed to save artifact {}.", artifactData.getId());
3687 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
3688 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
3689 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
3691 return Either.right(responseFormat);
3694 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus.right().value()), artifactDefinition.getArtifactDisplayName());
3695 log.debug("Failed To update artifact {}", artifactData.getId());
3696 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
3697 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
3699 return Either.right(responseFormat);
3704 graphLockOperation.unlockComponent(component.getUniqueId(), component.getComponentType().getNodeType());
3709 return Either.left(artifactDefinition);
3712 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdateHeatEnv(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType,
3713 org.openecomp.sdc.be.model.Component parent, String originData, String origMd5, ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) {
3714 convertParentType(componentType);
3715 String parentId = parent.getUniqueId();
3716 // Either<ArtifactDefinition, StorageOperationStatus> artifactRes = this.artifactToscaOperation.getArtifactById(componentId, artifactId);
3717 ArtifactDefinition currArtifact = artifactInfo;
3719 if (origMd5 != null) {
3720 Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
3721 if (validateMd5.isRight()) {
3722 ResponseFormat responseFormat = validateMd5.right().value();
3723 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
3724 return Either.right(responseFormat);
3727 if (artifactInfo.getPayloadData() != null && artifactInfo.getPayloadData().length != 0) {
3728 Either<Boolean, ResponseFormat> deploymentValidationResult = validateDeploymentArtifact(parent, componentId, user.getUserId(), false, artifactInfo, currArtifact, NodeTypeEnum.ResourceInstance);
3729 if (deploymentValidationResult.isRight()) {
3730 ResponseFormat responseFormat = deploymentValidationResult.right().value();
3731 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
3732 return Either.right(responseFormat);
3735 Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
3736 if (payloadEither.isRight()) {
3737 ResponseFormat responseFormat = payloadEither.right().value();
3738 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
3739 return Either.right(responseFormat);
3741 } else { // duplicate
3742 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
3743 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
3744 return Either.right(responseFormat);
3750 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Update Artifact - lock ");
3751 if (lockComponent.isRight()) {
3752 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right().value(), componentType, null);
3753 return Either.right(lockComponent.right().value());
3756 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
3758 resultOp = updateHeatEnvParams(componentId, artifactId, artifactInfo, user, auditingAction, parent, componentType, currArtifact, origMd5, inTransaction);
3763 if (resultOp == null || resultOp.isRight()) {
3764 log.debug("all changes rollback");
3765 if (false == inTransaction)
3766 titanDao.rollback();
3768 log.debug("all changes committed");
3769 if (false == inTransaction)
3773 componentType = parent.getComponentType();
3774 NodeTypeEnum nodeType = componentType.getNodeType();
3775 graphLockOperation.unlockComponent(parent.getUniqueId(), nodeType);
3776 // graphLockOperation.unlockComponent(parentId, parentType);
3780 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateHeatEnvParams(String componentId, String artifactId, ArtifactDefinition artifactInfo, User user, AuditingActionEnum auditingAction, Component parent,
3781 ComponentTypeEnum componentType, ArtifactDefinition currArtifact1, String origMd5, boolean inTransaction) {
3783 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
3784 Either<ArtifactDefinition, Operation> insideEither = null;
3786 * currently getArtifactById does not retrieve heatParameters Either<ArtifactDefinition, StorageOperationStatus> artifactRes = artifactOperation.getArtifactById(artifactId, false); ArtifactDefinition currArtifact = artifactRes.left().value();
3788 Either<ComponentInstance, ResponseFormat> getRI = getRIFromComponent(parent, componentId, artifactId, auditingAction, user);
3789 if (getRI.isRight()) {
3790 return Either.right(getRI.right().value());
3792 ComponentInstance ri = getRI.left().value();
3793 Either<ArtifactDefinition, ResponseFormat> getArtifactRes = getArtifactFromRI(parent, ri, componentId, artifactId, auditingAction, user);
3794 if (getArtifactRes.isRight()) {
3795 return Either.right(getArtifactRes.right().value());
3797 ArtifactDefinition currArtifact = getArtifactRes.left().value();
3799 if (currArtifact.getArtifactType().equals(ArtifactTypeEnum.HEAT.getType()) || currArtifact.getArtifactType().equals(ArtifactTypeEnum.HEAT_VOL.getType()) || currArtifact.getArtifactType().equals(ArtifactTypeEnum.HEAT_NET.getType())) {
3800 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
3801 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
3802 return Either.right(responseFormat);
3804 List<HeatParameterDefinition> currentHeatEnvParams = currArtifact.getListHeatParameters();
3805 List<HeatParameterDefinition> updatedHeatEnvParams = artifactInfo.getListHeatParameters();
3806 new ArrayList<HeatParameterDefinition>();
3809 if (origMd5 != null) {
3810 Either<List<HeatParameterDefinition>, ResponseFormat> uploadParamsValidationResult = validateUploadParamsFromEnvFile(auditingAction, parent, user, artifactInfo, artifactId, componentType, ri.getName(), currentHeatEnvParams,
3811 updatedHeatEnvParams, currArtifact.getArtifactName());
3812 if (uploadParamsValidationResult.isRight()) {
3813 ResponseFormat responseFormat = uploadParamsValidationResult.right().value();
3814 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
3815 return Either.right(responseFormat);
3817 artifactInfo.setListHeatParameters(updatedHeatEnvParams);
3820 Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers = validateAndConvertHeatParamers(artifactInfo, ArtifactTypeEnum.HEAT_ENV.getType());
3821 if (validateAndConvertHeatParamers.isRight()) {
3822 ResponseFormat responseFormat = validateAndConvertHeatParamers.right().value();
3823 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
3824 return Either.right(responseFormat);
3827 if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty()) {
3829 // fill reduced heat env parameters List for updating
3830 for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) {
3831 paramName = heatEnvParam.getName();
3832 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
3833 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
3834 String updatedParamValue = heatEnvParam.getCurrentValue();
3835 if (updatedParamValue != null && updatedParamValue.equals("")) { // reset
3836 currHeatParam.setCurrentValue(heatEnvParam.getDefaultValue());
3837 } else if (updatedParamValue != null) {
3838 currHeatParam.setCurrentValue(updatedParamValue);
3843 currArtifact.setHeatParamsUpdateDate(System.currentTimeMillis());
3844 currArtifact.setListHeatParameters(currentHeatEnvParams);
3846 Either<ArtifactDefinition, StorageOperationStatus> updateArifactRes = artifactToscaOperation.updateArifactOnResource(currArtifact, parent.getUniqueId(), currArtifact.getUniqueId(), componentType.getNodeType(), componentId);
3847 if (updateArifactRes.isRight()) {
3848 log.debug("Failed to update artifact on graph - {}", artifactId);
3849 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateArifactRes.right().value()));
3850 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
3851 return Either.right(responseFormat);
3853 StorageOperationStatus error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), ri.getUniqueId(), componentType);
3854 if (error != StorageOperationStatus.OK) {
3855 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
3856 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
3857 return Either.right(responseFormat);
3860 error = generateCustomizationUUIDOnGroupInstance(ri, updateArifactRes.left().value().getUniqueId(), parent.getUniqueId());
3861 if (error != StorageOperationStatus.OK) {
3862 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
3863 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
3864 return Either.right(responseFormat);
3870 insideEither = Either.left(currArtifact);
3871 resultOp = Either.left(insideEither);
3872 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
3873 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currArtifact, null, artifactId, responseFormat, componentType, ri.getName());
3877 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateHeatParams(String componentId, String artifactId, ArtifactDefinition artifactEnvInfo, User user, AuditingActionEnum auditingAction, Component parent,
3878 ComponentTypeEnum componentType, ArtifactDefinition currHeatArtifact, String origMd5, boolean needToUpdateGroup) {
3880 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
3881 Either<ArtifactDefinition, Operation> insideEither = null;
3883 * currently getArtifactById does not retrieve heatParameters Either<ArtifactDefinition, StorageOperationStatus> artifactRes = artifactOperation.getArtifactById(artifactId, false); ArtifactDefinition currArtifact = artifactRes.left().value();
3885 String currentHeatId = currHeatArtifact.getUniqueId();
3887 String esArtifactId = currHeatArtifact.getEsId();
3888 Either<ESArtifactData, CassandraOperationStatus> artifactfromES = artifactCassandraDao.getArtifact(esArtifactId);
3889 if (artifactfromES.isRight()) {
3890 CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value();
3891 StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
3892 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
3893 log.debug("Error when getting artifact from ES, error: {}", actionStatus.name());
3894 return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, currHeatArtifact.getArtifactDisplayName()));
3897 ESArtifactData esArtifactData = artifactfromES.left().value();
3898 byte[] data = esArtifactData.getDataAsArray();
3901 ArtifactDefinition updatedHeatArt = currHeatArtifact;
3903 List<HeatParameterDefinition> updatedHeatEnvParams = artifactEnvInfo.getListHeatParameters();
3904 List<HeatParameterDefinition> currentHeatEnvParams = currHeatArtifact.getListHeatParameters();
3905 List<HeatParameterDefinition> newHeatEnvParams = new ArrayList<HeatParameterDefinition>();
3907 if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty() && currentHeatEnvParams != null && !currentHeatEnvParams.isEmpty()) {
3910 for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) {
3912 paramName = heatEnvParam.getName();
3913 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
3914 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
3916 String updatedParamValue = heatEnvParam.getCurrentValue();
3917 if (updatedParamValue == null)
3918 updatedParamValue = heatEnvParam.getDefaultValue();
3919 HeatParameterType paramType = HeatParameterType.isValidType(currHeatParam.getType());
3920 if (!paramType.getValidator().isValid(updatedParamValue, null)) {
3921 ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE;
3922 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, ArtifactTypeEnum.HEAT_ENV.getType(), paramType.getType(), paramName);
3923 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactEnvInfo, null, artifactId, responseFormat, componentType, "");
3924 return Either.right(responseFormat);
3927 currHeatParam.setCurrentValue(paramType.getConverter().convert(updatedParamValue, null, null));
3928 newHeatEnvParams.add(currHeatParam);
3933 if (!newHeatEnvParams.isEmpty()) {
3934 currHeatArtifact.setListHeatParameters(currentHeatEnvParams);
3935 Either<ArtifactDefinition, StorageOperationStatus> operationStatus = artifactToscaOperation.updateArifactOnResource(currHeatArtifact, parent.getUniqueId(), currHeatArtifact.getUniqueId(), componentType.getNodeType(), componentId);
3937 if (operationStatus.isRight()) {
3938 log.debug("Failed to update artifact on graph - {}", currHeatArtifact.getUniqueId());
3940 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(operationStatus.right().value()));
3941 return Either.right(responseFormat);
3944 updatedHeatArt = operationStatus.left().value();
3946 if (!updatedHeatArt.getDuplicated() || esArtifactData.getId() == null)
3947 esArtifactData.setId(updatedHeatArt.getEsId());
3948 res = saveArtifacts(esArtifactData, parent.getUniqueId(), false);
3951 log.debug("Artifact saved into ES - {}", updatedHeatArt.getUniqueId());
3952 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
3953 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, updatedHeatArt, currentHeatId, updatedHeatArt.getUniqueId(), responseFormat, componentType, null);
3954 // resultOp = Either.left(result.left().value());
3957 BeEcompErrorManager.getInstance().logBeDaoSystemError("Update Artifact");
3958 log.debug("Failed to save the artifact.");
3959 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
3960 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, updatedHeatArt, currentHeatId, updatedHeatArt.getUniqueId(), responseFormat, componentType, null);
3961 resultOp = Either.right(responseFormat);
3965 insideEither = Either.left(updatedHeatArt);
3968 Either<ArtifactDefinition, StorageOperationStatus> updateHeatEnvArtifact;
3969 if (!currentHeatId.equals(updatedHeatArt.getUniqueId())) {
3970 artifactEnvInfo.setArtifactChecksum(null);
3971 updateHeatEnvArtifact = artifactToscaOperation.updateHeatEnvArtifact(parent.getUniqueId(), artifactEnvInfo, currentHeatId, updatedHeatArt.getUniqueId(), componentType.getNodeType(), componentId);
3973 updateHeatEnvArtifact = artifactToscaOperation.updateHeatEnvPlaceholder(artifactEnvInfo, componentId, componentType.getNodeType());
3976 if ( needToUpdateGroup && updateHeatEnvArtifact.isLeft() ){
3977 ActionStatus result = updateGroupForHeat(currHeatArtifact, updatedHeatArt, artifactEnvInfo, updateHeatEnvArtifact.left().value(), parent, componentType);
3978 if ( result != ActionStatus.OK ){
3979 ResponseFormat responseFormat = componentsUtils.getResponseFormat(result);
3980 return Either.right(responseFormat);
3983 resultOp = Either.left(insideEither);
3984 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
3985 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currHeatArtifact, null, artifactId, responseFormat, componentType, "");
3990 private StorageOperationStatus generateCustomizationUUIDOnGroupInstance(ComponentInstance ri, String artifactId, String componentId) {
3991 StorageOperationStatus error = StorageOperationStatus.OK;
3992 log.debug("Need to re-generate customization UUID for group instance on component instance {}", ri.getUniqueId());
3993 List<GroupInstance> groupsInstances = ri.getGroupInstances();
3994 // List<GroupInstance> associatedGroups = null;
3995 List<String> groupInstancesId = null;
3996 if (groupsInstances != null && !groupsInstances.isEmpty()) {
3997 groupInstancesId = groupsInstances.stream().filter(p -> p.getGroupInstanceArtifacts() != null && p.getGroupInstanceArtifacts().contains(artifactId)).map(p -> p.getUniqueId()).collect(Collectors.toList());
3999 if (groupInstancesId != null && !groupInstancesId.isEmpty()) {
4000 // associatedGroups.stream().forEach(c -> this.groupInstanceOperation.updateCustomizationUUID(c.getUniqueId()));
4001 toscaOperationFacade.generateCustomizationUUIDOnInstanceGroup(componentId, ri.getUniqueId(), groupInstancesId);
4007 public Either<List<HeatParameterDefinition>, ResponseFormat> validateUploadParamsFromEnvFile(AuditingActionEnum auditingAction, Component parent, User user, ArtifactDefinition artifactInfo, String artifactId, ComponentTypeEnum componentType,
4008 String riName, List<HeatParameterDefinition> currentHeatEnvParams, List<HeatParameterDefinition> updatedHeatEnvParams, String currArtifactName) {
4010 if (updatedHeatEnvParams == null || updatedHeatEnvParams.isEmpty()) {
4011 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactInfo.getArtifactName(), currArtifactName);
4012 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, riName);
4013 return Either.right(responseFormat);
4016 for (HeatParameterDefinition uploadedHeatParam : updatedHeatEnvParams) {
4017 String paramName = uploadedHeatParam.getName();
4018 boolean isExistsInHeat = false;
4019 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
4020 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
4022 isExistsInHeat = true;
4023 uploadedHeatParam.setType(currHeatParam.getType());
4024 uploadedHeatParam.setCurrentValue(uploadedHeatParam.getDefaultValue());
4025 uploadedHeatParam.setDefaultValue(currHeatParam.getDefaultValue());
4026 uploadedHeatParam.setUniqueId(currHeatParam.getUniqueId());
4030 if (!isExistsInHeat) {
4031 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, currArtifactName);
4032 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, riName);
4033 return Either.right(responseFormat);
4036 return Either.left(updatedHeatEnvParams);
4039 private Either<ComponentInstance, ResponseFormat> getRIFromComponent(Component component, String riID, String artifactId, AuditingActionEnum auditingAction, User user) {
4040 ResponseFormat responseFormat = null;
4041 List<ComponentInstance> ris = component.getComponentInstances();
4042 for (ComponentInstance ri : ris) {
4043 if (riID.equals(ri.getUniqueId())) {
4044 return Either.left(ri);
4047 responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, riID);
4048 log.debug("Resource Instance not found, resourceInstanceId {}", riID);
4049 handleAuditing(auditingAction, null, riID, user, null, null, artifactId, responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE, null);
4050 return Either.right(responseFormat);
4053 private Either<ArtifactDefinition, ResponseFormat> getArtifactFromRI(Component component, ComponentInstance ri, String riID, String artifactId, AuditingActionEnum auditingAction, User user) {
4054 ResponseFormat responseFormat = null;
4055 Map<String, ArtifactDefinition> rtifactsMap = ri.getDeploymentArtifacts();
4056 for (ArtifactDefinition artifact : rtifactsMap.values()) {
4057 if (artifactId.equals(artifact.getUniqueId())) {
4058 return Either.left(artifact);
4061 responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, riID, component.getUniqueId());
4062 handleAuditing(auditingAction, component, riID, user, null, null, artifactId, responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE, ri.getName());
4063 return Either.right(responseFormat);
4066 public ArtifactDefinition extractArtifactDefinition(Either<ArtifactDefinition, Operation> eitherArtifact) {
4067 ArtifactDefinition ret;
4068 if (eitherArtifact.isLeft()) {
4069 ret = eitherArtifact.left().value();
4071 ret = eitherArtifact.right().value().getImplementationArtifact();
4077 * downloads artifact of component by UUIDs
4079 * @param componentType
4080 * @param componentUuid
4081 * @param artifactUUID
4082 * @param auditAdditionalParam
4085 public Either<byte[], ResponseFormat> downloadComponentArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String artifactUUID, Map<AuditingFieldsKeysEnum, Object> auditAdditionalParam) {
4086 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4087 Either<byte[], ResponseFormat> result;
4088 byte[] downloadedArtifact = null;
4089 Component component = getComponentByUuid(componentType, componentUuid, errorWrapper);
4090 if (errorWrapper.isEmpty()) {
4091 auditAdditionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, component.getName());
4092 downloadedArtifact = downloadArtifact(component.getDeploymentArtifacts(), artifactUUID, errorWrapper, component.getName());
4094 if (errorWrapper.isEmpty()) {
4095 result = Either.left(downloadedArtifact);
4097 result = Either.right(errorWrapper.getInnerElement());
4103 * downloads an artifact of resource instance of component by UUIDs
4105 * @param componentType
4106 * @param componentUuid
4107 * @param resourceName
4108 * @param artifactUUID
4109 * @param auditAdditionalParam
4112 public Either<byte[], ResponseFormat> downloadResourceInstanceArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID, Map<AuditingFieldsKeysEnum, Object> auditAdditionalParam) {
4113 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4114 Either<byte[], ResponseFormat> result;
4115 byte[] downloadedArtifact = null;
4116 ComponentInstance resourceInstance = getRelatedComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
4117 if (errorWrapper.isEmpty()) {
4118 downloadedArtifact = downloadArtifact(resourceInstance.getDeploymentArtifacts(), artifactUUID, errorWrapper, resourceInstance.getName());
4120 if (errorWrapper.isEmpty()) {
4121 result = Either.left(downloadedArtifact);
4123 result = Either.right(errorWrapper.getInnerElement());
4129 * uploads an artifact to a component by UUID
4133 * @param componentType
4134 * @param componentUuid
4135 * @param additionalParams
4139 public Either<ArtifactDefinition, ResponseFormat> uploadArtifactToComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, Map<AuditingFieldsKeysEnum, Object> additionalParams,
4140 ArtifactOperationInfo operation) {
4141 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4142 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4143 Either<ArtifactDefinition, ResponseFormat> uploadArtifactResult;
4144 ArtifactDefinition uploadArtifact = null;
4145 Component component = null;
4146 String componentId = null;
4147 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
4148 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4149 String userId = request.getHeader(Constants.USER_ID_HEADER);
4151 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4152 if (getComponentRes.isRight()) {
4153 StorageOperationStatus status = getComponentRes.right().value();
4154 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4155 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), componentUuid));
4157 if (errorWrapper.isEmpty()) {
4158 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
4159 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
4161 if (!getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4162 component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
4163 if (component != null) {
4164 componentId = component.getUniqueId();
4165 componentName = component.getName();
4168 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentName);
4170 if (errorWrapper.isEmpty()) {
4171 actionResult = handleArtifactRequest(componentId, userId, componentType, operation, null, artifactInfo, origMd5, data, null, null, null, null);
4172 if (actionResult.isRight()) {
4173 log.debug("Failed to upload artifact to component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, actionResult.right().value());
4174 errorWrapper.setInnerElement(actionResult.right().value());
4177 if (errorWrapper.isEmpty()) {
4178 uploadArtifact = actionResult.left().value().left().value();
4179 uploadArtifactResult = Either.left(uploadArtifact);
4181 uploadArtifactResult = Either.right(errorWrapper.getInnerElement());
4183 updateAuditParametersWithArtifactDefinition(additionalParams, uploadArtifact);
4184 return uploadArtifactResult;
4188 * upload an artifact to a resource instance by UUID
4192 * @param componentType
4193 * @param componentUuid
4194 * @param resourceInstanceName
4195 * @param additionalParams
4199 public Either<ArtifactDefinition, ResponseFormat> uploadArtifactToRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName,
4200 Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
4201 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4202 Either<ArtifactDefinition, ResponseFormat> uploadArtifactResult;
4203 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4204 ArtifactDefinition uploadArtifact = null;
4205 Component component = null;
4206 String componentInstanceId;
4208 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4209 String userId = request.getHeader(Constants.USER_ID_HEADER);
4211 ImmutablePair<Component, ComponentInstance> componentRiPair = null;
4212 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4213 if (getComponentRes.isRight()) {
4214 StorageOperationStatus status = getComponentRes.right().value();
4215 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4216 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), resourceInstanceName));
4218 if (errorWrapper.isEmpty() && !getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4219 component = checkoutParentComponent(componentType, getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(), userId, errorWrapper);
4221 if (errorWrapper.isEmpty()) {
4222 if (component == null) {
4223 componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
4225 componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
4228 if (errorWrapper.isEmpty()) {
4229 componentInstanceId = componentRiPair.getRight().getUniqueId();
4230 componentId = componentRiPair.getLeft().getUniqueId();
4231 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
4233 actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, null, artifactInfo, origMd5, data, null, null, componentId, ComponentTypeEnum.findParamByType(componentType));
4234 if (actionResult.isRight()) {
4235 log.debug("Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. ", resourceInstanceName, componentType, componentUuid, actionResult.right().value());
4236 errorWrapper.setInnerElement(actionResult.right().value());
4239 if (errorWrapper.isEmpty()) {
4240 uploadArtifact = actionResult.left().value().left().value();
4241 uploadArtifactResult = Either.left(uploadArtifact);
4243 uploadArtifactResult = Either.right(errorWrapper.getInnerElement());
4245 updateAuditParametersWithArtifactDefinition(additionalParams, uploadArtifact);
4246 return uploadArtifactResult;
4250 * updates an artifact on a component by UUID
4254 * @param componentType
4255 * @param componentUuid
4256 * @param artifactUUID
4257 * @param additionalParams
4262 public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID,
4263 Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
4264 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4265 Either<ArtifactDefinition, ResponseFormat> updateArtifactResult;
4266 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4267 ArtifactDefinition updateArtifact = null;
4268 Component component = null;
4269 String componentId = null;
4270 String artifactId = null;
4271 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
4272 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4273 String userId = request.getHeader(Constants.USER_ID_HEADER);
4275 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4276 if (getComponentRes.isRight()) {
4277 StorageOperationStatus status = getComponentRes.right().value();
4278 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4279 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4281 if (errorWrapper.isEmpty()) {
4282 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
4283 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
4285 if (!getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4286 component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
4287 if (component != null) {
4288 componentId = component.getUniqueId();
4289 componentName = component.getName();
4292 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentName);
4294 if (errorWrapper.isEmpty()) {
4295 artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentId, componentType);
4297 if (errorWrapper.isEmpty()) {
4298 actionResult = handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, origMd5, data, null, null, null, null);
4299 if (actionResult.isRight()) {
4300 log.debug("Failed to upload artifact to component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, actionResult.right().value());
4301 errorWrapper.setInnerElement(actionResult.right().value());
4304 if (errorWrapper.isEmpty()) {
4305 updateArtifact = actionResult.left().value().left().value();
4306 updateArtifactResult = Either.left(updateArtifact);
4309 updateArtifactResult = Either.right(errorWrapper.getInnerElement());
4311 updateAuditParametersWithArtifactDefinition(additionalParams, updateArtifact);
4312 return updateArtifactResult;
4316 * updates an artifact on a resource instance by UUID
4320 * @param componentType
4321 * @param componentUuid
4322 * @param resourceInstanceName
4323 * @param artifactUUID
4324 * @param additionalParams
4329 public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID,
4330 Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
4332 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4333 Either<ArtifactDefinition, ResponseFormat> updateArtifactResult;
4334 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4335 ArtifactDefinition updateArtifact = null;
4336 Component component = null;
4337 String componentInstanceId = null;
4338 String componentId = null;
4339 String artifactId = null;
4340 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4341 String userId = request.getHeader(Constants.USER_ID_HEADER);
4343 ImmutablePair<Component, ComponentInstance> componentRiPair = null;
4344 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4345 if (getComponentRes.isRight()) {
4346 StorageOperationStatus status = getComponentRes.right().value();
4347 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4348 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4350 if (errorWrapper.isEmpty() && !getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4351 component = checkoutParentComponent(componentType, getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(), userId, errorWrapper);
4353 if (errorWrapper.isEmpty()) {
4354 if (component == null) {
4355 componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
4357 componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
4360 if (errorWrapper.isEmpty()) {
4361 componentInstanceId = componentRiPair.getRight().getUniqueId();
4362 componentId = componentRiPair.getLeft().getUniqueId();
4363 artifactId = findArtifactId(componentRiPair.getRight(), artifactUUID, errorWrapper);
4365 if (errorWrapper.isEmpty()) {
4366 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
4368 actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, artifactInfo, origMd5, data, null, null, componentId, ComponentTypeEnum.findParamByType(componentType));
4369 if (actionResult.isRight()) {
4370 log.debug("Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. ", resourceInstanceName, componentType, componentUuid, actionResult.right().value());
4371 errorWrapper.setInnerElement(actionResult.right().value());
4374 if (errorWrapper.isEmpty()) {
4375 updateArtifact = actionResult.left().value().left().value();
4376 updateArtifactResult = Either.left(updateArtifact);
4378 updateArtifactResult = Either.right(errorWrapper.getInnerElement());
4380 updateAuditParametersWithArtifactDefinition(additionalParams, updateArtifact);
4381 return updateArtifactResult;
4385 * deletes an artifact on a component by UUID
4388 * @param componentType
4389 * @param componentUuid
4390 * @param artifactUUID
4391 * @param additionalParams
4396 public Either<ArtifactDefinition, ResponseFormat> deleteArtifactOnComponentByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID, Map<AuditingFieldsKeysEnum, Object> additionalParams,
4397 ArtifactOperationInfo operation) {
4399 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4400 Either<ArtifactDefinition, ResponseFormat> deleteArtifactResult;
4401 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4402 ArtifactDefinition deleteArtifact = null;
4403 Component component = null;
4404 String componentId = null;
4405 String artifactId = null;
4406 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4407 String userId = request.getHeader(Constants.USER_ID_HEADER);
4409 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4410 if (getComponentRes.isRight()) {
4411 StorageOperationStatus status = getComponentRes.right().value();
4412 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4413 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), componentUuid));
4415 if (errorWrapper.isEmpty()) {
4416 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
4417 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
4418 if (!getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4419 component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
4420 if (component != null) {
4421 componentId = component.getUniqueId();
4422 componentName = component.getName();
4425 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentName);
4427 if (errorWrapper.isEmpty()) {
4428 artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentId, componentType);
4430 if (errorWrapper.isEmpty()) {
4431 actionResult = handleArtifactRequest(componentId, userId, componentType, operation, artifactId, null, origMd5, null, null, null, null, null);
4432 if (actionResult.isRight()) {
4433 log.debug("Failed to upload artifact to component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, actionResult.right().value());
4434 errorWrapper.setInnerElement(actionResult.right().value());
4437 if (errorWrapper.isEmpty()) {
4438 deleteArtifact = actionResult.left().value().left().value();
4439 deleteArtifactResult = Either.left(deleteArtifact);
4441 deleteArtifactResult = Either.right(errorWrapper.getInnerElement());
4443 updateAuditParametersWithArtifactDefinition(additionalParams, deleteArtifact);
4444 return deleteArtifactResult;
4448 * deletes an artifact from a resource instance by UUID
4451 * @param componentType
4452 * @param componentUuid
4453 * @param resourceInstanceName
4454 * @param artifactUUID
4455 * @param additionalParams
4460 public Either<ArtifactDefinition, ResponseFormat> deleteArtifactOnRiByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID,
4461 Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
4463 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4464 Either<ArtifactDefinition, ResponseFormat> deleteArtifactResult;
4465 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4466 ArtifactDefinition deleteArtifact = null;
4467 Component component = null;
4468 String componentInstanceId = null;
4469 String componentId = null;
4470 String artifactId = null;
4471 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4472 String userId = request.getHeader(Constants.USER_ID_HEADER);
4473 ImmutablePair<Component, ComponentInstance> componentRiPair = null;
4474 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4475 if (getComponentRes.isRight()) {
4476 StorageOperationStatus status = getComponentRes.right().value();
4477 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4478 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4480 if (errorWrapper.isEmpty() && !getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4481 component = checkoutParentComponent(componentType, getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(), userId, errorWrapper);
4483 if (errorWrapper.isEmpty()) {
4484 if (component == null) {
4485 componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
4487 componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
4490 if (errorWrapper.isEmpty()) {
4491 componentInstanceId = componentRiPair.getRight().getUniqueId();
4492 componentId = componentRiPair.getLeft().getUniqueId();
4493 artifactId = findArtifactId(componentRiPair.getRight(), artifactUUID, errorWrapper);
4495 if (errorWrapper.isEmpty()) {
4497 actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, null, origMd5, null, null, null, componentId, ComponentTypeEnum.findParamByType(componentType));
4499 if (actionResult.isRight()) {
4500 log.debug("Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. ", resourceInstanceName, componentType, componentUuid, actionResult.right().value());
4501 errorWrapper.setInnerElement(actionResult.right().value());
4504 if (errorWrapper.isEmpty()) {
4505 deleteArtifact = actionResult.left().value().left().value();
4506 deleteArtifactResult = Either.left(deleteArtifact);
4508 deleteArtifactResult = Either.right(errorWrapper.getInnerElement());
4510 updateAuditParametersWithArtifactDefinition(additionalParams, deleteArtifact);
4511 return deleteArtifactResult;
4514 private String findArtifactId(ComponentInstance instance, String artifactUUID, Wrapper<ResponseFormat> errorWrapper) {
4515 String artifactId = null;
4516 ArtifactDefinition foundArtifact = null;
4517 if (instance.getDeploymentArtifacts() != null) {
4518 foundArtifact = instance.getDeploymentArtifacts().values().stream().filter(e -> e.getArtifactUUID() != null && e.getArtifactUUID().equals(artifactUUID)).findFirst().orElse(null);
4520 if (foundArtifact == null && instance.getArtifacts() != null) {
4521 foundArtifact = instance.getArtifacts().values().stream().filter(e -> e.getArtifactUUID() != null && e.getArtifactUUID().equals(artifactUUID)).findFirst().orElse(null);
4523 if (foundArtifact == null) {
4524 log.debug("The artifact {} was not found on instance {}. ", artifactUUID, instance.getUniqueId());
4525 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactUUID));
4527 artifactId = foundArtifact.getUniqueId();
4532 public Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder(ArtifactDefinition artifact, String envType, String parentId, NodeTypeEnum parentType, String parentName, User user, Component component,
4533 Map<String, String> existingEnvVersions) {
4534 return createHeatEnvPlaceHolder(artifact, envType, parentId, parentType, parentName, user, component, existingEnvVersions, true);
4538 @SuppressWarnings("unchecked")
4539 public Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder(ArtifactDefinition artifact, String envType, String parentId, NodeTypeEnum parentType, String parentName, User user, Component component,
4540 Map<String, String> existingEnvVersions, boolean overrideId) {
4541 Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getDeploymentResourceInstanceArtifacts();
4542 if (deploymentResourceArtifacts == null) {
4543 log.debug("no deployment artifacts are configured for generated artifacts");
4544 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
4546 Map<String, Object> placeHolderData = (Map<String, Object>) deploymentResourceArtifacts.get(envType);
4547 if (placeHolderData == null) {
4548 log.debug("no env type {} are configured for generated artifacts", envType);
4549 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
4552 String envLabel = (artifact.getArtifactLabel() + HEAT_ENV_SUFFIX).toLowerCase();
4553 String parentIdParam = parentId;
4555 parentIdParam = null;
4557 Either<ArtifactDefinition, ResponseFormat> createArtifactPlaceHolder = createArtifactPlaceHolderInfo(parentIdParam, envLabel, placeHolderData, user.getUserId(), ArtifactGroupTypeEnum.DEPLOYMENT, true);
4558 if (createArtifactPlaceHolder.isRight()) {
4559 return Either.right(createArtifactPlaceHolder.right().value());
4561 ArtifactDefinition artifactHeatEnv = createArtifactPlaceHolder.left().value();
4563 // fix for migration only!!!! create heat env placeholder according to heat id.
4564 artifactHeatEnv.setUniqueId(artifact.getUniqueId() + HEAT_ENV_SUFFIX);
4567 artifactHeatEnv.setGeneratedFromId(artifact.getUniqueId());
4568 artifactHeatEnv.setHeatParamsUpdateDate(System.currentTimeMillis());
4569 artifactHeatEnv.setTimeout(0);
4570 buildHeatEnvFileName(artifact, artifactHeatEnv, placeHolderData);
4571 // rbetzer - keep env artifactVersion - changeComponentInstanceVersion flow
4572 handleEnvArtifactVersion(artifactHeatEnv, existingEnvVersions);
4573 // clone heat parameters in case of heat env only not VF heat env
4574 if (envType.equals(HEAT_ENV_NAME)) {
4575 artifactHeatEnv.setHeatParameters(artifact.getHeatParameters());
4577 ArtifactDefinition artifactDefinition;
4578 // Evg : for resource instance artifact will be added later as block with other env artifacts from BL
4579 if (parentType != NodeTypeEnum.ResourceInstance) {
4580 Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact = addHeatEnvArtifact(artifactHeatEnv, artifact, component.getUniqueId(), parentType, parentId);
4581 if (addHeatEnvArtifact.isRight()) {
4582 log.debug("failed to create heat env artifact on resource instance");
4583 return Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(addHeatEnvArtifact.right().value(), false), "", null));
4585 artifactDefinition = createArtifactPlaceHolder.left().value();
4587 artifactDefinition = artifactHeatEnv;
4588 artifactToscaOperation.generateUUID(artifactDefinition, artifactDefinition.getArtifactVersion());
4591 if (artifact.getHeatParameters() != null) {
4592 List<HeatParameterDefinition> heatEnvParameters = new ArrayList<HeatParameterDefinition>();
4593 for (HeatParameterDefinition parameter : artifact.getListHeatParameters()) {
4594 HeatParameterDefinition heatEnvParameter = new HeatParameterDefinition(parameter);
4595 heatEnvParameter.setDefaultValue(parameter.getCurrentValue());
4596 heatEnvParameters.add(heatEnvParameter);
4598 artifactDefinition.setListHeatParameters(heatEnvParameters);
4602 EnumMap<AuditingFieldsKeysEnum, Object> artifactAuditingFields = createArtifactAuditingFields(artifactDefinition, "", artifactDefinition.getUniqueId());
4603 artifactAuditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, parentName);
4604 ComponentTypeEnum componentType = component.getComponentType();
4605 if (parentType == NodeTypeEnum.ResourceInstance) {
4606 componentType = ComponentTypeEnum.RESOURCE_INSTANCE;
4608 componentsUtils.auditComponent(componentsUtils.getResponseFormat(ActionStatus.OK), user, component, "", "", AuditingActionEnum.ARTIFACT_UPLOAD, componentType, artifactAuditingFields);
4609 return Either.left(artifactDefinition);
4612 private void buildHeatEnvFileName(ArtifactDefinition heatArtifact, ArtifactDefinition heatEnvArtifact, Map<String, Object> placeHolderData) {
4613 String heatExtension = GeneralUtility.getFilenameExtension(heatArtifact.getArtifactName());
4614 String envExtension = (String) placeHolderData.get(ARTIFACT_PLACEHOLDER_FILE_EXTENSION);
4615 String name = heatArtifact.getArtifactName();
4618 name = heatArtifact.getArtifactLabel();
4619 fileName = name + "." + envExtension;
4621 fileName = name.replaceAll("." + heatExtension, "." + envExtension);
4623 heatEnvArtifact.setArtifactName(fileName);
4626 private void handleEnvArtifactVersion(ArtifactDefinition heatEnvArtifact, Map<String, String> existingEnvVersions) {
4627 if (null != existingEnvVersions) {
4628 String prevVersion = existingEnvVersions.get(heatEnvArtifact.getArtifactName());
4629 if (null != prevVersion) {
4630 heatEnvArtifact.setArtifactVersion(prevVersion);
4636 * Handles Artifacts Request For Inner Component
4638 * @param artifactsToHandle
4641 * @param vfcsNewCreatedArtifacts
4644 * @param inTransaction
4647 public Either<List<ArtifactDefinition>, ResponseFormat> handleArtifactsRequestForInnerVfcComponent(List<ArtifactDefinition> artifactsToHandle, Resource component, User user, List<ArtifactDefinition> vfcsNewCreatedArtifacts,
4648 ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) {
4650 Either<List<ArtifactDefinition>, ResponseFormat> handleArtifactsResult = null;
4651 ComponentTypeEnum componentType = component.getComponentType();
4652 List<ArtifactDefinition> uploadedArtifacts = new ArrayList<>();
4653 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4654 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult;
4658 for (ArtifactDefinition artifact : artifactsToHandle) {
4659 originData = buildJsonStringForCsarVfcArtifact(artifact);
4660 origMd5 = GeneralUtility.calculateMD5ByString(originData);
4661 actionResult = handleArtifactRequest(component.getUniqueId(), user.getUserId(), componentType, operation, artifact.getUniqueId(), artifact, origMd5, originData, null, null, null, null, shouldLock, inTransaction);
4662 if (actionResult.isRight()) {
4663 log.debug("Failed to upload artifact to component with type {} and name {}. Status is {}. ", componentType, component.getName(), actionResult.right().value());
4664 errorWrapper.setInnerElement(actionResult.right().value());
4665 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create) {
4666 vfcsNewCreatedArtifacts.addAll(uploadedArtifacts);
4670 uploadedArtifacts.add(actionResult.left().value().left().value());
4672 if (errorWrapper.isEmpty()) {
4673 handleArtifactsResult = Either.left(uploadedArtifacts);
4675 handleArtifactsResult = Either.right(errorWrapper.getInnerElement());
4677 } catch (Exception e) {
4678 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
4679 handleArtifactsResult = Either.right(responseFormat);
4680 log.debug("Exception occured when handleArtifactsRequestForInnerVfcComponent, error is:{}", e.getMessage(), e);
4682 return handleArtifactsResult;
4685 private ComponentInstance getRelatedComponentInstance(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
4686 ComponentInstance componentInstance = null;
4687 String normalizedName = ValidationUtils.normalizeComponentInstanceName(resourceInstanceName);
4688 Component component = getComponentByUuid(componentType, componentUuid, errorWrapper);
4689 if (errorWrapper.isEmpty()) {
4690 componentInstance = component.getComponentInstances().stream().filter(ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName()).equals(normalizedName)).findFirst().orElse(null);
4691 if (componentInstance == null) {
4692 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, "resource instance", component.getComponentType().getValue(), component.getName()));
4693 log.debug("Component instance {} was not found for component {}", resourceInstanceName, component.getName());
4696 return componentInstance;
4699 private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(Component component, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
4701 ImmutablePair<Component, ComponentInstance> relatedComponentComponentInstancePair = null;
4702 String normalizedName = ValidationUtils.normalizeComponentInstanceName(resourceInstanceName);
4703 ComponentInstance componentInstance = component.getComponentInstances().stream().filter(ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName()).equals(normalizedName)).findFirst().orElse(null);
4704 if (componentInstance == null) {
4705 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, "resource instance", component.getComponentType().getValue(), component.getName()));
4706 log.debug("Component instance {} was not found for component {}", resourceInstanceName, component.getName());
4708 relatedComponentComponentInstancePair = new ImmutablePair<>(component, componentInstance);
4710 return relatedComponentComponentInstancePair;
4713 private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
4714 ComponentInstance componentInstance;
4715 ImmutablePair<Component, ComponentInstance> relatedComponentComponentInstancePair = null;
4716 Component component = getLatestComponentByUuid(componentType, componentUuid, errorWrapper);
4717 if (errorWrapper.isEmpty()) {
4718 componentInstance = component.getComponentInstances().stream().filter(ci -> ci.getNormalizedName().equals(resourceInstanceName)).findFirst().orElse(null);
4719 if (componentInstance == null) {
4720 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, "resource instance", component.getComponentType().getValue(), component.getName()));
4721 log.debug("Component instance {} was not found for component {}", resourceInstanceName, component.getName());
4723 relatedComponentComponentInstancePair = new ImmutablePair<>(component, componentInstance);
4726 return relatedComponentComponentInstancePair;
4729 private byte[] downloadArtifact(Map<String, ArtifactDefinition> artifacts, String artifactUUID, Wrapper<ResponseFormat> errorWrapper, String componentName) {
4731 byte[] downloadedArtifact = null;
4732 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = null;
4733 List<ArtifactDefinition> deploymentArtifacts = null;
4734 ArtifactDefinition deploymentArtifact = null;
4735 if (artifacts != null && !artifacts.isEmpty()) {
4736 deploymentArtifacts = artifacts.values().stream().filter(art -> art.getArtifactUUID() != null && art.getArtifactUUID().equals(artifactUUID)).collect(Collectors.toList());
4738 if (deploymentArtifacts == null || deploymentArtifacts.isEmpty()) {
4739 log.debug("Deployment artifact with uuid {} was not found for component {}", artifactUUID, componentName);
4740 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactUUID));
4742 if (errorWrapper.isEmpty()) {
4743 deploymentArtifact = deploymentArtifacts.get(0);
4744 downloadArtifactEither = downloadArtifact(deploymentArtifact);
4745 if (downloadArtifactEither.isRight()) {
4746 log.debug("Failed to download artifact {}. ", deploymentArtifact.getArtifactName());
4747 errorWrapper.setInnerElement(downloadArtifactEither.right().value());
4750 if (errorWrapper.isEmpty()) {
4751 log.trace("Succeeded to download artifact with uniqueId {}", deploymentArtifact.getUniqueId());
4752 downloadedArtifact = downloadArtifactEither.left().value().getRight();
4754 return downloadedArtifact;
4757 private Component getLatestComponentByUuid(ComponentTypeEnum componentType, String componentUuid, Wrapper<ResponseFormat> errorWrapper) {
4758 Component component = null;
4759 Either<Component, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentByUuid(componentUuid);
4760 if (getComponentRes.isRight()) {
4761 StorageOperationStatus status = getComponentRes.right().value();
4762 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4763 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4765 component = getComponentRes.left().value();
4770 private Component getComponentByUuid(ComponentTypeEnum componentType, String componentUuid, Wrapper<ResponseFormat> errorWrapper) {
4771 Component component = null;
4772 Either<List<Component>, StorageOperationStatus> getComponentRes = toscaOperationFacade.getComponentListByUuid(componentUuid, null);
4773 if (getComponentRes.isRight()) {
4774 StorageOperationStatus status = getComponentRes.right().value();
4775 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4776 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4778 List<Component> value = getComponentRes.left().value();
4779 if (value.isEmpty()){
4780 log.debug("Could not fetch component with type {} and uuid {}.", componentType, componentUuid);
4781 ActionStatus status = componentType == ComponentTypeEnum.RESOURCE ? ActionStatus.RESOURCE_NOT_FOUND : ActionStatus.SERVICE_NOT_FOUND;
4782 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(status));
4784 component = value.get(0);
4790 private String getLatestParentArtifactDataIdByArtifactUUID(String artifactUUID, Wrapper<ResponseFormat> errorWrapper, String parentId, ComponentTypeEnum componentType) {
4791 String artifactId = null;
4792 ActionStatus actionStatus = ActionStatus.ARTIFACT_NOT_FOUND;
4793 StorageOperationStatus storageStatus;
4794 ArtifactDefinition latestArtifact = null;
4795 List<ArtifactDefinition> artifacts = null;
4796 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifactsRes = artifactToscaOperation.getArtifacts(parentId);
4797 if (getArtifactsRes.isRight()) {
4798 storageStatus = getArtifactsRes.right().value();
4799 log.debug("Couldn't fetch artifacts data for parent component {} with uid {}, error: {}", componentType.name(), parentId, storageStatus);
4800 if (!storageStatus.equals(StorageOperationStatus.NOT_FOUND)) {
4801 actionStatus = componentsUtils.convertFromStorageResponse(storageStatus);
4803 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
4805 if (errorWrapper.isEmpty()) {
4806 artifacts = getArtifactsRes.left().value().values().stream().filter(a -> a.getArtifactUUID() != null && a.getArtifactUUID().equals(artifactUUID)).collect(Collectors.toList());
4807 if (artifacts == null || artifacts.isEmpty()) {
4808 log.debug("Couldn't fetch artifact with UUID {} data for parent component {} with uid {}, error: {}", artifactUUID, componentType.name(), parentId, actionStatus);
4809 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
4812 if (errorWrapper.isEmpty()) {
4813 latestArtifact = artifacts.stream().max((a1, a2) -> {
4814 int compareRes = Double.compare(Double.parseDouble(a1.getArtifactVersion()), Double.parseDouble(a2.getArtifactVersion()));
4815 if (compareRes == 0) {
4816 compareRes = Long.compare(a1.getLastUpdateDate() == null ? 0 : a1.getLastUpdateDate(), a2.getLastUpdateDate() == null ? 0 : a2.getLastUpdateDate());
4820 if (latestArtifact == null) {
4821 log.debug("Couldn't fetch latest artifact with UUID {} data for parent component {} with uid {}, error: {}", artifactUUID, componentType.name(), parentId, actionStatus);
4822 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
4825 if (errorWrapper.isEmpty()) {
4826 artifactId = latestArtifact.getUniqueId();
4831 private Component checkoutParentComponent(ComponentTypeEnum componentType, String parentId, String userId, Wrapper<ResponseFormat> errorWrapper) {
4833 Component component = null;
4834 Either<User, ActionStatus> getUserRes = userBusinessLogic.getUser(userId, false);
4835 if (getUserRes.isRight()) {
4836 log.debug("Could not fetch User of component {} with uid {} to checked out. Status is {}. ", componentType.getNodeType(), parentId, getUserRes.right().value());
4837 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(getUserRes.right().value()));
4839 if (errorWrapper.isEmpty()) {
4840 User modifier = getUserRes.left().value();
4841 LifecycleChangeInfoWithAction changeInfo = new LifecycleChangeInfoWithAction("External API checkout", LifecycleChanceActionEnum.UPDATE_FROM_EXTERNAL_API);
4842 Either<? extends Component, ResponseFormat> checkoutRes = lifecycleBusinessLogic.changeComponentState(componentType, parentId, modifier, LifeCycleTransitionEnum.CHECKOUT, changeInfo, false, true);
4843 if (checkoutRes.isRight()) {
4844 log.debug("Could not change state of component {} with uid {} to checked out. Status is {}. ", componentType.getNodeType(), parentId, checkoutRes.right().value().getStatus());
4845 errorWrapper.setInnerElement(checkoutRes.right().value());
4847 component = checkoutRes.left().value();
4853 private void updateAuditParametersWithArtifactDefinition(Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactDefinition artifact) {
4854 if (artifact == null) {
4855 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, "");
4856 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, "");
4857 if (!additionalParams.containsKey(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID)) {
4858 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, "");
4861 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifact.getArtifactUUID());
4862 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, buildAuditingArtifactData(artifact));
4863 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, artifact.getUpdaterFullName());
4867 private String buildJsonStringForCsarVfcArtifact(ArtifactDefinition artifact) {
4868 Map<String, Object> json = new HashMap<>();
4869 String artifactName = artifact.getArtifactName();
4870 json.put(Constants.ARTIFACT_NAME, artifactName);
4871 json.put(Constants.ARTIFACT_LABEL, artifact.getArtifactLabel());
4872 json.put(Constants.ARTIFACT_TYPE, artifact.getArtifactType());
4873 json.put(Constants.ARTIFACT_GROUP_TYPE, ArtifactGroupTypeEnum.DEPLOYMENT.getType());
4874 json.put(Constants.ARTIFACT_DESCRIPTION, artifact.getDescription());
4875 json.put(Constants.ARTIFACT_PAYLOAD_DATA, artifact.getPayloadData());
4876 json.put(Constants.ARTIFACT_DISPLAY_NAME, artifact.getArtifactDisplayName());
4877 return gson.toJson(json);