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 static org.openecomp.sdc.be.components.property.GetInputUtils.isGetInputValueForInput;
24 import static org.openecomp.sdc.be.components.utils.PropertiesUtils.getPropertyCapabilityOfChildInstance;
26 import com.google.common.collect.Sets;
27 import fj.data.Either;
28 import java.util.ArrayList;
29 import java.util.Arrays;
30 import java.util.Collection;
31 import java.util.Collections;
32 import java.util.HashMap;
33 import java.util.Iterator;
34 import java.util.List;
36 import java.util.Map.Entry;
37 import java.util.Objects;
38 import java.util.Optional;
40 import java.util.UUID;
41 import java.util.function.BiConsumer;
42 import java.util.stream.Collectors;
43 import org.apache.commons.collections.CollectionUtils;
44 import org.apache.commons.collections.MapUtils;
45 import org.apache.commons.lang.StringUtils;
46 import org.apache.commons.lang3.tuple.ImmutablePair;
47 import org.openecomp.sdc.be.components.impl.exceptions.BusinessLogicException;
48 import org.openecomp.sdc.be.components.impl.exceptions.ByActionStatusComponentException;
49 import org.openecomp.sdc.be.components.impl.exceptions.ByResponseFormatComponentException;
50 import org.openecomp.sdc.be.components.impl.exceptions.ComponentException;
51 import org.openecomp.sdc.be.components.impl.instance.ComponentInstanceChangeOperationOrchestrator;
52 import org.openecomp.sdc.be.components.impl.utils.DirectivesEnum;
53 import org.openecomp.sdc.be.components.merge.instance.ComponentInstanceMergeDataBusinessLogic;
54 import org.openecomp.sdc.be.components.merge.instance.DataForMergeHolder;
55 import org.openecomp.sdc.be.components.utils.PropertiesUtils;
56 import org.openecomp.sdc.be.components.validation.ComponentValidations;
57 import org.openecomp.sdc.be.config.BeEcompErrorManager;
58 import org.openecomp.sdc.be.config.BeEcompErrorManager.ErrorSeverity;
59 import org.openecomp.sdc.be.config.ConfigurationManager;
60 import org.openecomp.sdc.be.dao.api.ActionStatus;
61 import org.openecomp.sdc.be.dao.janusgraph.JanusGraphOperationStatus;
62 import org.openecomp.sdc.be.dao.jsongraph.types.JsonParseFlagEnum;
63 import org.openecomp.sdc.be.dao.neo4j.GraphPropertiesDictionary;
64 import org.openecomp.sdc.be.datamodel.utils.ContainerInstanceTypesData;
65 import org.openecomp.sdc.be.datatypes.elements.CINodeFilterDataDefinition;
66 import org.openecomp.sdc.be.datatypes.elements.CapabilityDataDefinition;
67 import org.openecomp.sdc.be.datatypes.elements.ForwardingPathDataDefinition;
68 import org.openecomp.sdc.be.datatypes.elements.GetInputValueDataDefinition;
69 import org.openecomp.sdc.be.datatypes.elements.GetPolicyValueDataDefinition;
70 import org.openecomp.sdc.be.datatypes.elements.PropertyDataDefinition;
71 import org.openecomp.sdc.be.datatypes.elements.RequirementDataDefinition;
72 import org.openecomp.sdc.be.datatypes.elements.SchemaDefinition;
73 import org.openecomp.sdc.be.datatypes.enums.ComponentTypeEnum;
74 import org.openecomp.sdc.be.datatypes.enums.NodeTypeEnum;
75 import org.openecomp.sdc.be.datatypes.enums.OriginTypeEnum;
76 import org.openecomp.sdc.be.datatypes.enums.ResourceTypeEnum;
77 import org.openecomp.sdc.be.impl.ComponentsUtils;
78 import org.openecomp.sdc.be.impl.ForwardingPathUtils;
79 import org.openecomp.sdc.be.impl.ServiceFilterUtils;
80 import org.openecomp.sdc.be.info.CreateAndAssotiateInfo;
81 import org.openecomp.sdc.be.model.ArtifactDefinition;
82 import org.openecomp.sdc.be.model.CapabilityDefinition;
83 import org.openecomp.sdc.be.model.Component;
84 import org.openecomp.sdc.be.model.ComponentInstance;
85 import org.openecomp.sdc.be.model.ComponentInstanceInput;
86 import org.openecomp.sdc.be.model.ComponentInstancePropInput;
87 import org.openecomp.sdc.be.model.ComponentInstanceProperty;
88 import org.openecomp.sdc.be.model.ComponentParametersView;
89 import org.openecomp.sdc.be.model.DataTypeDefinition;
90 import org.openecomp.sdc.be.model.GroupDefinition;
91 import org.openecomp.sdc.be.model.InputDefinition;
92 import org.openecomp.sdc.be.model.InterfaceDefinition;
93 import org.openecomp.sdc.be.model.LifecycleStateEnum;
94 import org.openecomp.sdc.be.model.PolicyDefinition;
95 import org.openecomp.sdc.be.model.PropertyDefinition;
96 import org.openecomp.sdc.be.model.RelationshipInfo;
97 import org.openecomp.sdc.be.model.RequirementCapabilityRelDef;
98 import org.openecomp.sdc.be.model.RequirementDefinition;
99 import org.openecomp.sdc.be.model.Resource;
100 import org.openecomp.sdc.be.model.Service;
101 import org.openecomp.sdc.be.model.User;
102 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ArtifactsOperations;
103 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ForwardingPathOperation;
104 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.InterfaceOperation;
105 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.NodeFilterOperation;
106 import org.openecomp.sdc.be.model.jsonjanusgraph.operations.ToscaOperationFacade;
107 import org.openecomp.sdc.be.model.jsonjanusgraph.utils.ModelConverter;
108 import org.openecomp.sdc.be.model.operations.StorageException;
109 import org.openecomp.sdc.be.model.operations.api.IElementOperation;
110 import org.openecomp.sdc.be.model.operations.api.IGroupInstanceOperation;
111 import org.openecomp.sdc.be.model.operations.api.IGroupOperation;
112 import org.openecomp.sdc.be.model.operations.api.IGroupTypeOperation;
113 import org.openecomp.sdc.be.model.operations.api.StorageOperationStatus;
114 import org.openecomp.sdc.be.model.operations.impl.ComponentInstanceOperation;
115 import org.openecomp.sdc.be.model.operations.impl.DaoStatusConverter;
116 import org.openecomp.sdc.be.model.operations.impl.InterfaceLifecycleOperation;
117 import org.openecomp.sdc.be.model.operations.impl.UniqueIdBuilder;
118 import org.openecomp.sdc.be.model.operations.utils.ComponentValidationUtils;
119 import org.openecomp.sdc.be.model.tosca.ToscaPropertyType;
120 import org.openecomp.sdc.be.resources.data.ComponentInstanceData;
121 import org.openecomp.sdc.be.user.Role;
122 import org.openecomp.sdc.common.api.ArtifactGroupTypeEnum;
123 import org.openecomp.sdc.common.api.ArtifactTypeEnum;
124 import org.openecomp.sdc.common.api.Constants;
125 import org.openecomp.sdc.common.datastructure.Wrapper;
126 import org.openecomp.sdc.common.jsongraph.util.CommonUtility;
127 import org.openecomp.sdc.common.jsongraph.util.CommonUtility.LogLevelEnum;
128 import org.openecomp.sdc.common.log.wrappers.Logger;
129 import org.openecomp.sdc.common.util.ValidationUtils;
130 import org.openecomp.sdc.exception.ResponseFormat;
131 import org.springframework.beans.factory.annotation.Autowired;
133 @org.springframework.stereotype.Component
134 public class ComponentInstanceBusinessLogic extends BaseBusinessLogic {
136 private static final Logger log = Logger.getLogger(ComponentInstanceBusinessLogic.class.getName());
137 private static final String VF_MODULE = "org.openecomp.groups.VfModule";
138 private static final String TRY_TO_CREATE_ENTRY_ON_GRAPH = "Try to create entry on graph";
139 private static final String CLOUD_SPECIFIC_FIXED_KEY_WORD = "cloudtech";
140 private static final String[][] CLOUD_SPECIFIC_KEY_WORDS = {{"k8s", "azure", "aws"}, /* cloud specific technology */
141 {"charts", "day0", "configtemplate"} /*cloud specific sub type*/};
142 private static final String FAILED_TO_CREATE_ENTRY_ON_GRAPH_FOR_COMPONENT_INSTANCE = "Failed to create entry on graph for component instance {}";
143 private static final String ENTITY_ON_GRAPH_IS_CREATED = "Entity on graph is created.";
144 private static final String INVALID_COMPONENT_TYPE = "invalid component type";
145 private static final String FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID = "Failed to retrieve component, component id {}";
146 private static final String FAILED_TO_LOCK_SERVICE = "Failed to lock service {}";
147 private static final String CREATE_OR_UPDATE_PROPERTY_VALUE = "CreateOrUpdatePropertyValue";
148 private static final String FAILED_TO_COPY_COMP_INSTANCE_TO_CANVAS = "Failed to copy the component instance to the canvas";
149 private static final String COPY_COMPONENT_INSTANCE_OK = "Copy component instance OK";
151 private ComponentInstanceOperation componentInstanceOperation;
152 private ArtifactsBusinessLogic artifactBusinessLogic;
153 private ComponentInstanceMergeDataBusinessLogic compInstMergeDataBL;
154 private ComponentInstanceChangeOperationOrchestrator onChangeInstanceOperationOrchestrator;
155 private ForwardingPathOperation forwardingPathOperation;
156 private NodeFilterOperation nodeFilterOperation;
159 public ComponentInstanceBusinessLogic(IElementOperation elementDao,
160 IGroupOperation groupOperation,
161 IGroupInstanceOperation groupInstanceOperation,
162 IGroupTypeOperation groupTypeOperation,
163 InterfaceOperation interfaceOperation,
164 InterfaceLifecycleOperation interfaceLifecycleTypeOperation,
165 ComponentInstanceOperation componentInstanceOperation, ArtifactsBusinessLogic artifactBusinessLogic,
166 ComponentInstanceMergeDataBusinessLogic compInstMergeDataBL,
167 ComponentInstanceChangeOperationOrchestrator onChangeInstanceOperationOrchestrator,
168 ForwardingPathOperation forwardingPathOperation, NodeFilterOperation nodeFilterOperation,
169 ArtifactsOperations artifactToscaOperation) {
170 super(elementDao, groupOperation, groupInstanceOperation, groupTypeOperation,
171 interfaceOperation, interfaceLifecycleTypeOperation, artifactToscaOperation);
172 this.componentInstanceOperation = componentInstanceOperation;
173 this.artifactBusinessLogic = artifactBusinessLogic;
174 this.compInstMergeDataBL = compInstMergeDataBL;
175 this.onChangeInstanceOperationOrchestrator = onChangeInstanceOperationOrchestrator;
176 this.forwardingPathOperation = forwardingPathOperation;
177 this.nodeFilterOperation = nodeFilterOperation;
181 private CompositionBusinessLogic compositionBusinessLogic;
184 private ContainerInstanceTypesData containerInstanceTypesData;
186 public ComponentInstance createComponentInstance(String containerComponentParam, String containerComponentId, String userId, ComponentInstance resourceInstance) {
187 return createComponentInstance(containerComponentParam, containerComponentId, userId, resourceInstance, false, true);
190 public List<ComponentInstanceProperty> getComponentInstancePropertiesByInputId(org.openecomp.sdc.be.model.Component component, String inputId){
191 List<ComponentInstanceProperty> resList = new ArrayList<>();
192 Map<String, List<ComponentInstanceProperty>> ciPropertiesMap = component.getComponentInstancesProperties();
193 if(ciPropertiesMap != null && !ciPropertiesMap.isEmpty()){
194 ciPropertiesMap.forEach(new BiConsumer<String, List<ComponentInstanceProperty>>() {
196 public void accept(String s, List<ComponentInstanceProperty> ciPropList) {
198 Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci ->ci.getUniqueId().equals(s)).findAny();
200 ciName = ciOp.get().getName();
201 if (ciPropList != null && !ciPropList.isEmpty()) {
202 for(ComponentInstanceProperty prop: ciPropList){
203 List<GetInputValueDataDefinition> inputsValues = prop.getGetInputValues();
204 addCompInstanceProperty(s, ciName, prop, inputsValues, inputId, resList);
214 private void addCompInstanceProperty(String s, String ciName, ComponentInstanceProperty prop, List<GetInputValueDataDefinition> inputsValues, String inputId, List<ComponentInstanceProperty> resList) {
215 if(inputsValues != null && !inputsValues.isEmpty()){
216 for(GetInputValueDataDefinition inputData: inputsValues){
217 if(isGetInputValueForInput(inputData, inputId)){
218 prop.setComponentInstanceId(s);
219 prop.setComponentInstanceName(ciName);
227 public Optional<ComponentInstanceProperty> getComponentInstancePropertyByPolicyId(Component component,
228 PolicyDefinition policy) {
230 Optional<ComponentInstanceProperty> propertyCandidate = getComponentInstancePropertyByPolicy(component, policy);
232 if(propertyCandidate.isPresent()) {
233 ComponentInstanceProperty componentInstanceProperty = propertyCandidate.get();
234 Optional<GetPolicyValueDataDefinition> getPolicyCandidate =
235 getGetPolicyValueDataDefinition(policy, componentInstanceProperty);
237 getPolicyCandidate.ifPresent(getPolicyValue ->
238 updateComponentInstancePropertyAfterUndeclaration(componentInstanceProperty, getPolicyValue, policy));
239 return Optional.of(componentInstanceProperty);
242 return Optional.empty();
246 private void updateComponentInstancePropertyAfterUndeclaration(ComponentInstanceProperty componentInstanceProperty,
247 GetPolicyValueDataDefinition getPolicyValue, PolicyDefinition policyDefinition) {
248 componentInstanceProperty.setValue(getPolicyValue.getOrigPropertyValue());
249 List<GetPolicyValueDataDefinition> getPolicyValues = componentInstanceProperty.getGetPolicyValues();
250 if(CollectionUtils.isNotEmpty(getPolicyValues)) {
251 getPolicyValues.remove(getPolicyValue);
252 componentInstanceProperty.setGetPolicyValues(getPolicyValues);
253 policyDefinition.setGetPolicyValues(getPolicyValues);
257 private Optional<GetPolicyValueDataDefinition> getGetPolicyValueDataDefinition(PolicyDefinition policy,
258 ComponentInstanceProperty componentInstanceProperty) {
259 List<GetPolicyValueDataDefinition> getPolicyValues = policy.getGetPolicyValues();
260 return getPolicyValues.stream()
261 .filter(getPolicyValue -> getPolicyValue
263 .equals(componentInstanceProperty
268 private Optional<ComponentInstanceProperty> getComponentInstancePropertyByPolicy(Component component,
269 PolicyDefinition policy) {
270 Map<String, List<ComponentInstanceProperty>> componentInstancesProperties =
271 component.getComponentInstancesProperties();
273 if(MapUtils.isEmpty(componentInstancesProperties)) {
274 return Optional.empty();
277 String instanceUniqueId = policy.getInstanceUniqueId();
279 List<ComponentInstanceProperty> componentInstanceProperties =
280 componentInstancesProperties.containsKey(instanceUniqueId)
281 ? componentInstancesProperties.get(instanceUniqueId)
284 return componentInstanceProperties
285 .stream().filter(property -> property.getName().equals(policy.getName())).findAny();
288 public List<ComponentInstanceInput> getComponentInstanceInputsByInputId(
289 org.openecomp.sdc.be.model.Component component, String inputId) {
290 List<ComponentInstanceInput> resList = new ArrayList<>();
291 Map<String, List<ComponentInstanceInput>> ciInputsMap = component.getComponentInstancesInputs();
292 if(ciInputsMap != null && !ciInputsMap.isEmpty()){
293 ciInputsMap.forEach(new BiConsumer<String, List<ComponentInstanceInput>>() {
295 public void accept(String s, List<ComponentInstanceInput> ciPropList) {
297 Optional<ComponentInstance> ciOp = component.getComponentInstances().stream().filter(ci ->ci.getUniqueId().equals(s)).findAny();
299 ciName = ciOp.get().getName();
300 if (ciPropList != null && !ciPropList.isEmpty()) {
301 for(ComponentInstanceInput prop: ciPropList){
302 List<GetInputValueDataDefinition> inputsValues = prop.getGetInputValues();
303 addCompInstanceInput(s, ciName, prop, inputsValues, inputId, resList);
314 private void addCompInstanceInput(String s, String ciName, ComponentInstanceInput prop, List<GetInputValueDataDefinition> inputsValues, String inputId, List<ComponentInstanceInput> resList) {
315 if(inputsValues != null && !inputsValues.isEmpty()){
316 for(GetInputValueDataDefinition inputData: inputsValues){
317 if(isGetInputValueForInput(inputData, inputId)){
318 prop.setComponentInstanceId(s);
319 prop.setComponentInstanceName(ciName);
327 public ComponentInstance createComponentInstance(String containerComponentParam, String containerComponentId, String userId, ComponentInstance resourceInstance, boolean inTransaction, boolean needLock) {
329 Component origComponent = null;
331 org.openecomp.sdc.be.model.Component containerComponent = null;
332 ComponentTypeEnum containerComponentType;
334 user = validateUserExists(userId);
335 validateUserNotEmpty(user, "Create component instance");
336 validateJsonBody(resourceInstance, ComponentInstance.class);
337 containerComponentType = validateComponentType(containerComponentParam);
338 containerComponent = validateComponentExists(containerComponentId, containerComponentType, null);
340 if (ModelConverter.isAtomicComponent(containerComponent)) {
341 log.debug("Cannot attach resource instances to container resource of type {}", containerComponent.assetType());
342 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType());
345 validateCanWorkOnComponent(containerComponent, userId);
347 if (resourceInstance != null && containerComponentType != null) {
348 OriginTypeEnum originType = resourceInstance.getOriginType();
349 validateInstanceName(resourceInstance);
350 if (originType == OriginTypeEnum.ServiceProxy) {
352 Either<Component, StorageOperationStatus> serviceProxyOrigin = toscaOperationFacade.getLatestByName("serviceProxy");
353 if (isServiceProxyOrigin(serviceProxyOrigin)) {
354 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(serviceProxyOrigin.right().value()));
356 origComponent = serviceProxyOrigin.left().value();
358 StorageOperationStatus fillProxyRes = fillProxyInstanceData(resourceInstance, origComponent);
359 if (isFillProxyRes(fillProxyRes)) {
360 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(fillProxyRes));
364 origComponent = getAndValidateOriginComponentOfComponentInstance(containerComponent, resourceInstance);
366 validateOriginAndResourceInstanceTypes(containerComponent, origComponent, originType);
367 validateResourceInstanceState(containerComponent, origComponent);
368 overrideFields(origComponent, resourceInstance);
369 compositionBusinessLogic.validateAndSetDefaultCoordinates(resourceInstance);
371 return createComponent(needLock, containerComponent,origComponent, resourceInstance, user);
373 }catch (ComponentException e){
378 private ComponentInstance createComponent(boolean needLock, Component containerComponent, Component origComponent, ComponentInstance resourceInstance, User user) {
380 boolean failed = false;
383 ComponentInstance lockComponent = isNeedLock(needLock, containerComponent);
384 if (lockComponent != null) {
385 return lockComponent;
387 log.debug(TRY_TO_CREATE_ENTRY_ON_GRAPH);
388 return createComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, user);
389 }catch (ComponentException e){
394 unlockComponent(failed, containerComponent);
398 private void overrideFields(Component origComponent, ComponentInstance resourceInstance) {
399 resourceInstance.setComponentVersion(origComponent.getVersion());
400 resourceInstance.setIcon(origComponent.getIcon());
403 private void validateInstanceName(ComponentInstance resourceInstance) {
405 String resourceInstanceName = resourceInstance.getName();
406 if (StringUtils.isEmpty(resourceInstanceName)) {
407 log.debug("ComponentInstance name is empty");
408 throw new ByActionStatusComponentException(ActionStatus.INVALID_COMPONENT_NAME, resourceInstance.getName());
411 if (!ValidationUtils.validateComponentNameLength(resourceInstanceName)) {
412 log.debug("ComponentInstance name exceeds max length {} ", ValidationUtils.COMPONENT_NAME_MAX_LENGTH);
413 throw new ByActionStatusComponentException(ActionStatus.INVALID_COMPONENT_NAME, resourceInstance.getName());
416 if (!ValidationUtils.validateComponentNamePattern(resourceInstanceName)) {
417 log.debug("ComponentInstance name {} has invalid format", resourceInstanceName);
418 throw new ByActionStatusComponentException(ActionStatus.INVALID_COMPONENT_NAME, resourceInstance.getName());
422 private void validateResourceInstanceState(Component containerComponent, Component origComponent) {
423 if (origComponent.getLifecycleState() == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT){
424 throw new ByActionStatusComponentException(ActionStatus.CONTAINER_CANNOT_CONTAIN_INSTANCE,
425 containerComponent.getComponentType().getValue(), origComponent.getLifecycleState().toString());
429 private void validateOriginAndResourceInstanceTypes(Component containerComponent, Component origComponent, OriginTypeEnum originType) {
430 ResourceTypeEnum resourceType = null;
431 ResourceTypeEnum convertedOriginType;
432 resourceType = getResourceTypeEnumFromOriginComponent(origComponent, resourceType);
433 validateOriginType(originType, resourceType);
434 validateOriginComponentIsValidForContainer(containerComponent, resourceType);
437 private void validateOriginComponentIsValidForContainer(Component containerComponent, ResourceTypeEnum resourceType) {
438 switch (containerComponent.getComponentType()) {
440 if (!containerInstanceTypesData.getServiceContainerList().contains((resourceType))) {
441 throw new ByActionStatusComponentException(ActionStatus.CONTAINER_CANNOT_CONTAIN_INSTANCE,
442 containerComponent.getComponentType().toString(), resourceType.name());
446 if (!containerInstanceTypesData.getValidInstanceTypesInResourceContainer().get(((Resource) containerComponent).getResourceType()).contains(resourceType)) {
447 throw new ByActionStatusComponentException(ActionStatus.CONTAINER_CANNOT_CONTAIN_INSTANCE,
448 containerComponent.getComponentType().toString(), resourceType.name());
452 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
456 private void validateOriginType(OriginTypeEnum originType, ResourceTypeEnum resourceType) {
457 ResourceTypeEnum convertedOriginType;
459 convertedOriginType = ResourceTypeEnum.getTypeIgnoreCase(originType.name());
462 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
465 if (resourceType != convertedOriginType) throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
468 private ResourceTypeEnum getResourceTypeEnumFromOriginComponent(Component origComponent, ResourceTypeEnum resourceType) {
469 switch (origComponent.getComponentType()) {
471 resourceType = ResourceTypeEnum.ServiceProxy;
474 resourceType = ((Resource) origComponent).getResourceType();
477 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT);
482 private ComponentInstance isNeedLock(boolean needLock, Component containerComponent) {
484 lockComponent(containerComponent, "createComponentInstance");
489 private boolean isServiceProxyOrigin(Either<Component, StorageOperationStatus> serviceProxyOrigin) {
490 if (serviceProxyOrigin.isRight()) {
491 log.debug("Failed to fetch normative service proxy resource by tosca name, error {}", serviceProxyOrigin.right().value());
497 private StorageOperationStatus fillProxyInstanceData(ComponentInstance resourceInstance, Component proxyTemplate) {
498 resourceInstance.setIsProxy(true);
499 ComponentParametersView filter = new ComponentParametersView(true);
500 filter.setIgnoreCapabilities(false);
501 filter.setIgnoreCapabiltyProperties(false);
502 filter.setIgnoreComponentInstances(false);
503 filter.setIgnoreRequirements(false);
504 filter.setIgnoreInterfaces(false);
505 filter.setIgnoreProperties(false);
506 filter.setIgnoreInputs(false);
507 Either<Component, StorageOperationStatus> serviceRes =
508 toscaOperationFacade.getToscaElement(resourceInstance.getComponentUid(), filter);
509 if (serviceRes.isRight()) {
510 return serviceRes.right().value();
512 Component service = serviceRes.left().value();
513 Map<String, List<CapabilityDefinition>> capabilities = service.getCapabilities();
514 resourceInstance.setCapabilities(capabilities);
515 Map<String, List<RequirementDefinition>> req = service.getRequirements();
516 resourceInstance.setRequirements(req);
517 Map<String, InterfaceDefinition> serviceInterfaces = service.getInterfaces();
518 if(MapUtils.isNotEmpty(serviceInterfaces)) {
519 serviceInterfaces.forEach(resourceInstance::addInterface);
523 resourceInstance.setProperties(PropertiesUtils.getProperties(service));
525 List<InputDefinition> serviceInputs = service.getInputs();
526 resourceInstance.setInputs(serviceInputs);
528 String name = ValidationUtils.normalizeComponentInstanceName(service.getName()) + ToscaOperationFacade.PROXY_SUFFIX;
529 String toscaResourceName = ((Resource) proxyTemplate).getToscaResourceName();
530 int lastIndexOf = toscaResourceName.lastIndexOf('.');
531 if (lastIndexOf != -1) {
532 String proxyToscaName = toscaResourceName.substring(0, lastIndexOf + 1) + name;
533 resourceInstance.setToscaComponentName(proxyToscaName);
535 resourceInstance.setName(name);
536 resourceInstance.setIsProxy(true);
537 resourceInstance.setSourceModelInvariant(service.getInvariantUUID());
538 resourceInstance.setSourceModelName(service.getName());
539 resourceInstance.setSourceModelUuid(service.getUUID());
540 resourceInstance.setSourceModelUid(service.getUniqueId());
541 resourceInstance.setComponentUid(proxyTemplate.getUniqueId());
542 resourceInstance.setDescription("A Proxy for Service " + service.getName());
543 resourceInstance.setComponentVersion(service.getVersion());
545 return StorageOperationStatus.OK;
548 public Either<CreateAndAssotiateInfo, ResponseFormat> createAndAssociateRIToRI(String containerComponentParam, String containerComponentId, String userId, CreateAndAssotiateInfo createAndAssotiateInfo) {
550 Either<CreateAndAssotiateInfo, ResponseFormat> resultOp = null;
551 ComponentInstance resourceInstance = createAndAssotiateInfo.getNode();
552 RequirementCapabilityRelDef associationInfo = createAndAssotiateInfo.getAssociate();
554 User user = validateUserExists(userId);
556 final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
558 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, null);
560 if (ModelConverter.isAtomicComponent(containerComponent)) {
561 log.debug("Cannot attach resource instances to container resource of type {}", containerComponent.assetType());
562 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_CANNOT_CONTAIN_RESOURCE_INSTANCES, containerComponent.assetType()));
565 validateCanWorkOnComponent(containerComponent, userId);
567 boolean failed = false;
569 lockComponent(containerComponent, "createAndAssociateRIToRI");
570 log.debug(TRY_TO_CREATE_ENTRY_ON_GRAPH);
571 Component origComponent = getOriginComponentFromComponentInstance(resourceInstance);
573 log.debug(ENTITY_ON_GRAPH_IS_CREATED);
574 ComponentInstance resResourceInfo = createComponentInstanceOnGraph(containerComponent, origComponent, resourceInstance, user);
575 if (associationInfo.getFromNode() == null || associationInfo.getFromNode().isEmpty()) {
576 associationInfo.setFromNode(resResourceInfo.getUniqueId());
578 associationInfo.setToNode(resResourceInfo.getUniqueId());
581 Either<RequirementCapabilityRelDef, StorageOperationStatus> resultReqCapDef = toscaOperationFacade.associateResourceInstances(containerComponent, containerComponentId, associationInfo);
582 if (resultReqCapDef.isLeft()) {
583 log.debug(ENTITY_ON_GRAPH_IS_CREATED);
584 RequirementCapabilityRelDef resReqCapabilityRelDef = resultReqCapDef.left().value();
585 CreateAndAssotiateInfo resInfo = new CreateAndAssotiateInfo(resResourceInfo, resReqCapabilityRelDef);
586 resultOp = Either.left(resInfo);
590 log.info("Failed to associate node {} with node {}", associationInfo.getFromNode(), associationInfo.getToNode());
591 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(resultReqCapDef.right().value(), true), "", null));
595 }catch (ComponentException e){
599 unlockComponent(failed, containerComponent);
603 private Component getOriginComponentFromComponentInstance(ComponentInstance componentInstance) {
604 return getOriginComponentFromComponentInstance(componentInstance.getName(), componentInstance.getComponentUid());
607 private Component getInstanceOriginNode(ComponentInstance componentInstance) {
608 return getOriginComponentFromComponentInstance(componentInstance.getName(), componentInstance.getActualComponentUid());
611 private Component getOriginComponentFromComponentInstance(String componentInstanceName, String origComponetId) {
612 Either<Component, StorageOperationStatus> eitherComponent = toscaOperationFacade.getToscaFullElement(origComponetId);
613 if (eitherComponent.isRight()) {
614 log.debug("Failed to get origin component with id {} for component instance {} ", origComponetId, componentInstanceName);
615 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(eitherComponent.right().value(), ComponentTypeEnum.RESOURCE), "", null);
617 return eitherComponent.left().value();
620 private ComponentInstance createComponentInstanceOnGraph(org.openecomp.sdc.be.model.Component containerComponent, Component originComponent, ComponentInstance componentInstance, User user) {
621 Either<ComponentInstance, ResponseFormat> resultOp;
623 Either<ImmutablePair<Component, String>, StorageOperationStatus> result = toscaOperationFacade.addComponentInstanceToTopologyTemplate(containerComponent, originComponent, componentInstance, false, user);
625 if (result.isRight()) {
626 log.debug(FAILED_TO_CREATE_ENTRY_ON_GRAPH_FOR_COMPONENT_INSTANCE, componentInstance.getName());
627 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true), "", null));
630 log.debug(ENTITY_ON_GRAPH_IS_CREATED);
631 Component updatedComponent = result.left().value().getLeft();
632 Map<String, String> existingEnvVersions = new HashMap<>();
633 // TODO existingEnvVersions ??
634 addComponentInstanceArtifacts(updatedComponent, componentInstance, originComponent, user, existingEnvVersions);
636 Optional<ComponentInstance> updatedInstanceOptional = updatedComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(result.left().value().getRight())).findFirst();
637 if (!updatedInstanceOptional.isPresent()) {
638 log.debug("Failed to fetch new added component instance {} from component {}", componentInstance.getName(), containerComponent.getName());
639 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName());
641 return updatedInstanceOptional.get();
644 public boolean isCloudSpecificArtifact(String artifact) {
645 if (artifact.contains(CLOUD_SPECIFIC_FIXED_KEY_WORD)) {
646 for (int i = 0; i < CLOUD_SPECIFIC_KEY_WORDS.length; i++) {
647 if (Arrays.stream(CLOUD_SPECIFIC_KEY_WORDS[i]).noneMatch(str -> artifact.contains(str))) {
659 * addResourceInstanceArtifacts - add artifacts (HEAT_ENV) to resource instance The instance artifacts are generated from the resource's artifacts
660 * @param containerComponent
661 * @param componentInstance
662 * @param originComponent
664 * @param existingEnvVersions
667 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) {
669 log.debug("add artifacts to resource instance");
670 List<GroupDefinition> filteredGroups = new ArrayList<>();
671 ActionStatus status = setResourceArtifactsOnResourceInstance(componentInstance);
672 if (ActionStatus.OK != status) {
673 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormatForResourceInstance(status, "", null));
675 StorageOperationStatus artStatus;
676 // generate heat_env if necessary
677 Map<String, ArtifactDefinition> componentDeploymentArtifacts = componentInstance.getDeploymentArtifacts();
678 if (MapUtils.isNotEmpty(componentDeploymentArtifacts)) {
680 Map<String, ArtifactDefinition> finalDeploymentArtifacts = new HashMap<>();
681 Map<String, List<ArtifactDefinition>> groupInstancesArtifacts = new HashMap<>();
682 Integer defaultHeatTimeout = ConfigurationManager.getConfigurationManager().getConfiguration()
683 .getHeatArtifactDeploymentTimeout().getDefaultMinutes();
684 List<ArtifactDefinition> listOfCloudSpecificArts = new ArrayList<>();
685 for (ArtifactDefinition artifact : componentDeploymentArtifacts.values()) {
686 String type = artifact.getArtifactType();
687 if (!type.equalsIgnoreCase(ArtifactTypeEnum.HEAT_ENV.getType())) {
688 finalDeploymentArtifacts.put(artifact.getArtifactLabel(), artifact);
690 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())) {
691 artifact.setTimeout(defaultHeatTimeout);
695 if (artifact.checkEsIdExist()) {
696 ArtifactDefinition artifactDefinition = artifactBusinessLogic.createHeatEnvPlaceHolder(new ArrayList<>(),
697 artifact, ArtifactsBusinessLogic.HEAT_ENV_NAME, componentInstance.getUniqueId(),
698 NodeTypeEnum.ResourceInstance, componentInstance.getName(), user, containerComponent,
699 existingEnvVersions);
701 finalDeploymentArtifacts.put(artifactDefinition.getArtifactLabel(), artifactDefinition);
703 if (CollectionUtils.isNotEmpty(originComponent.getGroups())) {
704 filteredGroups = originComponent.getGroups().stream().filter(g -> g.getType().equals(VF_MODULE)).collect(Collectors.toList());
706 if (isCloudSpecificArtifact(artifactDefinition.getArtifactName())) {
707 listOfCloudSpecificArts.add(artifact);
709 if (CollectionUtils.isNotEmpty(filteredGroups)) {
710 filteredGroups.stream().filter(g ->
713 .anyMatch(p -> p.equals(artifactDefinition.getGeneratedFromId())))
715 .ifPresent(g -> fillInstanceArtifactMap(groupInstancesArtifacts, artifactDefinition, g));
719 groupInstancesArtifacts.forEach((k,v) -> v.addAll(listOfCloudSpecificArts));
720 filteredGroups.forEach(g -> listOfCloudSpecificArts.forEach((e) -> {
721 g.getArtifactsUuid().add(e.getArtifactUUID());
722 g.getArtifacts().add(e.getUniqueId());
724 artStatus = toscaOperationFacade.addDeploymentArtifactsToInstance(containerComponent.getUniqueId(), componentInstance, finalDeploymentArtifacts);
725 if (artStatus != StorageOperationStatus.OK) {
726 log.debug("Failed to add instance deployment artifacts for instance {} in conatiner {} error {}", componentInstance.getUniqueId(), containerComponent.getUniqueId(), artStatus);
727 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(artStatus, false)));
730 StorageOperationStatus result = toscaOperationFacade.addGroupInstancesToComponentInstance(containerComponent, componentInstance, filteredGroups, groupInstancesArtifacts);
731 if (result != StorageOperationStatus.OK) {
732 log.debug("failed to update group instance for component instance {}", componentInstance.getUniqueId());
733 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(result)));
735 componentInstance.setDeploymentArtifacts(finalDeploymentArtifacts);
738 artStatus = toscaOperationFacade.addInformationalArtifactsToInstance(containerComponent.getUniqueId(), componentInstance, originComponent.getArtifacts());
739 if (artStatus != StorageOperationStatus.OK) {
740 log.debug("Failed to add informational artifacts to the instance {} belonging to the conatiner {}. Status is {}", componentInstance.getUniqueId(), containerComponent.getUniqueId(), artStatus);
741 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponseForResourceInstance(artStatus, false)));
744 componentInstance.setArtifacts(originComponent.getArtifacts());
745 return ActionStatus.OK;
748 private void fillInstanceArtifactMap(Map<String, List<ArtifactDefinition>> groupInstancesArtifacts, ArtifactDefinition artifactDefinition, GroupDefinition groupInstance) {
749 List<ArtifactDefinition> artifactsUid;
750 if (groupInstancesArtifacts.containsKey(groupInstance.getUniqueId())) {
751 artifactsUid = groupInstancesArtifacts.get(groupInstance.getUniqueId());
753 artifactsUid = new ArrayList<>();
755 artifactsUid.add(artifactDefinition);
756 groupInstancesArtifacts.put(groupInstance.getUniqueId(), artifactsUid);
759 private ActionStatus setResourceArtifactsOnResourceInstance(ComponentInstance resourceInstance) {
760 Either<Map<String, ArtifactDefinition>, StorageOperationStatus> getResourceDeploymentArtifacts =
761 artifactBusinessLogic.getArtifacts(resourceInstance.getComponentUid(), NodeTypeEnum.Resource, ArtifactGroupTypeEnum.DEPLOYMENT, null);
763 Map<String, ArtifactDefinition> deploymentArtifacts = new HashMap<>();
764 if (getResourceDeploymentArtifacts.isRight()) {
765 StorageOperationStatus status = getResourceDeploymentArtifacts.right().value();
766 if (status != StorageOperationStatus.NOT_FOUND) {
767 log.debug("Failed to fetch resource: {} artifacts. status is {}", resourceInstance.getComponentUid(), status);
768 return componentsUtils.convertFromStorageResponseForResourceInstance(status, true);
771 deploymentArtifacts = getResourceDeploymentArtifacts.left().value();
774 if (!deploymentArtifacts.isEmpty()) {
775 Map<String, ArtifactDefinition> tempDeploymentArtifacts = new HashMap<>(deploymentArtifacts);
776 for (Entry<String, ArtifactDefinition> artifact : deploymentArtifacts.entrySet()) {
777 if (!artifact.getValue().checkEsIdExist()) {
778 tempDeploymentArtifacts.remove(artifact.getKey());
782 resourceInstance.setDeploymentArtifacts(tempDeploymentArtifacts);
785 return ActionStatus.OK;
788 public Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance componentInstance) {
789 return updateComponentInstanceMetadata(containerComponentParam, containerComponentId, componentInstanceId, userId, componentInstance, false, true);
792 public Either<ComponentInstance, ResponseFormat> updateComponentInstanceMetadata(
793 final String containerComponentParam,
794 final String containerComponentId,
795 final String componentInstanceId,
797 ComponentInstance componentInstance,
798 final boolean inTransaction,
801 validateUserExists(userId);
803 final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
805 final Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, null);
807 validateCanWorkOnComponent(containerComponent, userId);
808 ComponentTypeEnum instanceType = getComponentType(containerComponentType);
809 Either<Boolean, StorageOperationStatus> validateParentStatus = toscaOperationFacade.validateComponentExists(componentInstance.getComponentUid());
810 if (validateParentStatus.isRight()) {
811 log.debug("Failed to get component instance {} on service {}", componentInstanceId, containerComponentId);
812 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND, componentInstance.getName(), instanceType.getValue().toLowerCase());
814 if (!validateParentStatus.left().value()) {
815 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName(), instanceType.getValue().toLowerCase(), containerComponentType.getValue().toLowerCase(), containerComponentId);
819 lockComponent(containerComponent, "updateComponentInstance");
821 Component origComponent;
822 boolean failed = false;
824 origComponent = getOriginComponentFromComponentInstance(componentInstance);
825 componentInstance = updateComponentInstanceMetadata(containerComponent, containerComponentType, origComponent, componentInstanceId, componentInstance);
826 }catch (ComponentException e) {
831 unlockComponent(failed, containerComponent);
834 return Either.left(componentInstance);
837 // New Multiple Instance Update API
838 public List<ComponentInstance> updateComponentInstance(String containerComponentParam, Component containerComponent, String containerComponentId, String userId, List<ComponentInstance> componentInstanceList, boolean needLock) {
840 boolean failed = false;
842 validateUserExists(userId);
844 final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
845 ComponentParametersView componentFilter = new ComponentParametersView();
846 componentFilter.disableAll();
847 componentFilter.setIgnoreUsers(false);
848 componentFilter.setIgnoreComponentInstances(false);
849 if (containerComponent == null) {
850 containerComponent = validateComponentExistsByFilter(containerComponentId, containerComponentType, componentFilter);
852 validateCanWorkOnComponent(containerComponent, userId);
854 ComponentTypeEnum instanceType = getComponentType(containerComponentType);
856 for (ComponentInstance componentInstance : componentInstanceList) {
857 boolean validateParent = validateParent(containerComponent, componentInstance.getUniqueId());
858 if (!validateParent) {
859 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName(),
860 instanceType.getValue().toLowerCase(), containerComponentType.getValue().toLowerCase(),
861 containerComponentId);
866 lockComponent(containerComponent, "updateComponentInstance");
869 List<ComponentInstance> updatedList = new ArrayList<>();
870 List<ComponentInstance> instancesFromContainerComponent = containerComponent.getComponentInstances();
871 List<ComponentInstance> listForUpdate = new ArrayList<>();
872 if (instancesFromContainerComponent == null || instancesFromContainerComponent.isEmpty())
873 containerComponent.setComponentInstances(componentInstanceList);
875 Iterator<ComponentInstance> iterator = instancesFromContainerComponent.iterator();
876 while (iterator.hasNext()) {
877 ComponentInstance origInst = iterator.next();
878 Optional<ComponentInstance> op = componentInstanceList.stream().filter(ci -> ci.getUniqueId().equals(origInst.getUniqueId())).findAny();
879 if (op.isPresent()) {
880 ComponentInstance updatedCi = op.get();
881 updatedCi = buildComponentInstance(updatedCi, origInst);
883 Boolean isUniqueName = validateInstanceNameUniquenessUponUpdate(containerComponent, origInst, updatedCi.getName());
885 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());
886 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(), origInst.getName()));
888 listForUpdate.add(updatedCi);
890 listForUpdate.add(origInst);
892 containerComponent.setComponentInstances(listForUpdate);
894 Either<Component, StorageOperationStatus> updateStatus = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, componentFilter);
895 if (updateStatus.isRight()) {
896 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update metadata belonging to container component {}. Status is {}. ", containerComponent.getName(), updateStatus.right().value());
897 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(updateStatus.right().value(), true), "", null));
900 for (ComponentInstance updatedInstance : updateStatus.left().value().getComponentInstances()) {
901 Optional<ComponentInstance> op = componentInstanceList.stream().filter(ci -> ci.getName().equals(updatedInstance.getName())).findAny();
902 if (op.isPresent()) {
903 updatedList.add(updatedInstance);
908 }catch (ComponentException e){
913 unlockComponent(failed, containerComponent);
918 private boolean validateParent(org.openecomp.sdc.be.model.Component containerComponent, String nodeTemplateId) {
919 return containerComponent.getComponentInstances().stream().anyMatch(p -> p.getUniqueId().equals(nodeTemplateId));
922 private ComponentTypeEnum getComponentType(ComponentTypeEnum containerComponentType) {
923 if (ComponentTypeEnum.PRODUCT == containerComponentType) {
924 return ComponentTypeEnum.SERVICE_INSTANCE;
926 return ComponentTypeEnum.RESOURCE_INSTANCE;
930 private ComponentInstance updateComponentInstanceMetadata(Component containerComponent, ComponentTypeEnum containerComponentType, org.openecomp.sdc.be.model.Component origComponent, String componentInstanceId,
931 ComponentInstance componentInstance) {
933 Optional<ComponentInstance> componentInstanceOptional;
934 Either<ImmutablePair<Component, String>, StorageOperationStatus> updateRes = null;
935 ComponentInstance oldComponentInstance = null;
936 boolean isNameChanged = false;
938 componentInstanceOptional = containerComponent.getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(componentInstance.getUniqueId())).findFirst();
939 if (!componentInstanceOptional.isPresent()) {
940 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to find the component instance {} in container component {}. ", componentInstance.getName(), containerComponent.getName());
941 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName());
943 String oldComponentName;
944 oldComponentInstance = componentInstanceOptional.get();
945 oldComponentName = oldComponentInstance.getName();
946 String newInstanceName = componentInstance.getName();
947 if (oldComponentName != null && !oldComponentInstance.getName().equals(newInstanceName))
948 isNameChanged = true;
949 Boolean isUniqueName = validateInstanceNameUniquenessUponUpdate(containerComponent, oldComponentInstance, newInstanceName);
951 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);
952 throw new ByActionStatusComponentException(ActionStatus.COMPONENT_NAME_ALREADY_EXIST, containerComponentType.getValue(), componentInstance.getName());
954 if(!DirectivesEnum.isValid(componentInstance.getDirectives())) {
955 final String directivesStr =
956 componentInstance.getDirectives().stream().collect(Collectors.joining(" , ", " [ ", " ] "));
957 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG,
958 "Failed to update the directives of the component instance {} to {}. Directives data {} is invalid. ",
959 oldComponentInstance.getName(), newInstanceName ,
961 throw new ByActionStatusComponentException(ActionStatus.DIRECTIVES_INVALID_VALUE, containerComponentType.getValue(), componentInstance.getName()); }
962 updateRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent, origComponent, updateComponentInstanceMetadata(oldComponentInstance, componentInstance));
963 if (updateRes.isRight()) {
964 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to update metadata of component instance {} belonging to container component {}. Status is {}. ", componentInstance.getName(), containerComponent.getName(),
965 updateRes.right().value());
966 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormatForResourceInstance(componentsUtils.convertFromStorageResponseForResourceInstance(updateRes.right().value(), true), "", null));
968 // region - Update instance Groups
970 Either<StorageOperationStatus, StorageOperationStatus> result =
971 toscaOperationFacade.cleanAndAddGroupInstancesToComponentInstance(containerComponent, oldComponentInstance, componentInstanceId);
972 if (result.isRight())
973 CommonUtility.addRecordToLog(log, LogLevelEnum.DEBUG, "Failed to rename group instances for container {}. error {} ", componentInstanceId, result.right().value());
975 if (containerComponent instanceof Service){
976 Either<ComponentInstance, ResponseFormat> renameEither =
977 renameServiceFilter((Service) containerComponent, newInstanceName,
978 oldComponentInstance.getName());
979 if (renameEither.isRight()) {
980 throw new ByResponseFormatComponentException(renameEither.right().value());
983 updateForwardingPathDefinition(containerComponent, componentInstance, oldComponentName);
988 String newInstanceId = updateRes.left().value().getRight();
989 Optional<ComponentInstance> updatedInstanceOptional = updateRes.left().value().getLeft().getComponentInstances().stream().filter(ci -> ci.getUniqueId().equals(newInstanceId)).findFirst();
991 if (!updatedInstanceOptional.isPresent()) {
992 log.debug("Failed to update metadata of component instance {} of container component {}", componentInstance.getName(), containerComponent.getName());
993 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, componentInstance.getName()));
996 return componentInstanceOptional.get();
999 private void updateForwardingPathDefinition(Component containerComponent, ComponentInstance componentInstance, String oldComponentName) {
1000 Collection<ForwardingPathDataDefinition> forwardingPathDataDefinitions = getForwardingPathDataDefinitions(containerComponent.getUniqueId());
1001 Set<ForwardingPathDataDefinition> updated = new ForwardingPathUtils()
1002 .updateComponentInstanceName(forwardingPathDataDefinitions, oldComponentName,
1003 componentInstance.getName());
1004 updated.forEach(fp -> {
1005 Either<ForwardingPathDataDefinition, StorageOperationStatus> resultEither = forwardingPathOperation
1006 .updateForwardingPath(containerComponent.getUniqueId(), fp);
1007 if (resultEither.isRight()){
1008 CommonUtility.addRecordToLog(log, LogLevelEnum.ERROR, "Failed to rename forwarding path for container {}. error {} ",containerComponent.getName(), resultEither.right().value());
1014 public Either<ComponentInstance, ResponseFormat> renameServiceFilter(Service containerComponent,
1015 String newInstanceName, String oldInstanceName) {
1017 Map<String, CINodeFilterDataDefinition> renamedNodesFilter =
1018 ServiceFilterUtils.getRenamedNodesFilter((Service) containerComponent,
1019 oldInstanceName, newInstanceName);
1020 for( Entry<String, CINodeFilterDataDefinition> entry : renamedNodesFilter.entrySet()){
1021 Either<CINodeFilterDataDefinition, StorageOperationStatus>
1022 renameEither = nodeFilterOperation.updateNodeFilter(
1023 containerComponent.getUniqueId(),entry.getKey(),entry.getValue());
1024 if (renameEither.isRight()){
1025 return Either.right(componentsUtils.getResponseFormatForResourceInstance(
1026 componentsUtils.convertFromStorageResponse(renameEither.right().value(), ComponentTypeEnum.SERVICE),
1027 containerComponent.getName(), null));
1031 return Either.left(null);
1036 * The normalized old vf name
1037 * @param newNormailzedPrefix-
1038 * The normalized new vf name
1039 * @param qualifiedGroupInstanceName-
1040 * old Group Instance Name
1042 // modify group names
1043 private String getNewGroupName(String oldPrefix, String newNormailzedPrefix, String qualifiedGroupInstanceName) {
1044 if (qualifiedGroupInstanceName == null) {
1045 log.info("CANNOT change group name ");
1048 if (qualifiedGroupInstanceName.startsWith(oldPrefix) || qualifiedGroupInstanceName.startsWith(ValidationUtils.normalizeComponentInstanceName(oldPrefix)))
1049 return qualifiedGroupInstanceName.replaceFirst(oldPrefix, newNormailzedPrefix);
1050 return qualifiedGroupInstanceName;
1053 private ComponentInstance updateComponentInstanceMetadata(ComponentInstance oldComponentInstance, ComponentInstance newComponentInstance) {
1054 oldComponentInstance.setName(newComponentInstance.getName());
1055 oldComponentInstance.setModificationTime(System.currentTimeMillis());
1056 oldComponentInstance.setCustomizationUUID(UUID.randomUUID().toString());
1057 oldComponentInstance.setDirectives(newComponentInstance.getDirectives());
1058 if (oldComponentInstance.getGroupInstances() != null)
1059 oldComponentInstance.getGroupInstances().forEach(group -> group.setName(getNewGroupName(oldComponentInstance.getNormalizedName(), ValidationUtils.normalizeComponentInstanceName(newComponentInstance.getName()), group.getName())));
1060 return oldComponentInstance;
1063 public ComponentInstance deleteComponentInstance(final String containerComponentParam,
1064 final String containerComponentId,
1065 final String componentInstanceId, String userId)
1066 throws BusinessLogicException {
1068 validateUserExists(userId);
1069 final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
1071 final Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, null);
1072 validateCanWorkOnComponent(containerComponent, userId);
1074 boolean failed = false;
1075 final Optional<ComponentInstance> componentInstanceOptional = containerComponent.getComponentInstanceById(componentInstanceId);
1076 if (!componentInstanceOptional.isPresent()) {
1077 throw new BusinessLogicException(componentsUtils
1078 .getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND));
1080 ComponentInstance componentInstance = componentInstanceOptional.get();
1083 if (containerComponent instanceof Service || containerComponent instanceof Resource &&
1084 isVFC(componentInstance.getOriginType())) {
1086 final Either<String, StorageOperationStatus> deleteServiceFilterEither =
1087 nodeFilterOperation.deleteNodeFilter(containerComponent, componentInstanceId);
1088 if (deleteServiceFilterEither.isRight()) {
1089 final ActionStatus status = componentsUtils.convertFromStorageResponse(deleteServiceFilterEither.right().value(),
1090 containerComponentType);
1091 janusGraphDao.rollback();
1092 throw new ByResponseFormatComponentException(componentsUtils.getResponseFormat(status, componentInstanceId));
1094 final Either<ComponentInstance, ResponseFormat> resultOp = deleteNodeFiltersFromComponentInstance(
1095 containerComponent, componentInstance, containerComponentType, userId);
1096 if (resultOp.isRight()) {
1097 janusGraphDao.rollback();
1098 throw new ByResponseFormatComponentException(resultOp.right().value());
1101 lockComponent(containerComponent, "deleteComponentInstance");
1102 final ComponentInstance deletedCompInstance = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentType);
1104 componentInstance = deleteForwardingPathsRelatedTobeDeletedComponentInstance(containerComponentId,
1105 containerComponentType, deletedCompInstance);
1106 final ActionStatus onDeleteOperationsStatus = onChangeInstanceOperationOrchestrator.doOnDeleteInstanceOperations(containerComponent, componentInstanceId);
1107 if (ActionStatus.OK != onDeleteOperationsStatus) {
1108 throw new ByActionStatusComponentException(onDeleteOperationsStatus);
1110 } catch (final ComponentException e) {
1115 unlockComponent(failed, containerComponent);
1117 return componentInstance;
1120 public Either<ComponentInstance, ResponseFormat> deleteNodeFiltersFromComponentInstance(
1121 final Component component,
1122 final ComponentInstance componentInstance,
1123 final ComponentTypeEnum containerComponentType,
1124 final String userId) {
1126 final Set<String> componentFiltersIDsToBeDeleted =
1127 getComponentFiltersRelatedToComponentInstance(component.getUniqueId(), componentInstance);
1128 if (!componentFiltersIDsToBeDeleted.isEmpty()) {
1129 final Set<String> ids = component.getComponentInstances().stream()
1130 .filter(ci -> componentFiltersIDsToBeDeleted.contains(ci.getName()))
1131 .map(ComponentInstance::getUniqueId).collect(Collectors.toSet());
1132 final Either<Set<String>, StorageOperationStatus> deleteComponentNodeFiltersEither =
1133 nodeFilterOperation.deleteNodeFilters(component, ids);
1134 if (deleteComponentNodeFiltersEither.isRight()) {
1135 final ActionStatus status = componentsUtils
1136 .convertFromStorageResponse(deleteComponentNodeFiltersEither.right().value(),
1137 containerComponentType);
1138 return Either.right(componentsUtils.getResponseFormat(status, componentInstance.getName()));
1140 for (final String id : ids) {
1141 final Optional<ComponentInstance> componentInstanceById = component.getComponentInstanceById(id);
1142 if (!componentInstanceById.isPresent()) {
1143 return Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
1145 final ComponentInstance componentInstanceToBeUpdated = componentInstanceById.get();
1146 final List<String> directives = componentInstanceToBeUpdated.getDirectives();
1147 if (CollectionUtils.isNotEmpty(directives)) {
1148 directives.removeAll(directives);
1149 componentInstanceToBeUpdated.setDirectives(Collections.emptyList());
1151 final Either<ComponentInstance, ResponseFormat> componentInstanceResponseFormatEither =
1152 updateComponentInstanceMetadata(containerComponentType.getValue(), component.getUniqueId(),
1153 componentInstanceToBeUpdated.getUniqueId(), userId, componentInstanceToBeUpdated, true, false);
1154 if (componentInstanceResponseFormatEither.isRight()) {
1155 return componentInstanceResponseFormatEither;
1159 return Either.left(componentInstance);
1164 private Set<String> getComponentFiltersRelatedToComponentInstance(String containerComponentId,
1165 ComponentInstance componentInstance) {
1166 ComponentParametersView filter = new ComponentParametersView(true);
1167 filter.setIgnoreComponentInstances(false);
1168 Either<Component, StorageOperationStatus> componentFilterOrigin =
1169 toscaOperationFacade.getToscaElement(containerComponentId, filter);
1170 final Component component = componentFilterOrigin.left().value();
1171 final Set<String> nodesFiltersToBeDeleted = ComponentsUtils.getNodesFiltersToBeDeleted(component,
1173 return nodesFiltersToBeDeleted;
1177 ComponentInstance deleteForwardingPathsRelatedTobeDeletedComponentInstance(String containerComponentId,
1178 ComponentTypeEnum containerComponentType, ComponentInstance componentInstance) {
1179 if(containerComponentType == ComponentTypeEnum.SERVICE){
1180 List<String> pathIDsToBeDeleted = getForwardingPathsRelatedToComponentInstance(containerComponentId, componentInstance.getName());
1181 if (!pathIDsToBeDeleted.isEmpty()) {
1182 deleteForwardingPaths(containerComponentId, pathIDsToBeDeleted);
1185 return componentInstance;
1188 private void deleteForwardingPaths(String serviceId, List<String> pathIdsToDelete){
1190 Either<Service, StorageOperationStatus> storageStatus = toscaOperationFacade.getToscaElement(serviceId);
1191 if(storageStatus.isRight()) {
1192 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(storageStatus.right().value()));
1194 Either<Set<String>, StorageOperationStatus> result = forwardingPathOperation.deleteForwardingPath(storageStatus.left().value(),
1195 Sets.newHashSet(pathIdsToDelete));
1197 if(result.isRight()) {
1198 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(result.right().value()));
1202 private List<String> getForwardingPathsRelatedToComponentInstance(String containerComponentId, String componentInstanceId){
1203 Collection<ForwardingPathDataDefinition> allPaths = getForwardingPathDataDefinitions(containerComponentId);
1204 List<String> pathIDsToBeDeleted = new ArrayList<>();
1206 allPaths.stream().filter(path -> isPathRelatedToComponent(path,componentInstanceId ))
1207 .forEach(path -> pathIDsToBeDeleted.add(path.getUniqueId()));
1209 return pathIDsToBeDeleted;
1212 private Collection<ForwardingPathDataDefinition> getForwardingPathDataDefinitions(String containerComponentId) {
1213 ComponentParametersView filter = new ComponentParametersView(true);
1214 filter.setIgnoreForwardingPath(false);
1215 Either<Service, StorageOperationStatus> forwardingPathOrigin = toscaOperationFacade
1216 .getToscaElement(containerComponentId, filter);
1217 return forwardingPathOrigin.left().value().getForwardingPaths().values();
1220 private boolean isPathRelatedToComponent(ForwardingPathDataDefinition pathDataDefinition,
1221 String componentInstanceId){
1222 return pathDataDefinition.getPathElements().getListToscaDataDefinition()
1223 .stream().anyMatch(elementDataDefinition -> elementDataDefinition.getFromNode().equalsIgnoreCase(componentInstanceId) ||
1224 elementDataDefinition.getToNode()
1225 .equalsIgnoreCase(componentInstanceId));
1229 private ComponentInstance deleteComponentInstance(Component containerComponent, String componentInstanceId, ComponentTypeEnum containerComponentType) {
1230 Either<ImmutablePair<Component, String>, StorageOperationStatus> deleteRes = toscaOperationFacade.deleteComponentInstanceFromTopologyTemplate(containerComponent, componentInstanceId);
1231 if (deleteRes.isRight()) {
1232 log.debug("Failed to delete entry on graph for resourceInstance {}", componentInstanceId);
1233 ActionStatus status = componentsUtils.convertFromStorageResponse(deleteRes.right().value(), containerComponentType);
1234 throw new ByActionStatusComponentException(status, componentInstanceId);
1236 log.debug("The component instance {} has been removed from container component {}. ", componentInstanceId, containerComponent);
1237 ComponentInstance deletedInstance = findAndRemoveComponentInstanceFromContainerComponent(componentInstanceId, containerComponent);
1239 if (CollectionUtils.isNotEmpty(containerComponent.getInputs())) {
1240 List<InputDefinition> inputsToDelete = containerComponent.getInputs().stream().filter(i -> i.getInstanceUniqueId() != null && i.getInstanceUniqueId().equals(componentInstanceId)).collect(Collectors.toList());
1241 if (CollectionUtils.isNotEmpty(inputsToDelete)) {
1242 StorageOperationStatus deleteInputsRes = toscaOperationFacade.deleteComponentInstanceInputsFromTopologyTemplate(containerComponent, inputsToDelete);
1243 if (deleteInputsRes != StorageOperationStatus.OK) {
1244 log.debug("Failed to delete inputs of the component instance {} from container component. ", componentInstanceId);
1245 throw new ByActionStatusComponentException(
1246 componentsUtils.convertFromStorageResponse(deleteInputsRes, containerComponentType), componentInstanceId);
1250 return deletedInstance;
1253 private ComponentInstance findAndRemoveComponentInstanceFromContainerComponent(String componentInstanceId, Component containerComponent) {
1254 ComponentInstance foundInstance = null;
1255 for (ComponentInstance instance : containerComponent.getComponentInstances()) {
1256 if (instance.getUniqueId().equals(componentInstanceId)) {
1257 foundInstance = instance;
1258 containerComponent.getComponentInstances().remove(instance);
1262 findAndRemoveComponentInstanceRelations(componentInstanceId, containerComponent);
1263 return foundInstance;
1266 private void findAndRemoveComponentInstanceRelations(String componentInstanceId, Component containerComponent) {
1267 if(CollectionUtils.isNotEmpty(containerComponent.getComponentInstancesRelations())){
1268 containerComponent.setComponentInstancesRelations(containerComponent.getComponentInstancesRelations().stream().filter(r -> isNotBelongingRelation(componentInstanceId, r)).collect(Collectors.toList()));
1272 private boolean isNotBelongingRelation(String componentInstanceId, RequirementCapabilityRelDef relation) {
1273 return !relation.getToNode().equals(componentInstanceId) && !relation.getFromNode().equals(componentInstanceId);
1276 public RequirementCapabilityRelDef associateRIToRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum) {
1277 return associateRIToRI(componentId, userId, requirementDef, componentTypeEnum, false, true);
1280 public RequirementCapabilityRelDef associateRIToRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum, boolean inTransaction, boolean needLock) {
1282 validateUserExists(userId);
1284 RequirementCapabilityRelDef requirementCapabilityRelDef = null;
1286 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(componentId, componentTypeEnum, null);
1288 validateCanWorkOnComponent(containerComponent, userId);
1289 boolean failed = false;
1292 lockComponent(containerComponent, "associateRIToRI");
1294 requirementCapabilityRelDef = associateRIToRIOnGraph(containerComponent, requirementDef);
1295 }catch (ComponentException e){
1300 unlockComponent(failed, containerComponent);
1302 return requirementCapabilityRelDef;
1305 public RequirementCapabilityRelDef associateRIToRIOnGraph(Component containerComponent, RequirementCapabilityRelDef requirementDef) {
1307 log.debug(TRY_TO_CREATE_ENTRY_ON_GRAPH);
1309 Either<RequirementCapabilityRelDef, StorageOperationStatus> result = toscaOperationFacade.associateResourceInstances(null, containerComponent.getUniqueId(), requirementDef);
1311 if (result.isLeft()) {
1312 log.debug(ENTITY_ON_GRAPH_IS_CREATED);
1313 RequirementCapabilityRelDef requirementCapabilityRelDef = result.left().value();
1314 return requirementCapabilityRelDef;
1317 log.debug("Failed to associate node: {} with node {}", requirementDef.getFromNode(), requirementDef.getToNode());
1318 String fromNameOrId = "";
1319 String toNameOrId = "";
1320 Either<ComponentInstance, StorageOperationStatus> fromResult = getResourceInstanceById(containerComponent, requirementDef.getFromNode());
1321 Either<ComponentInstance, StorageOperationStatus> toResult = getResourceInstanceById(containerComponent, requirementDef.getToNode());
1323 toNameOrId = requirementDef.getFromNode();
1324 fromNameOrId = requirementDef.getFromNode();
1325 if (fromResult.isLeft()) {
1326 fromNameOrId = fromResult.left().value().getName();
1328 if (toResult.isLeft()) {
1329 toNameOrId = toResult.left().value().getName();
1332 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponseForResourceInstance
1333 (result.right().value(), true), fromNameOrId, toNameOrId,
1334 requirementDef.getRelationships().get(0).getRelation().getRequirement());
1340 * @param componentId
1342 * @param requirementDefList
1343 * @param componentTypeEnum
1346 public List<RequirementCapabilityRelDef> batchDissociateRIFromRI(
1349 List<RequirementCapabilityRelDef> requirementDefList,
1350 ComponentTypeEnum componentTypeEnum) {
1352 validateUserExists(userId);
1353 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(componentId, componentTypeEnum, null);
1354 validateCanWorkOnComponent(containerComponent, userId);
1355 boolean failed = false;
1356 List<RequirementCapabilityRelDef> delOkResult = new ArrayList<>();
1358 lockComponent(containerComponent, "associateRIToRI");
1359 for (RequirementCapabilityRelDef requirementDef : requirementDefList) {
1360 RequirementCapabilityRelDef requirementCapabilityRelDef = dissociateRIFromRI(
1361 componentId, userId, requirementDef, containerComponent.getComponentType());
1362 delOkResult.add(requirementCapabilityRelDef);
1364 }catch (ComponentException e){
1368 unlockComponent(failed, containerComponent);
1374 public RequirementCapabilityRelDef dissociateRIFromRI(String componentId, String userId, RequirementCapabilityRelDef requirementDef, ComponentTypeEnum componentTypeEnum) {
1375 validateUserExists(userId);
1377 Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null;
1378 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(componentId, componentTypeEnum, null);
1380 validateCanWorkOnComponent(containerComponent, userId);
1381 boolean failed = false;
1383 lockComponent(containerComponent, "associateRIToRI");
1384 log.debug(TRY_TO_CREATE_ENTRY_ON_GRAPH);
1385 Either<RequirementCapabilityRelDef, StorageOperationStatus> result = toscaOperationFacade.dissociateResourceInstances(componentId, requirementDef);
1386 if (result.isLeft()) {
1387 log.debug(ENTITY_ON_GRAPH_IS_CREATED);
1388 return result.left().value();
1391 log.debug("Failed to dissocaite node {} from node {}", requirementDef.getFromNode(), requirementDef.getToNode());
1392 String fromNameOrId = "";
1393 String toNameOrId = "";
1394 Either<ComponentInstance, StorageOperationStatus> fromResult = getResourceInstanceById(containerComponent, requirementDef.getFromNode());
1395 Either<ComponentInstance, StorageOperationStatus> toResult = getResourceInstanceById(containerComponent, requirementDef.getToNode());
1397 toNameOrId = requirementDef.getFromNode();
1398 fromNameOrId = requirementDef.getFromNode();
1399 if (fromResult.isLeft()) {
1400 fromNameOrId = fromResult.left().value().getName();
1402 if (toResult.isLeft()) {
1403 toNameOrId = toResult.left().value().getName();
1406 throw new ByActionStatusComponentException(
1407 componentsUtils.convertFromStorageResponseForResourceInstance(result.right().value(), true),
1408 fromNameOrId, toNameOrId, requirementDef.getRelationships().get(0).getRelation().getRequirement());
1410 }catch (ComponentException e){
1414 unlockComponent(failed, containerComponent);
1418 * Allows to get relation contained in specified component according to received Id
1419 * @param componentId
1422 * @param componentTypeEnum
1425 public Either<RequirementCapabilityRelDef, ResponseFormat> getRelationById(String componentId, String relationId, String userId, ComponentTypeEnum componentTypeEnum) {
1427 Either<RequirementCapabilityRelDef, ResponseFormat> resultOp = null;
1429 org.openecomp.sdc.be.model.Component containerComponent = null;
1430 Either<org.openecomp.sdc.be.model.Component, ResponseFormat> validateComponentExists = null;
1431 RequirementCapabilityRelDef foundRelation = null;
1433 validateUserExists(userId);
1434 containerComponent = validateComponentExists(componentId, componentTypeEnum, null);
1435 List<RequirementCapabilityRelDef> requirementCapabilityRelations = containerComponent.getComponentInstancesRelations();
1436 foundRelation = findRelation(relationId, requirementCapabilityRelations);
1437 if(foundRelation == null){
1438 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.RELATION_NOT_FOUND, relationId, componentId);
1439 log.debug("Relation with id {} was not found on the component", relationId, componentId);
1440 resultOp = Either.right(responseFormat);
1442 if(resultOp == null){
1443 resultOp = setRelatedCapability(foundRelation, containerComponent);
1445 if(resultOp.isLeft()){
1446 resultOp = setRelatedRequirement(foundRelation, containerComponent);
1448 } catch (Exception e) {
1449 log.error("The exception {} occured upon get relation {} of the component {} ", e, relationId, componentId);
1450 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.GENERAL_ERROR));
1455 private RequirementCapabilityRelDef findRelation(String relationId, List<RequirementCapabilityRelDef> requirementCapabilityRelations) {
1456 for(RequirementCapabilityRelDef relationship : requirementCapabilityRelations){
1457 if(relationship.getRelationships().stream().filter(r -> r.getRelation().getId().equals(relationId)).findFirst().isPresent()){
1458 return relationship;
1464 private Either<RequirementCapabilityRelDef, ResponseFormat> setRelatedRequirement(RequirementCapabilityRelDef foundRelation, Component containerComponent) {
1465 Either<RequirementCapabilityRelDef, ResponseFormat> result = null;
1466 RelationshipInfo relationshipInfo = foundRelation.resolveSingleRelationship().getRelation();
1467 String instanceId = foundRelation.getFromNode();
1468 Optional<RequirementDefinition> foundRequirement;
1469 Optional<ComponentInstance> instance = containerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst();
1470 if(!instance.isPresent()){
1471 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, instanceId, "instance", containerComponent.getComponentType().getValue(), containerComponent.getName());
1472 log.debug("Component instance with id {} was not found on the component", instanceId, containerComponent.getUniqueId());
1473 result = Either.right(responseFormat);
1476 for(List<RequirementDefinition> requirements : instance.get().getRequirements().values()){
1477 foundRequirement = requirements.stream().filter(r -> isBelongingCalcRequirement(relationshipInfo, r, containerComponent.getLifecycleState())).findFirst();
1478 if(foundRequirement.isPresent()){
1479 foundRelation.resolveSingleRelationship().setRequirement(foundRequirement.get());
1480 result = Either.left(foundRelation);
1485 Either<RequirementDataDefinition, StorageOperationStatus> getfulfilledRequirementRes = toscaOperationFacade.getFulfilledRequirementByRelation(containerComponent.getUniqueId(), instanceId, foundRelation, this::isBelongingFullRequirement);
1486 if(getfulfilledRequirementRes.isRight()){
1487 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.REQUIREMENT_OF_INSTANCE_NOT_FOUND_ON_CONTAINER, relationshipInfo.getRequirement(), instanceId, containerComponent.getUniqueId());
1488 log.debug("Requirement {} of instance {} was not found on the container {}. ", relationshipInfo.getCapability(), instanceId, containerComponent.getUniqueId());
1489 result = Either.right(responseFormat);
1491 foundRelation.resolveSingleRelationship().setRequirement(getfulfilledRequirementRes.left().value());
1495 result = Either.left(foundRelation);
1500 private boolean isBelongingFullRequirement(RelationshipInfo relationshipInfo, RequirementDataDefinition req) {
1501 return req.getName().equals(relationshipInfo.getRequirement()) &&
1502 req.getUniqueId().equals(relationshipInfo.getRequirementUid()) &&
1503 req.getOwnerId().equals(relationshipInfo.getRequirementOwnerId());
1506 private boolean isBelongingCalcRequirement(RelationshipInfo relationshipInfo, RequirementDataDefinition req, LifecycleStateEnum state) {
1507 return nameMatches(relationshipInfo.getRequirement(), req.getName(), req.getPreviousName(), state) &&
1508 req.getUniqueId().equals(relationshipInfo.getRequirementUid()) &&
1509 req.getOwnerId().equals(relationshipInfo.getRequirementOwnerId());
1512 private Either<RequirementCapabilityRelDef, ResponseFormat> setRelatedCapability(RequirementCapabilityRelDef foundRelation, Component containerComponent) {
1513 Either<RequirementCapabilityRelDef, ResponseFormat> result = null;
1514 RelationshipInfo relationshipInfo = foundRelation.resolveSingleRelationship().getRelation();
1515 String instanceId = foundRelation.getToNode();
1516 Optional<CapabilityDefinition> foundCapability;
1517 Optional<ComponentInstance> instance = containerComponent.getComponentInstances().stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst();
1518 if(!instance.isPresent()){
1519 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER, instanceId, "instance", containerComponent.getComponentType().getValue(), containerComponent.getName());
1520 log.debug("Component instance with id {} was not found on the component", instanceId, containerComponent.getUniqueId());
1521 result = Either.right(responseFormat);
1524 for(List<CapabilityDefinition> capabilities : instance.get().getCapabilities().values()){
1525 foundCapability = capabilities.stream().filter(c -> isBelongingCalcCapability(relationshipInfo, c, containerComponent.getLifecycleState())).findFirst();
1526 if(foundCapability.isPresent()){
1527 foundRelation.resolveSingleRelationship().setCapability(foundCapability.get());
1528 result = Either.left(foundRelation);
1533 Either<CapabilityDataDefinition, StorageOperationStatus> getfulfilledRequirementRes =
1534 toscaOperationFacade.getFulfilledCapabilityByRelation(containerComponent.getUniqueId(), instanceId, foundRelation, this::isBelongingFullCapability);
1535 if(getfulfilledRequirementRes.isRight()){
1536 ResponseFormat responseFormat = componentsUtils.getResponseFormat(ActionStatus.CAPABILITY_OF_INSTANCE_NOT_FOUND_ON_CONTAINER, relationshipInfo.getCapability(), instanceId, containerComponent.getUniqueId());
1537 log.debug("Capability {} of instance {} was not found on the container {}. ", relationshipInfo.getCapability(), instanceId, containerComponent.getUniqueId());
1538 result = Either.right(responseFormat);
1540 foundRelation.resolveSingleRelationship().setCapability(getfulfilledRequirementRes.left().value());
1544 result = Either.left(foundRelation);
1549 private boolean isBelongingFullCapability(RelationshipInfo relationshipInfo, CapabilityDataDefinition cap) {
1550 return cap.getName().equals(relationshipInfo.getCapability()) &&
1551 cap.getUniqueId().equals(relationshipInfo.getCapabilityUid()) &&
1552 cap.getOwnerId().equals(relationshipInfo.getCapabilityOwnerId());
1555 private boolean isBelongingCalcCapability(RelationshipInfo relationshipInfo, CapabilityDataDefinition cap, LifecycleStateEnum state) {
1556 return nameMatches(relationshipInfo.getCapability(), cap.getName(), cap.getPreviousName(), state) &&
1557 cap.getUniqueId().equals(relationshipInfo.getCapabilityUid()) &&
1558 cap.getOwnerId().equals(relationshipInfo.getCapabilityOwnerId());
1561 private boolean nameMatches(String nameFromRelationship, String currName, String previousName, LifecycleStateEnum state) {
1562 return state == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT ?
1563 currName.equals(nameFromRelationship):
1564 previousName!= null && previousName.equals(nameFromRelationship);
1567 private Either<ComponentInstanceProperty, ResponseFormat> updateAttributeValue(ComponentInstanceProperty attribute, String resourceInstanceId) {
1568 Either<ComponentInstanceProperty, StorageOperationStatus> eitherAttribute = componentInstanceOperation.updateAttributeValueInResourceInstance(attribute, resourceInstanceId, true);
1569 Either<ComponentInstanceProperty, ResponseFormat> result;
1570 if (eitherAttribute.isLeft()) {
1571 log.debug("Attribute value {} was updated on graph.", attribute.getValueUniqueUid());
1572 ComponentInstanceProperty instanceAttribute = eitherAttribute.left().value();
1574 result = Either.left(instanceAttribute);
1577 log.debug("Failed to update attribute value {} in resource instance {}", attribute, resourceInstanceId);
1579 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(eitherAttribute.right().value());
1581 result = Either.right(componentsUtils.getResponseFormat(actionStatus, ""));
1587 private Either<ComponentInstanceProperty, ResponseFormat> createAttributeValue(ComponentInstanceProperty attribute, String resourceInstanceId) {
1589 Either<ComponentInstanceProperty, ResponseFormat> result;
1591 Wrapper<Integer> indexCounterWrapper = new Wrapper<>();
1592 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
1593 validateIncrementCounter(resourceInstanceId, GraphPropertiesDictionary.ATTRIBUTE_COUNTER, indexCounterWrapper, errorWrapper);
1595 if (!errorWrapper.isEmpty()) {
1596 result = Either.right(errorWrapper.getInnerElement());
1598 Either<ComponentInstanceProperty, StorageOperationStatus> eitherAttribute = componentInstanceOperation.addAttributeValueToResourceInstance(attribute, resourceInstanceId, indexCounterWrapper.getInnerElement(), true);
1599 if (eitherAttribute.isLeft()) {
1600 log.debug("Attribute value was added to resource instance {}", resourceInstanceId);
1601 ComponentInstanceProperty instanceAttribute = eitherAttribute.left().value();
1602 result = Either.left(instanceAttribute);
1605 log.debug("Failed to add attribute value {} to resource instance {}", attribute, resourceInstanceId);
1607 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(eitherAttribute.right().value());
1608 result = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1616 * Create Or Updates Attribute Instance
1618 * @param componentTypeEnum
1619 * @param componentId
1620 * @param resourceInstanceId
1625 public Either<ComponentInstanceProperty, ResponseFormat> createOrUpdateAttributeValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, ComponentInstanceProperty attribute, String userId) {
1626 Either<ComponentInstanceProperty, ResponseFormat> result = null;
1627 Wrapper<ResponseFormat> errorWrapper = new Wrapper<>();
1629 validateUserExists(userId);
1630 if (errorWrapper.isEmpty()) {
1631 validateComponentTypeEnum(componentTypeEnum, "CreateOrUpdateAttributeValue", errorWrapper);
1633 if (errorWrapper.isEmpty()) {
1634 validateCanWorkOnComponent(componentId, componentTypeEnum, userId, errorWrapper);
1636 if (errorWrapper.isEmpty()) {
1637 validateComponentLock(componentId, componentTypeEnum, errorWrapper);
1641 if (errorWrapper.isEmpty()) {
1642 final boolean isCreate = Objects.isNull(attribute.getValueUniqueUid());
1644 result = createAttributeValue(attribute, resourceInstanceId);
1646 result = updateAttributeValue(attribute, resourceInstanceId);
1649 result = Either.right(errorWrapper.getInnerElement());
1655 if (result == null || result.isRight()) {
1656 janusGraphDao.rollback();
1658 janusGraphDao.commit();
1661 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
1665 public Either<List<ComponentInstanceProperty>, ResponseFormat> createOrUpdatePropertiesValues(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, List<ComponentInstanceProperty> properties, String userId) {
1667 Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
1669 /*-------------------------------Validations---------------------------------*/
1670 validateUserExists(userId);
1672 if (componentTypeEnum == null) {
1673 BeEcompErrorManager.getInstance().logInvalidInputError("CreateOrUpdatePropertiesValues", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
1674 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
1677 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
1679 if (getResourceResult.isRight()) {
1680 log.debug(FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID, componentId);
1681 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getResourceResult.right().value(), componentTypeEnum);
1682 return Either.right(componentsUtils.getResponseFormat(actionStatus, componentId));
1684 Component containerComponent = getResourceResult.left().value();
1686 if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
1687 if (containerComponent.isArchived()) {
1688 log.info("Component is archived. Component id: {}", componentId);
1689 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_IS_ARCHIVED, containerComponent.getName()));
1691 log.info("Restricted operation for user: {} on service {}", userId, componentId);
1692 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1695 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId);
1696 if (resourceInstanceStatus.isRight()) {
1697 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER,
1698 resourceInstanceId, "resource instance", "service", componentId));
1700 ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
1703 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
1704 if (lockStatus != StorageOperationStatus.OK) {
1705 log.debug(FAILED_TO_LOCK_SERVICE, componentId);
1706 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
1708 List <ComponentInstanceProperty> updatedProperties = new ArrayList<>();
1710 for (ComponentInstanceProperty property: properties) {
1711 validateMandatoryFields(property);
1712 ComponentInstanceProperty componentInstanceProperty = validatePropertyExistsOnComponent(property, containerComponent, foundResourceInstance);
1713 String propertyParentUniqueId = property.getParentUniqueId();
1714 Either<String, ResponseFormat> updatedPropertyValue = updatePropertyObjectValue(property, false);
1715 if (updatedPropertyValue.isRight()) {
1716 log.error("Failed to update property object value of property: {}",
1718 throw new ByResponseFormatComponentException(updatedPropertyValue.right().value());
1720 Optional<CapabilityDefinition>
1721 capPropDefinition = getPropertyCapabilityOfChildInstance(propertyParentUniqueId, foundResourceInstance.getCapabilities());
1722 if (capPropDefinition.isPresent()) {
1723 updatedPropertyValue
1724 .bimap(updatedValue -> updateCapabilityPropFromUpdateInstProp(property, updatedValue,
1725 containerComponent, foundResourceInstance, capPropDefinition.get().getType(),
1726 capPropDefinition.get().getName()), Either::right);
1728 updatedPropertyValue.bimap(
1730 componentInstanceProperty.setValue(updatedValue);
1731 return updatePropertyOnContainerComponent(property, updatedValue,
1732 containerComponent, foundResourceInstance);
1734 updatedProperties.add(componentInstanceProperty);
1738 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
1739 if (updateContainerRes.isRight()) {
1740 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
1741 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
1744 resultOp = Either.left(updatedProperties);
1748 if (resultOp == null || resultOp.isRight()) {
1749 janusGraphDao.rollback();
1751 janusGraphDao.commit();
1754 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
1758 private void validateMandatoryFields(PropertyDataDefinition property) {
1759 if (StringUtils.isEmpty(property.getName())) {
1760 throw new ByActionStatusComponentException (ActionStatus.MISSING_PROPERTY_NAME);
1764 private ComponentInstanceProperty validatePropertyExistsOnComponent(ComponentInstanceProperty property, Component containerComponent, ComponentInstance foundResourceInstance) {
1765 List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties().get(foundResourceInstance.getUniqueId());
1766 Optional<ComponentInstanceProperty> instanceProperty = instanceProperties.stream().filter(p -> p.getName().equals(property.getName())).findAny();
1767 if (!instanceProperty.isPresent()) {
1768 throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND, property.getName());
1770 return instanceProperty.get();
1775 private ResponseFormat updateCapabilityPropertyOnContainerComponent(ComponentInstanceProperty property,
1776 String newValue, Component containerComponent, ComponentInstance foundResourceInstance,
1777 String capabilityType, String capabilityName) {
1778 String componentInstanceUniqueId = foundResourceInstance.getUniqueId();
1779 ResponseFormat actionStatus = updateCapPropOnContainerComponent(property, newValue, containerComponent,
1780 foundResourceInstance, capabilityType, capabilityName, componentInstanceUniqueId);
1781 if (actionStatus != null) {
1782 return actionStatus;
1785 return componentsUtils.getResponseFormat(ActionStatus.OK);
1788 private ResponseFormat updateCapabilityPropFromUpdateInstProp(ComponentInstanceProperty property,
1789 String newValue, Component containerComponent,
1790 ComponentInstance foundResourceInstance,
1791 String capabilityType, String capabilityName) {
1792 String componentInstanceUniqueId = foundResourceInstance.getUniqueId();
1793 Either<Component, StorageOperationStatus> getComponentRes =
1794 toscaOperationFacade.getToscaFullElement(foundResourceInstance.getComponentUid());
1795 if(getComponentRes.isRight()) {
1796 return componentsUtils.getResponseFormat(getComponentRes.right().value());
1799 if(!PropertiesUtils.isNodeServiceProxy(getComponentRes.left().value())) {
1800 propOwner = componentInstanceUniqueId;
1802 propOwner = foundResourceInstance.getSourceModelUid();
1805 ResponseFormat actionStatus = updateCapPropOnContainerComponent(property, newValue, containerComponent,
1806 foundResourceInstance, capabilityType, capabilityName, componentInstanceUniqueId);
1807 if (actionStatus != null) {
1808 return actionStatus;
1811 return componentsUtils.getResponseFormat(ActionStatus.OK);
1814 private ResponseFormat updateCapPropOnContainerComponent(ComponentInstanceProperty property, String newValue,
1815 Component containerComponent,
1816 ComponentInstance foundResourceInstance,
1817 String capabilityType, String capabilityName,
1818 String componentInstanceUniqueId) {
1819 Map<String, List<CapabilityDefinition>> capabilities =
1820 Optional.ofNullable(foundResourceInstance.getCapabilities()).orElse(Collections.emptyMap());
1821 List<CapabilityDefinition> capPerType =
1822 Optional.ofNullable(capabilities.get(capabilityType)).orElse(Collections.EMPTY_LIST);
1823 Optional<CapabilityDefinition> cap =
1824 capPerType.stream().filter(c -> c.getName().equals(capabilityName)).findAny();
1825 if (cap.isPresent()) {
1826 List<ComponentInstanceProperty> capProperties = cap.get().getProperties();
1827 if (capProperties != null) {
1828 Optional<ComponentInstanceProperty> instanceProperty =
1829 capProperties.stream().filter(p -> p.getUniqueId().equals(property.getUniqueId())).findAny();
1830 StorageOperationStatus status;
1831 if (instanceProperty.isPresent()) {
1832 String capKey = ModelConverter.buildCapabilityPropertyKey(foundResourceInstance.getOriginType().isAtomicType(), capabilityType, capabilityName, componentInstanceUniqueId, cap.get());
1833 instanceProperty.get().setValue(newValue);
1834 List<String> path = new ArrayList<>();
1835 path.add(componentInstanceUniqueId);
1837 instanceProperty.get().setPath(path);
1838 status = toscaOperationFacade.updateComponentInstanceCapabiltyProperty(containerComponent,
1839 componentInstanceUniqueId, capKey, instanceProperty.get());
1840 if (status != StorageOperationStatus.OK) {
1841 ActionStatus actionStatus =
1842 componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
1843 return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
1846 foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
1853 private ResponseFormat updatePropertyOnContainerComponent(ComponentInstanceProperty instanceProperty, String newValue, Component containerComponent, ComponentInstance foundResourceInstance) {
1854 StorageOperationStatus status;
1855 instanceProperty.setValue(newValue);
1856 status = toscaOperationFacade.updateComponentInstanceProperty(containerComponent, foundResourceInstance.getUniqueId(), instanceProperty);
1857 if (status != StorageOperationStatus.OK) {
1858 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
1859 return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
1861 foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
1862 return componentsUtils.getResponseFormat(ActionStatus.OK);
1865 private <T extends PropertyDefinition> Either<String,ResponseFormat> validatePropertyObjectValue(T property, String newValue, boolean isInput) {
1866 Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypesEither = dataTypeCache.getAll();
1867 if (allDataTypesEither.isRight()) {
1868 JanusGraphOperationStatus status = allDataTypesEither.right().value();
1869 BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
1870 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status))));
1872 Map<String, DataTypeDefinition> allDataTypes = allDataTypesEither.left().value();
1873 String propertyType = property.getType();
1874 String innerType = getInnerType(property);
1876 // Specific Update Logic
1877 Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(property.getType(), newValue, true, innerType, allDataTypes);
1878 if (isValid.isRight()) {
1879 Boolean res = isValid.right().value();
1881 log.error("Invalid value {} of property {} ", newValue, property.getName());
1882 return Either.right(componentsUtils.getResponseFormat(ActionStatus.INVALID_CONTENT));
1885 Object object = isValid.left().value();
1886 if (object != null) {
1887 newValue = object.toString();
1890 if (validateAndUpdateRules(property, isInput, allDataTypes, innerType, propertyType))
1891 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT))));
1892 return Either.left(newValue);
1895 private <T extends PropertyDefinition> boolean validateAndUpdateRules(T property, boolean isInput, Map<String, DataTypeDefinition> allDataTypes, String innerType, String propertyType) {
1897 ImmutablePair<String, Boolean> pair = propertyOperation.validateAndUpdateRules(propertyType, ((ComponentInstanceProperty) property).getRules(), innerType, allDataTypes, true);
1898 if (pair.getRight() != null && !pair.getRight()) {
1899 BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), property.getName(), propertyType);
1906 private <T extends PropertyDefinition> Either<String,ResponseFormat> updatePropertyObjectValue(T property, boolean isInput) {
1907 Either<Map<String, DataTypeDefinition>, JanusGraphOperationStatus> allDataTypesEither = dataTypeCache.getAll();
1908 if (allDataTypesEither.isRight()) {
1909 JanusGraphOperationStatus status = allDataTypesEither.right().value();
1910 BeEcompErrorManager.getInstance().logInternalFlowError("UpdatePropertyValueOnComponentInstance", "Failed to update property value on instance. Status is " + status, ErrorSeverity.ERROR);
1911 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(status))));
1913 Map<String, DataTypeDefinition> allDataTypes = allDataTypesEither.left().value();
1914 String innerType = null;
1915 String propertyType = property.getType();
1916 ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
1917 log.debug("The type of the property {} is {}", property.getUniqueId(), propertyType);
1919 if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
1920 SchemaDefinition def = property.getSchema();
1922 log.debug("Schema doesn't exists for property of type {}", type);
1923 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
1925 PropertyDataDefinition propDef = def.getProperty();
1926 if (propDef == null) {
1927 log.debug("Property in Schema Definition inside property of type {} doesn't exist", type);
1928 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
1930 innerType = propDef.getType();
1932 // Specific Update Logic
1933 Either<Object, Boolean> isValid = propertyOperation.validateAndUpdatePropertyValue(propertyType, property.getValue(), true, innerType, allDataTypes);
1934 String newValue = property.getValue();
1935 if (isValid.isRight()) {
1936 Boolean res = isValid.right().value();
1938 log.debug("validate and update property value has failed with value: {}", property.getValue());
1939 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT)));
1942 Object object = isValid.left().value();
1943 if (object != null) {
1944 newValue = object.toString();
1948 ImmutablePair<String, Boolean> pair = propertyOperation.validateAndUpdateRules(propertyType, ((ComponentInstanceProperty) property).getRules(), innerType, allDataTypes, true);
1949 if (pair.getRight() != null && pair.getRight() == false) {
1950 BeEcompErrorManager.getInstance().logBeInvalidValueError("Add property value", pair.getLeft(), property.getName(), propertyType);
1951 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(DaoStatusConverter.convertJanusGraphStatusToStorageStatus(JanusGraphOperationStatus.ILLEGAL_ARGUMENT))));
1954 return Either.left(newValue);
1957 private ResponseFormat updateInputOnContainerComponent(ComponentInstanceInput input, String newValue, Component containerComponent, ComponentInstance foundResourceInstance) {
1958 StorageOperationStatus status;
1959 input.setValue(newValue);
1960 status = toscaOperationFacade.updateComponentInstanceInput(containerComponent, foundResourceInstance.getUniqueId(), input);
1961 if (status != StorageOperationStatus.OK) {
1962 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
1963 return componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, "");
1965 foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
1966 return componentsUtils.getResponseFormat(ActionStatus.OK);
1969 public Either<List<ComponentInstanceInput>, ResponseFormat> createOrUpdateInstanceInputValues(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, List<ComponentInstanceInput> inputs, String userId) {
1971 Either<List<ComponentInstanceInput>, ResponseFormat> resultOp = null;
1973 validateUserExists(userId);
1975 if (componentTypeEnum == null) {
1976 BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_OR_UPDATE_PROPERTY_VALUE, INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
1977 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
1980 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
1982 if (getResourceResult.isRight()) {
1983 log.debug(FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID, componentId);
1984 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getResourceResult.right().value(), componentTypeEnum);
1985 return Either.right(componentsUtils.getResponseFormat(actionStatus, componentId));
1987 Component containerComponent = getResourceResult.left().value();
1989 if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
1990 if (containerComponent.isArchived()) {
1991 log.info("Component is archived. Component id: {}", componentId);
1992 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_IS_ARCHIVED, containerComponent.getName()));
1994 log.info("Restricted operation for user: {} on service {}", userId, componentId);
1995 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
1998 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId);
1999 if (resourceInstanceStatus.isRight()) {
2000 return Either.right(componentsUtils.getResponseFormat(ActionStatus.COMPONENT_INSTANCE_NOT_FOUND_ON_CONTAINER,
2001 resourceInstanceId, "resource instance", "service", componentId));
2004 ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
2007 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
2008 if (lockStatus != StorageOperationStatus.OK) {
2009 log.debug(FAILED_TO_LOCK_SERVICE, componentId);
2010 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
2012 List <ComponentInstanceInput> updatedInputs = new ArrayList<>();
2014 for (ComponentInstanceInput input: inputs) {
2015 validateMandatoryFields(input);
2016 ComponentInstanceInput componentInstanceInput = validateInputExistsOnComponent(input, containerComponent, foundResourceInstance);
2017 Either<String, ResponseFormat> validatedInputValue = validatePropertyObjectValue(componentInstanceInput, input.getValue(), true);
2018 if (validatedInputValue.isRight()){
2019 throw new ByActionStatusComponentException(ActionStatus.INVALID_CONTENT, input.getName());
2021 updateInputOnContainerComponent(componentInstanceInput, validatedInputValue.left().value(), containerComponent, foundResourceInstance);
2022 updatedInputs.add(componentInstanceInput);
2024 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
2025 if (updateContainerRes.isRight()) {
2026 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
2027 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2030 resultOp = Either.left(updatedInputs);
2034 if (resultOp == null || resultOp.isRight()) {
2035 janusGraphDao.rollback();
2037 janusGraphDao.commit();
2040 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
2045 private ComponentInstanceInput validateInputExistsOnComponent(ComponentInstanceInput input, Component containerComponent, ComponentInstance foundResourceInstance) {
2046 List<ComponentInstanceInput> instanceProperties = containerComponent.getComponentInstancesInputs().get(foundResourceInstance.getUniqueId());
2047 Optional<ComponentInstanceInput> instanceInput = instanceProperties.stream().filter(p -> p.getName().equals(input.getName())).findAny();
2048 if (!instanceInput.isPresent()) {
2049 throw new ByActionStatusComponentException(ActionStatus.PROPERTY_NOT_FOUND, input.getName());
2051 return instanceInput.get();
2054 public Either<ComponentInstanceProperty, ResponseFormat> createOrUpdateGroupInstancePropertyValue(ComponentTypeEnum componentTypeEnum, String componentId, String resourceInstanceId, String groupInstanceId, ComponentInstanceProperty property, String userId) {
2056 Either<ComponentInstanceProperty, ResponseFormat> resultOp = null;
2058 validateUserExists(userId);
2060 if (componentTypeEnum == null) {
2061 BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_OR_UPDATE_PROPERTY_VALUE, INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
2062 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
2066 if (!ComponentValidationUtils.canWorkOnComponent(componentId, toscaOperationFacade, userId)) {
2067 log.info("Restricted operation for user: {} on service: {}", userId, componentId);
2068 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2072 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(componentId, componentTypeEnum.getNodeType());
2073 if (lockStatus != StorageOperationStatus.OK) {
2074 log.debug(FAILED_TO_LOCK_SERVICE, componentId);
2075 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
2079 String propertyValueUid = property.getValueUniqueUid();
2081 if (propertyValueUid == null) {
2083 Either<Integer, StorageOperationStatus> counterRes = groupInstanceOperation.increaseAndGetGroupInstancePropertyCounter(groupInstanceId);
2085 if (counterRes.isRight()) {
2086 log.debug("increaseAndGetResourcePropertyCounter failed resource instance: {} property: {}", resourceInstanceId, property);
2087 StorageOperationStatus status = counterRes.right().value();
2088 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
2089 resultOp = Either.right(componentsUtils.getResponseFormat(actionStatus));
2091 Integer index = counterRes.left().value();
2092 Either<ComponentInstanceProperty, StorageOperationStatus> result = groupInstanceOperation.addPropertyValueToGroupInstance(property, resourceInstanceId, index, true);
2094 if (result.isLeft()) {
2095 log.trace("Property value was added to resource instance {}", resourceInstanceId);
2096 ComponentInstanceProperty instanceProperty = result.left().value();
2098 resultOp = Either.left(instanceProperty);
2101 log.debug("Failed to add property value: {} to resource instance {}", property, resourceInstanceId);
2103 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
2105 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2109 Either<ComponentInstanceProperty, StorageOperationStatus> result = groupInstanceOperation.updatePropertyValueInGroupInstance(property, resourceInstanceId, true);
2111 if (result.isLeft()) {
2112 log.debug("Property value {} was updated on graph.", property.getValueUniqueUid());
2113 ComponentInstanceProperty instanceProperty = result.left().value();
2115 resultOp = Either.left(instanceProperty);
2118 log.debug("Failed to update property value: {}, in resource instance {}", property, resourceInstanceId);
2120 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
2122 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2125 if (resultOp.isLeft()) {
2126 StorageOperationStatus updateCustomizationUUID = componentInstanceOperation.updateCustomizationUUID(resourceInstanceId);
2127 if (updateCustomizationUUID != StorageOperationStatus.OK) {
2128 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateCustomizationUUID);
2130 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2137 if (resultOp == null || resultOp.isRight()) {
2138 janusGraphDao.rollback();
2140 janusGraphDao.commit();
2143 graphLockOperation.unlockComponent(componentId, componentTypeEnum.getNodeType());
2148 public Either<ComponentInstanceProperty, ResponseFormat> deletePropertyValue(ComponentTypeEnum componentTypeEnum, String serviceId, String resourceInstanceId, String propertyValueId, String userId) {
2150 validateUserExists(userId);
2152 Either<ComponentInstanceProperty, ResponseFormat> resultOp = null;
2154 if (componentTypeEnum == null) {
2155 BeEcompErrorManager.getInstance().logInvalidInputError(CREATE_OR_UPDATE_PROPERTY_VALUE, INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
2156 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
2160 if (!ComponentValidationUtils.canWorkOnComponent(serviceId, toscaOperationFacade, userId)) {
2161 log.info("Restricted operation for user {} on service {}", userId, serviceId);
2162 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2166 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(serviceId, componentTypeEnum.getNodeType());
2167 if (lockStatus != StorageOperationStatus.OK) {
2168 log.debug(FAILED_TO_LOCK_SERVICE, serviceId);
2169 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
2173 Either<ComponentInstanceProperty, StorageOperationStatus> result = propertyOperation.removePropertyValueFromResourceInstance(propertyValueId, resourceInstanceId, true);
2175 if (result.isLeft()) {
2176 log.debug("Property value {} was removed from graph.", propertyValueId);
2177 ComponentInstanceProperty instanceProperty = result.left().value();
2179 resultOp = Either.left(instanceProperty);
2183 log.debug("Failed to remove property value {} in resource instance {}", propertyValueId, resourceInstanceId);
2185 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(result.right().value());
2187 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2193 if (resultOp == null || resultOp.isRight()) {
2194 janusGraphDao.rollback();
2196 janusGraphDao.commit();
2199 graphLockOperation.unlockComponent(serviceId, componentTypeEnum.getNodeType());
2204 private Component getAndValidateOriginComponentOfComponentInstance(Component containerComponent, ComponentInstance componentInstance) {
2206 ComponentTypeEnum componentType = getComponentTypeByParentComponentType(containerComponent.getComponentType());
2207 Component component;
2208 Either<Component, StorageOperationStatus> getComponentRes = toscaOperationFacade.getToscaFullElement(componentInstance.getComponentUid());
2209 if (getComponentRes.isRight()) {
2210 log.debug("Failed to get the component with id {} for component instance {} creation. ", componentInstance.getComponentUid(), componentInstance.getName());
2211 ActionStatus actionStatus = componentsUtils.convertFromStorageResponse(getComponentRes.right().value(), componentType);
2212 throw new ByActionStatusComponentException(actionStatus, Constants.EMPTY_STRING);
2214 component = getComponentRes.left().value();
2215 LifecycleStateEnum resourceCurrState = component.getLifecycleState();
2216 if (resourceCurrState == LifecycleStateEnum.NOT_CERTIFIED_CHECKOUT) {
2217 ActionStatus actionStatus = ActionStatus.CONTAINER_CANNOT_CONTAIN_COMPONENT_IN_STATE;
2218 throw new ByActionStatusComponentException(actionStatus, containerComponent.getComponentType().toString(), resourceCurrState.toString());
2220 if (component.isArchived() == true){
2221 ActionStatus actionStatus = ActionStatus.COMPONENT_IS_ARCHIVED;
2222 throw new ByActionStatusComponentException(actionStatus, component.getName());
2227 public Either<Set<String>, ResponseFormat> forwardingPathOnVersionChange(String containerComponentParam,
2228 String containerComponentId,
2229 String componentInstanceId,
2230 ComponentInstance newComponentInstance) {
2231 Either<Set<String>, ResponseFormat> resultOp;
2232 final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
2233 ComponentParametersView componentParametersView = getComponentParametersViewForForwardingPath();
2236 Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, componentParametersView);
2238 //Fetch current component instance
2239 Either<ComponentInstance, StorageOperationStatus> eitherResourceInstance =
2240 getResourceInstanceById(containerComponent, componentInstanceId);
2241 if (eitherResourceInstance.isRight()) {
2242 resultOp = Either.right(componentsUtils.getResponseFormat(
2243 ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceId, containerComponentId));
2246 ComponentInstance currentResourceInstance = eitherResourceInstance.left().value();
2248 //Check whether new componentInstance exists
2249 String resourceId = newComponentInstance.getComponentUid();
2250 Either<Boolean, StorageOperationStatus> componentExistsRes = toscaOperationFacade.validateComponentExists(resourceId);
2251 if (componentExistsRes.isRight()) {
2252 log.debug("Failed to find resource {}", resourceId);
2253 resultOp = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse
2254 (componentExistsRes.right().value()), resourceId));
2256 } else if (!componentExistsRes.left().value()) {
2257 log.debug("The resource {} not found ", resourceId);
2258 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_NOT_FOUND, resourceId));
2262 //Fetch component using new component instance uid
2263 Component updatedContainerComponent=getOriginComponentFromComponentInstance(newComponentInstance);
2264 Set<String> toDeleteForwardingPaths = getForwardingPaths(containerComponent,
2265 currentResourceInstance, updatedContainerComponent);
2266 resultOp=Either.left(toDeleteForwardingPaths);
2271 private Set<String> getForwardingPaths(Component containerComponent, ComponentInstance currentResourceInstance,
2272 Component updatedContainerComponent) {
2273 DataForMergeHolder dataForMergeHolder=new DataForMergeHolder();
2274 dataForMergeHolder.setOrigComponentInstId(currentResourceInstance.getName());
2276 Service service = (Service) containerComponent;
2277 ForwardingPathUtils forwardingPathUtils = new ForwardingPathUtils();
2279 return forwardingPathUtils.
2280 getForwardingPathsToBeDeletedOnVersionChange(service,dataForMergeHolder,updatedContainerComponent);
2283 private ComponentParametersView getComponentParametersViewForForwardingPath() {
2284 ComponentParametersView componentParametersView = new ComponentParametersView();
2285 componentParametersView.setIgnoreCapabiltyProperties(false);
2286 componentParametersView.setIgnoreForwardingPath(false);
2287 return componentParametersView;
2290 public ComponentInstance changeComponentInstanceVersion(String containerComponentParam, String containerComponentId, String componentInstanceId, String userId, ComponentInstance newComponentInstance) {
2292 User user = validateUserExists(userId);
2293 final ComponentTypeEnum containerComponentType = validateComponentType(containerComponentParam);
2294 ComponentParametersView componentParametersView = new ComponentParametersView();
2295 componentParametersView.setIgnoreCapabiltyProperties(false);
2297 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(containerComponentId, containerComponentType, componentParametersView);
2299 validateCanWorkOnComponent(containerComponent, userId);
2301 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceId);
2302 if (resourceInstanceStatus.isRight()) {
2303 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceId, containerComponentId);
2306 ComponentInstance currentResourceInstance = resourceInstanceStatus.left().value();
2308 return changeInstanceVersion(containerComponent, currentResourceInstance, newComponentInstance, user, containerComponentType );
2311 public ComponentInstance changeInstanceVersion(org.openecomp.sdc.be.model.Component containerComponent,
2312 ComponentInstance currentResourceInstance,
2313 ComponentInstance newComponentInstance,
2315 final ComponentTypeEnum containerComponentType) {
2316 boolean failed = false;
2317 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus;
2320 lockComponent(containerComponent, "changeComponentInstanceVersion");
2321 String containerComponentId = containerComponent.getUniqueId();
2322 String componentInstanceId = currentResourceInstance.getUniqueId();
2323 if (currentResourceInstance.getComponentUid().equals(newComponentInstance.getComponentUid())) {
2324 return currentResourceInstance;
2326 String resourceId = newComponentInstance.getComponentUid();
2328 Either<Boolean, StorageOperationStatus> componentExistsRes = toscaOperationFacade
2329 .validateComponentExists(resourceId);
2330 if (componentExistsRes.isRight()) {
2331 StorageOperationStatus errorStatus = componentExistsRes.right().value();
2333 log.debug("Failed to validate existing of the component {}. Status is {} ", resourceId, errorStatus);
2334 throw new ByActionStatusComponentException(
2335 componentsUtils.convertFromStorageResponse(errorStatus), resourceId);
2336 } else if (!componentExistsRes.left().value()) {
2337 log.debug("The resource {} not found ", resourceId);
2338 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_NOT_FOUND, resourceId);
2341 Component eitherOriginComponent = getInstanceOriginNode(currentResourceInstance);
2343 DataForMergeHolder dataHolder = compInstMergeDataBL
2344 .saveAllDataBeforeDeleting(containerComponent, currentResourceInstance, eitherOriginComponent);
2345 ComponentInstance resResourceInfo = deleteComponentInstance(containerComponent, componentInstanceId,
2346 containerComponentType);
2348 if (resResourceInfo == null) {
2349 log.error("Calling `deleteComponentInstance` for the resource {} returned a null", resourceId);
2350 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_NOT_FOUND, resourceId);
2352 Component origComponent = null;
2353 OriginTypeEnum originType = currentResourceInstance.getOriginType();
2354 if (originType == OriginTypeEnum.ServiceProxy) {
2355 Either<Component, StorageOperationStatus> serviceProxyOrigin = toscaOperationFacade
2356 .getLatestByName("serviceProxy");
2357 if (isServiceProxyOrigin(serviceProxyOrigin)) {
2358 throw new ByActionStatusComponentException(
2359 componentsUtils.convertFromStorageResponse(serviceProxyOrigin.right().value()));
2361 origComponent = serviceProxyOrigin.left().value();
2363 StorageOperationStatus fillProxyRes = fillProxyInstanceData(newComponentInstance, origComponent);
2365 if (isFillProxyRes(fillProxyRes)) {
2366 throw new ByActionStatusComponentException(
2367 componentsUtils.convertFromStorageResponse(fillProxyRes));
2369 newComponentInstance.setOriginType(originType);
2371 origComponent = getOriginComponentFromComponentInstance(newComponentInstance);
2372 newComponentInstance.setName(resResourceInfo.getName());
2375 newComponentInstance.setInvariantName(resResourceInfo.getInvariantName());
2376 newComponentInstance.setPosX(resResourceInfo.getPosX());
2377 newComponentInstance.setPosY(resResourceInfo.getPosY());
2378 newComponentInstance.setDescription(resResourceInfo.getDescription());
2380 ComponentInstance updatedComponentInstance = createComponentInstanceOnGraph(containerComponent,
2381 origComponent, newComponentInstance, user);
2382 dataHolder.setCurrInstanceNode(origComponent);
2383 Component mergeStatusEither = compInstMergeDataBL
2384 .mergeComponentUserOrigData(user, dataHolder, containerComponent, containerComponentId,
2385 newComponentInstance.getUniqueId());
2387 ActionStatus postChangeVersionResult = onChangeInstanceOperationOrchestrator
2388 .doPostChangeVersionOperations(containerComponent, currentResourceInstance, newComponentInstance);
2389 if (postChangeVersionResult != ActionStatus.OK) {
2390 throw new ByActionStatusComponentException(postChangeVersionResult);
2393 ComponentParametersView filter = new ComponentParametersView(true);
2394 filter.setIgnoreComponentInstances(false);
2395 Either<Component, StorageOperationStatus> updatedComponentRes = toscaOperationFacade
2396 .getToscaElement(containerComponentId, filter);
2397 if (updatedComponentRes.isRight()) {
2398 StorageOperationStatus storageOperationStatus = updatedComponentRes.right().value();
2399 ActionStatus actionStatus = componentsUtils
2400 .convertFromStorageResponse(storageOperationStatus, containerComponent.getComponentType());
2401 log.debug("Component with id {} was not found", containerComponentId);
2402 throw new ByActionStatusComponentException(actionStatus, Constants.EMPTY_STRING);
2404 resourceInstanceStatus = getResourceInstanceById(updatedComponentRes.left().value(),
2405 updatedComponentInstance.getUniqueId());
2406 if (resourceInstanceStatus.isRight()) {
2407 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse
2408 (resourceInstanceStatus.right().value()), updatedComponentInstance.getUniqueId());
2410 return resourceInstanceStatus.left().value();
2412 } catch (ComponentException e) {
2416 unlockComponent(failed, containerComponent);
2420 private boolean isFillProxyRes(StorageOperationStatus fillProxyRes) {
2421 if (fillProxyRes != StorageOperationStatus.OK) {
2422 log.debug("Failed to fill service proxy resource data with data from service, error {}", fillProxyRes);
2429 public List<ComponentInstanceProperty> getComponentInstancePropertiesById(String containerComponentTypeParam, String containerComponentId, String componentInstanceUniqueId, String userId) {
2430 Component containerComponent = null;
2432 boolean failed = false;
2434 validateUserExists(userId);
2435 validateComponentType(containerComponentTypeParam);
2437 Either<Component, StorageOperationStatus> validateContainerComponentExists = toscaOperationFacade.getToscaElement(containerComponentId);
2438 if (validateContainerComponentExists.isRight()) {
2439 throw new ByActionStatusComponentException(componentsUtils.convertFromStorageResponse(validateContainerComponentExists.right().value()));
2441 containerComponent = validateContainerComponentExists.left().value();
2443 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId);
2444 if (resourceInstanceStatus.isRight()) {
2445 throw new ByActionStatusComponentException(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId);
2448 List<ComponentInstanceProperty> instanceProperties = containerComponent.getComponentInstancesProperties().get(componentInstanceUniqueId);
2449 if (CollectionUtils.isEmpty(instanceProperties)) {
2450 instanceProperties = new ArrayList<>();
2452 return instanceProperties;
2453 }catch (ComponentException e){
2457 unlockComponent(failed, containerComponent);
2461 protected void validateIncrementCounter(String resourceInstanceId, GraphPropertiesDictionary counterType, Wrapper<Integer> instaceCounterWrapper, Wrapper<ResponseFormat> errorWrapper) {
2462 Either<Integer, StorageOperationStatus> counterRes = componentInstanceOperation.increaseAndGetResourceInstanceSpecificCounter(resourceInstanceId, counterType, true);
2464 if (counterRes.isRight()) {
2465 log.debug("increase And Get {} failed resource instance {}", counterType, resourceInstanceId);
2466 StorageOperationStatus status = counterRes.right().value();
2467 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
2468 errorWrapper.setInnerElement(componentsUtils.getResponseFormat(actionStatus));
2470 instaceCounterWrapper.setInnerElement(counterRes.left().value());
2476 * updates componentInstance modificationTime
2478 * @param componentInstance
2479 * @param componentInstanceType
2480 * @param modificationTime
2481 * @param inTransaction
2484 public Either<ComponentInstanceData, ResponseFormat> updateComponentInstanceModificationTimeAndCustomizationUuid(ComponentInstance componentInstance, NodeTypeEnum componentInstanceType, Long modificationTime, boolean inTransaction) {
2485 Either<ComponentInstanceData, ResponseFormat> result;
2486 Either<ComponentInstanceData, StorageOperationStatus> updateComponentInstanceRes = componentInstanceOperation.updateComponentInstanceModificationTimeAndCustomizationUuidOnGraph(componentInstance, componentInstanceType, modificationTime,
2488 if (updateComponentInstanceRes.isRight()) {
2489 log.debug("Failed to update component instance {} with new last update date and mofifier. Status is {}. ", componentInstance.getName(), updateComponentInstanceRes.right().value());
2490 result = Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(updateComponentInstanceRes.right().value())));
2492 result = Either.left(updateComponentInstanceRes.left().value());
2497 public Either<ComponentInstance, ResponseFormat> deleteServiceProxy() {
2498 // TODO Add implementation
2499 return Either.left(new ComponentInstance());
2502 public Either<ComponentInstance, ResponseFormat> createServiceProxy() {
2503 // TODO Add implementation
2504 return Either.left(new ComponentInstance());
2507 public Either<ComponentInstance, ResponseFormat> changeServiceProxyVersion() {
2508 // TODO Add implementation
2509 return Either.left(new ComponentInstance());
2512 private Boolean validateInstanceNameUniquenessUponUpdate(Component containerComponent, ComponentInstance oldComponentInstance, String newInstanceName) {
2513 return ComponentValidations.validateNameIsUniqueInComponent(oldComponentInstance.getName(), newInstanceName, containerComponent);
2516 private Either<ComponentInstance, StorageOperationStatus> getResourceInstanceById(Component containerComponent, String instanceId) {
2518 Either<ComponentInstance, StorageOperationStatus> result = null;
2519 List<ComponentInstance> instances = containerComponent.getComponentInstances();
2520 Optional<ComponentInstance> foundInstance = null;
2521 if (CollectionUtils.isEmpty(instances)) {
2522 result = Either.right(StorageOperationStatus.NOT_FOUND);
2524 if (result == null) {
2525 foundInstance = instances.stream().filter(i -> i.getUniqueId().equals(instanceId)).findFirst();
2526 if (!foundInstance.isPresent()) {
2527 result = Either.right(StorageOperationStatus.NOT_FOUND);
2530 if (result == null) {
2531 result = Either.left(foundInstance.get());
2536 private ComponentInstance buildComponentInstance(ComponentInstance resourceInstanceForUpdate, ComponentInstance origInstanceForUpdate) {
2538 Long creationDate = origInstanceForUpdate.getCreationTime();
2540 Long modificationTime = System.currentTimeMillis();
2541 resourceInstanceForUpdate.setCreationTime(creationDate);
2542 resourceInstanceForUpdate.setModificationTime(modificationTime);
2544 resourceInstanceForUpdate.setCustomizationUUID(origInstanceForUpdate.getCustomizationUUID());
2546 if (StringUtils.isEmpty(resourceInstanceForUpdate.getName()) && StringUtils.isNotEmpty(origInstanceForUpdate.getName())) {
2547 resourceInstanceForUpdate.setName(origInstanceForUpdate.getName());
2550 resourceInstanceForUpdate.setNormalizedName(ValidationUtils.normalizeComponentInstanceName(resourceInstanceForUpdate.getName()));
2552 if (StringUtils.isEmpty(resourceInstanceForUpdate.getIcon()))
2553 resourceInstanceForUpdate.setIcon(origInstanceForUpdate.getIcon());
2555 if (StringUtils.isEmpty(resourceInstanceForUpdate.getComponentVersion()))
2556 resourceInstanceForUpdate.setComponentVersion(origInstanceForUpdate.getComponentVersion());
2558 if (StringUtils.isEmpty(resourceInstanceForUpdate.getComponentName()))
2559 resourceInstanceForUpdate.setComponentName(origInstanceForUpdate.getComponentName());
2561 if (StringUtils.isEmpty(resourceInstanceForUpdate.getToscaComponentName()))
2562 resourceInstanceForUpdate.setToscaComponentName(origInstanceForUpdate.getToscaComponentName());
2564 if (resourceInstanceForUpdate.getOriginType() == null) {
2565 resourceInstanceForUpdate.setOriginType(origInstanceForUpdate.getOriginType());
2567 if(resourceInstanceForUpdate.getOriginType() == OriginTypeEnum.ServiceProxy)
2568 resourceInstanceForUpdate.setIsProxy(true);
2569 if (resourceInstanceForUpdate.getSourceModelInvariant() == null) {
2570 resourceInstanceForUpdate.setSourceModelInvariant(origInstanceForUpdate.getSourceModelInvariant());
2572 if (resourceInstanceForUpdate.getSourceModelName() == null) {
2573 resourceInstanceForUpdate.setSourceModelName(origInstanceForUpdate.getSourceModelName());
2575 if (resourceInstanceForUpdate.getSourceModelUuid() == null) {
2576 resourceInstanceForUpdate.setSourceModelUuid(origInstanceForUpdate.getSourceModelUuid());
2578 if (resourceInstanceForUpdate.getSourceModelUid() == null) {
2579 resourceInstanceForUpdate.setSourceModelUid(origInstanceForUpdate.getSourceModelUid());
2581 if (resourceInstanceForUpdate.getCreatedFrom() == null) {
2582 resourceInstanceForUpdate.setCreatedFrom(origInstanceForUpdate.getCreatedFrom());
2584 return resourceInstanceForUpdate;
2587 * Returns list of ComponentInstanceProperty belonging to component instance capability specified by name, type and ownerId
2588 * @param containerComponentType
2589 * @param containerComponentId
2590 * @param componentInstanceUniqueId
2591 * @param capabilityType
2592 * @param capabilityName
2597 public List<ComponentInstanceProperty> getComponentInstanceCapabilityPropertiesById(String containerComponentType, String containerComponentId, String componentInstanceUniqueId, String capabilityType, String capabilityName, String ownerId, String userId) {
2599 Component containerComponent = null;
2601 List<ComponentInstanceProperty> resultOp = null;
2603 validateUserExists(userId);
2604 validateComponentType(containerComponentType);
2605 containerComponent = toscaOperationFacade.getToscaFullElement(containerComponentId).left().on(this::componentException);
2606 ComponentInstance resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId).left().on(this::componentInstanceException);
2607 resultOp = findCapabilityOfInstance(containerComponentId, componentInstanceUniqueId, capabilityType, capabilityName, ownerId, resourceInstanceStatus.getCapabilities());
2608 } catch(StorageException e){
2609 unlockRollbackWithException(containerComponent, e);
2610 } catch (ComponentException e) {
2611 unlockRollbackWithException(containerComponent, e);
2612 } catch (Exception e){
2613 unlockRollbackWithException(containerComponent, new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR));
2615 unlockWithCommit(containerComponent);
2619 private List<ComponentInstanceProperty> findCapabilityOfInstance( String componentId, String instanceId, String capabilityType, String capabilityName, String ownerId, Map<String, List<CapabilityDefinition>> instanceCapabilities) {
2620 CapabilityDefinition foundCapability;
2621 if (MapUtils.isNotEmpty(instanceCapabilities)) {
2622 List<CapabilityDefinition> capabilitiesPerType = instanceCapabilities.get(capabilityType);
2623 if (capabilitiesPerType != null) {
2624 Optional<CapabilityDefinition> capabilityOpt = capabilitiesPerType.stream().filter(c -> c.getName().equals(capabilityName) && c.getOwnerId().equals(ownerId)).findFirst();
2625 if (capabilityOpt.isPresent()) {
2626 foundCapability = capabilityOpt.get();
2627 return foundCapability.getProperties() == null ? new ArrayList<>() : foundCapability.getProperties();
2631 return fetchComponentInstanceCapabilityProperties(componentId, instanceId, capabilityType, capabilityName, ownerId);
2634 private List<ComponentInstanceProperty> fetchComponentInstanceCapabilityProperties(String componentId, String instanceId, String capabilityType, String capabilityName, String ownerId) {
2636 return toscaOperationFacade.getComponentInstanceCapabilityProperties(componentId, instanceId, capabilityName, capabilityType, ownerId)
2638 .on(this::componentInstancePropertyListException);
2639 } catch(Exception e){
2640 log.debug("The exception {} occurred upon the component {} instance {} capability {} properties retrieving. ", componentId, instanceId, capabilityName, e);
2641 throw new ByActionStatusComponentException(ActionStatus.GENERAL_ERROR);
2645 public Either<List<ComponentInstanceProperty>, ResponseFormat> updateInstanceCapabilityProperties(ComponentTypeEnum componentTypeEnum, String containerComponentId, String componentInstanceUniqueId, String capabilityType, String capabilityName,
2646 List<ComponentInstanceProperty> properties, String userId) {
2647 Either<List<ComponentInstanceProperty>, ResponseFormat> resultOp = null;
2649 validateUserExists(userId);
2650 if (componentTypeEnum == null) {
2651 BeEcompErrorManager.getInstance().logInvalidInputError("updateInstanceCapabilityProperty", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
2652 return Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
2654 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaFullElement(containerComponentId);
2656 if (getResourceResult.isRight()) {
2657 log.debug(FAILED_TO_RETRIEVE_COMPONENT_COMPONENT_ID, containerComponentId);
2658 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2660 Component containerComponent = getResourceResult.left().value();
2662 if (!ComponentValidationUtils.canWorkOnComponent(containerComponent, userId)) {
2663 log.info("Restricted operation for user: {} on component {}", userId, containerComponentId);
2664 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2666 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, componentInstanceUniqueId);
2667 if (resourceInstanceStatus.isRight()) {
2668 return Either.right(componentsUtils.getResponseFormat(ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, componentInstanceUniqueId, containerComponentId));
2670 ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
2672 StorageOperationStatus lockStatus = graphLockOperation.lockComponent(containerComponentId, componentTypeEnum.getNodeType());
2673 if (lockStatus != StorageOperationStatus.OK) {
2674 log.debug("Failed to lock component {}", containerComponentId);
2675 return Either.right(componentsUtils.getResponseFormat(componentsUtils.convertFromStorageResponse(lockStatus)));
2679 for (ComponentInstanceProperty property : properties) {
2680 Either<String, ResponseFormat> newPropertyValueEither = validatePropertyObjectValue(property, property.getValue(), false);
2681 newPropertyValueEither.bimap(updatedValue ->
2682 updateCapabilityPropertyOnContainerComponent(property,updatedValue, containerComponent, foundResourceInstance, capabilityType, capabilityName),
2685 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
2687 if (updateContainerRes.isRight()) {
2688 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
2689 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
2692 resultOp = Either.left(properties);
2696 if (resultOp == null || resultOp.isRight()) {
2697 janusGraphDao.rollback();
2699 janusGraphDao.commit();
2702 graphLockOperation.unlockComponent(containerComponentId, componentTypeEnum.getNodeType());
2706 public Either<Map<String, ComponentInstance>, ResponseFormat> copyComponentInstance(ComponentInstance inputComponentInstance,
2707 String containerComponentId,
2708 String componentInstanceId,
2711 Map<String, ComponentInstance> resultMap = new HashMap<>();
2712 Either<Component, StorageOperationStatus> getOrigComponent = toscaOperationFacade.getToscaElement(containerComponentId);
2713 if (getOrigComponent.isRight()) {
2714 log.error("Failed to get the original component information");
2715 return Either.right(componentsUtils.getResponseFormat(
2716 ActionStatus.USER_DEFINED, FAILED_TO_COPY_COMP_INSTANCE_TO_CANVAS));
2719 Component origComponent = getOrigComponent.left().value();
2722 lockComponent(origComponent, "copyComponentInstance");
2724 } catch (ComponentException e) {
2725 log.error("destComponentInstance's data is {}", origComponent.toString());
2726 return Either.right(componentsUtils.getResponseFormat(
2727 ActionStatus.USER_DEFINED, "Failed to lock component destComponentInstance's data is {}", origComponent.toString()));
2730 boolean failed = false;
2731 ComponentInstance actionResponse = null;
2734 actionResponse = createComponentInstance(
2735 "services", containerComponentId, userId, inputComponentInstance, true, false);
2737 } catch (ComponentException e) {
2742 // on failure of the create instance unlock the resource and rollback the transaction.
2743 if (null == actionResponse || failed) {
2744 janusGraphDao.rollback();
2745 log.error("Failed to copy the component instance to the canvas");
2747 unlockComponent(failed, origComponent);
2749 return Either.right(componentsUtils.getResponseFormat(
2750 ActionStatus.USER_DEFINED, "Failed to copy the component instance to the canvas"));
2754 Either<String, ResponseFormat> resultOp = null;
2757 ComponentInstance destComponentInstance = actionResponse;
2758 log.debug("destComponentInstance's data is {}", destComponentInstance.toString());
2761 resultOp = deepCopyComponentInstance(
2762 origComponent, containerComponentId, componentInstanceId, destComponentInstance, userId);
2764 resultMap.put("componentInstance", destComponentInstance);
2768 if (resultOp == null || resultOp.isRight()) {
2769 unlockComponent(true, origComponent);
2770 janusGraphDao.rollback();
2771 log.error("Failed to deep copy component instance");
2772 return Either.right(componentsUtils.getResponseFormat(
2773 ActionStatus.USER_DEFINED, "Failed to deep copy the component instance to the canvas"));
2775 unlockComponent(false, origComponent);
2776 janusGraphDao.commit();
2777 log.debug("Success trasaction commit");
2781 return Either.left(resultMap);
2784 private Either<String, ResponseFormat> deepCopyComponentInstance(
2785 Component sourceComponent, String containerComponentId, String sourceComponentInstanceId,
2786 ComponentInstance destComponentInstance, String userId) {
2788 Either<Component, StorageOperationStatus> getDestComponent = toscaOperationFacade.getToscaElement(containerComponentId);
2789 if (getDestComponent.isRight()) {
2790 log.error("Failed to get the dest component information");
2791 return Either.right(componentsUtils.getResponseFormat(
2792 ActionStatus.USER_DEFINED, "Failed to copy the component instance to the canvas"));
2795 Component destComponent = getDestComponent.left().value();
2797 Either<String, ResponseFormat> copyComponentInstanceWithPropertiesAndInputs = copyComponentInstanceWithPropertiesAndInputs(
2798 sourceComponent, destComponent, sourceComponentInstanceId, destComponentInstance, userId);
2799 if (copyComponentInstanceWithPropertiesAndInputs.isRight()) {
2800 log.error("Failed to copy component instance with properties and inputs as part of deep copy");
2801 return Either.right(componentsUtils.getResponseFormat(
2802 ActionStatus.USER_DEFINED, "Failed to copy the component instance with properties and inputs as part of deep copy"));
2805 Either<String, ResponseFormat> copyComponentInstanceWithAttributes = copyComponentInstanceWithAttributes(
2806 sourceComponent, destComponent, sourceComponentInstanceId, destComponentInstance, userId);
2807 if (copyComponentInstanceWithAttributes.isRight()) {
2808 log.error("Failed to copy component instance with attributes as part of deep copy");
2809 return Either.right(componentsUtils.getResponseFormat(
2810 ActionStatus.USER_DEFINED, "Failed to copy the component instance with attributes as part of deep copy"));
2812 return Either.left(COPY_COMPONENT_INSTANCE_OK);
2815 private Either<String, ResponseFormat> copyComponentInstanceWithPropertiesAndInputs(
2816 Component sourceComponent, Component destComponent, String sourceComponentInstanceId,
2817 ComponentInstance destComponentInstance, String userId) {
2818 log.debug("start to copy ComponentInstance with properties and inputs");
2820 List<ComponentInstanceProperty> sourcePropList = null;
2821 if (sourceComponent.getComponentInstancesProperties() != null
2822 && sourceComponent.getComponentInstancesProperties().get(sourceComponentInstanceId) != null) {
2823 sourcePropList = sourceComponent.getComponentInstancesProperties().get(sourceComponentInstanceId);
2824 log.debug("sourcePropList");
2827 List<ComponentInstanceProperty> destPropList = null;
2828 String destComponentInstanceId = destComponentInstance.getUniqueId();
2829 log.debug("destComponentInstanceId: {}", destComponentInstance.getUniqueId());
2830 if (destComponent.getComponentInstancesProperties() != null
2831 && destComponent.getComponentInstancesProperties().get(destComponentInstanceId) != null) {
2832 destPropList = destComponent.getComponentInstancesProperties().get(destComponentInstanceId);
2833 log.debug("destPropList {}");
2836 List<ComponentInstancePropInput> componentInstancePropInputList = new ArrayList<>();
2838 if (null != destPropList && null != sourcePropList) {
2839 log.debug("start to set property and attribute");
2840 for (ComponentInstanceProperty destProp : destPropList) {
2841 String destPropertyName = destProp.getName();
2842 for (ComponentInstanceProperty sourceProp : sourcePropList) {
2843 if (!destPropertyName.equals(sourceProp.getName())) {
2846 log.debug("now set property");
2847 if (sourceProp.getGetInputValues() == null && !StringUtils.isEmpty(sourceProp.getValue())
2848 && (destProp.getValue() == null || !destProp.getValue().equals(sourceProp.getValue()))) {
2849 log.debug("Now starting to copy the property {} in value {}", destPropertyName, sourceProp.getValue());
2851 destProp.setValue(sourceProp.getValue());
2852 Either<String, ResponseFormat> updatePropertyValueEither = updateComponentInstanceProperty(
2853 destComponent.getUniqueId(), destComponentInstanceId, destProp);
2854 if (updatePropertyValueEither.isRight()) {
2855 log.error("Failed to copy the property {}", destPropertyName);
2856 return Either.right(componentsUtils.getResponseFormat(
2857 ActionStatus.INVALID_CONTENT_PARAM, "Failed to paste component instance to the canvas, property copy"));
2862 log.debug("Now start to update inputs");
2864 if (sourceProp.getGetInputValues() != null) {
2865 if (sourceProp.getGetInputValues().size() < 1) {
2866 log.debug("property is return from input, set by man");
2869 log.debug("Now starting to copy the {} property", destPropertyName);
2871 Either<String, ResponseFormat> getSourceInputDefaultValue = getInputListDefaultValue(
2872 sourceComponent, sourceProp.getGetInputValues().get(0).getInputId());
2873 if (getSourceInputDefaultValue.isRight()) {
2874 return Either.right(getSourceInputDefaultValue.right().value());
2876 componentInstancePropInputList.add(new ComponentInstancePropInput(destProp));
2881 return Either.left(COPY_COMPONENT_INSTANCE_OK);
2884 private Either<String, ResponseFormat> copyComponentInstanceWithAttributes(Component sourceComponent,
2885 Component destComponent,
2886 String sourceComponentInstanceId,
2887 ComponentInstance destComponentInstance,
2889 String destComponentInstanceId = destComponentInstance.getUniqueId();
2891 log.info("start to copy component instance with attributes");
2893 List<ComponentInstanceProperty> sourceAttributeList = null;
2894 if (sourceComponent.getComponentInstancesAttributes() != null
2895 && sourceComponent.getComponentInstancesAttributes().get(sourceComponentInstanceId) != null) {
2896 sourceAttributeList = sourceComponent.getComponentInstancesAttributes().get(sourceComponentInstanceId);
2897 log.info("sourceAttributes {}");
2900 List<ComponentInstanceProperty> destAttributeList = null;
2901 if (destComponent.getComponentInstancesAttributes() != null
2902 && destComponent.getComponentInstancesAttributes().get(destComponentInstanceId) != null) {
2903 destAttributeList = destComponent.getComponentInstancesAttributes().get(destComponentInstanceId);
2904 log.info("destAttributeList {}");
2906 if (null != sourceAttributeList && null != destAttributeList) {
2907 log.info("set attribute");
2909 for (ComponentInstanceProperty sourceAttribute : sourceAttributeList) {
2910 String sourceAttributeName = sourceAttribute.getName();
2911 for (ComponentInstanceProperty destAttribute : destAttributeList) {
2912 if (sourceAttributeName.equals(destAttribute.getName())) {
2913 if (sourceAttribute.getValue() != null && !sourceAttribute.getValue().isEmpty()) {
2914 log.debug("Start to copy the attribute exists {}", sourceAttributeName);
2916 sourceAttribute.setUniqueId(
2917 UniqueIdBuilder.buildResourceInstanceUniuqeId(
2918 "attribute" , destComponentInstanceId.split("\\.")[1] , sourceAttributeName));
2920 Either<ComponentInstanceProperty, ResponseFormat> updateAttributeValueEither =
2921 createOrUpdateAttributeValueForCopyPaste(ComponentTypeEnum.SERVICE,
2922 destComponent.getUniqueId(), destComponentInstanceId, sourceAttribute,
2924 if (updateAttributeValueEither.isRight()) {
2925 log.error("Failed to copy the attribute");
2926 return Either.right(componentsUtils
2927 .getResponseFormat(ActionStatus.INVALID_CONTENT_PARAM,
2928 "Failed to paste component instance to the canvas, attribute copy"));
2937 return Either.left(COPY_COMPONENT_INSTANCE_OK);
2940 private Either<ComponentInstanceProperty, ResponseFormat> createOrUpdateAttributeValueForCopyPaste(ComponentTypeEnum componentTypeEnum,
2942 String resourceInstanceId,
2943 ComponentInstanceProperty attribute,
2946 Either<ComponentInstanceProperty, ResponseFormat> resultOp = null;
2948 validateUserExists(userId);
2950 if (componentTypeEnum == null) {
2951 BeEcompErrorManager.getInstance().logInvalidInputError(
2952 "createOrUpdateAttributeValue", INVALID_COMPONENT_TYPE, ErrorSeverity.INFO);
2953 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.NOT_ALLOWED));
2957 Either<Component, StorageOperationStatus> getResourceResult = toscaOperationFacade.getToscaElement(componentId, JsonParseFlagEnum.ParseAll);
2959 if (getResourceResult.isRight()) {
2960 log.info("Failed to retrieve component id {}", componentId);
2961 resultOp = Either.right(componentsUtils.getResponseFormat(ActionStatus.RESTRICTED_OPERATION));
2965 Component containerComponent = getResourceResult.left().value();
2967 Either<ComponentInstance, StorageOperationStatus> resourceInstanceStatus = getResourceInstanceById(containerComponent, resourceInstanceId);
2969 if (resourceInstanceStatus.isRight()) {
2970 resultOp = Either.right(componentsUtils.getResponseFormat(
2971 ActionStatus.RESOURCE_INSTANCE_NOT_FOUND_ON_SERVICE, resourceInstanceId, componentId));
2975 ComponentInstance foundResourceInstance = resourceInstanceStatus.left().value();
2978 String propertyType = attribute.getType();
2979 ToscaPropertyType type = ToscaPropertyType.isValidType(propertyType);
2980 log.info("The type of attribute id{},is {} ", attribute.getUniqueId(), propertyType);
2982 if (type == ToscaPropertyType.LIST || type == ToscaPropertyType.MAP) {
2983 SchemaDefinition def = attribute.getSchema();
2985 log.info("Schema doesn't exists for attribute of type {}", type);
2986 return Either.right(componentsUtils.getResponseFormat(
2987 componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
2989 PropertyDataDefinition propDef = def.getProperty();
2990 if (propDef == null) {
2991 log.info("Attribute in Schema Definition inside attribute of type {} doesn't exist", type);
2992 return Either.right(componentsUtils.getResponseFormat(
2993 componentsUtils.convertFromStorageResponse(StorageOperationStatus.INVALID_VALUE)));
2997 List<ComponentInstanceProperty> instanceAttributes = containerComponent.
2998 getComponentInstancesAttributes().get(resourceInstanceId);
2999 Optional<ComponentInstanceProperty> instanceAttribute =
3000 instanceAttributes.stream().filter(p -> p.getUniqueId().equals(attribute.getUniqueId())).findAny();
3001 StorageOperationStatus status;
3003 if (instanceAttribute.isPresent()) {
3004 log.info("updateComponentInstanceAttribute");
3005 status = toscaOperationFacade.updateComponentInstanceAttribute(containerComponent, foundResourceInstance.getUniqueId(), attribute);
3007 log.info("addComponentInstanceAttribute");
3008 status = toscaOperationFacade.addComponentInstanceAttribute(containerComponent, foundResourceInstance.getUniqueId(), attribute);
3010 if (status != StorageOperationStatus.OK) {
3011 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
3012 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
3015 List<String> path = new ArrayList<>();
3016 path.add(foundResourceInstance.getUniqueId());
3017 attribute.setPath(path);
3019 foundResourceInstance.setCustomizationUUID(UUID.randomUUID().toString());
3020 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.
3021 updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
3023 if (updateContainerRes.isRight()) {
3024 ActionStatus actionStatus = componentsUtils.
3025 convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
3026 resultOp = Either.right(componentsUtils.
3027 getResponseFormatForResourceInstanceProperty(actionStatus, ""));
3030 resultOp = Either.left(attribute);
3037 private Either<String, ResponseFormat> updateComponentInstanceProperty(String containerComponentId,
3038 String componentInstanceId,
3039 ComponentInstanceProperty property) {
3040 Either<String, ResponseFormat> resultOp;
3041 Either<Component, StorageOperationStatus> getComponent = toscaOperationFacade.getToscaElement(containerComponentId);
3043 if (getComponent.isRight()) {
3044 log.error("Failed to get the component information");
3045 return Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(
3046 ActionStatus.INVALID_CONTENT_PARAM, "Failed to get the component information"));
3049 Component containerComponent = getComponent.left().value();
3051 StorageOperationStatus status = toscaOperationFacade.updateComponentInstanceProperty(
3052 containerComponent, componentInstanceId, property);
3053 if (status != StorageOperationStatus.OK) {
3054 ActionStatus actionStatus = componentsUtils.convertFromStorageResponseForResourceInstanceProperty(status);
3055 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
3059 Either<Component, StorageOperationStatus> updateContainerRes = toscaOperationFacade.
3060 updateComponentInstanceMetadataOfTopologyTemplate(containerComponent);
3062 if (updateContainerRes.isRight()) {
3063 ActionStatus actionStatus = componentsUtils.
3064 convertFromStorageResponseForResourceInstanceProperty(updateContainerRes.right().value());
3065 resultOp = Either.right(componentsUtils.getResponseFormatForResourceInstanceProperty(actionStatus, ""));
3069 return Either.left("Update OK");
3072 private Either<String, ResponseFormat> getInputListDefaultValue(Component component, String inputId) {
3073 List<InputDefinition> inputList = component.getInputs();
3074 for (InputDefinition input : inputList) {
3075 if (input.getUniqueId().equals(inputId)) {
3076 if (input.getDefaultValue() == null) {
3077 log.debug("The input's default value is null");
3078 return Either.left(null);
3080 return Either.left(input.getDefaultValue());
3083 log.error("The input's default value with id {} is not found", inputId);
3084 return Either.right(componentsUtils.getResponseFormat(
3085 ActionStatus.USER_DEFINED, "Failed to paste component instance to the canvas"));
3089 * Method to delete selected nodes and edges on composition page
3090 * @param containerComponentType
3091 * @param componentId
3092 * @param componentInstanceIdList
3096 public Map<String, List<String>> batchDeleteComponentInstance(String containerComponentType,
3098 List<String> componentInstanceIdList,
3101 List<String> deleteErrorIds = new ArrayList<>();
3102 Map<String, List<String>> deleteErrorMap = new HashMap<>();
3103 validateUserExists(userId);
3104 org.openecomp.sdc.be.model.Component containerComponent = validateComponentExists(componentId, ComponentTypeEnum.findByParamName(containerComponentType), null);
3106 boolean failed = false;
3108 lockComponent(containerComponent, "batchDeleteComponentInstance");
3109 for (String eachInstanceId : componentInstanceIdList) {
3110 Either<ComponentInstance, ResponseFormat> actionResponse = batchDeleteComponentInstance(
3111 containerComponent, containerComponentType, componentId, eachInstanceId);
3112 log.debug("batchDeleteResourceInstances actionResponse is {}", actionResponse);
3113 if (actionResponse.isRight()) {
3114 log.error("Failed to delete ComponentInstance [{}]", eachInstanceId);
3115 deleteErrorIds.add(eachInstanceId);
3118 //sending the ids of the error nodes that were not deleted to UI
3119 deleteErrorMap.put("deleteFailedIds", deleteErrorIds);
3120 return deleteErrorMap;
3121 }catch (ComponentException e){
3125 unlockComponent(failed, containerComponent);
3129 private Either<ComponentInstance, ResponseFormat> batchDeleteComponentInstance(Component containerComponent,
3130 String containerComponentType,
3131 String containerComponentId,
3132 String componentInstanceId) {
3134 ComponentInstance resultOp;
3135 final ComponentTypeEnum containerComponentTypeEnum = ComponentTypeEnum.findByParamName(containerComponentType);
3137 boolean failed = false;
3139 resultOp = deleteComponentInstance(containerComponent, componentInstanceId, containerComponentTypeEnum);
3140 log.info("Successfully deleted instance with id {}", componentInstanceId);
3141 return Either.left(resultOp);
3143 catch (ComponentException e){
3144 log.error("Failed to deleteComponentInstance with instanceId[{}]", componentInstanceId);
3145 return Either.right(new ResponseFormat());
3149 public boolean isVFC(final OriginTypeEnum originTypeEnum) {
3150 return OriginTypeEnum.VFC.equals(originTypeEnum);
3153 public void validateUser(final String userId) {
3154 final User user = userValidations.validateUserExists(userId);
3155 userValidations.validateUserRole(user, Arrays.asList(Role.DESIGNER, Role.ADMIN));