2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.openecomp.sdc.be.components.impl;
23 import java.io.ByteArrayInputStream;
24 import java.io.IOException;
25 import java.math.BigDecimal;
26 import java.util.ArrayList;
27 import java.util.Comparator;
28 import java.util.EnumMap;
29 import java.util.HashMap;
30 import java.util.Iterator;
31 import java.util.List;
33 import java.util.Optional;
35 import java.util.function.Predicate;
36 import java.util.function.Supplier;
37 import java.util.stream.Collectors;
39 import javax.servlet.http.HttpServletRequest;
41 import org.apache.commons.codec.binary.Base64;
42 import org.apache.commons.collections.CollectionUtils;
43 import org.apache.commons.collections.MapUtils;
44 import org.apache.commons.lang.StringUtils;
45 import org.apache.commons.lang3.tuple.ImmutablePair;
46 import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum;
47 import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaTagNamesEnum;
48 import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
49 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
50 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction.LifecycleChanceActionEnum;
51 import org.openecomp.sdc.be.config.BeEcompErrorManager;
52 import org.openecomp.sdc.be.config.Configuration.ArtifactTypeConfig;
53 import org.openecomp.sdc.be.config.ConfigurationManager;
54 import org.openecomp.sdc.be.config.validation.DeploymentArtifactHeatConfiguration;
55 import org.openecomp.sdc.be.dao.api.ActionStatus;
56 import org.openecomp.sdc.be.dao.cassandra.ArtifactCassandraDao;
57 import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus;
58 import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
59 import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
60 import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
61 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
62 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
63 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
64 import org.openecomp.sdc.be.model.ArtifactDefinition;
65 import org.openecomp.sdc.be.model.ArtifactType;
66 import org.openecomp.sdc.be.model.Component;
67 import org.openecomp.sdc.be.model.ComponentInstance;
68 import org.openecomp.sdc.be.model.ComponentParametersView;
69 import org.openecomp.sdc.be.model.GroupDefinition;
70 import org.openecomp.sdc.be.model.GroupInstance;
71 import org.openecomp.sdc.be.model.HeatParameterDefinition;
72 import org.openecomp.sdc.be.model.InterfaceDefinition;
73 import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;
74 import org.openecomp.sdc.be.model.LifecycleStateEnum;
75 import org.openecomp.sdc.be.model.Operation;
76 import org.openecomp.sdc.be.model.Resource;
77 import org.openecomp.sdc.be.model.Service;
78 import org.openecomp.sdc.be.model.User;
79 import org.openecomp.sdc.be.model.heat.HeatParameterType;
80 import org.openecomp.sdc.be.model.jsontitan.operations.NodeTemplateOperation;
81 import org.openecomp.sdc.be.model.operations.api.IElementOperation;
82 import org.openecomp.sdc.be.model.operations.api.IHeatParametersOperation;
83 import org.openecomp.sdc.be.model.operations.api.IInterfaceLifecycleOperation;
84 import org.openecomp.sdc.be.model.operations.api.IUserAdminOperation;
85 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
86 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
87 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
88 import org.openecomp.sdc.be.resources.data.ComponentMetadataData;
89 import org.openecomp.sdc.be.resources.data.ESArtifactData;
90 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
91 import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants;
92 import org.openecomp.sdc.be.servlets.RepresentationUtils;
93 import org.openecomp.sdc.be.tosca.CsarUtils;
94 import org.openecomp.sdc.be.tosca.ToscaError;
95 import org.openecomp.sdc.be.tosca.ToscaExportHandler;
96 import org.openecomp.sdc.be.tosca.ToscaRepresentation;
97 import org.openecomp.sdc.be.user.IUserBusinessLogic;
98 import org.openecomp.sdc.be.user.Role;
99 import org.openecomp.sdc.be.user.UserBusinessLogic;
100 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
101 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
102 import org.openecomp.sdc.common.api.Constants;
103 import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
104 import org.openecomp.sdc.common.datastructure.Wrapper;
105 import org.openecomp.sdc.common.util.GeneralUtility;
106 import org.openecomp.sdc.common.util.ValidationUtils;
107 import org.openecomp.sdc.common.util.YamlToObjectConverter;
108 import org.openecomp.sdc.exception.ResponseFormat;
109 import org.slf4j.Logger;
110 import org.slf4j.LoggerFactory;
111 import org.springframework.beans.factory.annotation.Autowired;
112 import org.xml.sax.InputSource;
113 import org.xml.sax.SAXException;
114 import org.xml.sax.XMLReader;
115 import org.yaml.snakeyaml.Yaml;
117 import com.google.gson.Gson;
118 import com.google.gson.GsonBuilder;
119 import com.sun.org.apache.xerces.internal.parsers.SAXParser;
121 import fj.data.Either;
123 @org.springframework.stereotype.Component("artifactBusinessLogic")
124 public class ArtifactsBusinessLogic extends BaseBusinessLogic {
125 private static final String ARTIFACT_TYPE_OTHER = "OTHER";
126 private static final String ARTIFACT_DESCRIPTION = "artifact description";
127 private static final String ARTIFACT_LABEL = "artifact label";
128 private static final String ARTIFACT_URL = "artifact url";
129 private static final String ARTIFACT_NAME = "artifact name";
130 private static final String ARTIFACT_PAYLOAD = "artifact payload";
132 private static final String ARTIFACT_PLACEHOLDER_TYPE = "type";
133 private static final String ARTIFACT_PLACEHOLDER_DISPLAY_NAME = "displayName";
134 private static final Object ARTIFACT_PLACEHOLDER_DESCRIPTION = "description";
136 public static final String HEAT_ENV_NAME = "heatEnv";
137 public static final String HEAT_VF_ENV_NAME = "VfHeatEnv";
138 public static final String HEAT_ENV_SUFFIX = "env";
139 private static final String ARTIFACT_PLACEHOLDER_FILE_EXTENSION = "fileExtension";
141 // private static Integer defaultHeatTimeout;
142 // private static final Integer NON_HEAT_TIMEOUT = 0;
143 private static Logger log = LoggerFactory.getLogger(ArtifactsBusinessLogic.class.getName());
144 private Gson gson = new GsonBuilder().setPrettyPrinting().create();
146 @javax.annotation.Resource
147 private IInterfaceLifecycleOperation interfaceLifecycleOperation;
148 @javax.annotation.Resource
149 private IUserAdminOperation userOperaton;
151 @javax.annotation.Resource
152 private IElementOperation elementOperation;
154 @javax.annotation.Resource
155 private ResourceBusinessLogic resourceBusinessLogic;
157 @javax.annotation.Resource
158 private ServiceBusinessLogic serviceBusinessLogic;
160 @javax.annotation.Resource
161 private UserBusinessLogic userAdminManager;
163 @javax.annotation.Resource
164 private IHeatParametersOperation heatParametersOperation;
167 private ArtifactCassandraDao artifactCassandraDao;
170 private ToscaExportHandler toscaExportUtils;
173 private CsarUtils csarUtils;
176 private LifecycleBusinessLogic lifecycleBusinessLogic;
179 private IUserBusinessLogic userBusinessLogic;
181 NodeTemplateOperation nodeTemplateOperation;
183 public ArtifactsBusinessLogic() {
184 // defaultHeatTimeout = ConfigurationManager.getConfigurationManager().getConfiguration().getDefaultHeatArtifactTimeoutMinutes();
185 // if ((defaultHeatTimeout == null) || (defaultHeatTimeout < 1)) {
186 // defaultHeatTimeout = 60;
190 public static enum ArtifactOperationEnum {
191 Create(), Update(), Delete(), Download();
194 public class ArtifactOperationInfo {
196 private ArtifactOperationEnum artifactOperationEnum;
197 private boolean isExternalApi;
198 private boolean ignoreLifecycleState;
200 public ArtifactOperationInfo(boolean isExternalApi, boolean ignoreLifecycleState, ArtifactOperationEnum artifactOperationEnum) {
201 this.artifactOperationEnum = artifactOperationEnum;
202 this.isExternalApi = isExternalApi;
203 this.ignoreLifecycleState = ignoreLifecycleState;
206 public boolean isExternalApi() {
207 return isExternalApi;
210 public boolean ignoreLifecycleState() {
211 return ignoreLifecycleState;
214 public ArtifactOperationEnum getArtifactOperationEnum() {
215 return artifactOperationEnum;
221 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleArtifactRequest(String componentId, String userId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo,
222 String origMd5, String originData, String interfaceName, String operationName, String parentId, String containerComponentType) {
223 return handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, origMd5, originData, interfaceName, operationName, parentId, containerComponentType, true, false);
226 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleArtifactRequest(String componentId, String userId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo,
227 String origMd5, String originData, String interfaceName, String operationName, String parentId, String containerComponentType, boolean shouldLock, boolean inTransaction) {
229 // step 1 - detect auditing type
230 AuditingActionEnum auditingAction = detectAuditingType(operation, origMd5);
231 // step 2 - check header
232 if (userId == null) {
233 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
234 log.debug("handleArtifactRequest - no HTTP_CSP_HEADER , component id {}", componentId);
235 handleAuditing(auditingAction, null, componentId, null, null, null, artifactId, responseFormat, componentType, null);
236 return Either.right(responseFormat);
238 // step 3 - check user existence
239 Either<User, ResponseFormat> userResult = validateUserExists(userId, auditingAction, componentId, artifactId, componentType, inTransaction);
240 if (userResult.isRight()) {
241 return Either.right(userResult.right().value());
244 // step 4 - check user's role
245 User user = userResult.left().value();
246 Either<Boolean, ResponseFormat> validateUserRole = validateUserRole(user, auditingAction, componentId, artifactId, componentType, operation);
247 if (validateUserRole.isRight()) {
248 return Either.right(validateUserRole.right().value());
252 // 5. check service/resource existence
253 // 6. check service/resource check out
254 // 7. user is owner of checkout state
255 org.openecomp.sdc.be.model.Component component = null;
256 // ComponentInstance resourceInstance = null;
257 String realComponentId = componentType == ComponentTypeEnum.RESOURCE_INSTANCE ? parentId : componentId;
258 Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(realComponentId, userId, auditingAction, user, artifactId, componentType, containerComponentType, inTransaction);
259 if (validateComponent.isRight()) {
260 return Either.right(validateComponent.right().value());
262 component = validateComponent.left().value();
263 Either<Boolean, ResponseFormat> validateWorkOnResource = validateWorkOnComponent(component, userId, auditingAction, user, artifactId, operation, componentType);
264 if (validateWorkOnResource.isRight()) {
265 return Either.right(validateWorkOnResource.right().value());
268 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result = validateAndHandleArtifact(componentId, componentType, operation, artifactId, artifactInfo, origMd5, originData, interfaceName, operationName, parentId, user, component,
269 shouldLock, inTransaction);
275 * This Method validates only the Artifact and does not validate user / role / component ect...<br>
276 * For regular usage use <br>
277 * {@link #handleArtifactRequest(String, String, ComponentTypeEnum, ArtifactOperationInfo, String, ArtifactDefinition, String, String, String, String, String, String)}
281 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> validateAndHandleArtifact(String componentUniqueId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactUniqueId,
282 ArtifactDefinition artifactDefinition, String origMd5, String originData, String interfaceName, String operationName, String parentId, User user, Component component, boolean shouldLock, boolean inTransaction) {
283 Component parent = component;
284 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
286 AuditingActionEnum auditingAction = detectAuditingType(operation, origMd5);
287 artifactDefinition = validateArtifact(componentUniqueId, componentType, operation, artifactUniqueId, artifactDefinition, parentId, auditingAction, user, component, parent, shouldLock, errorWrapper, inTransaction);
289 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result;
290 if (errorWrapper.isEmpty()) {
292 result = doAction(componentUniqueId, componentType, operation, artifactUniqueId, artifactDefinition, origMd5, originData, interfaceName, operationName, auditingAction, user, parent, shouldLock, inTransaction);
294 result = Either.right(errorWrapper.getInnerElement());
299 private ArtifactDefinition validateArtifact(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, String parentId, AuditingActionEnum auditingAction, User user,
300 org.openecomp.sdc.be.model.Component component, org.openecomp.sdc.be.model.Component parent, boolean shouldLock, Wrapper<ResponseFormat> errorWrapper, boolean inTransaction) {
301 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Update || operation.getArtifactOperationEnum() == ArtifactOperationEnum.Delete || operation.getArtifactOperationEnum() == ArtifactOperationEnum.Download) {
302 Either<ArtifactDefinition, ResponseFormat> validateArtifact = validateArtifact(componentId, componentType, artifactId, component, auditingAction, parentId, inTransaction);
303 if (validateArtifact.isRight()) {
304 ResponseFormat responseFormat = validateArtifact.right().value();
305 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
306 errorWrapper.setInnerElement(validateArtifact.right().value());
308 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Download) {
309 artifactInfo = validateArtifact.left().value();
310 handleHeatEnvDownload(componentId, componentType, user, component, validateArtifact, shouldLock, errorWrapper);
317 private void handleHeatEnvDownload(String componentId, ComponentTypeEnum componentType, User user, org.openecomp.sdc.be.model.Component component, Either<ArtifactDefinition, ResponseFormat> validateArtifact, boolean shouldLock,
318 Wrapper<ResponseFormat> errorWrapper) {
319 ArtifactDefinition validatedArtifact = validateArtifact.left().value();
321 if (validatedArtifact.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType())) {
322 if (ComponentTypeEnum.SERVICE == component.getComponentType()) {
323 ComponentInstance componentInstance = component.getComponentInstances().stream().filter(p -> p.getUniqueId().equals(componentId)).findAny().get();
324 Map<String, ArtifactDefinition> deploymentArtifacts = componentInstance.getDeploymentArtifacts();
326 ArtifactDefinition heatEnvWithHeatParams = deploymentArtifacts.values().stream().filter(p -> p.getUniqueId().equals(validatedArtifact.getUniqueId())).findAny().get();
327 Either<ArtifactDefinition, ResponseFormat> eitherGenerated = generateHeatEnvArtifact(heatEnvWithHeatParams, componentType, component, componentInstance.getName(), user, shouldLock, componentId);
328 if (eitherGenerated.isRight()) {
329 errorWrapper.setInnerElement(eitherGenerated.right().value());
335 private boolean artifactGenerationRequired(org.openecomp.sdc.be.model.Component component, ArtifactDefinition artifactInfo) {
336 boolean needGenerate;
337 needGenerate = artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA && (component.getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN || component.getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
338 needGenerate = needGenerate || (ComponentTypeEnum.RESOURCE == component.getComponentType() && artifactInfo.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType()));
342 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateAndSaveToscaArtifact(ArtifactDefinition artifactDefinition, org.openecomp.sdc.be.model.Component component, User user, boolean isInCertificationRequest,
343 boolean shouldLock, boolean inTransaction, boolean fetchTemplatesFromDB) {
345 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generated = generateToscaArtifact(component, artifactDefinition, isInCertificationRequest, fetchTemplatesFromDB);
346 if (generated.isRight()) {
349 byte[] decodedPayload = artifactDefinition.getPayloadData();
350 artifactDefinition.setEsId(artifactDefinition.getUniqueId());
351 artifactDefinition.setArtifactChecksum(GeneralUtility.calculateMD5ByByteArray(decodedPayload));
352 return lockComponentAndUpdateArtifact(component.getUniqueId(), artifactDefinition, AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, artifactDefinition.getUniqueId(), user, component.getComponentType(), component, decodedPayload, null, null,
353 shouldLock, inTransaction);
357 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateToscaArtifact(Component parent, ArtifactDefinition artifactInfo, boolean isInCertificationRequest, boolean fetchTemplatesFromDB) {
358 log.debug("tosca artifact generation");
359 if (artifactInfo.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType())) {
360 Either<byte[], ResponseFormat> generated = csarUtils.createCsar(parent, fetchTemplatesFromDB, isInCertificationRequest);
362 if (generated.isRight()) {
363 log.debug("Failed to export tosca csar for component {} error {}", parent.getUniqueId(), generated.right().value());
365 return Either.right(generated.right().value());
367 byte[] value = generated.left().value();
368 artifactInfo.setPayload(value);
371 Either<ToscaRepresentation, ToscaError> exportComponent = toscaExportUtils.exportComponent(parent);
372 if (exportComponent.isRight()) {
373 log.debug("Failed export tosca yaml for component {} error {}", parent.getUniqueId(), exportComponent.right().value());
374 ActionStatus status = componentsUtils.convertFromToscaError(exportComponent.right().value());
375 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status);
376 return Either.right(responseFormat);
378 log.debug("Tosca yaml exported for component {} ", parent.getUniqueId());
379 String payload = exportComponent.left().value().getMainYaml();
380 artifactInfo.setPayloadData(payload);
382 return Either.left(Either.left(artifactInfo));
385 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> doAction(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, String origMd5,
386 String originData, String interfaceName, String operationName, AuditingActionEnum auditingAction, User user, org.openecomp.sdc.be.model.Component parent, boolean shouldLock, boolean inTransaction) {
387 if (interfaceName != null && operationName != null) {
388 interfaceName = interfaceName.toLowerCase();
389 operationName = operationName.toLowerCase();
391 switch (operation.getArtifactOperationEnum()) {
393 if (artifactGenerationRequired(parent, artifactInfo)) {
394 return generateNotSavedArtifact(parent, artifactInfo, shouldLock, inTransaction);
396 return handleDownload(componentId, artifactId, user, auditingAction, componentType, parent, shouldLock, inTransaction);
398 return handleDelete(componentId, artifactId, user, auditingAction, componentType, parent, interfaceName, operationName, shouldLock, inTransaction);
400 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
401 if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)
402 && (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_VOL || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_ENV)) {
403 return handleUpdateHeatEnv(componentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, originData, origMd5, operation, shouldLock, inTransaction);
405 if (componentType.equals(ComponentTypeEnum.RESOURCE) && artifactType == ArtifactTypeEnum.HEAT_ENV) {
406 return handleUpdateHeatWithHeatEnvParams(componentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, originData, origMd5, operation, shouldLock, inTransaction);
409 return handleUpdate(componentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceName, operationName, shouldLock, inTransaction);
411 return handleCreate(componentId, artifactInfo, operation, auditingAction, user, componentType, parent, origMd5, originData, interfaceName, operationName, shouldLock, inTransaction);
416 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateNotSavedArtifact(org.openecomp.sdc.be.model.Component parent, ArtifactDefinition artifactInfo, boolean shouldLock, boolean inTransaction) {
417 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result;
418 if (artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA) {
419 result = generateToscaArtifact(parent, artifactInfo, false, false);
421 String heatArtifactId = artifactInfo.getGeneratedFromId();
422 Either<ArtifactDefinition, StorageOperationStatus> heatRes = artifactToscaOperation.getArtifactById(parent.getUniqueId(), heatArtifactId);
423 if (heatRes.isRight()) {
424 log.debug("Failed to fetch heat artifact by generated id {} for heat env {}", heatArtifactId, artifactInfo.getUniqueId());
425 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(heatRes.right().value()), "");
426 return Either.right(responseFormat);
428 String generatedPayload = generateHeatEnvPayload(heatRes.left().value());
429 artifactInfo.setPayloadData(generatedPayload);
430 result = Either.left(Either.left(artifactInfo));
435 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdateHeatWithHeatEnvParams(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user,
436 ComponentTypeEnum componentType, Component parent, String originData, String origMd5, ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) {
437 convertParentType(componentType);
438 String parentId = parent.getUniqueId();
439 Either<ArtifactDefinition, StorageOperationStatus> artifactHeatRes = artifactToscaOperation.getArtifactById(componentId, artifactInfo.getGeneratedFromId());
440 ArtifactDefinition currHeatArtifact = artifactHeatRes.left().value();
442 if (origMd5 != null) {
443 Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
444 if (validateMd5.isRight()) {
445 ResponseFormat responseFormat = validateMd5.right().value();
446 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
447 return Either.right(responseFormat);
450 if (artifactInfo.getPayloadData() != null && artifactInfo.getPayloadData().length != 0) {
452 Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
453 if (payloadEither.isRight()) {
454 ResponseFormat responseFormat = payloadEither.right().value();
455 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
456 return Either.right(responseFormat);
458 } else { // duplicate
459 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
460 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
461 return Either.right(responseFormat);
467 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Update Artifact - lock ");
468 if (lockComponent.isRight()) {
469 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right().value(), componentType, null);
470 return Either.right(lockComponent.right().value());
473 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
475 resultOp = updateHeatParams(componentId, artifactId, artifactInfo, user, auditingAction, parent, componentType, currHeatArtifact, origMd5);
480 if (resultOp == null || resultOp.isRight()) {
481 log.debug("all changes rollback");
482 if (false == inTransaction)
485 log.debug("all changes committed");
486 if (false == inTransaction)
490 componentType = parent.getComponentType();
491 NodeTypeEnum nodeType = componentType.getNodeType();
492 graphLockOperation.unlockComponent(parent.getUniqueId(), nodeType);
493 // graphLockOperation.unlockComponent(parentId, parentType);
502 * @param componentType
507 public Either<ImmutablePair<String, byte[]>, ResponseFormat> handleDownloadToscaModelRequest(Component component, ArtifactDefinition csarArtifact) {
508 if (artifactGenerationRequired(component, csarArtifact)) {
509 Either<byte[], ResponseFormat> generated = csarUtils.createCsar(component, false, false);
511 if (generated.isRight()) {
512 log.debug("Failed to export tosca csar for component {} error {}", component.getUniqueId(), generated.right().value());
514 return Either.right(generated.right().value());
516 return Either.left(new ImmutablePair<String, byte[]>(csarArtifact.getArtifactName(), generated.left().value()));
518 return downloadArtifact(csarArtifact);
521 public Either<ImmutablePair<String, byte[]>, ResponseFormat> handleDownloadRequestById(String componentId, String artifactId, String userId, ComponentTypeEnum componentType, String parentId, String containerComponentType) {
522 // perform all validation in common flow
523 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result = handleArtifactRequest(componentId, userId, componentType, new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Download), artifactId, null, null, null, null,
524 null, parentId, containerComponentType);
525 if (result.isRight()) {
526 return Either.right(result.right().value());
528 ArtifactDefinition artifactDefinition;
529 Either<ArtifactDefinition, Operation> insideValue = result.left().value();
530 if (insideValue.isLeft()) {
531 artifactDefinition = insideValue.left().value();
533 artifactDefinition = insideValue.right().value().getImplementationArtifact();
535 // for tosca artifacts and heat env on VF level generated on download without saving
536 if (artifactDefinition.getPayloadData() != null) {
537 return Either.left(new ImmutablePair<String, byte[]>(artifactDefinition.getArtifactName(), artifactDefinition.getPayloadData()));
539 return downloadArtifact(artifactDefinition);
542 public Either<Map<String, ArtifactDefinition>, ResponseFormat> handleGetArtifactsByType(String containerComponentType, String parentId, ComponentTypeEnum componentType, String componentId, String artifactGroupType, String userId) {
544 // detect auditing type
545 Map<String, ArtifactDefinition> resMap = null;
546 Either<Map<String, ArtifactDefinition>, ResponseFormat> resultOp = null;
551 if (userId == null) {
552 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
553 log.debug("handleGetArtifactsByType - no HTTP_CSP_HEADER , component id {}", componentId);
555 resultOp = Either.right(responseFormat);
559 // check user existence
563 Either<User, ResponseFormat> userResult = validateUserExists(userId, "get artifacts", false);
564 if (userResult.isRight()) {
566 resultOp = Either.right(userResult.right().value());
570 userResult.left().value();
573 // 5. check service/resource existence
574 // 6. check service/resource check out
575 // 7. user is owner of checkout state
576 org.openecomp.sdc.be.model.Component component = null;
577 // ComponentInstance resourceInstance = null;
578 String realComponentId = componentType == ComponentTypeEnum.RESOURCE_INSTANCE ? parentId : componentId;
579 ComponentParametersView componentFilter = new ComponentParametersView();
580 componentFilter.disableAll();
581 componentFilter.setIgnoreArtifacts(false);
582 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE)
583 componentFilter.setIgnoreComponentInstances(false);
585 Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExistsByFilter(realComponentId, ComponentTypeEnum.findByParamName(containerComponentType), componentFilter, false);
587 if (validateComponent.isRight()) {
588 resultOp = Either.right(validateComponent.right().value());
591 component = validateComponent.left().value();
592 Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, "Update Artifact - lock ");
593 if (lockComponent.isRight()) {
595 resultOp = Either.right(lockComponent.right().value());
600 ArtifactGroupTypeEnum groupType = ArtifactGroupTypeEnum.findType(artifactGroupType);
602 if (groupType == null) {
603 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
604 log.debug("handleGetArtifactsByType - not falid groupType {} , component id {}", artifactGroupType, componentId);
606 resultOp = Either.right(responseFormat);
610 if (groupType == ArtifactGroupTypeEnum.DEPLOYMENT) {
611 List<ArtifactDefinition> list = getDeploymentArtifacts(component, componentType.getNodeType(), componentId);
612 if (list != null && !list.isEmpty()){
613 resMap = list.stream().collect(Collectors.toMap(a -> a.getArtifactLabel(), a -> a));
615 resMap = new HashMap<>();
617 resultOp = Either.left(resMap);
621 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifactsMapStatus = getArtifacts(realComponentId, componentType.getNodeType(), false, groupType, componentId );
622 if (artifactsMapStatus.isRight()) {
623 if (artifactsMapStatus.right().value() != StorageOperationStatus.NOT_FOUND) {
624 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
625 log.debug("handleGetArtifactsByType - not falid groupType {} , component id {}", artifactGroupType, componentId);
626 resultOp = Either.right(responseFormat);
628 resMap = new HashMap<>();
629 resultOp = Either.left(resMap);
632 resMap = artifactsMapStatus.left().value();
633 resultOp = Either.left(resMap);
639 if (resultOp == null || resultOp.isRight()) {
640 log.debug("all changes rollback");
643 log.debug("all changes committed");
648 componentType = component.getComponentType();
649 NodeTypeEnum nodeType = componentType.getNodeType();
650 graphLockOperation.unlockComponent(component.getUniqueId(), nodeType);
651 // graphLockOperation.unlockComponent(parentId, parentType);
656 private Either<ArtifactDefinition, ResponseFormat> validateArtifact(String componentId, ComponentTypeEnum componentType, String artifactId, org.openecomp.sdc.be.model.Component component, AuditingActionEnum auditingAction, String parentId,
657 boolean inTransaction) {
659 // check artifact existence
660 Either<ArtifactDefinition, StorageOperationStatus> artifactResult = artifactToscaOperation.getArtifactById(componentId, artifactId, componentType, component.getUniqueId());
661 if (artifactResult.isRight()) {
662 if (artifactResult.right().value().equals(StorageOperationStatus.ARTIFACT_NOT_FOUND)) {
663 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, "");
664 log.debug("addArtifact - artifact {} not found", artifactId);
665 return Either.right(responseFormat);
668 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(artifactResult.right().value()));
669 log.debug("addArtifact - failed to fetch artifact {}, error {}", artifactId, artifactResult.right().value());
670 return Either.right(responseFormat);
674 // check artifact belong to component
675 boolean found = false;
676 switch (componentType) {
679 found = checkArtifactInComponent(component, artifactId);
681 case RESOURCE_INSTANCE:
682 found = checkArtifactInResourceInstance(component, componentId, artifactId);
688 // String component =
689 // componentType.equals(ComponentTypeEnum.RESOURCE) ? "resource" :
691 String componentName = componentType.name().toLowerCase();
692 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ARTIFACT_NOT_FOUND, componentName);
693 log.debug("addArtifact - Component artifact not found component Id {}, artifact id {}", componentId, artifactId);
694 return Either.right(responseFormat);
696 return Either.left(artifactResult.left().value());
699 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleCreate(String parentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, User user, ComponentTypeEnum componentType,
700 org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
702 String artifactId = null;
705 Either<byte[], ResponseFormat> payloadEither = validateInput(parentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceType, operationName, inTransaction);
706 if (payloadEither.isRight()) {
707 return Either.right(payloadEither.right().value());
709 byte[] decodedPayload = payloadEither.left().value();
710 convertParentType(componentType);
713 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Upload Artifact - lock ");
714 if (lockComponent.isRight()) {
715 handleAuditing(auditingAction, parent, parentId, user, null, null, null, lockComponent.right().value(), componentType, null);
716 return Either.right(lockComponent.right().value());
719 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
722 resultOp = createArtifact(parent, parentId, artifactInfo, decodedPayload, user, componentType, auditingAction, interfaceType, operationName);
726 unlockComponent(resultOp, parent, inTransaction);
733 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> lockComponentAndUpdateArtifact(String parentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user,
734 ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent, byte[] decodedPayload, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
736 convertParentType(componentType);
740 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Update Artifact - lock ");
742 if (lockComponent.isRight()) {
743 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right().value(), componentType, null);
744 return Either.right(lockComponent.right().value());
748 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
750 resultOp = updateArtifactFlow(parent, parentId, artifactId, artifactInfo, user, decodedPayload, componentType, auditingAction, interfaceType, operationName);
755 unlockComponent(resultOp, parent, inTransaction);
760 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdate(String parentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, String artifactId, User user,
761 ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
763 Either<byte[], ResponseFormat> payloadEither = validateInput(parentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceType, operationName, inTransaction);
765 if (payloadEither.isRight()) {
766 return Either.right(payloadEither.right().value());
768 byte[] decodedPayload = payloadEither.left().value();
770 return lockComponentAndUpdateArtifact(parentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, decodedPayload, interfaceType, operationName, shouldLock, inTransaction);
773 private Either<byte[], ResponseFormat> validateInput(String parentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType,
774 org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean inTransaction) {
776 Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
777 if (validateMd5.isRight()) {
778 ResponseFormat responseFormat = validateMd5.right().value();
779 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
780 return Either.right(responseFormat);
784 Either<ArtifactDefinition, ResponseFormat> validateResult = validateInput(parentId, artifactInfo, operation, artifactId, user, interfaceType, operationName, componentType, parent, inTransaction);
785 if (validateResult.isRight()) {
786 ResponseFormat responseFormat = validateResult.right().value();
787 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
788 return Either.right(validateResult.right().value());
791 Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
792 if (payloadEither.isRight()) {
793 ResponseFormat responseFormat = payloadEither.right().value();
794 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
795 log.debug("Error during handle payload");
796 return Either.right(responseFormat);
799 // validate heat parameters. this part must be after the parameters are
800 // extracted in "handlePayload"
801 Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers = validateAndConvertHeatParamers(artifactInfo, artifactInfo.getArtifactType());
802 if (validateAndConvertHeatParamers.isRight()) {
803 ResponseFormat responseFormat = validateAndConvertHeatParamers.right().value();
804 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, null, artifactId, responseFormat, componentType, null);
805 log.debug("Error during handle payload");
806 return Either.right(responseFormat);
808 return payloadEither;
811 public void handleAuditing(AuditingActionEnum auditingActionEnum, Component component, String componentId, User user, ArtifactDefinition artifactDefinition, String prevArtifactUuid, String currentArtifactUuid, ResponseFormat responseFormat,
812 ComponentTypeEnum componentTypeEnum, String resourceInstanceName) {
814 if (auditingActionEnum.getAuditingEsType().equals(AuditingTypesConstants.EXTERNAL_API_EVENT_TYPE)) {
818 EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = createArtifactAuditingFields(artifactDefinition, prevArtifactUuid, currentArtifactUuid);
822 user.setUserId("UNKNOWN");
824 switch (componentTypeEnum) {
827 Resource resource = (Resource) component;
828 if (resource == null) {
829 // In that case, component ID should be instead of name
830 resource = new Resource();
831 resource.setName(componentId);
833 componentsUtils.auditResource(responseFormat, user, resource, null, null, auditingActionEnum, auditingFields);
837 Service service = (Service) component;
838 if (service == null) {
839 // In that case, component ID should be instead of name
840 service = new Service();
841 service.setName(componentId);
843 componentsUtils.auditComponent(responseFormat, user, service, null, null, auditingActionEnum, ComponentTypeEnum.SERVICE, auditingFields);
846 case RESOURCE_INSTANCE:
847 if (resourceInstanceName == null) {
848 resourceInstanceName = getResourceInstanceNameFromComponent(component, componentId);
850 auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceInstanceName);
851 componentsUtils.auditComponent(responseFormat, user, component, null, null, auditingActionEnum, ComponentTypeEnum.RESOURCE_INSTANCE, auditingFields);
859 private String getResourceInstanceNameFromComponent(Component component, String componentId) {
860 ComponentInstance resourceInstance = component.getComponentInstances().stream().filter(p -> p.getUniqueId().equals(componentId)).findFirst().orElse(null);
861 String resourceInstanceName = null;
862 if (resourceInstance != null) {
863 resourceInstanceName = resourceInstance.getName();
865 return resourceInstanceName;
868 public EnumMap<AuditingFieldsKeysEnum, Object> createArtifactAuditingFields(ArtifactDefinition artifactDefinition, String prevArtifactUuid, String currentArtifactUuid) {
869 EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
870 // Putting together artifact info
871 String artifactData = buildAuditingArtifactData(artifactDefinition);
872 auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, artifactData);
873 auditingFields.put(AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID, prevArtifactUuid);
874 auditingFields.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, currentArtifactUuid);
875 return auditingFields;
880 private String buildAuditingArtifactData(ArtifactDefinition artifactDefinition) {
881 StringBuilder sb = new StringBuilder();
882 if (artifactDefinition != null) {
883 sb.append(artifactDefinition.getArtifactGroupType().getType()).append(",").append("'").append(artifactDefinition.getArtifactLabel()).append("'").append(",").append(artifactDefinition.getArtifactType()).append(",")
884 .append(artifactDefinition.getArtifactName()).append(",").append(artifactDefinition.getTimeout()).append(",").append(artifactDefinition.getEsId());
887 if (artifactDefinition.getArtifactVersion() != null) {
889 sb.append(artifactDefinition.getArtifactVersion());
894 if (artifactDefinition.getArtifactUUID() != null) {
895 sb.append(artifactDefinition.getArtifactUUID());
900 return sb.toString();
903 private Either<Boolean, ResponseFormat> validateMd5(String origMd5, String originData, byte[] payload, ArtifactOperationInfo operation) {
905 if (origMd5 != null) {
906 String encodeBase64Str = GeneralUtility.calculateMD5ByString(originData);
908 if (false == encodeBase64Str.equals(origMd5)) {
909 log.debug("The calculated md5 is different then the received one");
910 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_MD5));
913 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create) {
914 log.debug("Missing md5 header during artifact create");
915 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_MD5));
918 if (payload != null && payload.length != 0) {
919 log.debug("Cannot have payload while md5 header is missing");
920 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
923 return Either.left(true);
926 private Either<ArtifactDefinition, ResponseFormat> validateInput(String parentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, String artifactId, User user, String interfaceName, String operationName,
927 ComponentTypeEnum componentType, Component parentComponent, boolean inTransaction) {
929 Either<Boolean, ResponseFormat> validateInformationalArtifactRes = validateInformationalArtifact(artifactInfo, parentComponent);
930 if (validateInformationalArtifactRes.isRight()) {
931 return Either.right(validateInformationalArtifactRes.right().value());
933 Either<Boolean, ResponseFormat> validateAndSetArtifactname = validateAndSetArtifactname(artifactInfo);
934 if (validateAndSetArtifactname.isRight()) {
935 return Either.right(validateAndSetArtifactname.right().value());
937 Either<ArtifactDefinition, ResponseFormat> artifactById = findArtifactOnParentComponent(parentComponent, parentId, operation, artifactId);
938 if (artifactById.isRight()) {
939 return Either.right(artifactById.right().value());
941 ArtifactDefinition currentArtifactInfo = artifactById.left().value();
942 if (operationName != null && interfaceName != null) {
943 operationName = operationName.toLowerCase();
944 interfaceName = interfaceName.toLowerCase();
946 Either<ActionStatus, ResponseFormat> logicalNameStatus = handleArtifactLabel(parentId, operation, artifactId, artifactInfo, interfaceName, operationName, currentArtifactInfo, componentType, inTransaction);
947 if (logicalNameStatus.isRight()) {
948 return Either.right(logicalNameStatus.right().value());
950 // This is a patch to block possibility of updating service api fields
951 // through other artifacts flow
953 if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.Create) {
954 checkAndSetUnUpdatableFields(user, artifactInfo, currentArtifactInfo, (operationName != null ? ArtifactGroupTypeEnum.LIFE_CYCLE : ArtifactGroupTypeEnum.INFORMATIONAL));
956 checkCreateFields(user, artifactInfo, (operationName != null ? ArtifactGroupTypeEnum.LIFE_CYCLE : ArtifactGroupTypeEnum.INFORMATIONAL));
959 composeArtifactId(parentId, artifactId, artifactInfo, interfaceName, operationName);
960 if (currentArtifactInfo != null) {
961 artifactInfo.setMandatory(currentArtifactInfo.getMandatory());
964 // artifactGroupType is not allowed to be updated
965 if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.Create) {
966 Either<ArtifactDefinition, ResponseFormat> validateGroupType = validateOrSetArtifactGroupType(artifactInfo, currentArtifactInfo);
967 if (validateGroupType.isRight()) {
968 return Either.right(validateGroupType.right().value());
972 NodeTypeEnum parentType = convertParentType(componentType);
975 boolean isCreate = operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create;
977 if (isDeploymentArtifact(artifactInfo)) {
978 Either<Boolean, ResponseFormat> deploymentValidationResult = validateDeploymentArtifact(parentComponent, parentId, user.getUserId(), isCreate, artifactInfo, currentArtifactInfo, parentType);
979 if (deploymentValidationResult.isRight()) {
980 return Either.right(deploymentValidationResult.right().value());
983 artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
986 * if (informationDeployedArtifactsBusinessLogic. isInformationDeployedArtifact(artifactInfo)) { Either<Boolean, ResponseFormat> validationResult = informationDeployedArtifactsBusinessLogic.validateArtifact( isCreate, artifactInfo,
987 * parentComponent, parentType); if (validationResult.isRight()) { return Either.right(validationResult.right().value()); } }
991 Either<Boolean, ResponseFormat> descriptionResult = validateAndCleanDescription(artifactInfo);
992 if (descriptionResult.isRight()) {
993 return Either.right(descriptionResult.right().value());
996 if (currentArtifactInfo != null && currentArtifactInfo.getArtifactGroupType().equals(ArtifactGroupTypeEnum.SERVICE_API)) {
997 Either<ActionStatus, ResponseFormat> validateServiceApiType = validateArtifactType(user.getUserId(), artifactInfo, parentType);
998 if (validateServiceApiType.isRight()) {
999 return Either.right(validateServiceApiType.right().value());
1001 // Change of type is not allowed and should be ignored
1003 artifactInfo.setArtifactType(ARTIFACT_TYPE_OTHER);
1005 Either<Boolean, ResponseFormat> validateUrl = validateAndServiceApiUrl(artifactInfo);
1006 if (validateUrl.isRight()) {
1007 return Either.right(validateUrl.right().value());
1010 Either<Boolean, ResponseFormat> validateUpdate = validateFirstUpdateHasPayload(artifactInfo, currentArtifactInfo);
1011 if (validateUpdate.isRight()) {
1012 log.debug("serviceApi first update cnnot be without payload.");
1013 return Either.right(validateUpdate.right().value());
1016 Either<ActionStatus, ResponseFormat> validateArtifactType = validateArtifactType(user.getUserId(), artifactInfo, parentType);
1017 if (validateArtifactType.isRight()) {
1018 return Either.right(validateArtifactType.right().value());
1020 if (artifactInfo.getApiUrl() != null) {
1021 artifactInfo.setApiUrl(null);
1022 log.error("Artifact URL cannot be set through this API - ignoring");
1025 if (artifactInfo.getServiceApi() != null) {
1026 if (artifactInfo.getServiceApi()) {
1027 artifactInfo.setServiceApi(false);
1028 log.error("Artifact service API flag cannot be changed - ignoring");
1033 return Either.left(artifactInfo);
1036 private Either<ArtifactDefinition, ResponseFormat> findArtifactOnParentComponent(Component parentComponent, String parentId, ArtifactOperationInfo operation, String artifactId) {
1038 Either<ArtifactDefinition, ResponseFormat> result = null;
1039 ArtifactDefinition foundArtifact = null;
1040 if (StringUtils.isNotEmpty(artifactId)) {
1041 if (parentComponent.getUniqueId().equals(parentId)) {
1042 if (parentComponent.getDeploymentArtifacts() != null) {
1043 foundArtifact = parentComponent.getDeploymentArtifacts().values().stream().filter(e -> e.getUniqueId().equals(artifactId)).findFirst().orElse(null);
1045 if (foundArtifact == null && parentComponent.getArtifacts() != null) {
1046 foundArtifact = parentComponent.getArtifacts().values().stream().filter(e -> e.getUniqueId().equals(artifactId)).findFirst().orElse(null);
1049 ComponentInstance instance = findComponentInstance(parentId, parentComponent);
1050 if (instance.getDeploymentArtifacts() != null) {
1051 foundArtifact = instance.getDeploymentArtifacts().values().stream().filter(e -> e.getUniqueId().equals(artifactId)).findFirst().orElse(null);
1053 if (foundArtifact == null && instance.getArtifacts() != null) {
1054 foundArtifact = instance.getArtifacts().values().stream().filter(e -> e.getUniqueId().equals(artifactId)).findFirst().orElse(null);
1058 if (foundArtifact != null && operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create) {
1059 log.debug("Artifact {} already exist", artifactId);
1060 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, foundArtifact.getArtifactLabel()));
1062 if (foundArtifact == null && operation.getArtifactOperationEnum() != ArtifactOperationEnum.Create) {
1063 log.debug("The artifact {} was not found on parent {}. ", artifactId, parentId);
1064 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ""));
1066 if (result == null) {
1067 result = Either.left(foundArtifact);
1072 private Either<Boolean, ResponseFormat> validateInformationalArtifact(ArtifactDefinition artifactInfo, Component parentComponent) {
1073 ComponentTypeEnum parentComponentType = parentComponent.getComponentType();
1074 ArtifactGroupTypeEnum groupType = artifactInfo.getArtifactGroupType();
1075 Either<Boolean, ResponseFormat> validationResult = Either.left(true);
1076 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
1077 if (artifactType == null) {
1078 validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType()));
1079 } else if (parentComponentType == ComponentTypeEnum.RESOURCE && groupType == ArtifactGroupTypeEnum.INFORMATIONAL) {
1080 String artifactTypeName = artifactType.getType();
1081 ResourceTypeEnum parentResourceType = ((Resource) parentComponent).getResourceType();
1082 Map<String, ArtifactTypeConfig> resourceInformationalArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceInformationalArtifacts();
1083 Set<String> validArtifactTypes = resourceInformationalArtifacts.keySet();
1084 if (!validArtifactTypes.contains(artifactTypeName)) {
1085 validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactTypeName));
1087 List<String> validResourceType = resourceInformationalArtifacts.get(artifactTypeName).getValidForResourceTypes();
1088 if (!validResourceType.contains(parentResourceType.name())) {
1089 validationResult = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactTypeName));
1093 return validationResult;
1096 private NodeTypeEnum convertParentType(ComponentTypeEnum componentType) {
1097 if (componentType.equals(ComponentTypeEnum.RESOURCE)) {
1098 return NodeTypeEnum.Resource;
1099 } else if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)) {
1100 return NodeTypeEnum.ResourceInstance;
1102 return NodeTypeEnum.Service;
1106 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete(String parentId, String artifactId, User user, AuditingActionEnum auditingAction, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent,
1107 String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
1109 NodeTypeEnum parentType = convertParentType(componentType);
1110 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
1111 Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> getArtifactRes = null;
1112 ArtifactDefinition foundArtifact = null;
1113 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
1114 Either<org.openecomp.sdc.be.model.Component, StorageOperationStatus> getContainerRes = null;
1115 org.openecomp.sdc.be.model.Component fetchedContainerComponent = null;
1116 boolean isDuplicated = false;
1118 Either<Boolean, StorageOperationStatus> needCloneRes = null;
1121 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Delete Artifact - lock resource: ");
1122 if (lockComponent.isRight()) {
1123 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right().value(), componentType, null);
1124 resultOp = Either.right(lockComponent.right().value());
1127 if (resultOp == null) {
1128 log.debug("Going to fetch the container component {}. ", parent.getUniqueId());
1129 getContainerRes = toscaOperationFacade.getToscaElement(parent.getUniqueId());
1130 if (getContainerRes.isRight()) {
1131 log.debug("Failed to fetch the container component {}. ", parentId);
1132 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(getContainerRes.right().value()), artifactId);
1133 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1134 resultOp = Either.right(responseFormat);
1137 if (resultOp == null) {
1138 fetchedContainerComponent = getContainerRes.left().value();
1139 log.debug("Going to find the artifact {} on the component {}", artifactId, fetchedContainerComponent.getUniqueId());
1140 getArtifactRes = findArtifact(artifactId, fetchedContainerComponent, parentId, componentType);
1141 if (getArtifactRes.isRight()) {
1142 log.debug("Failed to find the artifact {} belonging to {} on the component {}", artifactId, parentId, fetchedContainerComponent.getUniqueId());
1143 responseFormat = componentsUtils.getResponseFormatByArtifactId(getArtifactRes.right().value(), artifactId);
1144 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1145 resultOp = Either.right(responseFormat);
1147 foundArtifact = getArtifactRes.left().value().getLeft();
1148 esId = foundArtifact.getEsId();
1151 if (resultOp == null && StringUtils.isNotEmpty(esId)) {
1152 needCloneRes = artifactToscaOperation.isCloneNeeded(parent.getUniqueId(), foundArtifact, convertParentType(parent.getComponentType()));
1153 if (needCloneRes.isRight()) {
1154 log.debug("Failed to delete or update the artifact {}. Parent uniqueId is {}", artifactId, parentId);
1155 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(needCloneRes.right().value()), foundArtifact.getArtifactDisplayName());
1156 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1157 resultOp = Either.right(responseFormat);
1160 if (resultOp == null) {
1161 Either<ArtifactDataDefinition, StorageOperationStatus> updatedArtifactRes = deleteOrUpdateArtifactOnGraph(parent, parentId, artifactId, parentType, foundArtifact, needCloneRes.left().value());
1162 if (updatedArtifactRes.isRight()) {
1163 log.debug("Failed to delete or update the artifact {}. Parent uniqueId is {}", artifactId, parentId);
1164 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updatedArtifactRes.right().value()), foundArtifact.getArtifactDisplayName());
1165 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1166 resultOp = Either.right(responseFormat);
1168 isDuplicated = updatedArtifactRes.left().value().getDuplicated();
1172 if (resultOp == null && (!needCloneRes.left().value() && !isDuplicated)) {
1173 log.debug("Going to delete the artifact {} from the database. ", artifactId);
1174 CassandraOperationStatus cassandraStatus = artifactCassandraDao.deleteArtifact(esId);
1175 if (cassandraStatus != CassandraOperationStatus.OK) {
1176 log.debug("Failed to delete the artifact {} from the database. ", artifactId);
1177 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(convertToStorageOperationStatus(cassandraStatus)), foundArtifact.getArtifactDisplayName());
1178 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1179 resultOp = Either.right(responseFormat);
1182 if (resultOp == null && componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1184 List<GroupInstance> updatedGroupInstances = getUpdatedGroupInstances(artifactId, foundArtifact, getArtifactRes.left().value().getRight().getGroupInstances());
1185 if (CollectionUtils.isNotEmpty(updatedGroupInstances)) {
1186 Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(fetchedContainerComponent, componentType, parentId, updatedGroupInstances);
1187 if (status.isRight()) {
1188 log.debug("Failed to update groups of the component {}. ", fetchedContainerComponent.getUniqueId());
1189 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status.right().value()), foundArtifact.getArtifactDisplayName());
1190 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1191 resultOp = Either.right(responseFormat);
1195 if (resultOp == null && componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1196 StorageOperationStatus status = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentType);
1197 if (status != StorageOperationStatus.OK) {
1198 log.debug("Failed to generate new customization UUID for the component instance {}. ", parentId);
1199 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status), foundArtifact.getArtifactDisplayName());
1200 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1201 resultOp = Either.right(responseFormat);
1204 if (resultOp == null && componentType != ComponentTypeEnum.RESOURCE_INSTANCE) {
1205 List<GroupDataDefinition> updatedGroups = getUpdatedGroups(artifactId, foundArtifact, fetchedContainerComponent.getGroups());
1206 if (CollectionUtils.isNotEmpty(updatedGroups)) {
1207 Either<List<GroupDefinition>, StorageOperationStatus> status = toscaOperationFacade.updateGroupsOnComponent(fetchedContainerComponent, componentType, updatedGroups);
1208 if (status.isRight()) {
1209 log.debug("Failed to update groups of the component {}. ", fetchedContainerComponent.getUniqueId());
1210 responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status.right().value()), foundArtifact.getArtifactDisplayName());
1211 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
1212 resultOp = Either.right(responseFormat);
1216 if (resultOp == null) {
1217 resultOp = Either.left(Either.left(foundArtifact));
1218 handleAuditing(auditingAction, parent, parentId, user, foundArtifact, null, artifactId, responseFormat, componentType, null);
1223 unlockComponent(resultOp, parent, inTransaction);
1228 private List<GroupDataDefinition> getUpdatedGroups(String artifactId, ArtifactDefinition foundArtifact, List<GroupDefinition> groups) {
1229 List<GroupDataDefinition> updatedGroups = new ArrayList<>();
1230 boolean isUpdated = false;
1231 if (groups != null) {
1232 for (GroupDefinition group : groups) {
1234 if (CollectionUtils.isNotEmpty(group.getArtifacts()) && group.getArtifacts().contains(artifactId)) {
1235 group.getArtifacts().remove(artifactId);
1238 if (CollectionUtils.isNotEmpty(group.getArtifactsUuid()) && group.getArtifactsUuid().contains(foundArtifact.getArtifactUUID())) {
1239 group.getArtifacts().remove(foundArtifact.getArtifactUUID());
1243 updatedGroups.add(group);
1247 return updatedGroups;
1250 private List<GroupInstance> getUpdatedGroupInstances(String artifactId, ArtifactDefinition foundArtifact, List<GroupInstance> groupInstances) {
1251 List<GroupInstance> updatedGroupInstances = new ArrayList<>();
1252 if (CollectionUtils.isNotEmpty(groupInstances)) {
1253 boolean isUpdated = false;
1254 for (GroupInstance groupInstance : groupInstances) {
1256 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifacts()) && groupInstance.getGroupInstanceArtifacts().contains(artifactId)) {
1257 groupInstance.getArtifacts().remove(artifactId);
1260 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifactsUuid()) && groupInstance.getGroupInstanceArtifactsUuid().contains(foundArtifact.getArtifactUUID())) {
1261 groupInstance.getArtifacts().remove(foundArtifact.getArtifactUUID());
1265 updatedGroupInstances.add(groupInstance);
1269 return updatedGroupInstances;
1272 private Either<ArtifactDataDefinition, StorageOperationStatus> deleteOrUpdateArtifactOnGraph(Component component, String parentId, String artifactId, NodeTypeEnum parentType, ArtifactDefinition foundArtifact, Boolean cloneIsNeeded) {
1274 Either<ArtifactDataDefinition, StorageOperationStatus> result;
1275 boolean isMandatory = foundArtifact.getMandatory() || foundArtifact.getServiceApi();
1276 String componentId = component.getUniqueId();
1277 String instanceId = componentId.equals(parentId) ? null : parentId;
1279 log.debug("Going to update mandatory artifact {} from the component {}", artifactId, parentId);
1280 resetMandatoryArtifactFields(foundArtifact);
1281 result = artifactToscaOperation.updateArtifactOnGraph(componentId, foundArtifact, parentType, artifactId, instanceId);
1282 } else if (cloneIsNeeded) {
1283 log.debug("Going to clone artifacts and to delete the artifact {} from the component {}", artifactId, parentId);
1284 result = artifactToscaOperation.deleteArtifactWithClonnigOnGraph(componentId, foundArtifact, parentType, instanceId, false);
1286 log.debug("Going to delete the artifact {} from the component {}", artifactId, parentId);
1287 result = artifactToscaOperation.removeArtifactOnGraph(foundArtifact, componentId, instanceId, parentType, false);
1292 private Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> findArtifact(String artifactId, Component fetchedContainerComponent, String parentId, ComponentTypeEnum componentType) {
1294 Either<ImmutablePair<ArtifactDefinition, ComponentInstance>, ActionStatus> result = null;
1295 Map<String, ArtifactDefinition> artifacts = new HashMap<>();
1296 ComponentInstance foundInstance = null;
1297 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE && StringUtils.isNotEmpty(parentId)) {
1298 Optional<ComponentInstance> componentInstanceOpt = fetchedContainerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(parentId)).findFirst();
1299 if (!componentInstanceOpt.isPresent()) {
1300 result = Either.right(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER);
1302 foundInstance = componentInstanceOpt.get();
1303 fetchArtifactsFromInstance(artifactId, artifacts, foundInstance);
1306 fetchArtifactsFromComponent(artifactId, fetchedContainerComponent, artifacts);
1308 if (result == null) {
1309 if (artifacts.containsKey(artifactId)) {
1310 result = Either.left(new ImmutablePair<>(artifacts.get(artifactId), foundInstance));
1312 result = Either.right(ActionStatus.ARTIFACT_NOT_FOUND);
1318 private void fetchArtifactsFromComponent(String artifactId, Component component, Map<String, ArtifactDefinition> artifacts) {
1319 Map<String, ArtifactDefinition> currArtifacts;
1320 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getDeploymentArtifacts())) {
1321 currArtifacts = component.getDeploymentArtifacts().values().stream().collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1322 if (MapUtils.isNotEmpty(currArtifacts)) {
1323 artifacts.putAll(currArtifacts);
1326 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getArtifacts())) {
1327 currArtifacts = component.getArtifacts().values().stream().collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1328 if (MapUtils.isNotEmpty(currArtifacts)) {
1329 artifacts.putAll(currArtifacts);
1332 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(component.getArtifacts())) {
1333 currArtifacts = component.getToscaArtifacts().values().stream().collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1334 if (MapUtils.isNotEmpty(currArtifacts)) {
1335 artifacts.putAll(currArtifacts);
1340 private void fetchArtifactsFromInstance(String artifactId, Map<String, ArtifactDefinition> artifacts, ComponentInstance instance) {
1341 Map<String, ArtifactDefinition> currArtifacts;
1342 if (MapUtils.isNotEmpty(instance.getDeploymentArtifacts())) {
1343 currArtifacts = instance.getDeploymentArtifacts().values().stream().collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1344 if (MapUtils.isNotEmpty(currArtifacts)) {
1345 artifacts.putAll(currArtifacts);
1348 if (!artifacts.containsKey(artifactId) && MapUtils.isNotEmpty(instance.getArtifacts())) {
1349 currArtifacts = instance.getArtifacts().values().stream().collect(Collectors.toMap(i -> i.getUniqueId(), i -> i));
1350 if (MapUtils.isNotEmpty(currArtifacts)) {
1351 artifacts.putAll(currArtifacts);
1356 private StorageOperationStatus convertToStorageOperationStatus(CassandraOperationStatus cassandraStatus) {
1357 StorageOperationStatus result;
1358 switch (cassandraStatus) {
1360 result = StorageOperationStatus.OK;
1363 result = StorageOperationStatus.NOT_FOUND;
1365 case CLUSTER_NOT_CONNECTED:
1366 case KEYSPACE_NOT_CONNECTED:
1367 result = StorageOperationStatus.CONNECTION_FAILURE;
1370 result = StorageOperationStatus.GENERAL_ERROR;
1376 private void resetMandatoryArtifactFields(ArtifactDefinition fetchedArtifact) {
1377 if (fetchedArtifact != null) {
1378 log.debug("Going to reset mandatory artifact {} fields. ", fetchedArtifact.getUniqueId());
1379 fetchedArtifact.setEsId("");
1380 fetchedArtifact.setArtifactName("");
1381 fetchedArtifact.setDescription("");
1382 fetchedArtifact.setApiUrl("");
1383 fetchedArtifact.setArtifactChecksum("");
1384 nodeTemplateOperation.setDefaultArtifactTimeout(fetchedArtifact.getArtifactGroupType(), fetchedArtifact);
1385 fetchedArtifact.setArtifactUUID("");
1386 long time = System.currentTimeMillis();
1387 fetchedArtifact.setPayloadUpdateDate(time);
1388 fetchedArtifact.setHeatParameters(null);
1389 fetchedArtifact.setHeatParamsUpdateDate(null);
1393 private StorageOperationStatus generateCustomizationUUIDOnInstance(String componentId, String instanceId, ComponentTypeEnum componentType) {
1394 StorageOperationStatus error = StorageOperationStatus.OK;
1395 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE) {
1396 log.debug("Need to re-generate customization UUID for instance {}", instanceId);
1397 error = toscaOperationFacade.generateCustomizationUUIDOnInstance(componentId, instanceId);
1402 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDownload(String componentId, String artifactId, User user, AuditingActionEnum auditingAction, ComponentTypeEnum componentType,
1403 org.openecomp.sdc.be.model.Component parent, boolean shouldLock, boolean inTransaction) {
1404 Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(componentId, artifactId, componentType, parent.getUniqueId());
1405 if (artifactById.isRight()) {
1406 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(artifactById.right().value());
1407 log.debug("Error when getting artifact info by id{}, error: {}", artifactId, actionStatus.name());
1408 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(actionStatus, "");
1409 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
1410 return Either.right(responseFormat);
1412 ArtifactDefinition artifactDefinition = artifactById.left().value();
1413 if (artifactDefinition == null) {
1414 log.debug("Empty artifact definition returned from DB by artifact id {}", artifactId);
1415 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, "");
1416 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
1417 return Either.right(responseFormat);
1419 Either<ArtifactDefinition, Operation> insideEither = Either.left(artifactDefinition);
1420 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
1421 handleAuditing(auditingAction, parent, componentId, user, artifactDefinition, null, artifactId, responseFormat, componentType, null);
1422 return Either.left(insideEither);
1425 private Either<ArtifactDefinition, ResponseFormat> fetchCurrentArtifact(String parentId, ArtifactOperationInfo operation, String artifactId) {
1426 Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(parentId, artifactId);
1427 if (!(operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create) && artifactById.isRight()) {
1428 // in case of update artifact must be
1429 BeEcompErrorManager.getInstance().logBeArtifactMissingError("Artifact Update / Upload", artifactId);
1430 log.debug("Failed to fetch artifact {}. error: {}", artifactId, artifactById.right().value());
1431 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(artifactById.right().value()), artifactId));
1433 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create && artifactById.isLeft()) {
1434 log.debug("Artifact {} already exist", artifactId);
1435 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactById.left().value().getArtifactLabel()));
1437 ArtifactDefinition currentArtifactInfo = null;
1438 if (artifactById.isLeft()) {
1439 // get previous value
1440 currentArtifactInfo = artifactById.left().value();
1442 return Either.left(currentArtifactInfo);
1445 private Either<ActionStatus, ResponseFormat> handleArtifactLabel(String componentId, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, String interfaceName, String operationName,
1446 ArtifactDefinition currentArtifactInfo, ComponentTypeEnum componentType, boolean inTransaction) {
1447 String artifactLabel = artifactInfo.getArtifactLabel();
1449 if (operationName == null && (artifactInfo.getArtifactLabel() == null || artifactInfo.getArtifactLabel().isEmpty())) {
1450 BeEcompErrorManager.getInstance().logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel");
1451 log.debug("missing artifact logical name for component {}", componentId);
1452 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_LABEL));
1454 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create && !artifactInfo.getMandatory()) {
1456 if (operationName != null) {
1457 if (artifactInfo.getArtifactLabel() != null && !operationName.equals(artifactInfo.getArtifactLabel())) {
1458 log.debug("artifact label cannot be set {}", artifactLabel);
1459 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_LOGICAL_NAME_CANNOT_BE_CHANGED));
1461 artifactLabel = operationName;
1464 String displayName = artifactInfo.getArtifactDisplayName();
1465 if (displayName == null || displayName.isEmpty())
1466 displayName = artifactLabel;
1467 displayName = ValidationUtils.cleanArtifactDisplayName(displayName);
1468 // if (!ValidationUtils.validateArtifactDisplayName(displayName)) {
1469 // log.debug("Invalid format form Artifact displayName : {}", displayName);
1470 // return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1472 artifactInfo.setArtifactDisplayName(displayName);
1474 if (!ValidationUtils.validateArtifactLabel(artifactLabel)) {
1475 log.debug("Invalid format form Artifact label : {}", artifactLabel);
1476 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1478 artifactLabel = ValidationUtils.normalizeArtifactLabel(artifactLabel);
1480 if (artifactLabel.isEmpty()) {
1481 log.debug("missing normalized artifact logical name for component {}", componentId);
1482 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_LABEL));
1485 if (!ValidationUtils.validateArtifactLabelLength(artifactLabel)) {
1486 log.debug("Invalid lenght form Artifact label : {}", artifactLabel);
1487 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_LABEL, String.valueOf(ValidationUtils.ARTIFACT_LABEL_LENGTH)));
1489 if (!validateLabelUniqueness(componentId, artifactLabel, componentType)) {
1490 log.debug("Non unique Artifact label : {}", artifactLabel);
1491 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactLabel));
1494 artifactInfo.setArtifactLabel(artifactLabel);
1496 if (currentArtifactInfo != null && !currentArtifactInfo.getArtifactLabel().equals(artifactInfo.getArtifactLabel())) {
1497 log.info("Logical artifact's name cannot be changed {}", artifactId);
1498 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_LOGICAL_NAME_CANNOT_BE_CHANGED));
1500 return Either.left(ActionStatus.OK);
1503 private boolean validateLabelUniqueness(String parentId, String artifactLabel, ComponentTypeEnum componentType) {
1504 boolean isUnique = true;
1505 if (componentType.equals(ComponentTypeEnum.RESOURCE)) {
1508 // Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifacts = artifactOperation.getArtifacts(parentId, parentType, inTransaction);
1509 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifacts = artifactToscaOperation.getArtifacts(parentId);
1510 if (artifacts.isLeft()) {
1511 for (String label : artifacts.left().value().keySet()) {
1512 if (label.equals(artifactLabel)) {
1518 if (componentType.equals(ComponentTypeEnum.RESOURCE)) {
1519 Either<Map<String, InterfaceDefinition>, StorageOperationStatus> allInterfacesOfResource = interfaceLifecycleOperation.getAllInterfacesOfResource(parentId, true, true);
1520 if (allInterfacesOfResource.isLeft()) {
1521 for (InterfaceDefinition interace : allInterfacesOfResource.left().value().values()) {
1522 for (Operation operation : interace.getOperationsMap().values()) {
1523 if (operation.getImplementation() != null && operation.getImplementation().getArtifactLabel().equals(artifactLabel)) {
1534 // ***************************************************************
1536 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> createArtifact(org.openecomp.sdc.be.model.Component parent, String parentId, ArtifactDefinition artifactInfo, byte[] decodedPayload, User user,
1537 ComponentTypeEnum componentTypeEnum, AuditingActionEnum auditingActionEnum, String interfaceType, String operationName) {
1539 ESArtifactData artifactData = createEsArtifactData(artifactInfo, decodedPayload);
1540 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
1541 Either<ArtifactDefinition, Operation> insideEither = null;
1542 ComponentInstance foundInstance = findComponentInstance(parentId, parent);
1543 String instanceId = null;
1544 String instanceName = null;
1545 if (foundInstance != null) {
1546 instanceId = foundInstance.getUniqueId();
1547 instanceName = foundInstance.getName();
1549 if (artifactData == null) {
1550 BeEcompErrorManager.getInstance().logBeDaoSystemError("Upload Artifact");
1551 log.debug("Failed to create artifact object for ES.");
1552 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
1553 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, null);
1554 resultOp = Either.right(responseFormat);
1558 // set on graph object id of artifact in ES!
1559 artifactInfo.setEsId(artifactData.getId());
1561 boolean isLeft = false;
1562 String artifactUniqueId = null;
1563 StorageOperationStatus error = null;
1564 if (interfaceType != null && operationName != null) {
1565 // lifecycle artifact
1566 Operation operation = convertToOperation(artifactInfo, operationName);
1568 Either<Operation, StorageOperationStatus> result = interfaceLifecycleOperation.updateInterfaceOperation(parentId, interfaceType, operationName, operation);
1570 isLeft = result.isLeft();
1572 artifactUniqueId = result.left().value().getImplementation().getUniqueId();
1573 result.left().value().getImplementation();
1575 insideEither = Either.right(result.left().value());
1576 resultOp = Either.left(insideEither);
1578 error = result.right().value();
1581 // information/deployment/api aritfacts
1582 log.trace("Try to create entry on graph");
1583 NodeTypeEnum nodeType = convertParentType(componentTypeEnum);
1584 Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.addArifactToComponent(artifactInfo, parent.getUniqueId(), nodeType, true, instanceId);
1586 isLeft = result.isLeft();
1588 artifactUniqueId = result.left().value().getUniqueId();
1589 result.left().value();
1591 insideEither = Either.left(result.left().value());
1592 resultOp = Either.left(insideEither);
1594 error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentTypeEnum);
1595 if (error != StorageOperationStatus.OK) {
1600 error = result.right().value();
1604 boolean res = saveArtifacts(artifactData, parentId, false);
1605 // String uniqueId = artifactDefinition.getUniqueId();
1608 log.debug("Artifact saved into ES - {}", artifactUniqueId);
1610 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
1611 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, artifactUniqueId, artifactUniqueId, responseFormat, componentTypeEnum, instanceName);
1614 BeEcompErrorManager.getInstance().logBeDaoSystemError("Upload Artifact");
1615 log.debug("Failed to save the artifact.");
1616 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
1617 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, artifactUniqueId, responseFormat, componentTypeEnum, instanceName);
1619 resultOp = Either.right(responseFormat);
1623 log.debug("Failed to create entry on graph for artifact {}", artifactInfo.getArtifactName());
1624 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(error), artifactInfo.getArtifactDisplayName());
1625 handleAuditing(auditingActionEnum, parent, parentId, user, artifactInfo, null, null, responseFormat, componentTypeEnum, instanceName);
1626 resultOp = Either.right(responseFormat);
1632 private ComponentInstance findComponentInstance(String componentInstanceId, Component containerComponent) {
1633 ComponentInstance foundInstance = null;
1634 if (CollectionUtils.isNotEmpty(containerComponent.getComponentInstances())) {
1635 foundInstance = containerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(componentInstanceId)).findFirst().orElse(null);
1637 return foundInstance;
1640 private Either<Boolean, ResponseFormat> validateDeploymentArtifact(Component parentComponent, String parentId, String userId, boolean isCreate, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, NodeTypeEnum parentType) {
1642 Either<Boolean, ResponseFormat> result = Either.left(true);
1643 Wrapper<ResponseFormat> responseWrapper = new Wrapper<ResponseFormat>();
1645 validateArtifactTypeExists(responseWrapper, artifactInfo);
1647 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
1649 Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts = fillDeploymentArtifactTypeConf(parentType);
1651 if (responseWrapper.isEmpty()) {
1652 validateDeploymentArtifactConf(artifactInfo, responseWrapper, artifactType, resourceDeploymentArtifacts);
1655 if (responseWrapper.isEmpty()) {
1656 // Common code for all types
1657 // not allowed to change artifactType
1659 Either<Boolean, ResponseFormat> validateServiceApiType = validateArtifactTypeNotChanged(artifactInfo, currentArtifact);
1660 if (validateServiceApiType.isRight()) {
1661 responseWrapper.setInnerElement(validateServiceApiType.right().value());
1665 if (responseWrapper.isEmpty()) {
1666 if (parentType.equals(NodeTypeEnum.Resource)) {
1667 // if (parentComponent instanceof Resource) {
1668 Resource resource = (Resource) parentComponent;
1669 ResourceTypeEnum resourceType = resource.getResourceType();
1670 ArtifactTypeConfig config = resourceDeploymentArtifacts.get(artifactType.getType());
1671 if (config == null) {
1672 responseWrapper.setInnerElement(ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType()));
1674 List<String> myList = config.getValidForResourceTypes();
1675 Either<Boolean, ResponseFormat> either = validateResourceType(resourceType, artifactInfo, myList);
1676 if (either.isRight()) {
1677 responseWrapper.setInnerElement(either.right().value());
1682 if (responseWrapper.isEmpty()) {
1683 validateFileExtension(responseWrapper, () -> getDeploymentArtifactTypeConfig(parentType, artifactType), artifactInfo, parentType, artifactType);
1686 if (responseWrapper.isEmpty() && !NodeTypeEnum.ResourceInstance.equals(parentType)) {
1687 String artifactName = artifactInfo.getArtifactName();
1688 if (isCreate || !artifactName.equalsIgnoreCase(currentArtifact.getArtifactName())) {
1689 validateSingleDeploymentArtifactName(responseWrapper, artifactName, parentComponent, parentType);
1693 if (responseWrapper.isEmpty()) {
1694 switch (artifactType) {
1698 result = validateHeatDeploymentArtifact(parentComponent, userId, isCreate, artifactInfo, currentArtifact, parentType);
1702 result = validateHeatEnvDeploymentArtifact(parentComponent, parentId, userId, isCreate, artifactInfo, parentType);
1703 artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
1706 case DCAE_INVENTORY_TOSCA:
1707 case DCAE_INVENTORY_JSON:
1708 case DCAE_INVENTORY_POLICY:
1709 // Validation is done in handle payload.
1710 case DCAE_INVENTORY_DOC:
1711 case DCAE_INVENTORY_BLUEPRINT:
1712 case DCAE_INVENTORY_EVENT:
1713 // No specific validation
1715 artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
1721 if (!responseWrapper.isEmpty()) {
1722 result = Either.right(responseWrapper.getInnerElement());
1727 private void validateDeploymentArtifactConf(ArtifactDefinition artifactInfo, Wrapper<ResponseFormat> responseWrapper, ArtifactTypeEnum artifactType, Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts) {
1728 if ((resourceDeploymentArtifacts == null) || !resourceDeploymentArtifacts.containsKey(artifactType.name())) {
1729 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType());
1730 responseWrapper.setInnerElement(responseFormat);
1731 log.debug("Artifact Type: {} Not found !", artifactInfo.getArtifactType());
1735 private Map<String, ArtifactTypeConfig> fillDeploymentArtifactTypeConf(NodeTypeEnum parentType) {
1736 Map<String, ArtifactTypeConfig> resourceDeploymentArtifacts = null;
1737 if (parentType.equals(NodeTypeEnum.Resource)) {
1738 resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceDeploymentArtifacts();
1739 } else if (parentType.equals(NodeTypeEnum.ResourceInstance)) {
1740 resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceInstanceDeploymentArtifacts();
1742 resourceDeploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getServiceDeploymentArtifacts();
1744 return resourceDeploymentArtifacts;
1747 public void validateArtifactTypeExists(Wrapper<ResponseFormat> responseWrapper, ArtifactDefinition artifactInfo) {
1748 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
1749 if (artifactType == null) {
1750 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType());
1751 responseWrapper.setInnerElement(responseFormat);
1752 log.debug("Artifact Type: {} Not found !", artifactInfo.getArtifactType());
1756 private ArtifactTypeConfig getDeploymentArtifactTypeConfig(NodeTypeEnum parentType, ArtifactTypeEnum artifactType) {
1757 ArtifactTypeConfig retConfig = null;
1758 String fileType = artifactType.getType();
1759 if (parentType.equals(NodeTypeEnum.Resource)) {
1760 retConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceDeploymentArtifacts().get(fileType);
1761 } else if (parentType.equals(NodeTypeEnum.Service)) {
1762 retConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getServiceDeploymentArtifacts().get(fileType);
1763 } else if (parentType.equals(NodeTypeEnum.ResourceInstance)) {
1764 retConfig = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceInstanceDeploymentArtifacts().get(fileType);
1769 private Either<Boolean, ResponseFormat> extractHeatParameters(ArtifactDefinition artifactInfo) {
1770 // extract heat parameters
1771 if (artifactInfo.getPayloadData() != null) {
1772 String heatDecodedPayload = new String(Base64.decodeBase64(artifactInfo.getPayloadData()));
1773 Either<List<HeatParameterDefinition>, ResultStatusEnum> heatParameters = ImportUtils.getHeatParamsWithoutImplicitTypes(heatDecodedPayload, artifactInfo.getArtifactType());
1774 if (heatParameters.isRight() && (!heatParameters.right().value().equals(ResultStatusEnum.ELEMENT_NOT_FOUND))) {
1775 log.info("failed to parse heat parameters ");
1776 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactInfo.getArtifactType());
1777 return Either.right(responseFormat);
1778 } else if (heatParameters.isLeft() && heatParameters.left().value() != null) {
1779 artifactInfo.setListHeatParameters(heatParameters.left().value());
1782 return Either.left(true);
1787 public void validateFileExtension(Wrapper<ResponseFormat> responseWrapper, IDeploymentArtifactTypeConfigGetter deploymentConfigGetter, ArtifactDefinition artifactInfo, NodeTypeEnum parentType, ArtifactTypeEnum artifactType) {
1788 String fileType = artifactType.getType();
1789 List<String> acceptedTypes = null;
1790 ArtifactTypeConfig deploymentAcceptedTypes = deploymentConfigGetter.getDeploymentArtifactConfig();
1791 if (!parentType.equals(NodeTypeEnum.Resource) && !parentType.equals(NodeTypeEnum.Service) && !parentType.equals(NodeTypeEnum.ResourceInstance)) {
1792 log.debug("parent type of artifact can be either resource or service");
1793 responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
1797 if (deploymentAcceptedTypes == null) {
1798 log.debug("parent type of artifact can be either resource or service");
1799 responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType()));
1802 acceptedTypes = deploymentAcceptedTypes.getAcceptedTypes();
1805 * No need to check specific types. In case there are no acceptedTypes in configuration, then any type is accepted.
1807 * if ((!artifactType.equals(ArtifactTypeEnum.OTHER) && !artifactType.equals(ArtifactTypeEnum.HEAT_ARTIFACT )) && (acceptedTypes == null || acceptedTypes.isEmpty()) ) { log.debug( "No accepted types found for type {}, parent type {}",
1808 * fileType, parentType.getName()); String methodName = new Object() { }.getClass().getEnclosingMethod().getName(); String configEntryMissing = (parentType.equals(NodeTypeEnum.Resource)) ? "resourceDeploymentArtifacts:" + fileType :
1809 * "serviceDeploymentArtifacts:" + fileType; BeEcompErrorManager.getInstance().processEcompError(EcompErrorName. BeMissingConfigurationError, methodName, configEntryMissing); BeEcompErrorManager.getInstance().logBeMissingConfigurationError(
1810 * methodName, configEntryMissing); responseWrapper.setInnerElement(componentsUtils.getResponseFormat( ActionStatus.GENERAL_ERROR)); return; }
1813 String artifactName = artifactInfo.getArtifactName();
1814 String fileExtension = GeneralUtility.getFilenameExtension(artifactName);
1815 // Pavel - File extension validation is case-insensitive - Ella,
1817 if (acceptedTypes != null && !acceptedTypes.isEmpty() && !acceptedTypes.contains(fileExtension.toLowerCase())) {
1818 log.debug("File extension \"{}\" is not allowed for {} which is of type:{}", fileExtension, artifactName, fileType);
1819 responseWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.WRONG_ARTIFACT_FILE_EXTENSION, fileType));
1824 private Either<Boolean, ResponseFormat> validateHeatEnvDeploymentArtifact(Component parentComponent, String parentId, String userId, boolean isCreate, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) {
1826 Wrapper<ResponseFormat> errorWrapper = new Wrapper<ResponseFormat>();
1827 Wrapper<ArtifactDefinition> heatMDWrapper = new Wrapper<ArtifactDefinition>();
1828 Wrapper<byte[]> payloadWrapper = new Wrapper<>();
1830 if (errorWrapper.isEmpty()) {
1831 validateValidYaml(errorWrapper, artifactInfo);
1834 if (errorWrapper.isEmpty()) {
1835 // Validate Heat Exist
1836 validateHeatExist(parentComponent.getUniqueId(), parentId, errorWrapper, heatMDWrapper, artifactInfo, parentType, parentComponent.getComponentType());
1839 // if (errorWrapper.isEmpty() && isCreate) {
1840 // // Validate Only Single HeatEnv Artifact
1841 // validateSingleArtifactType(errorWrapper, ArtifactTypeEnum.HEAT_ENV, parentComponent, parentType, parentId);
1844 if (errorWrapper.isEmpty() && !heatMDWrapper.isEmpty()) {
1845 fillArtifactPayloadValidation(errorWrapper, payloadWrapper, heatMDWrapper.getInnerElement());
1848 if (errorWrapper.isEmpty() && !heatMDWrapper.isEmpty()) {
1849 validateEnvVsHeat(errorWrapper, artifactInfo, heatMDWrapper.getInnerElement(), payloadWrapper.getInnerElement());
1853 Either<Boolean, ResponseFormat> eitherResponse;
1854 if (errorWrapper.isEmpty()) {
1855 eitherResponse = Either.left(true);
1857 eitherResponse = Either.right(errorWrapper.getInnerElement());
1859 return eitherResponse;
1862 public void fillArtifactPayloadValidation(Wrapper<ResponseFormat> errorWrapper, Wrapper<byte[]> payloadWrapper, ArtifactDefinition artifactDefinition) {
1863 if (artifactDefinition.getPayloadData() == null || artifactDefinition.getPayloadData().length == 0) {
1864 Either<Boolean, ResponseFormat> fillArtifactPayload = fillArtifactPayload(payloadWrapper, artifactDefinition);
1865 if (fillArtifactPayload.isRight()) {
1866 errorWrapper.setInnerElement(fillArtifactPayload.right().value());
1867 log.debug("Error getting payload for artifact:{}", artifactDefinition.getArtifactName());
1870 payloadWrapper.setInnerElement(artifactDefinition.getPayloadData());
1874 public Either<Boolean, ResponseFormat> fillArtifactPayload(Wrapper<byte[]> payloadWrapper, ArtifactDefinition artifactMD) {
1875 Either<Boolean, ResponseFormat> result = Either.left(true);
1876 Either<ESArtifactData, CassandraOperationStatus> eitherArtifactData = artifactCassandraDao.getArtifact(artifactMD.getEsId());
1877 if (eitherArtifactData.isLeft()) {
1878 byte[] data = eitherArtifactData.left().value().getDataAsArray();
1879 data = Base64.encodeBase64(data);
1880 payloadWrapper.setInnerElement(data);
1882 StorageOperationStatus storageStatus = DaoStatusConverter.convertCassandraStatusToStorageStatus(eitherArtifactData.right().value());
1883 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(storageStatus));
1884 result = Either.right(responseFormat);
1890 @SuppressWarnings("unchecked")
1891 private void validateEnvVsHeat(Wrapper<ResponseFormat> errorWrapper, ArtifactDefinition envArtifact, ArtifactDefinition heatArtifact, byte[] heatPayloadData) {
1892 String envPayload = new String(Base64.decodeBase64(envArtifact.getPayloadData()));
1893 Map<String, Object> heatEnvToscaJson = (Map<String, Object>) new Yaml().load(envPayload);
1894 String heatDecodedPayload = new String(Base64.decodeBase64(heatPayloadData));
1895 Map<String, Object> heatToscaJson = (Map<String, Object>) new Yaml().load(heatDecodedPayload);
1897 Either<Map<String, Object>, ResultStatusEnum> eitherHeatEnvProperties = ImportUtils.findFirstToscaMapElement(heatEnvToscaJson, ToscaTagNamesEnum.PARAMETERS);
1898 Either<Map<String, Object>, ResultStatusEnum> eitherHeatProperties = ImportUtils.findFirstToscaMapElement(heatToscaJson, ToscaTagNamesEnum.PARAMETERS);
1899 if (eitherHeatEnvProperties.isRight()) {
1900 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.CORRUPTED_FORMAT, "Heat Env");
1901 errorWrapper.setInnerElement(responseFormat);
1902 log.debug("Invalid heat env format for file:{}", envArtifact.getArtifactName());
1903 } else if (eitherHeatProperties.isRight()) {
1904 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, envArtifact.getArtifactName(), heatArtifact.getArtifactName());
1905 errorWrapper.setInnerElement(responseFormat);
1906 log.debug("Validation of heat_env for artifact:{} vs heat artifact for artifact :{} failed", envArtifact.getArtifactName(), heatArtifact.getArtifactName());
1908 Set<String> heatPropertiesKeys = eitherHeatProperties.left().value().keySet();
1909 Set<String> heatEnvPropertiesKeys = eitherHeatEnvProperties.left().value().keySet();
1910 heatEnvPropertiesKeys.removeAll(heatPropertiesKeys);
1911 if (heatEnvPropertiesKeys.size() > 0) {
1912 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, envArtifact.getArtifactName(), heatArtifact.getArtifactName());
1913 errorWrapper.setInnerElement(responseFormat);
1918 private void validateValidYaml(Wrapper<ResponseFormat> errorWrapper, ArtifactDefinition artifactInfo) {
1919 YamlToObjectConverter yamlConvertor = new YamlToObjectConverter();
1920 boolean isYamlValid = yamlConvertor.isValidYamlEncoded64(artifactInfo.getPayloadData());
1922 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.INVALID_YAML, artifactInfo.getArtifactType());
1923 errorWrapper.setInnerElement(responseFormat);
1924 log.debug("Yaml is not valid for artifact : {}", artifactInfo.getArtifactName());
1928 @SuppressWarnings("restriction")
1929 public boolean isValidXml(byte[] xmlToParse) {
1930 XMLReader parser = new SAXParser();
1931 boolean isXmlValid = true;
1933 parser.parse(new InputSource(new ByteArrayInputStream(xmlToParse)));
1934 } catch (IOException | SAXException e) {
1935 log.debug("Xml is invalid : {}", e.getMessage(), e);
1941 public boolean isValidJson(byte[] jsonToParse) {
1942 String parsed = new String(jsonToParse);
1944 gson.fromJson(parsed, Object.class);
1945 } catch (Exception e) {
1946 log.debug("Json is invalid : {}", e.getMessage(), e);
1952 public void validateSingleArtifactType(Wrapper<ResponseFormat> errorWrapper, ArtifactTypeEnum allowedArtifactType, Component parentComponent, NodeTypeEnum parentType, String parentRiId) {
1953 boolean typeArtifactFound = false;
1954 // Iterator<ArtifactDefinition> parentDeploymentArtifactsItr =
1955 // (parentType == NodeTypeEnum.Resource) ?
1956 // informationDeployedArtifactsBusinessLogic.getAllDeployableArtifacts((Resource)
1957 // parentComponent).iterator()
1958 // : getDeploymentArtifacts(parentComponent, parentType).iterator();
1960 Iterator<ArtifactDefinition> parentDeploymentArtifactsItr = getDeploymentArtifacts(parentComponent, parentType, parentRiId).iterator();
1962 while (!typeArtifactFound && parentDeploymentArtifactsItr.hasNext()) {
1963 ArtifactTypeEnum foundArtifactType = ArtifactTypeEnum.findType(parentDeploymentArtifactsItr.next().getArtifactType());
1964 typeArtifactFound = (foundArtifactType == allowedArtifactType);
1966 if (typeArtifactFound) {
1967 String parentName = parentComponent.getName();
1968 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.DEPLOYMENT_ARTIFACT_OF_TYPE_ALREADY_EXISTS, parentType.name(), parentName, allowedArtifactType.getType(), allowedArtifactType.getType());
1970 errorWrapper.setInnerElement(responseFormat);
1971 log.debug("Can't upload artifact of type: {}, because another artifact of this type already exist.", allowedArtifactType.getType());
1976 public void validateSingleDeploymentArtifactName(Wrapper<ResponseFormat> errorWrapper, String artifactName, Component parentComponent, NodeTypeEnum parentType) {
1977 boolean artifactNameFound = false;
1978 // Iterator<ArtifactDefinition> parentDeploymentArtifactsItr =
1979 // (parentType == NodeTypeEnum.Resource) ?
1980 // informationDeployedArtifactsBusinessLogic.getAllDeployableArtifacts((Resource)
1981 // parentComponent).iterator()
1982 // : getDeploymentArtifacts(parentComponent, parentType).iterator();
1984 Iterator<ArtifactDefinition> parentDeploymentArtifactsItr = getDeploymentArtifacts(parentComponent, parentType, null).iterator();
1986 while (!artifactNameFound && parentDeploymentArtifactsItr.hasNext()) {
1987 artifactNameFound = (artifactName.equalsIgnoreCase(parentDeploymentArtifactsItr.next().getArtifactName()));
1989 if (artifactNameFound) {
1990 String parentName = parentComponent.getName();
1991 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.DEPLOYMENT_ARTIFACT_NAME_ALREADY_EXISTS, parentType.name(), parentName, artifactName);
1993 errorWrapper.setInnerElement(responseFormat);
1994 log.debug("Can't upload artifact: {}, because another artifact with this name already exist.", artifactName);
1999 private void validateHeatExist(String componentId, String parentRiId, Wrapper<ResponseFormat> errorWrapper, Wrapper<ArtifactDefinition> heatArtifactMDWrapper, ArtifactDefinition heatEnvArtifact, NodeTypeEnum parentType,
2000 ComponentTypeEnum componentType) {
2001 Either<ArtifactDefinition, StorageOperationStatus> res = artifactToscaOperation.getHeatArtifactByHeatEnvId(parentRiId, heatEnvArtifact, parentType, componentId, componentType);
2002 if (res.isRight()) {
2003 ResponseFormat responseFormat;
2004 if (res.right().value() == StorageOperationStatus.NOT_FOUND) {
2005 responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT);
2007 responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT);
2009 errorWrapper.setInnerElement(responseFormat);
2013 ArtifactDefinition heatArtifact = res.left().value();
2014 heatArtifactMDWrapper.setInnerElement(heatArtifact);
2015 // Iterator<ArtifactDefinition> parentArtifactsItr = parentDeploymentArtifacts.iterator();
2016 // while (!heatFound && parentArtifactsItr.hasNext()) {
2017 // ArtifactDefinition currArtifact = parentArtifactsItr.next();
2018 // if (heatArtifact.getUniqueId().equals(currArtifact.getUniqueId())) {
2019 // heatFound = true;
2020 // heatArtifactMDWrapper.setInnerElement(currArtifact);
2021 // log.trace("In validateHeatExist found artifact {}", currArtifact);
2023 // * ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(currArtifact.getArtifactType()); if(artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_VOL || artifactType == ArtifactTypeEnum.HEAT_NET){
2024 // * heatFound = true; } if (heatFound) { heatArtifactMDWrapper.setInnerElement(currArtifact); }
2028 // if (!heatFound) {
2029 // ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISSING_HEAT);
2030 // errorWrapper.setInnerElement(responseFormat);
2031 // log.debug("Can't create heat env artifact because No heat Artifact exist.");
2036 private Either<Boolean, ResponseFormat> validateHeatDeploymentArtifact(Component parentComponent, String userId, boolean isCreate, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, NodeTypeEnum parentType) {
2037 log.trace("Started HEAT pre-payload validation for artifact {}", artifactInfo.getArtifactLabel());
2038 // timeout > 0 for HEAT artifacts
2039 Integer timeout = artifactInfo.getTimeout();
2040 Integer defaultTimeout = (isCreate) ? NodeTemplateOperation.getDefaultHeatTimeout() : currentArtifact.getTimeout();
2041 if (timeout == null) {
2042 artifactInfo.setTimeout(defaultTimeout);
2043 // HEAT artifact but timeout is invalid
2044 } else if (timeout < 1) {
2045 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_TIMEOUT));
2048 // US649856 - Allow several HEAT files on Resource
2050 * if (isCreate) { Wrapper<ResponseFormat> errorWrapper = new Wrapper<>(); validateSingleArtifactType(errorWrapper, ArtifactTypeEnum.findType(artifactInfo.getArtifactType()), parentComponent, parentType); if (!errorWrapper.isEmpty()) { return
2051 * Either.right(errorWrapper.getInnerElement()); } }
2054 log.trace("Ended HEAT validation for artifact {}", artifactInfo.getArtifactLabel());
2055 return Either.left(true);
2058 private Either<Boolean, ResponseFormat> validateResourceType(ResourceTypeEnum resourceType, ArtifactDefinition artifactInfo, List<String> typeList) {
2059 String listToString = (typeList != null) ? typeList.toString() : "";
2060 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.MISMATCH_BETWEEN_ARTIFACT_TYPE_AND_COMPONENT_TYPE, artifactInfo.getArtifactName(), listToString, resourceType.getValue());
2061 Either<Boolean, ResponseFormat> either = Either.right(responseFormat);
2062 String resourceTypeName = resourceType.name();
2063 if (typeList != null && typeList.contains(resourceTypeName)) {
2064 either = Either.left(true);
2069 private Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers(ArtifactDefinition artifactInfo, String artifactType) {
2070 if (artifactInfo.getHeatParameters() != null) {
2071 for (HeatParameterDefinition heatParam : artifactInfo.getListHeatParameters()) {
2072 String parameterType = heatParam.getType();
2073 HeatParameterType heatParameterType = HeatParameterType.isValidType(parameterType);
2074 String artifactTypeStr = artifactType != null ? artifactType : ArtifactTypeEnum.HEAT.getType();
2075 if (heatParameterType == null) {
2076 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_HEAT_PARAMETER_TYPE, artifactTypeStr, heatParam.getType());
2077 return Either.right(responseFormat);
2080 StorageOperationStatus validateAndUpdateProperty = heatParametersOperation.validateAndUpdateProperty(heatParam);
2081 if (validateAndUpdateProperty != StorageOperationStatus.OK) {
2082 log.debug("Heat parameter {} is invalid. Status is {}", heatParam.getName(), validateAndUpdateProperty);
2083 ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE;
2084 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, artifactTypeStr, heatParam.getType(), heatParam.getName());
2085 return Either.right(responseFormat);
2089 return Either.left(artifactInfo);
2092 public List<ArtifactDefinition> getDeploymentArtifacts(Component parentComponent, NodeTypeEnum parentType, String ciId) {
2093 List<ArtifactDefinition> deploymentArtifacts = new ArrayList<>();
2094 if (parentComponent.getDeploymentArtifacts() != null) {
2095 if (NodeTypeEnum.ResourceInstance == parentType && ciId != null) {
2096 Either<ComponentInstance, ResponseFormat> getRI = getRIFromComponent(parentComponent, ciId, null, null, null);
2097 if (getRI.isRight()) {
2098 return deploymentArtifacts;
2100 ComponentInstance ri = getRI.left().value();
2101 if(ri.getDeploymentArtifacts() != null){
2102 deploymentArtifacts.addAll(ri.getDeploymentArtifacts().values());
2104 } else if(parentComponent.getDeploymentArtifacts() !=null){
2105 deploymentArtifacts.addAll(parentComponent.getDeploymentArtifacts().values());
2108 return deploymentArtifacts;
2111 private void checkCreateFields(User user, ArtifactDefinition artifactInfo, ArtifactGroupTypeEnum type) {
2112 // on create if null add informational to current
2113 if (artifactInfo.getArtifactGroupType() == null) {
2114 artifactInfo.setArtifactGroupType(type);
2116 if (artifactInfo.getUniqueId() != null) {
2117 log.error("artifact uniqid cannot be set ignoring");
2119 artifactInfo.setUniqueId(null);
2121 if (artifactInfo.getArtifactRef() != null) {
2122 log.error("artifact ref cannot be set ignoring");
2124 artifactInfo.setArtifactRef(null);
2126 if (artifactInfo.getArtifactRepository() != null) {
2127 log.error("artifact repository cannot be set ignoring");
2129 artifactInfo.setArtifactRepository(null);
2131 if (artifactInfo.getUserIdCreator() != null) {
2132 log.error("creator uuid cannot be set ignoring");
2134 artifactInfo.setArtifactCreator(user.getUserId());
2136 if (artifactInfo.getUserIdLastUpdater() != null) {
2137 log.error("userId of last updater cannot be set ignoring");
2139 artifactInfo.setUserIdLastUpdater(user.getUserId());
2141 if (artifactInfo.getCreatorFullName() != null) {
2142 log.error("creator Full name cannot be set ignoring");
2144 String fullName = user.getFirstName() + " " + user.getLastName();
2145 artifactInfo.setUpdaterFullName(fullName);
2147 if (artifactInfo.getUpdaterFullName() != null) {
2148 log.error("updater Full name cannot be set ignoring");
2150 artifactInfo.setUpdaterFullName(fullName);
2152 if (artifactInfo.getCreationDate() != null) {
2153 log.error("Creation Date cannot be set ignoring");
2155 long time = System.currentTimeMillis();
2156 artifactInfo.setCreationDate(time);
2158 if (artifactInfo.getLastUpdateDate() != null) {
2159 log.error("Last Update Date cannot be set ignoring");
2161 artifactInfo.setLastUpdateDate(time);
2163 if (artifactInfo.getEsId() != null) {
2164 log.error("es id cannot be set ignoring");
2166 artifactInfo.setEsId(null);
2171 * private Either<ArtifactDefinition, ResponseFormat> fetchCurrentArtifact(boolean isCreate, String artifactId) { Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(artifactId); if (isCreate
2172 * == false && artifactById.isRight()) { // in case of update artifact must be BeEcompErrorManager.getInstance().processEcompError(EcompErrorName.BeArtifactMissingError, "Artifact Update / Upload", artifactId);
2173 * BeEcompErrorManager.getInstance().logBeArtifactMissingError("Artifact Update / Upload", artifactId); log.debug("Failed to fetch artifact {}. error: {}", artifactId, artifactById.right().value()); return
2174 * Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(artifactById.right().value()), artifactId)); } if (isCreate && artifactById.isLeft()) { log.debug("Artifact {} already exist", artifactId); return
2175 * Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, artifactById.left().value().getArtifactLabel())); } ArtifactDefinition currentArtifactInfo = null; if (artifactById.isLeft()) { // get previous value
2176 * currentArtifactInfo = artifactById.left().value(); } return Either.left(currentArtifactInfo); }
2179 private String composeArtifactId(String resourceId, String artifactId, ArtifactDefinition artifactInfo, String interfaceName, String operationName) {
2180 String id = artifactId;
2181 if (artifactId == null || artifactId.isEmpty()) {
2182 String uniqueId = null;
2183 if (interfaceName != null && operationName != null) {
2184 uniqueId = UniqueIdBuilder.buildArtifactByInterfaceUniqueId(resourceId, interfaceName, operationName, artifactInfo.getArtifactLabel());
2186 uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId, artifactInfo.getArtifactLabel());
2188 artifactInfo.setUniqueId(uniqueId);
2189 artifactInfo.setEsId(uniqueId);
2192 artifactInfo.setUniqueId(artifactId);
2193 artifactInfo.setEsId(artifactId);
2198 private Either<ActionStatus, ResponseFormat> validateArtifactType(String userId, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) {
2199 if (artifactInfo.getArtifactType() == null || artifactInfo.getArtifactType().isEmpty()) {
2200 BeEcompErrorManager.getInstance().logBeMissingArtifactInformationError("Artifact Update / Upload", "artifactLabel");
2201 log.debug("Missing artifact type for artifact {}", artifactInfo.getArtifactName());
2202 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_TYPE));
2205 boolean artifactTypeExist = false;
2206 Either<List<ArtifactType>, ActionStatus> allArtifactTypes = null;
2207 ArtifactGroupTypeEnum artifactGroupType = artifactInfo.getArtifactGroupType();
2209 if ((artifactGroupType != null) && artifactGroupType.equals(ArtifactGroupTypeEnum.DEPLOYMENT)) {
2210 allArtifactTypes = getDeploymentArtifactTypes(userId, artifactInfo, parentType);
2213 allArtifactTypes = elementOperation.getAllArtifactTypes();
2215 if (allArtifactTypes.isRight()) {
2216 BeEcompErrorManager.getInstance().logBeInvalidConfigurationError("Artifact Upload / Update", "artifactTypes", allArtifactTypes.right().value().name());
2217 log.debug("Failed to retrieve list of suported artifact types. error: {}", allArtifactTypes.right().value());
2218 return Either.right(componentsUtils.getResponseFormatByUserId(allArtifactTypes.right().value(), userId));
2221 for (ArtifactType type : allArtifactTypes.left().value()) {
2222 if (type.getName().equalsIgnoreCase(artifactInfo.getArtifactType())) {
2223 artifactInfo.setArtifactType(artifactInfo.getArtifactType().toUpperCase());
2224 artifactTypeExist = true;
2229 if (!artifactTypeExist) {
2230 BeEcompErrorManager.getInstance().logBeInvalidTypeError("Artifact Upload / Delete / Update - Not supported artifact type", artifactInfo.getArtifactType(), "Artifact " + artifactInfo.getArtifactName());
2231 log.debug("Not supported artifact type = {}", artifactInfo.getArtifactType());
2232 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_TYPE_NOT_SUPPORTED, artifactInfo.getArtifactType()));
2235 return Either.left(ActionStatus.OK);
2238 private Either<List<ArtifactType>, ActionStatus> getDeploymentArtifactTypes(String userId, ArtifactDefinition artifactInfo, NodeTypeEnum parentType) {
2240 Map<String, ArtifactTypeConfig> deploymentArtifacts = null;
2241 List<ArtifactType> artifactTypes = new ArrayList<ArtifactType>();
2243 if (parentType.equals(NodeTypeEnum.Service)) {
2244 deploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getServiceDeploymentArtifacts();
2245 } else if (parentType.equals(NodeTypeEnum.ResourceInstance)) {
2246 deploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceInstanceDeploymentArtifacts();
2248 deploymentArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getResourceDeploymentArtifacts();
2250 if (deploymentArtifacts != null) {
2251 for (String artifactType : deploymentArtifacts.keySet()) {
2252 ArtifactType artifactT = new ArtifactType();
2253 artifactT.setName(artifactType);
2254 artifactTypes.add(artifactT);
2256 return Either.left(artifactTypes);
2258 return Either.right(ActionStatus.GENERAL_ERROR);
2263 private Either<Boolean, ResponseFormat> validateFirstUpdateHasPayload(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2264 if (currentArtifact.getEsId() == null && (artifactInfo.getPayloadData() == null || artifactInfo.getPayloadData().length == 0)) {
2265 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD));
2267 return Either.left(true);
2271 private Either<Boolean, ResponseFormat> validateAndSetArtifactname(ArtifactDefinition artifactInfo) {
2272 if (artifactInfo.getArtifactName() == null || artifactInfo.getArtifactName().isEmpty()) {
2273 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_NAME));
2276 String normalizeFileName = ValidationUtils.normalizeFileName(artifactInfo.getArtifactName());
2277 if (normalizeFileName == null || normalizeFileName.isEmpty()) {
2278 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_NAME));
2280 artifactInfo.setArtifactName(normalizeFileName);
2282 if (!ValidationUtils.validateArtifactNameLength(artifactInfo.getArtifactName())) {
2283 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_NAME, String.valueOf(ValidationUtils.ARTIFACT_NAME_LENGTH)));
2286 return Either.left(true);
2289 private Either<Boolean, ResponseFormat> validateArtifactTypeNotChanged(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2290 if (artifactInfo.getArtifactType() == null || artifactInfo.getArtifactType().isEmpty()) {
2291 log.info("artifact type is missing operation ignored");
2292 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_ARTIFACT_TYPE));
2295 if (!currentArtifact.getArtifactType().equalsIgnoreCase(artifactInfo.getArtifactType())) {
2296 log.info("artifact type cannot be changed operation ignored");
2297 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2299 return Either.left(true);
2302 private Either<ArtifactDefinition, ResponseFormat> validateOrSetArtifactGroupType(ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact) {
2303 if (artifactInfo.getArtifactGroupType() == null) {
2304 artifactInfo.setArtifactGroupType(currentArtifact.getArtifactGroupType());
2307 else if (!currentArtifact.getArtifactGroupType().getType().equalsIgnoreCase(artifactInfo.getArtifactGroupType().getType())) {
2308 log.info("artifact group type cannot be changed. operation failed");
2309 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2311 return Either.left(artifactInfo);
2314 private void checkAndSetUnUpdatableFields(User user, ArtifactDefinition artifactInfo, ArtifactDefinition currentArtifact, ArtifactGroupTypeEnum type) {
2316 // on update if null add informational to current
2317 if (currentArtifact.getArtifactGroupType() == null && type != null) {
2318 currentArtifact.setArtifactGroupType(type);
2321 if (artifactInfo.getUniqueId() != null && !currentArtifact.getUniqueId().equals(artifactInfo.getUniqueId())) {
2322 log.error("artifact uniqid cannot be set ignoring");
2324 artifactInfo.setUniqueId(currentArtifact.getUniqueId());
2326 if (artifactInfo.getArtifactRef() != null && !currentArtifact.getArtifactRef().equals(artifactInfo.getArtifactRef())) {
2327 log.error("artifact ref cannot be set ignoring");
2329 artifactInfo.setArtifactRef(currentArtifact.getArtifactRef());
2331 if (artifactInfo.getArtifactRepository() != null && !currentArtifact.getArtifactRepository().equals(artifactInfo.getArtifactRepository())) {
2332 log.error("artifact repository cannot be set ignoring");
2334 artifactInfo.setArtifactRepository(currentArtifact.getArtifactRepository());
2336 if (artifactInfo.getUserIdCreator() != null && !currentArtifact.getUserIdCreator().equals(artifactInfo.getUserIdCreator())) {
2337 log.error("creator uuid cannot be set ignoring");
2339 artifactInfo.setUserIdCreator(currentArtifact.getUserIdCreator());
2341 if (artifactInfo.getArtifactCreator() != null && !currentArtifact.getArtifactCreator().equals(artifactInfo.getArtifactCreator())) {
2342 log.error("artifact creator cannot be set ignoring");
2344 artifactInfo.setArtifactCreator(currentArtifact.getArtifactCreator());
2346 if (artifactInfo.getUserIdLastUpdater() != null && !currentArtifact.getUserIdLastUpdater().equals(artifactInfo.getUserIdLastUpdater())) {
2347 log.error("userId of last updater cannot be set ignoring");
2349 artifactInfo.setUserIdLastUpdater(user.getUserId());
2351 if (artifactInfo.getCreatorFullName() != null && !currentArtifact.getCreatorFullName().equals(artifactInfo.getCreatorFullName())) {
2352 log.error("creator Full name cannot be set ignoring");
2354 artifactInfo.setCreatorFullName(currentArtifact.getCreatorFullName());
2356 if (artifactInfo.getUpdaterFullName() != null && !currentArtifact.getUpdaterFullName().equals(artifactInfo.getUpdaterFullName())) {
2357 log.error("updater Full name cannot be set ignoring");
2359 String fullName = user.getFirstName() + " " + user.getLastName();
2360 artifactInfo.setUpdaterFullName(fullName);
2362 if (artifactInfo.getCreationDate() != null && !currentArtifact.getCreationDate().equals(artifactInfo.getCreationDate())) {
2363 log.error("Creation Date cannot be set ignoring");
2365 artifactInfo.setCreationDate(currentArtifact.getCreationDate());
2367 if (artifactInfo.getLastUpdateDate() != null && !currentArtifact.getLastUpdateDate().equals(artifactInfo.getLastUpdateDate())) {
2368 log.error("Last Update Date cannot be set ignoring");
2370 long time = System.currentTimeMillis();
2371 artifactInfo.setLastUpdateDate(time);
2373 if (artifactInfo.getEsId() != null && !currentArtifact.getEsId().equals(artifactInfo.getEsId())) {
2374 log.error("es id cannot be set ignoring");
2376 artifactInfo.setEsId(currentArtifact.getUniqueId());
2378 if (artifactInfo.getArtifactDisplayName() != null && !currentArtifact.getArtifactDisplayName().equals(artifactInfo.getArtifactDisplayName())) {
2379 log.error(" Artifact Display Name cannot be set ignoring");
2381 artifactInfo.setArtifactDisplayName(currentArtifact.getArtifactDisplayName());
2383 if (artifactInfo.getServiceApi() != null && !currentArtifact.getServiceApi().equals(artifactInfo.getServiceApi())) {
2384 log.debug("serviceApi cannot be set. ignoring.");
2386 artifactInfo.setServiceApi(currentArtifact.getServiceApi());
2388 if (artifactInfo.getArtifactGroupType() != null && !currentArtifact.getArtifactGroupType().equals(artifactInfo.getArtifactGroupType())) {
2389 log.debug("artifact group cannot be set. ignoring.");
2391 artifactInfo.setArtifactGroupType(currentArtifact.getArtifactGroupType());
2393 artifactInfo.setArtifactVersion(currentArtifact.getArtifactVersion());
2395 if (artifactInfo.getArtifactUUID() != null && !artifactInfo.getArtifactUUID().isEmpty() && !currentArtifact.getArtifactUUID().equals(artifactInfo.getArtifactUUID())) {
2396 log.debug("artifact UUID cannot be set. ignoring.");
2398 artifactInfo.setArtifactUUID(currentArtifact.getArtifactUUID());
2400 if ((artifactInfo.getHeatParameters() != null) && (currentArtifact.getHeatParameters() != null) && !artifactInfo.getHeatParameters().isEmpty() && !currentArtifact.getHeatParameters().isEmpty()) {
2401 checkAndSetUnupdatableHeatParams(artifactInfo.getListHeatParameters(), currentArtifact.getListHeatParameters());
2405 private void checkAndSetUnupdatableHeatParams(List<HeatParameterDefinition> heatParameters, List<HeatParameterDefinition> currentParameters) {
2407 Map<String, HeatParameterDefinition> currentParametersMap = getMapOfParameters(currentParameters);
2408 for (HeatParameterDefinition parameter : heatParameters) {
2409 HeatParameterDefinition currentParam = currentParametersMap.get(parameter.getUniqueId());
2411 if (currentParam != null) {
2413 if (parameter.getName() != null && !parameter.getName().equalsIgnoreCase(currentParam.getName())) {
2414 log.debug("heat parameter name cannot be updated ({}). ignoring.", parameter.getName());
2415 parameter.setName(currentParam.getName());
2417 if (parameter.getDefaultValue() != null && !parameter.getDefaultValue().equalsIgnoreCase(currentParam.getDefaultValue())) {
2418 log.debug("heat parameter defaultValue cannot be updated ({}). ignoring.", parameter.getDefaultValue());
2419 parameter.setDefaultValue(currentParam.getDefaultValue());
2421 if (parameter.getType() != null && !parameter.getType().equalsIgnoreCase(currentParam.getType())) {
2422 log.debug("heat parameter type cannot be updated ({}). ignoring.", parameter.getType());
2423 parameter.setType(currentParam.getType());
2425 if (parameter.getDescription() != null && !parameter.getDescription().equalsIgnoreCase(currentParam.getDescription())) {
2426 log.debug("heat parameter description cannot be updated ({}). ignoring.", parameter.getDescription());
2427 parameter.setDescription(currentParam.getDescription());
2430 // check and set current value
2431 if ((parameter.getCurrentValue() == null) && (currentParam.getDefaultValue() != null)) {
2432 log.debug("heat parameter current value is null. set it to default value {}). ignoring.", parameter.getDefaultValue());
2433 parameter.setCurrentValue(currentParam.getDefaultValue());
2439 private Map<String, HeatParameterDefinition> getMapOfParameters(List<HeatParameterDefinition> currentParameters) {
2441 Map<String, HeatParameterDefinition> currentParamsMap = new HashMap<String, HeatParameterDefinition>();
2442 for (HeatParameterDefinition param : currentParameters) {
2443 currentParamsMap.put(param.getUniqueId(), param);
2445 return currentParamsMap;
2448 private Either<Boolean, ResponseFormat> validateAndServiceApiUrl(ArtifactDefinition artifactInfo) {
2449 if (!ValidationUtils.validateStringNotEmpty(artifactInfo.getApiUrl())) {
2450 log.debug("Artifact url cannot be empty.");
2451 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_URL));
2453 artifactInfo.setApiUrl(artifactInfo.getApiUrl().toLowerCase());
2455 if (!ValidationUtils.validateUrl(artifactInfo.getApiUrl())) {
2456 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_SERVICE_API_URL));
2458 if (!ValidationUtils.validateUrlLength(artifactInfo.getApiUrl())) {
2459 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_URL, String.valueOf(ValidationUtils.API_URL_LENGTH)));
2462 return Either.left(true);
2465 private Either<Boolean, ResponseFormat> validateAndCleanDescription(ArtifactDefinition artifactInfo) {
2466 if (artifactInfo.getDescription() == null || artifactInfo.getDescription().isEmpty()) {
2467 log.debug("Artifact description cannot be empty.");
2468 return Either.right(componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_DESCRIPTION));
2470 String description = artifactInfo.getDescription();
2471 description = ValidationUtils.removeNoneUtf8Chars(description);
2472 description = ValidationUtils.normaliseWhitespace(description);
2473 description = ValidationUtils.stripOctets(description);
2474 description = ValidationUtils.removeHtmlTagsOnly(description);
2475 if (!ValidationUtils.validateIsEnglish(description)) {
2476 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2478 if (!ValidationUtils.validateLength(description, ValidationUtils.ARTIFACT_DESCRIPTION_MAX_LENGTH)) {
2479 return Either.right(componentsUtils.getResponseFormat(ActionStatus.EXCEEDS_LIMIT, ARTIFACT_DESCRIPTION, String.valueOf(ValidationUtils.ARTIFACT_DESCRIPTION_MAX_LENGTH)));
2481 artifactInfo.setDescription(description);
2482 return Either.left(true);
2485 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateArtifactFlow(org.openecomp.sdc.be.model.Component parent, String parentId, String artifactId, ArtifactDefinition artifactInfo, User user, byte[] decodedPayload,
2486 ComponentTypeEnum componentType, AuditingActionEnum auditingAction, String interfaceType, String operationName) {
2487 ESArtifactData artifactData = createEsArtifactData(artifactInfo, decodedPayload);
2488 String prevArtifactId = null;
2489 String currArtifactId = artifactId;
2491 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
2492 Either<ArtifactDefinition, Operation> insideEither = null;
2494 if (artifactData == null) {
2495 BeEcompErrorManager.getInstance().logBeDaoSystemError("Update Artifact");
2496 log.debug("Failed to create artifact object for ES.");
2497 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
2498 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
2499 resultOp = Either.right(responseFormat);
2502 log.trace("Try to update entry on graph");
2503 String artifactUniqueId = null;
2504 ArtifactDefinition artifactDefinition = artifactInfo;
2505 StorageOperationStatus error = null;
2507 boolean isLeft = false;
2508 if (interfaceType != null && operationName != null) {
2509 // lifecycle artifact
2511 * Operation operation = convertToOperation(artifactInfo, operationName);
2513 * Either<Operation, StorageOperationStatus> result = interfaceLifecycleOperation.updateInterfaceOperation(parentId, interfaceType, operationName, operation);
2515 * isLeft = result.isLeft(); if (isLeft) { artifactUniqueId = result.left().value().getUniqueId(); artifactDefinition = result.left().value().getImplementation();
2517 * insideEither = Either.right(result.left().value()); resultOp = Either.left(insideEither); } else { error = result.right().value(); }
2520 log.debug("Enty on graph is updated. Update artifact in ES");
2522 // Changing previous and current artifactId for auditing
2523 prevArtifactId = currArtifactId;
2524 currArtifactId = artifactDefinition.getUniqueId();
2526 NodeTypeEnum convertParentType = convertParentType(componentType);
2528 if (decodedPayload == null) {
2529 if (!artifactDefinition.getMandatory() || artifactDefinition.getEsId() != null) {
2530 Either<ESArtifactData, CassandraOperationStatus> artifactFromCassandra = artifactCassandraDao.getArtifact(artifactDefinition.getEsId());
2531 // Either<ESArtifactData, ResourceUploadStatus>
2532 // artifactfromES = daoUploader.getArtifact(artifactId);
2533 if (artifactFromCassandra.isRight()) {
2534 log.debug("Failed to get artifact data from ES for artifact id {}", artifactId);
2535 error = DaoStatusConverter.convertCassandraStatusToStorageStatus(artifactFromCassandra.right().value());
2536 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
2537 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
2538 resultOp = Either.right(responseFormat);
2541 // clone data to new artifact
2542 artifactData.setData(artifactFromCassandra.left().value().getData());
2543 artifactData.setId(artifactFromCassandra.left().value().getId());
2546 if (artifactDefinition.getEsId() == null) {
2547 artifactDefinition.setEsId(artifactDefinition.getUniqueId());
2548 artifactData.setId(artifactDefinition.getUniqueId());
2552 Either<ArtifactDefinition, StorageOperationStatus> result = artifactToscaOperation.updateArifactOnResource(artifactInfo, parent.getUniqueId(), artifactId, convertParentType, parentId);
2553 isLeft = result.isLeft();
2555 artifactUniqueId = result.left().value().getUniqueId();
2556 artifactDefinition = result.left().value();
2557 String artifactType = artifactInfo.getArtifactType();
2558 if (NodeTypeEnum.Resource == convertParentType
2559 && (ArtifactTypeEnum.HEAT.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.HEAT_VOL.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.HEAT_NET.getType().equalsIgnoreCase(artifactType))) {
2561 * if (!artifactUniqueId.equals(artifactId)) { artifactToscaOperation.updateHeatEnvArtifact(parentId, null, artifactId, artifactUniqueId, convertParentType);
2563 * } else { if (!artifactInfo.getArtifactChecksum().equals(artifactDefinition.getArtifactChecksum())) { Either<ArtifactDefinition, StorageOperationStatus> heatEnvEither =
2564 * artifactToscaOperation.getHeatEnvByGeneratedFromId(artifactUniqueId); if (heatEnvEither.isLeft()) { artifactToscaOperation.updateHeatEnvPlaceholder(heatEnvEither.left().value(), parentId);
2569 error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), parentId, componentType);
2571 insideEither = Either.left(result.left().value());
2572 resultOp = Either.left(insideEither);
2573 if (error != StorageOperationStatus.OK) {
2578 error = result.right().value();
2582 // create new entry in ES
2584 if (artifactData.getData() != null) {
2585 if (!artifactDefinition.getDuplicated() || artifactData.getId() == null)
2586 artifactData.setId(artifactDefinition.getEsId());
2587 res = saveArtifacts(artifactData, parentId, false);
2593 log.debug("Artifact saved into ES - {}", artifactUniqueId);
2594 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
2595 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
2596 // resultOp = Either.left(result.left().value());
2599 BeEcompErrorManager.getInstance().logBeDaoSystemError("Update Artifact");
2600 log.debug("Failed to save the artifact.");
2601 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
2602 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, prevArtifactId, currArtifactId, responseFormat, componentType, null);
2603 resultOp = Either.right(responseFormat);
2611 private Either<byte[], ResponseFormat> handlePayload(ArtifactDefinition artifactInfo, boolean isArtifactMetadataUpdate) {
2612 log.trace("Starting payload handling");
2613 byte[] payload = artifactInfo.getPayloadData();
2614 byte[] decodedPayload = null;
2616 if (payload != null && payload.length != 0) {
2617 // the generated artifacts were already decoded by the handler
2618 decodedPayload = artifactInfo.getGenerated() ? payload : Base64.decodeBase64(payload);
2619 if (decodedPayload.length == 0) {
2620 log.debug("Failed to decode the payload.");
2621 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT);
2622 return Either.right(responseFormat);
2625 String checkSum = GeneralUtility.calculateMD5ByByteArray(decodedPayload);
2626 artifactInfo.setArtifactChecksum(checkSum);
2627 log.trace("Calculated checksum, base64 payload: {}, checksum: {}", payload, checkSum);
2629 // Specific payload validations of different types
2630 Either<Boolean, ResponseFormat> isValidPayload = Either.left(true);
2631 if (isDeploymentArtifact(artifactInfo)) {
2632 log.trace("Starting deployment artifacts payload validation");
2633 String artifactType = artifactInfo.getArtifactType();
2634 if (ArtifactTypeEnum.HEAT.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.HEAT_VOL.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.HEAT_NET.getType().equalsIgnoreCase(artifactType)
2635 || ArtifactTypeEnum.HEAT_ENV.getType().equalsIgnoreCase(artifactType)) {
2636 isValidPayload = validateDeploymentHeatPayload(decodedPayload, artifactType);
2637 if (isValidPayload.isLeft()) {
2638 isValidPayload = extractHeatParameters(artifactInfo);
2640 } else if (ArtifactTypeEnum.YANG_XML.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.VNF_CATALOG.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.VF_LICENSE.getType().equalsIgnoreCase(artifactType)
2641 || ArtifactTypeEnum.VENDOR_LICENSE.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.MODEL_INVENTORY_PROFILE.getType().equalsIgnoreCase(artifactType)
2642 || ArtifactTypeEnum.MODEL_QUERY_SPEC.getType().equalsIgnoreCase(artifactType)) {
2643 isValidPayload = validateYangPayload(decodedPayload, artifactType);
2645 // if(ArtifactTypeEnum.APPC_CONFIG.getType().equalsIgnoreCase(artifactType)
2647 } else if (ArtifactTypeEnum.DCAE_INVENTORY_JSON.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.DCAE_INVENTORY_TOSCA.getType().equalsIgnoreCase(artifactType)
2648 || ArtifactTypeEnum.VES_EVENTS.getType().equalsIgnoreCase(artifactType) || ArtifactTypeEnum.LIFECYCLE_OPERATIONS.getType().equalsIgnoreCase(artifactType)) {
2649 String artifactFileName = artifactInfo.getArtifactName();
2650 String fileExtension = GeneralUtility.getFilenameExtension(artifactFileName).toLowerCase();
2651 switch (fileExtension) {
2653 isValidPayload = validateYangPayload(decodedPayload, artifactType);
2656 isValidPayload = validateJsonPayload(decodedPayload, artifactType);
2660 isValidPayload = validateYmlPayload(decodedPayload, artifactType);
2665 if (isValidPayload.isRight()) {
2666 ResponseFormat responseFormat = isValidPayload.right().value();
2667 return Either.right(responseFormat);
2670 } // null/empty payload is normal if called from metadata update ONLY.
2671 // The validation of whether this is metadata/payload update case is
2672 // currently done separately
2674 if (!isArtifactMetadataUpdate) {
2675 log.debug("Payload is missing.");
2676 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
2677 return Either.right(responseFormat);
2680 log.trace("Ended payload handling");
2681 return Either.left(decodedPayload);
2684 private Either<Boolean, ResponseFormat> validateDeploymentHeatPayload(byte[] decodedPayload, String artifactType) {
2685 // Basic YAML validation
2686 YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter();
2687 if (!yamlToObjectConverter.isValidYaml(decodedPayload)) {
2688 log.debug("Invalid YAML format");
2689 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, artifactType);
2690 return Either.right(responseFormat);
2692 if (!ArtifactTypeEnum.HEAT_ENV.getType().equalsIgnoreCase(artifactType)) {
2693 // HEAT specific YAML validation
2694 DeploymentArtifactHeatConfiguration heatConfiguration = yamlToObjectConverter.convert(decodedPayload, DeploymentArtifactHeatConfiguration.class);
2695 if (heatConfiguration == null || heatConfiguration.getHeat_template_version() == null || heatConfiguration.getResources() == null) {
2696 log.debug("HEAT doesn't contain required \"heat_template_version\" and \"resources\" sections ");
2697 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactType);
2698 return Either.right(responseFormat);
2702 return Either.left(true);
2705 private Either<Boolean, ResponseFormat> validateYmlPayload(byte[] decodedPayload, String artifactType) {
2706 Either<Boolean, ResponseFormat> res = Either.left(true);
2707 YamlToObjectConverter yamlToObjectConverter = new YamlToObjectConverter();
2708 if (!yamlToObjectConverter.isValidYaml(decodedPayload)) {
2709 log.debug("Invalid YAML format");
2710 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_YAML, artifactType);
2711 res = Either.right(responseFormat);
2717 private Either<Boolean, ResponseFormat> validateYangPayload(byte[] payload, String artifactType) {
2718 boolean isXmlValid = isValidXml(payload);
2720 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.INVALID_XML, artifactType);
2721 log.debug("Invalid XML content");
2722 return Either.right(responseFormat);
2724 return Either.left(true);
2727 private Either<Boolean, ResponseFormat> validateJsonPayload(byte[] payload, String type) {
2728 boolean isJsonValid = isValidJson(payload);
2730 ResponseFormat responseFormat = ResponseFormatManager.getInstance().getResponseFormat(ActionStatus.INVALID_JSON, type);
2731 log.debug("Invalid JSON content");
2732 return Either.right(responseFormat);
2734 return Either.left(true);
2737 public void handleTransaction(Either<Operation, ResponseFormat> opState) {
2738 if (opState == null || opState.isRight()) {
2739 titanDao.rollback();
2745 public Either<Operation, ResponseFormat> deleteArtifactByInterface(String resourceId, String interfaceType, String operationName, String userUserId, String artifactId, ImmutablePair<User, Resource> userResourceAuditPair, boolean shouldLock,
2746 boolean inTransaction) {
2747 User user = new User();
2748 user.setUserId(userUserId);
2749 Either<Resource, StorageOperationStatus> parent = toscaOperationFacade.getToscaElement(resourceId, JsonParseFlagEnum.ParseMetadata);
2750 if (parent.isRight()) {
2751 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(parent.right().value()));
2752 return Either.right(responseFormat);
2754 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleDelete = handleDelete(resourceId, artifactId, user, AuditingActionEnum.ARTIFACT_DELETE, ComponentTypeEnum.RESOURCE, parent.left().value(), interfaceType, operationName,
2755 false, inTransaction);
2756 if (handleDelete.isRight()) {
2757 return Either.right(handleDelete.right().value());
2759 Either<ArtifactDefinition, Operation> result = handleDelete.left().value();
2760 return Either.left(result.right().value());
2764 public StorageOperationStatus deleteAllComponentArtifactsIfNotOnGraph(List<ArtifactDefinition> artifacts) {
2766 if (artifacts != null && !artifacts.isEmpty()) {
2767 for (ArtifactDefinition artifactDefinition : artifacts) {
2768 String esId = artifactDefinition.getEsId();
2769 if (esId != null && !esId.isEmpty()) {
2770 StorageOperationStatus deleteIfNotOnGraph = deleteIfNotOnGraph(artifactDefinition.getUniqueId(), esId, false);
2771 if (!deleteIfNotOnGraph.equals(StorageOperationStatus.OK)) {
2772 return deleteIfNotOnGraph;
2777 return StorageOperationStatus.OK;
2780 private Operation convertToOperation(ArtifactDefinition artifactInfo, String operationName) {
2781 Operation op = new Operation();
2782 long time = System.currentTimeMillis();
2783 op.setCreationDate(time);
2785 String artifactName = artifactInfo.getArtifactName();
2786 artifactInfo.setArtifactName(createInterfaceArtifactNameFromOperation(operationName, artifactName));
2788 op.setImplementation(artifactInfo);
2789 op.setLastUpdateDate(time);
2793 private String createInterfaceArtifactNameFromOperation(String operationName, String artifactName) {
2794 String newArtifactName = operationName + "_" + artifactName;
2795 log.trace("converting artifact name {} to {}", artifactName, newArtifactName);
2796 return newArtifactName;
2799 public StorageOperationStatus deleteIfNotOnGraph(String artifactId, String artifactEsId, boolean deleteOnlyPayload) {
2800 log.debug("deleteIfNotOnGraph: delete only payload = {}", deleteOnlyPayload);
2801 // Either<ArtifactData, TitanOperationStatus> checkArtifactNode = titanDao.getNode(UniqueIdBuilder.getKeyByNodeType(NodeTypeEnum.ArtifactRef), artifactId, ArtifactData.class);
2802 // if ((artifactEsId != null && !artifactEsId.isEmpty())) {
2803 // boolean isNotExistOnGraph = checkArtifactNode.isRight() && checkArtifactNode.right().value().equals(TitanOperationStatus.NOT_FOUND);
2805 // if ((isNotExistOnGraph) || (checkArtifactNode.left().value().getArtifactDataDefinition().getMandatory() && deleteOnlyPayload)
2806 // || (ArtifactGroupTypeEnum.SERVICE_API.equals(checkArtifactNode.left().value().getArtifactDataDefinition().getArtifactGroupType()) && deleteOnlyPayload)) {
2807 // // last one. need to delete in ES
2808 // log.debug("Entry on graph is deleted. Delete artifact in ES for id = {}", artifactEsId);
2809 // artifactCassandraDao.deleteArtifact(artifactEsId);
2810 // return StorageOperationStatus.OK;
2812 // // componentsUtils.getResponseFormatByResourceId(ActionStatus.OK,
2816 // log.debug("Entry on graph is deleted. Exist more connections on this artifact. Don't delete artifact in ES for id = {}", artifactEsId);
2817 // return StorageOperationStatus.OK;
2821 return StorageOperationStatus.OK;
2825 public Either<byte[], ResponseFormat> downloadRsrcArtifactByNames(String serviceName, String serviceVersion, String resourceName, String resourceVersion, String artifactName) {
2827 // General validation
2828 if (serviceName == null || serviceVersion == null || resourceName == null || resourceVersion == null || artifactName == null) {
2829 log.debug("One of the function parameteres is null");
2830 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2833 // Normalizing artifact name
2834 artifactName = ValidationUtils.normalizeFileName(artifactName);
2836 // Resource validation
2837 Either<Resource, ResponseFormat> validateResourceNameAndVersion = validateResourceNameAndVersion(resourceName, resourceVersion);
2838 if (validateResourceNameAndVersion.isRight()) {
2839 return Either.right(validateResourceNameAndVersion.right().value());
2842 Resource resource = validateResourceNameAndVersion.left().value();
2843 String resourceId = resource.getUniqueId();
2845 // Service validation
2846 Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
2847 if (validateServiceNameAndVersion.isRight()) {
2848 return Either.right(validateServiceNameAndVersion.right().value());
2851 Map<String, ArtifactDefinition> artifacts = resource.getDeploymentArtifacts();
2852 if (artifacts == null || artifacts.isEmpty()) {
2853 log.debug("Deployment artifacts of resource {} are not found", resourceId);
2854 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
2857 ArtifactDefinition deploymentArtifact = null;
2859 for (ArtifactDefinition artifactDefinition : artifacts.values()) {
2860 if (artifactDefinition.getArtifactName() != null && artifactDefinition.getArtifactName().equals(artifactName)) {
2861 log.debug("Found deployment artifact {}", artifactName);
2862 deploymentArtifact = artifactDefinition;
2867 if (deploymentArtifact == null) {
2868 log.debug("No deployment artifact {} was found for resource {}", artifactName, resourceId);
2869 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
2872 // Downloading the artifact
2873 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(deploymentArtifact);
2874 if (downloadArtifactEither.isRight()) {
2875 log.debug("Download artifact {} failed", artifactName);
2876 return Either.right(downloadArtifactEither.right().value());
2878 log.trace("Download of resource artifact succeeded, uniqueId {}", deploymentArtifact.getUniqueId());
2879 return Either.left(downloadArtifactEither.left().value().getRight());
2883 public Either<byte[], ResponseFormat> downloadRsrcInstArtifactByNames(String serviceName, String serviceVersion, String resourceInstanceName, String artifactName) {
2885 // General validation
2886 if (serviceName == null || serviceVersion == null || resourceInstanceName == null || artifactName == null) {
2887 log.debug("One of the function parameteres is null");
2888 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2891 // Normalizing artifact name
2892 artifactName = ValidationUtils.normalizeFileName(artifactName);
2894 // Resource validation
2896 * Either<Resource, ResponseFormat> validateResourceNameAndVersion = validateResourceNameAndVersion(resourceName, resourceVersion); if (validateResourceNameAndVersion.isRight()) { return
2897 * Either.right(validateResourceNameAndVersion.right().value()); }
2899 * Resource resource = validateResourceNameAndVersion.left().value(); String resourceId = resource.getUniqueId();
2902 // Service validation
2903 Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
2904 if (validateServiceNameAndVersion.isRight()) {
2905 return Either.right(validateServiceNameAndVersion.right().value());
2908 Service service = validateServiceNameAndVersion.left().value();
2910 // ResourceInstance validation
2911 Either<ComponentInstance, ResponseFormat> validateResourceInstance = validateResourceInstance(service, resourceInstanceName);
2912 if (validateResourceInstance.isRight()) {
2913 return Either.right(validateResourceInstance.right().value());
2916 ComponentInstance resourceInstance = validateResourceInstance.left().value();
2918 Map<String, ArtifactDefinition> artifacts = resourceInstance.getDeploymentArtifacts();
2920 final String finalArtifactName = artifactName;
2921 Predicate<ArtifactDefinition> filterArtifactByName = p -> p.getArtifactName().equals(finalArtifactName);
2923 boolean hasDeploymentArtifacts = artifacts != null && artifacts.values().stream().anyMatch(filterArtifactByName);
2924 ArtifactDefinition deployableArtifact;
2926 if (!hasDeploymentArtifacts) {
2927 log.debug("Deployment artifact with name {} not found", artifactName);
2928 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactName));
2931 log.debug("Found deployment artifact {}", artifactName);
2932 deployableArtifact = artifacts.values().stream().filter(filterArtifactByName).findFirst().get();
2933 // Downloading the artifact
2934 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(deployableArtifact);
2936 if (downloadArtifactEither.isRight()) {
2937 log.debug("Download artifact {} failed", artifactName);
2938 return Either.right(downloadArtifactEither.right().value());
2940 log.trace("Download of resource artifact succeeded, uniqueId {}", deployableArtifact.getUniqueId());
2941 return Either.left(downloadArtifactEither.left().value().getRight());
2944 private Either<ComponentInstance, ResponseFormat> validateResourceInstance(Service service, String resourceInstanceName) {
2946 List<ComponentInstance> riList = service.getComponentInstances();
2947 for (ComponentInstance ri : riList) {
2948 if (ri.getNormalizedName().equals(resourceInstanceName))
2949 return Either.left(ri);
2952 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND, resourceInstanceName));
2955 private Either<Service, ResponseFormat> validateServiceNameAndVersion(String serviceName, String serviceVersion) {
2957 Either<List<Service>, StorageOperationStatus> serviceListBySystemName = toscaOperationFacade.getBySystemName(ComponentTypeEnum.SERVICE, serviceName);
2958 if (serviceListBySystemName.isRight()) {
2959 log.debug("Couldn't fetch any service with name {}", serviceName);
2960 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(serviceListBySystemName.right().value(), ComponentTypeEnum.SERVICE), serviceName));
2962 List<Service> serviceList = serviceListBySystemName.left().value();
2963 if (serviceList == null || serviceList.isEmpty()) {
2964 log.debug("Couldn't fetch any service with name {}", serviceName);
2965 return Either.right(componentsUtils.getResponseFormat(ActionStatus.SERVICE_NOT_FOUND, serviceName));
2968 Service foundService = null;
2969 for (Service service : serviceList) {
2970 if (service.getVersion().equals(serviceVersion)) {
2971 log.trace("Found service with version {}", serviceVersion);
2972 foundService = service;
2977 if (foundService == null) {
2978 log.debug("Couldn't find version {} for service {}", serviceVersion, serviceName);
2979 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_VERSION_NOT_FOUND, ComponentTypeEnum.SERVICE.getValue(), serviceVersion));
2981 return Either.left(foundService);
2984 private Either<Resource, ResponseFormat> validateResourceNameAndVersion(String resourceName, String resourceVersion) {
2986 Either<Resource, StorageOperationStatus> resourceListBySystemName = toscaOperationFacade.getComponentByNameAndVersion(ComponentTypeEnum.RESOURCE, resourceName, resourceVersion, JsonParseFlagEnum.ParseMetadata);
2987 if (resourceListBySystemName.isRight()) {
2988 log.debug("Couldn't fetch any resource with name {} and version {}. ", resourceName, resourceVersion);
2989 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(resourceListBySystemName.right().value()), resourceName));
2991 return Either.left(resourceListBySystemName.left().value());
2994 public Either<byte[], ResponseFormat> downloadServiceArtifactByNames(String serviceName, String serviceVersion, String artifactName) {
2996 log.trace("Starting download of service interface artifact, serviceName {}, serviceVersion {}, artifact name {}", serviceName, serviceVersion, artifactName);
2997 if (serviceName == null || serviceVersion == 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 final String normalizedArtifactName = ValidationUtils.normalizeFileName(artifactName);
3005 // Service validation
3006 Either<Service, ResponseFormat> validateServiceNameAndVersion = validateServiceNameAndVersion(serviceName, serviceVersion);
3007 if (validateServiceNameAndVersion.isRight()) {
3008 return Either.right(validateServiceNameAndVersion.right().value());
3011 String serviceId = validateServiceNameAndVersion.left().value().getUniqueId();
3013 // Looking for deployment or tosca artifacts
3014 Service service = validateServiceNameAndVersion.left().value();
3016 if (MapUtils.isEmpty(service.getDeploymentArtifacts()) && MapUtils.isEmpty(service.getToscaArtifacts())) {
3017 log.debug("Neither Deployment nor Tosca artifacts of service {} are found", serviceId);
3018 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, normalizedArtifactName));
3021 Optional<ArtifactDefinition> foundArtifactOptl = null;
3023 if (!MapUtils.isEmpty(service.getDeploymentArtifacts())) {
3024 foundArtifactOptl = service.getDeploymentArtifacts().values().stream()
3025 // filters artifact by name
3026 .filter(a -> a.getArtifactName().equals(normalizedArtifactName)).findAny();
3028 if ((foundArtifactOptl == null || !foundArtifactOptl.isPresent()) && !MapUtils.isEmpty(service.getToscaArtifacts())) {
3029 foundArtifactOptl = service.getToscaArtifacts().values().stream()
3030 // filters TOSCA artifact by name
3031 .filter(a -> a.getArtifactName().equals(normalizedArtifactName)).findAny();
3033 if (!foundArtifactOptl.isPresent()) {
3034 log.debug("The artifact {} was not found for service {}", normalizedArtifactName, serviceId);
3035 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, normalizedArtifactName));
3037 log.debug("Found deployment artifact {}", normalizedArtifactName);
3038 // Downloading the artifact
3039 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = downloadArtifact(foundArtifactOptl.get());
3040 if (downloadArtifactEither.isRight()) {
3041 log.debug("Download artifact {} failed", normalizedArtifactName);
3042 return Either.right(downloadArtifactEither.right().value());
3044 log.trace("Download of service artifact succeeded, uniqueId {}", foundArtifactOptl.get().getUniqueId());
3045 return Either.left(downloadArtifactEither.left().value().getRight());
3048 public Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifact(String parentId, String artifactUniqueId) {
3049 log.trace("Starting download of artifact, uniqueId {}", artifactUniqueId);
3050 Either<ArtifactDefinition, StorageOperationStatus> artifactById = artifactToscaOperation.getArtifactById(parentId, artifactUniqueId);
3051 if (artifactById.isRight()) {
3052 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(artifactById.right().value());
3053 log.debug("Error when getting artifact info by id{}, error: {}", artifactUniqueId, actionStatus.name());
3054 return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, ""));
3056 ArtifactDefinition artifactDefinition = artifactById.left().value();
3057 if (artifactDefinition == null) {
3058 log.debug("Empty artifact definition returned from DB by artifact id {}", artifactUniqueId);
3059 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ""));
3062 return downloadArtifact(artifactDefinition);
3065 private boolean checkArtifactInComponent(org.openecomp.sdc.be.model.Component component, String artifactId) {
3066 boolean found = false;
3067 Map<String, ArtifactDefinition> artifactsS = component.getArtifacts();
3068 if (artifactsS != null) {
3069 for (Map.Entry<String, ArtifactDefinition> entry : artifactsS.entrySet()) {
3070 if (entry.getValue().getUniqueId().equals(artifactId)) {
3076 Map<String, ArtifactDefinition> deploymentArtifactsS = component.getDeploymentArtifacts();
3077 if (!found && deploymentArtifactsS != null) {
3078 for (Map.Entry<String, ArtifactDefinition> entry : deploymentArtifactsS.entrySet()) {
3079 if (entry.getValue().getUniqueId().equals(artifactId)) {
3085 Map<String, ArtifactDefinition> toscaArtifactsS = component.getToscaArtifacts();
3086 if (!found && toscaArtifactsS != null) {
3087 for (Map.Entry<String, ArtifactDefinition> entry : toscaArtifactsS.entrySet()) {
3088 if (entry.getValue().getUniqueId().equals(artifactId)) {
3094 switch (component.getComponentType()) {
3096 Map<String, InterfaceDefinition> interfaces = ((Resource) component).getInterfaces();
3097 if (!found && interfaces != null) {
3098 for (Map.Entry<String, InterfaceDefinition> entry : interfaces.entrySet()) {
3099 Map<String, Operation> operations = entry.getValue().getOperationsMap();
3100 for (Map.Entry<String, Operation> entryOp : operations.entrySet()) {
3101 if (entryOp.getValue().getImplementation() != null && entryOp.getValue().getImplementation().getUniqueId().equals(artifactId)) {
3110 Map<String, ArtifactDefinition> apiArtifacts = ((Service) component).getServiceApiArtifacts();
3111 if (!found && apiArtifacts != null) {
3112 for (Map.Entry<String, ArtifactDefinition> entry : apiArtifacts.entrySet()) {
3113 if (entry.getValue().getUniqueId().equals(artifactId)) {
3127 private boolean checkArtifactInResourceInstance(Component component, String resourceInstanceId, String artifactId) {
3129 boolean found = false;
3130 List<ComponentInstance> resourceInstances = component.getComponentInstances();
3131 ComponentInstance resourceInstance = null;
3132 for (ComponentInstance ri : resourceInstances) {
3133 if (ri.getUniqueId().equals(resourceInstanceId)) {
3134 resourceInstance = ri;
3138 if (resourceInstance != null) {
3139 Map<String, ArtifactDefinition> artifacts = resourceInstance.getDeploymentArtifacts();
3140 if (artifacts != null) {
3141 for (Map.Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) {
3142 if (entry.getValue().getUniqueId().equals(artifactId)) {
3149 artifacts = resourceInstance.getArtifacts();
3150 if (artifacts != null) {
3151 for (Map.Entry<String, ArtifactDefinition> entry : artifacts.entrySet()) {
3152 if (entry.getValue().getUniqueId().equals(artifactId)) {
3163 private Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists(String componentId, String userId, AuditingActionEnum auditingAction, User user, String artifactId, ComponentTypeEnum componentType,
3164 String containerComponentType, boolean inTransaction) {
3166 ComponentTypeEnum componentForAudit = null == containerComponentType ? componentType : ComponentTypeEnum.findByParamName(containerComponentType);
3167 componentForAudit.getNodeType();
3169 Either<? extends org.openecomp.sdc.be.model.Component, StorageOperationStatus> componentResult = toscaOperationFacade.getToscaFullElement(componentId);
3171 if (componentResult.isRight()) {
3172 ActionStatus status = componentForAudit == ComponentTypeEnum.RESOURCE ? ActionStatus.RESOURCE_NOT_FOUND : componentType == ComponentTypeEnum.SERVICE ? ActionStatus.SERVICE_NOT_FOUND : ActionStatus.PRODUCT_NOT_FOUND;
3173 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, componentId);
3174 log.debug("Service not found, serviceId {}", componentId);
3175 handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentForAudit, null);
3176 return Either.right(responseFormat);
3178 return Either.left(componentResult.left().value());
3181 private Either<Boolean, ResponseFormat> validateWorkOnComponent(org.openecomp.sdc.be.model.Component component, String userId, AuditingActionEnum auditingAction, User user, String artifactId, ArtifactOperationInfo operation,
3182 ComponentTypeEnum componentType) {
3183 if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.Download && !operation.ignoreLifecycleState()) {
3184 Either<Boolean, ResponseFormat> canWork = validateCanWorkOnComponent(component, userId);
3185 if (canWork.isRight()) {
3186 String uniqueId = component.getUniqueId();
3187 log.debug("Service status isn't CHECKOUT or user isn't owner, serviceId {}", uniqueId);
3188 handleAuditing(auditingAction, component, uniqueId, user, null, null, artifactId, canWork.right().value(), component.getComponentType(), null);
3189 return Either.right(canWork.right().value());
3192 return Either.left(true);
3195 private Either<Boolean, ResponseFormat> validateUserRole(User user, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType, ArtifactOperationInfo operation) {
3197 if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.Download) {
3198 String role = user.getRole();
3199 if (!role.equals(Role.ADMIN.name()) && !role.equals(Role.DESIGNER.name())) {
3200 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
3201 log.debug("addArtifact - user isn't permitted to perform operation, userId {}, role {}", user.getUserId(), role);
3202 handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, responseFormat, componentType, null);
3203 return Either.right(responseFormat);
3206 return Either.left(true);
3209 private Either<User, ResponseFormat> validateUserExists(String userId, AuditingActionEnum auditingAction, String componentId, String artifactId, ComponentTypeEnum componentType, boolean inTransaction) {
3210 Either<User, ResponseFormat> validateUserExists = validateUserExists(userId, auditingAction.getName(), inTransaction);
3212 if (validateUserExists.isRight()) {
3213 User user = new User();
3214 user.setUserId(userId);
3215 handleAuditing(auditingAction, null, componentId, user, null, null, artifactId, validateUserExists.right().value(), componentType, null);
3216 return Either.right(validateUserExists.right().value());
3218 return Either.left(validateUserExists.left().value());
3221 protected AuditingActionEnum detectAuditingType(ArtifactOperationInfo operation, String origMd5) {
3222 AuditingActionEnum auditingAction = null;
3223 switch (operation.getArtifactOperationEnum()) {
3225 auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_UPLOAD_BY_API : AuditingActionEnum.ARTIFACT_UPLOAD;
3228 auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_UPLOAD_BY_API : origMd5 == null ? AuditingActionEnum.ARTIFACT_METADATA_UPDATE : AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE;
3231 auditingAction = operation.isExternalApi() ? AuditingActionEnum.ARTIFACT_DELETE_BY_API : AuditingActionEnum.ARTIFACT_DELETE;
3234 auditingAction = operation.isExternalApi() ? AuditingActionEnum.DOWNLOAD_ARTIFACT : AuditingActionEnum.ARTIFACT_DOWNLOAD;
3239 return auditingAction;
3242 private Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifact(ArtifactDefinition artifactDefinition) {
3243 String esArtifactId = artifactDefinition.getEsId();
3244 Either<ESArtifactData, CassandraOperationStatus> artifactfromES = artifactCassandraDao.getArtifact(esArtifactId);
3245 if (artifactfromES.isRight()) {
3246 CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value();
3247 StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
3248 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
3249 log.debug("Error when getting artifact from ES, error: {}", actionStatus.name());
3250 return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, artifactDefinition.getArtifactDisplayName()));
3253 ESArtifactData esArtifactData = artifactfromES.left().value();
3254 byte[] data = esArtifactData.getDataAsArray();
3256 log.debug("Artifact data from ES is null");
3257 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactDefinition.getArtifactDisplayName()));
3259 String artifactName = artifactDefinition.getArtifactName();
3260 log.trace("Download of artifact succeeded, uniqueId {}, artifact file name {}", artifactDefinition.getUniqueId(), artifactName);
3261 return Either.left(new ImmutablePair<String, byte[]>(artifactName, data));
3264 public ESArtifactData createEsArtifactData(ArtifactDataDefinition artifactInfo, byte[] artifactPayload) {
3265 ESArtifactData artifactData = new ESArtifactData(artifactInfo.getEsId(), artifactPayload);
3266 return artifactData;
3269 private boolean saveArtifacts(ESArtifactData artifactData, String resourceId, boolean reload) {
3271 CassandraOperationStatus resourceUploadStatus = artifactCassandraDao.saveArtifact(artifactData);
3273 if (resourceUploadStatus.equals(CassandraOperationStatus.OK)) {
3274 log.debug("Artifact {} was saved in component .", artifactData.getId(), resourceId);
3276 log.info("Failed to save artifact {}.", artifactData.getId());
3282 private boolean isArtifactMetadataUpdate(AuditingActionEnum auditingActionEnum) {
3283 return (auditingActionEnum.equals(AuditingActionEnum.ARTIFACT_METADATA_UPDATE));
3286 private boolean isDeploymentArtifact(ArtifactDefinition artifactInfo) {
3287 return (ArtifactGroupTypeEnum.DEPLOYMENT.equals(artifactInfo.getArtifactGroupType()));
3290 public Either<ArtifactDefinition, ResponseFormat> createArtifactPlaceHolderInfo(String resourceId, String logicalName, Map<String, Object> artifactInfoMap, String userUserId, ArtifactGroupTypeEnum groupType, boolean inTransaction) {
3291 Either<User, ActionStatus> user = userAdminManager.getUser(userUserId, inTransaction);
3292 if (user.isRight()) {
3293 ResponseFormat responseFormat;
3294 if (user.right().value().equals(ActionStatus.USER_NOT_FOUND)) {
3295 log.debug("create artifact placeholder - not authorized user, userId {}", userUserId);
3296 responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
3298 log.debug("create artifact placeholder - failed to authorize user, userId {}", userUserId);
3299 responseFormat = componentsUtils.getResponseFormat(user.right().value());
3301 return Either.right(responseFormat);
3304 ArtifactDefinition artifactDefinition = createArtifactPlaceHolderInfo(resourceId, logicalName, artifactInfoMap, user.left().value(), groupType);
3305 return Either.left(artifactDefinition);
3308 public ArtifactDefinition createArtifactPlaceHolderInfo(String resourceId, String logicalName, Map<String, Object> artifactInfoMap, User user, ArtifactGroupTypeEnum groupType) {
3309 ArtifactDefinition artifactInfo = new ArtifactDefinition();
3311 String artifactName = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_DISPLAY_NAME);
3312 String artifactType = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_TYPE);
3313 String artifactDescription = (String) artifactInfoMap.get(ARTIFACT_PLACEHOLDER_DESCRIPTION);
3315 artifactInfo.setArtifactDisplayName(artifactName);
3316 artifactInfo.setArtifactLabel(logicalName.toLowerCase());
3317 artifactInfo.setArtifactType(artifactType);
3318 artifactInfo.setDescription(artifactDescription);
3319 artifactInfo.setArtifactGroupType(groupType);
3320 nodeTemplateOperation.setDefaultArtifactTimeout(groupType, artifactInfo);
3322 setArtifactPlaceholderCommonFields(resourceId, user, artifactInfo);
3324 return artifactInfo;
3327 private void setArtifactPlaceholderCommonFields(String resourceId, User user, ArtifactDefinition artifactInfo) {
3328 String uniqueId = null;
3330 if (resourceId != null) {
3331 uniqueId = UniqueIdBuilder.buildPropertyUniqueId(resourceId.toLowerCase(), artifactInfo.getArtifactLabel().toLowerCase());
3332 artifactInfo.setUniqueId(uniqueId);
3334 artifactInfo.setUserIdCreator(user.getUserId());
3335 String fullName = user.getFullName();
3336 artifactInfo.setUpdaterFullName(fullName);
3338 long time = System.currentTimeMillis();
3340 artifactInfo.setCreatorFullName(fullName);
3341 artifactInfo.setCreationDate(time);
3343 artifactInfo.setLastUpdateDate(time);
3344 artifactInfo.setUserIdLastUpdater(user.getUserId());
3346 artifactInfo.setMandatory(true);
3349 public Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifacts(String parentId, NodeTypeEnum parentType, boolean inTransaction, ArtifactGroupTypeEnum groupType, String instanceId) {
3350 return artifactToscaOperation.getArtifacts(parentId, parentType, groupType, instanceId);
3353 public Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact(ArtifactDefinition artifactHeatEnv, ArtifactDefinition artifact, String componentId, NodeTypeEnum parentType, String instanceId) {
3354 return artifactToscaOperation.addHeatEnvArtifact(artifactHeatEnv, artifact, componentId, parentType, true, instanceId);
3357 private Either<ESArtifactData, ResponseFormat> createEsHeatEnvArtifactDataFromString(ArtifactDefinition artifactDefinition, String payloadStr) {
3359 byte[] payload = payloadStr.getBytes();
3361 ESArtifactData artifactData = createEsArtifactData(artifactDefinition, payload);
3362 return Either.left(artifactData);
3367 * @param artifactDefinition
3370 public Either<ArtifactDefinition, ResponseFormat> generateHeatEnvArtifact(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier,
3371 boolean shouldLock, String instanceId) {
3372 String payload = generateHeatEnvPayload(artifactDefinition);
3373 return generateAndSaveHeatEnvArtifact(artifactDefinition, payload, componentType, component, resourceInstanceName, modifier, shouldLock, instanceId);
3376 private String generateHeatEnvPayload(ArtifactDefinition artifactDefinition) {
3377 List<HeatParameterDefinition> heatParameters = artifactDefinition.getListHeatParameters();
3378 heatParameters.sort(Comparator.comparing(e -> e.getName()));
3379 StringBuilder sb = new StringBuilder();
3380 sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactHeader());
3381 sb.append("parameters:\n");
3382 if (heatParameters != null) {
3383 List<HeatParameterDefinition> empltyHeatValues = new ArrayList<>();
3385 for (HeatParameterDefinition heatParameterDefinition : heatParameters) {
3387 String heatValue = heatParameterDefinition.getCurrentValue();
3388 if (!ValidationUtils.validateStringNotEmpty(heatValue)) {
3389 heatValue = heatParameterDefinition.getDefaultValue();
3390 if (!ValidationUtils.validateStringNotEmpty(heatValue)) {
3391 empltyHeatValues.add(heatParameterDefinition);
3395 HeatParameterType type = HeatParameterType.isValidType(heatParameterDefinition.getType());
3399 sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(Boolean.parseBoolean(heatValue)).append("\n");
3402 sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(new BigDecimal(heatValue).toPlainString()).append("\n");
3404 case COMMA_DELIMITED_LIST:
3406 sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(heatValue).append("\n");
3409 String value = heatValue;
3410 boolean starts = value.startsWith("\"");
3411 boolean ends = value.endsWith("\"");
3412 if (!(starts && ends)) {
3413 starts = value.startsWith("'");
3414 ends = value.endsWith("'");
3415 if (!(starts && ends)) {
3416 value = "\"" + value + "\"";
3419 sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(value);
3426 if (!empltyHeatValues.isEmpty()) {
3427 empltyHeatValues.sort(Comparator.comparing(e -> e.getName()));
3428 empltyHeatValues.forEach(hv -> {
3429 sb.append(" ").append(hv.getName()).append(":");
3430 HeatParameterType type = HeatParameterType.isValidType(hv.getType());
3431 if (type != null && type == HeatParameterType.STRING && (hv.getCurrentValue() != null && "".equals(hv.getCurrentValue()) || hv.getDefaultValue() != null && "".equals(hv.getDefaultValue()))) {
3432 sb.append(" \"\"").append("\n");
3434 sb.append(" ").append("\n");
3439 sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactFooter());
3441 // DE265919 fix Tal G
3442 String result = sb.toString().replaceAll("\\\\n", "\n");
3449 * @param artifactDefinition
3453 public Either<ArtifactDefinition, ResponseFormat> generateAndSaveHeatEnvArtifact(ArtifactDefinition artifactDefinition, String payload, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName,
3454 User modifier, boolean shouldLock, String instanceId) {
3455 return generateArtifactPayload(artifactDefinition, componentType, component, resourceInstanceName, modifier, shouldLock, () -> artifactDefinition.getHeatParamsUpdateDate(),
3456 () -> createEsHeatEnvArtifactDataFromString(artifactDefinition, payload), instanceId);
3460 protected Either<ArtifactDefinition, ResponseFormat> generateArtifactPayload(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier,
3461 boolean shouldLock, Supplier<Long> payloadUpdateDateGen, Supplier<Either<ESArtifactData, ResponseFormat>> esDataCreator, String instanceId) {
3463 if (artifactDefinition.getPayloadUpdateDate() == null || artifactDefinition.getPayloadUpdateDate() == 0 || artifactDefinition.getPayloadUpdateDate() < payloadUpdateDateGen.get()) {
3465 log.trace("Generaing payload for {} artifact {}", artifactDefinition.getArtifactType(), artifactDefinition.getEsId());
3466 Either<ESArtifactData, ResponseFormat> artifactDataRes = esDataCreator.get();
3467 ESArtifactData artifactData = null;
3469 if (artifactDataRes.isLeft()) {
3470 artifactData = artifactDataRes.left().value();
3472 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
3473 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
3474 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
3476 return Either.right(artifactDataRes.right().value());
3478 String newCheckSum = GeneralUtility.calculateMD5ByByteArray(artifactData.getDataAsArray());
3480 String esArtifactId = artifactDefinition.getEsId();
3481 Either<ESArtifactData, CassandraOperationStatus> artifactfromES;
3482 ESArtifactData esArtifactData;
3483 if (esArtifactId != null && !esArtifactId.isEmpty() && artifactDefinition.getPayloadData() == null) {
3484 artifactfromES = artifactCassandraDao.getArtifact(esArtifactId);
3485 if (artifactfromES.isRight()) {
3486 CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value();
3487 StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
3488 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
3489 log.debug("Error when getting artifact from ES, error: {}", actionStatus.name());
3490 return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, artifactDefinition.getArtifactDisplayName()));
3492 esArtifactData = artifactfromES.left().value();
3493 oldCheckSum = GeneralUtility.calculateMD5ByByteArray(esArtifactData.getDataAsArray());
3495 oldCheckSum = artifactDefinition.getArtifactChecksum();
3498 Either<ArtifactDefinition, StorageOperationStatus> updateArifactDefinitionStatus = null;
3501 Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, "Update Artifact - lock resource: ");
3502 if (lockComponent.isRight()) {
3503 handleAuditing(AuditingActionEnum.ARTIFACT_METADATA_UPDATE, component, component.getUniqueId(), modifier, null, null, artifactDefinition.getUniqueId(), lockComponent.right().value(), component.getComponentType(), null);
3504 return Either.right(lockComponent.right().value());
3508 if (oldCheckSum != null && oldCheckSum.equals(newCheckSum)) {
3510 artifactDefinition.setPayloadUpdateDate(payloadUpdateDateGen.get());
3511 updateArifactDefinitionStatus = artifactToscaOperation.updateArifactOnResource(artifactDefinition, component.getUniqueId(), artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId);
3512 log.trace("No real update done in payload for {} artifact, updating payloadUpdateDate {}", artifactDefinition.getArtifactType(), artifactDefinition.getEsId());
3513 if (updateArifactDefinitionStatus.isRight()) {
3514 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus.right().value()), artifactDefinition.getArtifactDisplayName());
3515 log.trace("Failed to update payloadUpdateDate {}", artifactDefinition.getEsId());
3516 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
3517 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
3519 return Either.right(responseFormat);
3523 oldCheckSum = artifactDefinition.getArtifactChecksum();
3524 artifactDefinition.setArtifactChecksum(newCheckSum);
3525 artifactToscaOperation.updateUUID(artifactDefinition, oldCheckSum, artifactDefinition.getArtifactVersion());
3526 artifactDefinition.setEsId(artifactDefinition.getUniqueId());
3527 updateArifactDefinitionStatus = artifactToscaOperation.updateArifactOnResource(artifactDefinition, component.getUniqueId(), artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId);
3529 log.trace("Update Payload ", artifactDefinition.getEsId());
3531 if (updateArifactDefinitionStatus != null && updateArifactDefinitionStatus.isLeft()) {
3533 artifactData.setId(artifactDefinition.getUniqueId());
3534 CassandraOperationStatus saveArtifactStatus = artifactCassandraDao.saveArtifact(artifactData);
3536 if (saveArtifactStatus.equals(CassandraOperationStatus.OK)) {
3538 log.debug("Artifact Saved In ES {}", artifactData.getId());
3539 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
3540 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
3541 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
3544 titanDao.rollback();
3545 log.info("Failed to save artifact {}.", artifactData.getId());
3546 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
3547 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
3548 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
3550 return Either.right(responseFormat);
3553 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus.right().value()), artifactDefinition.getArtifactDisplayName());
3554 log.debug("Failed To update artifact {}", artifactData.getId());
3555 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
3556 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
3558 return Either.right(responseFormat);
3563 graphLockOperation.unlockComponent(component.getUniqueId(), component.getComponentType().getNodeType());
3568 return Either.left(artifactDefinition);
3571 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdateHeatEnv(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType,
3572 org.openecomp.sdc.be.model.Component parent, String originData, String origMd5, ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) {
3573 convertParentType(componentType);
3574 String parentId = parent.getUniqueId();
3575 // Either<ArtifactDefinition, StorageOperationStatus> artifactRes = this.artifactToscaOperation.getArtifactById(componentId, artifactId);
3576 ArtifactDefinition currArtifact = artifactInfo;
3578 if (origMd5 != null) {
3579 Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
3580 if (validateMd5.isRight()) {
3581 ResponseFormat responseFormat = validateMd5.right().value();
3582 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
3583 return Either.right(responseFormat);
3586 if (artifactInfo.getPayloadData() != null && artifactInfo.getPayloadData().length != 0) {
3587 Either<Boolean, ResponseFormat> deploymentValidationResult = validateDeploymentArtifact(parent, componentId, user.getUserId(), false, artifactInfo, currArtifact, NodeTypeEnum.ResourceInstance);
3588 if (deploymentValidationResult.isRight()) {
3589 ResponseFormat responseFormat = deploymentValidationResult.right().value();
3590 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
3591 return Either.right(responseFormat);
3594 Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
3595 if (payloadEither.isRight()) {
3596 ResponseFormat responseFormat = payloadEither.right().value();
3597 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
3598 return Either.right(responseFormat);
3600 } else { // duplicate
3601 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
3602 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
3603 return Either.right(responseFormat);
3609 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Update Artifact - lock ");
3610 if (lockComponent.isRight()) {
3611 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right().value(), componentType, null);
3612 return Either.right(lockComponent.right().value());
3615 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
3617 resultOp = updateHeatEnvParams(componentId, artifactId, artifactInfo, user, auditingAction, parent, componentType, currArtifact, origMd5, inTransaction);
3622 if (resultOp == null || resultOp.isRight()) {
3623 log.debug("all changes rollback");
3624 if (false == inTransaction)
3625 titanDao.rollback();
3627 log.debug("all changes committed");
3628 if (false == inTransaction)
3632 componentType = parent.getComponentType();
3633 NodeTypeEnum nodeType = componentType.getNodeType();
3634 graphLockOperation.unlockComponent(parent.getUniqueId(), nodeType);
3635 // graphLockOperation.unlockComponent(parentId, parentType);
3639 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateHeatEnvParams(String componentId, String artifactId, ArtifactDefinition artifactInfo, User user, AuditingActionEnum auditingAction, Component parent,
3640 ComponentTypeEnum componentType, ArtifactDefinition currArtifact1, String origMd5, boolean inTransaction) {
3642 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
3643 Either<ArtifactDefinition, Operation> insideEither = null;
3645 * currently getArtifactById does not retrieve heatParameters Either<ArtifactDefinition, StorageOperationStatus> artifactRes = artifactOperation.getArtifactById(artifactId, false); ArtifactDefinition currArtifact = artifactRes.left().value();
3647 Either<ComponentInstance, ResponseFormat> getRI = getRIFromComponent(parent, componentId, artifactId, auditingAction, user);
3648 if (getRI.isRight()) {
3649 return Either.right(getRI.right().value());
3651 ComponentInstance ri = getRI.left().value();
3652 Either<ArtifactDefinition, ResponseFormat> getArtifactRes = getArtifactFromRI(parent, ri, componentId, artifactId, auditingAction, user);
3653 if (getArtifactRes.isRight()) {
3654 return Either.right(getArtifactRes.right().value());
3656 ArtifactDefinition currArtifact = getArtifactRes.left().value();
3658 if (currArtifact.getArtifactType().equals(ArtifactTypeEnum.HEAT.getType()) || currArtifact.getArtifactType().equals(ArtifactTypeEnum.HEAT_VOL.getType()) || currArtifact.getArtifactType().equals(ArtifactTypeEnum.HEAT_NET.getType())) {
3659 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
3660 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
3661 return Either.right(responseFormat);
3663 List<HeatParameterDefinition> currentHeatEnvParams = currArtifact.getListHeatParameters();
3664 List<HeatParameterDefinition> updatedHeatEnvParams = artifactInfo.getListHeatParameters();
3665 new ArrayList<HeatParameterDefinition>();
3668 if (origMd5 != null) {
3669 Either<List<HeatParameterDefinition>, ResponseFormat> uploadParamsValidationResult = validateUploadParamsFromEnvFile(auditingAction, parent, user, artifactInfo, artifactId, componentType, ri.getName(), currentHeatEnvParams,
3670 updatedHeatEnvParams, currArtifact.getArtifactName());
3671 if (uploadParamsValidationResult.isRight()) {
3672 ResponseFormat responseFormat = uploadParamsValidationResult.right().value();
3673 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
3674 return Either.right(responseFormat);
3676 artifactInfo.setListHeatParameters(updatedHeatEnvParams);
3679 Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers = validateAndConvertHeatParamers(artifactInfo, ArtifactTypeEnum.HEAT_ENV.getType());
3680 if (validateAndConvertHeatParamers.isRight()) {
3681 ResponseFormat responseFormat = validateAndConvertHeatParamers.right().value();
3682 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
3683 return Either.right(responseFormat);
3686 if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty()) {
3688 // fill reduced heat env parameters List for updating
3689 for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) {
3690 paramName = heatEnvParam.getName();
3691 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
3692 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
3693 String updatedParamValue = heatEnvParam.getCurrentValue();
3694 if (updatedParamValue != null && updatedParamValue.equals("")) { // reset
3695 currHeatParam.setCurrentValue(heatEnvParam.getDefaultValue());
3696 } else if (updatedParamValue != null) {
3697 currHeatParam.setCurrentValue(updatedParamValue);
3702 currArtifact.setHeatParamsUpdateDate(System.currentTimeMillis());
3703 currArtifact.setListHeatParameters(currentHeatEnvParams);
3705 Either<ArtifactDefinition, StorageOperationStatus> updateArifactRes = artifactToscaOperation.updateArifactOnResource(currArtifact, parent.getUniqueId(), currArtifact.getUniqueId(), componentType.getNodeType(), componentId);
3706 if (updateArifactRes.isRight()) {
3707 log.debug("Failed to update artifact on graph - {}", artifactId);
3708 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateArifactRes.right().value()));
3709 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
3710 return Either.right(responseFormat);
3712 StorageOperationStatus error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), ri.getUniqueId(), componentType);
3713 if (error != StorageOperationStatus.OK) {
3714 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
3715 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
3716 return Either.right(responseFormat);
3719 error = generateCustomizationUUIDOnGroupInstance(ri, updateArifactRes.left().value().getUniqueId(), parent.getUniqueId());
3720 if (error != StorageOperationStatus.OK) {
3721 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
3722 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
3723 return Either.right(responseFormat);
3729 insideEither = Either.left(currArtifact);
3730 resultOp = Either.left(insideEither);
3731 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
3732 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currArtifact, null, artifactId, responseFormat, componentType, ri.getName());
3736 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateHeatParams(String componentId, String artifactId, ArtifactDefinition artifactEnvInfo, User user, AuditingActionEnum auditingAction, Component parent,
3737 ComponentTypeEnum componentType, ArtifactDefinition currHeatArtifact, String origMd5) {
3739 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
3740 Either<ArtifactDefinition, Operation> insideEither = null;
3742 * currently getArtifactById does not retrieve heatParameters Either<ArtifactDefinition, StorageOperationStatus> artifactRes = artifactOperation.getArtifactById(artifactId, false); ArtifactDefinition currArtifact = artifactRes.left().value();
3744 String currentHeatId = currHeatArtifact.getUniqueId();
3745 ArtifactDefinition updatedHeatArt = currHeatArtifact;
3747 List<HeatParameterDefinition> updatedHeatEnvParams = artifactEnvInfo.getListHeatParameters();
3748 List<HeatParameterDefinition> currentHeatEnvParams = currHeatArtifact.getListHeatParameters();
3749 List<HeatParameterDefinition> newHeatEnvParams = new ArrayList<HeatParameterDefinition>();
3751 if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty() && currentHeatEnvParams != null && !currentHeatEnvParams.isEmpty()) {
3754 for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) {
3756 paramName = heatEnvParam.getName();
3757 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
3758 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
3760 String updatedParamValue = heatEnvParam.getCurrentValue();
3761 if (updatedParamValue == null)
3762 updatedParamValue = heatEnvParam.getDefaultValue();
3763 HeatParameterType paramType = HeatParameterType.isValidType(currHeatParam.getType());
3764 if (!paramType.getValidator().isValid(updatedParamValue, null)) {
3765 ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE;
3766 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, ArtifactTypeEnum.HEAT_ENV.getType(), paramType.getType(), paramName);
3767 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactEnvInfo, null, artifactId, responseFormat, componentType, "");
3768 return Either.right(responseFormat);
3771 currHeatParam.setCurrentValue(paramType.getConverter().convert(updatedParamValue, null, null));
3772 newHeatEnvParams.add(currHeatParam);
3777 if (!newHeatEnvParams.isEmpty()) {
3778 currHeatArtifact.setListHeatParameters(currentHeatEnvParams);
3779 Either<ArtifactDefinition, StorageOperationStatus> operationStatus = artifactToscaOperation.updateArifactOnResource(currHeatArtifact, parent.getUniqueId(), currHeatArtifact.getUniqueId(), componentType.getNodeType(), componentId);
3781 if (operationStatus.isRight()) {
3782 log.debug("Failed to update artifact on graph - {}", currHeatArtifact.getUniqueId());
3784 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(operationStatus.right().value()));
3785 return Either.right(responseFormat);
3788 updatedHeatArt = operationStatus.left().value();
3789 insideEither = Either.left(updatedHeatArt);
3793 if (!currentHeatId.equals(updatedHeatArt.getUniqueId())) {
3794 artifactEnvInfo.setArtifactChecksum(null);
3795 artifactToscaOperation.updateHeatEnvArtifact(parent.getUniqueId(), artifactEnvInfo, currentHeatId, updatedHeatArt.getUniqueId(), componentType.getNodeType(), componentId);
3797 artifactToscaOperation.updateHeatEnvPlaceholder(artifactEnvInfo, componentId, componentType.getNodeType());
3800 resultOp = Either.left(insideEither);
3801 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
3802 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currHeatArtifact, null, artifactId, responseFormat, componentType, "");
3807 private StorageOperationStatus generateCustomizationUUIDOnGroupInstance(ComponentInstance ri, String artifactId, String componentId) {
3808 StorageOperationStatus error = StorageOperationStatus.OK;
3809 log.debug("Need to re-generate customization UUID for group instance on component instance {}", ri.getUniqueId());
3810 List<GroupInstance> groupsInstances = ri.getGroupInstances();
3811 // List<GroupInstance> associatedGroups = null;
3812 List<String> groupInstancesId = null;
3813 if (groupsInstances != null && !groupsInstances.isEmpty()) {
3814 groupInstancesId = groupsInstances.stream().filter(p -> p.getGroupInstanceArtifacts() != null && p.getGroupInstanceArtifacts().contains(artifactId)).map(p -> p.getUniqueId()).collect(Collectors.toList());
3816 if (groupInstancesId != null && !groupInstancesId.isEmpty()) {
3817 // associatedGroups.stream().forEach(c -> this.groupInstanceOperation.updateCustomizationUUID(c.getUniqueId()));
3818 toscaOperationFacade.generateCustomizationUUIDOnInstanceGroup(componentId, ri.getUniqueId(), groupInstancesId);
3824 public Either<List<HeatParameterDefinition>, ResponseFormat> validateUploadParamsFromEnvFile(AuditingActionEnum auditingAction, Component parent, User user, ArtifactDefinition artifactInfo, String artifactId, ComponentTypeEnum componentType,
3825 String riName, List<HeatParameterDefinition> currentHeatEnvParams, List<HeatParameterDefinition> updatedHeatEnvParams, String currArtifactName) {
3827 if (updatedHeatEnvParams == null || updatedHeatEnvParams.isEmpty()) {
3828 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactInfo.getArtifactName(), currArtifactName);
3829 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, riName);
3830 return Either.right(responseFormat);
3833 for (HeatParameterDefinition uploadedHeatParam : updatedHeatEnvParams) {
3834 String paramName = uploadedHeatParam.getName();
3835 boolean isExistsInHeat = false;
3836 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
3837 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
3839 isExistsInHeat = true;
3840 uploadedHeatParam.setType(currHeatParam.getType());
3841 uploadedHeatParam.setCurrentValue(uploadedHeatParam.getDefaultValue());
3842 uploadedHeatParam.setDefaultValue(currHeatParam.getDefaultValue());
3843 uploadedHeatParam.setUniqueId(currHeatParam.getUniqueId());
3847 if (!isExistsInHeat) {
3848 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, currArtifactName);
3849 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, riName);
3850 return Either.right(responseFormat);
3853 return Either.left(updatedHeatEnvParams);
3856 private Either<ComponentInstance, ResponseFormat> getRIFromComponent(Component component, String riID, String artifactId, AuditingActionEnum auditingAction, User user) {
3857 ResponseFormat responseFormat = null;
3858 List<ComponentInstance> ris = component.getComponentInstances();
3859 for (ComponentInstance ri : ris) {
3860 if (riID.equals(ri.getUniqueId())) {
3861 return Either.left(ri);
3864 responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, riID);
3865 log.debug("Resource Instance not found, resourceInstanceId {}", riID);
3866 handleAuditing(auditingAction, null, riID, user, null, null, artifactId, responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE, null);
3867 return Either.right(responseFormat);
3870 private Either<ArtifactDefinition, ResponseFormat> getArtifactFromRI(Component component, ComponentInstance ri, String riID, String artifactId, AuditingActionEnum auditingAction, User user) {
3871 ResponseFormat responseFormat = null;
3872 Map<String, ArtifactDefinition> rtifactsMap = ri.getDeploymentArtifacts();
3873 for (ArtifactDefinition artifact : rtifactsMap.values()) {
3874 if (artifactId.equals(artifact.getUniqueId())) {
3875 return Either.left(artifact);
3878 responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, riID, component.getUniqueId());
3879 handleAuditing(auditingAction, component, riID, user, null, null, artifactId, responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE, ri.getName());
3880 return Either.right(responseFormat);
3883 public ArtifactDefinition extractArtifactDefinition(Either<ArtifactDefinition, Operation> eitherArtifact) {
3884 ArtifactDefinition ret;
3885 if (eitherArtifact.isLeft()) {
3886 ret = eitherArtifact.left().value();
3888 ret = eitherArtifact.right().value().getImplementationArtifact();
3894 * downloads artifact of component by UUIDs
3896 * @param componentType
3897 * @param componentUuid
3898 * @param artifactUUID
3899 * @param auditAdditionalParam
3902 public Either<byte[], ResponseFormat> downloadComponentArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String artifactUUID, Map<AuditingFieldsKeysEnum, Object> auditAdditionalParam) {
3903 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
3904 Either<byte[], ResponseFormat> result;
3905 byte[] downloadedArtifact = null;
3906 Component component = getLatestComponentByUuid(componentType, componentUuid, errorWrapper);
3907 if (errorWrapper.isEmpty()) {
3908 auditAdditionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, component.getName());
3909 downloadedArtifact = downloadArtifact(component.getDeploymentArtifacts(), artifactUUID, errorWrapper, component.getName());
3911 if (errorWrapper.isEmpty()) {
3912 result = Either.left(downloadedArtifact);
3914 result = Either.right(errorWrapper.getInnerElement());
3920 * downloads an artifact of resource instance of component by UUIDs
3922 * @param componentType
3923 * @param componentUuid
3924 * @param resourceName
3925 * @param artifactUUID
3926 * @param auditAdditionalParam
3929 public Either<byte[], ResponseFormat> downloadResourceInstanceArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID, Map<AuditingFieldsKeysEnum, Object> auditAdditionalParam) {
3930 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
3931 Either<byte[], ResponseFormat> result;
3932 byte[] downloadedArtifact = null;
3933 ComponentInstance resourceInstance = getRelatedComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
3934 if (errorWrapper.isEmpty()) {
3935 downloadedArtifact = downloadArtifact(resourceInstance.getDeploymentArtifacts(), artifactUUID, errorWrapper, resourceInstance.getName());
3937 if (errorWrapper.isEmpty()) {
3938 result = Either.left(downloadedArtifact);
3940 result = Either.right(errorWrapper.getInnerElement());
3946 * uploads an artifact to a component by UUID
3950 * @param componentType
3951 * @param componentUuid
3952 * @param additionalParams
3956 public Either<ArtifactDefinition, ResponseFormat> uploadArtifactToComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, Map<AuditingFieldsKeysEnum, Object> additionalParams,
3957 ArtifactOperationInfo operation) {
3958 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
3959 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
3960 Either<ArtifactDefinition, ResponseFormat> uploadArtifactResult;
3961 ArtifactDefinition uploadArtifact = null;
3962 Component component = null;
3963 String componentId = null;
3964 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
3965 String origMd5 = request.getHeader(Constants.MD5_HEADER);
3966 String userId = request.getHeader(Constants.USER_ID_HEADER);
3968 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata);
3969 if (getComponentRes.isRight()) {
3970 StorageOperationStatus status = getComponentRes.right().value();
3971 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
3972 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), componentUuid));
3974 if (errorWrapper.isEmpty()) {
3975 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
3976 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
3978 if (!getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
3979 component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
3980 if (component != null) {
3981 componentId = component.getUniqueId();
3982 componentName = component.getName();
3985 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentName);
3987 if (errorWrapper.isEmpty()) {
3988 actionResult = handleArtifactRequest(componentId, userId, componentType, operation, null, artifactInfo, origMd5, data, null, null, null, null);
3989 if (actionResult.isRight()) {
3990 log.debug("Failed to upload artifact to component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, actionResult.right().value());
3991 errorWrapper.setInnerElement(actionResult.right().value());
3994 if (errorWrapper.isEmpty()) {
3995 uploadArtifact = actionResult.left().value().left().value();
3996 uploadArtifactResult = Either.left(uploadArtifact);
3998 uploadArtifactResult = Either.right(errorWrapper.getInnerElement());
4000 updateAuditParametersWithArtifactDefinition(additionalParams, uploadArtifact);
4001 return uploadArtifactResult;
4005 * upload an artifact to a resource instance by UUID
4009 * @param componentType
4010 * @param componentUuid
4011 * @param resourceInstanceName
4012 * @param additionalParams
4016 public Either<ArtifactDefinition, ResponseFormat> uploadArtifactToRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName,
4017 Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
4018 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4019 Either<ArtifactDefinition, ResponseFormat> uploadArtifactResult;
4020 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4021 ArtifactDefinition uploadArtifact = null;
4022 Component component = null;
4023 String componentInstanceId;
4025 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4026 String userId = request.getHeader(Constants.USER_ID_HEADER);
4028 ImmutablePair<Component, ComponentInstance> componentRiPair = null;
4029 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata);
4030 if (getComponentRes.isRight()) {
4031 StorageOperationStatus status = getComponentRes.right().value();
4032 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4033 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), resourceInstanceName));
4035 if (errorWrapper.isEmpty() && !getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4036 component = checkoutParentComponent(componentType, getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(), userId, errorWrapper);
4038 if (errorWrapper.isEmpty()) {
4039 if (component == null) {
4040 componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
4042 componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
4045 if (errorWrapper.isEmpty()) {
4046 componentInstanceId = componentRiPair.getRight().getUniqueId();
4047 componentId = componentRiPair.getLeft().getUniqueId();
4048 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
4050 actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, null, artifactInfo, origMd5, data, null, null, componentId, ComponentTypeEnum.findParamByType(componentType));
4051 if (actionResult.isRight()) {
4052 log.debug("Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. ", resourceInstanceName, componentType, componentUuid, actionResult.right().value());
4053 errorWrapper.setInnerElement(actionResult.right().value());
4056 if (errorWrapper.isEmpty()) {
4057 uploadArtifact = actionResult.left().value().left().value();
4058 uploadArtifactResult = Either.left(uploadArtifact);
4060 uploadArtifactResult = Either.right(errorWrapper.getInnerElement());
4062 updateAuditParametersWithArtifactDefinition(additionalParams, uploadArtifact);
4063 return uploadArtifactResult;
4067 * updates an artifact on a component by UUID
4071 * @param componentType
4072 * @param componentUuid
4073 * @param artifactUUID
4074 * @param additionalParams
4079 public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID,
4080 Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
4081 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4082 Either<ArtifactDefinition, ResponseFormat> updateArtifactResult;
4083 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4084 ArtifactDefinition updateArtifact = null;
4085 Component component = null;
4086 String componentId = null;
4087 String artifactId = null;
4088 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
4089 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4090 String userId = request.getHeader(Constants.USER_ID_HEADER);
4092 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata);
4093 if (getComponentRes.isRight()) {
4094 StorageOperationStatus status = getComponentRes.right().value();
4095 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4096 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4098 if (errorWrapper.isEmpty()) {
4099 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
4100 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
4102 if (!getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4103 component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
4104 if (component != null) {
4105 componentId = component.getUniqueId();
4106 componentName = component.getName();
4109 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentName);
4111 if (errorWrapper.isEmpty()) {
4112 artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentId, componentType);
4114 if (errorWrapper.isEmpty()) {
4115 actionResult = handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, origMd5, data, null, null, null, null);
4116 if (actionResult.isRight()) {
4117 log.debug("Failed to upload artifact to component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, actionResult.right().value());
4118 errorWrapper.setInnerElement(actionResult.right().value());
4121 if (errorWrapper.isEmpty()) {
4122 updateArtifact = actionResult.left().value().left().value();
4123 updateArtifactResult = Either.left(updateArtifact);
4126 updateArtifactResult = Either.right(errorWrapper.getInnerElement());
4128 updateAuditParametersWithArtifactDefinition(additionalParams, updateArtifact);
4129 return updateArtifactResult;
4133 * updates an artifact on a resource instance by UUID
4137 * @param componentType
4138 * @param componentUuid
4139 * @param resourceInstanceName
4140 * @param artifactUUID
4141 * @param additionalParams
4146 public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID,
4147 Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
4149 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4150 Either<ArtifactDefinition, ResponseFormat> updateArtifactResult;
4151 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4152 ArtifactDefinition updateArtifact = null;
4153 Component component = null;
4154 String componentInstanceId = null;
4155 String componentId = null;
4156 String artifactId = null;
4157 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4158 String userId = request.getHeader(Constants.USER_ID_HEADER);
4160 ImmutablePair<Component, ComponentInstance> componentRiPair = null;
4161 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata);
4162 if (getComponentRes.isRight()) {
4163 StorageOperationStatus status = getComponentRes.right().value();
4164 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4165 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4167 if (errorWrapper.isEmpty() && !getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4168 component = checkoutParentComponent(componentType, getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(), userId, errorWrapper);
4170 if (errorWrapper.isEmpty()) {
4171 if (component == null) {
4172 componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
4174 componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
4177 if (errorWrapper.isEmpty()) {
4178 componentInstanceId = componentRiPair.getRight().getUniqueId();
4179 componentId = componentRiPair.getLeft().getUniqueId();
4180 artifactId = findArtifactId(componentRiPair.getRight(), artifactUUID, errorWrapper);
4182 if (errorWrapper.isEmpty()) {
4183 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
4185 actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, artifactInfo, origMd5, data, null, null, componentId, ComponentTypeEnum.findParamByType(componentType));
4186 if (actionResult.isRight()) {
4187 log.debug("Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. ", resourceInstanceName, componentType, componentUuid, actionResult.right().value());
4188 errorWrapper.setInnerElement(actionResult.right().value());
4191 if (errorWrapper.isEmpty()) {
4192 updateArtifact = actionResult.left().value().left().value();
4193 updateArtifactResult = Either.left(updateArtifact);
4195 updateArtifactResult = Either.right(errorWrapper.getInnerElement());
4197 updateAuditParametersWithArtifactDefinition(additionalParams, updateArtifact);
4198 return updateArtifactResult;
4202 * deletes an artifact on a component by UUID
4205 * @param componentType
4206 * @param componentUuid
4207 * @param artifactUUID
4208 * @param additionalParams
4213 public Either<ArtifactDefinition, ResponseFormat> deleteArtifactOnComponentByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID, Map<AuditingFieldsKeysEnum, Object> additionalParams,
4214 ArtifactOperationInfo operation) {
4216 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4217 Either<ArtifactDefinition, ResponseFormat> deleteArtifactResult;
4218 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4219 ArtifactDefinition deleteArtifact = null;
4220 Component component = null;
4221 String componentId = null;
4222 String artifactId = null;
4223 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4224 String userId = request.getHeader(Constants.USER_ID_HEADER);
4226 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata);
4227 if (getComponentRes.isRight()) {
4228 StorageOperationStatus status = getComponentRes.right().value();
4229 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4230 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), componentUuid));
4232 if (errorWrapper.isEmpty()) {
4233 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
4234 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
4235 if (!getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4236 component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
4237 if (component != null) {
4238 componentId = component.getUniqueId();
4239 componentName = component.getName();
4242 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentName);
4244 if (errorWrapper.isEmpty()) {
4245 artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentId, componentType);
4247 if (errorWrapper.isEmpty()) {
4248 actionResult = handleArtifactRequest(componentId, userId, componentType, operation, artifactId, null, origMd5, null, null, null, null, null);
4249 if (actionResult.isRight()) {
4250 log.debug("Failed to upload artifact to component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, actionResult.right().value());
4251 errorWrapper.setInnerElement(actionResult.right().value());
4254 if (errorWrapper.isEmpty()) {
4255 deleteArtifact = actionResult.left().value().left().value();
4256 deleteArtifactResult = Either.left(deleteArtifact);
4258 deleteArtifactResult = Either.right(errorWrapper.getInnerElement());
4260 updateAuditParametersWithArtifactDefinition(additionalParams, deleteArtifact);
4261 return deleteArtifactResult;
4265 * deletes an artifact from a resource instance by UUID
4268 * @param componentType
4269 * @param componentUuid
4270 * @param resourceInstanceName
4271 * @param artifactUUID
4272 * @param additionalParams
4277 public Either<ArtifactDefinition, ResponseFormat> deleteArtifactOnRiByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID,
4278 Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
4280 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4281 Either<ArtifactDefinition, ResponseFormat> deleteArtifactResult;
4282 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4283 ArtifactDefinition deleteArtifact = null;
4284 Component component = null;
4285 String componentInstanceId = null;
4286 String componentId = null;
4287 String artifactId = null;
4288 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4289 String userId = request.getHeader(Constants.USER_ID_HEADER);
4290 ImmutablePair<Component, ComponentInstance> componentRiPair = null;
4291 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata);
4292 if (getComponentRes.isRight()) {
4293 StorageOperationStatus status = getComponentRes.right().value();
4294 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4295 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4297 if (errorWrapper.isEmpty() && !getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4298 component = checkoutParentComponent(componentType, getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(), userId, errorWrapper);
4300 if (errorWrapper.isEmpty()) {
4301 if (component == null) {
4302 componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
4304 componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
4307 if (errorWrapper.isEmpty()) {
4308 componentInstanceId = componentRiPair.getRight().getUniqueId();
4309 componentId = componentRiPair.getLeft().getUniqueId();
4310 artifactId = findArtifactId(componentRiPair.getRight(), artifactUUID, errorWrapper);
4312 if (errorWrapper.isEmpty()) {
4314 actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, null, origMd5, null, null, null, componentId, ComponentTypeEnum.findParamByType(componentType));
4316 if (actionResult.isRight()) {
4317 log.debug("Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. ", resourceInstanceName, componentType, componentUuid, actionResult.right().value());
4318 errorWrapper.setInnerElement(actionResult.right().value());
4321 if (errorWrapper.isEmpty()) {
4322 deleteArtifact = actionResult.left().value().left().value();
4323 deleteArtifactResult = Either.left(deleteArtifact);
4325 deleteArtifactResult = Either.right(errorWrapper.getInnerElement());
4327 updateAuditParametersWithArtifactDefinition(additionalParams, deleteArtifact);
4328 return deleteArtifactResult;
4331 private String findArtifactId(ComponentInstance instance, String artifactUUID, Wrapper<ResponseFormat> errorWrapper) {
4332 String artifactId = null;
4333 ArtifactDefinition foundArtifact = null;
4334 if (instance.getDeploymentArtifacts() != null) {
4335 foundArtifact = instance.getDeploymentArtifacts().values().stream().filter(e -> e.getArtifactUUID() != null && e.getArtifactUUID().equals(artifactUUID)).findFirst().orElse(null);
4337 if (foundArtifact == null && instance.getArtifacts() != null) {
4338 foundArtifact = instance.getArtifacts().values().stream().filter(e -> e.getArtifactUUID() != null && e.getArtifactUUID().equals(artifactUUID)).findFirst().orElse(null);
4340 if (foundArtifact == null) {
4341 log.debug("The artifact {} was not found on instance {}. ", artifactUUID, instance.getUniqueId());
4342 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactUUID));
4344 artifactId = foundArtifact.getUniqueId();
4349 public Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder(ArtifactDefinition artifact, String envType, String parentId, NodeTypeEnum parentType, String parentName, User user, Component component,
4350 Map<String, String> existingEnvVersions) {
4351 return createHeatEnvPlaceHolder(artifact, envType, parentId, parentType, parentName, user, component, existingEnvVersions, true);
4355 @SuppressWarnings("unchecked")
4356 public Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder(ArtifactDefinition artifact, String envType, String parentId, NodeTypeEnum parentType, String parentName, User user, Component component,
4357 Map<String, String> existingEnvVersions, boolean overrideId) {
4358 Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getDeploymentResourceInstanceArtifacts();
4359 if (deploymentResourceArtifacts == null) {
4360 log.debug("no deployment artifacts are configured for generated artifacts");
4361 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
4363 Map<String, Object> placeHolderData = (Map<String, Object>) deploymentResourceArtifacts.get(envType);
4364 if (placeHolderData == null) {
4365 log.debug("no env type {} are configured for generated artifacts", envType);
4366 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
4369 String envLabel = (artifact.getArtifactLabel() + HEAT_ENV_SUFFIX).toLowerCase();
4370 String parentIdParam = parentId;
4372 parentIdParam = null;
4374 Either<ArtifactDefinition, ResponseFormat> createArtifactPlaceHolder = createArtifactPlaceHolderInfo(parentIdParam, envLabel, placeHolderData, user.getUserId(), ArtifactGroupTypeEnum.DEPLOYMENT, true);
4375 if (createArtifactPlaceHolder.isRight()) {
4376 return Either.right(createArtifactPlaceHolder.right().value());
4378 ArtifactDefinition artifactHeatEnv = createArtifactPlaceHolder.left().value();
4380 // fix for migration only!!!! create heat env placeholder according to heat id.
4381 artifactHeatEnv.setUniqueId(artifact.getUniqueId() + HEAT_ENV_SUFFIX);
4384 artifactHeatEnv.setGeneratedFromId(artifact.getUniqueId());
4385 artifactHeatEnv.setHeatParamsUpdateDate(System.currentTimeMillis());
4386 artifactHeatEnv.setTimeout(0);
4387 buildHeatEnvFileName(artifact, artifactHeatEnv, placeHolderData);
4388 // rbetzer - keep env artifactVersion - changeComponentInstanceVersion flow
4389 handleEnvArtifactVersion(artifactHeatEnv, existingEnvVersions);
4390 // clone heat parameters in case of heat env only not VF heat env
4391 if (envType.equals(HEAT_ENV_NAME)) {
4392 artifactHeatEnv.setHeatParameters(artifact.getHeatParameters());
4394 ArtifactDefinition artifactDefinition;
4395 // Evg : for resource instance artifact will be added later as block with other env artifacts from BL
4396 if (parentType != NodeTypeEnum.ResourceInstance) {
4397 Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact = addHeatEnvArtifact(artifactHeatEnv, artifact, component.getUniqueId(), parentType, parentId);
4398 if (addHeatEnvArtifact.isRight()) {
4399 log.debug("failed to create heat env artifact on resource instance");
4400 return Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(addHeatEnvArtifact.right().value(), false), "", null));
4402 artifactDefinition = createArtifactPlaceHolder.left().value();
4404 artifactDefinition = artifactHeatEnv;
4405 artifactToscaOperation.generateUUID(artifactDefinition, artifactDefinition.getArtifactVersion());
4408 if (artifact.getHeatParameters() != null) {
4409 List<HeatParameterDefinition> heatEnvParameters = new ArrayList<HeatParameterDefinition>();
4410 for (HeatParameterDefinition parameter : artifact.getListHeatParameters()) {
4411 HeatParameterDefinition heatEnvParameter = new HeatParameterDefinition(parameter);
4412 heatEnvParameter.setDefaultValue(parameter.getCurrentValue());
4413 heatEnvParameters.add(heatEnvParameter);
4415 artifactDefinition.setListHeatParameters(heatEnvParameters);
4419 EnumMap<AuditingFieldsKeysEnum, Object> artifactAuditingFields = createArtifactAuditingFields(artifactDefinition, "", artifactDefinition.getUniqueId());
4420 artifactAuditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, parentName);
4421 ComponentTypeEnum componentType = component.getComponentType();
4422 if (parentType == NodeTypeEnum.ResourceInstance) {
4423 componentType = ComponentTypeEnum.RESOURCE_INSTANCE;
4425 componentsUtils.auditComponent(componentsUtils.getResponseFormat(ActionStatus.OK), user, component, "", "", AuditingActionEnum.ARTIFACT_UPLOAD, componentType, artifactAuditingFields);
4426 return Either.left(artifactDefinition);
4429 private void buildHeatEnvFileName(ArtifactDefinition heatArtifact, ArtifactDefinition heatEnvArtifact, Map<String, Object> placeHolderData) {
4430 String heatExtension = GeneralUtility.getFilenameExtension(heatArtifact.getArtifactName());
4431 String envExtension = (String) placeHolderData.get(ARTIFACT_PLACEHOLDER_FILE_EXTENSION);
4432 String name = heatArtifact.getArtifactName();
4435 name = heatArtifact.getArtifactLabel();
4436 fileName = name + "." + envExtension;
4438 fileName = name.replaceAll("." + heatExtension, "." + envExtension);
4440 heatEnvArtifact.setArtifactName(fileName);
4443 private void handleEnvArtifactVersion(ArtifactDefinition heatEnvArtifact, Map<String, String> existingEnvVersions) {
4444 if (null != existingEnvVersions) {
4445 String prevVersion = existingEnvVersions.get(heatEnvArtifact.getArtifactName());
4446 if (null != prevVersion) {
4447 heatEnvArtifact.setArtifactVersion(prevVersion);
4453 * Handles Artifacts Request For Inner Component
4455 * @param artifactsToHandle
4458 * @param vfcsNewCreatedArtifacts
4461 * @param inTransaction
4464 public Either<List<ArtifactDefinition>, ResponseFormat> handleArtifactsRequestForInnerVfcComponent(List<ArtifactDefinition> artifactsToHandle, Resource component, User user, List<ArtifactDefinition> vfcsNewCreatedArtifacts,
4465 ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) {
4467 Either<List<ArtifactDefinition>, ResponseFormat> handleArtifactsResult = null;
4468 ComponentTypeEnum componentType = component.getComponentType();
4469 List<ArtifactDefinition> uploadedArtifacts = new ArrayList<>();
4470 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4471 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult;
4475 for (ArtifactDefinition artifact : artifactsToHandle) {
4476 originData = buildJsonStringForCsarVfcArtifact(artifact);
4477 origMd5 = GeneralUtility.calculateMD5ByString(originData);
4478 actionResult = handleArtifactRequest(component.getUniqueId(), user.getUserId(), componentType, operation, artifact.getUniqueId(), artifact, origMd5, originData, null, null, null, null, shouldLock, inTransaction);
4479 if (actionResult.isRight()) {
4480 log.debug("Failed to upload artifact to component with type {} and name {}. Status is {}. ", componentType, component.getName(), actionResult.right().value());
4481 errorWrapper.setInnerElement(actionResult.right().value());
4482 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create) {
4483 vfcsNewCreatedArtifacts.addAll(uploadedArtifacts);
4487 uploadedArtifacts.add(actionResult.left().value().left().value());
4489 if (errorWrapper.isEmpty()) {
4490 handleArtifactsResult = Either.left(uploadedArtifacts);
4492 handleArtifactsResult = Either.right(errorWrapper.getInnerElement());
4494 } catch (Exception e) {
4495 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
4496 handleArtifactsResult = Either.right(responseFormat);
4497 log.debug("Exception occured when handleArtifactsRequestForInnerVfcComponent, error is:{}", e.getMessage(), e);
4499 return handleArtifactsResult;
4502 private ComponentInstance getRelatedComponentInstance(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
4503 ComponentInstance componentInstance = null;
4504 String normalizedName = ValidationUtils.normalizeComponentInstanceName(resourceInstanceName);
4505 Component component = getLatestComponentByUuid(componentType, componentUuid, errorWrapper);
4506 if (errorWrapper.isEmpty()) {
4507 componentInstance = component.getComponentInstances().stream().filter(ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName()).equals(normalizedName)).findFirst().orElse(null);
4508 if (componentInstance == null) {
4509 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, "resource instance", component.getComponentType().getValue(), component.getName()));
4510 log.debug("Component instance {} was not found for component {}", resourceInstanceName, component.getName());
4513 return componentInstance;
4516 private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(Component component, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
4518 ImmutablePair<Component, ComponentInstance> relatedComponentComponentInstancePair = null;
4519 String normalizedName = ValidationUtils.normalizeComponentInstanceName(resourceInstanceName);
4520 ComponentInstance componentInstance = component.getComponentInstances().stream().filter(ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName()).equals(normalizedName)).findFirst().orElse(null);
4521 if (componentInstance == null) {
4522 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, "resource instance", component.getComponentType().getValue(), component.getName()));
4523 log.debug("Component instance {} was not found for component {}", resourceInstanceName, component.getName());
4525 relatedComponentComponentInstancePair = new ImmutablePair<>(component, componentInstance);
4527 return relatedComponentComponentInstancePair;
4530 private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
4531 ComponentInstance componentInstance;
4532 ImmutablePair<Component, ComponentInstance> relatedComponentComponentInstancePair = null;
4533 Component component = getLatestComponentByUuid(componentType, componentUuid, errorWrapper);
4534 if (errorWrapper.isEmpty()) {
4535 componentInstance = component.getComponentInstances().stream().filter(ci -> ci.getNormalizedName().equals(resourceInstanceName)).findFirst().orElse(null);
4536 if (componentInstance == null) {
4537 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, "resource instance", component.getComponentType().getValue(), component.getName()));
4538 log.debug("Component instance {} was not found for component {}", resourceInstanceName, component.getName());
4540 relatedComponentComponentInstancePair = new ImmutablePair<>(component, componentInstance);
4543 return relatedComponentComponentInstancePair;
4546 private byte[] downloadArtifact(Map<String, ArtifactDefinition> artifacts, String artifactUUID, Wrapper<ResponseFormat> errorWrapper, String componentName) {
4548 byte[] downloadedArtifact = null;
4549 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = null;
4550 List<ArtifactDefinition> deploymentArtifacts = null;
4551 ArtifactDefinition deploymentArtifact = null;
4552 if (artifacts != null && !artifacts.isEmpty()) {
4553 deploymentArtifacts = artifacts.values().stream().filter(art -> art.getArtifactUUID() != null && art.getArtifactUUID().equals(artifactUUID)).collect(Collectors.toList());
4555 if (deploymentArtifacts == null || deploymentArtifacts.isEmpty()) {
4556 log.debug("Deployment artifact with uuid {} was not found for component {}", artifactUUID, componentName);
4557 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactUUID));
4559 if (errorWrapper.isEmpty()) {
4560 deploymentArtifact = deploymentArtifacts.get(0);
4561 downloadArtifactEither = downloadArtifact(deploymentArtifact);
4562 if (downloadArtifactEither.isRight()) {
4563 log.debug("Failed to download artifact {}. ", deploymentArtifact.getArtifactName());
4564 errorWrapper.setInnerElement(downloadArtifactEither.right().value());
4567 if (errorWrapper.isEmpty()) {
4568 log.trace("Succeeded to download artifact with uniqueId {}", deploymentArtifact.getUniqueId());
4569 downloadedArtifact = downloadArtifactEither.left().value().getRight();
4571 return downloadedArtifact;
4574 private Component getLatestComponentByUuid(ComponentTypeEnum componentType, String componentUuid, Wrapper<ResponseFormat> errorWrapper) {
4575 Component component = null;
4576 Either<Component, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentByUuid(componentUuid);
4577 if (getComponentRes.isRight()) {
4578 StorageOperationStatus status = getComponentRes.right().value();
4579 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4580 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4582 component = getComponentRes.left().value();
4587 private String getLatestParentArtifactDataIdByArtifactUUID(String artifactUUID, Wrapper<ResponseFormat> errorWrapper, String parentId, ComponentTypeEnum componentType) {
4588 String artifactId = null;
4589 ActionStatus actionStatus = ActionStatus.ARTIFACT_NOT_FOUND;
4590 StorageOperationStatus storageStatus;
4591 ArtifactDefinition latestArtifact = null;
4592 List<ArtifactDefinition> artifacts = null;
4593 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifactsRes = artifactToscaOperation.getArtifacts(parentId);
4594 if (getArtifactsRes.isRight()) {
4595 storageStatus = getArtifactsRes.right().value();
4596 log.debug("Couldn't fetch artifacts data for parent component {} with uid {}, error: {}", componentType.name(), parentId, storageStatus);
4597 if (!storageStatus.equals(StorageOperationStatus.NOT_FOUND)) {
4598 actionStatus = componentsUtils.convertFromStorageResponse(storageStatus);
4600 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
4602 if (errorWrapper.isEmpty()) {
4603 artifacts = getArtifactsRes.left().value().values().stream().filter(a -> a.getArtifactUUID() != null && a.getArtifactUUID().equals(artifactUUID)).collect(Collectors.toList());
4604 if (artifacts == null || artifacts.isEmpty()) {
4605 log.debug("Couldn't fetch artifact with UUID {} data for parent component {} with uid {}, error: {}", artifactUUID, componentType.name(), parentId, actionStatus);
4606 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
4609 if (errorWrapper.isEmpty()) {
4610 latestArtifact = artifacts.stream().max((a1, a2) -> {
4611 int compareRes = Double.compare(Double.parseDouble(a1.getArtifactVersion()), Double.parseDouble(a2.getArtifactVersion()));
4612 if (compareRes == 0) {
4613 compareRes = Long.compare(a1.getLastUpdateDate() == null ? 0 : a1.getLastUpdateDate(), a2.getLastUpdateDate() == null ? 0 : a2.getLastUpdateDate());
4617 if (latestArtifact == null) {
4618 log.debug("Couldn't fetch latest artifact with UUID {} data for parent component {} with uid {}, error: {}", artifactUUID, componentType.name(), parentId, actionStatus);
4619 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
4622 if (errorWrapper.isEmpty()) {
4623 artifactId = latestArtifact.getUniqueId();
4628 private Component checkoutParentComponent(ComponentTypeEnum componentType, String parentId, String userId, Wrapper<ResponseFormat> errorWrapper) {
4630 Component component = null;
4631 Either<User, ActionStatus> getUserRes = userBusinessLogic.getUser(userId, false);
4632 if (getUserRes.isRight()) {
4633 log.debug("Could not fetch User of component {} with uid {} to checked out. Status is {}. ", componentType.getNodeType(), parentId, getUserRes.right().value());
4634 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(getUserRes.right().value()));
4636 if (errorWrapper.isEmpty()) {
4637 User modifier = getUserRes.left().value();
4638 LifecycleChangeInfoWithAction changeInfo = new LifecycleChangeInfoWithAction("External API checkout", LifecycleChanceActionEnum.UPDATE_FROM_EXTERNAL_API);
4639 Either<? extends Component, ResponseFormat> checkoutRes = lifecycleBusinessLogic.changeComponentState(componentType, parentId, modifier, LifeCycleTransitionEnum.CHECKOUT, changeInfo, false, true);
4640 if (checkoutRes.isRight()) {
4641 log.debug("Could not change state of component {} with uid {} to checked out. Status is {}. ", componentType.getNodeType(), parentId, checkoutRes.right().value().getStatus());
4642 errorWrapper.setInnerElement(checkoutRes.right().value());
4644 component = checkoutRes.left().value();
4650 private void updateAuditParametersWithArtifactDefinition(Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactDefinition artifact) {
4651 if (artifact == null) {
4652 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, "");
4653 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, "");
4654 if (!additionalParams.containsKey(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID)) {
4655 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, "");
4658 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifact.getArtifactUUID());
4659 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, buildAuditingArtifactData(artifact));
4660 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, artifact.getUpdaterFullName());
4664 private String buildJsonStringForCsarVfcArtifact(ArtifactDefinition artifact) {
4665 Map<String, Object> json = new HashMap<>();
4666 String artifactName = artifact.getArtifactName();
4667 json.put(Constants.ARTIFACT_NAME, artifactName);
4668 json.put(Constants.ARTIFACT_LABEL, artifact.getArtifactLabel());
4669 json.put(Constants.ARTIFACT_TYPE, artifact.getArtifactType());
4670 json.put(Constants.ARTIFACT_GROUP_TYPE, ArtifactGroupTypeEnum.DEPLOYMENT.getType());
4671 json.put(Constants.ARTIFACT_DESCRIPTION, artifact.getDescription());
4672 json.put(Constants.ARTIFACT_PAYLOAD_DATA, artifact.getPayloadData());
4673 json.put(Constants.ARTIFACT_DISPLAY_NAME, artifact.getArtifactDisplayName());
4674 return gson.toJson(json);