2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
20 package org.openecomp.sdc.be.components.impl;
22 import static org.openecomp.sdc.be.components.attribute.GetOutputUtils.isGetOutputValueForOutput;
23 import static org.openecomp.sdc.be.components.property.GetInputUtils.isGetInputValueForInput;
24 import static org.openecomp.sdc.be.components.utils.PropertiesUtils.getPropertyCapabilityOfChildInstance;
26 import com.google.common.collect.Sets;
27 import fj.data.Either;
28 import java.util.ArrayList;
29 import java.util.Arrays;
30 import java.util.Collection;
31 import java.util.Collections;
32 import java.util.HashMap;
33 import java.util.Iterator;
34 import java.util.List;
36 import java.util.Map.Entry;
37 import java.util.Objects;
38 import java.util.Optional;
40 import java.util.UUID;
41 import java.util.stream.Collectors;
42 import org.apache.commons.collections.CollectionUtils;
43 import org.apache.commons.collections.MapUtils;
44 import org.apache.commons.lang3.StringUtils;
45 import org.apache.commons.lang3.tuple.ImmutablePair;
46 import org.json.JSONObject;
47 import org.onap.sdc.tosca.datatypes.model.PropertyType;
48 import org.openecomp.sdc.be.components.impl.exceptions.BusinessLogicException;
49 import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
50 import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException;
51 import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
52 import org.openecomp.sdc.be.components.impl.exceptions.ToscaGetFunctionExceptionSupplier;
53 import org.openecomp.sdc.be.components.impl.instance.ComponentInstanceChangeOperationOrchestrator;
54 import org.openecomp.sdc.be.components.impl.utils.DirectivesUtil;
55 import org.openecomp.sdc.be.components.merge.instance.ComponentInstanceMergeDataBusinessLogic;
56 import org.openecomp.sdc.be.components.merge.instance.DataForMergeHolder;
57 import org.openecomp.sdc.be.components.utils.PropertiesUtils;
58 import org.openecomp.sdc.be.components.validation.ComponentValidations;
59 import org.openecomp.sdc.be.config.BeEcompErrorManager;
60 import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
61 import org.openecomp.sdc.be.config.ConfigurationManager;
62 import org.openecomp.sdc.be.dao.api.ActionStatus;
63 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
64 import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
65 import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
66 import org.openecomp.sdc.be.datamodel.utils.PropertyValueConstraintValidationUtil;
67 import org.openecomp.sdc.be.datatypes.elements.CINodeFilterDataDefinition;
68 import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition;
69 import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition;
70 import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition;
71 import org.openecomp.sdc.be.datatypes.elements.GetOutputValueDataDefinition;
72 import org.openecomp.sdc.be.datatypes.elements.GetPolicyValueDataDefinition;
73 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
74 import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition;
75 import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
76 import org.openecomp.sdc.be.datatypes.elements.ToscaGetFunctionDataDefinition;
77 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
78 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
79 import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
80 import org.openecomp.sdc.be.datatypes.enums.PropertySource;
81 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
82 import org.openecomp.sdc.be.datatypes.tosca.ToscaGetFunctionType;
83 import org.openecomp.sdc.be.exception.BusinessException;
84 import org.openecomp.sdc.be.impl.ComponentsUtils;
85 import org.openecomp.sdc.be.impl.ForwardingPathUtils;
86 import org.openecomp.sdc.be.impl.ServiceFilterUtils;
87 import org.openecomp.sdc.be.info.CreateAndAssotiateInfo;
88 import org.openecomp.sdc.be.model.ArtifactDefinition;
89 import org.openecomp.sdc.be.model.AttributeDefinition;
90 import org.openecomp.sdc.be.model.CapabilityDefinition;
91 import org.openecomp.sdc.be.model.Component;
92 import org.openecomp.sdc.be.model.ComponentInstance;
93 import org.openecomp.sdc.be.model.ComponentInstanceAttribute;
94 import org.openecomp.sdc.be.model.ComponentInstanceInput;
95 import org.openecomp.sdc.be.model.ComponentInstanceOutput;
96 import org.openecomp.sdc.be.model.ComponentInstancePropInput;
97 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
98 import org.openecomp.sdc.be.model.ComponentParametersView;
99 import org.openecomp.sdc.be.model.DataTypeDefinition;
100 import org.openecomp.sdc.be.model.GroupDefinition;
101 import org.openecomp.sdc.be.model.InputDefinition;
102 import org.openecomp.sdc.be.model.InterfaceDefinition;
103 import org.openecomp.sdc.be.model.LifecycleStateEnum;
104 import org.openecomp.sdc.be.model.OutputDefinition;
105 import org.openecomp.sdc.be.model.PolicyDefinition;
106 import org.openecomp.sdc.be.model.PropertyDefinition;
107 import org.openecomp.sdc.be.model.RelationshipInfo;
108 import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
109 import org.openecomp.sdc.be.model.RequirementDefinition;
110 import org.openecomp.sdc.be.model.Resource;
111 import org.openecomp.sdc.be.model.Service;
112 import org.openecomp.sdc.be.model.ToscaPropertyData;
113 import org.openecomp.sdc.be.model.User;
114 import org.openecomp.sdc.be.model.jsonjanusgraph.config.ContainerInstanceTypesData;
115 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ArtifactsOperations;
116 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ForwardingPathOperation;
117 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.InterfaceOperation;
118 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.NodeFilterOperation;
119 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.NodeTemplateOperation;
120 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade;
121 import org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter;
122 import org.openecomp.sdc.be.model.operations.StorageException;
123 import org.openecomp.sdc.be.model.operations.api.IElementOperation;
124 import org.openecomp.sdc.be.model.operations.api.IGroupInstanceOperation;
125 import org.openecomp.sdc.be.model.operations.api.IGroupOperation;
126 import org.openecomp.sdc.be.model.operations.api.IGroupTypeOperation;
127 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
128 import org.openecomp.sdc.be.model.operations.impl.ComponentInstanceOperation;
129 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
130 import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation;
131 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
132 import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
133 import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
134 import org.openecomp.sdc.be.model.validation.ToscaFunctionValidator;
135 import org.openecomp.sdc.be.resources.data.ComponentInstanceData;
136 import org.openecomp.sdc.be.user.Role;
137 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
138 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
139 import org.openecomp.sdc.common.api.Constants;
140 import org.openecomp.sdc.common.datastructure.Wrapper;
141 import org.openecomp.sdc.common.jsongraph.util.CommonUtility;
142 import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum;
143 import org.openecomp.sdc.common.log.elements.ErrorLogOptionalData;
144 import org.openecomp.sdc.common.log.enums.EcompLoggerErrorCode;
145 import org.openecomp.sdc.common.log.wrappers.Logger;
146 import org.openecomp.sdc.common.util.ValidationUtils;
147 import org.openecomp.sdc.exception.ResponseFormat;
148 import org.springframework.beans.factory.annotation.Autowired;
149 import org.yaml.snakeyaml.Yaml;
151 @org.springframework.stereotype.Component
152 public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
154 private static final Logger log = Logger.getLogger(ComponentInstanceBusinessLogic.class);
155 private static final String VF_MODULE = "org.openecomp.groups.VfModule";
156 private static final String TRY_TO_CREATE_ENTRY_ON_GRAPH = "Try to create entry on graph";
157 private static final String CLOUD_SPECIFIC_FIXED_KEY_WORD = "cloudtech";
158 private static final String[][] CLOUD_SPECIFIC_KEY_WORDS = {{"k8s", "azure", "aws"}, /* cloud specific technology */
159 {"charts", "day0", "configtemplate"} /*cloud specific sub type*/};
160 private static final String FAILED_TO_CREATE_ENTRY_ON_GRAPH_FOR_COMPONENT_INSTANCE = "Failed to create entry on graph for component instance {}";
161 private static final String ENTITY_ON_GRAPH_IS_CREATED = "Entity on graph is created.";
162 private static final String INVALID_COMPONENT_TYPE = "invalid component type";
163 private static final String FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID = "Failed to retrieve component, component id {}";
164 private static final String FAILED_TO_LOCK_SERVICE = "Failed to lock service {}";
165 private static final String CREATE_OR_UPDATE_PROPERTY_VALUE = "CreateOrUpdatePropertyValue";
166 private static final String FAILED_TO_COPY_COMP_INSTANCE_TO_CANVAS = "Failed to copy the component instance to the canvas";
167 private static final String COPY_COMPONENT_INSTANCE_OK = "Copy component instance OK";
168 private static final String CANNOT_ATTACH_RESOURCE_INSTANCES_TO_CONTAINER_RESOURCE_OF_TYPE = "Cannot attach resource instances to container resource of type {}";
169 private static final String FAILED_TO_UPDATE_COMPONENT_INSTANCE_CAPABILITY = "Failed to update component instance capability on instance {} in "
171 private static final String SERVICE_PROXY = "serviceProxy";
172 private static final String ASSOCIATE_RI_TO_RI = "associateRIToRI";
173 private static final String COMPONENT_ARCHIVED = "Component is archived. Component id: {}";
174 private static final String RESTRICTED_OPERATION_ON_SERVIVE = "Restricted operation for user: {} on service {}";
175 private static final String FAILED_TO_LOCK_COMPONENT = "Failed to lock component {}";
176 private static final String RESTRICTED_OPERATION_ON_COMPONENT = "Restricted operation for user: {} on component {}";
177 private static final String RESOURCE_INSTANCE = "resource instance";
178 private static final String SERVICE = "service";
180 private final ComponentInstanceOperation componentInstanceOperation;
181 private final ArtifactsBusinessLogic artifactBusinessLogic;
182 private final ComponentInstanceMergeDataBusinessLogic compInstMergeDataBL;
183 private final ComponentInstanceChangeOperationOrchestrator onChangeInstanceOperationOrchestrator;
184 private final ForwardingPathOperation forwardingPathOperation;
185 private final NodeFilterOperation nodeFilterOperation;
187 private CompositionBusinessLogic compositionBusinessLogic;
189 private ContainerInstanceTypesData containerInstanceTypesData;
190 private final ToscaFunctionValidator toscaFunctionValidator;
191 private final PropertyBusinessLogic propertyBusinessLogic;
194 public ComponentInstanceBusinessLogic(IElementOperation elementDao, IGroupOperation groupOperation,
195 IGroupInstanceOperation groupInstanceOperation, IGroupTypeOperation groupTypeOperation,
196 InterfaceOperation interfaceOperation, InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
197 ComponentInstanceOperation componentInstanceOperation, ArtifactsBusinessLogic artifactBusinessLogic,
198 ComponentInstanceMergeDataBusinessLogic compInstMergeDataBL,
199 ComponentInstanceChangeOperationOrchestrator onChangeInstanceOperationOrchestrator,
200 ForwardingPathOperation forwardingPathOperation, NodeFilterOperation nodeFilterOperation,
201 ArtifactsOperations artifactToscaOperation, final ToscaFunctionValidator toscaFunctionValidator,
202 PropertyBusinessLogic propertyBusinessLogic) {
203 super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation, interfaceOperation, interfaceLifecycleTypeOperation,
204 artifactToscaOperation);
205 this.componentInstanceOperation = componentInstanceOperation;
206 this.artifactBusinessLogic = artifactBusinessLogic;
207 this.compInstMergeDataBL = compInstMergeDataBL;
208 this.onChangeInstanceOperationOrchestrator = onChangeInstanceOperationOrchestrator;
209 this.forwardingPathOperation = forwardingPathOperation;
210 this.nodeFilterOperation = nodeFilterOperation;
211 this.toscaFunctionValidator = toscaFunctionValidator;
212 this.propertyBusinessLogic = propertyBusinessLogic;
215 public ComponentInstance createComponentInstance(String containerComponentParam, String containerComponentId, String userId,
216 ComponentInstance resourceInstance) {
217 return createComponentInstance(containerComponentParam, containerComponentId, userId, resourceInstance, true);
220 public List<ComponentInstanceProperty> getComponentInstancePropertiesByInputId(org.openecomp.sdc.be.model.Component component, String inputId) {
221 List<ComponentInstanceProperty> resList = new ArrayList<>();
222 Map<String, List<ComponentInstanceProperty>> ciPropertiesMap = component.getComponentInstancesProperties();
223 if (ciPropertiesMap != null && !ciPropertiesMap.isEmpty()) {
224 ciPropertiesMap.forEach((s, ciPropList) -> {
226 Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(s)).findAny();
227 if (ciOp.isPresent()) {
228 ciName = ciOp.get().getName();
230 if (ciPropList != null && !ciPropList.isEmpty()) {
231 for (ComponentInstanceProperty prop : ciPropList) {
232 List<GetInputValueDataDefinition> inputsValues = prop.getGetInputValues();
233 addCompInstanceProperty(s, ciName, prop, inputsValues, inputId, resList);
241 public List<ComponentInstanceAttribute> getComponentInstanceAttributesByOutputId(final org.openecomp.sdc.be.model.Component component,
242 final String outputId) {
243 final List<ComponentInstanceAttribute> resList = new ArrayList<>();
244 final Map<String, List<ComponentInstanceAttribute>> componentInstancesAttributes = component.getComponentInstancesAttributes();
245 if (org.apache.commons.collections4.MapUtils.isNotEmpty(componentInstancesAttributes)) {
246 componentInstancesAttributes.forEach((s, componentInstanceAttributeList) -> {
248 final Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(s))
250 if (ciOp.isPresent()) {
251 ciName = ciOp.get().getName();
253 if (componentInstanceAttributeList != null && !componentInstanceAttributeList.isEmpty()) {
254 for (final ComponentInstanceAttribute compInstanceAttribute : componentInstanceAttributeList) {
255 List<GetOutputValueDataDefinition> outputValues = compInstanceAttribute.getGetOutputValues();
256 addCompInstanceAttribute(s, ciName, compInstanceAttribute, outputValues, outputId, resList);
264 private void addCompInstanceProperty(String s, String ciName, ComponentInstanceProperty prop, List<GetInputValueDataDefinition> inputsValues,
265 String inputId, List<ComponentInstanceProperty> resList) {
266 if (inputsValues != null && !inputsValues.isEmpty()) {
267 for (GetInputValueDataDefinition inputData : inputsValues) {
268 if (isGetInputValueForInput(inputData, inputId)) {
269 prop.setComponentInstanceId(s);
270 prop.setComponentInstanceName(ciName);
278 private void addCompInstanceAttribute(final String s, final String ciName, final ComponentInstanceAttribute attribute,
279 final List<GetOutputValueDataDefinition> outputsValues, final String outputId,
280 final List<ComponentInstanceAttribute> resList) {
281 if (outputsValues != null && !outputsValues.isEmpty()) {
282 for (final GetOutputValueDataDefinition outputData : outputsValues) {
283 if (isGetOutputValueForOutput(outputData, outputId)) {
284 attribute.setComponentInstanceId(s);
285 attribute.setComponentInstanceName(ciName);
286 resList.add(attribute);
293 public Optional<ComponentInstanceProperty> getComponentInstancePropertyByPolicyId(Component component, PolicyDefinition policy) {
294 Optional<ComponentInstanceProperty> propertyCandidate = getComponentInstancePropertyByPolicy(component, policy);
295 if (propertyCandidate.isPresent()) {
296 ComponentInstanceProperty componentInstanceProperty = propertyCandidate.get();
297 Optional<GetPolicyValueDataDefinition> getPolicyCandidate = getGetPolicyValueDataDefinition(policy, componentInstanceProperty);
299 .ifPresent(getPolicyValue -> updateComponentInstancePropertyAfterUndeclaration(componentInstanceProperty, getPolicyValue, policy));
300 return Optional.of(componentInstanceProperty);
302 return Optional.empty();
305 private void updateComponentInstancePropertyAfterUndeclaration(ComponentInstanceProperty componentInstanceProperty,
306 GetPolicyValueDataDefinition getPolicyValue, PolicyDefinition policyDefinition) {
307 componentInstanceProperty.setValue(getPolicyValue.getOrigPropertyValue());
308 List<GetPolicyValueDataDefinition> getPolicyValues = componentInstanceProperty.getGetPolicyValues();
309 if (CollectionUtils.isNotEmpty(getPolicyValues)) {
310 getPolicyValues.remove(getPolicyValue);
311 componentInstanceProperty.setGetPolicyValues(getPolicyValues);
312 policyDefinition.setGetPolicyValues(getPolicyValues);
316 private Optional<GetPolicyValueDataDefinition> getGetPolicyValueDataDefinition(PolicyDefinition policy,
317 ComponentInstanceProperty componentInstanceProperty) {
318 List<GetPolicyValueDataDefinition> getPolicyValues = policy.getGetPolicyValues();
319 return getPolicyValues.stream().filter(getPolicyValue -> getPolicyValue.getPropertyName().equals(componentInstanceProperty.getName()))
323 private Optional<ComponentInstanceProperty> getComponentInstancePropertyByPolicy(Component component, PolicyDefinition policy) {
324 Map<String, List<ComponentInstanceProperty>> componentInstancesProperties = component.getComponentInstancesProperties();
325 if (MapUtils.isEmpty(componentInstancesProperties)) {
326 return Optional.empty();
328 String instanceUniqueId = policy.getInstanceUniqueId();
329 List<ComponentInstanceProperty> componentInstanceProperties =
330 componentInstancesProperties.containsKey(instanceUniqueId) ? componentInstancesProperties.get(instanceUniqueId) : new ArrayList<>();
331 return componentInstanceProperties.stream().filter(property -> property.getName().equals(policy.getName())).findAny();
334 public List<ComponentInstanceInput> getComponentInstanceInputsByInputId(org.openecomp.sdc.be.model.Component component, String inputId) {
335 List<ComponentInstanceInput> resList = new ArrayList<>();
336 Map<String, List<ComponentInstanceInput>> ciInputsMap = component.getComponentInstancesInputs();
337 if (ciInputsMap != null && !ciInputsMap.isEmpty()) {
338 ciInputsMap.forEach((s, ciPropList) -> {
340 Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(s)).findAny();
341 if (ciOp.isPresent()) {
342 ciName = ciOp.get().getName();
344 if (ciPropList != null && !ciPropList.isEmpty()) {
345 for (ComponentInstanceInput prop : ciPropList) {
346 List<GetInputValueDataDefinition> inputsValues = prop.getGetInputValues();
347 addCompInstanceInput(s, ciName, prop, inputsValues, inputId, resList);
355 public List<ComponentInstanceOutput> getComponentInstanceOutputsByOutputId(final org.openecomp.sdc.be.model.Component component,
356 final String outputId) {
357 final List<ComponentInstanceOutput> resList = new ArrayList<>();
358 final Map<String, List<ComponentInstanceOutput>> ciInputsMap = component.getComponentInstancesOutputs();
359 if (ciInputsMap != null && !ciInputsMap.isEmpty()) {
360 ciInputsMap.forEach((s, ciPropList) -> {
362 final Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(s))
364 if (ciOp.isPresent()) {
365 ciName = ciOp.get().getName();
367 if (ciPropList != null && !ciPropList.isEmpty()) {
368 for (final ComponentInstanceOutput prop : ciPropList) {
369 final List<GetOutputValueDataDefinition> outputValues = prop.getGetOutputValues();
370 addCompInstanceOutput(s, ciName, prop, outputValues, outputId, resList);
378 private void addCompInstanceInput(String s, String ciName, ComponentInstanceInput prop, List<GetInputValueDataDefinition> inputsValues,
379 String inputId, List<ComponentInstanceInput> resList) {
380 if (inputsValues != null && !inputsValues.isEmpty()) {
381 for (GetInputValueDataDefinition inputData : inputsValues) {
382 if (isGetInputValueForInput(inputData, inputId)) {
383 prop.setComponentInstanceId(s);
384 prop.setComponentInstanceName(ciName);
392 private void addCompInstanceOutput(final String s, final String ciName, final ComponentInstanceOutput prop,
393 final List<GetOutputValueDataDefinition> outputsValues, final String outputId,
394 final List<ComponentInstanceOutput> resList) {
395 if (outputsValues != null && !outputsValues.isEmpty()) {
396 for (final GetOutputValueDataDefinition outputData : outputsValues) {
397 if (isGetOutputValueForOutput(outputData, outputId)) {
398 prop.setComponentInstanceId(s);
399 prop.setComponentInstanceName(ciName);
407 public ComponentInstance createComponentInstance(final String containerComponentParam, final String containerComponentId, final String userId,
408 final ComponentInstance resourceInstance, final boolean needLock) {
409 final User user = validateUserExists(userId);
410 validateUserNotEmpty(user, "Create component instance");
411 validateJsonBody(resourceInstance, ComponentInstance.class);
412 final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
413 final org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, null);
414 if (ModelConverter.isAtomicComponent(containerComponent)) {
415 if (log.isDebugEnabled()) {
416 log.debug(CANNOT_ATTACH_RESOURCE_INSTANCES_TO_CONTAINER_RESOURCE_OF_TYPE, containerComponent.assetType());
418 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType());
420 validateCanWorkOnComponent(containerComponent, userId);
421 Component origComponent = null;
422 if (resourceInstance != null && containerComponentType != null) {
423 final OriginTypeEnum originType = resourceInstance.getOriginType();
424 validateInstanceName(resourceInstance);
425 if (originType == OriginTypeEnum.ServiceProxy) {
426 origComponent = getOrigComponentForServiceProxy(containerComponent, resourceInstance);
427 } else if (originType == OriginTypeEnum.ServiceSubstitution) {
428 origComponent = getOrigComponentForServiceSubstitution(resourceInstance);
430 origComponent = getAndValidateOriginComponentOfComponentInstance(containerComponent, resourceInstance);
431 validateOriginAndResourceInstanceTypes(containerComponent, origComponent, originType);
433 validateResourceInstanceState(containerComponent, origComponent);
434 overrideFields(origComponent, resourceInstance);
435 compositionBusinessLogic.validateAndSetDefaultCoordinates(resourceInstance);
437 return createComponent(needLock, containerComponent, origComponent, resourceInstance, user);
440 private Component getOrigComponentForServiceProxy(org.openecomp.sdc.be.model.Component containerComponent, ComponentInstance resourceInstance) {
441 Either<Component, StorageOperationStatus> serviceProxyOrigin = toscaOperationFacade.getLatestByName(SERVICE_PROXY, null);
442 if (isServiceProxyOrigin(serviceProxyOrigin)) {
443 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(serviceProxyOrigin.right().value()));
445 Component origComponent = serviceProxyOrigin.left().value();
446 StorageOperationStatus fillProxyRes = fillInstanceData(resourceInstance, origComponent);
447 if (isFillProxyRes(fillProxyRes)) {
448 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(fillProxyRes));
450 validateOriginAndResourceInstanceTypes(containerComponent, origComponent, OriginTypeEnum.ServiceProxy);
451 return origComponent;
454 private Component getOrigComponentForServiceSubstitution(ComponentInstance resourceInstance) {
455 final Either<Component, StorageOperationStatus> getServiceResult = toscaOperationFacade
456 .getToscaFullElement(resourceInstance.getComponentUid());
457 if (getServiceResult.isRight()) {
458 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(getServiceResult.right().value()));
460 final Component service = getServiceResult.left().value();
461 final Either<Component, StorageOperationStatus> getServiceDerivedFromTypeResult = toscaOperationFacade
462 .getLatestByToscaResourceName(service.getDerivedFromGenericType(), service.getModel());
463 if (getServiceDerivedFromTypeResult.isRight()) {
464 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(getServiceResult.right().value()));
466 Component origComponent = getServiceDerivedFromTypeResult.left().value();
467 final StorageOperationStatus fillProxyRes = fillInstanceData(resourceInstance, origComponent);
468 if (isFillProxyRes(fillProxyRes)) {
469 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(fillProxyRes));
471 return origComponent;
474 private ComponentInstance createComponent(boolean needLock, Component containerComponent, Component origComponent,
475 ComponentInstance resourceInstance, User user) {
476 boolean failed = false;
478 lockIfNeed(needLock, containerComponent);
479 log.debug(TRY_TO_CREATE_ENTRY_ON_GRAPH);
480 return createComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, user);
481 } catch (ComponentException e) {
486 unlockComponent(failed, containerComponent);
492 * Try using either to make a judgment
494 * @param containerComponentParam
495 * @param containerComponentId
497 * @param resourceInstance
500 public Either<ComponentInstance, ResponseFormat> createRealComponentInstance(String containerComponentParam, String containerComponentId,
501 String userId, ComponentInstance resourceInstance) {
502 log.debug("enter createRealComponentInstance");
503 return createRealComponentInstance(containerComponentParam, containerComponentId, userId, resourceInstance, true);
507 * Try using either to make a judgment
510 * @param containerComponentParam
511 * @param containerComponentId
513 * @param resourceInstance
516 public Either<ComponentInstance, ResponseFormat> createRealComponentInstance(String containerComponentParam, String containerComponentId,
517 String userId, ComponentInstance resourceInstance,
519 log.debug("enter createRealComponentInstance");
520 Component origComponent = null;
522 org.openecomp.sdc.be.model.Component containerComponent = null;
523 ComponentTypeEnum containerComponentType;
525 user = validateUserExists(userId);
526 validateUserNotEmpty(user, "Create component instance");
527 validateJsonBody(resourceInstance, ComponentInstance.class);
528 containerComponentType = validateComponentType(containerComponentParam);
529 containerComponent = validateComponentExists(containerComponentId, containerComponentType, null);
530 log.debug("enter createRealComponentInstance,validate user json success");
531 if (ModelConverter.isAtomicComponent(containerComponent)) {
532 log.debug(CANNOT_ATTACH_RESOURCE_INSTANCES_TO_CONTAINER_RESOURCE_OF_TYPE, containerComponent.assetType());
533 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType());
535 validateCanWorkOnComponent(containerComponent, userId);
536 log.debug("enter createRealComponentInstance,validateCanWorkOnComponent success");
537 if (resourceInstance != null && containerComponentType != null) {
538 log.debug("enter createRealComponentInstance,start create ComponentInstance");
539 OriginTypeEnum originType = resourceInstance.getOriginType();
540 validateInstanceName(resourceInstance);
541 if (originType == OriginTypeEnum.ServiceProxy) {
542 log.debug("enter createRealComponentInstance,originType equals ServiceProxy");
543 Either<Component, StorageOperationStatus> serviceProxyOrigin = toscaOperationFacade.getLatestByName(SERVICE_PROXY, null);
544 if (isServiceProxyOrigin(serviceProxyOrigin)) {
545 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(serviceProxyOrigin.right().value()));
547 origComponent = serviceProxyOrigin.left().value();
548 StorageOperationStatus fillProxyRes = fillInstanceData(resourceInstance, origComponent);
549 if (isFillProxyRes(fillProxyRes)) {
550 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(fillProxyRes));
553 log.debug("enter createRealComponentInstance,originType is not ServiceProxy");
554 origComponent = getAndValidateOriginComponentOfComponentInstance(containerComponent, resourceInstance);
556 validateOriginAndResourceInstanceTypes(containerComponent, origComponent, originType);
557 validateResourceInstanceState(containerComponent, origComponent);
558 overrideFields(origComponent, resourceInstance);
559 compositionBusinessLogic.validateAndSetDefaultCoordinates(resourceInstance);
560 log.debug("enter createRealComponentInstance,final validate success");
562 return createRealComponent(needLock, containerComponent, origComponent, resourceInstance, user);
563 } catch (ComponentException e) {
564 log.debug("create Real Component Instance failed");
569 private Either<ComponentInstance, ResponseFormat> createRealComponent(boolean needLock, Component containerComponent, Component origComponent,
570 ComponentInstance resourceInstance, User user) {
571 log.debug("enter createRealComponent");
572 boolean failed = false;
574 lockIfNeed(needLock, containerComponent);
575 log.debug(TRY_TO_CREATE_ENTRY_ON_GRAPH);
576 return createRealComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, user);
577 } catch (ComponentException e) {
582 unlockComponent(failed, containerComponent);
587 private Either<ComponentInstance, ResponseFormat> createRealComponentInstanceOnGraph(org.openecomp.sdc.be.model.Component containerComponent,
588 Component originComponent,
589 ComponentInstance componentInstance, User user) {
590 log.debug("enter createRealComponentInstanceOnGraph");
591 Either<ImmutablePair<Component, String>, StorageOperationStatus> result = toscaOperationFacade
592 .addComponentInstanceToTopologyTemplate(containerComponent, originComponent, componentInstance, false, user);
593 if (result.isRight()) {
594 log.debug("enter createRealComponentInstanceOnGraph,result is right");
595 ActionStatus status = componentsUtils.convertFromStorageResponse(result.right().value());
596 log.debug(FAILED_TO_CREATE_ENTRY_ON_GRAPH_FOR_COMPONENT_INSTANCE, componentInstance.getName());
597 return Either.right(componentsUtils.getResponseFormat(status));
599 log.debug(ENTITY_ON_GRAPH_IS_CREATED);
600 log.debug("enter createRealComponentInstanceOnGraph,Entity on graph is created.");
601 Component updatedComponent = result.left().value().getLeft();
602 Map<String, String> existingEnvVersions = new HashMap<>();
603 // TODO existingEnvVersions ??
604 addComponentInstanceArtifacts(updatedComponent, componentInstance, originComponent, user, existingEnvVersions);
605 Optional<ComponentInstance> updatedInstanceOptional = updatedComponent.getComponentInstances().stream()
606 .filter(ci -> ci.getUniqueId().equals(result.left().value().getRight())).findFirst();
607 if (!updatedInstanceOptional.isPresent()) {
608 log.debug("Failed to fetch new added component instance {} from component {}", componentInstance.getName(), containerComponent.getName());
609 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName());
611 log.debug("enter createRealComponentInstanceOnGraph,and final success");
612 return Either.left(updatedInstanceOptional.get());
615 private void overrideFields(Component origComponent, ComponentInstance resourceInstance) {
616 resourceInstance.setComponentVersion(origComponent.getVersion());
617 resourceInstance.setIcon(origComponent.getIcon());
620 private void validateInstanceName(ComponentInstance resourceInstance) {
621 String resourceInstanceName = resourceInstance.getName();
622 if (StringUtils.isEmpty(resourceInstanceName)) {
623 log.debug("ComponentInstance name is empty");
624 throw new ByActionStatusComponentException(ActionStatus.INVALID_COMPONENT_NAME, resourceInstance.getName());
626 if (!ValidationUtils.validateComponentNameLength(resourceInstanceName)) {
627 log.debug("ComponentInstance name exceeds max length {} ", ValidationUtils.COMPONENT_NAME_MAX_LENGTH);
628 throw new ByActionStatusComponentException(ActionStatus.INVALID_COMPONENT_NAME, resourceInstance.getName());
630 if (!ValidationUtils.validateComponentNamePattern(resourceInstanceName)) {
631 log.debug("ComponentInstance name {} has invalid format", resourceInstanceName);
632 throw new ByActionStatusComponentException(ActionStatus.INVALID_COMPONENT_NAME, resourceInstance.getName());
636 private void validateResourceInstanceState(Component containerComponent, Component origComponent) {
637 if (origComponent.getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) {
638 throw new ByActionStatusComponentException(ActionStatus.CONTAINER_CANNOT_CONTAIN_INSTANCE,
639 containerComponent.getComponentType().getValue(), origComponent.getLifecycleState().toString());
643 private void validateOriginAndResourceInstanceTypes(final Component containerComponent, final Component origComponent,
644 final OriginTypeEnum originType) {
645 final ResourceTypeEnum resourceType = getResourceTypeEnumFromOriginComponent(origComponent);
646 validateOriginType(originType, resourceType);
647 validateOriginComponentIsValidForContainer(containerComponent, resourceType);
650 private void validateOriginComponentIsValidForContainer(Component containerComponent, ResourceTypeEnum resourceType) {
651 switch (containerComponent.getComponentType()) {
653 if (!containerInstanceTypesData.isAllowedForServiceComponent(resourceType, containerComponent.getModel())) {
654 throw new ByActionStatusComponentException(ActionStatus.CONTAINER_CANNOT_CONTAIN_INSTANCE,
655 containerComponent.getComponentType().toString(), resourceType.name());
659 final ResourceTypeEnum componentResourceType = ((Resource) containerComponent).getResourceType();
660 if (!containerInstanceTypesData.isAllowedForResourceComponent(componentResourceType, resourceType)) {
661 throw new ByActionStatusComponentException(ActionStatus.CONTAINER_CANNOT_CONTAIN_INSTANCE,
662 containerComponent.getComponentType().toString(), resourceType.name());
666 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
670 private void validateOriginType(OriginTypeEnum originType, ResourceTypeEnum resourceType) {
671 ResourceTypeEnum convertedOriginType;
673 convertedOriginType = ResourceTypeEnum.getTypeIgnoreCase(originType.name());
674 } catch (Exception e) {
675 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
677 if (resourceType != convertedOriginType) {
678 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
682 private ResourceTypeEnum getResourceTypeEnumFromOriginComponent(final Component origComponent) {
683 switch (origComponent.getComponentType()) {
685 return ResourceTypeEnum.ServiceProxy;
687 return ((Resource) origComponent).getResourceType();
689 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
693 private void lockIfNeed(boolean needLock, Component containerComponent) {
695 lockComponent(containerComponent, "createComponentInstance");
699 private boolean isServiceProxyOrigin(Either<Component, StorageOperationStatus> serviceProxyOrigin) {
700 if (serviceProxyOrigin.isRight()) {
701 log.debug("Failed to fetch normative service proxy resource by tosca name, error {}", serviceProxyOrigin.right().value());
707 private StorageOperationStatus fillInstanceData(ComponentInstance resourceInstance, Component origComponent) {
708 final ComponentParametersView filter = new ComponentParametersView(true);
709 filter.setIgnoreCapabilities(false);
710 filter.setIgnoreCapabiltyProperties(false);
711 filter.setIgnoreComponentInstances(false);
712 filter.setIgnoreRequirements(false);
713 filter.setIgnoreInterfaces(false);
714 filter.setIgnoreProperties(false);
715 filter.setIgnoreAttributes(false);
716 filter.setIgnoreInputs(false);
717 Either<Component, StorageOperationStatus> serviceRes = toscaOperationFacade.getToscaElement(resourceInstance.getComponentUid(), filter);
718 if (serviceRes.isRight()) {
719 return serviceRes.right().value();
721 final Component service = serviceRes.left().value();
722 final Map<String, List<CapabilityDefinition>> capabilities = service.getCapabilities();
723 resourceInstance.setCapabilities(capabilities);
724 final Map<String, List<RequirementDefinition>> req = service.getRequirements();
725 resourceInstance.setRequirements(req);
726 final Map<String, InterfaceDefinition> serviceInterfaces = service.getInterfaces();
727 if (MapUtils.isNotEmpty(serviceInterfaces)) {
728 serviceInterfaces.forEach(resourceInstance::addInterface);
730 resourceInstance.setProperties(PropertiesUtils.getProperties(service));
731 resourceInstance.setAttributes(service.getAttributes());
732 final List<InputDefinition> serviceInputs = service.getInputs();
733 resourceInstance.setInputs(serviceInputs);
734 resourceInstance.setSourceModelInvariant(service.getInvariantUUID());
735 resourceInstance.setSourceModelName(service.getName());
736 resourceInstance.setSourceModelUuid(service.getUUID());
737 resourceInstance.setSourceModelUid(service.getUniqueId());
738 resourceInstance.setComponentUid(origComponent.getUniqueId());
739 resourceInstance.setComponentVersion(service.getVersion());
740 switch (resourceInstance.getOriginType()) {
742 return fillProxyInstanceData(resourceInstance, origComponent, service);
743 case ServiceSubstitution:
744 return fillServiceSubstitutableNodeTypeData(resourceInstance, service);
746 return StorageOperationStatus.OK;
750 private StorageOperationStatus fillProxyInstanceData(final ComponentInstance resourceInstance, final Component origComponent,
751 final Component service) {
752 final String name = ValidationUtils.normalizeComponentInstanceName(service.getName()) + ToscaOperationFacade.PROXY_SUFFIX;
753 final String toscaResourceName = ((Resource) origComponent).getToscaResourceName();
754 final int lastIndexOf = toscaResourceName.lastIndexOf('.');
755 if (lastIndexOf != -1) {
756 final String proxyToscaName = toscaResourceName.substring(0, lastIndexOf + 1) + name;
757 resourceInstance.setToscaComponentName(proxyToscaName);
759 resourceInstance.setName(name);
760 resourceInstance.setIsProxy(true);
761 resourceInstance.setDescription("A Proxy for Service " + service.getName());
762 return StorageOperationStatus.OK;
765 private StorageOperationStatus fillServiceSubstitutableNodeTypeData(final ComponentInstance resourceInstance, final Component service) {
766 resourceInstance.setToscaComponentName("org.openecomp.service." + ValidationUtils.convertToSystemName(service.getName()));
767 resourceInstance.setName(ValidationUtils.normalizeComponentInstanceName(service.getName()));
768 resourceInstance.setIsProxy(false);
769 resourceInstance.setDescription("A substitutable node type for service " + service.getName());
770 return StorageOperationStatus.OK;
773 public Either<CreateAndAssotiateInfo, ResponseFormat> createAndAssociateRIToRI(String containerComponentParam, String containerComponentId,
774 String userId, CreateAndAssotiateInfo createAndAssotiateInfo) {
775 Either<CreateAndAssotiateInfo, ResponseFormat> resultOp = null;
776 ComponentInstance resourceInstance = createAndAssotiateInfo.getNode();
777 RequirementCapabilityRelDef associationInfo = createAndAssotiateInfo.getAssociate();
778 User user = validateUserExists(userId);
779 final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
780 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, null);
781 if (ModelConverter.isAtomicComponent(containerComponent)) {
782 log.debug(CANNOT_ATTACH_RESOURCE_INSTANCES_TO_CONTAINER_RESOURCE_OF_TYPE, containerComponent.assetType());
784 .right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType()));
786 validateCanWorkOnComponent(containerComponent, userId);
787 boolean failed = false;
789 lockComponent(containerComponent, "createAndAssociateRIToRI");
790 log.debug(TRY_TO_CREATE_ENTRY_ON_GRAPH);
791 Component origComponent = getOriginComponentFromComponentInstance(resourceInstance);
792 log.debug(ENTITY_ON_GRAPH_IS_CREATED);
793 ComponentInstance resResourceInfo = createComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, user);
794 if (associationInfo.getFromNode() == null || associationInfo.getFromNode().isEmpty()) {
795 associationInfo.setFromNode(resResourceInfo.getUniqueId());
797 associationInfo.setToNode(resResourceInfo.getUniqueId());
799 Either<RequirementCapabilityRelDef, StorageOperationStatus> resultReqCapDef = toscaOperationFacade
800 .associateResourceInstances(containerComponent, containerComponentId, associationInfo);
801 if (resultReqCapDef.isLeft()) {
802 log.debug(ENTITY_ON_GRAPH_IS_CREATED);
803 RequirementCapabilityRelDef resReqCapabilityRelDef = resultReqCapDef.left().value();
804 CreateAndAssotiateInfo resInfo = new CreateAndAssotiateInfo(resResourceInfo, resReqCapabilityRelDef);
805 resultOp = Either.left(resInfo);
808 log.info("Failed to associate node {} with node {}", associationInfo.getFromNode(), associationInfo.getToNode());
809 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(
810 componentsUtils.convertFromStorageResponseForResourceInstance(resultReqCapDef.right().value(), true), "", null));
813 } catch (ComponentException e) {
817 unlockComponent(failed, containerComponent);
821 private Component getOriginComponentFromComponentInstance(ComponentInstance componentInstance) {
822 return getOriginComponentFromComponentInstance(componentInstance.getName(), componentInstance.getComponentUid());
825 private Component getInstanceOriginNode(ComponentInstance componentInstance) {
826 return getOriginComponentFromComponentInstance(componentInstance.getName(), componentInstance.getActualComponentUid());
829 private Component getOriginComponentFromComponentInstance(String componentInstanceName, String origComponetId) {
830 Either<Component, StorageOperationStatus> eitherComponent = toscaOperationFacade.getToscaFullElement(origComponetId);
831 if (eitherComponent.isRight()) {
832 log.debug("Failed to get origin component with id {} for component instance {} ", origComponetId, componentInstanceName);
833 throw new ByActionStatusComponentException(
834 componentsUtils.convertFromStorageResponse(eitherComponent.right().value(), ComponentTypeEnum.RESOURCE), "", null);
836 return eitherComponent.left().value();
839 private ComponentInstance createComponentInstanceOnGraph(org.openecomp.sdc.be.model.Component containerComponent, Component originComponent,
840 ComponentInstance componentInstance, User user) {
841 Either<ImmutablePair<Component, String>, StorageOperationStatus> result = toscaOperationFacade
842 .addComponentInstanceToTopologyTemplate(containerComponent, originComponent, componentInstance, false, user);
843 if (result.isRight()) {
844 log.debug(FAILED_TO_CREATE_ENTRY_ON_GRAPH_FOR_COMPONENT_INSTANCE, componentInstance.getName());
845 throw new ByResponseFormatComponentException(componentsUtils
846 .getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), "",
849 log.debug(ENTITY_ON_GRAPH_IS_CREATED);
850 Component updatedComponent = result.left().value().getLeft();
851 Map<String, String> existingEnvVersions = new HashMap<>();
852 // TODO existingEnvVersions ??
853 addComponentInstanceArtifacts(updatedComponent, componentInstance, originComponent, user, existingEnvVersions);
854 Optional<ComponentInstance> updatedInstanceOptional = updatedComponent.getComponentInstances().stream()
855 .filter(ci -> ci.getUniqueId().equals(result.left().value().getRight())).findFirst();
856 if (!updatedInstanceOptional.isPresent()) {
857 log.debug("Failed to fetch new added component instance {} from component {}", componentInstance.getName(), containerComponent.getName());
858 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName());
860 return updatedInstanceOptional.get();
863 public boolean isCloudSpecificArtifact(String artifact) {
864 if (artifact.contains(CLOUD_SPECIFIC_FIXED_KEY_WORD)) {
865 for (int i = 0; i < CLOUD_SPECIFIC_KEY_WORDS.length; i++) {
866 if (Arrays.stream(CLOUD_SPECIFIC_KEY_WORDS[i]).noneMatch(artifact::contains)) {
877 * addResourceInstanceArtifacts - add artifacts (HEAT_ENV) to resource instance The instance artifacts are generated from the resource's
880 * @param containerComponent
881 * @param componentInstance
882 * @param originComponent
884 * @param existingEnvVersions
887 protected ActionStatus addComponentInstanceArtifacts(org.openecomp.sdc.be.model.Component containerComponent, ComponentInstance componentInstance,
888 org.openecomp.sdc.be.model.Component originComponent, User user,
889 Map<String, String> existingEnvVersions) {
890 log.debug("add artifacts to resource instance");
891 List<GroupDefinition> filteredGroups = new ArrayList<>();
892 ActionStatus status = setResourceArtifactsOnResourceInstance(componentInstance);
893 if (ActionStatus.OK != status) {
894 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormatForResourceInstance(status, "", null));
896 StorageOperationStatus artStatus;
897 // generate heat_env if necessary
898 Map<String, ArtifactDefinition> componentDeploymentArtifacts = componentInstance.getDeploymentArtifacts();
899 if (MapUtils.isNotEmpty(componentDeploymentArtifacts)) {
900 Map<String, ArtifactDefinition> finalDeploymentArtifacts = new HashMap<>();
901 Map<String, List<ArtifactDefinition>> groupInstancesArtifacts = new HashMap<>();
902 Integer defaultHeatTimeout = ConfigurationManager.getConfigurationManager().getConfiguration().getHeatArtifactDeploymentTimeout()
903 .getDefaultMinutes();
904 List<ArtifactDefinition> listOfCloudSpecificArts = new ArrayList<>();
905 for (ArtifactDefinition artifact : componentDeploymentArtifacts.values()) {
906 String type = artifact.getArtifactType();
907 if (!type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType())) {
908 finalDeploymentArtifacts.put(artifact.getArtifactLabel(), artifact);
910 if (type.equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HELM.getType()) || type
911 .equalsIgnoreCase(ArtifactTypeEnum.HEAT_NET.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType()) || type
912 .equalsIgnoreCase(ArtifactTypeEnum.CLOUD_TECHNOLOGY_SPECIFIC_ARTIFACT.getType())) {
913 artifact.setTimeout(defaultHeatTimeout);
917 if (artifact.checkEsIdExist()) {
918 ArtifactDefinition artifactDefinition = artifactBusinessLogic
919 .createHeatEnvPlaceHolder(new ArrayList<>(), artifact, ArtifactsBusinessLogic.HEAT_ENV_NAME, componentInstance.getUniqueId(),
920 NodeTypeEnum.ResourceInstance, componentInstance.getName(), user, containerComponent, existingEnvVersions);
922 finalDeploymentArtifacts.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
923 if (CollectionUtils.isNotEmpty(originComponent.getGroups())) {
924 filteredGroups = originComponent.getGroups().stream().filter(g -> g.getType().equals(VF_MODULE)).collect(Collectors.toList());
926 if (isCloudSpecificArtifact(artifactDefinition.getArtifactName())) {
927 listOfCloudSpecificArts.add(artifact);
929 if (CollectionUtils.isNotEmpty(filteredGroups)) {
930 filteredGroups.stream()
931 .filter(g -> g.getArtifacts() != null && g.getArtifacts().stream().anyMatch(p -> p.equals(artifactDefinition.getGeneratedFromId()))).findFirst()
932 .ifPresent(g -> fillInstanceArtifactMap(groupInstancesArtifacts, artifactDefinition, g));
936 groupInstancesArtifacts.forEach((k, v) -> v.addAll(listOfCloudSpecificArts));
937 filteredGroups.forEach(g -> listOfCloudSpecificArts.forEach(e -> {
938 g.getArtifactsUuid().add(e.getArtifactUUID());
939 g.getArtifacts().add(e.getUniqueId());
941 artStatus = toscaOperationFacade
942 .addDeploymentArtifactsToInstance(containerComponent.getUniqueId(), componentInstance, finalDeploymentArtifacts);
943 if (artStatus != StorageOperationStatus.OK) {
944 log.debug("Failed to add instance deployment artifacts for instance {} in conatiner {} error {}", componentInstance.getUniqueId(),
945 containerComponent.getUniqueId(), artStatus);
946 throw new ByResponseFormatComponentException(
947 componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(artStatus, false)));
949 StorageOperationStatus result = toscaOperationFacade
950 .addGroupInstancesToComponentInstance(containerComponent, componentInstance, filteredGroups, groupInstancesArtifacts);
951 if (result != StorageOperationStatus.OK) {
952 log.debug("failed to update group instance for component instance {}", componentInstance.getUniqueId());
953 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(result)));
955 componentInstance.setDeploymentArtifacts(finalDeploymentArtifacts);
957 artStatus = toscaOperationFacade
958 .addInformationalArtifactsToInstance(containerComponent.getUniqueId(), componentInstance, originComponent.getArtifacts());
959 if (artStatus != StorageOperationStatus.OK) {
960 log.debug("Failed to add informational artifacts to the instance {} belonging to the conatiner {}. Status is {}",
961 componentInstance.getUniqueId(), containerComponent.getUniqueId(), artStatus);
962 throw new ByResponseFormatComponentException(
963 componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(artStatus, false)));
965 componentInstance.setArtifacts(originComponent.getArtifacts());
966 return ActionStatus.OK;
969 private void fillInstanceArtifactMap(Map<String, List<ArtifactDefinition>> groupInstancesArtifacts, ArtifactDefinition artifactDefinition,
970 GroupDefinition groupInstance) {
971 List<ArtifactDefinition> artifactsUid;
972 if (groupInstancesArtifacts.containsKey(groupInstance.getUniqueId())) {
973 artifactsUid = groupInstancesArtifacts.get(groupInstance.getUniqueId());
975 artifactsUid = new ArrayList<>();
977 artifactsUid.add(artifactDefinition);
978 groupInstancesArtifacts.put(groupInstance.getUniqueId(), artifactsUid);
981 private ActionStatus setResourceArtifactsOnResourceInstance(ComponentInstance resourceInstance) {
982 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getResourceDeploymentArtifacts = artifactBusinessLogic
983 .getArtifacts(resourceInstance.getComponentUid(), NodeTypeEnum.Resource, ArtifactGroupTypeEnum.DEPLOYMENT, null);
984 Map<String, ArtifactDefinition> deploymentArtifacts = new HashMap<>();
985 if (getResourceDeploymentArtifacts.isRight()) {
986 StorageOperationStatus status = getResourceDeploymentArtifacts.right().value();
987 if (status != StorageOperationStatus.NOT_FOUND) {
988 log.debug("Failed to fetch resource: {} artifacts. status is {}", resourceInstance.getComponentUid(), status);
989 return componentsUtils.convertFromStorageResponseForResourceInstance(status, true);
992 deploymentArtifacts = getResourceDeploymentArtifacts.left().value();
994 if (!deploymentArtifacts.isEmpty()) {
995 Map<String, ArtifactDefinition> tempDeploymentArtifacts = new HashMap<>(deploymentArtifacts);
996 for (Entry<String, ArtifactDefinition> artifact : deploymentArtifacts.entrySet()) {
997 if (!artifact.getValue().checkEsIdExist()) {
998 tempDeploymentArtifacts.remove(artifact.getKey());
1001 resourceInstance.setDeploymentArtifacts(tempDeploymentArtifacts);
1003 return ActionStatus.OK;
1006 public Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(String containerComponentParam, String containerComponentId,
1007 String componentInstanceId, String userId,
1008 ComponentInstance componentInstance) {
1009 return updateComponentInstanceMetadata(containerComponentParam, containerComponentId, componentInstanceId, userId, componentInstance, true);
1012 public Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(final String containerComponentParam,
1013 final String containerComponentId,
1014 final String componentInstanceId, final String userId,
1015 ComponentInstance componentInstance, boolean needLock) {
1016 validateUserExists(userId);
1017 final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
1018 final Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, null);
1019 validateCanWorkOnComponent(containerComponent, userId);
1020 ComponentTypeEnum instanceType = getComponentType(containerComponentType);
1021 Either<Boolean, StorageOperationStatus> validateParentStatus = toscaOperationFacade
1022 .validateComponentExists(componentInstance.getComponentUid());
1023 if (validateParentStatus.isRight()) {
1024 log.debug("Failed to get component instance {} on service {}", componentInstanceId, containerComponentId);
1025 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND, componentInstance.getName(),
1026 instanceType.getValue().toLowerCase());
1028 if (!Boolean.TRUE.equals(validateParentStatus.left().value())) {
1029 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName(),
1030 instanceType.getValue().toLowerCase(), containerComponentType.getValue().toLowerCase(), containerComponentId);
1033 lockComponent(containerComponent, "updateComponentInstance");
1035 Component origComponent;
1036 boolean failed = false;
1038 origComponent = getOriginComponentFromComponentInstance(componentInstance);
1039 componentInstance = updateComponentInstanceMetadata(containerComponent, containerComponentType, origComponent, componentInstanceId,
1041 } catch (ComponentException e) {
1046 unlockComponent(failed, containerComponent);
1049 return Either.left(componentInstance);
1052 // New Multiple Instance Update API
1053 public List<ComponentInstance> updateComponentInstance(String containerComponentParam, Component containerComponent, String containerComponentId,
1054 String userId, List<ComponentInstance> componentInstanceList, boolean needLock) {
1055 boolean failed = false;
1057 validateUserExists(userId);
1058 final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
1059 ComponentParametersView componentFilter = new ComponentParametersView();
1060 componentFilter.disableAll();
1061 componentFilter.setIgnoreUsers(false);
1062 componentFilter.setIgnoreComponentInstances(false);
1063 if (containerComponent == null) {
1064 containerComponent = validateComponentExistsByFilter(containerComponentId, containerComponentType, componentFilter);
1066 validateCanWorkOnComponent(containerComponent, userId);
1067 ComponentTypeEnum instanceType = getComponentType(containerComponentType);
1068 for (ComponentInstance componentInstance : componentInstanceList) {
1069 boolean validateParent = validateParent(containerComponent, componentInstance.getUniqueId());
1070 if (!validateParent) {
1071 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName(),
1072 instanceType.getValue().toLowerCase(), containerComponentType.getValue().toLowerCase(), containerComponentId);
1076 lockComponent(containerComponent, "updateComponentInstance");
1078 List<ComponentInstance> updatedList = new ArrayList<>();
1079 List<ComponentInstance> instancesFromContainerComponent = containerComponent.getComponentInstances();
1080 List<ComponentInstance> listForUpdate = new ArrayList<>();
1081 if (instancesFromContainerComponent == null || instancesFromContainerComponent.isEmpty()) {
1082 containerComponent.setComponentInstances(componentInstanceList);
1084 Iterator<ComponentInstance> iterator = instancesFromContainerComponent.iterator();
1085 while (iterator.hasNext()) {
1086 ComponentInstance origInst = iterator.next();
1087 Optional<ComponentInstance> op = componentInstanceList.stream().filter(ci -> ci.getUniqueId().equals(origInst.getUniqueId()))
1089 if (op.isPresent()) {
1090 ComponentInstance updatedCi = op.get();
1091 updatedCi = buildComponentInstance(updatedCi, origInst);
1092 Boolean isUniqueName = validateInstanceNameUniquenessUponUpdate(containerComponent, origInst, updatedCi.getName());
1093 if (!Boolean.TRUE.equals(isUniqueName)) {
1094 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
1095 "Failed to update the name of the component instance {} to {}. A component instance with the same name already exists. ",
1096 origInst.getName(), updatedCi.getName());
1097 throw new ByResponseFormatComponentException(componentsUtils
1098 .getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(), origInst.getName()));
1100 listForUpdate.add(updatedCi);
1102 listForUpdate.add(origInst);
1105 containerComponent.setComponentInstances(listForUpdate);
1106 Either<Component, StorageOperationStatus> updateStatus = toscaOperationFacade
1107 .updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, componentFilter);
1108 if (updateStatus.isRight()) {
1110 .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update metadata belonging to container component {}. Status is {}. ",
1111 containerComponent.getName(), updateStatus.right().value());
1112 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormatForResourceInstance(
1113 componentsUtils.convertFromStorageResponseForResourceInstance(updateStatus.right().value(), true), "", null));
1115 for (ComponentInstance updatedInstance : updateStatus.left().value().getComponentInstances()) {
1116 Optional<ComponentInstance> op = componentInstanceList.stream().filter(ci -> ci.getName().equals(updatedInstance.getName()))
1118 if (op.isPresent()) {
1119 updatedList.add(updatedInstance);
1124 } catch (ComponentException e) {
1129 unlockComponent(failed, containerComponent);
1134 private boolean validateParent(org.openecomp.sdc.be.model.Component containerComponent, String nodeTemplateId) {
1135 return containerComponent.getComponentInstances().stream().anyMatch(p -> p.getUniqueId().equals(nodeTemplateId));
1138 private ComponentTypeEnum getComponentType(ComponentTypeEnum containerComponentType) {
1139 if (ComponentTypeEnum.PRODUCT == containerComponentType) {
1140 return ComponentTypeEnum.SERVICE_INSTANCE;
1142 return ComponentTypeEnum.RESOURCE_INSTANCE;
1146 private ComponentInstance updateComponentInstanceMetadata(Component containerComponent, ComponentTypeEnum containerComponentType,
1147 org.openecomp.sdc.be.model.Component origComponent, String componentInstanceId,
1148 ComponentInstance componentInstance) {
1149 Optional<ComponentInstance> componentInstanceOptional;
1150 Either<ImmutablePair<Component, String>, StorageOperationStatus> updateRes = null;
1151 ComponentInstance oldComponentInstance = null;
1152 boolean isNameChanged = false;
1153 componentInstanceOptional = containerComponent.getComponentInstances().stream()
1154 .filter(ci -> ci.getUniqueId().equals(componentInstance.getUniqueId())).findFirst();
1155 if (!componentInstanceOptional.isPresent()) {
1156 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find the component instance {} in container component {}. ",
1157 componentInstance.getName(), containerComponent.getName());
1158 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName());
1160 String oldComponentName;
1161 oldComponentInstance = componentInstanceOptional.get();
1162 oldComponentName = oldComponentInstance.getName();
1163 String newInstanceName = componentInstance.getName();
1164 if (oldComponentName != null && !oldComponentInstance.getName().equals(newInstanceName)) {
1165 isNameChanged = true;
1167 Boolean isUniqueName = validateInstanceNameUniquenessUponUpdate(containerComponent, oldComponentInstance, newInstanceName);
1168 if (!Boolean.TRUE.equals(isUniqueName)) {
1169 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
1170 "Failed to update the name of the component instance {} to {}. A component instance with the same name already exists. ",
1171 oldComponentInstance.getName(), newInstanceName);
1172 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(),
1173 componentInstance.getName());
1175 if (!DirectivesUtil.isValid(componentInstance.getDirectives())) {
1176 final String directivesStr = componentInstance.getDirectives().stream().collect(Collectors.joining(" , ", " [ ", " ] "));
1177 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
1178 "Failed to update the directives of the component instance {} to {}. Directives data {} is invalid. ", oldComponentInstance.getName(),
1179 newInstanceName, directivesStr);
1180 throw new ByActionStatusComponentException(ActionStatus.DIRECTIVES_INVALID_VALUE, containerComponentType.getValue(),
1181 componentInstance.getName());
1183 updateRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, origComponent,
1184 updateComponentInstanceMetadata(oldComponentInstance, componentInstance));
1185 if (updateRes.isRight()) {
1186 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
1187 "Failed to update metadata of component instance {} belonging to container component {}. Status is {}. ", componentInstance.getName(),
1188 containerComponent.getName(), updateRes.right().value());
1189 throw new ByResponseFormatComponentException(componentsUtils
1190 .getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(updateRes.right().value(), true),
1193 // region - Update instance Groups
1194 if (isNameChanged) {
1195 Either<StorageOperationStatus, StorageOperationStatus> result = toscaOperationFacade
1196 .cleanAndAddGroupInstancesToComponentInstance(containerComponent, oldComponentInstance, componentInstanceId);
1197 if (result.isRight()) {
1199 .addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to rename group instances for container {}. error {} ", componentInstanceId,
1200 result.right().value());
1202 if (containerComponent instanceof Service) {
1203 Either<ComponentInstance, ResponseFormat> renameEither = renameServiceFilter((Service) containerComponent, newInstanceName,
1204 oldComponentInstance.getName());
1205 if (renameEither.isRight()) {
1206 throw new ByResponseFormatComponentException(renameEither.right().value());
1208 updateForwardingPathDefinition(containerComponent, componentInstance, oldComponentName);
1213 String newInstanceId = updateRes.left().value().getRight();
1214 Optional<ComponentInstance> updatedInstanceOptional = updateRes.left().value().getLeft().getComponentInstances().stream()
1215 .filter(ci -> ci.getUniqueId().equals(newInstanceId)).findFirst();
1216 if (!updatedInstanceOptional.isPresent()) {
1217 log.debug("Failed to update metadata of component instance {} of container component {}", componentInstance.getName(),
1218 containerComponent.getName());
1219 throw new ByResponseFormatComponentException(
1220 componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName()));
1222 return componentInstanceOptional.get();
1225 private void updateForwardingPathDefinition(Component containerComponent, ComponentInstance componentInstance, String oldComponentName) {
1226 Collection<ForwardingPathDataDefinition> forwardingPathDataDefinitions = getForwardingPathDataDefinitions(containerComponent.getUniqueId());
1227 Set<ForwardingPathDataDefinition> updated = new ForwardingPathUtils()
1228 .updateComponentInstanceName(forwardingPathDataDefinitions, oldComponentName, componentInstance.getName());
1229 updated.forEach(fp -> {
1230 Either<ForwardingPathDataDefinition, StorageOperationStatus> resultEither = forwardingPathOperation
1231 .updateForwardingPath(containerComponent.getUniqueId(), fp);
1232 if (resultEither.isRight()) {
1233 CommonUtility.addRecordToLog(log, LogLevelEnum.ERROR, "Failed to rename forwarding path for container {}. error {} ",
1234 containerComponent.getName(), resultEither.right().value());
1239 public Either<ComponentInstance, ResponseFormat> renameServiceFilter(final Service containerComponent, final String newInstanceName,
1240 final String oldInstanceName) {
1241 Map<String, CINodeFilterDataDefinition> renamedNodesFilter = ServiceFilterUtils
1242 .getRenamedNodesFilter(containerComponent, oldInstanceName, newInstanceName);
1243 for (Entry<String, CINodeFilterDataDefinition> entry : renamedNodesFilter.entrySet()) {
1244 Either<CINodeFilterDataDefinition, StorageOperationStatus> renameEither = nodeFilterOperation
1245 .updateNodeFilter(containerComponent.getUniqueId(), entry.getKey(), entry.getValue());
1246 if (renameEither.isRight()) {
1247 return Either.right(componentsUtils.getResponseFormatForResourceInstance(
1248 componentsUtils.convertFromStorageResponse(renameEither.right().value(), ComponentTypeEnum.SERVICE), containerComponent.getName(),
1252 return Either.left(null);
1256 * @param oldPrefix- The normalized old vf name
1257 * @param newNormailzedPrefix- The normalized new vf name
1258 * @param qualifiedGroupInstanceName- old Group Instance Name
1261 // modify group names
1262 private String getNewGroupName(String oldPrefix, String newNormailzedPrefix, String qualifiedGroupInstanceName) {
1263 if (qualifiedGroupInstanceName == null) {
1264 log.info("CANNOT change group name ");
1267 if (qualifiedGroupInstanceName.startsWith(oldPrefix) || qualifiedGroupInstanceName
1268 .startsWith(ValidationUtils.normalizeComponentInstanceName(oldPrefix))) {
1269 return qualifiedGroupInstanceName.replaceFirst(oldPrefix, newNormailzedPrefix);
1271 return qualifiedGroupInstanceName;
1274 private ComponentInstance updateComponentInstanceMetadata(ComponentInstance oldComponentInstance, ComponentInstance newComponentInstance) {
1275 oldComponentInstance.setName(newComponentInstance.getName());
1276 oldComponentInstance.setModificationTime(System.currentTimeMillis());
1277 oldComponentInstance.setCustomizationUUID(UUID.randomUUID().toString());
1278 oldComponentInstance.setDirectives(newComponentInstance.getDirectives());
1279 oldComponentInstance.setMaxOccurrences(newComponentInstance.getMaxOccurrences());
1280 oldComponentInstance.setMinOccurrences(newComponentInstance.getMinOccurrences());
1281 oldComponentInstance.setInstanceCount(newComponentInstance.getInstanceCount());
1282 if (oldComponentInstance.getGroupInstances() != null) {
1283 oldComponentInstance.getGroupInstances().forEach(group -> group.setName(getNewGroupName(oldComponentInstance.getNormalizedName(),
1284 ValidationUtils.normalizeComponentInstanceName(newComponentInstance.getName()), group.getName())));
1286 return oldComponentInstance;
1289 public ComponentInstance deleteComponentInstance(final String containerComponentParam, final String containerComponentId,
1290 final String componentInstanceId, String userId) throws BusinessLogicException {
1291 validateUserExists(userId);
1292 final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
1293 final Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, null);
1294 validateCanWorkOnComponent(containerComponent, userId);
1295 boolean failed = false;
1296 final Optional<ComponentInstance> componentInstanceOptional = containerComponent.getComponentInstanceById(componentInstanceId);
1297 if (!componentInstanceOptional.isPresent()) {
1298 throw new BusinessLogicException(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND));
1300 ComponentInstance componentInstance = componentInstanceOptional.get();
1302 if (containerComponent instanceof Service || containerComponent instanceof Resource) {
1303 final Either<String, StorageOperationStatus> deleteServiceFilterEither = nodeFilterOperation
1304 .deleteNodeFilter(containerComponent, componentInstanceId);
1305 if (deleteServiceFilterEither.isRight()) {
1306 final ActionStatus status = componentsUtils
1307 .convertFromStorageResponse(deleteServiceFilterEither.right().value(), containerComponentType);
1308 janusGraphDao.rollback();
1309 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(status, componentInstanceId));
1311 final Either<ComponentInstance, ResponseFormat> resultOp = deleteNodeFiltersFromComponentInstance(containerComponent,
1312 componentInstance, containerComponentType, userId);
1313 if (resultOp.isRight()) {
1314 janusGraphDao.rollback();
1315 throw new ByResponseFormatComponentException(resultOp.right().value());
1318 lockComponent(containerComponent, "deleteComponentInstance");
1319 final ComponentInstance deletedCompInstance = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentType);
1320 componentInstance = deleteForwardingPathsRelatedTobeDeletedComponentInstance(containerComponentId, containerComponentType,
1321 deletedCompInstance);
1322 final ActionStatus onDeleteOperationsStatus = onChangeInstanceOperationOrchestrator
1323 .doOnDeleteInstanceOperations(containerComponent, componentInstanceId);
1324 if (ActionStatus.OK != onDeleteOperationsStatus) {
1325 throw new ByActionStatusComponentException(onDeleteOperationsStatus);
1327 } catch (final ComponentException e) {
1331 unlockComponent(failed, containerComponent);
1333 return componentInstance;
1337 * Try to modify the delete and return two cases
1339 * @param containerComponentParam
1340 * @param containerComponentId
1341 * @param componentInstanceId
1345 public Either<ComponentInstance, ResponseFormat> deleteAbstractComponentInstance(String containerComponentParam, String containerComponentId,
1346 String componentInstanceId, String userId) {
1347 log.debug("enter deleteAbstractComponentInstance");
1348 validateUserExists(userId);
1349 final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
1350 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, null);
1351 validateCanWorkOnComponent(containerComponent, userId);
1352 boolean failed = false;
1353 ComponentInstance deletedRelatedInst;
1355 if (containerComponent instanceof Service) {
1356 final Optional<ComponentInstance> componentInstanceById = containerComponent.getComponentInstanceById(componentInstanceId);
1357 if (componentInstanceById.isPresent()) {
1358 ComponentInstance componentInstance = componentInstanceById.get();
1359 Either<String, StorageOperationStatus> deleteServiceFilterEither = nodeFilterOperation
1360 .deleteNodeFilter(containerComponent, componentInstanceId);
1361 if (deleteServiceFilterEither.isRight()) {
1362 log.debug("enter deleteAbstractComponentInstance:deleteServiceFilterEither is right, filed");
1363 ActionStatus status = componentsUtils
1364 .convertFromStorageResponse(deleteServiceFilterEither.right().value(), containerComponentType);
1365 janusGraphDao.rollback();
1366 return Either.right(componentsUtils.getResponseFormat(status, componentInstance.getName()));
1368 Either<ComponentInstance, ResponseFormat> resultOp = deleteNodeFiltersFromComponentInstance(containerComponent, componentInstance,
1369 ComponentTypeEnum.SERVICE, userId);
1370 if (resultOp.isRight()) {
1371 log.debug("enter deleteAbstractComponentInstance:resultOp is right, filed");
1372 janusGraphDao.rollback();
1377 log.debug("enter deleteAbstractComponentInstance:");
1378 lockComponent(containerComponent, "deleteComponentInstance");
1379 ComponentInstance deletedCompInstance = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentType);
1380 deletedRelatedInst = deleteForwardingPathsRelatedTobeDeletedComponentInstance(containerComponentId, containerComponentType,
1381 deletedCompInstance);
1382 ActionStatus onDeleteOperationsStatus = onChangeInstanceOperationOrchestrator
1383 .doOnDeleteInstanceOperations(containerComponent, componentInstanceId);
1384 log.debug("enter deleteAbstractComponentInstance,get onDeleteOperationsStatus:{}", onDeleteOperationsStatus);
1385 if (ActionStatus.OK != onDeleteOperationsStatus) {
1386 throw new ByActionStatusComponentException(onDeleteOperationsStatus);
1388 } catch (ComponentException e) {
1392 unlockComponent(failed, containerComponent);
1394 log.debug("enter deleteAbstractComponentInstance,deleted RelatedInst success");
1395 return Either.left(deletedRelatedInst);
1398 public Either<ComponentInstance, ResponseFormat> deleteNodeFiltersFromComponentInstance(final Component component,
1399 final ComponentInstance componentInstance,
1400 final ComponentTypeEnum containerComponentType,
1401 final String userId) {
1402 final Set<String> componentFiltersIDsToBeDeleted = getComponentFiltersRelatedToComponentInstance(component.getUniqueId(), componentInstance);
1403 if (!componentFiltersIDsToBeDeleted.isEmpty()) {
1404 final Set<String> ids = component.getComponentInstances().stream().filter(ci -> componentFiltersIDsToBeDeleted.contains(ci.getName()))
1405 .map(ComponentInstance::getUniqueId).collect(Collectors.toSet());
1406 final Either<Set<String>, StorageOperationStatus> deleteComponentNodeFiltersEither = nodeFilterOperation
1407 .deleteNodeFilters(component, ids);
1408 if (deleteComponentNodeFiltersEither.isRight()) {
1409 final ActionStatus status = componentsUtils
1410 .convertFromStorageResponse(deleteComponentNodeFiltersEither.right().value(), containerComponentType);
1411 return Either.right(componentsUtils.getResponseFormat(status, componentInstance.getName()));
1413 for (final String id : ids) {
1414 final Optional<ComponentInstance> componentInstanceById = component.getComponentInstanceById(id);
1415 if (!componentInstanceById.isPresent()) {
1416 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
1418 final ComponentInstance componentInstanceToBeUpdated = componentInstanceById.get();
1419 componentInstanceToBeUpdated.setDirectives(Collections.emptyList());
1420 final Either<ComponentInstance, ResponseFormat> componentInstanceResponseFormatEither = updateComponentInstanceMetadata(
1421 containerComponentType.getValue(), component.getUniqueId(), componentInstanceToBeUpdated.getUniqueId(), userId,
1422 componentInstanceToBeUpdated, false);
1423 if (componentInstanceResponseFormatEither.isRight()) {
1424 return componentInstanceResponseFormatEither;
1428 return Either.left(componentInstance);
1431 private Set<String> getComponentFiltersRelatedToComponentInstance(String containerComponentId, ComponentInstance componentInstance) {
1432 ComponentParametersView filter = new ComponentParametersView(true);
1433 filter.setIgnoreComponentInstances(false);
1434 Either<Component, StorageOperationStatus> componentFilterOrigin = toscaOperationFacade.getToscaElement(containerComponentId, filter);
1435 final Component component = componentFilterOrigin.left().value();
1436 return ComponentsUtils.getNodesFiltersToBeDeleted(component, componentInstance);
1439 ComponentInstance deleteForwardingPathsRelatedTobeDeletedComponentInstance(String containerComponentId, ComponentTypeEnum containerComponentType,
1440 ComponentInstance componentInstance) {
1441 if (containerComponentType == ComponentTypeEnum.SERVICE) {
1442 List<String> pathIDsToBeDeleted = getForwardingPathsRelatedToComponentInstance(containerComponentId, componentInstance.getName());
1443 if (!pathIDsToBeDeleted.isEmpty()) {
1444 deleteForwardingPaths(containerComponentId, pathIDsToBeDeleted);
1447 return componentInstance;
1450 private void deleteForwardingPaths(String serviceId, List<String> pathIdsToDelete) {
1451 Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(serviceId);
1452 if (storageStatus.isRight()) {
1453 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(storageStatus.right().value()));
1455 Either<Set<String>, StorageOperationStatus> result = forwardingPathOperation
1456 .deleteForwardingPath(storageStatus.left().value(), Sets.newHashSet(pathIdsToDelete));
1457 if (result.isRight()) {
1458 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(result.right().value()));
1462 private List<String> getForwardingPathsRelatedToComponentInstance(String containerComponentId, String componentInstanceId) {
1463 Collection<ForwardingPathDataDefinition> allPaths = getForwardingPathDataDefinitions(containerComponentId);
1464 List<String> pathIDsToBeDeleted = new ArrayList<>();
1465 allPaths.stream().filter(path -> isPathRelatedToComponent(path, componentInstanceId))
1466 .forEach(path -> pathIDsToBeDeleted.add(path.getUniqueId()));
1467 return pathIDsToBeDeleted;
1470 private Collection<ForwardingPathDataDefinition> getForwardingPathDataDefinitions(String containerComponentId) {
1471 ComponentParametersView filter = new ComponentParametersView(true);
1472 filter.setIgnoreServicePath(false);
1473 Either<Service, StorageOperationStatus> forwardingPathOrigin = toscaOperationFacade.getToscaElement(containerComponentId, filter);
1474 return forwardingPathOrigin.left().value().getForwardingPaths().values();
1477 private boolean isPathRelatedToComponent(ForwardingPathDataDefinition pathDataDefinition, String componentInstanceId) {
1478 return pathDataDefinition.getPathElements().getListToscaDataDefinition().stream().anyMatch(
1479 elementDataDefinition -> elementDataDefinition.getFromNode().equalsIgnoreCase(componentInstanceId) || elementDataDefinition.getToNode()
1480 .equalsIgnoreCase(componentInstanceId));
1483 private ComponentInstance deleteComponentInstance(Component containerComponent, String componentInstanceId,
1484 ComponentTypeEnum containerComponentType) {
1485 Either<ImmutablePair<Component, String>, StorageOperationStatus> deleteRes = toscaOperationFacade
1486 .deleteComponentInstanceFromTopologyTemplate(containerComponent, componentInstanceId);
1487 if (deleteRes.isRight()) {
1488 log.debug("Failed to delete entry on graph for resourceInstance {}", componentInstanceId);
1489 ActionStatus status = componentsUtils.convertFromStorageResponse(deleteRes.right().value(), containerComponentType);
1490 throw new ByActionStatusComponentException(status, componentInstanceId);
1492 log.debug("The component instance {} has been removed from container component {}. ", componentInstanceId, containerComponent);
1493 ComponentInstance deletedInstance = findAndRemoveComponentInstanceFromContainerComponent(componentInstanceId, containerComponent);
1494 if (CollectionUtils.isNotEmpty(containerComponent.getInputs())) {
1495 List<InputDefinition> inputsToDelete = containerComponent.getInputs().stream()
1496 .filter(i -> i.getInstanceUniqueId() != null && i.getInstanceUniqueId().equals(componentInstanceId)).collect(Collectors.toList());
1497 if (CollectionUtils.isNotEmpty(inputsToDelete)) {
1498 StorageOperationStatus deleteInputsRes = toscaOperationFacade
1499 .deleteComponentInstanceInputsFromTopologyTemplate(containerComponent, inputsToDelete);
1500 if (deleteInputsRes != StorageOperationStatus.OK) {
1501 log.debug("Failed to delete inputs of the component instance {} from container component. ", componentInstanceId);
1502 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(deleteInputsRes, containerComponentType),
1503 componentInstanceId);
1507 if (CollectionUtils.isNotEmpty(containerComponent.getOutputs())) {
1508 final List<OutputDefinition> outputsToDelete = containerComponent.getOutputs().stream()
1509 .filter(i -> i.getInstanceUniqueId() != null && i.getInstanceUniqueId().equals(componentInstanceId)).collect(Collectors.toList());
1510 if (CollectionUtils.isNotEmpty(outputsToDelete)) {
1511 final StorageOperationStatus deleteOutputsRes = toscaOperationFacade
1512 .deleteComponentInstanceOutputsFromTopologyTemplate(containerComponent, outputsToDelete);
1513 if (deleteOutputsRes != StorageOperationStatus.OK) {
1514 log.debug("Failed to delete outputs of the component instance {} from container component. ", componentInstanceId);
1515 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(deleteOutputsRes, containerComponentType),
1516 componentInstanceId);
1520 return deletedInstance;
1523 private ComponentInstance findAndRemoveComponentInstanceFromContainerComponent(String componentInstanceId, Component containerComponent) {
1524 ComponentInstance foundInstance = null;
1525 for (ComponentInstance instance : containerComponent.getComponentInstances()) {
1526 if (instance.getUniqueId().equals(componentInstanceId)) {
1527 foundInstance = instance;
1528 containerComponent.getComponentInstances().remove(instance);
1532 findAndRemoveComponentInstanceRelations(componentInstanceId, containerComponent);
1533 return foundInstance;
1536 private void findAndRemoveComponentInstanceRelations(String componentInstanceId, Component containerComponent) {
1537 if (CollectionUtils.isNotEmpty(containerComponent.getComponentInstancesRelations())) {
1538 containerComponent.setComponentInstancesRelations(
1539 containerComponent.getComponentInstancesRelations().stream().filter(r -> isNotBelongingRelation(componentInstanceId, r))
1540 .collect(Collectors.toList()));
1544 private boolean isNotBelongingRelation(String componentInstanceId, RequirementCapabilityRelDef relation) {
1545 return !relation.getToNode().equals(componentInstanceId) && !relation.getFromNode().equals(componentInstanceId);
1548 public RequirementCapabilityRelDef associateRIToRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef,
1549 ComponentTypeEnum componentTypeEnum) {
1550 return associateRIToRI(componentId, userId, requirementDef, componentTypeEnum, true);
1553 public RequirementCapabilityRelDef associateRIToRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef,
1554 ComponentTypeEnum componentTypeEnum, boolean needLock) {
1555 validateUserExists(userId);
1556 RequirementCapabilityRelDef requirementCapabilityRelDef;
1557 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(componentId, componentTypeEnum, null);
1558 validateCanWorkOnComponent(containerComponent, userId);
1559 boolean failed = false;
1562 lockComponent(containerComponent, ASSOCIATE_RI_TO_RI);
1564 requirementCapabilityRelDef = associateRIToRIOnGraph(containerComponent, requirementDef);
1565 } catch (ComponentException e) {
1570 unlockComponent(failed, containerComponent);
1573 return requirementCapabilityRelDef;
1576 public RequirementCapabilityRelDef associateRIToRIOnGraph(Component containerComponent, RequirementCapabilityRelDef requirementDef) {
1577 log.debug(TRY_TO_CREATE_ENTRY_ON_GRAPH);
1578 Either<RequirementCapabilityRelDef, StorageOperationStatus> result = toscaOperationFacade
1579 .associateResourceInstances(null, containerComponent.getUniqueId(), requirementDef);
1580 if (result.isLeft()) {
1581 log.debug(ENTITY_ON_GRAPH_IS_CREATED);
1582 return result.left().value();
1584 log.debug("Failed to associate node: {} with node {}", requirementDef.getFromNode(), requirementDef.getToNode());
1585 String fromNameOrId = "";
1586 String toNameOrId = "";
1587 Either<ComponentInstance, StorageOperationStatus> fromResult = getResourceInstanceById(containerComponent, requirementDef.getFromNode());
1588 Either<ComponentInstance, StorageOperationStatus> toResult = getResourceInstanceById(containerComponent, requirementDef.getToNode());
1589 toNameOrId = requirementDef.getFromNode();
1590 fromNameOrId = requirementDef.getFromNode();
1591 if (fromResult.isLeft()) {
1592 fromNameOrId = fromResult.left().value().getName();
1594 if (toResult.isLeft()) {
1595 toNameOrId = toResult.left().value().getName();
1597 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true),
1598 fromNameOrId, toNameOrId, requirementDef.getRelationships().get(0).getRelation().getRequirement());
1603 * @param componentId
1605 * @param requirementDefList
1606 * @param componentTypeEnum
1609 public List<RequirementCapabilityRelDef> batchDissociateRIFromRI(String componentId, String userId,
1610 List<RequirementCapabilityRelDef> requirementDefList,
1611 ComponentTypeEnum componentTypeEnum) {
1612 validateUserExists(userId);
1613 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(componentId, componentTypeEnum, null);
1614 validateCanWorkOnComponent(containerComponent, userId);
1615 boolean failed = false;
1616 List<RequirementCapabilityRelDef> delOkResult = new ArrayList<>();
1618 lockComponent(containerComponent, ASSOCIATE_RI_TO_RI);
1619 for (RequirementCapabilityRelDef requirementDef : requirementDefList) {
1620 RequirementCapabilityRelDef requirementCapabilityRelDef = dissociateRIFromRI(componentId, userId, requirementDef,
1621 containerComponent.getComponentType());
1622 delOkResult.add(requirementCapabilityRelDef);
1624 } catch (ComponentException e) {
1628 unlockComponent(failed, containerComponent);
1633 public RequirementCapabilityRelDef dissociateRIFromRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef,
1634 ComponentTypeEnum componentTypeEnum) {
1635 validateUserExists(userId);
1636 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(componentId, componentTypeEnum, null);
1637 validateCanWorkOnComponent(containerComponent, userId);
1638 boolean failed = false;
1640 lockComponent(containerComponent, ASSOCIATE_RI_TO_RI);
1641 log.debug(TRY_TO_CREATE_ENTRY_ON_GRAPH);
1642 Either<RequirementCapabilityRelDef, StorageOperationStatus> result = toscaOperationFacade
1643 .dissociateResourceInstances(componentId, requirementDef);
1644 if (result.isLeft()) {
1645 log.debug(ENTITY_ON_GRAPH_IS_CREATED);
1646 return result.left().value();
1648 log.debug("Failed to dissocaite node {} from node {}", requirementDef.getFromNode(), requirementDef.getToNode());
1649 String fromNameOrId = "";
1650 String toNameOrId = "";
1651 Either<ComponentInstance, StorageOperationStatus> fromResult = getResourceInstanceById(containerComponent,
1652 requirementDef.getFromNode());
1653 Either<ComponentInstance, StorageOperationStatus> toResult = getResourceInstanceById(containerComponent, requirementDef.getToNode());
1654 toNameOrId = requirementDef.getFromNode();
1655 fromNameOrId = requirementDef.getFromNode();
1656 if (fromResult.isLeft()) {
1657 fromNameOrId = fromResult.left().value().getName();
1659 if (toResult.isLeft()) {
1660 toNameOrId = toResult.left().value().getName();
1662 throw new ByActionStatusComponentException(
1663 componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), fromNameOrId, toNameOrId,
1664 requirementDef.getRelationships().get(0).getRelation().getRequirement());
1666 } catch (ComponentException e) {
1670 unlockComponent(failed, containerComponent);
1675 * Allows to get relation contained in specified component according to received Id
1677 * @param componentId
1680 * @param componentTypeEnum
1683 public Either<RequirementCapabilityRelDef, ResponseFormat> getRelationById(String componentId, String relationId, String userId,
1684 ComponentTypeEnum componentTypeEnum) {
1685 Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null;
1687 org.openecomp.sdc.be.model.Component containerComponent = null;
1688 RequirementCapabilityRelDef foundRelation = null;
1689 validateUserExists(userId);
1690 containerComponent = validateComponentExists(componentId, componentTypeEnum, null);
1691 List<RequirementCapabilityRelDef> requirementCapabilityRelations = containerComponent.getComponentInstancesRelations();
1692 foundRelation = findRelation(relationId, requirementCapabilityRelations);
1693 if (foundRelation == null) {
1694 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RELATION_NOT_FOUND, relationId, componentId);
1695 log.debug("Relation with id {} was not found on the component", relationId, componentId);
1696 resultOp = Either.right(responseFormat);
1698 if (resultOp == null) {
1699 resultOp = setRelatedCapability(foundRelation, containerComponent);
1701 if (resultOp.isLeft()) {
1702 resultOp = setRelatedRequirement(foundRelation, containerComponent);
1704 } catch (Exception e) {
1705 log.error("The exception {} occured upon get relation {} of the component {} ", e, relationId, componentId);
1706 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
1711 private RequirementCapabilityRelDef findRelation(String relationId, List<RequirementCapabilityRelDef> requirementCapabilityRelations) {
1712 for (RequirementCapabilityRelDef relationship : requirementCapabilityRelations) {
1713 if (relationship.getRelationships().stream().anyMatch(r -> r.getRelation().getId().equals(relationId))) {
1714 return relationship;
1720 private Either<RequirementCapabilityRelDef, ResponseFormat> setRelatedRequirement(RequirementCapabilityRelDef foundRelation,
1721 Component containerComponent) {
1722 Either<RequirementCapabilityRelDef, ResponseFormat> result = null;
1723 RelationshipInfo relationshipInfo = foundRelation.resolveSingleRelationship().getRelation();
1724 String instanceId = foundRelation.getFromNode();
1725 Optional<RequirementDefinition> foundRequirement;
1726 Optional<ComponentInstance> instance = containerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(instanceId))
1728 if (!instance.isPresent()) {
1729 ResponseFormat responseFormat = componentsUtils
1730 .getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, instanceId, "instance",
1731 containerComponent.getComponentType().getValue(), containerComponent.getName());
1732 log.debug("Component instance with id {} was not found on the component", instanceId, containerComponent.getUniqueId());
1733 result = Either.right(responseFormat);
1735 if (result == null && instance.isPresent()) {
1736 for (List<RequirementDefinition> requirements : instance.get().getRequirements().values()) {
1737 foundRequirement = requirements.stream()
1738 .filter(r -> isBelongingCalcRequirement(relationshipInfo, r, containerComponent.getLifecycleState())).findFirst();
1739 if (foundRequirement.isPresent()) {
1740 foundRelation.resolveSingleRelationship().setRequirement(foundRequirement.get());
1741 result = Either.left(foundRelation);
1745 if (result == null) {
1746 Either<RequirementDataDefinition, StorageOperationStatus> getfulfilledRequirementRes = toscaOperationFacade
1747 .getFulfilledRequirementByRelation(containerComponent.getUniqueId(), instanceId, foundRelation, this::isBelongingFullRequirement);
1748 if (getfulfilledRequirementRes.isRight()) {
1749 ResponseFormat responseFormat = componentsUtils
1750 .getResponseFormat(ActionStatus.REQUIREMENT_OF_INSTANCE_NOT_FOUND_ON_CONTAINER, relationshipInfo.getRequirement(), instanceId,
1751 containerComponent.getUniqueId());
1752 log.debug("Requirement {} of instance {} was not found on the container {}. ", relationshipInfo.getCapability(), instanceId,
1753 containerComponent.getUniqueId());
1754 result = Either.right(responseFormat);
1756 foundRelation.resolveSingleRelationship().setRequirement(getfulfilledRequirementRes.left().value());
1759 if (result == null) {
1760 result = Either.left(foundRelation);
1765 private boolean isBelongingFullRequirement(RelationshipInfo relationshipInfo, RequirementDataDefinition req) {
1766 return req.getName().equals(relationshipInfo.getRequirement()) && req.getUniqueId().equals(relationshipInfo.getRequirementUid()) && req
1767 .getOwnerId().equals(relationshipInfo.getRequirementOwnerId());
1770 private boolean isBelongingCalcRequirement(RelationshipInfo relationshipInfo, RequirementDataDefinition req, LifecycleStateEnum state) {
1771 return nameMatches(relationshipInfo.getRequirement(), req.getName(), req.getPreviousName(), state) && req.getUniqueId()
1772 .equals(relationshipInfo.getRequirementUid()) && req.getOwnerId().equals(relationshipInfo.getRequirementOwnerId());
1775 private Either<RequirementCapabilityRelDef, ResponseFormat> setRelatedCapability(RequirementCapabilityRelDef foundRelation,
1776 Component containerComponent) {
1777 Either<RequirementCapabilityRelDef, ResponseFormat> result = null;
1778 RelationshipInfo relationshipInfo = foundRelation.resolveSingleRelationship().getRelation();
1779 String instanceId = foundRelation.getToNode();
1780 Optional<CapabilityDefinition> foundCapability;
1781 Optional<ComponentInstance> instance = containerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(instanceId))
1783 if (!instance.isPresent()) {
1784 ResponseFormat responseFormat = componentsUtils
1785 .getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, instanceId, "instance",
1786 containerComponent.getComponentType().getValue(), containerComponent.getName());
1787 log.debug("Component instance with id {} was not found on the component", instanceId, containerComponent.getUniqueId());
1788 result = Either.right(responseFormat);
1790 if (result == null && instance.isPresent()) {
1791 for (List<CapabilityDefinition> capabilities : instance.get().getCapabilities().values()) {
1792 foundCapability = capabilities.stream()
1793 .filter(c -> isBelongingCalcCapability(relationshipInfo, c, containerComponent.getLifecycleState())).findFirst();
1794 if (foundCapability.isPresent()) {
1795 foundRelation.resolveSingleRelationship().setCapability(foundCapability.get());
1796 result = Either.left(foundRelation);
1800 if (result == null) {
1801 Either<CapabilityDataDefinition, StorageOperationStatus> getfulfilledRequirementRes = toscaOperationFacade
1802 .getFulfilledCapabilityByRelation(containerComponent.getUniqueId(), instanceId, foundRelation, this::isBelongingFullCapability);
1803 if (getfulfilledRequirementRes.isRight()) {
1804 ResponseFormat responseFormat = componentsUtils
1805 .getResponseFormat(ActionStatus.CAPABILITY_OF_INSTANCE_NOT_FOUND_ON_CONTAINER, relationshipInfo.getCapability(), instanceId,
1806 containerComponent.getUniqueId());
1807 log.debug("Capability {} of instance {} was not found on the container {}. ", relationshipInfo.getCapability(), instanceId,
1808 containerComponent.getUniqueId());
1809 result = Either.right(responseFormat);
1811 foundRelation.resolveSingleRelationship().setCapability(getfulfilledRequirementRes.left().value());
1814 if (result == null) {
1815 result = Either.left(foundRelation);
1820 private boolean isBelongingFullCapability(RelationshipInfo relationshipInfo, CapabilityDataDefinition cap) {
1821 return cap.getName().equals(relationshipInfo.getCapability()) && cap.getUniqueId().equals(relationshipInfo.getCapabilityUid()) && cap
1822 .getOwnerId().equals(relationshipInfo.getCapabilityOwnerId());
1825 private boolean isBelongingCalcCapability(RelationshipInfo relationshipInfo, CapabilityDataDefinition cap, LifecycleStateEnum state) {
1826 return nameMatches(relationshipInfo.getCapability(), cap.getName(), cap.getPreviousName(), state) && cap.getUniqueId()
1827 .equals(relationshipInfo.getCapabilityUid()) && cap.getOwnerId().equals(relationshipInfo.getCapabilityOwnerId());
1830 private boolean nameMatches(String nameFromRelationship, String currName, String previousName, LifecycleStateEnum state) {
1831 return state == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT ? currName.equals(nameFromRelationship)
1832 : previousName != null && previousName.equals(nameFromRelationship);
1835 private Either<ComponentInstanceProperty, ResponseFormat> updateAttributeValue(ComponentInstanceProperty attribute, String resourceInstanceId) {
1836 Either<ComponentInstanceProperty, StorageOperationStatus> eitherAttribute = componentInstanceOperation
1837 .updateAttributeValueInResourceInstance(attribute, resourceInstanceId, true);
1838 Either<ComponentInstanceProperty, ResponseFormat> result;
1839 if (eitherAttribute.isLeft()) {
1840 log.debug("Attribute value {} was updated on graph.", attribute.getValueUniqueUid());
1841 ComponentInstanceProperty instanceAttribute = eitherAttribute.left().value();
1842 result = Either.left(instanceAttribute);
1844 log.debug("Failed to update attribute value {} in resource instance {}", attribute, resourceInstanceId);
1845 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(eitherAttribute.right().value());
1846 result = Either.right(componentsUtils.getResponseFormat(actionStatus, ""));
1851 private Either<ComponentInstanceProperty, ResponseFormat> createAttributeValue(ComponentInstanceProperty attribute, String resourceInstanceId) {
1852 Either<ComponentInstanceProperty, ResponseFormat> result;
1853 Wrapper<Integer> indexCounterWrapper = new Wrapper<>();
1854 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
1855 validateIncrementCounter(resourceInstanceId, GraphPropertiesDictionary.ATTRIBUTE_COUNTER, indexCounterWrapper, errorWrapper);
1856 if (!errorWrapper.isEmpty()) {
1857 result = Either.right(errorWrapper.getInnerElement());
1859 Either<ComponentInstanceProperty, StorageOperationStatus> eitherAttribute = componentInstanceOperation
1860 .addAttributeValueToResourceInstance(attribute, resourceInstanceId, indexCounterWrapper.getInnerElement(), true);
1861 if (eitherAttribute.isLeft()) {
1862 log.debug("Attribute value was added to resource instance {}", resourceInstanceId);
1863 ComponentInstanceProperty instanceAttribute = eitherAttribute.left().value();
1864 result = Either.left(instanceAttribute);
1866 log.debug("Failed to add attribute value {} to resource instance {}", attribute, resourceInstanceId);
1867 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(eitherAttribute.right().value());
1868 result = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1875 * Create Or Updates Attribute Instance
1877 * @param componentTypeEnum
1878 * @param componentId
1879 * @param resourceInstanceId
1884 public Either<ComponentInstanceProperty, ResponseFormat> createOrUpdateAttributeValue(ComponentTypeEnum componentTypeEnum, String componentId,
1885 String resourceInstanceId,
1886 ComponentInstanceProperty attribute, String userId) {
1887 Either<ComponentInstanceProperty, ResponseFormat> result = null;
1888 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
1889 validateUserExists(userId);
1890 if (errorWrapper.isEmpty()) {
1891 validateComponentTypeEnum(componentTypeEnum, "CreateOrUpdateAttributeValue", errorWrapper);
1893 if (errorWrapper.isEmpty()) {
1894 validateCanWorkOnComponent(componentId, componentTypeEnum, userId, errorWrapper);
1896 if (errorWrapper.isEmpty()) {
1897 validateComponentLock(componentId, componentTypeEnum, errorWrapper);
1900 if (errorWrapper.isEmpty()) {
1901 final boolean isCreate = Objects.isNull(attribute.getValueUniqueUid());
1903 result = createAttributeValue(attribute, resourceInstanceId);
1905 result = updateAttributeValue(attribute, resourceInstanceId);
1908 result = Either.right(errorWrapper.getInnerElement());
1912 if (result == null || result.isRight()) {
1913 janusGraphDao.rollback();
1915 janusGraphDao.commit();
1918 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
1922 public Either<List<ComponentInstanceProperty>, ResponseFormat> createOrUpdatePropertiesValues(ComponentTypeEnum componentTypeEnum,
1923 String componentId, String resourceInstanceId,
1924 List<ComponentInstanceProperty> properties,
1926 Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
1927 /*-------------------------------Validations---------------------------------*/
1928 validateUserExists(userId);
1930 if (componentTypeEnum == null) {
1931 BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertiesValues", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
1932 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
1935 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
1937 if (getResourceResult.isRight()) {
1938 log.debug(FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID, componentId);
1939 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getResourceResult.right().value(), componentTypeEnum);
1940 return Either.right(componentsUtils.getResponseFormat(actionStatus, componentId));
1942 Component containerComponent = getResourceResult.left().value();
1944 if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
1945 if (Boolean.TRUE.equals(containerComponent.isArchived())) {
1946 log.info(COMPONENT_ARCHIVED, componentId);
1947 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_IS_ARCHIVED, containerComponent.getName()));
1949 log.info(RESTRICTED_OPERATION_ON_SERVIVE, userId, componentId);
1950 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1953 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId);
1954 if (resourceInstanceStatus.isRight()) {
1955 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER,
1956 resourceInstanceId, RESOURCE_INSTANCE, SERVICE, componentId));
1958 ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
1960 // Validate instance property against it's constrains
1961 Either<Boolean, ResponseFormat> constraintValidatorResponse = validatePropertyValueConstraint(properties,componentId);
1962 if (constraintValidatorResponse.isRight()) {
1963 log.error("Failed validation value and constraint of property: {}", constraintValidatorResponse.right().value());
1964 return Either.right(constraintValidatorResponse.right().value());
1967 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
1968 if (lockStatus != StorageOperationStatus.OK) {
1969 log.debug(FAILED_TO_LOCK_SERVICE, componentId);
1970 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
1972 List<ComponentInstanceProperty> updatedProperties = new ArrayList<>();
1974 for (ComponentInstanceProperty property : properties) {
1975 validateMandatoryFields(property);
1976 validatePropertyExistsOnComponent(property, containerComponent, foundResourceInstance);
1977 String propertyParentUniqueId = property.getParentUniqueId();
1978 if (property.isToscaFunction()) {
1979 toscaFunctionValidator.validate(property, containerComponent);
1980 property.setValue(property.getToscaFunction().getValue());
1983 if (CollectionUtils.isNotEmpty(property.getSubPropertyToscaFunctions())){
1984 final JSONObject jObject = property.getValue() == null ? new JSONObject() : new JSONObject(property.getValue());
1985 property.getSubPropertyToscaFunctions().stream().forEach(subToscaFunction -> {
1986 setJsonObjectForSubProperty(jObject, subToscaFunction.getSubPropertyPath(), subToscaFunction.getToscaFunction().getValue());
1988 property.setValue(jObject.toString());
1990 Either<String, ResponseFormat> updatedPropertyValue = updatePropertyObjectValue(property, containerComponent.getModel());
1991 if (updatedPropertyValue.isRight()) {
1992 log.error("Failed to update property object value of property: {}",
1994 throw new ByResponseFormatComponentException(updatedPropertyValue.right().value());
1996 Optional<CapabilityDefinition>
1997 capPropDefinition = getPropertyCapabilityOfChildInstance(propertyParentUniqueId, foundResourceInstance.getCapabilities());
1998 if (capPropDefinition.isPresent()) {
1999 updatedPropertyValue
2000 .bimap(updatedValue -> updateCapabilityPropFromUpdateInstProp(property, updatedValue,
2001 containerComponent, foundResourceInstance, capPropDefinition.get().getType(),
2002 capPropDefinition.get().getName()), Either::right);
2004 updatedPropertyValue.bimap(
2005 updatedValue -> updatePropertyOnContainerComponent(property, updatedValue, containerComponent, foundResourceInstance),
2008 updatedProperties.add(property);
2012 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade
2013 .updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
2014 if (updateContainerRes.isRight()) {
2015 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
2016 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2019 resultOp = Either.left(updatedProperties);
2022 } catch (final ComponentException e) {
2023 return Either.right(e.getResponseFormat());
2025 if (resultOp == null || resultOp.isRight()) {
2026 janusGraphDao.rollback();
2028 janusGraphDao.commit();
2031 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
2035 private void setJsonObjectForSubProperty(final JSONObject jObject, final List<String> path, String value) {
2036 if (path.size() == 1) {
2037 Object valueAsObject = new Yaml().loadAs(value, Object.class);
2038 jObject.put(path.get(0), valueAsObject);
2040 if (!jObject.has(path.get(0))) {
2041 jObject.put(path.get(0), new JSONObject());
2043 final JSONObject jsonObject = jObject.getJSONObject(path.get(0));
2044 setJsonObjectForSubProperty(jsonObject, path.subList(1, path.size()), value);
2048 public Either<List<ComponentInstanceAttribute>, ResponseFormat> createOrUpdateAttributeValues(final ComponentTypeEnum componentTypeEnum,
2049 final String componentId,
2050 final String resourceInstanceId,
2051 final List<ComponentInstanceAttribute> attributes,
2052 final String userId) {
2053 Either<List<ComponentInstanceAttribute>, ResponseFormat> resultOp = null;
2054 /*-------------------------------Validations---------------------------------*/
2055 validateUserExists(userId);
2057 if (componentTypeEnum == null) {
2058 BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertiesValues", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
2059 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
2062 final Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade
2063 .getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
2065 if (getResourceResult.isRight()) {
2066 log.debug(FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID, componentId);
2067 final ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getResourceResult.right().value(), componentTypeEnum);
2068 return Either.right(componentsUtils.getResponseFormat(actionStatus, componentId));
2070 final Component containerComponent = getResourceResult.left().value();
2072 if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
2073 if (Boolean.TRUE.equals(containerComponent.isArchived())) {
2074 log.info(COMPONENT_ARCHIVED, componentId);
2075 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_IS_ARCHIVED, containerComponent.getName()));
2077 log.info(RESTRICTED_OPERATION_ON_SERVIVE, userId, componentId);
2078 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2081 final Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent,
2082 resourceInstanceId);
2083 if (resourceInstanceStatus.isRight()) {
2084 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER,
2085 resourceInstanceId, RESOURCE_INSTANCE, SERVICE, componentId));
2087 final ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
2090 final StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
2091 if (lockStatus != StorageOperationStatus.OK) {
2092 log.debug(FAILED_TO_LOCK_SERVICE, componentId);
2093 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
2095 final List<ComponentInstanceAttribute> updatedProperties = new ArrayList<>();
2097 for (final ComponentInstanceAttribute attribute : attributes) {
2098 final ComponentInstanceAttribute componentInstanceProperty = validateAttributeExistsOnComponent(attribute, containerComponent,
2099 foundResourceInstance);
2100 final Either<String, ResponseFormat> updatedPropertyValue = updateAttributeObjectValue(attribute);
2101 if (updatedPropertyValue.isRight()) {
2102 log.error("Failed to update attribute object value of attribute: {}", attribute);
2103 throw new ByResponseFormatComponentException(updatedPropertyValue.right().value());
2105 updatedPropertyValue.bimap(
2107 componentInstanceProperty.setValue(updatedValue);
2108 return updateAttributeOnContainerComponent(attribute, updatedValue,
2109 containerComponent, foundResourceInstance);
2111 updatedProperties.add(componentInstanceProperty);
2114 final Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade
2115 .updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
2116 if (updateContainerRes.isRight()) {
2117 final ActionStatus actionStatus = componentsUtils
2118 .convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
2119 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2122 resultOp = Either.left(updatedProperties);
2125 } catch (final ComponentException e) {
2126 return Either.right(e.getResponseFormat());
2128 if (resultOp == null || resultOp.isRight()) {
2129 janusGraphDao.rollback();
2131 janusGraphDao.commit();
2134 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
2138 private void validateMandatoryFields(PropertyDataDefinition property) {
2139 if (StringUtils.isEmpty(property.getName())) {
2140 throw new ByActionStatusComponentException(ActionStatus.MISSING_PROPERTY_NAME);
2144 private void validatePropertyExistsOnComponent(ComponentInstanceProperty property, Component containerComponent,
2145 ComponentInstance foundResourceInstance) {
2146 List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties()
2147 .get(foundResourceInstance.getUniqueId());
2148 final boolean hasProperty = instanceProperties.stream().anyMatch(p -> p.getName().equals(property.getName()));
2150 throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND, property.getName());
2154 private ComponentInstanceAttribute validateAttributeExistsOnComponent(final ComponentInstanceAttribute attribute,
2155 final Component containerComponent,
2156 final ComponentInstance foundResourceInstance) {
2157 final List<ComponentInstanceAttribute> instanceProperties =
2158 containerComponent.getComponentInstancesAttributes().get(foundResourceInstance.getUniqueId());
2159 final Optional<ComponentInstanceAttribute> instanceAttribute =
2160 instanceProperties.stream().filter(p -> p.getName().equals(attribute.getName())).findAny();
2161 if (!instanceAttribute.isPresent()) {
2162 throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND, attribute.getName());
2164 return instanceAttribute.get();
2167 private ResponseFormat updateCapabilityPropertyOnContainerComponent(ComponentInstanceProperty property,
2168 String newValue, Component containerComponent,
2169 ComponentInstance foundResourceInstance,
2170 String capabilityType, String capabilityName) {
2171 String componentInstanceUniqueId = foundResourceInstance.getUniqueId();
2172 ResponseFormat actionStatus = updateCapPropOnContainerComponent(property, newValue, containerComponent,
2173 foundResourceInstance, capabilityType, capabilityName, componentInstanceUniqueId);
2174 if (actionStatus != null) {
2175 return actionStatus;
2178 return componentsUtils.getResponseFormat(ActionStatus.OK);
2181 private ResponseFormat updateCapabilityPropFromUpdateInstProp(ComponentInstanceProperty property,
2182 String newValue, Component containerComponent,
2183 ComponentInstance foundResourceInstance,
2184 String capabilityType, String capabilityName) {
2185 String componentInstanceUniqueId = foundResourceInstance.getUniqueId();
2186 Either<Component, StorageOperationStatus> getComponentRes =
2187 toscaOperationFacade.getToscaFullElement(foundResourceInstance.getComponentUid());
2188 if (getComponentRes.isRight()) {
2189 return componentsUtils.getResponseFormat(getComponentRes.right().value());
2192 ResponseFormat actionStatus = updateCapPropOnContainerComponent(property, newValue, containerComponent,
2193 foundResourceInstance, capabilityType, capabilityName, componentInstanceUniqueId);
2194 if (actionStatus != null) {
2195 return actionStatus;
2198 return componentsUtils.getResponseFormat(ActionStatus.OK);
2201 private ResponseFormat updateCapPropOnContainerComponent(ComponentInstanceProperty property, String newValue,
2202 Component containerComponent,
2203 ComponentInstance foundResourceInstance,
2204 String capabilityType, String capabilityName,
2205 String componentInstanceUniqueId) {
2206 Map<String, List<CapabilityDefinition>> capabilities =
2207 Optional.ofNullable(foundResourceInstance.getCapabilities()).orElse(Collections.emptyMap());
2208 List<CapabilityDefinition> capPerType =
2209 Optional.ofNullable(capabilities.get(capabilityType)).orElse(Collections.emptyList());
2210 Optional<CapabilityDefinition> cap =
2211 capPerType.stream().filter(c -> c.getName().equals(capabilityName)).findAny();
2212 if (cap.isPresent()) {
2213 List<ComponentInstanceProperty> capProperties = cap.get().getProperties();
2214 if (capProperties != null) {
2215 Optional<ComponentInstanceProperty> instanceProperty =
2216 capProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
2217 StorageOperationStatus status;
2218 if (instanceProperty.isPresent()) {
2219 String capKey = ModelConverter
2220 .buildCapabilityPropertyKey(foundResourceInstance.getOriginType().isAtomicType(), capabilityType, capabilityName,
2221 componentInstanceUniqueId, cap.get());
2222 instanceProperty.get().setValue(newValue);
2223 List<String> path = new ArrayList<>();
2224 path.add(componentInstanceUniqueId);
2226 instanceProperty.get().setPath(path);
2227 status = toscaOperationFacade.updateComponentInstanceCapabiltyProperty(containerComponent,
2228 componentInstanceUniqueId, capKey, instanceProperty.get());
2229 if (status != StorageOperationStatus.OK) {
2230 ActionStatus actionStatus =
2231 componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
2232 return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
2235 foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
2242 private ResponseFormat updatePropertyOnContainerComponent(ComponentInstanceProperty instanceProperty, String newValue,
2243 Component containerComponent, ComponentInstance foundResourceInstance) {
2244 StorageOperationStatus status;
2245 instanceProperty.setValue(newValue);
2246 status = toscaOperationFacade.updateComponentInstanceProperty(containerComponent, foundResourceInstance.getUniqueId(), instanceProperty);
2247 if (status != StorageOperationStatus.OK) {
2248 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
2249 return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
2251 foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
2252 return componentsUtils.getResponseFormat(ActionStatus.OK);
2255 private ResponseFormat updateAttributeOnContainerComponent(final ComponentInstanceAttribute instanceAttribute,
2256 final String newValue,
2257 final Component containerComponent,
2258 final ComponentInstance foundResourceInstance) {
2260 instanceAttribute.setValue(newValue);
2261 final StorageOperationStatus status =
2262 toscaOperationFacade.updateComponentInstanceAttribute(containerComponent, foundResourceInstance.getUniqueId(), instanceAttribute);
2263 if (status != StorageOperationStatus.OK) {
2264 final ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
2265 return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
2267 foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
2268 return componentsUtils.getResponseFormat(ActionStatus.OK);
2271 private <T extends PropertyDefinition> Either<String, ResponseFormat> validatePropertyObjectValue(T property, String newValue, boolean isInput) {
2272 final Map<String, DataTypeDefinition> allDataTypes = componentsUtils.getAllDataTypes(applicationDataTypeCache, property.getModel());
2273 String propertyType = property.getType();
2274 String innerType = getInnerType(property);
2276 // Specific Update Logic
2277 Either<Object, Boolean> isValid = propertyOperation
2278 .validateAndUpdatePropertyValue(property.getType(), newValue, true, innerType, allDataTypes);
2279 if (isValid.isRight()) {
2280 if (!Boolean.TRUE.equals(isValid.right().value())) {
2281 log.error("Invalid value {} of property {} ", newValue, property.getName());
2282 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
2285 Object object = isValid.left().value();
2286 if (object != null) {
2287 newValue = object.toString();
2290 if (validateAndUpdateRules(property, isInput, allDataTypes, innerType, propertyType)) {
2291 return Either.right(componentsUtils.getResponseFormat(componentsUtils
2292 .convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT))));
2294 return Either.left(newValue);
2297 private <T extends PropertyDefinition> boolean validateAndUpdateRules(T property, boolean isInput, Map<String, DataTypeDefinition> allDataTypes,
2298 String innerType, String propertyType) {
2300 ImmutablePair<String, Boolean> pair = propertyOperation
2301 .validateAndUpdateRules(propertyType, ((ComponentInstanceProperty) property).getRules(), innerType, allDataTypes, true);
2302 if (pair.getRight() != null && !pair.getRight()) {
2303 BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), property.getName(), propertyType);
2310 private <T extends PropertyDefinition> Either<String, ResponseFormat> updatePropertyObjectValue(T property, final String model) {
2311 final Map<String, DataTypeDefinition> allDataTypes = componentsUtils.getAllDataTypes(applicationDataTypeCache, model);
2312 String innerType = null;
2313 String propertyType = property.getType();
2314 ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
2315 log.debug("The type of the property {} is {}", property.getUniqueId(), propertyType);
2317 if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
2318 SchemaDefinition schema = property.getSchema();
2319 if (schema == null) {
2320 log.debug("Schema doesn't exists for property of type {}", type);
2322 .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
2324 PropertyDataDefinition propDef = schema.getProperty();
2325 if (propDef == null) {
2326 log.debug("Property in Schema Definition inside property of type {} doesn't exist", type);
2328 .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
2330 innerType = propDef.getType();
2333 // Specific Update Logic
2334 String newValue = property.getValue();
2336 if (property.hasToscaFunction() || CollectionUtils.isNotEmpty(property.getSubPropertyToscaFunctions())) {
2337 return Either.left(newValue);
2340 Either<Object, Boolean> isValid = propertyOperation
2341 .validateAndUpdatePropertyValue(propertyType, property.getValue(), true, innerType, allDataTypes);
2342 if (isValid.isRight()) {
2343 if (!Boolean.TRUE.equals(isValid.right().value())) {
2344 log.debug("validate and update property value has failed with value: {}", property.getValue());
2345 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(
2346 DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT)));
2349 Object object = isValid.left().value();
2350 if (object != null) {
2351 newValue = object.toString();
2354 ImmutablePair<String, Boolean> pair = propertyOperation
2355 .validateAndUpdateRules(propertyType, ((ComponentInstanceProperty) property).getRules(), innerType, allDataTypes, true);
2356 if (pair.getRight() != null && Boolean.FALSE.equals(pair.getRight())) {
2357 BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), property.getName(), propertyType);
2358 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(
2359 DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT))));
2361 return Either.left(newValue);
2364 private <T extends AttributeDefinition> Either<String, ResponseFormat> updateAttributeObjectValue(final T attribute) {
2365 String innerType = null;
2366 final String attributeType = attribute.getType();
2367 final ToscaPropertyType type = ToscaPropertyType.isValidType(attributeType);
2368 log.debug("The type of the attribute {} is {}", attribute.getUniqueId(), attributeType);
2370 if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
2371 final SchemaDefinition def = attribute.getSchema();
2373 log.debug("Schema doesn't exists for attribute of type {}", type);
2375 .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
2377 PropertyDataDefinition propDef = def.getProperty();
2378 if (propDef == null) {
2379 log.debug("Property in Schema Definition inside attribute of type {} doesn't exist", type);
2381 .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
2383 innerType = propDef.getType();
2386 // Specific Update Logic
2387 String newValue = attribute.getValue();
2389 final var isValid = attributeOperation.validateAndUpdateAttributeValue(attribute, innerType,
2390 componentsUtils.getAllDataTypes(applicationDataTypeCache, attribute.getModel()));
2391 if (isValid.isRight()) {
2392 final Boolean res = isValid.right().value();
2393 if (!Boolean.TRUE.equals(res)) {
2394 log.debug("validate and update attribute value has failed with value: {}", newValue);
2395 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(
2396 DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT)));
2399 final Object object = isValid.left().value();
2400 if (object != null) {
2401 newValue = object.toString();
2404 return Either.left(newValue);
2407 private <T extends PropertyDefinition> void validateToscaGetFunction(T property, Component parentComponent) {
2408 final ToscaGetFunctionDataDefinition toscaGetFunction = (ToscaGetFunctionDataDefinition) property.getToscaFunction();
2409 validateGetToscaFunctionAttributes(toscaGetFunction);
2410 validateGetPropertySource(toscaGetFunction.getFunctionType(), toscaGetFunction.getPropertySource());
2411 if (toscaGetFunction.getFunctionType() == ToscaGetFunctionType.GET_INPUT) {
2412 validateGetFunction(property, parentComponent.getInputs(), parentComponent.getModel());
2415 if (toscaGetFunction.getFunctionType() == ToscaGetFunctionType.GET_PROPERTY) {
2416 if (toscaGetFunction.getPropertySource() == PropertySource.SELF) {
2417 validateGetFunction(property, parentComponent.getProperties(), parentComponent.getModel());
2418 } else if (toscaGetFunction.getPropertySource() == PropertySource.INSTANCE) {
2419 final ComponentInstance componentInstance =
2420 parentComponent.getComponentInstanceById(toscaGetFunction.getSourceUniqueId())
2421 .orElseThrow(ToscaGetFunctionExceptionSupplier.instanceNotFound(toscaGetFunction.getSourceName()));
2422 validateGetFunction(property, componentInstance.getProperties(), parentComponent.getModel());
2427 if (toscaGetFunction.getFunctionType() == ToscaGetFunctionType.GET_ATTRIBUTE) {
2428 if (toscaGetFunction.getPropertySource() == PropertySource.SELF) {
2429 validateGetFunction(property, parentComponent.getAttributes(), parentComponent.getModel());
2430 } else if (toscaGetFunction.getPropertySource() == PropertySource.INSTANCE) {
2431 final ComponentInstance componentInstance =
2432 parentComponent.getComponentInstanceById(toscaGetFunction.getSourceUniqueId())
2433 .orElseThrow(ToscaGetFunctionExceptionSupplier.instanceNotFound(toscaGetFunction.getSourceName()));
2434 validateGetFunction(property, componentInstance.getAttributes(), parentComponent.getModel());
2440 throw ToscaGetFunctionExceptionSupplier.functionNotSupported(toscaGetFunction.getFunctionType()).get();
2443 private <T extends PropertyDefinition> void validateGetFunction(final T property,
2444 final List<? extends ToscaPropertyData> parentProperties,
2445 final String model) {
2446 final ToscaGetFunctionDataDefinition toscaGetFunction = (ToscaGetFunctionDataDefinition) property.getToscaFunction();
2447 if (CollectionUtils.isEmpty(parentProperties)) {
2448 throw ToscaGetFunctionExceptionSupplier
2449 .propertyNotFoundOnTarget(toscaGetFunction.getPropertyName(), toscaGetFunction.getPropertySource(),
2450 toscaGetFunction.getFunctionType()
2453 final String getFunctionPropertyUniqueId = toscaGetFunction.getPropertyUniqueId();
2454 ToscaPropertyData referredProperty = parentProperties.stream()
2455 .filter(property1 -> getFunctionPropertyUniqueId.equals(property1.getUniqueId()))
2457 .orElseThrow(ToscaGetFunctionExceptionSupplier
2458 .propertyNotFoundOnTarget(toscaGetFunction.getPropertyName(), toscaGetFunction.getPropertySource()
2459 , toscaGetFunction.getFunctionType())
2461 if (toscaGetFunction.isSubProperty()) {
2462 referredProperty = findSubProperty(referredProperty, toscaGetFunction, model);
2465 if (!property.getType().equals(referredProperty.getType())) {
2466 throw ToscaGetFunctionExceptionSupplier
2467 .propertyTypeDiverge(toscaGetFunction.getType(), referredProperty.getType(), property.getType()).get();
2469 if (PropertyType.typeHasSchema(referredProperty.getType()) && !referredProperty.getSchemaType().equals(property.getSchemaType())) {
2470 throw ToscaGetFunctionExceptionSupplier
2471 .propertySchemaDiverge(toscaGetFunction.getType(), referredProperty.getSchemaType(), property.getSchemaType()).get();
2475 private ToscaPropertyData findSubProperty(final ToscaPropertyData referredProperty,
2476 final ToscaGetFunctionDataDefinition toscaGetFunction,
2477 final String model) {
2478 final Map<String, DataTypeDefinition> dataTypeMap = loadDataTypes(model);
2479 final List<String> propertyPathFromSource = toscaGetFunction.getPropertyPathFromSource();
2480 DataTypeDefinition dataType = dataTypeMap.get(referredProperty.getType());
2481 if (dataType == null) {
2482 throw ToscaGetFunctionExceptionSupplier
2483 .propertyDataTypeNotFound(propertyPathFromSource.get(0), referredProperty.getType(), toscaGetFunction.getFunctionType()).get();
2485 ToscaPropertyData foundProperty = referredProperty;
2486 for (int i = 1; i < propertyPathFromSource.size(); i++) {
2487 final String currentPropertyName = propertyPathFromSource.get(i);
2488 foundProperty = dataType.getProperties().stream()
2489 .filter(propertyDefinition -> currentPropertyName.equals(propertyDefinition.getName())).findFirst()
2491 ToscaGetFunctionExceptionSupplier
2492 .propertyNotFoundOnTarget(propertyPathFromSource.subList(0, i), toscaGetFunction.getPropertySource(),
2493 toscaGetFunction.getFunctionType())
2495 dataType = dataTypeMap.get(foundProperty.getType());
2496 if (dataType == null) {
2497 throw ToscaGetFunctionExceptionSupplier
2498 .propertyDataTypeNotFound(propertyPathFromSource.subList(0, i), foundProperty.getType(),
2499 toscaGetFunction.getFunctionType()).get();
2502 return foundProperty;
2505 private Map<String, DataTypeDefinition> loadDataTypes(String model) {
2506 final Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> dataTypeEither =
2507 applicationDataTypeCache.getAll(model);
2508 if (dataTypeEither.isRight()) {
2509 throw ToscaGetFunctionExceptionSupplier.couldNotLoadDataTypes(model).get();
2511 return dataTypeEither.left().value();
2514 private void validateGetPropertySource(final ToscaGetFunctionType functionType, final PropertySource propertySource) {
2515 if (functionType == ToscaGetFunctionType.GET_INPUT && propertySource != PropertySource.SELF) {
2516 throw ToscaGetFunctionExceptionSupplier
2517 .targetSourceNotSupported(functionType, propertySource).get();
2519 if (functionType == ToscaGetFunctionType.GET_PROPERTY && !List.of(PropertySource.SELF, PropertySource.INSTANCE).contains(propertySource)) {
2520 throw ToscaGetFunctionExceptionSupplier
2521 .targetSourceNotSupported(functionType, propertySource).get();
2525 private void validateGetToscaFunctionAttributes(final ToscaGetFunctionDataDefinition toscaGetFunction) {
2526 if (toscaGetFunction.getFunctionType() == null) {
2527 throw ToscaGetFunctionExceptionSupplier.targetFunctionTypeNotFound().get();
2529 if (toscaGetFunction.getPropertySource() == null) {
2530 throw ToscaGetFunctionExceptionSupplier.targetPropertySourceNotFound(toscaGetFunction.getFunctionType()).get();
2532 if (CollectionUtils.isEmpty(toscaGetFunction.getPropertyPathFromSource())) {
2533 throw ToscaGetFunctionExceptionSupplier
2534 .targetSourcePathNotFound(toscaGetFunction.getFunctionType()).get();
2536 if (StringUtils.isEmpty(toscaGetFunction.getSourceName()) || StringUtils.isBlank(toscaGetFunction.getSourceName())) {
2537 throw ToscaGetFunctionExceptionSupplier.sourceNameNotFound(toscaGetFunction.getPropertySource()).get();
2539 if (StringUtils.isEmpty(toscaGetFunction.getSourceUniqueId()) || StringUtils.isBlank(toscaGetFunction.getSourceUniqueId())) {
2540 throw ToscaGetFunctionExceptionSupplier.sourceIdNotFound(toscaGetFunction.getPropertySource()).get();
2542 if (StringUtils.isEmpty(toscaGetFunction.getPropertyName()) || StringUtils.isBlank(toscaGetFunction.getPropertyName())) {
2543 throw ToscaGetFunctionExceptionSupplier.propertyNameNotFound(toscaGetFunction.getPropertySource()).get();
2545 if (StringUtils.isEmpty(toscaGetFunction.getPropertyUniqueId()) || StringUtils.isBlank(toscaGetFunction.getPropertyUniqueId())) {
2546 throw ToscaGetFunctionExceptionSupplier.propertyIdNotFound(toscaGetFunction.getPropertySource()).get();
2550 private ResponseFormat updateInputOnContainerComponent(ComponentInstanceInput input, String newValue, Component containerComponent,
2551 ComponentInstance foundResourceInstance) {
2552 StorageOperationStatus status;
2553 input.setValue(newValue);
2554 status = toscaOperationFacade.updateComponentInstanceInput(containerComponent, foundResourceInstance.getUniqueId(), input);
2555 if (status != StorageOperationStatus.OK) {
2556 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
2557 return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
2559 foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
2560 return componentsUtils.getResponseFormat(ActionStatus.OK);
2563 public Either<List<ComponentInstanceInput>, ResponseFormat> createOrUpdateInstanceInputValues(ComponentTypeEnum componentTypeEnum,
2564 String componentId, String resourceInstanceId,
2565 List<ComponentInstanceInput> inputs,
2568 Either<List<ComponentInstanceInput>, ResponseFormat> resultOp = null;
2570 validateUserExists(userId);
2572 if (componentTypeEnum == null) {
2573 BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_OR_UPDATE_PROPERTY_VALUE, INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
2574 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
2577 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
2579 if (getResourceResult.isRight()) {
2580 log.debug(FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID, componentId);
2581 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getResourceResult.right().value(), componentTypeEnum);
2582 return Either.right(componentsUtils.getResponseFormat(actionStatus, componentId));
2584 Component containerComponent = getResourceResult.left().value();
2586 if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
2587 if (Boolean.TRUE.equals(containerComponent.isArchived())) {
2588 log.info(COMPONENT_ARCHIVED, componentId);
2589 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_IS_ARCHIVED, containerComponent.getName()));
2591 log.info(RESTRICTED_OPERATION_ON_SERVIVE, userId, componentId);
2592 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2595 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId);
2596 if (resourceInstanceStatus.isRight()) {
2597 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER,
2598 resourceInstanceId, RESOURCE_INSTANCE, SERVICE, componentId));
2601 ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
2604 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
2605 if (lockStatus != StorageOperationStatus.OK) {
2606 log.debug(FAILED_TO_LOCK_SERVICE, componentId);
2607 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
2609 List<ComponentInstanceInput> updatedInputs = new ArrayList<>();
2611 for (ComponentInstanceInput input : inputs) {
2612 validateMandatoryFields(input);
2613 ComponentInstanceInput componentInstanceInput = validateInputExistsOnComponent(input, containerComponent, foundResourceInstance);
2614 Either<String, ResponseFormat> validatedInputValue = validatePropertyObjectValue(componentInstanceInput, input.getValue(), true);
2615 if (validatedInputValue.isRight()) {
2616 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT, input.getName());
2618 updateInputOnContainerComponent(componentInstanceInput, validatedInputValue.left().value(), containerComponent,
2619 foundResourceInstance);
2620 updatedInputs.add(componentInstanceInput);
2622 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade
2623 .updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
2624 if (updateContainerRes.isRight()) {
2625 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
2626 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2629 resultOp = Either.left(updatedInputs);
2633 if (resultOp == null || resultOp.isRight()) {
2634 janusGraphDao.rollback();
2636 janusGraphDao.commit();
2639 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
2644 private ComponentInstanceInput validateInputExistsOnComponent(ComponentInstanceInput input, Component containerComponent,
2645 ComponentInstance foundResourceInstance) {
2646 List<ComponentInstanceInput> instanceProperties = containerComponent.getComponentInstancesInputs().get(foundResourceInstance.getUniqueId());
2647 Optional<ComponentInstanceInput> instanceInput = instanceProperties.stream().filter(p -> p.getName().equals(input.getName())).findAny();
2648 if (!instanceInput.isPresent()) {
2649 throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND, input.getName());
2651 return instanceInput.get();
2654 public Either<ComponentInstanceProperty, ResponseFormat> createOrUpdateGroupInstancePropertyValue(ComponentTypeEnum componentTypeEnum,
2655 String componentId, String resourceInstanceId,
2656 String groupInstanceId,
2657 ComponentInstanceProperty property,
2660 Either<ComponentInstanceProperty, ResponseFormat> resultOp = null;
2662 validateUserExists(userId);
2664 if (componentTypeEnum == null) {
2665 BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_OR_UPDATE_PROPERTY_VALUE, INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
2666 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
2670 if (!ComponentValidationUtils.canWorkOnComponent(componentId, toscaOperationFacade, userId)) {
2671 log.info("Restricted operation for user: {} on service: {}", userId, componentId);
2672 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2676 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
2677 if (lockStatus != StorageOperationStatus.OK) {
2678 log.debug(FAILED_TO_LOCK_SERVICE, componentId);
2679 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
2683 String propertyValueUid = property.getValueUniqueUid();
2685 if (propertyValueUid == null) {
2687 Either<Integer, StorageOperationStatus> counterRes = groupInstanceOperation
2688 .increaseAndGetGroupInstancePropertyCounter(groupInstanceId);
2690 if (counterRes.isRight()) {
2691 log.debug("increaseAndGetResourcePropertyCounter failed resource instance: {} property: {}", resourceInstanceId, property);
2692 StorageOperationStatus status = counterRes.right().value();
2693 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
2694 resultOp = Either.right(componentsUtils.getResponseFormat(actionStatus));
2696 Integer index = counterRes.left().value();
2697 Either<ComponentInstanceProperty, StorageOperationStatus> result = groupInstanceOperation
2698 .addPropertyValueToGroupInstance(property, resourceInstanceId, index, true);
2700 if (result.isLeft()) {
2701 log.trace("Property value was added to resource instance {}", resourceInstanceId);
2702 ComponentInstanceProperty instanceProperty = result.left().value();
2704 resultOp = Either.left(instanceProperty);
2707 log.debug("Failed to add property value: {} to resource instance {}", property, resourceInstanceId);
2709 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
2711 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2715 Either<ComponentInstanceProperty, StorageOperationStatus> result = groupInstanceOperation
2716 .updatePropertyValueInGroupInstance(property, resourceInstanceId, true);
2718 if (result.isLeft()) {
2719 log.debug("Property value {} was updated on graph.", property.getValueUniqueUid());
2720 ComponentInstanceProperty instanceProperty = result.left().value();
2722 resultOp = Either.left(instanceProperty);
2725 log.debug("Failed to update property value: {}, in resource instance {}", property, resourceInstanceId);
2727 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
2729 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2732 if (resultOp.isLeft()) {
2733 StorageOperationStatus updateCustomizationUUID = componentInstanceOperation.updateCustomizationUUID(resourceInstanceId);
2734 if (updateCustomizationUUID != StorageOperationStatus.OK) {
2735 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateCustomizationUUID);
2737 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2744 if (resultOp == null || resultOp.isRight()) {
2745 janusGraphDao.rollback();
2747 janusGraphDao.commit();
2750 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
2755 public Either<ComponentInstanceProperty, ResponseFormat> deletePropertyValue(ComponentTypeEnum componentTypeEnum, String serviceId,
2756 String resourceInstanceId, String propertyValueId, String userId) {
2758 validateUserExists(userId);
2760 Either<ComponentInstanceProperty, ResponseFormat> resultOp = null;
2762 if (componentTypeEnum == null) {
2763 BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_OR_UPDATE_PROPERTY_VALUE, INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
2764 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
2768 if (!ComponentValidationUtils.canWorkOnComponent(serviceId, toscaOperationFacade, userId)) {
2769 log.info("Restricted operation for user {} on service {}", userId, serviceId);
2770 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2774 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(serviceId, componentTypeEnum.getNodeType());
2775 if (lockStatus != StorageOperationStatus.OK) {
2776 log.debug(FAILED_TO_LOCK_SERVICE, serviceId);
2777 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
2781 Either<ComponentInstanceProperty, StorageOperationStatus> result = propertyOperation
2782 .removePropertyValueFromResourceInstance(propertyValueId, resourceInstanceId, true);
2784 if (result.isLeft()) {
2785 log.debug("Property value {} was removed from graph.", propertyValueId);
2786 ComponentInstanceProperty instanceProperty = result.left().value();
2788 resultOp = Either.left(instanceProperty);
2792 log.debug("Failed to remove property value {} in resource instance {}", propertyValueId, resourceInstanceId);
2794 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
2796 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2802 if (resultOp == null || resultOp.isRight()) {
2803 janusGraphDao.rollback();
2805 janusGraphDao.commit();
2808 graphLockOperation.unlockComponent(serviceId, componentTypeEnum.getNodeType());
2813 private Component getAndValidateOriginComponentOfComponentInstance(Component containerComponent, ComponentInstance componentInstance) {
2815 ComponentTypeEnum componentType = getComponentTypeByParentComponentType(containerComponent.getComponentType());
2816 Component component;
2817 Either<Component, StorageOperationStatus> getComponentRes = toscaOperationFacade.getToscaFullElement(componentInstance.getComponentUid());
2818 if (getComponentRes.isRight()) {
2819 log.debug("Failed to get the component with id {} for component instance {} creation. ", componentInstance.getComponentUid(),
2820 componentInstance.getName());
2821 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentRes.right().value(), componentType);
2822 throw new ByActionStatusComponentException(actionStatus, Constants.EMPTY_STRING);
2824 component = getComponentRes.left().value();
2825 LifecycleStateEnum resourceCurrState = component.getLifecycleState();
2826 if (resourceCurrState == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) {
2827 ActionStatus actionStatus = ActionStatus.CONTAINER_CANNOT_CONTAIN_COMPONENT_IN_STATE;
2828 throw new ByActionStatusComponentException(actionStatus, containerComponent.getComponentType().toString(), resourceCurrState.toString());
2830 if (Boolean.TRUE.equals(component.isArchived())) {
2831 ActionStatus actionStatus = ActionStatus.COMPONENT_IS_ARCHIVED;
2832 throw new ByActionStatusComponentException(actionStatus, component.getName());
2834 final Map<String, InterfaceDefinition> componentInterfaces = component.getInterfaces();
2835 if (MapUtils.isNotEmpty(componentInterfaces)) {
2836 componentInterfaces.forEach(componentInstance::addInterface);
2841 public Either<Set<String>, ResponseFormat> forwardingPathOnVersionChange(String containerComponentParam,
2842 String containerComponentId,
2843 String componentInstanceId,
2844 ComponentInstance newComponentInstance) {
2845 Either<Set<String>, ResponseFormat> resultOp;
2846 final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
2847 ComponentParametersView componentParametersView = getComponentParametersViewForForwardingPath();
2850 Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, componentParametersView);
2852 //Fetch current component instance
2853 Either<ComponentInstance, StorageOperationStatus> eitherResourceInstance =
2854 getResourceInstanceById(containerComponent, componentInstanceId);
2855 if (eitherResourceInstance.isRight()) {
2856 resultOp = Either.right(componentsUtils.getResponseFormat(
2857 ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceId, containerComponentId));
2860 ComponentInstance currentResourceInstance = eitherResourceInstance.left().value();
2862 //Check whether new componentInstance exists
2863 String resourceId = newComponentInstance.getComponentUid();
2864 Either<Boolean, StorageOperationStatus> componentExistsRes = toscaOperationFacade.validateComponentExists(resourceId);
2865 if (componentExistsRes.isRight()) {
2866 log.debug("Failed to find resource {}", resourceId);
2867 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse
2868 (componentExistsRes.right().value()), resourceId));
2870 } else if (!Boolean.TRUE.equals(componentExistsRes.left().value())) {
2871 log.debug("The resource {} not found ", resourceId);
2872 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId));
2876 //Fetch component using new component instance uid
2877 Component updatedContainerComponent = getOriginComponentFromComponentInstance(newComponentInstance);
2878 Set<String> toDeleteForwardingPaths = getForwardingPaths(containerComponent,
2879 currentResourceInstance, updatedContainerComponent);
2880 resultOp = Either.left(toDeleteForwardingPaths);
2885 private Set<String> getForwardingPaths(Component containerComponent, ComponentInstance currentResourceInstance,
2886 Component updatedContainerComponent) {
2887 DataForMergeHolder dataForMergeHolder = new DataForMergeHolder();
2888 dataForMergeHolder.setOrigComponentInstId(currentResourceInstance.getName());
2890 Service service = (Service) containerComponent;
2891 ForwardingPathUtils forwardingPathUtils = new ForwardingPathUtils();
2893 return forwardingPathUtils.
2894 getForwardingPathsToBeDeletedOnVersionChange(service, dataForMergeHolder, updatedContainerComponent);
2897 private ComponentParametersView getComponentParametersViewForForwardingPath() {
2898 ComponentParametersView componentParametersView = new ComponentParametersView();
2899 componentParametersView.setIgnoreCapabiltyProperties(false);
2900 componentParametersView.setIgnoreServicePath(false);
2901 return componentParametersView;
2904 public ComponentInstance changeComponentInstanceVersion(String containerComponentParam, String containerComponentId, String componentInstanceId,
2905 String userId, ComponentInstance newComponentInstance) {
2907 User user = validateUserExists(userId);
2908 final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
2909 ComponentParametersView componentParametersView = new ComponentParametersView();
2910 componentParametersView.setIgnoreCapabiltyProperties(false);
2912 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(containerComponentId, containerComponentType,
2913 componentParametersView);
2915 validateCanWorkOnComponent(containerComponent, userId);
2917 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceId);
2918 if (resourceInstanceStatus.isRight()) {
2919 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceId,
2920 containerComponentId);
2923 ComponentInstance currentResourceInstance = resourceInstanceStatus.left().value();
2925 return changeInstanceVersion(containerComponent, currentResourceInstance, newComponentInstance, user, containerComponentType);
2928 public ComponentInstance changeInstanceVersion(org.openecomp.sdc.be.model.Component containerComponent,
2929 ComponentInstance currentResourceInstance,
2930 ComponentInstance newComponentInstance,
2932 final ComponentTypeEnum containerComponentType) {
2933 boolean failed = false;
2934 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus;
2937 lockComponent(containerComponent, "changeComponentInstanceVersion");
2938 String containerComponentId = containerComponent.getUniqueId();
2939 String componentInstanceId = currentResourceInstance.getUniqueId();
2940 if (currentResourceInstance.getComponentUid().equals(newComponentInstance.getComponentUid())) {
2941 return currentResourceInstance;
2943 String resourceId = newComponentInstance.getComponentUid();
2945 Either<Boolean, StorageOperationStatus> componentExistsRes = toscaOperationFacade
2946 .validateComponentExists(resourceId);
2947 if (componentExistsRes.isRight()) {
2948 StorageOperationStatus errorStatus = componentExistsRes.right().value();
2950 log.debug("Failed to validate existing of the component {}. Status is {} ", resourceId, errorStatus);
2951 throw new ByActionStatusComponentException(
2952 componentsUtils.convertFromStorageResponse(errorStatus), resourceId);
2953 } else if (!Boolean.TRUE.equals(componentExistsRes.left().value())) {
2954 log.debug("The resource {} not found ", resourceId);
2955 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_NOT_FOUND, resourceId);
2958 Component eitherOriginComponent = getInstanceOriginNode(currentResourceInstance);
2959 DataForMergeHolder dataHolder = compInstMergeDataBL
2960 .saveAllDataBeforeDeleting(containerComponent, currentResourceInstance, eitherOriginComponent);
2961 ComponentInstance resResourceInfo = deleteComponentInstance(containerComponent, componentInstanceId,
2962 containerComponentType);
2964 if (resResourceInfo == null) {
2965 log.error("Calling `deleteComponentInstance` for the resource {} returned a null", resourceId);
2966 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_NOT_FOUND, resourceId);
2968 Component origComponent = null;
2969 OriginTypeEnum originType = currentResourceInstance.getOriginType();
2970 newComponentInstance.setOriginType(originType);
2971 if (originType == OriginTypeEnum.ServiceProxy) {
2972 Either<Component, StorageOperationStatus> serviceProxyOrigin = toscaOperationFacade
2973 .getLatestByName(SERVICE_PROXY, null);
2974 if (isServiceProxyOrigin(serviceProxyOrigin)) {
2975 throw new ByActionStatusComponentException(
2976 componentsUtils.convertFromStorageResponse(serviceProxyOrigin.right().value()));
2978 origComponent = serviceProxyOrigin.left().value();
2980 StorageOperationStatus fillProxyRes = fillInstanceData(newComponentInstance, origComponent);
2982 if (isFillProxyRes(fillProxyRes)) {
2983 throw new ByActionStatusComponentException(
2984 componentsUtils.convertFromStorageResponse(fillProxyRes));
2986 } else if (originType == OriginTypeEnum.ServiceSubstitution) {
2987 final Either<Component, StorageOperationStatus> getServiceResult = toscaOperationFacade
2988 .getToscaFullElement(newComponentInstance.getComponentUid());
2989 if (getServiceResult.isRight()) {
2990 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(getServiceResult.right().value()));
2992 final Component service = getServiceResult.left().value();
2994 final Either<Component, StorageOperationStatus> getServiceDerivedFromTypeResult = toscaOperationFacade
2995 .getLatestByToscaResourceName(service.getDerivedFromGenericType(), service.getModel());
2996 if (getServiceDerivedFromTypeResult.isRight()) {
2997 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(getServiceResult.right().value()));
3000 origComponent = getServiceDerivedFromTypeResult.left().value();
3002 final StorageOperationStatus fillProxyRes = fillInstanceData(newComponentInstance, origComponent);
3003 if (isFillProxyRes(fillProxyRes)) {
3004 throw new ByActionStatusComponentException(
3005 componentsUtils.convertFromStorageResponse(fillProxyRes));
3008 origComponent = getOriginComponentFromComponentInstance(newComponentInstance);
3009 newComponentInstance.setName(resResourceInfo.getName());
3010 final Map<String, InterfaceDefinition> componentInterfaces = origComponent.getInterfaces();
3011 if (MapUtils.isNotEmpty(componentInterfaces)) {
3012 componentInterfaces.forEach(newComponentInstance::addInterface);
3016 newComponentInstance.setInvariantName(resResourceInfo.getInvariantName());
3017 newComponentInstance.setPosX(resResourceInfo.getPosX());
3018 newComponentInstance.setPosY(resResourceInfo.getPosY());
3019 newComponentInstance.setDescription(resResourceInfo.getDescription());
3020 newComponentInstance.setInstanceCount(resResourceInfo.getInstanceCount());
3021 newComponentInstance.setMaxOccurrences(resResourceInfo.getMaxOccurrences());
3022 newComponentInstance.setMinOccurrences(resResourceInfo.getMinOccurrences());
3023 newComponentInstance.setDirectives(resResourceInfo.getDirectives());
3024 checkForExternalReqAndCapabilities(origComponent, resResourceInfo);
3026 ComponentInstance updatedComponentInstance =
3027 createComponentInstanceOnGraph(containerComponent, origComponent, newComponentInstance, user);
3028 dataHolder.setCurrInstanceNode(origComponent);
3030 .mergeComponentUserOrigData(user, dataHolder, containerComponent, containerComponentId, newComponentInstance.getUniqueId());
3032 ActionStatus postChangeVersionResult = onChangeInstanceOperationOrchestrator
3033 .doPostChangeVersionOperations(containerComponent, currentResourceInstance, newComponentInstance);
3034 if (postChangeVersionResult != ActionStatus.OK) {
3035 throw new ByActionStatusComponentException(postChangeVersionResult);
3038 ComponentParametersView filter = new ComponentParametersView(true);
3039 filter.setIgnoreComponentInstances(false);
3040 Either<Component, StorageOperationStatus> updatedComponentRes = toscaOperationFacade.getToscaElement(containerComponentId, filter);
3041 if (updatedComponentRes.isRight()) {
3042 StorageOperationStatus storageOperationStatus = updatedComponentRes.right().value();
3043 ActionStatus actionStatus = componentsUtils
3044 .convertFromStorageResponse(storageOperationStatus, containerComponent.getComponentType());
3045 log.debug("Component with id {} was not found", containerComponentId);
3046 throw new ByActionStatusComponentException(actionStatus, Constants.EMPTY_STRING);
3049 maintainNodeFilters(currentResourceInstance, newComponentInstance, containerComponentId);
3051 resourceInstanceStatus = getResourceInstanceById(updatedComponentRes.left().value(),
3052 updatedComponentInstance.getUniqueId());
3053 if (resourceInstanceStatus.isRight()) {
3054 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse
3055 (resourceInstanceStatus.right().value()), updatedComponentInstance.getUniqueId());
3057 return resourceInstanceStatus.left().value();
3059 } catch (ComponentException e) {
3063 unlockComponent(failed, containerComponent);
3067 private void maintainNodeFilters(
3068 ComponentInstance currentResourceInstance,
3069 ComponentInstance newComponentInstance,
3070 String containerComponentId) {
3071 CINodeFilterDataDefinition filterToMaintain = currentResourceInstance.getNodeFilter();
3072 if (null != filterToMaintain) {
3073 nodeFilterOperation.addNodeFilterData(
3074 containerComponentId.toLowerCase(),
3075 newComponentInstance.getUniqueId(),
3080 private void checkForExternalReqAndCapabilities(Component component, ComponentInstance resResourceInfo) {
3081 if (MapUtils.isNotEmpty(component.getRequirements())) {
3082 component.getRequirements().entrySet().forEach(requirementsMap -> {
3083 if (MapUtils.isNotEmpty(resResourceInfo.getRequirements()) && resResourceInfo.getRequirements().containsKey(requirementsMap.getKey())) {
3084 List<RequirementDefinition> resourceReqList = resResourceInfo.getRequirements().get(requirementsMap.getKey());
3085 for (RequirementDefinition requirements : requirementsMap.getValue()) {
3086 String requirementName = requirements.getName();
3087 resourceReqList.forEach(requirementDefinition -> {
3088 if (requirementName.equals(requirementDefinition.getName()) && requirementDefinition.isExternal()) {
3089 requirements.setExternal(requirementDefinition.isExternal());
3096 if (MapUtils.isNotEmpty(component.getCapabilities())) {
3097 component.getCapabilities().entrySet().forEach(capabilityMap -> {
3098 if (MapUtils.isNotEmpty(resResourceInfo.getCapabilities()) && resResourceInfo.getCapabilities().containsKey(capabilityMap.getKey())) {
3099 List<CapabilityDefinition> resourceCapList = resResourceInfo.getCapabilities().get(capabilityMap.getKey());
3100 capabilityMap.getValue().forEach(capabilities -> {
3101 String capabilityName = capabilities.getName();
3102 for (CapabilityDefinition capDef : resourceCapList) {
3103 if (capabilityName.equals(capDef.getName()) && capDef.isExternal()) {
3104 capabilities.setExternal(capDef.isExternal());
3113 private boolean isFillProxyRes(StorageOperationStatus fillProxyRes) {
3114 if (fillProxyRes != StorageOperationStatus.OK) {
3115 log.debug("Failed to fill service proxy resource data with data from service, error {}", fillProxyRes);
3122 public List<ComponentInstanceProperty> getComponentInstancePropertiesById(String containerComponentTypeParam, String containerComponentId,
3123 String componentInstanceUniqueId, String userId) {
3124 Component containerComponent = null;
3126 boolean failed = false;
3128 validateUserExists(userId);
3129 validateComponentType(containerComponentTypeParam);
3131 Either<Component, StorageOperationStatus> validateContainerComponentExists = toscaOperationFacade.getToscaElement(containerComponentId);
3132 if (validateContainerComponentExists.isRight()) {
3133 throw new ByActionStatusComponentException(
3134 componentsUtils.convertFromStorageResponse(validateContainerComponentExists.right().value()));
3136 containerComponent = validateContainerComponentExists.left().value();
3138 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent,
3139 componentInstanceUniqueId);
3140 if (resourceInstanceStatus.isRight()) {
3141 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId,
3142 containerComponentId);
3145 List<ComponentInstanceProperty> instanceProperties = new ArrayList<>();
3146 if (MapUtils.isNotEmpty(containerComponent.getComponentInstancesProperties())) {
3147 instanceProperties = containerComponent.getComponentInstancesProperties()
3148 .get(componentInstanceUniqueId);
3150 return instanceProperties;
3151 } catch (ComponentException e) {
3155 unlockComponent(failed, containerComponent);
3159 public List<ComponentInstanceAttribute> getComponentInstanceAttributesById(final String containerComponentTypeParam,
3160 final String containerComponentId,
3161 final String componentInstanceUniqueId,
3162 final String userId) {
3163 Component containerComponent = null;
3165 boolean failed = false;
3167 validateUserExists(userId);
3168 validateComponentType(containerComponentTypeParam);
3170 final Either<Component, StorageOperationStatus> validateContainerComponentExists =
3171 toscaOperationFacade.getToscaElement(containerComponentId);
3172 if (validateContainerComponentExists.isRight()) {
3173 throw new ByActionStatusComponentException(
3174 componentsUtils.convertFromStorageResponse(validateContainerComponentExists.right().value()));
3176 containerComponent = validateContainerComponentExists.left().value();
3178 if (getResourceInstanceById(containerComponent, componentInstanceUniqueId).isRight()) {
3179 throw new ByActionStatusComponentException(
3180 ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId);
3183 final Map<String, List<ComponentInstanceAttribute>> componentInstancesAttributes = containerComponent.getComponentInstancesAttributes();
3184 return componentInstancesAttributes == null ? new ArrayList<>()
3185 : componentInstancesAttributes.getOrDefault(componentInstanceUniqueId, new ArrayList<>());
3186 } catch (final ComponentException e) {
3190 unlockComponent(failed, containerComponent);
3194 protected void validateIncrementCounter(String resourceInstanceId, GraphPropertiesDictionary counterType,
3195 Wrapper<Integer> instaceCounterWrapper,
3196 Wrapper<ResponseFormat> errorWrapper) {
3197 Either<Integer, StorageOperationStatus> counterRes = componentInstanceOperation
3198 .increaseAndGetResourceInstanceSpecificCounter(resourceInstanceId, counterType, true);
3200 if (counterRes.isRight()) {
3201 log.debug("increase And Get {} failed resource instance {}", counterType, resourceInstanceId);
3202 StorageOperationStatus status = counterRes.right().value();
3203 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
3204 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus));
3206 instaceCounterWrapper.setInnerElement(counterRes.left().value());
3212 * updates componentInstance modificationTime
3214 * @param componentInstance
3215 * @param componentInstanceType
3216 * @param modificationTime
3217 * @param inTransaction
3220 public Either<ComponentInstanceData, ResponseFormat> updateComponentInstanceModificationTimeAndCustomizationUuid(
3221 ComponentInstance componentInstance, NodeTypeEnum componentInstanceType, Long modificationTime, boolean inTransaction) {
3222 Either<ComponentInstanceData, ResponseFormat> result;
3223 Either<ComponentInstanceData, StorageOperationStatus> updateComponentInstanceRes = componentInstanceOperation
3224 .updateComponentInstanceModificationTimeAndCustomizationUuidOnGraph(componentInstance, componentInstanceType, modificationTime,
3226 if (updateComponentInstanceRes.isRight()) {
3227 log.debug("Failed to update component instance {} with new last update date and mofifier. Status is {}. ", componentInstance.getName(),
3228 updateComponentInstanceRes.right().value());
3230 .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateComponentInstanceRes.right().value())));
3232 result = Either.left(updateComponentInstanceRes.left().value());
3237 public Either<ComponentInstance, ResponseFormat> deleteServiceProxy() {
3238 // TODO Add implementation
3239 return Either.left(new ComponentInstance());
3242 public Either<ComponentInstance, ResponseFormat> createServiceProxy() {
3243 // TODO Add implementation
3244 return Either.left(new ComponentInstance());
3247 public Either<ComponentInstance, ResponseFormat> changeServiceProxyVersion() {
3248 // TODO Add implementation
3249 return Either.left(new ComponentInstance());
3252 private Boolean validateInstanceNameUniquenessUponUpdate(Component containerComponent, ComponentInstance oldComponentInstance,
3253 String newInstanceName) {
3254 return ComponentValidations.validateNameIsUniqueInComponent(oldComponentInstance.getName(), newInstanceName, containerComponent);
3257 private Either<ComponentInstance, StorageOperationStatus> getResourceInstanceById(final Component containerComponent, final String instanceId) {
3258 final List<ComponentInstance> instances = containerComponent.getComponentInstances();
3259 if (CollectionUtils.isEmpty(instances)) {
3260 return Either.right(StorageOperationStatus.NOT_FOUND);
3263 final Optional<ComponentInstance> foundInstance = instances.stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst();
3264 if (foundInstance.isEmpty()) {
3265 return Either.right(StorageOperationStatus.NOT_FOUND);
3268 return Either.left(foundInstance.get());
3271 private ComponentInstance buildComponentInstance(ComponentInstance resourceInstanceForUpdate, ComponentInstance origInstanceForUpdate) {
3272 Long creationDate = origInstanceForUpdate.getCreationTime();
3273 Long modificationTime = System.currentTimeMillis();
3274 resourceInstanceForUpdate.setCreationTime(creationDate);
3275 resourceInstanceForUpdate.setModificationTime(modificationTime);
3276 resourceInstanceForUpdate.setCustomizationUUID(origInstanceForUpdate.getCustomizationUUID());
3277 if (StringUtils.isEmpty(resourceInstanceForUpdate.getName()) && StringUtils.isNotEmpty(origInstanceForUpdate.getName())) {
3278 resourceInstanceForUpdate.setName(origInstanceForUpdate.getName());
3280 resourceInstanceForUpdate.setNormalizedName(ValidationUtils.normalizeComponentInstanceName(resourceInstanceForUpdate.getName()));
3281 if (StringUtils.isEmpty(resourceInstanceForUpdate.getIcon())) {
3282 resourceInstanceForUpdate.setIcon(origInstanceForUpdate.getIcon());
3284 if (StringUtils.isEmpty(resourceInstanceForUpdate.getComponentVersion())) {
3285 resourceInstanceForUpdate.setComponentVersion(origInstanceForUpdate.getComponentVersion());
3287 if (StringUtils.isEmpty(resourceInstanceForUpdate.getComponentName())) {
3288 resourceInstanceForUpdate.setComponentName(origInstanceForUpdate.getComponentName());
3290 if (StringUtils.isEmpty(resourceInstanceForUpdate.getToscaComponentName())) {
3291 resourceInstanceForUpdate.setToscaComponentName(origInstanceForUpdate.getToscaComponentName());
3293 if (resourceInstanceForUpdate.getOriginType() == null) {
3294 resourceInstanceForUpdate.setOriginType(origInstanceForUpdate.getOriginType());
3296 if (resourceInstanceForUpdate.getOriginType() == OriginTypeEnum.ServiceProxy) {
3297 resourceInstanceForUpdate.setIsProxy(true);
3299 if (resourceInstanceForUpdate.getSourceModelInvariant() == null) {
3300 resourceInstanceForUpdate.setSourceModelInvariant(origInstanceForUpdate.getSourceModelInvariant());
3302 if (resourceInstanceForUpdate.getSourceModelName() == null) {
3303 resourceInstanceForUpdate.setSourceModelName(origInstanceForUpdate.getSourceModelName());
3305 if (resourceInstanceForUpdate.getSourceModelUuid() == null) {
3306 resourceInstanceForUpdate.setSourceModelUuid(origInstanceForUpdate.getSourceModelUuid());
3308 if (resourceInstanceForUpdate.getSourceModelUid() == null) {
3309 resourceInstanceForUpdate.setSourceModelUid(origInstanceForUpdate.getSourceModelUid());
3311 if (resourceInstanceForUpdate.getCreatedFrom() == null) {
3312 resourceInstanceForUpdate.setCreatedFrom(origInstanceForUpdate.getCreatedFrom());
3314 return resourceInstanceForUpdate;
3318 * Returns list of ComponentInstanceProperty belonging to component instance capability specified by name, type and ownerId
3320 * @param containerComponentType
3321 * @param containerComponentId
3322 * @param componentInstanceUniqueId
3323 * @param capabilityType
3324 * @param capabilityName
3329 public List<ComponentInstanceProperty> getComponentInstanceCapabilityPropertiesById(String containerComponentType, String containerComponentId,
3330 String componentInstanceUniqueId, String capabilityType,
3331 String capabilityName, String ownerId, String userId) {
3332 Component containerComponent = null;
3333 List<ComponentInstanceProperty> resultOp = null;
3335 validateUserExists(userId);
3336 validateComponentType(containerComponentType);
3337 containerComponent = toscaOperationFacade.getToscaFullElement(containerComponentId).left().on(this::componentException);
3338 ComponentInstance resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId).left()
3339 .on(this::componentInstanceException);
3340 resultOp = findCapabilityOfInstance(containerComponentId, componentInstanceUniqueId, capabilityType, capabilityName, ownerId,
3341 resourceInstanceStatus.getCapabilities());
3342 } catch (StorageException | ComponentException e) {
3343 unlockRollbackWithException(containerComponent, e);
3344 } catch (Exception e) {
3345 unlockRollbackWithException(containerComponent, new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR));
3347 unlockWithCommit(containerComponent);
3351 private List<ComponentInstanceProperty> findCapabilityOfInstance(String componentId, String instanceId, String capabilityType,
3352 String capabilityName, String ownerId,
3353 Map<String, List<CapabilityDefinition>> instanceCapabilities) {
3354 CapabilityDefinition foundCapability;
3355 if (MapUtils.isNotEmpty(instanceCapabilities)) {
3356 List<CapabilityDefinition> capabilitiesPerType = instanceCapabilities.get(capabilityType);
3357 if (capabilitiesPerType != null) {
3358 Optional<CapabilityDefinition> capabilityOpt = capabilitiesPerType.stream()
3359 .filter(c -> c.getName().equals(capabilityName) && c.getOwnerId().equals(ownerId)).findFirst();
3360 if (capabilityOpt.isPresent()) {
3361 foundCapability = capabilityOpt.get();
3362 return foundCapability.getProperties() == null ? new ArrayList<>() : foundCapability.getProperties();
3366 return fetchComponentInstanceCapabilityProperties(componentId, instanceId, capabilityType, capabilityName, ownerId);
3369 private List<ComponentInstanceProperty> fetchComponentInstanceCapabilityProperties(String componentId, String instanceId, String capabilityType,
3370 String capabilityName, String ownerId) {
3372 return toscaOperationFacade.getComponentInstanceCapabilityProperties(componentId, instanceId, capabilityName, capabilityType, ownerId)
3373 .left().on(this::componentInstancePropertyListException);
3374 } catch (Exception e) {
3375 log.debug("The exception {} occurred upon the component {} instance {} capability {} properties retrieving. ", componentId, instanceId,
3377 throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
3381 public Either<RequirementDefinition, ResponseFormat> updateInstanceRequirement(ComponentTypeEnum componentTypeEnum, String containerComponentId,
3382 String componentInstanceUniqueId,
3383 RequirementDefinition requirementDef, String userId) {
3384 Either<RequirementDefinition, ResponseFormat> resultOp = null;
3385 validateUserExists(userId);
3386 if (componentTypeEnum == null) {
3387 BeEcompErrorManager.getInstance().logInvalidInputError("updateInstanceRequirement", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
3388 return Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
3390 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaFullElement(containerComponentId);
3391 if (getResourceResult.isRight()) {
3392 log.debug(FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID, containerComponentId);
3393 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
3395 Component containerComponent = getResourceResult.left().value();
3396 if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
3397 log.info(RESTRICTED_OPERATION_ON_COMPONENT, userId, containerComponentId);
3398 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
3400 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent,
3401 componentInstanceUniqueId);
3402 if (resourceInstanceStatus.isRight()) {
3403 return Either.right(componentsUtils
3404 .getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
3407 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(containerComponentId, componentTypeEnum.getNodeType());
3408 if (lockStatus != StorageOperationStatus.OK) {
3409 log.debug(FAILED_TO_LOCK_COMPONENT, containerComponentId);
3410 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
3413 StorageOperationStatus updateRequirementStatus = toscaOperationFacade
3414 .updateComponentInstanceRequirement(containerComponentId, componentInstanceUniqueId, requirementDef);
3415 if (updateRequirementStatus != StorageOperationStatus.OK) {
3416 log.debug("Failed to update component instance requirement on instance {} in container {}", componentInstanceUniqueId,
3417 containerComponentId);
3418 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateRequirementStatus)));
3420 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade
3421 .updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
3422 if (updateContainerRes.isRight()) {
3423 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
3424 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
3427 resultOp = Either.left(requirementDef);
3430 if (resultOp == null || resultOp.isRight()) {
3431 janusGraphDao.rollback();
3433 janusGraphDao.commit();
3436 graphLockOperation.unlockComponent(containerComponentId, componentTypeEnum.getNodeType());
3440 public Either<CapabilityDefinition, ResponseFormat> updateInstanceCapability(final ComponentTypeEnum containerComponentType,
3441 final String containerComponentId,
3442 final String componentInstanceUniqueId,
3443 final CapabilityDefinition capabilityDefinition,
3444 final String userId) {
3445 if (containerComponentType == null) {
3446 BeEcompErrorManager.getInstance().logInvalidInputError("updateInstanceCapability", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
3447 return Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
3449 validateUserExists(userId);
3450 final Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaFullElement(containerComponentId);
3451 if (getResourceResult.isRight()) {
3452 log.debug(FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID, containerComponentId);
3453 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NOT_FOUND, containerComponentId));
3455 final Component containerComponent = getResourceResult.left().value();
3456 if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
3457 log.info(RESTRICTED_OPERATION_ON_COMPONENT, userId, containerComponentId);
3458 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
3460 final Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus =
3461 getResourceInstanceById(containerComponent, componentInstanceUniqueId);
3462 if (resourceInstanceStatus.isRight()) {
3463 return Either.right(componentsUtils
3464 .getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
3467 final StorageOperationStatus lockStatus = graphLockOperation.lockComponent(containerComponentId, containerComponentType.getNodeType());
3468 if (lockStatus != StorageOperationStatus.OK) {
3469 log.debug(FAILED_TO_LOCK_COMPONENT, containerComponentId);
3470 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
3472 var success = false;
3474 final CapabilityDataDefinition updatedCapabilityDefinition = toscaOperationFacade
3475 .updateComponentInstanceCapability(containerComponentId, componentInstanceUniqueId, capabilityDefinition);
3476 final Either<Component, StorageOperationStatus> updateContainerEither = toscaOperationFacade
3477 .updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
3478 if (updateContainerEither.isRight()) {
3479 var actionStatus = componentsUtils.convertFromStorageResponse(updateContainerEither.right().value(), containerComponentType);
3480 return Either.right(componentsUtils.getResponseFormat(actionStatus));
3483 return Either.left(new CapabilityDefinition(updatedCapabilityDefinition));
3484 } catch (final BusinessException e) {
3485 log.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, NodeTemplateOperation.class.getName(), (ErrorLogOptionalData) null,
3486 FAILED_TO_UPDATE_COMPONENT_INSTANCE_CAPABILITY, componentInstanceUniqueId, containerComponentId);
3488 } catch (final Exception e) {
3489 log.error(EcompLoggerErrorCode.BUSINESS_PROCESS_ERROR, NodeTemplateOperation.class.getName(), (ErrorLogOptionalData) null,
3490 FAILED_TO_UPDATE_COMPONENT_INSTANCE_CAPABILITY, componentInstanceUniqueId, containerComponentId);
3491 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
3494 janusGraphDao.commit();
3496 janusGraphDao.rollback();
3499 graphLockOperation.unlockComponent(containerComponentId, containerComponentType.getNodeType());
3503 public Either<List<ComponentInstanceProperty>, ResponseFormat> updateInstanceCapabilityProperties(ComponentTypeEnum componentTypeEnum,
3504 String containerComponentId,
3505 String componentInstanceUniqueId,
3506 String capabilityType, String capabilityName,
3507 List<ComponentInstanceProperty> properties,
3509 Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
3510 validateUserExists(userId);
3511 if (componentTypeEnum == null) {
3512 BeEcompErrorManager.getInstance().logInvalidInputError("updateInstanceCapabilityProperty", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
3513 return Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
3515 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaFullElement(containerComponentId);
3516 if (getResourceResult.isRight()) {
3517 log.debug(FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID, containerComponentId);
3518 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
3520 Component containerComponent = getResourceResult.left().value();
3521 if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
3522 log.info(RESTRICTED_OPERATION_ON_COMPONENT, userId, containerComponentId);
3523 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
3525 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent,
3526 componentInstanceUniqueId);
3527 if (resourceInstanceStatus.isRight()) {
3528 return Either.right(componentsUtils
3529 .getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
3531 ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
3533 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(containerComponentId, componentTypeEnum.getNodeType());
3534 if (lockStatus != StorageOperationStatus.OK) {
3535 log.debug(FAILED_TO_LOCK_COMPONENT, containerComponentId);
3536 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
3539 for (ComponentInstanceProperty property : properties) {
3540 Either<String, ResponseFormat> newPropertyValueEither = validatePropertyObjectValue(property, property.getValue(), false);
3541 newPropertyValueEither.bimap(
3542 updatedValue -> updateCapabilityPropertyOnContainerComponent(property, updatedValue, containerComponent, foundResourceInstance,
3543 capabilityType, capabilityName), Either::right);
3545 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade
3546 .updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
3547 if (updateContainerRes.isRight()) {
3548 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
3549 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
3552 resultOp = Either.left(properties);
3555 if (resultOp == null || resultOp.isRight()) {
3556 janusGraphDao.rollback();
3558 janusGraphDao.commit();
3561 graphLockOperation.unlockComponent(containerComponentId, componentTypeEnum.getNodeType());
3565 public Either<Map<String, ComponentInstance>, ResponseFormat> copyComponentInstance(ComponentInstance inputComponentInstance,
3566 String containerComponentId, String componentInstanceId,
3568 Map<String, ComponentInstance> resultMap = new HashMap<>();
3569 Either<Component, StorageOperationStatus> getOrigComponent = toscaOperationFacade.getToscaElement(containerComponentId);
3570 if (getOrigComponent.isRight()) {
3571 log.error("Failed to get the original component information");
3572 return Either.right(componentsUtils.getResponseFormat(ActionStatus.USER_DEFINED, FAILED_TO_COPY_COMP_INSTANCE_TO_CANVAS));
3574 Component origComponent = getOrigComponent.left().value();
3576 lockComponent(origComponent, "copyComponentInstance");
3577 } catch (ComponentException e) {
3578 log.error("destComponentInstance's data is {}", origComponent.toString());
3579 return Either.right(componentsUtils
3580 .getResponseFormat(ActionStatus.USER_DEFINED, "Failed to lock component destComponentInstance's data is {}",
3581 origComponent.toString()));
3583 boolean failed = false;
3584 ComponentInstance actionResponse = null;
3586 actionResponse = createComponentInstance("services", containerComponentId, userId, inputComponentInstance, false);
3587 } catch (ComponentException e) {
3589 // on failure of the create instance unlock the resource and rollback the transaction.
3590 return Either.right(componentsUtils.getResponseFormat(ActionStatus.USER_DEFINED, FAILED_TO_COPY_COMP_INSTANCE_TO_CANVAS));
3592 // on failure of the create instance unlock the resource and rollback the transaction.
3593 if (null == actionResponse) {
3594 log.error(FAILED_TO_COPY_COMP_INSTANCE_TO_CANVAS);
3595 unlockComponent(failed, origComponent);
3598 Either<String, ResponseFormat> resultOp = null;
3600 ComponentInstance destComponentInstance = actionResponse;
3601 log.debug("destComponentInstance's data is {}", destComponentInstance);
3602 resultOp = deepCopyComponentInstance(origComponent, containerComponentId, componentInstanceId, destComponentInstance, userId);
3603 resultMap.put("componentInstance", destComponentInstance);
3606 if (resultOp == null || resultOp.isRight()) {
3607 unlockComponent(true, origComponent);
3608 janusGraphDao.rollback();
3609 log.error("Failed to deep copy component instance");
3611 unlockComponent(false, origComponent);
3612 janusGraphDao.commit();
3613 log.debug("Success trasaction commit");
3616 if (resultOp == null || resultOp.isRight()) {
3618 .right(componentsUtils.getResponseFormat(ActionStatus.USER_DEFINED, "Failed to deep copy the component instance to the canvas"));
3620 return Either.left(resultMap);
3624 private Either<String, ResponseFormat> deepCopyComponentInstance(Component sourceComponent, String containerComponentId,
3625 String sourceComponentInstanceId, ComponentInstance destComponentInstance,
3627 Either<Component, StorageOperationStatus> getDestComponent = toscaOperationFacade.getToscaElement(containerComponentId);
3628 if (getDestComponent.isRight()) {
3629 log.error("Failed to get the dest component information");
3630 return Either.right(componentsUtils.getResponseFormat(ActionStatus.USER_DEFINED, FAILED_TO_COPY_COMP_INSTANCE_TO_CANVAS));
3632 Component destComponent = getDestComponent.left().value();
3633 Either<String, ResponseFormat> copyComponentInstanceWithPropertiesAndInputs = copyComponentInstanceWithPropertiesAndInputs(sourceComponent,
3634 destComponent, sourceComponentInstanceId, destComponentInstance);
3635 if (copyComponentInstanceWithPropertiesAndInputs.isRight()) {
3636 log.error("Failed to copy component instance with properties and inputs as part of deep copy");
3637 return Either.right(componentsUtils.getResponseFormat(ActionStatus.USER_DEFINED,
3638 "Failed to copy the component instance with properties and inputs as part of deep copy"));
3640 Either<String, ResponseFormat> copyComponentInstanceWithAttributes = copyComponentInstanceWithAttributes(sourceComponent, destComponent,
3641 sourceComponentInstanceId, destComponentInstance, userId);
3642 if (copyComponentInstanceWithAttributes.isRight()) {
3643 log.error("Failed to copy component instance with attributes as part of deep copy");
3644 return Either.right(componentsUtils
3645 .getResponseFormat(ActionStatus.USER_DEFINED, "Failed to copy the component instance with attributes as part of deep copy"));
3647 return Either.left(COPY_COMPONENT_INSTANCE_OK);
3650 private Either<String, ResponseFormat> copyComponentInstanceWithPropertiesAndInputs(Component sourceComponent, Component destComponent,
3651 String sourceComponentInstanceId,
3652 ComponentInstance destComponentInstance) {
3653 log.debug("start to copy ComponentInstance with properties and inputs");
3654 List<ComponentInstanceProperty> sourcePropList = null;
3655 if (sourceComponent.getComponentInstancesProperties() != null
3656 && sourceComponent.getComponentInstancesProperties().get(sourceComponentInstanceId) != null) {
3657 sourcePropList = sourceComponent.getComponentInstancesProperties().get(sourceComponentInstanceId);
3658 log.debug("sourcePropList");
3660 List<ComponentInstanceProperty> destPropList = null;
3661 String destComponentInstanceId = destComponentInstance.getUniqueId();
3662 log.debug("destComponentInstanceId: {}", destComponentInstance.getUniqueId());
3663 if (destComponent.getComponentInstancesProperties() != null
3664 && destComponent.getComponentInstancesProperties().get(destComponentInstanceId) != null) {
3665 destPropList = destComponent.getComponentInstancesProperties().get(destComponentInstanceId);
3666 log.debug("destPropList {}");
3668 List<ComponentInstancePropInput> componentInstancePropInputList = new ArrayList<>();
3669 if (null != destPropList && null != sourcePropList) {
3670 log.debug("start to set property and attribute");
3671 for (ComponentInstanceProperty destProp : destPropList) {
3672 String destPropertyName = destProp.getName();
3673 for (ComponentInstanceProperty sourceProp : sourcePropList) {
3674 if (!destPropertyName.equals(sourceProp.getName())) {
3677 log.debug("now set property");
3678 final List<GetInputValueDataDefinition> getInputValues = sourceProp.getGetInputValues();
3679 if (getInputValues == null && !StringUtils.isEmpty(sourceProp.getValue()) && (destProp.getValue() == null || !destProp.getValue()
3680 .equals(sourceProp.getValue()))) {
3681 log.debug("Now starting to copy the property {} in value {}", destPropertyName, sourceProp.getValue());
3682 destProp.setValue(sourceProp.getValue());
3683 Either<String, ResponseFormat> updatePropertyValueEither = updateComponentInstanceProperty(destComponent.getUniqueId(),
3684 destComponentInstanceId, destProp);
3685 if (updatePropertyValueEither.isRight()) {
3686 log.error("Failed to copy the property {}", destPropertyName);
3687 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM,
3688 "Failed to paste component instance to the canvas, property copy"));
3692 log.debug("Now start to update inputs");
3693 if (getInputValues != null) {
3694 if (getInputValues.isEmpty()) {
3695 log.debug("property is return from input, set by man");
3698 log.debug("Now starting to copy the {} property", destPropertyName);
3699 Either<String, ResponseFormat> getSourceInputDefaultValue = getInputListDefaultValue(sourceComponent,
3700 getInputValues.get(0).getInputId());
3701 if (getSourceInputDefaultValue.isRight()) {
3702 return Either.right(getSourceInputDefaultValue.right().value());
3704 componentInstancePropInputList.add(new ComponentInstancePropInput(destProp));
3709 return Either.left(COPY_COMPONENT_INSTANCE_OK);
3712 private Either<String, ResponseFormat> copyComponentInstanceWithAttributes(Component sourceComponent, Component destComponent,
3713 String sourceComponentInstanceId,
3714 ComponentInstance destComponentInstance, String userId) {
3715 String destComponentInstanceId = destComponentInstance.getUniqueId();
3716 log.info("start to copy component instance with attributes");
3717 List<ComponentInstanceAttribute> sourceAttributeList = null;
3718 if (sourceComponent.getComponentInstancesAttributes() != null
3719 && sourceComponent.getComponentInstancesAttributes().get(sourceComponentInstanceId) != null) {
3720 sourceAttributeList = sourceComponent.getComponentInstancesAttributes().get(sourceComponentInstanceId);
3721 log.info("sourceAttributes {}");
3723 List<ComponentInstanceAttribute> destAttributeList = null;
3724 if (destComponent.getComponentInstancesAttributes() != null
3725 && destComponent.getComponentInstancesAttributes().get(destComponentInstanceId) != null) {
3726 destAttributeList = destComponent.getComponentInstancesAttributes().get(destComponentInstanceId);
3727 log.info("destAttributeList {}");
3729 if (null != sourceAttributeList && null != destAttributeList) {
3730 log.info("set attribute");
3731 for (ComponentInstanceAttribute sourceAttribute : sourceAttributeList) {
3732 String sourceAttributeName = sourceAttribute.getName();
3733 for (ComponentInstanceAttribute destAttribute : destAttributeList) {
3734 if (sourceAttributeName.equals(destAttribute.getName())) {
3735 log.debug("Start to copy the attribute exists {}", sourceAttributeName);
3736 sourceAttribute.setUniqueId(
3737 UniqueIdBuilder.buildResourceInstanceUniqueId("attribute", destComponentInstanceId.split("\\.")[1], sourceAttributeName));
3738 Either<ComponentInstanceAttribute, ResponseFormat> updateAttributeValueEither = createOrUpdateAttributeValueForCopyPaste(
3739 ComponentTypeEnum.SERVICE, destComponent.getUniqueId(), destComponentInstanceId, sourceAttribute, userId);
3740 if (updateAttributeValueEither.isRight()) {
3741 log.error("Failed to copy the attribute");
3742 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM,
3743 "Failed to paste component instance to the canvas, attribute copy"));
3750 return Either.left(COPY_COMPONENT_INSTANCE_OK);
3753 private Either<ComponentInstanceAttribute, ResponseFormat> createOrUpdateAttributeValueForCopyPaste(ComponentTypeEnum componentTypeEnum,
3754 String componentId, String resourceInstanceId,
3755 ComponentInstanceAttribute attribute,
3757 Either<ComponentInstanceAttribute, ResponseFormat> resultOp = null;
3758 validateUserExists(userId);
3759 if (componentTypeEnum == null) {
3760 BeEcompErrorManager.getInstance()
3761 .logInvalidInputError("createOrUpdateAttributeValueForCopyPaste", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
3762 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
3765 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
3766 if (getResourceResult.isRight()) {
3767 log.info("Failed to retrieve component id {}", componentId);
3768 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
3771 Component containerComponent = getResourceResult.left().value();
3772 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId);
3773 if (resourceInstanceStatus.isRight()) {
3775 .right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, resourceInstanceId, componentId));
3778 ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
3779 String propertyType = attribute.getType();
3780 ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
3781 log.info("The type of attribute id{},is {} ", attribute.getUniqueId(), propertyType);
3782 if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
3783 SchemaDefinition def = attribute.getSchema();
3785 log.info("Schema doesn't exists for attribute of type {}", type);
3787 .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
3789 PropertyDataDefinition propDef = def.getProperty();
3790 if (propDef == null) {
3791 log.info("Attribute in Schema Definition inside attribute of type {} doesn't exist", type);
3793 .right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
3796 List<ComponentInstanceAttribute> instanceAttributes = containerComponent.getComponentInstancesAttributes().get(resourceInstanceId);
3797 Optional<ComponentInstanceAttribute> instanceAttribute = instanceAttributes.stream()
3798 .filter(p -> p.getUniqueId().equals(attribute.getUniqueId())).findAny();
3799 StorageOperationStatus status;
3800 if (instanceAttribute.isPresent()) {
3801 log.info("updateComponentInstanceAttribute");
3802 status = toscaOperationFacade.updateComponentInstanceAttribute(containerComponent, foundResourceInstance.getUniqueId(), attribute);
3804 log.info("addComponentInstanceAttribute");
3805 status = toscaOperationFacade.addComponentInstanceAttribute(containerComponent, foundResourceInstance.getUniqueId(), attribute);
3807 if (status != StorageOperationStatus.OK) {
3808 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
3809 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
3812 List<String> path = new ArrayList<>();
3813 path.add(foundResourceInstance.getUniqueId());
3814 attribute.setPath(path);
3815 foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
3816 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade
3817 .updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
3818 if (updateContainerRes.isRight()) {
3819 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
3820 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
3823 resultOp = Either.left(attribute);
3827 private Either<String, ResponseFormat> updateComponentInstanceProperty(String containerComponentId, String componentInstanceId,
3828 ComponentInstanceProperty property) {
3829 Either<String, ResponseFormat> resultOp;
3830 Either<Component, StorageOperationStatus> getComponent = toscaOperationFacade.getToscaElement(containerComponentId);
3831 if (getComponent.isRight()) {
3832 log.error("Failed to get the component information");
3833 return Either.right(componentsUtils
3834 .getResponseFormatForResourceInstanceProperty(ActionStatus.INVALID_CONTENT_PARAM, "Failed to get the component information"));
3836 Component containerComponent = getComponent.left().value();
3837 StorageOperationStatus status = toscaOperationFacade.updateComponentInstanceProperty(containerComponent, componentInstanceId, property);
3838 if (status != StorageOperationStatus.OK) {
3839 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
3840 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
3843 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade
3844 .updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
3845 if (updateContainerRes.isRight()) {
3846 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
3847 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
3850 return Either.left("Update OK");
3853 private Either<String, ResponseFormat> getInputListDefaultValue(Component component, String inputId) {
3854 List<InputDefinition> inputList = component.getInputs();
3855 for (InputDefinition input : inputList) {
3856 if (input.getUniqueId().equals(inputId)) {
3857 if (input.getDefaultValue() == null) {
3858 log.debug("The input's default value is null");
3859 return Either.left(null);
3861 return Either.left(input.getDefaultValue());
3864 log.error("The input's default value with id {} is not found", inputId);
3865 return Either.right(componentsUtils.getResponseFormat(ActionStatus.USER_DEFINED, "Failed to paste component instance to the canvas"));
3869 * Method to delete selected nodes and edges on composition page
3871 * @param containerComponentType
3872 * @param componentId
3873 * @param componentInstanceIdList
3877 public Map<String, List<String>> batchDeleteComponentInstance(String containerComponentType, String componentId,
3878 List<String> componentInstanceIdList, String userId) {
3879 List<String> deleteErrorIds = new ArrayList<>();
3880 Map<String, List<String>> deleteErrorMap = new HashMap<>();
3881 validateUserExists(userId);
3882 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(componentId,
3883 ComponentTypeEnum.findByParamName(containerComponentType), null);
3884 boolean failed = false;
3886 lockComponent(containerComponent, "batchDeleteComponentInstance");
3887 for (String eachInstanceId : componentInstanceIdList) {
3888 Either<ComponentInstance, ResponseFormat> actionResponse = batchDeleteComponentInstance(containerComponent, containerComponentType,
3890 log.debug("batchDeleteResourceInstances actionResponse is {}", actionResponse);
3891 if (actionResponse.isRight()) {
3892 log.error("Failed to delete ComponentInstance [{}]", eachInstanceId);
3893 deleteErrorIds.add(eachInstanceId);
3896 //sending the ids of the error nodes that were not deleted to UI
3897 deleteErrorMap.put("deleteFailedIds", deleteErrorIds);
3898 return deleteErrorMap;
3899 } catch (ComponentException e) {
3903 unlockComponent(failed, containerComponent);
3907 private Either<ComponentInstance, ResponseFormat> batchDeleteComponentInstance(Component containerComponent, String containerComponentType,
3908 String componentInstanceId) {
3909 ComponentInstance resultOp;
3910 final ComponentTypeEnum containerComponentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
3912 resultOp = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentTypeEnum);
3913 log.info("Successfully deleted instance with id {}", componentInstanceId);
3914 return Either.left(resultOp);
3915 } catch (ComponentException e) {
3916 log.error("Failed to deleteComponentInstance with instanceId[{}]", componentInstanceId);
3917 return Either.right(new ResponseFormat());
3921 private Either<Boolean, ResponseFormat> validatePropertyValueConstraint(List<ComponentInstanceProperty> properties, final String componentId) {
3923 String propertyModel = propertyBusinessLogic.getComponentModelByComponentId(componentId);
3924 PropertyValueConstraintValidationUtil propertyValueConstraintValidationUtil = new PropertyValueConstraintValidationUtil();
3925 return propertyValueConstraintValidationUtil.validatePropertyConstraints(properties, applicationDataTypeCache, propertyModel);
3926 } catch (BusinessLogicException e) {
3927 return Either.right(e.getResponseFormat());
3931 public void validateUser(final String userId) {
3932 final User user = userValidations.validateUserExists(userId);
3933 userValidations.validateUserRole(user, Arrays.asList(Role.DESIGNER, Role.ADMIN));
3936 public void setCompositionBusinessLogic(CompositionBusinessLogic compositionBusinessLogic) {
3937 this.compositionBusinessLogic = compositionBusinessLogic;
3940 public void setContainerInstanceTypesData(ContainerInstanceTypesData containerInstanceTypesData) {
3941 this.containerInstanceTypesData = containerInstanceTypesData;