2 * ============LICENSE_START=======================================================
4 * ================================================================================
5 * Copyright (C) 2017 AT&T Intellectual Property. All rights reserved.
6 * ================================================================================
7 * Licensed under the Apache License, Version 2.0 (the "License");
8 * you may not use this file except in compliance with the License.
9 * You may obtain a copy of the License at
11 * http://www.apache.org/licenses/LICENSE-2.0
13 * Unless required by applicable law or agreed to in writing, software
14 * distributed under the License is distributed on an "AS IS" BASIS,
15 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16 * See the License for the specific language governing permissions and
17 * limitations under the License.
18 * ============LICENSE_END=========================================================
21 package org.openecomp.sdc.be.components.impl;
23 import com.google.common.collect.Sets;
24 import fj.data.Either;
25 import org.apache.commons.collections.CollectionUtils;
26 import org.apache.commons.collections.MapUtils;
27 import org.apache.commons.lang.StringUtils;
28 import org.apache.commons.lang3.tuple.ImmutablePair;
29 import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
30 import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException;
31 import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
32 import org.openecomp.sdc.be.components.impl.instance.ComponentInstanceChangeOperationOrchestrator;
33 import org.openecomp.sdc.be.components.impl.utils.DirectivesUtils;
34 import org.openecomp.sdc.be.components.merge.instance.ComponentInstanceMergeDataBusinessLogic;
35 import org.openecomp.sdc.be.components.merge.instance.DataForMergeHolder;
36 import org.openecomp.sdc.be.components.utils.PropertiesUtils;
37 import org.openecomp.sdc.be.components.validation.ComponentValidations;
38 import org.openecomp.sdc.be.config.BeEcompErrorManager;
39 import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
40 import org.openecomp.sdc.be.config.ConfigurationManager;
41 import org.openecomp.sdc.be.dao.api.ActionStatus;
42 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
43 import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
44 import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
45 import org.openecomp.sdc.be.datamodel.utils.ContainerInstanceTypesData;
46 import org.openecomp.sdc.be.datatypes.elements.CINodeFilterDataDefinition;
47 import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition;
48 import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition;
49 import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition;
50 import org.openecomp.sdc.be.datatypes.elements.GetPolicyValueDataDefinition;
51 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
52 import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition;
53 import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
54 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
55 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
56 import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
57 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
58 import org.openecomp.sdc.be.impl.ForwardingPathUtils;
59 import org.openecomp.sdc.be.impl.ServiceFilterUtils;
60 import org.openecomp.sdc.be.info.CreateAndAssotiateInfo;
61 import org.openecomp.sdc.be.model.ArtifactDefinition;
62 import org.openecomp.sdc.be.model.CapabilityDefinition;
63 import org.openecomp.sdc.be.model.Component;
64 import org.openecomp.sdc.be.model.ComponentInstance;
65 import org.openecomp.sdc.be.model.ComponentInstanceInput;
66 import org.openecomp.sdc.be.model.ComponentInstancePropInput;
67 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
68 import org.openecomp.sdc.be.model.ComponentParametersView;
69 import org.openecomp.sdc.be.model.DataTypeDefinition;
70 import org.openecomp.sdc.be.model.GroupDefinition;
71 import org.openecomp.sdc.be.model.InputDefinition;
72 import org.openecomp.sdc.be.model.InterfaceDefinition;
73 import org.openecomp.sdc.be.model.LifecycleStateEnum;
74 import org.openecomp.sdc.be.model.PolicyDefinition;
75 import org.openecomp.sdc.be.model.PropertyDefinition;
76 import org.openecomp.sdc.be.model.RelationshipInfo;
77 import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
78 import org.openecomp.sdc.be.model.RequirementDefinition;
79 import org.openecomp.sdc.be.model.Resource;
80 import org.openecomp.sdc.be.model.Service;
81 import org.openecomp.sdc.be.model.User;
82 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ArtifactsOperations;
83 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ForwardingPathOperation;
84 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.InterfaceOperation;
85 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.NodeFilterOperation;
86 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade;
87 import org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter;
88 import org.openecomp.sdc.be.model.operations.StorageException;
89 import org.openecomp.sdc.be.model.operations.api.IElementOperation;
90 import org.openecomp.sdc.be.model.operations.api.IGroupInstanceOperation;
91 import org.openecomp.sdc.be.model.operations.api.IGroupOperation;
92 import org.openecomp.sdc.be.model.operations.api.IGroupTypeOperation;
93 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
94 import org.openecomp.sdc.be.model.operations.impl.ComponentInstanceOperation;
95 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
96 import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation;
97 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
98 import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
99 import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
100 import org.openecomp.sdc.be.resources.data.ComponentInstanceData;
101 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
102 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
103 import org.openecomp.sdc.common.api.Constants;
104 import org.openecomp.sdc.common.datastructure.Wrapper;
105 import org.openecomp.sdc.common.jsongraph.util.CommonUtility;
106 import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum;
107 import org.openecomp.sdc.common.log.wrappers.Logger;
108 import org.openecomp.sdc.common.util.ValidationUtils;
109 import org.openecomp.sdc.exception.ResponseFormat;
110 import org.springframework.beans.factory.annotation.Autowired;
112 import java.util.ArrayList;
113 import java.util.Arrays;
114 import java.util.Collection;
115 import java.util.Collections;
116 import java.util.HashMap;
117 import java.util.Iterator;
118 import java.util.List;
119 import java.util.Map;
120 import java.util.Map.Entry;
121 import java.util.Objects;
122 import java.util.Optional;
123 import java.util.Set;
124 import java.util.UUID;
125 import java.util.function.BiConsumer;
126 import java.util.stream.Collectors;
128 import static org.openecomp.sdc.be.components.property.GetInputUtils.isGetInputValueForInput;
129 import static org.openecomp.sdc.be.components.utils.PropertiesUtils.getPropertyCapabilityOfChildInstance;
131 @org.springframework.stereotype.Component
132 public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
134 private static final Logger log = Logger.getLogger(ComponentInstanceBusinessLogic.class.getName());
135 private static final String VF_MODULE = "org.openecomp.groups.VfModule";
136 private static final String TRY_TO_CREATE_ENTRY_ON_GRAPH = "Try to create entry on graph";
137 private static final String CLOUD_SPECIFIC_FIXED_KEY_WORD = "cloudtech";
138 private static final String[][] CLOUD_SPECIFIC_KEY_WORDS = {{"k8s", "azure", "aws"}, /* cloud specific technology */
139 {"charts", "day0", "configtemplate"} /*cloud specific sub type*/};
140 private static final String FAILED_TO_CREATE_ENTRY_ON_GRAPH_FOR_COMPONENT_INSTANCE = "Failed to create entry on graph for component instance {}";
141 private static final String ENTITY_ON_GRAPH_IS_CREATED = "Entity on graph is created.";
142 private static final String INVALID_COMPONENT_TYPE = "invalid component type";
143 private static final String FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID = "Failed to retrieve component, component id {}";
144 private static final String FAILED_TO_LOCK_SERVICE = "Failed to lock service {}";
145 private static final String CREATE_OR_UPDATE_PROPERTY_VALUE = "CreateOrUpdatePropertyValue";
146 private static final String FAILED_TO_COPY_COMP_INSTANCE_TO_CANVAS = "Failed to copy the component instance to the canvas";
147 private static final String COPY_COMPONENT_INSTANCE_OK = "Copy component instance OK";
149 private ComponentInstanceOperation componentInstanceOperation;
150 private ArtifactsBusinessLogic artifactBusinessLogic;
151 private ComponentInstanceMergeDataBusinessLogic compInstMergeDataBL;
152 private ComponentInstanceChangeOperationOrchestrator onChangeInstanceOperationOrchestrator;
153 private ForwardingPathOperation forwardingPathOperation;
154 private NodeFilterOperation serviceFilterOperation;
157 public ComponentInstanceBusinessLogic(IElementOperation elementDao,
158 IGroupOperation groupOperation,
159 IGroupInstanceOperation groupInstanceOperation,
160 IGroupTypeOperation groupTypeOperation,
161 InterfaceOperation interfaceOperation,
162 InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
163 ComponentInstanceOperation componentInstanceOperation, ArtifactsBusinessLogic artifactBusinessLogic,
164 ComponentInstanceMergeDataBusinessLogic compInstMergeDataBL,
165 ComponentInstanceChangeOperationOrchestrator onChangeInstanceOperationOrchestrator,
166 ForwardingPathOperation forwardingPathOperation, NodeFilterOperation serviceFilterOperation,
167 ArtifactsOperations artifactToscaOperation) {
168 super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation,
169 interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation);
170 this.componentInstanceOperation = componentInstanceOperation;
171 this.artifactBusinessLogic = artifactBusinessLogic;
172 this.compInstMergeDataBL = compInstMergeDataBL;
173 this.onChangeInstanceOperationOrchestrator = onChangeInstanceOperationOrchestrator;
174 this.forwardingPathOperation = forwardingPathOperation;
175 this.serviceFilterOperation = serviceFilterOperation;
179 private CompositionBusinessLogic compositionBusinessLogic;
182 private ContainerInstanceTypesData containerInstanceTypesData;
184 public ComponentInstance createComponentInstance(String containerComponentParam, String containerComponentId, String userId, ComponentInstance resourceInstance) {
185 return createComponentInstance(containerComponentParam, containerComponentId, userId, resourceInstance, false, true);
188 public List<ComponentInstanceProperty> getComponentInstancePropertiesByInputId(org.openecomp.sdc.be.model.Component component, String inputId){
189 List<ComponentInstanceProperty> resList = new ArrayList<>();
190 Map<String, List<ComponentInstanceProperty>> ciPropertiesMap = component.getComponentInstancesProperties();
191 if(ciPropertiesMap != null && !ciPropertiesMap.isEmpty()){
192 ciPropertiesMap.forEach(new BiConsumer<String, List<ComponentInstanceProperty>>() {
194 public void accept(String s, List<ComponentInstanceProperty> ciPropList) {
196 Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci ->ci.getUniqueId().equals(s)).findAny();
198 ciName = ciOp.get().getName();
199 if (ciPropList != null && !ciPropList.isEmpty()) {
200 for(ComponentInstanceProperty prop: ciPropList){
201 List<GetInputValueDataDefinition> inputsValues = prop.getGetInputValues();
202 addCompInstanceProperty(s, ciName, prop, inputsValues, inputId, resList);
212 private void addCompInstanceProperty(String s, String ciName, ComponentInstanceProperty prop, List<GetInputValueDataDefinition> inputsValues, String inputId, List<ComponentInstanceProperty> resList) {
213 if(inputsValues != null && !inputsValues.isEmpty()){
214 for(GetInputValueDataDefinition inputData: inputsValues){
215 if(isGetInputValueForInput(inputData, inputId)){
216 prop.setComponentInstanceId(s);
217 prop.setComponentInstanceName(ciName);
225 public Optional<ComponentInstanceProperty> getComponentInstancePropertyByPolicyId(Component component,
226 PolicyDefinition policy) {
228 Optional<ComponentInstanceProperty> propertyCandidate = getComponentInstancePropertyByPolicy(component, policy);
230 if(propertyCandidate.isPresent()) {
231 ComponentInstanceProperty componentInstanceProperty = propertyCandidate.get();
232 Optional<GetPolicyValueDataDefinition> getPolicyCandidate =
233 getGetPolicyValueDataDefinition(policy, componentInstanceProperty);
235 getPolicyCandidate.ifPresent(getPolicyValue ->
236 updateComponentInstancePropertyAfterUndeclaration(componentInstanceProperty, getPolicyValue, policy));
237 return Optional.of(componentInstanceProperty);
240 return Optional.empty();
244 private void updateComponentInstancePropertyAfterUndeclaration(ComponentInstanceProperty componentInstanceProperty,
245 GetPolicyValueDataDefinition getPolicyValue, PolicyDefinition policyDefinition) {
246 componentInstanceProperty.setValue(getPolicyValue.getOrigPropertyValue());
247 List<GetPolicyValueDataDefinition> getPolicyValues = componentInstanceProperty.getGetPolicyValues();
248 if(CollectionUtils.isNotEmpty(getPolicyValues)) {
249 getPolicyValues.remove(getPolicyValue);
250 componentInstanceProperty.setGetPolicyValues(getPolicyValues);
251 policyDefinition.setGetPolicyValues(getPolicyValues);
255 private Optional<GetPolicyValueDataDefinition> getGetPolicyValueDataDefinition(PolicyDefinition policy,
256 ComponentInstanceProperty componentInstanceProperty) {
257 List<GetPolicyValueDataDefinition> getPolicyValues = policy.getGetPolicyValues();
258 return getPolicyValues.stream()
259 .filter(getPolicyValue -> getPolicyValue
261 .equals(componentInstanceProperty
266 private Optional<ComponentInstanceProperty> getComponentInstancePropertyByPolicy(Component component,
267 PolicyDefinition policy) {
268 Map<String, List<ComponentInstanceProperty>> componentInstancesProperties =
269 component.getComponentInstancesProperties();
271 if(MapUtils.isEmpty(componentInstancesProperties)) {
272 return Optional.empty();
275 String instanceUniqueId = policy.getInstanceUniqueId();
277 List<ComponentInstanceProperty> componentInstanceProperties =
278 componentInstancesProperties.containsKey(instanceUniqueId)
279 ? componentInstancesProperties.get(instanceUniqueId)
282 return componentInstanceProperties
283 .stream().filter(property -> property.getName().equals(policy.getName())).findAny();
286 public List<ComponentInstanceInput> getComponentInstanceInputsByInputId(
287 org.openecomp.sdc.be.model.Component component, String inputId) {
288 List<ComponentInstanceInput> resList = new ArrayList<>();
289 Map<String, List<ComponentInstanceInput>> ciInputsMap = component.getComponentInstancesInputs();
290 if(ciInputsMap != null && !ciInputsMap.isEmpty()){
291 ciInputsMap.forEach(new BiConsumer<String, List<ComponentInstanceInput>>() {
293 public void accept(String s, List<ComponentInstanceInput> ciPropList) {
295 Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci ->ci.getUniqueId().equals(s)).findAny();
297 ciName = ciOp.get().getName();
298 if (ciPropList != null && !ciPropList.isEmpty()) {
299 for(ComponentInstanceInput prop: ciPropList){
300 List<GetInputValueDataDefinition> inputsValues = prop.getGetInputValues();
301 addCompInstanceInput(s, ciName, prop, inputsValues, inputId, resList);
312 private void addCompInstanceInput(String s, String ciName, ComponentInstanceInput prop, List<GetInputValueDataDefinition> inputsValues, String inputId, List<ComponentInstanceInput> resList) {
313 if(inputsValues != null && !inputsValues.isEmpty()){
314 for(GetInputValueDataDefinition inputData: inputsValues){
315 if(isGetInputValueForInput(inputData, inputId)){
316 prop.setComponentInstanceId(s);
317 prop.setComponentInstanceName(ciName);
325 public ComponentInstance createComponentInstance(String containerComponentParam, String containerComponentId, String userId, ComponentInstance resourceInstance, boolean inTransaction, boolean needLock) {
327 Component origComponent = null;
329 org.openecomp.sdc.be.model.Component containerComponent = null;
330 ComponentTypeEnum containerComponentType;
332 user = validateUserExists(userId);
333 validateUserNotEmpty(user, "Create component instance");
334 validateJsonBody(resourceInstance, ComponentInstance.class);
335 containerComponentType = validateComponentType(containerComponentParam);
336 containerComponent = validateComponentExists(containerComponentId, containerComponentType, null);
338 if (ModelConverter.isAtomicComponent(containerComponent)) {
339 log.debug("Cannot attach resource instances to container resource of type {}", containerComponent.assetType());
340 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType());
343 validateCanWorkOnComponent(containerComponent, userId);
345 if (resourceInstance != null && containerComponentType != null) {
346 OriginTypeEnum originType = resourceInstance.getOriginType();
347 validateInstanceName(resourceInstance);
348 if (originType == OriginTypeEnum.ServiceProxy) {
350 Either<Component, StorageOperationStatus> serviceProxyOrigin = toscaOperationFacade.getLatestByName("serviceProxy");
351 if (isServiceProxyOrigin(serviceProxyOrigin)) {
352 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(serviceProxyOrigin.right().value()));
354 origComponent = serviceProxyOrigin.left().value();
356 StorageOperationStatus fillProxyRes = fillProxyInstanceData(resourceInstance, origComponent);
357 if (isFillProxyRes(fillProxyRes)) {
358 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(fillProxyRes));
362 origComponent = getAndValidateOriginComponentOfComponentInstance(containerComponent, resourceInstance);
364 validateOriginAndResourceInstanceTypes(containerComponent, origComponent, originType);
365 validateResourceInstanceState(containerComponent, origComponent);
366 overrideFields(origComponent, resourceInstance);
367 compositionBusinessLogic.validateAndSetDefaultCoordinates(resourceInstance);
369 return createComponent(needLock, containerComponent,origComponent, resourceInstance, user);
371 }catch (ComponentException e){
376 private ComponentInstance createComponent(boolean needLock, Component containerComponent, Component origComponent, ComponentInstance resourceInstance, User user) {
378 boolean failed = false;
381 ComponentInstance lockComponent = isNeedLock(needLock, containerComponent);
382 if (lockComponent != null) {
383 return lockComponent;
385 log.debug(TRY_TO_CREATE_ENTRY_ON_GRAPH);
386 return createComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, user);
387 }catch (ComponentException e){
392 unlockComponent(failed, containerComponent);
396 private void overrideFields(Component origComponent, ComponentInstance resourceInstance) {
397 resourceInstance.setComponentVersion(origComponent.getVersion());
398 resourceInstance.setIcon(origComponent.getIcon());
401 private void validateInstanceName(ComponentInstance resourceInstance) {
403 String resourceInstanceName = resourceInstance.getName();
404 if (StringUtils.isEmpty(resourceInstanceName)) {
405 log.debug("ComponentInstance name is empty");
406 throw new ByActionStatusComponentException(ActionStatus.INVALID_COMPONENT_NAME, resourceInstance.getName());
409 if (!ValidationUtils.validateComponentNameLength(resourceInstanceName)) {
410 log.debug("ComponentInstance name exceeds max length {} ", ValidationUtils.COMPONENT_NAME_MAX_LENGTH);
411 throw new ByActionStatusComponentException(ActionStatus.INVALID_COMPONENT_NAME, resourceInstance.getName());
414 if (!ValidationUtils.validateComponentNamePattern(resourceInstanceName)) {
415 log.debug("ComponentInstance name {} has invalid format", resourceInstanceName);
416 throw new ByActionStatusComponentException(ActionStatus.INVALID_COMPONENT_NAME, resourceInstance.getName());
420 private void validateResourceInstanceState(Component containerComponent, Component origComponent) {
421 if (origComponent.getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT){
422 throw new ByActionStatusComponentException(ActionStatus.CONTAINER_CANNOT_CONTAIN_INSTANCE,
423 containerComponent.getComponentType().getValue(), origComponent.getLifecycleState().toString());
427 private void validateOriginAndResourceInstanceTypes(Component containerComponent, Component origComponent, OriginTypeEnum originType) {
428 ResourceTypeEnum resourceType = null;
429 ResourceTypeEnum convertedOriginType;
430 resourceType = getResourceTypeEnumFromOriginComponent(origComponent, resourceType);
431 validateOriginType(originType, resourceType);
432 validateOriginComponentIsValidForContainer(containerComponent, resourceType);
435 private void validateOriginComponentIsValidForContainer(Component containerComponent, ResourceTypeEnum resourceType) {
436 switch (containerComponent.getComponentType()) {
438 if (!containerInstanceTypesData.getServiceContainerList().contains((resourceType))) {
439 throw new ByActionStatusComponentException(ActionStatus.CONTAINER_CANNOT_CONTAIN_INSTANCE,
440 containerComponent.getComponentType().toString(), resourceType.name());
444 if (!containerInstanceTypesData.getValidInstanceTypesInResourceContainer().get(((Resource) containerComponent).getResourceType()).contains(resourceType)) {
445 throw new ByActionStatusComponentException(ActionStatus.CONTAINER_CANNOT_CONTAIN_INSTANCE,
446 containerComponent.getComponentType().toString(), resourceType.name());
450 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
454 private void validateOriginType(OriginTypeEnum originType, ResourceTypeEnum resourceType) {
455 ResourceTypeEnum convertedOriginType;
457 convertedOriginType = ResourceTypeEnum.getTypeIgnoreCase(originType.name());
460 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
463 if (resourceType != convertedOriginType) throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
466 private ResourceTypeEnum getResourceTypeEnumFromOriginComponent(Component origComponent, ResourceTypeEnum resourceType) {
467 switch (origComponent.getComponentType()) {
469 resourceType = ResourceTypeEnum.ServiceProxy;
472 resourceType = ((Resource) origComponent).getResourceType();
475 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
480 private ComponentInstance isNeedLock(boolean needLock, Component containerComponent) {
482 lockComponent(containerComponent, "createComponentInstance");
487 private boolean isServiceProxyOrigin(Either<Component, StorageOperationStatus> serviceProxyOrigin) {
488 if (serviceProxyOrigin.isRight()) {
489 log.debug("Failed to fetch normative service proxy resource by tosca name, error {}", serviceProxyOrigin.right().value());
495 private StorageOperationStatus fillProxyInstanceData(ComponentInstance resourceInstance, Component proxyTemplate) {
496 resourceInstance.setIsProxy(true);
497 ComponentParametersView filter = new ComponentParametersView(true);
498 filter.setIgnoreCapabilities(false);
499 filter.setIgnoreCapabiltyProperties(false);
500 filter.setIgnoreComponentInstances(false);
501 filter.setIgnoreRequirements(false);
502 filter.setIgnoreInterfaces(false);
503 filter.setIgnoreProperties(false);
504 filter.setIgnoreInputs(false);
505 Either<Component, StorageOperationStatus> serviceRes =
506 toscaOperationFacade.getToscaElement(resourceInstance.getComponentUid(), filter);
507 if (serviceRes.isRight()) {
508 return serviceRes.right().value();
510 Component service = serviceRes.left().value();
511 Map<String, List<CapabilityDefinition>> capabilities = service.getCapabilities();
512 resourceInstance.setCapabilities(capabilities);
513 Map<String, List<RequirementDefinition>> req = service.getRequirements();
514 resourceInstance.setRequirements(req);
515 Map<String, InterfaceDefinition> serviceInterfaces = service.getInterfaces();
516 if(MapUtils.isNotEmpty(serviceInterfaces)) {
517 serviceInterfaces.forEach(resourceInstance::addInterface);
521 resourceInstance.setProperties(PropertiesUtils.getProperties(service));
523 List<InputDefinition> serviceInputs = service.getInputs();
524 resourceInstance.setInputs(serviceInputs);
526 String name = ValidationUtils.normalizeComponentInstanceName(service.getName()) + ToscaOperationFacade.PROXY_SUFFIX;
527 String toscaResourceName = ((Resource) proxyTemplate).getToscaResourceName();
528 int lastIndexOf = toscaResourceName.lastIndexOf('.');
529 if (lastIndexOf != -1) {
530 String proxyToscaName = toscaResourceName.substring(0, lastIndexOf + 1) + name;
531 resourceInstance.setToscaComponentName(proxyToscaName);
533 resourceInstance.setName(name);
534 resourceInstance.setIsProxy(true);
535 resourceInstance.setSourceModelInvariant(service.getInvariantUUID());
536 resourceInstance.setSourceModelName(service.getName());
537 resourceInstance.setSourceModelUuid(service.getUUID());
538 resourceInstance.setSourceModelUid(service.getUniqueId());
539 resourceInstance.setComponentUid(proxyTemplate.getUniqueId());
540 resourceInstance.setDescription("A Proxy for Service " + service.getName());
541 resourceInstance.setComponentVersion(service.getVersion());
543 return StorageOperationStatus.OK;
546 public Either<CreateAndAssotiateInfo, ResponseFormat> createAndAssociateRIToRI(String containerComponentParam, String containerComponentId, String userId, CreateAndAssotiateInfo createAndAssotiateInfo) {
548 Either<CreateAndAssotiateInfo, ResponseFormat> resultOp = null;
549 ComponentInstance resourceInstance = createAndAssotiateInfo.getNode();
550 RequirementCapabilityRelDef associationInfo = createAndAssotiateInfo.getAssociate();
552 User user = validateUserExists(userId);
554 final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
556 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, null);
558 if (ModelConverter.isAtomicComponent(containerComponent)) {
559 log.debug("Cannot attach resource instances to container resource of type {}", containerComponent.assetType());
560 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType()));
563 validateCanWorkOnComponent(containerComponent, userId);
565 boolean failed = false;
567 lockComponent(containerComponent, "createAndAssociateRIToRI");
568 log.debug(TRY_TO_CREATE_ENTRY_ON_GRAPH);
569 Component origComponent = getOriginComponentFromComponentInstance(resourceInstance);
571 log.debug(ENTITY_ON_GRAPH_IS_CREATED);
572 ComponentInstance resResourceInfo = createComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, user);
573 if (associationInfo.getFromNode() == null || associationInfo.getFromNode().isEmpty()) {
574 associationInfo.setFromNode(resResourceInfo.getUniqueId());
576 associationInfo.setToNode(resResourceInfo.getUniqueId());
579 Either<RequirementCapabilityRelDef, StorageOperationStatus> resultReqCapDef = toscaOperationFacade.associateResourceInstances(containerComponent, containerComponentId, associationInfo);
580 if (resultReqCapDef.isLeft()) {
581 log.debug(ENTITY_ON_GRAPH_IS_CREATED);
582 RequirementCapabilityRelDef resReqCapabilityRelDef = resultReqCapDef.left().value();
583 CreateAndAssotiateInfo resInfo = new CreateAndAssotiateInfo(resResourceInfo, resReqCapabilityRelDef);
584 resultOp = Either.left(resInfo);
588 log.info("Failed to associate node {} with node {}", associationInfo.getFromNode(), associationInfo.getToNode());
589 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(resultReqCapDef.right().value(), true), "", null));
593 }catch (ComponentException e){
597 unlockComponent(failed, containerComponent);
601 private Component getOriginComponentFromComponentInstance(ComponentInstance componentInstance) {
602 return getOriginComponentFromComponentInstance(componentInstance.getName(), componentInstance.getComponentUid());
605 private Component getInstanceOriginNode(ComponentInstance componentInstance) {
606 return getOriginComponentFromComponentInstance(componentInstance.getName(), componentInstance.getActualComponentUid());
609 private Component getOriginComponentFromComponentInstance(String componentInstanceName, String origComponetId) {
610 Either<Component, StorageOperationStatus> eitherComponent = toscaOperationFacade.getToscaFullElement(origComponetId);
611 if (eitherComponent.isRight()) {
612 log.debug("Failed to get origin component with id {} for component instance {} ", origComponetId, componentInstanceName);
613 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(eitherComponent.right().value(), ComponentTypeEnum.RESOURCE), "", null);
615 return eitherComponent.left().value();
618 private ComponentInstance createComponentInstanceOnGraph(org.openecomp.sdc.be.model.Component containerComponent, Component originComponent, ComponentInstance componentInstance, User user) {
619 Either<ComponentInstance, ResponseFormat> resultOp;
621 Either<ImmutablePair<Component, String>, StorageOperationStatus> result = toscaOperationFacade.addComponentInstanceToTopologyTemplate(containerComponent, originComponent, componentInstance, false, user);
623 if (result.isRight()) {
624 log.debug(FAILED_TO_CREATE_ENTRY_ON_GRAPH_FOR_COMPONENT_INSTANCE, componentInstance.getName());
625 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), "", null));
628 log.debug(ENTITY_ON_GRAPH_IS_CREATED);
629 Component updatedComponent = result.left().value().getLeft();
630 Map<String, String> existingEnvVersions = new HashMap<>();
631 // TODO existingEnvVersions ??
632 addComponentInstanceArtifacts(updatedComponent, componentInstance, originComponent, user, existingEnvVersions);
634 Optional<ComponentInstance> updatedInstanceOptional = updatedComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(result.left().value().getRight())).findFirst();
635 if (!updatedInstanceOptional.isPresent()) {
636 log.debug("Failed to fetch new added component instance {} from component {}", componentInstance.getName(), containerComponent.getName());
637 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName());
639 return updatedInstanceOptional.get();
642 public boolean isCloudSpecificArtifact(String artifact) {
643 if (artifact.contains(CLOUD_SPECIFIC_FIXED_KEY_WORD)) {
644 for (int i = 0; i < CLOUD_SPECIFIC_KEY_WORDS.length; i++) {
645 if (Arrays.stream(CLOUD_SPECIFIC_KEY_WORDS[i]).noneMatch(str -> artifact.contains(str))) {
657 * addResourceInstanceArtifacts - add artifacts (HEAT_ENV) to resource instance The instance artifacts are generated from the resource's artifacts
658 * @param containerComponent
659 * @param componentInstance
660 * @param originComponent
662 * @param existingEnvVersions
665 protected ActionStatus addComponentInstanceArtifacts(org.openecomp.sdc.be.model.Component containerComponent, ComponentInstance componentInstance, org.openecomp.sdc.be.model.Component originComponent, User user, Map<String, String> existingEnvVersions) {
667 log.debug("add artifacts to resource instance");
668 List<GroupDefinition> filteredGroups = null;
669 ActionStatus status = setResourceArtifactsOnResourceInstance(componentInstance);
670 if (ActionStatus.OK != status) {
671 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormatForResourceInstance(status, "", null));
673 StorageOperationStatus artStatus;
674 // generate heat_env if necessary
675 Map<String, ArtifactDefinition> componentDeploymentArtifacts = componentInstance.getDeploymentArtifacts();
676 if (MapUtils.isNotEmpty(componentDeploymentArtifacts)) {
678 Map<String, ArtifactDefinition> finalDeploymentArtifacts = new HashMap<>();
679 Map<String, List<ArtifactDefinition>> groupInstancesArtifacts = new HashMap<>();
680 Integer defaultHeatTimeout = ConfigurationManager.getConfigurationManager().getConfiguration()
681 .getHeatArtifactDeploymentTimeout().getDefaultMinutes();
682 for (ArtifactDefinition artifact : componentDeploymentArtifacts.values()) {
683 String type = artifact.getArtifactType();
684 if (!type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType())) {
685 finalDeploymentArtifacts.put(artifact.getArtifactLabel(), artifact);
687 if (type.equalsIgnoreCase(ArtifactTypeEnum.HEAT.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_NET.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_VOL.getType()) || type.equalsIgnoreCase(ArtifactTypeEnum.CLOUD_TECHNOLOGY_SPECIFIC_ARTIFACT.getType())) {
688 artifact.setTimeout(defaultHeatTimeout);
692 if (artifact.checkEsIdExist()) {
693 ArtifactDefinition artifactDefinition = artifactBusinessLogic.createHeatEnvPlaceHolder(new ArrayList<>(),
694 artifact, ArtifactsBusinessLogic.HEAT_ENV_NAME, componentInstance.getUniqueId(),
695 NodeTypeEnum.ResourceInstance, componentInstance.getName(), user, containerComponent,
696 existingEnvVersions);
698 finalDeploymentArtifacts.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
700 if (CollectionUtils.isNotEmpty(originComponent.getGroups())) {
701 filteredGroups = originComponent.getGroups().stream().filter(g -> g.getType().equals(VF_MODULE)).collect(Collectors.toList());
703 if (CollectionUtils.isNotEmpty(filteredGroups)) {
704 filteredGroups.stream().filter(g ->
707 .anyMatch(p -> p.equals(artifactDefinition.getGeneratedFromId())))
709 .ifPresent(g -> fillInstanceArtifactMap(groupInstancesArtifacts, artifactDefinition, g));
713 artStatus = toscaOperationFacade.addDeploymentArtifactsToInstance(containerComponent.getUniqueId(), componentInstance, finalDeploymentArtifacts);
714 if (artStatus != StorageOperationStatus.OK) {
715 log.debug("Failed to add instance deployment artifacts for instance {} in conatiner {} error {}", componentInstance.getUniqueId(), containerComponent.getUniqueId(), artStatus);
716 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(artStatus, false)));
719 StorageOperationStatus result = toscaOperationFacade.addGroupInstancesToComponentInstance(containerComponent, componentInstance, filteredGroups, groupInstancesArtifacts);
720 if (result != StorageOperationStatus.OK) {
721 log.debug("failed to update group instance for component instance {}", componentInstance.getUniqueId());
722 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(result)));
724 componentInstance.setDeploymentArtifacts(finalDeploymentArtifacts);
727 artStatus = toscaOperationFacade.addInformationalArtifactsToInstance(containerComponent.getUniqueId(), componentInstance, originComponent.getArtifacts());
728 if (artStatus != StorageOperationStatus.OK) {
729 log.debug("Failed to add informational artifacts to the instance {} belonging to the conatiner {}. Status is {}", componentInstance.getUniqueId(), containerComponent.getUniqueId(), artStatus);
730 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(artStatus, false)));
733 componentInstance.setArtifacts(originComponent.getArtifacts());
734 return ActionStatus.OK;
737 private void fillInstanceArtifactMap(Map<String, List<ArtifactDefinition>> groupInstancesArtifacts, ArtifactDefinition artifactDefinition, GroupDefinition groupInstance) {
738 List<ArtifactDefinition> artifactsUid;
739 if (groupInstancesArtifacts.containsKey(groupInstance.getUniqueId())) {
740 artifactsUid = groupInstancesArtifacts.get(groupInstance.getUniqueId());
742 artifactsUid = new ArrayList<>();
744 artifactsUid.add(artifactDefinition);
745 groupInstancesArtifacts.put(groupInstance.getUniqueId(), artifactsUid);
746 if (isCloudSpecificArtifact(artifactDefinition.getArtifactName())) {
747 groupInstance.getArtifacts().add(artifactDefinition.getGeneratedFromId());
751 private ActionStatus setResourceArtifactsOnResourceInstance(ComponentInstance resourceInstance) {
752 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getResourceDeploymentArtifacts =
753 artifactBusinessLogic.getArtifacts(resourceInstance.getComponentUid(), NodeTypeEnum.Resource, ArtifactGroupTypeEnum.DEPLOYMENT, null);
755 Map<String, ArtifactDefinition> deploymentArtifacts = new HashMap<>();
756 if (getResourceDeploymentArtifacts.isRight()) {
757 StorageOperationStatus status = getResourceDeploymentArtifacts.right().value();
758 if (status != StorageOperationStatus.NOT_FOUND) {
759 log.debug("Failed to fetch resource: {} artifacts. status is {}", resourceInstance.getComponentUid(), status);
760 return componentsUtils.convertFromStorageResponseForResourceInstance(status, true);
763 deploymentArtifacts = getResourceDeploymentArtifacts.left().value();
766 if (!deploymentArtifacts.isEmpty()) {
767 Map<String, ArtifactDefinition> tempDeploymentArtifacts = new HashMap<>(deploymentArtifacts);
768 for (Entry<String, ArtifactDefinition> artifact : deploymentArtifacts.entrySet()) {
769 if (!artifact.getValue().checkEsIdExist()) {
770 tempDeploymentArtifacts.remove(artifact.getKey());
774 resourceInstance.setDeploymentArtifacts(tempDeploymentArtifacts);
777 return ActionStatus.OK;
780 public Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance componentInstance) {
781 return updateComponentInstanceMetadata(containerComponentParam, containerComponentId, componentInstanceId, userId, componentInstance, false, true);
784 public Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance componentInstance, boolean inTransaction,
787 validateUserExists(userId);
789 final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
791 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, null);
793 validateCanWorkOnComponent(containerComponent, userId);
794 ComponentTypeEnum instanceType = getComponentType(containerComponentType);
795 Either<Boolean, StorageOperationStatus> validateParentStatus = toscaOperationFacade.validateComponentExists(componentInstance.getComponentUid());
796 if (validateParentStatus.isRight()) {
797 log.debug("Failed to get component instance {} on service {}", componentInstanceId, containerComponentId);
798 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND, componentInstance.getName(), instanceType.getValue().toLowerCase());
800 if (!validateParentStatus.left().value()) {
801 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName(), instanceType.getValue().toLowerCase(), containerComponentType.getValue().toLowerCase(), containerComponentId);
805 lockComponent(containerComponent, "updateComponentInstance");
807 Component origComponent;
808 boolean failed = false;
810 origComponent = getOriginComponentFromComponentInstance(componentInstance);
811 componentInstance = updateComponentInstanceMetadata(containerComponent, containerComponentType, origComponent, componentInstanceId, componentInstance);
812 }catch (ComponentException e) {
817 unlockComponent(failed, containerComponent);
820 return Either.left(componentInstance);
823 // New Multiple Instance Update API
824 public List<ComponentInstance> updateComponentInstance(String containerComponentParam, Component containerComponent, String containerComponentId, String userId, List<ComponentInstance> componentInstanceList, boolean needLock) {
826 boolean failed = false;
828 validateUserExists(userId);
830 final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
831 ComponentParametersView componentFilter = new ComponentParametersView();
832 componentFilter.disableAll();
833 componentFilter.setIgnoreUsers(false);
834 componentFilter.setIgnoreComponentInstances(false);
835 if (containerComponent == null) {
836 containerComponent = validateComponentExistsByFilter(containerComponentId, containerComponentType, componentFilter);
838 validateCanWorkOnComponent(containerComponent, userId);
840 ComponentTypeEnum instanceType = getComponentType(containerComponentType);
842 for (ComponentInstance componentInstance : componentInstanceList) {
843 boolean validateParent = validateParent(containerComponent, componentInstance.getUniqueId());
844 if (!validateParent) {
845 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName(),
846 instanceType.getValue().toLowerCase(), containerComponentType.getValue().toLowerCase(),
847 containerComponentId);
852 lockComponent(containerComponent, "updateComponentInstance");
855 List<ComponentInstance> updatedList = new ArrayList<>();
856 List<ComponentInstance> instancesFromContainerComponent = containerComponent.getComponentInstances();
857 List<ComponentInstance> listForUpdate = new ArrayList<>();
858 if (instancesFromContainerComponent == null || instancesFromContainerComponent.isEmpty())
859 containerComponent.setComponentInstances(componentInstanceList);
861 Iterator<ComponentInstance> iterator = instancesFromContainerComponent.iterator();
862 while (iterator.hasNext()) {
863 ComponentInstance origInst = iterator.next();
864 Optional<ComponentInstance> op = componentInstanceList.stream().filter(ci -> ci.getUniqueId().equals(origInst.getUniqueId())).findAny();
865 if (op.isPresent()) {
866 ComponentInstance updatedCi = op.get();
867 updatedCi = buildComponentInstance(updatedCi, origInst);
869 Boolean isUniqueName = validateInstanceNameUniquenessUponUpdate(containerComponent, origInst, updatedCi.getName());
871 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the name of the component instance {} to {}. A component instance with the same name already exists. ", origInst.getName(), updatedCi.getName());
872 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(), origInst.getName()));
874 listForUpdate.add(updatedCi);
876 listForUpdate.add(origInst);
878 containerComponent.setComponentInstances(listForUpdate);
880 Either<Component, StorageOperationStatus> updateStatus = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, componentFilter);
881 if (updateStatus.isRight()) {
882 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update metadata belonging to container component {}. Status is {}. ", containerComponent.getName(), updateStatus.right().value());
883 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(updateStatus.right().value(), true), "", null));
886 for (ComponentInstance updatedInstance : updateStatus.left().value().getComponentInstances()) {
887 Optional<ComponentInstance> op = componentInstanceList.stream().filter(ci -> ci.getName().equals(updatedInstance.getName())).findAny();
888 if (op.isPresent()) {
889 updatedList.add(updatedInstance);
894 }catch (ComponentException e){
899 unlockComponent(failed, containerComponent);
904 private boolean validateParent(org.openecomp.sdc.be.model.Component containerComponent, String nodeTemplateId) {
905 return containerComponent.getComponentInstances().stream().anyMatch(p -> p.getUniqueId().equals(nodeTemplateId));
908 private ComponentTypeEnum getComponentType(ComponentTypeEnum containerComponentType) {
909 if (ComponentTypeEnum.PRODUCT == containerComponentType) {
910 return ComponentTypeEnum.SERVICE_INSTANCE;
912 return ComponentTypeEnum.RESOURCE_INSTANCE;
916 private ComponentInstance updateComponentInstanceMetadata(Component containerComponent, ComponentTypeEnum containerComponentType, org.openecomp.sdc.be.model.Component origComponent, String componentInstanceId,
917 ComponentInstance componentInstance) {
919 Optional<ComponentInstance> componentInstanceOptional;
920 Either<ImmutablePair<Component, String>, StorageOperationStatus> updateRes = null;
921 ComponentInstance oldComponentInstance = null;
922 boolean isNameChanged = false;
924 componentInstanceOptional = containerComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(componentInstance.getUniqueId())).findFirst();
925 if (!componentInstanceOptional.isPresent()) {
926 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find the component instance {} in container component {}. ", componentInstance.getName(), containerComponent.getName());
927 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName());
929 String oldComponentName;
930 oldComponentInstance = componentInstanceOptional.get();
931 oldComponentName = oldComponentInstance.getName();
932 String newInstanceName = componentInstance.getName();
933 if (oldComponentName != null && !oldComponentInstance.getName().equals(newInstanceName))
934 isNameChanged = true;
935 Boolean isUniqueName = validateInstanceNameUniquenessUponUpdate(containerComponent, oldComponentInstance, newInstanceName);
937 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update the name of the component instance {} to {}. A component instance with the same name already exists. ", oldComponentInstance.getName(), newInstanceName);
938 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(), componentInstance.getName());
940 if(!DirectivesUtils.isValid(componentInstance.getDirectives())) {
941 final String directivesStr =
942 componentInstance.getDirectives().stream().collect(Collectors.joining(" , ", " [ ", " ] "));
943 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
944 "Failed to update the directives of the component instance {} to {}. Directives data {} is invalid. ",
945 oldComponentInstance.getName(), newInstanceName ,
947 throw new ByActionStatusComponentException(ActionStatus.DIRECTIVES_INVALID_VALUE, containerComponentType.getValue(), componentInstance.getName()); }
948 updateRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, origComponent, updateComponentInstanceMetadata(oldComponentInstance, componentInstance));
949 if (updateRes.isRight()) {
950 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update metadata of component instance {} belonging to container component {}. Status is {}. ", componentInstance.getName(), containerComponent.getName(),
951 updateRes.right().value());
952 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(updateRes.right().value(), true), "", null));
954 // region - Update instance Groups
956 Either<StorageOperationStatus, StorageOperationStatus> result =
957 toscaOperationFacade.cleanAndAddGroupInstancesToComponentInstance(containerComponent, oldComponentInstance, componentInstanceId);
958 if (result.isRight())
959 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to rename group instances for container {}. error {} ", componentInstanceId, result.right().value());
961 if (containerComponent instanceof Service){
962 Either<ComponentInstance, ResponseFormat> renameEither =
963 renameServiceFilter((Service) containerComponent, newInstanceName,
964 oldComponentInstance.getName());
965 if (renameEither.isRight()) {
966 throw new ByResponseFormatComponentException(renameEither.right().value());
969 updateForwardingPathDefinition(containerComponent, componentInstance, oldComponentName);
974 String newInstanceId = updateRes.left().value().getRight();
975 Optional<ComponentInstance> updatedInstanceOptional = updateRes.left().value().getLeft().getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(newInstanceId)).findFirst();
977 if (!updatedInstanceOptional.isPresent()) {
978 log.debug("Failed to update metadata of component instance {} of container component {}", componentInstance.getName(), containerComponent.getName());
979 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName()));
982 return componentInstanceOptional.get();
985 private void updateForwardingPathDefinition(Component containerComponent, ComponentInstance componentInstance, String oldComponentName) {
986 Collection<ForwardingPathDataDefinition> forwardingPathDataDefinitions = getForwardingPathDataDefinitions(containerComponent.getUniqueId());
987 Set<ForwardingPathDataDefinition> updated = new ForwardingPathUtils()
988 .updateComponentInstanceName(forwardingPathDataDefinitions, oldComponentName,
989 componentInstance.getName());
990 updated.forEach(fp -> {
991 Either<ForwardingPathDataDefinition, StorageOperationStatus> resultEither = forwardingPathOperation
992 .updateForwardingPath(containerComponent.getUniqueId(), fp);
993 if (resultEither.isRight()){
994 CommonUtility.addRecordToLog(log, LogLevelEnum.ERROR, "Failed to rename forwarding path for container {}. error {} ",containerComponent.getName(), resultEither.right().value());
1000 public Either<ComponentInstance, ResponseFormat> renameServiceFilter(Service containerComponent,
1001 String newInstanceName, String oldInstanceName) {
1003 Map<String, CINodeFilterDataDefinition> renamedNodesFilter =
1004 ServiceFilterUtils.getRenamedNodesFilter((Service) containerComponent,
1005 oldInstanceName, newInstanceName);
1006 for( Entry<String, CINodeFilterDataDefinition> entry : renamedNodesFilter.entrySet()){
1007 Either<CINodeFilterDataDefinition, StorageOperationStatus>
1008 renameEither = serviceFilterOperation.updateNodeFilter(
1009 containerComponent.getUniqueId(),entry.getKey(),entry.getValue());
1010 if (renameEither.isRight()){
1011 return Either.right(componentsUtils.getResponseFormatForResourceInstance(
1012 componentsUtils.convertFromStorageResponse(renameEither.right().value(), ComponentTypeEnum.SERVICE),
1013 containerComponent.getName(), null));
1017 return Either.left(null);
1022 * The normalized old vf name
1023 * @param newNormailzedPrefix-
1024 * The normalized new vf name
1025 * @param qualifiedGroupInstanceName-
1026 * old Group Instance Name
1028 // modify group names
1029 private String getNewGroupName(String oldPrefix, String newNormailzedPrefix, String qualifiedGroupInstanceName) {
1030 if (qualifiedGroupInstanceName == null) {
1031 log.info("CANNOT change group name ");
1034 if (qualifiedGroupInstanceName.startsWith(oldPrefix) || qualifiedGroupInstanceName.startsWith(ValidationUtils.normalizeComponentInstanceName(oldPrefix)))
1035 return qualifiedGroupInstanceName.replaceFirst(oldPrefix, newNormailzedPrefix);
1036 return qualifiedGroupInstanceName;
1039 private ComponentInstance updateComponentInstanceMetadata(ComponentInstance oldComponentInstance, ComponentInstance newComponentInstance) {
1040 oldComponentInstance.setName(newComponentInstance.getName());
1041 oldComponentInstance.setModificationTime(System.currentTimeMillis());
1042 oldComponentInstance.setCustomizationUUID(UUID.randomUUID().toString());
1043 oldComponentInstance.setDirectives(newComponentInstance.getDirectives());
1044 if (oldComponentInstance.getGroupInstances() != null)
1045 oldComponentInstance.getGroupInstances().forEach(group -> group.setName(getNewGroupName(oldComponentInstance.getNormalizedName(), ValidationUtils.normalizeComponentInstanceName(newComponentInstance.getName()), group.getName())));
1046 return oldComponentInstance;
1049 public ComponentInstance deleteComponentInstance(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId) {
1051 validateUserExists(userId);
1053 final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
1055 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, null);
1056 validateCanWorkOnComponent(containerComponent, userId);
1058 boolean failed = false;
1059 ComponentInstance deletedRelatedInst;
1061 if (containerComponent instanceof Service) {
1062 ComponentInstance componentInstance = containerComponent.getComponentInstanceById(componentInstanceId).get();
1063 Either<String, StorageOperationStatus> deleteServiceFilterEither =
1064 serviceFilterOperation.deleteNodeFilter((Service) containerComponent, componentInstanceId);
1065 if (deleteServiceFilterEither.isRight()) {
1066 ActionStatus status = componentsUtils.convertFromStorageResponse(deleteServiceFilterEither.right().value(),
1067 containerComponentType);
1068 janusGraphDao.rollback();
1069 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(status, componentInstanceId));
1071 Either<ComponentInstance, ResponseFormat> resultOp = deleteServiceFiltersRelatedTobeDeletedComponentInstance((Service) containerComponent,
1072 componentInstance, ComponentTypeEnum.SERVICE, userId);
1073 if (resultOp.isRight()) {
1074 janusGraphDao.rollback();
1075 throw new ByResponseFormatComponentException(resultOp.right().value());
1078 lockComponent(containerComponent, "deleteComponentInstance");
1079 ComponentInstance deletedCompInstance = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentType);
1081 deletedRelatedInst = deleteForwardingPathsRelatedTobeDeletedComponentInstance(containerComponentId,
1082 containerComponentType, deletedCompInstance);
1083 ActionStatus onDeleteOperationsStatus = onChangeInstanceOperationOrchestrator.doOnDeleteInstanceOperations(containerComponent, componentInstanceId);
1084 if (ActionStatus.OK != onDeleteOperationsStatus) {
1085 throw new ByActionStatusComponentException(onDeleteOperationsStatus);
1087 } catch (ComponentException e) {
1092 unlockComponent(failed, containerComponent);
1094 return deletedRelatedInst;
1097 public Either<ComponentInstance, ResponseFormat> deleteServiceFiltersRelatedTobeDeletedComponentInstance(
1098 Service service, ComponentInstance componentInstance, ComponentTypeEnum containerComponentType, String userId) {
1099 if (containerComponentType.equals(ComponentTypeEnum.SERVICE)) {
1100 Set<String> serviceFiltersIDsToBeDeleted =
1101 getServiceFiltersRelatedToComponentInstance(service.getUniqueId(), componentInstance);
1102 if (!serviceFiltersIDsToBeDeleted.isEmpty()) {
1103 Set<String> ids = service.getComponentInstances().stream()
1104 .filter(ci -> serviceFiltersIDsToBeDeleted
1105 .contains(ci.getName()))
1106 .map(ComponentInstance::getUniqueId)
1107 .collect(Collectors.toSet());
1108 Either<Set<String>, StorageOperationStatus> deleteServiceFiltersEither =
1109 serviceFilterOperation.deleteNodeFilters(service, ids);
1110 if (deleteServiceFiltersEither.isRight()) {
1111 ActionStatus status = componentsUtils.convertFromStorageResponse(deleteServiceFiltersEither.right().value(),
1112 containerComponentType);
1113 return Either.right(componentsUtils.getResponseFormat(status, componentInstance.getName()));
1115 for (String id : ids) {
1116 final Optional<ComponentInstance> componentInstanceById = service.getComponentInstanceById(id);
1117 if (!componentInstanceById.isPresent()){
1118 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
1120 ComponentInstance ci = componentInstanceById.get();
1121 List<String> directives = ci.getDirectives();
1122 directives.remove(DirectivesUtils.SELECTABLE);
1123 ci.setDirectives(directives);
1124 final Either<ComponentInstance, ResponseFormat> componentInstanceResponseFormatEither =
1125 updateComponentInstanceMetadata(ComponentTypeEnum.SERVICE_PARAM_NAME, service.getUniqueId(),
1126 ci.getUniqueId(), userId, ci, true, false);
1127 if (componentInstanceResponseFormatEither.isRight()) {
1128 return componentInstanceResponseFormatEither;
1133 return Either.left(componentInstance);
1138 private Set<String> getServiceFiltersRelatedToComponentInstance(String containerComponentId,
1139 ComponentInstance componentInstance) {
1140 ComponentParametersView filter = new ComponentParametersView(true);
1141 filter.setIgnoreComponentInstances(false);
1142 Either<Service, StorageOperationStatus> serviceFilterOrigin =
1143 toscaOperationFacade.getToscaElement(containerComponentId, filter);
1144 final Service service = serviceFilterOrigin.left().value();
1145 final Set<String> nodesFiltersToBeDeleted = ServiceFilterUtils.getNodesFiltersToBeDeleted(service,
1147 return nodesFiltersToBeDeleted;
1151 ComponentInstance deleteForwardingPathsRelatedTobeDeletedComponentInstance(String containerComponentId,
1152 ComponentTypeEnum containerComponentType, ComponentInstance componentInstance) {
1153 if(containerComponentType == ComponentTypeEnum.SERVICE){
1154 List<String> pathIDsToBeDeleted = getForwardingPathsRelatedToComponentInstance(containerComponentId, componentInstance.getName());
1155 if (!pathIDsToBeDeleted.isEmpty()) {
1156 deleteForwardingPaths(containerComponentId, pathIDsToBeDeleted);
1159 return componentInstance;
1166 private void deleteForwardingPaths(String serviceId, List<String> pathIdsToDelete){
1168 Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(serviceId);
1169 if(storageStatus.isRight()) {
1170 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(storageStatus.right().value()));
1172 Either<Set<String>, StorageOperationStatus> result = forwardingPathOperation.deleteForwardingPath(storageStatus.left().value(),
1173 Sets.newHashSet(pathIdsToDelete));
1175 if(result.isRight()) {
1176 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(result.right().value()));
1180 private List<String> getForwardingPathsRelatedToComponentInstance(String containerComponentId, String componentInstanceId){
1181 Collection<ForwardingPathDataDefinition> allPaths = getForwardingPathDataDefinitions(containerComponentId);
1182 List<String> pathIDsToBeDeleted = new ArrayList<>();
1184 allPaths.stream().filter(path -> isPathRelatedToComponent(path,componentInstanceId ))
1185 .forEach(path -> pathIDsToBeDeleted.add(path.getUniqueId()));
1187 return pathIDsToBeDeleted;
1190 private Collection<ForwardingPathDataDefinition> getForwardingPathDataDefinitions(String containerComponentId) {
1191 ComponentParametersView filter = new ComponentParametersView(true);
1192 filter.setIgnoreForwardingPath(false);
1193 Either<Service, StorageOperationStatus> forwardingPathOrigin = toscaOperationFacade
1194 .getToscaElement(containerComponentId, filter);
1195 return forwardingPathOrigin.left().value().getForwardingPaths().values();
1198 private boolean isPathRelatedToComponent(ForwardingPathDataDefinition pathDataDefinition,
1199 String componentInstanceId){
1200 return pathDataDefinition.getPathElements().getListToscaDataDefinition()
1201 .stream().anyMatch(elementDataDefinition -> elementDataDefinition.getFromNode().equalsIgnoreCase(componentInstanceId) ||
1202 elementDataDefinition.getToNode()
1203 .equalsIgnoreCase(componentInstanceId));
1207 private ComponentInstance deleteComponentInstance(Component containerComponent, String componentInstanceId, ComponentTypeEnum containerComponentType) {
1208 Either<ImmutablePair<Component, String>, StorageOperationStatus> deleteRes = toscaOperationFacade.deleteComponentInstanceFromTopologyTemplate(containerComponent, componentInstanceId);
1209 if (deleteRes.isRight()) {
1210 log.debug("Failed to delete entry on graph for resourceInstance {}", componentInstanceId);
1211 ActionStatus status = componentsUtils.convertFromStorageResponse(deleteRes.right().value(), containerComponentType);
1212 throw new ByActionStatusComponentException(status, componentInstanceId);
1214 log.debug("The component instance {} has been removed from container component {}. ", componentInstanceId, containerComponent);
1215 ComponentInstance deletedInstance = findAndRemoveComponentInstanceFromContainerComponent(componentInstanceId, containerComponent);
1217 if (CollectionUtils.isNotEmpty(containerComponent.getInputs())) {
1218 List<InputDefinition> inputsToDelete = containerComponent.getInputs().stream().filter(i -> i.getInstanceUniqueId() != null && i.getInstanceUniqueId().equals(componentInstanceId)).collect(Collectors.toList());
1219 if (CollectionUtils.isNotEmpty(inputsToDelete)) {
1220 StorageOperationStatus deleteInputsRes = toscaOperationFacade.deleteComponentInstanceInputsFromTopologyTemplate(containerComponent, inputsToDelete);
1221 if (deleteInputsRes != StorageOperationStatus.OK) {
1222 log.debug("Failed to delete inputs of the component instance {} from container component. ", componentInstanceId);
1223 throw new ByActionStatusComponentException(
1224 componentsUtils.convertFromStorageResponse(deleteInputsRes, containerComponentType), componentInstanceId);
1228 return deletedInstance;
1231 private ComponentInstance findAndRemoveComponentInstanceFromContainerComponent(String componentInstanceId, Component containerComponent) {
1232 ComponentInstance foundInstance = null;
1233 for (ComponentInstance instance : containerComponent.getComponentInstances()) {
1234 if (instance.getUniqueId().equals(componentInstanceId)) {
1235 foundInstance = instance;
1236 containerComponent.getComponentInstances().remove(instance);
1240 findAndRemoveComponentInstanceRelations(componentInstanceId, containerComponent);
1241 return foundInstance;
1244 private void findAndRemoveComponentInstanceRelations(String componentInstanceId, Component containerComponent) {
1245 if(CollectionUtils.isNotEmpty(containerComponent.getComponentInstancesRelations())){
1246 containerComponent.setComponentInstancesRelations(containerComponent.getComponentInstancesRelations().stream().filter(r -> isNotBelongingRelation(componentInstanceId, r)).collect(Collectors.toList()));
1250 private boolean isNotBelongingRelation(String componentInstanceId, RequirementCapabilityRelDef relation) {
1251 return !relation.getToNode().equals(componentInstanceId) && !relation.getFromNode().equals(componentInstanceId);
1254 public RequirementCapabilityRelDef associateRIToRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum) {
1255 return associateRIToRI(componentId, userId, requirementDef, componentTypeEnum, false, true);
1258 public RequirementCapabilityRelDef associateRIToRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum, boolean inTransaction, boolean needLock) {
1260 validateUserExists(userId);
1262 RequirementCapabilityRelDef requirementCapabilityRelDef = null;
1264 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(componentId, componentTypeEnum, null);
1266 validateCanWorkOnComponent(containerComponent, userId);
1267 boolean failed = false;
1270 lockComponent(containerComponent, "associateRIToRI");
1272 requirementCapabilityRelDef = associateRIToRIOnGraph(containerComponent, requirementDef);
1273 }catch (ComponentException e){
1278 unlockComponent(failed, containerComponent);
1280 return requirementCapabilityRelDef;
1283 public RequirementCapabilityRelDef associateRIToRIOnGraph(Component containerComponent, RequirementCapabilityRelDef requirementDef) {
1285 log.debug(TRY_TO_CREATE_ENTRY_ON_GRAPH);
1287 Either<RequirementCapabilityRelDef, StorageOperationStatus> result = toscaOperationFacade.associateResourceInstances(null, containerComponent.getUniqueId(), requirementDef);
1289 if (result.isLeft()) {
1290 log.debug(ENTITY_ON_GRAPH_IS_CREATED);
1291 RequirementCapabilityRelDef requirementCapabilityRelDef = result.left().value();
1292 return requirementCapabilityRelDef;
1295 log.debug("Failed to associate node: {} with node {}", requirementDef.getFromNode(), requirementDef.getToNode());
1296 String fromNameOrId = "";
1297 String toNameOrId = "";
1298 Either<ComponentInstance, StorageOperationStatus> fromResult = getResourceInstanceById(containerComponent, requirementDef.getFromNode());
1299 Either<ComponentInstance, StorageOperationStatus> toResult = getResourceInstanceById(containerComponent, requirementDef.getToNode());
1301 toNameOrId = requirementDef.getFromNode();
1302 fromNameOrId = requirementDef.getFromNode();
1303 if (fromResult.isLeft()) {
1304 fromNameOrId = fromResult.left().value().getName();
1306 if (toResult.isLeft()) {
1307 toNameOrId = toResult.left().value().getName();
1310 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponseForResourceInstance
1311 (result.right().value(), true), fromNameOrId, toNameOrId,
1312 requirementDef.getRelationships().get(0).getRelation().getRequirement());
1318 * @param componentId
1320 * @param requirementDefList
1321 * @param componentTypeEnum
1324 public List<RequirementCapabilityRelDef> batchDissociateRIFromRI(
1327 List<RequirementCapabilityRelDef> requirementDefList,
1328 ComponentTypeEnum componentTypeEnum) {
1330 validateUserExists(userId);
1331 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(componentId, componentTypeEnum, null);
1332 validateCanWorkOnComponent(containerComponent, userId);
1333 boolean failed = false;
1334 List<RequirementCapabilityRelDef> delOkResult = new ArrayList<>();
1336 lockComponent(containerComponent, "associateRIToRI");
1337 for (RequirementCapabilityRelDef requirementDef : requirementDefList) {
1338 RequirementCapabilityRelDef requirementCapabilityRelDef = dissociateRIFromRI(
1339 componentId, userId, requirementDef, containerComponent.getComponentType());
1340 delOkResult.add(requirementCapabilityRelDef);
1342 }catch (ComponentException e){
1346 unlockComponent(failed, containerComponent);
1352 public RequirementCapabilityRelDef dissociateRIFromRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum) {
1353 validateUserExists(userId);
1355 Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null;
1356 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(componentId, componentTypeEnum, null);
1358 validateCanWorkOnComponent(containerComponent, userId);
1359 boolean failed = false;
1361 lockComponent(containerComponent, "associateRIToRI");
1362 log.debug(TRY_TO_CREATE_ENTRY_ON_GRAPH);
1363 Either<RequirementCapabilityRelDef, StorageOperationStatus> result = toscaOperationFacade.dissociateResourceInstances(componentId, requirementDef);
1364 if (result.isLeft()) {
1365 log.debug(ENTITY_ON_GRAPH_IS_CREATED);
1366 return result.left().value();
1369 log.debug("Failed to dissocaite node {} from node {}", requirementDef.getFromNode(), requirementDef.getToNode());
1370 String fromNameOrId = "";
1371 String toNameOrId = "";
1372 Either<ComponentInstance, StorageOperationStatus> fromResult = getResourceInstanceById(containerComponent, requirementDef.getFromNode());
1373 Either<ComponentInstance, StorageOperationStatus> toResult = getResourceInstanceById(containerComponent, requirementDef.getToNode());
1375 toNameOrId = requirementDef.getFromNode();
1376 fromNameOrId = requirementDef.getFromNode();
1377 if (fromResult.isLeft()) {
1378 fromNameOrId = fromResult.left().value().getName();
1380 if (toResult.isLeft()) {
1381 toNameOrId = toResult.left().value().getName();
1384 throw new ByActionStatusComponentException(
1385 componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true),
1386 fromNameOrId, toNameOrId, requirementDef.getRelationships().get(0).getRelation().getRequirement());
1388 }catch (ComponentException e){
1392 unlockComponent(failed, containerComponent);
1396 * Allows to get relation contained in specified component according to received Id
1397 * @param componentId
1400 * @param componentTypeEnum
1403 public Either<RequirementCapabilityRelDef, ResponseFormat> getRelationById(String componentId, String relationId, String userId, ComponentTypeEnum componentTypeEnum) {
1405 Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null;
1407 org.openecomp.sdc.be.model.Component containerComponent = null;
1408 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = null;
1409 RequirementCapabilityRelDef foundRelation = null;
1411 validateUserExists(userId);
1412 containerComponent = validateComponentExists(componentId, componentTypeEnum, null);
1413 List<RequirementCapabilityRelDef> requirementCapabilityRelations = containerComponent.getComponentInstancesRelations();
1414 foundRelation = findRelation(relationId, requirementCapabilityRelations);
1415 if(foundRelation == null){
1416 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RELATION_NOT_FOUND, relationId, componentId);
1417 log.debug("Relation with id {} was not found on the component", relationId, componentId);
1418 resultOp = Either.right(responseFormat);
1420 if(resultOp == null){
1421 resultOp = setRelatedCapability(foundRelation, containerComponent);
1423 if(resultOp.isLeft()){
1424 resultOp = setRelatedRequirement(foundRelation, containerComponent);
1426 } catch (Exception e) {
1427 log.error("The exception {} occured upon get relation {} of the component {} ", e, relationId, componentId);
1428 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
1433 private RequirementCapabilityRelDef findRelation(String relationId, List<RequirementCapabilityRelDef> requirementCapabilityRelations) {
1434 for(RequirementCapabilityRelDef relationship : requirementCapabilityRelations){
1435 if(relationship.getRelationships().stream().filter(r -> r.getRelation().getId().equals(relationId)).findFirst().isPresent()){
1436 return relationship;
1442 private Either<RequirementCapabilityRelDef, ResponseFormat> setRelatedRequirement(RequirementCapabilityRelDef foundRelation, Component containerComponent) {
1443 Either<RequirementCapabilityRelDef, ResponseFormat> result = null;
1444 RelationshipInfo relationshipInfo = foundRelation.resolveSingleRelationship().getRelation();
1445 String instanceId = foundRelation.getFromNode();
1446 Optional<RequirementDefinition> foundRequirement;
1447 Optional<ComponentInstance> instance = containerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst();
1448 if(!instance.isPresent()){
1449 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, instanceId, "instance", containerComponent.getComponentType().getValue(), containerComponent.getName());
1450 log.debug("Component instance with id {} was not found on the component", instanceId, containerComponent.getUniqueId());
1451 result = Either.right(responseFormat);
1454 for(List<RequirementDefinition> requirements : instance.get().getRequirements().values()){
1455 foundRequirement = requirements.stream().filter(r -> isBelongingCalcRequirement(relationshipInfo, r, containerComponent.getLifecycleState())).findFirst();
1456 if(foundRequirement.isPresent()){
1457 foundRelation.resolveSingleRelationship().setRequirement(foundRequirement.get());
1458 result = Either.left(foundRelation);
1463 Either<RequirementDataDefinition, StorageOperationStatus> getfulfilledRequirementRes = toscaOperationFacade.getFulfilledRequirementByRelation(containerComponent.getUniqueId(), instanceId, foundRelation, this::isBelongingFullRequirement);
1464 if(getfulfilledRequirementRes.isRight()){
1465 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.REQUIREMENT_OF_INSTANCE_NOT_FOUND_ON_CONTAINER, relationshipInfo.getRequirement(), instanceId, containerComponent.getUniqueId());
1466 log.debug("Requirement {} of instance {} was not found on the container {}. ", relationshipInfo.getCapability(), instanceId, containerComponent.getUniqueId());
1467 result = Either.right(responseFormat);
1469 foundRelation.resolveSingleRelationship().setRequirement(getfulfilledRequirementRes.left().value());
1473 result = Either.left(foundRelation);
1478 private boolean isBelongingFullRequirement(RelationshipInfo relationshipInfo, RequirementDataDefinition req) {
1479 return req.getName().equals(relationshipInfo.getRequirement()) &&
1480 req.getUniqueId().equals(relationshipInfo.getRequirementUid()) &&
1481 req.getOwnerId().equals(relationshipInfo.getRequirementOwnerId());
1484 private boolean isBelongingCalcRequirement(RelationshipInfo relationshipInfo, RequirementDataDefinition req, LifecycleStateEnum state) {
1485 return nameMatches(relationshipInfo.getRequirement(), req.getName(), req.getPreviousName(), state) &&
1486 req.getUniqueId().equals(relationshipInfo.getRequirementUid()) &&
1487 req.getOwnerId().equals(relationshipInfo.getRequirementOwnerId());
1490 private Either<RequirementCapabilityRelDef, ResponseFormat> setRelatedCapability(RequirementCapabilityRelDef foundRelation, Component containerComponent) {
1491 Either<RequirementCapabilityRelDef, ResponseFormat> result = null;
1492 RelationshipInfo relationshipInfo = foundRelation.resolveSingleRelationship().getRelation();
1493 String instanceId = foundRelation.getToNode();
1494 Optional<CapabilityDefinition> foundCapability;
1495 Optional<ComponentInstance> instance = containerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst();
1496 if(!instance.isPresent()){
1497 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, instanceId, "instance", containerComponent.getComponentType().getValue(), containerComponent.getName());
1498 log.debug("Component instance with id {} was not found on the component", instanceId, containerComponent.getUniqueId());
1499 result = Either.right(responseFormat);
1502 for(List<CapabilityDefinition> capabilities : instance.get().getCapabilities().values()){
1503 foundCapability = capabilities.stream().filter(c -> isBelongingCalcCapability(relationshipInfo, c, containerComponent.getLifecycleState())).findFirst();
1504 if(foundCapability.isPresent()){
1505 foundRelation.resolveSingleRelationship().setCapability(foundCapability.get());
1506 result = Either.left(foundRelation);
1511 Either<CapabilityDataDefinition, StorageOperationStatus> getfulfilledRequirementRes =
1512 toscaOperationFacade.getFulfilledCapabilityByRelation(containerComponent.getUniqueId(), instanceId, foundRelation, this::isBelongingFullCapability);
1513 if(getfulfilledRequirementRes.isRight()){
1514 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CAPABILITY_OF_INSTANCE_NOT_FOUND_ON_CONTAINER, relationshipInfo.getCapability(), instanceId, containerComponent.getUniqueId());
1515 log.debug("Capability {} of instance {} was not found on the container {}. ", relationshipInfo.getCapability(), instanceId, containerComponent.getUniqueId());
1516 result = Either.right(responseFormat);
1518 foundRelation.resolveSingleRelationship().setCapability(getfulfilledRequirementRes.left().value());
1522 result = Either.left(foundRelation);
1527 private boolean isBelongingFullCapability(RelationshipInfo relationshipInfo, CapabilityDataDefinition cap) {
1528 return cap.getName().equals(relationshipInfo.getCapability()) &&
1529 cap.getUniqueId().equals(relationshipInfo.getCapabilityUid()) &&
1530 cap.getOwnerId().equals(relationshipInfo.getCapabilityOwnerId());
1533 private boolean isBelongingCalcCapability(RelationshipInfo relationshipInfo, CapabilityDataDefinition cap, LifecycleStateEnum state) {
1534 return nameMatches(relationshipInfo.getCapability(), cap.getName(), cap.getPreviousName(), state) &&
1535 cap.getUniqueId().equals(relationshipInfo.getCapabilityUid()) &&
1536 cap.getOwnerId().equals(relationshipInfo.getCapabilityOwnerId());
1539 private boolean nameMatches(String nameFromRelationship, String currName, String previousName, LifecycleStateEnum state) {
1540 return state == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT ?
1541 currName.equals(nameFromRelationship):
1542 previousName!= null && previousName.equals(nameFromRelationship);
1545 private Either<ComponentInstanceProperty, ResponseFormat> updateAttributeValue(ComponentInstanceProperty attribute, String resourceInstanceId) {
1546 Either<ComponentInstanceProperty, StorageOperationStatus> eitherAttribute = componentInstanceOperation.updateAttributeValueInResourceInstance(attribute, resourceInstanceId, true);
1547 Either<ComponentInstanceProperty, ResponseFormat> result;
1548 if (eitherAttribute.isLeft()) {
1549 log.debug("Attribute value {} was updated on graph.", attribute.getValueUniqueUid());
1550 ComponentInstanceProperty instanceAttribute = eitherAttribute.left().value();
1552 result = Either.left(instanceAttribute);
1555 log.debug("Failed to update attribute value {} in resource instance {}", attribute, resourceInstanceId);
1557 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(eitherAttribute.right().value());
1559 result = Either.right(componentsUtils.getResponseFormat(actionStatus, ""));
1565 private Either<ComponentInstanceProperty, ResponseFormat> createAttributeValue(ComponentInstanceProperty attribute, String resourceInstanceId) {
1567 Either<ComponentInstanceProperty, ResponseFormat> result;
1569 Wrapper<Integer> indexCounterWrapper = new Wrapper<>();
1570 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
1571 validateIncrementCounter(resourceInstanceId, GraphPropertiesDictionary.ATTRIBUTE_COUNTER, indexCounterWrapper, errorWrapper);
1573 if (!errorWrapper.isEmpty()) {
1574 result = Either.right(errorWrapper.getInnerElement());
1576 Either<ComponentInstanceProperty, StorageOperationStatus> eitherAttribute = componentInstanceOperation.addAttributeValueToResourceInstance(attribute, resourceInstanceId, indexCounterWrapper.getInnerElement(), true);
1577 if (eitherAttribute.isLeft()) {
1578 log.debug("Attribute value was added to resource instance {}", resourceInstanceId);
1579 ComponentInstanceProperty instanceAttribute = eitherAttribute.left().value();
1580 result = Either.left(instanceAttribute);
1583 log.debug("Failed to add attribute value {} to resource instance {}", attribute, resourceInstanceId);
1585 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(eitherAttribute.right().value());
1586 result = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1594 * Create Or Updates Attribute Instance
1596 * @param componentTypeEnum
1597 * @param componentId
1598 * @param resourceInstanceId
1603 public Either<ComponentInstanceProperty, ResponseFormat> createOrUpdateAttributeValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceProperty attribute, String userId) {
1604 Either<ComponentInstanceProperty, ResponseFormat> result = null;
1605 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
1607 validateUserExists(userId);
1608 if (errorWrapper.isEmpty()) {
1609 validateComponentTypeEnum(componentTypeEnum, "CreateOrUpdateAttributeValue", errorWrapper);
1611 if (errorWrapper.isEmpty()) {
1612 validateCanWorkOnComponent(componentId, componentTypeEnum, userId, errorWrapper);
1614 if (errorWrapper.isEmpty()) {
1615 validateComponentLock(componentId, componentTypeEnum, errorWrapper);
1619 if (errorWrapper.isEmpty()) {
1620 final boolean isCreate = Objects.isNull(attribute.getValueUniqueUid());
1622 result = createAttributeValue(attribute, resourceInstanceId);
1624 result = updateAttributeValue(attribute, resourceInstanceId);
1627 result = Either.right(errorWrapper.getInnerElement());
1633 if (result == null || result.isRight()) {
1634 janusGraphDao.rollback();
1636 janusGraphDao.commit();
1639 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
1643 public Either<List<ComponentInstanceProperty>, ResponseFormat> createOrUpdatePropertiesValues(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, List<ComponentInstanceProperty> properties, String userId) {
1645 Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
1647 /*-------------------------------Validations---------------------------------*/
1648 validateUserExists(userId);
1650 if (componentTypeEnum == null) {
1651 BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertiesValues", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
1652 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
1655 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
1657 if (getResourceResult.isRight()) {
1658 log.debug(FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID, componentId);
1659 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getResourceResult.right().value(), componentTypeEnum);
1660 return Either.right(componentsUtils.getResponseFormat(actionStatus, componentId));
1662 Component containerComponent = getResourceResult.left().value();
1664 if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
1665 if (containerComponent.isArchived()) {
1666 log.info("Component is archived. Component id: {}", componentId);
1667 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_IS_ARCHIVED, containerComponent.getName()));
1669 log.info("Restricted operation for user: {} on service {}", userId, componentId);
1670 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1673 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId);
1674 if (resourceInstanceStatus.isRight()) {
1675 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER,
1676 resourceInstanceId, "resource instance", "service", componentId));
1678 ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
1681 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
1682 if (lockStatus != StorageOperationStatus.OK) {
1683 log.debug(FAILED_TO_LOCK_SERVICE, componentId);
1684 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
1686 List <ComponentInstanceProperty> updatedProperties = new ArrayList<>();
1688 for (ComponentInstanceProperty property: properties) {
1689 validateMandatoryFields(property);
1690 ComponentInstanceProperty componentInstanceProperty = validatePropertyExistsOnComponent(property, containerComponent, foundResourceInstance);
1691 String propertyParentUniqueId = property.getParentUniqueId();
1692 Either<String, ResponseFormat> updatedPropertyValue = updatePropertyObjectValue(property, false);
1693 if (updatedPropertyValue.isRight()) {
1694 log.error("Failed to update property object value of property: {}",
1696 throw new ByResponseFormatComponentException(updatedPropertyValue.right().value());
1698 Optional<CapabilityDefinition>
1699 capPropDefinition = getPropertyCapabilityOfChildInstance(propertyParentUniqueId, foundResourceInstance.getCapabilities());
1700 if(capPropDefinition.isPresent()) {
1701 updatedPropertyValue
1702 .bimap(updatedValue -> updateCapabilityPropFromUpdateInstProp(property, updatedValue,
1703 containerComponent, foundResourceInstance, capPropDefinition.get().getType(),
1704 capPropDefinition.get().getName()), Either::right);
1707 updatedPropertyValue.bimap(updatedValue -> updatePropertyOnContainerComponent(property, updatedValue,
1708 containerComponent, foundResourceInstance), Either::right);
1709 updatedProperties.add(componentInstanceProperty);
1713 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
1714 if (updateContainerRes.isRight()) {
1715 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
1716 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1719 resultOp = Either.left(updatedProperties);
1723 if (resultOp == null || resultOp.isRight()) {
1724 janusGraphDao.rollback();
1726 janusGraphDao.commit();
1729 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
1733 private void validateMandatoryFields(PropertyDataDefinition property) {
1734 if (StringUtils.isEmpty(property.getName())) {
1735 throw new ByActionStatusComponentException (ActionStatus.MISSING_PROPERTY_NAME);
1739 private ComponentInstanceProperty validatePropertyExistsOnComponent(ComponentInstanceProperty property, Component containerComponent, ComponentInstance foundResourceInstance) {
1740 List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties().get(foundResourceInstance.getUniqueId());
1741 Optional<ComponentInstanceProperty> instanceProperty = instanceProperties.stream().filter(p -> p.getName().equals(property.getName())).findAny();
1742 if (!instanceProperty.isPresent()) {
1743 throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND, property.getName());
1745 return instanceProperty.get();
1750 private ResponseFormat updateCapabilityPropertyOnContainerComponent(ComponentInstanceProperty property,
1751 String newValue, Component containerComponent, ComponentInstance foundResourceInstance,
1752 String capabilityType, String capabilityName) {
1753 String componentInstanceUniqueId = foundResourceInstance.getUniqueId();
1754 ResponseFormat actionStatus = updateCapPropOnContainerComponent(property, newValue, containerComponent,
1755 foundResourceInstance, capabilityType, capabilityName, componentInstanceUniqueId);
1756 if (actionStatus != null) {
1757 return actionStatus;
1760 return componentsUtils.getResponseFormat(ActionStatus.OK);
1763 private ResponseFormat updateCapabilityPropFromUpdateInstProp(ComponentInstanceProperty property,
1764 String newValue, Component containerComponent,
1765 ComponentInstance foundResourceInstance,
1766 String capabilityType, String capabilityName) {
1767 String componentInstanceUniqueId = foundResourceInstance.getUniqueId();
1768 Either<Component, StorageOperationStatus> getComponentRes =
1769 toscaOperationFacade.getToscaFullElement(foundResourceInstance.getComponentUid());
1770 if(getComponentRes.isRight()) {
1771 return componentsUtils.getResponseFormat(getComponentRes.right().value());
1774 if(!PropertiesUtils.isNodeServiceProxy(getComponentRes.left().value())) {
1775 propOwner = componentInstanceUniqueId;
1777 propOwner = foundResourceInstance.getSourceModelUid();
1780 ResponseFormat actionStatus = updateCapPropOnContainerComponent(property, newValue, containerComponent,
1781 foundResourceInstance, capabilityType, capabilityName, componentInstanceUniqueId);
1782 if (actionStatus != null) {
1783 return actionStatus;
1786 return componentsUtils.getResponseFormat(ActionStatus.OK);
1789 private ResponseFormat updateCapPropOnContainerComponent(ComponentInstanceProperty property, String newValue,
1790 Component containerComponent,
1791 ComponentInstance foundResourceInstance,
1792 String capabilityType, String capabilityName,
1793 String componentInstanceUniqueId) {
1794 Map<String, List<CapabilityDefinition>> capabilities =
1795 Optional.ofNullable(foundResourceInstance.getCapabilities()).orElse(Collections.emptyMap());
1796 List<CapabilityDefinition> capPerType =
1797 Optional.ofNullable(capabilities.get(capabilityType)).orElse(Collections.EMPTY_LIST);
1798 Optional<CapabilityDefinition> cap =
1799 capPerType.stream().filter(c -> c.getName().equals(capabilityName)).findAny();
1800 if (cap.isPresent()) {
1801 List<ComponentInstanceProperty> capProperties = cap.get().getProperties();
1802 if (capProperties != null) {
1803 Optional<ComponentInstanceProperty> instanceProperty =
1804 capProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
1805 StorageOperationStatus status;
1806 if (instanceProperty.isPresent()) {
1807 String capKey = ModelConverter.buildCapabilityPropertyKey(foundResourceInstance.getOriginType().isAtomicType(), capabilityType, capabilityName, componentInstanceUniqueId, cap.get());
1808 instanceProperty.get().setValue(newValue);
1809 List<String> path = new ArrayList<>();
1810 path.add(componentInstanceUniqueId);
1812 instanceProperty.get().setPath(path);
1813 status = toscaOperationFacade.updateComponentInstanceCapabiltyProperty(containerComponent,
1814 componentInstanceUniqueId, capKey, instanceProperty.get());
1815 if (status != StorageOperationStatus.OK) {
1816 ActionStatus actionStatus =
1817 componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
1818 return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
1821 foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
1828 private ResponseFormat updatePropertyOnContainerComponent(ComponentInstanceProperty instanceProperty, String newValue, Component containerComponent, ComponentInstance foundResourceInstance) {
1829 StorageOperationStatus status;
1830 instanceProperty.setValue(newValue);
1831 status = toscaOperationFacade.updateComponentInstanceProperty(containerComponent, foundResourceInstance.getUniqueId(), instanceProperty);
1832 if (status != StorageOperationStatus.OK) {
1833 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
1834 return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
1836 foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
1837 return componentsUtils.getResponseFormat(ActionStatus.OK);
1840 private <T extends PropertyDefinition> Either<String,ResponseFormat> validatePropertyObjectValue(T property, String newValue, boolean isInput) {
1841 Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypesEither = dataTypeCache.getAll();
1842 if (allDataTypesEither.isRight()) {
1843 JanusGraphOperationStatus status = allDataTypesEither.right().value();
1844 BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
1845 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status))));
1847 Map<String, DataTypeDefinition> allDataTypes = allDataTypesEither.left().value();
1848 String propertyType = property.getType();
1849 String innerType = getInnerType(property);
1851 // Specific Update Logic
1852 Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(property.getType(), newValue, true, innerType, allDataTypes);
1853 if (isValid.isRight()) {
1854 Boolean res = isValid.right().value();
1856 log.error("Invalid value {} of property {} ", newValue, property.getName());
1857 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1860 Object object = isValid.left().value();
1861 if (object != null) {
1862 newValue = object.toString();
1865 if (validateAndUpdateRules(property, isInput, allDataTypes, innerType, propertyType))
1866 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT))));
1867 return Either.left(newValue);
1870 private <T extends PropertyDefinition> boolean validateAndUpdateRules(T property, boolean isInput, Map<String, DataTypeDefinition> allDataTypes, String innerType, String propertyType) {
1872 ImmutablePair<String, Boolean> pair = propertyOperation.validateAndUpdateRules(propertyType, ((ComponentInstanceProperty) property).getRules(), innerType, allDataTypes, true);
1873 if (pair.getRight() != null && !pair.getRight()) {
1874 BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), property.getName(), propertyType);
1881 private <T extends PropertyDefinition> Either<String,ResponseFormat> updatePropertyObjectValue(T property, boolean isInput) {
1882 Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypesEither = dataTypeCache.getAll();
1883 if (allDataTypesEither.isRight()) {
1884 JanusGraphOperationStatus status = allDataTypesEither.right().value();
1885 BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
1886 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status))));
1888 Map<String, DataTypeDefinition> allDataTypes = allDataTypesEither.left().value();
1889 String innerType = null;
1890 String propertyType = property.getType();
1891 ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
1892 log.debug("The type of the property {} is {}", property.getUniqueId(), propertyType);
1894 if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
1895 SchemaDefinition def = property.getSchema();
1897 log.debug("Schema doesn't exists for property of type {}", type);
1898 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
1900 PropertyDataDefinition propDef = def.getProperty();
1901 if (propDef == null) {
1902 log.debug("Property in Schema Definition inside property of type {} doesn't exist", type);
1903 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
1905 innerType = propDef.getType();
1907 // Specific Update Logic
1908 Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, property.getValue(), true, innerType, allDataTypes);
1909 String newValue = property.getValue();
1910 if (isValid.isRight()) {
1911 Boolean res = isValid.right().value();
1913 log.debug("validate and update property value has failed with value: {}", property.getValue());
1914 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT)));
1917 Object object = isValid.left().value();
1918 if (object != null) {
1919 newValue = object.toString();
1923 ImmutablePair<String, Boolean> pair = propertyOperation.validateAndUpdateRules(propertyType, ((ComponentInstanceProperty) property).getRules(), innerType, allDataTypes, true);
1924 if (pair.getRight() != null && pair.getRight() == false) {
1925 BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), property.getName(), propertyType);
1926 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT))));
1929 return Either.left(newValue);
1932 private ResponseFormat updateInputOnContainerComponent(ComponentInstanceInput input, String newValue, Component containerComponent, ComponentInstance foundResourceInstance) {
1933 StorageOperationStatus status;
1934 input.setValue(newValue);
1935 status = toscaOperationFacade.updateComponentInstanceInput(containerComponent, foundResourceInstance.getUniqueId(), input);
1936 if (status != StorageOperationStatus.OK) {
1937 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
1938 return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
1940 foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
1941 return componentsUtils.getResponseFormat(ActionStatus.OK);
1944 public Either<List<ComponentInstanceInput>, ResponseFormat> createOrUpdateInstanceInputValues(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, List<ComponentInstanceInput> inputs, String userId) {
1946 Either<List<ComponentInstanceInput>, ResponseFormat> resultOp = null;
1948 validateUserExists(userId);
1950 if (componentTypeEnum == null) {
1951 BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_OR_UPDATE_PROPERTY_VALUE, INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
1952 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
1955 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
1957 if (getResourceResult.isRight()) {
1958 log.debug(FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID, componentId);
1959 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getResourceResult.right().value(), componentTypeEnum);
1960 return Either.right(componentsUtils.getResponseFormat(actionStatus, componentId));
1962 Component containerComponent = getResourceResult.left().value();
1964 if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
1965 if (containerComponent.isArchived()) {
1966 log.info("Component is archived. Component id: {}", componentId);
1967 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_IS_ARCHIVED, containerComponent.getName()));
1969 log.info("Restricted operation for user: {} on service {}", userId, componentId);
1970 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1973 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId);
1974 if (resourceInstanceStatus.isRight()) {
1975 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER,
1976 resourceInstanceId, "resource instance", "service", componentId));
1979 ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
1982 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
1983 if (lockStatus != StorageOperationStatus.OK) {
1984 log.debug(FAILED_TO_LOCK_SERVICE, componentId);
1985 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
1987 List <ComponentInstanceInput> updatedInputs = new ArrayList<>();
1989 for (ComponentInstanceInput input: inputs) {
1990 validateMandatoryFields(input);
1991 ComponentInstanceInput componentInstanceInput = validateInputExistsOnComponent(input, containerComponent, foundResourceInstance);
1992 Either<String, ResponseFormat> validatedInputValue = validatePropertyObjectValue(componentInstanceInput, input.getValue(), true);
1993 if (validatedInputValue.isRight()){
1994 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT, input.getName());
1996 updateInputOnContainerComponent(componentInstanceInput, validatedInputValue.left().value(), containerComponent, foundResourceInstance);
1997 updatedInputs.add(componentInstanceInput);
1999 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
2000 if (updateContainerRes.isRight()) {
2001 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
2002 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2005 resultOp = Either.left(updatedInputs);
2009 if (resultOp == null || resultOp.isRight()) {
2010 janusGraphDao.rollback();
2012 janusGraphDao.commit();
2015 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
2020 private ComponentInstanceInput validateInputExistsOnComponent(ComponentInstanceInput input, Component containerComponent, ComponentInstance foundResourceInstance) {
2021 List<ComponentInstanceInput> instanceProperties = containerComponent.getComponentInstancesInputs().get(foundResourceInstance.getUniqueId());
2022 Optional<ComponentInstanceInput> instanceInput = instanceProperties.stream().filter(p -> p.getName().equals(input.getName())).findAny();
2023 if (!instanceInput.isPresent()) {
2024 throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND, input.getName());
2026 return instanceInput.get();
2029 public Either<ComponentInstanceProperty, ResponseFormat> createOrUpdateGroupInstancePropertyValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, String groupInstanceId, ComponentInstanceProperty property, String userId) {
2031 Either<ComponentInstanceProperty, ResponseFormat> resultOp = null;
2033 validateUserExists(userId);
2035 if (componentTypeEnum == null) {
2036 BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_OR_UPDATE_PROPERTY_VALUE, INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
2037 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
2041 if (!ComponentValidationUtils.canWorkOnComponent(componentId, toscaOperationFacade, userId)) {
2042 log.info("Restricted operation for user: {} on service: {}", userId, componentId);
2043 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2047 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
2048 if (lockStatus != StorageOperationStatus.OK) {
2049 log.debug(FAILED_TO_LOCK_SERVICE, componentId);
2050 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
2054 String propertyValueUid = property.getValueUniqueUid();
2056 if (propertyValueUid == null) {
2058 Either<Integer, StorageOperationStatus> counterRes = groupInstanceOperation.increaseAndGetGroupInstancePropertyCounter(groupInstanceId);
2060 if (counterRes.isRight()) {
2061 log.debug("increaseAndGetResourcePropertyCounter failed resource instance: {} property: {}", resourceInstanceId, property);
2062 StorageOperationStatus status = counterRes.right().value();
2063 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
2064 resultOp = Either.right(componentsUtils.getResponseFormat(actionStatus));
2066 Integer index = counterRes.left().value();
2067 Either<ComponentInstanceProperty, StorageOperationStatus> result = groupInstanceOperation.addPropertyValueToGroupInstance(property, resourceInstanceId, index, true);
2069 if (result.isLeft()) {
2070 log.trace("Property value was added to resource instance {}", resourceInstanceId);
2071 ComponentInstanceProperty instanceProperty = result.left().value();
2073 resultOp = Either.left(instanceProperty);
2076 log.debug("Failed to add property value: {} to resource instance {}", property, resourceInstanceId);
2078 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
2080 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2084 Either<ComponentInstanceProperty, StorageOperationStatus> result = groupInstanceOperation.updatePropertyValueInGroupInstance(property, resourceInstanceId, true);
2086 if (result.isLeft()) {
2087 log.debug("Property value {} was updated on graph.", property.getValueUniqueUid());
2088 ComponentInstanceProperty instanceProperty = result.left().value();
2090 resultOp = Either.left(instanceProperty);
2093 log.debug("Failed to update property value: {}, in resource instance {}", property, resourceInstanceId);
2095 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
2097 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2100 if (resultOp.isLeft()) {
2101 StorageOperationStatus updateCustomizationUUID = componentInstanceOperation.updateCustomizationUUID(resourceInstanceId);
2102 if (updateCustomizationUUID != StorageOperationStatus.OK) {
2103 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateCustomizationUUID);
2105 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2112 if (resultOp == null || resultOp.isRight()) {
2113 janusGraphDao.rollback();
2115 janusGraphDao.commit();
2118 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
2123 public Either<ComponentInstanceProperty, ResponseFormat> deletePropertyValue(ComponentTypeEnum componentTypeEnum, String serviceId, String resourceInstanceId, String propertyValueId, String userId) {
2125 validateUserExists(userId);
2127 Either<ComponentInstanceProperty, ResponseFormat> resultOp = null;
2129 if (componentTypeEnum == null) {
2130 BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_OR_UPDATE_PROPERTY_VALUE, INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
2131 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
2135 if (!ComponentValidationUtils.canWorkOnComponent(serviceId, toscaOperationFacade, userId)) {
2136 log.info("Restricted operation for user {} on service {}", userId, serviceId);
2137 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2141 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(serviceId, componentTypeEnum.getNodeType());
2142 if (lockStatus != StorageOperationStatus.OK) {
2143 log.debug(FAILED_TO_LOCK_SERVICE, serviceId);
2144 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
2148 Either<ComponentInstanceProperty, StorageOperationStatus> result = propertyOperation.removePropertyValueFromResourceInstance(propertyValueId, resourceInstanceId, true);
2150 if (result.isLeft()) {
2151 log.debug("Property value {} was removed from graph.", propertyValueId);
2152 ComponentInstanceProperty instanceProperty = result.left().value();
2154 resultOp = Either.left(instanceProperty);
2158 log.debug("Failed to remove property value {} in resource instance {}", propertyValueId, resourceInstanceId);
2160 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
2162 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2168 if (resultOp == null || resultOp.isRight()) {
2169 janusGraphDao.rollback();
2171 janusGraphDao.commit();
2174 graphLockOperation.unlockComponent(serviceId, componentTypeEnum.getNodeType());
2179 private Component getAndValidateOriginComponentOfComponentInstance(Component containerComponent, ComponentInstance componentInstance) {
2181 ComponentTypeEnum componentType = getComponentTypeByParentComponentType(containerComponent.getComponentType());
2182 Component component;
2183 Either<Component, StorageOperationStatus> getComponentRes = toscaOperationFacade.getToscaFullElement(componentInstance.getComponentUid());
2184 if (getComponentRes.isRight()) {
2185 log.debug("Failed to get the component with id {} for component instance {} creation. ", componentInstance.getComponentUid(), componentInstance.getName());
2186 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentRes.right().value(), componentType);
2187 throw new ByActionStatusComponentException(actionStatus, Constants.EMPTY_STRING);
2189 component = getComponentRes.left().value();
2190 LifecycleStateEnum resourceCurrState = component.getLifecycleState();
2191 if (resourceCurrState == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) {
2192 ActionStatus actionStatus = ActionStatus.CONTAINER_CANNOT_CONTAIN_COMPONENT_IN_STATE;
2193 throw new ByActionStatusComponentException(actionStatus, containerComponent.getComponentType().toString(), resourceCurrState.toString());
2195 if (component.isArchived() == true){
2196 ActionStatus actionStatus = ActionStatus.COMPONENT_IS_ARCHIVED;
2197 throw new ByActionStatusComponentException(actionStatus, component.getName());
2202 public Either<Set<String>, ResponseFormat> forwardingPathOnVersionChange(String containerComponentParam,
2203 String containerComponentId,
2204 String componentInstanceId,
2205 ComponentInstance newComponentInstance) {
2206 Either<Set<String>, ResponseFormat> resultOp;
2207 final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
2208 ComponentParametersView componentParametersView = getComponentParametersViewForForwardingPath();
2211 Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, componentParametersView);
2213 //Fetch current component instance
2214 Either<ComponentInstance, StorageOperationStatus> eitherResourceInstance =
2215 getResourceInstanceById(containerComponent, componentInstanceId);
2216 if (eitherResourceInstance.isRight()) {
2217 resultOp = Either.right(componentsUtils.getResponseFormat(
2218 ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceId, containerComponentId));
2221 ComponentInstance currentResourceInstance = eitherResourceInstance.left().value();
2223 //Check whether new componentInstance exists
2224 String resourceId = newComponentInstance.getComponentUid();
2225 Either<Boolean, StorageOperationStatus> componentExistsRes = toscaOperationFacade.validateComponentExists(resourceId);
2226 if (componentExistsRes.isRight()) {
2227 log.debug("Failed to find resource {}", resourceId);
2228 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse
2229 (componentExistsRes.right().value()), resourceId));
2231 } else if (!componentExistsRes.left().value()) {
2232 log.debug("The resource {} not found ", resourceId);
2233 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId));
2237 //Fetch component using new component instance uid
2238 Component updatedContainerComponent=getOriginComponentFromComponentInstance(newComponentInstance);
2239 Set<String> toDeleteForwardingPaths = getForwardingPaths(containerComponent,
2240 currentResourceInstance, updatedContainerComponent);
2241 resultOp=Either.left(toDeleteForwardingPaths);
2246 private Set<String> getForwardingPaths(Component containerComponent, ComponentInstance currentResourceInstance,
2247 Component updatedContainerComponent) {
2248 DataForMergeHolder dataForMergeHolder=new DataForMergeHolder();
2249 dataForMergeHolder.setOrigComponentInstId(currentResourceInstance.getName());
2251 Service service = (Service) containerComponent;
2252 ForwardingPathUtils forwardingPathUtils = new ForwardingPathUtils();
2254 return forwardingPathUtils.
2255 getForwardingPathsToBeDeletedOnVersionChange(service,dataForMergeHolder,updatedContainerComponent);
2258 private ComponentParametersView getComponentParametersViewForForwardingPath() {
2259 ComponentParametersView componentParametersView = new ComponentParametersView();
2260 componentParametersView.setIgnoreCapabiltyProperties(false);
2261 componentParametersView.setIgnoreForwardingPath(false);
2262 return componentParametersView;
2265 public ComponentInstance changeComponentInstanceVersion(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance newComponentInstance) {
2267 User user = validateUserExists(userId);
2268 final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
2269 ComponentParametersView componentParametersView = new ComponentParametersView();
2270 componentParametersView.setIgnoreCapabiltyProperties(false);
2272 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, componentParametersView);
2274 validateCanWorkOnComponent(containerComponent, userId);
2276 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceId);
2277 if (resourceInstanceStatus.isRight()) {
2278 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceId, containerComponentId);
2281 ComponentInstance currentResourceInstance = resourceInstanceStatus.left().value();
2283 return changeInstanceVersion(containerComponent, currentResourceInstance, newComponentInstance, user, containerComponentType );
2286 public ComponentInstance changeInstanceVersion(org.openecomp.sdc.be.model.Component containerComponent, ComponentInstance currentResourceInstance,
2287 ComponentInstance newComponentInstance, User user, final ComponentTypeEnum containerComponentType ) {
2288 boolean failed = false;
2289 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus;
2292 lockComponent(containerComponent, "changeComponentInstanceVersion");
2293 String containerComponentId = containerComponent.getUniqueId();
2294 String componentInstanceId = currentResourceInstance.getUniqueId();
2295 if (currentResourceInstance.getComponentUid().equals(newComponentInstance.getComponentUid())) {
2296 return currentResourceInstance;
2298 String resourceId = newComponentInstance.getComponentUid();
2300 Either<Boolean, StorageOperationStatus> componentExistsRes = toscaOperationFacade.validateComponentExists(resourceId);
2301 if (componentExistsRes.isRight()) {
2302 log.debug("Failed to validate existing of the component {}. Status is {} ", resourceId, componentExistsRes.right().value());
2303 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(componentExistsRes.right().value()), resourceId);
2304 } else if (!componentExistsRes.left().value()) {
2305 log.debug("The resource {} not found ", resourceId);
2306 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_NOT_FOUND, resourceId);
2309 Component eitherOriginComponent = getInstanceOriginNode(currentResourceInstance);
2311 DataForMergeHolder dataHolder = compInstMergeDataBL.saveAllDataBeforeDeleting(containerComponent, currentResourceInstance, eitherOriginComponent);
2312 ComponentInstance resResourceInfo = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentType);
2313 Component origComponent = null;
2314 OriginTypeEnum originType = currentResourceInstance.getOriginType();
2315 if (originType == OriginTypeEnum.ServiceProxy) {
2316 Either<Component, StorageOperationStatus> serviceProxyOrigin = toscaOperationFacade.getLatestByName("serviceProxy");
2317 if (isServiceProxyOrigin(serviceProxyOrigin))
2318 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(serviceProxyOrigin.right().value()));
2319 origComponent = serviceProxyOrigin.left().value();
2321 StorageOperationStatus fillProxyRes = fillProxyInstanceData(newComponentInstance, origComponent);
2323 if (isFillProxyRes(fillProxyRes))
2324 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(fillProxyRes));
2325 newComponentInstance.setOriginType(originType);
2327 origComponent = getOriginComponentFromComponentInstance(newComponentInstance);
2328 newComponentInstance.setName(resResourceInfo.getName());
2331 newComponentInstance.setInvariantName(resResourceInfo.getInvariantName());
2332 newComponentInstance.setPosX(resResourceInfo.getPosX());
2333 newComponentInstance.setPosY(resResourceInfo.getPosY());
2334 newComponentInstance.setDescription(resResourceInfo.getDescription());
2336 ComponentInstance updatedComponentInstance = createComponentInstanceOnGraph(containerComponent, origComponent, newComponentInstance, user);
2337 dataHolder.setCurrInstanceNode(origComponent);
2338 Component mergeStatusEither = compInstMergeDataBL.mergeComponentUserOrigData(user, dataHolder, containerComponent, containerComponentId, newComponentInstance.getUniqueId());
2340 ActionStatus postChangeVersionResult = onChangeInstanceOperationOrchestrator.doPostChangeVersionOperations(containerComponent, currentResourceInstance, newComponentInstance);
2341 if (postChangeVersionResult != ActionStatus.OK) {
2342 throw new ByActionStatusComponentException(postChangeVersionResult);
2345 ComponentParametersView filter = new ComponentParametersView(true);
2346 filter.setIgnoreComponentInstances(false);
2347 Either<Component, StorageOperationStatus> updatedComponentRes = toscaOperationFacade.getToscaElement(containerComponentId, filter);
2348 if (updatedComponentRes.isRight()) {
2349 StorageOperationStatus storageOperationStatus = updatedComponentRes.right().value();
2350 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(storageOperationStatus, containerComponent.getComponentType());
2351 log.debug("Component with id {} was not found", containerComponentId);
2352 throw new ByActionStatusComponentException(actionStatus, Constants.EMPTY_STRING);
2354 resourceInstanceStatus = getResourceInstanceById(updatedComponentRes.left().value(), updatedComponentInstance.getUniqueId());
2355 if (resourceInstanceStatus.isRight()) {
2356 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse
2357 (resourceInstanceStatus.right().value()), updatedComponentInstance.getUniqueId());
2359 return resourceInstanceStatus.left().value();
2361 }catch (ComponentException e){
2365 unlockComponent(failed, containerComponent);
2369 private boolean isFillProxyRes(StorageOperationStatus fillProxyRes) {
2370 if (fillProxyRes != StorageOperationStatus.OK) {
2371 log.debug("Failed to fill service proxy resource data with data from service, error {}", fillProxyRes);
2378 public List<ComponentInstanceProperty> getComponentInstancePropertiesById(String containerComponentTypeParam, String containerComponentId, String componentInstanceUniqueId, String userId) {
2379 Component containerComponent = null;
2381 boolean failed = false;
2383 validateUserExists(userId);
2384 validateComponentType(containerComponentTypeParam);
2386 Either<Component, StorageOperationStatus> validateContainerComponentExists = toscaOperationFacade.getToscaElement(containerComponentId);
2387 if (validateContainerComponentExists.isRight()) {
2388 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(validateContainerComponentExists.right().value()));
2390 containerComponent = validateContainerComponentExists.left().value();
2392 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId);
2393 if (resourceInstanceStatus.isRight()) {
2394 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId);
2397 List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties().get(componentInstanceUniqueId);
2398 if (CollectionUtils.isEmpty(instanceProperties)) {
2399 instanceProperties = new ArrayList<>();
2401 return instanceProperties;
2402 }catch (ComponentException e){
2406 unlockComponent(failed, containerComponent);
2410 protected void validateIncrementCounter(String resourceInstanceId, GraphPropertiesDictionary counterType, Wrapper<Integer> instaceCounterWrapper, Wrapper<ResponseFormat> errorWrapper) {
2411 Either<Integer, StorageOperationStatus> counterRes = componentInstanceOperation.increaseAndGetResourceInstanceSpecificCounter(resourceInstanceId, counterType, true);
2413 if (counterRes.isRight()) {
2414 log.debug("increase And Get {} failed resource instance {}", counterType, resourceInstanceId);
2415 StorageOperationStatus status = counterRes.right().value();
2416 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
2417 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus));
2419 instaceCounterWrapper.setInnerElement(counterRes.left().value());
2425 * updates componentInstance modificationTime
2427 * @param componentInstance
2428 * @param componentInstanceType
2429 * @param modificationTime
2430 * @param inTransaction
2433 public Either<ComponentInstanceData, ResponseFormat> updateComponentInstanceModificationTimeAndCustomizationUuid(ComponentInstance componentInstance, NodeTypeEnum componentInstanceType, Long modificationTime, boolean inTransaction) {
2434 Either<ComponentInstanceData, ResponseFormat> result;
2435 Either<ComponentInstanceData, StorageOperationStatus> updateComponentInstanceRes = componentInstanceOperation.updateComponentInstanceModificationTimeAndCustomizationUuidOnGraph(componentInstance, componentInstanceType, modificationTime,
2437 if (updateComponentInstanceRes.isRight()) {
2438 log.debug("Failed to update component instance {} with new last update date and mofifier. Status is {}. ", componentInstance.getName(), updateComponentInstanceRes.right().value());
2439 result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateComponentInstanceRes.right().value())));
2441 result = Either.left(updateComponentInstanceRes.left().value());
2446 public Either<ComponentInstance, ResponseFormat> deleteServiceProxy() {
2447 // TODO Add implementation
2448 return Either.left(new ComponentInstance());
2451 public Either<ComponentInstance, ResponseFormat> createServiceProxy() {
2452 // TODO Add implementation
2453 return Either.left(new ComponentInstance());
2456 public Either<ComponentInstance, ResponseFormat> changeServiceProxyVersion() {
2457 // TODO Add implementation
2458 return Either.left(new ComponentInstance());
2461 private Boolean validateInstanceNameUniquenessUponUpdate(Component containerComponent, ComponentInstance oldComponentInstance, String newInstanceName) {
2462 return ComponentValidations.validateNameIsUniqueInComponent(oldComponentInstance.getName(), newInstanceName, containerComponent);
2465 private Either<ComponentInstance, StorageOperationStatus> getResourceInstanceById(Component containerComponent, String instanceId) {
2467 Either<ComponentInstance, StorageOperationStatus> result = null;
2468 List<ComponentInstance> instances = containerComponent.getComponentInstances();
2469 Optional<ComponentInstance> foundInstance = null;
2470 if (CollectionUtils.isEmpty(instances)) {
2471 result = Either.right(StorageOperationStatus.NOT_FOUND);
2473 if (result == null) {
2474 foundInstance = instances.stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst();
2475 if (!foundInstance.isPresent()) {
2476 result = Either.right(StorageOperationStatus.NOT_FOUND);
2479 if (result == null) {
2480 result = Either.left(foundInstance.get());
2485 private ComponentInstance buildComponentInstance(ComponentInstance resourceInstanceForUpdate, ComponentInstance origInstanceForUpdate) {
2487 Long creationDate = origInstanceForUpdate.getCreationTime();
2489 Long modificationTime = System.currentTimeMillis();
2490 resourceInstanceForUpdate.setCreationTime(creationDate);
2491 resourceInstanceForUpdate.setModificationTime(modificationTime);
2493 resourceInstanceForUpdate.setCustomizationUUID(origInstanceForUpdate.getCustomizationUUID());
2495 if (StringUtils.isEmpty(resourceInstanceForUpdate.getName()) && StringUtils.isNotEmpty(origInstanceForUpdate.getName())) {
2496 resourceInstanceForUpdate.setName(origInstanceForUpdate.getName());
2499 resourceInstanceForUpdate.setNormalizedName(ValidationUtils.normalizeComponentInstanceName(resourceInstanceForUpdate.getName()));
2501 if (StringUtils.isEmpty(resourceInstanceForUpdate.getIcon()))
2502 resourceInstanceForUpdate.setIcon(origInstanceForUpdate.getIcon());
2504 if (StringUtils.isEmpty(resourceInstanceForUpdate.getComponentVersion()))
2505 resourceInstanceForUpdate.setComponentVersion(origInstanceForUpdate.getComponentVersion());
2507 if (StringUtils.isEmpty(resourceInstanceForUpdate.getComponentName()))
2508 resourceInstanceForUpdate.setComponentName(origInstanceForUpdate.getComponentName());
2510 if (StringUtils.isEmpty(resourceInstanceForUpdate.getToscaComponentName()))
2511 resourceInstanceForUpdate.setToscaComponentName(origInstanceForUpdate.getToscaComponentName());
2513 if (resourceInstanceForUpdate.getOriginType() == null) {
2514 resourceInstanceForUpdate.setOriginType(origInstanceForUpdate.getOriginType());
2516 if(resourceInstanceForUpdate.getOriginType() == OriginTypeEnum.ServiceProxy)
2517 resourceInstanceForUpdate.setIsProxy(true);
2518 if (resourceInstanceForUpdate.getSourceModelInvariant() == null) {
2519 resourceInstanceForUpdate.setSourceModelInvariant(origInstanceForUpdate.getSourceModelInvariant());
2521 if (resourceInstanceForUpdate.getSourceModelName() == null) {
2522 resourceInstanceForUpdate.setSourceModelName(origInstanceForUpdate.getSourceModelName());
2524 if (resourceInstanceForUpdate.getSourceModelUuid() == null) {
2525 resourceInstanceForUpdate.setSourceModelUuid(origInstanceForUpdate.getSourceModelUuid());
2527 if (resourceInstanceForUpdate.getSourceModelUid() == null) {
2528 resourceInstanceForUpdate.setSourceModelUid(origInstanceForUpdate.getSourceModelUid());
2530 if (resourceInstanceForUpdate.getCreatedFrom() == null) {
2531 resourceInstanceForUpdate.setCreatedFrom(origInstanceForUpdate.getCreatedFrom());
2533 return resourceInstanceForUpdate;
2536 * Returns list of ComponentInstanceProperty belonging to component instance capability specified by name, type and ownerId
2537 * @param containerComponentType
2538 * @param containerComponentId
2539 * @param componentInstanceUniqueId
2540 * @param capabilityType
2541 * @param capabilityName
2546 public List<ComponentInstanceProperty> getComponentInstanceCapabilityPropertiesById(String containerComponentType, String containerComponentId, String componentInstanceUniqueId, String capabilityType, String capabilityName, String ownerId, String userId) {
2548 Component containerComponent = null;
2550 List<ComponentInstanceProperty> resultOp = null;
2552 validateUserExists(userId);
2553 validateComponentType(containerComponentType);
2554 containerComponent = toscaOperationFacade.getToscaFullElement(containerComponentId).left().on(this::componentException);
2555 ComponentInstance resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId).left().on(this::componentInstanceException);
2556 resultOp = findCapabilityOfInstance(containerComponentId, componentInstanceUniqueId, capabilityType, capabilityName, ownerId, resourceInstanceStatus.getCapabilities());
2557 } catch(StorageException e){
2558 unlockRollbackWithException(containerComponent, e);
2559 } catch (ComponentException e) {
2560 unlockRollbackWithException(containerComponent, e);
2561 } catch (Exception e){
2562 unlockRollbackWithException(containerComponent, new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR));
2564 unlockWithCommit(containerComponent);
2568 private List<ComponentInstanceProperty> findCapabilityOfInstance( String componentId, String instanceId, String capabilityType, String capabilityName, String ownerId, Map<String, List<CapabilityDefinition>> instanceCapabilities) {
2569 CapabilityDefinition foundCapability;
2570 if (MapUtils.isNotEmpty(instanceCapabilities)) {
2571 List<CapabilityDefinition> capabilitiesPerType = instanceCapabilities.get(capabilityType);
2572 if (capabilitiesPerType != null) {
2573 Optional<CapabilityDefinition> capabilityOpt = capabilitiesPerType.stream().filter(c -> c.getName().equals(capabilityName) && c.getOwnerId().equals(ownerId)).findFirst();
2574 if (capabilityOpt.isPresent()) {
2575 foundCapability = capabilityOpt.get();
2576 return foundCapability.getProperties() == null ? new ArrayList<>() : foundCapability.getProperties();
2580 return fetchComponentInstanceCapabilityProperties(componentId, instanceId, capabilityType, capabilityName, ownerId);
2583 private List<ComponentInstanceProperty> fetchComponentInstanceCapabilityProperties(String componentId, String instanceId, String capabilityType, String capabilityName, String ownerId) {
2585 return toscaOperationFacade.getComponentInstanceCapabilityProperties(componentId, instanceId, capabilityName, capabilityType, ownerId)
2587 .on(this::componentInstancePropertyListException);
2588 } catch(Exception e){
2589 log.debug("The exception {} occurred upon the component {} instance {} capability {} properties retrieving. ", componentId, instanceId, capabilityName, e);
2590 throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
2594 /*private ResponseFormat updateCapabilityPropertyOnContainerComponent(ComponentInstanceProperty property, String newValue, Component containerComponent, ComponentInstance foundResourceInstance,
2595 String capabilityType, String capabilityName, String ownerId) {
2596 String componentInstanceUniqueId = foundResourceInstance.getUniqueId();
2597 Map<String, List<CapabilityDefinition>> capabilities = Optional.ofNullable(foundResourceInstance.getCapabilities())
2598 .orElse(Collections.emptyMap());
2599 List<CapabilityDefinition> capPerType = Optional.ofNullable(capabilities.get(capabilityType)).orElse(Collections.emptyList());
2600 Optional<CapabilityDefinition> cap = capPerType.stream().filter(c -> c.getName().equals(capabilityName) && c.getOwnerId().equals(ownerId)).findAny();
2601 if (cap.isPresent()) {
2602 List<ComponentInstanceProperty> capProperties = cap.get().getProperties();
2603 if (capProperties != null) {
2604 Optional<ComponentInstanceProperty> instanceProperty = capProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
2605 StorageOperationStatus status;
2606 if (instanceProperty.isPresent()) {
2607 String capKey = ModelConverter.buildCapabilityPropertyKey(foundResourceInstance.getOriginType().isAtomicType(), capabilityType, capabilityName, componentInstanceUniqueId, cap.get());
2608 instanceProperty.get().setValue(newValue);
2609 List<String> path = new ArrayList<>();
2610 path.add(componentInstanceUniqueId);
2612 instanceProperty.get().setPath(path);
2613 status = toscaOperationFacade.updateComponentInstanceCapabiltyProperty(containerComponent, componentInstanceUniqueId, capKey, instanceProperty.get());
2614 if (status != StorageOperationStatus.OK) {
2615 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
2616 return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
2619 foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
2623 return componentsUtils.getResponseFormat(ActionStatus.OK);
2626 /*public Either<List<ComponentInstanceProperty>, ResponseFormat> updateInstanceCapabilityProperties(ComponentTypeEnum componentTypeEnum, String containerComponentId, String componentInstanceUniqueId, String capabilityType, String capabilityName, String ownerId,
2627 List<ComponentInstanceProperty> properties, String userId) {
2628 Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
2630 validateUserExists(userId);
2632 if (componentTypeEnum == null) {
2633 BeEcompErrorManager.getInstance().logInvalidInputError("updateInstanceCapabilityProperty", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
2634 return Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
2636 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaFullElement(containerComponentId);
2638 if (getResourceResult.isRight()) {
2639 log.debug(FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID, containerComponentId);
2640 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2642 Component containerComponent = getResourceResult.left().value();
2644 if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
2645 log.info("Restricted operation for user: {} on component {}", userId, containerComponentId);
2646 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2648 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId);
2649 if (resourceInstanceStatus.isRight()) {
2650 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
2652 ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
2654 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(containerComponentId, componentTypeEnum.getNodeType());
2655 if (lockStatus != StorageOperationStatus.OK) {
2656 log.debug("Failed to lock component {}", containerComponentId);
2657 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
2660 Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypes = dataTypeCache.getAll();
2661 if (allDataTypes.isRight()) {
2662 JanusGraphOperationStatus status = allDataTypes.right().value();
2663 BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
2664 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status))));
2668 for (ComponentInstanceProperty property : properties) {
2669 Either<String, ResponseFormat> newPropertyValueEither = validatePropertyObjectValue(property, false);
2670 newPropertyValueEither.bimap(updatedValue ->
2671 updateCapabilityPropertyOnContainerComponent(property,updatedValue, containerComponent, foundResourceInstance, capabilityType, capabilityName, ownerId),
2674 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
2676 if (updateContainerRes.isRight()) {
2677 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
2678 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2681 resultOp = Either.left(properties);
2685 if (resultOp == null || resultOp.isRight()) {
2686 janusGraphDao.rollback();
2688 janusGraphDao.commit();
2691 graphLockOperation.unlockComponent(containerComponentId, componentTypeEnum.getNodeType());
2695 public Either<List<ComponentInstanceProperty>, ResponseFormat> updateInstanceCapabilityProperties(ComponentTypeEnum componentTypeEnum, String containerComponentId, String componentInstanceUniqueId, String capabilityType, String capabilityName,
2696 List<ComponentInstanceProperty> properties, String userId) {
2697 Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
2699 validateUserExists(userId);
2700 if (componentTypeEnum == null) {
2701 BeEcompErrorManager.getInstance().logInvalidInputError("updateInstanceCapabilityProperty", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
2702 return Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
2704 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaFullElement(containerComponentId);
2706 if (getResourceResult.isRight()) {
2707 log.debug(FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID, containerComponentId);
2708 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2710 Component containerComponent = getResourceResult.left().value();
2712 if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
2713 log.info("Restricted operation for user: {} on component {}", userId, containerComponentId);
2714 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2716 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId);
2717 if (resourceInstanceStatus.isRight()) {
2718 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
2720 ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
2722 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(containerComponentId, componentTypeEnum.getNodeType());
2723 if (lockStatus != StorageOperationStatus.OK) {
2724 log.debug("Failed to lock component {}", containerComponentId);
2725 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
2729 for (ComponentInstanceProperty property : properties) {
2730 Either<String, ResponseFormat> newPropertyValueEither = validatePropertyObjectValue(property, property.getValue(), false);
2731 newPropertyValueEither.bimap(updatedValue ->
2732 updateCapabilityPropertyOnContainerComponent(property,updatedValue, containerComponent, foundResourceInstance, capabilityType, capabilityName),
2735 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
2737 if (updateContainerRes.isRight()) {
2738 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
2739 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2742 resultOp = Either.left(properties);
2746 if (resultOp == null || resultOp.isRight()) {
2747 janusGraphDao.rollback();
2749 janusGraphDao.commit();
2752 graphLockOperation.unlockComponent(containerComponentId, componentTypeEnum.getNodeType());
2756 public Either<Map<String, ComponentInstance>, ResponseFormat> copyComponentInstance(ComponentInstance inputComponentInstance,
2757 String containerComponentId,
2758 String componentInstanceId,
2761 Map<String, ComponentInstance> resultMap = new HashMap<>();
2762 Either<Component, StorageOperationStatus> getOrigComponent = toscaOperationFacade.getToscaElement(containerComponentId);
2763 if (getOrigComponent.isRight()) {
2764 log.error("Failed to get the original component information");
2765 return Either.right(componentsUtils.getResponseFormat(
2766 ActionStatus.USER_DEFINED, FAILED_TO_COPY_COMP_INSTANCE_TO_CANVAS));
2769 Component origComponent = getOrigComponent.left().value();
2772 lockComponent(origComponent, "copyComponentInstance");
2774 } catch (ComponentException e) {
2775 log.error("destComponentInstance's data is {}", origComponent.toString());
2776 return Either.right(componentsUtils.getResponseFormat(
2777 ActionStatus.USER_DEFINED, "Failed to lock component destComponentInstance's data is {}", origComponent.toString()));
2780 boolean failed = false;
2781 ComponentInstance actionResponse = null;
2784 actionResponse = createComponentInstance(
2785 "services", containerComponentId, userId, inputComponentInstance, true, false);
2787 } catch (ComponentException e) {
2792 // on failure of the create instance unlock the resource and rollback the transaction.
2793 if (null == actionResponse || failed) {
2794 janusGraphDao.rollback();
2795 log.error("Failed to copy the component instance to the canvas");
2797 unlockComponent(failed, origComponent);
2799 return Either.right(componentsUtils.getResponseFormat(
2800 ActionStatus.USER_DEFINED, "Failed to copy the component instance to the canvas"));
2804 Either<String, ResponseFormat> resultOp = null;
2807 ComponentInstance destComponentInstance = actionResponse;
2808 log.debug("destComponentInstance's data is {}", destComponentInstance.toString());
2811 resultOp = deepCopyComponentInstance(
2812 origComponent, containerComponentId, componentInstanceId, destComponentInstance, userId);
2814 resultMap.put("componentInstance", destComponentInstance);
2818 if (resultOp == null || resultOp.isRight()) {
2819 unlockComponent(true, origComponent);
2820 janusGraphDao.rollback();
2821 log.error("Failed to deep copy component instance");
2822 return Either.right(componentsUtils.getResponseFormat(
2823 ActionStatus.USER_DEFINED, "Failed to deep copy the component instance to the canvas"));
2825 unlockComponent(false, origComponent);
2826 janusGraphDao.commit();
2827 log.debug("Success trasaction commit");
2831 return Either.left(resultMap);
2834 private Either<String, ResponseFormat> deepCopyComponentInstance(
2835 Component sourceComponent, String containerComponentId, String sourceComponentInstanceId,
2836 ComponentInstance destComponentInstance, String userId) {
2838 Either<Component, StorageOperationStatus> getDestComponent = toscaOperationFacade.getToscaElement(containerComponentId);
2839 if (getDestComponent.isRight()) {
2840 log.error("Failed to get the dest component information");
2841 return Either.right(componentsUtils.getResponseFormat(
2842 ActionStatus.USER_DEFINED, "Failed to copy the component instance to the canvas"));
2845 Component destComponent = getDestComponent.left().value();
2847 Either<String, ResponseFormat> copyComponentInstanceWithPropertiesAndInputs = copyComponentInstanceWithPropertiesAndInputs(
2848 sourceComponent, destComponent, sourceComponentInstanceId, destComponentInstance, userId);
2849 if (copyComponentInstanceWithPropertiesAndInputs.isRight()) {
2850 log.error("Failed to copy component instance with properties and inputs as part of deep copy");
2851 return Either.right(componentsUtils.getResponseFormat(
2852 ActionStatus.USER_DEFINED, "Failed to copy the component instance with properties and inputs as part of deep copy"));
2855 Either<String, ResponseFormat> copyComponentInstanceWithAttributes = copyComponentInstanceWithAttributes(
2856 sourceComponent, destComponent, sourceComponentInstanceId, destComponentInstance, userId);
2857 if (copyComponentInstanceWithAttributes.isRight()) {
2858 log.error("Failed to copy component instance with attributes as part of deep copy");
2859 return Either.right(componentsUtils.getResponseFormat(
2860 ActionStatus.USER_DEFINED, "Failed to copy the component instance with attributes as part of deep copy"));
2862 return Either.left(COPY_COMPONENT_INSTANCE_OK);
2865 private Either<String, ResponseFormat> copyComponentInstanceWithPropertiesAndInputs(
2866 Component sourceComponent, Component destComponent, String sourceComponentInstanceId,
2867 ComponentInstance destComponentInstance, String userId) {
2868 log.debug("start to copy ComponentInstance with properties and inputs");
2870 List<ComponentInstanceProperty> sourcePropList = null;
2871 if (sourceComponent.getComponentInstancesProperties() != null
2872 && sourceComponent.getComponentInstancesProperties().get(sourceComponentInstanceId) != null) {
2873 sourcePropList = sourceComponent.getComponentInstancesProperties().get(sourceComponentInstanceId);
2874 log.debug("sourcePropList");
2877 List<ComponentInstanceProperty> destPropList = null;
2878 String destComponentInstanceId = destComponentInstance.getUniqueId();
2879 log.debug("destComponentInstanceId: {}", destComponentInstance.getUniqueId());
2880 if (destComponent.getComponentInstancesProperties() != null
2881 && destComponent.getComponentInstancesProperties().get(destComponentInstanceId) != null) {
2882 destPropList = destComponent.getComponentInstancesProperties().get(destComponentInstanceId);
2883 log.debug("destPropList {}");
2886 List<ComponentInstancePropInput> componentInstancePropInputList = new ArrayList<>();
2888 if (null != destPropList && null != sourcePropList) {
2889 log.debug("start to set property and attribute");
2890 for (ComponentInstanceProperty destProp : destPropList) {
2891 String destPropertyName = destProp.getName();
2892 for (ComponentInstanceProperty sourceProp : sourcePropList) {
2893 if (!destPropertyName.equals(sourceProp.getName())) {
2896 log.debug("now set property");
2897 if (sourceProp.getGetInputValues() == null && !StringUtils.isEmpty(sourceProp.getValue())
2898 && (destProp.getValue() == null || !destProp.getValue().equals(sourceProp.getValue()))) {
2899 log.debug("Now starting to copy the property {} in value {}", destPropertyName, sourceProp.getValue());
2901 destProp.setValue(sourceProp.getValue());
2902 Either<String, ResponseFormat> updatePropertyValueEither = updateComponentInstanceProperty(
2903 destComponent.getUniqueId(), destComponentInstanceId, destProp);
2904 if (updatePropertyValueEither.isRight()) {
2905 log.error("Failed to copy the property {}", destPropertyName);
2906 return Either.right(componentsUtils.getResponseFormat(
2907 ActionStatus.INVALID_CONTENT_PARAM, "Failed to paste component instance to the canvas, property copy"));
2912 log.debug("Now start to update inputs");
2914 if (sourceProp.getGetInputValues() != null) {
2915 if (sourceProp.getGetInputValues().size() < 1) {
2916 log.debug("property is return from input, set by man");
2919 log.debug("Now starting to copy the {} property", destPropertyName);
2921 Either<String, ResponseFormat> getSourceInputDefaultValue = getInputListDefaultValue(
2922 sourceComponent, sourceProp.getGetInputValues().get(0).getInputId());
2923 if (getSourceInputDefaultValue.isRight()) {
2924 return Either.right(getSourceInputDefaultValue.right().value());
2926 componentInstancePropInputList.add(new ComponentInstancePropInput(destProp));
2931 return Either.left(COPY_COMPONENT_INSTANCE_OK);
2934 private Either<String, ResponseFormat> copyComponentInstanceWithAttributes(Component sourceComponent,
2935 Component destComponent,
2936 String sourceComponentInstanceId,
2937 ComponentInstance destComponentInstance,
2939 String destComponentInstanceId = destComponentInstance.getUniqueId();
2941 log.info("start to copy component instance with attributes");
2943 List<ComponentInstanceProperty> sourceAttributeList = null;
2944 if (sourceComponent.getComponentInstancesAttributes() != null
2945 && sourceComponent.getComponentInstancesAttributes().get(sourceComponentInstanceId) != null) {
2946 sourceAttributeList = sourceComponent.getComponentInstancesAttributes().get(sourceComponentInstanceId);
2947 log.info("sourceAttributes {}");
2950 List<ComponentInstanceProperty> destAttributeList = null;
2951 if (destComponent.getComponentInstancesAttributes() != null
2952 && destComponent.getComponentInstancesAttributes().get(destComponentInstanceId) != null) {
2953 destAttributeList = destComponent.getComponentInstancesAttributes().get(destComponentInstanceId);
2954 log.info("destAttributeList {}");
2956 if (null != sourceAttributeList && null != destAttributeList) {
2957 log.info("set attribute");
2959 for (ComponentInstanceProperty sourceAttribute : sourceAttributeList) {
2960 String sourceAttributeName = sourceAttribute.getName();
2961 for (ComponentInstanceProperty destAttribute : destAttributeList) {
2962 if (sourceAttributeName.equals(destAttribute.getName())) {
2963 if (sourceAttribute.getValue() != null && !sourceAttribute.getValue().isEmpty()) {
2964 log.debug("Start to copy the attribute exists {}", sourceAttributeName);
2966 sourceAttribute.setUniqueId(
2967 UniqueIdBuilder.buildResourceInstanceUniuqeId(
2968 "attribute" , destComponentInstanceId.split("\\.")[1] , sourceAttributeName));
2970 Either<ComponentInstanceProperty, ResponseFormat> updateAttributeValueEither =
2971 createOrUpdateAttributeValueForCopyPaste(ComponentTypeEnum.SERVICE,
2972 destComponent.getUniqueId(), destComponentInstanceId, sourceAttribute,
2974 if (updateAttributeValueEither.isRight()) {
2975 log.error("Failed to copy the attribute");
2976 return Either.right(componentsUtils
2977 .getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM,
2978 "Failed to paste component instance to the canvas, attribute copy"));
2987 return Either.left(COPY_COMPONENT_INSTANCE_OK);
2990 private Either<ComponentInstanceProperty, ResponseFormat> createOrUpdateAttributeValueForCopyPaste(ComponentTypeEnum componentTypeEnum,
2992 String resourceInstanceId,
2993 ComponentInstanceProperty attribute,
2996 Either<ComponentInstanceProperty, ResponseFormat> resultOp = null;
2998 validateUserExists(userId);
3000 if (componentTypeEnum == null) {
3001 BeEcompErrorManager.getInstance().logInvalidInputError(
3002 "createOrUpdateAttributeValue", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
3003 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
3007 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
3009 if (getResourceResult.isRight()) {
3010 log.info("Failed to retrieve component id {}", componentId);
3011 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
3015 Component containerComponent = getResourceResult.left().value();
3017 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId);
3019 if (resourceInstanceStatus.isRight()) {
3020 resultOp = Either.right(componentsUtils.getResponseFormat(
3021 ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, resourceInstanceId, componentId));
3025 ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
3028 String propertyType = attribute.getType();
3029 ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
3030 log.info("The type of attribute id{},is {} ", attribute.getUniqueId(), propertyType);
3032 if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
3033 SchemaDefinition def = attribute.getSchema();
3035 log.info("Schema doesn't exists for attribute of type {}", type);
3036 return Either.right(componentsUtils.getResponseFormat(
3037 componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
3039 PropertyDataDefinition propDef = def.getProperty();
3040 if (propDef == null) {
3041 log.info("Attribute in Schema Definition inside attribute of type {} doesn't exist", type);
3042 return Either.right(componentsUtils.getResponseFormat(
3043 componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
3047 List<ComponentInstanceProperty> instanceAttributes = containerComponent.
3048 getComponentInstancesAttributes().get(resourceInstanceId);
3049 Optional<ComponentInstanceProperty> instanceAttribute =
3050 instanceAttributes.stream().filter(p -> p.getUniqueId().equals(attribute.getUniqueId())).findAny();
3051 StorageOperationStatus status;
3053 if (instanceAttribute.isPresent()) {
3054 log.info("updateComponentInstanceAttribute");
3055 status = toscaOperationFacade.updateComponentInstanceAttribute(containerComponent, foundResourceInstance.getUniqueId(), attribute);
3057 log.info("addComponentInstanceAttribute");
3058 status = toscaOperationFacade.addComponentInstanceAttribute(containerComponent, foundResourceInstance.getUniqueId(), attribute);
3060 if (status != StorageOperationStatus.OK) {
3061 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
3062 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
3065 List<String> path = new ArrayList<>();
3066 path.add(foundResourceInstance.getUniqueId());
3067 attribute.setPath(path);
3069 foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
3070 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.
3071 updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
3073 if (updateContainerRes.isRight()) {
3074 ActionStatus actionStatus = componentsUtils.
3075 convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
3076 resultOp = Either.right(componentsUtils.
3077 getResponseFormatForResourceInstanceProperty(actionStatus, ""));
3080 resultOp = Either.left(attribute);
3087 private Either<String, ResponseFormat> updateComponentInstanceProperty(String containerComponentId,
3088 String componentInstanceId,
3089 ComponentInstanceProperty property) {
3090 Either<String, ResponseFormat> resultOp;
3091 Either<Component, StorageOperationStatus> getComponent = toscaOperationFacade.getToscaElement(containerComponentId);
3093 if (getComponent.isRight()) {
3094 log.error("Failed to get the component information");
3095 return Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(
3096 ActionStatus.INVALID_CONTENT_PARAM, "Failed to get the component information"));
3099 Component containerComponent = getComponent.left().value();
3101 StorageOperationStatus status = toscaOperationFacade.updateComponentInstanceProperty(
3102 containerComponent, componentInstanceId, property);
3103 if (status != StorageOperationStatus.OK) {
3104 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
3105 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
3109 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.
3110 updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
3112 if (updateContainerRes.isRight()) {
3113 ActionStatus actionStatus = componentsUtils.
3114 convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
3115 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
3119 return Either.left("Update OK");
3122 private Either<String, ResponseFormat> getInputListDefaultValue(Component component, String inputId) {
3123 List<InputDefinition> inputList = component.getInputs();
3124 for (InputDefinition input : inputList) {
3125 if (input.getUniqueId().equals(inputId)) {
3126 if (input.getDefaultValue() == null) {
3127 log.debug("The input's default value is null");
3128 return Either.left(null);
3130 return Either.left(input.getDefaultValue());
3133 log.error("The input's default value with id {} is not found", inputId);
3134 return Either.right(componentsUtils.getResponseFormat(
3135 ActionStatus.USER_DEFINED, "Failed to paste component instance to the canvas"));
3139 * Method to delete selected nodes and edges on composition page
3140 * @param containerComponentType
3141 * @param componentId
3142 * @param componentInstanceIdList
3146 public Map<String, List<String>> batchDeleteComponentInstance(String containerComponentType,
3148 List<String> componentInstanceIdList,
3151 List<String> deleteErrorIds = new ArrayList<>();
3152 Map<String, List<String>> deleteErrorMap = new HashMap<>();
3153 validateUserExists(userId);
3154 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(componentId, ComponentTypeEnum.findByParamName(containerComponentType), null);
3156 boolean failed = false;
3158 lockComponent(containerComponent, "batchDeleteComponentInstance");
3159 for (String eachInstanceId : componentInstanceIdList) {
3160 Either<ComponentInstance, ResponseFormat> actionResponse = batchDeleteComponentInstance(
3161 containerComponent, containerComponentType, componentId, eachInstanceId);
3162 log.debug("batchDeleteResourceInstances actionResponse is {}", actionResponse);
3163 if (actionResponse.isRight()) {
3164 log.error("Failed to delete ComponentInstance [{}]", eachInstanceId);
3165 deleteErrorIds.add(eachInstanceId);
3168 //sending the ids of the error nodes that were not deleted to UI
3169 deleteErrorMap.put("deleteFailedIds", deleteErrorIds);
3170 return deleteErrorMap;
3171 }catch (ComponentException e){
3175 unlockComponent(failed, containerComponent);
3179 private Either<ComponentInstance, ResponseFormat> batchDeleteComponentInstance(Component containerComponent,
3180 String containerComponentType,
3181 String containerComponentId,
3182 String componentInstanceId) {
3184 ComponentInstance resultOp;
3185 final ComponentTypeEnum containerComponentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
3187 boolean failed = false;
3189 resultOp = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentTypeEnum);
3190 log.info("Successfully deleted instance with id {}", componentInstanceId);
3191 return Either.left(resultOp);
3193 catch (ComponentException e){
3194 log.error("Failed to deleteComponentInstance with instanceId[{}]", componentInstanceId);
3195 return Either.right(new ResponseFormat());