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.onap.sdc.tosca.datatypes.model.PropertyType;
47 import org.openecomp.sdc.be.components.impl.exceptions.BusinessLogicException;
48 import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
49 import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException;
50 import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
51 import org.openecomp.sdc.be.components.impl.exceptions.ToscaGetFunctionExceptionSupplier;
52 import org.openecomp.sdc.be.components.impl.instance.ComponentInstanceChangeOperationOrchestrator;
53 import org.openecomp.sdc.be.components.impl.utils.DirectivesUtil;
54 import org.openecomp.sdc.be.components.merge.instance.ComponentInstanceMergeDataBusinessLogic;
55 import org.openecomp.sdc.be.components.merge.instance.DataForMergeHolder;
56 import org.openecomp.sdc.be.components.utils.PropertiesUtils;
57 import org.openecomp.sdc.be.components.validation.ComponentValidations;
58 import org.openecomp.sdc.be.config.BeEcompErrorManager;
59 import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
60 import org.openecomp.sdc.be.config.ConfigurationManager;
61 import org.openecomp.sdc.be.dao.api.ActionStatus;
62 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
63 import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
64 import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
65 import org.openecomp.sdc.be.datatypes.elements.CINodeFilterDataDefinition;
66 import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition;
67 import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition;
68 import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition;
69 import org.openecomp.sdc.be.datatypes.elements.GetOutputValueDataDefinition;
70 import org.openecomp.sdc.be.datatypes.elements.GetPolicyValueDataDefinition;
71 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
72 import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition;
73 import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
74 import org.openecomp.sdc.be.datatypes.elements.ToscaGetFunctionDataDefinition;
75 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
76 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
77 import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
78 import org.openecomp.sdc.be.datatypes.enums.PropertySource;
79 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
80 import org.openecomp.sdc.be.datatypes.tosca.ToscaGetFunctionType;
81 import org.openecomp.sdc.be.exception.BusinessException;
82 import org.openecomp.sdc.be.impl.ComponentsUtils;
83 import org.openecomp.sdc.be.impl.ForwardingPathUtils;
84 import org.openecomp.sdc.be.impl.ServiceFilterUtils;
85 import org.openecomp.sdc.be.info.CreateAndAssotiateInfo;
86 import org.openecomp.sdc.be.model.ArtifactDefinition;
87 import org.openecomp.sdc.be.model.AttributeDefinition;
88 import org.openecomp.sdc.be.model.CapabilityDefinition;
89 import org.openecomp.sdc.be.model.Component;
90 import org.openecomp.sdc.be.model.ComponentInstance;
91 import org.openecomp.sdc.be.model.ComponentInstanceAttribute;
92 import org.openecomp.sdc.be.model.ComponentInstanceInput;
93 import org.openecomp.sdc.be.model.ComponentInstanceOutput;
94 import org.openecomp.sdc.be.model.ComponentInstancePropInput;
95 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
96 import org.openecomp.sdc.be.model.ComponentParametersView;
97 import org.openecomp.sdc.be.model.DataTypeDefinition;
98 import org.openecomp.sdc.be.model.GroupDefinition;
99 import org.openecomp.sdc.be.model.InputDefinition;
100 import org.openecomp.sdc.be.model.InterfaceDefinition;
101 import org.openecomp.sdc.be.model.LifecycleStateEnum;
102 import org.openecomp.sdc.be.model.OutputDefinition;
103 import org.openecomp.sdc.be.model.PolicyDefinition;
104 import org.openecomp.sdc.be.model.PropertyDefinition;
105 import org.openecomp.sdc.be.model.RelationshipInfo;
106 import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
107 import org.openecomp.sdc.be.model.RequirementDefinition;
108 import org.openecomp.sdc.be.model.Resource;
109 import org.openecomp.sdc.be.model.Service;
110 import org.openecomp.sdc.be.model.User;
111 import org.openecomp.sdc.be.model.jsonjanusgraph.config.ContainerInstanceTypesData;
112 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ArtifactsOperations;
113 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ForwardingPathOperation;
114 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.InterfaceOperation;
115 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.NodeFilterOperation;
116 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.NodeTemplateOperation;
117 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade;
118 import org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter;
119 import org.openecomp.sdc.be.model.operations.StorageException;
120 import org.openecomp.sdc.be.model.operations.api.IElementOperation;
121 import org.openecomp.sdc.be.model.operations.api.IGroupInstanceOperation;
122 import org.openecomp.sdc.be.model.operations.api.IGroupOperation;
123 import org.openecomp.sdc.be.model.operations.api.IGroupTypeOperation;
124 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
125 import org.openecomp.sdc.be.model.operations.impl.ComponentInstanceOperation;
126 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
127 import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation;
128 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
129 import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
130 import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
131 import org.openecomp.sdc.be.resources.data.ComponentInstanceData;
132 import org.openecomp.sdc.be.user.Role;
133 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
134 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
135 import org.openecomp.sdc.common.api.Constants;
136 import org.openecomp.sdc.common.datastructure.Wrapper;
137 import org.openecomp.sdc.common.jsongraph.util.CommonUtility;
138 import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum;
139 import org.openecomp.sdc.common.log.elements.ErrorLogOptionalData;
140 import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode;
141 import org.openecomp.sdc.common.log.wrappers.Logger;
142 import org.openecomp.sdc.common.util.ValidationUtils;
143 import org.openecomp.sdc.exception.ResponseFormat;
144 import org.springframework.beans.factory.annotation.Autowired;
146 @org.springframework.stereotype.Component
147 public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
149 private static final Logger log = Logger.getLogger(ComponentInstanceBusinessLogic.class);
150 private static final String VF_MODULE = "org.openecomp.groups.VfModule";
151 private static final String TRY_TO_CREATE_ENTRY_ON_GRAPH = "Try to create entry on graph";
152 private static final String CLOUD_SPECIFIC_FIXED_KEY_WORD = "cloudtech";
153 private static final String[][] CLOUD_SPECIFIC_KEY_WORDS = {{"k8s", "azure", "aws"}, /* cloud specific technology */
154 {"charts", "day0", "configtemplate"} /*cloud specific sub type*/};
155 private static final String FAILED_TO_CREATE_ENTRY_ON_GRAPH_FOR_COMPONENT_INSTANCE = "Failed to create entry on graph for component instance {}";
156 private static final String ENTITY_ON_GRAPH_IS_CREATED = "Entity on graph is created.";
157 private static final String INVALID_COMPONENT_TYPE = "invalid component type";
158 private static final String FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID = "Failed to retrieve component, component id {}";
159 private static final String FAILED_TO_LOCK_SERVICE = "Failed to lock service {}";
160 private static final String CREATE_OR_UPDATE_PROPERTY_VALUE = "CreateOrUpdatePropertyValue";
161 private static final String FAILED_TO_COPY_COMP_INSTANCE_TO_CANVAS = "Failed to copy the component instance to the canvas";
162 private static final String COPY_COMPONENT_INSTANCE_OK = "Copy component instance OK";
163 private static final String CANNOT_ATTACH_RESOURCE_INSTANCES_TO_CONTAINER_RESOURCE_OF_TYPE = "Cannot attach resource instances to container resource of type {}";
164 private static final String FAILED_TO_UPDATE_COMPONENT_INSTANCE_CAPABILITY = "Failed to update component instance capability on instance {} in "
166 private static final String SERVICE_PROXY = "serviceProxy";
167 private static final String ASSOCIATE_RI_TO_RI = "associateRIToRI";
168 private static final String COMPONENT_ARCHIVED = "Component is archived. Component id: {}";
169 private static final String RESTRICTED_OPERATION_ON_SERVIVE = "Restricted operation for user: {} on service {}";
170 private static final String FAILED_TO_LOCK_COMPONENT = "Failed to lock component {}";
171 private static final String RESTRICTED_OPERATION_ON_COMPONENT = "Restricted operation for user: {} on component {}";
172 private static final String RESOURCE_INSTANCE = "resource instance";
173 private static final String SERVICE = "service";
175 private final ComponentInstanceOperation componentInstanceOperation;
176 private final ArtifactsBusinessLogic artifactBusinessLogic;
177 private final ComponentInstanceMergeDataBusinessLogic compInstMergeDataBL;
178 private final ComponentInstanceChangeOperationOrchestrator onChangeInstanceOperationOrchestrator;
179 private final ForwardingPathOperation forwardingPathOperation;
180 private final NodeFilterOperation nodeFilterOperation;
182 private CompositionBusinessLogic compositionBusinessLogic;
184 private ContainerInstanceTypesData containerInstanceTypesData;
187 public ComponentInstanceBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation,
188 IGroupInstanceOperation groupInstanceOperation, IGroupTypeOperation groupTypeOperation,
189 InterfaceOperation interfaceOperation, InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
190 ComponentInstanceOperation componentInstanceOperation, ArtifactsBusinessLogic artifactBusinessLogic,
191 ComponentInstanceMergeDataBusinessLogic compInstMergeDataBL,
192 ComponentInstanceChangeOperationOrchestrator onChangeInstanceOperationOrchestrator,
193 ForwardingPathOperation forwardingPathOperation, NodeFilterOperation nodeFilterOperation,
194 ArtifactsOperations artifactToscaOperation) {
195 super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation,
196 artifactToscaOperation);
197 this.componentInstanceOperation = componentInstanceOperation;
198 this.artifactBusinessLogic = artifactBusinessLogic;
199 this.compInstMergeDataBL = compInstMergeDataBL;
200 this.onChangeInstanceOperationOrchestrator = onChangeInstanceOperationOrchestrator;
201 this.forwardingPathOperation = forwardingPathOperation;
202 this.nodeFilterOperation = nodeFilterOperation;
205 public ComponentInstance createComponentInstance(String containerComponentParam, String containerComponentId, String userId,
206 ComponentInstance resourceInstance) {
207 return createComponentInstance(containerComponentParam, containerComponentId, userId, resourceInstance, true);
210 public List<ComponentInstanceProperty> getComponentInstancePropertiesByInputId(org.openecomp.sdc.be.model.Component component, String inputId) {
211 List<ComponentInstanceProperty> resList = new ArrayList<>();
212 Map<String, List<ComponentInstanceProperty>> ciPropertiesMap = component.getComponentInstancesProperties();
213 if (ciPropertiesMap != null && !ciPropertiesMap.isEmpty()) {
214 ciPropertiesMap.forEach((s, ciPropList) -> {
216 Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(s)).findAny();
217 if (ciOp.isPresent()) {
218 ciName = ciOp.get().getName();
220 if (ciPropList != null && !ciPropList.isEmpty()) {
221 for (ComponentInstanceProperty prop : ciPropList) {
222 List<GetInputValueDataDefinition> inputsValues = prop.getGetInputValues();
223 addCompInstanceProperty(s, ciName, prop, inputsValues, inputId, resList);
231 public List<ComponentInstanceAttribute> getComponentInstanceAttributesByOutputId(final org.openecomp.sdc.be.model.Component component,
232 final String outputId) {
233 final List<ComponentInstanceAttribute> resList = new ArrayList<>();
234 final Map<String, List<ComponentInstanceAttribute>> componentInstancesAttributes = component.getComponentInstancesAttributes();
235 if (org.apache.commons.collections4.MapUtils.isNotEmpty(componentInstancesAttributes)) {
236 componentInstancesAttributes.forEach((s, componentInstanceAttributeList) -> {
238 final Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(s))
240 if (ciOp.isPresent()) {
241 ciName = ciOp.get().getName();
243 if (componentInstanceAttributeList != null && !componentInstanceAttributeList.isEmpty()) {
244 for (final ComponentInstanceAttribute compInstanceAttribute : componentInstanceAttributeList) {
245 List<GetOutputValueDataDefinition> outputValues = compInstanceAttribute.getGetOutputValues();
246 addCompInstanceAttribute(s, ciName, compInstanceAttribute, outputValues, outputId, resList);
254 private void addCompInstanceProperty(String s, String ciName, ComponentInstanceProperty prop, List<GetInputValueDataDefinition> inputsValues,
255 String inputId, List<ComponentInstanceProperty> resList) {
256 if (inputsValues != null && !inputsValues.isEmpty()) {
257 for (GetInputValueDataDefinition inputData : inputsValues) {
258 if (isGetInputValueForInput(inputData, inputId)) {
259 prop.setComponentInstanceId(s);
260 prop.setComponentInstanceName(ciName);
268 private void addCompInstanceAttribute(final String s, final String ciName, final ComponentInstanceAttribute attribute,
269 final List<GetOutputValueDataDefinition> outputsValues, final String outputId,
270 final List<ComponentInstanceAttribute> resList) {
271 if (outputsValues != null && !outputsValues.isEmpty()) {
272 for (final GetOutputValueDataDefinition outputData : outputsValues) {
273 if (isGetOutputValueForOutput(outputData, outputId)) {
274 attribute.setComponentInstanceId(s);
275 attribute.setComponentInstanceName(ciName);
276 resList.add(attribute);
283 public Optional<ComponentInstanceProperty> getComponentInstancePropertyByPolicyId(Component component, PolicyDefinition policy) {
284 Optional<ComponentInstanceProperty> propertyCandidate = getComponentInstancePropertyByPolicy(component, policy);
285 if (propertyCandidate.isPresent()) {
286 ComponentInstanceProperty componentInstanceProperty = propertyCandidate.get();
287 Optional<GetPolicyValueDataDefinition> getPolicyCandidate = getGetPolicyValueDataDefinition(policy, componentInstanceProperty);
289 .ifPresent(getPolicyValue -> updateComponentInstancePropertyAfterUndeclaration(componentInstanceProperty, getPolicyValue, policy));
290 return Optional.of(componentInstanceProperty);
292 return Optional.empty();
295 private void updateComponentInstancePropertyAfterUndeclaration(ComponentInstanceProperty componentInstanceProperty,
296 GetPolicyValueDataDefinition getPolicyValue, PolicyDefinition policyDefinition) {
297 componentInstanceProperty.setValue(getPolicyValue.getOrigPropertyValue());
298 List<GetPolicyValueDataDefinition> getPolicyValues = componentInstanceProperty.getGetPolicyValues();
299 if (CollectionUtils.isNotEmpty(getPolicyValues)) {
300 getPolicyValues.remove(getPolicyValue);
301 componentInstanceProperty.setGetPolicyValues(getPolicyValues);
302 policyDefinition.setGetPolicyValues(getPolicyValues);
306 private Optional<GetPolicyValueDataDefinition> getGetPolicyValueDataDefinition(PolicyDefinition policy,
307 ComponentInstanceProperty componentInstanceProperty) {
308 List<GetPolicyValueDataDefinition> getPolicyValues = policy.getGetPolicyValues();
309 return getPolicyValues.stream().filter(getPolicyValue -> getPolicyValue.getPropertyName().equals(componentInstanceProperty.getName()))
313 private Optional<ComponentInstanceProperty> getComponentInstancePropertyByPolicy(Component component, PolicyDefinition policy) {
314 Map<String, List<ComponentInstanceProperty>> componentInstancesProperties = component.getComponentInstancesProperties();
315 if (MapUtils.isEmpty(componentInstancesProperties)) {
316 return Optional.empty();
318 String instanceUniqueId = policy.getInstanceUniqueId();
319 List<ComponentInstanceProperty> componentInstanceProperties =
320 componentInstancesProperties.containsKey(instanceUniqueId) ? componentInstancesProperties.get(instanceUniqueId) : new ArrayList<>();
321 return componentInstanceProperties.stream().filter(property -> property.getName().equals(policy.getName())).findAny();
324 public List<ComponentInstanceInput> getComponentInstanceInputsByInputId(org.openecomp.sdc.be.model.Component component, String inputId) {
325 List<ComponentInstanceInput> resList = new ArrayList<>();
326 Map<String, List<ComponentInstanceInput>> ciInputsMap = component.getComponentInstancesInputs();
327 if (ciInputsMap != null && !ciInputsMap.isEmpty()) {
328 ciInputsMap.forEach((s, ciPropList) -> {
330 Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(s)).findAny();
331 if (ciOp.isPresent()) {
332 ciName = ciOp.get().getName();
334 if (ciPropList != null && !ciPropList.isEmpty()) {
335 for (ComponentInstanceInput prop : ciPropList) {
336 List<GetInputValueDataDefinition> inputsValues = prop.getGetInputValues();
337 addCompInstanceInput(s, ciName, prop, inputsValues, inputId, resList);
345 public List<ComponentInstanceOutput> getComponentInstanceOutputsByOutputId(final org.openecomp.sdc.be.model.Component component,
346 final String outputId) {
347 final List<ComponentInstanceOutput> resList = new ArrayList<>();
348 final Map<String, List<ComponentInstanceOutput>> ciInputsMap = component.getComponentInstancesOutputs();
349 if (ciInputsMap != null && !ciInputsMap.isEmpty()) {
350 ciInputsMap.forEach((s, ciPropList) -> {
352 final Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(s))
354 if (ciOp.isPresent()) {
355 ciName = ciOp.get().getName();
357 if (ciPropList != null && !ciPropList.isEmpty()) {
358 for (final ComponentInstanceOutput prop : ciPropList) {
359 final List<GetOutputValueDataDefinition> outputValues = prop.getGetOutputValues();
360 addCompInstanceOutput(s, ciName, prop, outputValues, outputId, resList);
368 private void addCompInstanceInput(String s, String ciName, ComponentInstanceInput prop, List<GetInputValueDataDefinition> inputsValues,
369 String inputId, List<ComponentInstanceInput> resList) {
370 if (inputsValues != null && !inputsValues.isEmpty()) {
371 for (GetInputValueDataDefinition inputData : inputsValues) {
372 if (isGetInputValueForInput(inputData, inputId)) {
373 prop.setComponentInstanceId(s);
374 prop.setComponentInstanceName(ciName);
382 private void addCompInstanceOutput(final String s, final String ciName, final ComponentInstanceOutput prop,
383 final List<GetOutputValueDataDefinition> outputsValues, final String outputId,
384 final List<ComponentInstanceOutput> resList) {
385 if (outputsValues != null && !outputsValues.isEmpty()) {
386 for (final GetOutputValueDataDefinition outputData : outputsValues) {
387 if (isGetOutputValueForOutput(outputData, outputId)) {
388 prop.setComponentInstanceId(s);
389 prop.setComponentInstanceName(ciName);
397 public ComponentInstance createComponentInstance(final String containerComponentParam, final String containerComponentId, final String userId,
398 final ComponentInstance resourceInstance, final boolean needLock) {
399 final User user = validateUserExists(userId);
400 validateUserNotEmpty(user, "Create component instance");
401 validateJsonBody(resourceInstance, ComponentInstance.class);
402 final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
403 final org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, null);
404 if (ModelConverter.isAtomicComponent(containerComponent)) {
405 if (log.isDebugEnabled()) {
406 log.debug(CANNOT_ATTACH_RESOURCE_INSTANCES_TO_CONTAINER_RESOURCE_OF_TYPE, containerComponent.assetType());
408 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType());
410 validateCanWorkOnComponent(containerComponent, userId);
411 Component origComponent = null;
412 if (resourceInstance != null && containerComponentType != null) {
413 final OriginTypeEnum originType = resourceInstance.getOriginType();
414 validateInstanceName(resourceInstance);
415 if (originType == OriginTypeEnum.ServiceProxy) {
416 origComponent = getOrigComponentForServiceProxy(containerComponent, resourceInstance);
417 } else if (originType == OriginTypeEnum.ServiceSubstitution) {
418 origComponent = getOrigComponentForServiceSubstitution(resourceInstance);
420 origComponent = getAndValidateOriginComponentOfComponentInstance(containerComponent, resourceInstance);
421 validateOriginAndResourceInstanceTypes(containerComponent, origComponent, originType);
423 validateResourceInstanceState(containerComponent, origComponent);
424 overrideFields(origComponent, resourceInstance);
425 compositionBusinessLogic.validateAndSetDefaultCoordinates(resourceInstance);
427 return createComponent(needLock, containerComponent, origComponent, resourceInstance, user);
430 private Component getOrigComponentForServiceProxy(org.openecomp.sdc.be.model.Component containerComponent, ComponentInstance resourceInstance) {
431 Either<Component, StorageOperationStatus> serviceProxyOrigin = toscaOperationFacade.getLatestByName(SERVICE_PROXY, null);
432 if (isServiceProxyOrigin(serviceProxyOrigin)) {
433 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(serviceProxyOrigin.right().value()));
435 Component origComponent = serviceProxyOrigin.left().value();
436 StorageOperationStatus fillProxyRes = fillInstanceData(resourceInstance, origComponent);
437 if (isFillProxyRes(fillProxyRes)) {
438 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(fillProxyRes));
440 validateOriginAndResourceInstanceTypes(containerComponent, origComponent, OriginTypeEnum.ServiceProxy);
441 return origComponent;
444 private Component getOrigComponentForServiceSubstitution(ComponentInstance resourceInstance) {
445 final Either<Component, StorageOperationStatus> getServiceResult = toscaOperationFacade
446 .getToscaFullElement(resourceInstance.getComponentUid());
447 if (getServiceResult.isRight()) {
448 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(getServiceResult.right().value()));
450 final Component service = getServiceResult.left().value();
451 final Either<Component, StorageOperationStatus> getServiceDerivedFromTypeResult = toscaOperationFacade
452 .getLatestByToscaResourceName(service.getDerivedFromGenericType(), service.getModel());
453 if (getServiceDerivedFromTypeResult.isRight()) {
454 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(getServiceResult.right().value()));
456 Component origComponent = getServiceDerivedFromTypeResult.left().value();
457 final StorageOperationStatus fillProxyRes = fillInstanceData(resourceInstance, origComponent);
458 if (isFillProxyRes(fillProxyRes)) {
459 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(fillProxyRes));
461 return origComponent;
464 private ComponentInstance createComponent(boolean needLock, Component containerComponent, Component origComponent,
465 ComponentInstance resourceInstance, User user) {
466 boolean failed = false;
468 lockIfNeed(needLock, containerComponent);
469 log.debug(TRY_TO_CREATE_ENTRY_ON_GRAPH);
470 return createComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, user);
471 } catch (ComponentException e) {
476 unlockComponent(failed, containerComponent);
482 * Try using either to make a judgment
484 * @param containerComponentParam
485 * @param containerComponentId
487 * @param resourceInstance
490 public Either<ComponentInstance, ResponseFormat> createRealComponentInstance(String containerComponentParam, String containerComponentId,
491 String userId, ComponentInstance resourceInstance) {
492 log.debug("enter createRealComponentInstance");
493 return createRealComponentInstance(containerComponentParam, containerComponentId, userId, resourceInstance, true);
497 * Try using either to make a judgment
500 * @param containerComponentParam
501 * @param containerComponentId
503 * @param resourceInstance
506 public Either<ComponentInstance, ResponseFormat> createRealComponentInstance(String containerComponentParam, String containerComponentId,
507 String userId, ComponentInstance resourceInstance,
509 log.debug("enter createRealComponentInstance");
510 Component origComponent = null;
512 org.openecomp.sdc.be.model.Component containerComponent = null;
513 ComponentTypeEnum containerComponentType;
515 user = validateUserExists(userId);
516 validateUserNotEmpty(user, "Create component instance");
517 validateJsonBody(resourceInstance, ComponentInstance.class);
518 containerComponentType = validateComponentType(containerComponentParam);
519 containerComponent = validateComponentExists(containerComponentId, containerComponentType, null);
520 log.debug("enter createRealComponentInstance,validate user json success");
521 if (ModelConverter.isAtomicComponent(containerComponent)) {
522 log.debug(CANNOT_ATTACH_RESOURCE_INSTANCES_TO_CONTAINER_RESOURCE_OF_TYPE, containerComponent.assetType());
523 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType());
525 validateCanWorkOnComponent(containerComponent, userId);
526 log.debug("enter createRealComponentInstance,validateCanWorkOnComponent success");
527 if (resourceInstance != null && containerComponentType != null) {
528 log.debug("enter createRealComponentInstance,start create ComponentInstance");
529 OriginTypeEnum originType = resourceInstance.getOriginType();
530 validateInstanceName(resourceInstance);
531 if (originType == OriginTypeEnum.ServiceProxy) {
532 log.debug("enter createRealComponentInstance,originType equals ServiceProxy");
533 Either<Component, StorageOperationStatus> serviceProxyOrigin = toscaOperationFacade.getLatestByName(SERVICE_PROXY, null);
534 if (isServiceProxyOrigin(serviceProxyOrigin)) {
535 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(serviceProxyOrigin.right().value()));
537 origComponent = serviceProxyOrigin.left().value();
538 StorageOperationStatus fillProxyRes = fillInstanceData(resourceInstance, origComponent);
539 if (isFillProxyRes(fillProxyRes)) {
540 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(fillProxyRes));
543 log.debug("enter createRealComponentInstance,originType is not ServiceProxy");
544 origComponent = getAndValidateOriginComponentOfComponentInstance(containerComponent, resourceInstance);
546 validateOriginAndResourceInstanceTypes(containerComponent, origComponent, originType);
547 validateResourceInstanceState(containerComponent, origComponent);
548 overrideFields(origComponent, resourceInstance);
549 compositionBusinessLogic.validateAndSetDefaultCoordinates(resourceInstance);
550 log.debug("enter createRealComponentInstance,final validate success");
552 return createRealComponent(needLock, containerComponent, origComponent, resourceInstance, user);
553 } catch (ComponentException e) {
554 log.debug("create Real Component Instance failed");
559 private Either<ComponentInstance, ResponseFormat> createRealComponent(boolean needLock, Component containerComponent, Component origComponent,
560 ComponentInstance resourceInstance, User user) {
561 log.debug("enter createRealComponent");
562 boolean failed = false;
564 lockIfNeed(needLock, containerComponent);
565 log.debug(TRY_TO_CREATE_ENTRY_ON_GRAPH);
566 return createRealComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, user);
567 } catch (ComponentException e) {
572 unlockComponent(failed, containerComponent);
577 private Either<ComponentInstance, ResponseFormat> createRealComponentInstanceOnGraph(org.openecomp.sdc.be.model.Component containerComponent,
578 Component originComponent,
579 ComponentInstance componentInstance, User user) {
580 log.debug("enter createRealComponentInstanceOnGraph");
581 Either<ImmutablePair<Component, String>, StorageOperationStatus> result = toscaOperationFacade
582 .addComponentInstanceToTopologyTemplate(containerComponent, originComponent, componentInstance, false, user);
583 if (result.isRight()) {
584 log.debug("enter createRealComponentInstanceOnGraph,result is right");
585 ActionStatus status = componentsUtils.convertFromStorageResponse(result.right().value());
586 log.debug(FAILED_TO_CREATE_ENTRY_ON_GRAPH_FOR_COMPONENT_INSTANCE, componentInstance.getName());
587 return Either.right(componentsUtils.getResponseFormat(status));
589 log.debug(ENTITY_ON_GRAPH_IS_CREATED);
590 log.debug("enter createRealComponentInstanceOnGraph,Entity on graph is created.");
591 Component updatedComponent = result.left().value().getLeft();
592 Map<String, String> existingEnvVersions = new HashMap<>();
593 // TODO existingEnvVersions ??
594 addComponentInstanceArtifacts(updatedComponent, componentInstance, originComponent, user, existingEnvVersions);
595 Optional<ComponentInstance> updatedInstanceOptional = updatedComponent.getComponentInstances().stream()
596 .filter(ci -> ci.getUniqueId().equals(result.left().value().getRight())).findFirst();
597 if (!updatedInstanceOptional.isPresent()) {
598 log.debug("Failed to fetch new added component instance {} from component {}", componentInstance.getName(), containerComponent.getName());
599 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName());
601 log.debug("enter createRealComponentInstanceOnGraph,and final success");
602 return Either.left(updatedInstanceOptional.get());
605 private void overrideFields(Component origComponent, ComponentInstance resourceInstance) {
606 resourceInstance.setComponentVersion(origComponent.getVersion());
607 resourceInstance.setIcon(origComponent.getIcon());
610 private void validateInstanceName(ComponentInstance resourceInstance) {
611 String resourceInstanceName = resourceInstance.getName();
612 if (StringUtils.isEmpty(resourceInstanceName)) {
613 log.debug("ComponentInstance name is empty");
614 throw new ByActionStatusComponentException(ActionStatus.INVALID_COMPONENT_NAME, resourceInstance.getName());
616 if (!ValidationUtils.validateComponentNameLength(resourceInstanceName)) {
617 log.debug("ComponentInstance name exceeds max length {} ", ValidationUtils.COMPONENT_NAME_MAX_LENGTH);
618 throw new ByActionStatusComponentException(ActionStatus.INVALID_COMPONENT_NAME, resourceInstance.getName());
620 if (!ValidationUtils.validateComponentNamePattern(resourceInstanceName)) {
621 log.debug("ComponentInstance name {} has invalid format", resourceInstanceName);
622 throw new ByActionStatusComponentException(ActionStatus.INVALID_COMPONENT_NAME, resourceInstance.getName());
626 private void validateResourceInstanceState(Component containerComponent, Component origComponent) {
627 if (origComponent.getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) {
628 throw new ByActionStatusComponentException(ActionStatus.CONTAINER_CANNOT_CONTAIN_INSTANCE,
629 containerComponent.getComponentType().getValue(), origComponent.getLifecycleState().toString());
633 private void validateOriginAndResourceInstanceTypes(final Component containerComponent, final Component origComponent,
634 final OriginTypeEnum originType) {
635 final ResourceTypeEnum resourceType = getResourceTypeEnumFromOriginComponent(origComponent);
636 validateOriginType(originType, resourceType);
637 validateOriginComponentIsValidForContainer(containerComponent, resourceType);
640 private void validateOriginComponentIsValidForContainer(Component containerComponent, ResourceTypeEnum resourceType) {
641 switch (containerComponent.getComponentType()) {
643 if (!containerInstanceTypesData.isAllowedForServiceComponent(resourceType, containerComponent.getModel())) {
644 throw new ByActionStatusComponentException(ActionStatus.CONTAINER_CANNOT_CONTAIN_INSTANCE,
645 containerComponent.getComponentType().toString(), resourceType.name());
649 final ResourceTypeEnum componentResourceType = ((Resource) containerComponent).getResourceType();
650 if (!containerInstanceTypesData.isAllowedForResourceComponent(componentResourceType, resourceType)) {
651 throw new ByActionStatusComponentException(ActionStatus.CONTAINER_CANNOT_CONTAIN_INSTANCE,
652 containerComponent.getComponentType().toString(), resourceType.name());
656 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
660 private void validateOriginType(OriginTypeEnum originType, ResourceTypeEnum resourceType) {
661 ResourceTypeEnum convertedOriginType;
663 convertedOriginType = ResourceTypeEnum.getTypeIgnoreCase(originType.name());
664 } catch (Exception e) {
665 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
667 if (resourceType != convertedOriginType) {
668 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
672 private ResourceTypeEnum getResourceTypeEnumFromOriginComponent(final Component origComponent) {
673 switch (origComponent.getComponentType()) {
675 return ResourceTypeEnum.ServiceProxy;
677 return ((Resource) origComponent).getResourceType();
679 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
683 private void lockIfNeed(boolean needLock, Component containerComponent) {
685 lockComponent(containerComponent, "createComponentInstance");
689 private boolean isServiceProxyOrigin(Either<Component, StorageOperationStatus> serviceProxyOrigin) {
690 if (serviceProxyOrigin.isRight()) {
691 log.debug("Failed to fetch normative service proxy resource by tosca name, error {}", serviceProxyOrigin.right().value());
697 private StorageOperationStatus fillInstanceData(ComponentInstance resourceInstance, Component origComponent) {
698 final ComponentParametersView filter = new ComponentParametersView(true);
699 filter.setIgnoreCapabilities(false);
700 filter.setIgnoreCapabiltyProperties(false);
701 filter.setIgnoreComponentInstances(false);
702 filter.setIgnoreRequirements(false);
703 filter.setIgnoreInterfaces(false);
704 filter.setIgnoreProperties(false);
705 filter.setIgnoreAttributes(false);
706 filter.setIgnoreInputs(false);
707 Either<Component, StorageOperationStatus> serviceRes = toscaOperationFacade.getToscaElement(resourceInstance.getComponentUid(), filter);
708 if (serviceRes.isRight()) {
709 return serviceRes.right().value();
711 final Component service = serviceRes.left().value();
712 final Map<String, List<CapabilityDefinition>> capabilities = service.getCapabilities();
713 resourceInstance.setCapabilities(capabilities);
714 final Map<String, List<RequirementDefinition>> req = service.getRequirements();
715 resourceInstance.setRequirements(req);
716 final Map<String, InterfaceDefinition> serviceInterfaces = service.getInterfaces();
717 if (MapUtils.isNotEmpty(serviceInterfaces)) {
718 serviceInterfaces.forEach(resourceInstance::addInterface);
720 resourceInstance.setProperties(PropertiesUtils.getProperties(service));
721 resourceInstance.setAttributes(service.getAttributes());
722 final List<InputDefinition> serviceInputs = service.getInputs();
723 resourceInstance.setInputs(serviceInputs);
724 resourceInstance.setSourceModelInvariant(service.getInvariantUUID());
725 resourceInstance.setSourceModelName(service.getName());
726 resourceInstance.setSourceModelUuid(service.getUUID());
727 resourceInstance.setSourceModelUid(service.getUniqueId());
728 resourceInstance.setComponentUid(origComponent.getUniqueId());
729 resourceInstance.setComponentVersion(service.getVersion());
730 switch (resourceInstance.getOriginType()) {
732 return fillProxyInstanceData(resourceInstance, origComponent, service);
733 case ServiceSubstitution:
734 return fillServiceSubstitutableNodeTypeData(resourceInstance, service);
736 return StorageOperationStatus.OK;
740 private StorageOperationStatus fillProxyInstanceData(final ComponentInstance resourceInstance, final Component origComponent,
741 final Component service) {
742 final String name = ValidationUtils.normalizeComponentInstanceName(service.getName()) + ToscaOperationFacade.PROXY_SUFFIX;
743 final String toscaResourceName = ((Resource) origComponent).getToscaResourceName();
744 final int lastIndexOf = toscaResourceName.lastIndexOf('.');
745 if (lastIndexOf != -1) {
746 final String proxyToscaName = toscaResourceName.substring(0, lastIndexOf + 1) + name;
747 resourceInstance.setToscaComponentName(proxyToscaName);
749 resourceInstance.setName(name);
750 resourceInstance.setIsProxy(true);
751 resourceInstance.setDescription("A Proxy for Service " + service.getName());
752 return StorageOperationStatus.OK;
755 private StorageOperationStatus fillServiceSubstitutableNodeTypeData(final ComponentInstance resourceInstance, final Component service) {
756 resourceInstance.setToscaComponentName("org.openecomp.service." + ValidationUtils.convertToSystemName(service.getName()));
757 resourceInstance.setName(ValidationUtils.normalizeComponentInstanceName(service.getName()));
758 resourceInstance.setIsProxy(false);
759 resourceInstance.setDescription("A substitutable node type for service " + service.getName());
760 return StorageOperationStatus.OK;
763 public Either<CreateAndAssotiateInfo, ResponseFormat> createAndAssociateRIToRI(String containerComponentParam, String containerComponentId,
764 String userId, CreateAndAssotiateInfo createAndAssotiateInfo) {
765 Either<CreateAndAssotiateInfo, ResponseFormat> resultOp = null;
766 ComponentInstance resourceInstance = createAndAssotiateInfo.getNode();
767 RequirementCapabilityRelDef associationInfo = createAndAssotiateInfo.getAssociate();
768 User user = validateUserExists(userId);
769 final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
770 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, null);
771 if (ModelConverter.isAtomicComponent(containerComponent)) {
772 log.debug(CANNOT_ATTACH_RESOURCE_INSTANCES_TO_CONTAINER_RESOURCE_OF_TYPE, containerComponent.assetType());
774 .right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType()));
776 validateCanWorkOnComponent(containerComponent, userId);
777 boolean failed = false;
779 lockComponent(containerComponent, "createAndAssociateRIToRI");
780 log.debug(TRY_TO_CREATE_ENTRY_ON_GRAPH);
781 Component origComponent = getOriginComponentFromComponentInstance(resourceInstance);
782 log.debug(ENTITY_ON_GRAPH_IS_CREATED);
783 ComponentInstance resResourceInfo = createComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, user);
784 if (associationInfo.getFromNode() == null || associationInfo.getFromNode().isEmpty()) {
785 associationInfo.setFromNode(resResourceInfo.getUniqueId());
787 associationInfo.setToNode(resResourceInfo.getUniqueId());
789 Either<RequirementCapabilityRelDef, StorageOperationStatus> resultReqCapDef = toscaOperationFacade
790 .associateResourceInstances(containerComponent, containerComponentId, associationInfo);
791 if (resultReqCapDef.isLeft()) {
792 log.debug(ENTITY_ON_GRAPH_IS_CREATED);
793 RequirementCapabilityRelDef resReqCapabilityRelDef = resultReqCapDef.left().value();
794 CreateAndAssotiateInfo resInfo = new CreateAndAssotiateInfo(resResourceInfo, resReqCapabilityRelDef);
795 resultOp = Either.left(resInfo);
798 log.info("Failed to associate node {} with node {}", associationInfo.getFromNode(), associationInfo.getToNode());
799 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(
800 componentsUtils.convertFromStorageResponseForResourceInstance(resultReqCapDef.right().value(), true), "", null));
803 } catch (ComponentException e) {
807 unlockComponent(failed, containerComponent);
811 private Component getOriginComponentFromComponentInstance(ComponentInstance componentInstance) {
812 return getOriginComponentFromComponentInstance(componentInstance.getName(), componentInstance.getComponentUid());
815 private Component getInstanceOriginNode(ComponentInstance componentInstance) {
816 return getOriginComponentFromComponentInstance(componentInstance.getName(), componentInstance.getActualComponentUid());
819 private Component getOriginComponentFromComponentInstance(String componentInstanceName, String origComponetId) {
820 Either<Component, StorageOperationStatus> eitherComponent = toscaOperationFacade.getToscaFullElement(origComponetId);
821 if (eitherComponent.isRight()) {
822 log.debug("Failed to get origin component with id {} for component instance {} ", origComponetId, componentInstanceName);
823 throw new ByActionStatusComponentException(
824 componentsUtils.convertFromStorageResponse(eitherComponent.right().value(), ComponentTypeEnum.RESOURCE), "", null);
826 return eitherComponent.left().value();
829 private ComponentInstance createComponentInstanceOnGraph(org.openecomp.sdc.be.model.Component containerComponent, Component originComponent,
830 ComponentInstance componentInstance, User user) {
831 Either<ImmutablePair<Component, String>, StorageOperationStatus> result = toscaOperationFacade
832 .addComponentInstanceToTopologyTemplate(containerComponent, originComponent, componentInstance, false, user);
833 if (result.isRight()) {
834 log.debug(FAILED_TO_CREATE_ENTRY_ON_GRAPH_FOR_COMPONENT_INSTANCE, componentInstance.getName());
835 throw new ByResponseFormatComponentException(componentsUtils
836 .getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), "",
839 log.debug(ENTITY_ON_GRAPH_IS_CREATED);
840 Component updatedComponent = result.left().value().getLeft();
841 Map<String, String> existingEnvVersions = new HashMap<>();
842 // TODO existingEnvVersions ??
843 addComponentInstanceArtifacts(updatedComponent, componentInstance, originComponent, user, existingEnvVersions);
844 Optional<ComponentInstance> updatedInstanceOptional = updatedComponent.getComponentInstances().stream()
845 .filter(ci -> ci.getUniqueId().equals(result.left().value().getRight())).findFirst();
846 if (!updatedInstanceOptional.isPresent()) {
847 log.debug("Failed to fetch new added component instance {} from component {}", componentInstance.getName(), containerComponent.getName());
848 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName());
850 return updatedInstanceOptional.get();
853 public boolean isCloudSpecificArtifact(String artifact) {
854 if (artifact.contains(CLOUD_SPECIFIC_FIXED_KEY_WORD)) {
855 for (int i = 0; i < CLOUD_SPECIFIC_KEY_WORDS.length; i++) {
856 if (Arrays.stream(CLOUD_SPECIFIC_KEY_WORDS[i]).noneMatch(artifact::contains)) {
867 * addResourceInstanceArtifacts - add artifacts (HEAT_ENV) to resource instance The instance artifacts are generated from the resource's
870 * @param containerComponent
871 * @param componentInstance
872 * @param originComponent
874 * @param existingEnvVersions
877 protected ActionStatus addComponentInstanceArtifacts(org.openecomp.sdc.be.model.Component containerComponent, ComponentInstance componentInstance,
878 org.openecomp.sdc.be.model.Component originComponent, User user,
879 Map<String, String> existingEnvVersions) {
880 log.debug("add artifacts to resource instance");
881 List<GroupDefinition> filteredGroups = new ArrayList<>();
882 ActionStatus status = setResourceArtifactsOnResourceInstance(componentInstance);
883 if (ActionStatus.OK != status) {
884 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormatForResourceInstance(status, "", null));
886 StorageOperationStatus artStatus;
887 // generate heat_env if necessary
888 Map<String, ArtifactDefinition> componentDeploymentArtifacts = componentInstance.getDeploymentArtifacts();
889 if (MapUtils.isNotEmpty(componentDeploymentArtifacts)) {
890 Map<String, ArtifactDefinition> finalDeploymentArtifacts = new HashMap<>();
891 Map<String, List<ArtifactDefinition>> groupInstancesArtifacts = new HashMap<>();
892 Integer defaultHeatTimeout = ConfigurationManager.getConfigurationManager().getConfiguration().getHeatArtifactDeploymentTimeout()
893 .getDefaultMinutes();
894 List<ArtifactDefinition> listOfCloudSpecificArts = new ArrayList<>();
895 for (ArtifactDefinition artifact : componentDeploymentArtifacts.values()) {
896 String type = artifact.getArtifactType();
897 if (!type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType())) {
898 finalDeploymentArtifacts.put(artifact.getArtifactLabel(), artifact);
900 if (type.equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HELM.getType()) || type
901 .equalsIgnoreCase(ArtifactTypeEnum.HEAT_NET.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType()) || type
902 .equalsIgnoreCase(ArtifactTypeEnum.CLOUD_TECHNOLOGY_SPECIFIC_ARTIFACT.getType())) {
903 artifact.setTimeout(defaultHeatTimeout);
907 if (artifact.checkEsIdExist()) {
908 ArtifactDefinition artifactDefinition = artifactBusinessLogic
909 .createHeatEnvPlaceHolder(new ArrayList<>(), artifact, ArtifactsBusinessLogic.HEAT_ENV_NAME, componentInstance.getUniqueId(),
910 NodeTypeEnum.ResourceInstance, componentInstance.getName(), user, containerComponent, existingEnvVersions);
912 finalDeploymentArtifacts.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
913 if (CollectionUtils.isNotEmpty(originComponent.getGroups())) {
914 filteredGroups = originComponent.getGroups().stream().filter(g -> g.getType().equals(VF_MODULE)).collect(Collectors.toList());
916 if (isCloudSpecificArtifact(artifactDefinition.getArtifactName())) {
917 listOfCloudSpecificArts.add(artifact);
919 if (CollectionUtils.isNotEmpty(filteredGroups)) {
920 filteredGroups.stream()
921 .filter(g -> g.getArtifacts() != null && g.getArtifacts().stream().anyMatch(p -> p.equals(artifactDefinition.getGeneratedFromId()))).findFirst()
922 .ifPresent(g -> fillInstanceArtifactMap(groupInstancesArtifacts, artifactDefinition, g));
926 groupInstancesArtifacts.forEach((k, v) -> v.addAll(listOfCloudSpecificArts));
927 filteredGroups.forEach(g -> listOfCloudSpecificArts.forEach(e -> {
928 g.getArtifactsUuid().add(e.getArtifactUUID());
929 g.getArtifacts().add(e.getUniqueId());
931 artStatus = toscaOperationFacade
932 .addDeploymentArtifactsToInstance(containerComponent.getUniqueId(), componentInstance, finalDeploymentArtifacts);
933 if (artStatus != StorageOperationStatus.OK) {
934 log.debug("Failed to add instance deployment artifacts for instance {} in conatiner {} error {}", componentInstance.getUniqueId(),
935 containerComponent.getUniqueId(), artStatus);
936 throw new ByResponseFormatComponentException(
937 componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(artStatus, false)));
939 StorageOperationStatus result = toscaOperationFacade
940 .addGroupInstancesToComponentInstance(containerComponent, componentInstance, filteredGroups, groupInstancesArtifacts);
941 if (result != StorageOperationStatus.OK) {
942 log.debug("failed to update group instance for component instance {}", componentInstance.getUniqueId());
943 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(result)));
945 componentInstance.setDeploymentArtifacts(finalDeploymentArtifacts);
947 artStatus = toscaOperationFacade
948 .addInformationalArtifactsToInstance(containerComponent.getUniqueId(), componentInstance, originComponent.getArtifacts());
949 if (artStatus != StorageOperationStatus.OK) {
950 log.debug("Failed to add informational artifacts to the instance {} belonging to the conatiner {}. Status is {}",
951 componentInstance.getUniqueId(), containerComponent.getUniqueId(), artStatus);
952 throw new ByResponseFormatComponentException(
953 componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(artStatus, false)));
955 componentInstance.setArtifacts(originComponent.getArtifacts());
956 return ActionStatus.OK;
959 private void fillInstanceArtifactMap(Map<String, List<ArtifactDefinition>> groupInstancesArtifacts, ArtifactDefinition artifactDefinition,
960 GroupDefinition groupInstance) {
961 List<ArtifactDefinition> artifactsUid;
962 if (groupInstancesArtifacts.containsKey(groupInstance.getUniqueId())) {
963 artifactsUid = groupInstancesArtifacts.get(groupInstance.getUniqueId());
965 artifactsUid = new ArrayList<>();
967 artifactsUid.add(artifactDefinition);
968 groupInstancesArtifacts.put(groupInstance.getUniqueId(), artifactsUid);
971 private ActionStatus setResourceArtifactsOnResourceInstance(ComponentInstance resourceInstance) {
972 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getResourceDeploymentArtifacts = artifactBusinessLogic
973 .getArtifacts(resourceInstance.getComponentUid(), NodeTypeEnum.Resource, ArtifactGroupTypeEnum.DEPLOYMENT, null);
974 Map<String, ArtifactDefinition> deploymentArtifacts = new HashMap<>();
975 if (getResourceDeploymentArtifacts.isRight()) {
976 StorageOperationStatus status = getResourceDeploymentArtifacts.right().value();
977 if (status != StorageOperationStatus.NOT_FOUND) {
978 log.debug("Failed to fetch resource: {} artifacts. status is {}", resourceInstance.getComponentUid(), status);
979 return componentsUtils.convertFromStorageResponseForResourceInstance(status, true);
982 deploymentArtifacts = getResourceDeploymentArtifacts.left().value();
984 if (!deploymentArtifacts.isEmpty()) {
985 Map<String, ArtifactDefinition> tempDeploymentArtifacts = new HashMap<>(deploymentArtifacts);
986 for (Entry<String, ArtifactDefinition> artifact : deploymentArtifacts.entrySet()) {
987 if (!artifact.getValue().checkEsIdExist()) {
988 tempDeploymentArtifacts.remove(artifact.getKey());
991 resourceInstance.setDeploymentArtifacts(tempDeploymentArtifacts);
993 return ActionStatus.OK;
996 public Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(String containerComponentParam, String containerComponentId,
997 String componentInstanceId, String userId,
998 ComponentInstance componentInstance) {
999 return updateComponentInstanceMetadata(containerComponentParam, containerComponentId, componentInstanceId, userId, componentInstance, true);
1002 public Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(final String containerComponentParam,
1003 final String containerComponentId,
1004 final String componentInstanceId, final String userId,
1005 ComponentInstance componentInstance, boolean needLock) {
1006 validateUserExists(userId);
1007 final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
1008 final Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, null);
1009 validateCanWorkOnComponent(containerComponent, userId);
1010 ComponentTypeEnum instanceType = getComponentType(containerComponentType);
1011 Either<Boolean, StorageOperationStatus> validateParentStatus = toscaOperationFacade
1012 .validateComponentExists(componentInstance.getComponentUid());
1013 if (validateParentStatus.isRight()) {
1014 log.debug("Failed to get component instance {} on service {}", componentInstanceId, containerComponentId);
1015 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND, componentInstance.getName(),
1016 instanceType.getValue().toLowerCase());
1018 if (!Boolean.TRUE.equals(validateParentStatus.left().value())) {
1019 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName(),
1020 instanceType.getValue().toLowerCase(), containerComponentType.getValue().toLowerCase(), containerComponentId);
1023 lockComponent(containerComponent, "updateComponentInstance");
1025 Component origComponent;
1026 boolean failed = false;
1028 origComponent = getOriginComponentFromComponentInstance(componentInstance);
1029 componentInstance = updateComponentInstanceMetadata(containerComponent, containerComponentType, origComponent, componentInstanceId,
1031 } catch (ComponentException e) {
1036 unlockComponent(failed, containerComponent);
1039 return Either.left(componentInstance);
1042 // New Multiple Instance Update API
1043 public List<ComponentInstance> updateComponentInstance(String containerComponentParam, Component containerComponent, String containerComponentId,
1044 String userId, List<ComponentInstance> componentInstanceList, boolean needLock) {
1045 boolean failed = false;
1047 validateUserExists(userId);
1048 final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
1049 ComponentParametersView componentFilter = new ComponentParametersView();
1050 componentFilter.disableAll();
1051 componentFilter.setIgnoreUsers(false);
1052 componentFilter.setIgnoreComponentInstances(false);
1053 if (containerComponent == null) {
1054 containerComponent = validateComponentExistsByFilter(containerComponentId, containerComponentType, componentFilter);
1056 validateCanWorkOnComponent(containerComponent, userId);
1057 ComponentTypeEnum instanceType = getComponentType(containerComponentType);
1058 for (ComponentInstance componentInstance : componentInstanceList) {
1059 boolean validateParent = validateParent(containerComponent, componentInstance.getUniqueId());
1060 if (!validateParent) {
1061 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName(),
1062 instanceType.getValue().toLowerCase(), containerComponentType.getValue().toLowerCase(), containerComponentId);
1066 lockComponent(containerComponent, "updateComponentInstance");
1068 List<ComponentInstance> updatedList = new ArrayList<>();
1069 List<ComponentInstance> instancesFromContainerComponent = containerComponent.getComponentInstances();
1070 List<ComponentInstance> listForUpdate = new ArrayList<>();
1071 if (instancesFromContainerComponent == null || instancesFromContainerComponent.isEmpty()) {
1072 containerComponent.setComponentInstances(componentInstanceList);
1074 Iterator<ComponentInstance> iterator = instancesFromContainerComponent.iterator();
1075 while (iterator.hasNext()) {
1076 ComponentInstance origInst = iterator.next();
1077 Optional<ComponentInstance> op = componentInstanceList.stream().filter(ci -> ci.getUniqueId().equals(origInst.getUniqueId()))
1079 if (op.isPresent()) {
1080 ComponentInstance updatedCi = op.get();
1081 updatedCi = buildComponentInstance(updatedCi, origInst);
1082 Boolean isUniqueName = validateInstanceNameUniquenessUponUpdate(containerComponent, origInst, updatedCi.getName());
1083 if (!Boolean.TRUE.equals(isUniqueName)) {
1084 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
1085 "Failed to update the name of the component instance {} to {}. A component instance with the same name already exists. ",
1086 origInst.getName(), updatedCi.getName());
1087 throw new ByResponseFormatComponentException(componentsUtils
1088 .getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(), origInst.getName()));
1090 listForUpdate.add(updatedCi);
1092 listForUpdate.add(origInst);
1095 containerComponent.setComponentInstances(listForUpdate);
1096 Either<Component, StorageOperationStatus> updateStatus = toscaOperationFacade
1097 .updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, componentFilter);
1098 if (updateStatus.isRight()) {
1100 .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update metadata belonging to container component {}. Status is {}. ",
1101 containerComponent.getName(), updateStatus.right().value());
1102 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormatForResourceInstance(
1103 componentsUtils.convertFromStorageResponseForResourceInstance(updateStatus.right().value(), true), "", null));
1105 for (ComponentInstance updatedInstance : updateStatus.left().value().getComponentInstances()) {
1106 Optional<ComponentInstance> op = componentInstanceList.stream().filter(ci -> ci.getName().equals(updatedInstance.getName()))
1108 if (op.isPresent()) {
1109 updatedList.add(updatedInstance);
1114 } catch (ComponentException e) {
1119 unlockComponent(failed, containerComponent);
1124 private boolean validateParent(org.openecomp.sdc.be.model.Component containerComponent, String nodeTemplateId) {
1125 return containerComponent.getComponentInstances().stream().anyMatch(p -> p.getUniqueId().equals(nodeTemplateId));
1128 private ComponentTypeEnum getComponentType(ComponentTypeEnum containerComponentType) {
1129 if (ComponentTypeEnum.PRODUCT == containerComponentType) {
1130 return ComponentTypeEnum.SERVICE_INSTANCE;
1132 return ComponentTypeEnum.RESOURCE_INSTANCE;
1136 private ComponentInstance updateComponentInstanceMetadata(Component containerComponent, ComponentTypeEnum containerComponentType,
1137 org.openecomp.sdc.be.model.Component origComponent, String componentInstanceId,
1138 ComponentInstance componentInstance) {
1139 Optional<ComponentInstance> componentInstanceOptional;
1140 Either<ImmutablePair<Component, String>, StorageOperationStatus> updateRes = null;
1141 ComponentInstance oldComponentInstance = null;
1142 boolean isNameChanged = false;
1143 componentInstanceOptional = containerComponent.getComponentInstances().stream()
1144 .filter(ci -> ci.getUniqueId().equals(componentInstance.getUniqueId())).findFirst();
1145 if (!componentInstanceOptional.isPresent()) {
1146 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find the component instance {} in container component {}. ",
1147 componentInstance.getName(), containerComponent.getName());
1148 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName());
1150 String oldComponentName;
1151 oldComponentInstance = componentInstanceOptional.get();
1152 oldComponentName = oldComponentInstance.getName();
1153 String newInstanceName = componentInstance.getName();
1154 if (oldComponentName != null && !oldComponentInstance.getName().equals(newInstanceName)) {
1155 isNameChanged = true;
1157 Boolean isUniqueName = validateInstanceNameUniquenessUponUpdate(containerComponent, oldComponentInstance, newInstanceName);
1158 if (!Boolean.TRUE.equals(isUniqueName)) {
1159 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
1160 "Failed to update the name of the component instance {} to {}. A component instance with the same name already exists. ",
1161 oldComponentInstance.getName(), newInstanceName);
1162 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(),
1163 componentInstance.getName());
1165 if (!DirectivesUtil.isValid(componentInstance.getDirectives())) {
1166 final String directivesStr = componentInstance.getDirectives().stream().collect(Collectors.joining(" , ", " [ ", " ] "));
1167 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
1168 "Failed to update the directives of the component instance {} to {}. Directives data {} is invalid. ", oldComponentInstance.getName(),
1169 newInstanceName, directivesStr);
1170 throw new ByActionStatusComponentException(ActionStatus.DIRECTIVES_INVALID_VALUE, containerComponentType.getValue(),
1171 componentInstance.getName());
1173 updateRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, origComponent,
1174 updateComponentInstanceMetadata(oldComponentInstance, componentInstance));
1175 if (updateRes.isRight()) {
1176 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
1177 "Failed to update metadata of component instance {} belonging to container component {}. Status is {}. ", componentInstance.getName(),
1178 containerComponent.getName(), updateRes.right().value());
1179 throw new ByResponseFormatComponentException(componentsUtils
1180 .getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(updateRes.right().value(), true),
1183 // region - Update instance Groups
1184 if (isNameChanged) {
1185 Either<StorageOperationStatus, StorageOperationStatus> result = toscaOperationFacade
1186 .cleanAndAddGroupInstancesToComponentInstance(containerComponent, oldComponentInstance, componentInstanceId);
1187 if (result.isRight()) {
1189 .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to rename group instances for container {}. error {} ", componentInstanceId,
1190 result.right().value());
1192 if (containerComponent instanceof Service) {
1193 Either<ComponentInstance, ResponseFormat> renameEither = renameServiceFilter((Service) containerComponent, newInstanceName,
1194 oldComponentInstance.getName());
1195 if (renameEither.isRight()) {
1196 throw new ByResponseFormatComponentException(renameEither.right().value());
1198 updateForwardingPathDefinition(containerComponent, componentInstance, oldComponentName);
1203 String newInstanceId = updateRes.left().value().getRight();
1204 Optional<ComponentInstance> updatedInstanceOptional = updateRes.left().value().getLeft().getComponentInstances().stream()
1205 .filter(ci -> ci.getUniqueId().equals(newInstanceId)).findFirst();
1206 if (!updatedInstanceOptional.isPresent()) {
1207 log.debug("Failed to update metadata of component instance {} of container component {}", componentInstance.getName(),
1208 containerComponent.getName());
1209 throw new ByResponseFormatComponentException(
1210 componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName()));
1212 return componentInstanceOptional.get();
1215 private void updateForwardingPathDefinition(Component containerComponent, ComponentInstance componentInstance, String oldComponentName) {
1216 Collection<ForwardingPathDataDefinition> forwardingPathDataDefinitions = getForwardingPathDataDefinitions(containerComponent.getUniqueId());
1217 Set<ForwardingPathDataDefinition> updated = new ForwardingPathUtils()
1218 .updateComponentInstanceName(forwardingPathDataDefinitions, oldComponentName, componentInstance.getName());
1219 updated.forEach(fp -> {
1220 Either<ForwardingPathDataDefinition, StorageOperationStatus> resultEither = forwardingPathOperation
1221 .updateForwardingPath(containerComponent.getUniqueId(), fp);
1222 if (resultEither.isRight()) {
1223 CommonUtility.addRecordToLog(log, LogLevelEnum.ERROR, "Failed to rename forwarding path for container {}. error {} ",
1224 containerComponent.getName(), resultEither.right().value());
1229 public Either<ComponentInstance, ResponseFormat> renameServiceFilter(final Service containerComponent, final String newInstanceName,
1230 final String oldInstanceName) {
1231 Map<String, CINodeFilterDataDefinition> renamedNodesFilter = ServiceFilterUtils
1232 .getRenamedNodesFilter(containerComponent, oldInstanceName, newInstanceName);
1233 for (Entry<String, CINodeFilterDataDefinition> entry : renamedNodesFilter.entrySet()) {
1234 Either<CINodeFilterDataDefinition, StorageOperationStatus> renameEither = nodeFilterOperation
1235 .updateNodeFilter(containerComponent.getUniqueId(), entry.getKey(), entry.getValue());
1236 if (renameEither.isRight()) {
1237 return Either.right(componentsUtils.getResponseFormatForResourceInstance(
1238 componentsUtils.convertFromStorageResponse(renameEither.right().value(), ComponentTypeEnum.SERVICE), containerComponent.getName(),
1242 return Either.left(null);
1246 * @param oldPrefix- The normalized old vf name
1247 * @param newNormailzedPrefix- The normalized new vf name
1248 * @param qualifiedGroupInstanceName- old Group Instance Name
1251 // modify group names
1252 private String getNewGroupName(String oldPrefix, String newNormailzedPrefix, String qualifiedGroupInstanceName) {
1253 if (qualifiedGroupInstanceName == null) {
1254 log.info("CANNOT change group name ");
1257 if (qualifiedGroupInstanceName.startsWith(oldPrefix) || qualifiedGroupInstanceName
1258 .startsWith(ValidationUtils.normalizeComponentInstanceName(oldPrefix))) {
1259 return qualifiedGroupInstanceName.replaceFirst(oldPrefix, newNormailzedPrefix);
1261 return qualifiedGroupInstanceName;
1264 private ComponentInstance updateComponentInstanceMetadata(ComponentInstance oldComponentInstance, ComponentInstance newComponentInstance) {
1265 oldComponentInstance.setName(newComponentInstance.getName());
1266 oldComponentInstance.setModificationTime(System.currentTimeMillis());
1267 oldComponentInstance.setCustomizationUUID(UUID.randomUUID().toString());
1268 oldComponentInstance.setDirectives(newComponentInstance.getDirectives());
1269 oldComponentInstance.setMaxOccurrences(newComponentInstance.getMaxOccurrences());
1270 oldComponentInstance.setMinOccurrences(newComponentInstance.getMinOccurrences());
1271 oldComponentInstance.setInstanceCount(newComponentInstance.getInstanceCount());
1272 if (oldComponentInstance.getGroupInstances() != null) {
1273 oldComponentInstance.getGroupInstances().forEach(group -> group.setName(getNewGroupName(oldComponentInstance.getNormalizedName(),
1274 ValidationUtils.normalizeComponentInstanceName(newComponentInstance.getName()), group.getName())));
1276 return oldComponentInstance;
1279 public ComponentInstance deleteComponentInstance(final String containerComponentParam, final String containerComponentId,
1280 final String componentInstanceId, String userId) throws BusinessLogicException {
1281 validateUserExists(userId);
1282 final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
1283 final Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, null);
1284 validateCanWorkOnComponent(containerComponent, userId);
1285 boolean failed = false;
1286 final Optional<ComponentInstance> componentInstanceOptional = containerComponent.getComponentInstanceById(componentInstanceId);
1287 if (!componentInstanceOptional.isPresent()) {
1288 throw new BusinessLogicException(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND));
1290 ComponentInstance componentInstance = componentInstanceOptional.get();
1292 if (containerComponent instanceof Service || containerComponent instanceof Resource) {
1293 final Either<String, StorageOperationStatus> deleteServiceFilterEither = nodeFilterOperation
1294 .deleteNodeFilter(containerComponent, componentInstanceId);
1295 if (deleteServiceFilterEither.isRight()) {
1296 final ActionStatus status = componentsUtils
1297 .convertFromStorageResponse(deleteServiceFilterEither.right().value(), containerComponentType);
1298 janusGraphDao.rollback();
1299 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(status, componentInstanceId));
1301 final Either<ComponentInstance, ResponseFormat> resultOp = deleteNodeFiltersFromComponentInstance(containerComponent,
1302 componentInstance, containerComponentType, userId);
1303 if (resultOp.isRight()) {
1304 janusGraphDao.rollback();
1305 throw new ByResponseFormatComponentException(resultOp.right().value());
1308 lockComponent(containerComponent, "deleteComponentInstance");
1309 final ComponentInstance deletedCompInstance = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentType);
1310 componentInstance = deleteForwardingPathsRelatedTobeDeletedComponentInstance(containerComponentId, containerComponentType,
1311 deletedCompInstance);
1312 final ActionStatus onDeleteOperationsStatus = onChangeInstanceOperationOrchestrator
1313 .doOnDeleteInstanceOperations(containerComponent, componentInstanceId);
1314 if (ActionStatus.OK != onDeleteOperationsStatus) {
1315 throw new ByActionStatusComponentException(onDeleteOperationsStatus);
1317 } catch (final ComponentException e) {
1321 unlockComponent(failed, containerComponent);
1323 return componentInstance;
1327 * Try to modify the delete and return two cases
1329 * @param containerComponentParam
1330 * @param containerComponentId
1331 * @param componentInstanceId
1335 public Either<ComponentInstance, ResponseFormat> deleteAbstractComponentInstance(String containerComponentParam, String containerComponentId,
1336 String componentInstanceId, String userId) {
1337 log.debug("enter deleteAbstractComponentInstance");
1338 validateUserExists(userId);
1339 final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
1340 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, null);
1341 validateCanWorkOnComponent(containerComponent, userId);
1342 boolean failed = false;
1343 ComponentInstance deletedRelatedInst;
1345 if (containerComponent instanceof Service) {
1346 final Optional<ComponentInstance> componentInstanceById = containerComponent.getComponentInstanceById(componentInstanceId);
1347 if (componentInstanceById.isPresent()) {
1348 ComponentInstance componentInstance = componentInstanceById.get();
1349 Either<String, StorageOperationStatus> deleteServiceFilterEither = nodeFilterOperation
1350 .deleteNodeFilter(containerComponent, componentInstanceId);
1351 if (deleteServiceFilterEither.isRight()) {
1352 log.debug("enter deleteAbstractComponentInstance:deleteServiceFilterEither is right, filed");
1353 ActionStatus status = componentsUtils
1354 .convertFromStorageResponse(deleteServiceFilterEither.right().value(), containerComponentType);
1355 janusGraphDao.rollback();
1356 return Either.right(componentsUtils.getResponseFormat(status, componentInstance.getName()));
1358 Either<ComponentInstance, ResponseFormat> resultOp = deleteNodeFiltersFromComponentInstance(containerComponent, componentInstance,
1359 ComponentTypeEnum.SERVICE, userId);
1360 if (resultOp.isRight()) {
1361 log.debug("enter deleteAbstractComponentInstance:resultOp is right, filed");
1362 janusGraphDao.rollback();
1367 log.debug("enter deleteAbstractComponentInstance:");
1368 lockComponent(containerComponent, "deleteComponentInstance");
1369 ComponentInstance deletedCompInstance = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentType);
1370 deletedRelatedInst = deleteForwardingPathsRelatedTobeDeletedComponentInstance(containerComponentId, containerComponentType,
1371 deletedCompInstance);
1372 ActionStatus onDeleteOperationsStatus = onChangeInstanceOperationOrchestrator
1373 .doOnDeleteInstanceOperations(containerComponent, componentInstanceId);
1374 log.debug("enter deleteAbstractComponentInstance,get onDeleteOperationsStatus:{}", onDeleteOperationsStatus);
1375 if (ActionStatus.OK != onDeleteOperationsStatus) {
1376 throw new ByActionStatusComponentException(onDeleteOperationsStatus);
1378 } catch (ComponentException e) {
1382 unlockComponent(failed, containerComponent);
1384 log.debug("enter deleteAbstractComponentInstance,deleted RelatedInst success");
1385 return Either.left(deletedRelatedInst);
1388 public Either<ComponentInstance, ResponseFormat> deleteNodeFiltersFromComponentInstance(final Component component,
1389 final ComponentInstance componentInstance,
1390 final ComponentTypeEnum containerComponentType,
1391 final String userId) {
1392 final Set<String> componentFiltersIDsToBeDeleted = getComponentFiltersRelatedToComponentInstance(component.getUniqueId(), componentInstance);
1393 if (!componentFiltersIDsToBeDeleted.isEmpty()) {
1394 final Set<String> ids = component.getComponentInstances().stream().filter(ci -> componentFiltersIDsToBeDeleted.contains(ci.getName()))
1395 .map(ComponentInstance::getUniqueId).collect(Collectors.toSet());
1396 final Either<Set<String>, StorageOperationStatus> deleteComponentNodeFiltersEither = nodeFilterOperation
1397 .deleteNodeFilters(component, ids);
1398 if (deleteComponentNodeFiltersEither.isRight()) {
1399 final ActionStatus status = componentsUtils
1400 .convertFromStorageResponse(deleteComponentNodeFiltersEither.right().value(), containerComponentType);
1401 return Either.right(componentsUtils.getResponseFormat(status, componentInstance.getName()));
1403 for (final String id : ids) {
1404 final Optional<ComponentInstance> componentInstanceById = component.getComponentInstanceById(id);
1405 if (!componentInstanceById.isPresent()) {
1406 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
1408 final ComponentInstance componentInstanceToBeUpdated = componentInstanceById.get();
1409 componentInstanceToBeUpdated.setDirectives(Collections.emptyList());
1410 final Either<ComponentInstance, ResponseFormat> componentInstanceResponseFormatEither = updateComponentInstanceMetadata(
1411 containerComponentType.getValue(), component.getUniqueId(), componentInstanceToBeUpdated.getUniqueId(), userId,
1412 componentInstanceToBeUpdated, false);
1413 if (componentInstanceResponseFormatEither.isRight()) {
1414 return componentInstanceResponseFormatEither;
1418 return Either.left(componentInstance);
1421 private Set<String> getComponentFiltersRelatedToComponentInstance(String containerComponentId, ComponentInstance componentInstance) {
1422 ComponentParametersView filter = new ComponentParametersView(true);
1423 filter.setIgnoreComponentInstances(false);
1424 Either<Component, StorageOperationStatus> componentFilterOrigin = toscaOperationFacade.getToscaElement(containerComponentId, filter);
1425 final Component component = componentFilterOrigin.left().value();
1426 return ComponentsUtils.getNodesFiltersToBeDeleted(component, componentInstance);
1429 ComponentInstance deleteForwardingPathsRelatedTobeDeletedComponentInstance(String containerComponentId, ComponentTypeEnum containerComponentType,
1430 ComponentInstance componentInstance) {
1431 if (containerComponentType == ComponentTypeEnum.SERVICE) {
1432 List<String> pathIDsToBeDeleted = getForwardingPathsRelatedToComponentInstance(containerComponentId, componentInstance.getName());
1433 if (!pathIDsToBeDeleted.isEmpty()) {
1434 deleteForwardingPaths(containerComponentId, pathIDsToBeDeleted);
1437 return componentInstance;
1440 private void deleteForwardingPaths(String serviceId, List<String> pathIdsToDelete) {
1441 Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(serviceId);
1442 if (storageStatus.isRight()) {
1443 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(storageStatus.right().value()));
1445 Either<Set<String>, StorageOperationStatus> result = forwardingPathOperation
1446 .deleteForwardingPath(storageStatus.left().value(), Sets.newHashSet(pathIdsToDelete));
1447 if (result.isRight()) {
1448 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(result.right().value()));
1452 private List<String> getForwardingPathsRelatedToComponentInstance(String containerComponentId, String componentInstanceId) {
1453 Collection<ForwardingPathDataDefinition> allPaths = getForwardingPathDataDefinitions(containerComponentId);
1454 List<String> pathIDsToBeDeleted = new ArrayList<>();
1455 allPaths.stream().filter(path -> isPathRelatedToComponent(path, componentInstanceId))
1456 .forEach(path -> pathIDsToBeDeleted.add(path.getUniqueId()));
1457 return pathIDsToBeDeleted;
1460 private Collection<ForwardingPathDataDefinition> getForwardingPathDataDefinitions(String containerComponentId) {
1461 ComponentParametersView filter = new ComponentParametersView(true);
1462 filter.setIgnoreServicePath(false);
1463 Either<Service, StorageOperationStatus> forwardingPathOrigin = toscaOperationFacade.getToscaElement(containerComponentId, filter);
1464 return forwardingPathOrigin.left().value().getForwardingPaths().values();
1467 private boolean isPathRelatedToComponent(ForwardingPathDataDefinition pathDataDefinition, String componentInstanceId) {
1468 return pathDataDefinition.getPathElements().getListToscaDataDefinition().stream().anyMatch(
1469 elementDataDefinition -> elementDataDefinition.getFromNode().equalsIgnoreCase(componentInstanceId) || elementDataDefinition.getToNode()
1470 .equalsIgnoreCase(componentInstanceId));
1473 private ComponentInstance deleteComponentInstance(Component containerComponent, String componentInstanceId,
1474 ComponentTypeEnum containerComponentType) {
1475 Either<ImmutablePair<Component, String>, StorageOperationStatus> deleteRes = toscaOperationFacade
1476 .deleteComponentInstanceFromTopologyTemplate(containerComponent, componentInstanceId);
1477 if (deleteRes.isRight()) {
1478 log.debug("Failed to delete entry on graph for resourceInstance {}", componentInstanceId);
1479 ActionStatus status = componentsUtils.convertFromStorageResponse(deleteRes.right().value(), containerComponentType);
1480 throw new ByActionStatusComponentException(status, componentInstanceId);
1482 log.debug("The component instance {} has been removed from container component {}. ", componentInstanceId, containerComponent);
1483 ComponentInstance deletedInstance = findAndRemoveComponentInstanceFromContainerComponent(componentInstanceId, containerComponent);
1484 if (CollectionUtils.isNotEmpty(containerComponent.getInputs())) {
1485 List<InputDefinition> inputsToDelete = containerComponent.getInputs().stream()
1486 .filter(i -> i.getInstanceUniqueId() != null && i.getInstanceUniqueId().equals(componentInstanceId)).collect(Collectors.toList());
1487 if (CollectionUtils.isNotEmpty(inputsToDelete)) {
1488 StorageOperationStatus deleteInputsRes = toscaOperationFacade
1489 .deleteComponentInstanceInputsFromTopologyTemplate(containerComponent, inputsToDelete);
1490 if (deleteInputsRes != StorageOperationStatus.OK) {
1491 log.debug("Failed to delete inputs of the component instance {} from container component. ", componentInstanceId);
1492 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(deleteInputsRes, containerComponentType),
1493 componentInstanceId);
1497 if (CollectionUtils.isNotEmpty(containerComponent.getOutputs())) {
1498 final List<OutputDefinition> outputsToDelete = containerComponent.getOutputs().stream()
1499 .filter(i -> i.getInstanceUniqueId() != null && i.getInstanceUniqueId().equals(componentInstanceId)).collect(Collectors.toList());
1500 if (CollectionUtils.isNotEmpty(outputsToDelete)) {
1501 final StorageOperationStatus deleteOutputsRes = toscaOperationFacade
1502 .deleteComponentInstanceOutputsFromTopologyTemplate(containerComponent, outputsToDelete);
1503 if (deleteOutputsRes != StorageOperationStatus.OK) {
1504 log.debug("Failed to delete outputs of the component instance {} from container component. ", componentInstanceId);
1505 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(deleteOutputsRes, containerComponentType),
1506 componentInstanceId);
1510 return deletedInstance;
1513 private ComponentInstance findAndRemoveComponentInstanceFromContainerComponent(String componentInstanceId, Component containerComponent) {
1514 ComponentInstance foundInstance = null;
1515 for (ComponentInstance instance : containerComponent.getComponentInstances()) {
1516 if (instance.getUniqueId().equals(componentInstanceId)) {
1517 foundInstance = instance;
1518 containerComponent.getComponentInstances().remove(instance);
1522 findAndRemoveComponentInstanceRelations(componentInstanceId, containerComponent);
1523 return foundInstance;
1526 private void findAndRemoveComponentInstanceRelations(String componentInstanceId, Component containerComponent) {
1527 if (CollectionUtils.isNotEmpty(containerComponent.getComponentInstancesRelations())) {
1528 containerComponent.setComponentInstancesRelations(
1529 containerComponent.getComponentInstancesRelations().stream().filter(r -> isNotBelongingRelation(componentInstanceId, r))
1530 .collect(Collectors.toList()));
1534 private boolean isNotBelongingRelation(String componentInstanceId, RequirementCapabilityRelDef relation) {
1535 return !relation.getToNode().equals(componentInstanceId) && !relation.getFromNode().equals(componentInstanceId);
1538 public RequirementCapabilityRelDef associateRIToRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef,
1539 ComponentTypeEnum componentTypeEnum) {
1540 return associateRIToRI(componentId, userId, requirementDef, componentTypeEnum, true);
1543 public RequirementCapabilityRelDef associateRIToRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef,
1544 ComponentTypeEnum componentTypeEnum, boolean needLock) {
1545 validateUserExists(userId);
1546 RequirementCapabilityRelDef requirementCapabilityRelDef;
1547 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(componentId, componentTypeEnum, null);
1548 validateCanWorkOnComponent(containerComponent, userId);
1549 boolean failed = false;
1552 lockComponent(containerComponent, ASSOCIATE_RI_TO_RI);
1554 requirementCapabilityRelDef = associateRIToRIOnGraph(containerComponent, requirementDef);
1555 } catch (ComponentException e) {
1560 unlockComponent(failed, containerComponent);
1563 return requirementCapabilityRelDef;
1566 public RequirementCapabilityRelDef associateRIToRIOnGraph(Component containerComponent, RequirementCapabilityRelDef requirementDef) {
1567 log.debug(TRY_TO_CREATE_ENTRY_ON_GRAPH);
1568 Either<RequirementCapabilityRelDef, StorageOperationStatus> result = toscaOperationFacade
1569 .associateResourceInstances(null, containerComponent.getUniqueId(), requirementDef);
1570 if (result.isLeft()) {
1571 log.debug(ENTITY_ON_GRAPH_IS_CREATED);
1572 return result.left().value();
1574 log.debug("Failed to associate node: {} with node {}", requirementDef.getFromNode(), requirementDef.getToNode());
1575 String fromNameOrId = "";
1576 String toNameOrId = "";
1577 Either<ComponentInstance, StorageOperationStatus> fromResult = getResourceInstanceById(containerComponent, requirementDef.getFromNode());
1578 Either<ComponentInstance, StorageOperationStatus> toResult = getResourceInstanceById(containerComponent, requirementDef.getToNode());
1579 toNameOrId = requirementDef.getFromNode();
1580 fromNameOrId = requirementDef.getFromNode();
1581 if (fromResult.isLeft()) {
1582 fromNameOrId = fromResult.left().value().getName();
1584 if (toResult.isLeft()) {
1585 toNameOrId = toResult.left().value().getName();
1587 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true),
1588 fromNameOrId, toNameOrId, requirementDef.getRelationships().get(0).getRelation().getRequirement());
1593 * @param componentId
1595 * @param requirementDefList
1596 * @param componentTypeEnum
1599 public List<RequirementCapabilityRelDef> batchDissociateRIFromRI(String componentId, String userId,
1600 List<RequirementCapabilityRelDef> requirementDefList,
1601 ComponentTypeEnum componentTypeEnum) {
1602 validateUserExists(userId);
1603 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(componentId, componentTypeEnum, null);
1604 validateCanWorkOnComponent(containerComponent, userId);
1605 boolean failed = false;
1606 List<RequirementCapabilityRelDef> delOkResult = new ArrayList<>();
1608 lockComponent(containerComponent, ASSOCIATE_RI_TO_RI);
1609 for (RequirementCapabilityRelDef requirementDef : requirementDefList) {
1610 RequirementCapabilityRelDef requirementCapabilityRelDef = dissociateRIFromRI(componentId, userId, requirementDef,
1611 containerComponent.getComponentType());
1612 delOkResult.add(requirementCapabilityRelDef);
1614 } catch (ComponentException e) {
1618 unlockComponent(failed, containerComponent);
1623 public RequirementCapabilityRelDef dissociateRIFromRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef,
1624 ComponentTypeEnum componentTypeEnum) {
1625 validateUserExists(userId);
1626 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(componentId, componentTypeEnum, null);
1627 validateCanWorkOnComponent(containerComponent, userId);
1628 boolean failed = false;
1630 lockComponent(containerComponent, ASSOCIATE_RI_TO_RI);
1631 log.debug(TRY_TO_CREATE_ENTRY_ON_GRAPH);
1632 Either<RequirementCapabilityRelDef, StorageOperationStatus> result = toscaOperationFacade
1633 .dissociateResourceInstances(componentId, requirementDef);
1634 if (result.isLeft()) {
1635 log.debug(ENTITY_ON_GRAPH_IS_CREATED);
1636 return result.left().value();
1638 log.debug("Failed to dissocaite node {} from node {}", requirementDef.getFromNode(), requirementDef.getToNode());
1639 String fromNameOrId = "";
1640 String toNameOrId = "";
1641 Either<ComponentInstance, StorageOperationStatus> fromResult = getResourceInstanceById(containerComponent,
1642 requirementDef.getFromNode());
1643 Either<ComponentInstance, StorageOperationStatus> toResult = getResourceInstanceById(containerComponent, requirementDef.getToNode());
1644 toNameOrId = requirementDef.getFromNode();
1645 fromNameOrId = requirementDef.getFromNode();
1646 if (fromResult.isLeft()) {
1647 fromNameOrId = fromResult.left().value().getName();
1649 if (toResult.isLeft()) {
1650 toNameOrId = toResult.left().value().getName();
1652 throw new ByActionStatusComponentException(
1653 componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), fromNameOrId, toNameOrId,
1654 requirementDef.getRelationships().get(0).getRelation().getRequirement());
1656 } catch (ComponentException e) {
1660 unlockComponent(failed, containerComponent);
1665 * Allows to get relation contained in specified component according to received Id
1667 * @param componentId
1670 * @param componentTypeEnum
1673 public Either<RequirementCapabilityRelDef, ResponseFormat> getRelationById(String componentId, String relationId, String userId,
1674 ComponentTypeEnum componentTypeEnum) {
1675 Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null;
1677 org.openecomp.sdc.be.model.Component containerComponent = null;
1678 RequirementCapabilityRelDef foundRelation = null;
1679 validateUserExists(userId);
1680 containerComponent = validateComponentExists(componentId, componentTypeEnum, null);
1681 List<RequirementCapabilityRelDef> requirementCapabilityRelations = containerComponent.getComponentInstancesRelations();
1682 foundRelation = findRelation(relationId, requirementCapabilityRelations);
1683 if (foundRelation == null) {
1684 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RELATION_NOT_FOUND, relationId, componentId);
1685 log.debug("Relation with id {} was not found on the component", relationId, componentId);
1686 resultOp = Either.right(responseFormat);
1688 if (resultOp == null) {
1689 resultOp = setRelatedCapability(foundRelation, containerComponent);
1691 if (resultOp.isLeft()) {
1692 resultOp = setRelatedRequirement(foundRelation, containerComponent);
1694 } catch (Exception e) {
1695 log.error("The exception {} occured upon get relation {} of the component {} ", e, relationId, componentId);
1696 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
1701 private RequirementCapabilityRelDef findRelation(String relationId, List<RequirementCapabilityRelDef> requirementCapabilityRelations) {
1702 for (RequirementCapabilityRelDef relationship : requirementCapabilityRelations) {
1703 if (relationship.getRelationships().stream().anyMatch(r -> r.getRelation().getId().equals(relationId))) {
1704 return relationship;
1710 private Either<RequirementCapabilityRelDef, ResponseFormat> setRelatedRequirement(RequirementCapabilityRelDef foundRelation,
1711 Component containerComponent) {
1712 Either<RequirementCapabilityRelDef, ResponseFormat> result = null;
1713 RelationshipInfo relationshipInfo = foundRelation.resolveSingleRelationship().getRelation();
1714 String instanceId = foundRelation.getFromNode();
1715 Optional<RequirementDefinition> foundRequirement;
1716 Optional<ComponentInstance> instance = containerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(instanceId))
1718 if (!instance.isPresent()) {
1719 ResponseFormat responseFormat = componentsUtils
1720 .getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, instanceId, "instance",
1721 containerComponent.getComponentType().getValue(), containerComponent.getName());
1722 log.debug("Component instance with id {} was not found on the component", instanceId, containerComponent.getUniqueId());
1723 result = Either.right(responseFormat);
1725 if (result == null && instance.isPresent()) {
1726 for (List<RequirementDefinition> requirements : instance.get().getRequirements().values()) {
1727 foundRequirement = requirements.stream()
1728 .filter(r -> isBelongingCalcRequirement(relationshipInfo, r, containerComponent.getLifecycleState())).findFirst();
1729 if (foundRequirement.isPresent()) {
1730 foundRelation.resolveSingleRelationship().setRequirement(foundRequirement.get());
1731 result = Either.left(foundRelation);
1735 if (result == null) {
1736 Either<RequirementDataDefinition, StorageOperationStatus> getfulfilledRequirementRes = toscaOperationFacade
1737 .getFulfilledRequirementByRelation(containerComponent.getUniqueId(), instanceId, foundRelation, this::isBelongingFullRequirement);
1738 if (getfulfilledRequirementRes.isRight()) {
1739 ResponseFormat responseFormat = componentsUtils
1740 .getResponseFormat(ActionStatus.REQUIREMENT_OF_INSTANCE_NOT_FOUND_ON_CONTAINER, relationshipInfo.getRequirement(), instanceId,
1741 containerComponent.getUniqueId());
1742 log.debug("Requirement {} of instance {} was not found on the container {}. ", relationshipInfo.getCapability(), instanceId,
1743 containerComponent.getUniqueId());
1744 result = Either.right(responseFormat);
1746 foundRelation.resolveSingleRelationship().setRequirement(getfulfilledRequirementRes.left().value());
1749 if (result == null) {
1750 result = Either.left(foundRelation);
1755 private boolean isBelongingFullRequirement(RelationshipInfo relationshipInfo, RequirementDataDefinition req) {
1756 return req.getName().equals(relationshipInfo.getRequirement()) && req.getUniqueId().equals(relationshipInfo.getRequirementUid()) && req
1757 .getOwnerId().equals(relationshipInfo.getRequirementOwnerId());
1760 private boolean isBelongingCalcRequirement(RelationshipInfo relationshipInfo, RequirementDataDefinition req, LifecycleStateEnum state) {
1761 return nameMatches(relationshipInfo.getRequirement(), req.getName(), req.getPreviousName(), state) && req.getUniqueId()
1762 .equals(relationshipInfo.getRequirementUid()) && req.getOwnerId().equals(relationshipInfo.getRequirementOwnerId());
1765 private Either<RequirementCapabilityRelDef, ResponseFormat> setRelatedCapability(RequirementCapabilityRelDef foundRelation,
1766 Component containerComponent) {
1767 Either<RequirementCapabilityRelDef, ResponseFormat> result = null;
1768 RelationshipInfo relationshipInfo = foundRelation.resolveSingleRelationship().getRelation();
1769 String instanceId = foundRelation.getToNode();
1770 Optional<CapabilityDefinition> foundCapability;
1771 Optional<ComponentInstance> instance = containerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(instanceId))
1773 if (!instance.isPresent()) {
1774 ResponseFormat responseFormat = componentsUtils
1775 .getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, instanceId, "instance",
1776 containerComponent.getComponentType().getValue(), containerComponent.getName());
1777 log.debug("Component instance with id {} was not found on the component", instanceId, containerComponent.getUniqueId());
1778 result = Either.right(responseFormat);
1780 if (result == null && instance.isPresent()) {
1781 for (List<CapabilityDefinition> capabilities : instance.get().getCapabilities().values()) {
1782 foundCapability = capabilities.stream()
1783 .filter(c -> isBelongingCalcCapability(relationshipInfo, c, containerComponent.getLifecycleState())).findFirst();
1784 if (foundCapability.isPresent()) {
1785 foundRelation.resolveSingleRelationship().setCapability(foundCapability.get());
1786 result = Either.left(foundRelation);
1790 if (result == null) {
1791 Either<CapabilityDataDefinition, StorageOperationStatus> getfulfilledRequirementRes = toscaOperationFacade
1792 .getFulfilledCapabilityByRelation(containerComponent.getUniqueId(), instanceId, foundRelation, this::isBelongingFullCapability);
1793 if (getfulfilledRequirementRes.isRight()) {
1794 ResponseFormat responseFormat = componentsUtils
1795 .getResponseFormat(ActionStatus.CAPABILITY_OF_INSTANCE_NOT_FOUND_ON_CONTAINER, relationshipInfo.getCapability(), instanceId,
1796 containerComponent.getUniqueId());
1797 log.debug("Capability {} of instance {} was not found on the container {}. ", relationshipInfo.getCapability(), instanceId,
1798 containerComponent.getUniqueId());
1799 result = Either.right(responseFormat);
1801 foundRelation.resolveSingleRelationship().setCapability(getfulfilledRequirementRes.left().value());
1804 if (result == null) {
1805 result = Either.left(foundRelation);
1810 private boolean isBelongingFullCapability(RelationshipInfo relationshipInfo, CapabilityDataDefinition cap) {
1811 return cap.getName().equals(relationshipInfo.getCapability()) && cap.getUniqueId().equals(relationshipInfo.getCapabilityUid()) && cap
1812 .getOwnerId().equals(relationshipInfo.getCapabilityOwnerId());
1815 private boolean isBelongingCalcCapability(RelationshipInfo relationshipInfo, CapabilityDataDefinition cap, LifecycleStateEnum state) {
1816 return nameMatches(relationshipInfo.getCapability(), cap.getName(), cap.getPreviousName(), state) && cap.getUniqueId()
1817 .equals(relationshipInfo.getCapabilityUid()) && cap.getOwnerId().equals(relationshipInfo.getCapabilityOwnerId());
1820 private boolean nameMatches(String nameFromRelationship, String currName, String previousName, LifecycleStateEnum state) {
1821 return state == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT ? currName.equals(nameFromRelationship)
1822 : previousName != null && previousName.equals(nameFromRelationship);
1825 private Either<ComponentInstanceProperty, ResponseFormat> updateAttributeValue(ComponentInstanceProperty attribute, String resourceInstanceId) {
1826 Either<ComponentInstanceProperty, StorageOperationStatus> eitherAttribute = componentInstanceOperation
1827 .updateAttributeValueInResourceInstance(attribute, resourceInstanceId, true);
1828 Either<ComponentInstanceProperty, ResponseFormat> result;
1829 if (eitherAttribute.isLeft()) {
1830 log.debug("Attribute value {} was updated on graph.", attribute.getValueUniqueUid());
1831 ComponentInstanceProperty instanceAttribute = eitherAttribute.left().value();
1832 result = Either.left(instanceAttribute);
1834 log.debug("Failed to update attribute value {} in resource instance {}", attribute, resourceInstanceId);
1835 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(eitherAttribute.right().value());
1836 result = Either.right(componentsUtils.getResponseFormat(actionStatus, ""));
1841 private Either<ComponentInstanceProperty, ResponseFormat> createAttributeValue(ComponentInstanceProperty attribute, String resourceInstanceId) {
1842 Either<ComponentInstanceProperty, ResponseFormat> result;
1843 Wrapper<Integer> indexCounterWrapper = new Wrapper<>();
1844 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
1845 validateIncrementCounter(resourceInstanceId, GraphPropertiesDictionary.ATTRIBUTE_COUNTER, indexCounterWrapper, errorWrapper);
1846 if (!errorWrapper.isEmpty()) {
1847 result = Either.right(errorWrapper.getInnerElement());
1849 Either<ComponentInstanceProperty, StorageOperationStatus> eitherAttribute = componentInstanceOperation
1850 .addAttributeValueToResourceInstance(attribute, resourceInstanceId, indexCounterWrapper.getInnerElement(), true);
1851 if (eitherAttribute.isLeft()) {
1852 log.debug("Attribute value was added to resource instance {}", resourceInstanceId);
1853 ComponentInstanceProperty instanceAttribute = eitherAttribute.left().value();
1854 result = Either.left(instanceAttribute);
1856 log.debug("Failed to add attribute value {} to resource instance {}", attribute, resourceInstanceId);
1857 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(eitherAttribute.right().value());
1858 result = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1865 * Create Or Updates Attribute Instance
1867 * @param componentTypeEnum
1868 * @param componentId
1869 * @param resourceInstanceId
1874 public Either<ComponentInstanceProperty, ResponseFormat> createOrUpdateAttributeValue(ComponentTypeEnum componentTypeEnum, String componentId,
1875 String resourceInstanceId,
1876 ComponentInstanceProperty attribute, String userId) {
1877 Either<ComponentInstanceProperty, ResponseFormat> result = null;
1878 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
1879 validateUserExists(userId);
1880 if (errorWrapper.isEmpty()) {
1881 validateComponentTypeEnum(componentTypeEnum, "CreateOrUpdateAttributeValue", errorWrapper);
1883 if (errorWrapper.isEmpty()) {
1884 validateCanWorkOnComponent(componentId, componentTypeEnum, userId, errorWrapper);
1886 if (errorWrapper.isEmpty()) {
1887 validateComponentLock(componentId, componentTypeEnum, errorWrapper);
1890 if (errorWrapper.isEmpty()) {
1891 final boolean isCreate = Objects.isNull(attribute.getValueUniqueUid());
1893 result = createAttributeValue(attribute, resourceInstanceId);
1895 result = updateAttributeValue(attribute, resourceInstanceId);
1898 result = Either.right(errorWrapper.getInnerElement());
1902 if (result == null || result.isRight()) {
1903 janusGraphDao.rollback();
1905 janusGraphDao.commit();
1908 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
1912 public Either<List<ComponentInstanceProperty>, ResponseFormat> createOrUpdatePropertiesValues(ComponentTypeEnum componentTypeEnum,
1913 String componentId, String resourceInstanceId,
1914 List<ComponentInstanceProperty> properties,
1916 Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
1917 /*-------------------------------Validations---------------------------------*/
1918 validateUserExists(userId);
1920 if (componentTypeEnum == null) {
1921 BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertiesValues", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
1922 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
1925 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
1927 if (getResourceResult.isRight()) {
1928 log.debug(FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID, componentId);
1929 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getResourceResult.right().value(), componentTypeEnum);
1930 return Either.right(componentsUtils.getResponseFormat(actionStatus, componentId));
1932 Component containerComponent = getResourceResult.left().value();
1934 if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
1935 if (Boolean.TRUE.equals(containerComponent.isArchived())) {
1936 log.info(COMPONENT_ARCHIVED, componentId);
1937 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_IS_ARCHIVED, containerComponent.getName()));
1939 log.info(RESTRICTED_OPERATION_ON_SERVIVE, userId, componentId);
1940 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1943 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId);
1944 if (resourceInstanceStatus.isRight()) {
1945 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER,
1946 resourceInstanceId, RESOURCE_INSTANCE, SERVICE, componentId));
1948 ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
1951 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
1952 if (lockStatus != StorageOperationStatus.OK) {
1953 log.debug(FAILED_TO_LOCK_SERVICE, componentId);
1954 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
1956 List<ComponentInstanceProperty> updatedProperties = new ArrayList<>();
1958 for (ComponentInstanceProperty property : properties) {
1959 validateMandatoryFields(property);
1960 ComponentInstanceProperty componentInstanceProperty = validatePropertyExistsOnComponent(property, containerComponent,
1961 foundResourceInstance);
1962 String propertyParentUniqueId = property.getParentUniqueId();
1963 if (property.isGetFunction()) {
1964 validateToscaGetFunction(property, containerComponent);
1965 property.setValue(property.getToscaGetFunction().generatePropertyValue());
1967 Either<String, ResponseFormat> updatedPropertyValue = updatePropertyObjectValue(property, containerComponent.getModel());
1968 if (updatedPropertyValue.isRight()) {
1969 log.error("Failed to update property object value of property: {}",
1971 throw new ByResponseFormatComponentException(updatedPropertyValue.right().value());
1973 Optional<CapabilityDefinition>
1974 capPropDefinition = getPropertyCapabilityOfChildInstance(propertyParentUniqueId, foundResourceInstance.getCapabilities());
1975 if (capPropDefinition.isPresent()) {
1976 updatedPropertyValue
1977 .bimap(updatedValue -> updateCapabilityPropFromUpdateInstProp(property, updatedValue,
1978 containerComponent, foundResourceInstance, capPropDefinition.get().getType(),
1979 capPropDefinition.get().getName()), Either::right);
1981 updatedPropertyValue.bimap(
1983 componentInstanceProperty.setValue(updatedValue);
1984 return updatePropertyOnContainerComponent(property, updatedValue,
1985 containerComponent, foundResourceInstance);
1987 updatedProperties.add(componentInstanceProperty);
1991 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade
1992 .updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
1993 if (updateContainerRes.isRight()) {
1994 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
1995 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1998 resultOp = Either.left(updatedProperties);
2001 } catch (final ComponentException e) {
2002 return Either.right(e.getResponseFormat());
2004 if (resultOp == null || resultOp.isRight()) {
2005 janusGraphDao.rollback();
2007 janusGraphDao.commit();
2010 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
2014 public Either<List<ComponentInstanceAttribute>, ResponseFormat> createOrUpdateAttributeValues(final ComponentTypeEnum componentTypeEnum,
2015 final String componentId,
2016 final String resourceInstanceId,
2017 final List<ComponentInstanceAttribute> attributes,
2018 final String userId) {
2019 Either<List<ComponentInstanceAttribute>, ResponseFormat> resultOp = null;
2020 /*-------------------------------Validations---------------------------------*/
2021 validateUserExists(userId);
2023 if (componentTypeEnum == null) {
2024 BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertiesValues", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
2025 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
2028 final Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade
2029 .getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
2031 if (getResourceResult.isRight()) {
2032 log.debug(FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID, componentId);
2033 final ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getResourceResult.right().value(), componentTypeEnum);
2034 return Either.right(componentsUtils.getResponseFormat(actionStatus, componentId));
2036 final Component containerComponent = getResourceResult.left().value();
2038 if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
2039 if (Boolean.TRUE.equals(containerComponent.isArchived())) {
2040 log.info(COMPONENT_ARCHIVED, componentId);
2041 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_IS_ARCHIVED, containerComponent.getName()));
2043 log.info(RESTRICTED_OPERATION_ON_SERVIVE, userId, componentId);
2044 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2047 final Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent,
2048 resourceInstanceId);
2049 if (resourceInstanceStatus.isRight()) {
2050 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER,
2051 resourceInstanceId, RESOURCE_INSTANCE, SERVICE, componentId));
2053 final ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
2056 final StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
2057 if (lockStatus != StorageOperationStatus.OK) {
2058 log.debug(FAILED_TO_LOCK_SERVICE, componentId);
2059 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
2061 final List<ComponentInstanceAttribute> updatedProperties = new ArrayList<>();
2063 for (final ComponentInstanceAttribute attribute : attributes) {
2064 final ComponentInstanceAttribute componentInstanceProperty = validateAttributeExistsOnComponent(attribute, containerComponent,
2065 foundResourceInstance);
2066 final Either<String, ResponseFormat> updatedPropertyValue = updateAttributeObjectValue(attribute);
2067 if (updatedPropertyValue.isRight()) {
2068 log.error("Failed to update attribute object value of attribute: {}", attribute);
2069 throw new ByResponseFormatComponentException(updatedPropertyValue.right().value());
2071 updatedPropertyValue.bimap(
2073 componentInstanceProperty.setValue(updatedValue);
2074 return updateAttributeOnContainerComponent(attribute, updatedValue,
2075 containerComponent, foundResourceInstance);
2077 updatedProperties.add(componentInstanceProperty);
2080 final Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade
2081 .updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
2082 if (updateContainerRes.isRight()) {
2083 final ActionStatus actionStatus = componentsUtils
2084 .convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
2085 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2088 resultOp = Either.left(updatedProperties);
2091 } catch (final ComponentException e) {
2092 return Either.right(e.getResponseFormat());
2094 if (resultOp == null || resultOp.isRight()) {
2095 janusGraphDao.rollback();
2097 janusGraphDao.commit();
2100 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
2104 private void validateMandatoryFields(PropertyDataDefinition property) {
2105 if (StringUtils.isEmpty(property.getName())) {
2106 throw new ByActionStatusComponentException(ActionStatus.MISSING_PROPERTY_NAME);
2110 private ComponentInstanceProperty validatePropertyExistsOnComponent(ComponentInstanceProperty property, Component containerComponent,
2111 ComponentInstance foundResourceInstance) {
2112 List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties()
2113 .get(foundResourceInstance.getUniqueId());
2114 Optional<ComponentInstanceProperty> instanceProperty = instanceProperties.stream().filter(p -> p.getName().equals(property.getName()))
2116 if (instanceProperty.isEmpty()) {
2117 throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND, property.getName());
2119 return instanceProperty.get();
2122 private ComponentInstanceAttribute validateAttributeExistsOnComponent(final ComponentInstanceAttribute attribute,
2123 final Component containerComponent,
2124 final ComponentInstance foundResourceInstance) {
2125 final List<ComponentInstanceAttribute> instanceProperties =
2126 containerComponent.getComponentInstancesAttributes().get(foundResourceInstance.getUniqueId());
2127 final Optional<ComponentInstanceAttribute> instanceAttribute =
2128 instanceProperties.stream().filter(p -> p.getName().equals(attribute.getName())).findAny();
2129 if (!instanceAttribute.isPresent()) {
2130 throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND, attribute.getName());
2132 return instanceAttribute.get();
2135 private ResponseFormat updateCapabilityPropertyOnContainerComponent(ComponentInstanceProperty property,
2136 String newValue, Component containerComponent,
2137 ComponentInstance foundResourceInstance,
2138 String capabilityType, String capabilityName) {
2139 String componentInstanceUniqueId = foundResourceInstance.getUniqueId();
2140 ResponseFormat actionStatus = updateCapPropOnContainerComponent(property, newValue, containerComponent,
2141 foundResourceInstance, capabilityType, capabilityName, componentInstanceUniqueId);
2142 if (actionStatus != null) {
2143 return actionStatus;
2146 return componentsUtils.getResponseFormat(ActionStatus.OK);
2149 private ResponseFormat updateCapabilityPropFromUpdateInstProp(ComponentInstanceProperty property,
2150 String newValue, Component containerComponent,
2151 ComponentInstance foundResourceInstance,
2152 String capabilityType, String capabilityName) {
2153 String componentInstanceUniqueId = foundResourceInstance.getUniqueId();
2154 Either<Component, StorageOperationStatus> getComponentRes =
2155 toscaOperationFacade.getToscaFullElement(foundResourceInstance.getComponentUid());
2156 if (getComponentRes.isRight()) {
2157 return componentsUtils.getResponseFormat(getComponentRes.right().value());
2160 ResponseFormat actionStatus = updateCapPropOnContainerComponent(property, newValue, containerComponent,
2161 foundResourceInstance, capabilityType, capabilityName, componentInstanceUniqueId);
2162 if (actionStatus != null) {
2163 return actionStatus;
2166 return componentsUtils.getResponseFormat(ActionStatus.OK);
2169 private ResponseFormat updateCapPropOnContainerComponent(ComponentInstanceProperty property, String newValue,
2170 Component containerComponent,
2171 ComponentInstance foundResourceInstance,
2172 String capabilityType, String capabilityName,
2173 String componentInstanceUniqueId) {
2174 Map<String, List<CapabilityDefinition>> capabilities =
2175 Optional.ofNullable(foundResourceInstance.getCapabilities()).orElse(Collections.emptyMap());
2176 List<CapabilityDefinition> capPerType =
2177 Optional.ofNullable(capabilities.get(capabilityType)).orElse(Collections.emptyList());
2178 Optional<CapabilityDefinition> cap =
2179 capPerType.stream().filter(c -> c.getName().equals(capabilityName)).findAny();
2180 if (cap.isPresent()) {
2181 List<ComponentInstanceProperty> capProperties = cap.get().getProperties();
2182 if (capProperties != null) {
2183 Optional<ComponentInstanceProperty> instanceProperty =
2184 capProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
2185 StorageOperationStatus status;
2186 if (instanceProperty.isPresent()) {
2187 String capKey = ModelConverter
2188 .buildCapabilityPropertyKey(foundResourceInstance.getOriginType().isAtomicType(), capabilityType, capabilityName,
2189 componentInstanceUniqueId, cap.get());
2190 instanceProperty.get().setValue(newValue);
2191 List<String> path = new ArrayList<>();
2192 path.add(componentInstanceUniqueId);
2194 instanceProperty.get().setPath(path);
2195 status = toscaOperationFacade.updateComponentInstanceCapabiltyProperty(containerComponent,
2196 componentInstanceUniqueId, capKey, instanceProperty.get());
2197 if (status != StorageOperationStatus.OK) {
2198 ActionStatus actionStatus =
2199 componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
2200 return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
2203 foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
2210 private ResponseFormat updatePropertyOnContainerComponent(ComponentInstanceProperty instanceProperty, String newValue,
2211 Component containerComponent, ComponentInstance foundResourceInstance) {
2212 StorageOperationStatus status;
2213 instanceProperty.setValue(newValue);
2214 status = toscaOperationFacade.updateComponentInstanceProperty(containerComponent, foundResourceInstance.getUniqueId(), instanceProperty);
2215 if (status != StorageOperationStatus.OK) {
2216 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
2217 return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
2219 foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
2220 return componentsUtils.getResponseFormat(ActionStatus.OK);
2223 private ResponseFormat updateAttributeOnContainerComponent(final ComponentInstanceAttribute instanceAttribute,
2224 final String newValue,
2225 final Component containerComponent,
2226 final ComponentInstance foundResourceInstance) {
2228 instanceAttribute.setValue(newValue);
2229 final StorageOperationStatus status =
2230 toscaOperationFacade.updateComponentInstanceAttribute(containerComponent, foundResourceInstance.getUniqueId(), instanceAttribute);
2231 if (status != StorageOperationStatus.OK) {
2232 final ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
2233 return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
2235 foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
2236 return componentsUtils.getResponseFormat(ActionStatus.OK);
2239 private <T extends PropertyDefinition> Either<String, ResponseFormat> validatePropertyObjectValue(T property, String newValue, boolean isInput) {
2240 final Map<String, DataTypeDefinition> allDataTypes = componentsUtils.getAllDataTypes(applicationDataTypeCache, property.getModel());
2241 String propertyType = property.getType();
2242 String innerType = getInnerType(property);
2244 // Specific Update Logic
2245 Either<Object, Boolean> isValid = propertyOperation
2246 .validateAndUpdatePropertyValue(property.getType(), newValue, true, innerType, allDataTypes);
2247 if (isValid.isRight()) {
2248 if (!Boolean.TRUE.equals(isValid.right().value())) {
2249 log.error("Invalid value {} of property {} ", newValue, property.getName());
2250 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2253 Object object = isValid.left().value();
2254 if (object != null) {
2255 newValue = object.toString();
2258 if (validateAndUpdateRules(property, isInput, allDataTypes, innerType, propertyType)) {
2259 return Either.right(componentsUtils.getResponseFormat(componentsUtils
2260 .convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT))));
2262 return Either.left(newValue);
2265 private <T extends PropertyDefinition> boolean validateAndUpdateRules(T property, boolean isInput, Map<String, DataTypeDefinition> allDataTypes,
2266 String innerType, String propertyType) {
2268 ImmutablePair<String, Boolean> pair = propertyOperation
2269 .validateAndUpdateRules(propertyType, ((ComponentInstanceProperty) property).getRules(), innerType, allDataTypes, true);
2270 if (pair.getRight() != null && !pair.getRight()) {
2271 BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), property.getName(), propertyType);
2278 private <T extends PropertyDefinition> Either<String, ResponseFormat> updatePropertyObjectValue(T property, final String model) {
2279 final Map<String, DataTypeDefinition> allDataTypes = componentsUtils.getAllDataTypes(applicationDataTypeCache, model);
2280 String innerType = null;
2281 String propertyType = property.getType();
2282 ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
2283 log.debug("The type of the property {} is {}", property.getUniqueId(), propertyType);
2285 if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
2286 SchemaDefinition schema = property.getSchema();
2287 if (schema == null) {
2288 log.debug("Schema doesn't exists for property of type {}", type);
2290 .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
2292 PropertyDataDefinition propDef = schema.getProperty();
2293 if (propDef == null) {
2294 log.debug("Property in Schema Definition inside property of type {} doesn't exist", type);
2296 .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
2298 innerType = propDef.getType();
2301 // Specific Update Logic
2302 String newValue = property.getValue();
2304 if (property.hasGetFunction()) {
2305 return Either.left(newValue);
2308 Either<Object, Boolean> isValid = propertyOperation
2309 .validateAndUpdatePropertyValue(propertyType, property.getValue(), true, innerType, allDataTypes);
2310 if (isValid.isRight()) {
2311 if (!Boolean.TRUE.equals(isValid.right().value())) {
2312 log.debug("validate and update property value has failed with value: {}", property.getValue());
2313 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(
2314 DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT)));
2317 Object object = isValid.left().value();
2318 if (object != null) {
2319 newValue = object.toString();
2322 ImmutablePair<String, Boolean> pair = propertyOperation
2323 .validateAndUpdateRules(propertyType, ((ComponentInstanceProperty) property).getRules(), innerType, allDataTypes, true);
2324 if (pair.getRight() != null && Boolean.FALSE.equals(pair.getRight())) {
2325 BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), property.getName(), propertyType);
2326 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(
2327 DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT))));
2329 return Either.left(newValue);
2332 private <T extends AttributeDefinition> Either<String, ResponseFormat> updateAttributeObjectValue(final T attribute) {
2333 String innerType = null;
2334 final String attributeType = attribute.getType();
2335 final ToscaPropertyType type = ToscaPropertyType.isValidType(attributeType);
2336 log.debug("The type of the attribute {} is {}", attribute.getUniqueId(), attributeType);
2338 if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
2339 final SchemaDefinition def = attribute.getSchema();
2341 log.debug("Schema doesn't exists for attribute of type {}", type);
2343 .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
2345 PropertyDataDefinition propDef = def.getProperty();
2346 if (propDef == null) {
2347 log.debug("Property in Schema Definition inside attribute of type {} doesn't exist", type);
2349 .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
2351 innerType = propDef.getType();
2354 // Specific Update Logic
2355 String newValue = attribute.getValue();
2357 final var isValid = attributeOperation.validateAndUpdateAttributeValue(attribute, innerType,
2358 componentsUtils.getAllDataTypes(applicationDataTypeCache, attribute.getModel()));
2359 if (isValid.isRight()) {
2360 final Boolean res = isValid.right().value();
2361 if (!Boolean.TRUE.equals(res)) {
2362 log.debug("validate and update attribute value has failed with value: {}", newValue);
2363 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(
2364 DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT)));
2367 final Object object = isValid.left().value();
2368 if (object != null) {
2369 newValue = object.toString();
2372 return Either.left(newValue);
2375 private <T extends PropertyDefinition> void validateToscaGetFunction(T property, Component parentComponent) {
2376 final ToscaGetFunctionDataDefinition toscaGetFunction = property.getToscaGetFunction();
2377 validateGetPropertySource(toscaGetFunction.getFunctionType(), toscaGetFunction.getPropertySource());
2378 if (toscaGetFunction.getFunctionType() == ToscaGetFunctionType.GET_INPUT) {
2379 validateGetFunction(property, parentComponent.getInputs(), parentComponent.getModel());
2382 if (toscaGetFunction.getFunctionType() == ToscaGetFunctionType.GET_PROPERTY) {
2383 if (toscaGetFunction.getPropertySource() == PropertySource.SELF) {
2384 validateGetFunction(property, parentComponent.getProperties(), parentComponent.getModel());
2385 } else if (toscaGetFunction.getPropertySource() == PropertySource.INSTANCE) {
2386 final ComponentInstance componentInstance =
2387 parentComponent.getComponentInstanceById(toscaGetFunction.getSourceUniqueId())
2388 .orElseThrow(ToscaGetFunctionExceptionSupplier.instanceNotFound(toscaGetFunction.getSourceName()));
2389 validateGetFunction(property, componentInstance.getProperties(), parentComponent.getModel());
2395 throw ToscaGetFunctionExceptionSupplier.functionNotSupported(toscaGetFunction.getFunctionType()).get();
2398 private <T extends PropertyDefinition, U extends PropertyDefinition> void validateGetFunction(final T property,
2399 final List<U> parentProperties,
2400 final String model) {
2401 final ToscaGetFunctionDataDefinition toscaGetFunction = property.getToscaGetFunction();
2402 if (CollectionUtils.isEmpty(parentProperties)) {
2403 throw ToscaGetFunctionExceptionSupplier
2404 .propertyNotFoundOnTarget(toscaGetFunction.getPropertyName(), toscaGetFunction.getPropertySource(),
2405 toscaGetFunction.getFunctionType()
2408 final String getFunctionPropertyUniqueId = toscaGetFunction.getPropertyUniqueId();
2409 T referredProperty = (T) parentProperties.stream()
2410 .filter(property1 -> getFunctionPropertyUniqueId.equals(property1.getUniqueId()))
2412 .orElseThrow(ToscaGetFunctionExceptionSupplier
2413 .propertyNotFoundOnTarget(toscaGetFunction.getPropertyName(), toscaGetFunction.getPropertySource()
2414 , toscaGetFunction.getFunctionType())
2416 if (toscaGetFunction.isSubProperty()) {
2417 referredProperty = findSubProperty(referredProperty, toscaGetFunction, model);
2420 if (!property.getType().equals(referredProperty.getType())) {
2421 throw ToscaGetFunctionExceptionSupplier
2422 .propertyTypeDiverge(toscaGetFunction.getFunctionType(), referredProperty.getType(), property.getType()).get();
2424 if (PropertyType.typeHasSchema(referredProperty.getType()) && !referredProperty.getSchemaType().equals(property.getSchemaType())) {
2425 throw ToscaGetFunctionExceptionSupplier
2426 .propertySchemaDiverge(toscaGetFunction.getFunctionType(), referredProperty.getSchemaType(), property.getSchemaType()).get();
2430 private <T extends PropertyDefinition> T findSubProperty(final T referredProperty, final ToscaGetFunctionDataDefinition toscaGetFunction,
2431 final String model) {
2432 final Map<String, DataTypeDefinition> dataTypeMap = loadDataTypes(model);
2433 final List<String> propertyPathFromSource = toscaGetFunction.getPropertyPathFromSource();
2434 DataTypeDefinition dataType = dataTypeMap.get(referredProperty.getType());
2435 if (dataType == null) {
2436 throw ToscaGetFunctionExceptionSupplier
2437 .propertyDataTypeNotFound(propertyPathFromSource.get(0), referredProperty.getType(), toscaGetFunction.getFunctionType()).get();
2439 T foundProperty = referredProperty;
2440 for (int i = 1; i < propertyPathFromSource.size(); i++) {
2441 final String currentPropertyName = propertyPathFromSource.get(i);
2442 foundProperty = (T) dataType.getProperties().stream()
2443 .filter(propertyDefinition -> currentPropertyName.equals(propertyDefinition.getName())).findFirst()
2445 ToscaGetFunctionExceptionSupplier
2446 .propertyNotFoundOnTarget(propertyPathFromSource.subList(0, i), toscaGetFunction.getPropertySource(),
2447 toscaGetFunction.getFunctionType())
2449 dataType = dataTypeMap.get(foundProperty.getType());
2450 if (dataType == null) {
2451 throw ToscaGetFunctionExceptionSupplier
2452 .propertyDataTypeNotFound(propertyPathFromSource.subList(0, i), foundProperty.getType(),
2453 toscaGetFunction.getFunctionType()).get();
2456 return foundProperty;
2459 private Map<String, DataTypeDefinition> loadDataTypes(String model) {
2460 final Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> dataTypeEither =
2461 applicationDataTypeCache.getAll(model);
2462 if (dataTypeEither.isRight()) {
2463 throw ToscaGetFunctionExceptionSupplier.couldNotLoadDataTypes(model).get();
2465 return dataTypeEither.left().value();
2468 private void validateGetPropertySource(final ToscaGetFunctionType functionType, final PropertySource propertySource) {
2469 if (functionType == ToscaGetFunctionType.GET_INPUT && propertySource != PropertySource.SELF) {
2470 throw ToscaGetFunctionExceptionSupplier
2471 .targetSourceNotSupported(functionType, propertySource).get();
2473 if (functionType == ToscaGetFunctionType.GET_PROPERTY && !List.of(PropertySource.SELF, PropertySource.INSTANCE).contains(propertySource)) {
2474 throw ToscaGetFunctionExceptionSupplier
2475 .targetSourceNotSupported(functionType, propertySource).get();
2479 private ResponseFormat updateInputOnContainerComponent(ComponentInstanceInput input, String newValue, Component containerComponent,
2480 ComponentInstance foundResourceInstance) {
2481 StorageOperationStatus status;
2482 input.setValue(newValue);
2483 status = toscaOperationFacade.updateComponentInstanceInput(containerComponent, foundResourceInstance.getUniqueId(), input);
2484 if (status != StorageOperationStatus.OK) {
2485 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
2486 return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
2488 foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
2489 return componentsUtils.getResponseFormat(ActionStatus.OK);
2492 public Either<List<ComponentInstanceInput>, ResponseFormat> createOrUpdateInstanceInputValues(ComponentTypeEnum componentTypeEnum,
2493 String componentId, String resourceInstanceId,
2494 List<ComponentInstanceInput> inputs,
2497 Either<List<ComponentInstanceInput>, ResponseFormat> resultOp = null;
2499 validateUserExists(userId);
2501 if (componentTypeEnum == null) {
2502 BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_OR_UPDATE_PROPERTY_VALUE, INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
2503 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
2506 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
2508 if (getResourceResult.isRight()) {
2509 log.debug(FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID, componentId);
2510 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getResourceResult.right().value(), componentTypeEnum);
2511 return Either.right(componentsUtils.getResponseFormat(actionStatus, componentId));
2513 Component containerComponent = getResourceResult.left().value();
2515 if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
2516 if (Boolean.TRUE.equals(containerComponent.isArchived())) {
2517 log.info(COMPONENT_ARCHIVED, componentId);
2518 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_IS_ARCHIVED, containerComponent.getName()));
2520 log.info(RESTRICTED_OPERATION_ON_SERVIVE, userId, componentId);
2521 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2524 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId);
2525 if (resourceInstanceStatus.isRight()) {
2526 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER,
2527 resourceInstanceId, RESOURCE_INSTANCE, SERVICE, componentId));
2530 ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
2533 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
2534 if (lockStatus != StorageOperationStatus.OK) {
2535 log.debug(FAILED_TO_LOCK_SERVICE, componentId);
2536 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
2538 List<ComponentInstanceInput> updatedInputs = new ArrayList<>();
2540 for (ComponentInstanceInput input : inputs) {
2541 validateMandatoryFields(input);
2542 ComponentInstanceInput componentInstanceInput = validateInputExistsOnComponent(input, containerComponent, foundResourceInstance);
2543 Either<String, ResponseFormat> validatedInputValue = validatePropertyObjectValue(componentInstanceInput, input.getValue(), true);
2544 if (validatedInputValue.isRight()) {
2545 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT, input.getName());
2547 updateInputOnContainerComponent(componentInstanceInput, validatedInputValue.left().value(), containerComponent,
2548 foundResourceInstance);
2549 updatedInputs.add(componentInstanceInput);
2551 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade
2552 .updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
2553 if (updateContainerRes.isRight()) {
2554 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
2555 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2558 resultOp = Either.left(updatedInputs);
2562 if (resultOp == null || resultOp.isRight()) {
2563 janusGraphDao.rollback();
2565 janusGraphDao.commit();
2568 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
2573 private ComponentInstanceInput validateInputExistsOnComponent(ComponentInstanceInput input, Component containerComponent,
2574 ComponentInstance foundResourceInstance) {
2575 List<ComponentInstanceInput> instanceProperties = containerComponent.getComponentInstancesInputs().get(foundResourceInstance.getUniqueId());
2576 Optional<ComponentInstanceInput> instanceInput = instanceProperties.stream().filter(p -> p.getName().equals(input.getName())).findAny();
2577 if (!instanceInput.isPresent()) {
2578 throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND, input.getName());
2580 return instanceInput.get();
2583 public Either<ComponentInstanceProperty, ResponseFormat> createOrUpdateGroupInstancePropertyValue(ComponentTypeEnum componentTypeEnum,
2584 String componentId, String resourceInstanceId,
2585 String groupInstanceId,
2586 ComponentInstanceProperty property,
2589 Either<ComponentInstanceProperty, ResponseFormat> resultOp = null;
2591 validateUserExists(userId);
2593 if (componentTypeEnum == null) {
2594 BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_OR_UPDATE_PROPERTY_VALUE, INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
2595 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
2599 if (!ComponentValidationUtils.canWorkOnComponent(componentId, toscaOperationFacade, userId)) {
2600 log.info("Restricted operation for user: {} on service: {}", userId, componentId);
2601 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2605 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
2606 if (lockStatus != StorageOperationStatus.OK) {
2607 log.debug(FAILED_TO_LOCK_SERVICE, componentId);
2608 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
2612 String propertyValueUid = property.getValueUniqueUid();
2614 if (propertyValueUid == null) {
2616 Either<Integer, StorageOperationStatus> counterRes = groupInstanceOperation
2617 .increaseAndGetGroupInstancePropertyCounter(groupInstanceId);
2619 if (counterRes.isRight()) {
2620 log.debug("increaseAndGetResourcePropertyCounter failed resource instance: {} property: {}", resourceInstanceId, property);
2621 StorageOperationStatus status = counterRes.right().value();
2622 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
2623 resultOp = Either.right(componentsUtils.getResponseFormat(actionStatus));
2625 Integer index = counterRes.left().value();
2626 Either<ComponentInstanceProperty, StorageOperationStatus> result = groupInstanceOperation
2627 .addPropertyValueToGroupInstance(property, resourceInstanceId, index, true);
2629 if (result.isLeft()) {
2630 log.trace("Property value was added to resource instance {}", resourceInstanceId);
2631 ComponentInstanceProperty instanceProperty = result.left().value();
2633 resultOp = Either.left(instanceProperty);
2636 log.debug("Failed to add property value: {} to resource instance {}", property, resourceInstanceId);
2638 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
2640 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2644 Either<ComponentInstanceProperty, StorageOperationStatus> result = groupInstanceOperation
2645 .updatePropertyValueInGroupInstance(property, resourceInstanceId, true);
2647 if (result.isLeft()) {
2648 log.debug("Property value {} was updated on graph.", property.getValueUniqueUid());
2649 ComponentInstanceProperty instanceProperty = result.left().value();
2651 resultOp = Either.left(instanceProperty);
2654 log.debug("Failed to update property value: {}, in resource instance {}", property, resourceInstanceId);
2656 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
2658 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2661 if (resultOp.isLeft()) {
2662 StorageOperationStatus updateCustomizationUUID = componentInstanceOperation.updateCustomizationUUID(resourceInstanceId);
2663 if (updateCustomizationUUID != StorageOperationStatus.OK) {
2664 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateCustomizationUUID);
2666 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2673 if (resultOp == null || resultOp.isRight()) {
2674 janusGraphDao.rollback();
2676 janusGraphDao.commit();
2679 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
2684 public Either<ComponentInstanceProperty, ResponseFormat> deletePropertyValue(ComponentTypeEnum componentTypeEnum, String serviceId,
2685 String resourceInstanceId, String propertyValueId, String userId) {
2687 validateUserExists(userId);
2689 Either<ComponentInstanceProperty, ResponseFormat> resultOp = null;
2691 if (componentTypeEnum == null) {
2692 BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_OR_UPDATE_PROPERTY_VALUE, INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
2693 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
2697 if (!ComponentValidationUtils.canWorkOnComponent(serviceId, toscaOperationFacade, userId)) {
2698 log.info("Restricted operation for user {} on service {}", userId, serviceId);
2699 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2703 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(serviceId, componentTypeEnum.getNodeType());
2704 if (lockStatus != StorageOperationStatus.OK) {
2705 log.debug(FAILED_TO_LOCK_SERVICE, serviceId);
2706 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
2710 Either<ComponentInstanceProperty, StorageOperationStatus> result = propertyOperation
2711 .removePropertyValueFromResourceInstance(propertyValueId, resourceInstanceId, true);
2713 if (result.isLeft()) {
2714 log.debug("Property value {} was removed from graph.", propertyValueId);
2715 ComponentInstanceProperty instanceProperty = result.left().value();
2717 resultOp = Either.left(instanceProperty);
2721 log.debug("Failed to remove property value {} in resource instance {}", propertyValueId, resourceInstanceId);
2723 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
2725 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2731 if (resultOp == null || resultOp.isRight()) {
2732 janusGraphDao.rollback();
2734 janusGraphDao.commit();
2737 graphLockOperation.unlockComponent(serviceId, componentTypeEnum.getNodeType());
2742 private Component getAndValidateOriginComponentOfComponentInstance(Component containerComponent, ComponentInstance componentInstance) {
2744 ComponentTypeEnum componentType = getComponentTypeByParentComponentType(containerComponent.getComponentType());
2745 Component component;
2746 Either<Component, StorageOperationStatus> getComponentRes = toscaOperationFacade.getToscaFullElement(componentInstance.getComponentUid());
2747 if (getComponentRes.isRight()) {
2748 log.debug("Failed to get the component with id {} for component instance {} creation. ", componentInstance.getComponentUid(),
2749 componentInstance.getName());
2750 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentRes.right().value(), componentType);
2751 throw new ByActionStatusComponentException(actionStatus, Constants.EMPTY_STRING);
2753 component = getComponentRes.left().value();
2754 LifecycleStateEnum resourceCurrState = component.getLifecycleState();
2755 if (resourceCurrState == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) {
2756 ActionStatus actionStatus = ActionStatus.CONTAINER_CANNOT_CONTAIN_COMPONENT_IN_STATE;
2757 throw new ByActionStatusComponentException(actionStatus, containerComponent.getComponentType().toString(), resourceCurrState.toString());
2759 if (Boolean.TRUE.equals(component.isArchived())) {
2760 ActionStatus actionStatus = ActionStatus.COMPONENT_IS_ARCHIVED;
2761 throw new ByActionStatusComponentException(actionStatus, component.getName());
2763 final Map<String, InterfaceDefinition> componentInterfaces = component.getInterfaces();
2764 if (MapUtils.isNotEmpty(componentInterfaces)) {
2765 componentInterfaces.forEach(componentInstance::addInterface);
2770 public Either<Set<String>, ResponseFormat> forwardingPathOnVersionChange(String containerComponentParam,
2771 String containerComponentId,
2772 String componentInstanceId,
2773 ComponentInstance newComponentInstance) {
2774 Either<Set<String>, ResponseFormat> resultOp;
2775 final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
2776 ComponentParametersView componentParametersView = getComponentParametersViewForForwardingPath();
2779 Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, componentParametersView);
2781 //Fetch current component instance
2782 Either<ComponentInstance, StorageOperationStatus> eitherResourceInstance =
2783 getResourceInstanceById(containerComponent, componentInstanceId);
2784 if (eitherResourceInstance.isRight()) {
2785 resultOp = Either.right(componentsUtils.getResponseFormat(
2786 ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceId, containerComponentId));
2789 ComponentInstance currentResourceInstance = eitherResourceInstance.left().value();
2791 //Check whether new componentInstance exists
2792 String resourceId = newComponentInstance.getComponentUid();
2793 Either<Boolean, StorageOperationStatus> componentExistsRes = toscaOperationFacade.validateComponentExists(resourceId);
2794 if (componentExistsRes.isRight()) {
2795 log.debug("Failed to find resource {}", resourceId);
2796 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse
2797 (componentExistsRes.right().value()), resourceId));
2799 } else if (!Boolean.TRUE.equals(componentExistsRes.left().value())) {
2800 log.debug("The resource {} not found ", resourceId);
2801 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId));
2805 //Fetch component using new component instance uid
2806 Component updatedContainerComponent = getOriginComponentFromComponentInstance(newComponentInstance);
2807 Set<String> toDeleteForwardingPaths = getForwardingPaths(containerComponent,
2808 currentResourceInstance, updatedContainerComponent);
2809 resultOp = Either.left(toDeleteForwardingPaths);
2814 private Set<String> getForwardingPaths(Component containerComponent, ComponentInstance currentResourceInstance,
2815 Component updatedContainerComponent) {
2816 DataForMergeHolder dataForMergeHolder = new DataForMergeHolder();
2817 dataForMergeHolder.setOrigComponentInstId(currentResourceInstance.getName());
2819 Service service = (Service) containerComponent;
2820 ForwardingPathUtils forwardingPathUtils = new ForwardingPathUtils();
2822 return forwardingPathUtils.
2823 getForwardingPathsToBeDeletedOnVersionChange(service, dataForMergeHolder, updatedContainerComponent);
2826 private ComponentParametersView getComponentParametersViewForForwardingPath() {
2827 ComponentParametersView componentParametersView = new ComponentParametersView();
2828 componentParametersView.setIgnoreCapabiltyProperties(false);
2829 componentParametersView.setIgnoreServicePath(false);
2830 return componentParametersView;
2833 public ComponentInstance changeComponentInstanceVersion(String containerComponentParam, String containerComponentId, String componentInstanceId,
2834 String userId, ComponentInstance newComponentInstance) {
2836 User user = validateUserExists(userId);
2837 final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
2838 ComponentParametersView componentParametersView = new ComponentParametersView();
2839 componentParametersView.setIgnoreCapabiltyProperties(false);
2841 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(containerComponentId, containerComponentType,
2842 componentParametersView);
2844 validateCanWorkOnComponent(containerComponent, userId);
2846 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceId);
2847 if (resourceInstanceStatus.isRight()) {
2848 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceId,
2849 containerComponentId);
2852 ComponentInstance currentResourceInstance = resourceInstanceStatus.left().value();
2854 return changeInstanceVersion(containerComponent, currentResourceInstance, newComponentInstance, user, containerComponentType);
2857 public ComponentInstance changeInstanceVersion(org.openecomp.sdc.be.model.Component containerComponent,
2858 ComponentInstance currentResourceInstance,
2859 ComponentInstance newComponentInstance,
2861 final ComponentTypeEnum containerComponentType) {
2862 boolean failed = false;
2863 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus;
2866 lockComponent(containerComponent, "changeComponentInstanceVersion");
2867 String containerComponentId = containerComponent.getUniqueId();
2868 String componentInstanceId = currentResourceInstance.getUniqueId();
2869 if (currentResourceInstance.getComponentUid().equals(newComponentInstance.getComponentUid())) {
2870 return currentResourceInstance;
2872 String resourceId = newComponentInstance.getComponentUid();
2874 Either<Boolean, StorageOperationStatus> componentExistsRes = toscaOperationFacade
2875 .validateComponentExists(resourceId);
2876 if (componentExistsRes.isRight()) {
2877 StorageOperationStatus errorStatus = componentExistsRes.right().value();
2879 log.debug("Failed to validate existing of the component {}. Status is {} ", resourceId, errorStatus);
2880 throw new ByActionStatusComponentException(
2881 componentsUtils.convertFromStorageResponse(errorStatus), resourceId);
2882 } else if (!Boolean.TRUE.equals(componentExistsRes.left().value())) {
2883 log.debug("The resource {} not found ", resourceId);
2884 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_NOT_FOUND, resourceId);
2887 Component eitherOriginComponent = getInstanceOriginNode(currentResourceInstance);
2888 DataForMergeHolder dataHolder = compInstMergeDataBL
2889 .saveAllDataBeforeDeleting(containerComponent, currentResourceInstance, eitherOriginComponent);
2890 ComponentInstance resResourceInfo = deleteComponentInstance(containerComponent, componentInstanceId,
2891 containerComponentType);
2893 if (resResourceInfo == null) {
2894 log.error("Calling `deleteComponentInstance` for the resource {} returned a null", resourceId);
2895 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_NOT_FOUND, resourceId);
2897 Component origComponent = null;
2898 OriginTypeEnum originType = currentResourceInstance.getOriginType();
2899 newComponentInstance.setOriginType(originType);
2900 if (originType == OriginTypeEnum.ServiceProxy) {
2901 Either<Component, StorageOperationStatus> serviceProxyOrigin = toscaOperationFacade
2902 .getLatestByName(SERVICE_PROXY, null);
2903 if (isServiceProxyOrigin(serviceProxyOrigin)) {
2904 throw new ByActionStatusComponentException(
2905 componentsUtils.convertFromStorageResponse(serviceProxyOrigin.right().value()));
2907 origComponent = serviceProxyOrigin.left().value();
2909 StorageOperationStatus fillProxyRes = fillInstanceData(newComponentInstance, origComponent);
2911 if (isFillProxyRes(fillProxyRes)) {
2912 throw new ByActionStatusComponentException(
2913 componentsUtils.convertFromStorageResponse(fillProxyRes));
2915 } else if (originType == OriginTypeEnum.ServiceSubstitution) {
2916 final Either<Component, StorageOperationStatus> getServiceResult = toscaOperationFacade
2917 .getToscaFullElement(newComponentInstance.getComponentUid());
2918 if (getServiceResult.isRight()) {
2919 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(getServiceResult.right().value()));
2921 final Component service = getServiceResult.left().value();
2923 final Either<Component, StorageOperationStatus> getServiceDerivedFromTypeResult = toscaOperationFacade
2924 .getLatestByToscaResourceName(service.getDerivedFromGenericType(), service.getModel());
2925 if (getServiceDerivedFromTypeResult.isRight()) {
2926 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(getServiceResult.right().value()));
2929 origComponent = getServiceDerivedFromTypeResult.left().value();
2931 final StorageOperationStatus fillProxyRes = fillInstanceData(newComponentInstance, origComponent);
2932 if (isFillProxyRes(fillProxyRes)) {
2933 throw new ByActionStatusComponentException(
2934 componentsUtils.convertFromStorageResponse(fillProxyRes));
2937 origComponent = getOriginComponentFromComponentInstance(newComponentInstance);
2938 newComponentInstance.setName(resResourceInfo.getName());
2939 final Either<Component, StorageOperationStatus> getComponentRes = toscaOperationFacade
2940 .getToscaFullElement(newComponentInstance.getComponentUid());
2941 if (getComponentRes.isRight()) {
2942 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(getComponentRes.right().value()));
2944 final Component component = getComponentRes.left().value();
2945 final Map<String, InterfaceDefinition> componentInterfaces = component.getInterfaces();
2946 if (MapUtils.isNotEmpty(componentInterfaces)) {
2947 componentInterfaces.forEach(newComponentInstance::addInterface);
2951 newComponentInstance.setInvariantName(resResourceInfo.getInvariantName());
2952 newComponentInstance.setPosX(resResourceInfo.getPosX());
2953 newComponentInstance.setPosY(resResourceInfo.getPosY());
2954 newComponentInstance.setDescription(resResourceInfo.getDescription());
2955 newComponentInstance.setInstanceCount(resResourceInfo.getInstanceCount());
2956 newComponentInstance.setMaxOccurrences(resResourceInfo.getMaxOccurrences());
2957 newComponentInstance.setMinOccurrences(resResourceInfo.getMinOccurrences());
2958 checkForExternalReqAndCapabilities(origComponent, resResourceInfo);
2960 ComponentInstance updatedComponentInstance =
2961 createComponentInstanceOnGraph(containerComponent, origComponent, newComponentInstance, user);
2962 dataHolder.setCurrInstanceNode(origComponent);
2964 .mergeComponentUserOrigData(user, dataHolder, containerComponent, containerComponentId, newComponentInstance.getUniqueId());
2966 ActionStatus postChangeVersionResult = onChangeInstanceOperationOrchestrator
2967 .doPostChangeVersionOperations(containerComponent, currentResourceInstance, newComponentInstance);
2968 if (postChangeVersionResult != ActionStatus.OK) {
2969 throw new ByActionStatusComponentException(postChangeVersionResult);
2972 ComponentParametersView filter = new ComponentParametersView(true);
2973 filter.setIgnoreComponentInstances(false);
2974 Either<Component, StorageOperationStatus> updatedComponentRes = toscaOperationFacade.getToscaElement(containerComponentId, filter);
2975 if (updatedComponentRes.isRight()) {
2976 StorageOperationStatus storageOperationStatus = updatedComponentRes.right().value();
2977 ActionStatus actionStatus = componentsUtils
2978 .convertFromStorageResponse(storageOperationStatus, containerComponent.getComponentType());
2979 log.debug("Component with id {} was not found", containerComponentId);
2980 throw new ByActionStatusComponentException(actionStatus, Constants.EMPTY_STRING);
2982 resourceInstanceStatus = getResourceInstanceById(updatedComponentRes.left().value(),
2983 updatedComponentInstance.getUniqueId());
2984 if (resourceInstanceStatus.isRight()) {
2985 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse
2986 (resourceInstanceStatus.right().value()), updatedComponentInstance.getUniqueId());
2988 return resourceInstanceStatus.left().value();
2990 } catch (ComponentException e) {
2994 unlockComponent(failed, containerComponent);
2998 private void checkForExternalReqAndCapabilities(Component component, ComponentInstance resResourceInfo) {
2999 Map<String, List<RequirementDefinition>> requirementsMap = resResourceInfo.getRequirements();
3000 Map<String, List<RequirementDefinition>> externalRequirementsMap = new HashMap<>();
3001 List<RequirementDefinition> externalRequirementList = new ArrayList<>();
3002 if (requirementsMap != null && !requirementsMap.isEmpty()) {
3003 requirementsMap.forEach((type, requirementDefinitions) -> {
3004 if (requirementDefinitions != null && !requirementDefinitions.isEmpty()) {
3005 for (final RequirementDefinition requirementDefinition : requirementDefinitions) {
3006 if (requirementDefinition.isExternal()) {
3007 externalRequirementList.add(requirementDefinition);
3008 externalRequirementsMap.put(type, externalRequirementList);
3015 Map<String, List<CapabilityDefinition>> capabilitiesMap = resResourceInfo.getCapabilities();
3016 Map<String, List<CapabilityDefinition>> externalCapabilitiesMap = new HashMap<>();
3017 List<CapabilityDefinition> externalCapabilitiesList = new ArrayList<>();
3018 if (capabilitiesMap != null && !capabilitiesMap.isEmpty()) {
3019 capabilitiesMap.forEach((type, capabilityDefinitions) -> {
3020 if (capabilityDefinitions != null && !capabilityDefinitions.isEmpty()) {
3021 for (final CapabilityDefinition capabilityDefinition : capabilityDefinitions) {
3022 if (capabilityDefinition.isExternal()) {
3023 externalCapabilitiesList.add(capabilityDefinition);
3024 externalCapabilitiesMap.put(type, externalCapabilitiesList);
3030 component.setCapabilities(externalCapabilitiesMap);
3031 component.setRequirements(externalRequirementsMap);
3034 private boolean isFillProxyRes(StorageOperationStatus fillProxyRes) {
3035 if (fillProxyRes != StorageOperationStatus.OK) {
3036 log.debug("Failed to fill service proxy resource data with data from service, error {}", fillProxyRes);
3043 public List<ComponentInstanceProperty> getComponentInstancePropertiesById(String containerComponentTypeParam, String containerComponentId,
3044 String componentInstanceUniqueId, String userId) {
3045 Component containerComponent = null;
3047 boolean failed = false;
3049 validateUserExists(userId);
3050 validateComponentType(containerComponentTypeParam);
3052 Either<Component, StorageOperationStatus> validateContainerComponentExists = toscaOperationFacade.getToscaElement(containerComponentId);
3053 if (validateContainerComponentExists.isRight()) {
3054 throw new ByActionStatusComponentException(
3055 componentsUtils.convertFromStorageResponse(validateContainerComponentExists.right().value()));
3057 containerComponent = validateContainerComponentExists.left().value();
3059 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent,
3060 componentInstanceUniqueId);
3061 if (resourceInstanceStatus.isRight()) {
3062 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId,
3063 containerComponentId);
3066 List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties().get(componentInstanceUniqueId);
3067 if (CollectionUtils.isEmpty(instanceProperties)) {
3068 instanceProperties = new ArrayList<>();
3070 return instanceProperties;
3071 } catch (ComponentException e) {
3075 unlockComponent(failed, containerComponent);
3079 public List<ComponentInstanceAttribute> getComponentInstanceAttributesById(final String containerComponentTypeParam,
3080 final String containerComponentId,
3081 final String componentInstanceUniqueId,
3082 final String userId) {
3083 Component containerComponent = null;
3085 boolean failed = false;
3087 validateUserExists(userId);
3088 validateComponentType(containerComponentTypeParam);
3090 final Either<Component, StorageOperationStatus> validateContainerComponentExists =
3091 toscaOperationFacade.getToscaElement(containerComponentId);
3092 if (validateContainerComponentExists.isRight()) {
3093 throw new ByActionStatusComponentException(
3094 componentsUtils.convertFromStorageResponse(validateContainerComponentExists.right().value()));
3096 containerComponent = validateContainerComponentExists.left().value();
3098 if (getResourceInstanceById(containerComponent, componentInstanceUniqueId).isRight()) {
3099 throw new ByActionStatusComponentException(
3100 ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId);
3103 final Map<String, List<ComponentInstanceAttribute>> componentInstancesAttributes = containerComponent.getComponentInstancesAttributes();
3104 return componentInstancesAttributes == null ? new ArrayList<>()
3105 : componentInstancesAttributes.getOrDefault(componentInstanceUniqueId, new ArrayList<>());
3106 } catch (final ComponentException e) {
3110 unlockComponent(failed, containerComponent);
3114 protected void validateIncrementCounter(String resourceInstanceId, GraphPropertiesDictionary counterType,
3115 Wrapper<Integer> instaceCounterWrapper,
3116 Wrapper<ResponseFormat> errorWrapper) {
3117 Either<Integer, StorageOperationStatus> counterRes = componentInstanceOperation
3118 .increaseAndGetResourceInstanceSpecificCounter(resourceInstanceId, counterType, true);
3120 if (counterRes.isRight()) {
3121 log.debug("increase And Get {} failed resource instance {}", counterType, resourceInstanceId);
3122 StorageOperationStatus status = counterRes.right().value();
3123 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
3124 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus));
3126 instaceCounterWrapper.setInnerElement(counterRes.left().value());
3132 * updates componentInstance modificationTime
3134 * @param componentInstance
3135 * @param componentInstanceType
3136 * @param modificationTime
3137 * @param inTransaction
3140 public Either<ComponentInstanceData, ResponseFormat> updateComponentInstanceModificationTimeAndCustomizationUuid(
3141 ComponentInstance componentInstance, NodeTypeEnum componentInstanceType, Long modificationTime, boolean inTransaction) {
3142 Either<ComponentInstanceData, ResponseFormat> result;
3143 Either<ComponentInstanceData, StorageOperationStatus> updateComponentInstanceRes = componentInstanceOperation
3144 .updateComponentInstanceModificationTimeAndCustomizationUuidOnGraph(componentInstance, componentInstanceType, modificationTime,
3146 if (updateComponentInstanceRes.isRight()) {
3147 log.debug("Failed to update component instance {} with new last update date and mofifier. Status is {}. ", componentInstance.getName(),
3148 updateComponentInstanceRes.right().value());
3150 .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateComponentInstanceRes.right().value())));
3152 result = Either.left(updateComponentInstanceRes.left().value());
3157 public Either<ComponentInstance, ResponseFormat> deleteServiceProxy() {
3158 // TODO Add implementation
3159 return Either.left(new ComponentInstance());
3162 public Either<ComponentInstance, ResponseFormat> createServiceProxy() {
3163 // TODO Add implementation
3164 return Either.left(new ComponentInstance());
3167 public Either<ComponentInstance, ResponseFormat> changeServiceProxyVersion() {
3168 // TODO Add implementation
3169 return Either.left(new ComponentInstance());
3172 private Boolean validateInstanceNameUniquenessUponUpdate(Component containerComponent, ComponentInstance oldComponentInstance,
3173 String newInstanceName) {
3174 return ComponentValidations.validateNameIsUniqueInComponent(oldComponentInstance.getName(), newInstanceName, containerComponent);
3177 private Either<ComponentInstance, StorageOperationStatus> getResourceInstanceById(final Component containerComponent, final String instanceId) {
3178 final List<ComponentInstance> instances = containerComponent.getComponentInstances();
3179 if (CollectionUtils.isEmpty(instances)) {
3180 return Either.right(StorageOperationStatus.NOT_FOUND);
3183 final Optional<ComponentInstance> foundInstance = instances.stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst();
3184 if (foundInstance.isEmpty()) {
3185 return Either.right(StorageOperationStatus.NOT_FOUND);
3188 return Either.left(foundInstance.get());
3191 private ComponentInstance buildComponentInstance(ComponentInstance resourceInstanceForUpdate, ComponentInstance origInstanceForUpdate) {
3192 Long creationDate = origInstanceForUpdate.getCreationTime();
3193 Long modificationTime = System.currentTimeMillis();
3194 resourceInstanceForUpdate.setCreationTime(creationDate);
3195 resourceInstanceForUpdate.setModificationTime(modificationTime);
3196 resourceInstanceForUpdate.setCustomizationUUID(origInstanceForUpdate.getCustomizationUUID());
3197 if (StringUtils.isEmpty(resourceInstanceForUpdate.getName()) && StringUtils.isNotEmpty(origInstanceForUpdate.getName())) {
3198 resourceInstanceForUpdate.setName(origInstanceForUpdate.getName());
3200 resourceInstanceForUpdate.setNormalizedName(ValidationUtils.normalizeComponentInstanceName(resourceInstanceForUpdate.getName()));
3201 if (StringUtils.isEmpty(resourceInstanceForUpdate.getIcon())) {
3202 resourceInstanceForUpdate.setIcon(origInstanceForUpdate.getIcon());
3204 if (StringUtils.isEmpty(resourceInstanceForUpdate.getComponentVersion())) {
3205 resourceInstanceForUpdate.setComponentVersion(origInstanceForUpdate.getComponentVersion());
3207 if (StringUtils.isEmpty(resourceInstanceForUpdate.getComponentName())) {
3208 resourceInstanceForUpdate.setComponentName(origInstanceForUpdate.getComponentName());
3210 if (StringUtils.isEmpty(resourceInstanceForUpdate.getToscaComponentName())) {
3211 resourceInstanceForUpdate.setToscaComponentName(origInstanceForUpdate.getToscaComponentName());
3213 if (resourceInstanceForUpdate.getOriginType() == null) {
3214 resourceInstanceForUpdate.setOriginType(origInstanceForUpdate.getOriginType());
3216 if (resourceInstanceForUpdate.getOriginType() == OriginTypeEnum.ServiceProxy) {
3217 resourceInstanceForUpdate.setIsProxy(true);
3219 if (resourceInstanceForUpdate.getSourceModelInvariant() == null) {
3220 resourceInstanceForUpdate.setSourceModelInvariant(origInstanceForUpdate.getSourceModelInvariant());
3222 if (resourceInstanceForUpdate.getSourceModelName() == null) {
3223 resourceInstanceForUpdate.setSourceModelName(origInstanceForUpdate.getSourceModelName());
3225 if (resourceInstanceForUpdate.getSourceModelUuid() == null) {
3226 resourceInstanceForUpdate.setSourceModelUuid(origInstanceForUpdate.getSourceModelUuid());
3228 if (resourceInstanceForUpdate.getSourceModelUid() == null) {
3229 resourceInstanceForUpdate.setSourceModelUid(origInstanceForUpdate.getSourceModelUid());
3231 if (resourceInstanceForUpdate.getCreatedFrom() == null) {
3232 resourceInstanceForUpdate.setCreatedFrom(origInstanceForUpdate.getCreatedFrom());
3234 return resourceInstanceForUpdate;
3238 * Returns list of ComponentInstanceProperty belonging to component instance capability specified by name, type and ownerId
3240 * @param containerComponentType
3241 * @param containerComponentId
3242 * @param componentInstanceUniqueId
3243 * @param capabilityType
3244 * @param capabilityName
3249 public List<ComponentInstanceProperty> getComponentInstanceCapabilityPropertiesById(String containerComponentType, String containerComponentId,
3250 String componentInstanceUniqueId, String capabilityType,
3251 String capabilityName, String ownerId, String userId) {
3252 Component containerComponent = null;
3253 List<ComponentInstanceProperty> resultOp = null;
3255 validateUserExists(userId);
3256 validateComponentType(containerComponentType);
3257 containerComponent = toscaOperationFacade.getToscaFullElement(containerComponentId).left().on(this::componentException);
3258 ComponentInstance resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId).left()
3259 .on(this::componentInstanceException);
3260 resultOp = findCapabilityOfInstance(containerComponentId, componentInstanceUniqueId, capabilityType, capabilityName, ownerId,
3261 resourceInstanceStatus.getCapabilities());
3262 } catch (StorageException | ComponentException e) {
3263 unlockRollbackWithException(containerComponent, e);
3264 } catch (Exception e) {
3265 unlockRollbackWithException(containerComponent, new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR));
3267 unlockWithCommit(containerComponent);
3271 private List<ComponentInstanceProperty> findCapabilityOfInstance(String componentId, String instanceId, String capabilityType,
3272 String capabilityName, String ownerId,
3273 Map<String, List<CapabilityDefinition>> instanceCapabilities) {
3274 CapabilityDefinition foundCapability;
3275 if (MapUtils.isNotEmpty(instanceCapabilities)) {
3276 List<CapabilityDefinition> capabilitiesPerType = instanceCapabilities.get(capabilityType);
3277 if (capabilitiesPerType != null) {
3278 Optional<CapabilityDefinition> capabilityOpt = capabilitiesPerType.stream()
3279 .filter(c -> c.getName().equals(capabilityName) && c.getOwnerId().equals(ownerId)).findFirst();
3280 if (capabilityOpt.isPresent()) {
3281 foundCapability = capabilityOpt.get();
3282 return foundCapability.getProperties() == null ? new ArrayList<>() : foundCapability.getProperties();
3286 return fetchComponentInstanceCapabilityProperties(componentId, instanceId, capabilityType, capabilityName, ownerId);
3289 private List<ComponentInstanceProperty> fetchComponentInstanceCapabilityProperties(String componentId, String instanceId, String capabilityType,
3290 String capabilityName, String ownerId) {
3292 return toscaOperationFacade.getComponentInstanceCapabilityProperties(componentId, instanceId, capabilityName, capabilityType, ownerId)
3293 .left().on(this::componentInstancePropertyListException);
3294 } catch (Exception e) {
3295 log.debug("The exception {} occurred upon the component {} instance {} capability {} properties retrieving. ", componentId, instanceId,
3297 throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
3301 public Either<RequirementDefinition, ResponseFormat> updateInstanceRequirement(ComponentTypeEnum componentTypeEnum, String containerComponentId,
3302 String componentInstanceUniqueId,
3303 RequirementDefinition requirementDef, String userId) {
3304 Either<RequirementDefinition, ResponseFormat> resultOp = null;
3305 validateUserExists(userId);
3306 if (componentTypeEnum == null) {
3307 BeEcompErrorManager.getInstance().logInvalidInputError("updateInstanceRequirement", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
3308 return Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
3310 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaFullElement(containerComponentId);
3311 if (getResourceResult.isRight()) {
3312 log.debug(FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID, containerComponentId);
3313 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
3315 Component containerComponent = getResourceResult.left().value();
3316 if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
3317 log.info(RESTRICTED_OPERATION_ON_COMPONENT, userId, containerComponentId);
3318 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
3320 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent,
3321 componentInstanceUniqueId);
3322 if (resourceInstanceStatus.isRight()) {
3323 return Either.right(componentsUtils
3324 .getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
3327 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(containerComponentId, componentTypeEnum.getNodeType());
3328 if (lockStatus != StorageOperationStatus.OK) {
3329 log.debug(FAILED_TO_LOCK_COMPONENT, containerComponentId);
3330 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
3333 StorageOperationStatus updateRequirementStatus = toscaOperationFacade
3334 .updateComponentInstanceRequirement(containerComponentId, componentInstanceUniqueId, requirementDef);
3335 if (updateRequirementStatus != StorageOperationStatus.OK) {
3336 log.debug("Failed to update component instance requirement on instance {} in container {}", componentInstanceUniqueId,
3337 containerComponentId);
3338 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateRequirementStatus)));
3340 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade
3341 .updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
3342 if (updateContainerRes.isRight()) {
3343 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
3344 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
3347 resultOp = Either.left(requirementDef);
3350 if (resultOp == null || resultOp.isRight()) {
3351 janusGraphDao.rollback();
3353 janusGraphDao.commit();
3356 graphLockOperation.unlockComponent(containerComponentId, componentTypeEnum.getNodeType());
3360 public Either<CapabilityDefinition, ResponseFormat> updateInstanceCapability(final ComponentTypeEnum containerComponentType,
3361 final String containerComponentId,
3362 final String componentInstanceUniqueId,
3363 final CapabilityDefinition capabilityDefinition,
3364 final String userId) {
3365 if (containerComponentType == null) {
3366 BeEcompErrorManager.getInstance().logInvalidInputError("updateInstanceCapability", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
3367 return Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
3369 validateUserExists(userId);
3370 final Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaFullElement(containerComponentId);
3371 if (getResourceResult.isRight()) {
3372 log.debug(FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID, containerComponentId);
3373 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NOT_FOUND, containerComponentId));
3375 final Component containerComponent = getResourceResult.left().value();
3376 if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
3377 log.info(RESTRICTED_OPERATION_ON_COMPONENT, userId, containerComponentId);
3378 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
3380 final Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus =
3381 getResourceInstanceById(containerComponent, componentInstanceUniqueId);
3382 if (resourceInstanceStatus.isRight()) {
3383 return Either.right(componentsUtils
3384 .getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
3387 final StorageOperationStatus lockStatus = graphLockOperation.lockComponent(containerComponentId, containerComponentType.getNodeType());
3388 if (lockStatus != StorageOperationStatus.OK) {
3389 log.debug(FAILED_TO_LOCK_COMPONENT, containerComponentId);
3390 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
3392 var success = false;
3394 final CapabilityDataDefinition updatedCapabilityDefinition = toscaOperationFacade
3395 .updateComponentInstanceCapability(containerComponentId, componentInstanceUniqueId, capabilityDefinition);
3396 final Either<Component, StorageOperationStatus> updateContainerEither = toscaOperationFacade
3397 .updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
3398 if (updateContainerEither.isRight()) {
3399 var actionStatus = componentsUtils.convertFromStorageResponse(updateContainerEither.right().value(), containerComponentType);
3400 return Either.right(componentsUtils.getResponseFormat(actionStatus));
3403 return Either.left(new CapabilityDefinition(updatedCapabilityDefinition));
3404 } catch (final BusinessException e) {
3405 log.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, NodeTemplateOperation.class.getName(), (ErrorLogOptionalData) null,
3406 FAILED_TO_UPDATE_COMPONENT_INSTANCE_CAPABILITY, componentInstanceUniqueId, containerComponentId);
3408 } catch (final Exception e) {
3409 log.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, NodeTemplateOperation.class.getName(), (ErrorLogOptionalData) null,
3410 FAILED_TO_UPDATE_COMPONENT_INSTANCE_CAPABILITY, componentInstanceUniqueId, containerComponentId);
3411 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
3414 janusGraphDao.commit();
3416 janusGraphDao.rollback();
3419 graphLockOperation.unlockComponent(containerComponentId, containerComponentType.getNodeType());
3423 public Either<List<ComponentInstanceProperty>, ResponseFormat> updateInstanceCapabilityProperties(ComponentTypeEnum componentTypeEnum,
3424 String containerComponentId,
3425 String componentInstanceUniqueId,
3426 String capabilityType, String capabilityName,
3427 List<ComponentInstanceProperty> properties,
3429 Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
3430 validateUserExists(userId);
3431 if (componentTypeEnum == null) {
3432 BeEcompErrorManager.getInstance().logInvalidInputError("updateInstanceCapabilityProperty", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
3433 return Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
3435 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaFullElement(containerComponentId);
3436 if (getResourceResult.isRight()) {
3437 log.debug(FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID, containerComponentId);
3438 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
3440 Component containerComponent = getResourceResult.left().value();
3441 if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
3442 log.info(RESTRICTED_OPERATION_ON_COMPONENT, userId, containerComponentId);
3443 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
3445 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent,
3446 componentInstanceUniqueId);
3447 if (resourceInstanceStatus.isRight()) {
3448 return Either.right(componentsUtils
3449 .getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
3451 ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
3453 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(containerComponentId, componentTypeEnum.getNodeType());
3454 if (lockStatus != StorageOperationStatus.OK) {
3455 log.debug(FAILED_TO_LOCK_COMPONENT, containerComponentId);
3456 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
3459 for (ComponentInstanceProperty property : properties) {
3460 Either<String, ResponseFormat> newPropertyValueEither = validatePropertyObjectValue(property, property.getValue(), false);
3461 newPropertyValueEither.bimap(
3462 updatedValue -> updateCapabilityPropertyOnContainerComponent(property, updatedValue, containerComponent, foundResourceInstance,
3463 capabilityType, capabilityName), Either::right);
3465 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade
3466 .updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
3467 if (updateContainerRes.isRight()) {
3468 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
3469 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
3472 resultOp = Either.left(properties);
3475 if (resultOp == null || resultOp.isRight()) {
3476 janusGraphDao.rollback();
3478 janusGraphDao.commit();
3481 graphLockOperation.unlockComponent(containerComponentId, componentTypeEnum.getNodeType());
3485 public Either<Map<String, ComponentInstance>, ResponseFormat> copyComponentInstance(ComponentInstance inputComponentInstance,
3486 String containerComponentId, String componentInstanceId,
3488 Map<String, ComponentInstance> resultMap = new HashMap<>();
3489 Either<Component, StorageOperationStatus> getOrigComponent = toscaOperationFacade.getToscaElement(containerComponentId);
3490 if (getOrigComponent.isRight()) {
3491 log.error("Failed to get the original component information");
3492 return Either.right(componentsUtils.getResponseFormat(ActionStatus.USER_DEFINED, FAILED_TO_COPY_COMP_INSTANCE_TO_CANVAS));
3494 Component origComponent = getOrigComponent.left().value();
3496 lockComponent(origComponent, "copyComponentInstance");
3497 } catch (ComponentException e) {
3498 log.error("destComponentInstance's data is {}", origComponent.toString());
3499 return Either.right(componentsUtils
3500 .getResponseFormat(ActionStatus.USER_DEFINED, "Failed to lock component destComponentInstance's data is {}",
3501 origComponent.toString()));
3503 boolean failed = false;
3504 ComponentInstance actionResponse = null;
3506 actionResponse = createComponentInstance("services", containerComponentId, userId, inputComponentInstance, false);
3507 } catch (ComponentException e) {
3509 // on failure of the create instance unlock the resource and rollback the transaction.
3510 return Either.right(componentsUtils.getResponseFormat(ActionStatus.USER_DEFINED, FAILED_TO_COPY_COMP_INSTANCE_TO_CANVAS));
3512 // on failure of the create instance unlock the resource and rollback the transaction.
3513 if (null == actionResponse) {
3514 log.error(FAILED_TO_COPY_COMP_INSTANCE_TO_CANVAS);
3515 unlockComponent(failed, origComponent);
3518 Either<String, ResponseFormat> resultOp = null;
3520 ComponentInstance destComponentInstance = actionResponse;
3521 log.debug("destComponentInstance's data is {}", destComponentInstance);
3522 resultOp = deepCopyComponentInstance(origComponent, containerComponentId, componentInstanceId, destComponentInstance, userId);
3523 resultMap.put("componentInstance", destComponentInstance);
3526 if (resultOp == null || resultOp.isRight()) {
3527 unlockComponent(true, origComponent);
3528 janusGraphDao.rollback();
3529 log.error("Failed to deep copy component instance");
3531 unlockComponent(false, origComponent);
3532 janusGraphDao.commit();
3533 log.debug("Success trasaction commit");
3536 if (resultOp == null || resultOp.isRight()) {
3538 .right(componentsUtils.getResponseFormat(ActionStatus.USER_DEFINED, "Failed to deep copy the component instance to the canvas"));
3540 return Either.left(resultMap);
3544 private Either<String, ResponseFormat> deepCopyComponentInstance(Component sourceComponent, String containerComponentId,
3545 String sourceComponentInstanceId, ComponentInstance destComponentInstance,
3547 Either<Component, StorageOperationStatus> getDestComponent = toscaOperationFacade.getToscaElement(containerComponentId);
3548 if (getDestComponent.isRight()) {
3549 log.error("Failed to get the dest component information");
3550 return Either.right(componentsUtils.getResponseFormat(ActionStatus.USER_DEFINED, FAILED_TO_COPY_COMP_INSTANCE_TO_CANVAS));
3552 Component destComponent = getDestComponent.left().value();
3553 Either<String, ResponseFormat> copyComponentInstanceWithPropertiesAndInputs = copyComponentInstanceWithPropertiesAndInputs(sourceComponent,
3554 destComponent, sourceComponentInstanceId, destComponentInstance);
3555 if (copyComponentInstanceWithPropertiesAndInputs.isRight()) {
3556 log.error("Failed to copy component instance with properties and inputs as part of deep copy");
3557 return Either.right(componentsUtils.getResponseFormat(ActionStatus.USER_DEFINED,
3558 "Failed to copy the component instance with properties and inputs as part of deep copy"));
3560 Either<String, ResponseFormat> copyComponentInstanceWithAttributes = copyComponentInstanceWithAttributes(sourceComponent, destComponent,
3561 sourceComponentInstanceId, destComponentInstance, userId);
3562 if (copyComponentInstanceWithAttributes.isRight()) {
3563 log.error("Failed to copy component instance with attributes as part of deep copy");
3564 return Either.right(componentsUtils
3565 .getResponseFormat(ActionStatus.USER_DEFINED, "Failed to copy the component instance with attributes as part of deep copy"));
3567 return Either.left(COPY_COMPONENT_INSTANCE_OK);
3570 private Either<String, ResponseFormat> copyComponentInstanceWithPropertiesAndInputs(Component sourceComponent, Component destComponent,
3571 String sourceComponentInstanceId,
3572 ComponentInstance destComponentInstance) {
3573 log.debug("start to copy ComponentInstance with properties and inputs");
3574 List<ComponentInstanceProperty> sourcePropList = null;
3575 if (sourceComponent.getComponentInstancesProperties() != null
3576 && sourceComponent.getComponentInstancesProperties().get(sourceComponentInstanceId) != null) {
3577 sourcePropList = sourceComponent.getComponentInstancesProperties().get(sourceComponentInstanceId);
3578 log.debug("sourcePropList");
3580 List<ComponentInstanceProperty> destPropList = null;
3581 String destComponentInstanceId = destComponentInstance.getUniqueId();
3582 log.debug("destComponentInstanceId: {}", destComponentInstance.getUniqueId());
3583 if (destComponent.getComponentInstancesProperties() != null
3584 && destComponent.getComponentInstancesProperties().get(destComponentInstanceId) != null) {
3585 destPropList = destComponent.getComponentInstancesProperties().get(destComponentInstanceId);
3586 log.debug("destPropList {}");
3588 List<ComponentInstancePropInput> componentInstancePropInputList = new ArrayList<>();
3589 if (null != destPropList && null != sourcePropList) {
3590 log.debug("start to set property and attribute");
3591 for (ComponentInstanceProperty destProp : destPropList) {
3592 String destPropertyName = destProp.getName();
3593 for (ComponentInstanceProperty sourceProp : sourcePropList) {
3594 if (!destPropertyName.equals(sourceProp.getName())) {
3597 log.debug("now set property");
3598 final List<GetInputValueDataDefinition> getInputValues = sourceProp.getGetInputValues();
3599 if (getInputValues == null && !StringUtils.isEmpty(sourceProp.getValue()) && (destProp.getValue() == null || !destProp.getValue()
3600 .equals(sourceProp.getValue()))) {
3601 log.debug("Now starting to copy the property {} in value {}", destPropertyName, sourceProp.getValue());
3602 destProp.setValue(sourceProp.getValue());
3603 Either<String, ResponseFormat> updatePropertyValueEither = updateComponentInstanceProperty(destComponent.getUniqueId(),
3604 destComponentInstanceId, destProp);
3605 if (updatePropertyValueEither.isRight()) {
3606 log.error("Failed to copy the property {}", destPropertyName);
3607 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM,
3608 "Failed to paste component instance to the canvas, property copy"));
3612 log.debug("Now start to update inputs");
3613 if (getInputValues != null) {
3614 if (getInputValues.isEmpty()) {
3615 log.debug("property is return from input, set by man");
3618 log.debug("Now starting to copy the {} property", destPropertyName);
3619 Either<String, ResponseFormat> getSourceInputDefaultValue = getInputListDefaultValue(sourceComponent,
3620 getInputValues.get(0).getInputId());
3621 if (getSourceInputDefaultValue.isRight()) {
3622 return Either.right(getSourceInputDefaultValue.right().value());
3624 componentInstancePropInputList.add(new ComponentInstancePropInput(destProp));
3629 return Either.left(COPY_COMPONENT_INSTANCE_OK);
3632 private Either<String, ResponseFormat> copyComponentInstanceWithAttributes(Component sourceComponent, Component destComponent,
3633 String sourceComponentInstanceId,
3634 ComponentInstance destComponentInstance, String userId) {
3635 String destComponentInstanceId = destComponentInstance.getUniqueId();
3636 log.info("start to copy component instance with attributes");
3637 List<ComponentInstanceAttribute> sourceAttributeList = null;
3638 if (sourceComponent.getComponentInstancesAttributes() != null
3639 && sourceComponent.getComponentInstancesAttributes().get(sourceComponentInstanceId) != null) {
3640 sourceAttributeList = sourceComponent.getComponentInstancesAttributes().get(sourceComponentInstanceId);
3641 log.info("sourceAttributes {}");
3643 List<ComponentInstanceAttribute> destAttributeList = null;
3644 if (destComponent.getComponentInstancesAttributes() != null
3645 && destComponent.getComponentInstancesAttributes().get(destComponentInstanceId) != null) {
3646 destAttributeList = destComponent.getComponentInstancesAttributes().get(destComponentInstanceId);
3647 log.info("destAttributeList {}");
3649 if (null != sourceAttributeList && null != destAttributeList) {
3650 log.info("set attribute");
3651 for (ComponentInstanceAttribute sourceAttribute : sourceAttributeList) {
3652 String sourceAttributeName = sourceAttribute.getName();
3653 for (ComponentInstanceAttribute destAttribute : destAttributeList) {
3654 if (sourceAttributeName.equals(destAttribute.getName())) {
3655 log.debug("Start to copy the attribute exists {}", sourceAttributeName);
3656 sourceAttribute.setUniqueId(
3657 UniqueIdBuilder.buildResourceInstanceUniuqeId("attribute", destComponentInstanceId.split("\\.")[1], sourceAttributeName));
3658 Either<ComponentInstanceAttribute, ResponseFormat> updateAttributeValueEither = createOrUpdateAttributeValueForCopyPaste(
3659 ComponentTypeEnum.SERVICE, destComponent.getUniqueId(), destComponentInstanceId, sourceAttribute, userId);
3660 if (updateAttributeValueEither.isRight()) {
3661 log.error("Failed to copy the attribute");
3662 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM,
3663 "Failed to paste component instance to the canvas, attribute copy"));
3670 return Either.left(COPY_COMPONENT_INSTANCE_OK);
3673 private Either<ComponentInstanceAttribute, ResponseFormat> createOrUpdateAttributeValueForCopyPaste(ComponentTypeEnum componentTypeEnum,
3674 String componentId, String resourceInstanceId,
3675 ComponentInstanceAttribute attribute,
3677 Either<ComponentInstanceAttribute, ResponseFormat> resultOp = null;
3678 validateUserExists(userId);
3679 if (componentTypeEnum == null) {
3680 BeEcompErrorManager.getInstance()
3681 .logInvalidInputError("createOrUpdateAttributeValueForCopyPaste", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
3682 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
3685 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
3686 if (getResourceResult.isRight()) {
3687 log.info("Failed to retrieve component id {}", componentId);
3688 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
3691 Component containerComponent = getResourceResult.left().value();
3692 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId);
3693 if (resourceInstanceStatus.isRight()) {
3695 .right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, resourceInstanceId, componentId));
3698 ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
3699 String propertyType = attribute.getType();
3700 ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
3701 log.info("The type of attribute id{},is {} ", attribute.getUniqueId(), propertyType);
3702 if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
3703 SchemaDefinition def = attribute.getSchema();
3705 log.info("Schema doesn't exists for attribute of type {}", type);
3707 .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
3709 PropertyDataDefinition propDef = def.getProperty();
3710 if (propDef == null) {
3711 log.info("Attribute in Schema Definition inside attribute of type {} doesn't exist", type);
3713 .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
3716 List<ComponentInstanceAttribute> instanceAttributes = containerComponent.getComponentInstancesAttributes().get(resourceInstanceId);
3717 Optional<ComponentInstanceAttribute> instanceAttribute = instanceAttributes.stream()
3718 .filter(p -> p.getUniqueId().equals(attribute.getUniqueId())).findAny();
3719 StorageOperationStatus status;
3720 if (instanceAttribute.isPresent()) {
3721 log.info("updateComponentInstanceAttribute");
3722 status = toscaOperationFacade.updateComponentInstanceAttribute(containerComponent, foundResourceInstance.getUniqueId(), attribute);
3724 log.info("addComponentInstanceAttribute");
3725 status = toscaOperationFacade.addComponentInstanceAttribute(containerComponent, foundResourceInstance.getUniqueId(), attribute);
3727 if (status != StorageOperationStatus.OK) {
3728 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
3729 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
3732 List<String> path = new ArrayList<>();
3733 path.add(foundResourceInstance.getUniqueId());
3734 attribute.setPath(path);
3735 foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
3736 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade
3737 .updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
3738 if (updateContainerRes.isRight()) {
3739 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
3740 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
3743 resultOp = Either.left(attribute);
3747 private Either<String, ResponseFormat> updateComponentInstanceProperty(String containerComponentId, String componentInstanceId,
3748 ComponentInstanceProperty property) {
3749 Either<String, ResponseFormat> resultOp;
3750 Either<Component, StorageOperationStatus> getComponent = toscaOperationFacade.getToscaElement(containerComponentId);
3751 if (getComponent.isRight()) {
3752 log.error("Failed to get the component information");
3753 return Either.right(componentsUtils
3754 .getResponseFormatForResourceInstanceProperty(ActionStatus.INVALID_CONTENT_PARAM, "Failed to get the component information"));
3756 Component containerComponent = getComponent.left().value();
3757 StorageOperationStatus status = toscaOperationFacade.updateComponentInstanceProperty(containerComponent, componentInstanceId, property);
3758 if (status != StorageOperationStatus.OK) {
3759 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
3760 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
3763 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade
3764 .updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
3765 if (updateContainerRes.isRight()) {
3766 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
3767 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
3770 return Either.left("Update OK");
3773 private Either<String, ResponseFormat> getInputListDefaultValue(Component component, String inputId) {
3774 List<InputDefinition> inputList = component.getInputs();
3775 for (InputDefinition input : inputList) {
3776 if (input.getUniqueId().equals(inputId)) {
3777 if (input.getDefaultValue() == null) {
3778 log.debug("The input's default value is null");
3779 return Either.left(null);
3781 return Either.left(input.getDefaultValue());
3784 log.error("The input's default value with id {} is not found", inputId);
3785 return Either.right(componentsUtils.getResponseFormat(ActionStatus.USER_DEFINED, "Failed to paste component instance to the canvas"));
3789 * Method to delete selected nodes and edges on composition page
3791 * @param containerComponentType
3792 * @param componentId
3793 * @param componentInstanceIdList
3797 public Map<String, List<String>> batchDeleteComponentInstance(String containerComponentType, String componentId,
3798 List<String> componentInstanceIdList, String userId) {
3799 List<String> deleteErrorIds = new ArrayList<>();
3800 Map<String, List<String>> deleteErrorMap = new HashMap<>();
3801 validateUserExists(userId);
3802 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(componentId,
3803 ComponentTypeEnum.findByParamName(containerComponentType), null);
3804 boolean failed = false;
3806 lockComponent(containerComponent, "batchDeleteComponentInstance");
3807 for (String eachInstanceId : componentInstanceIdList) {
3808 Either<ComponentInstance, ResponseFormat> actionResponse = batchDeleteComponentInstance(containerComponent, containerComponentType,
3810 log.debug("batchDeleteResourceInstances actionResponse is {}", actionResponse);
3811 if (actionResponse.isRight()) {
3812 log.error("Failed to delete ComponentInstance [{}]", eachInstanceId);
3813 deleteErrorIds.add(eachInstanceId);
3816 //sending the ids of the error nodes that were not deleted to UI
3817 deleteErrorMap.put("deleteFailedIds", deleteErrorIds);
3818 return deleteErrorMap;
3819 } catch (ComponentException e) {
3823 unlockComponent(failed, containerComponent);
3827 private Either<ComponentInstance, ResponseFormat> batchDeleteComponentInstance(Component containerComponent, String containerComponentType,
3828 String componentInstanceId) {
3829 ComponentInstance resultOp;
3830 final ComponentTypeEnum containerComponentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
3832 resultOp = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentTypeEnum);
3833 log.info("Successfully deleted instance with id {}", componentInstanceId);
3834 return Either.left(resultOp);
3835 } catch (ComponentException e) {
3836 log.error("Failed to deleteComponentInstance with instanceId[{}]", componentInstanceId);
3837 return Either.right(new ResponseFormat());
3841 public void validateUser(final String userId) {
3842 final User user = userValidations.validateUserExists(userId);
3843 userValidations.validateUserRole(user, Arrays.asList(Role.DESIGNER, Role.ADMIN));
3846 public void setCompositionBusinessLogic(CompositionBusinessLogic compositionBusinessLogic) {
3847 this.compositionBusinessLogic = compositionBusinessLogic;
3850 public void setContainerInstanceTypesData(ContainerInstanceTypesData containerInstanceTypesData) {
3851 this.containerInstanceTypesData = containerInstanceTypesData;