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 log.trace("Start generating payload for {} artifact {}", artifactDefinition.getArtifactType(), artifactDefinition.getEsId());
3604 if (artifactDefinition.getPayloadUpdateDate() == null || artifactDefinition.getPayloadUpdateDate() == 0 || artifactDefinition.getPayloadUpdateDate() <= payloadUpdateDateGen.get()) {
3606 log.trace("Generating payload for {} artifact {}", artifactDefinition.getArtifactType(), artifactDefinition.getEsId());
3607 Either<ESArtifactData, ResponseFormat> artifactDataRes = esDataCreator.get();
3608 ESArtifactData artifactData = null;
3610 if (artifactDataRes.isLeft()) {
3611 artifactData = artifactDataRes.left().value();
3613 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
3614 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
3615 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
3617 return Either.right(artifactDataRes.right().value());
3619 String newCheckSum = GeneralUtility.calculateMD5ByByteArray(artifactData.getDataAsArray());
3621 String esArtifactId = artifactDefinition.getEsId();
3622 Either<ESArtifactData, CassandraOperationStatus> artifactfromES;
3623 ESArtifactData esArtifactData;
3624 if (esArtifactId != null && !esArtifactId.isEmpty() && artifactDefinition.getPayloadData() == null) {
3625 artifactfromES = artifactCassandraDao.getArtifact(esArtifactId);
3626 if (artifactfromES.isRight()) {
3627 CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value();
3628 StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
3629 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
3630 log.debug("Error when getting artifact from ES, error: {}", actionStatus.name());
3631 return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, artifactDefinition.getArtifactDisplayName()));
3633 esArtifactData = artifactfromES.left().value();
3634 oldCheckSum = GeneralUtility.calculateMD5ByByteArray(esArtifactData.getDataAsArray());
3636 oldCheckSum = artifactDefinition.getArtifactChecksum();
3639 Either<ArtifactDefinition, StorageOperationStatus> updateArifactDefinitionStatus = null;
3642 Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, "Update Artifact - lock resource: ");
3643 if (lockComponent.isRight()) {
3644 handleAuditing(AuditingActionEnum.ARTIFACT_METADATA_UPDATE, component, component.getUniqueId(), modifier, null, null, artifactDefinition.getUniqueId(), lockComponent.right().value(), component.getComponentType(), null);
3645 return Either.right(lockComponent.right().value());
3649 if (oldCheckSum != null && oldCheckSum.equals(newCheckSum)) {
3651 artifactDefinition.setPayloadUpdateDate(payloadUpdateDateGen.get());
3652 updateArifactDefinitionStatus = artifactToscaOperation.updateArifactOnResource(artifactDefinition, component.getUniqueId(), artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId);
3653 log.trace("No real update done in payload for {} artifact, updating payloadUpdateDate {}", artifactDefinition.getArtifactType(), artifactDefinition.getEsId());
3654 if (updateArifactDefinitionStatus.isRight()) {
3655 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus.right().value()), artifactDefinition.getArtifactDisplayName());
3656 log.trace("Failed to update payloadUpdateDate {}", artifactDefinition.getEsId());
3657 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
3658 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
3660 return Either.right(responseFormat);
3664 oldCheckSum = artifactDefinition.getArtifactChecksum();
3665 artifactDefinition.setArtifactChecksum(newCheckSum);
3666 // artifactToscaOperation.updateUUID(artifactDefinition, oldCheckSum, artifactDefinition.getArtifactVersion());
3667 artifactDefinition.setEsId(artifactDefinition.getUniqueId());
3668 log.trace("No real update done in payload for {} artifact, updating payloadUpdateDate {}", artifactDefinition.getArtifactType(), artifactDefinition.getEsId());
3669 updateArifactDefinitionStatus = artifactToscaOperation.updateArifactOnResource(artifactDefinition, component.getUniqueId(), artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId);
3671 log.trace("Update Payload ", artifactDefinition.getEsId());
3673 if (updateArifactDefinitionStatus != null && updateArifactDefinitionStatus.isLeft()) {
3675 artifactDefinition = updateArifactDefinitionStatus.left().value();
3676 artifactData.setId(artifactDefinition.getUniqueId());
3677 CassandraOperationStatus saveArtifactStatus = artifactCassandraDao.saveArtifact(artifactData);
3679 if (saveArtifactStatus.equals(CassandraOperationStatus.OK)) {
3681 log.debug("Artifact Saved In ES {}", artifactData.getId());
3682 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
3683 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
3684 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
3687 titanDao.rollback();
3688 log.info("Failed to save artifact {}.", artifactData.getId());
3689 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
3690 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
3691 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
3693 return Either.right(responseFormat);
3696 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus.right().value()), artifactDefinition.getArtifactDisplayName());
3697 log.debug("Failed To update artifact {}", artifactData.getId());
3698 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
3699 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
3701 return Either.right(responseFormat);
3706 graphLockOperation.unlockComponent(component.getUniqueId(), component.getComponentType().getNodeType());
3711 return Either.left(artifactDefinition);
3714 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdateHeatEnv(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType,
3715 org.openecomp.sdc.be.model.Component parent, String originData, String origMd5, ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) {
3716 convertParentType(componentType);
3717 String parentId = parent.getUniqueId();
3718 // Either<ArtifactDefinition, StorageOperationStatus> artifactRes = this.artifactToscaOperation.getArtifactById(componentId, artifactId);
3719 ArtifactDefinition currArtifact = artifactInfo;
3721 if (origMd5 != null) {
3722 Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
3723 if (validateMd5.isRight()) {
3724 ResponseFormat responseFormat = validateMd5.right().value();
3725 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
3726 return Either.right(responseFormat);
3729 if (artifactInfo.getPayloadData() != null && artifactInfo.getPayloadData().length != 0) {
3730 Either<Boolean, ResponseFormat> deploymentValidationResult = validateDeploymentArtifact(parent, componentId, user.getUserId(), false, artifactInfo, currArtifact, NodeTypeEnum.ResourceInstance);
3731 if (deploymentValidationResult.isRight()) {
3732 ResponseFormat responseFormat = deploymentValidationResult.right().value();
3733 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
3734 return Either.right(responseFormat);
3737 Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
3738 if (payloadEither.isRight()) {
3739 ResponseFormat responseFormat = payloadEither.right().value();
3740 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
3741 return Either.right(responseFormat);
3743 } else { // duplicate
3744 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
3745 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
3746 return Either.right(responseFormat);
3752 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Update Artifact - lock ");
3753 if (lockComponent.isRight()) {
3754 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right().value(), componentType, null);
3755 return Either.right(lockComponent.right().value());
3758 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
3760 resultOp = updateHeatEnvParams(componentId, artifactId, artifactInfo, user, auditingAction, parent, componentType, currArtifact, origMd5, inTransaction);
3765 if (resultOp == null || resultOp.isRight()) {
3766 log.debug("all changes rollback");
3767 if (false == inTransaction)
3768 titanDao.rollback();
3770 log.debug("all changes committed");
3771 if (false == inTransaction)
3775 componentType = parent.getComponentType();
3776 NodeTypeEnum nodeType = componentType.getNodeType();
3777 graphLockOperation.unlockComponent(parent.getUniqueId(), nodeType);
3778 // graphLockOperation.unlockComponent(parentId, parentType);
3782 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateHeatEnvParams(String componentId, String artifactId, ArtifactDefinition artifactInfo, User user, AuditingActionEnum auditingAction, Component parent,
3783 ComponentTypeEnum componentType, ArtifactDefinition currArtifact1, String origMd5, boolean inTransaction) {
3785 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
3786 Either<ArtifactDefinition, Operation> insideEither = null;
3788 * currently getArtifactById does not retrieve heatParameters Either<ArtifactDefinition, StorageOperationStatus> artifactRes = artifactOperation.getArtifactById(artifactId, false); ArtifactDefinition currArtifact = artifactRes.left().value();
3790 Either<ComponentInstance, ResponseFormat> getRI = getRIFromComponent(parent, componentId, artifactId, auditingAction, user);
3791 if (getRI.isRight()) {
3792 return Either.right(getRI.right().value());
3794 ComponentInstance ri = getRI.left().value();
3795 Either<ArtifactDefinition, ResponseFormat> getArtifactRes = getArtifactFromRI(parent, ri, componentId, artifactId, auditingAction, user);
3796 if (getArtifactRes.isRight()) {
3797 return Either.right(getArtifactRes.right().value());
3799 ArtifactDefinition currArtifact = getArtifactRes.left().value();
3801 if (currArtifact.getArtifactType().equals(ArtifactTypeEnum.HEAT.getType()) || currArtifact.getArtifactType().equals(ArtifactTypeEnum.HEAT_VOL.getType()) || currArtifact.getArtifactType().equals(ArtifactTypeEnum.HEAT_NET.getType())) {
3802 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
3803 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
3804 return Either.right(responseFormat);
3806 List<HeatParameterDefinition> currentHeatEnvParams = currArtifact.getListHeatParameters();
3807 List<HeatParameterDefinition> updatedHeatEnvParams = artifactInfo.getListHeatParameters();
3808 new ArrayList<HeatParameterDefinition>();
3811 if (origMd5 != null) {
3812 Either<List<HeatParameterDefinition>, ResponseFormat> uploadParamsValidationResult = validateUploadParamsFromEnvFile(auditingAction, parent, user, artifactInfo, artifactId, componentType, ri.getName(), currentHeatEnvParams,
3813 updatedHeatEnvParams, currArtifact.getArtifactName());
3814 if (uploadParamsValidationResult.isRight()) {
3815 ResponseFormat responseFormat = uploadParamsValidationResult.right().value();
3816 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
3817 return Either.right(responseFormat);
3819 artifactInfo.setListHeatParameters(updatedHeatEnvParams);
3822 Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers = validateAndConvertHeatParamers(artifactInfo, ArtifactTypeEnum.HEAT_ENV.getType());
3823 if (validateAndConvertHeatParamers.isRight()) {
3824 ResponseFormat responseFormat = validateAndConvertHeatParamers.right().value();
3825 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
3826 return Either.right(responseFormat);
3829 if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty()) {
3831 // fill reduced heat env parameters List for updating
3832 for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) {
3833 paramName = heatEnvParam.getName();
3834 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
3835 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
3836 String updatedParamValue = heatEnvParam.getCurrentValue();
3837 if (updatedParamValue != null && updatedParamValue.equals("")) { // reset
3838 currHeatParam.setCurrentValue(heatEnvParam.getDefaultValue());
3839 } else if (updatedParamValue != null) {
3840 currHeatParam.setCurrentValue(updatedParamValue);
3845 currArtifact.setHeatParamsUpdateDate(System.currentTimeMillis());
3846 currArtifact.setListHeatParameters(currentHeatEnvParams);
3848 Either<ArtifactDefinition, StorageOperationStatus> updateArifactRes = artifactToscaOperation.updateArifactOnResource(currArtifact, parent.getUniqueId(), currArtifact.getUniqueId(), componentType.getNodeType(), componentId);
3849 if (updateArifactRes.isRight()) {
3850 log.debug("Failed to update artifact on graph - {}", artifactId);
3851 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateArifactRes.right().value()));
3852 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
3853 return Either.right(responseFormat);
3855 StorageOperationStatus error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), ri.getUniqueId(), componentType);
3856 if (error != StorageOperationStatus.OK) {
3857 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
3858 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
3859 return Either.right(responseFormat);
3862 error = generateCustomizationUUIDOnGroupInstance(ri, updateArifactRes.left().value().getUniqueId(), parent.getUniqueId());
3863 if (error != StorageOperationStatus.OK) {
3864 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
3865 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
3866 return Either.right(responseFormat);
3872 insideEither = Either.left(currArtifact);
3873 resultOp = Either.left(insideEither);
3874 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
3875 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currArtifact, null, artifactId, responseFormat, componentType, ri.getName());
3879 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateHeatParams(String componentId, String artifactId, ArtifactDefinition artifactEnvInfo, User user, AuditingActionEnum auditingAction, Component parent,
3880 ComponentTypeEnum componentType, ArtifactDefinition currHeatArtifact, String origMd5, boolean needToUpdateGroup) {
3882 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
3883 Either<ArtifactDefinition, Operation> insideEither = null;
3885 * currently getArtifactById does not retrieve heatParameters Either<ArtifactDefinition, StorageOperationStatus> artifactRes = artifactOperation.getArtifactById(artifactId, false); ArtifactDefinition currArtifact = artifactRes.left().value();
3887 String currentHeatId = currHeatArtifact.getUniqueId();
3889 String esArtifactId = currHeatArtifact.getEsId();
3890 Either<ESArtifactData, CassandraOperationStatus> artifactfromES = artifactCassandraDao.getArtifact(esArtifactId);
3891 if (artifactfromES.isRight()) {
3892 CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value();
3893 StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
3894 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
3895 log.debug("Error when getting artifact from ES, error: {}", actionStatus.name());
3896 return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, currHeatArtifact.getArtifactDisplayName()));
3899 ESArtifactData esArtifactData = artifactfromES.left().value();
3900 byte[] data = esArtifactData.getDataAsArray();
3903 ArtifactDefinition updatedHeatArt = currHeatArtifact;
3905 List<HeatParameterDefinition> updatedHeatEnvParams = artifactEnvInfo.getListHeatParameters();
3906 List<HeatParameterDefinition> currentHeatEnvParams = currHeatArtifact.getListHeatParameters();
3907 List<HeatParameterDefinition> newHeatEnvParams = new ArrayList<HeatParameterDefinition>();
3909 if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty() && currentHeatEnvParams != null && !currentHeatEnvParams.isEmpty()) {
3912 for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) {
3914 paramName = heatEnvParam.getName();
3915 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
3916 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
3918 String updatedParamValue = heatEnvParam.getCurrentValue();
3919 if (updatedParamValue == null)
3920 updatedParamValue = heatEnvParam.getDefaultValue();
3921 HeatParameterType paramType = HeatParameterType.isValidType(currHeatParam.getType());
3922 if (!paramType.getValidator().isValid(updatedParamValue, null)) {
3923 ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE;
3924 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, ArtifactTypeEnum.HEAT_ENV.getType(), paramType.getType(), paramName);
3925 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactEnvInfo, null, artifactId, responseFormat, componentType, "");
3926 return Either.right(responseFormat);
3929 currHeatParam.setCurrentValue(paramType.getConverter().convert(updatedParamValue, null, null));
3930 newHeatEnvParams.add(currHeatParam);
3935 if (!newHeatEnvParams.isEmpty()) {
3936 currHeatArtifact.setListHeatParameters(currentHeatEnvParams);
3937 Either<ArtifactDefinition, StorageOperationStatus> operationStatus = artifactToscaOperation.updateArifactOnResource(currHeatArtifact, parent.getUniqueId(), currHeatArtifact.getUniqueId(), componentType.getNodeType(), componentId);
3939 if (operationStatus.isRight()) {
3940 log.debug("Failed to update artifact on graph - {}", currHeatArtifact.getUniqueId());
3942 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(operationStatus.right().value()));
3943 return Either.right(responseFormat);
3946 updatedHeatArt = operationStatus.left().value();
3948 if (!updatedHeatArt.getDuplicated() || esArtifactData.getId() == null)
3949 esArtifactData.setId(updatedHeatArt.getEsId());
3950 res = saveArtifacts(esArtifactData, parent.getUniqueId(), false);
3953 log.debug("Artifact saved into ES - {}", updatedHeatArt.getUniqueId());
3954 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
3955 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, updatedHeatArt, currentHeatId, updatedHeatArt.getUniqueId(), responseFormat, componentType, null);
3956 // resultOp = Either.left(result.left().value());
3959 BeEcompErrorManager.getInstance().logBeDaoSystemError("Update Artifact");
3960 log.debug("Failed to save the artifact.");
3961 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
3962 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, updatedHeatArt, currentHeatId, updatedHeatArt.getUniqueId(), responseFormat, componentType, null);
3963 resultOp = Either.right(responseFormat);
3967 insideEither = Either.left(updatedHeatArt);
3970 Either<ArtifactDefinition, StorageOperationStatus> updateHeatEnvArtifact;
3971 if (!currentHeatId.equals(updatedHeatArt.getUniqueId())) {
3972 artifactEnvInfo.setArtifactChecksum(null);
3973 updateHeatEnvArtifact = artifactToscaOperation.updateHeatEnvArtifact(parent.getUniqueId(), artifactEnvInfo, currentHeatId, updatedHeatArt.getUniqueId(), componentType.getNodeType(), componentId);
3975 updateHeatEnvArtifact = artifactToscaOperation.updateHeatEnvPlaceholder(artifactEnvInfo, componentId, componentType.getNodeType());
3978 if ( needToUpdateGroup && updateHeatEnvArtifact.isLeft() ){
3979 ActionStatus result = updateGroupForHeat(currHeatArtifact, updatedHeatArt, artifactEnvInfo, updateHeatEnvArtifact.left().value(), parent, componentType);
3980 if ( result != ActionStatus.OK ){
3981 ResponseFormat responseFormat = componentsUtils.getResponseFormat(result);
3982 return Either.right(responseFormat);
3985 resultOp = Either.left(insideEither);
3986 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
3987 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currHeatArtifact, null, artifactId, responseFormat, componentType, "");
3992 private StorageOperationStatus generateCustomizationUUIDOnGroupInstance(ComponentInstance ri, String artifactId, String componentId) {
3993 StorageOperationStatus error = StorageOperationStatus.OK;
3994 log.debug("Need to re-generate customization UUID for group instance on component instance {}", ri.getUniqueId());
3995 List<GroupInstance> groupsInstances = ri.getGroupInstances();
3996 // List<GroupInstance> associatedGroups = null;
3997 List<String> groupInstancesId = null;
3998 if (groupsInstances != null && !groupsInstances.isEmpty()) {
3999 groupInstancesId = groupsInstances.stream().filter(p -> p.getGroupInstanceArtifacts() != null && p.getGroupInstanceArtifacts().contains(artifactId)).map(p -> p.getUniqueId()).collect(Collectors.toList());
4001 if (groupInstancesId != null && !groupInstancesId.isEmpty()) {
4002 // associatedGroups.stream().forEach(c -> this.groupInstanceOperation.updateCustomizationUUID(c.getUniqueId()));
4003 toscaOperationFacade.generateCustomizationUUIDOnInstanceGroup(componentId, ri.getUniqueId(), groupInstancesId);
4009 public Either<List<HeatParameterDefinition>, ResponseFormat> validateUploadParamsFromEnvFile(AuditingActionEnum auditingAction, Component parent, User user, ArtifactDefinition artifactInfo, String artifactId, ComponentTypeEnum componentType,
4010 String riName, List<HeatParameterDefinition> currentHeatEnvParams, List<HeatParameterDefinition> updatedHeatEnvParams, String currArtifactName) {
4012 if (updatedHeatEnvParams == null || updatedHeatEnvParams.isEmpty()) {
4013 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactInfo.getArtifactName(), currArtifactName);
4014 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, riName);
4015 return Either.right(responseFormat);
4018 for (HeatParameterDefinition uploadedHeatParam : updatedHeatEnvParams) {
4019 String paramName = uploadedHeatParam.getName();
4020 boolean isExistsInHeat = false;
4021 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
4022 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
4024 isExistsInHeat = true;
4025 uploadedHeatParam.setType(currHeatParam.getType());
4026 uploadedHeatParam.setCurrentValue(uploadedHeatParam.getDefaultValue());
4027 uploadedHeatParam.setDefaultValue(currHeatParam.getDefaultValue());
4028 uploadedHeatParam.setUniqueId(currHeatParam.getUniqueId());
4032 if (!isExistsInHeat) {
4033 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, currArtifactName);
4034 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, riName);
4035 return Either.right(responseFormat);
4038 return Either.left(updatedHeatEnvParams);
4041 private Either<ComponentInstance, ResponseFormat> getRIFromComponent(Component component, String riID, String artifactId, AuditingActionEnum auditingAction, User user) {
4042 ResponseFormat responseFormat = null;
4043 List<ComponentInstance> ris = component.getComponentInstances();
4044 for (ComponentInstance ri : ris) {
4045 if (riID.equals(ri.getUniqueId())) {
4046 return Either.left(ri);
4049 responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, riID);
4050 log.debug("Resource Instance not found, resourceInstanceId {}", riID);
4051 handleAuditing(auditingAction, null, riID, user, null, null, artifactId, responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE, null);
4052 return Either.right(responseFormat);
4055 private Either<ArtifactDefinition, ResponseFormat> getArtifactFromRI(Component component, ComponentInstance ri, String riID, String artifactId, AuditingActionEnum auditingAction, User user) {
4056 ResponseFormat responseFormat = null;
4057 Map<String, ArtifactDefinition> rtifactsMap = ri.getDeploymentArtifacts();
4058 for (ArtifactDefinition artifact : rtifactsMap.values()) {
4059 if (artifactId.equals(artifact.getUniqueId())) {
4060 return Either.left(artifact);
4063 responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, riID, component.getUniqueId());
4064 handleAuditing(auditingAction, component, riID, user, null, null, artifactId, responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE, ri.getName());
4065 return Either.right(responseFormat);
4068 public ArtifactDefinition extractArtifactDefinition(Either<ArtifactDefinition, Operation> eitherArtifact) {
4069 ArtifactDefinition ret;
4070 if (eitherArtifact.isLeft()) {
4071 ret = eitherArtifact.left().value();
4073 ret = eitherArtifact.right().value().getImplementationArtifact();
4079 * downloads artifact of component by UUIDs
4081 * @param componentType
4082 * @param componentUuid
4083 * @param artifactUUID
4084 * @param auditAdditionalParam
4087 public Either<byte[], ResponseFormat> downloadComponentArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String artifactUUID, Map<AuditingFieldsKeysEnum, Object> auditAdditionalParam) {
4088 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4089 Either<byte[], ResponseFormat> result;
4090 byte[] downloadedArtifact = null;
4091 Component component = getComponentByUuid(componentType, componentUuid, errorWrapper);
4092 if (errorWrapper.isEmpty()) {
4093 auditAdditionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, component.getName());
4094 downloadedArtifact = downloadArtifact(component.getDeploymentArtifacts(), artifactUUID, errorWrapper, component.getName());
4096 if (errorWrapper.isEmpty()) {
4097 result = Either.left(downloadedArtifact);
4099 result = Either.right(errorWrapper.getInnerElement());
4105 * downloads an artifact of resource instance of component by UUIDs
4107 * @param componentType
4108 * @param componentUuid
4109 * @param resourceName
4110 * @param artifactUUID
4111 * @param auditAdditionalParam
4114 public Either<byte[], ResponseFormat> downloadResourceInstanceArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID, Map<AuditingFieldsKeysEnum, Object> auditAdditionalParam) {
4115 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4116 Either<byte[], ResponseFormat> result;
4117 byte[] downloadedArtifact = null;
4118 ComponentInstance resourceInstance = getRelatedComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
4119 if (errorWrapper.isEmpty()) {
4120 downloadedArtifact = downloadArtifact(resourceInstance.getDeploymentArtifacts(), artifactUUID, errorWrapper, resourceInstance.getName());
4122 if (errorWrapper.isEmpty()) {
4123 result = Either.left(downloadedArtifact);
4125 result = Either.right(errorWrapper.getInnerElement());
4131 * uploads an artifact to a component by UUID
4135 * @param componentType
4136 * @param componentUuid
4137 * @param additionalParams
4141 public Either<ArtifactDefinition, ResponseFormat> uploadArtifactToComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, Map<AuditingFieldsKeysEnum, Object> additionalParams,
4142 ArtifactOperationInfo operation) {
4143 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4144 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4145 Either<ArtifactDefinition, ResponseFormat> uploadArtifactResult;
4146 ArtifactDefinition uploadArtifact = null;
4147 Component component = null;
4148 String componentId = null;
4149 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
4150 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4151 String userId = request.getHeader(Constants.USER_ID_HEADER);
4153 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4154 if (getComponentRes.isRight()) {
4155 StorageOperationStatus status = getComponentRes.right().value();
4156 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4157 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), componentUuid));
4159 if (errorWrapper.isEmpty()) {
4160 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
4161 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
4163 if (!getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4164 component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
4165 if (component != null) {
4166 componentId = component.getUniqueId();
4167 componentName = component.getName();
4170 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentName);
4172 if (errorWrapper.isEmpty()) {
4173 actionResult = handleArtifactRequest(componentId, userId, componentType, operation, null, artifactInfo, origMd5, data, null, null, null, null);
4174 if (actionResult.isRight()) {
4175 log.debug("Failed to upload artifact to component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, actionResult.right().value());
4176 errorWrapper.setInnerElement(actionResult.right().value());
4179 if (errorWrapper.isEmpty()) {
4180 uploadArtifact = actionResult.left().value().left().value();
4181 uploadArtifactResult = Either.left(uploadArtifact);
4183 uploadArtifactResult = Either.right(errorWrapper.getInnerElement());
4185 updateAuditParametersWithArtifactDefinition(additionalParams, uploadArtifact);
4186 return uploadArtifactResult;
4190 * upload an artifact to a resource instance by UUID
4194 * @param componentType
4195 * @param componentUuid
4196 * @param resourceInstanceName
4197 * @param additionalParams
4201 public Either<ArtifactDefinition, ResponseFormat> uploadArtifactToRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName,
4202 Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
4203 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4204 Either<ArtifactDefinition, ResponseFormat> uploadArtifactResult;
4205 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4206 ArtifactDefinition uploadArtifact = null;
4207 Component component = null;
4208 String componentInstanceId;
4210 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4211 String userId = request.getHeader(Constants.USER_ID_HEADER);
4213 ImmutablePair<Component, ComponentInstance> componentRiPair = null;
4214 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4215 if (getComponentRes.isRight()) {
4216 StorageOperationStatus status = getComponentRes.right().value();
4217 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4218 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), resourceInstanceName));
4220 if (errorWrapper.isEmpty() && !getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4221 component = checkoutParentComponent(componentType, getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(), userId, errorWrapper);
4223 if (errorWrapper.isEmpty()) {
4224 if (component == null) {
4225 componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
4227 componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
4230 if (errorWrapper.isEmpty()) {
4231 componentInstanceId = componentRiPair.getRight().getUniqueId();
4232 componentId = componentRiPair.getLeft().getUniqueId();
4233 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
4235 actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, null, artifactInfo, origMd5, data, null, null, componentId, ComponentTypeEnum.findParamByType(componentType));
4236 if (actionResult.isRight()) {
4237 log.debug("Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. ", resourceInstanceName, componentType, componentUuid, actionResult.right().value());
4238 errorWrapper.setInnerElement(actionResult.right().value());
4241 if (errorWrapper.isEmpty()) {
4242 uploadArtifact = actionResult.left().value().left().value();
4243 uploadArtifactResult = Either.left(uploadArtifact);
4245 uploadArtifactResult = Either.right(errorWrapper.getInnerElement());
4247 updateAuditParametersWithArtifactDefinition(additionalParams, uploadArtifact);
4248 return uploadArtifactResult;
4252 * updates an artifact on a component by UUID
4256 * @param componentType
4257 * @param componentUuid
4258 * @param artifactUUID
4259 * @param additionalParams
4264 public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID,
4265 Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
4266 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4267 Either<ArtifactDefinition, ResponseFormat> updateArtifactResult;
4268 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4269 ArtifactDefinition updateArtifact = null;
4270 Component component = null;
4271 String componentId = null;
4272 String artifactId = null;
4273 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
4274 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4275 String userId = request.getHeader(Constants.USER_ID_HEADER);
4277 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4278 if (getComponentRes.isRight()) {
4279 StorageOperationStatus status = getComponentRes.right().value();
4280 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4281 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4283 if (errorWrapper.isEmpty()) {
4284 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
4285 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
4287 if (!getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4288 component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
4289 if (component != null) {
4290 componentId = component.getUniqueId();
4291 componentName = component.getName();
4294 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentName);
4296 if (errorWrapper.isEmpty()) {
4297 artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentId, componentType);
4299 if (errorWrapper.isEmpty()) {
4300 actionResult = handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, origMd5, data, null, null, null, null);
4301 if (actionResult.isRight()) {
4302 log.debug("Failed to upload artifact to component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, actionResult.right().value());
4303 errorWrapper.setInnerElement(actionResult.right().value());
4306 if (errorWrapper.isEmpty()) {
4307 updateArtifact = actionResult.left().value().left().value();
4308 updateArtifactResult = Either.left(updateArtifact);
4311 updateArtifactResult = Either.right(errorWrapper.getInnerElement());
4313 updateAuditParametersWithArtifactDefinition(additionalParams, updateArtifact);
4314 return updateArtifactResult;
4318 * updates an artifact on a resource instance by UUID
4322 * @param componentType
4323 * @param componentUuid
4324 * @param resourceInstanceName
4325 * @param artifactUUID
4326 * @param additionalParams
4331 public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID,
4332 Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
4334 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4335 Either<ArtifactDefinition, ResponseFormat> updateArtifactResult;
4336 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4337 ArtifactDefinition updateArtifact = null;
4338 Component component = null;
4339 String componentInstanceId = null;
4340 String componentId = null;
4341 String artifactId = null;
4342 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4343 String userId = request.getHeader(Constants.USER_ID_HEADER);
4345 ImmutablePair<Component, ComponentInstance> componentRiPair = null;
4346 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4347 if (getComponentRes.isRight()) {
4348 StorageOperationStatus status = getComponentRes.right().value();
4349 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4350 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4352 if (errorWrapper.isEmpty() && !getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4353 component = checkoutParentComponent(componentType, getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(), userId, errorWrapper);
4355 if (errorWrapper.isEmpty()) {
4356 if (component == null) {
4357 componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
4359 componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
4362 if (errorWrapper.isEmpty()) {
4363 componentInstanceId = componentRiPair.getRight().getUniqueId();
4364 componentId = componentRiPair.getLeft().getUniqueId();
4365 artifactId = findArtifactId(componentRiPair.getRight(), artifactUUID, errorWrapper);
4367 if (errorWrapper.isEmpty()) {
4368 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
4370 actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, artifactInfo, origMd5, data, null, null, componentId, ComponentTypeEnum.findParamByType(componentType));
4371 if (actionResult.isRight()) {
4372 log.debug("Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. ", resourceInstanceName, componentType, componentUuid, actionResult.right().value());
4373 errorWrapper.setInnerElement(actionResult.right().value());
4376 if (errorWrapper.isEmpty()) {
4377 updateArtifact = actionResult.left().value().left().value();
4378 updateArtifactResult = Either.left(updateArtifact);
4380 updateArtifactResult = Either.right(errorWrapper.getInnerElement());
4382 updateAuditParametersWithArtifactDefinition(additionalParams, updateArtifact);
4383 return updateArtifactResult;
4387 * deletes an artifact on a component by UUID
4390 * @param componentType
4391 * @param componentUuid
4392 * @param artifactUUID
4393 * @param additionalParams
4398 public Either<ArtifactDefinition, ResponseFormat> deleteArtifactOnComponentByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID, Map<AuditingFieldsKeysEnum, Object> additionalParams,
4399 ArtifactOperationInfo operation) {
4401 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4402 Either<ArtifactDefinition, ResponseFormat> deleteArtifactResult;
4403 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4404 ArtifactDefinition deleteArtifact = null;
4405 Component component = null;
4406 String componentId = null;
4407 String artifactId = null;
4408 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4409 String userId = request.getHeader(Constants.USER_ID_HEADER);
4411 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4412 if (getComponentRes.isRight()) {
4413 StorageOperationStatus status = getComponentRes.right().value();
4414 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4415 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), componentUuid));
4417 if (errorWrapper.isEmpty()) {
4418 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
4419 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
4420 if (!getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4421 component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
4422 if (component != null) {
4423 componentId = component.getUniqueId();
4424 componentName = component.getName();
4427 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentName);
4429 if (errorWrapper.isEmpty()) {
4430 artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentId, componentType);
4432 if (errorWrapper.isEmpty()) {
4433 actionResult = handleArtifactRequest(componentId, userId, componentType, operation, artifactId, null, origMd5, null, null, null, null, null);
4434 if (actionResult.isRight()) {
4435 log.debug("Failed to upload artifact to component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, actionResult.right().value());
4436 errorWrapper.setInnerElement(actionResult.right().value());
4439 if (errorWrapper.isEmpty()) {
4440 deleteArtifact = actionResult.left().value().left().value();
4441 deleteArtifactResult = Either.left(deleteArtifact);
4443 deleteArtifactResult = Either.right(errorWrapper.getInnerElement());
4445 updateAuditParametersWithArtifactDefinition(additionalParams, deleteArtifact);
4446 return deleteArtifactResult;
4450 * deletes an artifact from a resource instance by UUID
4453 * @param componentType
4454 * @param componentUuid
4455 * @param resourceInstanceName
4456 * @param artifactUUID
4457 * @param additionalParams
4462 public Either<ArtifactDefinition, ResponseFormat> deleteArtifactOnRiByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID,
4463 Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
4465 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4466 Either<ArtifactDefinition, ResponseFormat> deleteArtifactResult;
4467 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4468 ArtifactDefinition deleteArtifact = null;
4469 Component component = null;
4470 String componentInstanceId = null;
4471 String componentId = null;
4472 String artifactId = null;
4473 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4474 String userId = request.getHeader(Constants.USER_ID_HEADER);
4475 ImmutablePair<Component, ComponentInstance> componentRiPair = null;
4476 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4477 if (getComponentRes.isRight()) {
4478 StorageOperationStatus status = getComponentRes.right().value();
4479 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4480 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4482 if (errorWrapper.isEmpty() && !getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4483 component = checkoutParentComponent(componentType, getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(), userId, errorWrapper);
4485 if (errorWrapper.isEmpty()) {
4486 if (component == null) {
4487 componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
4489 componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
4492 if (errorWrapper.isEmpty()) {
4493 componentInstanceId = componentRiPair.getRight().getUniqueId();
4494 componentId = componentRiPair.getLeft().getUniqueId();
4495 artifactId = findArtifactId(componentRiPair.getRight(), artifactUUID, errorWrapper);
4497 if (errorWrapper.isEmpty()) {
4499 actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, null, origMd5, null, null, null, componentId, ComponentTypeEnum.findParamByType(componentType));
4501 if (actionResult.isRight()) {
4502 log.debug("Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. ", resourceInstanceName, componentType, componentUuid, actionResult.right().value());
4503 errorWrapper.setInnerElement(actionResult.right().value());
4506 if (errorWrapper.isEmpty()) {
4507 deleteArtifact = actionResult.left().value().left().value();
4508 deleteArtifactResult = Either.left(deleteArtifact);
4510 deleteArtifactResult = Either.right(errorWrapper.getInnerElement());
4512 updateAuditParametersWithArtifactDefinition(additionalParams, deleteArtifact);
4513 return deleteArtifactResult;
4516 private String findArtifactId(ComponentInstance instance, String artifactUUID, Wrapper<ResponseFormat> errorWrapper) {
4517 String artifactId = null;
4518 ArtifactDefinition foundArtifact = null;
4519 if (instance.getDeploymentArtifacts() != null) {
4520 foundArtifact = instance.getDeploymentArtifacts().values().stream().filter(e -> e.getArtifactUUID() != null && e.getArtifactUUID().equals(artifactUUID)).findFirst().orElse(null);
4522 if (foundArtifact == null && instance.getArtifacts() != null) {
4523 foundArtifact = instance.getArtifacts().values().stream().filter(e -> e.getArtifactUUID() != null && e.getArtifactUUID().equals(artifactUUID)).findFirst().orElse(null);
4525 if (foundArtifact == null) {
4526 log.debug("The artifact {} was not found on instance {}. ", artifactUUID, instance.getUniqueId());
4527 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactUUID));
4529 artifactId = foundArtifact.getUniqueId();
4534 public Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder(ArtifactDefinition artifact, String envType, String parentId, NodeTypeEnum parentType, String parentName, User user, Component component,
4535 Map<String, String> existingEnvVersions) {
4536 return createHeatEnvPlaceHolder(artifact, envType, parentId, parentType, parentName, user, component, existingEnvVersions, true);
4540 @SuppressWarnings("unchecked")
4541 public Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder(ArtifactDefinition artifact, String envType, String parentId, NodeTypeEnum parentType, String parentName, User user, Component component,
4542 Map<String, String> existingEnvVersions, boolean overrideId) {
4543 Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getDeploymentResourceInstanceArtifacts();
4544 if (deploymentResourceArtifacts == null) {
4545 log.debug("no deployment artifacts are configured for generated artifacts");
4546 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
4548 Map<String, Object> placeHolderData = (Map<String, Object>) deploymentResourceArtifacts.get(envType);
4549 if (placeHolderData == null) {
4550 log.debug("no env type {} are configured for generated artifacts", envType);
4551 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
4554 String envLabel = (artifact.getArtifactLabel() + HEAT_ENV_SUFFIX).toLowerCase();
4555 String parentIdParam = parentId;
4557 parentIdParam = null;
4559 Either<ArtifactDefinition, ResponseFormat> createArtifactPlaceHolder = createArtifactPlaceHolderInfo(parentIdParam, envLabel, placeHolderData, user.getUserId(), ArtifactGroupTypeEnum.DEPLOYMENT, true);
4560 if (createArtifactPlaceHolder.isRight()) {
4561 return Either.right(createArtifactPlaceHolder.right().value());
4563 ArtifactDefinition artifactHeatEnv = createArtifactPlaceHolder.left().value();
4565 // fix for migration only!!!! create heat env placeholder according to heat id.
4566 artifactHeatEnv.setUniqueId(artifact.getUniqueId() + HEAT_ENV_SUFFIX);
4569 artifactHeatEnv.setGeneratedFromId(artifact.getUniqueId());
4570 artifactHeatEnv.setHeatParamsUpdateDate(System.currentTimeMillis());
4571 artifactHeatEnv.setTimeout(0);
4572 buildHeatEnvFileName(artifact, artifactHeatEnv, placeHolderData);
4573 // rbetzer - keep env artifactVersion - changeComponentInstanceVersion flow
4574 handleEnvArtifactVersion(artifactHeatEnv, existingEnvVersions);
4575 // clone heat parameters in case of heat env only not VF heat env
4576 if (envType.equals(HEAT_ENV_NAME)) {
4577 artifactHeatEnv.setHeatParameters(artifact.getHeatParameters());
4579 ArtifactDefinition artifactDefinition;
4580 // Evg : for resource instance artifact will be added later as block with other env artifacts from BL
4581 if (parentType != NodeTypeEnum.ResourceInstance) {
4582 Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact = addHeatEnvArtifact(artifactHeatEnv, artifact, component.getUniqueId(), parentType, parentId);
4583 if (addHeatEnvArtifact.isRight()) {
4584 log.debug("failed to create heat env artifact on resource instance");
4585 return Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(addHeatEnvArtifact.right().value(), false), "", null));
4587 artifactDefinition = createArtifactPlaceHolder.left().value();
4589 artifactDefinition = artifactHeatEnv;
4590 artifactToscaOperation.generateUUID(artifactDefinition, artifactDefinition.getArtifactVersion());
4593 if (artifact.getHeatParameters() != null) {
4594 List<HeatParameterDefinition> heatEnvParameters = new ArrayList<HeatParameterDefinition>();
4595 for (HeatParameterDefinition parameter : artifact.getListHeatParameters()) {
4596 HeatParameterDefinition heatEnvParameter = new HeatParameterDefinition(parameter);
4597 heatEnvParameter.setDefaultValue(parameter.getCurrentValue());
4598 heatEnvParameters.add(heatEnvParameter);
4600 artifactDefinition.setListHeatParameters(heatEnvParameters);
4604 EnumMap<AuditingFieldsKeysEnum, Object> artifactAuditingFields = createArtifactAuditingFields(artifactDefinition, "", artifactDefinition.getUniqueId());
4605 artifactAuditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, parentName);
4606 ComponentTypeEnum componentType = component.getComponentType();
4607 if (parentType == NodeTypeEnum.ResourceInstance) {
4608 componentType = ComponentTypeEnum.RESOURCE_INSTANCE;
4610 componentsUtils.auditComponent(componentsUtils.getResponseFormat(ActionStatus.OK), user, component, "", "", AuditingActionEnum.ARTIFACT_UPLOAD, componentType, artifactAuditingFields);
4611 return Either.left(artifactDefinition);
4614 private void buildHeatEnvFileName(ArtifactDefinition heatArtifact, ArtifactDefinition heatEnvArtifact, Map<String, Object> placeHolderData) {
4615 String heatExtension = GeneralUtility.getFilenameExtension(heatArtifact.getArtifactName());
4616 String envExtension = (String) placeHolderData.get(ARTIFACT_PLACEHOLDER_FILE_EXTENSION);
4617 String name = heatArtifact.getArtifactName();
4620 name = heatArtifact.getArtifactLabel();
4621 fileName = name + "." + envExtension;
4623 fileName = name.replaceAll("." + heatExtension, "." + envExtension);
4625 heatEnvArtifact.setArtifactName(fileName);
4628 private void handleEnvArtifactVersion(ArtifactDefinition heatEnvArtifact, Map<String, String> existingEnvVersions) {
4629 if (null != existingEnvVersions) {
4630 String prevVersion = existingEnvVersions.get(heatEnvArtifact.getArtifactName());
4631 if (null != prevVersion) {
4632 heatEnvArtifact.setArtifactVersion(prevVersion);
4638 * Handles Artifacts Request For Inner Component
4640 * @param artifactsToHandle
4643 * @param vfcsNewCreatedArtifacts
4646 * @param inTransaction
4649 public Either<List<ArtifactDefinition>, ResponseFormat> handleArtifactsRequestForInnerVfcComponent(List<ArtifactDefinition> artifactsToHandle, Resource component, User user, List<ArtifactDefinition> vfcsNewCreatedArtifacts,
4650 ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) {
4652 Either<List<ArtifactDefinition>, ResponseFormat> handleArtifactsResult = null;
4653 ComponentTypeEnum componentType = component.getComponentType();
4654 List<ArtifactDefinition> uploadedArtifacts = new ArrayList<>();
4655 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4656 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult;
4660 for (ArtifactDefinition artifact : artifactsToHandle) {
4661 originData = buildJsonStringForCsarVfcArtifact(artifact);
4662 origMd5 = GeneralUtility.calculateMD5ByString(originData);
4663 actionResult = handleArtifactRequest(component.getUniqueId(), user.getUserId(), componentType, operation, artifact.getUniqueId(), artifact, origMd5, originData, null, null, null, null, shouldLock, inTransaction);
4664 if (actionResult.isRight()) {
4665 log.debug("Failed to upload artifact to component with type {} and name {}. Status is {}. ", componentType, component.getName(), actionResult.right().value());
4666 errorWrapper.setInnerElement(actionResult.right().value());
4667 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create) {
4668 vfcsNewCreatedArtifacts.addAll(uploadedArtifacts);
4672 uploadedArtifacts.add(actionResult.left().value().left().value());
4674 if (errorWrapper.isEmpty()) {
4675 handleArtifactsResult = Either.left(uploadedArtifacts);
4677 handleArtifactsResult = Either.right(errorWrapper.getInnerElement());
4679 } catch (Exception e) {
4680 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
4681 handleArtifactsResult = Either.right(responseFormat);
4682 log.debug("Exception occured when handleArtifactsRequestForInnerVfcComponent, error is:{}", e.getMessage(), e);
4684 return handleArtifactsResult;
4687 private ComponentInstance getRelatedComponentInstance(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
4688 ComponentInstance componentInstance = null;
4689 String normalizedName = ValidationUtils.normalizeComponentInstanceName(resourceInstanceName);
4690 Component component = getComponentByUuid(componentType, componentUuid, errorWrapper);
4691 if (errorWrapper.isEmpty()) {
4692 componentInstance = component.getComponentInstances().stream().filter(ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName()).equals(normalizedName)).findFirst().orElse(null);
4693 if (componentInstance == null) {
4694 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, "resource instance", component.getComponentType().getValue(), component.getName()));
4695 log.debug("Component instance {} was not found for component {}", resourceInstanceName, component.getName());
4698 return componentInstance;
4701 private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(Component component, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
4703 ImmutablePair<Component, ComponentInstance> relatedComponentComponentInstancePair = null;
4704 String normalizedName = ValidationUtils.normalizeComponentInstanceName(resourceInstanceName);
4705 ComponentInstance componentInstance = component.getComponentInstances().stream().filter(ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName()).equals(normalizedName)).findFirst().orElse(null);
4706 if (componentInstance == null) {
4707 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, "resource instance", component.getComponentType().getValue(), component.getName()));
4708 log.debug("Component instance {} was not found for component {}", resourceInstanceName, component.getName());
4710 relatedComponentComponentInstancePair = new ImmutablePair<>(component, componentInstance);
4712 return relatedComponentComponentInstancePair;
4715 private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
4716 ComponentInstance componentInstance;
4717 ImmutablePair<Component, ComponentInstance> relatedComponentComponentInstancePair = null;
4718 Component component = getLatestComponentByUuid(componentType, componentUuid, errorWrapper);
4719 if (errorWrapper.isEmpty()) {
4720 componentInstance = component.getComponentInstances().stream().filter(ci -> ci.getNormalizedName().equals(resourceInstanceName)).findFirst().orElse(null);
4721 if (componentInstance == null) {
4722 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, "resource instance", component.getComponentType().getValue(), component.getName()));
4723 log.debug("Component instance {} was not found for component {}", resourceInstanceName, component.getName());
4725 relatedComponentComponentInstancePair = new ImmutablePair<>(component, componentInstance);
4728 return relatedComponentComponentInstancePair;
4731 private byte[] downloadArtifact(Map<String, ArtifactDefinition> artifacts, String artifactUUID, Wrapper<ResponseFormat> errorWrapper, String componentName) {
4733 byte[] downloadedArtifact = null;
4734 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = null;
4735 List<ArtifactDefinition> deploymentArtifacts = null;
4736 ArtifactDefinition deploymentArtifact = null;
4737 if (artifacts != null && !artifacts.isEmpty()) {
4738 deploymentArtifacts = artifacts.values().stream().filter(art -> art.getArtifactUUID() != null && art.getArtifactUUID().equals(artifactUUID)).collect(Collectors.toList());
4740 if (deploymentArtifacts == null || deploymentArtifacts.isEmpty()) {
4741 log.debug("Deployment artifact with uuid {} was not found for component {}", artifactUUID, componentName);
4742 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactUUID));
4744 if (errorWrapper.isEmpty()) {
4745 deploymentArtifact = deploymentArtifacts.get(0);
4746 downloadArtifactEither = downloadArtifact(deploymentArtifact);
4747 if (downloadArtifactEither.isRight()) {
4748 log.debug("Failed to download artifact {}. ", deploymentArtifact.getArtifactName());
4749 errorWrapper.setInnerElement(downloadArtifactEither.right().value());
4752 if (errorWrapper.isEmpty()) {
4753 log.trace("Succeeded to download artifact with uniqueId {}", deploymentArtifact.getUniqueId());
4754 downloadedArtifact = downloadArtifactEither.left().value().getRight();
4756 return downloadedArtifact;
4759 private Component getLatestComponentByUuid(ComponentTypeEnum componentType, String componentUuid, Wrapper<ResponseFormat> errorWrapper) {
4760 Component component = null;
4761 Either<Component, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentByUuid(componentUuid);
4762 if (getComponentRes.isRight()) {
4763 StorageOperationStatus status = getComponentRes.right().value();
4764 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4765 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4767 component = getComponentRes.left().value();
4772 private Component getComponentByUuid(ComponentTypeEnum componentType, String componentUuid, Wrapper<ResponseFormat> errorWrapper) {
4773 Component component = null;
4774 Either<List<Component>, StorageOperationStatus> getComponentRes = toscaOperationFacade.getComponentListByUuid(componentUuid, null);
4775 if (getComponentRes.isRight()) {
4776 StorageOperationStatus status = getComponentRes.right().value();
4777 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4778 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4780 List<Component> value = getComponentRes.left().value();
4781 if (value.isEmpty()){
4782 log.debug("Could not fetch component with type {} and uuid {}.", componentType, componentUuid);
4783 ActionStatus status = componentType == ComponentTypeEnum.RESOURCE ? ActionStatus.RESOURCE_NOT_FOUND : ActionStatus.SERVICE_NOT_FOUND;
4784 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(status));
4786 component = value.get(0);
4792 private String getLatestParentArtifactDataIdByArtifactUUID(String artifactUUID, Wrapper<ResponseFormat> errorWrapper, String parentId, ComponentTypeEnum componentType) {
4793 String artifactId = null;
4794 ActionStatus actionStatus = ActionStatus.ARTIFACT_NOT_FOUND;
4795 StorageOperationStatus storageStatus;
4796 ArtifactDefinition latestArtifact = null;
4797 List<ArtifactDefinition> artifacts = null;
4798 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifactsRes = artifactToscaOperation.getArtifacts(parentId);
4799 if (getArtifactsRes.isRight()) {
4800 storageStatus = getArtifactsRes.right().value();
4801 log.debug("Couldn't fetch artifacts data for parent component {} with uid {}, error: {}", componentType.name(), parentId, storageStatus);
4802 if (!storageStatus.equals(StorageOperationStatus.NOT_FOUND)) {
4803 actionStatus = componentsUtils.convertFromStorageResponse(storageStatus);
4805 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
4807 if (errorWrapper.isEmpty()) {
4808 artifacts = getArtifactsRes.left().value().values().stream().filter(a -> a.getArtifactUUID() != null && a.getArtifactUUID().equals(artifactUUID)).collect(Collectors.toList());
4809 if (artifacts == null || artifacts.isEmpty()) {
4810 log.debug("Couldn't fetch artifact with UUID {} data for parent component {} with uid {}, error: {}", artifactUUID, componentType.name(), parentId, actionStatus);
4811 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
4814 if (errorWrapper.isEmpty()) {
4815 latestArtifact = artifacts.stream().max((a1, a2) -> {
4816 int compareRes = Double.compare(Double.parseDouble(a1.getArtifactVersion()), Double.parseDouble(a2.getArtifactVersion()));
4817 if (compareRes == 0) {
4818 compareRes = Long.compare(a1.getLastUpdateDate() == null ? 0 : a1.getLastUpdateDate(), a2.getLastUpdateDate() == null ? 0 : a2.getLastUpdateDate());
4822 if (latestArtifact == null) {
4823 log.debug("Couldn't fetch latest artifact with UUID {} data for parent component {} with uid {}, error: {}", artifactUUID, componentType.name(), parentId, actionStatus);
4824 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
4827 if (errorWrapper.isEmpty()) {
4828 artifactId = latestArtifact.getUniqueId();
4833 private Component checkoutParentComponent(ComponentTypeEnum componentType, String parentId, String userId, Wrapper<ResponseFormat> errorWrapper) {
4835 Component component = null;
4836 Either<User, ActionStatus> getUserRes = userBusinessLogic.getUser(userId, false);
4837 if (getUserRes.isRight()) {
4838 log.debug("Could not fetch User of component {} with uid {} to checked out. Status is {}. ", componentType.getNodeType(), parentId, getUserRes.right().value());
4839 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(getUserRes.right().value()));
4841 if (errorWrapper.isEmpty()) {
4842 User modifier = getUserRes.left().value();
4843 LifecycleChangeInfoWithAction changeInfo = new LifecycleChangeInfoWithAction("External API checkout", LifecycleChanceActionEnum.UPDATE_FROM_EXTERNAL_API);
4844 Either<? extends Component, ResponseFormat> checkoutRes = lifecycleBusinessLogic.changeComponentState(componentType, parentId, modifier, LifeCycleTransitionEnum.CHECKOUT, changeInfo, false, true);
4845 if (checkoutRes.isRight()) {
4846 log.debug("Could not change state of component {} with uid {} to checked out. Status is {}. ", componentType.getNodeType(), parentId, checkoutRes.right().value().getStatus());
4847 errorWrapper.setInnerElement(checkoutRes.right().value());
4849 component = checkoutRes.left().value();
4855 private void updateAuditParametersWithArtifactDefinition(Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactDefinition artifact) {
4856 if (artifact == null) {
4857 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, "");
4858 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, "");
4859 if (!additionalParams.containsKey(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID)) {
4860 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, "");
4863 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifact.getArtifactUUID());
4864 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, buildAuditingArtifactData(artifact));
4865 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, artifact.getUpdaterFullName());
4869 private String buildJsonStringForCsarVfcArtifact(ArtifactDefinition artifact) {
4870 Map<String, Object> json = new HashMap<>();
4871 String artifactName = artifact.getArtifactName();
4872 json.put(Constants.ARTIFACT_NAME, artifactName);
4873 json.put(Constants.ARTIFACT_LABEL, artifact.getArtifactLabel());
4874 json.put(Constants.ARTIFACT_TYPE, artifact.getArtifactType());
4875 json.put(Constants.ARTIFACT_GROUP_TYPE, ArtifactGroupTypeEnum.DEPLOYMENT.getType());
4876 json.put(Constants.ARTIFACT_DESCRIPTION, artifact.getDescription());
4877 json.put(Constants.ARTIFACT_PAYLOAD_DATA, artifact.getPayloadData());
4878 json.put(Constants.ARTIFACT_DISPLAY_NAME, artifact.getArtifactDisplayName());
4879 return gson.toJson(json);