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.ArtifactsResolver;
47 import org.openecomp.sdc.be.components.impl.ImportUtils.ResultStatusEnum;
48 import org.openecomp.sdc.be.components.impl.ImportUtils.ToscaTagNamesEnum;
49 import org.openecomp.sdc.be.components.lifecycle.LifecycleBusinessLogic;
50 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction;
51 import org.openecomp.sdc.be.components.lifecycle.LifecycleChangeInfoWithAction.LifecycleChanceActionEnum;
52 import org.openecomp.sdc.be.config.BeEcompErrorManager;
53 import org.openecomp.sdc.be.config.Configuration.ArtifactTypeConfig;
54 import org.openecomp.sdc.be.config.ConfigurationManager;
55 import org.openecomp.sdc.be.config.validation.DeploymentArtifactHeatConfiguration;
56 import org.openecomp.sdc.be.dao.api.ActionStatus;
57 import org.openecomp.sdc.be.dao.cassandra.ArtifactCassandraDao;
58 import org.openecomp.sdc.be.dao.cassandra.CassandraOperationStatus;
59 import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
60 import org.openecomp.sdc.be.datatypes.elements.ArtifactDataDefinition;
61 import org.openecomp.sdc.be.datatypes.elements.GroupDataDefinition;
62 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
63 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
64 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
65 import org.openecomp.sdc.be.model.ArtifactDefinition;
66 import org.openecomp.sdc.be.model.ArtifactType;
67 import org.openecomp.sdc.be.model.Component;
68 import org.openecomp.sdc.be.model.ComponentInstance;
69 import org.openecomp.sdc.be.model.ComponentParametersView;
70 import org.openecomp.sdc.be.model.GroupDefinition;
71 import org.openecomp.sdc.be.model.GroupInstance;
72 import org.openecomp.sdc.be.model.HeatParameterDefinition;
73 import org.openecomp.sdc.be.model.InterfaceDefinition;
74 import org.openecomp.sdc.be.model.LifeCycleTransitionEnum;
75 import org.openecomp.sdc.be.model.LifecycleStateEnum;
76 import org.openecomp.sdc.be.model.Operation;
77 import org.openecomp.sdc.be.model.Resource;
78 import org.openecomp.sdc.be.model.Service;
79 import org.openecomp.sdc.be.model.User;
80 import org.openecomp.sdc.be.model.heat.HeatParameterType;
81 import org.openecomp.sdc.be.model.jsontitan.operations.NodeTemplateOperation;
82 import org.openecomp.sdc.be.model.operations.api.IElementOperation;
83 import org.openecomp.sdc.be.model.operations.api.IHeatParametersOperation;
84 import org.openecomp.sdc.be.model.operations.api.IInterfaceLifecycleOperation;
85 import org.openecomp.sdc.be.model.operations.api.IUserAdminOperation;
86 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
87 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
88 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
89 import org.openecomp.sdc.be.resources.data.ComponentMetadataData;
90 import org.openecomp.sdc.be.resources.data.ESArtifactData;
91 import org.openecomp.sdc.be.resources.data.auditing.AuditingActionEnum;
92 import org.openecomp.sdc.be.resources.data.auditing.AuditingTypesConstants;
93 import org.openecomp.sdc.be.servlets.RepresentationUtils;
94 import org.openecomp.sdc.be.tosca.CsarUtils;
95 import org.openecomp.sdc.be.tosca.ToscaError;
96 import org.openecomp.sdc.be.tosca.ToscaExportHandler;
97 import org.openecomp.sdc.be.tosca.ToscaRepresentation;
98 import org.openecomp.sdc.be.user.IUserBusinessLogic;
99 import org.openecomp.sdc.be.user.Role;
100 import org.openecomp.sdc.be.user.UserBusinessLogic;
101 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
102 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
103 import org.openecomp.sdc.common.api.Constants;
104 import org.openecomp.sdc.common.datastructure.AuditingFieldsKeysEnum;
105 import org.openecomp.sdc.common.datastructure.Wrapper;
106 import org.openecomp.sdc.common.util.GeneralUtility;
107 import org.openecomp.sdc.common.util.ValidationUtils;
108 import org.openecomp.sdc.common.util.YamlToObjectConverter;
109 import org.openecomp.sdc.exception.ResponseFormat;
110 import org.slf4j.Logger;
111 import org.slf4j.LoggerFactory;
112 import org.springframework.beans.factory.annotation.Autowired;
113 import org.xml.sax.InputSource;
114 import org.xml.sax.SAXException;
115 import org.xml.sax.XMLReader;
116 import org.yaml.snakeyaml.Yaml;
118 import com.google.gson.Gson;
119 import com.google.gson.GsonBuilder;
120 import com.sun.org.apache.xerces.internal.parsers.SAXParser;
122 import fj.data.Either;
124 @org.springframework.stereotype.Component("artifactBusinessLogic")
125 public class ArtifactsBusinessLogic extends BaseBusinessLogic {
126 private static final String ARTIFACT_TYPE_OTHER = "OTHER";
127 private static final String ARTIFACT_DESCRIPTION = "artifact description";
128 private static final String ARTIFACT_LABEL = "artifact label";
129 private static final String ARTIFACT_URL = "artifact url";
130 private static final String ARTIFACT_NAME = "artifact name";
131 private static final String ARTIFACT_PAYLOAD = "artifact payload";
133 private static final String ARTIFACT_PLACEHOLDER_TYPE = "type";
134 private static final String ARTIFACT_PLACEHOLDER_DISPLAY_NAME = "displayName";
135 private static final Object ARTIFACT_PLACEHOLDER_DESCRIPTION = "description";
137 public static final String HEAT_ENV_NAME = "heatEnv";
138 public static final String HEAT_VF_ENV_NAME = "VfHeatEnv";
139 public static final String HEAT_ENV_SUFFIX = "env";
140 private static final String ARTIFACT_PLACEHOLDER_FILE_EXTENSION = "fileExtension";
142 // private static Integer defaultHeatTimeout;
143 // private static final Integer NON_HEAT_TIMEOUT = 0;
144 private static Logger log = LoggerFactory.getLogger(ArtifactsBusinessLogic.class.getName());
145 private Gson gson = new GsonBuilder().setPrettyPrinting().create();
147 @javax.annotation.Resource
148 private IInterfaceLifecycleOperation interfaceLifecycleOperation;
149 @javax.annotation.Resource
150 private IUserAdminOperation userOperaton;
152 @javax.annotation.Resource
153 private IElementOperation elementOperation;
155 @javax.annotation.Resource
156 private ResourceBusinessLogic resourceBusinessLogic;
158 @javax.annotation.Resource
159 private ServiceBusinessLogic serviceBusinessLogic;
161 @javax.annotation.Resource
162 private UserBusinessLogic userAdminManager;
164 @javax.annotation.Resource
165 private IHeatParametersOperation heatParametersOperation;
168 private ArtifactCassandraDao artifactCassandraDao;
171 private ToscaExportHandler toscaExportUtils;
174 private CsarUtils csarUtils;
177 private LifecycleBusinessLogic lifecycleBusinessLogic;
180 private IUserBusinessLogic userBusinessLogic;
182 NodeTemplateOperation nodeTemplateOperation;
185 private ArtifactsResolver artifactsResolver;
187 public ArtifactsBusinessLogic() {
188 // defaultHeatTimeout = ConfigurationManager.getConfigurationManager().getConfiguration().getDefaultHeatArtifactTimeoutMinutes();
189 // if ((defaultHeatTimeout == null) || (defaultHeatTimeout < 1)) {
190 // defaultHeatTimeout = 60;
194 public static enum ArtifactOperationEnum {
195 Create(), Update(), Delete(), Download();
198 public class ArtifactOperationInfo {
200 private ArtifactOperationEnum artifactOperationEnum;
201 private boolean isExternalApi;
202 private boolean ignoreLifecycleState;
204 public ArtifactOperationInfo(boolean isExternalApi, boolean ignoreLifecycleState, ArtifactOperationEnum artifactOperationEnum) {
205 this.artifactOperationEnum = artifactOperationEnum;
206 this.isExternalApi = isExternalApi;
207 this.ignoreLifecycleState = ignoreLifecycleState;
210 public boolean isExternalApi() {
211 return isExternalApi;
214 public boolean ignoreLifecycleState() {
215 return ignoreLifecycleState;
218 public ArtifactOperationEnum getArtifactOperationEnum() {
219 return artifactOperationEnum;
225 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleArtifactRequest(String componentId, String userId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo,
226 String origMd5, String originData, String interfaceName, String operationName, String parentId, String containerComponentType) {
227 return handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, origMd5, originData, interfaceName, operationName, parentId, containerComponentType, true, false);
230 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleArtifactRequest(String componentId, String userId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo,
231 String origMd5, String originData, String interfaceName, String operationName, String parentId, String containerComponentType, boolean shouldLock, boolean inTransaction) {
233 // step 1 - detect auditing type
234 AuditingActionEnum auditingAction = detectAuditingType(operation, origMd5);
235 // step 2 - check header
236 if (userId == null) {
237 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
238 log.debug("handleArtifactRequest - no HTTP_CSP_HEADER , component id {}", componentId);
239 handleAuditing(auditingAction, null, componentId, null, null, null, artifactId, responseFormat, componentType, null);
240 return Either.right(responseFormat);
242 // step 3 - check user existence
243 Either<User, ResponseFormat> userResult = validateUserExists(userId, auditingAction, componentId, artifactId, componentType, inTransaction);
244 if (userResult.isRight()) {
245 return Either.right(userResult.right().value());
248 // step 4 - check user's role
249 User user = userResult.left().value();
250 Either<Boolean, ResponseFormat> validateUserRole = validateUserRole(user, auditingAction, componentId, artifactId, componentType, operation);
251 if (validateUserRole.isRight()) {
252 return Either.right(validateUserRole.right().value());
256 // 5. check service/resource existence
257 // 6. check service/resource check out
258 // 7. user is owner of checkout state
259 org.openecomp.sdc.be.model.Component component = null;
260 // ComponentInstance resourceInstance = null;
261 String realComponentId = componentType == ComponentTypeEnum.RESOURCE_INSTANCE ? parentId : componentId;
262 Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExists(realComponentId, userId, auditingAction, user, artifactId, componentType, containerComponentType, inTransaction);
263 if (validateComponent.isRight()) {
264 return Either.right(validateComponent.right().value());
266 component = validateComponent.left().value();
267 Either<Boolean, ResponseFormat> validateWorkOnResource = validateWorkOnComponent(component, userId, auditingAction, user, artifactId, operation, componentType);
268 if (validateWorkOnResource.isRight()) {
269 return Either.right(validateWorkOnResource.right().value());
272 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result = validateAndHandleArtifact(componentId, componentType, operation, artifactId, artifactInfo, origMd5, originData, interfaceName, operationName, parentId, user, component,
273 shouldLock, inTransaction);
279 * This Method validates only the Artifact and does not validate user / role / component ect...<br>
280 * For regular usage use <br>
281 * {@link #handleArtifactRequest(String, String, ComponentTypeEnum, ArtifactOperationInfo, String, ArtifactDefinition, String, String, String, String, String, String)}
285 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> validateAndHandleArtifact(String componentUniqueId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactUniqueId,
286 ArtifactDefinition artifactDefinition, String origMd5, String originData, String interfaceName, String operationName, String parentId, User user, Component component, boolean shouldLock, boolean inTransaction) {
287 Component parent = component;
288 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
290 AuditingActionEnum auditingAction = detectAuditingType(operation, origMd5);
291 artifactDefinition = validateArtifact(componentUniqueId, componentType, operation, artifactUniqueId, artifactDefinition, parentId, auditingAction, user, component, parent, shouldLock, errorWrapper, inTransaction);
293 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result;
294 if (errorWrapper.isEmpty()) {
296 result = doAction(componentUniqueId, componentType, operation, artifactUniqueId, artifactDefinition, origMd5, originData, interfaceName, operationName, auditingAction, user, parent, shouldLock, inTransaction);
298 result = Either.right(errorWrapper.getInnerElement());
303 private ArtifactDefinition validateArtifact(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, String parentId, AuditingActionEnum auditingAction, User user,
304 org.openecomp.sdc.be.model.Component component, org.openecomp.sdc.be.model.Component parent, boolean shouldLock, Wrapper<ResponseFormat> errorWrapper, boolean inTransaction) {
305 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Update || operation.getArtifactOperationEnum() == ArtifactOperationEnum.Delete || operation.getArtifactOperationEnum() == ArtifactOperationEnum.Download) {
306 Either<ArtifactDefinition, ResponseFormat> validateArtifact = validateArtifact(componentId, componentType, artifactId, component, auditingAction, parentId, inTransaction);
307 if (validateArtifact.isRight()) {
308 ResponseFormat responseFormat = validateArtifact.right().value();
309 handleAuditing(auditingAction, parent, componentId, user, null, null, artifactId, responseFormat, componentType, null);
310 errorWrapper.setInnerElement(validateArtifact.right().value());
312 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Download) {
313 artifactInfo = validateArtifact.left().value();
314 handleHeatEnvDownload(componentId, componentType, user, component, validateArtifact, shouldLock, errorWrapper);
321 private void handleHeatEnvDownload(String componentId, ComponentTypeEnum componentType, User user, org.openecomp.sdc.be.model.Component component, Either<ArtifactDefinition, ResponseFormat> validateArtifact, boolean shouldLock,
322 Wrapper<ResponseFormat> errorWrapper) {
323 ArtifactDefinition validatedArtifact = validateArtifact.left().value();
325 if (validatedArtifact.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType())) {
326 if (ComponentTypeEnum.SERVICE == component.getComponentType()) {
327 ComponentInstance componentInstance = component.getComponentInstances().stream().filter(p -> p.getUniqueId().equals(componentId)).findAny().get();
328 Map<String, ArtifactDefinition> deploymentArtifacts = componentInstance.getDeploymentArtifacts();
330 ArtifactDefinition heatEnvWithHeatParams = deploymentArtifacts.values().stream().filter(p -> p.getUniqueId().equals(validatedArtifact.getUniqueId())).findAny().get();
331 Either<ArtifactDefinition, ResponseFormat> eitherGenerated = generateHeatEnvArtifact(heatEnvWithHeatParams, componentType, component, componentInstance.getName(), user, shouldLock, componentId);
332 if (eitherGenerated.isRight()) {
333 errorWrapper.setInnerElement(eitherGenerated.right().value());
339 private boolean artifactGenerationRequired(org.openecomp.sdc.be.model.Component component, ArtifactDefinition artifactInfo) {
340 boolean needGenerate;
341 needGenerate = artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA && (component.getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKIN || component.getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT);
342 needGenerate = needGenerate || (ComponentTypeEnum.RESOURCE == component.getComponentType() && artifactInfo.getArtifactType().equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType()));
346 public Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateAndSaveToscaArtifact(ArtifactDefinition artifactDefinition, org.openecomp.sdc.be.model.Component component, User user, boolean isInCertificationRequest,
347 boolean shouldLock, boolean inTransaction, boolean fetchTemplatesFromDB) {
349 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generated = generateToscaArtifact(component, artifactDefinition, isInCertificationRequest, fetchTemplatesFromDB);
350 if (generated.isRight()) {
353 byte[] decodedPayload = artifactDefinition.getPayloadData();
354 artifactDefinition.setEsId(artifactDefinition.getUniqueId());
355 artifactDefinition.setArtifactChecksum(GeneralUtility.calculateMD5ByByteArray(decodedPayload));
356 return lockComponentAndUpdateArtifact(component.getUniqueId(), artifactDefinition, AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, artifactDefinition.getUniqueId(), user, component.getComponentType(), component, decodedPayload, null, null,
357 shouldLock, inTransaction);
361 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateToscaArtifact(Component parent, ArtifactDefinition artifactInfo, boolean isInCertificationRequest, boolean fetchTemplatesFromDB) {
362 log.debug("tosca artifact generation");
363 if (artifactInfo.getArtifactType().equals(ArtifactTypeEnum.TOSCA_CSAR.getType())) {
364 Either<byte[], ResponseFormat> generated = csarUtils.createCsar(parent, fetchTemplatesFromDB, isInCertificationRequest);
366 if (generated.isRight()) {
367 log.debug("Failed to export tosca csar for component {} error {}", parent.getUniqueId(), generated.right().value());
369 return Either.right(generated.right().value());
371 byte[] value = generated.left().value();
372 artifactInfo.setPayload(value);
375 Either<ToscaRepresentation, ToscaError> exportComponent = toscaExportUtils.exportComponent(parent);
376 if (exportComponent.isRight()) {
377 log.debug("Failed export tosca yaml for component {} error {}", parent.getUniqueId(), exportComponent.right().value());
378 ActionStatus status = componentsUtils.convertFromToscaError(exportComponent.right().value());
379 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status);
380 return Either.right(responseFormat);
382 log.debug("Tosca yaml exported for component {} ", parent.getUniqueId());
383 String payload = exportComponent.left().value().getMainYaml();
384 artifactInfo.setPayloadData(payload);
386 return Either.left(Either.left(artifactInfo));
389 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> doAction(String componentId, ComponentTypeEnum componentType, ArtifactOperationInfo operation, String artifactId, ArtifactDefinition artifactInfo, String origMd5,
390 String originData, String interfaceName, String operationName, AuditingActionEnum auditingAction, User user, org.openecomp.sdc.be.model.Component parent, boolean shouldLock, boolean inTransaction) {
391 if (interfaceName != null && operationName != null) {
392 interfaceName = interfaceName.toLowerCase();
393 operationName = operationName.toLowerCase();
395 switch (operation.getArtifactOperationEnum()) {
397 if (artifactGenerationRequired(parent, artifactInfo)) {
398 return generateNotSavedArtifact(parent, artifactInfo, shouldLock, inTransaction);
400 return handleDownload(componentId, artifactId, user, auditingAction, componentType, parent, shouldLock, inTransaction);
402 return handleDelete(componentId, artifactId, user, auditingAction, componentType, parent, interfaceName, operationName, shouldLock, inTransaction);
404 ArtifactTypeEnum artifactType = ArtifactTypeEnum.findType(artifactInfo.getArtifactType());
405 if (componentType.equals(ComponentTypeEnum.RESOURCE_INSTANCE)
406 && (artifactType == ArtifactTypeEnum.HEAT || artifactType == ArtifactTypeEnum.HEAT_VOL || artifactType == ArtifactTypeEnum.HEAT_NET || artifactType == ArtifactTypeEnum.HEAT_ENV)) {
407 return handleUpdateHeatEnv(componentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, originData, origMd5, operation, shouldLock, inTransaction);
409 if (componentType.equals(ComponentTypeEnum.RESOURCE) && artifactType == ArtifactTypeEnum.HEAT_ENV) {
410 return handleUpdateHeatWithHeatEnvParams(componentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, originData, origMd5, operation, shouldLock, inTransaction);
413 return handleUpdate(componentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceName, operationName, shouldLock, inTransaction);
415 return handleCreate(componentId, artifactInfo, operation, auditingAction, user, componentType, parent, origMd5, originData, interfaceName, operationName, shouldLock, inTransaction);
420 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> generateNotSavedArtifact(org.openecomp.sdc.be.model.Component parent, ArtifactDefinition artifactInfo, boolean shouldLock, boolean inTransaction) {
421 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result;
422 if (artifactInfo.getArtifactGroupType() == ArtifactGroupTypeEnum.TOSCA) {
423 result = generateToscaArtifact(parent, artifactInfo, false, false);
425 String heatArtifactId = artifactInfo.getGeneratedFromId();
426 Either<ArtifactDefinition, StorageOperationStatus> heatRes = artifactToscaOperation.getArtifactById(parent.getUniqueId(), heatArtifactId);
427 if (heatRes.isRight()) {
428 log.debug("Failed to fetch heat artifact by generated id {} for heat env {}", heatArtifactId, artifactInfo.getUniqueId());
429 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(heatRes.right().value()), "");
430 return Either.right(responseFormat);
432 String generatedPayload = generateHeatEnvPayload(heatRes.left().value());
433 artifactInfo.setPayloadData(generatedPayload);
434 result = Either.left(Either.left(artifactInfo));
439 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdateHeatWithHeatEnvParams(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user,
440 ComponentTypeEnum componentType, Component parent, String originData, String origMd5, ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) {
441 convertParentType(componentType);
442 String parentId = parent.getUniqueId();
443 Either<ArtifactDefinition, StorageOperationStatus> artifactHeatRes = artifactToscaOperation.getArtifactById(componentId, artifactInfo.getGeneratedFromId());
444 ArtifactDefinition currHeatArtifact = artifactHeatRes.left().value();
446 if (origMd5 != null) {
447 Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
448 if (validateMd5.isRight()) {
449 ResponseFormat responseFormat = validateMd5.right().value();
450 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
451 return Either.right(responseFormat);
454 if (artifactInfo.getPayloadData() != null && artifactInfo.getPayloadData().length != 0) {
456 Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
457 if (payloadEither.isRight()) {
458 ResponseFormat responseFormat = payloadEither.right().value();
459 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
460 return Either.right(responseFormat);
462 } else { // duplicate
463 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
464 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
465 return Either.right(responseFormat);
471 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Update Artifact - lock ");
472 if (lockComponent.isRight()) {
473 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right().value(), componentType, null);
474 return Either.right(lockComponent.right().value());
477 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
479 resultOp = updateHeatParams(componentId, artifactId, artifactInfo, user, auditingAction, parent, componentType, currHeatArtifact, origMd5);
484 if (resultOp == null || resultOp.isRight()) {
485 log.debug("all changes rollback");
486 if (false == inTransaction)
489 log.debug("all changes committed");
490 if (false == inTransaction)
494 componentType = parent.getComponentType();
495 NodeTypeEnum nodeType = componentType.getNodeType();
496 graphLockOperation.unlockComponent(parent.getUniqueId(), nodeType);
497 // graphLockOperation.unlockComponent(parentId, parentType);
506 * @param componentType
511 public Either<ImmutablePair<String, byte[]>, ResponseFormat> handleDownloadToscaModelRequest(Component component, ArtifactDefinition csarArtifact) {
512 if (artifactGenerationRequired(component, csarArtifact)) {
513 Either<byte[], ResponseFormat> generated = csarUtils.createCsar(component, false, false);
515 if (generated.isRight()) {
516 log.debug("Failed to export tosca csar for component {} error {}", component.getUniqueId(), generated.right().value());
518 return Either.right(generated.right().value());
520 return Either.left(new ImmutablePair<String, byte[]>(csarArtifact.getArtifactName(), generated.left().value()));
522 return downloadArtifact(csarArtifact);
525 public Either<ImmutablePair<String, byte[]>, ResponseFormat> handleDownloadRequestById(String componentId, String artifactId, String userId, ComponentTypeEnum componentType, String parentId, String containerComponentType) {
526 // perform all validation in common flow
527 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> result = handleArtifactRequest(componentId, userId, componentType, new ArtifactOperationInfo(false, false, ArtifactOperationEnum.Download), artifactId, null, null, null, null,
528 null, parentId, containerComponentType);
529 if (result.isRight()) {
530 return Either.right(result.right().value());
532 ArtifactDefinition artifactDefinition;
533 Either<ArtifactDefinition, Operation> insideValue = result.left().value();
534 if (insideValue.isLeft()) {
535 artifactDefinition = insideValue.left().value();
537 artifactDefinition = insideValue.right().value().getImplementationArtifact();
539 // for tosca artifacts and heat env on VF level generated on download without saving
540 if (artifactDefinition.getPayloadData() != null) {
541 return Either.left(new ImmutablePair<String, byte[]>(artifactDefinition.getArtifactName(), artifactDefinition.getPayloadData()));
543 return downloadArtifact(artifactDefinition);
546 public Either<Map<String, ArtifactDefinition>, ResponseFormat> handleGetArtifactsByType(String containerComponentType, String parentId, ComponentTypeEnum componentType, String componentId, String artifactGroupType, String userId) {
548 // detect auditing type
549 Map<String, ArtifactDefinition> resMap = null;
550 Either<Map<String, ArtifactDefinition>, ResponseFormat> resultOp = null;
555 if (userId == null) {
556 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
557 log.debug("handleGetArtifactsByType - no HTTP_CSP_HEADER , component id {}", componentId);
559 resultOp = Either.right(responseFormat);
563 // check user existence
567 Either<User, ResponseFormat> userResult = validateUserExists(userId, "get artifacts", false);
568 if (userResult.isRight()) {
570 resultOp = Either.right(userResult.right().value());
574 userResult.left().value();
577 // 5. check service/resource existence
578 // 6. check service/resource check out
579 // 7. user is owner of checkout state
580 org.openecomp.sdc.be.model.Component component = null;
581 // ComponentInstance resourceInstance = null;
582 String realComponentId = componentType == ComponentTypeEnum.RESOURCE_INSTANCE ? parentId : componentId;
583 ComponentParametersView componentFilter = new ComponentParametersView();
584 componentFilter.disableAll();
585 componentFilter.setIgnoreArtifacts(false);
586 if (componentType == ComponentTypeEnum.RESOURCE_INSTANCE)
587 componentFilter.setIgnoreComponentInstances(false);
589 Either<? extends org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponent = validateComponentExistsByFilter(realComponentId, ComponentTypeEnum.findByParamName(containerComponentType), componentFilter, false);
591 if (validateComponent.isRight()) {
592 resultOp = Either.right(validateComponent.right().value());
595 component = validateComponent.left().value();
596 Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, "Update Artifact - lock ");
597 if (lockComponent.isRight()) {
599 resultOp = Either.right(lockComponent.right().value());
604 ArtifactGroupTypeEnum groupType = ArtifactGroupTypeEnum.findType(artifactGroupType);
606 if (groupType == null) {
607 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
608 log.debug("handleGetArtifactsByType - not falid groupType {} , component id {}", artifactGroupType, componentId);
610 resultOp = Either.right(responseFormat);
614 if (groupType == ArtifactGroupTypeEnum.DEPLOYMENT) {
615 List<ArtifactDefinition> list = getDeploymentArtifacts(component, componentType.getNodeType(), componentId);
616 if (list != null && !list.isEmpty()) {
617 resMap = list.stream().collect(Collectors.toMap(a -> a.getArtifactLabel(), a -> a));
619 resMap = new HashMap<>();
621 resultOp = Either.left(resMap);
625 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> artifactsMapStatus = getArtifacts(realComponentId, componentType.getNodeType(), false, groupType, componentId);
626 if (artifactsMapStatus.isRight()) {
627 if (artifactsMapStatus.right().value() != StorageOperationStatus.NOT_FOUND) {
628 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_INFORMATION);
629 log.debug("handleGetArtifactsByType - not falid groupType {} , component id {}", artifactGroupType, componentId);
630 resultOp = Either.right(responseFormat);
632 resMap = new HashMap<>();
633 resultOp = Either.left(resMap);
636 resMap = artifactsMapStatus.left().value();
637 resultOp = Either.left(resMap);
643 if (resultOp == null || resultOp.isRight()) {
644 log.debug("all changes rollback");
647 log.debug("all changes committed");
652 componentType = component.getComponentType();
653 NodeTypeEnum nodeType = componentType.getNodeType();
654 graphLockOperation.unlockComponent(component.getUniqueId(), nodeType);
655 // graphLockOperation.unlockComponent(parentId, parentType);
660 private Either<ArtifactDefinition, ResponseFormat> validateArtifact(String componentId, ComponentTypeEnum componentType, String artifactId, org.openecomp.sdc.be.model.Component component, AuditingActionEnum auditingAction, String parentId,
661 boolean inTransaction) {
663 // check artifact existence
664 Either<ArtifactDefinition, StorageOperationStatus> artifactResult = artifactToscaOperation.getArtifactById(componentId, artifactId, componentType, component.getUniqueId());
665 if (artifactResult.isRight()) {
666 if (artifactResult.right().value().equals(StorageOperationStatus.ARTIFACT_NOT_FOUND)) {
667 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, "");
668 log.debug("addArtifact - artifact {} not found", artifactId);
669 return Either.right(responseFormat);
672 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(artifactResult.right().value()));
673 log.debug("addArtifact - failed to fetch artifact {}, error {}", artifactId, artifactResult.right().value());
674 return Either.right(responseFormat);
678 // check artifact belong to component
679 boolean found = false;
680 switch (componentType) {
683 found = checkArtifactInComponent(component, artifactId);
685 case RESOURCE_INSTANCE:
686 found = checkArtifactInResourceInstance(component, componentId, artifactId);
692 // String component =
693 // componentType.equals(ComponentTypeEnum.RESOURCE) ? "resource" :
695 String componentName = componentType.name().toLowerCase();
696 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_ARTIFACT_NOT_FOUND, componentName);
697 log.debug("addArtifact - Component artifact not found component Id {}, artifact id {}", componentId, artifactId);
698 return Either.right(responseFormat);
700 return Either.left(artifactResult.left().value());
703 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleCreate(String parentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, User user, ComponentTypeEnum componentType,
704 org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
706 String artifactId = null;
709 Either<byte[], ResponseFormat> payloadEither = validateInput(parentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceType, operationName, inTransaction);
710 if (payloadEither.isRight()) {
711 return Either.right(payloadEither.right().value());
713 byte[] decodedPayload = payloadEither.left().value();
714 convertParentType(componentType);
717 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Upload Artifact - lock ");
718 if (lockComponent.isRight()) {
719 handleAuditing(auditingAction, parent, parentId, user, null, null, null, lockComponent.right().value(), componentType, null);
720 return Either.right(lockComponent.right().value());
723 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
726 resultOp = createArtifact(parent, parentId, artifactInfo, decodedPayload, user, componentType, auditingAction, interfaceType, operationName);
730 unlockComponent(resultOp, parent, inTransaction);
737 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> lockComponentAndUpdateArtifact(String parentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user,
738 ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent, byte[] decodedPayload, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
740 convertParentType(componentType);
744 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Update Artifact - lock ");
746 if (lockComponent.isRight()) {
747 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right().value(), componentType, null);
748 return Either.right(lockComponent.right().value());
752 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
754 resultOp = updateArtifactFlow(parent, parentId, artifactId, artifactInfo, user, decodedPayload, componentType, auditingAction, interfaceType, operationName);
759 unlockComponent(resultOp, parent, inTransaction);
764 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdate(String parentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, String artifactId, User user,
765 ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean shouldLock, boolean inTransaction) {
767 Either<byte[], ResponseFormat> payloadEither = validateInput(parentId, artifactInfo, operation, auditingAction, artifactId, user, componentType, parent, origMd5, originData, interfaceType, operationName, inTransaction);
769 if (payloadEither.isRight()) {
770 return Either.right(payloadEither.right().value());
772 byte[] decodedPayload = payloadEither.left().value();
774 return lockComponentAndUpdateArtifact(parentId, artifactInfo, auditingAction, artifactId, user, componentType, parent, decodedPayload, interfaceType, operationName, shouldLock, inTransaction);
777 private Either<byte[], ResponseFormat> validateInput(String parentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType,
778 org.openecomp.sdc.be.model.Component parent, String origMd5, String originData, String interfaceType, String operationName, boolean inTransaction) {
780 Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
781 if (validateMd5.isRight()) {
782 ResponseFormat responseFormat = validateMd5.right().value();
783 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
784 return Either.right(responseFormat);
788 Either<ArtifactDefinition, ResponseFormat> validateResult = validateInput(parentId, artifactInfo, operation, artifactId, user, interfaceType, operationName, componentType, parent, inTransaction);
789 if (validateResult.isRight()) {
790 ResponseFormat responseFormat = validateResult.right().value();
791 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
792 return Either.right(validateResult.right().value());
795 Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
796 if (payloadEither.isRight()) {
797 ResponseFormat responseFormat = payloadEither.right().value();
798 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
799 log.debug("Error during handle payload");
800 return Either.right(responseFormat);
803 // validate heat parameters. this part must be after the parameters are
804 // extracted in "handlePayload"
805 Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers = validateAndConvertHeatParamers(artifactInfo, artifactInfo.getArtifactType());
806 if (validateAndConvertHeatParamers.isRight()) {
807 ResponseFormat responseFormat = validateAndConvertHeatParamers.right().value();
808 handleAuditing(auditingAction, parent, parentId, user, artifactInfo, null, artifactId, responseFormat, componentType, null);
809 log.debug("Error during handle payload");
810 return Either.right(responseFormat);
812 return payloadEither;
815 public void handleAuditing(AuditingActionEnum auditingActionEnum, Component component, String componentId, User user, ArtifactDefinition artifactDefinition, String prevArtifactUuid, String currentArtifactUuid, ResponseFormat responseFormat,
816 ComponentTypeEnum componentTypeEnum, String resourceInstanceName) {
818 if (auditingActionEnum.getAuditingEsType().equals(AuditingTypesConstants.EXTERNAL_API_EVENT_TYPE)) {
822 EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = createArtifactAuditingFields(artifactDefinition, prevArtifactUuid, currentArtifactUuid);
826 user.setUserId("UNKNOWN");
828 switch (componentTypeEnum) {
831 Resource resource = (Resource) component;
832 if (resource == null) {
833 // In that case, component ID should be instead of name
834 resource = new Resource();
835 resource.setName(componentId);
837 componentsUtils.auditResource(responseFormat, user, resource, null, null, auditingActionEnum, auditingFields);
841 Service service = (Service) component;
842 if (service == null) {
843 // In that case, component ID should be instead of name
844 service = new Service();
845 service.setName(componentId);
847 componentsUtils.auditComponent(responseFormat, user, service, null, null, auditingActionEnum, ComponentTypeEnum.SERVICE, auditingFields);
850 case RESOURCE_INSTANCE:
851 if (resourceInstanceName == null) {
852 resourceInstanceName = getResourceInstanceNameFromComponent(component, componentId);
854 auditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, resourceInstanceName);
855 componentsUtils.auditComponent(responseFormat, user, component, null, null, auditingActionEnum, ComponentTypeEnum.RESOURCE_INSTANCE, auditingFields);
863 private String getResourceInstanceNameFromComponent(Component component, String componentId) {
864 ComponentInstance resourceInstance = component.getComponentInstances().stream().filter(p -> p.getUniqueId().equals(componentId)).findFirst().orElse(null);
865 String resourceInstanceName = null;
866 if (resourceInstance != null) {
867 resourceInstanceName = resourceInstance.getName();
869 return resourceInstanceName;
872 public EnumMap<AuditingFieldsKeysEnum, Object> createArtifactAuditingFields(ArtifactDefinition artifactDefinition, String prevArtifactUuid, String currentArtifactUuid) {
873 EnumMap<AuditingFieldsKeysEnum, Object> auditingFields = new EnumMap<AuditingFieldsKeysEnum, Object>(AuditingFieldsKeysEnum.class);
874 // Putting together artifact info
875 String artifactData = buildAuditingArtifactData(artifactDefinition);
876 auditingFields.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, artifactData);
877 auditingFields.put(AuditingFieldsKeysEnum.AUDIT_PREV_ARTIFACT_UUID, prevArtifactUuid);
878 auditingFields.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, currentArtifactUuid);
879 return auditingFields;
884 private String buildAuditingArtifactData(ArtifactDefinition artifactDefinition) {
885 StringBuilder sb = new StringBuilder();
886 if (artifactDefinition != null) {
887 sb.append(artifactDefinition.getArtifactGroupType().getType()).append(",").append("'").append(artifactDefinition.getArtifactLabel()).append("'").append(",").append(artifactDefinition.getArtifactType()).append(",")
888 .append(artifactDefinition.getArtifactName()).append(",").append(artifactDefinition.getTimeout()).append(",").append(artifactDefinition.getEsId());
891 if (artifactDefinition.getArtifactVersion() != null) {
893 sb.append(artifactDefinition.getArtifactVersion());
898 if (artifactDefinition.getArtifactUUID() != null) {
899 sb.append(artifactDefinition.getArtifactUUID());
904 return sb.toString();
907 private Either<Boolean, ResponseFormat> validateMd5(String origMd5, String originData, byte[] payload, ArtifactOperationInfo operation) {
909 if (origMd5 != null) {
910 String encodeBase64Str = GeneralUtility.calculateMD5ByString(originData);
912 if (false == encodeBase64Str.equals(origMd5)) {
913 log.debug("The calculated md5 is different then the received one");
914 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_MD5));
917 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create) {
918 log.debug("Missing md5 header during artifact create");
919 return Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_INVALID_MD5));
922 if (payload != null && payload.length != 0) {
923 log.debug("Cannot have payload while md5 header is missing");
924 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
927 return Either.left(true);
930 private Either<ArtifactDefinition, ResponseFormat> validateInput(String parentId, ArtifactDefinition artifactInfo, ArtifactOperationInfo operation, String artifactId, User user, String interfaceName, String operationName,
931 ComponentTypeEnum componentType, Component parentComponent, boolean inTransaction) {
933 Either<Boolean, ResponseFormat> validateInformationalArtifactRes = validateInformationalArtifact(artifactInfo, parentComponent);
934 if (validateInformationalArtifactRes.isRight()) {
935 return Either.right(validateInformationalArtifactRes.right().value());
937 Either<Boolean, ResponseFormat> validateAndSetArtifactname = validateAndSetArtifactname(artifactInfo);
938 if (validateAndSetArtifactname.isRight()) {
939 return Either.right(validateAndSetArtifactname.right().value());
941 Either<ArtifactDefinition, ResponseFormat> artifactById = findArtifactOnParentComponent(parentComponent, componentType, parentId, operation, artifactId);
942 if (artifactById.isRight()) {
943 return Either.right(artifactById.right().value());
945 ArtifactDefinition currentArtifactInfo = artifactById.left().value();
946 if (operationName != null && interfaceName != null) {
947 operationName = operationName.toLowerCase();
948 interfaceName = interfaceName.toLowerCase();
950 Either<ActionStatus, ResponseFormat> logicalNameStatus = handleArtifactLabel(parentId, operation, artifactId, artifactInfo, interfaceName, operationName, currentArtifactInfo, componentType, inTransaction);
951 if (logicalNameStatus.isRight()) {
952 return Either.right(logicalNameStatus.right().value());
954 // This is a patch to block possibility of updating service api fields
955 // through other artifacts flow
957 if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.Create) {
958 checkAndSetUnUpdatableFields(user, artifactInfo, currentArtifactInfo, (operationName != null ? ArtifactGroupTypeEnum.LIFE_CYCLE : ArtifactGroupTypeEnum.INFORMATIONAL));
960 checkCreateFields(user, artifactInfo, (operationName != null ? ArtifactGroupTypeEnum.LIFE_CYCLE : ArtifactGroupTypeEnum.INFORMATIONAL));
963 composeArtifactId(parentId, artifactId, artifactInfo, interfaceName, operationName);
964 if (currentArtifactInfo != null) {
965 artifactInfo.setMandatory(currentArtifactInfo.getMandatory());
968 // artifactGroupType is not allowed to be updated
969 if (operation.getArtifactOperationEnum() != ArtifactOperationEnum.Create) {
970 Either<ArtifactDefinition, ResponseFormat> validateGroupType = validateOrSetArtifactGroupType(artifactInfo, currentArtifactInfo);
971 if (validateGroupType.isRight()) {
972 return Either.right(validateGroupType.right().value());
976 NodeTypeEnum parentType = convertParentType(componentType);
979 boolean isCreate = operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create;
981 if (isDeploymentArtifact(artifactInfo)) {
982 Either<Boolean, ResponseFormat> deploymentValidationResult = validateDeploymentArtifact(parentComponent, parentId, user.getUserId(), isCreate, artifactInfo, currentArtifactInfo, parentType);
983 if (deploymentValidationResult.isRight()) {
984 return Either.right(deploymentValidationResult.right().value());
987 artifactInfo.setTimeout(NodeTemplateOperation.NON_HEAT_TIMEOUT);
990 * if (informationDeployedArtifactsBusinessLogic. isInformationDeployedArtifact(artifactInfo)) { Either<Boolean, ResponseFormat> validationResult = informationDeployedArtifactsBusinessLogic.validateArtifact( isCreate, artifactInfo,
991 * parentComponent, parentType); if (validationResult.isRight()) { return Either.right(validationResult.right().value()); } }
995 Either<Boolean, ResponseFormat> descriptionResult = validateAndCleanDescription(artifactInfo);
996 if (descriptionResult.isRight()) {
997 return Either.right(descriptionResult.right().value());
1000 if (currentArtifactInfo != null && currentArtifactInfo.getArtifactGroupType().equals(ArtifactGroupTypeEnum.SERVICE_API)) {
1001 Either<ActionStatus, ResponseFormat> validateServiceApiType = validateArtifactType(user.getUserId(), artifactInfo, parentType);
1002 if (validateServiceApiType.isRight()) {
1003 return Either.right(validateServiceApiType.right().value());
1005 // Change of type is not allowed and should be ignored
1007 artifactInfo.setArtifactType(ARTIFACT_TYPE_OTHER);
1009 Either<Boolean, ResponseFormat> validateUrl = validateAndServiceApiUrl(artifactInfo);
1010 if (validateUrl.isRight()) {
1011 return Either.right(validateUrl.right().value());
1014 Either<Boolean, ResponseFormat> validateUpdate = validateFirstUpdateHasPayload(artifactInfo, currentArtifactInfo);
1015 if (validateUpdate.isRight()) {
1016 log.debug("serviceApi first update cnnot be without payload.");
1017 return Either.right(validateUpdate.right().value());
1020 Either<ActionStatus, ResponseFormat> validateArtifactType = validateArtifactType(user.getUserId(), artifactInfo, parentType);
1021 if (validateArtifactType.isRight()) {
1022 return Either.right(validateArtifactType.right().value());
1024 if (artifactInfo.getApiUrl() != null) {
1025 artifactInfo.setApiUrl(null);
1026 log.error("Artifact URL cannot be set through this API - ignoring");
1029 if (artifactInfo.getServiceApi() != null) {
1030 if (artifactInfo.getServiceApi()) {
1031 artifactInfo.setServiceApi(false);
1032 log.error("Artifact service API flag cannot be changed - ignoring");
1037 return Either.left(artifactInfo);
1040 private Either<ArtifactDefinition, ResponseFormat> findArtifactOnParentComponent(Component parentComponent, ComponentTypeEnum componentType, String parentId, ArtifactOperationInfo operation, String artifactId) {
1042 Either<ArtifactDefinition, ResponseFormat> result = null;
1043 ArtifactDefinition foundArtifact = null;
1044 if (StringUtils.isNotEmpty(artifactId)) {
1045 foundArtifact = findArtifact(parentComponent, componentType, parentId, artifactId);
1047 if (foundArtifact != null && operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create) {
1048 log.debug("Artifact {} already exist", artifactId);
1049 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_EXIST, foundArtifact.getArtifactLabel()));
1051 if (foundArtifact == null && operation.getArtifactOperationEnum() != ArtifactOperationEnum.Create) {
1052 log.debug("The artifact {} was not found on parent {}. ", artifactId, parentId);
1053 result = Either.right(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, ""));
1055 if (result == null) {
1056 result = Either.left(foundArtifact);
1061 private ArtifactDefinition findArtifact(Component parentComponent, ComponentTypeEnum componentType, String parentId, String artifactId) {
1062 ArtifactDefinition foundArtifact;
1063 if (parentComponent.getUniqueId().equals(parentId)) {
1064 foundArtifact = artifactsResolver.findArtifactOnComponent(parentComponent, componentType, artifactId);
1066 ComponentInstance instance = findComponentInstance(parentId, parentComponent);
1067 foundArtifact = artifactsResolver.findArtifactOnComponentInstance(instance, artifactId);
1069 return 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.getGroupInstanceArtifacts().remove(artifactId);
1260 if (CollectionUtils.isNotEmpty(groupInstance.getGroupInstanceArtifactsUuid()) && groupInstance.getGroupInstanceArtifactsUuid().contains(foundArtifact.getArtifactUUID())) {
1261 groupInstance.getGroupInstanceArtifactsUuid().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, true);
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 String prevUUID = artifactDefinition.getArtifactUUID();
3374 ArtifactDefinition clonedBeforeGenerate = new ArtifactDefinition(artifactDefinition);
3375 Either<ArtifactDefinition, ResponseFormat> generateResult = generateAndSaveHeatEnvArtifact(artifactDefinition, payload, componentType, component, resourceInstanceName, modifier, shouldLock, instanceId);
3376 if (generateResult.isLeft()) {
3377 ArtifactDefinition updatedArtDef = generateResult.left().value();
3378 if (!prevUUID.equals(updatedArtDef.getArtifactUUID())) {
3379 List<ComponentInstance> componentInstances = component.getComponentInstances();
3380 if (componentInstances != null) {
3381 Optional<ComponentInstance> findFirst = componentInstances.stream().filter(ci -> ci.getUniqueId().equals(instanceId)).findFirst();
3382 if (findFirst.isPresent()) {
3383 ComponentInstance relevantInst = findFirst.get();
3384 List<GroupInstance> updatedGroupInstances = getUpdatedGroupInstances(updatedArtDef.getUniqueId(), clonedBeforeGenerate, relevantInst.getGroupInstances());
3386 if (CollectionUtils.isNotEmpty(updatedGroupInstances)) {
3387 updatedGroupInstances.forEach(gi -> {
3388 gi.getGroupInstanceArtifacts().add(updatedArtDef.getUniqueId());
3389 gi.getGroupInstanceArtifactsUuid().add(updatedArtDef.getArtifactUUID());
3391 Either<List<GroupInstance>, StorageOperationStatus> status = toscaOperationFacade.updateGroupInstancesOnComponent(component, componentType, instanceId, updatedGroupInstances);
3392 if (status.isRight()) {
3393 log.debug("Failed to update groups of the component {}. ", component.getUniqueId());
3394 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(status.right().value()), clonedBeforeGenerate.getArtifactDisplayName());
3395 return Either.right(responseFormat);
3403 return generateResult;
3406 private String generateHeatEnvPayload(ArtifactDefinition artifactDefinition) {
3407 List<HeatParameterDefinition> heatParameters = artifactDefinition.getListHeatParameters();
3408 heatParameters.sort(Comparator.comparing(e -> e.getName()));
3409 StringBuilder sb = new StringBuilder();
3410 sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactHeader());
3411 sb.append("parameters:\n");
3412 if (heatParameters != null) {
3413 List<HeatParameterDefinition> empltyHeatValues = new ArrayList<>();
3415 for (HeatParameterDefinition heatParameterDefinition : heatParameters) {
3417 String heatValue = heatParameterDefinition.getCurrentValue();
3418 if (!ValidationUtils.validateStringNotEmpty(heatValue)) {
3419 heatValue = heatParameterDefinition.getDefaultValue();
3420 if (!ValidationUtils.validateStringNotEmpty(heatValue)) {
3421 empltyHeatValues.add(heatParameterDefinition);
3425 HeatParameterType type = HeatParameterType.isValidType(heatParameterDefinition.getType());
3429 sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(Boolean.parseBoolean(heatValue)).append("\n");
3432 sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(new BigDecimal(heatValue).toPlainString()).append("\n");
3434 case COMMA_DELIMITED_LIST:
3436 sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(heatValue).append("\n");
3439 String value = heatValue;
3440 boolean starts = value.startsWith("\"");
3441 boolean ends = value.endsWith("\"");
3442 if (!(starts && ends)) {
3443 starts = value.startsWith("'");
3444 ends = value.endsWith("'");
3445 if (!(starts && ends)) {
3446 value = "\"" + value + "\"";
3449 sb.append(" ").append(heatParameterDefinition.getName()).append(":").append(" ").append(value);
3456 if (!empltyHeatValues.isEmpty()) {
3457 empltyHeatValues.sort(Comparator.comparing(e -> e.getName()));
3458 empltyHeatValues.forEach(hv -> {
3459 sb.append(" ").append(hv.getName()).append(":");
3460 HeatParameterType type = HeatParameterType.isValidType(hv.getType());
3461 if (type != null && type == HeatParameterType.STRING && (hv.getCurrentValue() != null && "".equals(hv.getCurrentValue()) || hv.getDefaultValue() != null && "".equals(hv.getDefaultValue()))) {
3462 sb.append(" \"\"").append("\n");
3464 sb.append(" ").append("\n");
3469 sb.append(ConfigurationManager.getConfigurationManager().getConfiguration().getHeatEnvArtifactFooter());
3472 String result = sb.toString().replaceAll("\\\\n", "\n");
3479 * @param artifactDefinition
3483 public Either<ArtifactDefinition, ResponseFormat> generateAndSaveHeatEnvArtifact(ArtifactDefinition artifactDefinition, String payload, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName,
3484 User modifier, boolean shouldLock, String instanceId) {
3485 return generateArtifactPayload(artifactDefinition, componentType, component, resourceInstanceName, modifier, shouldLock, () -> artifactDefinition.getHeatParamsUpdateDate(),
3486 () -> createEsHeatEnvArtifactDataFromString(artifactDefinition, payload), instanceId);
3490 protected Either<ArtifactDefinition, ResponseFormat> generateArtifactPayload(ArtifactDefinition artifactDefinition, ComponentTypeEnum componentType, org.openecomp.sdc.be.model.Component component, String resourceInstanceName, User modifier,
3491 boolean shouldLock, Supplier<Long> payloadUpdateDateGen, Supplier<Either<ESArtifactData, ResponseFormat>> esDataCreator, String instanceId) {
3493 if (artifactDefinition.getPayloadUpdateDate() == null || artifactDefinition.getPayloadUpdateDate() == 0 || artifactDefinition.getPayloadUpdateDate() < payloadUpdateDateGen.get()) {
3495 log.trace("Generaing payload for {} artifact {}", artifactDefinition.getArtifactType(), artifactDefinition.getEsId());
3496 Either<ESArtifactData, ResponseFormat> artifactDataRes = esDataCreator.get();
3497 ESArtifactData artifactData = null;
3499 if (artifactDataRes.isLeft()) {
3500 artifactData = artifactDataRes.left().value();
3502 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
3503 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
3504 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
3506 return Either.right(artifactDataRes.right().value());
3508 String newCheckSum = GeneralUtility.calculateMD5ByByteArray(artifactData.getDataAsArray());
3510 String esArtifactId = artifactDefinition.getEsId();
3511 Either<ESArtifactData, CassandraOperationStatus> artifactfromES;
3512 ESArtifactData esArtifactData;
3513 if (esArtifactId != null && !esArtifactId.isEmpty() && artifactDefinition.getPayloadData() == null) {
3514 artifactfromES = artifactCassandraDao.getArtifact(esArtifactId);
3515 if (artifactfromES.isRight()) {
3516 CassandraOperationStatus resourceUploadStatus = artifactfromES.right().value();
3517 StorageOperationStatus storageResponse = DaoStatusConverter.convertCassandraStatusToStorageStatus(resourceUploadStatus);
3518 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageResponse);
3519 log.debug("Error when getting artifact from ES, error: {}", actionStatus.name());
3520 return Either.right(componentsUtils.getResponseFormatByArtifactId(actionStatus, artifactDefinition.getArtifactDisplayName()));
3522 esArtifactData = artifactfromES.left().value();
3523 oldCheckSum = GeneralUtility.calculateMD5ByByteArray(esArtifactData.getDataAsArray());
3525 oldCheckSum = artifactDefinition.getArtifactChecksum();
3528 Either<ArtifactDefinition, StorageOperationStatus> updateArifactDefinitionStatus = null;
3531 Either<Boolean, ResponseFormat> lockComponent = lockComponent(component, "Update Artifact - lock resource: ");
3532 if (lockComponent.isRight()) {
3533 handleAuditing(AuditingActionEnum.ARTIFACT_METADATA_UPDATE, component, component.getUniqueId(), modifier, null, null, artifactDefinition.getUniqueId(), lockComponent.right().value(), component.getComponentType(), null);
3534 return Either.right(lockComponent.right().value());
3538 if (oldCheckSum != null && oldCheckSum.equals(newCheckSum)) {
3540 artifactDefinition.setPayloadUpdateDate(payloadUpdateDateGen.get());
3541 updateArifactDefinitionStatus = artifactToscaOperation.updateArifactOnResource(artifactDefinition, component.getUniqueId(), artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId);
3542 log.trace("No real update done in payload for {} artifact, updating payloadUpdateDate {}", artifactDefinition.getArtifactType(), artifactDefinition.getEsId());
3543 if (updateArifactDefinitionStatus.isRight()) {
3544 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus.right().value()), artifactDefinition.getArtifactDisplayName());
3545 log.trace("Failed to update payloadUpdateDate {}", artifactDefinition.getEsId());
3546 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
3547 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
3549 return Either.right(responseFormat);
3553 oldCheckSum = artifactDefinition.getArtifactChecksum();
3554 artifactDefinition.setArtifactChecksum(newCheckSum);
3555 // artifactToscaOperation.updateUUID(artifactDefinition, oldCheckSum, artifactDefinition.getArtifactVersion());
3556 artifactDefinition.setEsId(artifactDefinition.getUniqueId());
3557 updateArifactDefinitionStatus = artifactToscaOperation.updateArifactOnResource(artifactDefinition, component.getUniqueId(), artifactDefinition.getUniqueId(), componentType.getNodeType(), instanceId);
3559 log.trace("Update Payload ", artifactDefinition.getEsId());
3561 if (updateArifactDefinitionStatus != null && updateArifactDefinitionStatus.isLeft()) {
3563 artifactDefinition = updateArifactDefinitionStatus.left().value();
3564 artifactData.setId(artifactDefinition.getUniqueId());
3565 CassandraOperationStatus saveArtifactStatus = artifactCassandraDao.saveArtifact(artifactData);
3567 if (saveArtifactStatus.equals(CassandraOperationStatus.OK)) {
3569 log.debug("Artifact Saved In ES {}", artifactData.getId());
3570 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
3571 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
3572 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
3575 titanDao.rollback();
3576 log.info("Failed to save artifact {}.", artifactData.getId());
3577 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
3578 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
3579 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
3581 return Either.right(responseFormat);
3584 ResponseFormat responseFormat = componentsUtils.getResponseFormatByArtifactId(componentsUtils.convertFromStorageResponse(updateArifactDefinitionStatus.right().value()), artifactDefinition.getArtifactDisplayName());
3585 log.debug("Failed To update artifact {}", artifactData.getId());
3586 handleAuditing(AuditingActionEnum.ARTIFACT_PAYLOAD_UPDATE, component, component.getUniqueId(), modifier, artifactDefinition, artifactDefinition.getUniqueId(), artifactDefinition.getUniqueId(), responseFormat,
3587 ComponentTypeEnum.RESOURCE_INSTANCE, resourceInstanceName);
3589 return Either.right(responseFormat);
3594 graphLockOperation.unlockComponent(component.getUniqueId(), component.getComponentType().getNodeType());
3599 return Either.left(artifactDefinition);
3602 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> handleUpdateHeatEnv(String componentId, ArtifactDefinition artifactInfo, AuditingActionEnum auditingAction, String artifactId, User user, ComponentTypeEnum componentType,
3603 org.openecomp.sdc.be.model.Component parent, String originData, String origMd5, ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) {
3604 convertParentType(componentType);
3605 String parentId = parent.getUniqueId();
3606 // Either<ArtifactDefinition, StorageOperationStatus> artifactRes = this.artifactToscaOperation.getArtifactById(componentId, artifactId);
3607 ArtifactDefinition currArtifact = artifactInfo;
3609 if (origMd5 != null) {
3610 Either<Boolean, ResponseFormat> validateMd5 = validateMd5(origMd5, originData, artifactInfo.getPayloadData(), operation);
3611 if (validateMd5.isRight()) {
3612 ResponseFormat responseFormat = validateMd5.right().value();
3613 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
3614 return Either.right(responseFormat);
3617 if (artifactInfo.getPayloadData() != null && artifactInfo.getPayloadData().length != 0) {
3618 Either<Boolean, ResponseFormat> deploymentValidationResult = validateDeploymentArtifact(parent, componentId, user.getUserId(), false, artifactInfo, currArtifact, NodeTypeEnum.ResourceInstance);
3619 if (deploymentValidationResult.isRight()) {
3620 ResponseFormat responseFormat = deploymentValidationResult.right().value();
3621 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
3622 return Either.right(responseFormat);
3625 Either<byte[], ResponseFormat> payloadEither = handlePayload(artifactInfo, isArtifactMetadataUpdate(auditingAction));
3626 if (payloadEither.isRight()) {
3627 ResponseFormat responseFormat = payloadEither.right().value();
3628 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
3629 return Either.right(responseFormat);
3631 } else { // duplicate
3632 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISSING_DATA, ARTIFACT_PAYLOAD);
3633 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, responseFormat, componentType, null);
3634 return Either.right(responseFormat);
3640 Either<Boolean, ResponseFormat> lockComponent = lockComponent(parent, "Update Artifact - lock ");
3641 if (lockComponent.isRight()) {
3642 handleAuditing(auditingAction, parent, parentId, user, null, null, artifactId, lockComponent.right().value(), componentType, null);
3643 return Either.right(lockComponent.right().value());
3646 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
3648 resultOp = updateHeatEnvParams(componentId, artifactId, artifactInfo, user, auditingAction, parent, componentType, currArtifact, origMd5, inTransaction);
3653 if (resultOp == null || resultOp.isRight()) {
3654 log.debug("all changes rollback");
3655 if (false == inTransaction)
3656 titanDao.rollback();
3658 log.debug("all changes committed");
3659 if (false == inTransaction)
3663 componentType = parent.getComponentType();
3664 NodeTypeEnum nodeType = componentType.getNodeType();
3665 graphLockOperation.unlockComponent(parent.getUniqueId(), nodeType);
3666 // graphLockOperation.unlockComponent(parentId, parentType);
3670 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateHeatEnvParams(String componentId, String artifactId, ArtifactDefinition artifactInfo, User user, AuditingActionEnum auditingAction, Component parent,
3671 ComponentTypeEnum componentType, ArtifactDefinition currArtifact1, String origMd5, boolean inTransaction) {
3673 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
3674 Either<ArtifactDefinition, Operation> insideEither = null;
3676 * currently getArtifactById does not retrieve heatParameters Either<ArtifactDefinition, StorageOperationStatus> artifactRes = artifactOperation.getArtifactById(artifactId, false); ArtifactDefinition currArtifact = artifactRes.left().value();
3678 Either<ComponentInstance, ResponseFormat> getRI = getRIFromComponent(parent, componentId, artifactId, auditingAction, user);
3679 if (getRI.isRight()) {
3680 return Either.right(getRI.right().value());
3682 ComponentInstance ri = getRI.left().value();
3683 Either<ArtifactDefinition, ResponseFormat> getArtifactRes = getArtifactFromRI(parent, ri, componentId, artifactId, auditingAction, user);
3684 if (getArtifactRes.isRight()) {
3685 return Either.right(getArtifactRes.right().value());
3687 ArtifactDefinition currArtifact = getArtifactRes.left().value();
3689 if (currArtifact.getArtifactType().equals(ArtifactTypeEnum.HEAT.getType()) || currArtifact.getArtifactType().equals(ArtifactTypeEnum.HEAT_VOL.getType()) || currArtifact.getArtifactType().equals(ArtifactTypeEnum.HEAT_NET.getType())) {
3690 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION);
3691 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
3692 return Either.right(responseFormat);
3694 List<HeatParameterDefinition> currentHeatEnvParams = currArtifact.getListHeatParameters();
3695 List<HeatParameterDefinition> updatedHeatEnvParams = artifactInfo.getListHeatParameters();
3696 new ArrayList<HeatParameterDefinition>();
3699 if (origMd5 != null) {
3700 Either<List<HeatParameterDefinition>, ResponseFormat> uploadParamsValidationResult = validateUploadParamsFromEnvFile(auditingAction, parent, user, artifactInfo, artifactId, componentType, ri.getName(), currentHeatEnvParams,
3701 updatedHeatEnvParams, currArtifact.getArtifactName());
3702 if (uploadParamsValidationResult.isRight()) {
3703 ResponseFormat responseFormat = uploadParamsValidationResult.right().value();
3704 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
3705 return Either.right(responseFormat);
3707 artifactInfo.setListHeatParameters(updatedHeatEnvParams);
3710 Either<ArtifactDefinition, ResponseFormat> validateAndConvertHeatParamers = validateAndConvertHeatParamers(artifactInfo, ArtifactTypeEnum.HEAT_ENV.getType());
3711 if (validateAndConvertHeatParamers.isRight()) {
3712 ResponseFormat responseFormat = validateAndConvertHeatParamers.right().value();
3713 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
3714 return Either.right(responseFormat);
3717 if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty()) {
3719 // fill reduced heat env parameters List for updating
3720 for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) {
3721 paramName = heatEnvParam.getName();
3722 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
3723 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
3724 String updatedParamValue = heatEnvParam.getCurrentValue();
3725 if (updatedParamValue != null && updatedParamValue.equals("")) { // reset
3726 currHeatParam.setCurrentValue(heatEnvParam.getDefaultValue());
3727 } else if (updatedParamValue != null) {
3728 currHeatParam.setCurrentValue(updatedParamValue);
3733 currArtifact.setHeatParamsUpdateDate(System.currentTimeMillis());
3734 currArtifact.setListHeatParameters(currentHeatEnvParams);
3736 Either<ArtifactDefinition, StorageOperationStatus> updateArifactRes = artifactToscaOperation.updateArifactOnResource(currArtifact, parent.getUniqueId(), currArtifact.getUniqueId(), componentType.getNodeType(), componentId);
3737 if (updateArifactRes.isRight()) {
3738 log.debug("Failed to update artifact on graph - {}", artifactId);
3739 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateArifactRes.right().value()));
3740 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
3741 return Either.right(responseFormat);
3743 StorageOperationStatus error = generateCustomizationUUIDOnInstance(parent.getUniqueId(), ri.getUniqueId(), componentType);
3744 if (error != StorageOperationStatus.OK) {
3745 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
3746 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
3747 return Either.right(responseFormat);
3750 error = generateCustomizationUUIDOnGroupInstance(ri, updateArifactRes.left().value().getUniqueId(), parent.getUniqueId());
3751 if (error != StorageOperationStatus.OK) {
3752 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(error));
3753 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, ri.getName());
3754 return Either.right(responseFormat);
3760 insideEither = Either.left(currArtifact);
3761 resultOp = Either.left(insideEither);
3762 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
3763 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currArtifact, null, artifactId, responseFormat, componentType, ri.getName());
3767 private Either<Either<ArtifactDefinition, Operation>, ResponseFormat> updateHeatParams(String componentId, String artifactId, ArtifactDefinition artifactEnvInfo, User user, AuditingActionEnum auditingAction, Component parent,
3768 ComponentTypeEnum componentType, ArtifactDefinition currHeatArtifact, String origMd5) {
3770 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> resultOp = null;
3771 Either<ArtifactDefinition, Operation> insideEither = null;
3773 * currently getArtifactById does not retrieve heatParameters Either<ArtifactDefinition, StorageOperationStatus> artifactRes = artifactOperation.getArtifactById(artifactId, false); ArtifactDefinition currArtifact = artifactRes.left().value();
3775 String currentHeatId = currHeatArtifact.getUniqueId();
3776 ArtifactDefinition updatedHeatArt = currHeatArtifact;
3778 List<HeatParameterDefinition> updatedHeatEnvParams = artifactEnvInfo.getListHeatParameters();
3779 List<HeatParameterDefinition> currentHeatEnvParams = currHeatArtifact.getListHeatParameters();
3780 List<HeatParameterDefinition> newHeatEnvParams = new ArrayList<HeatParameterDefinition>();
3782 if (updatedHeatEnvParams != null && !updatedHeatEnvParams.isEmpty() && currentHeatEnvParams != null && !currentHeatEnvParams.isEmpty()) {
3785 for (HeatParameterDefinition heatEnvParam : updatedHeatEnvParams) {
3787 paramName = heatEnvParam.getName();
3788 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
3789 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
3791 String updatedParamValue = heatEnvParam.getCurrentValue();
3792 if (updatedParamValue == null)
3793 updatedParamValue = heatEnvParam.getDefaultValue();
3794 HeatParameterType paramType = HeatParameterType.isValidType(currHeatParam.getType());
3795 if (!paramType.getValidator().isValid(updatedParamValue, null)) {
3796 ActionStatus status = ActionStatus.INVALID_HEAT_PARAMETER_VALUE;
3797 ResponseFormat responseFormat = componentsUtils.getResponseFormat(status, ArtifactTypeEnum.HEAT_ENV.getType(), paramType.getType(), paramName);
3798 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactEnvInfo, null, artifactId, responseFormat, componentType, "");
3799 return Either.right(responseFormat);
3802 currHeatParam.setCurrentValue(paramType.getConverter().convert(updatedParamValue, null, null));
3803 newHeatEnvParams.add(currHeatParam);
3808 if (!newHeatEnvParams.isEmpty()) {
3809 currHeatArtifact.setListHeatParameters(currentHeatEnvParams);
3810 Either<ArtifactDefinition, StorageOperationStatus> operationStatus = artifactToscaOperation.updateArifactOnResource(currHeatArtifact, parent.getUniqueId(), currHeatArtifact.getUniqueId(), componentType.getNodeType(), componentId);
3812 if (operationStatus.isRight()) {
3813 log.debug("Failed to update artifact on graph - {}", currHeatArtifact.getUniqueId());
3815 ResponseFormat responseFormat = componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(operationStatus.right().value()));
3816 return Either.right(responseFormat);
3819 updatedHeatArt = operationStatus.left().value();
3820 insideEither = Either.left(updatedHeatArt);
3824 if (!currentHeatId.equals(updatedHeatArt.getUniqueId())) {
3825 artifactEnvInfo.setArtifactChecksum(null);
3826 artifactToscaOperation.updateHeatEnvArtifact(parent.getUniqueId(), artifactEnvInfo, currentHeatId, updatedHeatArt.getUniqueId(), componentType.getNodeType(), componentId);
3828 artifactToscaOperation.updateHeatEnvPlaceholder(artifactEnvInfo, componentId, componentType.getNodeType());
3831 resultOp = Either.left(insideEither);
3832 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.OK);
3833 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, currHeatArtifact, null, artifactId, responseFormat, componentType, "");
3838 private StorageOperationStatus generateCustomizationUUIDOnGroupInstance(ComponentInstance ri, String artifactId, String componentId) {
3839 StorageOperationStatus error = StorageOperationStatus.OK;
3840 log.debug("Need to re-generate customization UUID for group instance on component instance {}", ri.getUniqueId());
3841 List<GroupInstance> groupsInstances = ri.getGroupInstances();
3842 // List<GroupInstance> associatedGroups = null;
3843 List<String> groupInstancesId = null;
3844 if (groupsInstances != null && !groupsInstances.isEmpty()) {
3845 groupInstancesId = groupsInstances.stream().filter(p -> p.getGroupInstanceArtifacts() != null && p.getGroupInstanceArtifacts().contains(artifactId)).map(p -> p.getUniqueId()).collect(Collectors.toList());
3847 if (groupInstancesId != null && !groupInstancesId.isEmpty()) {
3848 // associatedGroups.stream().forEach(c -> this.groupInstanceOperation.updateCustomizationUUID(c.getUniqueId()));
3849 toscaOperationFacade.generateCustomizationUUIDOnInstanceGroup(componentId, ri.getUniqueId(), groupInstancesId);
3855 public Either<List<HeatParameterDefinition>, ResponseFormat> validateUploadParamsFromEnvFile(AuditingActionEnum auditingAction, Component parent, User user, ArtifactDefinition artifactInfo, String artifactId, ComponentTypeEnum componentType,
3856 String riName, List<HeatParameterDefinition> currentHeatEnvParams, List<HeatParameterDefinition> updatedHeatEnvParams, String currArtifactName) {
3858 if (updatedHeatEnvParams == null || updatedHeatEnvParams.isEmpty()) {
3859 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.INVALID_DEPLOYMENT_ARTIFACT_HEAT, artifactInfo.getArtifactName(), currArtifactName);
3860 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, riName);
3861 return Either.right(responseFormat);
3864 for (HeatParameterDefinition uploadedHeatParam : updatedHeatEnvParams) {
3865 String paramName = uploadedHeatParam.getName();
3866 boolean isExistsInHeat = false;
3867 for (HeatParameterDefinition currHeatParam : currentHeatEnvParams) {
3868 if (paramName.equalsIgnoreCase(currHeatParam.getName())) {
3870 isExistsInHeat = true;
3871 uploadedHeatParam.setType(currHeatParam.getType());
3872 uploadedHeatParam.setCurrentValue(uploadedHeatParam.getDefaultValue());
3873 uploadedHeatParam.setDefaultValue(currHeatParam.getDefaultValue());
3874 uploadedHeatParam.setUniqueId(currHeatParam.getUniqueId());
3878 if (!isExistsInHeat) {
3879 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.MISMATCH_HEAT_VS_HEAT_ENV, currArtifactName);
3880 handleAuditing(auditingAction, parent, parent.getUniqueId(), user, artifactInfo, null, artifactId, responseFormat, componentType, riName);
3881 return Either.right(responseFormat);
3884 return Either.left(updatedHeatEnvParams);
3887 private Either<ComponentInstance, ResponseFormat> getRIFromComponent(Component component, String riID, String artifactId, AuditingActionEnum auditingAction, User user) {
3888 ResponseFormat responseFormat = null;
3889 List<ComponentInstance> ris = component.getComponentInstances();
3890 for (ComponentInstance ri : ris) {
3891 if (riID.equals(ri.getUniqueId())) {
3892 return Either.left(ri);
3895 responseFormat = componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, riID);
3896 log.debug("Resource Instance not found, resourceInstanceId {}", riID);
3897 handleAuditing(auditingAction, null, riID, user, null, null, artifactId, responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE, null);
3898 return Either.right(responseFormat);
3901 private Either<ArtifactDefinition, ResponseFormat> getArtifactFromRI(Component component, ComponentInstance ri, String riID, String artifactId, AuditingActionEnum auditingAction, User user) {
3902 ResponseFormat responseFormat = null;
3903 Map<String, ArtifactDefinition> rtifactsMap = ri.getDeploymentArtifacts();
3904 for (ArtifactDefinition artifact : rtifactsMap.values()) {
3905 if (artifactId.equals(artifact.getUniqueId())) {
3906 return Either.left(artifact);
3909 responseFormat = componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, riID, component.getUniqueId());
3910 handleAuditing(auditingAction, component, riID, user, null, null, artifactId, responseFormat, ComponentTypeEnum.RESOURCE_INSTANCE, ri.getName());
3911 return Either.right(responseFormat);
3914 public ArtifactDefinition extractArtifactDefinition(Either<ArtifactDefinition, Operation> eitherArtifact) {
3915 ArtifactDefinition ret;
3916 if (eitherArtifact.isLeft()) {
3917 ret = eitherArtifact.left().value();
3919 ret = eitherArtifact.right().value().getImplementationArtifact();
3925 * downloads artifact of component by UUIDs
3927 * @param componentType
3928 * @param componentUuid
3929 * @param artifactUUID
3930 * @param auditAdditionalParam
3933 public Either<byte[], ResponseFormat> downloadComponentArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String artifactUUID, Map<AuditingFieldsKeysEnum, Object> auditAdditionalParam) {
3934 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
3935 Either<byte[], ResponseFormat> result;
3936 byte[] downloadedArtifact = null;
3937 Component component = getLatestComponentByUuid(componentType, componentUuid, errorWrapper);
3938 if (errorWrapper.isEmpty()) {
3939 auditAdditionalParam.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, component.getName());
3940 downloadedArtifact = downloadArtifact(component.getDeploymentArtifacts(), artifactUUID, errorWrapper, component.getName());
3942 if (errorWrapper.isEmpty()) {
3943 result = Either.left(downloadedArtifact);
3945 result = Either.right(errorWrapper.getInnerElement());
3951 * downloads an artifact of resource instance of component by UUIDs
3953 * @param componentType
3954 * @param componentUuid
3955 * @param resourceName
3956 * @param artifactUUID
3957 * @param auditAdditionalParam
3960 public Either<byte[], ResponseFormat> downloadResourceInstanceArtifactByUUIDs(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID, Map<AuditingFieldsKeysEnum, Object> auditAdditionalParam) {
3961 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
3962 Either<byte[], ResponseFormat> result;
3963 byte[] downloadedArtifact = null;
3964 ComponentInstance resourceInstance = getRelatedComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
3965 if (errorWrapper.isEmpty()) {
3966 downloadedArtifact = downloadArtifact(resourceInstance.getDeploymentArtifacts(), artifactUUID, errorWrapper, resourceInstance.getName());
3968 if (errorWrapper.isEmpty()) {
3969 result = Either.left(downloadedArtifact);
3971 result = Either.right(errorWrapper.getInnerElement());
3977 * uploads an artifact to a component by UUID
3981 * @param componentType
3982 * @param componentUuid
3983 * @param additionalParams
3987 public Either<ArtifactDefinition, ResponseFormat> uploadArtifactToComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, Map<AuditingFieldsKeysEnum, Object> additionalParams,
3988 ArtifactOperationInfo operation) {
3989 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
3990 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
3991 Either<ArtifactDefinition, ResponseFormat> uploadArtifactResult;
3992 ArtifactDefinition uploadArtifact = null;
3993 Component component = null;
3994 String componentId = null;
3995 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
3996 String origMd5 = request.getHeader(Constants.MD5_HEADER);
3997 String userId = request.getHeader(Constants.USER_ID_HEADER);
3999 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4000 if (getComponentRes.isRight()) {
4001 StorageOperationStatus status = getComponentRes.right().value();
4002 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4003 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), componentUuid));
4005 if (errorWrapper.isEmpty()) {
4006 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
4007 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
4009 if (!getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4010 component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
4011 if (component != null) {
4012 componentId = component.getUniqueId();
4013 componentName = component.getName();
4016 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentName);
4018 if (errorWrapper.isEmpty()) {
4019 actionResult = handleArtifactRequest(componentId, userId, componentType, operation, null, artifactInfo, origMd5, data, null, null, null, null);
4020 if (actionResult.isRight()) {
4021 log.debug("Failed to upload artifact to component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, actionResult.right().value());
4022 errorWrapper.setInnerElement(actionResult.right().value());
4025 if (errorWrapper.isEmpty()) {
4026 uploadArtifact = actionResult.left().value().left().value();
4027 uploadArtifactResult = Either.left(uploadArtifact);
4029 uploadArtifactResult = Either.right(errorWrapper.getInnerElement());
4031 updateAuditParametersWithArtifactDefinition(additionalParams, uploadArtifact);
4032 return uploadArtifactResult;
4036 * upload an artifact to a resource instance by UUID
4040 * @param componentType
4041 * @param componentUuid
4042 * @param resourceInstanceName
4043 * @param additionalParams
4047 public Either<ArtifactDefinition, ResponseFormat> uploadArtifactToRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName,
4048 Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
4049 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4050 Either<ArtifactDefinition, ResponseFormat> uploadArtifactResult;
4051 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4052 ArtifactDefinition uploadArtifact = null;
4053 Component component = null;
4054 String componentInstanceId;
4056 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4057 String userId = request.getHeader(Constants.USER_ID_HEADER);
4059 ImmutablePair<Component, ComponentInstance> componentRiPair = null;
4060 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4061 if (getComponentRes.isRight()) {
4062 StorageOperationStatus status = getComponentRes.right().value();
4063 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4064 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), resourceInstanceName));
4066 if (errorWrapper.isEmpty() && !getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4067 component = checkoutParentComponent(componentType, getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(), userId, errorWrapper);
4069 if (errorWrapper.isEmpty()) {
4070 if (component == null) {
4071 componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
4073 componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
4076 if (errorWrapper.isEmpty()) {
4077 componentInstanceId = componentRiPair.getRight().getUniqueId();
4078 componentId = componentRiPair.getLeft().getUniqueId();
4079 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
4081 actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, null, artifactInfo, origMd5, data, null, null, componentId, ComponentTypeEnum.findParamByType(componentType));
4082 if (actionResult.isRight()) {
4083 log.debug("Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. ", resourceInstanceName, componentType, componentUuid, actionResult.right().value());
4084 errorWrapper.setInnerElement(actionResult.right().value());
4087 if (errorWrapper.isEmpty()) {
4088 uploadArtifact = actionResult.left().value().left().value();
4089 uploadArtifactResult = Either.left(uploadArtifact);
4091 uploadArtifactResult = Either.right(errorWrapper.getInnerElement());
4093 updateAuditParametersWithArtifactDefinition(additionalParams, uploadArtifact);
4094 return uploadArtifactResult;
4098 * updates an artifact on a component by UUID
4102 * @param componentType
4103 * @param componentUuid
4104 * @param artifactUUID
4105 * @param additionalParams
4110 public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnComponentByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID,
4111 Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
4112 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4113 Either<ArtifactDefinition, ResponseFormat> updateArtifactResult;
4114 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4115 ArtifactDefinition updateArtifact = null;
4116 Component component = null;
4117 String componentId = null;
4118 String artifactId = null;
4119 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
4120 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4121 String userId = request.getHeader(Constants.USER_ID_HEADER);
4123 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4124 if (getComponentRes.isRight()) {
4125 StorageOperationStatus status = getComponentRes.right().value();
4126 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4127 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4129 if (errorWrapper.isEmpty()) {
4130 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
4131 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
4133 if (!getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4134 component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
4135 if (component != null) {
4136 componentId = component.getUniqueId();
4137 componentName = component.getName();
4140 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentName);
4142 if (errorWrapper.isEmpty()) {
4143 artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentId, componentType);
4145 if (errorWrapper.isEmpty()) {
4146 actionResult = handleArtifactRequest(componentId, userId, componentType, operation, artifactId, artifactInfo, origMd5, data, null, null, null, null);
4147 if (actionResult.isRight()) {
4148 log.debug("Failed to upload artifact to component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, actionResult.right().value());
4149 errorWrapper.setInnerElement(actionResult.right().value());
4152 if (errorWrapper.isEmpty()) {
4153 updateArtifact = actionResult.left().value().left().value();
4154 updateArtifactResult = Either.left(updateArtifact);
4157 updateArtifactResult = Either.right(errorWrapper.getInnerElement());
4159 updateAuditParametersWithArtifactDefinition(additionalParams, updateArtifact);
4160 return updateArtifactResult;
4164 * updates an artifact on a resource instance by UUID
4168 * @param componentType
4169 * @param componentUuid
4170 * @param resourceInstanceName
4171 * @param artifactUUID
4172 * @param additionalParams
4177 public Either<ArtifactDefinition, ResponseFormat> updateArtifactOnRiByUUID(String data, HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID,
4178 Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
4180 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4181 Either<ArtifactDefinition, ResponseFormat> updateArtifactResult;
4182 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4183 ArtifactDefinition updateArtifact = null;
4184 Component component = null;
4185 String componentInstanceId = null;
4186 String componentId = null;
4187 String artifactId = null;
4188 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4189 String userId = request.getHeader(Constants.USER_ID_HEADER);
4191 ImmutablePair<Component, ComponentInstance> componentRiPair = null;
4192 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4193 if (getComponentRes.isRight()) {
4194 StorageOperationStatus status = getComponentRes.right().value();
4195 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4196 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4198 if (errorWrapper.isEmpty() && !getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4199 component = checkoutParentComponent(componentType, getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(), userId, errorWrapper);
4201 if (errorWrapper.isEmpty()) {
4202 if (component == null) {
4203 componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
4205 componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
4208 if (errorWrapper.isEmpty()) {
4209 componentInstanceId = componentRiPair.getRight().getUniqueId();
4210 componentId = componentRiPair.getLeft().getUniqueId();
4211 artifactId = findArtifactId(componentRiPair.getRight(), artifactUUID, errorWrapper);
4213 if (errorWrapper.isEmpty()) {
4214 ArtifactDefinition artifactInfo = RepresentationUtils.convertJsonToArtifactDefinition(data, ArtifactDefinition.class);
4216 actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, artifactInfo, origMd5, data, null, null, componentId, ComponentTypeEnum.findParamByType(componentType));
4217 if (actionResult.isRight()) {
4218 log.debug("Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. ", resourceInstanceName, componentType, componentUuid, actionResult.right().value());
4219 errorWrapper.setInnerElement(actionResult.right().value());
4222 if (errorWrapper.isEmpty()) {
4223 updateArtifact = actionResult.left().value().left().value();
4224 updateArtifactResult = Either.left(updateArtifact);
4226 updateArtifactResult = Either.right(errorWrapper.getInnerElement());
4228 updateAuditParametersWithArtifactDefinition(additionalParams, updateArtifact);
4229 return updateArtifactResult;
4233 * deletes an artifact on a component by UUID
4236 * @param componentType
4237 * @param componentUuid
4238 * @param artifactUUID
4239 * @param additionalParams
4244 public Either<ArtifactDefinition, ResponseFormat> deleteArtifactOnComponentByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String artifactUUID, Map<AuditingFieldsKeysEnum, Object> additionalParams,
4245 ArtifactOperationInfo operation) {
4247 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4248 Either<ArtifactDefinition, ResponseFormat> deleteArtifactResult;
4249 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4250 ArtifactDefinition deleteArtifact = null;
4251 Component component = null;
4252 String componentId = null;
4253 String artifactId = null;
4254 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4255 String userId = request.getHeader(Constants.USER_ID_HEADER);
4257 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4258 if (getComponentRes.isRight()) {
4259 StorageOperationStatus status = getComponentRes.right().value();
4260 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4261 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status, componentType), componentUuid));
4263 if (errorWrapper.isEmpty()) {
4264 componentId = getComponentRes.left().value().getMetadataDataDefinition().getUniqueId();
4265 String componentName = getComponentRes.left().value().getMetadataDataDefinition().getName();
4266 if (!getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4267 component = checkoutParentComponent(componentType, componentId, userId, errorWrapper);
4268 if (component != null) {
4269 componentId = component.getUniqueId();
4270 componentName = component.getName();
4273 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, componentName);
4275 if (errorWrapper.isEmpty()) {
4276 artifactId = getLatestParentArtifactDataIdByArtifactUUID(artifactUUID, errorWrapper, componentId, componentType);
4278 if (errorWrapper.isEmpty()) {
4279 actionResult = handleArtifactRequest(componentId, userId, componentType, operation, artifactId, null, origMd5, null, null, null, null, null);
4280 if (actionResult.isRight()) {
4281 log.debug("Failed to upload artifact to component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, actionResult.right().value());
4282 errorWrapper.setInnerElement(actionResult.right().value());
4285 if (errorWrapper.isEmpty()) {
4286 deleteArtifact = actionResult.left().value().left().value();
4287 deleteArtifactResult = Either.left(deleteArtifact);
4289 deleteArtifactResult = Either.right(errorWrapper.getInnerElement());
4291 updateAuditParametersWithArtifactDefinition(additionalParams, deleteArtifact);
4292 return deleteArtifactResult;
4296 * deletes an artifact from a resource instance by UUID
4299 * @param componentType
4300 * @param componentUuid
4301 * @param resourceInstanceName
4302 * @param artifactUUID
4303 * @param additionalParams
4308 public Either<ArtifactDefinition, ResponseFormat> deleteArtifactOnRiByUUID(HttpServletRequest request, ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, String artifactUUID,
4309 Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactOperationInfo operation) {
4311 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4312 Either<ArtifactDefinition, ResponseFormat> deleteArtifactResult;
4313 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult = null;
4314 ArtifactDefinition deleteArtifact = null;
4315 Component component = null;
4316 String componentInstanceId = null;
4317 String componentId = null;
4318 String artifactId = null;
4319 String origMd5 = request.getHeader(Constants.MD5_HEADER);
4320 String userId = request.getHeader(Constants.USER_ID_HEADER);
4321 ImmutablePair<Component, ComponentInstance> componentRiPair = null;
4322 Either<ComponentMetadataData, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentMetadataByUuid(componentUuid, JsonParseFlagEnum.ParseMetadata, true);
4323 if (getComponentRes.isRight()) {
4324 StorageOperationStatus status = getComponentRes.right().value();
4325 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4326 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4328 if (errorWrapper.isEmpty() && !getComponentRes.left().value().getMetadataDataDefinition().getState().equals(LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT.name())) {
4329 component = checkoutParentComponent(componentType, getComponentRes.left().value().getMetadataDataDefinition().getUniqueId(), userId, errorWrapper);
4331 if (errorWrapper.isEmpty()) {
4332 if (component == null) {
4333 componentRiPair = getRelatedComponentComponentInstance(componentType, componentUuid, resourceInstanceName, errorWrapper);
4335 componentRiPair = getRelatedComponentComponentInstance(component, resourceInstanceName, errorWrapper);
4338 if (errorWrapper.isEmpty()) {
4339 componentInstanceId = componentRiPair.getRight().getUniqueId();
4340 componentId = componentRiPair.getLeft().getUniqueId();
4341 artifactId = findArtifactId(componentRiPair.getRight(), artifactUUID, errorWrapper);
4343 if (errorWrapper.isEmpty()) {
4345 actionResult = handleArtifactRequest(componentInstanceId, userId, ComponentTypeEnum.RESOURCE_INSTANCE, operation, artifactId, null, origMd5, null, null, null, componentId, ComponentTypeEnum.findParamByType(componentType));
4347 if (actionResult.isRight()) {
4348 log.debug("Failed to upload artifact to component instance {} of component with type {} and uuid {}. Status is {}. ", resourceInstanceName, componentType, componentUuid, actionResult.right().value());
4349 errorWrapper.setInnerElement(actionResult.right().value());
4352 if (errorWrapper.isEmpty()) {
4353 deleteArtifact = actionResult.left().value().left().value();
4354 deleteArtifactResult = Either.left(deleteArtifact);
4356 deleteArtifactResult = Either.right(errorWrapper.getInnerElement());
4358 updateAuditParametersWithArtifactDefinition(additionalParams, deleteArtifact);
4359 return deleteArtifactResult;
4362 private String findArtifactId(ComponentInstance instance, String artifactUUID, Wrapper<ResponseFormat> errorWrapper) {
4363 String artifactId = null;
4364 ArtifactDefinition foundArtifact = null;
4365 if (instance.getDeploymentArtifacts() != null) {
4366 foundArtifact = instance.getDeploymentArtifacts().values().stream().filter(e -> e.getArtifactUUID() != null && e.getArtifactUUID().equals(artifactUUID)).findFirst().orElse(null);
4368 if (foundArtifact == null && instance.getArtifacts() != null) {
4369 foundArtifact = instance.getArtifacts().values().stream().filter(e -> e.getArtifactUUID() != null && e.getArtifactUUID().equals(artifactUUID)).findFirst().orElse(null);
4371 if (foundArtifact == null) {
4372 log.debug("The artifact {} was not found on instance {}. ", artifactUUID, instance.getUniqueId());
4373 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactUUID));
4375 artifactId = foundArtifact.getUniqueId();
4380 public Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder(ArtifactDefinition artifact, String envType, String parentId, NodeTypeEnum parentType, String parentName, User user, Component component,
4381 Map<String, String> existingEnvVersions) {
4382 return createHeatEnvPlaceHolder(artifact, envType, parentId, parentType, parentName, user, component, existingEnvVersions, true);
4386 @SuppressWarnings("unchecked")
4387 public Either<ArtifactDefinition, ResponseFormat> createHeatEnvPlaceHolder(ArtifactDefinition artifact, String envType, String parentId, NodeTypeEnum parentType, String parentName, User user, Component component,
4388 Map<String, String> existingEnvVersions, boolean overrideId) {
4389 Map<String, Object> deploymentResourceArtifacts = ConfigurationManager.getConfigurationManager().getConfiguration().getDeploymentResourceInstanceArtifacts();
4390 if (deploymentResourceArtifacts == null) {
4391 log.debug("no deployment artifacts are configured for generated artifacts");
4392 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
4394 Map<String, Object> placeHolderData = (Map<String, Object>) deploymentResourceArtifacts.get(envType);
4395 if (placeHolderData == null) {
4396 log.debug("no env type {} are configured for generated artifacts", envType);
4397 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
4400 String envLabel = (artifact.getArtifactLabel() + HEAT_ENV_SUFFIX).toLowerCase();
4401 String parentIdParam = parentId;
4403 parentIdParam = null;
4405 Either<ArtifactDefinition, ResponseFormat> createArtifactPlaceHolder = createArtifactPlaceHolderInfo(parentIdParam, envLabel, placeHolderData, user.getUserId(), ArtifactGroupTypeEnum.DEPLOYMENT, true);
4406 if (createArtifactPlaceHolder.isRight()) {
4407 return Either.right(createArtifactPlaceHolder.right().value());
4409 ArtifactDefinition artifactHeatEnv = createArtifactPlaceHolder.left().value();
4411 // fix for migration only!!!! create heat env placeholder according to heat id.
4412 artifactHeatEnv.setUniqueId(artifact.getUniqueId() + HEAT_ENV_SUFFIX);
4415 artifactHeatEnv.setGeneratedFromId(artifact.getUniqueId());
4416 artifactHeatEnv.setHeatParamsUpdateDate(System.currentTimeMillis());
4417 artifactHeatEnv.setTimeout(0);
4418 buildHeatEnvFileName(artifact, artifactHeatEnv, placeHolderData);
4419 // rbetzer - keep env artifactVersion - changeComponentInstanceVersion flow
4420 handleEnvArtifactVersion(artifactHeatEnv, existingEnvVersions);
4421 // clone heat parameters in case of heat env only not VF heat env
4422 if (envType.equals(HEAT_ENV_NAME)) {
4423 artifactHeatEnv.setHeatParameters(artifact.getHeatParameters());
4425 ArtifactDefinition artifactDefinition;
4426 // Evg : for resource instance artifact will be added later as block with other env artifacts from BL
4427 if (parentType != NodeTypeEnum.ResourceInstance) {
4428 Either<ArtifactDefinition, StorageOperationStatus> addHeatEnvArtifact = addHeatEnvArtifact(artifactHeatEnv, artifact, component.getUniqueId(), parentType, parentId);
4429 if (addHeatEnvArtifact.isRight()) {
4430 log.debug("failed to create heat env artifact on resource instance");
4431 return Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(addHeatEnvArtifact.right().value(), false), "", null));
4433 artifactDefinition = createArtifactPlaceHolder.left().value();
4435 artifactDefinition = artifactHeatEnv;
4436 artifactToscaOperation.generateUUID(artifactDefinition, artifactDefinition.getArtifactVersion());
4439 if (artifact.getHeatParameters() != null) {
4440 List<HeatParameterDefinition> heatEnvParameters = new ArrayList<HeatParameterDefinition>();
4441 for (HeatParameterDefinition parameter : artifact.getListHeatParameters()) {
4442 HeatParameterDefinition heatEnvParameter = new HeatParameterDefinition(parameter);
4443 heatEnvParameter.setDefaultValue(parameter.getCurrentValue());
4444 heatEnvParameters.add(heatEnvParameter);
4446 artifactDefinition.setListHeatParameters(heatEnvParameters);
4450 EnumMap<AuditingFieldsKeysEnum, Object> artifactAuditingFields = createArtifactAuditingFields(artifactDefinition, "", artifactDefinition.getUniqueId());
4451 artifactAuditingFields.put(AuditingFieldsKeysEnum.AUDIT_RESOURCE_NAME, parentName);
4452 ComponentTypeEnum componentType = component.getComponentType();
4453 if (parentType == NodeTypeEnum.ResourceInstance) {
4454 componentType = ComponentTypeEnum.RESOURCE_INSTANCE;
4456 componentsUtils.auditComponent(componentsUtils.getResponseFormat(ActionStatus.OK), user, component, "", "", AuditingActionEnum.ARTIFACT_UPLOAD, componentType, artifactAuditingFields);
4457 return Either.left(artifactDefinition);
4460 private void buildHeatEnvFileName(ArtifactDefinition heatArtifact, ArtifactDefinition heatEnvArtifact, Map<String, Object> placeHolderData) {
4461 String heatExtension = GeneralUtility.getFilenameExtension(heatArtifact.getArtifactName());
4462 String envExtension = (String) placeHolderData.get(ARTIFACT_PLACEHOLDER_FILE_EXTENSION);
4463 String name = heatArtifact.getArtifactName();
4466 name = heatArtifact.getArtifactLabel();
4467 fileName = name + "." + envExtension;
4469 fileName = name.replaceAll("." + heatExtension, "." + envExtension);
4471 heatEnvArtifact.setArtifactName(fileName);
4474 private void handleEnvArtifactVersion(ArtifactDefinition heatEnvArtifact, Map<String, String> existingEnvVersions) {
4475 if (null != existingEnvVersions) {
4476 String prevVersion = existingEnvVersions.get(heatEnvArtifact.getArtifactName());
4477 if (null != prevVersion) {
4478 heatEnvArtifact.setArtifactVersion(prevVersion);
4484 * Handles Artifacts Request For Inner Component
4486 * @param artifactsToHandle
4489 * @param vfcsNewCreatedArtifacts
4492 * @param inTransaction
4495 public Either<List<ArtifactDefinition>, ResponseFormat> handleArtifactsRequestForInnerVfcComponent(List<ArtifactDefinition> artifactsToHandle, Resource component, User user, List<ArtifactDefinition> vfcsNewCreatedArtifacts,
4496 ArtifactOperationInfo operation, boolean shouldLock, boolean inTransaction) {
4498 Either<List<ArtifactDefinition>, ResponseFormat> handleArtifactsResult = null;
4499 ComponentTypeEnum componentType = component.getComponentType();
4500 List<ArtifactDefinition> uploadedArtifacts = new ArrayList<>();
4501 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
4502 Either<Either<ArtifactDefinition, Operation>, ResponseFormat> actionResult;
4506 for (ArtifactDefinition artifact : artifactsToHandle) {
4507 originData = buildJsonStringForCsarVfcArtifact(artifact);
4508 origMd5 = GeneralUtility.calculateMD5ByString(originData);
4509 actionResult = handleArtifactRequest(component.getUniqueId(), user.getUserId(), componentType, operation, artifact.getUniqueId(), artifact, origMd5, originData, null, null, null, null, shouldLock, inTransaction);
4510 if (actionResult.isRight()) {
4511 log.debug("Failed to upload artifact to component with type {} and name {}. Status is {}. ", componentType, component.getName(), actionResult.right().value());
4512 errorWrapper.setInnerElement(actionResult.right().value());
4513 if (operation.getArtifactOperationEnum() == ArtifactOperationEnum.Create) {
4514 vfcsNewCreatedArtifacts.addAll(uploadedArtifacts);
4518 uploadedArtifacts.add(actionResult.left().value().left().value());
4520 if (errorWrapper.isEmpty()) {
4521 handleArtifactsResult = Either.left(uploadedArtifacts);
4523 handleArtifactsResult = Either.right(errorWrapper.getInnerElement());
4525 } catch (Exception e) {
4526 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR);
4527 handleArtifactsResult = Either.right(responseFormat);
4528 log.debug("Exception occured when handleArtifactsRequestForInnerVfcComponent, error is:{}", e.getMessage(), e);
4530 return handleArtifactsResult;
4533 private ComponentInstance getRelatedComponentInstance(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
4534 ComponentInstance componentInstance = null;
4535 String normalizedName = ValidationUtils.normalizeComponentInstanceName(resourceInstanceName);
4536 Component component = getLatestComponentByUuid(componentType, componentUuid, errorWrapper);
4537 if (errorWrapper.isEmpty()) {
4538 componentInstance = component.getComponentInstances().stream().filter(ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName()).equals(normalizedName)).findFirst().orElse(null);
4539 if (componentInstance == null) {
4540 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, "resource instance", component.getComponentType().getValue(), component.getName()));
4541 log.debug("Component instance {} was not found for component {}", resourceInstanceName, component.getName());
4544 return componentInstance;
4547 private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(Component component, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
4549 ImmutablePair<Component, ComponentInstance> relatedComponentComponentInstancePair = null;
4550 String normalizedName = ValidationUtils.normalizeComponentInstanceName(resourceInstanceName);
4551 ComponentInstance componentInstance = component.getComponentInstances().stream().filter(ci -> ValidationUtils.normalizeComponentInstanceName(ci.getName()).equals(normalizedName)).findFirst().orElse(null);
4552 if (componentInstance == null) {
4553 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, "resource instance", component.getComponentType().getValue(), component.getName()));
4554 log.debug("Component instance {} was not found for component {}", resourceInstanceName, component.getName());
4556 relatedComponentComponentInstancePair = new ImmutablePair<>(component, componentInstance);
4558 return relatedComponentComponentInstancePair;
4561 private ImmutablePair<Component, ComponentInstance> getRelatedComponentComponentInstance(ComponentTypeEnum componentType, String componentUuid, String resourceInstanceName, Wrapper<ResponseFormat> errorWrapper) {
4562 ComponentInstance componentInstance;
4563 ImmutablePair<Component, ComponentInstance> relatedComponentComponentInstancePair = null;
4564 Component component = getLatestComponentByUuid(componentType, componentUuid, errorWrapper);
4565 if (errorWrapper.isEmpty()) {
4566 componentInstance = component.getComponentInstances().stream().filter(ci -> ci.getNormalizedName().equals(resourceInstanceName)).findFirst().orElse(null);
4567 if (componentInstance == null) {
4568 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, resourceInstanceName, "resource instance", component.getComponentType().getValue(), component.getName()));
4569 log.debug("Component instance {} was not found for component {}", resourceInstanceName, component.getName());
4571 relatedComponentComponentInstancePair = new ImmutablePair<>(component, componentInstance);
4574 return relatedComponentComponentInstancePair;
4577 private byte[] downloadArtifact(Map<String, ArtifactDefinition> artifacts, String artifactUUID, Wrapper<ResponseFormat> errorWrapper, String componentName) {
4579 byte[] downloadedArtifact = null;
4580 Either<ImmutablePair<String, byte[]>, ResponseFormat> downloadArtifactEither = null;
4581 List<ArtifactDefinition> deploymentArtifacts = null;
4582 ArtifactDefinition deploymentArtifact = null;
4583 if (artifacts != null && !artifacts.isEmpty()) {
4584 deploymentArtifacts = artifacts.values().stream().filter(art -> art.getArtifactUUID() != null && art.getArtifactUUID().equals(artifactUUID)).collect(Collectors.toList());
4586 if (deploymentArtifacts == null || deploymentArtifacts.isEmpty()) {
4587 log.debug("Deployment artifact with uuid {} was not found for component {}", artifactUUID, componentName);
4588 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(ActionStatus.ARTIFACT_NOT_FOUND, artifactUUID));
4590 if (errorWrapper.isEmpty()) {
4591 deploymentArtifact = deploymentArtifacts.get(0);
4592 downloadArtifactEither = downloadArtifact(deploymentArtifact);
4593 if (downloadArtifactEither.isRight()) {
4594 log.debug("Failed to download artifact {}. ", deploymentArtifact.getArtifactName());
4595 errorWrapper.setInnerElement(downloadArtifactEither.right().value());
4598 if (errorWrapper.isEmpty()) {
4599 log.trace("Succeeded to download artifact with uniqueId {}", deploymentArtifact.getUniqueId());
4600 downloadedArtifact = downloadArtifactEither.left().value().getRight();
4602 return downloadedArtifact;
4605 private Component getLatestComponentByUuid(ComponentTypeEnum componentType, String componentUuid, Wrapper<ResponseFormat> errorWrapper) {
4606 Component component = null;
4607 Either<Component, StorageOperationStatus> getComponentRes = toscaOperationFacade.getLatestComponentByUuid(componentUuid);
4608 if (getComponentRes.isRight()) {
4609 StorageOperationStatus status = getComponentRes.right().value();
4610 log.debug("Could not fetch component with type {} and uuid {}. Status is {}. ", componentType, componentUuid, status);
4611 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(status)));
4613 component = getComponentRes.left().value();
4618 private String getLatestParentArtifactDataIdByArtifactUUID(String artifactUUID, Wrapper<ResponseFormat> errorWrapper, String parentId, ComponentTypeEnum componentType) {
4619 String artifactId = null;
4620 ActionStatus actionStatus = ActionStatus.ARTIFACT_NOT_FOUND;
4621 StorageOperationStatus storageStatus;
4622 ArtifactDefinition latestArtifact = null;
4623 List<ArtifactDefinition> artifacts = null;
4624 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getArtifactsRes = artifactToscaOperation.getArtifacts(parentId);
4625 if (getArtifactsRes.isRight()) {
4626 storageStatus = getArtifactsRes.right().value();
4627 log.debug("Couldn't fetch artifacts data for parent component {} with uid {}, error: {}", componentType.name(), parentId, storageStatus);
4628 if (!storageStatus.equals(StorageOperationStatus.NOT_FOUND)) {
4629 actionStatus = componentsUtils.convertFromStorageResponse(storageStatus);
4631 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
4633 if (errorWrapper.isEmpty()) {
4634 artifacts = getArtifactsRes.left().value().values().stream().filter(a -> a.getArtifactUUID() != null && a.getArtifactUUID().equals(artifactUUID)).collect(Collectors.toList());
4635 if (artifacts == null || artifacts.isEmpty()) {
4636 log.debug("Couldn't fetch artifact with UUID {} data for parent component {} with uid {}, error: {}", artifactUUID, componentType.name(), parentId, actionStatus);
4637 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
4640 if (errorWrapper.isEmpty()) {
4641 latestArtifact = artifacts.stream().max((a1, a2) -> {
4642 int compareRes = Double.compare(Double.parseDouble(a1.getArtifactVersion()), Double.parseDouble(a2.getArtifactVersion()));
4643 if (compareRes == 0) {
4644 compareRes = Long.compare(a1.getLastUpdateDate() == null ? 0 : a1.getLastUpdateDate(), a2.getLastUpdateDate() == null ? 0 : a2.getLastUpdateDate());
4648 if (latestArtifact == null) {
4649 log.debug("Couldn't fetch latest artifact with UUID {} data for parent component {} with uid {}, error: {}", artifactUUID, componentType.name(), parentId, actionStatus);
4650 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus, artifactUUID));
4653 if (errorWrapper.isEmpty()) {
4654 artifactId = latestArtifact.getUniqueId();
4659 private Component checkoutParentComponent(ComponentTypeEnum componentType, String parentId, String userId, Wrapper<ResponseFormat> errorWrapper) {
4661 Component component = null;
4662 Either<User, ActionStatus> getUserRes = userBusinessLogic.getUser(userId, false);
4663 if (getUserRes.isRight()) {
4664 log.debug("Could not fetch User of component {} with uid {} to checked out. Status is {}. ", componentType.getNodeType(), parentId, getUserRes.right().value());
4665 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(getUserRes.right().value()));
4667 if (errorWrapper.isEmpty()) {
4668 User modifier = getUserRes.left().value();
4669 LifecycleChangeInfoWithAction changeInfo = new LifecycleChangeInfoWithAction("External API checkout", LifecycleChanceActionEnum.UPDATE_FROM_EXTERNAL_API);
4670 Either<? extends Component, ResponseFormat> checkoutRes = lifecycleBusinessLogic.changeComponentState(componentType, parentId, modifier, LifeCycleTransitionEnum.CHECKOUT, changeInfo, false, true);
4671 if (checkoutRes.isRight()) {
4672 log.debug("Could not change state of component {} with uid {} to checked out. Status is {}. ", componentType.getNodeType(), parentId, checkoutRes.right().value().getStatus());
4673 errorWrapper.setInnerElement(checkoutRes.right().value());
4675 component = checkoutRes.left().value();
4681 private void updateAuditParametersWithArtifactDefinition(Map<AuditingFieldsKeysEnum, Object> additionalParams, ArtifactDefinition artifact) {
4682 if (artifact == null) {
4683 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, "");
4684 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, "");
4685 if (!additionalParams.containsKey(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID)) {
4686 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, "");
4689 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_CURR_ARTIFACT_UUID, artifact.getArtifactUUID());
4690 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_ARTIFACT_DATA, buildAuditingArtifactData(artifact));
4691 additionalParams.put(AuditingFieldsKeysEnum.AUDIT_MODIFIER_NAME, artifact.getUpdaterFullName());
4695 private String buildJsonStringForCsarVfcArtifact(ArtifactDefinition artifact) {
4696 Map<String, Object> json = new HashMap<>();
4697 String artifactName = artifact.getArtifactName();
4698 json.put(Constants.ARTIFACT_NAME, artifactName);
4699 json.put(Constants.ARTIFACT_LABEL, artifact.getArtifactLabel());
4700 json.put(Constants.ARTIFACT_TYPE, artifact.getArtifactType());
4701 json.put(Constants.ARTIFACT_GROUP_TYPE, ArtifactGroupTypeEnum.DEPLOYMENT.getType());
4702 json.put(Constants.ARTIFACT_DESCRIPTION, artifact.getDescription());
4703 json.put(Constants.ARTIFACT_PAYLOAD_DATA, artifact.getPayloadData());
4704 json.put(Constants.ARTIFACT_DISPLAY_NAME, artifact.getArtifactDisplayName());
4705 return gson.toJson(json);