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.rmi.activation.ActivationSystem;
27 import java.util.ArrayList;
28 import java.util.Comparator;
29 import java.util.EnumMap;
30 import java.util.HashMap;
31 import java.util.Iterator;
32 import java.util.List;
34 import java.util.Map.Entry;
35 import java.util.Optional;
37 import java.util.function.Predicate;
38 import java.util.function.Supplier;
39 import java.util.stream.Collectors;
41 import javax.servlet.http.HttpServletRequest;
43 import org.apache.commons.codec.binary.Base64;
44 import org.apache.commons.collections.CollectionUtils;
45 import org.apache.commons.collections.MapUtils;
46 import org.apache.commons.lang.StringUtils;
47 import org.apache.commons.lang3.tuple.ImmutablePair;
48 import org.openecomp.sdc.be.components.ArtifactsResolver;
49 import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum;
50 import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaTagNamesEnum;
51 import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
52 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
53 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction.LifecycleChanceActionEnum;
54 import org.openecomp.sdc.be.config.BeEcompErrorManager;
55 import org.openecomp.sdc.be.config.Configuration.ArtifactTypeConfig;
56 import org.openecomp.sdc.be.config.ConfigurationManager;
57 import org.openecomp.sdc.be.config.validation.DeploymentArtifactHeatConfiguration;
58 import org.openecomp.sdc.be.dao.api.ActionStatus;
59 import org.openecomp.sdc.be.dao.cassandra.ArtifactCassandraDao;
60 import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus;
61 import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
62 import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
63 import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
64 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
65 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
66 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
67 import org.openecomp.sdc.be.model.ArtifactDefinition;
68 import org.openecomp.sdc.be.model.ArtifactType;
69 import org.openecomp.sdc.be.model.Component;
70 import org.openecomp.sdc.be.model.ComponentInstance;
71 import org.openecomp.sdc.be.model.ComponentParametersView;
72 import org.openecomp.sdc.be.model.GroupDefinition;
73 import org.openecomp.sdc.be.model.GroupInstance;
74 import org.openecomp.sdc.be.model.HeatParameterDefinition;
75 import org.openecomp.sdc.be.model.InterfaceDefinition;
76 import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;
77 import org.openecomp.sdc.be.model.LifecycleStateEnum;
78 import org.openecomp.sdc.be.model.Operation;
79 import org.openecomp.sdc.be.model.Resource;
80 import org.openecomp.sdc.be.model.Service;
81 import org.openecomp.sdc.be.model.User;
82 import org.openecomp.sdc.be.model.heat.HeatParameterType;
83 import org.openecomp.sdc.be.model.jsontitan.operations.NodeTemplateOperation;
84 import org.openecomp.sdc.be.model.operations.api.IElementOperation;
85 import org.openecomp.sdc.be.model.operations.api.IHeatParametersOperation;
86 import org.openecomp.sdc.be.model.operations.api.IInterfaceLifecycleOperation;
87 import org.openecomp.sdc.be.model.operations.api.IUserAdminOperation;
88 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
89 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
90 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
91 import org.openecomp.sdc.be.resources.data.ComponentMetadataData;
92 import org.openecomp.sdc.be.resources.data.ESArtifactData;
93 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
94 import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants;
95 import org.openecomp.sdc.be.servlets.RepresentationUtils;
96 import org.openecomp.sdc.be.tosca.CsarUtils;
97 import org.openecomp.sdc.be.tosca.ToscaError;
98 import org.openecomp.sdc.be.tosca.ToscaExportHandler;
99 import org.openecomp.sdc.be.tosca.ToscaRepresentation;
100 import org.openecomp.sdc.be.user.IUserBusinessLogic;
101 import org.openecomp.sdc.be.user.Role;
102 import org.openecomp.sdc.be.user.UserBusinessLogic;
103 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
104 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
105 import org.openecomp.sdc.common.api.Constants;
106 import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
107 import org.openecomp.sdc.common.datastructure.Wrapper;
108 import org.openecomp.sdc.common.util.GeneralUtility;
109 import org.openecomp.sdc.common.util.ValidationUtils;
110 import org.openecomp.sdc.common.util.YamlToObjectConverter;
111 import org.openecomp.sdc.exception.ResponseFormat;
112 import org.slf4j.Logger;
113 import org.slf4j.LoggerFactory;
114 import org.springframework.beans.factory.annotation.Autowired;
115 import org.xml.sax.InputSource;
116 import org.xml.sax.SAXException;
117 import org.xml.sax.XMLReader;
118 import org.yaml.snakeyaml.Yaml;
120 import com.google.gson.Gson;
121 import com.google.gson.GsonBuilder;
122 import com.sun.org.apache.xerces.internal.parsers.SAXParser;
124 import fj.data.Either;
126 @org.springframework.stereotype.Component("artifactBusinessLogic")
127 public class ArtifactsBusinessLogic extends BaseBusinessLogic {
128 private static final String ARTIFACT_TYPE_OTHER = "OTHER";
129 private static final String ARTIFACT_DESCRIPTION = "artifact description";
130 private static final String ARTIFACT_LABEL = "artifact label";
131 private static final String ARTIFACT_URL = "artifact url";
132 private static final String ARTIFACT_NAME = "artifact name";
133 private static final String ARTIFACT_PAYLOAD = "artifact payload";
135 private static final String ARTIFACT_PLACEHOLDER_TYPE = "type";
136 private static final String ARTIFACT_PLACEHOLDER_DISPLAY_NAME = "displayName";
137 private static final Object ARTIFACT_PLACEHOLDER_DESCRIPTION = "description";
139 public static final String HEAT_ENV_NAME = "heatEnv";
140 public static final String HEAT_VF_ENV_NAME = "VfHeatEnv";
141 public static final String HEAT_ENV_SUFFIX = "env";
142 private static final String ARTIFACT_PLACEHOLDER_FILE_EXTENSION = "fileExtension";
144 // private static Integer defaultHeatTimeout;
145 // private static final Integer NON_HEAT_TIMEOUT = 0;
146 private static Logger log = LoggerFactory.getLogger(ArtifactsBusinessLogic.class.getName());
147 private Gson gson = new GsonBuilder().setPrettyPrinting().create();
149 @javax.annotation.Resource
150 private IInterfaceLifecycleOperation interfaceLifecycleOperation;
151 @javax.annotation.Resource
152 private IUserAdminOperation userOperaton;
154 @javax.annotation.Resource
155 private IElementOperation elementOperation;
157 @javax.annotation.Resource
158 private ResourceBusinessLogic resourceBusinessLogic;
160 @javax.annotation.Resource
161 private ServiceBusinessLogic serviceBusinessLogic;
163 @javax.annotation.Resource
164 private UserBusinessLogic userAdminManager;
166 @javax.annotation.Resource
167 private IHeatParametersOperation heatParametersOperation;
170 private ArtifactCassandraDao artifactCassandraDao;
173 private ToscaExportHandler toscaExportUtils;
176 private CsarUtils csarUtils;
179 private LifecycleBusinessLogic lifecycleBusinessLogic;
182 private IUserBusinessLogic userBusinessLogic;
184 NodeTemplateOperation nodeTemplateOperation;
187 private ArtifactsResolver artifactsResolver;
189 public ArtifactsBusinessLogic() {
190 // defaultHeatTimeout = ConfigurationManager.getConfigurationManager().getConfiguration().getDefaultHeatArtifactTimeoutMinutes();
191 // if ((defaultHeatTimeout == null) || (defaultHeatTimeout < 1)) {
192 // defaultHeatTimeout = 60;
196 public static enum ArtifactOperationEnum {
197 Create(), Update(), Delete(), Download();
200 public class ArtifactOperationInfo {
202 private ArtifactOperationEnum artifactOperationEnum;
203 private boolean isExternalApi;
204 private boolean ignoreLifecycleState;
206 public ArtifactOperationInfo(boolean isExternalApi, boolean ignoreLifecycleState, ArtifactOperationEnum artifactOperationEnum) {
207 this.artifactOperationEnum = artifactOperationEnum;
208 this.isExternalApi = isExternalApi;
209 this.ignoreLifecycleState = ignoreLifecycleState;
212 public boolean isExternalApi() {
213 return isExternalApi;
216 public boolean ignoreLifecycleState() {
217 return ignoreLifecycleState;
220 public ArtifactOperationEnum getArtifactOperationEnum() {
221 return artifactOperationEnum;
227 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleArtifactRequest(String componentId, String userId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo,
228 String origMd5, String originData, String interfaceName, String operationName, String parentId, String containerComponentType) {
229 return handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, origMd5, originData, interfaceName, operationName, parentId, containerComponentType, true, false);
232 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleArtifactRequest(String componentId, String userId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo,
233 String origMd5, String originData, String interfaceName, String operationName, String parentId, String containerComponentType, boolean shouldLock, boolean inTransaction) {
235 // step 1 - detect auditing type
236 AuditingActionEnum auditingAction = detectAuditingType(operation, origMd5);
237 // step 2 - check header
238 if (userId == null) {
239 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
240 log.debug("handleArtifactRequest - no HTTP_CSP_HEADER , component id {}", componentId);
241 handleAuditing(auditingAction, null, componentId, null, null, null, artifactId, responseFormat, componentType, null);
242 return Either.right(responseFormat);
244 // step 3 - check user existence
245 Either<User, ResponseFormat> userResult = validateUserExists(userId, auditingAction, componentId, artifactId, componentType, inTransaction);
246 if (userResult.isRight()) {
247 return Either.right(userResult.right().value());
250 // step 4 - check user's role
251 User user = userResult.left().value();
252 Either<Boolean, ResponseFormat> validateUserRole = validateUserRole(user, auditingAction, componentId, artifactId, componentType, operation);
253 if (validateUserRole.isRight()) {
254 return Either.right(validateUserRole.right().value());
258 // 5. check service/resource existence
259 // 6. check service/resource check out
260 // 7. user is owner of checkout state
261 org.openecomp.sdc.be.model.Component component = null;
262 // ComponentInstance resourceInstance = null;
263 String realComponentId = componentType == ComponentTypeEnum.RESOURCE_INSTANCE ? parentId : componentId;
264 Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(realComponentId, userId, auditingAction, user, artifactId, componentType, containerComponentType, inTransaction);
265 if (validateComponent.isRight()) {
266 return Either.right(validateComponent.right().value());
268 component = validateComponent.left().value();
269 Either<Boolean, ResponseFormat> validateWorkOnResource = validateWorkOnComponent(component, userId, auditingAction, user, artifactId, operation, componentType);
270 if (validateWorkOnResource.isRight()) {
271 return Either.right(validateWorkOnResource.right().value());
274 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result = validateAndHandleArtifact(componentId, componentType, operation, artifactId, artifactInfo, origMd5, originData, interfaceName, operationName, parentId, user, component,
275 shouldLock, inTransaction, true);
281 * This Method validates only the Artifact and does not validate user / role / component ect...<br>
282 * For regular usage use <br>
283 * {@link #handleArtifactRequest(String, String, ComponentTypeEnum, ArtifactOperationInfo, String, ArtifactDefinition, String, String, String, String, String, String)}
287 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> validateAndHandleArtifact(String componentUniqueId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactUniqueId,
288 ArtifactDefinition artifactDefinition, String origMd5, String originData, String interfaceName, String operationName, String parentId, User user, Component component, boolean shouldLock, boolean inTransaction, boolean needUpdateGroup) {
289 Component parent = component;
290 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
292 AuditingActionEnum auditingAction = detectAuditingType(operation, origMd5);
293 artifactDefinition = validateArtifact(componentUniqueId, componentType, operation, artifactUniqueId, artifactDefinition, parentId, auditingAction, user, component, parent, shouldLock, errorWrapper, inTransaction);
295 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result;
296 if (errorWrapper.isEmpty()) {
298 result = doAction(componentUniqueId, componentType, operation, artifactUniqueId, artifactDefinition, origMd5, originData, interfaceName, operationName, auditingAction, user, parent, shouldLock, inTransaction, needUpdateGroup);
300 result = Either.right(errorWrapper.getInnerElement());
305 private ArtifactDefinition validateArtifact(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, String parentId, AuditingActionEnum auditingAction, User user,
306 org.openecomp.sdc.be.model.Component component, org.openecomp.sdc.be.model.Component parent, boolean shouldLock, Wrapper<ResponseFormat> errorWrapper, boolean inTransaction) {
307 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Update || operation.getArtifactOperationEnum() == ArtifactOperationEnum.Delete || operation.getArtifactOperationEnum() == ArtifactOperationEnum.Download) {
308 Either<ArtifactDefinition, ResponseFormat> validateArtifact = validateArtifact(componentId, componentType, artifactId, component, auditingAction, parentId, inTransaction);
309 if (validateArtifact.isRight()) {
310 ResponseFormat responseFormat = validateArtifact.right().value();
311 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
312 errorWrapper.setInnerElement(validateArtifact.right().value());
314 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Download) {
315 artifactInfo = validateArtifact.left().value();
316 handleHeatEnvDownload(componentId, componentType, user, component, validateArtifact, shouldLock, errorWrapper);
323 private void handleHeatEnvDownload(String componentId, ComponentTypeEnum componentType, User user, org.openecomp.sdc.be.model.Component component, Either<ArtifactDefinition, ResponseFormat> validateArtifact, boolean shouldLock,
324 Wrapper<ResponseFormat> errorWrapper) {
325 ArtifactDefinition validatedArtifact = validateArtifact.left().value();
327 if (validatedArtifact.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType())) {
328 if (ComponentTypeEnum.SERVICE == component.getComponentType()) {
329 ComponentInstance componentInstance = component.getComponentInstances().stream().filter(p -> p.getUniqueId().equals(componentId)).findAny().get();
330 Map<String, ArtifactDefinition> deploymentArtifacts = componentInstance.getDeploymentArtifacts();
332 ArtifactDefinition heatEnvWithHeatParams = deploymentArtifacts.values().stream().filter(p -> p.getUniqueId().equals(validatedArtifact.getUniqueId())).findAny().get();
333 Either<ArtifactDefinition, ResponseFormat> eitherGenerated = generateHeatEnvArtifact(heatEnvWithHeatParams, componentType, component, componentInstance.getName(), user, shouldLock, componentId);
334 if (eitherGenerated.isRight()) {
335 errorWrapper.setInnerElement(eitherGenerated.right().value());
341 private boolean artifactGenerationRequired(org.openecomp.sdc.be.model.Component component, ArtifactDefinition artifactInfo) {
342 boolean needGenerate;
343 needGenerate = artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA && (component.getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN || component.getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
344 needGenerate = needGenerate || (ComponentTypeEnum.RESOURCE == component.getComponentType() && artifactInfo.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType()));
348 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateAndSaveToscaArtifact(ArtifactDefinition artifactDefinition, org.openecomp.sdc.be.model.Component component, User user, boolean isInCertificationRequest,
349 boolean shouldLock, boolean inTransaction, boolean fetchTemplatesFromDB) {
351 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generated = generateToscaArtifact(component, artifactDefinition, isInCertificationRequest, fetchTemplatesFromDB);
352 if (generated.isRight()) {
355 byte[] decodedPayload = artifactDefinition.getPayloadData();
356 artifactDefinition.setEsId(artifactDefinition.getUniqueId());
357 artifactDefinition.setArtifactChecksum(GeneralUtility.calculateMD5ByByteArray(decodedPayload));
358 return lockComponentAndUpdateArtifact(component.getUniqueId(), artifactDefinition, AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, artifactDefinition.getUniqueId(), user, component.getComponentType(), component, decodedPayload, null, null,
359 shouldLock, inTransaction);
363 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateToscaArtifact(Component parent, ArtifactDefinition artifactInfo, boolean isInCertificationRequest, boolean fetchTemplatesFromDB) {
364 log.debug("tosca artifact generation");
365 if (artifactInfo.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType())) {
366 Either<byte[], ResponseFormat> generated = csarUtils.createCsar(parent, fetchTemplatesFromDB, isInCertificationRequest);
368 if (generated.isRight()) {
369 log.debug("Failed to export tosca csar for component {} error {}", parent.getUniqueId(), generated.right().value());
371 return Either.right(generated.right().value());
373 byte[] value = generated.left().value();
374 artifactInfo.setPayload(value);
377 Either<ToscaRepresentation, ToscaError> exportComponent = toscaExportUtils.exportComponent(parent);
378 if (exportComponent.isRight()) {
379 log.debug("Failed export tosca yaml for component {} error {}", parent.getUniqueId(), exportComponent.right().value());
380 ActionStatus status = componentsUtils.convertFromToscaError(exportComponent.right().value());
381 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status);
382 return Either.right(responseFormat);
384 log.debug("Tosca yaml exported for component {} ", parent.getUniqueId());
385 String payload = exportComponent.left().value().getMainYaml();
386 artifactInfo.setPayloadData(payload);
388 return Either.left(Either.left(artifactInfo));
391 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> doAction(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, String origMd5,
392 String originData, String interfaceName, String operationName, AuditingActionEnum auditingAction, User user, org.openecomp.sdc.be.model.Component parent, boolean shouldLock, boolean inTransaction, boolean needUpdateGroup) {
393 if (interfaceName != null && operationName != null) {
394 interfaceName = interfaceName.toLowerCase();
395 operationName = operationName.toLowerCase();
397 switch (operation.getArtifactOperationEnum()) {
399 if (artifactGenerationRequired(parent, artifactInfo)) {
400 return generateNotSavedArtifact(parent, artifactInfo, shouldLock, inTransaction);
402 return handleDownload(componentId, artifactId, user, auditingAction, componentType, parent, shouldLock, inTransaction);
404 return handleDelete(componentId, artifactId, user, auditingAction, componentType, parent, interfaceName, operationName, shouldLock, inTransaction);
406 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result = null;
407 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
408 if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)
409 && (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_VOL || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_ENV)) {
410 result = handleUpdateHeatEnv(componentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, originData, origMd5, operation, shouldLock, inTransaction);
411 if (needUpdateGroup && result.isLeft()) {
412 Either<ArtifactDefinition, Operation> updateResult = result.left().value();
413 ActionStatus error = updateGroupInstance(artifactInfo, updateResult.left().value(), parent, componentType, componentId);
414 if (error != ActionStatus.OK) {
415 result = Either.right(componentsUtils.getResponseFormat(error));
419 if (componentType.equals(ComponentTypeEnum.RESOURCE) && artifactType == ArtifactTypeEnum.HEAT_ENV) {
420 result = handleUpdateHeatWithHeatEnvParams(componentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, originData, origMd5, operation, shouldLock, inTransaction, needUpdateGroup);
423 if (result == null) {
424 result = handleUpdate(componentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceName, operationName, shouldLock, inTransaction);
425 if (needUpdateGroup && result.isLeft()) {
426 Either<ArtifactDefinition, Operation> updateResult = result.left().value();
428 ActionStatus error = updateGroupForHeat(artifactInfo, updateResult.left().value(), parent, componentType);
429 if (error != ActionStatus.OK) {
430 result = Either.right(componentsUtils.getResponseFormat(error));
436 return handleCreate(componentId, artifactInfo, operation, auditingAction, user, componentType, parent, origMd5, originData, interfaceName, operationName, shouldLock, inTransaction);
441 private ActionStatus updateGroupForHeat(ArtifactDefinition artifactInfo, ArtifactDefinition artAfterUpdate, Component parent, ComponentTypeEnum componentType) {
442 List<GroupDefinition> groups = parent.getGroups();
443 if (groups != null && !groups.isEmpty()) {
444 List<GroupDataDefinition> groupToUpdate = groups.stream().filter(g -> g.getArtifacts() != null && g.getArtifacts().contains(artifactInfo.getUniqueId())).collect(Collectors.toList());
445 if (groupToUpdate != null && !groupToUpdate.isEmpty()) {
446 groupToUpdate.forEach(g -> {
447 g.getArtifacts().remove(artifactInfo.getUniqueId());
448 g.getArtifactsUuid().remove(artifactInfo.getArtifactUUID());
449 g.getArtifacts().add(artAfterUpdate.getUniqueId());
450 g.getArtifactsUuid().add(artAfterUpdate.getArtifactUUID());
452 Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(parent, componentType, groupToUpdate);
453 if (status.isRight()) {
454 log.debug("Failed to update groups of the component {}. ", parent.getUniqueId());
455 return componentsUtils.convertFromStorageResponse(status.right().value());
459 return ActionStatus.OK;
462 private ActionStatus updateGroupForHeat(ArtifactDefinition artifactInfoHeat, ArtifactDefinition artHeatAfterUpdate, ArtifactDefinition artifactInfoHeatE, ArtifactDefinition artHEAfterUpdate, Component parent, ComponentTypeEnum componentType) {
463 List<GroupDefinition> groups = parent.getGroups();
464 if (groups != null && !groups.isEmpty()) {
465 List<GroupDataDefinition> groupToUpdate = groups.stream().filter(g -> g.getArtifacts() != null && g.getArtifacts().contains(artifactInfoHeat.getUniqueId())).collect(Collectors.toList());
466 if (groupToUpdate != null && !groupToUpdate.isEmpty()) {
467 groupToUpdate.forEach(g -> {
468 g.getArtifacts().remove(artifactInfoHeat.getUniqueId());
469 g.getArtifactsUuid().remove(artifactInfoHeat.getArtifactUUID());
470 g.getArtifacts().remove(artifactInfoHeatE.getUniqueId());
471 g.getArtifacts().add(artHeatAfterUpdate.getUniqueId());
472 g.getArtifactsUuid().add(artHeatAfterUpdate.getArtifactUUID());
473 g.getArtifacts().add(artHEAfterUpdate.getUniqueId());
475 Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(parent, componentType, groupToUpdate);
476 if (status.isRight()) {
477 log.debug("Failed to update groups of the component {}. ", parent.getUniqueId());
478 return componentsUtils.convertFromStorageResponse(status.right().value());
482 return ActionStatus.OK;
485 private ActionStatus updateGroupInstance(ArtifactDefinition artifactInfo, ArtifactDefinition artAfterUpdate, Component parent, ComponentTypeEnum componentType, String parentId) {
486 List<GroupInstance> updatedGroupInstances = new ArrayList<>();
487 List<GroupInstance> groupInstances = null;
488 Optional<ComponentInstance> componentInstOp = parent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(parentId)).findFirst();
489 if (componentInstOp.isPresent()) {
490 groupInstances = componentInstOp.get().getGroupInstances();
492 if (CollectionUtils.isNotEmpty(groupInstances)) {
493 boolean isUpdated = false;
494 for (GroupInstance groupInstance : groupInstances) {
496 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifacts()) && groupInstance.getGroupInstanceArtifacts().contains(artifactInfo.getUniqueId())) {
497 groupInstance.getGroupInstanceArtifacts().remove(artifactInfo.getUniqueId());
498 groupInstance.getGroupInstanceArtifacts().add(artAfterUpdate.getUniqueId());
501 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifactsUuid()) && groupInstance.getGroupInstanceArtifactsUuid().contains(artifactInfo.getArtifactUUID())) {
502 groupInstance.getGroupInstanceArtifactsUuid().remove(artifactInfo.getArtifactUUID());
503 groupInstance.getGroupInstanceArtifacts().add(artAfterUpdate.getArtifactUUID());
507 updatedGroupInstances.add(groupInstance);
511 Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(parent, componentType, parentId, updatedGroupInstances);
512 if (status.isRight()) {
513 log.debug("Failed to update groups of the component {}. ", parent.getUniqueId());
514 return componentsUtils.convertFromStorageResponse(status.right().value());
516 return ActionStatus.OK;
519 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateNotSavedArtifact(org.openecomp.sdc.be.model.Component parent, ArtifactDefinition artifactInfo, boolean shouldLock, boolean inTransaction) {
520 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result;
521 if (artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA) {
522 result = generateToscaArtifact(parent, artifactInfo, false, false);
524 String heatArtifactId = artifactInfo.getGeneratedFromId();
525 Either<ArtifactDefinition, StorageOperationStatus> heatRes = artifactToscaOperation.getArtifactById(parent.getUniqueId(), heatArtifactId);
526 if (heatRes.isRight()) {
527 log.debug("Failed to fetch heat artifact by generated id {} for heat env {}", heatArtifactId, artifactInfo.getUniqueId());
528 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(heatRes.right().value()), "");
529 return Either.right(responseFormat);
531 String generatedPayload = generateHeatEnvPayload(heatRes.left().value());
532 artifactInfo.setPayloadData(generatedPayload);
533 result = Either.left(Either.left(artifactInfo));
538 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdateHeatWithHeatEnvParams(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user,
539 ComponentTypeEnum componentType, Component parent, String originData, String origMd5, ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction, boolean needToUpdateGroup) {
540 convertParentType(componentType);
541 String parentId = parent.getUniqueId();
542 Either<ArtifactDefinition, StorageOperationStatus> artifactHeatRes = artifactToscaOperation.getArtifactById(componentId, artifactInfo.getGeneratedFromId());
543 ArtifactDefinition currHeatArtifact = artifactHeatRes.left().value();
545 if (origMd5 != null) {
546 Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
547 if (validateMd5.isRight()) {
548 ResponseFormat responseFormat = validateMd5.right().value();
549 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
550 return Either.right(responseFormat);
553 if (artifactInfo.getPayloadData() != null && artifactInfo.getPayloadData().length != 0) {
555 Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
556 if (payloadEither.isRight()) {
557 ResponseFormat responseFormat = payloadEither.right().value();
558 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
559 return Either.right(responseFormat);
561 } else { // duplicate
562 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
563 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
564 return Either.right(responseFormat);
570 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Update Artifact - lock ");
571 if (lockComponent.isRight()) {
572 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right().value(), componentType, null);
573 return Either.right(lockComponent.right().value());
576 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
578 resultOp = updateHeatParams(componentId, artifactId, artifactInfo, user, auditingAction, parent, componentType, currHeatArtifact, origMd5, needToUpdateGroup);
583 if (resultOp == null || resultOp.isRight()) {
584 log.debug("all changes rollback");
585 if (false == inTransaction)
588 log.debug("all changes committed");
589 if (false == inTransaction)
593 componentType = parent.getComponentType();
594 NodeTypeEnum nodeType = componentType.getNodeType();
595 graphLockOperation.unlockComponent(parent.getUniqueId(), nodeType);
596 // graphLockOperation.unlockComponent(parentId, parentType);
605 * @param componentType
610 public Either<ImmutablePair<String, byte[]>, ResponseFormat> handleDownloadToscaModelRequest(Component component, ArtifactDefinition csarArtifact) {
611 if (artifactGenerationRequired(component, csarArtifact)) {
612 Either<byte[], ResponseFormat> generated = csarUtils.createCsar(component, false, false);
614 if (generated.isRight()) {
615 log.debug("Failed to export tosca csar for component {} error {}", component.getUniqueId(), generated.right().value());
617 return Either.right(generated.right().value());
619 return Either.left(new ImmutablePair<String, byte[]>(csarArtifact.getArtifactName(), generated.left().value()));
621 return downloadArtifact(csarArtifact);
624 public Either<ImmutablePair<String, byte[]>, ResponseFormat> handleDownloadRequestById(String componentId, String artifactId, String userId, ComponentTypeEnum componentType, String parentId, String containerComponentType) {
625 // perform all validation in common flow
626 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result = handleArtifactRequest(componentId, userId, componentType, new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Download), artifactId, null, null, null, null,
627 null, parentId, containerComponentType);
628 if (result.isRight()) {
629 return Either.right(result.right().value());
631 ArtifactDefinition artifactDefinition;
632 Either<ArtifactDefinition, Operation> insideValue = result.left().value();
633 if (insideValue.isLeft()) {
634 artifactDefinition = insideValue.left().value();
636 artifactDefinition = insideValue.right().value().getImplementationArtifact();
638 // for tosca artifacts and heat env on VF level generated on download without saving
639 if (artifactDefinition.getPayloadData() != null) {
640 return Either.left(new ImmutablePair<String, byte[]>(artifactDefinition.getArtifactName(), artifactDefinition.getPayloadData()));
642 return downloadArtifact(artifactDefinition);
645 public Either<Map<String, ArtifactDefinition>, ResponseFormat> handleGetArtifactsByType(String containerComponentType, String parentId, ComponentTypeEnum componentType, String componentId, String artifactGroupType, String userId) {
647 // detect auditing type
648 Map<String, ArtifactDefinition> resMap = null;
649 Either<Map<String, ArtifactDefinition>, ResponseFormat> resultOp = null;
654 if (userId == null) {
655 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
656 log.debug("handleGetArtifactsByType - no HTTP_CSP_HEADER , component id {}", componentId);
658 resultOp = Either.right(responseFormat);
662 // check user existence
666 Either<User, ResponseFormat> userResult = validateUserExists(userId, "get artifacts", false);
667 if (userResult.isRight()) {
669 resultOp = Either.right(userResult.right().value());
673 userResult.left().value();
676 // 5. check service/resource existence
677 // 6. check service/resource check out
678 // 7. user is owner of checkout state
679 org.openecomp.sdc.be.model.Component component = null;
680 // ComponentInstance resourceInstance = null;
681 String realComponentId = componentType == ComponentTypeEnum.RESOURCE_INSTANCE ? parentId : componentId;
682 ComponentParametersView componentFilter = new ComponentParametersView();
683 componentFilter.disableAll();
684 componentFilter.setIgnoreArtifacts(false);
685 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE)
686 componentFilter.setIgnoreComponentInstances(false);
688 Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExistsByFilter(realComponentId, ComponentTypeEnum.findByParamName(containerComponentType), componentFilter, false);
690 if (validateComponent.isRight()) {
691 resultOp = Either.right(validateComponent.right().value());
694 component = validateComponent.left().value();
695 Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, "Update Artifact - lock ");
696 if (lockComponent.isRight()) {
698 resultOp = Either.right(lockComponent.right().value());
703 ArtifactGroupTypeEnum groupType = ArtifactGroupTypeEnum.findType(artifactGroupType);
705 if (groupType == null) {
706 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
707 log.debug("handleGetArtifactsByType - not falid groupType {} , component id {}", artifactGroupType, componentId);
709 resultOp = Either.right(responseFormat);
713 if (groupType == ArtifactGroupTypeEnum.DEPLOYMENT) {
714 List<ArtifactDefinition> list = getDeploymentArtifacts(component, componentType.getNodeType(), componentId);
715 if (list != null && !list.isEmpty()) {
716 resMap = list.stream().collect(Collectors.toMap(a -> a.getArtifactLabel(), a -> a));
718 resMap = new HashMap<>();
720 resultOp = Either.left(resMap);
724 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifactsMapStatus = getArtifacts(realComponentId, componentType.getNodeType(), false, groupType, componentId);
725 if (artifactsMapStatus.isRight()) {
726 if (artifactsMapStatus.right().value() != StorageOperationStatus.NOT_FOUND) {
727 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
728 log.debug("handleGetArtifactsByType - not falid groupType {} , component id {}", artifactGroupType, componentId);
729 resultOp = Either.right(responseFormat);
731 resMap = new HashMap<>();
732 resultOp = Either.left(resMap);
735 resMap = artifactsMapStatus.left().value();
736 resultOp = Either.left(resMap);
742 if (resultOp == null || resultOp.isRight()) {
743 log.debug("all changes rollback");
746 log.debug("all changes committed");
751 componentType = component.getComponentType();
752 NodeTypeEnum nodeType = componentType.getNodeType();
753 graphLockOperation.unlockComponent(component.getUniqueId(), nodeType);
754 // graphLockOperation.unlockComponent(parentId, parentType);
759 private Either<ArtifactDefinition, ResponseFormat> validateArtifact(String componentId, ComponentTypeEnum componentType, String artifactId, org.openecomp.sdc.be.model.Component component, AuditingActionEnum auditingAction, String parentId,
760 boolean inTransaction) {
762 // check artifact existence
763 Either<ArtifactDefinition, StorageOperationStatus> artifactResult = artifactToscaOperation.getArtifactById(componentId, artifactId, componentType, component.getUniqueId());
764 if (artifactResult.isRight()) {
765 if (artifactResult.right().value().equals(StorageOperationStatus.ARTIFACT_NOT_FOUND)) {
766 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, "");
767 log.debug("addArtifact - artifact {} not found", artifactId);
768 return Either.right(responseFormat);
771 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(artifactResult.right().value()));
772 log.debug("addArtifact - failed to fetch artifact {}, error {}", artifactId, artifactResult.right().value());
773 return Either.right(responseFormat);
777 // check artifact belong to component
778 boolean found = false;
779 switch (componentType) {
782 found = checkArtifactInComponent(component, artifactId);
784 case RESOURCE_INSTANCE:
785 found = checkArtifactInResourceInstance(component, componentId, artifactId);
791 // String component =
792 // componentType.equals(ComponentTypeEnum.RESOURCE) ? "resource" :
794 String componentName = componentType.name().toLowerCase();
795 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ARTIFACT_NOT_FOUND, componentName);
796 log.debug("addArtifact - Component artifact not found component Id {}, artifact id {}", componentId, artifactId);
797 return Either.right(responseFormat);
799 return Either.left(artifactResult.left().value());
802 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleCreate(String parentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, User user, ComponentTypeEnum componentType,
803 org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
805 String artifactId = null;
808 Either<byte[], ResponseFormat> payloadEither = validateInput(parentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceType, operationName, inTransaction);
809 if (payloadEither.isRight()) {
810 return Either.right(payloadEither.right().value());
812 byte[] decodedPayload = payloadEither.left().value();
813 convertParentType(componentType);
816 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Upload Artifact - lock ");
817 if (lockComponent.isRight()) {
818 handleAuditing(auditingAction, parent, parentId, user, null, null, null, lockComponent.right().value(), componentType, null);
819 return Either.right(lockComponent.right().value());
822 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
825 resultOp = createArtifact(parent, parentId, artifactInfo, decodedPayload, user, componentType, auditingAction, interfaceType, operationName);
829 unlockComponent(resultOp, parent, inTransaction);
836 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> lockComponentAndUpdateArtifact(String parentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user,
837 ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent, byte[] decodedPayload, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
839 convertParentType(componentType);
843 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Update Artifact - lock ");
845 if (lockComponent.isRight()) {
846 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right().value(), componentType, null);
847 return Either.right(lockComponent.right().value());
851 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
853 resultOp = updateArtifactFlow(parent, parentId, artifactId, artifactInfo, user, decodedPayload, componentType, auditingAction, interfaceType, operationName);
858 unlockComponent(resultOp, parent, inTransaction);
863 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdate(String parentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, String artifactId, User user,
864 ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
866 Either<byte[], ResponseFormat> payloadEither = validateInput(parentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceType, operationName, inTransaction);
868 if (payloadEither.isRight()) {
869 return Either.right(payloadEither.right().value());
871 byte[] decodedPayload = payloadEither.left().value();
873 return lockComponentAndUpdateArtifact(parentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, decodedPayload, interfaceType, operationName, shouldLock, inTransaction);
876 private Either<byte[], ResponseFormat> validateInput(String parentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType,
877 org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean inTransaction) {
879 Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
880 if (validateMd5.isRight()) {
881 ResponseFormat responseFormat = validateMd5.right().value();
882 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
883 return Either.right(responseFormat);
887 Either<ArtifactDefinition, ResponseFormat> validateResult = validateInput(parentId, artifactInfo, operation, artifactId, user, interfaceType, operationName, componentType, parent, inTransaction);
888 if (validateResult.isRight()) {
889 ResponseFormat responseFormat = validateResult.right().value();
890 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
891 return Either.right(validateResult.right().value());
894 Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
895 if (payloadEither.isRight()) {
896 ResponseFormat responseFormat = payloadEither.right().value();
897 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
898 log.debug("Error during handle payload");
899 return Either.right(responseFormat);
902 // validate heat parameters. this part must be after the parameters are
903 // extracted in "handlePayload"
904 Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers = validateAndConvertHeatParamers(artifactInfo, artifactInfo.getArtifactType());
905 if (validateAndConvertHeatParamers.isRight()) {
906 ResponseFormat responseFormat = validateAndConvertHeatParamers.right().value();
907 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, null, artifactId, responseFormat, componentType, null);
908 log.debug("Error during handle payload");
909 return Either.right(responseFormat);
911 return payloadEither;
914 public void handleAuditing(AuditingActionEnum auditingActionEnum, Component component, String componentId, User user, ArtifactDefinition artifactDefinition, String prevArtifactUuid, String currentArtifactUuid, ResponseFormat responseFormat,
915 ComponentTypeEnum componentTypeEnum, String resourceInstanceName) {
917 if (auditingActionEnum.getAuditingEsType().equals(AuditingTypesConstants.EXTERNAL_API_EVENT_TYPE)) {
921 EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = createArtifactAuditingFields(artifactDefinition, prevArtifactUuid, currentArtifactUuid);
925 user.setUserId("UNKNOWN");
927 switch (componentTypeEnum) {
930 Resource resource = (Resource) component;
931 if (resource == null) {
932 // In that case, component ID should be instead of name
933 resource = new Resource();
934 resource.setName(componentId);
936 componentsUtils.auditResource(responseFormat, user, resource, null, null, auditingActionEnum, auditingFields);
940 Service service = (Service) component;
941 if (service == null) {
942 // In that case, component ID should be instead of name
943 service = new Service();
944 service.setName(componentId);
946 componentsUtils.auditComponent(responseFormat, user, service, null, null, auditingActionEnum, ComponentTypeEnum.SERVICE, auditingFields);
949 case RESOURCE_INSTANCE:
950 if (resourceInstanceName == null) {
951 resourceInstanceName = getResourceInstanceNameFromComponent(component, componentId);
953 auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceInstanceName);
954 componentsUtils.auditComponent(responseFormat, user, component, null, null, auditingActionEnum, ComponentTypeEnum.RESOURCE_INSTANCE, auditingFields);
962 private String getResourceInstanceNameFromComponent(Component component, String componentId) {
963 ComponentInstance resourceInstance = component.getComponentInstances().stream().filter(p -> p.getUniqueId().equals(componentId)).findFirst().orElse(null);
964 String resourceInstanceName = null;
965 if (resourceInstance != null) {
966 resourceInstanceName = resourceInstance.getName();
968 return resourceInstanceName;
971 public EnumMap<AuditingFieldsKeysEnum, Object> createArtifactAuditingFields(ArtifactDefinition artifactDefinition, String prevArtifactUuid, String currentArtifactUuid) {
972 EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
973 // Putting together artifact info
974 String artifactData = buildAuditingArtifactData(artifactDefinition);
975 auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, artifactData);
976 auditingFields.put(AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID, prevArtifactUuid);
977 auditingFields.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, currentArtifactUuid);
978 return auditingFields;
983 private String buildAuditingArtifactData(ArtifactDefinition artifactDefinition) {
984 StringBuilder sb = new StringBuilder();
985 if (artifactDefinition != null) {
986 sb.append(artifactDefinition.getArtifactGroupType().getType()).append(",").append("'").append(artifactDefinition.getArtifactLabel()).append("'").append(",").append(artifactDefinition.getArtifactType()).append(",")
987 .append(artifactDefinition.getArtifactName()).append(",").append(artifactDefinition.getTimeout()).append(",").append(artifactDefinition.getEsId());
990 if (artifactDefinition.getArtifactVersion() != null) {
992 sb.append(artifactDefinition.getArtifactVersion());
997 if (artifactDefinition.getArtifactUUID() != null) {
998 sb.append(artifactDefinition.getArtifactUUID());
1003 return sb.toString();
1006 private Either<Boolean, ResponseFormat> validateMd5(String origMd5, String originData, byte[] payload, ArtifactOperationInfo operation) {
1008 if (origMd5 != null) {
1009 String encodeBase64Str = GeneralUtility.calculateMD5ByString(originData);
1011 if (false == encodeBase64Str.equals(origMd5)) {
1012 log.debug("The calculated md5 is different then the received one");
1013 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_MD5));
1016 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create) {
1017 log.debug("Missing md5 header during artifact create");
1018 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_MD5));
1021 if (payload != null && payload.length != 0) {
1022 log.debug("Cannot have payload while md5 header is missing");
1023 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1026 return Either.left(true);
1029 private Either<ArtifactDefinition, ResponseFormat> validateInput(String parentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, String artifactId, User user, String interfaceName, String operationName,
1030 ComponentTypeEnum componentType, Component parentComponent, boolean inTransaction) {
1032 Either<Boolean, ResponseFormat> validateInformationalArtifactRes = validateInformationalArtifact(artifactInfo, parentComponent);
1033 if (validateInformationalArtifactRes.isRight()) {
1034 return Either.right(validateInformationalArtifactRes.right().value());
1036 Either<Boolean, ResponseFormat> validateAndSetArtifactname = validateAndSetArtifactname(artifactInfo);
1037 if (validateAndSetArtifactname.isRight()) {
1038 return Either.right(validateAndSetArtifactname.right().value());
1040 Either<ArtifactDefinition, ResponseFormat> artifactById = findArtifactOnParentComponent(parentComponent, componentType, parentId, operation, artifactId);
1041 if (artifactById.isRight()) {
1042 return Either.right(artifactById.right().value());
1044 ArtifactDefinition currentArtifactInfo = artifactById.left().value();
1045 if (operationName != null && interfaceName != null) {
1046 operationName = operationName.toLowerCase();
1047 interfaceName = interfaceName.toLowerCase();
1049 Either<ActionStatus, ResponseFormat> logicalNameStatus = handleArtifactLabel(parentId, operation, artifactId, artifactInfo, interfaceName, operationName, currentArtifactInfo, componentType, inTransaction);
1050 if (logicalNameStatus.isRight()) {
1051 return Either.right(logicalNameStatus.right().value());
1053 // This is a patch to block possibility of updating service api fields
1054 // through other artifacts flow
1056 if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.Create) {
1057 checkAndSetUnUpdatableFields(user, artifactInfo, currentArtifactInfo, (operationName != null ? ArtifactGroupTypeEnum.LIFE_CYCLE : ArtifactGroupTypeEnum.INFORMATIONAL));
1059 checkCreateFields(user, artifactInfo, (operationName != null ? ArtifactGroupTypeEnum.LIFE_CYCLE : ArtifactGroupTypeEnum.INFORMATIONAL));
1062 composeArtifactId(parentId, artifactId, artifactInfo, interfaceName, operationName);
1063 if (currentArtifactInfo != null) {
1064 artifactInfo.setMandatory(currentArtifactInfo.getMandatory());
1067 // artifactGroupType is not allowed to be updated
1068 if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.Create) {
1069 Either<ArtifactDefinition, ResponseFormat> validateGroupType = validateOrSetArtifactGroupType(artifactInfo, currentArtifactInfo);
1070 if (validateGroupType.isRight()) {
1071 return Either.right(validateGroupType.right().value());
1075 NodeTypeEnum parentType = convertParentType(componentType);
1078 boolean isCreate = operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create;
1080 if (isDeploymentArtifact(artifactInfo)) {
1081 Either<Boolean, ResponseFormat> deploymentValidationResult = validateDeploymentArtifact(parentComponent, parentId, user.getUserId(), isCreate, artifactInfo, currentArtifactInfo, parentType);
1082 if (deploymentValidationResult.isRight()) {
1083 return Either.right(deploymentValidationResult.right().value());
1086 artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
1089 * if (informationDeployedArtifactsBusinessLogic. isInformationDeployedArtifact(artifactInfo)) { Either<Boolean, ResponseFormat> validationResult = informationDeployedArtifactsBusinessLogic.validateArtifact( isCreate, artifactInfo,
1090 * parentComponent, parentType); if (validationResult.isRight()) { return Either.right(validationResult.right().value()); } }
1094 Either<Boolean, ResponseFormat> descriptionResult = validateAndCleanDescription(artifactInfo);
1095 if (descriptionResult.isRight()) {
1096 return Either.right(descriptionResult.right().value());
1099 if (currentArtifactInfo != null && currentArtifactInfo.getArtifactGroupType().equals(ArtifactGroupTypeEnum.SERVICE_API)) {
1100 Either<ActionStatus, ResponseFormat> validateServiceApiType = validateArtifactType(user.getUserId(), artifactInfo, parentType);
1101 if (validateServiceApiType.isRight()) {
1102 return Either.right(validateServiceApiType.right().value());
1104 // Change of type is not allowed and should be ignored
1106 artifactInfo.setArtifactType(ARTIFACT_TYPE_OTHER);
1108 Either<Boolean, ResponseFormat> validateUrl = validateAndServiceApiUrl(artifactInfo);
1109 if (validateUrl.isRight()) {
1110 return Either.right(validateUrl.right().value());
1113 Either<Boolean, ResponseFormat> validateUpdate = validateFirstUpdateHasPayload(artifactInfo, currentArtifactInfo);
1114 if (validateUpdate.isRight()) {
1115 log.debug("serviceApi first update cnnot be without payload.");
1116 return Either.right(validateUpdate.right().value());
1119 Either<ActionStatus, ResponseFormat> validateArtifactType = validateArtifactType(user.getUserId(), artifactInfo, parentType);
1120 if (validateArtifactType.isRight()) {
1121 return Either.right(validateArtifactType.right().value());
1123 if (artifactInfo.getApiUrl() != null) {
1124 artifactInfo.setApiUrl(null);
1125 log.error("Artifact URL cannot be set through this API - ignoring");
1128 if (artifactInfo.getServiceApi() != null) {
1129 if (artifactInfo.getServiceApi()) {
1130 artifactInfo.setServiceApi(false);
1131 log.error("Artifact service API flag cannot be changed - ignoring");
1136 return Either.left(artifactInfo);
1139 private Either<ArtifactDefinition, ResponseFormat> findArtifactOnParentComponent(Component parentComponent, ComponentTypeEnum componentType, String parentId, ArtifactOperationInfo operation, String artifactId) {
1141 Either<ArtifactDefinition, ResponseFormat> result = null;
1142 ArtifactDefinition foundArtifact = null;
1143 if (StringUtils.isNotEmpty(artifactId)) {
1144 foundArtifact = findArtifact(parentComponent, componentType, parentId, artifactId);
1146 if (foundArtifact != null && operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create) {
1147 log.debug("Artifact {} already exist", artifactId);
1148 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, foundArtifact.getArtifactLabel()));
1150 if (foundArtifact == null && operation.getArtifactOperationEnum() != ArtifactOperationEnum.Create) {
1151 log.debug("The artifact {} was not found on parent {}. ", artifactId, parentId);
1152 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ""));
1154 if (result == null) {
1155 result = Either.left(foundArtifact);
1160 private ArtifactDefinition findArtifact(Component parentComponent, ComponentTypeEnum componentType, String parentId, String artifactId) {
1161 ArtifactDefinition foundArtifact;
1162 if (parentComponent.getUniqueId().equals(parentId)) {
1163 foundArtifact = artifactsResolver.findArtifactOnComponent(parentComponent, componentType, artifactId);
1165 ComponentInstance instance = findComponentInstance(parentId, parentComponent);
1166 foundArtifact = artifactsResolver.findArtifactOnComponentInstance(instance, artifactId);
1168 return foundArtifact;
1171 private Either<Boolean, ResponseFormat> validateInformationalArtifact(ArtifactDefinition artifactInfo, Component parentComponent) {
1172 ComponentTypeEnum parentComponentType = parentComponent.getComponentType();
1173 ArtifactGroupTypeEnum groupType = artifactInfo.getArtifactGroupType();
1174 Either<Boolean, ResponseFormat> validationResult = Either.left(true);
1175 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
1176 if (artifactType == null) {
1177 validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType()));
1178 } else if (parentComponentType == ComponentTypeEnum.RESOURCE && groupType == ArtifactGroupTypeEnum.INFORMATIONAL) {
1179 String artifactTypeName = artifactType.getType();
1180 ResourceTypeEnum parentResourceType = ((Resource) parentComponent).getResourceType();
1181 Map<String, ArtifactTypeConfig> resourceInformationalArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceInformationalArtifacts();
1182 Set<String> validArtifactTypes = resourceInformationalArtifacts.keySet();
1183 if (!validArtifactTypes.contains(artifactTypeName)) {
1184 validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactTypeName));
1186 List<String> validResourceType = resourceInformationalArtifacts.get(artifactTypeName).getValidForResourceTypes();
1187 if (!validResourceType.contains(parentResourceType.name())) {
1188 validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactTypeName));
1192 return validationResult;
1195 private NodeTypeEnum convertParentType(ComponentTypeEnum componentType) {
1196 if (componentType.equals(ComponentTypeEnum.RESOURCE)) {
1197 return NodeTypeEnum.Resource;
1198 } else if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) {
1199 return NodeTypeEnum.ResourceInstance;
1201 return NodeTypeEnum.Service;
1205 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete(String parentId, String artifactId, User user, AuditingActionEnum auditingAction, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent,
1206 String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
1208 NodeTypeEnum parentType = convertParentType(componentType);
1209 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
1210 Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> getArtifactRes = null;
1211 ArtifactDefinition foundArtifact = null;
1212 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
1213 Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getContainerRes = null;
1214 org.openecomp.sdc.be.model.Component fetchedContainerComponent = null;
1215 boolean isDuplicated = false;
1217 Either<Boolean, StorageOperationStatus> needCloneRes = null;
1220 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Delete Artifact - lock resource: ");
1221 if (lockComponent.isRight()) {
1222 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right().value(), componentType, null);
1223 resultOp = Either.right(lockComponent.right().value());
1226 if (resultOp == null) {
1227 log.debug("Going to fetch the container component {}. ", parent.getUniqueId());
1228 getContainerRes = toscaOperationFacade.getToscaElement(parent.getUniqueId());
1229 if (getContainerRes.isRight()) {
1230 log.debug("Failed to fetch the container component {}. ", parentId);
1231 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(getContainerRes.right().value()), artifactId);
1232 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1233 resultOp = Either.right(responseFormat);
1236 if (resultOp == null) {
1237 fetchedContainerComponent = getContainerRes.left().value();
1238 log.debug("Going to find the artifact {} on the component {}", artifactId, fetchedContainerComponent.getUniqueId());
1239 getArtifactRes = findArtifact(artifactId, fetchedContainerComponent, parentId, componentType);
1240 if (getArtifactRes.isRight()) {
1241 log.debug("Failed to find the artifact {} belonging to {} on the component {}", artifactId, parentId, fetchedContainerComponent.getUniqueId());
1242 responseFormat = componentsUtils.getResponseFormatByArtifactId(getArtifactRes.right().value(), artifactId);
1243 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1244 resultOp = Either.right(responseFormat);
1246 foundArtifact = getArtifactRes.left().value().getLeft();
1247 esId = foundArtifact.getEsId();
1250 if (resultOp == null && StringUtils.isNotEmpty(esId)) {
1251 needCloneRes = artifactToscaOperation.isCloneNeeded(parent.getUniqueId(), foundArtifact, convertParentType(parent.getComponentType()));
1252 if (needCloneRes.isRight()) {
1253 log.debug("Failed to delete or update the artifact {}. Parent uniqueId is {}", artifactId, parentId);
1254 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(needCloneRes.right().value()), foundArtifact.getArtifactDisplayName());
1255 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1256 resultOp = Either.right(responseFormat);
1259 if (resultOp == null) {
1260 Either<ArtifactDataDefinition, StorageOperationStatus> updatedArtifactRes = deleteOrUpdateArtifactOnGraph(parent, parentId, artifactId, parentType, foundArtifact, needCloneRes.left().value());
1261 if (updatedArtifactRes.isRight()) {
1262 log.debug("Failed to delete or update the artifact {}. Parent uniqueId is {}", artifactId, parentId);
1263 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updatedArtifactRes.right().value()), foundArtifact.getArtifactDisplayName());
1264 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1265 resultOp = Either.right(responseFormat);
1267 isDuplicated = updatedArtifactRes.left().value().getDuplicated();
1271 if (resultOp == null && (!needCloneRes.left().value() && !isDuplicated)) {
1272 log.debug("Going to delete the artifact {} from the database. ", artifactId);
1273 CassandraOperationStatus cassandraStatus = artifactCassandraDao.deleteArtifact(esId);
1274 if (cassandraStatus != CassandraOperationStatus.OK) {
1275 log.debug("Failed to delete the artifact {} from the database. ", artifactId);
1276 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(convertToStorageOperationStatus(cassandraStatus)), foundArtifact.getArtifactDisplayName());
1277 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1278 resultOp = Either.right(responseFormat);
1281 if (resultOp == null && componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1283 List<GroupInstance> updatedGroupInstances = getUpdatedGroupInstances(artifactId, foundArtifact, getArtifactRes.left().value().getRight().getGroupInstances());
1284 if (CollectionUtils.isNotEmpty(updatedGroupInstances)) {
1285 Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(fetchedContainerComponent, componentType, parentId, updatedGroupInstances);
1286 if (status.isRight()) {
1287 log.debug("Failed to update groups of the component {}. ", fetchedContainerComponent.getUniqueId());
1288 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status.right().value()), foundArtifact.getArtifactDisplayName());
1289 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1290 resultOp = Either.right(responseFormat);
1294 if (resultOp == null && componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1295 StorageOperationStatus status = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentType);
1296 if (status != StorageOperationStatus.OK) {
1297 log.debug("Failed to generate new customization UUID for the component instance {}. ", parentId);
1298 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status), foundArtifact.getArtifactDisplayName());
1299 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1300 resultOp = Either.right(responseFormat);
1303 if (resultOp == null && componentType != ComponentTypeEnum.RESOURCE_INSTANCE) {
1304 List<GroupDataDefinition> updatedGroups = getUpdatedGroups(artifactId, foundArtifact, fetchedContainerComponent.getGroups());
1305 if (CollectionUtils.isNotEmpty(updatedGroups)) {
1306 Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(fetchedContainerComponent, componentType, updatedGroups);
1307 if (status.isRight()) {
1308 log.debug("Failed to update groups of the component {}. ", fetchedContainerComponent.getUniqueId());
1309 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status.right().value()), foundArtifact.getArtifactDisplayName());
1310 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1311 resultOp = Either.right(responseFormat);
1315 if (resultOp == null) {
1316 resultOp = Either.left(Either.left(foundArtifact));
1317 handleAuditing(auditingAction, parent, parentId, user, foundArtifact, null, artifactId, responseFormat, componentType, null);
1322 unlockComponent(resultOp, parent, inTransaction);
1327 private List<GroupDataDefinition> getUpdatedGroups(String artifactId, ArtifactDefinition foundArtifact, List<GroupDefinition> groups) {
1328 List<GroupDataDefinition> updatedGroups = new ArrayList<>();
1329 boolean isUpdated = false;
1330 if (groups != null) {
1331 for (GroupDefinition group : groups) {
1333 if (CollectionUtils.isNotEmpty(group.getArtifacts()) && group.getArtifacts().contains(artifactId)) {
1334 group.getArtifacts().remove(artifactId);
1337 if (CollectionUtils.isNotEmpty(group.getArtifactsUuid()) && group.getArtifactsUuid().contains(foundArtifact.getArtifactUUID())) {
1338 group.getArtifacts().remove(foundArtifact.getArtifactUUID());
1342 updatedGroups.add(group);
1346 return updatedGroups;
1349 private List<GroupInstance> getUpdatedGroupInstances(String artifactId, ArtifactDefinition foundArtifact, List<GroupInstance> groupInstances) {
1350 List<GroupInstance> updatedGroupInstances = new ArrayList<>();
1351 if (CollectionUtils.isNotEmpty(groupInstances)) {
1352 boolean isUpdated = false;
1353 for (GroupInstance groupInstance : groupInstances) {
1355 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifacts()) && groupInstance.getGroupInstanceArtifacts().contains(artifactId)) {
1356 groupInstance.getGroupInstanceArtifacts().remove(artifactId);
1359 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifactsUuid()) && groupInstance.getGroupInstanceArtifactsUuid().contains(foundArtifact.getArtifactUUID())) {
1360 groupInstance.getGroupInstanceArtifactsUuid().remove(foundArtifact.getArtifactUUID());
1364 updatedGroupInstances.add(groupInstance);
1368 return updatedGroupInstances;
1371 private Either<ArtifactDataDefinition, StorageOperationStatus> deleteOrUpdateArtifactOnGraph(Component component, String parentId, String artifactId, NodeTypeEnum parentType, ArtifactDefinition foundArtifact, Boolean cloneIsNeeded) {
1373 Either<ArtifactDataDefinition, StorageOperationStatus> result;
1374 boolean isMandatory = foundArtifact.getMandatory() || foundArtifact.getServiceApi();
1375 String componentId = component.getUniqueId();
1376 String instanceId = componentId.equals(parentId) ? null : parentId;
1378 log.debug("Going to update mandatory artifact {} from the component {}", artifactId, parentId);
1379 resetMandatoryArtifactFields(foundArtifact);
1380 result = artifactToscaOperation.updateArtifactOnGraph(componentId, foundArtifact, parentType, artifactId, instanceId, true);
1381 } else if (cloneIsNeeded) {
1382 log.debug("Going to clone artifacts and to delete the artifact {} from the component {}", artifactId, parentId);
1383 result = artifactToscaOperation.deleteArtifactWithClonnigOnGraph(componentId, foundArtifact, parentType, instanceId, false);
1385 log.debug("Going to delete the artifact {} from the component {}", artifactId, parentId);
1386 result = artifactToscaOperation.removeArtifactOnGraph(foundArtifact, componentId, instanceId, parentType, false);
1391 private Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> findArtifact(String artifactId, Component fetchedContainerComponent, String parentId, ComponentTypeEnum componentType) {
1393 Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> result = null;
1394 Map<String, ArtifactDefinition> artifacts = new HashMap<>();
1395 ComponentInstance foundInstance = null;
1396 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE && StringUtils.isNotEmpty(parentId)) {
1397 Optional<ComponentInstance> componentInstanceOpt = fetchedContainerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(parentId)).findFirst();
1398 if (!componentInstanceOpt.isPresent()) {
1399 result = Either.right(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER);
1401 foundInstance = componentInstanceOpt.get();
1402 fetchArtifactsFromInstance(artifactId, artifacts, foundInstance);
1405 fetchArtifactsFromComponent(artifactId, fetchedContainerComponent, artifacts);
1407 if (result == null) {
1408 if (artifacts.containsKey(artifactId)) {
1409 result = Either.left(new ImmutablePair<>(artifacts.get(artifactId), foundInstance));
1411 result = Either.right(ActionStatus.ARTIFACT_NOT_FOUND);
1417 private void fetchArtifactsFromComponent(String artifactId, Component component, Map<String, ArtifactDefinition> artifacts) {
1418 Map<String, ArtifactDefinition> currArtifacts;
1419 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getDeploymentArtifacts())) {
1420 currArtifacts = component.getDeploymentArtifacts().values().stream().collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1421 if (MapUtils.isNotEmpty(currArtifacts)) {
1422 artifacts.putAll(currArtifacts);
1425 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getArtifacts())) {
1426 currArtifacts = component.getArtifacts().values().stream().collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1427 if (MapUtils.isNotEmpty(currArtifacts)) {
1428 artifacts.putAll(currArtifacts);
1431 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getArtifacts())) {
1432 currArtifacts = component.getToscaArtifacts().values().stream().collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1433 if (MapUtils.isNotEmpty(currArtifacts)) {
1434 artifacts.putAll(currArtifacts);
1439 private void fetchArtifactsFromInstance(String artifactId, Map<String, ArtifactDefinition> artifacts, ComponentInstance instance) {
1440 Map<String, ArtifactDefinition> currArtifacts;
1441 if (MapUtils.isNotEmpty(instance.getDeploymentArtifacts())) {
1442 currArtifacts = instance.getDeploymentArtifacts().values().stream().collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1443 if (MapUtils.isNotEmpty(currArtifacts)) {
1444 artifacts.putAll(currArtifacts);
1447 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(instance.getArtifacts())) {
1448 currArtifacts = instance.getArtifacts().values().stream().collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1449 if (MapUtils.isNotEmpty(currArtifacts)) {
1450 artifacts.putAll(currArtifacts);
1455 private StorageOperationStatus convertToStorageOperationStatus(CassandraOperationStatus cassandraStatus) {
1456 StorageOperationStatus result;
1457 switch (cassandraStatus) {
1459 result = StorageOperationStatus.OK;
1462 result = StorageOperationStatus.NOT_FOUND;
1464 case CLUSTER_NOT_CONNECTED:
1465 case KEYSPACE_NOT_CONNECTED:
1466 result = StorageOperationStatus.CONNECTION_FAILURE;
1469 result = StorageOperationStatus.GENERAL_ERROR;
1475 private void resetMandatoryArtifactFields(ArtifactDefinition fetchedArtifact) {
1476 if (fetchedArtifact != null) {
1477 log.debug("Going to reset mandatory artifact {} fields. ", fetchedArtifact.getUniqueId());
1478 fetchedArtifact.setEsId("");
1479 fetchedArtifact.setArtifactName("");
1480 fetchedArtifact.setDescription("");
1481 fetchedArtifact.setApiUrl("");
1482 fetchedArtifact.setArtifactChecksum("");
1483 nodeTemplateOperation.setDefaultArtifactTimeout(fetchedArtifact.getArtifactGroupType(), fetchedArtifact);
1484 fetchedArtifact.setArtifactUUID("");
1485 long time = System.currentTimeMillis();
1486 fetchedArtifact.setPayloadUpdateDate(time);
1487 fetchedArtifact.setHeatParameters(null);
1488 fetchedArtifact.setHeatParamsUpdateDate(null);
1492 private StorageOperationStatus generateCustomizationUUIDOnInstance(String componentId, String instanceId, ComponentTypeEnum componentType) {
1493 StorageOperationStatus error = StorageOperationStatus.OK;
1494 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1495 log.debug("Need to re-generate customization UUID for instance {}", instanceId);
1496 error = toscaOperationFacade.generateCustomizationUUIDOnInstance(componentId, instanceId);
1501 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDownload(String componentId, String artifactId, User user, AuditingActionEnum auditingAction, ComponentTypeEnum componentType,
1502 org.openecomp.sdc.be.model.Component parent, boolean shouldLock, boolean inTransaction) {
1503 Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(componentId, artifactId, componentType, parent.getUniqueId());
1504 if (artifactById.isRight()) {
1505 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(artifactById.right().value());
1506 log.debug("Error when getting artifact info by id{}, error: {}", artifactId, actionStatus.name());
1507 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(actionStatus, "");
1508 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
1509 return Either.right(responseFormat);
1511 ArtifactDefinition artifactDefinition = artifactById.left().value();
1512 if (artifactDefinition == null) {
1513 log.debug("Empty artifact definition returned from DB by artifact id {}", artifactId);
1514 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, "");
1515 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
1516 return Either.right(responseFormat);
1518 Either<ArtifactDefinition, Operation> insideEither = Either.left(artifactDefinition);
1519 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
1520 handleAuditing(auditingAction, parent, componentId, user, artifactDefinition, null, artifactId, responseFormat, componentType, null);
1521 return Either.left(insideEither);
1524 private Either<ArtifactDefinition, ResponseFormat> fetchCurrentArtifact(String parentId, ArtifactOperationInfo operation, String artifactId) {
1525 Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(parentId, artifactId);
1526 if (!(operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create) && artifactById.isRight()) {
1527 // in case of update artifact must be
1528 BeEcompErrorManager.getInstance().logBeArtifactMissingError("Artifact Update / Upload", artifactId);
1529 log.debug("Failed to fetch artifact {}. error: {}", artifactId, artifactById.right().value());
1530 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(artifactById.right().value()), artifactId));
1532 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create && artifactById.isLeft()) {
1533 log.debug("Artifact {} already exist", artifactId);
1534 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactById.left().value().getArtifactLabel()));
1536 ArtifactDefinition currentArtifactInfo = null;
1537 if (artifactById.isLeft()) {
1538 // get previous value
1539 currentArtifactInfo = artifactById.left().value();
1541 return Either.left(currentArtifactInfo);
1544 private Either<ActionStatus, ResponseFormat> handleArtifactLabel(String componentId, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, String interfaceName, String operationName,
1545 ArtifactDefinition currentArtifactInfo, ComponentTypeEnum componentType, boolean inTransaction) {
1546 String artifactLabel = artifactInfo.getArtifactLabel();
1548 if (operationName == null && (artifactInfo.getArtifactLabel() == null || artifactInfo.getArtifactLabel().isEmpty())) {
1549 BeEcompErrorManager.getInstance().logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel");
1550 log.debug("missing artifact logical name for component {}", componentId);
1551 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_LABEL));
1553 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create && !artifactInfo.getMandatory()) {
1555 if (operationName != null) {
1556 if (artifactInfo.getArtifactLabel() != null && !operationName.equals(artifactInfo.getArtifactLabel())) {
1557 log.debug("artifact label cannot be set {}", artifactLabel);
1558 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_LOGICAL_NAME_CANNOT_BE_CHANGED));
1560 artifactLabel = operationName;
1563 String displayName = artifactInfo.getArtifactDisplayName();
1564 if (displayName == null || displayName.isEmpty())
1565 displayName = artifactLabel;
1566 displayName = ValidationUtils.cleanArtifactDisplayName(displayName);
1567 // if (!ValidationUtils.validateArtifactDisplayName(displayName)) {
1568 // log.debug("Invalid format form Artifact displayName : {}", displayName);
1569 // return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1571 artifactInfo.setArtifactDisplayName(displayName);
1573 if (!ValidationUtils.validateArtifactLabel(artifactLabel)) {
1574 log.debug("Invalid format form Artifact label : {}", artifactLabel);
1575 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1577 artifactLabel = ValidationUtils.normalizeArtifactLabel(artifactLabel);
1579 if (artifactLabel.isEmpty()) {
1580 log.debug("missing normalized artifact logical name for component {}", componentId);
1581 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_LABEL));
1584 if (!ValidationUtils.validateArtifactLabelLength(artifactLabel)) {
1585 log.debug("Invalid lenght form Artifact label : {}", artifactLabel);
1586 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_LABEL, String.valueOf(ValidationUtils.ARTIFACT_LABEL_LENGTH)));
1588 if (!validateLabelUniqueness(componentId, artifactLabel, componentType)) {
1589 log.debug("Non unique Artifact label : {}", artifactLabel);
1590 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactLabel));
1593 artifactInfo.setArtifactLabel(artifactLabel);
1595 if (currentArtifactInfo != null && !currentArtifactInfo.getArtifactLabel().equals(artifactInfo.getArtifactLabel())) {
1596 log.info("Logical artifact's name cannot be changed {}", artifactId);
1597 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_LOGICAL_NAME_CANNOT_BE_CHANGED));
1599 return Either.left(ActionStatus.OK);
1602 private boolean validateLabelUniqueness(String parentId, String artifactLabel, ComponentTypeEnum componentType) {
1603 boolean isUnique = true;
1604 if (componentType.equals(ComponentTypeEnum.RESOURCE)) {
1607 // Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifacts = artifactOperation.getArtifacts(parentId, parentType, inTransaction);
1608 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifacts = artifactToscaOperation.getArtifacts(parentId);
1609 if (artifacts.isLeft()) {
1610 for (String label : artifacts.left().value().keySet()) {
1611 if (label.equals(artifactLabel)) {
1617 if (componentType.equals(ComponentTypeEnum.RESOURCE)) {
1618 Either<Map<String, InterfaceDefinition>, StorageOperationStatus> allInterfacesOfResource = interfaceLifecycleOperation.getAllInterfacesOfResource(parentId, true, true);
1619 if (allInterfacesOfResource.isLeft()) {
1620 for (InterfaceDefinition interace : allInterfacesOfResource.left().value().values()) {
1621 for (Operation operation : interace.getOperationsMap().values()) {
1622 if (operation.getImplementation() != null && operation.getImplementation().getArtifactLabel().equals(artifactLabel)) {
1633 // ***************************************************************
1635 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> createArtifact(org.openecomp.sdc.be.model.Component parent, String parentId, ArtifactDefinition artifactInfo, byte[] decodedPayload, User user,
1636 ComponentTypeEnum componentTypeEnum, AuditingActionEnum auditingActionEnum, String interfaceType, String operationName) {
1638 ESArtifactData artifactData = createEsArtifactData(artifactInfo, decodedPayload);
1639 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
1640 Either<ArtifactDefinition, Operation> insideEither = null;
1641 ComponentInstance foundInstance = findComponentInstance(parentId, parent);
1642 String instanceId = null;
1643 String instanceName = null;
1644 if (foundInstance != null) {
1645 instanceId = foundInstance.getUniqueId();
1646 instanceName = foundInstance.getName();
1648 if (artifactData == null) {
1649 BeEcompErrorManager.getInstance().logBeDaoSystemError("Upload Artifact");
1650 log.debug("Failed to create artifact object for ES.");
1651 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
1652 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, null);
1653 resultOp = Either.right(responseFormat);
1657 // set on graph object id of artifact in ES!
1658 artifactInfo.setEsId(artifactData.getId());
1660 boolean isLeft = false;
1661 String artifactUniqueId = null;
1662 StorageOperationStatus error = null;
1663 if (interfaceType != null && operationName != null) {
1664 // lifecycle artifact
1665 Operation operation = convertToOperation(artifactInfo, operationName);
1667 Either<Operation, StorageOperationStatus> result = interfaceLifecycleOperation.updateInterfaceOperation(parentId, interfaceType, operationName, operation);
1669 isLeft = result.isLeft();
1671 artifactUniqueId = result.left().value().getImplementation().getUniqueId();
1672 result.left().value().getImplementation();
1674 insideEither = Either.right(result.left().value());
1675 resultOp = Either.left(insideEither);
1677 error = result.right().value();
1680 // information/deployment/api aritfacts
1681 log.trace("Try to create entry on graph");
1682 NodeTypeEnum nodeType = convertParentType(componentTypeEnum);
1683 Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.addArifactToComponent(artifactInfo, parent.getUniqueId(), nodeType, true, instanceId);
1685 isLeft = result.isLeft();
1687 artifactUniqueId = result.left().value().getUniqueId();
1688 result.left().value();
1690 insideEither = Either.left(result.left().value());
1691 resultOp = Either.left(insideEither);
1693 error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentTypeEnum);
1694 if (error != StorageOperationStatus.OK) {
1699 error = result.right().value();
1703 boolean res = saveArtifacts(artifactData, parentId, false);
1704 // String uniqueId = artifactDefinition.getUniqueId();
1707 log.debug("Artifact saved into ES - {}", artifactUniqueId);
1709 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
1710 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, artifactUniqueId, artifactUniqueId, responseFormat, componentTypeEnum, instanceName);
1713 BeEcompErrorManager.getInstance().logBeDaoSystemError("Upload Artifact");
1714 log.debug("Failed to save the artifact.");
1715 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
1716 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, artifactUniqueId, responseFormat, componentTypeEnum, instanceName);
1718 resultOp = Either.right(responseFormat);
1722 log.debug("Failed to create entry on graph for artifact {}", artifactInfo.getArtifactName());
1723 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(error), artifactInfo.getArtifactDisplayName());
1724 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, instanceName);
1725 resultOp = Either.right(responseFormat);
1731 private ComponentInstance findComponentInstance(String componentInstanceId, Component containerComponent) {
1732 ComponentInstance foundInstance = null;
1733 if (CollectionUtils.isNotEmpty(containerComponent.getComponentInstances())) {
1734 foundInstance = containerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(componentInstanceId)).findFirst().orElse(null);
1736 return foundInstance;
1739 private Either<Boolean, ResponseFormat> validateDeploymentArtifact(Component parentComponent, String parentId, String userId, boolean isCreate, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, NodeTypeEnum parentType) {
1741 Either<Boolean, ResponseFormat> result = Either.left(true);
1742 Wrapper<ResponseFormat> responseWrapper = new Wrapper<ResponseFormat>();
1744 validateArtifactTypeExists(responseWrapper, artifactInfo);
1746 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
1748 Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts = fillDeploymentArtifactTypeConf(parentType);
1750 if (responseWrapper.isEmpty()) {
1751 validateDeploymentArtifactConf(artifactInfo, responseWrapper, artifactType, resourceDeploymentArtifacts);
1754 if (responseWrapper.isEmpty()) {
1755 // Common code for all types
1756 // not allowed to change artifactType
1758 Either<Boolean, ResponseFormat> validateServiceApiType = validateArtifactTypeNotChanged(artifactInfo, currentArtifact);
1759 if (validateServiceApiType.isRight()) {
1760 responseWrapper.setInnerElement(validateServiceApiType.right().value());
1764 if (responseWrapper.isEmpty()) {
1765 if (parentType.equals(NodeTypeEnum.Resource)) {
1766 // if (parentComponent instanceof Resource) {
1767 Resource resource = (Resource) parentComponent;
1768 ResourceTypeEnum resourceType = resource.getResourceType();
1769 ArtifactTypeConfig config = resourceDeploymentArtifacts.get(artifactType.getType());
1770 if (config == null) {
1771 responseWrapper.setInnerElement(ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType()));
1773 List<String> myList = config.getValidForResourceTypes();
1774 Either<Boolean, ResponseFormat> either = validateResourceType(resourceType, artifactInfo, myList);
1775 if (either.isRight()) {
1776 responseWrapper.setInnerElement(either.right().value());
1781 if (responseWrapper.isEmpty()) {
1782 validateFileExtension(responseWrapper, () -> getDeploymentArtifactTypeConfig(parentType, artifactType), artifactInfo, parentType, artifactType);
1785 if (responseWrapper.isEmpty() && !NodeTypeEnum.ResourceInstance.equals(parentType)) {
1786 String artifactName = artifactInfo.getArtifactName();
1787 if (isCreate || !artifactName.equalsIgnoreCase(currentArtifact.getArtifactName())) {
1788 validateSingleDeploymentArtifactName(responseWrapper, artifactName, parentComponent, parentType);
1792 if (responseWrapper.isEmpty()) {
1793 switch (artifactType) {
1797 result = validateHeatDeploymentArtifact(parentComponent, userId, isCreate, artifactInfo, currentArtifact, parentType);
1801 result = validateHeatEnvDeploymentArtifact(parentComponent, parentId, userId, isCreate, artifactInfo, parentType);
1802 artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
1805 case DCAE_INVENTORY_TOSCA:
1806 case DCAE_INVENTORY_JSON:
1807 case DCAE_INVENTORY_POLICY:
1808 // Validation is done in handle payload.
1809 case DCAE_INVENTORY_DOC:
1810 case DCAE_INVENTORY_BLUEPRINT:
1811 case DCAE_INVENTORY_EVENT:
1812 // No specific validation
1814 artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
1820 if (!responseWrapper.isEmpty()) {
1821 result = Either.right(responseWrapper.getInnerElement());
1826 private void validateDeploymentArtifactConf(ArtifactDefinition artifactInfo, Wrapper<ResponseFormat> responseWrapper, ArtifactTypeEnum artifactType, Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts) {
1827 if ((resourceDeploymentArtifacts == null) || !resourceDeploymentArtifacts.containsKey(artifactType.name())) {
1828 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType());
1829 responseWrapper.setInnerElement(responseFormat);
1830 log.debug("Artifact Type: {} Not found !", artifactInfo.getArtifactType());
1834 private Map<String, ArtifactTypeConfig> fillDeploymentArtifactTypeConf(NodeTypeEnum parentType) {
1835 Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts = null;
1836 if (parentType.equals(NodeTypeEnum.Resource)) {
1837 resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceDeploymentArtifacts();
1838 } else if (parentType.equals(NodeTypeEnum.ResourceInstance)) {
1839 resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceInstanceDeploymentArtifacts();
1841 resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getServiceDeploymentArtifacts();
1843 return resourceDeploymentArtifacts;
1846 public void validateArtifactTypeExists(Wrapper<ResponseFormat> responseWrapper, ArtifactDefinition artifactInfo) {
1847 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
1848 if (artifactType == null) {
1849 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType());
1850 responseWrapper.setInnerElement(responseFormat);
1851 log.debug("Artifact Type: {} Not found !", artifactInfo.getArtifactType());
1855 private ArtifactTypeConfig getDeploymentArtifactTypeConfig(NodeTypeEnum parentType, ArtifactTypeEnum artifactType) {
1856 ArtifactTypeConfig retConfig = null;
1857 String fileType = artifactType.getType();
1858 if (parentType.equals(NodeTypeEnum.Resource)) {
1859 retConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceDeploymentArtifacts().get(fileType);
1860 } else if (parentType.equals(NodeTypeEnum.Service)) {
1861 retConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getServiceDeploymentArtifacts().get(fileType);
1862 } else if (parentType.equals(NodeTypeEnum.ResourceInstance)) {
1863 retConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceInstanceDeploymentArtifacts().get(fileType);
1868 private Either<Boolean, ResponseFormat> extractHeatParameters(ArtifactDefinition artifactInfo) {
1869 // extract heat parameters
1870 if (artifactInfo.getPayloadData() != null) {
1871 String heatDecodedPayload = new String(Base64.decodeBase64(artifactInfo.getPayloadData()));
1872 Either<List<HeatParameterDefinition>, ResultStatusEnum> heatParameters = ImportUtils.getHeatParamsWithoutImplicitTypes(heatDecodedPayload, artifactInfo.getArtifactType());
1873 if (heatParameters.isRight() && (!heatParameters.right().value().equals(ResultStatusEnum.ELEMENT_NOT_FOUND))) {
1874 log.info("failed to parse heat parameters ");
1875 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactInfo.getArtifactType());
1876 return Either.right(responseFormat);
1877 } else if (heatParameters.isLeft() && heatParameters.left().value() != null) {
1878 artifactInfo.setListHeatParameters(heatParameters.left().value());
1881 return Either.left(true);
1886 public void validateFileExtension(Wrapper<ResponseFormat> responseWrapper, IDeploymentArtifactTypeConfigGetter deploymentConfigGetter, ArtifactDefinition artifactInfo, NodeTypeEnum parentType, ArtifactTypeEnum artifactType) {
1887 String fileType = artifactType.getType();
1888 List<String> acceptedTypes = null;
1889 ArtifactTypeConfig deploymentAcceptedTypes = deploymentConfigGetter.getDeploymentArtifactConfig();
1890 if (!parentType.equals(NodeTypeEnum.Resource) && !parentType.equals(NodeTypeEnum.Service) && !parentType.equals(NodeTypeEnum.ResourceInstance)) {
1891 log.debug("parent type of artifact can be either resource or service");
1892 responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
1896 if (deploymentAcceptedTypes == null) {
1897 log.debug("parent type of artifact can be either resource or service");
1898 responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType()));
1901 acceptedTypes = deploymentAcceptedTypes.getAcceptedTypes();
1904 * No need to check specific types. In case there are no acceptedTypes in configuration, then any type is accepted.
1906 * if ((!artifactType.equals(ArtifactTypeEnum.OTHER) && !artifactType.equals(ArtifactTypeEnum.HEAT_ARTIFACT )) && (acceptedTypes == null || acceptedTypes.isEmpty()) ) { log.debug( "No accepted types found for type {}, parent type {}",
1907 * fileType, parentType.getName()); String methodName = new Object() { }.getClass().getEnclosingMethod().getName(); String configEntryMissing = (parentType.equals(NodeTypeEnum.Resource)) ? "resourceDeploymentArtifacts:" + fileType :
1908 * "serviceDeploymentArtifacts:" + fileType; BeEcompErrorManager.getInstance().processEcompError(EcompErrorName. BeMissingConfigurationError, methodName, configEntryMissing); BeEcompErrorManager.getInstance().logBeMissingConfigurationError(
1909 * methodName, configEntryMissing); responseWrapper.setInnerElement(componentsUtils.getResponseFormat( ActionStatus.GENERAL_ERROR)); return; }
1912 String artifactName = artifactInfo.getArtifactName();
1913 String fileExtension = GeneralUtility.getFilenameExtension(artifactName);
1914 // Pavel - File extension validation is case-insensitive - Ella,
1916 if (acceptedTypes != null && !acceptedTypes.isEmpty() && !acceptedTypes.contains(fileExtension.toLowerCase())) {
1917 log.debug("File extension \"{}\" is not allowed for {} which is of type:{}", fileExtension, artifactName, fileType);
1918 responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.WRONG_ARTIFACT_FILE_EXTENSION, fileType));
1923 private Either<Boolean, ResponseFormat> validateHeatEnvDeploymentArtifact(Component parentComponent, String parentId, String userId, boolean isCreate, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) {
1925 Wrapper<ResponseFormat> errorWrapper = new Wrapper<ResponseFormat>();
1926 Wrapper<ArtifactDefinition> heatMDWrapper = new Wrapper<ArtifactDefinition>();
1927 Wrapper<byte[]> payloadWrapper = new Wrapper<>();
1929 if (errorWrapper.isEmpty()) {
1930 validateValidYaml(errorWrapper, artifactInfo);
1933 if (errorWrapper.isEmpty()) {
1934 // Validate Heat Exist
1935 validateHeatExist(parentComponent.getUniqueId(), parentId, errorWrapper, heatMDWrapper, artifactInfo, parentType, parentComponent.getComponentType());
1938 // if (errorWrapper.isEmpty() && isCreate) {
1939 // // Validate Only Single HeatEnv Artifact
1940 // validateSingleArtifactType(errorWrapper, ArtifactTypeEnum.HEAT_ENV, parentComponent, parentType, parentId);
1943 if (errorWrapper.isEmpty() && !heatMDWrapper.isEmpty()) {
1944 fillArtifactPayloadValidation(errorWrapper, payloadWrapper, heatMDWrapper.getInnerElement());
1947 if (errorWrapper.isEmpty() && !heatMDWrapper.isEmpty()) {
1948 validateEnvVsHeat(errorWrapper, artifactInfo, heatMDWrapper.getInnerElement(), payloadWrapper.getInnerElement());
1952 Either<Boolean, ResponseFormat> eitherResponse;
1953 if (errorWrapper.isEmpty()) {
1954 eitherResponse = Either.left(true);
1956 eitherResponse = Either.right(errorWrapper.getInnerElement());
1958 return eitherResponse;
1961 public void fillArtifactPayloadValidation(Wrapper<ResponseFormat> errorWrapper, Wrapper<byte[]> payloadWrapper, ArtifactDefinition artifactDefinition) {
1962 if (artifactDefinition.getPayloadData() == null || artifactDefinition.getPayloadData().length == 0) {
1963 Either<Boolean, ResponseFormat> fillArtifactPayload = fillArtifactPayload(payloadWrapper, artifactDefinition);
1964 if (fillArtifactPayload.isRight()) {
1965 errorWrapper.setInnerElement(fillArtifactPayload.right().value());
1966 log.debug("Error getting payload for artifact:{}", artifactDefinition.getArtifactName());
1969 payloadWrapper.setInnerElement(artifactDefinition.getPayloadData());
1973 public Either<Boolean, ResponseFormat> fillArtifactPayload(Wrapper<byte[]> payloadWrapper, ArtifactDefinition artifactMD) {
1974 Either<Boolean, ResponseFormat> result = Either.left(true);
1975 Either<ESArtifactData, CassandraOperationStatus> eitherArtifactData = artifactCassandraDao.getArtifact(artifactMD.getEsId());
1976 if (eitherArtifactData.isLeft()) {
1977 byte[] data = eitherArtifactData.left().value().getDataAsArray();
1978 data = Base64.encodeBase64(data);
1979 payloadWrapper.setInnerElement(data);
1981 StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(eitherArtifactData.right().value());
1982 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus));
1983 result = Either.right(responseFormat);
1989 @SuppressWarnings("unchecked")
1990 private void validateEnvVsHeat(Wrapper<ResponseFormat> errorWrapper, ArtifactDefinition envArtifact, ArtifactDefinition heatArtifact, byte[] heatPayloadData) {
1991 String envPayload = new String(Base64.decodeBase64(envArtifact.getPayloadData()));
1992 Map<String, Object> heatEnvToscaJson = (Map<String, Object>) new Yaml().load(envPayload);
1993 String heatDecodedPayload = new String(Base64.decodeBase64(heatPayloadData));
1994 Map<String, Object> heatToscaJson = (Map<String, Object>) new Yaml().load(heatDecodedPayload);
1996 Either<Map<String, Object>, ResultStatusEnum> eitherHeatEnvProperties = ImportUtils.findFirstToscaMapElement(heatEnvToscaJson, ToscaTagNamesEnum.PARAMETERS);
1997 Either<Map<String, Object>, ResultStatusEnum> eitherHeatProperties = ImportUtils.findFirstToscaMapElement(heatToscaJson, ToscaTagNamesEnum.PARAMETERS);
1998 if (eitherHeatEnvProperties.isRight()) {
1999 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.CORRUPTED_FORMAT, "Heat Env");
2000 errorWrapper.setInnerElement(responseFormat);
2001 log.debug("Invalid heat env format for file:{}", envArtifact.getArtifactName());
2002 } else if (eitherHeatProperties.isRight()) {
2003 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, envArtifact.getArtifactName(), heatArtifact.getArtifactName());
2004 errorWrapper.setInnerElement(responseFormat);
2005 log.debug("Validation of heat_env for artifact:{} vs heat artifact for artifact :{} failed", envArtifact.getArtifactName(), heatArtifact.getArtifactName());
2007 Set<String> heatPropertiesKeys = eitherHeatProperties.left().value().keySet();
2008 Set<String> heatEnvPropertiesKeys = eitherHeatEnvProperties.left().value().keySet();
2009 heatEnvPropertiesKeys.removeAll(heatPropertiesKeys);
2010 if (heatEnvPropertiesKeys.size() > 0) {
2011 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, envArtifact.getArtifactName(), heatArtifact.getArtifactName());
2012 errorWrapper.setInnerElement(responseFormat);
2017 private void validateValidYaml(Wrapper<ResponseFormat> errorWrapper, ArtifactDefinition artifactInfo) {
2018 YamlToObjectConverter yamlConvertor = new YamlToObjectConverter();
2019 boolean isYamlValid = yamlConvertor.isValidYamlEncoded64(artifactInfo.getPayloadData());
2021 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.INVALID_YAML, artifactInfo.getArtifactType());
2022 errorWrapper.setInnerElement(responseFormat);
2023 log.debug("Yaml is not valid for artifact : {}", artifactInfo.getArtifactName());
2027 @SuppressWarnings("restriction")
2028 public boolean isValidXml(byte[] xmlToParse) {
2029 XMLReader parser = new SAXParser();
2030 boolean isXmlValid = true;
2032 parser.parse(new InputSource(new ByteArrayInputStream(xmlToParse)));
2033 } catch (IOException | SAXException e) {
2034 log.debug("Xml is invalid : {}", e.getMessage(), e);
2040 public boolean isValidJson(byte[] jsonToParse) {
2041 String parsed = new String(jsonToParse);
2043 gson.fromJson(parsed, Object.class);
2044 } catch (Exception e) {
2045 log.debug("Json is invalid : {}", e.getMessage(), e);
2051 public void validateSingleArtifactType(Wrapper<ResponseFormat> errorWrapper, ArtifactTypeEnum allowedArtifactType, Component parentComponent, NodeTypeEnum parentType, String parentRiId) {
2052 boolean typeArtifactFound = false;
2053 // Iterator<ArtifactDefinition> parentDeploymentArtifactsItr =
2054 // (parentType == NodeTypeEnum.Resource) ?
2055 // informationDeployedArtifactsBusinessLogic.getAllDeployableArtifacts((Resource)
2056 // parentComponent).iterator()
2057 // : getDeploymentArtifacts(parentComponent, parentType).iterator();
2059 Iterator<ArtifactDefinition> parentDeploymentArtifactsItr = getDeploymentArtifacts(parentComponent, parentType, parentRiId).iterator();
2061 while (!typeArtifactFound && parentDeploymentArtifactsItr.hasNext()) {
2062 ArtifactTypeEnum foundArtifactType = ArtifactTypeEnum.findType(parentDeploymentArtifactsItr.next().getArtifactType());
2063 typeArtifactFound = (foundArtifactType == allowedArtifactType);
2065 if (typeArtifactFound) {
2066 String parentName = parentComponent.getName();
2067 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.DEPLOYMENT_ARTIFACT_OF_TYPE_ALREADY_EXISTS, parentType.name(), parentName, allowedArtifactType.getType(), allowedArtifactType.getType());
2069 errorWrapper.setInnerElement(responseFormat);
2070 log.debug("Can't upload artifact of type: {}, because another artifact of this type already exist.", allowedArtifactType.getType());
2075 public void validateSingleDeploymentArtifactName(Wrapper<ResponseFormat> errorWrapper, String artifactName, Component parentComponent, NodeTypeEnum parentType) {
2076 boolean artifactNameFound = false;
2077 // Iterator<ArtifactDefinition> parentDeploymentArtifactsItr =
2078 // (parentType == NodeTypeEnum.Resource) ?
2079 // informationDeployedArtifactsBusinessLogic.getAllDeployableArtifacts((Resource)
2080 // parentComponent).iterator()
2081 // : getDeploymentArtifacts(parentComponent, parentType).iterator();
2083 Iterator<ArtifactDefinition> parentDeploymentArtifactsItr = getDeploymentArtifacts(parentComponent, parentType, null).iterator();
2085 while (!artifactNameFound && parentDeploymentArtifactsItr.hasNext()) {
2086 artifactNameFound = (artifactName.equalsIgnoreCase(parentDeploymentArtifactsItr.next().getArtifactName()));
2088 if (artifactNameFound) {
2089 String parentName = parentComponent.getName();
2090 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.DEPLOYMENT_ARTIFACT_NAME_ALREADY_EXISTS, parentType.name(), parentName, artifactName);
2092 errorWrapper.setInnerElement(responseFormat);
2093 log.debug("Can't upload artifact: {}, because another artifact with this name already exist.", artifactName);
2098 private void validateHeatExist(String componentId, String parentRiId, Wrapper<ResponseFormat> errorWrapper, Wrapper<ArtifactDefinition> heatArtifactMDWrapper, ArtifactDefinition heatEnvArtifact, NodeTypeEnum parentType,
2099 ComponentTypeEnum componentType) {
2100 Either<ArtifactDefinition, StorageOperationStatus> res = artifactToscaOperation.getHeatArtifactByHeatEnvId(parentRiId, heatEnvArtifact, parentType, componentId, componentType);
2101 if (res.isRight()) {
2102 ResponseFormat responseFormat;
2103 if (res.right().value() == StorageOperationStatus.NOT_FOUND) {
2104 responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT);
2106 responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT);
2108 errorWrapper.setInnerElement(responseFormat);
2112 ArtifactDefinition heatArtifact = res.left().value();
2113 heatArtifactMDWrapper.setInnerElement(heatArtifact);
2114 // Iterator<ArtifactDefinition> parentArtifactsItr = parentDeploymentArtifacts.iterator();
2115 // while (!heatFound && parentArtifactsItr.hasNext()) {
2116 // ArtifactDefinition currArtifact = parentArtifactsItr.next();
2117 // if (heatArtifact.getUniqueId().equals(currArtifact.getUniqueId())) {
2118 // heatFound = true;
2119 // heatArtifactMDWrapper.setInnerElement(currArtifact);
2120 // log.trace("In validateHeatExist found artifact {}", currArtifact);
2122 // * ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(currArtifact.getArtifactType()); if(artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_VOL || artifactType == ArtifactTypeEnum.HEAT_NET){
2123 // * heatFound = true; } if (heatFound) { heatArtifactMDWrapper.setInnerElement(currArtifact); }
2127 // if (!heatFound) {
2128 // ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT);
2129 // errorWrapper.setInnerElement(responseFormat);
2130 // log.debug("Can't create heat env artifact because No heat Artifact exist.");
2135 private Either<Boolean, ResponseFormat> validateHeatDeploymentArtifact(Component parentComponent, String userId, boolean isCreate, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, NodeTypeEnum parentType) {
2136 log.trace("Started HEAT pre-payload validation for artifact {}", artifactInfo.getArtifactLabel());
2137 // timeout > 0 for HEAT artifacts
2138 Integer timeout = artifactInfo.getTimeout();
2139 Integer defaultTimeout = (isCreate) ? NodeTemplateOperation.getDefaultHeatTimeout() : currentArtifact.getTimeout();
2140 if (timeout == null) {
2141 artifactInfo.setTimeout(defaultTimeout);
2142 // HEAT artifact but timeout is invalid
2143 } else if (timeout < 1) {
2144 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_TIMEOUT));
2147 // US649856 - Allow several HEAT files on Resource
2149 * if (isCreate) { Wrapper<ResponseFormat> errorWrapper = new Wrapper<>(); validateSingleArtifactType(errorWrapper, ArtifactTypeEnum.findType(artifactInfo.getArtifactType()), parentComponent, parentType); if (!errorWrapper.isEmpty()) { return
2150 * Either.right(errorWrapper.getInnerElement()); } }
2153 log.trace("Ended HEAT validation for artifact {}", artifactInfo.getArtifactLabel());
2154 return Either.left(true);
2157 private Either<Boolean, ResponseFormat> validateResourceType(ResourceTypeEnum resourceType, ArtifactDefinition artifactInfo, List<String> typeList) {
2158 String listToString = (typeList != null) ? typeList.toString() : "";
2159 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISMATCH_BETWEEN_ARTIFACT_TYPE_AND_COMPONENT_TYPE, artifactInfo.getArtifactName(), listToString, resourceType.getValue());
2160 Either<Boolean, ResponseFormat> either = Either.right(responseFormat);
2161 String resourceTypeName = resourceType.name();
2162 if (typeList != null && typeList.contains(resourceTypeName)) {
2163 either = Either.left(true);
2168 private Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers(ArtifactDefinition artifactInfo, String artifactType) {
2169 if (artifactInfo.getHeatParameters() != null) {
2170 for (HeatParameterDefinition heatParam : artifactInfo.getListHeatParameters()) {
2171 String parameterType = heatParam.getType();
2172 HeatParameterType heatParameterType = HeatParameterType.isValidType(parameterType);
2173 String artifactTypeStr = artifactType != null ? artifactType : ArtifactTypeEnum.HEAT.getType();
2174 if (heatParameterType == null) {
2175 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_HEAT_PARAMETER_TYPE, artifactTypeStr, heatParam.getType());
2176 return Either.right(responseFormat);
2179 StorageOperationStatus validateAndUpdateProperty = heatParametersOperation.validateAndUpdateProperty(heatParam);
2180 if (validateAndUpdateProperty != StorageOperationStatus.OK) {
2181 log.debug("Heat parameter {} is invalid. Status is {}", heatParam.getName(), validateAndUpdateProperty);
2182 ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE;
2183 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, artifactTypeStr, heatParam.getType(), heatParam.getName());
2184 return Either.right(responseFormat);
2188 return Either.left(artifactInfo);
2191 public List<ArtifactDefinition> getDeploymentArtifacts(Component parentComponent, NodeTypeEnum parentType, String ciId) {
2192 List<ArtifactDefinition> deploymentArtifacts = new ArrayList<>();
2193 if (parentComponent.getDeploymentArtifacts() != null) {
2194 if (NodeTypeEnum.ResourceInstance == parentType && ciId != null) {
2195 Either<ComponentInstance, ResponseFormat> getRI = getRIFromComponent(parentComponent, ciId, null, null, null);
2196 if (getRI.isRight()) {
2197 return deploymentArtifacts;
2199 ComponentInstance ri = getRI.left().value();
2200 if (ri.getDeploymentArtifacts() != null) {
2201 deploymentArtifacts.addAll(ri.getDeploymentArtifacts().values());
2203 } else if (parentComponent.getDeploymentArtifacts() != null) {
2204 deploymentArtifacts.addAll(parentComponent.getDeploymentArtifacts().values());
2207 return deploymentArtifacts;
2210 private void checkCreateFields(User user, ArtifactDefinition artifactInfo, ArtifactGroupTypeEnum type) {
2211 // on create if null add informational to current
2212 if (artifactInfo.getArtifactGroupType() == null) {
2213 artifactInfo.setArtifactGroupType(type);
2215 if (artifactInfo.getUniqueId() != null) {
2216 log.error("artifact uniqid cannot be set ignoring");
2218 artifactInfo.setUniqueId(null);
2220 if (artifactInfo.getArtifactRef() != null) {
2221 log.error("artifact ref cannot be set ignoring");
2223 artifactInfo.setArtifactRef(null);
2225 if (artifactInfo.getArtifactRepository() != null) {
2226 log.error("artifact repository cannot be set ignoring");
2228 artifactInfo.setArtifactRepository(null);
2230 if (artifactInfo.getUserIdCreator() != null) {
2231 log.error("creator uuid cannot be set ignoring");
2233 artifactInfo.setArtifactCreator(user.getUserId());
2235 if (artifactInfo.getUserIdLastUpdater() != null) {
2236 log.error("userId of last updater cannot be set ignoring");
2238 artifactInfo.setUserIdLastUpdater(user.getUserId());
2240 if (artifactInfo.getCreatorFullName() != null) {
2241 log.error("creator Full name cannot be set ignoring");
2243 String fullName = user.getFirstName() + " " + user.getLastName();
2244 artifactInfo.setUpdaterFullName(fullName);
2246 if (artifactInfo.getUpdaterFullName() != null) {
2247 log.error("updater Full name cannot be set ignoring");
2249 artifactInfo.setUpdaterFullName(fullName);
2251 if (artifactInfo.getCreationDate() != null) {
2252 log.error("Creation Date cannot be set ignoring");
2254 long time = System.currentTimeMillis();
2255 artifactInfo.setCreationDate(time);
2257 if (artifactInfo.getLastUpdateDate() != null) {
2258 log.error("Last Update Date cannot be set ignoring");
2260 artifactInfo.setLastUpdateDate(time);
2262 if (artifactInfo.getEsId() != null) {
2263 log.error("es id cannot be set ignoring");
2265 artifactInfo.setEsId(null);
2270 * private Either<ArtifactDefinition, ResponseFormat> fetchCurrentArtifact(boolean isCreate, String artifactId) { Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(artifactId); if (isCreate
2271 * == false && artifactById.isRight()) { // in case of update artifact must be BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeArtifactMissingError, "Artifact Update / Upload", artifactId);
2272 * BeEcompErrorManager.getInstance().logBeArtifactMissingError("Artifact Update / Upload", artifactId); log.debug("Failed to fetch artifact {}. error: {}", artifactId, artifactById.right().value()); return
2273 * Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(artifactById.right().value()), artifactId)); } if (isCreate && artifactById.isLeft()) { log.debug("Artifact {} already exist", artifactId); return
2274 * Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactById.left().value().getArtifactLabel())); } ArtifactDefinition currentArtifactInfo = null; if (artifactById.isLeft()) { // get previous value
2275 * currentArtifactInfo = artifactById.left().value(); } return Either.left(currentArtifactInfo); }
2278 private String composeArtifactId(String resourceId, String artifactId, ArtifactDefinition artifactInfo, String interfaceName, String operationName) {
2279 String id = artifactId;
2280 if (artifactId == null || artifactId.isEmpty()) {
2281 String uniqueId = null;
2282 if (interfaceName != null && operationName != null) {
2283 uniqueId = UniqueIdBuilder.buildArtifactByInterfaceUniqueId(resourceId, interfaceName, operationName, artifactInfo.getArtifactLabel());
2285 uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId, artifactInfo.getArtifactLabel());
2287 artifactInfo.setUniqueId(uniqueId);
2288 artifactInfo.setEsId(uniqueId);
2291 artifactInfo.setUniqueId(artifactId);
2292 artifactInfo.setEsId(artifactId);
2297 private Either<ActionStatus, ResponseFormat> validateArtifactType(String userId, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) {
2298 if (artifactInfo.getArtifactType() == null || artifactInfo.getArtifactType().isEmpty()) {
2299 BeEcompErrorManager.getInstance().logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel");
2300 log.debug("Missing artifact type for artifact {}", artifactInfo.getArtifactName());
2301 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_TYPE));
2304 boolean artifactTypeExist = false;
2305 Either<List<ArtifactType>, ActionStatus> allArtifactTypes = null;
2306 ArtifactGroupTypeEnum artifactGroupType = artifactInfo.getArtifactGroupType();
2308 if ((artifactGroupType != null) && artifactGroupType.equals(ArtifactGroupTypeEnum.DEPLOYMENT)) {
2309 allArtifactTypes = getDeploymentArtifactTypes(userId, artifactInfo, parentType);
2312 allArtifactTypes = elementOperation.getAllArtifactTypes();
2314 if (allArtifactTypes.isRight()) {
2315 BeEcompErrorManager.getInstance().logBeInvalidConfigurationError("Artifact Upload / Update", "artifactTypes", allArtifactTypes.right().value().name());
2316 log.debug("Failed to retrieve list of suported artifact types. error: {}", allArtifactTypes.right().value());
2317 return Either.right(componentsUtils.getResponseFormatByUserId(allArtifactTypes.right().value(), userId));
2320 for (ArtifactType type : allArtifactTypes.left().value()) {
2321 if (type.getName().equalsIgnoreCase(artifactInfo.getArtifactType())) {
2322 artifactInfo.setArtifactType(artifactInfo.getArtifactType().toUpperCase());
2323 artifactTypeExist = true;
2328 if (!artifactTypeExist) {
2329 BeEcompErrorManager.getInstance().logBeInvalidTypeError("Artifact Upload / Delete / Update - Not supported artifact type", artifactInfo.getArtifactType(), "Artifact " + artifactInfo.getArtifactName());
2330 log.debug("Not supported artifact type = {}", artifactInfo.getArtifactType());
2331 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType()));
2334 return Either.left(ActionStatus.OK);
2337 private Either<List<ArtifactType>, ActionStatus> getDeploymentArtifactTypes(String userId, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) {
2339 Map<String, ArtifactTypeConfig> deploymentArtifacts = null;
2340 List<ArtifactType> artifactTypes = new ArrayList<ArtifactType>();
2342 if (parentType.equals(NodeTypeEnum.Service)) {
2343 deploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getServiceDeploymentArtifacts();
2344 } else if (parentType.equals(NodeTypeEnum.ResourceInstance)) {
2345 deploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceInstanceDeploymentArtifacts();
2347 deploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceDeploymentArtifacts();
2349 if (deploymentArtifacts != null) {
2350 for (String artifactType : deploymentArtifacts.keySet()) {
2351 ArtifactType artifactT = new ArtifactType();
2352 artifactT.setName(artifactType);
2353 artifactTypes.add(artifactT);
2355 return Either.left(artifactTypes);
2357 return Either.right(ActionStatus.GENERAL_ERROR);
2362 private Either<Boolean, ResponseFormat> validateFirstUpdateHasPayload(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2363 if (currentArtifact.getEsId() == null && (artifactInfo.getPayloadData() == null || artifactInfo.getPayloadData().length == 0)) {
2364 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD));
2366 return Either.left(true);
2370 private Either<Boolean, ResponseFormat> validateAndSetArtifactname(ArtifactDefinition artifactInfo) {
2371 if (artifactInfo.getArtifactName() == null || artifactInfo.getArtifactName().isEmpty()) {
2372 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_NAME));
2375 String normalizeFileName = ValidationUtils.normalizeFileName(artifactInfo.getArtifactName());
2376 if (normalizeFileName == null || normalizeFileName.isEmpty()) {
2377 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_NAME));
2379 artifactInfo.setArtifactName(normalizeFileName);
2381 if (!ValidationUtils.validateArtifactNameLength(artifactInfo.getArtifactName())) {
2382 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_NAME, String.valueOf(ValidationUtils.ARTIFACT_NAME_LENGTH)));
2385 return Either.left(true);
2388 private Either<Boolean, ResponseFormat> validateArtifactTypeNotChanged(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2389 if (artifactInfo.getArtifactType() == null || artifactInfo.getArtifactType().isEmpty()) {
2390 log.info("artifact type is missing operation ignored");
2391 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_TYPE));
2394 if (!currentArtifact.getArtifactType().equalsIgnoreCase(artifactInfo.getArtifactType())) {
2395 log.info("artifact type cannot be changed operation ignored");
2396 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2398 return Either.left(true);
2401 private Either<ArtifactDefinition, ResponseFormat> validateOrSetArtifactGroupType(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2402 if (artifactInfo.getArtifactGroupType() == null) {
2403 artifactInfo.setArtifactGroupType(currentArtifact.getArtifactGroupType());
2406 else if (!currentArtifact.getArtifactGroupType().getType().equalsIgnoreCase(artifactInfo.getArtifactGroupType().getType())) {
2407 log.info("artifact group type cannot be changed. operation failed");
2408 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2410 return Either.left(artifactInfo);
2413 private void checkAndSetUnUpdatableFields(User user, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, ArtifactGroupTypeEnum type) {
2415 // on update if null add informational to current
2416 if (currentArtifact.getArtifactGroupType() == null && type != null) {
2417 currentArtifact.setArtifactGroupType(type);
2420 if (artifactInfo.getUniqueId() != null && !currentArtifact.getUniqueId().equals(artifactInfo.getUniqueId())) {
2421 log.error("artifact uniqid cannot be set ignoring");
2423 artifactInfo.setUniqueId(currentArtifact.getUniqueId());
2425 if (artifactInfo.getArtifactRef() != null && !currentArtifact.getArtifactRef().equals(artifactInfo.getArtifactRef())) {
2426 log.error("artifact ref cannot be set ignoring");
2428 artifactInfo.setArtifactRef(currentArtifact.getArtifactRef());
2430 if (artifactInfo.getArtifactRepository() != null && !currentArtifact.getArtifactRepository().equals(artifactInfo.getArtifactRepository())) {
2431 log.error("artifact repository cannot be set ignoring");
2433 artifactInfo.setArtifactRepository(currentArtifact.getArtifactRepository());
2435 if (artifactInfo.getUserIdCreator() != null && !currentArtifact.getUserIdCreator().equals(artifactInfo.getUserIdCreator())) {
2436 log.error("creator uuid cannot be set ignoring");
2438 artifactInfo.setUserIdCreator(currentArtifact.getUserIdCreator());
2440 if (artifactInfo.getArtifactCreator() != null && !currentArtifact.getArtifactCreator().equals(artifactInfo.getArtifactCreator())) {
2441 log.error("artifact creator cannot be set ignoring");
2443 artifactInfo.setArtifactCreator(currentArtifact.getArtifactCreator());
2445 if (artifactInfo.getUserIdLastUpdater() != null && !currentArtifact.getUserIdLastUpdater().equals(artifactInfo.getUserIdLastUpdater())) {
2446 log.error("userId of last updater cannot be set ignoring");
2448 artifactInfo.setUserIdLastUpdater(user.getUserId());
2450 if (artifactInfo.getCreatorFullName() != null && !currentArtifact.getCreatorFullName().equals(artifactInfo.getCreatorFullName())) {
2451 log.error("creator Full name cannot be set ignoring");
2453 artifactInfo.setCreatorFullName(currentArtifact.getCreatorFullName());
2455 if (artifactInfo.getUpdaterFullName() != null && !currentArtifact.getUpdaterFullName().equals(artifactInfo.getUpdaterFullName())) {
2456 log.error("updater Full name cannot be set ignoring");
2458 String fullName = user.getFirstName() + " " + user.getLastName();
2459 artifactInfo.setUpdaterFullName(fullName);
2461 if (artifactInfo.getCreationDate() != null && !currentArtifact.getCreationDate().equals(artifactInfo.getCreationDate())) {
2462 log.error("Creation Date cannot be set ignoring");
2464 artifactInfo.setCreationDate(currentArtifact.getCreationDate());
2466 if (artifactInfo.getLastUpdateDate() != null && !currentArtifact.getLastUpdateDate().equals(artifactInfo.getLastUpdateDate())) {
2467 log.error("Last Update Date cannot be set ignoring");
2469 long time = System.currentTimeMillis();
2470 artifactInfo.setLastUpdateDate(time);
2472 if (artifactInfo.getEsId() != null && !currentArtifact.getEsId().equals(artifactInfo.getEsId())) {
2473 log.error("es id cannot be set ignoring");
2475 artifactInfo.setEsId(currentArtifact.getUniqueId());
2477 if (artifactInfo.getArtifactDisplayName() != null && !currentArtifact.getArtifactDisplayName().equals(artifactInfo.getArtifactDisplayName())) {
2478 log.error(" Artifact Display Name cannot be set ignoring");
2480 artifactInfo.setArtifactDisplayName(currentArtifact.getArtifactDisplayName());
2482 if (artifactInfo.getServiceApi() != null && !currentArtifact.getServiceApi().equals(artifactInfo.getServiceApi())) {
2483 log.debug("serviceApi cannot be set. ignoring.");
2485 artifactInfo.setServiceApi(currentArtifact.getServiceApi());
2487 if (artifactInfo.getArtifactGroupType() != null && !currentArtifact.getArtifactGroupType().equals(artifactInfo.getArtifactGroupType())) {
2488 log.debug("artifact group cannot be set. ignoring.");
2490 artifactInfo.setArtifactGroupType(currentArtifact.getArtifactGroupType());
2492 artifactInfo.setArtifactVersion(currentArtifact.getArtifactVersion());
2494 if (artifactInfo.getArtifactUUID() != null && !artifactInfo.getArtifactUUID().isEmpty() && !currentArtifact.getArtifactUUID().equals(artifactInfo.getArtifactUUID())) {
2495 log.debug("artifact UUID cannot be set. ignoring.");
2497 artifactInfo.setArtifactUUID(currentArtifact.getArtifactUUID());
2499 if ((artifactInfo.getHeatParameters() != null) && (currentArtifact.getHeatParameters() != null) && !artifactInfo.getHeatParameters().isEmpty() && !currentArtifact.getHeatParameters().isEmpty()) {
2500 checkAndSetUnupdatableHeatParams(artifactInfo.getListHeatParameters(), currentArtifact.getListHeatParameters());
2504 private void checkAndSetUnupdatableHeatParams(List<HeatParameterDefinition> heatParameters, List<HeatParameterDefinition> currentParameters) {
2506 Map<String, HeatParameterDefinition> currentParametersMap = getMapOfParameters(currentParameters);
2507 for (HeatParameterDefinition parameter : heatParameters) {
2508 HeatParameterDefinition currentParam = currentParametersMap.get(parameter.getUniqueId());
2510 if (currentParam != null) {
2512 if (parameter.getName() != null && !parameter.getName().equalsIgnoreCase(currentParam.getName())) {
2513 log.debug("heat parameter name cannot be updated ({}). ignoring.", parameter.getName());
2514 parameter.setName(currentParam.getName());
2516 if (parameter.getDefaultValue() != null && !parameter.getDefaultValue().equalsIgnoreCase(currentParam.getDefaultValue())) {
2517 log.debug("heat parameter defaultValue cannot be updated ({}). ignoring.", parameter.getDefaultValue());
2518 parameter.setDefaultValue(currentParam.getDefaultValue());
2520 if (parameter.getType() != null && !parameter.getType().equalsIgnoreCase(currentParam.getType())) {
2521 log.debug("heat parameter type cannot be updated ({}). ignoring.", parameter.getType());
2522 parameter.setType(currentParam.getType());
2524 if (parameter.getDescription() != null && !parameter.getDescription().equalsIgnoreCase(currentParam.getDescription())) {
2525 log.debug("heat parameter description cannot be updated ({}). ignoring.", parameter.getDescription());
2526 parameter.setDescription(currentParam.getDescription());
2529 // check and set current value
2530 if ((parameter.getCurrentValue() == null) && (currentParam.getDefaultValue() != null)) {
2531 log.debug("heat parameter current value is null. set it to default value {}). ignoring.", parameter.getDefaultValue());
2532 parameter.setCurrentValue(currentParam.getDefaultValue());
2538 private Map<String, HeatParameterDefinition> getMapOfParameters(List<HeatParameterDefinition> currentParameters) {
2540 Map<String, HeatParameterDefinition> currentParamsMap = new HashMap<String, HeatParameterDefinition>();
2541 for (HeatParameterDefinition param : currentParameters) {
2542 currentParamsMap.put(param.getUniqueId(), param);
2544 return currentParamsMap;
2547 private Either<Boolean, ResponseFormat> validateAndServiceApiUrl(ArtifactDefinition artifactInfo) {
2548 if (!ValidationUtils.validateStringNotEmpty(artifactInfo.getApiUrl())) {
2549 log.debug("Artifact url cannot be empty.");
2550 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_URL));
2552 artifactInfo.setApiUrl(artifactInfo.getApiUrl().toLowerCase());
2554 if (!ValidationUtils.validateUrl(artifactInfo.getApiUrl())) {
2555 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_SERVICE_API_URL));
2557 if (!ValidationUtils.validateUrlLength(artifactInfo.getApiUrl())) {
2558 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_URL, String.valueOf(ValidationUtils.API_URL_LENGTH)));
2561 return Either.left(true);
2564 private Either<Boolean, ResponseFormat> validateAndCleanDescription(ArtifactDefinition artifactInfo) {
2565 if (artifactInfo.getDescription() == null || artifactInfo.getDescription().isEmpty()) {
2566 log.debug("Artifact description cannot be empty.");
2567 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_DESCRIPTION));
2569 String description = artifactInfo.getDescription();
2570 description = ValidationUtils.removeNoneUtf8Chars(description);
2571 description = ValidationUtils.normaliseWhitespace(description);
2572 description = ValidationUtils.stripOctets(description);
2573 description = ValidationUtils.removeHtmlTagsOnly(description);
2574 if (!ValidationUtils.validateIsEnglish(description)) {
2575 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2577 if (!ValidationUtils.validateLength(description, ValidationUtils.ARTIFACT_DESCRIPTION_MAX_LENGTH)) {
2578 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_DESCRIPTION, String.valueOf(ValidationUtils.ARTIFACT_DESCRIPTION_MAX_LENGTH)));
2580 artifactInfo.setDescription(description);
2581 return Either.left(true);
2584 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateArtifactFlow(org.openecomp.sdc.be.model.Component parent, String parentId, String artifactId, ArtifactDefinition artifactInfo, User user, byte[] decodedPayload,
2585 ComponentTypeEnum componentType, AuditingActionEnum auditingAction, String interfaceType, String operationName) {
2586 ESArtifactData artifactData = createEsArtifactData(artifactInfo, decodedPayload);
2587 String prevArtifactId = null;
2588 String currArtifactId = artifactId;
2590 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
2591 Either<ArtifactDefinition, Operation> insideEither = null;
2593 if (artifactData == null) {
2594 BeEcompErrorManager.getInstance().logBeDaoSystemError("Update Artifact");
2595 log.debug("Failed to create artifact object for ES.");
2596 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
2597 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
2598 resultOp = Either.right(responseFormat);
2601 log.trace("Try to update entry on graph");
2602 String artifactUniqueId = null;
2603 ArtifactDefinition artifactDefinition = artifactInfo;
2604 StorageOperationStatus error = null;
2606 boolean isLeft = false;
2607 if (interfaceType != null && operationName != null) {
2608 // lifecycle artifact
2610 * Operation operation = convertToOperation(artifactInfo, operationName);
2612 * Either<Operation, StorageOperationStatus> result = interfaceLifecycleOperation.updateInterfaceOperation(parentId, interfaceType, operationName, operation);
2614 * isLeft = result.isLeft(); if (isLeft) { artifactUniqueId = result.left().value().getUniqueId(); artifactDefinition = result.left().value().getImplementation();
2616 * insideEither = Either.right(result.left().value()); resultOp = Either.left(insideEither); } else { error = result.right().value(); }
2619 log.debug("Enty on graph is updated. Update artifact in ES");
2621 // Changing previous and current artifactId for auditing
2622 prevArtifactId = currArtifactId;
2623 currArtifactId = artifactDefinition.getUniqueId();
2625 NodeTypeEnum convertParentType = convertParentType(componentType);
2627 if (decodedPayload == null) {
2628 if (!artifactDefinition.getMandatory() || artifactDefinition.getEsId() != null) {
2629 Either<ESArtifactData, CassandraOperationStatus> artifactFromCassandra = artifactCassandraDao.getArtifact(artifactDefinition.getEsId());
2630 // Either<ESArtifactData, ResourceUploadStatus>
2631 // artifactfromES = daoUploader.getArtifact(artifactId);
2632 if (artifactFromCassandra.isRight()) {
2633 log.debug("Failed to get artifact data from ES for artifact id {}", artifactId);
2634 error = DaoStatusConverter.convertCassandraStatusToStorageStatus(artifactFromCassandra.right().value());
2635 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
2636 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
2637 resultOp = Either.right(responseFormat);
2640 // clone data to new artifact
2641 artifactData.setData(artifactFromCassandra.left().value().getData());
2642 artifactData.setId(artifactFromCassandra.left().value().getId());
2645 if (artifactDefinition.getEsId() == null) {
2646 artifactDefinition.setEsId(artifactDefinition.getUniqueId());
2647 artifactData.setId(artifactDefinition.getUniqueId());
2651 Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.updateArifactOnResource(artifactInfo, parent.getUniqueId(), artifactId, convertParentType, parentId);
2652 isLeft = result.isLeft();
2654 artifactUniqueId = result.left().value().getUniqueId();
2655 artifactDefinition = result.left().value();
2656 String artifactType = artifactInfo.getArtifactType();
2657 if (NodeTypeEnum.Resource == convertParentType
2658 && (ArtifactTypeEnum.HEAT.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.HEAT_VOL.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.HEAT_NET.getType().equalsIgnoreCase(artifactType))) {
2660 if (!artifactUniqueId.equals(artifactId)) {
2661 // need to update the generated id in heat env
2662 Map<String, ArtifactDefinition> deploymentArtifacts = parent.getDeploymentArtifacts();
2663 Optional<Entry<String, ArtifactDefinition>> findFirst = deploymentArtifacts.entrySet().stream().filter(a -> a.getValue().getGeneratedFromId()!=null && a.getValue().getGeneratedFromId().equals(artifactId)).findFirst();
2664 if (findFirst.isPresent()) {
2665 ArtifactDefinition artifactEnvInfo = findFirst.get().getValue();
2666 artifactEnvInfo.setArtifactChecksum(null);
2667 artifactToscaOperation.updateHeatEnvArtifact(parent.getUniqueId(), artifactEnvInfo, artifactId, artifactUniqueId, convertParentType, parentId);
2672 * if (!artifactUniqueId.equals(artifactId)) { artifactToscaOperation.updateHeatEnvArtifact(parentId, null, artifactId, artifactUniqueId, convertParentType);
2674 * } else { if (!artifactInfo.getArtifactChecksum().equals(artifactDefinition.getArtifactChecksum())) { Either<ArtifactDefinition, StorageOperationStatus> heatEnvEither =
2675 * artifactToscaOperation.getHeatEnvByGeneratedFromId(artifactUniqueId); if (heatEnvEither.isLeft()) { artifactToscaOperation.updateHeatEnvPlaceholder(heatEnvEither.left().value(), parentId);
2680 error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentType);
2682 insideEither = Either.left(result.left().value());
2683 resultOp = Either.left(insideEither);
2684 if (error != StorageOperationStatus.OK) {
2689 error = result.right().value();
2693 // create new entry in ES
2695 if (artifactData.getData() != null) {
2696 if (!artifactDefinition.getDuplicated() || artifactData.getId() == null)
2697 artifactData.setId(artifactDefinition.getEsId());
2698 res = saveArtifacts(artifactData, parentId, false);
2704 log.debug("Artifact saved into ES - {}", artifactUniqueId);
2705 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
2706 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
2707 // resultOp = Either.left(result.left().value());
2710 BeEcompErrorManager.getInstance().logBeDaoSystemError("Update Artifact");
2711 log.debug("Failed to save the artifact.");
2712 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
2713 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
2714 resultOp = Either.right(responseFormat);
2722 private Either<byte[], ResponseFormat> handlePayload(ArtifactDefinition artifactInfo, boolean isArtifactMetadataUpdate) {
2723 log.trace("Starting payload handling");
2724 byte[] payload = artifactInfo.getPayloadData();
2725 byte[] decodedPayload = null;
2727 if (payload != null && payload.length != 0) {
2728 // the generated artifacts were already decoded by the handler
2729 decodedPayload = artifactInfo.getGenerated() ? payload : Base64.decodeBase64(payload);
2730 if (decodedPayload.length == 0) {
2731 log.debug("Failed to decode the payload.");
2732 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
2733 return Either.right(responseFormat);
2736 String checkSum = GeneralUtility.calculateMD5ByByteArray(decodedPayload);
2737 artifactInfo.setArtifactChecksum(checkSum);
2738 log.trace("Calculated checksum, base64 payload: {}, checksum: {}", payload, checkSum);
2740 // Specific payload validations of different types
2741 Either<Boolean, ResponseFormat> isValidPayload = Either.left(true);
2742 if (isDeploymentArtifact(artifactInfo)) {
2743 log.trace("Starting deployment artifacts payload validation");
2744 String artifactType = artifactInfo.getArtifactType();
2745 if (ArtifactTypeEnum.HEAT.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.HEAT_VOL.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.HEAT_NET.getType().equalsIgnoreCase(artifactType)
2746 || ArtifactTypeEnum.HEAT_ENV.getType().equalsIgnoreCase(artifactType)) {
2747 isValidPayload = validateDeploymentHeatPayload(decodedPayload, artifactType);
2748 if (isValidPayload.isLeft()) {
2749 isValidPayload = extractHeatParameters(artifactInfo);
2751 } else if (ArtifactTypeEnum.YANG_XML.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.VNF_CATALOG.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.VF_LICENSE.getType().equalsIgnoreCase(artifactType)
2752 || ArtifactTypeEnum.VENDOR_LICENSE.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.MODEL_INVENTORY_PROFILE.getType().equalsIgnoreCase(artifactType)
2753 || ArtifactTypeEnum.MODEL_QUERY_SPEC.getType().equalsIgnoreCase(artifactType)) {
2754 isValidPayload = validateYangPayload(decodedPayload, artifactType);
2756 // if(ArtifactTypeEnum.APPC_CONFIG.getType().equalsIgnoreCase(artifactType)
2758 } else if (ArtifactTypeEnum.DCAE_INVENTORY_JSON.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType().equalsIgnoreCase(artifactType)
2759 || ArtifactTypeEnum.VES_EVENTS.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.LIFECYCLE_OPERATIONS.getType().equalsIgnoreCase(artifactType)) {
2760 String artifactFileName = artifactInfo.getArtifactName();
2761 String fileExtension = GeneralUtility.getFilenameExtension(artifactFileName).toLowerCase();
2762 switch (fileExtension) {
2764 isValidPayload = validateYangPayload(decodedPayload, artifactType);
2767 isValidPayload = validateJsonPayload(decodedPayload, artifactType);
2771 isValidPayload = validateYmlPayload(decodedPayload, artifactType);
2776 if (isValidPayload.isRight()) {
2777 ResponseFormat responseFormat = isValidPayload.right().value();
2778 return Either.right(responseFormat);
2781 } // null/empty payload is normal if called from metadata update ONLY.
2782 // The validation of whether this is metadata/payload update case is
2783 // currently done separately
2785 if (!isArtifactMetadataUpdate) {
2786 log.debug("Payload is missing.");
2787 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
2788 return Either.right(responseFormat);
2791 log.trace("Ended payload handling");
2792 return Either.left(decodedPayload);
2795 private Either<Boolean, ResponseFormat> validateDeploymentHeatPayload(byte[] decodedPayload, String artifactType) {
2796 // Basic YAML validation
2797 YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter();
2798 if (!yamlToObjectConverter.isValidYaml(decodedPayload)) {
2799 log.debug("Invalid YAML format");
2800 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, artifactType);
2801 return Either.right(responseFormat);
2803 if (!ArtifactTypeEnum.HEAT_ENV.getType().equalsIgnoreCase(artifactType)) {
2804 // HEAT specific YAML validation
2805 DeploymentArtifactHeatConfiguration heatConfiguration = yamlToObjectConverter.convert(decodedPayload, DeploymentArtifactHeatConfiguration.class);
2806 if (heatConfiguration == null || heatConfiguration.getHeat_template_version() == null) {
2807 log.debug("HEAT doesn't contain required \"heat_template_version\" section.");
2808 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactType);
2809 return Either.right(responseFormat);
2813 return Either.left(true);
2816 private Either<Boolean, ResponseFormat> validateYmlPayload(byte[] decodedPayload, String artifactType) {
2817 Either<Boolean, ResponseFormat> res = Either.left(true);
2818 YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter();
2819 if (!yamlToObjectConverter.isValidYaml(decodedPayload)) {
2820 log.debug("Invalid YAML format");
2821 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, artifactType);
2822 res = Either.right(responseFormat);
2828 private Either<Boolean, ResponseFormat> validateYangPayload(byte[] payload, String artifactType) {
2829 boolean isXmlValid = isValidXml(payload);
2831 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.INVALID_XML, artifactType);
2832 log.debug("Invalid XML content");
2833 return Either.right(responseFormat);
2835 return Either.left(true);
2838 private Either<Boolean, ResponseFormat> validateJsonPayload(byte[] payload, String type) {
2839 boolean isJsonValid = isValidJson(payload);
2841 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.INVALID_JSON, type);
2842 log.debug("Invalid JSON content");
2843 return Either.right(responseFormat);
2845 return Either.left(true);
2848 public void handleTransaction(Either<Operation, ResponseFormat> opState) {
2849 if (opState == null || opState.isRight()) {
2850 titanDao.rollback();
2856 public Either<Operation, ResponseFormat> deleteArtifactByInterface(String resourceId, String interfaceType, String operationName, String userUserId, String artifactId, ImmutablePair<User, Resource> userResourceAuditPair, boolean shouldLock,
2857 boolean inTransaction) {
2858 User user = new User();
2859 user.setUserId(userUserId);
2860 Either<Resource, StorageOperationStatus> parent = toscaOperationFacade.getToscaElement(resourceId, JsonParseFlagEnum.ParseMetadata);
2861 if (parent.isRight()) {
2862 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(parent.right().value()));
2863 return Either.right(responseFormat);
2865 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = handleDelete(resourceId, artifactId, user, AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, parent.left().value(), interfaceType, operationName,
2866 false, inTransaction);
2867 if (handleDelete.isRight()) {
2868 return Either.right(handleDelete.right().value());
2870 Either<ArtifactDefinition, Operation> result = handleDelete.left().value();
2871 return Either.left(result.right().value());
2875 public StorageOperationStatus deleteAllComponentArtifactsIfNotOnGraph(List<ArtifactDefinition> artifacts) {
2877 if (artifacts != null && !artifacts.isEmpty()) {
2878 for (ArtifactDefinition artifactDefinition : artifacts) {
2879 String esId = artifactDefinition.getEsId();
2880 if (esId != null && !esId.isEmpty()) {
2881 StorageOperationStatus deleteIfNotOnGraph = deleteIfNotOnGraph(artifactDefinition.getUniqueId(), esId, false);
2882 if (!deleteIfNotOnGraph.equals(StorageOperationStatus.OK)) {
2883 return deleteIfNotOnGraph;
2888 return StorageOperationStatus.OK;
2891 private Operation convertToOperation(ArtifactDefinition artifactInfo, String operationName) {
2892 Operation op = new Operation();
2893 long time = System.currentTimeMillis();
2894 op.setCreationDate(time);
2896 String artifactName = artifactInfo.getArtifactName();
2897 artifactInfo.setArtifactName(createInterfaceArtifactNameFromOperation(operationName, artifactName));
2899 op.setImplementation(artifactInfo);
2900 op.setLastUpdateDate(time);
2904 private String createInterfaceArtifactNameFromOperation(String operationName, String artifactName) {
2905 String newArtifactName = operationName + "_" + artifactName;
2906 log.trace("converting artifact name {} to {}", artifactName, newArtifactName);
2907 return newArtifactName;
2910 public StorageOperationStatus deleteIfNotOnGraph(String artifactId, String artifactEsId, boolean deleteOnlyPayload) {
2911 log.debug("deleteIfNotOnGraph: delete only payload = {}", deleteOnlyPayload);
2912 // Either<ArtifactData, TitanOperationStatus> checkArtifactNode = titanDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ArtifactRef), artifactId, ArtifactData.class);
2913 // if ((artifactEsId != null && !artifactEsId.isEmpty())) {
2914 // boolean isNotExistOnGraph = checkArtifactNode.isRight() && checkArtifactNode.right().value().equals(TitanOperationStatus.NOT_FOUND);
2916 // if ((isNotExistOnGraph) || (checkArtifactNode.left().value().getArtifactDataDefinition().getMandatory() && deleteOnlyPayload)
2917 // || (ArtifactGroupTypeEnum.SERVICE_API.equals(checkArtifactNode.left().value().getArtifactDataDefinition().getArtifactGroupType()) && deleteOnlyPayload)) {
2918 // // last one. need to delete in ES
2919 // log.debug("Entry on graph is deleted. Delete artifact in ES for id = {}", artifactEsId);
2920 // artifactCassandraDao.deleteArtifact(artifactEsId);
2921 // return StorageOperationStatus.OK;
2923 // // componentsUtils.getResponseFormatByResourceId(ActionStatus.OK,
2927 // log.debug("Entry on graph is deleted. Exist more connections on this artifact. Don't delete artifact in ES for id = {}", artifactEsId);
2928 // return StorageOperationStatus.OK;
2932 return StorageOperationStatus.OK;
2936 public Either<byte[], ResponseFormat> downloadRsrcArtifactByNames(String serviceName, String serviceVersion, String resourceName, String resourceVersion, String artifactName) {
2938 // General validation
2939 if (serviceName == null || serviceVersion == null || resourceName == null || resourceVersion == null || artifactName == null) {
2940 log.debug("One of the function parameteres is null");
2941 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2944 // Normalizing artifact name
2945 artifactName = ValidationUtils.normalizeFileName(artifactName);
2947 // Resource validation
2948 Either<Resource, ResponseFormat> validateResourceNameAndVersion = validateResourceNameAndVersion(resourceName, resourceVersion);
2949 if (validateResourceNameAndVersion.isRight()) {
2950 return Either.right(validateResourceNameAndVersion.right().value());
2953 Resource resource = validateResourceNameAndVersion.left().value();
2954 String resourceId = resource.getUniqueId();
2956 // Service validation
2957 Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
2958 if (validateServiceNameAndVersion.isRight()) {
2959 return Either.right(validateServiceNameAndVersion.right().value());
2962 Map<String, ArtifactDefinition> artifacts = resource.getDeploymentArtifacts();
2963 if (artifacts == null || artifacts.isEmpty()) {
2964 log.debug("Deployment artifacts of resource {} are not found", resourceId);
2965 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
2968 ArtifactDefinition deploymentArtifact = null;
2970 for (ArtifactDefinition artifactDefinition : artifacts.values()) {
2971 if (artifactDefinition.getArtifactName() != null && artifactDefinition.getArtifactName().equals(artifactName)) {
2972 log.debug("Found deployment artifact {}", artifactName);
2973 deploymentArtifact = artifactDefinition;
2978 if (deploymentArtifact == null) {
2979 log.debug("No deployment artifact {} was found for resource {}", artifactName, resourceId);
2980 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
2983 // Downloading the artifact
2984 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(deploymentArtifact);
2985 if (downloadArtifactEither.isRight()) {
2986 log.debug("Download artifact {} failed", artifactName);
2987 return Either.right(downloadArtifactEither.right().value());
2989 log.trace("Download of resource artifact succeeded, uniqueId {}", deploymentArtifact.getUniqueId());
2990 return Either.left(downloadArtifactEither.left().value().getRight());
2994 public Either<byte[], ResponseFormat> downloadRsrcInstArtifactByNames(String serviceName, String serviceVersion, String resourceInstanceName, String artifactName) {
2996 // General validation
2997 if (serviceName == null || serviceVersion == null || resourceInstanceName == null || artifactName == null) {
2998 log.debug("One of the function parameteres is null");
2999 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
3002 // Normalizing artifact name
3003 artifactName = ValidationUtils.normalizeFileName(artifactName);
3005 // Resource validation
3007 * Either<Resource, ResponseFormat> validateResourceNameAndVersion = validateResourceNameAndVersion(resourceName, resourceVersion); if (validateResourceNameAndVersion.isRight()) { return
3008 * Either.right(validateResourceNameAndVersion.right().value()); }
3010 * Resource resource = validateResourceNameAndVersion.left().value(); String resourceId = resource.getUniqueId();
3013 // Service validation
3014 Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
3015 if (validateServiceNameAndVersion.isRight()) {
3016 return Either.right(validateServiceNameAndVersion.right().value());
3019 Service service = validateServiceNameAndVersion.left().value();
3021 // ResourceInstance validation
3022 Either<ComponentInstance, ResponseFormat> validateResourceInstance = validateResourceInstance(service, resourceInstanceName);
3023 if (validateResourceInstance.isRight()) {
3024 return Either.right(validateResourceInstance.right().value());
3027 ComponentInstance resourceInstance = validateResourceInstance.left().value();
3029 Map<String, ArtifactDefinition> artifacts = resourceInstance.getDeploymentArtifacts();
3031 final String finalArtifactName = artifactName;
3032 Predicate<ArtifactDefinition> filterArtifactByName = p -> p.getArtifactName().equals(finalArtifactName);
3034 boolean hasDeploymentArtifacts = artifacts != null && artifacts.values().stream().anyMatch(filterArtifactByName);
3035 ArtifactDefinition deployableArtifact;
3037 if (!hasDeploymentArtifacts) {
3038 log.debug("Deployment artifact with name {} not found", artifactName);
3039 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
3042 log.debug("Found deployment artifact {}", artifactName);
3043 deployableArtifact = artifacts.values().stream().filter(filterArtifactByName).findFirst().get();
3044 // Downloading the artifact
3045 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(deployableArtifact);
3047 if (downloadArtifactEither.isRight()) {
3048 log.debug("Download artifact {} failed", artifactName);
3049 return Either.right(downloadArtifactEither.right().value());
3051 log.trace("Download of resource artifact succeeded, uniqueId {}", deployableArtifact.getUniqueId());
3052 return Either.left(downloadArtifactEither.left().value().getRight());
3055 private Either<ComponentInstance, ResponseFormat> validateResourceInstance(Service service, String resourceInstanceName) {
3057 List<ComponentInstance> riList = service.getComponentInstances();
3058 for (ComponentInstance ri : riList) {
3059 if (ri.getNormalizedName().equals(resourceInstanceName))
3060 return Either.left(ri);
3063 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND, resourceInstanceName));
3066 private Either<Service, ResponseFormat> validateServiceNameAndVersion(String serviceName, String serviceVersion) {
3068 Either<List<Service>, StorageOperationStatus> serviceListBySystemName = toscaOperationFacade.getBySystemName(ComponentTypeEnum.SERVICE, serviceName);
3069 if (serviceListBySystemName.isRight()) {
3070 log.debug("Couldn't fetch any service with name {}", serviceName);
3071 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceListBySystemName.right().value(), ComponentTypeEnum.SERVICE), serviceName));
3073 List<Service> serviceList = serviceListBySystemName.left().value();
3074 if (serviceList == null || serviceList.isEmpty()) {
3075 log.debug("Couldn't fetch any service with name {}", serviceName);
3076 return Either.right(componentsUtils.getResponseFormat(ActionStatus.SERVICE_NOT_FOUND, serviceName));
3079 Service foundService = null;
3080 for (Service service : serviceList) {
3081 if (service.getVersion().equals(serviceVersion)) {
3082 log.trace("Found service with version {}", serviceVersion);
3083 foundService = service;
3088 if (foundService == null) {
3089 log.debug("Couldn't find version {} for service {}", serviceVersion, serviceName);
3090 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_VERSION_NOT_FOUND, ComponentTypeEnum.SERVICE.getValue(), serviceVersion));
3092 return Either.left(foundService);
3095 private Either<Resource, ResponseFormat> validateResourceNameAndVersion(String resourceName, String resourceVersion) {
3097 Either<Resource, StorageOperationStatus> resourceListBySystemName = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, resourceVersion, JsonParseFlagEnum.ParseMetadata);
3098 if (resourceListBySystemName.isRight()) {
3099 log.debug("Couldn't fetch any resource with name {} and version {}. ", resourceName, resourceVersion);
3100 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceListBySystemName.right().value()), resourceName));
3102 return Either.left(resourceListBySystemName.left().value());
3105 public Either<byte[], ResponseFormat> downloadServiceArtifactByNames(String serviceName, String serviceVersion, String artifactName) {
3107 log.trace("Starting download of service interface artifact, serviceName {}, serviceVersion {}, artifact name {}", serviceName, serviceVersion, artifactName);
3108 if (serviceName == null || serviceVersion == null || artifactName == null) {
3109 log.debug("One of the function parameteres is null");
3110 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
3113 // Normalizing artifact name
3114 final String normalizedArtifactName = ValidationUtils.normalizeFileName(artifactName);
3116 // Service validation
3117 Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
3118 if (validateServiceNameAndVersion.isRight()) {
3119 return Either.right(validateServiceNameAndVersion.right().value());
3122 String serviceId = validateServiceNameAndVersion.left().value().getUniqueId();
3124 // Looking for deployment or tosca artifacts
3125 Service service = validateServiceNameAndVersion.left().value();
3127 if (MapUtils.isEmpty(service.getDeploymentArtifacts()) && MapUtils.isEmpty(service.getToscaArtifacts())) {
3128 log.debug("Neither Deployment nor Tosca artifacts of service {} are found", serviceId);
3129 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, normalizedArtifactName));
3132 Optional<ArtifactDefinition> foundArtifactOptl = null;
3134 if (!MapUtils.isEmpty(service.getDeploymentArtifacts())) {
3135 foundArtifactOptl = service.getDeploymentArtifacts().values().stream()
3136 // filters artifact by name
3137 .filter(a -> a.getArtifactName().equals(normalizedArtifactName)).findAny();
3139 if ((foundArtifactOptl == null || !foundArtifactOptl.isPresent()) && !MapUtils.isEmpty(service.getToscaArtifacts())) {
3140 foundArtifactOptl = service.getToscaArtifacts().values().stream()
3141 // filters TOSCA artifact by name
3142 .filter(a -> a.getArtifactName().equals(normalizedArtifactName)).findAny();
3144 if (!foundArtifactOptl.isPresent()) {
3145 log.debug("The artifact {} was not found for service {}", normalizedArtifactName, serviceId);
3146 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, normalizedArtifactName));
3148 log.debug("Found deployment artifact {}", normalizedArtifactName);
3149 // Downloading the artifact
3150 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(foundArtifactOptl.get());
3151 if (downloadArtifactEither.isRight()) {
3152 log.debug("Download artifact {} failed", normalizedArtifactName);
3153 return Either.right(downloadArtifactEither.right().value());
3155 log.trace("Download of service artifact succeeded, uniqueId {}", foundArtifactOptl.get().getUniqueId());
3156 return Either.left(downloadArtifactEither.left().value().getRight());
3159 public Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifact(String parentId, String artifactUniqueId) {
3160 log.trace("Starting download of artifact, uniqueId {}", artifactUniqueId);
3161 Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(parentId, artifactUniqueId);
3162 if (artifactById.isRight()) {
3163 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(artifactById.right().value());
3164 log.debug("Error when getting artifact info by id{}, error: {}", artifactUniqueId, actionStatus.name());
3165 return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, ""));
3167 ArtifactDefinition artifactDefinition = artifactById.left().value();
3168 if (artifactDefinition == null) {
3169 log.debug("Empty artifact definition returned from DB by artifact id {}", artifactUniqueId);
3170 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ""));
3173 return downloadArtifact(artifactDefinition);
3176 private boolean checkArtifactInComponent(org.openecomp.sdc.be.model.Component component, String artifactId) {
3177 boolean found = false;
3178 Map<String, ArtifactDefinition> artifactsS = component.getArtifacts();
3179 if (artifactsS != null) {
3180 for (Map.Entry<String, ArtifactDefinition> entry : artifactsS.entrySet()) {
3181 if (entry.getValue().getUniqueId().equals(artifactId)) {
3187 Map<String, ArtifactDefinition> deploymentArtifactsS = component.getDeploymentArtifacts();
3188 if (!found && deploymentArtifactsS != null) {
3189 for (Map.Entry<String, ArtifactDefinition> entry : deploymentArtifactsS.entrySet()) {
3190 if (entry.getValue().getUniqueId().equals(artifactId)) {
3196 Map<String, ArtifactDefinition> toscaArtifactsS = component.getToscaArtifacts();
3197 if (!found && toscaArtifactsS != null) {
3198 for (Map.Entry<String, ArtifactDefinition> entry : toscaArtifactsS.entrySet()) {
3199 if (entry.getValue().getUniqueId().equals(artifactId)) {
3205 switch (component.getComponentType()) {
3207 Map<String, InterfaceDefinition> interfaces = ((Resource) component).getInterfaces();
3208 if (!found && interfaces != null) {
3209 for (Map.Entry<String, InterfaceDefinition> entry : interfaces.entrySet()) {
3210 Map<String, Operation> operations = entry.getValue().getOperationsMap();
3211 for (Map.Entry<String, Operation> entryOp : operations.entrySet()) {
3212 if (entryOp.getValue().getImplementation() != null && entryOp.getValue().getImplementation().getUniqueId().equals(artifactId)) {
3221 Map<String, ArtifactDefinition> apiArtifacts = ((Service) component).getServiceApiArtifacts();
3222 if (!found && apiArtifacts != null) {
3223 for (Map.Entry<String, ArtifactDefinition> entry : apiArtifacts.entrySet()) {
3224 if (entry.getValue().getUniqueId().equals(artifactId)) {
3238 private boolean checkArtifactInResourceInstance(Component component, String resourceInstanceId, String artifactId) {
3240 boolean found = false;
3241 List<ComponentInstance> resourceInstances = component.getComponentInstances();
3242 ComponentInstance resourceInstance = null;
3243 for (ComponentInstance ri : resourceInstances) {
3244 if (ri.getUniqueId().equals(resourceInstanceId)) {
3245 resourceInstance = ri;
3249 if (resourceInstance != null) {
3250 Map<String, ArtifactDefinition> artifacts = resourceInstance.getDeploymentArtifacts();
3251 if (artifacts != null) {
3252 for (Map.Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) {
3253 if (entry.getValue().getUniqueId().equals(artifactId)) {
3260 artifacts = resourceInstance.getArtifacts();
3261 if (artifacts != null) {
3262 for (Map.Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) {
3263 if (entry.getValue().getUniqueId().equals(artifactId)) {
3274 private Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists(String componentId, String userId, AuditingActionEnum auditingAction, User user, String artifactId, ComponentTypeEnum componentType,
3275 String containerComponentType, boolean inTransaction) {
3277 ComponentTypeEnum componentForAudit = null == containerComponentType ? componentType : ComponentTypeEnum.findByParamName(containerComponentType);
3278 componentForAudit.getNodeType();
3280 Either<? extends org.openecomp.sdc.be.model.Component, StorageOperationStatus> componentResult = toscaOperationFacade.getToscaFullElement(componentId);
3282 if (componentResult.isRight()) {
3283 ActionStatus status = componentForAudit == ComponentTypeEnum.RESOURCE ? ActionStatus.RESOURCE_NOT_FOUND : componentType == ComponentTypeEnum.SERVICE ? ActionStatus.SERVICE_NOT_FOUND : ActionStatus.PRODUCT_NOT_FOUND;
3284 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, componentId);
3285 log.debug("Service not found, serviceId {}", componentId);
3286 handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentForAudit, null);
3287 return Either.right(responseFormat);
3289 return Either.left(componentResult.left().value());
3292 private Either<Boolean, ResponseFormat> validateWorkOnComponent(org.openecomp.sdc.be.model.Component component, String userId, AuditingActionEnum auditingAction, User user, String artifactId, ArtifactOperationInfo operation,
3293 ComponentTypeEnum componentType) {
3294 if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.Download && !operation.ignoreLifecycleState()) {
3295 Either<Boolean, ResponseFormat> canWork = validateCanWorkOnComponent(component, userId);
3296 if (canWork.isRight()) {
3297 String uniqueId = component.getUniqueId();
3298 log.debug("Service status isn't CHECKOUT or user isn't owner, serviceId {}", uniqueId);
3299 handleAuditing(auditingAction, component, uniqueId, user, null, null, artifactId, canWork.right().value(), component.getComponentType(), null);
3300 return Either.right(canWork.right().value());
3303 return Either.left(true);
3306 private Either<Boolean, ResponseFormat> validateUserRole(User user, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType, ArtifactOperationInfo operation) {
3308 if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.Download) {
3309 String role = user.getRole();
3310 if (!role.equals(Role.ADMIN.name()) && !role.equals(Role.DESIGNER.name())) {
3311 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
3312 log.debug("addArtifact - user isn't permitted to perform operation, userId {}, role {}", user.getUserId(), role);
3313 handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentType, null);
3314 return Either.right(responseFormat);
3317 return Either.left(true);
3320 private Either<User, ResponseFormat> validateUserExists(String userId, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType, boolean inTransaction) {
3321 Either<User, ResponseFormat> validateUserExists = validateUserExists(userId, auditingAction.getName(), inTransaction);
3323 if (validateUserExists.isRight()) {
3324 User user = new User();
3325 user.setUserId(userId);
3326 handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, validateUserExists.right().value(), componentType, null);
3327 return Either.right(validateUserExists.right().value());
3329 return Either.left(validateUserExists.left().value());
3332 protected AuditingActionEnum detectAuditingType(ArtifactOperationInfo operation, String origMd5) {
3333 AuditingActionEnum auditingAction = null;
3334 switch (operation.getArtifactOperationEnum()) {
3336 auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_UPLOAD_BY_API : AuditingActionEnum.ARTIFACT_UPLOAD;
3339 auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_UPLOAD_BY_API : origMd5 == null ? AuditingActionEnum.ARTIFACT_METADATA_UPDATE : AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE;
3342 auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_DELETE_BY_API : AuditingActionEnum.ARTIFACT_DELETE;
3345 auditingAction = operation.isExternalApi() ? AuditingActionEnum.DOWNLOAD_ARTIFACT : AuditingActionEnum.ARTIFACT_DOWNLOAD;
3350 return auditingAction;
3353 private Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifact(ArtifactDefinition artifactDefinition) {
3354 String esArtifactId = artifactDefinition.getEsId();
3355 Either<ESArtifactData, CassandraOperationStatus> artifactfromES = artifactCassandraDao.getArtifact(esArtifactId);
3356 if (artifactfromES.isRight()) {
3357 CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value();
3358 StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
3359 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
3360 log.debug("Error when getting artifact from ES, error: {}", actionStatus.name());
3361 return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, artifactDefinition.getArtifactDisplayName()));
3364 ESArtifactData esArtifactData = artifactfromES.left().value();
3365 byte[] data = esArtifactData.getDataAsArray();
3367 log.debug("Artifact data from ES is null");
3368 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactDefinition.getArtifactDisplayName()));
3370 String artifactName = artifactDefinition.getArtifactName();
3371 log.trace("Download of artifact succeeded, uniqueId {}, artifact file name {}", artifactDefinition.getUniqueId(), artifactName);
3372 return Either.left(new ImmutablePair<String, byte[]>(artifactName, data));
3375 public ESArtifactData createEsArtifactData(ArtifactDataDefinition artifactInfo, byte[] artifactPayload) {
3376 ESArtifactData artifactData = new ESArtifactData(artifactInfo.getEsId(), artifactPayload);
3377 return artifactData;
3380 private boolean saveArtifacts(ESArtifactData artifactData, String resourceId, boolean reload) {
3382 CassandraOperationStatus resourceUploadStatus = artifactCassandraDao.saveArtifact(artifactData);
3384 if (resourceUploadStatus.equals(CassandraOperationStatus.OK)) {
3385 log.debug("Artifact {} was saved in component .", artifactData.getId(), resourceId);
3387 log.info("Failed to save artifact {}.", artifactData.getId());
3393 private boolean isArtifactMetadataUpdate(AuditingActionEnum auditingActionEnum) {
3394 return (auditingActionEnum.equals(AuditingActionEnum.ARTIFACT_METADATA_UPDATE));
3397 private boolean isDeploymentArtifact(ArtifactDefinition artifactInfo) {
3398 return (ArtifactGroupTypeEnum.DEPLOYMENT.equals(artifactInfo.getArtifactGroupType()));
3401 public Either<ArtifactDefinition, ResponseFormat> createArtifactPlaceHolderInfo(String resourceId, String logicalName, Map<String, Object> artifactInfoMap, String userUserId, ArtifactGroupTypeEnum groupType, boolean inTransaction) {
3402 Either<User, ActionStatus> user = userAdminManager.getUser(userUserId, inTransaction);
3403 if (user.isRight()) {
3404 ResponseFormat responseFormat;
3405 if (user.right().value().equals(ActionStatus.USER_NOT_FOUND)) {
3406 log.debug("create artifact placeholder - not authorized user, userId {}", userUserId);
3407 responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
3409 log.debug("create artifact placeholder - failed to authorize user, userId {}", userUserId);
3410 responseFormat = componentsUtils.getResponseFormat(user.right().value());
3412 return Either.right(responseFormat);
3415 ArtifactDefinition artifactDefinition = createArtifactPlaceHolderInfo(resourceId, logicalName, artifactInfoMap, user.left().value(), groupType);
3416 return Either.left(artifactDefinition);
3419 public ArtifactDefinition createArtifactPlaceHolderInfo(String resourceId, String logicalName, Map<String, Object> artifactInfoMap, User user, ArtifactGroupTypeEnum groupType) {
3420 ArtifactDefinition artifactInfo = new ArtifactDefinition();
3422 String artifactName = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_DISPLAY_NAME);
3423 String artifactType = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_TYPE);
3424 String artifactDescription = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_DESCRIPTION);
3426 artifactInfo.setArtifactDisplayName(artifactName);
3427 artifactInfo.setArtifactLabel(logicalName.toLowerCase());
3428 artifactInfo.setArtifactType(artifactType);
3429 artifactInfo.setDescription(artifactDescription);
3430 artifactInfo.setArtifactGroupType(groupType);
3431 nodeTemplateOperation.setDefaultArtifactTimeout(groupType, artifactInfo);
3433 setArtifactPlaceholderCommonFields(resourceId, user, artifactInfo);
3435 return artifactInfo;
3438 private void setArtifactPlaceholderCommonFields(String resourceId, User user, ArtifactDefinition artifactInfo) {
3439 String uniqueId = null;
3441 if (resourceId != null) {
3442 uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId.toLowerCase(), artifactInfo.getArtifactLabel().toLowerCase());
3443 artifactInfo.setUniqueId(uniqueId);
3445 artifactInfo.setUserIdCreator(user.getUserId());
3446 String fullName = user.getFullName();
3447 artifactInfo.setUpdaterFullName(fullName);
3449 long time = System.currentTimeMillis();
3451 artifactInfo.setCreatorFullName(fullName);
3452 artifactInfo.setCreationDate(time);
3454 artifactInfo.setLastUpdateDate(time);
3455 artifactInfo.setUserIdLastUpdater(user.getUserId());
3457 artifactInfo.setMandatory(true);
3460 public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(String parentId, NodeTypeEnum parentType, boolean inTransaction, ArtifactGroupTypeEnum groupType, String instanceId) {
3461 return artifactToscaOperation.getArtifacts(parentId, parentType, groupType, instanceId);
3464 public Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact(ArtifactDefinition artifactHeatEnv, ArtifactDefinition artifact, String componentId, NodeTypeEnum parentType, String instanceId) {
3465 return artifactToscaOperation.addHeatEnvArtifact(artifactHeatEnv, artifact, componentId, parentType, true, instanceId);
3468 private Either<ESArtifactData, ResponseFormat> createEsHeatEnvArtifactDataFromString(ArtifactDefinition artifactDefinition, String payloadStr) {
3470 byte[] payload = payloadStr.getBytes();
3472 ESArtifactData artifactData = createEsArtifactData(artifactDefinition, payload);
3473 return Either.left(artifactData);
3478 * @param artifactDefinition
3481 public Either<ArtifactDefinition, ResponseFormat> generateHeatEnvArtifact(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier,
3482 boolean shouldLock, String instanceId) {
3483 String payload = generateHeatEnvPayload(artifactDefinition);
3484 String prevUUID = artifactDefinition.getArtifactUUID();
3485 ArtifactDefinition clonedBeforeGenerate = new ArtifactDefinition(artifactDefinition);
3486 Either<ArtifactDefinition, ResponseFormat> generateResult = generateAndSaveHeatEnvArtifact(artifactDefinition, payload, componentType, component, resourceInstanceName, modifier, shouldLock, instanceId);
3487 if (generateResult.isLeft()) {
3488 ArtifactDefinition updatedArtDef = generateResult.left().value();
3489 if (!prevUUID.equals(updatedArtDef.getArtifactUUID())) {
3490 List<ComponentInstance> componentInstances = component.getComponentInstances();
3491 if (componentInstances != null) {
3492 Optional<ComponentInstance> findFirst = componentInstances.stream().filter(ci -> ci.getUniqueId().equals(instanceId)).findFirst();
3493 if (findFirst.isPresent()) {
3494 ComponentInstance relevantInst = findFirst.get();
3495 List<GroupInstance> updatedGroupInstances = getUpdatedGroupInstances(updatedArtDef.getUniqueId(), clonedBeforeGenerate, relevantInst.getGroupInstances());
3497 if (CollectionUtils.isNotEmpty(updatedGroupInstances)) {
3498 updatedGroupInstances.forEach(gi -> {
3499 gi.getGroupInstanceArtifacts().add(updatedArtDef.getUniqueId());
3500 gi.getGroupInstanceArtifactsUuid().add(updatedArtDef.getArtifactUUID());
3502 Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(component, componentType, instanceId, updatedGroupInstances);
3503 if (status.isRight()) {
3504 log.debug("Failed to update groups of the component {}. ", component.getUniqueId());
3505 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status.right().value()), clonedBeforeGenerate.getArtifactDisplayName());
3506 return Either.right(responseFormat);
3514 return generateResult;
3517 private String generateHeatEnvPayload(ArtifactDefinition artifactDefinition) {
3518 List<HeatParameterDefinition> heatParameters = artifactDefinition.getListHeatParameters();
3519 heatParameters.sort(Comparator.comparing(e -> e.getName()));
3520 StringBuilder sb = new StringBuilder();
3521 sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactHeader());
3522 sb.append("parameters:\n");
3523 if (heatParameters != null) {
3524 List<HeatParameterDefinition> empltyHeatValues = new ArrayList<>();
3526 for (HeatParameterDefinition heatParameterDefinition : heatParameters) {
3528 String heatValue = heatParameterDefinition.getCurrentValue();
3529 if (!ValidationUtils.validateStringNotEmpty(heatValue)) {
3530 heatValue = heatParameterDefinition.getDefaultValue();
3531 if (!ValidationUtils.validateStringNotEmpty(heatValue)) {
3532 empltyHeatValues.add(heatParameterDefinition);
3536 HeatParameterType type = HeatParameterType.isValidType(heatParameterDefinition.getType());
3540 sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(Boolean.parseBoolean(heatValue)).append("\n");
3543 sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(new BigDecimal(heatValue).toPlainString()).append("\n");
3545 case COMMA_DELIMITED_LIST:
3547 sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(heatValue).append("\n");
3550 String value = heatValue;
3551 boolean starts = value.startsWith("\"");
3552 boolean ends = value.endsWith("\"");
3553 if (!(starts && ends)) {
3554 starts = value.startsWith("'");
3555 ends = value.endsWith("'");
3556 if (!(starts && ends)) {
3557 value = "\"" + value + "\"";
3560 sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(value);
3567 if (!empltyHeatValues.isEmpty()) {
3568 empltyHeatValues.sort(Comparator.comparing(e -> e.getName()));
3569 empltyHeatValues.forEach(hv -> {
3570 sb.append(" ").append(hv.getName()).append(":");
3571 HeatParameterType type = HeatParameterType.isValidType(hv.getType());
3572 if (type != null && type == HeatParameterType.STRING && (hv.getCurrentValue() != null && "".equals(hv.getCurrentValue()) || hv.getDefaultValue() != null && "".equals(hv.getDefaultValue()))) {
3573 sb.append(" \"\"").append("\n");
3575 sb.append(" ").append("\n");
3580 sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactFooter());
3583 String result = sb.toString().replaceAll("\\\\n", "\n");
3590 * @param artifactDefinition
3594 public Either<ArtifactDefinition, ResponseFormat> generateAndSaveHeatEnvArtifact(ArtifactDefinition artifactDefinition, String payload, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName,
3595 User modifier, boolean shouldLock, String instanceId) {
3596 return generateArtifactPayload(artifactDefinition, componentType, component, resourceInstanceName, modifier, shouldLock, () -> artifactDefinition.getHeatParamsUpdateDate(),
3597 () -> createEsHeatEnvArtifactDataFromString(artifactDefinition, payload), instanceId);
3601 protected Either<ArtifactDefinition, ResponseFormat> generateArtifactPayload(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier,
3602 boolean shouldLock, Supplier<Long> payloadUpdateDateGen, Supplier<Either<ESArtifactData, ResponseFormat>> esDataCreator, String instanceId) {
3604 if (artifactDefinition.getPayloadUpdateDate() == null || artifactDefinition.getPayloadUpdateDate() == 0 || artifactDefinition.getPayloadUpdateDate() < payloadUpdateDateGen.get()) {
3606 log.trace("Generaing 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 updateArifactDefinitionStatus = artifactToscaOperation.updateArifactOnResource(artifactDefinition, component.getUniqueId(), artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId);
3670 log.trace("Update Payload ", artifactDefinition.getEsId());
3672 if (updateArifactDefinitionStatus != null && updateArifactDefinitionStatus.isLeft()) {
3674 artifactDefinition = updateArifactDefinitionStatus.left().value();
3675 artifactData.setId(artifactDefinition.getUniqueId());
3676 CassandraOperationStatus saveArtifactStatus = artifactCassandraDao.saveArtifact(artifactData);
3678 if (saveArtifactStatus.equals(CassandraOperationStatus.OK)) {
3680 log.debug("Artifact Saved In ES {}", artifactData.getId());
3681 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
3682 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
3683 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
3686 titanDao.rollback();
3687 log.info("Failed to save artifact {}.", artifactData.getId());
3688 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
3689 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
3690 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
3692 return Either.right(responseFormat);
3695 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus.right().value()), artifactDefinition.getArtifactDisplayName());
3696 log.debug("Failed To update artifact {}", artifactData.getId());
3697 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
3698 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
3700 return Either.right(responseFormat);
3705 graphLockOperation.unlockComponent(component.getUniqueId(), component.getComponentType().getNodeType());
3710 return Either.left(artifactDefinition);
3713 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdateHeatEnv(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType,
3714 org.openecomp.sdc.be.model.Component parent, String originData, String origMd5, ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) {
3715 convertParentType(componentType);
3716 String parentId = parent.getUniqueId();
3717 // Either<ArtifactDefinition, StorageOperationStatus> artifactRes = this.artifactToscaOperation.getArtifactById(componentId, artifactId);
3718 ArtifactDefinition currArtifact = artifactInfo;
3720 if (origMd5 != null) {
3721 Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
3722 if (validateMd5.isRight()) {
3723 ResponseFormat responseFormat = validateMd5.right().value();
3724 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
3725 return Either.right(responseFormat);
3728 if (artifactInfo.getPayloadData() != null && artifactInfo.getPayloadData().length != 0) {
3729 Either<Boolean, ResponseFormat> deploymentValidationResult = validateDeploymentArtifact(parent, componentId, user.getUserId(), false, artifactInfo, currArtifact, NodeTypeEnum.ResourceInstance);
3730 if (deploymentValidationResult.isRight()) {
3731 ResponseFormat responseFormat = deploymentValidationResult.right().value();
3732 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
3733 return Either.right(responseFormat);
3736 Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
3737 if (payloadEither.isRight()) {
3738 ResponseFormat responseFormat = payloadEither.right().value();
3739 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
3740 return Either.right(responseFormat);
3742 } else { // duplicate
3743 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
3744 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
3745 return Either.right(responseFormat);
3751 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Update Artifact - lock ");
3752 if (lockComponent.isRight()) {
3753 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right().value(), componentType, null);
3754 return Either.right(lockComponent.right().value());
3757 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
3759 resultOp = updateHeatEnvParams(componentId, artifactId, artifactInfo, user, auditingAction, parent, componentType, currArtifact, origMd5, inTransaction);
3764 if (resultOp == null || resultOp.isRight()) {
3765 log.debug("all changes rollback");
3766 if (false == inTransaction)
3767 titanDao.rollback();
3769 log.debug("all changes committed");
3770 if (false == inTransaction)
3774 componentType = parent.getComponentType();
3775 NodeTypeEnum nodeType = componentType.getNodeType();
3776 graphLockOperation.unlockComponent(parent.getUniqueId(), nodeType);
3777 // graphLockOperation.unlockComponent(parentId, parentType);
3781 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateHeatEnvParams(String componentId, String artifactId, ArtifactDefinition artifactInfo, User user, AuditingActionEnum auditingAction, Component parent,
3782 ComponentTypeEnum componentType, ArtifactDefinition currArtifact1, String origMd5, boolean inTransaction) {
3784 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
3785 Either<ArtifactDefinition, Operation> insideEither = null;
3787 * currently getArtifactById does not retrieve heatParameters Either<ArtifactDefinition, StorageOperationStatus> artifactRes = artifactOperation.getArtifactById(artifactId, false); ArtifactDefinition currArtifact = artifactRes.left().value();
3789 Either<ComponentInstance, ResponseFormat> getRI = getRIFromComponent(parent, componentId, artifactId, auditingAction, user);
3790 if (getRI.isRight()) {
3791 return Either.right(getRI.right().value());
3793 ComponentInstance ri = getRI.left().value();
3794 Either<ArtifactDefinition, ResponseFormat> getArtifactRes = getArtifactFromRI(parent, ri, componentId, artifactId, auditingAction, user);
3795 if (getArtifactRes.isRight()) {
3796 return Either.right(getArtifactRes.right().value());
3798 ArtifactDefinition currArtifact = getArtifactRes.left().value();
3800 if (currArtifact.getArtifactType().equals(ArtifactTypeEnum.HEAT.getType()) || currArtifact.getArtifactType().equals(ArtifactTypeEnum.HEAT_VOL.getType()) || currArtifact.getArtifactType().equals(ArtifactTypeEnum.HEAT_NET.getType())) {
3801 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
3802 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
3803 return Either.right(responseFormat);
3805 List<HeatParameterDefinition> currentHeatEnvParams = currArtifact.getListHeatParameters();
3806 List<HeatParameterDefinition> updatedHeatEnvParams = artifactInfo.getListHeatParameters();
3807 new ArrayList<HeatParameterDefinition>();
3810 if (origMd5 != null) {
3811 Either<List<HeatParameterDefinition>, ResponseFormat> uploadParamsValidationResult = validateUploadParamsFromEnvFile(auditingAction, parent, user, artifactInfo, artifactId, componentType, ri.getName(), currentHeatEnvParams,
3812 updatedHeatEnvParams, currArtifact.getArtifactName());
3813 if (uploadParamsValidationResult.isRight()) {
3814 ResponseFormat responseFormat = uploadParamsValidationResult.right().value();
3815 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
3816 return Either.right(responseFormat);
3818 artifactInfo.setListHeatParameters(updatedHeatEnvParams);
3821 Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers = validateAndConvertHeatParamers(artifactInfo, ArtifactTypeEnum.HEAT_ENV.getType());
3822 if (validateAndConvertHeatParamers.isRight()) {
3823 ResponseFormat responseFormat = validateAndConvertHeatParamers.right().value();
3824 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
3825 return Either.right(responseFormat);
3828 if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty()) {
3830 // fill reduced heat env parameters List for updating
3831 for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) {
3832 paramName = heatEnvParam.getName();
3833 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
3834 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
3835 String updatedParamValue = heatEnvParam.getCurrentValue();
3836 if (updatedParamValue != null && updatedParamValue.equals("")) { // reset
3837 currHeatParam.setCurrentValue(heatEnvParam.getDefaultValue());
3838 } else if (updatedParamValue != null) {
3839 currHeatParam.setCurrentValue(updatedParamValue);
3844 currArtifact.setHeatParamsUpdateDate(System.currentTimeMillis());
3845 currArtifact.setListHeatParameters(currentHeatEnvParams);
3847 Either<ArtifactDefinition, StorageOperationStatus> updateArifactRes = artifactToscaOperation.updateArifactOnResource(currArtifact, parent.getUniqueId(), currArtifact.getUniqueId(), componentType.getNodeType(), componentId);
3848 if (updateArifactRes.isRight()) {
3849 log.debug("Failed to update artifact on graph - {}", artifactId);
3850 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateArifactRes.right().value()));
3851 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
3852 return Either.right(responseFormat);
3854 StorageOperationStatus error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), ri.getUniqueId(), componentType);
3855 if (error != StorageOperationStatus.OK) {
3856 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
3857 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
3858 return Either.right(responseFormat);
3861 error = generateCustomizationUUIDOnGroupInstance(ri, updateArifactRes.left().value().getUniqueId(), parent.getUniqueId());
3862 if (error != StorageOperationStatus.OK) {
3863 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
3864 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
3865 return Either.right(responseFormat);
3871 insideEither = Either.left(currArtifact);
3872 resultOp = Either.left(insideEither);
3873 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
3874 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currArtifact, null, artifactId, responseFormat, componentType, ri.getName());
3878 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateHeatParams(String componentId, String artifactId, ArtifactDefinition artifactEnvInfo, User user, AuditingActionEnum auditingAction, Component parent,
3879 ComponentTypeEnum componentType, ArtifactDefinition currHeatArtifact, String origMd5, boolean needToUpdateGroup) {
3881 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
3882 Either<ArtifactDefinition, Operation> insideEither = null;
3884 * currently getArtifactById does not retrieve heatParameters Either<ArtifactDefinition, StorageOperationStatus> artifactRes = artifactOperation.getArtifactById(artifactId, false); ArtifactDefinition currArtifact = artifactRes.left().value();
3886 String currentHeatId = currHeatArtifact.getUniqueId();
3888 String esArtifactId = currHeatArtifact.getEsId();
3889 Either<ESArtifactData, CassandraOperationStatus> artifactfromES = artifactCassandraDao.getArtifact(esArtifactId);
3890 if (artifactfromES.isRight()) {
3891 CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value();
3892 StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
3893 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
3894 log.debug("Error when getting artifact from ES, error: {}", actionStatus.name());
3895 return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, currHeatArtifact.getArtifactDisplayName()));
3898 ESArtifactData esArtifactData = artifactfromES.left().value();
3899 byte[] data = esArtifactData.getDataAsArray();
3902 ArtifactDefinition updatedHeatArt = currHeatArtifact;
3904 List<HeatParameterDefinition> updatedHeatEnvParams = artifactEnvInfo.getListHeatParameters();
3905 List<HeatParameterDefinition> currentHeatEnvParams = currHeatArtifact.getListHeatParameters();
3906 List<HeatParameterDefinition> newHeatEnvParams = new ArrayList<HeatParameterDefinition>();
3908 if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty() && currentHeatEnvParams != null && !currentHeatEnvParams.isEmpty()) {
3911 for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) {
3913 paramName = heatEnvParam.getName();
3914 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
3915 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
3917 String updatedParamValue = heatEnvParam.getCurrentValue();
3918 if (updatedParamValue == null)
3919 updatedParamValue = heatEnvParam.getDefaultValue();
3920 HeatParameterType paramType = HeatParameterType.isValidType(currHeatParam.getType());
3921 if (!paramType.getValidator().isValid(updatedParamValue, null)) {
3922 ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE;
3923 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, ArtifactTypeEnum.HEAT_ENV.getType(), paramType.getType(), paramName);
3924 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactEnvInfo, null, artifactId, responseFormat, componentType, "");
3925 return Either.right(responseFormat);
3928 currHeatParam.setCurrentValue(paramType.getConverter().convert(updatedParamValue, null, null));
3929 newHeatEnvParams.add(currHeatParam);
3934 if (!newHeatEnvParams.isEmpty()) {
3935 currHeatArtifact.setListHeatParameters(currentHeatEnvParams);
3936 Either<ArtifactDefinition, StorageOperationStatus> operationStatus = artifactToscaOperation.updateArifactOnResource(currHeatArtifact, parent.getUniqueId(), currHeatArtifact.getUniqueId(), componentType.getNodeType(), componentId);
3938 if (operationStatus.isRight()) {
3939 log.debug("Failed to update artifact on graph - {}", currHeatArtifact.getUniqueId());
3941 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(operationStatus.right().value()));
3942 return Either.right(responseFormat);
3945 updatedHeatArt = operationStatus.left().value();
3947 if (!updatedHeatArt.getDuplicated() || esArtifactData.getId() == null)
3948 esArtifactData.setId(updatedHeatArt.getEsId());
3949 res = saveArtifacts(esArtifactData, parent.getUniqueId(), false);
3952 log.debug("Artifact saved into ES - {}", updatedHeatArt.getUniqueId());
3953 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
3954 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, updatedHeatArt, currentHeatId, updatedHeatArt.getUniqueId(), responseFormat, componentType, null);
3955 // resultOp = Either.left(result.left().value());
3958 BeEcompErrorManager.getInstance().logBeDaoSystemError("Update Artifact");
3959 log.debug("Failed to save the artifact.");
3960 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
3961 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, updatedHeatArt, currentHeatId, updatedHeatArt.getUniqueId(), responseFormat, componentType, null);
3962 resultOp = Either.right(responseFormat);
3966 insideEither = Either.left(updatedHeatArt);
3969 Either<ArtifactDefinition, StorageOperationStatus> updateHeatEnvArtifact;
3970 if (!currentHeatId.equals(updatedHeatArt.getUniqueId())) {
3971 artifactEnvInfo.setArtifactChecksum(null);
3972 updateHeatEnvArtifact = artifactToscaOperation.updateHeatEnvArtifact(parent.getUniqueId(), artifactEnvInfo, currentHeatId, updatedHeatArt.getUniqueId(), componentType.getNodeType(), componentId);
3974 updateHeatEnvArtifact = artifactToscaOperation.updateHeatEnvPlaceholder(artifactEnvInfo, componentId, componentType.getNodeType());
3977 if ( needToUpdateGroup && updateHeatEnvArtifact.isLeft() ){
3978 ActionStatus result = updateGroupForHeat(currHeatArtifact, updatedHeatArt, artifactEnvInfo, updateHeatEnvArtifact.left().value(), parent, componentType);
3979 if ( result != ActionStatus.OK ){
3980 ResponseFormat responseFormat = componentsUtils.getResponseFormat(result);
3981 return Either.right(responseFormat);
3984 resultOp = Either.left(insideEither);
3985 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
3986 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currHeatArtifact, null, artifactId, responseFormat, componentType, "");
3991 private StorageOperationStatus generateCustomizationUUIDOnGroupInstance(ComponentInstance ri, String artifactId, String componentId) {
3992 StorageOperationStatus error = StorageOperationStatus.OK;
3993 log.debug("Need to re-generate customization UUID for group instance on component instance {}", ri.getUniqueId());
3994 List<GroupInstance> groupsInstances = ri.getGroupInstances();
3995 // List<GroupInstance> associatedGroups = null;
3996 List<String> groupInstancesId = null;
3997 if (groupsInstances != null && !groupsInstances.isEmpty()) {
3998 groupInstancesId = groupsInstances.stream().filter(p -> p.getGroupInstanceArtifacts() != null && p.getGroupInstanceArtifacts().contains(artifactId)).map(p -> p.getUniqueId()).collect(Collectors.toList());
4000 if (groupInstancesId != null && !groupInstancesId.isEmpty()) {
4001 // associatedGroups.stream().forEach(c -> this.groupInstanceOperation.updateCustomizationUUID(c.getUniqueId()));
4002 toscaOperationFacade.generateCustomizationUUIDOnInstanceGroup(componentId, ri.getUniqueId(), groupInstancesId);
4008 public Either<List<HeatParameterDefinition>, ResponseFormat> validateUploadParamsFromEnvFile(AuditingActionEnum auditingAction, Component parent, User user, ArtifactDefinition artifactInfo, String artifactId, ComponentTypeEnum componentType,
4009 String riName, List<HeatParameterDefinition> currentHeatEnvParams, List<HeatParameterDefinition> updatedHeatEnvParams, String currArtifactName) {
4011 if (updatedHeatEnvParams == null || updatedHeatEnvParams.isEmpty()) {
4012 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactInfo.getArtifactName(), currArtifactName);
4013 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, riName);
4014 return Either.right(responseFormat);
4017 for (HeatParameterDefinition uploadedHeatParam : updatedHeatEnvParams) {
4018 String paramName = uploadedHeatParam.getName();
4019 boolean isExistsInHeat = false;
4020 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
4021 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
4023 isExistsInHeat = true;
4024 uploadedHeatParam.setType(currHeatParam.getType());
4025 uploadedHeatParam.setCurrentValue(uploadedHeatParam.getDefaultValue());
4026 uploadedHeatParam.setDefaultValue(currHeatParam.getDefaultValue());
4027 uploadedHeatParam.setUniqueId(currHeatParam.getUniqueId());
4031 if (!isExistsInHeat) {
4032 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, currArtifactName);
4033 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, riName);
4034 return Either.right(responseFormat);
4037 return Either.left(updatedHeatEnvParams);
4040 private Either<ComponentInstance, ResponseFormat> getRIFromComponent(Component component, String riID, String artifactId, AuditingActionEnum auditingAction, User user) {
4041 ResponseFormat responseFormat = null;
4042 List<ComponentInstance> ris = component.getComponentInstances();
4043 for (ComponentInstance ri : ris) {
4044 if (riID.equals(ri.getUniqueId())) {
4045 return Either.left(ri);
4048 responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, riID);
4049 log.debug("Resource Instance not found, resourceInstanceId {}", riID);
4050 handleAuditing(auditingAction, null, riID, user, null, null, artifactId, responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE, null);
4051 return Either.right(responseFormat);
4054 private Either<ArtifactDefinition, ResponseFormat> getArtifactFromRI(Component component, ComponentInstance ri, String riID, String artifactId, AuditingActionEnum auditingAction, User user) {
4055 ResponseFormat responseFormat = null;
4056 Map<String, ArtifactDefinition> rtifactsMap = ri.getDeploymentArtifacts();
4057 for (ArtifactDefinition artifact : rtifactsMap.values()) {
4058 if (artifactId.equals(artifact.getUniqueId())) {
4059 return Either.left(artifact);
4062 responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, riID, component.getUniqueId());
4063 handleAuditing(auditingAction, component, riID, user, null, null, artifactId, responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE, ri.getName());
4064 return Either.right(responseFormat);
4067 public ArtifactDefinition extractArtifactDefinition(Either<ArtifactDefinition, Operation> eitherArtifact) {
4068 ArtifactDefinition ret;
4069 if (eitherArtifact.isLeft()) {
4070 ret = eitherArtifact.left().value();
4072 ret = eitherArtifact.right().value().getImplementationArtifact();
4078 * downloads artifact of component by UUIDs
4080 * @param componentType
4081 * @param componentUuid
4082 * @param artifactUUID
4083 * @param auditAdditionalParam
4086 public Either<byte[], ResponseFormat> downloadComponentArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String artifactUUID, Map<AuditingFieldsKeysEnum, Object> auditAdditionalParam) {
4087 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4088 Either<byte[], ResponseFormat> result;
4089 byte[] downloadedArtifact = null;
4090 Component component = getLatestComponentByUuid(componentType, componentUuid, errorWrapper);
4091 if (errorWrapper.isEmpty()) {
4092 auditAdditionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, component.getName());
4093 downloadedArtifact = downloadArtifact(component.getDeploymentArtifacts(), artifactUUID, errorWrapper, component.getName());
4095 if (errorWrapper.isEmpty()) {
4096 result = Either.left(downloadedArtifact);
4098 result = Either.right(errorWrapper.getInnerElement());
4104 * downloads an artifact of resource instance of component by UUIDs
4106 * @param componentType
4107 * @param componentUuid
4108 * @param resourceName
4109 * @param artifactUUID
4110 * @param auditAdditionalParam
4113 public Either<byte[], ResponseFormat> downloadResourceInstanceArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID, Map<AuditingFieldsKeysEnum, Object> auditAdditionalParam) {
4114 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4115 Either<byte[], ResponseFormat> result;
4116 byte[] downloadedArtifact = null;
4117 ComponentInstance resourceInstance = getRelatedComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
4118 if (errorWrapper.isEmpty()) {
4119 downloadedArtifact = downloadArtifact(resourceInstance.getDeploymentArtifacts(), artifactUUID, errorWrapper, resourceInstance.getName());
4121 if (errorWrapper.isEmpty()) {
4122 result = Either.left(downloadedArtifact);
4124 result = Either.right(errorWrapper.getInnerElement());
4130 * uploads an artifact to a component by UUID
4134 * @param componentType
4135 * @param componentUuid
4136 * @param additionalParams
4140 public Either<ArtifactDefinition, ResponseFormat> uploadArtifactToComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, Map<AuditingFieldsKeysEnum, Object> additionalParams,
4141 ArtifactOperationInfo operation) {
4142 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4143 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4144 Either<ArtifactDefinition, ResponseFormat> uploadArtifactResult;
4145 ArtifactDefinition uploadArtifact = null;
4146 Component component = null;
4147 String componentId = null;
4148 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
4149 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4150 String userId = request.getHeader(Constants.USER_ID_HEADER);
4152 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4153 if (getComponentRes.isRight()) {
4154 StorageOperationStatus status = getComponentRes.right().value();
4155 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4156 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), componentUuid));
4158 if (errorWrapper.isEmpty()) {
4159 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
4160 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
4162 if (!getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4163 component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
4164 if (component != null) {
4165 componentId = component.getUniqueId();
4166 componentName = component.getName();
4169 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentName);
4171 if (errorWrapper.isEmpty()) {
4172 actionResult = handleArtifactRequest(componentId, userId, componentType, operation, null, artifactInfo, origMd5, data, null, null, null, null);
4173 if (actionResult.isRight()) {
4174 log.debug("Failed to upload artifact to component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, actionResult.right().value());
4175 errorWrapper.setInnerElement(actionResult.right().value());
4178 if (errorWrapper.isEmpty()) {
4179 uploadArtifact = actionResult.left().value().left().value();
4180 uploadArtifactResult = Either.left(uploadArtifact);
4182 uploadArtifactResult = Either.right(errorWrapper.getInnerElement());
4184 updateAuditParametersWithArtifactDefinition(additionalParams, uploadArtifact);
4185 return uploadArtifactResult;
4189 * upload an artifact to a resource instance by UUID
4193 * @param componentType
4194 * @param componentUuid
4195 * @param resourceInstanceName
4196 * @param additionalParams
4200 public Either<ArtifactDefinition, ResponseFormat> uploadArtifactToRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName,
4201 Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
4202 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4203 Either<ArtifactDefinition, ResponseFormat> uploadArtifactResult;
4204 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4205 ArtifactDefinition uploadArtifact = null;
4206 Component component = null;
4207 String componentInstanceId;
4209 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4210 String userId = request.getHeader(Constants.USER_ID_HEADER);
4212 ImmutablePair<Component, ComponentInstance> componentRiPair = null;
4213 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4214 if (getComponentRes.isRight()) {
4215 StorageOperationStatus status = getComponentRes.right().value();
4216 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4217 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), resourceInstanceName));
4219 if (errorWrapper.isEmpty() && !getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4220 component = checkoutParentComponent(componentType, getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(), userId, errorWrapper);
4222 if (errorWrapper.isEmpty()) {
4223 if (component == null) {
4224 componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
4226 componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
4229 if (errorWrapper.isEmpty()) {
4230 componentInstanceId = componentRiPair.getRight().getUniqueId();
4231 componentId = componentRiPair.getLeft().getUniqueId();
4232 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
4234 actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, null, artifactInfo, origMd5, data, null, null, componentId, ComponentTypeEnum.findParamByType(componentType));
4235 if (actionResult.isRight()) {
4236 log.debug("Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. ", resourceInstanceName, componentType, componentUuid, actionResult.right().value());
4237 errorWrapper.setInnerElement(actionResult.right().value());
4240 if (errorWrapper.isEmpty()) {
4241 uploadArtifact = actionResult.left().value().left().value();
4242 uploadArtifactResult = Either.left(uploadArtifact);
4244 uploadArtifactResult = Either.right(errorWrapper.getInnerElement());
4246 updateAuditParametersWithArtifactDefinition(additionalParams, uploadArtifact);
4247 return uploadArtifactResult;
4251 * updates an artifact on a component by UUID
4255 * @param componentType
4256 * @param componentUuid
4257 * @param artifactUUID
4258 * @param additionalParams
4263 public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID,
4264 Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
4265 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4266 Either<ArtifactDefinition, ResponseFormat> updateArtifactResult;
4267 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4268 ArtifactDefinition updateArtifact = null;
4269 Component component = null;
4270 String componentId = null;
4271 String artifactId = null;
4272 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
4273 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4274 String userId = request.getHeader(Constants.USER_ID_HEADER);
4276 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4277 if (getComponentRes.isRight()) {
4278 StorageOperationStatus status = getComponentRes.right().value();
4279 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4280 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4282 if (errorWrapper.isEmpty()) {
4283 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
4284 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
4286 if (!getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4287 component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
4288 if (component != null) {
4289 componentId = component.getUniqueId();
4290 componentName = component.getName();
4293 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentName);
4295 if (errorWrapper.isEmpty()) {
4296 artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentId, componentType);
4298 if (errorWrapper.isEmpty()) {
4299 actionResult = handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, origMd5, data, null, null, null, null);
4300 if (actionResult.isRight()) {
4301 log.debug("Failed to upload artifact to component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, actionResult.right().value());
4302 errorWrapper.setInnerElement(actionResult.right().value());
4305 if (errorWrapper.isEmpty()) {
4306 updateArtifact = actionResult.left().value().left().value();
4307 updateArtifactResult = Either.left(updateArtifact);
4310 updateArtifactResult = Either.right(errorWrapper.getInnerElement());
4312 updateAuditParametersWithArtifactDefinition(additionalParams, updateArtifact);
4313 return updateArtifactResult;
4317 * updates an artifact on a resource instance by UUID
4321 * @param componentType
4322 * @param componentUuid
4323 * @param resourceInstanceName
4324 * @param artifactUUID
4325 * @param additionalParams
4330 public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID,
4331 Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
4333 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4334 Either<ArtifactDefinition, ResponseFormat> updateArtifactResult;
4335 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4336 ArtifactDefinition updateArtifact = null;
4337 Component component = null;
4338 String componentInstanceId = null;
4339 String componentId = null;
4340 String artifactId = null;
4341 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4342 String userId = request.getHeader(Constants.USER_ID_HEADER);
4344 ImmutablePair<Component, ComponentInstance> componentRiPair = null;
4345 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4346 if (getComponentRes.isRight()) {
4347 StorageOperationStatus status = getComponentRes.right().value();
4348 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4349 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4351 if (errorWrapper.isEmpty() && !getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4352 component = checkoutParentComponent(componentType, getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(), userId, errorWrapper);
4354 if (errorWrapper.isEmpty()) {
4355 if (component == null) {
4356 componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
4358 componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
4361 if (errorWrapper.isEmpty()) {
4362 componentInstanceId = componentRiPair.getRight().getUniqueId();
4363 componentId = componentRiPair.getLeft().getUniqueId();
4364 artifactId = findArtifactId(componentRiPair.getRight(), artifactUUID, errorWrapper);
4366 if (errorWrapper.isEmpty()) {
4367 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
4369 actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, artifactInfo, origMd5, data, null, null, componentId, ComponentTypeEnum.findParamByType(componentType));
4370 if (actionResult.isRight()) {
4371 log.debug("Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. ", resourceInstanceName, componentType, componentUuid, actionResult.right().value());
4372 errorWrapper.setInnerElement(actionResult.right().value());
4375 if (errorWrapper.isEmpty()) {
4376 updateArtifact = actionResult.left().value().left().value();
4377 updateArtifactResult = Either.left(updateArtifact);
4379 updateArtifactResult = Either.right(errorWrapper.getInnerElement());
4381 updateAuditParametersWithArtifactDefinition(additionalParams, updateArtifact);
4382 return updateArtifactResult;
4386 * deletes an artifact on a component by UUID
4389 * @param componentType
4390 * @param componentUuid
4391 * @param artifactUUID
4392 * @param additionalParams
4397 public Either<ArtifactDefinition, ResponseFormat> deleteArtifactOnComponentByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID, Map<AuditingFieldsKeysEnum, Object> additionalParams,
4398 ArtifactOperationInfo operation) {
4400 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4401 Either<ArtifactDefinition, ResponseFormat> deleteArtifactResult;
4402 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4403 ArtifactDefinition deleteArtifact = null;
4404 Component component = null;
4405 String componentId = null;
4406 String artifactId = null;
4407 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4408 String userId = request.getHeader(Constants.USER_ID_HEADER);
4410 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4411 if (getComponentRes.isRight()) {
4412 StorageOperationStatus status = getComponentRes.right().value();
4413 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4414 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), componentUuid));
4416 if (errorWrapper.isEmpty()) {
4417 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
4418 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
4419 if (!getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4420 component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
4421 if (component != null) {
4422 componentId = component.getUniqueId();
4423 componentName = component.getName();
4426 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentName);
4428 if (errorWrapper.isEmpty()) {
4429 artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentId, componentType);
4431 if (errorWrapper.isEmpty()) {
4432 actionResult = handleArtifactRequest(componentId, userId, componentType, operation, artifactId, null, origMd5, null, null, null, null, null);
4433 if (actionResult.isRight()) {
4434 log.debug("Failed to upload artifact to component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, actionResult.right().value());
4435 errorWrapper.setInnerElement(actionResult.right().value());
4438 if (errorWrapper.isEmpty()) {
4439 deleteArtifact = actionResult.left().value().left().value();
4440 deleteArtifactResult = Either.left(deleteArtifact);
4442 deleteArtifactResult = Either.right(errorWrapper.getInnerElement());
4444 updateAuditParametersWithArtifactDefinition(additionalParams, deleteArtifact);
4445 return deleteArtifactResult;
4449 * deletes an artifact from a resource instance by UUID
4452 * @param componentType
4453 * @param componentUuid
4454 * @param resourceInstanceName
4455 * @param artifactUUID
4456 * @param additionalParams
4461 public Either<ArtifactDefinition, ResponseFormat> deleteArtifactOnRiByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID,
4462 Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
4464 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4465 Either<ArtifactDefinition, ResponseFormat> deleteArtifactResult;
4466 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4467 ArtifactDefinition deleteArtifact = null;
4468 Component component = null;
4469 String componentInstanceId = null;
4470 String componentId = null;
4471 String artifactId = null;
4472 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4473 String userId = request.getHeader(Constants.USER_ID_HEADER);
4474 ImmutablePair<Component, ComponentInstance> componentRiPair = null;
4475 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4476 if (getComponentRes.isRight()) {
4477 StorageOperationStatus status = getComponentRes.right().value();
4478 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4479 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4481 if (errorWrapper.isEmpty() && !getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4482 component = checkoutParentComponent(componentType, getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(), userId, errorWrapper);
4484 if (errorWrapper.isEmpty()) {
4485 if (component == null) {
4486 componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
4488 componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
4491 if (errorWrapper.isEmpty()) {
4492 componentInstanceId = componentRiPair.getRight().getUniqueId();
4493 componentId = componentRiPair.getLeft().getUniqueId();
4494 artifactId = findArtifactId(componentRiPair.getRight(), artifactUUID, errorWrapper);
4496 if (errorWrapper.isEmpty()) {
4498 actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, null, origMd5, null, null, null, componentId, ComponentTypeEnum.findParamByType(componentType));
4500 if (actionResult.isRight()) {
4501 log.debug("Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. ", resourceInstanceName, componentType, componentUuid, actionResult.right().value());
4502 errorWrapper.setInnerElement(actionResult.right().value());
4505 if (errorWrapper.isEmpty()) {
4506 deleteArtifact = actionResult.left().value().left().value();
4507 deleteArtifactResult = Either.left(deleteArtifact);
4509 deleteArtifactResult = Either.right(errorWrapper.getInnerElement());
4511 updateAuditParametersWithArtifactDefinition(additionalParams, deleteArtifact);
4512 return deleteArtifactResult;
4515 private String findArtifactId(ComponentInstance instance, String artifactUUID, Wrapper<ResponseFormat> errorWrapper) {
4516 String artifactId = null;
4517 ArtifactDefinition foundArtifact = null;
4518 if (instance.getDeploymentArtifacts() != null) {
4519 foundArtifact = instance.getDeploymentArtifacts().values().stream().filter(e -> e.getArtifactUUID() != null && e.getArtifactUUID().equals(artifactUUID)).findFirst().orElse(null);
4521 if (foundArtifact == null && instance.getArtifacts() != null) {
4522 foundArtifact = instance.getArtifacts().values().stream().filter(e -> e.getArtifactUUID() != null && e.getArtifactUUID().equals(artifactUUID)).findFirst().orElse(null);
4524 if (foundArtifact == null) {
4525 log.debug("The artifact {} was not found on instance {}. ", artifactUUID, instance.getUniqueId());
4526 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactUUID));
4528 artifactId = foundArtifact.getUniqueId();
4533 public Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder(ArtifactDefinition artifact, String envType, String parentId, NodeTypeEnum parentType, String parentName, User user, Component component,
4534 Map<String, String> existingEnvVersions) {
4535 return createHeatEnvPlaceHolder(artifact, envType, parentId, parentType, parentName, user, component, existingEnvVersions, true);
4539 @SuppressWarnings("unchecked")
4540 public Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder(ArtifactDefinition artifact, String envType, String parentId, NodeTypeEnum parentType, String parentName, User user, Component component,
4541 Map<String, String> existingEnvVersions, boolean overrideId) {
4542 Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getDeploymentResourceInstanceArtifacts();
4543 if (deploymentResourceArtifacts == null) {
4544 log.debug("no deployment artifacts are configured for generated artifacts");
4545 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
4547 Map<String, Object> placeHolderData = (Map<String, Object>) deploymentResourceArtifacts.get(envType);
4548 if (placeHolderData == null) {
4549 log.debug("no env type {} are configured for generated artifacts", envType);
4550 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
4553 String envLabel = (artifact.getArtifactLabel() + HEAT_ENV_SUFFIX).toLowerCase();
4554 String parentIdParam = parentId;
4556 parentIdParam = null;
4558 Either<ArtifactDefinition, ResponseFormat> createArtifactPlaceHolder = createArtifactPlaceHolderInfo(parentIdParam, envLabel, placeHolderData, user.getUserId(), ArtifactGroupTypeEnum.DEPLOYMENT, true);
4559 if (createArtifactPlaceHolder.isRight()) {
4560 return Either.right(createArtifactPlaceHolder.right().value());
4562 ArtifactDefinition artifactHeatEnv = createArtifactPlaceHolder.left().value();
4564 // fix for migration only!!!! create heat env placeholder according to heat id.
4565 artifactHeatEnv.setUniqueId(artifact.getUniqueId() + HEAT_ENV_SUFFIX);
4568 artifactHeatEnv.setGeneratedFromId(artifact.getUniqueId());
4569 artifactHeatEnv.setHeatParamsUpdateDate(System.currentTimeMillis());
4570 artifactHeatEnv.setTimeout(0);
4571 buildHeatEnvFileName(artifact, artifactHeatEnv, placeHolderData);
4572 // rbetzer - keep env artifactVersion - changeComponentInstanceVersion flow
4573 handleEnvArtifactVersion(artifactHeatEnv, existingEnvVersions);
4574 // clone heat parameters in case of heat env only not VF heat env
4575 if (envType.equals(HEAT_ENV_NAME)) {
4576 artifactHeatEnv.setHeatParameters(artifact.getHeatParameters());
4578 ArtifactDefinition artifactDefinition;
4579 // Evg : for resource instance artifact will be added later as block with other env artifacts from BL
4580 if (parentType != NodeTypeEnum.ResourceInstance) {
4581 Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact = addHeatEnvArtifact(artifactHeatEnv, artifact, component.getUniqueId(), parentType, parentId);
4582 if (addHeatEnvArtifact.isRight()) {
4583 log.debug("failed to create heat env artifact on resource instance");
4584 return Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(addHeatEnvArtifact.right().value(), false), "", null));
4586 artifactDefinition = createArtifactPlaceHolder.left().value();
4588 artifactDefinition = artifactHeatEnv;
4589 artifactToscaOperation.generateUUID(artifactDefinition, artifactDefinition.getArtifactVersion());
4592 if (artifact.getHeatParameters() != null) {
4593 List<HeatParameterDefinition> heatEnvParameters = new ArrayList<HeatParameterDefinition>();
4594 for (HeatParameterDefinition parameter : artifact.getListHeatParameters()) {
4595 HeatParameterDefinition heatEnvParameter = new HeatParameterDefinition(parameter);
4596 heatEnvParameter.setDefaultValue(parameter.getCurrentValue());
4597 heatEnvParameters.add(heatEnvParameter);
4599 artifactDefinition.setListHeatParameters(heatEnvParameters);
4603 EnumMap<AuditingFieldsKeysEnum, Object> artifactAuditingFields = createArtifactAuditingFields(artifactDefinition, "", artifactDefinition.getUniqueId());
4604 artifactAuditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, parentName);
4605 ComponentTypeEnum componentType = component.getComponentType();
4606 if (parentType == NodeTypeEnum.ResourceInstance) {
4607 componentType = ComponentTypeEnum.RESOURCE_INSTANCE;
4609 componentsUtils.auditComponent(componentsUtils.getResponseFormat(ActionStatus.OK), user, component, "", "", AuditingActionEnum.ARTIFACT_UPLOAD, componentType, artifactAuditingFields);
4610 return Either.left(artifactDefinition);
4613 private void buildHeatEnvFileName(ArtifactDefinition heatArtifact, ArtifactDefinition heatEnvArtifact, Map<String, Object> placeHolderData) {
4614 String heatExtension = GeneralUtility.getFilenameExtension(heatArtifact.getArtifactName());
4615 String envExtension = (String) placeHolderData.get(ARTIFACT_PLACEHOLDER_FILE_EXTENSION);
4616 String name = heatArtifact.getArtifactName();
4619 name = heatArtifact.getArtifactLabel();
4620 fileName = name + "." + envExtension;
4622 fileName = name.replaceAll("." + heatExtension, "." + envExtension);
4624 heatEnvArtifact.setArtifactName(fileName);
4627 private void handleEnvArtifactVersion(ArtifactDefinition heatEnvArtifact, Map<String, String> existingEnvVersions) {
4628 if (null != existingEnvVersions) {
4629 String prevVersion = existingEnvVersions.get(heatEnvArtifact.getArtifactName());
4630 if (null != prevVersion) {
4631 heatEnvArtifact.setArtifactVersion(prevVersion);
4637 * Handles Artifacts Request For Inner Component
4639 * @param artifactsToHandle
4642 * @param vfcsNewCreatedArtifacts
4645 * @param inTransaction
4648 public Either<List<ArtifactDefinition>, ResponseFormat> handleArtifactsRequestForInnerVfcComponent(List<ArtifactDefinition> artifactsToHandle, Resource component, User user, List<ArtifactDefinition> vfcsNewCreatedArtifacts,
4649 ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) {
4651 Either<List<ArtifactDefinition>, ResponseFormat> handleArtifactsResult = null;
4652 ComponentTypeEnum componentType = component.getComponentType();
4653 List<ArtifactDefinition> uploadedArtifacts = new ArrayList<>();
4654 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4655 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult;
4659 for (ArtifactDefinition artifact : artifactsToHandle) {
4660 originData = buildJsonStringForCsarVfcArtifact(artifact);
4661 origMd5 = GeneralUtility.calculateMD5ByString(originData);
4662 actionResult = handleArtifactRequest(component.getUniqueId(), user.getUserId(), componentType, operation, artifact.getUniqueId(), artifact, origMd5, originData, null, null, null, null, shouldLock, inTransaction);
4663 if (actionResult.isRight()) {
4664 log.debug("Failed to upload artifact to component with type {} and name {}. Status is {}. ", componentType, component.getName(), actionResult.right().value());
4665 errorWrapper.setInnerElement(actionResult.right().value());
4666 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create) {
4667 vfcsNewCreatedArtifacts.addAll(uploadedArtifacts);
4671 uploadedArtifacts.add(actionResult.left().value().left().value());
4673 if (errorWrapper.isEmpty()) {
4674 handleArtifactsResult = Either.left(uploadedArtifacts);
4676 handleArtifactsResult = Either.right(errorWrapper.getInnerElement());
4678 } catch (Exception e) {
4679 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
4680 handleArtifactsResult = Either.right(responseFormat);
4681 log.debug("Exception occured when handleArtifactsRequestForInnerVfcComponent, error is:{}", e.getMessage(), e);
4683 return handleArtifactsResult;
4686 private ComponentInstance getRelatedComponentInstance(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
4687 ComponentInstance componentInstance = null;
4688 String normalizedName = ValidationUtils.normalizeComponentInstanceName(resourceInstanceName);
4689 Component component = getLatestComponentByUuid(componentType, componentUuid, errorWrapper);
4690 if (errorWrapper.isEmpty()) {
4691 componentInstance = component.getComponentInstances().stream().filter(ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName()).equals(normalizedName)).findFirst().orElse(null);
4692 if (componentInstance == null) {
4693 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, "resource instance", component.getComponentType().getValue(), component.getName()));
4694 log.debug("Component instance {} was not found for component {}", resourceInstanceName, component.getName());
4697 return componentInstance;
4700 private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(Component component, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
4702 ImmutablePair<Component, ComponentInstance> relatedComponentComponentInstancePair = null;
4703 String normalizedName = ValidationUtils.normalizeComponentInstanceName(resourceInstanceName);
4704 ComponentInstance componentInstance = component.getComponentInstances().stream().filter(ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName()).equals(normalizedName)).findFirst().orElse(null);
4705 if (componentInstance == null) {
4706 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, "resource instance", component.getComponentType().getValue(), component.getName()));
4707 log.debug("Component instance {} was not found for component {}", resourceInstanceName, component.getName());
4709 relatedComponentComponentInstancePair = new ImmutablePair<>(component, componentInstance);
4711 return relatedComponentComponentInstancePair;
4714 private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
4715 ComponentInstance componentInstance;
4716 ImmutablePair<Component, ComponentInstance> relatedComponentComponentInstancePair = null;
4717 Component component = getLatestComponentByUuid(componentType, componentUuid, errorWrapper);
4718 if (errorWrapper.isEmpty()) {
4719 componentInstance = component.getComponentInstances().stream().filter(ci -> ci.getNormalizedName().equals(resourceInstanceName)).findFirst().orElse(null);
4720 if (componentInstance == null) {
4721 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, "resource instance", component.getComponentType().getValue(), component.getName()));
4722 log.debug("Component instance {} was not found for component {}", resourceInstanceName, component.getName());
4724 relatedComponentComponentInstancePair = new ImmutablePair<>(component, componentInstance);
4727 return relatedComponentComponentInstancePair;
4730 private byte[] downloadArtifact(Map<String, ArtifactDefinition> artifacts, String artifactUUID, Wrapper<ResponseFormat> errorWrapper, String componentName) {
4732 byte[] downloadedArtifact = null;
4733 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = null;
4734 List<ArtifactDefinition> deploymentArtifacts = null;
4735 ArtifactDefinition deploymentArtifact = null;
4736 if (artifacts != null && !artifacts.isEmpty()) {
4737 deploymentArtifacts = artifacts.values().stream().filter(art -> art.getArtifactUUID() != null && art.getArtifactUUID().equals(artifactUUID)).collect(Collectors.toList());
4739 if (deploymentArtifacts == null || deploymentArtifacts.isEmpty()) {
4740 log.debug("Deployment artifact with uuid {} was not found for component {}", artifactUUID, componentName);
4741 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactUUID));
4743 if (errorWrapper.isEmpty()) {
4744 deploymentArtifact = deploymentArtifacts.get(0);
4745 downloadArtifactEither = downloadArtifact(deploymentArtifact);
4746 if (downloadArtifactEither.isRight()) {
4747 log.debug("Failed to download artifact {}. ", deploymentArtifact.getArtifactName());
4748 errorWrapper.setInnerElement(downloadArtifactEither.right().value());
4751 if (errorWrapper.isEmpty()) {
4752 log.trace("Succeeded to download artifact with uniqueId {}", deploymentArtifact.getUniqueId());
4753 downloadedArtifact = downloadArtifactEither.left().value().getRight();
4755 return downloadedArtifact;
4758 private Component getLatestComponentByUuid(ComponentTypeEnum componentType, String componentUuid, Wrapper<ResponseFormat> errorWrapper) {
4759 Component component = null;
4760 Either<Component, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentByUuid(componentUuid);
4761 if (getComponentRes.isRight()) {
4762 StorageOperationStatus status = getComponentRes.right().value();
4763 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4764 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4766 component = getComponentRes.left().value();
4771 private String getLatestParentArtifactDataIdByArtifactUUID(String artifactUUID, Wrapper<ResponseFormat> errorWrapper, String parentId, ComponentTypeEnum componentType) {
4772 String artifactId = null;
4773 ActionStatus actionStatus = ActionStatus.ARTIFACT_NOT_FOUND;
4774 StorageOperationStatus storageStatus;
4775 ArtifactDefinition latestArtifact = null;
4776 List<ArtifactDefinition> artifacts = null;
4777 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifactsRes = artifactToscaOperation.getArtifacts(parentId);
4778 if (getArtifactsRes.isRight()) {
4779 storageStatus = getArtifactsRes.right().value();
4780 log.debug("Couldn't fetch artifacts data for parent component {} with uid {}, error: {}", componentType.name(), parentId, storageStatus);
4781 if (!storageStatus.equals(StorageOperationStatus.NOT_FOUND)) {
4782 actionStatus = componentsUtils.convertFromStorageResponse(storageStatus);
4784 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
4786 if (errorWrapper.isEmpty()) {
4787 artifacts = getArtifactsRes.left().value().values().stream().filter(a -> a.getArtifactUUID() != null && a.getArtifactUUID().equals(artifactUUID)).collect(Collectors.toList());
4788 if (artifacts == null || artifacts.isEmpty()) {
4789 log.debug("Couldn't fetch artifact with UUID {} data for parent component {} with uid {}, error: {}", artifactUUID, componentType.name(), parentId, actionStatus);
4790 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
4793 if (errorWrapper.isEmpty()) {
4794 latestArtifact = artifacts.stream().max((a1, a2) -> {
4795 int compareRes = Double.compare(Double.parseDouble(a1.getArtifactVersion()), Double.parseDouble(a2.getArtifactVersion()));
4796 if (compareRes == 0) {
4797 compareRes = Long.compare(a1.getLastUpdateDate() == null ? 0 : a1.getLastUpdateDate(), a2.getLastUpdateDate() == null ? 0 : a2.getLastUpdateDate());
4801 if (latestArtifact == null) {
4802 log.debug("Couldn't fetch latest artifact with UUID {} data for parent component {} with uid {}, error: {}", artifactUUID, componentType.name(), parentId, actionStatus);
4803 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
4806 if (errorWrapper.isEmpty()) {
4807 artifactId = latestArtifact.getUniqueId();
4812 private Component checkoutParentComponent(ComponentTypeEnum componentType, String parentId, String userId, Wrapper<ResponseFormat> errorWrapper) {
4814 Component component = null;
4815 Either<User, ActionStatus> getUserRes = userBusinessLogic.getUser(userId, false);
4816 if (getUserRes.isRight()) {
4817 log.debug("Could not fetch User of component {} with uid {} to checked out. Status is {}. ", componentType.getNodeType(), parentId, getUserRes.right().value());
4818 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(getUserRes.right().value()));
4820 if (errorWrapper.isEmpty()) {
4821 User modifier = getUserRes.left().value();
4822 LifecycleChangeInfoWithAction changeInfo = new LifecycleChangeInfoWithAction("External API checkout", LifecycleChanceActionEnum.UPDATE_FROM_EXTERNAL_API);
4823 Either<? extends Component, ResponseFormat> checkoutRes = lifecycleBusinessLogic.changeComponentState(componentType, parentId, modifier, LifeCycleTransitionEnum.CHECKOUT, changeInfo, false, true);
4824 if (checkoutRes.isRight()) {
4825 log.debug("Could not change state of component {} with uid {} to checked out. Status is {}. ", componentType.getNodeType(), parentId, checkoutRes.right().value().getStatus());
4826 errorWrapper.setInnerElement(checkoutRes.right().value());
4828 component = checkoutRes.left().value();
4834 private void updateAuditParametersWithArtifactDefinition(Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactDefinition artifact) {
4835 if (artifact == null) {
4836 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, "");
4837 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, "");
4838 if (!additionalParams.containsKey(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID)) {
4839 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, "");
4842 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifact.getArtifactUUID());
4843 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, buildAuditingArtifactData(artifact));
4844 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, artifact.getUpdaterFullName());
4848 private String buildJsonStringForCsarVfcArtifact(ArtifactDefinition artifact) {
4849 Map<String, Object> json = new HashMap<>();
4850 String artifactName = artifact.getArtifactName();
4851 json.put(Constants.ARTIFACT_NAME, artifactName);
4852 json.put(Constants.ARTIFACT_LABEL, artifact.getArtifactLabel());
4853 json.put(Constants.ARTIFACT_TYPE, artifact.getArtifactType());
4854 json.put(Constants.ARTIFACT_GROUP_TYPE, ArtifactGroupTypeEnum.DEPLOYMENT.getType());
4855 json.put(Constants.ARTIFACT_DESCRIPTION, artifact.getDescription());
4856 json.put(Constants.ARTIFACT_PAYLOAD_DATA, artifact.getPayloadData());
4857 json.put(Constants.ARTIFACT_DISPLAY_NAME, artifact.getArtifactDisplayName());
4858 return gson.toJson(json);