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=========================================================
20 package org.openecomp.sdc.be.components.impl;
22 import static org.openecomp.sdc.be.components.attribute.GetOutputUtils.isGetOutputValueForOutput;
23 import static org.openecomp.sdc.be.components.property.GetInputUtils.isGetInputValueForInput;
24 import static org.openecomp.sdc.be.components.utils.PropertiesUtils.getPropertyCapabilityOfChildInstance;
26 import com.google.common.collect.Sets;
27 import fj.data.Either;
28 import java.util.ArrayList;
29 import java.util.Arrays;
30 import java.util.Collection;
31 import java.util.Collections;
32 import java.util.HashMap;
33 import java.util.Iterator;
34 import java.util.List;
36 import java.util.Map.Entry;
37 import java.util.Objects;
38 import java.util.Optional;
40 import java.util.UUID;
41 import java.util.stream.Collectors;
42 import org.apache.commons.collections.CollectionUtils;
43 import org.apache.commons.collections.MapUtils;
44 import org.apache.commons.lang3.StringUtils;
45 import org.apache.commons.lang3.tuple.ImmutablePair;
46 import org.json.JSONObject;
47 import org.onap.sdc.tosca.datatypes.model.PropertyType;
48 import org.openecomp.sdc.be.components.impl.exceptions.BusinessLogicException;
49 import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
50 import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException;
51 import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
52 import org.openecomp.sdc.be.components.impl.exceptions.ToscaGetFunctionExceptionSupplier;
53 import org.openecomp.sdc.be.components.impl.instance.ComponentInstanceChangeOperationOrchestrator;
54 import org.openecomp.sdc.be.components.impl.utils.DirectivesUtil;
55 import org.openecomp.sdc.be.components.merge.instance.ComponentInstanceMergeDataBusinessLogic;
56 import org.openecomp.sdc.be.components.merge.instance.DataForMergeHolder;
57 import org.openecomp.sdc.be.components.utils.PropertiesUtils;
58 import org.openecomp.sdc.be.components.validation.ComponentValidations;
59 import org.openecomp.sdc.be.config.BeEcompErrorManager;
60 import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
61 import org.openecomp.sdc.be.config.ConfigurationManager;
62 import org.openecomp.sdc.be.dao.api.ActionStatus;
63 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
64 import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
65 import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
66 import org.openecomp.sdc.be.datatypes.elements.CINodeFilterDataDefinition;
67 import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition;
68 import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition;
69 import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition;
70 import org.openecomp.sdc.be.datatypes.elements.GetOutputValueDataDefinition;
71 import org.openecomp.sdc.be.datatypes.elements.GetPolicyValueDataDefinition;
72 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
73 import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition;
74 import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
75 import org.openecomp.sdc.be.datatypes.elements.ToscaGetFunctionDataDefinition;
76 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
77 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
78 import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
79 import org.openecomp.sdc.be.datatypes.enums.PropertySource;
80 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
81 import org.openecomp.sdc.be.datatypes.tosca.ToscaGetFunctionType;
82 import org.openecomp.sdc.be.exception.BusinessException;
83 import org.openecomp.sdc.be.impl.ComponentsUtils;
84 import org.openecomp.sdc.be.impl.ForwardingPathUtils;
85 import org.openecomp.sdc.be.impl.ServiceFilterUtils;
86 import org.openecomp.sdc.be.info.CreateAndAssotiateInfo;
87 import org.openecomp.sdc.be.model.ArtifactDefinition;
88 import org.openecomp.sdc.be.model.AttributeDefinition;
89 import org.openecomp.sdc.be.model.CapabilityDefinition;
90 import org.openecomp.sdc.be.model.Component;
91 import org.openecomp.sdc.be.model.ComponentInstance;
92 import org.openecomp.sdc.be.model.ComponentInstanceAttribute;
93 import org.openecomp.sdc.be.model.ComponentInstanceInput;
94 import org.openecomp.sdc.be.model.ComponentInstanceOutput;
95 import org.openecomp.sdc.be.model.ComponentInstancePropInput;
96 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
97 import org.openecomp.sdc.be.model.ComponentParametersView;
98 import org.openecomp.sdc.be.model.DataTypeDefinition;
99 import org.openecomp.sdc.be.model.GroupDefinition;
100 import org.openecomp.sdc.be.model.InputDefinition;
101 import org.openecomp.sdc.be.model.InterfaceDefinition;
102 import org.openecomp.sdc.be.model.LifecycleStateEnum;
103 import org.openecomp.sdc.be.model.OutputDefinition;
104 import org.openecomp.sdc.be.model.PolicyDefinition;
105 import org.openecomp.sdc.be.model.PropertyDefinition;
106 import org.openecomp.sdc.be.model.RelationshipInfo;
107 import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
108 import org.openecomp.sdc.be.model.RequirementDefinition;
109 import org.openecomp.sdc.be.model.Resource;
110 import org.openecomp.sdc.be.model.Service;
111 import org.openecomp.sdc.be.model.ToscaPropertyData;
112 import org.openecomp.sdc.be.model.User;
113 import org.openecomp.sdc.be.model.jsonjanusgraph.config.ContainerInstanceTypesData;
114 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ArtifactsOperations;
115 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ForwardingPathOperation;
116 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.InterfaceOperation;
117 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.NodeFilterOperation;
118 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.NodeTemplateOperation;
119 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade;
120 import org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter;
121 import org.openecomp.sdc.be.model.operations.StorageException;
122 import org.openecomp.sdc.be.model.operations.api.IElementOperation;
123 import org.openecomp.sdc.be.model.operations.api.IGroupInstanceOperation;
124 import org.openecomp.sdc.be.model.operations.api.IGroupOperation;
125 import org.openecomp.sdc.be.model.operations.api.IGroupTypeOperation;
126 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
127 import org.openecomp.sdc.be.model.operations.impl.ComponentInstanceOperation;
128 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
129 import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation;
130 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
131 import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
132 import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
133 import org.openecomp.sdc.be.model.validation.ToscaFunctionValidator;
134 import org.openecomp.sdc.be.resources.data.ComponentInstanceData;
135 import org.openecomp.sdc.be.user.Role;
136 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
137 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
138 import org.openecomp.sdc.common.api.Constants;
139 import org.openecomp.sdc.common.datastructure.Wrapper;
140 import org.openecomp.sdc.common.jsongraph.util.CommonUtility;
141 import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum;
142 import org.openecomp.sdc.common.log.elements.ErrorLogOptionalData;
143 import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode;
144 import org.openecomp.sdc.common.log.wrappers.Logger;
145 import org.openecomp.sdc.common.util.ValidationUtils;
146 import org.openecomp.sdc.exception.ResponseFormat;
147 import org.springframework.beans.factory.annotation.Autowired;
149 @org.springframework.stereotype.Component
150 public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
152 private static final Logger log = Logger.getLogger(ComponentInstanceBusinessLogic.class);
153 private static final String VF_MODULE = "org.openecomp.groups.VfModule";
154 private static final String TRY_TO_CREATE_ENTRY_ON_GRAPH = "Try to create entry on graph";
155 private static final String CLOUD_SPECIFIC_FIXED_KEY_WORD = "cloudtech";
156 private static final String[][] CLOUD_SPECIFIC_KEY_WORDS = {{"k8s", "azure", "aws"}, /* cloud specific technology */
157 {"charts", "day0", "configtemplate"} /*cloud specific sub type*/};
158 private static final String FAILED_TO_CREATE_ENTRY_ON_GRAPH_FOR_COMPONENT_INSTANCE = "Failed to create entry on graph for component instance {}";
159 private static final String ENTITY_ON_GRAPH_IS_CREATED = "Entity on graph is created.";
160 private static final String INVALID_COMPONENT_TYPE = "invalid component type";
161 private static final String FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID = "Failed to retrieve component, component id {}";
162 private static final String FAILED_TO_LOCK_SERVICE = "Failed to lock service {}";
163 private static final String CREATE_OR_UPDATE_PROPERTY_VALUE = "CreateOrUpdatePropertyValue";
164 private static final String FAILED_TO_COPY_COMP_INSTANCE_TO_CANVAS = "Failed to copy the component instance to the canvas";
165 private static final String COPY_COMPONENT_INSTANCE_OK = "Copy component instance OK";
166 private static final String CANNOT_ATTACH_RESOURCE_INSTANCES_TO_CONTAINER_RESOURCE_OF_TYPE = "Cannot attach resource instances to container resource of type {}";
167 private static final String FAILED_TO_UPDATE_COMPONENT_INSTANCE_CAPABILITY = "Failed to update component instance capability on instance {} in "
169 private static final String SERVICE_PROXY = "serviceProxy";
170 private static final String ASSOCIATE_RI_TO_RI = "associateRIToRI";
171 private static final String COMPONENT_ARCHIVED = "Component is archived. Component id: {}";
172 private static final String RESTRICTED_OPERATION_ON_SERVIVE = "Restricted operation for user: {} on service {}";
173 private static final String FAILED_TO_LOCK_COMPONENT = "Failed to lock component {}";
174 private static final String RESTRICTED_OPERATION_ON_COMPONENT = "Restricted operation for user: {} on component {}";
175 private static final String RESOURCE_INSTANCE = "resource instance";
176 private static final String SERVICE = "service";
178 private final ComponentInstanceOperation componentInstanceOperation;
179 private final ArtifactsBusinessLogic artifactBusinessLogic;
180 private final ComponentInstanceMergeDataBusinessLogic compInstMergeDataBL;
181 private final ComponentInstanceChangeOperationOrchestrator onChangeInstanceOperationOrchestrator;
182 private final ForwardingPathOperation forwardingPathOperation;
183 private final NodeFilterOperation nodeFilterOperation;
185 private CompositionBusinessLogic compositionBusinessLogic;
187 private ContainerInstanceTypesData containerInstanceTypesData;
188 private final ToscaFunctionValidator toscaFunctionValidator;
191 public ComponentInstanceBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation,
192 IGroupInstanceOperation groupInstanceOperation, IGroupTypeOperation groupTypeOperation,
193 InterfaceOperation interfaceOperation, InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
194 ComponentInstanceOperation componentInstanceOperation, ArtifactsBusinessLogic artifactBusinessLogic,
195 ComponentInstanceMergeDataBusinessLogic compInstMergeDataBL,
196 ComponentInstanceChangeOperationOrchestrator onChangeInstanceOperationOrchestrator,
197 ForwardingPathOperation forwardingPathOperation, NodeFilterOperation nodeFilterOperation,
198 ArtifactsOperations artifactToscaOperation, final ToscaFunctionValidator toscaFunctionValidator) {
199 super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation,
200 artifactToscaOperation);
201 this.componentInstanceOperation = componentInstanceOperation;
202 this.artifactBusinessLogic = artifactBusinessLogic;
203 this.compInstMergeDataBL = compInstMergeDataBL;
204 this.onChangeInstanceOperationOrchestrator = onChangeInstanceOperationOrchestrator;
205 this.forwardingPathOperation = forwardingPathOperation;
206 this.nodeFilterOperation = nodeFilterOperation;
207 this.toscaFunctionValidator = toscaFunctionValidator;
210 public ComponentInstance createComponentInstance(String containerComponentParam, String containerComponentId, String userId,
211 ComponentInstance resourceInstance) {
212 return createComponentInstance(containerComponentParam, containerComponentId, userId, resourceInstance, true);
215 public List<ComponentInstanceProperty> getComponentInstancePropertiesByInputId(org.openecomp.sdc.be.model.Component component, String inputId) {
216 List<ComponentInstanceProperty> resList = new ArrayList<>();
217 Map<String, List<ComponentInstanceProperty>> ciPropertiesMap = component.getComponentInstancesProperties();
218 if (ciPropertiesMap != null && !ciPropertiesMap.isEmpty()) {
219 ciPropertiesMap.forEach((s, ciPropList) -> {
221 Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(s)).findAny();
222 if (ciOp.isPresent()) {
223 ciName = ciOp.get().getName();
225 if (ciPropList != null && !ciPropList.isEmpty()) {
226 for (ComponentInstanceProperty prop : ciPropList) {
227 List<GetInputValueDataDefinition> inputsValues = prop.getGetInputValues();
228 addCompInstanceProperty(s, ciName, prop, inputsValues, inputId, resList);
236 public List<ComponentInstanceAttribute> getComponentInstanceAttributesByOutputId(final org.openecomp.sdc.be.model.Component component,
237 final String outputId) {
238 final List<ComponentInstanceAttribute> resList = new ArrayList<>();
239 final Map<String, List<ComponentInstanceAttribute>> componentInstancesAttributes = component.getComponentInstancesAttributes();
240 if (org.apache.commons.collections4.MapUtils.isNotEmpty(componentInstancesAttributes)) {
241 componentInstancesAttributes.forEach((s, componentInstanceAttributeList) -> {
243 final Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(s))
245 if (ciOp.isPresent()) {
246 ciName = ciOp.get().getName();
248 if (componentInstanceAttributeList != null && !componentInstanceAttributeList.isEmpty()) {
249 for (final ComponentInstanceAttribute compInstanceAttribute : componentInstanceAttributeList) {
250 List<GetOutputValueDataDefinition> outputValues = compInstanceAttribute.getGetOutputValues();
251 addCompInstanceAttribute(s, ciName, compInstanceAttribute, outputValues, outputId, resList);
259 private void addCompInstanceProperty(String s, String ciName, ComponentInstanceProperty prop, List<GetInputValueDataDefinition> inputsValues,
260 String inputId, List<ComponentInstanceProperty> resList) {
261 if (inputsValues != null && !inputsValues.isEmpty()) {
262 for (GetInputValueDataDefinition inputData : inputsValues) {
263 if (isGetInputValueForInput(inputData, inputId)) {
264 prop.setComponentInstanceId(s);
265 prop.setComponentInstanceName(ciName);
273 private void addCompInstanceAttribute(final String s, final String ciName, final ComponentInstanceAttribute attribute,
274 final List<GetOutputValueDataDefinition> outputsValues, final String outputId,
275 final List<ComponentInstanceAttribute> resList) {
276 if (outputsValues != null && !outputsValues.isEmpty()) {
277 for (final GetOutputValueDataDefinition outputData : outputsValues) {
278 if (isGetOutputValueForOutput(outputData, outputId)) {
279 attribute.setComponentInstanceId(s);
280 attribute.setComponentInstanceName(ciName);
281 resList.add(attribute);
288 public Optional<ComponentInstanceProperty> getComponentInstancePropertyByPolicyId(Component component, PolicyDefinition policy) {
289 Optional<ComponentInstanceProperty> propertyCandidate = getComponentInstancePropertyByPolicy(component, policy);
290 if (propertyCandidate.isPresent()) {
291 ComponentInstanceProperty componentInstanceProperty = propertyCandidate.get();
292 Optional<GetPolicyValueDataDefinition> getPolicyCandidate = getGetPolicyValueDataDefinition(policy, componentInstanceProperty);
294 .ifPresent(getPolicyValue -> updateComponentInstancePropertyAfterUndeclaration(componentInstanceProperty, getPolicyValue, policy));
295 return Optional.of(componentInstanceProperty);
297 return Optional.empty();
300 private void updateComponentInstancePropertyAfterUndeclaration(ComponentInstanceProperty componentInstanceProperty,
301 GetPolicyValueDataDefinition getPolicyValue, PolicyDefinition policyDefinition) {
302 componentInstanceProperty.setValue(getPolicyValue.getOrigPropertyValue());
303 List<GetPolicyValueDataDefinition> getPolicyValues = componentInstanceProperty.getGetPolicyValues();
304 if (CollectionUtils.isNotEmpty(getPolicyValues)) {
305 getPolicyValues.remove(getPolicyValue);
306 componentInstanceProperty.setGetPolicyValues(getPolicyValues);
307 policyDefinition.setGetPolicyValues(getPolicyValues);
311 private Optional<GetPolicyValueDataDefinition> getGetPolicyValueDataDefinition(PolicyDefinition policy,
312 ComponentInstanceProperty componentInstanceProperty) {
313 List<GetPolicyValueDataDefinition> getPolicyValues = policy.getGetPolicyValues();
314 return getPolicyValues.stream().filter(getPolicyValue -> getPolicyValue.getPropertyName().equals(componentInstanceProperty.getName()))
318 private Optional<ComponentInstanceProperty> getComponentInstancePropertyByPolicy(Component component, PolicyDefinition policy) {
319 Map<String, List<ComponentInstanceProperty>> componentInstancesProperties = component.getComponentInstancesProperties();
320 if (MapUtils.isEmpty(componentInstancesProperties)) {
321 return Optional.empty();
323 String instanceUniqueId = policy.getInstanceUniqueId();
324 List<ComponentInstanceProperty> componentInstanceProperties =
325 componentInstancesProperties.containsKey(instanceUniqueId) ? componentInstancesProperties.get(instanceUniqueId) : new ArrayList<>();
326 return componentInstanceProperties.stream().filter(property -> property.getName().equals(policy.getName())).findAny();
329 public List<ComponentInstanceInput> getComponentInstanceInputsByInputId(org.openecomp.sdc.be.model.Component component, String inputId) {
330 List<ComponentInstanceInput> resList = new ArrayList<>();
331 Map<String, List<ComponentInstanceInput>> ciInputsMap = component.getComponentInstancesInputs();
332 if (ciInputsMap != null && !ciInputsMap.isEmpty()) {
333 ciInputsMap.forEach((s, ciPropList) -> {
335 Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(s)).findAny();
336 if (ciOp.isPresent()) {
337 ciName = ciOp.get().getName();
339 if (ciPropList != null && !ciPropList.isEmpty()) {
340 for (ComponentInstanceInput prop : ciPropList) {
341 List<GetInputValueDataDefinition> inputsValues = prop.getGetInputValues();
342 addCompInstanceInput(s, ciName, prop, inputsValues, inputId, resList);
350 public List<ComponentInstanceOutput> getComponentInstanceOutputsByOutputId(final org.openecomp.sdc.be.model.Component component,
351 final String outputId) {
352 final List<ComponentInstanceOutput> resList = new ArrayList<>();
353 final Map<String, List<ComponentInstanceOutput>> ciInputsMap = component.getComponentInstancesOutputs();
354 if (ciInputsMap != null && !ciInputsMap.isEmpty()) {
355 ciInputsMap.forEach((s, ciPropList) -> {
357 final Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(s))
359 if (ciOp.isPresent()) {
360 ciName = ciOp.get().getName();
362 if (ciPropList != null && !ciPropList.isEmpty()) {
363 for (final ComponentInstanceOutput prop : ciPropList) {
364 final List<GetOutputValueDataDefinition> outputValues = prop.getGetOutputValues();
365 addCompInstanceOutput(s, ciName, prop, outputValues, outputId, resList);
373 private void addCompInstanceInput(String s, String ciName, ComponentInstanceInput prop, List<GetInputValueDataDefinition> inputsValues,
374 String inputId, List<ComponentInstanceInput> resList) {
375 if (inputsValues != null && !inputsValues.isEmpty()) {
376 for (GetInputValueDataDefinition inputData : inputsValues) {
377 if (isGetInputValueForInput(inputData, inputId)) {
378 prop.setComponentInstanceId(s);
379 prop.setComponentInstanceName(ciName);
387 private void addCompInstanceOutput(final String s, final String ciName, final ComponentInstanceOutput prop,
388 final List<GetOutputValueDataDefinition> outputsValues, final String outputId,
389 final List<ComponentInstanceOutput> resList) {
390 if (outputsValues != null && !outputsValues.isEmpty()) {
391 for (final GetOutputValueDataDefinition outputData : outputsValues) {
392 if (isGetOutputValueForOutput(outputData, outputId)) {
393 prop.setComponentInstanceId(s);
394 prop.setComponentInstanceName(ciName);
402 public ComponentInstance createComponentInstance(final String containerComponentParam, final String containerComponentId, final String userId,
403 final ComponentInstance resourceInstance, final boolean needLock) {
404 final User user = validateUserExists(userId);
405 validateUserNotEmpty(user, "Create component instance");
406 validateJsonBody(resourceInstance, ComponentInstance.class);
407 final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
408 final org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, null);
409 if (ModelConverter.isAtomicComponent(containerComponent)) {
410 if (log.isDebugEnabled()) {
411 log.debug(CANNOT_ATTACH_RESOURCE_INSTANCES_TO_CONTAINER_RESOURCE_OF_TYPE, containerComponent.assetType());
413 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType());
415 validateCanWorkOnComponent(containerComponent, userId);
416 Component origComponent = null;
417 if (resourceInstance != null && containerComponentType != null) {
418 final OriginTypeEnum originType = resourceInstance.getOriginType();
419 validateInstanceName(resourceInstance);
420 if (originType == OriginTypeEnum.ServiceProxy) {
421 origComponent = getOrigComponentForServiceProxy(containerComponent, resourceInstance);
422 } else if (originType == OriginTypeEnum.ServiceSubstitution) {
423 origComponent = getOrigComponentForServiceSubstitution(resourceInstance);
425 origComponent = getAndValidateOriginComponentOfComponentInstance(containerComponent, resourceInstance);
426 validateOriginAndResourceInstanceTypes(containerComponent, origComponent, originType);
428 validateResourceInstanceState(containerComponent, origComponent);
429 overrideFields(origComponent, resourceInstance);
430 compositionBusinessLogic.validateAndSetDefaultCoordinates(resourceInstance);
432 return createComponent(needLock, containerComponent, origComponent, resourceInstance, user);
435 private Component getOrigComponentForServiceProxy(org.openecomp.sdc.be.model.Component containerComponent, ComponentInstance resourceInstance) {
436 Either<Component, StorageOperationStatus> serviceProxyOrigin = toscaOperationFacade.getLatestByName(SERVICE_PROXY, null);
437 if (isServiceProxyOrigin(serviceProxyOrigin)) {
438 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(serviceProxyOrigin.right().value()));
440 Component origComponent = serviceProxyOrigin.left().value();
441 StorageOperationStatus fillProxyRes = fillInstanceData(resourceInstance, origComponent);
442 if (isFillProxyRes(fillProxyRes)) {
443 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(fillProxyRes));
445 validateOriginAndResourceInstanceTypes(containerComponent, origComponent, OriginTypeEnum.ServiceProxy);
446 return origComponent;
449 private Component getOrigComponentForServiceSubstitution(ComponentInstance resourceInstance) {
450 final Either<Component, StorageOperationStatus> getServiceResult = toscaOperationFacade
451 .getToscaFullElement(resourceInstance.getComponentUid());
452 if (getServiceResult.isRight()) {
453 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(getServiceResult.right().value()));
455 final Component service = getServiceResult.left().value();
456 final Either<Component, StorageOperationStatus> getServiceDerivedFromTypeResult = toscaOperationFacade
457 .getLatestByToscaResourceName(service.getDerivedFromGenericType(), service.getModel());
458 if (getServiceDerivedFromTypeResult.isRight()) {
459 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(getServiceResult.right().value()));
461 Component origComponent = getServiceDerivedFromTypeResult.left().value();
462 final StorageOperationStatus fillProxyRes = fillInstanceData(resourceInstance, origComponent);
463 if (isFillProxyRes(fillProxyRes)) {
464 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(fillProxyRes));
466 return origComponent;
469 private ComponentInstance createComponent(boolean needLock, Component containerComponent, Component origComponent,
470 ComponentInstance resourceInstance, User user) {
471 boolean failed = false;
473 lockIfNeed(needLock, containerComponent);
474 log.debug(TRY_TO_CREATE_ENTRY_ON_GRAPH);
475 return createComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, user);
476 } catch (ComponentException e) {
481 unlockComponent(failed, containerComponent);
487 * Try using either to make a judgment
489 * @param containerComponentParam
490 * @param containerComponentId
492 * @param resourceInstance
495 public Either<ComponentInstance, ResponseFormat> createRealComponentInstance(String containerComponentParam, String containerComponentId,
496 String userId, ComponentInstance resourceInstance) {
497 log.debug("enter createRealComponentInstance");
498 return createRealComponentInstance(containerComponentParam, containerComponentId, userId, resourceInstance, true);
502 * Try using either to make a judgment
505 * @param containerComponentParam
506 * @param containerComponentId
508 * @param resourceInstance
511 public Either<ComponentInstance, ResponseFormat> createRealComponentInstance(String containerComponentParam, String containerComponentId,
512 String userId, ComponentInstance resourceInstance,
514 log.debug("enter createRealComponentInstance");
515 Component origComponent = null;
517 org.openecomp.sdc.be.model.Component containerComponent = null;
518 ComponentTypeEnum containerComponentType;
520 user = validateUserExists(userId);
521 validateUserNotEmpty(user, "Create component instance");
522 validateJsonBody(resourceInstance, ComponentInstance.class);
523 containerComponentType = validateComponentType(containerComponentParam);
524 containerComponent = validateComponentExists(containerComponentId, containerComponentType, null);
525 log.debug("enter createRealComponentInstance,validate user json success");
526 if (ModelConverter.isAtomicComponent(containerComponent)) {
527 log.debug(CANNOT_ATTACH_RESOURCE_INSTANCES_TO_CONTAINER_RESOURCE_OF_TYPE, containerComponent.assetType());
528 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType());
530 validateCanWorkOnComponent(containerComponent, userId);
531 log.debug("enter createRealComponentInstance,validateCanWorkOnComponent success");
532 if (resourceInstance != null && containerComponentType != null) {
533 log.debug("enter createRealComponentInstance,start create ComponentInstance");
534 OriginTypeEnum originType = resourceInstance.getOriginType();
535 validateInstanceName(resourceInstance);
536 if (originType == OriginTypeEnum.ServiceProxy) {
537 log.debug("enter createRealComponentInstance,originType equals ServiceProxy");
538 Either<Component, StorageOperationStatus> serviceProxyOrigin = toscaOperationFacade.getLatestByName(SERVICE_PROXY, null);
539 if (isServiceProxyOrigin(serviceProxyOrigin)) {
540 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(serviceProxyOrigin.right().value()));
542 origComponent = serviceProxyOrigin.left().value();
543 StorageOperationStatus fillProxyRes = fillInstanceData(resourceInstance, origComponent);
544 if (isFillProxyRes(fillProxyRes)) {
545 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(fillProxyRes));
548 log.debug("enter createRealComponentInstance,originType is not ServiceProxy");
549 origComponent = getAndValidateOriginComponentOfComponentInstance(containerComponent, resourceInstance);
551 validateOriginAndResourceInstanceTypes(containerComponent, origComponent, originType);
552 validateResourceInstanceState(containerComponent, origComponent);
553 overrideFields(origComponent, resourceInstance);
554 compositionBusinessLogic.validateAndSetDefaultCoordinates(resourceInstance);
555 log.debug("enter createRealComponentInstance,final validate success");
557 return createRealComponent(needLock, containerComponent, origComponent, resourceInstance, user);
558 } catch (ComponentException e) {
559 log.debug("create Real Component Instance failed");
564 private Either<ComponentInstance, ResponseFormat> createRealComponent(boolean needLock, Component containerComponent, Component origComponent,
565 ComponentInstance resourceInstance, User user) {
566 log.debug("enter createRealComponent");
567 boolean failed = false;
569 lockIfNeed(needLock, containerComponent);
570 log.debug(TRY_TO_CREATE_ENTRY_ON_GRAPH);
571 return createRealComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, user);
572 } catch (ComponentException e) {
577 unlockComponent(failed, containerComponent);
582 private Either<ComponentInstance, ResponseFormat> createRealComponentInstanceOnGraph(org.openecomp.sdc.be.model.Component containerComponent,
583 Component originComponent,
584 ComponentInstance componentInstance, User user) {
585 log.debug("enter createRealComponentInstanceOnGraph");
586 Either<ImmutablePair<Component, String>, StorageOperationStatus> result = toscaOperationFacade
587 .addComponentInstanceToTopologyTemplate(containerComponent, originComponent, componentInstance, false, user);
588 if (result.isRight()) {
589 log.debug("enter createRealComponentInstanceOnGraph,result is right");
590 ActionStatus status = componentsUtils.convertFromStorageResponse(result.right().value());
591 log.debug(FAILED_TO_CREATE_ENTRY_ON_GRAPH_FOR_COMPONENT_INSTANCE, componentInstance.getName());
592 return Either.right(componentsUtils.getResponseFormat(status));
594 log.debug(ENTITY_ON_GRAPH_IS_CREATED);
595 log.debug("enter createRealComponentInstanceOnGraph,Entity on graph is created.");
596 Component updatedComponent = result.left().value().getLeft();
597 Map<String, String> existingEnvVersions = new HashMap<>();
598 // TODO existingEnvVersions ??
599 addComponentInstanceArtifacts(updatedComponent, componentInstance, originComponent, user, existingEnvVersions);
600 Optional<ComponentInstance> updatedInstanceOptional = updatedComponent.getComponentInstances().stream()
601 .filter(ci -> ci.getUniqueId().equals(result.left().value().getRight())).findFirst();
602 if (!updatedInstanceOptional.isPresent()) {
603 log.debug("Failed to fetch new added component instance {} from component {}", componentInstance.getName(), containerComponent.getName());
604 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName());
606 log.debug("enter createRealComponentInstanceOnGraph,and final success");
607 return Either.left(updatedInstanceOptional.get());
610 private void overrideFields(Component origComponent, ComponentInstance resourceInstance) {
611 resourceInstance.setComponentVersion(origComponent.getVersion());
612 resourceInstance.setIcon(origComponent.getIcon());
615 private void validateInstanceName(ComponentInstance resourceInstance) {
616 String resourceInstanceName = resourceInstance.getName();
617 if (StringUtils.isEmpty(resourceInstanceName)) {
618 log.debug("ComponentInstance name is empty");
619 throw new ByActionStatusComponentException(ActionStatus.INVALID_COMPONENT_NAME, resourceInstance.getName());
621 if (!ValidationUtils.validateComponentNameLength(resourceInstanceName)) {
622 log.debug("ComponentInstance name exceeds max length {} ", ValidationUtils.COMPONENT_NAME_MAX_LENGTH);
623 throw new ByActionStatusComponentException(ActionStatus.INVALID_COMPONENT_NAME, resourceInstance.getName());
625 if (!ValidationUtils.validateComponentNamePattern(resourceInstanceName)) {
626 log.debug("ComponentInstance name {} has invalid format", resourceInstanceName);
627 throw new ByActionStatusComponentException(ActionStatus.INVALID_COMPONENT_NAME, resourceInstance.getName());
631 private void validateResourceInstanceState(Component containerComponent, Component origComponent) {
632 if (origComponent.getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) {
633 throw new ByActionStatusComponentException(ActionStatus.CONTAINER_CANNOT_CONTAIN_INSTANCE,
634 containerComponent.getComponentType().getValue(), origComponent.getLifecycleState().toString());
638 private void validateOriginAndResourceInstanceTypes(final Component containerComponent, final Component origComponent,
639 final OriginTypeEnum originType) {
640 final ResourceTypeEnum resourceType = getResourceTypeEnumFromOriginComponent(origComponent);
641 validateOriginType(originType, resourceType);
642 validateOriginComponentIsValidForContainer(containerComponent, resourceType);
645 private void validateOriginComponentIsValidForContainer(Component containerComponent, ResourceTypeEnum resourceType) {
646 switch (containerComponent.getComponentType()) {
648 if (!containerInstanceTypesData.isAllowedForServiceComponent(resourceType, containerComponent.getModel())) {
649 throw new ByActionStatusComponentException(ActionStatus.CONTAINER_CANNOT_CONTAIN_INSTANCE,
650 containerComponent.getComponentType().toString(), resourceType.name());
654 final ResourceTypeEnum componentResourceType = ((Resource) containerComponent).getResourceType();
655 if (!containerInstanceTypesData.isAllowedForResourceComponent(componentResourceType, resourceType)) {
656 throw new ByActionStatusComponentException(ActionStatus.CONTAINER_CANNOT_CONTAIN_INSTANCE,
657 containerComponent.getComponentType().toString(), resourceType.name());
661 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
665 private void validateOriginType(OriginTypeEnum originType, ResourceTypeEnum resourceType) {
666 ResourceTypeEnum convertedOriginType;
668 convertedOriginType = ResourceTypeEnum.getTypeIgnoreCase(originType.name());
669 } catch (Exception e) {
670 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
672 if (resourceType != convertedOriginType) {
673 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
677 private ResourceTypeEnum getResourceTypeEnumFromOriginComponent(final Component origComponent) {
678 switch (origComponent.getComponentType()) {
680 return ResourceTypeEnum.ServiceProxy;
682 return ((Resource) origComponent).getResourceType();
684 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
688 private void lockIfNeed(boolean needLock, Component containerComponent) {
690 lockComponent(containerComponent, "createComponentInstance");
694 private boolean isServiceProxyOrigin(Either<Component, StorageOperationStatus> serviceProxyOrigin) {
695 if (serviceProxyOrigin.isRight()) {
696 log.debug("Failed to fetch normative service proxy resource by tosca name, error {}", serviceProxyOrigin.right().value());
702 private StorageOperationStatus fillInstanceData(ComponentInstance resourceInstance, Component origComponent) {
703 final ComponentParametersView filter = new ComponentParametersView(true);
704 filter.setIgnoreCapabilities(false);
705 filter.setIgnoreCapabiltyProperties(false);
706 filter.setIgnoreComponentInstances(false);
707 filter.setIgnoreRequirements(false);
708 filter.setIgnoreInterfaces(false);
709 filter.setIgnoreProperties(false);
710 filter.setIgnoreAttributes(false);
711 filter.setIgnoreInputs(false);
712 Either<Component, StorageOperationStatus> serviceRes = toscaOperationFacade.getToscaElement(resourceInstance.getComponentUid(), filter);
713 if (serviceRes.isRight()) {
714 return serviceRes.right().value();
716 final Component service = serviceRes.left().value();
717 final Map<String, List<CapabilityDefinition>> capabilities = service.getCapabilities();
718 resourceInstance.setCapabilities(capabilities);
719 final Map<String, List<RequirementDefinition>> req = service.getRequirements();
720 resourceInstance.setRequirements(req);
721 final Map<String, InterfaceDefinition> serviceInterfaces = service.getInterfaces();
722 if (MapUtils.isNotEmpty(serviceInterfaces)) {
723 serviceInterfaces.forEach(resourceInstance::addInterface);
725 resourceInstance.setProperties(PropertiesUtils.getProperties(service));
726 resourceInstance.setAttributes(service.getAttributes());
727 final List<InputDefinition> serviceInputs = service.getInputs();
728 resourceInstance.setInputs(serviceInputs);
729 resourceInstance.setSourceModelInvariant(service.getInvariantUUID());
730 resourceInstance.setSourceModelName(service.getName());
731 resourceInstance.setSourceModelUuid(service.getUUID());
732 resourceInstance.setSourceModelUid(service.getUniqueId());
733 resourceInstance.setComponentUid(origComponent.getUniqueId());
734 resourceInstance.setComponentVersion(service.getVersion());
735 switch (resourceInstance.getOriginType()) {
737 return fillProxyInstanceData(resourceInstance, origComponent, service);
738 case ServiceSubstitution:
739 return fillServiceSubstitutableNodeTypeData(resourceInstance, service);
741 return StorageOperationStatus.OK;
745 private StorageOperationStatus fillProxyInstanceData(final ComponentInstance resourceInstance, final Component origComponent,
746 final Component service) {
747 final String name = ValidationUtils.normalizeComponentInstanceName(service.getName()) + ToscaOperationFacade.PROXY_SUFFIX;
748 final String toscaResourceName = ((Resource) origComponent).getToscaResourceName();
749 final int lastIndexOf = toscaResourceName.lastIndexOf('.');
750 if (lastIndexOf != -1) {
751 final String proxyToscaName = toscaResourceName.substring(0, lastIndexOf + 1) + name;
752 resourceInstance.setToscaComponentName(proxyToscaName);
754 resourceInstance.setName(name);
755 resourceInstance.setIsProxy(true);
756 resourceInstance.setDescription("A Proxy for Service " + service.getName());
757 return StorageOperationStatus.OK;
760 private StorageOperationStatus fillServiceSubstitutableNodeTypeData(final ComponentInstance resourceInstance, final Component service) {
761 resourceInstance.setToscaComponentName("org.openecomp.service." + ValidationUtils.convertToSystemName(service.getName()));
762 resourceInstance.setName(ValidationUtils.normalizeComponentInstanceName(service.getName()));
763 resourceInstance.setIsProxy(false);
764 resourceInstance.setDescription("A substitutable node type for service " + service.getName());
765 return StorageOperationStatus.OK;
768 public Either<CreateAndAssotiateInfo, ResponseFormat> createAndAssociateRIToRI(String containerComponentParam, String containerComponentId,
769 String userId, CreateAndAssotiateInfo createAndAssotiateInfo) {
770 Either<CreateAndAssotiateInfo, ResponseFormat> resultOp = null;
771 ComponentInstance resourceInstance = createAndAssotiateInfo.getNode();
772 RequirementCapabilityRelDef associationInfo = createAndAssotiateInfo.getAssociate();
773 User user = validateUserExists(userId);
774 final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
775 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, null);
776 if (ModelConverter.isAtomicComponent(containerComponent)) {
777 log.debug(CANNOT_ATTACH_RESOURCE_INSTANCES_TO_CONTAINER_RESOURCE_OF_TYPE, containerComponent.assetType());
779 .right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType()));
781 validateCanWorkOnComponent(containerComponent, userId);
782 boolean failed = false;
784 lockComponent(containerComponent, "createAndAssociateRIToRI");
785 log.debug(TRY_TO_CREATE_ENTRY_ON_GRAPH);
786 Component origComponent = getOriginComponentFromComponentInstance(resourceInstance);
787 log.debug(ENTITY_ON_GRAPH_IS_CREATED);
788 ComponentInstance resResourceInfo = createComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, user);
789 if (associationInfo.getFromNode() == null || associationInfo.getFromNode().isEmpty()) {
790 associationInfo.setFromNode(resResourceInfo.getUniqueId());
792 associationInfo.setToNode(resResourceInfo.getUniqueId());
794 Either<RequirementCapabilityRelDef, StorageOperationStatus> resultReqCapDef = toscaOperationFacade
795 .associateResourceInstances(containerComponent, containerComponentId, associationInfo);
796 if (resultReqCapDef.isLeft()) {
797 log.debug(ENTITY_ON_GRAPH_IS_CREATED);
798 RequirementCapabilityRelDef resReqCapabilityRelDef = resultReqCapDef.left().value();
799 CreateAndAssotiateInfo resInfo = new CreateAndAssotiateInfo(resResourceInfo, resReqCapabilityRelDef);
800 resultOp = Either.left(resInfo);
803 log.info("Failed to associate node {} with node {}", associationInfo.getFromNode(), associationInfo.getToNode());
804 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(
805 componentsUtils.convertFromStorageResponseForResourceInstance(resultReqCapDef.right().value(), true), "", null));
808 } catch (ComponentException e) {
812 unlockComponent(failed, containerComponent);
816 private Component getOriginComponentFromComponentInstance(ComponentInstance componentInstance) {
817 return getOriginComponentFromComponentInstance(componentInstance.getName(), componentInstance.getComponentUid());
820 private Component getInstanceOriginNode(ComponentInstance componentInstance) {
821 return getOriginComponentFromComponentInstance(componentInstance.getName(), componentInstance.getActualComponentUid());
824 private Component getOriginComponentFromComponentInstance(String componentInstanceName, String origComponetId) {
825 Either<Component, StorageOperationStatus> eitherComponent = toscaOperationFacade.getToscaFullElement(origComponetId);
826 if (eitherComponent.isRight()) {
827 log.debug("Failed to get origin component with id {} for component instance {} ", origComponetId, componentInstanceName);
828 throw new ByActionStatusComponentException(
829 componentsUtils.convertFromStorageResponse(eitherComponent.right().value(), ComponentTypeEnum.RESOURCE), "", null);
831 return eitherComponent.left().value();
834 private ComponentInstance createComponentInstanceOnGraph(org.openecomp.sdc.be.model.Component containerComponent, Component originComponent,
835 ComponentInstance componentInstance, User user) {
836 Either<ImmutablePair<Component, String>, StorageOperationStatus> result = toscaOperationFacade
837 .addComponentInstanceToTopologyTemplate(containerComponent, originComponent, componentInstance, false, user);
838 if (result.isRight()) {
839 log.debug(FAILED_TO_CREATE_ENTRY_ON_GRAPH_FOR_COMPONENT_INSTANCE, componentInstance.getName());
840 throw new ByResponseFormatComponentException(componentsUtils
841 .getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), "",
844 log.debug(ENTITY_ON_GRAPH_IS_CREATED);
845 Component updatedComponent = result.left().value().getLeft();
846 Map<String, String> existingEnvVersions = new HashMap<>();
847 // TODO existingEnvVersions ??
848 addComponentInstanceArtifacts(updatedComponent, componentInstance, originComponent, user, existingEnvVersions);
849 Optional<ComponentInstance> updatedInstanceOptional = updatedComponent.getComponentInstances().stream()
850 .filter(ci -> ci.getUniqueId().equals(result.left().value().getRight())).findFirst();
851 if (!updatedInstanceOptional.isPresent()) {
852 log.debug("Failed to fetch new added component instance {} from component {}", componentInstance.getName(), containerComponent.getName());
853 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName());
855 return updatedInstanceOptional.get();
858 public boolean isCloudSpecificArtifact(String artifact) {
859 if (artifact.contains(CLOUD_SPECIFIC_FIXED_KEY_WORD)) {
860 for (int i = 0; i < CLOUD_SPECIFIC_KEY_WORDS.length; i++) {
861 if (Arrays.stream(CLOUD_SPECIFIC_KEY_WORDS[i]).noneMatch(artifact::contains)) {
872 * addResourceInstanceArtifacts - add artifacts (HEAT_ENV) to resource instance The instance artifacts are generated from the resource's
875 * @param containerComponent
876 * @param componentInstance
877 * @param originComponent
879 * @param existingEnvVersions
882 protected ActionStatus addComponentInstanceArtifacts(org.openecomp.sdc.be.model.Component containerComponent, ComponentInstance componentInstance,
883 org.openecomp.sdc.be.model.Component originComponent, User user,
884 Map<String, String> existingEnvVersions) {
885 log.debug("add artifacts to resource instance");
886 List<GroupDefinition> filteredGroups = new ArrayList<>();
887 ActionStatus status = setResourceArtifactsOnResourceInstance(componentInstance);
888 if (ActionStatus.OK != status) {
889 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormatForResourceInstance(status, "", null));
891 StorageOperationStatus artStatus;
892 // generate heat_env if necessary
893 Map<String, ArtifactDefinition> componentDeploymentArtifacts = componentInstance.getDeploymentArtifacts();
894 if (MapUtils.isNotEmpty(componentDeploymentArtifacts)) {
895 Map<String, ArtifactDefinition> finalDeploymentArtifacts = new HashMap<>();
896 Map<String, List<ArtifactDefinition>> groupInstancesArtifacts = new HashMap<>();
897 Integer defaultHeatTimeout = ConfigurationManager.getConfigurationManager().getConfiguration().getHeatArtifactDeploymentTimeout()
898 .getDefaultMinutes();
899 List<ArtifactDefinition> listOfCloudSpecificArts = new ArrayList<>();
900 for (ArtifactDefinition artifact : componentDeploymentArtifacts.values()) {
901 String type = artifact.getArtifactType();
902 if (!type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType())) {
903 finalDeploymentArtifacts.put(artifact.getArtifactLabel(), artifact);
905 if (type.equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HELM.getType()) || type
906 .equalsIgnoreCase(ArtifactTypeEnum.HEAT_NET.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType()) || type
907 .equalsIgnoreCase(ArtifactTypeEnum.CLOUD_TECHNOLOGY_SPECIFIC_ARTIFACT.getType())) {
908 artifact.setTimeout(defaultHeatTimeout);
912 if (artifact.checkEsIdExist()) {
913 ArtifactDefinition artifactDefinition = artifactBusinessLogic
914 .createHeatEnvPlaceHolder(new ArrayList<>(), artifact, ArtifactsBusinessLogic.HEAT_ENV_NAME, componentInstance.getUniqueId(),
915 NodeTypeEnum.ResourceInstance, componentInstance.getName(), user, containerComponent, existingEnvVersions);
917 finalDeploymentArtifacts.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
918 if (CollectionUtils.isNotEmpty(originComponent.getGroups())) {
919 filteredGroups = originComponent.getGroups().stream().filter(g -> g.getType().equals(VF_MODULE)).collect(Collectors.toList());
921 if (isCloudSpecificArtifact(artifactDefinition.getArtifactName())) {
922 listOfCloudSpecificArts.add(artifact);
924 if (CollectionUtils.isNotEmpty(filteredGroups)) {
925 filteredGroups.stream()
926 .filter(g -> g.getArtifacts() != null && g.getArtifacts().stream().anyMatch(p -> p.equals(artifactDefinition.getGeneratedFromId()))).findFirst()
927 .ifPresent(g -> fillInstanceArtifactMap(groupInstancesArtifacts, artifactDefinition, g));
931 groupInstancesArtifacts.forEach((k, v) -> v.addAll(listOfCloudSpecificArts));
932 filteredGroups.forEach(g -> listOfCloudSpecificArts.forEach(e -> {
933 g.getArtifactsUuid().add(e.getArtifactUUID());
934 g.getArtifacts().add(e.getUniqueId());
936 artStatus = toscaOperationFacade
937 .addDeploymentArtifactsToInstance(containerComponent.getUniqueId(), componentInstance, finalDeploymentArtifacts);
938 if (artStatus != StorageOperationStatus.OK) {
939 log.debug("Failed to add instance deployment artifacts for instance {} in conatiner {} error {}", componentInstance.getUniqueId(),
940 containerComponent.getUniqueId(), artStatus);
941 throw new ByResponseFormatComponentException(
942 componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(artStatus, false)));
944 StorageOperationStatus result = toscaOperationFacade
945 .addGroupInstancesToComponentInstance(containerComponent, componentInstance, filteredGroups, groupInstancesArtifacts);
946 if (result != StorageOperationStatus.OK) {
947 log.debug("failed to update group instance for component instance {}", componentInstance.getUniqueId());
948 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(result)));
950 componentInstance.setDeploymentArtifacts(finalDeploymentArtifacts);
952 artStatus = toscaOperationFacade
953 .addInformationalArtifactsToInstance(containerComponent.getUniqueId(), componentInstance, originComponent.getArtifacts());
954 if (artStatus != StorageOperationStatus.OK) {
955 log.debug("Failed to add informational artifacts to the instance {} belonging to the conatiner {}. Status is {}",
956 componentInstance.getUniqueId(), containerComponent.getUniqueId(), artStatus);
957 throw new ByResponseFormatComponentException(
958 componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(artStatus, false)));
960 componentInstance.setArtifacts(originComponent.getArtifacts());
961 return ActionStatus.OK;
964 private void fillInstanceArtifactMap(Map<String, List<ArtifactDefinition>> groupInstancesArtifacts, ArtifactDefinition artifactDefinition,
965 GroupDefinition groupInstance) {
966 List<ArtifactDefinition> artifactsUid;
967 if (groupInstancesArtifacts.containsKey(groupInstance.getUniqueId())) {
968 artifactsUid = groupInstancesArtifacts.get(groupInstance.getUniqueId());
970 artifactsUid = new ArrayList<>();
972 artifactsUid.add(artifactDefinition);
973 groupInstancesArtifacts.put(groupInstance.getUniqueId(), artifactsUid);
976 private ActionStatus setResourceArtifactsOnResourceInstance(ComponentInstance resourceInstance) {
977 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getResourceDeploymentArtifacts = artifactBusinessLogic
978 .getArtifacts(resourceInstance.getComponentUid(), NodeTypeEnum.Resource, ArtifactGroupTypeEnum.DEPLOYMENT, null);
979 Map<String, ArtifactDefinition> deploymentArtifacts = new HashMap<>();
980 if (getResourceDeploymentArtifacts.isRight()) {
981 StorageOperationStatus status = getResourceDeploymentArtifacts.right().value();
982 if (status != StorageOperationStatus.NOT_FOUND) {
983 log.debug("Failed to fetch resource: {} artifacts. status is {}", resourceInstance.getComponentUid(), status);
984 return componentsUtils.convertFromStorageResponseForResourceInstance(status, true);
987 deploymentArtifacts = getResourceDeploymentArtifacts.left().value();
989 if (!deploymentArtifacts.isEmpty()) {
990 Map<String, ArtifactDefinition> tempDeploymentArtifacts = new HashMap<>(deploymentArtifacts);
991 for (Entry<String, ArtifactDefinition> artifact : deploymentArtifacts.entrySet()) {
992 if (!artifact.getValue().checkEsIdExist()) {
993 tempDeploymentArtifacts.remove(artifact.getKey());
996 resourceInstance.setDeploymentArtifacts(tempDeploymentArtifacts);
998 return ActionStatus.OK;
1001 public Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(String containerComponentParam, String containerComponentId,
1002 String componentInstanceId, String userId,
1003 ComponentInstance componentInstance) {
1004 return updateComponentInstanceMetadata(containerComponentParam, containerComponentId, componentInstanceId, userId, componentInstance, true);
1007 public Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(final String containerComponentParam,
1008 final String containerComponentId,
1009 final String componentInstanceId, final String userId,
1010 ComponentInstance componentInstance, boolean needLock) {
1011 validateUserExists(userId);
1012 final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
1013 final Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, null);
1014 validateCanWorkOnComponent(containerComponent, userId);
1015 ComponentTypeEnum instanceType = getComponentType(containerComponentType);
1016 Either<Boolean, StorageOperationStatus> validateParentStatus = toscaOperationFacade
1017 .validateComponentExists(componentInstance.getComponentUid());
1018 if (validateParentStatus.isRight()) {
1019 log.debug("Failed to get component instance {} on service {}", componentInstanceId, containerComponentId);
1020 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND, componentInstance.getName(),
1021 instanceType.getValue().toLowerCase());
1023 if (!Boolean.TRUE.equals(validateParentStatus.left().value())) {
1024 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName(),
1025 instanceType.getValue().toLowerCase(), containerComponentType.getValue().toLowerCase(), containerComponentId);
1028 lockComponent(containerComponent, "updateComponentInstance");
1030 Component origComponent;
1031 boolean failed = false;
1033 origComponent = getOriginComponentFromComponentInstance(componentInstance);
1034 componentInstance = updateComponentInstanceMetadata(containerComponent, containerComponentType, origComponent, componentInstanceId,
1036 } catch (ComponentException e) {
1041 unlockComponent(failed, containerComponent);
1044 return Either.left(componentInstance);
1047 // New Multiple Instance Update API
1048 public List<ComponentInstance> updateComponentInstance(String containerComponentParam, Component containerComponent, String containerComponentId,
1049 String userId, List<ComponentInstance> componentInstanceList, boolean needLock) {
1050 boolean failed = false;
1052 validateUserExists(userId);
1053 final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
1054 ComponentParametersView componentFilter = new ComponentParametersView();
1055 componentFilter.disableAll();
1056 componentFilter.setIgnoreUsers(false);
1057 componentFilter.setIgnoreComponentInstances(false);
1058 if (containerComponent == null) {
1059 containerComponent = validateComponentExistsByFilter(containerComponentId, containerComponentType, componentFilter);
1061 validateCanWorkOnComponent(containerComponent, userId);
1062 ComponentTypeEnum instanceType = getComponentType(containerComponentType);
1063 for (ComponentInstance componentInstance : componentInstanceList) {
1064 boolean validateParent = validateParent(containerComponent, componentInstance.getUniqueId());
1065 if (!validateParent) {
1066 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName(),
1067 instanceType.getValue().toLowerCase(), containerComponentType.getValue().toLowerCase(), containerComponentId);
1071 lockComponent(containerComponent, "updateComponentInstance");
1073 List<ComponentInstance> updatedList = new ArrayList<>();
1074 List<ComponentInstance> instancesFromContainerComponent = containerComponent.getComponentInstances();
1075 List<ComponentInstance> listForUpdate = new ArrayList<>();
1076 if (instancesFromContainerComponent == null || instancesFromContainerComponent.isEmpty()) {
1077 containerComponent.setComponentInstances(componentInstanceList);
1079 Iterator<ComponentInstance> iterator = instancesFromContainerComponent.iterator();
1080 while (iterator.hasNext()) {
1081 ComponentInstance origInst = iterator.next();
1082 Optional<ComponentInstance> op = componentInstanceList.stream().filter(ci -> ci.getUniqueId().equals(origInst.getUniqueId()))
1084 if (op.isPresent()) {
1085 ComponentInstance updatedCi = op.get();
1086 updatedCi = buildComponentInstance(updatedCi, origInst);
1087 Boolean isUniqueName = validateInstanceNameUniquenessUponUpdate(containerComponent, origInst, updatedCi.getName());
1088 if (!Boolean.TRUE.equals(isUniqueName)) {
1089 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
1090 "Failed to update the name of the component instance {} to {}. A component instance with the same name already exists. ",
1091 origInst.getName(), updatedCi.getName());
1092 throw new ByResponseFormatComponentException(componentsUtils
1093 .getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(), origInst.getName()));
1095 listForUpdate.add(updatedCi);
1097 listForUpdate.add(origInst);
1100 containerComponent.setComponentInstances(listForUpdate);
1101 Either<Component, StorageOperationStatus> updateStatus = toscaOperationFacade
1102 .updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, componentFilter);
1103 if (updateStatus.isRight()) {
1105 .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update metadata belonging to container component {}. Status is {}. ",
1106 containerComponent.getName(), updateStatus.right().value());
1107 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormatForResourceInstance(
1108 componentsUtils.convertFromStorageResponseForResourceInstance(updateStatus.right().value(), true), "", null));
1110 for (ComponentInstance updatedInstance : updateStatus.left().value().getComponentInstances()) {
1111 Optional<ComponentInstance> op = componentInstanceList.stream().filter(ci -> ci.getName().equals(updatedInstance.getName()))
1113 if (op.isPresent()) {
1114 updatedList.add(updatedInstance);
1119 } catch (ComponentException e) {
1124 unlockComponent(failed, containerComponent);
1129 private boolean validateParent(org.openecomp.sdc.be.model.Component containerComponent, String nodeTemplateId) {
1130 return containerComponent.getComponentInstances().stream().anyMatch(p -> p.getUniqueId().equals(nodeTemplateId));
1133 private ComponentTypeEnum getComponentType(ComponentTypeEnum containerComponentType) {
1134 if (ComponentTypeEnum.PRODUCT == containerComponentType) {
1135 return ComponentTypeEnum.SERVICE_INSTANCE;
1137 return ComponentTypeEnum.RESOURCE_INSTANCE;
1141 private ComponentInstance updateComponentInstanceMetadata(Component containerComponent, ComponentTypeEnum containerComponentType,
1142 org.openecomp.sdc.be.model.Component origComponent, String componentInstanceId,
1143 ComponentInstance componentInstance) {
1144 Optional<ComponentInstance> componentInstanceOptional;
1145 Either<ImmutablePair<Component, String>, StorageOperationStatus> updateRes = null;
1146 ComponentInstance oldComponentInstance = null;
1147 boolean isNameChanged = false;
1148 componentInstanceOptional = containerComponent.getComponentInstances().stream()
1149 .filter(ci -> ci.getUniqueId().equals(componentInstance.getUniqueId())).findFirst();
1150 if (!componentInstanceOptional.isPresent()) {
1151 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find the component instance {} in container component {}. ",
1152 componentInstance.getName(), containerComponent.getName());
1153 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName());
1155 String oldComponentName;
1156 oldComponentInstance = componentInstanceOptional.get();
1157 oldComponentName = oldComponentInstance.getName();
1158 String newInstanceName = componentInstance.getName();
1159 if (oldComponentName != null && !oldComponentInstance.getName().equals(newInstanceName)) {
1160 isNameChanged = true;
1162 Boolean isUniqueName = validateInstanceNameUniquenessUponUpdate(containerComponent, oldComponentInstance, newInstanceName);
1163 if (!Boolean.TRUE.equals(isUniqueName)) {
1164 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
1165 "Failed to update the name of the component instance {} to {}. A component instance with the same name already exists. ",
1166 oldComponentInstance.getName(), newInstanceName);
1167 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(),
1168 componentInstance.getName());
1170 if (!DirectivesUtil.isValid(componentInstance.getDirectives())) {
1171 final String directivesStr = componentInstance.getDirectives().stream().collect(Collectors.joining(" , ", " [ ", " ] "));
1172 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
1173 "Failed to update the directives of the component instance {} to {}. Directives data {} is invalid. ", oldComponentInstance.getName(),
1174 newInstanceName, directivesStr);
1175 throw new ByActionStatusComponentException(ActionStatus.DIRECTIVES_INVALID_VALUE, containerComponentType.getValue(),
1176 componentInstance.getName());
1178 updateRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, origComponent,
1179 updateComponentInstanceMetadata(oldComponentInstance, componentInstance));
1180 if (updateRes.isRight()) {
1181 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
1182 "Failed to update metadata of component instance {} belonging to container component {}. Status is {}. ", componentInstance.getName(),
1183 containerComponent.getName(), updateRes.right().value());
1184 throw new ByResponseFormatComponentException(componentsUtils
1185 .getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(updateRes.right().value(), true),
1188 // region - Update instance Groups
1189 if (isNameChanged) {
1190 Either<StorageOperationStatus, StorageOperationStatus> result = toscaOperationFacade
1191 .cleanAndAddGroupInstancesToComponentInstance(containerComponent, oldComponentInstance, componentInstanceId);
1192 if (result.isRight()) {
1194 .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to rename group instances for container {}. error {} ", componentInstanceId,
1195 result.right().value());
1197 if (containerComponent instanceof Service) {
1198 Either<ComponentInstance, ResponseFormat> renameEither = renameServiceFilter((Service) containerComponent, newInstanceName,
1199 oldComponentInstance.getName());
1200 if (renameEither.isRight()) {
1201 throw new ByResponseFormatComponentException(renameEither.right().value());
1203 updateForwardingPathDefinition(containerComponent, componentInstance, oldComponentName);
1208 String newInstanceId = updateRes.left().value().getRight();
1209 Optional<ComponentInstance> updatedInstanceOptional = updateRes.left().value().getLeft().getComponentInstances().stream()
1210 .filter(ci -> ci.getUniqueId().equals(newInstanceId)).findFirst();
1211 if (!updatedInstanceOptional.isPresent()) {
1212 log.debug("Failed to update metadata of component instance {} of container component {}", componentInstance.getName(),
1213 containerComponent.getName());
1214 throw new ByResponseFormatComponentException(
1215 componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName()));
1217 return componentInstanceOptional.get();
1220 private void updateForwardingPathDefinition(Component containerComponent, ComponentInstance componentInstance, String oldComponentName) {
1221 Collection<ForwardingPathDataDefinition> forwardingPathDataDefinitions = getForwardingPathDataDefinitions(containerComponent.getUniqueId());
1222 Set<ForwardingPathDataDefinition> updated = new ForwardingPathUtils()
1223 .updateComponentInstanceName(forwardingPathDataDefinitions, oldComponentName, componentInstance.getName());
1224 updated.forEach(fp -> {
1225 Either<ForwardingPathDataDefinition, StorageOperationStatus> resultEither = forwardingPathOperation
1226 .updateForwardingPath(containerComponent.getUniqueId(), fp);
1227 if (resultEither.isRight()) {
1228 CommonUtility.addRecordToLog(log, LogLevelEnum.ERROR, "Failed to rename forwarding path for container {}. error {} ",
1229 containerComponent.getName(), resultEither.right().value());
1234 public Either<ComponentInstance, ResponseFormat> renameServiceFilter(final Service containerComponent, final String newInstanceName,
1235 final String oldInstanceName) {
1236 Map<String, CINodeFilterDataDefinition> renamedNodesFilter = ServiceFilterUtils
1237 .getRenamedNodesFilter(containerComponent, oldInstanceName, newInstanceName);
1238 for (Entry<String, CINodeFilterDataDefinition> entry : renamedNodesFilter.entrySet()) {
1239 Either<CINodeFilterDataDefinition, StorageOperationStatus> renameEither = nodeFilterOperation
1240 .updateNodeFilter(containerComponent.getUniqueId(), entry.getKey(), entry.getValue());
1241 if (renameEither.isRight()) {
1242 return Either.right(componentsUtils.getResponseFormatForResourceInstance(
1243 componentsUtils.convertFromStorageResponse(renameEither.right().value(), ComponentTypeEnum.SERVICE), containerComponent.getName(),
1247 return Either.left(null);
1251 * @param oldPrefix- The normalized old vf name
1252 * @param newNormailzedPrefix- The normalized new vf name
1253 * @param qualifiedGroupInstanceName- old Group Instance Name
1256 // modify group names
1257 private String getNewGroupName(String oldPrefix, String newNormailzedPrefix, String qualifiedGroupInstanceName) {
1258 if (qualifiedGroupInstanceName == null) {
1259 log.info("CANNOT change group name ");
1262 if (qualifiedGroupInstanceName.startsWith(oldPrefix) || qualifiedGroupInstanceName
1263 .startsWith(ValidationUtils.normalizeComponentInstanceName(oldPrefix))) {
1264 return qualifiedGroupInstanceName.replaceFirst(oldPrefix, newNormailzedPrefix);
1266 return qualifiedGroupInstanceName;
1269 private ComponentInstance updateComponentInstanceMetadata(ComponentInstance oldComponentInstance, ComponentInstance newComponentInstance) {
1270 oldComponentInstance.setName(newComponentInstance.getName());
1271 oldComponentInstance.setModificationTime(System.currentTimeMillis());
1272 oldComponentInstance.setCustomizationUUID(UUID.randomUUID().toString());
1273 oldComponentInstance.setDirectives(newComponentInstance.getDirectives());
1274 oldComponentInstance.setMaxOccurrences(newComponentInstance.getMaxOccurrences());
1275 oldComponentInstance.setMinOccurrences(newComponentInstance.getMinOccurrences());
1276 oldComponentInstance.setInstanceCount(newComponentInstance.getInstanceCount());
1277 if (oldComponentInstance.getGroupInstances() != null) {
1278 oldComponentInstance.getGroupInstances().forEach(group -> group.setName(getNewGroupName(oldComponentInstance.getNormalizedName(),
1279 ValidationUtils.normalizeComponentInstanceName(newComponentInstance.getName()), group.getName())));
1281 return oldComponentInstance;
1284 public ComponentInstance deleteComponentInstance(final String containerComponentParam, final String containerComponentId,
1285 final String componentInstanceId, String userId) throws BusinessLogicException {
1286 validateUserExists(userId);
1287 final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
1288 final Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, null);
1289 validateCanWorkOnComponent(containerComponent, userId);
1290 boolean failed = false;
1291 final Optional<ComponentInstance> componentInstanceOptional = containerComponent.getComponentInstanceById(componentInstanceId);
1292 if (!componentInstanceOptional.isPresent()) {
1293 throw new BusinessLogicException(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND));
1295 ComponentInstance componentInstance = componentInstanceOptional.get();
1297 if (containerComponent instanceof Service || containerComponent instanceof Resource) {
1298 final Either<String, StorageOperationStatus> deleteServiceFilterEither = nodeFilterOperation
1299 .deleteNodeFilter(containerComponent, componentInstanceId);
1300 if (deleteServiceFilterEither.isRight()) {
1301 final ActionStatus status = componentsUtils
1302 .convertFromStorageResponse(deleteServiceFilterEither.right().value(), containerComponentType);
1303 janusGraphDao.rollback();
1304 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(status, componentInstanceId));
1306 final Either<ComponentInstance, ResponseFormat> resultOp = deleteNodeFiltersFromComponentInstance(containerComponent,
1307 componentInstance, containerComponentType, userId);
1308 if (resultOp.isRight()) {
1309 janusGraphDao.rollback();
1310 throw new ByResponseFormatComponentException(resultOp.right().value());
1313 lockComponent(containerComponent, "deleteComponentInstance");
1314 final ComponentInstance deletedCompInstance = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentType);
1315 componentInstance = deleteForwardingPathsRelatedTobeDeletedComponentInstance(containerComponentId, containerComponentType,
1316 deletedCompInstance);
1317 final ActionStatus onDeleteOperationsStatus = onChangeInstanceOperationOrchestrator
1318 .doOnDeleteInstanceOperations(containerComponent, componentInstanceId);
1319 if (ActionStatus.OK != onDeleteOperationsStatus) {
1320 throw new ByActionStatusComponentException(onDeleteOperationsStatus);
1322 } catch (final ComponentException e) {
1326 unlockComponent(failed, containerComponent);
1328 return componentInstance;
1332 * Try to modify the delete and return two cases
1334 * @param containerComponentParam
1335 * @param containerComponentId
1336 * @param componentInstanceId
1340 public Either<ComponentInstance, ResponseFormat> deleteAbstractComponentInstance(String containerComponentParam, String containerComponentId,
1341 String componentInstanceId, String userId) {
1342 log.debug("enter deleteAbstractComponentInstance");
1343 validateUserExists(userId);
1344 final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
1345 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, null);
1346 validateCanWorkOnComponent(containerComponent, userId);
1347 boolean failed = false;
1348 ComponentInstance deletedRelatedInst;
1350 if (containerComponent instanceof Service) {
1351 final Optional<ComponentInstance> componentInstanceById = containerComponent.getComponentInstanceById(componentInstanceId);
1352 if (componentInstanceById.isPresent()) {
1353 ComponentInstance componentInstance = componentInstanceById.get();
1354 Either<String, StorageOperationStatus> deleteServiceFilterEither = nodeFilterOperation
1355 .deleteNodeFilter(containerComponent, componentInstanceId);
1356 if (deleteServiceFilterEither.isRight()) {
1357 log.debug("enter deleteAbstractComponentInstance:deleteServiceFilterEither is right, filed");
1358 ActionStatus status = componentsUtils
1359 .convertFromStorageResponse(deleteServiceFilterEither.right().value(), containerComponentType);
1360 janusGraphDao.rollback();
1361 return Either.right(componentsUtils.getResponseFormat(status, componentInstance.getName()));
1363 Either<ComponentInstance, ResponseFormat> resultOp = deleteNodeFiltersFromComponentInstance(containerComponent, componentInstance,
1364 ComponentTypeEnum.SERVICE, userId);
1365 if (resultOp.isRight()) {
1366 log.debug("enter deleteAbstractComponentInstance:resultOp is right, filed");
1367 janusGraphDao.rollback();
1372 log.debug("enter deleteAbstractComponentInstance:");
1373 lockComponent(containerComponent, "deleteComponentInstance");
1374 ComponentInstance deletedCompInstance = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentType);
1375 deletedRelatedInst = deleteForwardingPathsRelatedTobeDeletedComponentInstance(containerComponentId, containerComponentType,
1376 deletedCompInstance);
1377 ActionStatus onDeleteOperationsStatus = onChangeInstanceOperationOrchestrator
1378 .doOnDeleteInstanceOperations(containerComponent, componentInstanceId);
1379 log.debug("enter deleteAbstractComponentInstance,get onDeleteOperationsStatus:{}", onDeleteOperationsStatus);
1380 if (ActionStatus.OK != onDeleteOperationsStatus) {
1381 throw new ByActionStatusComponentException(onDeleteOperationsStatus);
1383 } catch (ComponentException e) {
1387 unlockComponent(failed, containerComponent);
1389 log.debug("enter deleteAbstractComponentInstance,deleted RelatedInst success");
1390 return Either.left(deletedRelatedInst);
1393 public Either<ComponentInstance, ResponseFormat> deleteNodeFiltersFromComponentInstance(final Component component,
1394 final ComponentInstance componentInstance,
1395 final ComponentTypeEnum containerComponentType,
1396 final String userId) {
1397 final Set<String> componentFiltersIDsToBeDeleted = getComponentFiltersRelatedToComponentInstance(component.getUniqueId(), componentInstance);
1398 if (!componentFiltersIDsToBeDeleted.isEmpty()) {
1399 final Set<String> ids = component.getComponentInstances().stream().filter(ci -> componentFiltersIDsToBeDeleted.contains(ci.getName()))
1400 .map(ComponentInstance::getUniqueId).collect(Collectors.toSet());
1401 final Either<Set<String>, StorageOperationStatus> deleteComponentNodeFiltersEither = nodeFilterOperation
1402 .deleteNodeFilters(component, ids);
1403 if (deleteComponentNodeFiltersEither.isRight()) {
1404 final ActionStatus status = componentsUtils
1405 .convertFromStorageResponse(deleteComponentNodeFiltersEither.right().value(), containerComponentType);
1406 return Either.right(componentsUtils.getResponseFormat(status, componentInstance.getName()));
1408 for (final String id : ids) {
1409 final Optional<ComponentInstance> componentInstanceById = component.getComponentInstanceById(id);
1410 if (!componentInstanceById.isPresent()) {
1411 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
1413 final ComponentInstance componentInstanceToBeUpdated = componentInstanceById.get();
1414 componentInstanceToBeUpdated.setDirectives(Collections.emptyList());
1415 final Either<ComponentInstance, ResponseFormat> componentInstanceResponseFormatEither = updateComponentInstanceMetadata(
1416 containerComponentType.getValue(), component.getUniqueId(), componentInstanceToBeUpdated.getUniqueId(), userId,
1417 componentInstanceToBeUpdated, false);
1418 if (componentInstanceResponseFormatEither.isRight()) {
1419 return componentInstanceResponseFormatEither;
1423 return Either.left(componentInstance);
1426 private Set<String> getComponentFiltersRelatedToComponentInstance(String containerComponentId, ComponentInstance componentInstance) {
1427 ComponentParametersView filter = new ComponentParametersView(true);
1428 filter.setIgnoreComponentInstances(false);
1429 Either<Component, StorageOperationStatus> componentFilterOrigin = toscaOperationFacade.getToscaElement(containerComponentId, filter);
1430 final Component component = componentFilterOrigin.left().value();
1431 return ComponentsUtils.getNodesFiltersToBeDeleted(component, componentInstance);
1434 ComponentInstance deleteForwardingPathsRelatedTobeDeletedComponentInstance(String containerComponentId, ComponentTypeEnum containerComponentType,
1435 ComponentInstance componentInstance) {
1436 if (containerComponentType == ComponentTypeEnum.SERVICE) {
1437 List<String> pathIDsToBeDeleted = getForwardingPathsRelatedToComponentInstance(containerComponentId, componentInstance.getName());
1438 if (!pathIDsToBeDeleted.isEmpty()) {
1439 deleteForwardingPaths(containerComponentId, pathIDsToBeDeleted);
1442 return componentInstance;
1445 private void deleteForwardingPaths(String serviceId, List<String> pathIdsToDelete) {
1446 Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(serviceId);
1447 if (storageStatus.isRight()) {
1448 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(storageStatus.right().value()));
1450 Either<Set<String>, StorageOperationStatus> result = forwardingPathOperation
1451 .deleteForwardingPath(storageStatus.left().value(), Sets.newHashSet(pathIdsToDelete));
1452 if (result.isRight()) {
1453 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(result.right().value()));
1457 private List<String> getForwardingPathsRelatedToComponentInstance(String containerComponentId, String componentInstanceId) {
1458 Collection<ForwardingPathDataDefinition> allPaths = getForwardingPathDataDefinitions(containerComponentId);
1459 List<String> pathIDsToBeDeleted = new ArrayList<>();
1460 allPaths.stream().filter(path -> isPathRelatedToComponent(path, componentInstanceId))
1461 .forEach(path -> pathIDsToBeDeleted.add(path.getUniqueId()));
1462 return pathIDsToBeDeleted;
1465 private Collection<ForwardingPathDataDefinition> getForwardingPathDataDefinitions(String containerComponentId) {
1466 ComponentParametersView filter = new ComponentParametersView(true);
1467 filter.setIgnoreServicePath(false);
1468 Either<Service, StorageOperationStatus> forwardingPathOrigin = toscaOperationFacade.getToscaElement(containerComponentId, filter);
1469 return forwardingPathOrigin.left().value().getForwardingPaths().values();
1472 private boolean isPathRelatedToComponent(ForwardingPathDataDefinition pathDataDefinition, String componentInstanceId) {
1473 return pathDataDefinition.getPathElements().getListToscaDataDefinition().stream().anyMatch(
1474 elementDataDefinition -> elementDataDefinition.getFromNode().equalsIgnoreCase(componentInstanceId) || elementDataDefinition.getToNode()
1475 .equalsIgnoreCase(componentInstanceId));
1478 private ComponentInstance deleteComponentInstance(Component containerComponent, String componentInstanceId,
1479 ComponentTypeEnum containerComponentType) {
1480 Either<ImmutablePair<Component, String>, StorageOperationStatus> deleteRes = toscaOperationFacade
1481 .deleteComponentInstanceFromTopologyTemplate(containerComponent, componentInstanceId);
1482 if (deleteRes.isRight()) {
1483 log.debug("Failed to delete entry on graph for resourceInstance {}", componentInstanceId);
1484 ActionStatus status = componentsUtils.convertFromStorageResponse(deleteRes.right().value(), containerComponentType);
1485 throw new ByActionStatusComponentException(status, componentInstanceId);
1487 log.debug("The component instance {} has been removed from container component {}. ", componentInstanceId, containerComponent);
1488 ComponentInstance deletedInstance = findAndRemoveComponentInstanceFromContainerComponent(componentInstanceId, containerComponent);
1489 if (CollectionUtils.isNotEmpty(containerComponent.getInputs())) {
1490 List<InputDefinition> inputsToDelete = containerComponent.getInputs().stream()
1491 .filter(i -> i.getInstanceUniqueId() != null && i.getInstanceUniqueId().equals(componentInstanceId)).collect(Collectors.toList());
1492 if (CollectionUtils.isNotEmpty(inputsToDelete)) {
1493 StorageOperationStatus deleteInputsRes = toscaOperationFacade
1494 .deleteComponentInstanceInputsFromTopologyTemplate(containerComponent, inputsToDelete);
1495 if (deleteInputsRes != StorageOperationStatus.OK) {
1496 log.debug("Failed to delete inputs of the component instance {} from container component. ", componentInstanceId);
1497 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(deleteInputsRes, containerComponentType),
1498 componentInstanceId);
1502 if (CollectionUtils.isNotEmpty(containerComponent.getOutputs())) {
1503 final List<OutputDefinition> outputsToDelete = containerComponent.getOutputs().stream()
1504 .filter(i -> i.getInstanceUniqueId() != null && i.getInstanceUniqueId().equals(componentInstanceId)).collect(Collectors.toList());
1505 if (CollectionUtils.isNotEmpty(outputsToDelete)) {
1506 final StorageOperationStatus deleteOutputsRes = toscaOperationFacade
1507 .deleteComponentInstanceOutputsFromTopologyTemplate(containerComponent, outputsToDelete);
1508 if (deleteOutputsRes != StorageOperationStatus.OK) {
1509 log.debug("Failed to delete outputs of the component instance {} from container component. ", componentInstanceId);
1510 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(deleteOutputsRes, containerComponentType),
1511 componentInstanceId);
1515 return deletedInstance;
1518 private ComponentInstance findAndRemoveComponentInstanceFromContainerComponent(String componentInstanceId, Component containerComponent) {
1519 ComponentInstance foundInstance = null;
1520 for (ComponentInstance instance : containerComponent.getComponentInstances()) {
1521 if (instance.getUniqueId().equals(componentInstanceId)) {
1522 foundInstance = instance;
1523 containerComponent.getComponentInstances().remove(instance);
1527 findAndRemoveComponentInstanceRelations(componentInstanceId, containerComponent);
1528 return foundInstance;
1531 private void findAndRemoveComponentInstanceRelations(String componentInstanceId, Component containerComponent) {
1532 if (CollectionUtils.isNotEmpty(containerComponent.getComponentInstancesRelations())) {
1533 containerComponent.setComponentInstancesRelations(
1534 containerComponent.getComponentInstancesRelations().stream().filter(r -> isNotBelongingRelation(componentInstanceId, r))
1535 .collect(Collectors.toList()));
1539 private boolean isNotBelongingRelation(String componentInstanceId, RequirementCapabilityRelDef relation) {
1540 return !relation.getToNode().equals(componentInstanceId) && !relation.getFromNode().equals(componentInstanceId);
1543 public RequirementCapabilityRelDef associateRIToRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef,
1544 ComponentTypeEnum componentTypeEnum) {
1545 return associateRIToRI(componentId, userId, requirementDef, componentTypeEnum, true);
1548 public RequirementCapabilityRelDef associateRIToRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef,
1549 ComponentTypeEnum componentTypeEnum, boolean needLock) {
1550 validateUserExists(userId);
1551 RequirementCapabilityRelDef requirementCapabilityRelDef;
1552 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(componentId, componentTypeEnum, null);
1553 validateCanWorkOnComponent(containerComponent, userId);
1554 boolean failed = false;
1557 lockComponent(containerComponent, ASSOCIATE_RI_TO_RI);
1559 requirementCapabilityRelDef = associateRIToRIOnGraph(containerComponent, requirementDef);
1560 } catch (ComponentException e) {
1565 unlockComponent(failed, containerComponent);
1568 return requirementCapabilityRelDef;
1571 public RequirementCapabilityRelDef associateRIToRIOnGraph(Component containerComponent, RequirementCapabilityRelDef requirementDef) {
1572 log.debug(TRY_TO_CREATE_ENTRY_ON_GRAPH);
1573 Either<RequirementCapabilityRelDef, StorageOperationStatus> result = toscaOperationFacade
1574 .associateResourceInstances(null, containerComponent.getUniqueId(), requirementDef);
1575 if (result.isLeft()) {
1576 log.debug(ENTITY_ON_GRAPH_IS_CREATED);
1577 return result.left().value();
1579 log.debug("Failed to associate node: {} with node {}", requirementDef.getFromNode(), requirementDef.getToNode());
1580 String fromNameOrId = "";
1581 String toNameOrId = "";
1582 Either<ComponentInstance, StorageOperationStatus> fromResult = getResourceInstanceById(containerComponent, requirementDef.getFromNode());
1583 Either<ComponentInstance, StorageOperationStatus> toResult = getResourceInstanceById(containerComponent, requirementDef.getToNode());
1584 toNameOrId = requirementDef.getFromNode();
1585 fromNameOrId = requirementDef.getFromNode();
1586 if (fromResult.isLeft()) {
1587 fromNameOrId = fromResult.left().value().getName();
1589 if (toResult.isLeft()) {
1590 toNameOrId = toResult.left().value().getName();
1592 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true),
1593 fromNameOrId, toNameOrId, requirementDef.getRelationships().get(0).getRelation().getRequirement());
1598 * @param componentId
1600 * @param requirementDefList
1601 * @param componentTypeEnum
1604 public List<RequirementCapabilityRelDef> batchDissociateRIFromRI(String componentId, String userId,
1605 List<RequirementCapabilityRelDef> requirementDefList,
1606 ComponentTypeEnum componentTypeEnum) {
1607 validateUserExists(userId);
1608 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(componentId, componentTypeEnum, null);
1609 validateCanWorkOnComponent(containerComponent, userId);
1610 boolean failed = false;
1611 List<RequirementCapabilityRelDef> delOkResult = new ArrayList<>();
1613 lockComponent(containerComponent, ASSOCIATE_RI_TO_RI);
1614 for (RequirementCapabilityRelDef requirementDef : requirementDefList) {
1615 RequirementCapabilityRelDef requirementCapabilityRelDef = dissociateRIFromRI(componentId, userId, requirementDef,
1616 containerComponent.getComponentType());
1617 delOkResult.add(requirementCapabilityRelDef);
1619 } catch (ComponentException e) {
1623 unlockComponent(failed, containerComponent);
1628 public RequirementCapabilityRelDef dissociateRIFromRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef,
1629 ComponentTypeEnum componentTypeEnum) {
1630 validateUserExists(userId);
1631 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(componentId, componentTypeEnum, null);
1632 validateCanWorkOnComponent(containerComponent, userId);
1633 boolean failed = false;
1635 lockComponent(containerComponent, ASSOCIATE_RI_TO_RI);
1636 log.debug(TRY_TO_CREATE_ENTRY_ON_GRAPH);
1637 Either<RequirementCapabilityRelDef, StorageOperationStatus> result = toscaOperationFacade
1638 .dissociateResourceInstances(componentId, requirementDef);
1639 if (result.isLeft()) {
1640 log.debug(ENTITY_ON_GRAPH_IS_CREATED);
1641 return result.left().value();
1643 log.debug("Failed to dissocaite node {} from node {}", requirementDef.getFromNode(), requirementDef.getToNode());
1644 String fromNameOrId = "";
1645 String toNameOrId = "";
1646 Either<ComponentInstance, StorageOperationStatus> fromResult = getResourceInstanceById(containerComponent,
1647 requirementDef.getFromNode());
1648 Either<ComponentInstance, StorageOperationStatus> toResult = getResourceInstanceById(containerComponent, requirementDef.getToNode());
1649 toNameOrId = requirementDef.getFromNode();
1650 fromNameOrId = requirementDef.getFromNode();
1651 if (fromResult.isLeft()) {
1652 fromNameOrId = fromResult.left().value().getName();
1654 if (toResult.isLeft()) {
1655 toNameOrId = toResult.left().value().getName();
1657 throw new ByActionStatusComponentException(
1658 componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), fromNameOrId, toNameOrId,
1659 requirementDef.getRelationships().get(0).getRelation().getRequirement());
1661 } catch (ComponentException e) {
1665 unlockComponent(failed, containerComponent);
1670 * Allows to get relation contained in specified component according to received Id
1672 * @param componentId
1675 * @param componentTypeEnum
1678 public Either<RequirementCapabilityRelDef, ResponseFormat> getRelationById(String componentId, String relationId, String userId,
1679 ComponentTypeEnum componentTypeEnum) {
1680 Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null;
1682 org.openecomp.sdc.be.model.Component containerComponent = null;
1683 RequirementCapabilityRelDef foundRelation = null;
1684 validateUserExists(userId);
1685 containerComponent = validateComponentExists(componentId, componentTypeEnum, null);
1686 List<RequirementCapabilityRelDef> requirementCapabilityRelations = containerComponent.getComponentInstancesRelations();
1687 foundRelation = findRelation(relationId, requirementCapabilityRelations);
1688 if (foundRelation == null) {
1689 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RELATION_NOT_FOUND, relationId, componentId);
1690 log.debug("Relation with id {} was not found on the component", relationId, componentId);
1691 resultOp = Either.right(responseFormat);
1693 if (resultOp == null) {
1694 resultOp = setRelatedCapability(foundRelation, containerComponent);
1696 if (resultOp.isLeft()) {
1697 resultOp = setRelatedRequirement(foundRelation, containerComponent);
1699 } catch (Exception e) {
1700 log.error("The exception {} occured upon get relation {} of the component {} ", e, relationId, componentId);
1701 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
1706 private RequirementCapabilityRelDef findRelation(String relationId, List<RequirementCapabilityRelDef> requirementCapabilityRelations) {
1707 for (RequirementCapabilityRelDef relationship : requirementCapabilityRelations) {
1708 if (relationship.getRelationships().stream().anyMatch(r -> r.getRelation().getId().equals(relationId))) {
1709 return relationship;
1715 private Either<RequirementCapabilityRelDef, ResponseFormat> setRelatedRequirement(RequirementCapabilityRelDef foundRelation,
1716 Component containerComponent) {
1717 Either<RequirementCapabilityRelDef, ResponseFormat> result = null;
1718 RelationshipInfo relationshipInfo = foundRelation.resolveSingleRelationship().getRelation();
1719 String instanceId = foundRelation.getFromNode();
1720 Optional<RequirementDefinition> foundRequirement;
1721 Optional<ComponentInstance> instance = containerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(instanceId))
1723 if (!instance.isPresent()) {
1724 ResponseFormat responseFormat = componentsUtils
1725 .getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, instanceId, "instance",
1726 containerComponent.getComponentType().getValue(), containerComponent.getName());
1727 log.debug("Component instance with id {} was not found on the component", instanceId, containerComponent.getUniqueId());
1728 result = Either.right(responseFormat);
1730 if (result == null && instance.isPresent()) {
1731 for (List<RequirementDefinition> requirements : instance.get().getRequirements().values()) {
1732 foundRequirement = requirements.stream()
1733 .filter(r -> isBelongingCalcRequirement(relationshipInfo, r, containerComponent.getLifecycleState())).findFirst();
1734 if (foundRequirement.isPresent()) {
1735 foundRelation.resolveSingleRelationship().setRequirement(foundRequirement.get());
1736 result = Either.left(foundRelation);
1740 if (result == null) {
1741 Either<RequirementDataDefinition, StorageOperationStatus> getfulfilledRequirementRes = toscaOperationFacade
1742 .getFulfilledRequirementByRelation(containerComponent.getUniqueId(), instanceId, foundRelation, this::isBelongingFullRequirement);
1743 if (getfulfilledRequirementRes.isRight()) {
1744 ResponseFormat responseFormat = componentsUtils
1745 .getResponseFormat(ActionStatus.REQUIREMENT_OF_INSTANCE_NOT_FOUND_ON_CONTAINER, relationshipInfo.getRequirement(), instanceId,
1746 containerComponent.getUniqueId());
1747 log.debug("Requirement {} of instance {} was not found on the container {}. ", relationshipInfo.getCapability(), instanceId,
1748 containerComponent.getUniqueId());
1749 result = Either.right(responseFormat);
1751 foundRelation.resolveSingleRelationship().setRequirement(getfulfilledRequirementRes.left().value());
1754 if (result == null) {
1755 result = Either.left(foundRelation);
1760 private boolean isBelongingFullRequirement(RelationshipInfo relationshipInfo, RequirementDataDefinition req) {
1761 return req.getName().equals(relationshipInfo.getRequirement()) && req.getUniqueId().equals(relationshipInfo.getRequirementUid()) && req
1762 .getOwnerId().equals(relationshipInfo.getRequirementOwnerId());
1765 private boolean isBelongingCalcRequirement(RelationshipInfo relationshipInfo, RequirementDataDefinition req, LifecycleStateEnum state) {
1766 return nameMatches(relationshipInfo.getRequirement(), req.getName(), req.getPreviousName(), state) && req.getUniqueId()
1767 .equals(relationshipInfo.getRequirementUid()) && req.getOwnerId().equals(relationshipInfo.getRequirementOwnerId());
1770 private Either<RequirementCapabilityRelDef, ResponseFormat> setRelatedCapability(RequirementCapabilityRelDef foundRelation,
1771 Component containerComponent) {
1772 Either<RequirementCapabilityRelDef, ResponseFormat> result = null;
1773 RelationshipInfo relationshipInfo = foundRelation.resolveSingleRelationship().getRelation();
1774 String instanceId = foundRelation.getToNode();
1775 Optional<CapabilityDefinition> foundCapability;
1776 Optional<ComponentInstance> instance = containerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(instanceId))
1778 if (!instance.isPresent()) {
1779 ResponseFormat responseFormat = componentsUtils
1780 .getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, instanceId, "instance",
1781 containerComponent.getComponentType().getValue(), containerComponent.getName());
1782 log.debug("Component instance with id {} was not found on the component", instanceId, containerComponent.getUniqueId());
1783 result = Either.right(responseFormat);
1785 if (result == null && instance.isPresent()) {
1786 for (List<CapabilityDefinition> capabilities : instance.get().getCapabilities().values()) {
1787 foundCapability = capabilities.stream()
1788 .filter(c -> isBelongingCalcCapability(relationshipInfo, c, containerComponent.getLifecycleState())).findFirst();
1789 if (foundCapability.isPresent()) {
1790 foundRelation.resolveSingleRelationship().setCapability(foundCapability.get());
1791 result = Either.left(foundRelation);
1795 if (result == null) {
1796 Either<CapabilityDataDefinition, StorageOperationStatus> getfulfilledRequirementRes = toscaOperationFacade
1797 .getFulfilledCapabilityByRelation(containerComponent.getUniqueId(), instanceId, foundRelation, this::isBelongingFullCapability);
1798 if (getfulfilledRequirementRes.isRight()) {
1799 ResponseFormat responseFormat = componentsUtils
1800 .getResponseFormat(ActionStatus.CAPABILITY_OF_INSTANCE_NOT_FOUND_ON_CONTAINER, relationshipInfo.getCapability(), instanceId,
1801 containerComponent.getUniqueId());
1802 log.debug("Capability {} of instance {} was not found on the container {}. ", relationshipInfo.getCapability(), instanceId,
1803 containerComponent.getUniqueId());
1804 result = Either.right(responseFormat);
1806 foundRelation.resolveSingleRelationship().setCapability(getfulfilledRequirementRes.left().value());
1809 if (result == null) {
1810 result = Either.left(foundRelation);
1815 private boolean isBelongingFullCapability(RelationshipInfo relationshipInfo, CapabilityDataDefinition cap) {
1816 return cap.getName().equals(relationshipInfo.getCapability()) && cap.getUniqueId().equals(relationshipInfo.getCapabilityUid()) && cap
1817 .getOwnerId().equals(relationshipInfo.getCapabilityOwnerId());
1820 private boolean isBelongingCalcCapability(RelationshipInfo relationshipInfo, CapabilityDataDefinition cap, LifecycleStateEnum state) {
1821 return nameMatches(relationshipInfo.getCapability(), cap.getName(), cap.getPreviousName(), state) && cap.getUniqueId()
1822 .equals(relationshipInfo.getCapabilityUid()) && cap.getOwnerId().equals(relationshipInfo.getCapabilityOwnerId());
1825 private boolean nameMatches(String nameFromRelationship, String currName, String previousName, LifecycleStateEnum state) {
1826 return state == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT ? currName.equals(nameFromRelationship)
1827 : previousName != null && previousName.equals(nameFromRelationship);
1830 private Either<ComponentInstanceProperty, ResponseFormat> updateAttributeValue(ComponentInstanceProperty attribute, String resourceInstanceId) {
1831 Either<ComponentInstanceProperty, StorageOperationStatus> eitherAttribute = componentInstanceOperation
1832 .updateAttributeValueInResourceInstance(attribute, resourceInstanceId, true);
1833 Either<ComponentInstanceProperty, ResponseFormat> result;
1834 if (eitherAttribute.isLeft()) {
1835 log.debug("Attribute value {} was updated on graph.", attribute.getValueUniqueUid());
1836 ComponentInstanceProperty instanceAttribute = eitherAttribute.left().value();
1837 result = Either.left(instanceAttribute);
1839 log.debug("Failed to update attribute value {} in resource instance {}", attribute, resourceInstanceId);
1840 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(eitherAttribute.right().value());
1841 result = Either.right(componentsUtils.getResponseFormat(actionStatus, ""));
1846 private Either<ComponentInstanceProperty, ResponseFormat> createAttributeValue(ComponentInstanceProperty attribute, String resourceInstanceId) {
1847 Either<ComponentInstanceProperty, ResponseFormat> result;
1848 Wrapper<Integer> indexCounterWrapper = new Wrapper<>();
1849 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
1850 validateIncrementCounter(resourceInstanceId, GraphPropertiesDictionary.ATTRIBUTE_COUNTER, indexCounterWrapper, errorWrapper);
1851 if (!errorWrapper.isEmpty()) {
1852 result = Either.right(errorWrapper.getInnerElement());
1854 Either<ComponentInstanceProperty, StorageOperationStatus> eitherAttribute = componentInstanceOperation
1855 .addAttributeValueToResourceInstance(attribute, resourceInstanceId, indexCounterWrapper.getInnerElement(), true);
1856 if (eitherAttribute.isLeft()) {
1857 log.debug("Attribute value was added to resource instance {}", resourceInstanceId);
1858 ComponentInstanceProperty instanceAttribute = eitherAttribute.left().value();
1859 result = Either.left(instanceAttribute);
1861 log.debug("Failed to add attribute value {} to resource instance {}", attribute, resourceInstanceId);
1862 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(eitherAttribute.right().value());
1863 result = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1870 * Create Or Updates Attribute Instance
1872 * @param componentTypeEnum
1873 * @param componentId
1874 * @param resourceInstanceId
1879 public Either<ComponentInstanceProperty, ResponseFormat> createOrUpdateAttributeValue(ComponentTypeEnum componentTypeEnum, String componentId,
1880 String resourceInstanceId,
1881 ComponentInstanceProperty attribute, String userId) {
1882 Either<ComponentInstanceProperty, ResponseFormat> result = null;
1883 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
1884 validateUserExists(userId);
1885 if (errorWrapper.isEmpty()) {
1886 validateComponentTypeEnum(componentTypeEnum, "CreateOrUpdateAttributeValue", errorWrapper);
1888 if (errorWrapper.isEmpty()) {
1889 validateCanWorkOnComponent(componentId, componentTypeEnum, userId, errorWrapper);
1891 if (errorWrapper.isEmpty()) {
1892 validateComponentLock(componentId, componentTypeEnum, errorWrapper);
1895 if (errorWrapper.isEmpty()) {
1896 final boolean isCreate = Objects.isNull(attribute.getValueUniqueUid());
1898 result = createAttributeValue(attribute, resourceInstanceId);
1900 result = updateAttributeValue(attribute, resourceInstanceId);
1903 result = Either.right(errorWrapper.getInnerElement());
1907 if (result == null || result.isRight()) {
1908 janusGraphDao.rollback();
1910 janusGraphDao.commit();
1913 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
1917 public Either<List<ComponentInstanceProperty>, ResponseFormat> createOrUpdatePropertiesValues(ComponentTypeEnum componentTypeEnum,
1918 String componentId, String resourceInstanceId,
1919 List<ComponentInstanceProperty> properties,
1921 Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
1922 /*-------------------------------Validations---------------------------------*/
1923 validateUserExists(userId);
1925 if (componentTypeEnum == null) {
1926 BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertiesValues", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
1927 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
1930 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
1932 if (getResourceResult.isRight()) {
1933 log.debug(FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID, componentId);
1934 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getResourceResult.right().value(), componentTypeEnum);
1935 return Either.right(componentsUtils.getResponseFormat(actionStatus, componentId));
1937 Component containerComponent = getResourceResult.left().value();
1939 if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
1940 if (Boolean.TRUE.equals(containerComponent.isArchived())) {
1941 log.info(COMPONENT_ARCHIVED, componentId);
1942 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_IS_ARCHIVED, containerComponent.getName()));
1944 log.info(RESTRICTED_OPERATION_ON_SERVIVE, userId, componentId);
1945 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1948 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId);
1949 if (resourceInstanceStatus.isRight()) {
1950 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER,
1951 resourceInstanceId, RESOURCE_INSTANCE, SERVICE, componentId));
1953 ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
1956 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
1957 if (lockStatus != StorageOperationStatus.OK) {
1958 log.debug(FAILED_TO_LOCK_SERVICE, componentId);
1959 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
1961 List<ComponentInstanceProperty> updatedProperties = new ArrayList<>();
1963 for (ComponentInstanceProperty property : properties) {
1964 validateMandatoryFields(property);
1965 validatePropertyExistsOnComponent(property, containerComponent, foundResourceInstance);
1966 String propertyParentUniqueId = property.getParentUniqueId();
1967 if (property.isToscaFunction()) {
1968 toscaFunctionValidator.validate(property, containerComponent);
1969 property.setValue(property.getToscaFunction().getValue());
1971 if (CollectionUtils.isNotEmpty(property.getSubPropertyToscaFunctions())){
1972 final JSONObject jObject = property.getValue() == null ? new JSONObject() : new JSONObject(property.getValue());
1973 property.getSubPropertyToscaFunctions().stream().forEach(subToscaFunction -> {
1974 setJsonObjectForSubProperty(jObject, subToscaFunction.getSubPropertyPath(), subToscaFunction.getToscaFunction().getValue());
1976 property.setValue(jObject.toString());
1978 Either<String, ResponseFormat> updatedPropertyValue = updatePropertyObjectValue(property, containerComponent.getModel());
1979 if (updatedPropertyValue.isRight()) {
1980 log.error("Failed to update property object value of property: {}",
1982 throw new ByResponseFormatComponentException(updatedPropertyValue.right().value());
1984 Optional<CapabilityDefinition>
1985 capPropDefinition = getPropertyCapabilityOfChildInstance(propertyParentUniqueId, foundResourceInstance.getCapabilities());
1986 if (capPropDefinition.isPresent()) {
1987 updatedPropertyValue
1988 .bimap(updatedValue -> updateCapabilityPropFromUpdateInstProp(property, updatedValue,
1989 containerComponent, foundResourceInstance, capPropDefinition.get().getType(),
1990 capPropDefinition.get().getName()), Either::right);
1992 updatedPropertyValue.bimap(
1993 updatedValue -> updatePropertyOnContainerComponent(property, updatedValue, containerComponent, foundResourceInstance),
1996 updatedProperties.add(property);
2000 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade
2001 .updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
2002 if (updateContainerRes.isRight()) {
2003 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
2004 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2007 resultOp = Either.left(updatedProperties);
2010 } catch (final ComponentException e) {
2011 return Either.right(e.getResponseFormat());
2013 if (resultOp == null || resultOp.isRight()) {
2014 janusGraphDao.rollback();
2016 janusGraphDao.commit();
2019 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
2023 private void setJsonObjectForSubProperty(final JSONObject jObject, final List<String> path, String value) {
2024 if (path.size() == 1) {
2025 if (!value.startsWith("{")) {
2026 value = new StringBuilder("{").append(value).append("}").toString();
2028 final JSONObject jObjectSub = new JSONObject(value);
2029 jObject.put(path.get(0), jObjectSub);
2031 if (!jObject.has(path.get(0))) {
2032 jObject.put(path.get(0), new JSONObject());
2034 final JSONObject jsonObject = jObject.getJSONObject(path.get(0));
2035 setJsonObjectForSubProperty(jsonObject, path.subList(1, path.size()), value);
2039 public Either<List<ComponentInstanceAttribute>, ResponseFormat> createOrUpdateAttributeValues(final ComponentTypeEnum componentTypeEnum,
2040 final String componentId,
2041 final String resourceInstanceId,
2042 final List<ComponentInstanceAttribute> attributes,
2043 final String userId) {
2044 Either<List<ComponentInstanceAttribute>, ResponseFormat> resultOp = null;
2045 /*-------------------------------Validations---------------------------------*/
2046 validateUserExists(userId);
2048 if (componentTypeEnum == null) {
2049 BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertiesValues", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
2050 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
2053 final Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade
2054 .getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
2056 if (getResourceResult.isRight()) {
2057 log.debug(FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID, componentId);
2058 final ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getResourceResult.right().value(), componentTypeEnum);
2059 return Either.right(componentsUtils.getResponseFormat(actionStatus, componentId));
2061 final Component containerComponent = getResourceResult.left().value();
2063 if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
2064 if (Boolean.TRUE.equals(containerComponent.isArchived())) {
2065 log.info(COMPONENT_ARCHIVED, componentId);
2066 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_IS_ARCHIVED, containerComponent.getName()));
2068 log.info(RESTRICTED_OPERATION_ON_SERVIVE, userId, componentId);
2069 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2072 final Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent,
2073 resourceInstanceId);
2074 if (resourceInstanceStatus.isRight()) {
2075 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER,
2076 resourceInstanceId, RESOURCE_INSTANCE, SERVICE, componentId));
2078 final ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
2081 final StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
2082 if (lockStatus != StorageOperationStatus.OK) {
2083 log.debug(FAILED_TO_LOCK_SERVICE, componentId);
2084 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
2086 final List<ComponentInstanceAttribute> updatedProperties = new ArrayList<>();
2088 for (final ComponentInstanceAttribute attribute : attributes) {
2089 final ComponentInstanceAttribute componentInstanceProperty = validateAttributeExistsOnComponent(attribute, containerComponent,
2090 foundResourceInstance);
2091 final Either<String, ResponseFormat> updatedPropertyValue = updateAttributeObjectValue(attribute);
2092 if (updatedPropertyValue.isRight()) {
2093 log.error("Failed to update attribute object value of attribute: {}", attribute);
2094 throw new ByResponseFormatComponentException(updatedPropertyValue.right().value());
2096 updatedPropertyValue.bimap(
2098 componentInstanceProperty.setValue(updatedValue);
2099 return updateAttributeOnContainerComponent(attribute, updatedValue,
2100 containerComponent, foundResourceInstance);
2102 updatedProperties.add(componentInstanceProperty);
2105 final Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade
2106 .updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
2107 if (updateContainerRes.isRight()) {
2108 final ActionStatus actionStatus = componentsUtils
2109 .convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
2110 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2113 resultOp = Either.left(updatedProperties);
2116 } catch (final ComponentException e) {
2117 return Either.right(e.getResponseFormat());
2119 if (resultOp == null || resultOp.isRight()) {
2120 janusGraphDao.rollback();
2122 janusGraphDao.commit();
2125 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
2129 private void validateMandatoryFields(PropertyDataDefinition property) {
2130 if (StringUtils.isEmpty(property.getName())) {
2131 throw new ByActionStatusComponentException(ActionStatus.MISSING_PROPERTY_NAME);
2135 private void validatePropertyExistsOnComponent(ComponentInstanceProperty property, Component containerComponent,
2136 ComponentInstance foundResourceInstance) {
2137 List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties()
2138 .get(foundResourceInstance.getUniqueId());
2139 final boolean hasProperty = instanceProperties.stream().anyMatch(p -> p.getName().equals(property.getName()));
2141 throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND, property.getName());
2145 private ComponentInstanceAttribute validateAttributeExistsOnComponent(final ComponentInstanceAttribute attribute,
2146 final Component containerComponent,
2147 final ComponentInstance foundResourceInstance) {
2148 final List<ComponentInstanceAttribute> instanceProperties =
2149 containerComponent.getComponentInstancesAttributes().get(foundResourceInstance.getUniqueId());
2150 final Optional<ComponentInstanceAttribute> instanceAttribute =
2151 instanceProperties.stream().filter(p -> p.getName().equals(attribute.getName())).findAny();
2152 if (!instanceAttribute.isPresent()) {
2153 throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND, attribute.getName());
2155 return instanceAttribute.get();
2158 private ResponseFormat updateCapabilityPropertyOnContainerComponent(ComponentInstanceProperty property,
2159 String newValue, Component containerComponent,
2160 ComponentInstance foundResourceInstance,
2161 String capabilityType, String capabilityName) {
2162 String componentInstanceUniqueId = foundResourceInstance.getUniqueId();
2163 ResponseFormat actionStatus = updateCapPropOnContainerComponent(property, newValue, containerComponent,
2164 foundResourceInstance, capabilityType, capabilityName, componentInstanceUniqueId);
2165 if (actionStatus != null) {
2166 return actionStatus;
2169 return componentsUtils.getResponseFormat(ActionStatus.OK);
2172 private ResponseFormat updateCapabilityPropFromUpdateInstProp(ComponentInstanceProperty property,
2173 String newValue, Component containerComponent,
2174 ComponentInstance foundResourceInstance,
2175 String capabilityType, String capabilityName) {
2176 String componentInstanceUniqueId = foundResourceInstance.getUniqueId();
2177 Either<Component, StorageOperationStatus> getComponentRes =
2178 toscaOperationFacade.getToscaFullElement(foundResourceInstance.getComponentUid());
2179 if (getComponentRes.isRight()) {
2180 return componentsUtils.getResponseFormat(getComponentRes.right().value());
2183 ResponseFormat actionStatus = updateCapPropOnContainerComponent(property, newValue, containerComponent,
2184 foundResourceInstance, capabilityType, capabilityName, componentInstanceUniqueId);
2185 if (actionStatus != null) {
2186 return actionStatus;
2189 return componentsUtils.getResponseFormat(ActionStatus.OK);
2192 private ResponseFormat updateCapPropOnContainerComponent(ComponentInstanceProperty property, String newValue,
2193 Component containerComponent,
2194 ComponentInstance foundResourceInstance,
2195 String capabilityType, String capabilityName,
2196 String componentInstanceUniqueId) {
2197 Map<String, List<CapabilityDefinition>> capabilities =
2198 Optional.ofNullable(foundResourceInstance.getCapabilities()).orElse(Collections.emptyMap());
2199 List<CapabilityDefinition> capPerType =
2200 Optional.ofNullable(capabilities.get(capabilityType)).orElse(Collections.emptyList());
2201 Optional<CapabilityDefinition> cap =
2202 capPerType.stream().filter(c -> c.getName().equals(capabilityName)).findAny();
2203 if (cap.isPresent()) {
2204 List<ComponentInstanceProperty> capProperties = cap.get().getProperties();
2205 if (capProperties != null) {
2206 Optional<ComponentInstanceProperty> instanceProperty =
2207 capProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
2208 StorageOperationStatus status;
2209 if (instanceProperty.isPresent()) {
2210 String capKey = ModelConverter
2211 .buildCapabilityPropertyKey(foundResourceInstance.getOriginType().isAtomicType(), capabilityType, capabilityName,
2212 componentInstanceUniqueId, cap.get());
2213 instanceProperty.get().setValue(newValue);
2214 List<String> path = new ArrayList<>();
2215 path.add(componentInstanceUniqueId);
2217 instanceProperty.get().setPath(path);
2218 status = toscaOperationFacade.updateComponentInstanceCapabiltyProperty(containerComponent,
2219 componentInstanceUniqueId, capKey, instanceProperty.get());
2220 if (status != StorageOperationStatus.OK) {
2221 ActionStatus actionStatus =
2222 componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
2223 return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
2226 foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
2233 private ResponseFormat updatePropertyOnContainerComponent(ComponentInstanceProperty instanceProperty, String newValue,
2234 Component containerComponent, ComponentInstance foundResourceInstance) {
2235 StorageOperationStatus status;
2236 instanceProperty.setValue(newValue);
2237 status = toscaOperationFacade.updateComponentInstanceProperty(containerComponent, foundResourceInstance.getUniqueId(), instanceProperty);
2238 if (status != StorageOperationStatus.OK) {
2239 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
2240 return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
2242 foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
2243 return componentsUtils.getResponseFormat(ActionStatus.OK);
2246 private ResponseFormat updateAttributeOnContainerComponent(final ComponentInstanceAttribute instanceAttribute,
2247 final String newValue,
2248 final Component containerComponent,
2249 final ComponentInstance foundResourceInstance) {
2251 instanceAttribute.setValue(newValue);
2252 final StorageOperationStatus status =
2253 toscaOperationFacade.updateComponentInstanceAttribute(containerComponent, foundResourceInstance.getUniqueId(), instanceAttribute);
2254 if (status != StorageOperationStatus.OK) {
2255 final ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
2256 return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
2258 foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
2259 return componentsUtils.getResponseFormat(ActionStatus.OK);
2262 private <T extends PropertyDefinition> Either<String, ResponseFormat> validatePropertyObjectValue(T property, String newValue, boolean isInput) {
2263 final Map<String, DataTypeDefinition> allDataTypes = componentsUtils.getAllDataTypes(applicationDataTypeCache, property.getModel());
2264 String propertyType = property.getType();
2265 String innerType = getInnerType(property);
2267 // Specific Update Logic
2268 Either<Object, Boolean> isValid = propertyOperation
2269 .validateAndUpdatePropertyValue(property.getType(), newValue, true, innerType, allDataTypes);
2270 if (isValid.isRight()) {
2271 if (!Boolean.TRUE.equals(isValid.right().value())) {
2272 log.error("Invalid value {} of property {} ", newValue, property.getName());
2273 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2276 Object object = isValid.left().value();
2277 if (object != null) {
2278 newValue = object.toString();
2281 if (validateAndUpdateRules(property, isInput, allDataTypes, innerType, propertyType)) {
2282 return Either.right(componentsUtils.getResponseFormat(componentsUtils
2283 .convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT))));
2285 return Either.left(newValue);
2288 private <T extends PropertyDefinition> boolean validateAndUpdateRules(T property, boolean isInput, Map<String, DataTypeDefinition> allDataTypes,
2289 String innerType, String propertyType) {
2291 ImmutablePair<String, Boolean> pair = propertyOperation
2292 .validateAndUpdateRules(propertyType, ((ComponentInstanceProperty) property).getRules(), innerType, allDataTypes, true);
2293 if (pair.getRight() != null && !pair.getRight()) {
2294 BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), property.getName(), propertyType);
2301 private <T extends PropertyDefinition> Either<String, ResponseFormat> updatePropertyObjectValue(T property, final String model) {
2302 final Map<String, DataTypeDefinition> allDataTypes = componentsUtils.getAllDataTypes(applicationDataTypeCache, model);
2303 String innerType = null;
2304 String propertyType = property.getType();
2305 ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
2306 log.debug("The type of the property {} is {}", property.getUniqueId(), propertyType);
2308 if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
2309 SchemaDefinition schema = property.getSchema();
2310 if (schema == null) {
2311 log.debug("Schema doesn't exists for property of type {}", type);
2313 .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
2315 PropertyDataDefinition propDef = schema.getProperty();
2316 if (propDef == null) {
2317 log.debug("Property in Schema Definition inside property of type {} doesn't exist", type);
2319 .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
2321 innerType = propDef.getType();
2324 // Specific Update Logic
2325 String newValue = property.getValue();
2327 if (property.hasToscaFunction() || CollectionUtils.isNotEmpty(property.getSubPropertyToscaFunctions())) {
2328 return Either.left(newValue);
2331 Either<Object, Boolean> isValid = propertyOperation
2332 .validateAndUpdatePropertyValue(propertyType, property.getValue(), true, innerType, allDataTypes);
2333 if (isValid.isRight()) {
2334 if (!Boolean.TRUE.equals(isValid.right().value())) {
2335 log.debug("validate and update property value has failed with value: {}", property.getValue());
2336 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(
2337 DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT)));
2340 Object object = isValid.left().value();
2341 if (object != null) {
2342 newValue = object.toString();
2345 ImmutablePair<String, Boolean> pair = propertyOperation
2346 .validateAndUpdateRules(propertyType, ((ComponentInstanceProperty) property).getRules(), innerType, allDataTypes, true);
2347 if (pair.getRight() != null && Boolean.FALSE.equals(pair.getRight())) {
2348 BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), property.getName(), propertyType);
2349 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(
2350 DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT))));
2352 return Either.left(newValue);
2355 private <T extends AttributeDefinition> Either<String, ResponseFormat> updateAttributeObjectValue(final T attribute) {
2356 String innerType = null;
2357 final String attributeType = attribute.getType();
2358 final ToscaPropertyType type = ToscaPropertyType.isValidType(attributeType);
2359 log.debug("The type of the attribute {} is {}", attribute.getUniqueId(), attributeType);
2361 if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
2362 final SchemaDefinition def = attribute.getSchema();
2364 log.debug("Schema doesn't exists for attribute of type {}", type);
2366 .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
2368 PropertyDataDefinition propDef = def.getProperty();
2369 if (propDef == null) {
2370 log.debug("Property in Schema Definition inside attribute of type {} doesn't exist", type);
2372 .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
2374 innerType = propDef.getType();
2377 // Specific Update Logic
2378 String newValue = attribute.getValue();
2380 final var isValid = attributeOperation.validateAndUpdateAttributeValue(attribute, innerType,
2381 componentsUtils.getAllDataTypes(applicationDataTypeCache, attribute.getModel()));
2382 if (isValid.isRight()) {
2383 final Boolean res = isValid.right().value();
2384 if (!Boolean.TRUE.equals(res)) {
2385 log.debug("validate and update attribute value has failed with value: {}", newValue);
2386 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(
2387 DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT)));
2390 final Object object = isValid.left().value();
2391 if (object != null) {
2392 newValue = object.toString();
2395 return Either.left(newValue);
2398 private <T extends PropertyDefinition> void validateToscaGetFunction(T property, Component parentComponent) {
2399 final ToscaGetFunctionDataDefinition toscaGetFunction = (ToscaGetFunctionDataDefinition) property.getToscaFunction();
2400 validateGetToscaFunctionAttributes(toscaGetFunction);
2401 validateGetPropertySource(toscaGetFunction.getFunctionType(), toscaGetFunction.getPropertySource());
2402 if (toscaGetFunction.getFunctionType() == ToscaGetFunctionType.GET_INPUT) {
2403 validateGetFunction(property, parentComponent.getInputs(), parentComponent.getModel());
2406 if (toscaGetFunction.getFunctionType() == ToscaGetFunctionType.GET_PROPERTY) {
2407 if (toscaGetFunction.getPropertySource() == PropertySource.SELF) {
2408 validateGetFunction(property, parentComponent.getProperties(), parentComponent.getModel());
2409 } else if (toscaGetFunction.getPropertySource() == PropertySource.INSTANCE) {
2410 final ComponentInstance componentInstance =
2411 parentComponent.getComponentInstanceById(toscaGetFunction.getSourceUniqueId())
2412 .orElseThrow(ToscaGetFunctionExceptionSupplier.instanceNotFound(toscaGetFunction.getSourceName()));
2413 validateGetFunction(property, componentInstance.getProperties(), parentComponent.getModel());
2418 if (toscaGetFunction.getFunctionType() == ToscaGetFunctionType.GET_ATTRIBUTE) {
2419 if (toscaGetFunction.getPropertySource() == PropertySource.SELF) {
2420 validateGetFunction(property, parentComponent.getAttributes(), parentComponent.getModel());
2421 } else if (toscaGetFunction.getPropertySource() == PropertySource.INSTANCE) {
2422 final ComponentInstance componentInstance =
2423 parentComponent.getComponentInstanceById(toscaGetFunction.getSourceUniqueId())
2424 .orElseThrow(ToscaGetFunctionExceptionSupplier.instanceNotFound(toscaGetFunction.getSourceName()));
2425 validateGetFunction(property, componentInstance.getAttributes(), parentComponent.getModel());
2431 throw ToscaGetFunctionExceptionSupplier.functionNotSupported(toscaGetFunction.getFunctionType()).get();
2434 private <T extends PropertyDefinition> void validateGetFunction(final T property,
2435 final List<? extends ToscaPropertyData> parentProperties,
2436 final String model) {
2437 final ToscaGetFunctionDataDefinition toscaGetFunction = (ToscaGetFunctionDataDefinition) property.getToscaFunction();
2438 if (CollectionUtils.isEmpty(parentProperties)) {
2439 throw ToscaGetFunctionExceptionSupplier
2440 .propertyNotFoundOnTarget(toscaGetFunction.getPropertyName(), toscaGetFunction.getPropertySource(),
2441 toscaGetFunction.getFunctionType()
2444 final String getFunctionPropertyUniqueId = toscaGetFunction.getPropertyUniqueId();
2445 ToscaPropertyData referredProperty = parentProperties.stream()
2446 .filter(property1 -> getFunctionPropertyUniqueId.equals(property1.getUniqueId()))
2448 .orElseThrow(ToscaGetFunctionExceptionSupplier
2449 .propertyNotFoundOnTarget(toscaGetFunction.getPropertyName(), toscaGetFunction.getPropertySource()
2450 , toscaGetFunction.getFunctionType())
2452 if (toscaGetFunction.isSubProperty()) {
2453 referredProperty = findSubProperty(referredProperty, toscaGetFunction, model);
2456 if (!property.getType().equals(referredProperty.getType())) {
2457 throw ToscaGetFunctionExceptionSupplier
2458 .propertyTypeDiverge(toscaGetFunction.getType(), referredProperty.getType(), property.getType()).get();
2460 if (PropertyType.typeHasSchema(referredProperty.getType()) && !referredProperty.getSchemaType().equals(property.getSchemaType())) {
2461 throw ToscaGetFunctionExceptionSupplier
2462 .propertySchemaDiverge(toscaGetFunction.getType(), referredProperty.getSchemaType(), property.getSchemaType()).get();
2466 private ToscaPropertyData findSubProperty(final ToscaPropertyData referredProperty,
2467 final ToscaGetFunctionDataDefinition toscaGetFunction,
2468 final String model) {
2469 final Map<String, DataTypeDefinition> dataTypeMap = loadDataTypes(model);
2470 final List<String> propertyPathFromSource = toscaGetFunction.getPropertyPathFromSource();
2471 DataTypeDefinition dataType = dataTypeMap.get(referredProperty.getType());
2472 if (dataType == null) {
2473 throw ToscaGetFunctionExceptionSupplier
2474 .propertyDataTypeNotFound(propertyPathFromSource.get(0), referredProperty.getType(), toscaGetFunction.getFunctionType()).get();
2476 ToscaPropertyData foundProperty = referredProperty;
2477 for (int i = 1; i < propertyPathFromSource.size(); i++) {
2478 final String currentPropertyName = propertyPathFromSource.get(i);
2479 foundProperty = dataType.getProperties().stream()
2480 .filter(propertyDefinition -> currentPropertyName.equals(propertyDefinition.getName())).findFirst()
2482 ToscaGetFunctionExceptionSupplier
2483 .propertyNotFoundOnTarget(propertyPathFromSource.subList(0, i), toscaGetFunction.getPropertySource(),
2484 toscaGetFunction.getFunctionType())
2486 dataType = dataTypeMap.get(foundProperty.getType());
2487 if (dataType == null) {
2488 throw ToscaGetFunctionExceptionSupplier
2489 .propertyDataTypeNotFound(propertyPathFromSource.subList(0, i), foundProperty.getType(),
2490 toscaGetFunction.getFunctionType()).get();
2493 return foundProperty;
2496 private Map<String, DataTypeDefinition> loadDataTypes(String model) {
2497 final Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> dataTypeEither =
2498 applicationDataTypeCache.getAll(model);
2499 if (dataTypeEither.isRight()) {
2500 throw ToscaGetFunctionExceptionSupplier.couldNotLoadDataTypes(model).get();
2502 return dataTypeEither.left().value();
2505 private void validateGetPropertySource(final ToscaGetFunctionType functionType, final PropertySource propertySource) {
2506 if (functionType == ToscaGetFunctionType.GET_INPUT && propertySource != PropertySource.SELF) {
2507 throw ToscaGetFunctionExceptionSupplier
2508 .targetSourceNotSupported(functionType, propertySource).get();
2510 if (functionType == ToscaGetFunctionType.GET_PROPERTY && !List.of(PropertySource.SELF, PropertySource.INSTANCE).contains(propertySource)) {
2511 throw ToscaGetFunctionExceptionSupplier
2512 .targetSourceNotSupported(functionType, propertySource).get();
2516 private void validateGetToscaFunctionAttributes(final ToscaGetFunctionDataDefinition toscaGetFunction) {
2517 if (toscaGetFunction.getFunctionType() == null) {
2518 throw ToscaGetFunctionExceptionSupplier.targetFunctionTypeNotFound().get();
2520 if (toscaGetFunction.getPropertySource() == null) {
2521 throw ToscaGetFunctionExceptionSupplier.targetPropertySourceNotFound(toscaGetFunction.getFunctionType()).get();
2523 if (CollectionUtils.isEmpty(toscaGetFunction.getPropertyPathFromSource())) {
2524 throw ToscaGetFunctionExceptionSupplier
2525 .targetSourcePathNotFound(toscaGetFunction.getFunctionType()).get();
2527 if (StringUtils.isEmpty(toscaGetFunction.getSourceName()) || StringUtils.isBlank(toscaGetFunction.getSourceName())) {
2528 throw ToscaGetFunctionExceptionSupplier.sourceNameNotFound(toscaGetFunction.getPropertySource()).get();
2530 if (StringUtils.isEmpty(toscaGetFunction.getSourceUniqueId()) || StringUtils.isBlank(toscaGetFunction.getSourceUniqueId())) {
2531 throw ToscaGetFunctionExceptionSupplier.sourceIdNotFound(toscaGetFunction.getPropertySource()).get();
2533 if (StringUtils.isEmpty(toscaGetFunction.getPropertyName()) || StringUtils.isBlank(toscaGetFunction.getPropertyName())) {
2534 throw ToscaGetFunctionExceptionSupplier.propertyNameNotFound(toscaGetFunction.getPropertySource()).get();
2536 if (StringUtils.isEmpty(toscaGetFunction.getPropertyUniqueId()) || StringUtils.isBlank(toscaGetFunction.getPropertyUniqueId())) {
2537 throw ToscaGetFunctionExceptionSupplier.propertyIdNotFound(toscaGetFunction.getPropertySource()).get();
2541 private ResponseFormat updateInputOnContainerComponent(ComponentInstanceInput input, String newValue, Component containerComponent,
2542 ComponentInstance foundResourceInstance) {
2543 StorageOperationStatus status;
2544 input.setValue(newValue);
2545 status = toscaOperationFacade.updateComponentInstanceInput(containerComponent, foundResourceInstance.getUniqueId(), input);
2546 if (status != StorageOperationStatus.OK) {
2547 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
2548 return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
2550 foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
2551 return componentsUtils.getResponseFormat(ActionStatus.OK);
2554 public Either<List<ComponentInstanceInput>, ResponseFormat> createOrUpdateInstanceInputValues(ComponentTypeEnum componentTypeEnum,
2555 String componentId, String resourceInstanceId,
2556 List<ComponentInstanceInput> inputs,
2559 Either<List<ComponentInstanceInput>, ResponseFormat> resultOp = null;
2561 validateUserExists(userId);
2563 if (componentTypeEnum == null) {
2564 BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_OR_UPDATE_PROPERTY_VALUE, INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
2565 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
2568 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
2570 if (getResourceResult.isRight()) {
2571 log.debug(FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID, componentId);
2572 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getResourceResult.right().value(), componentTypeEnum);
2573 return Either.right(componentsUtils.getResponseFormat(actionStatus, componentId));
2575 Component containerComponent = getResourceResult.left().value();
2577 if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
2578 if (Boolean.TRUE.equals(containerComponent.isArchived())) {
2579 log.info(COMPONENT_ARCHIVED, componentId);
2580 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_IS_ARCHIVED, containerComponent.getName()));
2582 log.info(RESTRICTED_OPERATION_ON_SERVIVE, userId, componentId);
2583 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2586 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId);
2587 if (resourceInstanceStatus.isRight()) {
2588 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER,
2589 resourceInstanceId, RESOURCE_INSTANCE, SERVICE, componentId));
2592 ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
2595 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
2596 if (lockStatus != StorageOperationStatus.OK) {
2597 log.debug(FAILED_TO_LOCK_SERVICE, componentId);
2598 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
2600 List<ComponentInstanceInput> updatedInputs = new ArrayList<>();
2602 for (ComponentInstanceInput input : inputs) {
2603 validateMandatoryFields(input);
2604 ComponentInstanceInput componentInstanceInput = validateInputExistsOnComponent(input, containerComponent, foundResourceInstance);
2605 Either<String, ResponseFormat> validatedInputValue = validatePropertyObjectValue(componentInstanceInput, input.getValue(), true);
2606 if (validatedInputValue.isRight()) {
2607 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT, input.getName());
2609 updateInputOnContainerComponent(componentInstanceInput, validatedInputValue.left().value(), containerComponent,
2610 foundResourceInstance);
2611 updatedInputs.add(componentInstanceInput);
2613 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade
2614 .updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
2615 if (updateContainerRes.isRight()) {
2616 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
2617 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2620 resultOp = Either.left(updatedInputs);
2624 if (resultOp == null || resultOp.isRight()) {
2625 janusGraphDao.rollback();
2627 janusGraphDao.commit();
2630 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
2635 private ComponentInstanceInput validateInputExistsOnComponent(ComponentInstanceInput input, Component containerComponent,
2636 ComponentInstance foundResourceInstance) {
2637 List<ComponentInstanceInput> instanceProperties = containerComponent.getComponentInstancesInputs().get(foundResourceInstance.getUniqueId());
2638 Optional<ComponentInstanceInput> instanceInput = instanceProperties.stream().filter(p -> p.getName().equals(input.getName())).findAny();
2639 if (!instanceInput.isPresent()) {
2640 throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND, input.getName());
2642 return instanceInput.get();
2645 public Either<ComponentInstanceProperty, ResponseFormat> createOrUpdateGroupInstancePropertyValue(ComponentTypeEnum componentTypeEnum,
2646 String componentId, String resourceInstanceId,
2647 String groupInstanceId,
2648 ComponentInstanceProperty property,
2651 Either<ComponentInstanceProperty, ResponseFormat> resultOp = null;
2653 validateUserExists(userId);
2655 if (componentTypeEnum == null) {
2656 BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_OR_UPDATE_PROPERTY_VALUE, INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
2657 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
2661 if (!ComponentValidationUtils.canWorkOnComponent(componentId, toscaOperationFacade, userId)) {
2662 log.info("Restricted operation for user: {} on service: {}", userId, componentId);
2663 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2667 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
2668 if (lockStatus != StorageOperationStatus.OK) {
2669 log.debug(FAILED_TO_LOCK_SERVICE, componentId);
2670 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
2674 String propertyValueUid = property.getValueUniqueUid();
2676 if (propertyValueUid == null) {
2678 Either<Integer, StorageOperationStatus> counterRes = groupInstanceOperation
2679 .increaseAndGetGroupInstancePropertyCounter(groupInstanceId);
2681 if (counterRes.isRight()) {
2682 log.debug("increaseAndGetResourcePropertyCounter failed resource instance: {} property: {}", resourceInstanceId, property);
2683 StorageOperationStatus status = counterRes.right().value();
2684 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
2685 resultOp = Either.right(componentsUtils.getResponseFormat(actionStatus));
2687 Integer index = counterRes.left().value();
2688 Either<ComponentInstanceProperty, StorageOperationStatus> result = groupInstanceOperation
2689 .addPropertyValueToGroupInstance(property, resourceInstanceId, index, true);
2691 if (result.isLeft()) {
2692 log.trace("Property value was added to resource instance {}", resourceInstanceId);
2693 ComponentInstanceProperty instanceProperty = result.left().value();
2695 resultOp = Either.left(instanceProperty);
2698 log.debug("Failed to add property value: {} to resource instance {}", property, resourceInstanceId);
2700 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
2702 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2706 Either<ComponentInstanceProperty, StorageOperationStatus> result = groupInstanceOperation
2707 .updatePropertyValueInGroupInstance(property, resourceInstanceId, true);
2709 if (result.isLeft()) {
2710 log.debug("Property value {} was updated on graph.", property.getValueUniqueUid());
2711 ComponentInstanceProperty instanceProperty = result.left().value();
2713 resultOp = Either.left(instanceProperty);
2716 log.debug("Failed to update property value: {}, in resource instance {}", property, resourceInstanceId);
2718 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
2720 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2723 if (resultOp.isLeft()) {
2724 StorageOperationStatus updateCustomizationUUID = componentInstanceOperation.updateCustomizationUUID(resourceInstanceId);
2725 if (updateCustomizationUUID != StorageOperationStatus.OK) {
2726 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateCustomizationUUID);
2728 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2735 if (resultOp == null || resultOp.isRight()) {
2736 janusGraphDao.rollback();
2738 janusGraphDao.commit();
2741 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
2746 public Either<ComponentInstanceProperty, ResponseFormat> deletePropertyValue(ComponentTypeEnum componentTypeEnum, String serviceId,
2747 String resourceInstanceId, String propertyValueId, String userId) {
2749 validateUserExists(userId);
2751 Either<ComponentInstanceProperty, ResponseFormat> resultOp = null;
2753 if (componentTypeEnum == null) {
2754 BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_OR_UPDATE_PROPERTY_VALUE, INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
2755 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
2759 if (!ComponentValidationUtils.canWorkOnComponent(serviceId, toscaOperationFacade, userId)) {
2760 log.info("Restricted operation for user {} on service {}", userId, serviceId);
2761 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2765 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(serviceId, componentTypeEnum.getNodeType());
2766 if (lockStatus != StorageOperationStatus.OK) {
2767 log.debug(FAILED_TO_LOCK_SERVICE, serviceId);
2768 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
2772 Either<ComponentInstanceProperty, StorageOperationStatus> result = propertyOperation
2773 .removePropertyValueFromResourceInstance(propertyValueId, resourceInstanceId, true);
2775 if (result.isLeft()) {
2776 log.debug("Property value {} was removed from graph.", propertyValueId);
2777 ComponentInstanceProperty instanceProperty = result.left().value();
2779 resultOp = Either.left(instanceProperty);
2783 log.debug("Failed to remove property value {} in resource instance {}", propertyValueId, resourceInstanceId);
2785 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
2787 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2793 if (resultOp == null || resultOp.isRight()) {
2794 janusGraphDao.rollback();
2796 janusGraphDao.commit();
2799 graphLockOperation.unlockComponent(serviceId, componentTypeEnum.getNodeType());
2804 private Component getAndValidateOriginComponentOfComponentInstance(Component containerComponent, ComponentInstance componentInstance) {
2806 ComponentTypeEnum componentType = getComponentTypeByParentComponentType(containerComponent.getComponentType());
2807 Component component;
2808 Either<Component, StorageOperationStatus> getComponentRes = toscaOperationFacade.getToscaFullElement(componentInstance.getComponentUid());
2809 if (getComponentRes.isRight()) {
2810 log.debug("Failed to get the component with id {} for component instance {} creation. ", componentInstance.getComponentUid(),
2811 componentInstance.getName());
2812 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentRes.right().value(), componentType);
2813 throw new ByActionStatusComponentException(actionStatus, Constants.EMPTY_STRING);
2815 component = getComponentRes.left().value();
2816 LifecycleStateEnum resourceCurrState = component.getLifecycleState();
2817 if (resourceCurrState == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) {
2818 ActionStatus actionStatus = ActionStatus.CONTAINER_CANNOT_CONTAIN_COMPONENT_IN_STATE;
2819 throw new ByActionStatusComponentException(actionStatus, containerComponent.getComponentType().toString(), resourceCurrState.toString());
2821 if (Boolean.TRUE.equals(component.isArchived())) {
2822 ActionStatus actionStatus = ActionStatus.COMPONENT_IS_ARCHIVED;
2823 throw new ByActionStatusComponentException(actionStatus, component.getName());
2825 final Map<String, InterfaceDefinition> componentInterfaces = component.getInterfaces();
2826 if (MapUtils.isNotEmpty(componentInterfaces)) {
2827 componentInterfaces.forEach(componentInstance::addInterface);
2832 public Either<Set<String>, ResponseFormat> forwardingPathOnVersionChange(String containerComponentParam,
2833 String containerComponentId,
2834 String componentInstanceId,
2835 ComponentInstance newComponentInstance) {
2836 Either<Set<String>, ResponseFormat> resultOp;
2837 final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
2838 ComponentParametersView componentParametersView = getComponentParametersViewForForwardingPath();
2841 Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, componentParametersView);
2843 //Fetch current component instance
2844 Either<ComponentInstance, StorageOperationStatus> eitherResourceInstance =
2845 getResourceInstanceById(containerComponent, componentInstanceId);
2846 if (eitherResourceInstance.isRight()) {
2847 resultOp = Either.right(componentsUtils.getResponseFormat(
2848 ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceId, containerComponentId));
2851 ComponentInstance currentResourceInstance = eitherResourceInstance.left().value();
2853 //Check whether new componentInstance exists
2854 String resourceId = newComponentInstance.getComponentUid();
2855 Either<Boolean, StorageOperationStatus> componentExistsRes = toscaOperationFacade.validateComponentExists(resourceId);
2856 if (componentExistsRes.isRight()) {
2857 log.debug("Failed to find resource {}", resourceId);
2858 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse
2859 (componentExistsRes.right().value()), resourceId));
2861 } else if (!Boolean.TRUE.equals(componentExistsRes.left().value())) {
2862 log.debug("The resource {} not found ", resourceId);
2863 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId));
2867 //Fetch component using new component instance uid
2868 Component updatedContainerComponent = getOriginComponentFromComponentInstance(newComponentInstance);
2869 Set<String> toDeleteForwardingPaths = getForwardingPaths(containerComponent,
2870 currentResourceInstance, updatedContainerComponent);
2871 resultOp = Either.left(toDeleteForwardingPaths);
2876 private Set<String> getForwardingPaths(Component containerComponent, ComponentInstance currentResourceInstance,
2877 Component updatedContainerComponent) {
2878 DataForMergeHolder dataForMergeHolder = new DataForMergeHolder();
2879 dataForMergeHolder.setOrigComponentInstId(currentResourceInstance.getName());
2881 Service service = (Service) containerComponent;
2882 ForwardingPathUtils forwardingPathUtils = new ForwardingPathUtils();
2884 return forwardingPathUtils.
2885 getForwardingPathsToBeDeletedOnVersionChange(service, dataForMergeHolder, updatedContainerComponent);
2888 private ComponentParametersView getComponentParametersViewForForwardingPath() {
2889 ComponentParametersView componentParametersView = new ComponentParametersView();
2890 componentParametersView.setIgnoreCapabiltyProperties(false);
2891 componentParametersView.setIgnoreServicePath(false);
2892 return componentParametersView;
2895 public ComponentInstance changeComponentInstanceVersion(String containerComponentParam, String containerComponentId, String componentInstanceId,
2896 String userId, ComponentInstance newComponentInstance) {
2898 User user = validateUserExists(userId);
2899 final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
2900 ComponentParametersView componentParametersView = new ComponentParametersView();
2901 componentParametersView.setIgnoreCapabiltyProperties(false);
2903 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(containerComponentId, containerComponentType,
2904 componentParametersView);
2906 validateCanWorkOnComponent(containerComponent, userId);
2908 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceId);
2909 if (resourceInstanceStatus.isRight()) {
2910 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceId,
2911 containerComponentId);
2914 ComponentInstance currentResourceInstance = resourceInstanceStatus.left().value();
2916 return changeInstanceVersion(containerComponent, currentResourceInstance, newComponentInstance, user, containerComponentType);
2919 public ComponentInstance changeInstanceVersion(org.openecomp.sdc.be.model.Component containerComponent,
2920 ComponentInstance currentResourceInstance,
2921 ComponentInstance newComponentInstance,
2923 final ComponentTypeEnum containerComponentType) {
2924 boolean failed = false;
2925 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus;
2928 lockComponent(containerComponent, "changeComponentInstanceVersion");
2929 String containerComponentId = containerComponent.getUniqueId();
2930 String componentInstanceId = currentResourceInstance.getUniqueId();
2931 if (currentResourceInstance.getComponentUid().equals(newComponentInstance.getComponentUid())) {
2932 return currentResourceInstance;
2934 String resourceId = newComponentInstance.getComponentUid();
2936 Either<Boolean, StorageOperationStatus> componentExistsRes = toscaOperationFacade
2937 .validateComponentExists(resourceId);
2938 if (componentExistsRes.isRight()) {
2939 StorageOperationStatus errorStatus = componentExistsRes.right().value();
2941 log.debug("Failed to validate existing of the component {}. Status is {} ", resourceId, errorStatus);
2942 throw new ByActionStatusComponentException(
2943 componentsUtils.convertFromStorageResponse(errorStatus), resourceId);
2944 } else if (!Boolean.TRUE.equals(componentExistsRes.left().value())) {
2945 log.debug("The resource {} not found ", resourceId);
2946 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_NOT_FOUND, resourceId);
2949 Component eitherOriginComponent = getInstanceOriginNode(currentResourceInstance);
2950 DataForMergeHolder dataHolder = compInstMergeDataBL
2951 .saveAllDataBeforeDeleting(containerComponent, currentResourceInstance, eitherOriginComponent);
2952 ComponentInstance resResourceInfo = deleteComponentInstance(containerComponent, componentInstanceId,
2953 containerComponentType);
2955 if (resResourceInfo == null) {
2956 log.error("Calling `deleteComponentInstance` for the resource {} returned a null", resourceId);
2957 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_NOT_FOUND, resourceId);
2959 Component origComponent = null;
2960 OriginTypeEnum originType = currentResourceInstance.getOriginType();
2961 newComponentInstance.setOriginType(originType);
2962 if (originType == OriginTypeEnum.ServiceProxy) {
2963 Either<Component, StorageOperationStatus> serviceProxyOrigin = toscaOperationFacade
2964 .getLatestByName(SERVICE_PROXY, null);
2965 if (isServiceProxyOrigin(serviceProxyOrigin)) {
2966 throw new ByActionStatusComponentException(
2967 componentsUtils.convertFromStorageResponse(serviceProxyOrigin.right().value()));
2969 origComponent = serviceProxyOrigin.left().value();
2971 StorageOperationStatus fillProxyRes = fillInstanceData(newComponentInstance, origComponent);
2973 if (isFillProxyRes(fillProxyRes)) {
2974 throw new ByActionStatusComponentException(
2975 componentsUtils.convertFromStorageResponse(fillProxyRes));
2977 } else if (originType == OriginTypeEnum.ServiceSubstitution) {
2978 final Either<Component, StorageOperationStatus> getServiceResult = toscaOperationFacade
2979 .getToscaFullElement(newComponentInstance.getComponentUid());
2980 if (getServiceResult.isRight()) {
2981 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(getServiceResult.right().value()));
2983 final Component service = getServiceResult.left().value();
2985 final Either<Component, StorageOperationStatus> getServiceDerivedFromTypeResult = toscaOperationFacade
2986 .getLatestByToscaResourceName(service.getDerivedFromGenericType(), service.getModel());
2987 if (getServiceDerivedFromTypeResult.isRight()) {
2988 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(getServiceResult.right().value()));
2991 origComponent = getServiceDerivedFromTypeResult.left().value();
2993 final StorageOperationStatus fillProxyRes = fillInstanceData(newComponentInstance, origComponent);
2994 if (isFillProxyRes(fillProxyRes)) {
2995 throw new ByActionStatusComponentException(
2996 componentsUtils.convertFromStorageResponse(fillProxyRes));
2999 origComponent = getOriginComponentFromComponentInstance(newComponentInstance);
3000 newComponentInstance.setName(resResourceInfo.getName());
3001 final Map<String, InterfaceDefinition> componentInterfaces = origComponent.getInterfaces();
3002 if (MapUtils.isNotEmpty(componentInterfaces)) {
3003 componentInterfaces.forEach(newComponentInstance::addInterface);
3007 newComponentInstance.setInvariantName(resResourceInfo.getInvariantName());
3008 newComponentInstance.setPosX(resResourceInfo.getPosX());
3009 newComponentInstance.setPosY(resResourceInfo.getPosY());
3010 newComponentInstance.setDescription(resResourceInfo.getDescription());
3011 newComponentInstance.setInstanceCount(resResourceInfo.getInstanceCount());
3012 newComponentInstance.setMaxOccurrences(resResourceInfo.getMaxOccurrences());
3013 newComponentInstance.setMinOccurrences(resResourceInfo.getMinOccurrences());
3014 newComponentInstance.setDirectives(resResourceInfo.getDirectives());
3015 checkForExternalReqAndCapabilities(origComponent, resResourceInfo);
3017 ComponentInstance updatedComponentInstance =
3018 createComponentInstanceOnGraph(containerComponent, origComponent, newComponentInstance, user);
3019 dataHolder.setCurrInstanceNode(origComponent);
3021 .mergeComponentUserOrigData(user, dataHolder, containerComponent, containerComponentId, newComponentInstance.getUniqueId());
3023 ActionStatus postChangeVersionResult = onChangeInstanceOperationOrchestrator
3024 .doPostChangeVersionOperations(containerComponent, currentResourceInstance, newComponentInstance);
3025 if (postChangeVersionResult != ActionStatus.OK) {
3026 throw new ByActionStatusComponentException(postChangeVersionResult);
3029 ComponentParametersView filter = new ComponentParametersView(true);
3030 filter.setIgnoreComponentInstances(false);
3031 Either<Component, StorageOperationStatus> updatedComponentRes = toscaOperationFacade.getToscaElement(containerComponentId, filter);
3032 if (updatedComponentRes.isRight()) {
3033 StorageOperationStatus storageOperationStatus = updatedComponentRes.right().value();
3034 ActionStatus actionStatus = componentsUtils
3035 .convertFromStorageResponse(storageOperationStatus, containerComponent.getComponentType());
3036 log.debug("Component with id {} was not found", containerComponentId);
3037 throw new ByActionStatusComponentException(actionStatus, Constants.EMPTY_STRING);
3040 maintainNodeFilters(currentResourceInstance, newComponentInstance, containerComponentId);
3042 resourceInstanceStatus = getResourceInstanceById(updatedComponentRes.left().value(),
3043 updatedComponentInstance.getUniqueId());
3044 if (resourceInstanceStatus.isRight()) {
3045 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse
3046 (resourceInstanceStatus.right().value()), updatedComponentInstance.getUniqueId());
3048 return resourceInstanceStatus.left().value();
3050 } catch (ComponentException e) {
3054 unlockComponent(failed, containerComponent);
3058 private void maintainNodeFilters(
3059 ComponentInstance currentResourceInstance,
3060 ComponentInstance newComponentInstance,
3061 String containerComponentId) {
3062 CINodeFilterDataDefinition filterToMaintain = currentResourceInstance.getNodeFilter();
3063 if (null != filterToMaintain) {
3064 nodeFilterOperation.addNodeFilterData(
3065 containerComponentId.toLowerCase(),
3066 newComponentInstance.getUniqueId(),
3071 private void checkForExternalReqAndCapabilities(Component component, ComponentInstance resResourceInfo) {
3072 Map<String, List<RequirementDefinition>> requirementsMap = resResourceInfo.getRequirements();
3073 Map<String, List<RequirementDefinition>> externalRequirementsMap = new HashMap<>();
3074 List<RequirementDefinition> externalRequirementList = new ArrayList<>();
3075 if (requirementsMap != null && !requirementsMap.isEmpty()) {
3076 requirementsMap.forEach((type, requirementDefinitions) -> {
3077 if (requirementDefinitions != null && !requirementDefinitions.isEmpty()) {
3078 for (final RequirementDefinition requirementDefinition : requirementDefinitions) {
3079 if (requirementDefinition.isExternal()) {
3080 externalRequirementList.add(requirementDefinition);
3081 externalRequirementsMap.put(type, externalRequirementList);
3088 Map<String, List<CapabilityDefinition>> capabilitiesMap = resResourceInfo.getCapabilities();
3089 Map<String, List<CapabilityDefinition>> externalCapabilitiesMap = new HashMap<>();
3090 List<CapabilityDefinition> externalCapabilitiesList = new ArrayList<>();
3091 if (capabilitiesMap != null && !capabilitiesMap.isEmpty()) {
3092 capabilitiesMap.forEach((type, capabilityDefinitions) -> {
3093 if (capabilityDefinitions != null && !capabilityDefinitions.isEmpty()) {
3094 for (final CapabilityDefinition capabilityDefinition : capabilityDefinitions) {
3095 if (capabilityDefinition.isExternal()) {
3096 externalCapabilitiesList.add(capabilityDefinition);
3097 externalCapabilitiesMap.put(type, externalCapabilitiesList);
3103 component.setCapabilities(externalCapabilitiesMap);
3104 component.setRequirements(externalRequirementsMap);
3107 private boolean isFillProxyRes(StorageOperationStatus fillProxyRes) {
3108 if (fillProxyRes != StorageOperationStatus.OK) {
3109 log.debug("Failed to fill service proxy resource data with data from service, error {}", fillProxyRes);
3116 public List<ComponentInstanceProperty> getComponentInstancePropertiesById(String containerComponentTypeParam, String containerComponentId,
3117 String componentInstanceUniqueId, String userId) {
3118 Component containerComponent = null;
3120 boolean failed = false;
3122 validateUserExists(userId);
3123 validateComponentType(containerComponentTypeParam);
3125 Either<Component, StorageOperationStatus> validateContainerComponentExists = toscaOperationFacade.getToscaElement(containerComponentId);
3126 if (validateContainerComponentExists.isRight()) {
3127 throw new ByActionStatusComponentException(
3128 componentsUtils.convertFromStorageResponse(validateContainerComponentExists.right().value()));
3130 containerComponent = validateContainerComponentExists.left().value();
3132 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent,
3133 componentInstanceUniqueId);
3134 if (resourceInstanceStatus.isRight()) {
3135 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId,
3136 containerComponentId);
3139 List<ComponentInstanceProperty> instanceProperties = new ArrayList<>();
3140 if (MapUtils.isNotEmpty(containerComponent.getComponentInstancesProperties())) {
3141 instanceProperties = containerComponent.getComponentInstancesProperties()
3142 .get(componentInstanceUniqueId);
3144 return instanceProperties;
3145 } catch (ComponentException e) {
3149 unlockComponent(failed, containerComponent);
3153 public List<ComponentInstanceAttribute> getComponentInstanceAttributesById(final String containerComponentTypeParam,
3154 final String containerComponentId,
3155 final String componentInstanceUniqueId,
3156 final String userId) {
3157 Component containerComponent = null;
3159 boolean failed = false;
3161 validateUserExists(userId);
3162 validateComponentType(containerComponentTypeParam);
3164 final Either<Component, StorageOperationStatus> validateContainerComponentExists =
3165 toscaOperationFacade.getToscaElement(containerComponentId);
3166 if (validateContainerComponentExists.isRight()) {
3167 throw new ByActionStatusComponentException(
3168 componentsUtils.convertFromStorageResponse(validateContainerComponentExists.right().value()));
3170 containerComponent = validateContainerComponentExists.left().value();
3172 if (getResourceInstanceById(containerComponent, componentInstanceUniqueId).isRight()) {
3173 throw new ByActionStatusComponentException(
3174 ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId);
3177 final Map<String, List<ComponentInstanceAttribute>> componentInstancesAttributes = containerComponent.getComponentInstancesAttributes();
3178 return componentInstancesAttributes == null ? new ArrayList<>()
3179 : componentInstancesAttributes.getOrDefault(componentInstanceUniqueId, new ArrayList<>());
3180 } catch (final ComponentException e) {
3184 unlockComponent(failed, containerComponent);
3188 protected void validateIncrementCounter(String resourceInstanceId, GraphPropertiesDictionary counterType,
3189 Wrapper<Integer> instaceCounterWrapper,
3190 Wrapper<ResponseFormat> errorWrapper) {
3191 Either<Integer, StorageOperationStatus> counterRes = componentInstanceOperation
3192 .increaseAndGetResourceInstanceSpecificCounter(resourceInstanceId, counterType, true);
3194 if (counterRes.isRight()) {
3195 log.debug("increase And Get {} failed resource instance {}", counterType, resourceInstanceId);
3196 StorageOperationStatus status = counterRes.right().value();
3197 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
3198 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus));
3200 instaceCounterWrapper.setInnerElement(counterRes.left().value());
3206 * updates componentInstance modificationTime
3208 * @param componentInstance
3209 * @param componentInstanceType
3210 * @param modificationTime
3211 * @param inTransaction
3214 public Either<ComponentInstanceData, ResponseFormat> updateComponentInstanceModificationTimeAndCustomizationUuid(
3215 ComponentInstance componentInstance, NodeTypeEnum componentInstanceType, Long modificationTime, boolean inTransaction) {
3216 Either<ComponentInstanceData, ResponseFormat> result;
3217 Either<ComponentInstanceData, StorageOperationStatus> updateComponentInstanceRes = componentInstanceOperation
3218 .updateComponentInstanceModificationTimeAndCustomizationUuidOnGraph(componentInstance, componentInstanceType, modificationTime,
3220 if (updateComponentInstanceRes.isRight()) {
3221 log.debug("Failed to update component instance {} with new last update date and mofifier. Status is {}. ", componentInstance.getName(),
3222 updateComponentInstanceRes.right().value());
3224 .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateComponentInstanceRes.right().value())));
3226 result = Either.left(updateComponentInstanceRes.left().value());
3231 public Either<ComponentInstance, ResponseFormat> deleteServiceProxy() {
3232 // TODO Add implementation
3233 return Either.left(new ComponentInstance());
3236 public Either<ComponentInstance, ResponseFormat> createServiceProxy() {
3237 // TODO Add implementation
3238 return Either.left(new ComponentInstance());
3241 public Either<ComponentInstance, ResponseFormat> changeServiceProxyVersion() {
3242 // TODO Add implementation
3243 return Either.left(new ComponentInstance());
3246 private Boolean validateInstanceNameUniquenessUponUpdate(Component containerComponent, ComponentInstance oldComponentInstance,
3247 String newInstanceName) {
3248 return ComponentValidations.validateNameIsUniqueInComponent(oldComponentInstance.getName(), newInstanceName, containerComponent);
3251 private Either<ComponentInstance, StorageOperationStatus> getResourceInstanceById(final Component containerComponent, final String instanceId) {
3252 final List<ComponentInstance> instances = containerComponent.getComponentInstances();
3253 if (CollectionUtils.isEmpty(instances)) {
3254 return Either.right(StorageOperationStatus.NOT_FOUND);
3257 final Optional<ComponentInstance> foundInstance = instances.stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst();
3258 if (foundInstance.isEmpty()) {
3259 return Either.right(StorageOperationStatus.NOT_FOUND);
3262 return Either.left(foundInstance.get());
3265 private ComponentInstance buildComponentInstance(ComponentInstance resourceInstanceForUpdate, ComponentInstance origInstanceForUpdate) {
3266 Long creationDate = origInstanceForUpdate.getCreationTime();
3267 Long modificationTime = System.currentTimeMillis();
3268 resourceInstanceForUpdate.setCreationTime(creationDate);
3269 resourceInstanceForUpdate.setModificationTime(modificationTime);
3270 resourceInstanceForUpdate.setCustomizationUUID(origInstanceForUpdate.getCustomizationUUID());
3271 if (StringUtils.isEmpty(resourceInstanceForUpdate.getName()) && StringUtils.isNotEmpty(origInstanceForUpdate.getName())) {
3272 resourceInstanceForUpdate.setName(origInstanceForUpdate.getName());
3274 resourceInstanceForUpdate.setNormalizedName(ValidationUtils.normalizeComponentInstanceName(resourceInstanceForUpdate.getName()));
3275 if (StringUtils.isEmpty(resourceInstanceForUpdate.getIcon())) {
3276 resourceInstanceForUpdate.setIcon(origInstanceForUpdate.getIcon());
3278 if (StringUtils.isEmpty(resourceInstanceForUpdate.getComponentVersion())) {
3279 resourceInstanceForUpdate.setComponentVersion(origInstanceForUpdate.getComponentVersion());
3281 if (StringUtils.isEmpty(resourceInstanceForUpdate.getComponentName())) {
3282 resourceInstanceForUpdate.setComponentName(origInstanceForUpdate.getComponentName());
3284 if (StringUtils.isEmpty(resourceInstanceForUpdate.getToscaComponentName())) {
3285 resourceInstanceForUpdate.setToscaComponentName(origInstanceForUpdate.getToscaComponentName());
3287 if (resourceInstanceForUpdate.getOriginType() == null) {
3288 resourceInstanceForUpdate.setOriginType(origInstanceForUpdate.getOriginType());
3290 if (resourceInstanceForUpdate.getOriginType() == OriginTypeEnum.ServiceProxy) {
3291 resourceInstanceForUpdate.setIsProxy(true);
3293 if (resourceInstanceForUpdate.getSourceModelInvariant() == null) {
3294 resourceInstanceForUpdate.setSourceModelInvariant(origInstanceForUpdate.getSourceModelInvariant());
3296 if (resourceInstanceForUpdate.getSourceModelName() == null) {
3297 resourceInstanceForUpdate.setSourceModelName(origInstanceForUpdate.getSourceModelName());
3299 if (resourceInstanceForUpdate.getSourceModelUuid() == null) {
3300 resourceInstanceForUpdate.setSourceModelUuid(origInstanceForUpdate.getSourceModelUuid());
3302 if (resourceInstanceForUpdate.getSourceModelUid() == null) {
3303 resourceInstanceForUpdate.setSourceModelUid(origInstanceForUpdate.getSourceModelUid());
3305 if (resourceInstanceForUpdate.getCreatedFrom() == null) {
3306 resourceInstanceForUpdate.setCreatedFrom(origInstanceForUpdate.getCreatedFrom());
3308 return resourceInstanceForUpdate;
3312 * Returns list of ComponentInstanceProperty belonging to component instance capability specified by name, type and ownerId
3314 * @param containerComponentType
3315 * @param containerComponentId
3316 * @param componentInstanceUniqueId
3317 * @param capabilityType
3318 * @param capabilityName
3323 public List<ComponentInstanceProperty> getComponentInstanceCapabilityPropertiesById(String containerComponentType, String containerComponentId,
3324 String componentInstanceUniqueId, String capabilityType,
3325 String capabilityName, String ownerId, String userId) {
3326 Component containerComponent = null;
3327 List<ComponentInstanceProperty> resultOp = null;
3329 validateUserExists(userId);
3330 validateComponentType(containerComponentType);
3331 containerComponent = toscaOperationFacade.getToscaFullElement(containerComponentId).left().on(this::componentException);
3332 ComponentInstance resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId).left()
3333 .on(this::componentInstanceException);
3334 resultOp = findCapabilityOfInstance(containerComponentId, componentInstanceUniqueId, capabilityType, capabilityName, ownerId,
3335 resourceInstanceStatus.getCapabilities());
3336 } catch (StorageException | ComponentException e) {
3337 unlockRollbackWithException(containerComponent, e);
3338 } catch (Exception e) {
3339 unlockRollbackWithException(containerComponent, new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR));
3341 unlockWithCommit(containerComponent);
3345 private List<ComponentInstanceProperty> findCapabilityOfInstance(String componentId, String instanceId, String capabilityType,
3346 String capabilityName, String ownerId,
3347 Map<String, List<CapabilityDefinition>> instanceCapabilities) {
3348 CapabilityDefinition foundCapability;
3349 if (MapUtils.isNotEmpty(instanceCapabilities)) {
3350 List<CapabilityDefinition> capabilitiesPerType = instanceCapabilities.get(capabilityType);
3351 if (capabilitiesPerType != null) {
3352 Optional<CapabilityDefinition> capabilityOpt = capabilitiesPerType.stream()
3353 .filter(c -> c.getName().equals(capabilityName) && c.getOwnerId().equals(ownerId)).findFirst();
3354 if (capabilityOpt.isPresent()) {
3355 foundCapability = capabilityOpt.get();
3356 return foundCapability.getProperties() == null ? new ArrayList<>() : foundCapability.getProperties();
3360 return fetchComponentInstanceCapabilityProperties(componentId, instanceId, capabilityType, capabilityName, ownerId);
3363 private List<ComponentInstanceProperty> fetchComponentInstanceCapabilityProperties(String componentId, String instanceId, String capabilityType,
3364 String capabilityName, String ownerId) {
3366 return toscaOperationFacade.getComponentInstanceCapabilityProperties(componentId, instanceId, capabilityName, capabilityType, ownerId)
3367 .left().on(this::componentInstancePropertyListException);
3368 } catch (Exception e) {
3369 log.debug("The exception {} occurred upon the component {} instance {} capability {} properties retrieving. ", componentId, instanceId,
3371 throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
3375 public Either<RequirementDefinition, ResponseFormat> updateInstanceRequirement(ComponentTypeEnum componentTypeEnum, String containerComponentId,
3376 String componentInstanceUniqueId,
3377 RequirementDefinition requirementDef, String userId) {
3378 Either<RequirementDefinition, ResponseFormat> resultOp = null;
3379 validateUserExists(userId);
3380 if (componentTypeEnum == null) {
3381 BeEcompErrorManager.getInstance().logInvalidInputError("updateInstanceRequirement", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
3382 return Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
3384 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaFullElement(containerComponentId);
3385 if (getResourceResult.isRight()) {
3386 log.debug(FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID, containerComponentId);
3387 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
3389 Component containerComponent = getResourceResult.left().value();
3390 if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
3391 log.info(RESTRICTED_OPERATION_ON_COMPONENT, userId, containerComponentId);
3392 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
3394 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent,
3395 componentInstanceUniqueId);
3396 if (resourceInstanceStatus.isRight()) {
3397 return Either.right(componentsUtils
3398 .getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
3401 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(containerComponentId, componentTypeEnum.getNodeType());
3402 if (lockStatus != StorageOperationStatus.OK) {
3403 log.debug(FAILED_TO_LOCK_COMPONENT, containerComponentId);
3404 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
3407 StorageOperationStatus updateRequirementStatus = toscaOperationFacade
3408 .updateComponentInstanceRequirement(containerComponentId, componentInstanceUniqueId, requirementDef);
3409 if (updateRequirementStatus != StorageOperationStatus.OK) {
3410 log.debug("Failed to update component instance requirement on instance {} in container {}", componentInstanceUniqueId,
3411 containerComponentId);
3412 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateRequirementStatus)));
3414 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade
3415 .updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
3416 if (updateContainerRes.isRight()) {
3417 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
3418 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
3421 resultOp = Either.left(requirementDef);
3424 if (resultOp == null || resultOp.isRight()) {
3425 janusGraphDao.rollback();
3427 janusGraphDao.commit();
3430 graphLockOperation.unlockComponent(containerComponentId, componentTypeEnum.getNodeType());
3434 public Either<CapabilityDefinition, ResponseFormat> updateInstanceCapability(final ComponentTypeEnum containerComponentType,
3435 final String containerComponentId,
3436 final String componentInstanceUniqueId,
3437 final CapabilityDefinition capabilityDefinition,
3438 final String userId) {
3439 if (containerComponentType == null) {
3440 BeEcompErrorManager.getInstance().logInvalidInputError("updateInstanceCapability", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
3441 return Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
3443 validateUserExists(userId);
3444 final Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaFullElement(containerComponentId);
3445 if (getResourceResult.isRight()) {
3446 log.debug(FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID, containerComponentId);
3447 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NOT_FOUND, containerComponentId));
3449 final Component containerComponent = getResourceResult.left().value();
3450 if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
3451 log.info(RESTRICTED_OPERATION_ON_COMPONENT, userId, containerComponentId);
3452 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
3454 final Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus =
3455 getResourceInstanceById(containerComponent, componentInstanceUniqueId);
3456 if (resourceInstanceStatus.isRight()) {
3457 return Either.right(componentsUtils
3458 .getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
3461 final StorageOperationStatus lockStatus = graphLockOperation.lockComponent(containerComponentId, containerComponentType.getNodeType());
3462 if (lockStatus != StorageOperationStatus.OK) {
3463 log.debug(FAILED_TO_LOCK_COMPONENT, containerComponentId);
3464 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
3466 var success = false;
3468 final CapabilityDataDefinition updatedCapabilityDefinition = toscaOperationFacade
3469 .updateComponentInstanceCapability(containerComponentId, componentInstanceUniqueId, capabilityDefinition);
3470 final Either<Component, StorageOperationStatus> updateContainerEither = toscaOperationFacade
3471 .updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
3472 if (updateContainerEither.isRight()) {
3473 var actionStatus = componentsUtils.convertFromStorageResponse(updateContainerEither.right().value(), containerComponentType);
3474 return Either.right(componentsUtils.getResponseFormat(actionStatus));
3477 return Either.left(new CapabilityDefinition(updatedCapabilityDefinition));
3478 } catch (final BusinessException e) {
3479 log.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, NodeTemplateOperation.class.getName(), (ErrorLogOptionalData) null,
3480 FAILED_TO_UPDATE_COMPONENT_INSTANCE_CAPABILITY, componentInstanceUniqueId, containerComponentId);
3482 } catch (final Exception e) {
3483 log.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, NodeTemplateOperation.class.getName(), (ErrorLogOptionalData) null,
3484 FAILED_TO_UPDATE_COMPONENT_INSTANCE_CAPABILITY, componentInstanceUniqueId, containerComponentId);
3485 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
3488 janusGraphDao.commit();
3490 janusGraphDao.rollback();
3493 graphLockOperation.unlockComponent(containerComponentId, containerComponentType.getNodeType());
3497 public Either<List<ComponentInstanceProperty>, ResponseFormat> updateInstanceCapabilityProperties(ComponentTypeEnum componentTypeEnum,
3498 String containerComponentId,
3499 String componentInstanceUniqueId,
3500 String capabilityType, String capabilityName,
3501 List<ComponentInstanceProperty> properties,
3503 Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
3504 validateUserExists(userId);
3505 if (componentTypeEnum == null) {
3506 BeEcompErrorManager.getInstance().logInvalidInputError("updateInstanceCapabilityProperty", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
3507 return Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
3509 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaFullElement(containerComponentId);
3510 if (getResourceResult.isRight()) {
3511 log.debug(FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID, containerComponentId);
3512 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
3514 Component containerComponent = getResourceResult.left().value();
3515 if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
3516 log.info(RESTRICTED_OPERATION_ON_COMPONENT, userId, containerComponentId);
3517 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
3519 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent,
3520 componentInstanceUniqueId);
3521 if (resourceInstanceStatus.isRight()) {
3522 return Either.right(componentsUtils
3523 .getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
3525 ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
3527 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(containerComponentId, componentTypeEnum.getNodeType());
3528 if (lockStatus != StorageOperationStatus.OK) {
3529 log.debug(FAILED_TO_LOCK_COMPONENT, containerComponentId);
3530 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
3533 for (ComponentInstanceProperty property : properties) {
3534 Either<String, ResponseFormat> newPropertyValueEither = validatePropertyObjectValue(property, property.getValue(), false);
3535 newPropertyValueEither.bimap(
3536 updatedValue -> updateCapabilityPropertyOnContainerComponent(property, updatedValue, containerComponent, foundResourceInstance,
3537 capabilityType, capabilityName), Either::right);
3539 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade
3540 .updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
3541 if (updateContainerRes.isRight()) {
3542 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
3543 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
3546 resultOp = Either.left(properties);
3549 if (resultOp == null || resultOp.isRight()) {
3550 janusGraphDao.rollback();
3552 janusGraphDao.commit();
3555 graphLockOperation.unlockComponent(containerComponentId, componentTypeEnum.getNodeType());
3559 public Either<Map<String, ComponentInstance>, ResponseFormat> copyComponentInstance(ComponentInstance inputComponentInstance,
3560 String containerComponentId, String componentInstanceId,
3562 Map<String, ComponentInstance> resultMap = new HashMap<>();
3563 Either<Component, StorageOperationStatus> getOrigComponent = toscaOperationFacade.getToscaElement(containerComponentId);
3564 if (getOrigComponent.isRight()) {
3565 log.error("Failed to get the original component information");
3566 return Either.right(componentsUtils.getResponseFormat(ActionStatus.USER_DEFINED, FAILED_TO_COPY_COMP_INSTANCE_TO_CANVAS));
3568 Component origComponent = getOrigComponent.left().value();
3570 lockComponent(origComponent, "copyComponentInstance");
3571 } catch (ComponentException e) {
3572 log.error("destComponentInstance's data is {}", origComponent.toString());
3573 return Either.right(componentsUtils
3574 .getResponseFormat(ActionStatus.USER_DEFINED, "Failed to lock component destComponentInstance's data is {}",
3575 origComponent.toString()));
3577 boolean failed = false;
3578 ComponentInstance actionResponse = null;
3580 actionResponse = createComponentInstance("services", containerComponentId, userId, inputComponentInstance, false);
3581 } catch (ComponentException e) {
3583 // on failure of the create instance unlock the resource and rollback the transaction.
3584 return Either.right(componentsUtils.getResponseFormat(ActionStatus.USER_DEFINED, FAILED_TO_COPY_COMP_INSTANCE_TO_CANVAS));
3586 // on failure of the create instance unlock the resource and rollback the transaction.
3587 if (null == actionResponse) {
3588 log.error(FAILED_TO_COPY_COMP_INSTANCE_TO_CANVAS);
3589 unlockComponent(failed, origComponent);
3592 Either<String, ResponseFormat> resultOp = null;
3594 ComponentInstance destComponentInstance = actionResponse;
3595 log.debug("destComponentInstance's data is {}", destComponentInstance);
3596 resultOp = deepCopyComponentInstance(origComponent, containerComponentId, componentInstanceId, destComponentInstance, userId);
3597 resultMap.put("componentInstance", destComponentInstance);
3600 if (resultOp == null || resultOp.isRight()) {
3601 unlockComponent(true, origComponent);
3602 janusGraphDao.rollback();
3603 log.error("Failed to deep copy component instance");
3605 unlockComponent(false, origComponent);
3606 janusGraphDao.commit();
3607 log.debug("Success trasaction commit");
3610 if (resultOp == null || resultOp.isRight()) {
3612 .right(componentsUtils.getResponseFormat(ActionStatus.USER_DEFINED, "Failed to deep copy the component instance to the canvas"));
3614 return Either.left(resultMap);
3618 private Either<String, ResponseFormat> deepCopyComponentInstance(Component sourceComponent, String containerComponentId,
3619 String sourceComponentInstanceId, ComponentInstance destComponentInstance,
3621 Either<Component, StorageOperationStatus> getDestComponent = toscaOperationFacade.getToscaElement(containerComponentId);
3622 if (getDestComponent.isRight()) {
3623 log.error("Failed to get the dest component information");
3624 return Either.right(componentsUtils.getResponseFormat(ActionStatus.USER_DEFINED, FAILED_TO_COPY_COMP_INSTANCE_TO_CANVAS));
3626 Component destComponent = getDestComponent.left().value();
3627 Either<String, ResponseFormat> copyComponentInstanceWithPropertiesAndInputs = copyComponentInstanceWithPropertiesAndInputs(sourceComponent,
3628 destComponent, sourceComponentInstanceId, destComponentInstance);
3629 if (copyComponentInstanceWithPropertiesAndInputs.isRight()) {
3630 log.error("Failed to copy component instance with properties and inputs as part of deep copy");
3631 return Either.right(componentsUtils.getResponseFormat(ActionStatus.USER_DEFINED,
3632 "Failed to copy the component instance with properties and inputs as part of deep copy"));
3634 Either<String, ResponseFormat> copyComponentInstanceWithAttributes = copyComponentInstanceWithAttributes(sourceComponent, destComponent,
3635 sourceComponentInstanceId, destComponentInstance, userId);
3636 if (copyComponentInstanceWithAttributes.isRight()) {
3637 log.error("Failed to copy component instance with attributes as part of deep copy");
3638 return Either.right(componentsUtils
3639 .getResponseFormat(ActionStatus.USER_DEFINED, "Failed to copy the component instance with attributes as part of deep copy"));
3641 return Either.left(COPY_COMPONENT_INSTANCE_OK);
3644 private Either<String, ResponseFormat> copyComponentInstanceWithPropertiesAndInputs(Component sourceComponent, Component destComponent,
3645 String sourceComponentInstanceId,
3646 ComponentInstance destComponentInstance) {
3647 log.debug("start to copy ComponentInstance with properties and inputs");
3648 List<ComponentInstanceProperty> sourcePropList = null;
3649 if (sourceComponent.getComponentInstancesProperties() != null
3650 && sourceComponent.getComponentInstancesProperties().get(sourceComponentInstanceId) != null) {
3651 sourcePropList = sourceComponent.getComponentInstancesProperties().get(sourceComponentInstanceId);
3652 log.debug("sourcePropList");
3654 List<ComponentInstanceProperty> destPropList = null;
3655 String destComponentInstanceId = destComponentInstance.getUniqueId();
3656 log.debug("destComponentInstanceId: {}", destComponentInstance.getUniqueId());
3657 if (destComponent.getComponentInstancesProperties() != null
3658 && destComponent.getComponentInstancesProperties().get(destComponentInstanceId) != null) {
3659 destPropList = destComponent.getComponentInstancesProperties().get(destComponentInstanceId);
3660 log.debug("destPropList {}");
3662 List<ComponentInstancePropInput> componentInstancePropInputList = new ArrayList<>();
3663 if (null != destPropList && null != sourcePropList) {
3664 log.debug("start to set property and attribute");
3665 for (ComponentInstanceProperty destProp : destPropList) {
3666 String destPropertyName = destProp.getName();
3667 for (ComponentInstanceProperty sourceProp : sourcePropList) {
3668 if (!destPropertyName.equals(sourceProp.getName())) {
3671 log.debug("now set property");
3672 final List<GetInputValueDataDefinition> getInputValues = sourceProp.getGetInputValues();
3673 if (getInputValues == null && !StringUtils.isEmpty(sourceProp.getValue()) && (destProp.getValue() == null || !destProp.getValue()
3674 .equals(sourceProp.getValue()))) {
3675 log.debug("Now starting to copy the property {} in value {}", destPropertyName, sourceProp.getValue());
3676 destProp.setValue(sourceProp.getValue());
3677 Either<String, ResponseFormat> updatePropertyValueEither = updateComponentInstanceProperty(destComponent.getUniqueId(),
3678 destComponentInstanceId, destProp);
3679 if (updatePropertyValueEither.isRight()) {
3680 log.error("Failed to copy the property {}", destPropertyName);
3681 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM,
3682 "Failed to paste component instance to the canvas, property copy"));
3686 log.debug("Now start to update inputs");
3687 if (getInputValues != null) {
3688 if (getInputValues.isEmpty()) {
3689 log.debug("property is return from input, set by man");
3692 log.debug("Now starting to copy the {} property", destPropertyName);
3693 Either<String, ResponseFormat> getSourceInputDefaultValue = getInputListDefaultValue(sourceComponent,
3694 getInputValues.get(0).getInputId());
3695 if (getSourceInputDefaultValue.isRight()) {
3696 return Either.right(getSourceInputDefaultValue.right().value());
3698 componentInstancePropInputList.add(new ComponentInstancePropInput(destProp));
3703 return Either.left(COPY_COMPONENT_INSTANCE_OK);
3706 private Either<String, ResponseFormat> copyComponentInstanceWithAttributes(Component sourceComponent, Component destComponent,
3707 String sourceComponentInstanceId,
3708 ComponentInstance destComponentInstance, String userId) {
3709 String destComponentInstanceId = destComponentInstance.getUniqueId();
3710 log.info("start to copy component instance with attributes");
3711 List<ComponentInstanceAttribute> sourceAttributeList = null;
3712 if (sourceComponent.getComponentInstancesAttributes() != null
3713 && sourceComponent.getComponentInstancesAttributes().get(sourceComponentInstanceId) != null) {
3714 sourceAttributeList = sourceComponent.getComponentInstancesAttributes().get(sourceComponentInstanceId);
3715 log.info("sourceAttributes {}");
3717 List<ComponentInstanceAttribute> destAttributeList = null;
3718 if (destComponent.getComponentInstancesAttributes() != null
3719 && destComponent.getComponentInstancesAttributes().get(destComponentInstanceId) != null) {
3720 destAttributeList = destComponent.getComponentInstancesAttributes().get(destComponentInstanceId);
3721 log.info("destAttributeList {}");
3723 if (null != sourceAttributeList && null != destAttributeList) {
3724 log.info("set attribute");
3725 for (ComponentInstanceAttribute sourceAttribute : sourceAttributeList) {
3726 String sourceAttributeName = sourceAttribute.getName();
3727 for (ComponentInstanceAttribute destAttribute : destAttributeList) {
3728 if (sourceAttributeName.equals(destAttribute.getName())) {
3729 log.debug("Start to copy the attribute exists {}", sourceAttributeName);
3730 sourceAttribute.setUniqueId(
3731 UniqueIdBuilder.buildResourceInstanceUniuqeId("attribute", destComponentInstanceId.split("\\.")[1], sourceAttributeName));
3732 Either<ComponentInstanceAttribute, ResponseFormat> updateAttributeValueEither = createOrUpdateAttributeValueForCopyPaste(
3733 ComponentTypeEnum.SERVICE, destComponent.getUniqueId(), destComponentInstanceId, sourceAttribute, userId);
3734 if (updateAttributeValueEither.isRight()) {
3735 log.error("Failed to copy the attribute");
3736 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM,
3737 "Failed to paste component instance to the canvas, attribute copy"));
3744 return Either.left(COPY_COMPONENT_INSTANCE_OK);
3747 private Either<ComponentInstanceAttribute, ResponseFormat> createOrUpdateAttributeValueForCopyPaste(ComponentTypeEnum componentTypeEnum,
3748 String componentId, String resourceInstanceId,
3749 ComponentInstanceAttribute attribute,
3751 Either<ComponentInstanceAttribute, ResponseFormat> resultOp = null;
3752 validateUserExists(userId);
3753 if (componentTypeEnum == null) {
3754 BeEcompErrorManager.getInstance()
3755 .logInvalidInputError("createOrUpdateAttributeValueForCopyPaste", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
3756 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
3759 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
3760 if (getResourceResult.isRight()) {
3761 log.info("Failed to retrieve component id {}", componentId);
3762 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
3765 Component containerComponent = getResourceResult.left().value();
3766 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId);
3767 if (resourceInstanceStatus.isRight()) {
3769 .right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, resourceInstanceId, componentId));
3772 ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
3773 String propertyType = attribute.getType();
3774 ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
3775 log.info("The type of attribute id{},is {} ", attribute.getUniqueId(), propertyType);
3776 if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
3777 SchemaDefinition def = attribute.getSchema();
3779 log.info("Schema doesn't exists for attribute of type {}", type);
3781 .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
3783 PropertyDataDefinition propDef = def.getProperty();
3784 if (propDef == null) {
3785 log.info("Attribute in Schema Definition inside attribute of type {} doesn't exist", type);
3787 .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
3790 List<ComponentInstanceAttribute> instanceAttributes = containerComponent.getComponentInstancesAttributes().get(resourceInstanceId);
3791 Optional<ComponentInstanceAttribute> instanceAttribute = instanceAttributes.stream()
3792 .filter(p -> p.getUniqueId().equals(attribute.getUniqueId())).findAny();
3793 StorageOperationStatus status;
3794 if (instanceAttribute.isPresent()) {
3795 log.info("updateComponentInstanceAttribute");
3796 status = toscaOperationFacade.updateComponentInstanceAttribute(containerComponent, foundResourceInstance.getUniqueId(), attribute);
3798 log.info("addComponentInstanceAttribute");
3799 status = toscaOperationFacade.addComponentInstanceAttribute(containerComponent, foundResourceInstance.getUniqueId(), attribute);
3801 if (status != StorageOperationStatus.OK) {
3802 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
3803 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
3806 List<String> path = new ArrayList<>();
3807 path.add(foundResourceInstance.getUniqueId());
3808 attribute.setPath(path);
3809 foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
3810 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade
3811 .updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
3812 if (updateContainerRes.isRight()) {
3813 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
3814 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
3817 resultOp = Either.left(attribute);
3821 private Either<String, ResponseFormat> updateComponentInstanceProperty(String containerComponentId, String componentInstanceId,
3822 ComponentInstanceProperty property) {
3823 Either<String, ResponseFormat> resultOp;
3824 Either<Component, StorageOperationStatus> getComponent = toscaOperationFacade.getToscaElement(containerComponentId);
3825 if (getComponent.isRight()) {
3826 log.error("Failed to get the component information");
3827 return Either.right(componentsUtils
3828 .getResponseFormatForResourceInstanceProperty(ActionStatus.INVALID_CONTENT_PARAM, "Failed to get the component information"));
3830 Component containerComponent = getComponent.left().value();
3831 StorageOperationStatus status = toscaOperationFacade.updateComponentInstanceProperty(containerComponent, componentInstanceId, property);
3832 if (status != StorageOperationStatus.OK) {
3833 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
3834 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
3837 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade
3838 .updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
3839 if (updateContainerRes.isRight()) {
3840 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
3841 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
3844 return Either.left("Update OK");
3847 private Either<String, ResponseFormat> getInputListDefaultValue(Component component, String inputId) {
3848 List<InputDefinition> inputList = component.getInputs();
3849 for (InputDefinition input : inputList) {
3850 if (input.getUniqueId().equals(inputId)) {
3851 if (input.getDefaultValue() == null) {
3852 log.debug("The input's default value is null");
3853 return Either.left(null);
3855 return Either.left(input.getDefaultValue());
3858 log.error("The input's default value with id {} is not found", inputId);
3859 return Either.right(componentsUtils.getResponseFormat(ActionStatus.USER_DEFINED, "Failed to paste component instance to the canvas"));
3863 * Method to delete selected nodes and edges on composition page
3865 * @param containerComponentType
3866 * @param componentId
3867 * @param componentInstanceIdList
3871 public Map<String, List<String>> batchDeleteComponentInstance(String containerComponentType, String componentId,
3872 List<String> componentInstanceIdList, String userId) {
3873 List<String> deleteErrorIds = new ArrayList<>();
3874 Map<String, List<String>> deleteErrorMap = new HashMap<>();
3875 validateUserExists(userId);
3876 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(componentId,
3877 ComponentTypeEnum.findByParamName(containerComponentType), null);
3878 boolean failed = false;
3880 lockComponent(containerComponent, "batchDeleteComponentInstance");
3881 for (String eachInstanceId : componentInstanceIdList) {
3882 Either<ComponentInstance, ResponseFormat> actionResponse = batchDeleteComponentInstance(containerComponent, containerComponentType,
3884 log.debug("batchDeleteResourceInstances actionResponse is {}", actionResponse);
3885 if (actionResponse.isRight()) {
3886 log.error("Failed to delete ComponentInstance [{}]", eachInstanceId);
3887 deleteErrorIds.add(eachInstanceId);
3890 //sending the ids of the error nodes that were not deleted to UI
3891 deleteErrorMap.put("deleteFailedIds", deleteErrorIds);
3892 return deleteErrorMap;
3893 } catch (ComponentException e) {
3897 unlockComponent(failed, containerComponent);
3901 private Either<ComponentInstance, ResponseFormat> batchDeleteComponentInstance(Component containerComponent, String containerComponentType,
3902 String componentInstanceId) {
3903 ComponentInstance resultOp;
3904 final ComponentTypeEnum containerComponentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
3906 resultOp = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentTypeEnum);
3907 log.info("Successfully deleted instance with id {}", componentInstanceId);
3908 return Either.left(resultOp);
3909 } catch (ComponentException e) {
3910 log.error("Failed to deleteComponentInstance with instanceId[{}]", componentInstanceId);
3911 return Either.right(new ResponseFormat());
3915 public void validateUser(final String userId) {
3916 final User user = userValidations.validateUserExists(userId);
3917 userValidations.validateUserRole(user, Arrays.asList(Role.DESIGNER, Role.ADMIN));
3920 public void setCompositionBusinessLogic(CompositionBusinessLogic compositionBusinessLogic) {
3921 this.compositionBusinessLogic = compositionBusinessLogic;
3924 public void setContainerInstanceTypesData(ContainerInstanceTypesData containerInstanceTypesData) {
3925 this.containerInstanceTypesData = containerInstanceTypesData;